diff --git a/browser/brave_rewards/android/brave_rewards_native_worker.cc b/browser/brave_rewards/android/brave_rewards_native_worker.cc index 883ac8900b05..74fd096c4140 100644 --- a/browser/brave_rewards/android/brave_rewards_native_worker.cc +++ b/browser/brave_rewards/android/brave_rewards_native_worker.cc @@ -486,35 +486,23 @@ void BraveRewardsNativeWorker::GetReconcileStamp(JNIEnv* env, void BraveRewardsNativeWorker::ResetTheWholeState(JNIEnv* env, const base::android::JavaParamRef& obj) { - auto* ads_service_ = brave_ads::AdsServiceFactory::GetForProfile( - ProfileManager::GetActiveUserProfile()->GetOriginalProfile()); - if (ads_service_) { - ads_service_->ResetTheWholeState(base::Bind( - &BraveRewardsNativeWorker::OnAdsResetTheWholeState, - weak_factory_.GetWeakPtr())); - } else { - OnAdsResetTheWholeState(true); - } -} - -void BraveRewardsNativeWorker::OnAdsResetTheWholeState(bool sucess) { - if (sucess && brave_rewards_service_) { - brave_rewards_service_->ResetTheWholeState(base::Bind( + if (brave_rewards_service_) { + brave_rewards_service_->CompleteReset(base::Bind( &BraveRewardsNativeWorker::OnResetTheWholeState, weak_factory_.GetWeakPtr())); } else { JNIEnv* env = base::android::AttachCurrentThread(); Java_BraveRewardsNativeWorker_OnResetTheWholeState(env, - weak_java_brave_rewards_native_worker_.get(env), sucess); + weak_java_brave_rewards_native_worker_.get(env), false); } } -void BraveRewardsNativeWorker::OnResetTheWholeState(bool sucess) { +void BraveRewardsNativeWorker::OnResetTheWholeState(const bool success) { JNIEnv* env = base::android::AttachCurrentThread(); Java_BraveRewardsNativeWorker_OnResetTheWholeState(env, - weak_java_brave_rewards_native_worker_.get(env), sucess); + weak_java_brave_rewards_native_worker_.get(env), success); } double BraveRewardsNativeWorker::GetPublisherRecurrentDonationAmount( diff --git a/browser/brave_rewards/android/brave_rewards_native_worker.h b/browser/brave_rewards/android/brave_rewards_native_worker.h index 30ae13b5c1f5..f9d456b0b16c 100644 --- a/browser/brave_rewards/android/brave_rewards_native_worker.h +++ b/browser/brave_rewards/android/brave_rewards_native_worker.h @@ -182,9 +182,7 @@ class BraveRewardsNativeWorker : public brave_rewards::RewardsServiceObserver, const base::android::JavaParamRef& obj, const base::android::JavaParamRef& pass_phrase); - void OnAdsResetTheWholeState(bool sucess); - - void OnResetTheWholeState(bool sucess); + void OnResetTheWholeState(const bool success); void OnGetGetReconcileStamp(uint64_t timestamp); diff --git a/browser/brave_rewards/extension_rewards_service_observer.cc b/browser/brave_rewards/extension_rewards_service_observer.cc index 8fbe5e22765d..265be3d281ad 100644 --- a/browser/brave_rewards/extension_rewards_service_observer.cc +++ b/browser/brave_rewards/extension_rewards_service_observer.cc @@ -371,4 +371,23 @@ void ExtensionRewardsServiceObserver::OnUnblindedTokensReady( event_router->BroadcastEvent(std::move(event)); } +void ExtensionRewardsServiceObserver::OnCompleteReset(const bool success) { + auto* event_router = extensions::EventRouter::Get(profile_); + if (!event_router) { + return; + } + + extensions::api::brave_rewards::OnCompleteReset::Properties properties; + properties.success = success; + + std::unique_ptr args( + extensions::api::brave_rewards::OnCompleteReset::Create(properties) + .release()); + std::unique_ptr event(new extensions::Event( + extensions::events::BRAVE_START, + extensions::api::brave_rewards::OnCompleteReset::kEventName, + std::move(args))); + event_router->BroadcastEvent(std::move(event)); +} + } // namespace brave_rewards diff --git a/browser/brave_rewards/extension_rewards_service_observer.h b/browser/brave_rewards/extension_rewards_service_observer.h index f78d1c7d967e..c72ded30b528 100644 --- a/browser/brave_rewards/extension_rewards_service_observer.h +++ b/browser/brave_rewards/extension_rewards_service_observer.h @@ -87,6 +87,8 @@ class ExtensionRewardsServiceObserver : public RewardsServiceObserver, void OnAdsEnabled(RewardsService* rewards_service, bool ads_enabled) override; + void OnCompleteReset(const bool success) override; + private: Profile* profile_; diff --git a/browser/extensions/api/rewards_notifications_api.cc b/browser/extensions/api/rewards_notifications_api.cc index 021428886515..4e3f4a0d84d9 100644 --- a/browser/extensions/api/rewards_notifications_api.cc +++ b/browser/extensions/api/rewards_notifications_api.cc @@ -65,7 +65,7 @@ RewardsNotificationsDeleteAllNotificationsFunction::Run() { RewardsNotificationService* rewards_notification_service = RewardsServiceFactory::GetForProfile(profile)->GetNotificationService(); if (rewards_notification_service) { - rewards_notification_service->DeleteAllNotifications(); + rewards_notification_service->DeleteAllNotifications(false); } return RespondNow(NoArguments()); } diff --git a/browser/ui/webui/brave_rewards_page_ui.cc b/browser/ui/webui/brave_rewards_page_ui.cc index 0d53b1839cc3..65233d493f7b 100644 --- a/browser/ui/webui/brave_rewards_page_ui.cc +++ b/browser/ui/webui/brave_rewards_page_ui.cc @@ -203,6 +203,8 @@ class RewardsDOMHandler : public WebUIMessageHandler, void OnGetRewardsParameters( std::unique_ptr parameters); + void CompleteReset(const base::ListValue* args); + // RewardsServiceObserver implementation void OnWalletInitialized(brave_rewards::RewardsService* rewards_service, int32_t result) override; @@ -279,6 +281,8 @@ class RewardsDOMHandler : public WebUIMessageHandler, void ReconcileStampReset() override; + void OnCompleteReset(const bool success) override; + // RewardsNotificationsServiceObserver implementation void OnNotificationAdded( brave_rewards::RewardsNotificationService* rewards_notification_service, @@ -480,6 +484,9 @@ void RewardsDOMHandler::RegisterMessages() { web_ui()->RegisterMessageCallback("brave_rewards.getCountryCode", base::BindRepeating(&RewardsDOMHandler::GetCountryCode, base::Unretained(this))); + web_ui()->RegisterMessageCallback("brave_rewards.completeReset", + base::BindRepeating(&RewardsDOMHandler::CompleteReset, + base::Unretained(this))); } void RewardsDOMHandler::Init() { @@ -1917,6 +1924,22 @@ void RewardsDOMHandler::GetCountryCode(const base::ListValue* args) { "brave_rewards.countryCode", base::Value(country_code)); } +void RewardsDOMHandler::CompleteReset(const base::ListValue* args) { + if (!rewards_service_) { + return; + } + + rewards_service_->CompleteReset(base::DoNothing()); +} + +void RewardsDOMHandler::OnCompleteReset(const bool success) { + if (!web_ui()->CanCallJavascript()) { + return; + } + + web_ui()->CallJavascriptFunctionUnsafe( + "brave_rewards.completeReset", base::Value(success)); +} } // namespace diff --git a/browser/ui/webui/brave_webui_source.cc b/browser/ui/webui/brave_webui_source.cc index f87f7196d427..73305ae70ee0 100644 --- a/browser/ui/webui/brave_webui_source.cc +++ b/browser/ui/webui/brave_webui_source.cc @@ -581,6 +581,7 @@ void CustomizeWebUIHTMLSource(const std::string &name, { "reservedAmountText", IDS_BRAVE_UI_RESERVED_AMOUNT_TEXT }, { "reservedMoreLink", IDS_BRAVE_UI_RESERVED_MORE_LINK }, { "reservedAllLink", IDS_BRAVE_UI_RESERVED_ALL_LINK }, + { "reset", IDS_BRAVE_UI_RESET }, { "restore", IDS_BRAVE_UI_RESTORE }, { "restoreAll", IDS_BRAVE_UI_RESTORE_ALL }, { "reviewSitesMsg", IDS_BRAVE_UI_REVIEW_SITE_MSG }, @@ -619,6 +620,10 @@ void CustomizeWebUIHTMLSource(const std::string &name, { "rewardsRestoreText2", IDS_BRAVE_UI_REWARDS_RESTORE_TEXT2 }, { "rewardsRestoreText3", IDS_BRAVE_UI_REWARDS_RESTORE_TEXT3 }, { "rewardsRestoreText4", IDS_BRAVE_UI_REWARDS_RESTORE_TEXT4 }, + { "rewardsRestoreWarning", IDS_BRAVE_UI_REWARDS_RESTORE_WARNING }, + { "rewardsResetConfirmation", IDS_BRAVE_UI_REWARDS_RESET_CONFIRMATION }, + { "rewardsResetTextFunds", IDS_BRAVE_UI_REWARDS_RESET_TEXT_FUNDS }, + { "rewardsResetTextNoFunds", IDS_BRAVE_UI_REWARDS_RESET_TEXT_NO_FUNDS }, { "rewardsSummary", IDS_BRAVE_UI_REWARDS_SUMMARY }, { "rewardsWhy", IDS_BRAVE_UI_REWARDS_WHY }, { "saved", IDS_BRAVE_UI_ADS_SAVED }, diff --git a/common/extensions/api/brave_rewards.json b/common/extensions/api/brave_rewards.json index c31d906f9222..cd1b4649edba 100644 --- a/common/extensions/api/brave_rewards.json +++ b/common/extensions/api/brave_rewards.json @@ -310,6 +310,23 @@ "type": "function", "description": "Fired when we get unblinded tokens", "parameters": [] + }, + { + "name": "onCompleteReset", + "type": "function", + "description": "Fired when rewards was reset", + "parameters": [ + { + "name": "properties", + "type": "object", + "properties": { + "success": { + "type": "boolean", + "description": "was reset successful" + } + } + } + ] } ], "functions": [ diff --git a/components/brave_ads/browser/ads_service.h b/components/brave_ads/browser/ads_service.h index 360adcc3adff..a1293a4c11eb 100644 --- a/components/brave_ads/browser/ads_service.h +++ b/components/brave_ads/browser/ads_service.h @@ -133,8 +133,7 @@ class AdsService : public KeyedService { const bool flagged, OnToggleFlagAdCallback callback) = 0; - virtual void ResetTheWholeState( - const base::Callback& callback) = 0; + virtual void ResetAllState() = 0; }; } // namespace brave_ads diff --git a/components/brave_ads/browser/ads_service_impl.cc b/components/brave_ads/browser/ads_service_impl.cc index 4d56402d0606..107145f8cf51 100644 --- a/components/brave_ads/browser/ads_service_impl.cc +++ b/components/brave_ads/browser/ads_service_impl.cc @@ -645,6 +645,8 @@ void AdsServiceImpl::OnResetAllState( return; } + profile_->GetPrefs()->ClearPrefsWithPrefixSilently("brave.brave_ads"); + VLOG(1) << "Successfully reset ads state"; } @@ -1676,23 +1678,6 @@ std::string AdsServiceImpl::GetStringPref( return value; } -void AdsServiceImpl::ResetTheWholeState( - const base::Callback& callback) { - SetEnabled(false); - base::PostTaskAndReplyWithResult( - file_task_runner_.get(), FROM_HERE, - base::BindOnce(&ResetOnFileTaskRunner, - base_path_), - base::BindOnce(&AdsServiceImpl::OnResetTheWholeState, - AsWeakPtr(), std::move(callback))); -} - -void AdsServiceImpl::OnResetTheWholeState( - base::Callback callback, - bool success) { - callback.Run(success); -} - void AdsServiceImpl::SetStringPref( const std::string& path, const std::string& value) { diff --git a/components/brave_ads/browser/ads_service_impl.h b/components/brave_ads/browser/ads_service_impl.h index c7e17fd2e272..7af496c5513f 100644 --- a/components/brave_ads/browser/ads_service_impl.h +++ b/components/brave_ads/browser/ads_service_impl.h @@ -182,7 +182,7 @@ class AdsServiceImpl : public AdsService, void Start(); void Stop(); - void ResetAllState(); + void ResetAllState() override; void OnResetAllState( const bool success); @@ -218,7 +218,6 @@ class AdsServiceImpl : public AdsService, const std::string& json); void RetryViewingAdNotification( const std::string& uuid); - void ResetTheWholeState(const base::Callback& callback) override; void SetAdsServiceForNotificationHandler(); void ClearAdsServiceForNotificationHandler(); @@ -280,9 +279,6 @@ class AdsServiceImpl : public AdsService, const ads::ResultCallback& callback, const bool success); - void OnResetTheWholeState(base::Callback callback, - bool success); - void OnRunDBTransaction( ads::RunDBTransactionCallback callback, ads::DBCommandResponsePtr response); diff --git a/components/brave_ads/browser/ads_service_impl_unittest.cc b/components/brave_ads/browser/ads_service_impl_unittest.cc index 841c30a8b9b3..f7776614e8ff 100644 --- a/components/brave_ads/browser/ads_service_impl_unittest.cc +++ b/components/brave_ads/browser/ads_service_impl_unittest.cc @@ -193,8 +193,6 @@ class MockRewardsService : public RewardsService { void(RewardsServicePrivateObserver* observer)); MOCK_METHOD1(RemovePrivateObserver, void(RewardsServicePrivateObserver* observer)); - MOCK_METHOD1(ResetTheWholeState, - void(const base::Callback& callback)); MOCK_METHOD1(GetAnonWalletStatus, void(brave_rewards::GetAnonWalletStatusCallback callback)); @@ -230,6 +228,8 @@ class MockRewardsService : public RewardsService { MOCK_METHOD1(ClearDiagnosticLog, void( brave_rewards::ClearDiagnosticLogCallback callback)); + + MOCK_METHOD1(CompleteReset, void(brave_rewards::SuccessCallback callback)); }; class AdsServiceTest : public testing::Test { diff --git a/components/brave_rewards/browser/rewards_notification_service.h b/components/brave_rewards/browser/rewards_notification_service.h index c78296978672..decf4a2b4f3d 100644 --- a/components/brave_rewards/browser/rewards_notification_service.h +++ b/components/brave_rewards/browser/rewards_notification_service.h @@ -66,7 +66,7 @@ class RewardsNotificationService { RewardsNotificationID id = "", bool only_once = false) = 0; virtual void DeleteNotification(RewardsNotificationID id) = 0; - virtual void DeleteAllNotifications() = 0; + virtual void DeleteAllNotifications(const bool delete_displayed) = 0; virtual void GetNotification(RewardsNotificationID id) = 0; virtual void GetNotifications() = 0; virtual const RewardsNotificationsMap& GetAllNotifications() const = 0; diff --git a/components/brave_rewards/browser/rewards_notification_service_impl.cc b/components/brave_rewards/browser/rewards_notification_service_impl.cc index d41dd84adaa8..85be752db581 100644 --- a/components/brave_rewards/browser/rewards_notification_service_impl.cc +++ b/components/brave_rewards/browser/rewards_notification_service_impl.cc @@ -92,11 +92,19 @@ void RewardsNotificationServiceImpl::DeleteNotification( OnNotificationDeleted(rewards_notification); } -void RewardsNotificationServiceImpl::DeleteAllNotifications() { +void RewardsNotificationServiceImpl::DeleteAllNotifications( + const bool delete_displayed) { + bool displayed = delete_displayed; + + #if defined(OS_ANDROID) + displayed = true; + #endif + + if (displayed) { + rewards_notifications_displayed_.clear(); + } + rewards_notifications_.clear(); -#if defined(OS_ANDROID) - rewards_notifications_displayed_.clear(); -#endif StoreRewardsNotifications(); OnAllNotificationsDeleted(); } diff --git a/components/brave_rewards/browser/rewards_notification_service_impl.h b/components/brave_rewards/browser/rewards_notification_service_impl.h index 9633531d6737..e60b55a0880b 100644 --- a/components/brave_rewards/browser/rewards_notification_service_impl.h +++ b/components/brave_rewards/browser/rewards_notification_service_impl.h @@ -37,7 +37,7 @@ class RewardsNotificationServiceImpl RewardsNotificationID id = "", bool only_once = false) override; void DeleteNotification(RewardsNotificationID id) override; - void DeleteAllNotifications() override; + void DeleteAllNotifications(const bool delete_displayed) override; void GetNotification(RewardsNotificationID id) override; void GetNotifications() override; const RewardsNotificationsMap& GetAllNotifications() const override; diff --git a/components/brave_rewards/browser/rewards_service.h b/components/brave_rewards/browser/rewards_service.h index f10f12c252a7..35593c236313 100644 --- a/components/brave_rewards/browser/rewards_service.h +++ b/components/brave_rewards/browser/rewards_service.h @@ -133,6 +133,8 @@ using LoadDiagnosticLogCallback = base::OnceCallback; using ClearDiagnosticLogCallback = base::OnceCallback; +using SuccessCallback = base::OnceCallback; + class RewardsService : public KeyedService { public: RewardsService(); @@ -273,8 +275,6 @@ class RewardsService : public KeyedService { virtual void RemovePendingContribution(const uint64_t id) = 0; virtual void RemoveAllPendingContributions() = 0; - virtual void ResetTheWholeState( - const base::Callback& callback) = 0; void AddObserver(RewardsServiceObserver* observer); void RemoveObserver(RewardsServiceObserver* observer); @@ -350,6 +350,8 @@ class RewardsService : public KeyedService { virtual void ClearDiagnosticLog( ClearDiagnosticLogCallback callback) = 0; + virtual void CompleteReset(SuccessCallback callback) = 0; + protected: base::ObserverList observers_; diff --git a/components/brave_rewards/browser/rewards_service_impl.cc b/components/brave_rewards/browser/rewards_service_impl.cc index a62aff0dc3a7..114ff3a5a3fa 100644 --- a/components/brave_rewards/browser/rewards_service_impl.cc +++ b/components/brave_rewards/browser/rewards_service_impl.cc @@ -26,6 +26,7 @@ #include "base/sequenced_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" #include "base/task_runner_util.h" @@ -111,6 +112,7 @@ namespace { const int kDiagnosticLogMaxVerboseLevel = 6; const int kTailDiagnosticLogToNumLines = 20000; const int kDiagnosticLogMaxFileSize = 10 * (1024 * 1024); +const char pref_prefix[] = "brave.rewards"; ContentSite PublisherInfoToContentSite( const ledger::PublisherInfo& publisher_info) { @@ -316,7 +318,9 @@ bool ProcessPublisher(const GURL& url) { return true; } -const char pref_prefix[] = "brave.rewards."; +std::string GetPrefPath(const std::string& name) { + return base::StringPrintf("%s.%s", pref_prefix, name.c_str()); +} } // namespace @@ -368,20 +372,21 @@ RewardsServiceImpl::RewardsServiceImpl(Profile* profile) publisher_info_db_path_(profile->GetPath().Append(kPublisher_info_db)), publisher_list_path_(profile->GetPath().Append(kPublishers_list)), rewards_base_path_(profile_->GetPath().Append(kRewardsStatePath)), - rewards_database_(new RewardsDatabase(publisher_info_db_path_)), notification_service_(new RewardsNotificationServiceImpl(profile)), - next_timer_id_(0), - reset_states_(false) { + next_timer_id_(0) { file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&EnsureRewardsBaseDirectoryExists, rewards_base_path_)); // Set up the rewards data source content::URLDataSource::Add(profile_, std::make_unique(profile_)); + ready_ = std::make_unique(); } RewardsServiceImpl::~RewardsServiceImpl() { - file_task_runner_->DeleteSoon(FROM_HERE, rewards_database_.release()); + if (rewards_database_) { + file_task_runner_->DeleteSoon(FROM_HERE, rewards_database_.release()); + } StopNotificationTimers(); } @@ -424,6 +429,9 @@ void RewardsServiceImpl::StartLedger() { return; } + rewards_database_ = + std::make_unique(publisher_info_db_path_); + BLOG(1, "Starting ledger process"); auto* connection = content::ServiceManagerConnection::GetForProcess(); @@ -545,9 +553,9 @@ void RewardsServiceImpl::RemovePrivateObserver( } void RewardsServiceImpl::CreateWallet(CreateWalletCallback callback) { - if (!ready().is_signaled()) { + if (!ready_->is_signaled()) { StartLedger(); - ready().Post( + ready_->Post( FROM_HERE, base::BindOnce(&brave_rewards::RewardsService::CreateWallet, AsWeakPtr(), @@ -845,8 +853,9 @@ void RewardsServiceImpl::OnWalletInitialized(ledger::Result result) { is_wallet_initialized_ = true; } - if (!ready_.is_signaled()) - ready_.Signal(); + if (!ready_->is_signaled()) { + ready_->Signal(); + } if (result == ledger::Result::WALLET_CREATED) { StartNotificationTimers(true); @@ -1447,8 +1456,8 @@ void RewardsServiceImpl::SetRewardsMainEnabled(bool enabled) { if (enabled) { StartLedger(); - if (!ready().is_signaled()) { - ready().Post( + if (!ready_->is_signaled()) { + ready_->Post( FROM_HERE, base::Bind(&brave_rewards::RewardsService::SetRewardsMainEnabled, base::Unretained(this), @@ -1481,6 +1490,12 @@ void RewardsServiceImpl::EnableGreaseLion(const bool enabled) { void RewardsServiceImpl::StopLedger() { BLOG(1, "Shutting down ledger process"); + if (!Connected()) { + BLOG(1, "Ledger process not running"); + Reset(); + return; + } + bat_ledger_->Shutdown( base::BindOnce(&RewardsServiceImpl::OnStopLedger, AsWeakPtr())); } @@ -1490,7 +1505,11 @@ void RewardsServiceImpl::OnStopLedger(const ledger::Result result) { 1, result != ledger::Result::LEDGER_OK, "Ledger process was not shut down successfully"); + Reset(); + BLOG(1, "Successfully shutdown ledger"); +} +void RewardsServiceImpl::Reset() { for (auto* const url_loader : url_loaders_) { delete url_loader; } @@ -1504,11 +1523,17 @@ void RewardsServiceImpl::OnStopLedger(const ledger::Result result) { } } + current_media_fetchers_.clear(); + timers_.clear(); bat_ledger_.reset(); bat_ledger_client_receiver_.reset(); bat_ledger_service_.reset(); is_wallet_initialized_ = false; - BLOG(1, "Successfully shutdown ledger"); + ready_ = std::make_unique(); + bool success = + file_task_runner_->DeleteSoon(FROM_HERE, rewards_database_.release()); + BLOG_IF(1, !success, "Database was not released"); + BLOG(1, "Successfully reset rewards service"); } void RewardsServiceImpl::GetRewardsMainEnabled( @@ -1587,9 +1612,6 @@ void RewardsServiceImpl::OnGetTransactionHistory( void RewardsServiceImpl::SaveState(const std::string& name, const std::string& value, ledger::ResultCallback callback) { - if (reset_states_) { - return; - } base::ImportantFileWriter writer( rewards_base_path_.AppendASCII(name), file_task_runner_); @@ -1626,31 +1648,6 @@ void RewardsServiceImpl::ResetState( AsWeakPtr(), std::move(callback))); } -void RewardsServiceImpl::ResetTheWholeState( - const base::Callback& callback) { - reset_states_ = true; - ClearAllNotifications(); - std::vector paths; - paths.push_back(ledger_state_path_); - paths.push_back(publisher_state_path_); - paths.push_back(publisher_info_db_path_); - paths.push_back(publisher_list_path_); - paths.push_back(rewards_base_path_); - - base::PostTaskAndReplyWithResult( - file_task_runner_.get(), FROM_HERE, - base::BindOnce(&ResetOnFilesTaskRunner, - paths), - base::BindOnce(&RewardsServiceImpl::OnResetTheWholeState, - AsWeakPtr(), std::move(callback))); -} - -void RewardsServiceImpl::OnResetTheWholeState( - base::Callback callback, - bool success) { - callback.Run(success); -} - void RewardsServiceImpl::OnSavedState( ledger::ResultCallback callback, bool success) { if (!Connected()) { @@ -1674,57 +1671,57 @@ void RewardsServiceImpl::OnLoadedState( } void RewardsServiceImpl::SetBooleanState(const std::string& name, bool value) { - profile_->GetPrefs()->SetBoolean(pref_prefix + name, value); + profile_->GetPrefs()->SetBoolean(GetPrefPath(name), value); } bool RewardsServiceImpl::GetBooleanState(const std::string& name) const { - return profile_->GetPrefs()->GetBoolean(pref_prefix + name); + return profile_->GetPrefs()->GetBoolean(GetPrefPath(name)); } void RewardsServiceImpl::SetIntegerState(const std::string& name, int value) { - profile_->GetPrefs()->SetInteger(pref_prefix + name, value); + profile_->GetPrefs()->SetInteger(GetPrefPath(name), value); } int RewardsServiceImpl::GetIntegerState(const std::string& name) const { - return profile_->GetPrefs()->GetInteger(pref_prefix + name); + return profile_->GetPrefs()->GetInteger(GetPrefPath(name)); } void RewardsServiceImpl::SetDoubleState(const std::string& name, double value) { - profile_->GetPrefs()->SetDouble(pref_prefix + name, value); + profile_->GetPrefs()->SetDouble(GetPrefPath(name), value); } double RewardsServiceImpl::GetDoubleState(const std::string& name) const { - return profile_->GetPrefs()->GetDouble(pref_prefix + name); + return profile_->GetPrefs()->GetDouble(GetPrefPath(name)); } void RewardsServiceImpl::SetStringState(const std::string& name, const std::string& value) { - profile_->GetPrefs()->SetString(pref_prefix + name, value); + profile_->GetPrefs()->SetString(GetPrefPath(name), value); } std::string RewardsServiceImpl::GetStringState(const std::string& name) const { - return profile_->GetPrefs()->GetString(pref_prefix + name); + return profile_->GetPrefs()->GetString(GetPrefPath(name)); } void RewardsServiceImpl::SetInt64State(const std::string& name, int64_t value) { - profile_->GetPrefs()->SetInt64(pref_prefix + name, value); + profile_->GetPrefs()->SetInt64(GetPrefPath(name), value); } int64_t RewardsServiceImpl::GetInt64State(const std::string& name) const { - return profile_->GetPrefs()->GetInt64(pref_prefix + name); + return profile_->GetPrefs()->GetInt64(GetPrefPath(name)); } void RewardsServiceImpl::SetUint64State(const std::string& name, uint64_t value) { - profile_->GetPrefs()->SetUint64(pref_prefix + name, value); + profile_->GetPrefs()->SetUint64(GetPrefPath(name), value); } uint64_t RewardsServiceImpl::GetUint64State(const std::string& name) const { - return profile_->GetPrefs()->GetUint64(pref_prefix + name); + return profile_->GetPrefs()->GetUint64(GetPrefPath(name)); } void RewardsServiceImpl::ClearState(const std::string& name) { - profile_->GetPrefs()->ClearPref(pref_prefix + name); + profile_->GetPrefs()->ClearPref(GetPrefPath(name)); } bool RewardsServiceImpl::GetBooleanOption(const std::string& name) const { @@ -3115,7 +3112,6 @@ void RewardsServiceImpl::OnFetchBalance(FetchBalanceCallback callback, balance->user_funds); RecordWalletBalanceP3A(true, true, static_cast(balance_minus_grant)); - RecordBackendP3AStats(); } std::move(callback).Run(static_cast(result), std::move(new_balance)); @@ -3773,6 +3769,7 @@ ledger::DBCommandResponsePtr RunDBTransactionOnFileTaskRunner( void RewardsServiceImpl::RunDBTransaction( ledger::DBTransactionPtr transaction, ledger::RunDBTransactionCallback callback) { + DCHECK(rewards_database_); base::PostTaskAndReplyWithResult( file_task_runner_.get(), FROM_HERE, @@ -3902,7 +3899,46 @@ void RewardsServiceImpl::OnGetAllPromotions( } void RewardsServiceImpl::ClearAllNotifications() { - notification_service_->DeleteAllNotifications(); + notification_service_->DeleteAllNotifications(false); +} + +void RewardsServiceImpl::CompleteReset(SuccessCallback callback) { + notification_service_->DeleteAllNotifications(true); + std::vector paths; + paths.push_back(ledger_state_path_); + paths.push_back(publisher_state_path_); + paths.push_back(publisher_info_db_path_); + paths.push_back(diagnostic_log_path_); + paths.push_back(publisher_list_path_); + paths.push_back(rewards_base_path_); + + base::PostTaskAndReplyWithResult( + file_task_runner_.get(), + FROM_HERE, + base::BindOnce(&ResetOnFilesTaskRunner, paths), + base::BindOnce( + &RewardsServiceImpl::OnCompleteReset, + AsWeakPtr(), + std::move(callback))); +} + +void RewardsServiceImpl::OnCompleteReset( + SuccessCallback callback, + const bool success) { + profile_->GetPrefs()->ClearPrefsWithPrefixSilently(pref_prefix); + + auto* ads_service = brave_ads::AdsServiceFactory::GetForProfile(profile_); + if (ads_service) { + ads_service->ResetAllState(); + } + + for (auto& observer : observers_) { + observer.OnCompleteReset(success); + } + + StopLedger(); + StopNotificationTimers(); + std::move(callback).Run(true); } } // namespace brave_rewards diff --git a/components/brave_rewards/browser/rewards_service_impl.h b/components/brave_rewards/browser/rewards_service_impl.h index c5c777d82c72..09318a0fd915 100644 --- a/components/brave_rewards/browser/rewards_service_impl.h +++ b/components/brave_rewards/browser/rewards_service_impl.h @@ -231,7 +231,6 @@ class RewardsServiceImpl : public RewardsService, const RewardsNotificationService::RewardsNotificationsMap& GetAllNotifications() override; - void ResetTheWholeState(const base::Callback& callback) override; void SetAutoContributionAmount(const double amount) const override; @@ -335,7 +334,7 @@ class RewardsServiceImpl : public RewardsService, void OnStopLedger(const ledger::Result result); - const base::OneShotEvent& ready() const { return ready_; } + void Reset(); void OnCreate(); @@ -375,8 +374,6 @@ class RewardsServiceImpl : public RewardsService, const bool recurring, const double amount); - void OnResetTheWholeState(base::Callback callback, - bool success); void OnRecurringTip(const ledger::Result result); void TriggerOnGetCurrentBalanceReport( @@ -564,6 +561,8 @@ class RewardsServiceImpl : public RewardsService, void ClearDiagnosticLog(ClearDiagnosticLogCallback callback) override; + void CompleteReset(SuccessCallback callback) override; + bool ClearDiagnosticLogOnFileTaskRunner( const base::FilePath& path); @@ -719,6 +718,8 @@ class RewardsServiceImpl : public RewardsService, GetAllPromotionsCallback callback, base::flat_map promotions); + void OnCompleteReset(SuccessCallback callback, const bool success); + #if defined(OS_ANDROID) ledger::Environment GetServerEnvironmentForAndroid(); void CreateWalletAttestationResult( @@ -754,7 +755,7 @@ class RewardsServiceImpl : public RewardsService, std::unique_ptr extension_observer_; std::unique_ptr private_observer_; - base::OneShotEvent ready_; + std::unique_ptr ready_; base::flat_set url_loaders_; std::map> timers_; std::map diff --git a/components/brave_rewards/browser/rewards_service_observer.h b/components/brave_rewards/browser/rewards_service_observer.h index f86ecb1d7bc9..259d89e9d3a5 100644 --- a/components/brave_rewards/browser/rewards_service_observer.h +++ b/components/brave_rewards/browser/rewards_service_observer.h @@ -83,6 +83,7 @@ class RewardsServiceObserver : public base::CheckedObserver { virtual void OnUnblindedTokensReady( brave_rewards::RewardsService* rewards_service) {} virtual void ReconcileStampReset() {} + virtual void OnCompleteReset(const bool success) {} // DO NOT ADD ANY MORE METHODS HERE UNLESS IT IS A BROADCAST NOTIFICATION // RewardsServiceObserver should not be used to return responses to the // caller. Method calls on RewardsService should use callbacks to return diff --git a/components/brave_rewards/browser/test/rewards_browsertest.cc b/components/brave_rewards/browser/test/rewards_browsertest.cc index 57127a067574..1a8aa1758be5 100644 --- a/components/brave_rewards/browser/test/rewards_browsertest.cc +++ b/components/brave_rewards/browser/test/rewards_browsertest.cc @@ -409,4 +409,47 @@ IN_PROC_BROWSER_TEST_F(RewardsBrowserTest, BackupRestoreModalHasNoNotice) { "#backup-recovery-key"); } +IN_PROC_BROWSER_TEST_F(RewardsBrowserTest, ResetRewards) { + rewards_browsertest_helper::EnableRewards(browser()); + + rewards_browsertest_util::WaitForElementThenClick( + contents(), + "[data-test-id='settingsButton']"); + + rewards_browsertest_util::WaitForElementToAppear( + contents(), + "#modal"); + + rewards_browsertest_util::WaitForElementThenClick( + contents(), + "[data-test-id='settings-modal-tabs-2']"); + + rewards_browsertest_util::WaitForElementToContain( + contents(), + "[data-test-id='reset-text']", + "Your Rewards data will"); +} + +IN_PROC_BROWSER_TEST_F(RewardsBrowserTest, ResetRewardsWithBAT) { + rewards_browsertest_helper::EnableRewards(browser()); + contribution_->AddBalance(promotion_->ClaimPromotionViaCode()); + + rewards_browsertest_util::WaitForElementThenClick( + contents(), + "[data-test-id='settingsButton']"); + + rewards_browsertest_util::WaitForElementToAppear( + contents(), + "#modal"); + + rewards_browsertest_util::WaitForElementThenClick( + contents(), + "[data-test-id='settings-modal-tabs-2']"); + + rewards_browsertest_util::WaitForElementToContain( + contents(), + "[data-test-id='reset-text']", + "Your 30 BATs and other Rewards"); +} + } // namespace rewards_browsertest 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 8509bfeaa1b8..ac6542feb7fa 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 @@ -149,3 +149,7 @@ export const onAnonWalletStatus = (result: RewardsExtension.Result) => action(ty }) export const onAllNotificationsDeleted = () => action(types.ON_ALL_NOTIFICATIONS_DELETED) + +export const onCompleteReset = (success: boolean) => action(types.ON_COMPLETE_RESET, { + success +}) 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 c8648c731806..977b7516e30f 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 @@ -114,6 +114,10 @@ chrome.braveRewards.onPromotionFinish.addListener((result: RewardsExtension.Resu }) }) +chrome.braveRewards.onCompleteReset.addListener((properties: { success: boolean }) => { + rewardsPanelActions.onCompleteReset(properties.success) +}) + // Fetch initial data required to refresh state, keeping in mind // that the extension process be restarted at any time. // TODO(petemill): Move to initializer function or single 'init' action. diff --git a/components/brave_rewards/resources/extension/brave_rewards/background/reducers/index.ts b/components/brave_rewards/resources/extension/brave_rewards/background/reducers/index.ts index 8c196b7bed33..a18ced46856b 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/background/reducers/index.ts +++ b/components/brave_rewards/resources/extension/brave_rewards/background/reducers/index.ts @@ -4,6 +4,7 @@ import { combineReducers } from 'redux' import * as storage from '../storage' +import { setBadgeText } from '../browserAction' // Utils import { promotionPanelReducer } from './promotion_reducer' @@ -12,13 +13,17 @@ import { rewardsPanelReducer } from './rewards_panel_reducer' const mergeReducers = (state: RewardsExtension.State | undefined, action: any) => { if (state === undefined) { state = storage.load() + setBadgeText(state) } const startingState = state state = rewardsPanelReducer(state, action) state = promotionPanelReducer(state, action) - if (state !== startingState) { + if (!state) { + state = storage.defaultState + storage.save(state) + } else if (state !== startingState) { storage.debouncedSave(state) } diff --git a/components/brave_rewards/resources/extension/brave_rewards/background/reducers/promotion_reducer.ts b/components/brave_rewards/resources/extension/brave_rewards/background/reducers/promotion_reducer.ts index 2db483b008e8..54aa9d5f1bb8 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/background/reducers/promotion_reducer.ts +++ b/components/brave_rewards/resources/extension/brave_rewards/background/reducers/promotion_reducer.ts @@ -3,7 +3,7 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ import { types } from '../../constants/rewards_panel_types' -import * as storage from '../storage' +import { Reducer } from 'redux' const getPromotion = (id: string, promotions?: RewardsExtension.Promotion[]) => { if (!promotions) { @@ -34,10 +34,7 @@ const updatePromotion = (newPromotion: RewardsExtension.Promotion, promotions: R return Object.assign(oldPromotion[0], newPromotion) } -export const promotionPanelReducer = (state: RewardsExtension.State | undefined, action: any) => { - if (state === undefined) { - state = storage.load() - } +export const promotionPanelReducer: Reducer = (state: RewardsExtension.State, action: any) => { const payload = action.payload switch (action.type) { case types.FETCH_PROMOTIONS: { 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 b378bebe8645..e9adf1b8aaf8 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 @@ -4,6 +4,7 @@ import { types } from '../../constants/rewards_panel_types' import * as storage from '../storage' +import { Reducer } from 'redux' import { setBadgeText } from '../browserAction' import { isPublisherConnectedOrVerified } from '../../utils' @@ -36,11 +37,7 @@ const updateBadgeTextAllWindows = (windows: chrome.windows.Window[], state?: Rew } -export const rewardsPanelReducer = (state: RewardsExtension.State | undefined, action: any) => { - if (state === undefined) { - state = storage.load() - setBadgeText(state) - } +export const rewardsPanelReducer: Reducer = (state: RewardsExtension.State, action: any) => { const payload = action.payload switch (action.type) { case types.CREATE_WALLET: @@ -504,6 +501,12 @@ export const rewardsPanelReducer = (state: RewardsExtension.State | undefined, a setBadgeText(state) break } + case types.ON_COMPLETE_RESET: { + if (payload.success) { + return undefined + } + break + } } return state } diff --git a/components/brave_rewards/resources/extension/brave_rewards/background/storage.ts b/components/brave_rewards/resources/extension/brave_rewards/background/storage.ts index 2f5a98989d17..c125b7fa2e67 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/background/storage.ts +++ b/components/brave_rewards/resources/extension/brave_rewards/background/storage.ts @@ -72,3 +72,7 @@ export const debouncedSave = debounce((data: RewardsExtension.State) => { window.localStorage.setItem(keyName, JSON.stringify(cleanData(data))) } }, 50) + +export const save = (data: RewardsExtension.State) => { + window.localStorage.setItem(keyName, JSON.stringify(cleanData(data))) +} 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 6a413f8efbb3..5f5a058ddd23 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/components/app.tsx +++ b/components/brave_rewards/resources/extension/brave_rewards/components/app.tsx @@ -63,8 +63,6 @@ export class RewardsPanel extends React.Component { this.props.actions.onAllNotifications(list) }) - this.handleGrantNotification() - const { externalWallet, walletCreated } = this.props.rewardsPanelData if (walletCreated) { @@ -73,10 +71,22 @@ export class RewardsPanel extends React.Component { chrome.braveRewards.getRewardsParameters((parameters: RewardsExtension.RewardsParameters) => { rewardsPanelActions.onRewardsParameters(parameters) }) + + chrome.braveRewards.getAllNotifications((list: RewardsExtension.Notification[]) => { + this.props.actions.onAllNotifications(list) + }) + + chrome.windows.getCurrent({}, this.onWindowCallback) + + this.handleGrantNotification() } } componentDidUpdate (prevProps: Props, prevState: State) { + if (!this.props.rewardsPanelData.walletCreated) { + return + } + if ( !prevProps.rewardsPanelData.walletCreated && this.props.rewardsPanelData.walletCreated 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 d531adce55da..27b8962f5979 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx +++ b/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx @@ -170,7 +170,7 @@ export class Panel extends React.Component { onBackupWallet = (id: string) => { chrome.tabs.create({ - url: 'chrome://rewards#backup-restore' + url: 'chrome://rewards#manage-wallet' }) this.actions.deleteNotification(id) } 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 1d3f4a5a1f37..fb14f46e2ef7 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 @@ -35,7 +35,8 @@ export const enum types { 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_ALL_NOTIFICATIONS_DELETED = '@@rewards_panel/ON_ALL_NOTIFICATIONS_DELETED' + ON_ALL_NOTIFICATIONS_DELETED = '@@rewards_panel/ON_ALL_NOTIFICATIONS_DELETED', + ON_COMPLETE_RESET = '@@rewards_panel/ON_COMPLETE_RESET' } // Note: This declaration must match the RewardsNotificationType enum in diff --git a/components/brave_rewards/resources/page/actions/rewards_actions.ts b/components/brave_rewards/resources/page/actions/rewards_actions.ts index f694e995b1df..65d5c3395b31 100644 --- a/components/brave_rewards/resources/page/actions/rewards_actions.ts +++ b/components/brave_rewards/resources/page/actions/rewards_actions.ts @@ -344,3 +344,9 @@ export const toggleEnableMain = (enable: boolean) => action(types.TOGGLE_ENABLE_ export const onInitialized = (result: boolean) => action(types.ON_INITIALIZED, { result }) + +export const completeReset = () => action(types.COMPLETE_RESET) + +export const onCompleteReset = (success: boolean) => action(types.ON_COMPLETE_RESET, { + success +}) diff --git a/components/brave_rewards/resources/page/brave_rewards_page.tsx b/components/brave_rewards/resources/page/brave_rewards_page.tsx index 9ea3ec841db5..100a83ab3ebc 100644 --- a/components/brave_rewards/resources/page/brave_rewards_page.tsx +++ b/components/brave_rewards/resources/page/brave_rewards_page.tsx @@ -254,6 +254,10 @@ window.cr.define('brave_rewards', function () { getActions().onInitialized(result) } + function completeReset (success: boolean) { + getActions().onCompleteReset(success) + } + return { initialize, walletCreated, @@ -301,7 +305,8 @@ window.cr.define('brave_rewards', function () { reconcileStampReset, monthlyReportIds, countryCode, - initialized + initialized, + completeReset } }) diff --git a/components/brave_rewards/resources/page/components/app.tsx b/components/brave_rewards/resources/page/components/app.tsx index cb81e550a5bc..d05ed50a5ada 100644 --- a/components/brave_rewards/resources/page/components/app.tsx +++ b/components/brave_rewards/resources/page/components/app.tsx @@ -54,6 +54,15 @@ export class App extends React.Component { creating: false }) } + + if ( + !prevProps.rewardsData.walletCreated && + this.props.rewardsData.walletCreated + ) { + this.setState({ + creating: false + }) + } } onCreateWalletClicked = () => { diff --git a/components/brave_rewards/resources/page/components/pageWallet.tsx b/components/brave_rewards/resources/page/components/pageWallet.tsx index f50ec9776078..9e5585e588d9 100644 --- a/components/brave_rewards/resources/page/components/pageWallet.tsx +++ b/components/brave_rewards/resources/page/components/pageWallet.tsx @@ -31,7 +31,6 @@ const clipboardCopy = require('clipboard-copy') interface State { activeTabId: number - modalBackup: boolean modalActivity: boolean modalPendingContribution: boolean modalVerify: boolean @@ -45,7 +44,6 @@ class PageWallet extends React.Component { super(props) this.state = { activeTabId: 0, - modalBackup: false, modalActivity: false, modalPendingContribution: false, modalVerify: false @@ -68,7 +66,7 @@ class PageWallet extends React.Component { } onModalBackupClose = () => { - if (this.urlHashIs('#backup-restore')) { + if (this.urlHashIs('#manage-wallet')) { window.location.hash = '' } this.actions.onModalBackupClose() @@ -86,8 +84,7 @@ class PageWallet extends React.Component { return this.state.activeTabId === 0 && !this.hasUserFunds() } - onModalBackupTabChange = () => { - const newTabId = this.state.activeTabId === 0 ? 1 : 0 + onModalBackupTabChange = (newTabId: number) => { this.setState({ activeTabId: newTabId }) @@ -138,6 +135,11 @@ class PageWallet extends React.Component { } } + onModalBackupOnReset = () => { + this.actions.onModalBackupClose() + this.actions.completeReset() + } + pullRecoveryKeyFromFile = (key: string) => { let recoveryKey = null if (key) { @@ -210,7 +212,7 @@ class PageWallet extends React.Component { } isBackupUrl = () => { - if (this.urlHashIs('#backup-restore')) { + if (this.urlHashIs('#manage-wallet')) { this.onModalBackupOpen() } } @@ -745,6 +747,15 @@ class PageWallet extends React.Component { ) } + getInternalFunds = () => { + const { balance } = this.props.rewardsData + if (!balance.wallets) { + return 0 + } + + return (balance.wallets['anonymous'] || 0) + (balance.wallets['blinded'] || 0) + } + render () { const { recoveryKey, @@ -810,6 +821,8 @@ class PageWallet extends React.Component { onSaveFile={this.onModalBackupOnSaveFile} onRestore={this.onModalBackupOnRestore} onVerify={this.onVerifyClick.bind(this, true)} + onReset={this.onModalBackupOnReset} + internalFunds={this.getInternalFunds()} error={walletRecoverySuccess === false ? getLocale('walletRecoveryFail') : ''} /> : null diff --git a/components/brave_rewards/resources/page/constants/rewards_types.ts b/components/brave_rewards/resources/page/constants/rewards_types.ts index 158d9c927ae1..f898a8b274bb 100644 --- a/components/brave_rewards/resources/page/constants/rewards_types.ts +++ b/components/brave_rewards/resources/page/constants/rewards_types.ts @@ -97,5 +97,7 @@ export const enum types { GET_COUNTRY_CODE = '@@rewards/GET_COUNTRY_CODE', ON_COUNTRY_CODE = '@@rewards/ON_COUNTRY_CODE', TOGGLE_ENABLE_MAIN = '@@rewards/TOGGLE_ENABLE_MAIN', - ON_INITIALIZED = '@@rewards/ON_INITIALIZED' + ON_INITIALIZED = '@@rewards/ON_INITIALIZED', + COMPLETE_RESET = '@@rewards/COMPLETE_RESET', + ON_COMPLETE_RESET = '@@rewards/ON_COMPLETE_RESET' } diff --git a/components/brave_rewards/resources/page/reducers/index.ts b/components/brave_rewards/resources/page/reducers/index.ts index b67dd4b6b0a0..7b33db74bb47 100644 --- a/components/brave_rewards/resources/page/reducers/index.ts +++ b/components/brave_rewards/resources/page/reducers/index.ts @@ -22,7 +22,10 @@ const mergeReducers = (state: Rewards.State | undefined, action: any) => { state = promotionReducer(state, action) state = publishersReducer(state, action) - if (state !== startingState) { + if (!state) { + state = storage.defaultState + storage.save(state) + } else if (state !== startingState) { storage.debouncedSave(state) } diff --git a/components/brave_rewards/resources/page/reducers/rewards_reducer.ts b/components/brave_rewards/resources/page/reducers/rewards_reducer.ts index 2cea2b59a953..eb569bff5351 100644 --- a/components/brave_rewards/resources/page/reducers/rewards_reducer.ts +++ b/components/brave_rewards/resources/page/reducers/rewards_reducer.ts @@ -434,6 +434,16 @@ const rewardsReducer: Reducer = (state: Rewards.State } break } + case types.COMPLETE_RESET: { + chrome.send('brave_rewards.completeReset') + break + } + case types.ON_COMPLETE_RESET: { + if (action.payload.success) { + return undefined + } + break + } } return state diff --git a/components/brave_rewards/resources/page/storage.ts b/components/brave_rewards/resources/page/storage.ts index c0d64577b585..b6dbdfcc73e7 100644 --- a/components/brave_rewards/resources/page/storage.ts +++ b/components/brave_rewards/resources/page/storage.ts @@ -10,9 +10,9 @@ const keyName = 'rewards-data' export const defaultState: Rewards.State = { createdTimestamp: null, enabledMain: false, - enabledAds: true, + enabledAds: false, enabledAdsMigrated: false, - enabledContribute: true, + enabledContribute: false, firstLoad: null, walletCreated: false, walletCreateFailed: false, @@ -114,3 +114,7 @@ export const debouncedSave = debounce((data: Rewards.State) => { window.localStorage.setItem(keyName, JSON.stringify(cleanData(data))) } }, 50) + +export const save = (data: Rewards.State) => { + window.localStorage.setItem(keyName, JSON.stringify(cleanData(data))) +} diff --git a/components/brave_rewards/resources/ui/components/modalBackupRestore/index.tsx b/components/brave_rewards/resources/ui/components/modalBackupRestore/index.tsx index 45ae812a5884..f2a96992ce38 100644 --- a/components/brave_rewards/resources/ui/components/modalBackupRestore/index.tsx +++ b/components/brave_rewards/resources/ui/components/modalBackupRestore/index.tsx @@ -16,7 +16,6 @@ import { StyledTitle, StyledTitleWrapper, StyledSafe, - StyledTabWrapper, StyledControlWrapper, StyledText, StyledTextWrapper @@ -30,7 +29,7 @@ export interface Props { backupKey: string activeTabId: number showBackupNotice: boolean - onTabChange: () => void + onTabChange: (newTabId: number) => void onClose: () => void onCopy?: (key: string) => void onPrint?: (key: string) => void @@ -41,6 +40,8 @@ export interface Props { id?: string testId?: string funds?: string + onReset: () => void + internalFunds: number } interface State { @@ -237,7 +238,7 @@ export default class ModalBackupRestore extends React.PureComponent - {`Backup your wallet before replacing. Or you will lose the fund, ${funds}, in your current wallet.`} + {getLocale('rewardsRestoreWarning', { funds: funds })} : null @@ -301,6 +302,55 @@ export default class ModalBackupRestore extends React.PureComponent { + const confirmed = confirm(getLocale('rewardsResetConfirmation')) + if (confirmed === true) { + this.props.onReset() + } + } + + getReset = () => { + return ( + <> + + + { + this.props.internalFunds > 0 + ? + : getLocale('rewardsResetTextNoFunds') + } + + + + + + + ) + } + + getTabContent = (activeTabId: number) => { + switch (activeTabId) { + case 0: { + return this.getBackup() + } + case 1: { + return this.getRestore() + } + case 2: { + return this.getReset() + } + } + + return null + } + render () { const { id, @@ -318,21 +368,19 @@ export default class ModalBackupRestore extends React.PureComponent - - - + { - activeTabId === 0 - ? this.getBackup() - : this.getRestore() + this.getTabContent(activeTabId) } ) diff --git a/components/brave_rewards/resources/ui/components/modalBackupRestore/style.ts b/components/brave_rewards/resources/ui/components/modalBackupRestore/style.ts index 0fced47809ca..9b64d5611812 100644 --- a/components/brave_rewards/resources/ui/components/modalBackupRestore/style.ts +++ b/components/brave_rewards/resources/ui/components/modalBackupRestore/style.ts @@ -14,7 +14,7 @@ export const StyledContent = styled<{}, 'div'>('div')` font-size: 14px; font-family: Muli, sans-serif; letter-spacing: 0; - font-weight: 200; + color: ${p => p.theme.color.text}; line-height: 26px; margin-bottom: 40px; ` @@ -85,22 +85,17 @@ export const StyledSafe = styled<{}, 'span'>('span')` color: ${p => p.theme.color.brandBatInteracting}; ` -export const StyledTabWrapper = styled<{}, 'div'>('div')` - margin: 0 auto; - max-width: 400px; -` - export const StyledControlWrapper = styled<{}, 'div'>('div')` width: 100%; margin-bottom: 30px; ` export const StyledText = styled<{}, 'p'>('p')` - font-size: 16px; - font-weight: 200; + font-size: 15px; letter-spacing: 0; line-height: 26px; font-family: Muli, sans-serif; + color: ${p => p.theme.color.text}; ` export const StyledTextWrapper = styled<{}, 'div'>('div')` diff --git a/components/brave_rewards/resources/ui/components/tab/index.tsx b/components/brave_rewards/resources/ui/components/tab/index.tsx index c00bc1391e23..bc62afd2d522 100644 --- a/components/brave_rewards/resources/ui/components/tab/index.tsx +++ b/components/brave_rewards/resources/ui/components/tab/index.tsx @@ -19,7 +19,7 @@ export interface Props { testId?: string type?: Type tabIndexSelected?: number - onChange?: (event: React.MouseEvent) => void + onChange?: (newTabId: number) => void } export default class Tab extends React.PureComponent { @@ -33,8 +33,8 @@ export default class Tab extends React.PureComponent { const tabs: React.ReactNode[] = tabTitles.map((title: string, i: number) => { return ( { return tabs } - onSwitchChange = (index: number, event: React.MouseEvent) => { + onSwitchChange = (index: number) => { if (index === this.props.tabIndexSelected) { return } if (this.props.onChange) { - this.props.onChange(event) + this.props.onChange(index) } } @@ -66,8 +66,7 @@ export default class Tab extends React.PureComponent { tabIndexSelected } = this.props - if (!tabTitles || tabTitles.length !== 2) { - console.warn('Rewards Tab currently supports 2 tab titles') + if (!tabTitles) { return null } @@ -77,7 +76,7 @@ export default class Tab extends React.PureComponent { {this.getTabs(tabTitles)} - + ) diff --git a/components/brave_rewards/resources/ui/components/tab/style.ts b/components/brave_rewards/resources/ui/components/tab/style.ts index 37ca9ae567b8..6440fcb8059c 100644 --- a/components/brave_rewards/resources/ui/components/tab/style.ts +++ b/components/brave_rewards/resources/ui/components/tab/style.ts @@ -3,13 +3,30 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ import styled from 'styled-components' -import { Type, Props } from './index' +import { Type } from './index' import palette from 'brave-ui/theme/colors' interface StyleProps { - left?: boolean selected?: boolean type?: Type + size?: number + tabIndexSelected?: number +} + +const getMargin = (index?: number, size?: number) => { + if (index === 0) { + return 4 + } + + if (!index) { + index = 0 + } + + if (index + 1 === size) { + return -4 + } + + return 0 } export const RewardsTabWrapper = styled<{}, 'div'>('div')` @@ -30,25 +47,26 @@ export const StyledSlider = styled<{}, 'div'>('div')` height: 100%; background: #DFDFE8; border-radius: 21.5px 21.5px 21.5px 21.5px; + display: flex; ` -export const StyledBullet = styled('div')` +export const StyledBullet = styled('div')` top: -17px; - width: 50%; + width: ${p => 100 / ((p && p.size) || 1)}%; height: 37px; background: ${p => p.theme.color.primaryBackground}; border-radius: 21.5px 21.5px 21.5px 21.5px; position: relative; transition: all .4s ease; - transform: translate(calc(${p => p.tabIndexSelected === 0 ? 2 : 97}%), calc(-50% - 4px)); + transform: translate(calc(${p => 100 * (((p && p.tabIndexSelected) || 0))}%), calc(-50% - 4px)); box-shadow: 0 3px 3px rgba(0, 0, 0, 0.05); + margin-left: ${p => getMargin(p.tabIndexSelected, p.size)}px; ` export const StyledTab = styled('div')` - width: 50%; display: block; height: 100%; - float: ${p => p.left ? 'left' : 'right'}; + flex-basis: 100%; ` export const StyledText = styled('div')` diff --git a/components/brave_rewards/resources/ui/stories/modal.tsx b/components/brave_rewards/resources/ui/stories/modal.tsx index f55004ac8eb4..20a1494b2c26 100644 --- a/components/brave_rewards/resources/ui/stories/modal.tsx +++ b/components/brave_rewards/resources/ui/stories/modal.tsx @@ -57,6 +57,8 @@ storiesOf('Rewards/Modal', module) onPrint={doNothing} onSaveFile={doNothing} onRestore={doNothing} + onReset={doNothing} + internalFunds={0} /> ) diff --git a/components/brave_rewards/resources/ui/stories/settings/pageWallet.tsx b/components/brave_rewards/resources/ui/stories/settings/pageWallet.tsx index 8f03d8079d7b..c248f832be2a 100644 --- a/components/brave_rewards/resources/ui/stories/settings/pageWallet.tsx +++ b/components/brave_rewards/resources/ui/stories/settings/pageWallet.tsx @@ -283,6 +283,8 @@ class PageWallet extends React.Component { onPrint={doNothing} onSaveFile={doNothing} onRestore={doNothing} + onReset={doNothing} + internalFunds={0} /> : null } diff --git a/components/definitions/chromel.d.ts b/components/definitions/chromel.d.ts index fb98b600e218..5a5620f11140 100644 --- a/components/definitions/chromel.d.ts +++ b/components/definitions/chromel.d.ts @@ -147,6 +147,10 @@ declare namespace chrome.braveRewards { } const getAnonWalletStatus: (callback: (result: RewardsExtension.Result) => void) => {} + + const onCompleteReset: { + addListener: (callback: (properties: { success: boolean }) => void) => void + } } declare namespace chrome.binance { diff --git a/components/resources/brave_components_strings.grd b/components/resources/brave_components_strings.grd index d28e6cd70e5a..9f00b63b19f2 100644 --- a/components/resources/brave_components_strings.grd +++ b/components/resources/brave_components_strings.grd @@ -598,6 +598,7 @@ Remove From Saved You’ve designated {{reservedAmount}} {{currency}} for creators who haven’t yet signed up to receive contributions. Your browser will keep trying to contribute until they verify, or until 90 days have passed. Learn more. + Reset Restore Restore All Your pinned sites have been moved to @@ -637,6 +638,10 @@ Use your recovery key to restore your wallet. Restoring with a recovery key will replace your current wallet. So make sure you empty or back up your current wallet before restoring. Enter your recovery key or + Backup your wallet before replacing. Or you will lose the fund, {{funds}}, in your current wallet. + Are you sure you want to reset your Rewards Wallet? + Your <b>{{amount}} BATs</b> and other Rewards data will be permanently lost if you reset your wallet. Please ensure you have verified your wallet with Uphold so you can keep your BAT. + Your Rewards data will be permanently lost if you reset your wallet. Token Grants Claimed Rewards Summary Why Brave Rewards? 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 958f17faca78..b550cac3e906 100644 --- a/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts +++ b/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts @@ -50,6 +50,8 @@ describe('wallet reducer', () => { expectedState.walletCreated = true expectedState.enabledMain = true expectedState.createdTimestamp = constantDate.getTime() + expectedState.enabledAds = true + expectedState.enabledContribute = true expect(assertion).toEqual({ rewardsData: expectedState diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc index 597051378c78..4a1bb46c7204 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc @@ -229,6 +229,7 @@ void Contribution::OnTimer(uint32_t timer_id) { auto callback = std::bind(&Contribution::SetRetryCounter, this, _1); + ledger_->GetContributionInfo(contribution_id, callback); return; } diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_external_wallet.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_external_wallet.cc index 503439d92883..fb509afe2c13 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_external_wallet.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_external_wallet.cc @@ -56,7 +56,6 @@ void ContributionExternalWallet::Process( _1, *wallet, callback); - ledger_->GetContributionInfo(contribution_id, get_callback); } 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 e7b2cf284604..d8bd5d59b5f8 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 @@ -840,6 +840,11 @@ void DatabaseContributionInfo::OnGetList( return; } + if (response->result->get_records().empty()) { + callback({}); + return; + } + ledger::ContributionInfoList list; std::vector contribution_ids; for (auto const& record : response->result->get_records()) {