From e12b3bf2b7267c9548f1a81a180cc7a556935c85 Mon Sep 17 00:00:00 2001 From: Nejc Zdovc Date: Tue, 4 Aug 2020 11:13:50 +0200 Subject: [PATCH 1/2] Merge pull request #6323 from brave/ksmith-rewards-1-10-upgrade Add rewards page initialization check --- browser/ui/webui/brave_rewards_page_ui.cc | 17 +++++++++++++++++ .../browser/ads_service_impl_unittest.cc | 1 + .../brave_rewards/browser/rewards_service.h | 2 ++ .../browser/rewards_service_impl.cc | 4 ++++ .../browser/rewards_service_impl.h | 2 ++ .../android_page/actions/rewards_actions.ts | 2 ++ .../resources/android_page/components/app.tsx | 2 ++ .../android_page/constants/rewards_types.ts | 1 + .../android_page/reducers/rewards_reducer.ts | 4 ++++ .../resources/android_page/storage.ts | 3 ++- .../resources/page/actions/rewards_actions.ts | 2 ++ .../resources/page/components/app.tsx | 2 ++ .../resources/page/constants/rewards_types.ts | 1 + .../resources/page/reducers/rewards_reducer.ts | 4 ++++ .../brave_rewards/resources/page/storage.ts | 3 ++- package-lock.json | 4 ++-- package.json | 2 +- 17 files changed, 51 insertions(+), 5 deletions(-) diff --git a/browser/ui/webui/brave_rewards_page_ui.cc b/browser/ui/webui/brave_rewards_page_ui.cc index 86aa6a92f729..34ef973f96b3 100644 --- a/browser/ui/webui/brave_rewards_page_ui.cc +++ b/browser/ui/webui/brave_rewards_page_ui.cc @@ -70,6 +70,7 @@ class RewardsDOMHandler : public WebUIMessageHandler, void RegisterMessages() override; private: + void IsInitialized(const base::ListValue* args); void HandleCreateWalletRequested(const base::ListValue* args); void GetRewardsParameters(const base::ListValue* args); void GetAutoContributeProperties(const base::ListValue* args); @@ -339,6 +340,9 @@ void RewardsDOMHandler::RegisterMessages() { profile, chrome::FaviconUrlFormat::kFaviconLegacy)); #endif + web_ui()->RegisterMessageCallback("brave_rewards.isInitialized", + base::BindRepeating(&RewardsDOMHandler::IsInitialized, + base::Unretained(this))); web_ui()->RegisterMessageCallback("brave_rewards.createWalletRequested", base::BindRepeating(&RewardsDOMHandler::HandleCreateWalletRequested, base::Unretained(this))); @@ -501,6 +505,19 @@ void RewardsDOMHandler::Init() { rewards_service_->AddObserver(this); } +void RewardsDOMHandler::IsInitialized( + const base::ListValue* args) { + if (!web_ui()->CanCallJavascript()) { + return; + } + + if (rewards_service_ && rewards_service_->IsInitialized()) { + web_ui()->CallJavascriptFunctionUnsafe( + "brave_rewards.initialized", + base::Value(0)); + } +} + void RewardsDOMHandler::HandleCreateWalletRequested( const base::ListValue* args) { if (!rewards_service_) diff --git a/components/brave_ads/browser/ads_service_impl_unittest.cc b/components/brave_ads/browser/ads_service_impl_unittest.cc index f7776614e8ff..afc673fda18c 100644 --- a/components/brave_ads/browser/ads_service_impl_unittest.cc +++ b/components/brave_ads/browser/ads_service_impl_unittest.cc @@ -34,6 +34,7 @@ class MockRewardsService : public RewardsService { MockRewardsService() {} ~MockRewardsService() {} + MOCK_METHOD0(IsInitialized, bool()); MOCK_METHOD1(CreateWallet, void(brave_rewards::CreateWalletCallback)); MOCK_METHOD1( GetRewardsParameters, diff --git a/components/brave_rewards/browser/rewards_service.h b/components/brave_rewards/browser/rewards_service.h index 35593c236313..20a25cf158fe 100644 --- a/components/brave_rewards/browser/rewards_service.h +++ b/components/brave_rewards/browser/rewards_service.h @@ -140,6 +140,8 @@ class RewardsService : public KeyedService { RewardsService(); ~RewardsService() override; + virtual bool IsInitialized() = 0; + virtual void CreateWallet(CreateWalletCallback callback) = 0; virtual void GetRewardsParameters(GetRewardsParametersCallback callback) = 0; virtual void GetContentSiteList( diff --git a/components/brave_rewards/browser/rewards_service_impl.cc b/components/brave_rewards/browser/rewards_service_impl.cc index 65a61a970111..fcd5a2e56549 100644 --- a/components/brave_rewards/browser/rewards_service_impl.cc +++ b/components/brave_rewards/browser/rewards_service_impl.cc @@ -401,6 +401,10 @@ void RewardsServiceImpl::ConnectionClosed() { base::TimeDelta::FromSeconds(1)); } +bool RewardsServiceImpl::IsInitialized() { + return Connected() && ready_->is_signaled(); +} + void RewardsServiceImpl::Init( std::unique_ptr extension_observer, std::unique_ptr private_observer, diff --git a/components/brave_rewards/browser/rewards_service_impl.h b/components/brave_rewards/browser/rewards_service_impl.h index ee71e92b0dee..a9ae7631239a 100644 --- a/components/brave_rewards/browser/rewards_service_impl.h +++ b/components/brave_rewards/browser/rewards_service_impl.h @@ -105,6 +105,8 @@ class RewardsServiceImpl : public RewardsService, // KeyedService: void Shutdown() override; + bool IsInitialized() override; + void Init( std::unique_ptr extension_observer, std::unique_ptr private_observer, 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 84a88a31dff8..efa076be62f5 100644 --- a/components/brave_rewards/resources/android_page/actions/rewards_actions.ts +++ b/components/brave_rewards/resources/android_page/actions/rewards_actions.ts @@ -7,6 +7,8 @@ import { action } from 'typesafe-actions' // Constant import { types } from '../constants/rewards_types' +export const isInitialized = () => action(types.IS_INITIALIZED) + export const createWallet = () => action(types.CREATE_WALLET) export const onWalletCreated = () => action(types.WALLET_CREATED) diff --git a/components/brave_rewards/resources/android_page/components/app.tsx b/components/brave_rewards/resources/android_page/components/app.tsx index 88e4a7a6d16d..e84ea93a206e 100644 --- a/components/brave_rewards/resources/android_page/components/app.tsx +++ b/components/brave_rewards/resources/android_page/components/app.tsx @@ -29,6 +29,8 @@ export class App extends React.Component { } componentDidMount () { + this.actions.isInitialized() + if (!this.props.rewardsData.walletCreated) { this.actions.checkWalletExistence() } 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 94ed88b306cf..667f7cdc970c 100644 --- a/components/brave_rewards/resources/android_page/constants/rewards_types.ts +++ b/components/brave_rewards/resources/android_page/constants/rewards_types.ts @@ -3,6 +3,7 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ export const enum types { + IS_INITIALIZED = '@@rewards/IS_INITIALIZED', CREATE_WALLET = '@@rewards/CREATE_WALLET', WALLET_CREATED = '@@rewards/WALLET_CREATED', WALLET_CREATE_FAILED = '@@rewards/WALLET_CREATE_FAILED', 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 9b074d1dbf39..bdac2fc9d5a5 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,10 @@ import { defaultState } from '../storage' const rewardsReducer: Reducer = (state: Rewards.State, action) => { switch (action.type) { + case types.IS_INITIALIZED: { + chrome.send('brave_rewards.isInitialized') + break + } case types.TOGGLE_ENABLE_MAIN: { if (state.initializing) { break diff --git a/components/brave_rewards/resources/android_page/storage.ts b/components/brave_rewards/resources/android_page/storage.ts index 1bf94defaced..df36a81d397f 100644 --- a/components/brave_rewards/resources/android_page/storage.ts +++ b/components/brave_rewards/resources/android_page/storage.ts @@ -79,7 +79,7 @@ export const defaultState: Rewards.State = { autoContributeChoices: [], rate: 0 }, - initializing: false + initializing: true } const cleanData = (state: Rewards.State) => { @@ -100,6 +100,7 @@ export const load = (): Rewards.State => { if (data) { try { state = JSON.parse(data) + state.initializing = true } catch (e) { console.error('Could not parse local storage data: ', e) } diff --git a/components/brave_rewards/resources/page/actions/rewards_actions.ts b/components/brave_rewards/resources/page/actions/rewards_actions.ts index d9bebed30798..94ab0ab691a6 100644 --- a/components/brave_rewards/resources/page/actions/rewards_actions.ts +++ b/components/brave_rewards/resources/page/actions/rewards_actions.ts @@ -7,6 +7,8 @@ import { action } from 'typesafe-actions' // Constant import { types } from '../constants/rewards_types' +export const isInitialized = () => action(types.IS_INITIALIZED) + export const createWallet = () => action(types.CREATE_WALLET) export const onWalletCreated = () => action(types.WALLET_CREATED) diff --git a/components/brave_rewards/resources/page/components/app.tsx b/components/brave_rewards/resources/page/components/app.tsx index d05ed50a5ada..a120c653c80a 100644 --- a/components/brave_rewards/resources/page/components/app.tsx +++ b/components/brave_rewards/resources/page/components/app.tsx @@ -29,6 +29,8 @@ export class App extends React.Component { } componentDidMount () { + this.actions.isInitialized() + if (!this.props.rewardsData.walletCreated) { this.actions.checkWalletExistence() } diff --git a/components/brave_rewards/resources/page/constants/rewards_types.ts b/components/brave_rewards/resources/page/constants/rewards_types.ts index f898a8b274bb..90f5c08432a0 100644 --- a/components/brave_rewards/resources/page/constants/rewards_types.ts +++ b/components/brave_rewards/resources/page/constants/rewards_types.ts @@ -3,6 +3,7 @@ * You can obtain one at http://mozilla.org/MPL/2.0/. */ export const enum types { + IS_INITIALIZED = '@@rewards/IS_INITIALIZED', CREATE_WALLET = '@@rewards/CREATE_WALLET', WALLET_CREATED = '@@rewards/WALLET_CREATED', WALLET_CREATE_FAILED = '@@rewards/WALLET_CREATE_FAILED', diff --git a/components/brave_rewards/resources/page/reducers/rewards_reducer.ts b/components/brave_rewards/resources/page/reducers/rewards_reducer.ts index e8800bdbae54..b55e51fd3f57 100644 --- a/components/brave_rewards/resources/page/reducers/rewards_reducer.ts +++ b/components/brave_rewards/resources/page/reducers/rewards_reducer.ts @@ -10,6 +10,10 @@ import { defaultState } from '../storage' const rewardsReducer: Reducer = (state: Rewards.State, action) => { switch (action.type) { + case types.IS_INITIALIZED: { + chrome.send('brave_rewards.isInitialized') + break + } case types.TOGGLE_ENABLE_MAIN: { if (state.initializing) { break diff --git a/components/brave_rewards/resources/page/storage.ts b/components/brave_rewards/resources/page/storage.ts index 24827ec32458..f2691be20308 100644 --- a/components/brave_rewards/resources/page/storage.ts +++ b/components/brave_rewards/resources/page/storage.ts @@ -79,7 +79,7 @@ export const defaultState: Rewards.State = { autoContributeChoices: [], rate: 0 }, - initializing: false + initializing: true } const cleanData = (state: Rewards.State) => { @@ -102,6 +102,7 @@ export const load = (): Rewards.State => { if (data) { try { state = JSON.parse(data) + state.initializing = true } catch (e) { console.error('Could not parse local storage data: ', e) } diff --git a/package-lock.json b/package-lock.json index e340df153a0b..3a0709039b48 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7206,8 +7206,8 @@ } }, "brave-ui": { - "version": "github:brave/brave-ui#303a9d6424950a31836902f9bf2c03a0c174efda", - "from": "github:brave/brave-ui#303a9d6424950a31836902f9bf2c03a0c174efda", + "version": "github:brave/brave-ui#36f3cd135399060641123136feb8253e53d68499", + "from": "github:brave/brave-ui#36f3cd135399060641123136feb8253e53d68499", "dev": true, "requires": { "@ctrl/tinycolor": "^2.2.1", diff --git a/package.json b/package.json index f424321b2800..86f3f3d71f56 100644 --- a/package.json +++ b/package.json @@ -297,7 +297,7 @@ "@types/storybook__react": "^4.0.2", "acorn": "^7.1.1", "babel-loader": "^8.1.0", - "brave-ui": "github:brave/brave-ui#303a9d6424950a31836902f9bf2c03a0c174efda", + "brave-ui": "github:brave/brave-ui#36f3cd135399060641123136feb8253e53d68499", "css-loader": "^2.1.1", "csstype": "^2.5.5", "deep-freeze-node": "^1.1.3", From 0d626878ca223eb5a4a98fde87c4ae489f5136d9 Mon Sep 17 00:00:00 2001 From: NejcZdovc Date: Mon, 3 Aug 2020 15:21:05 +0200 Subject: [PATCH 2/2] Adds initialized to panel flow Resolves https://github.com/brave/brave-browser/issues/11038 --- .../extension_rewards_service_observer.cc | 29 ++++++- browser/extensions/api/brave_rewards_api.cc | 18 +++++ browser/extensions/api/brave_rewards_api.h | 10 +++ common/extensions/api/brave_rewards.json | 38 +++++++++- .../actions/rewards_actions.ts | 4 + .../brave_new_tab_ui/apiEventsToStore.ts | 62 +++++++++++---- .../constants/rewards_types.ts | 3 +- .../reducers/rewards_reducer.ts | 27 ++++--- .../android_page/components/settingsPage.tsx | 4 - .../android_page/reducers/rewards_reducer.ts | 12 +-- .../actions/rewards_panel_actions.ts | 14 +++- .../background/events/rewardsEvents.ts | 11 ++- .../background/reducers/index.ts | 5 +- .../background/reducers/promotion_reducer.ts | 4 + .../reducers/rewards_panel_reducer.ts | 75 ++++++++++++++----- .../brave_rewards/background/storage.ts | 8 +- .../brave_rewards/components/app.tsx | 24 +++++- .../brave_rewards/components/panel.tsx | 56 ++++++++------ .../constants/rewards_panel_types.ts | 8 +- .../page/components/settingsPage.tsx | 4 - .../page/reducers/rewards_reducer.ts | 12 +-- components/definitions/chromel.d.ts | 9 ++- components/definitions/rewardsExtensions.d.ts | 1 + .../page/components/app_test.tsx | 3 +- .../page/reducers/wallet_reducer_test.ts | 2 + 25 files changed, 335 insertions(+), 108 deletions(-) diff --git a/browser/brave_rewards/extension_rewards_service_observer.cc b/browser/brave_rewards/extension_rewards_service_observer.cc index 265be3d281ad..742e5a8e3c7f 100644 --- a/browser/brave_rewards/extension_rewards_service_observer.cc +++ b/browser/brave_rewards/extension_rewards_service_observer.cc @@ -34,13 +34,38 @@ void ExtensionRewardsServiceObserver::OnWalletInitialized( return; } + // ledger::Result::WALLET_CREATED + if (result == 12) { + auto args = std::make_unique(); + std::unique_ptr event(new extensions::Event( + extensions::events::BRAVE_START, + extensions::api::brave_rewards::WalletCreated::kEventName, + std::move(args))); + event_router->BroadcastEvent(std::move(event)); + return; + } + + if (result != 3 && result != 0) { + // Report back all errors except when ledger_state is missing + std::unique_ptr args( + extensions::api::brave_rewards::WalletCreationFailed::Create( + result).release()); + + std::unique_ptr event(new extensions::Event( + extensions::events::BRAVE_START, + extensions::api::brave_rewards::WalletCreationFailed::kEventName, + std::move(args))); + event_router->BroadcastEvent(std::move(event)); + return; + } + std::unique_ptr args( - extensions::api::brave_rewards::OnWalletInitialized::Create( + extensions::api::brave_rewards::Initialized::Create( result).release()); std::unique_ptr event(new extensions::Event( extensions::events::BRAVE_START, - extensions::api::brave_rewards::OnWalletInitialized::kEventName, + extensions::api::brave_rewards::Initialized::kEventName, std::move(args))); event_router->BroadcastEvent(std::move(event)); } diff --git a/browser/extensions/api/brave_rewards_api.cc b/browser/extensions/api/brave_rewards_api.cc index 33b2a4f52552..8930b134cc45 100644 --- a/browser/extensions/api/brave_rewards_api.cc +++ b/browser/extensions/api/brave_rewards_api.cc @@ -1174,5 +1174,23 @@ void BraveRewardsGetAnonWalletStatusFunction::OnGetAnonWalletStatus( Respond(OneArgument(std::make_unique(static_cast(result)))); } +BraveRewardsIsInitializedFunction:: +~BraveRewardsIsInitializedFunction() = default; + +ExtensionFunction::ResponseAction +BraveRewardsIsInitializedFunction::Run() { + Profile* profile = Profile::FromBrowserContext(browser_context()); + RewardsService* rewards_service = + RewardsServiceFactory::GetForProfile(profile); + + if (!rewards_service) { + return RespondNow(Error("Rewards service is not initialized")); + } + + const bool initialized = rewards_service->IsInitialized(); + return RespondNow( + OneArgument(std::make_unique(initialized))); +} + } // namespace api } // namespace extensions diff --git a/browser/extensions/api/brave_rewards_api.h b/browser/extensions/api/brave_rewards_api.h index e753ec0ba3de..a891f9c15b6f 100644 --- a/browser/extensions/api/brave_rewards_api.h +++ b/browser/extensions/api/brave_rewards_api.h @@ -466,6 +466,16 @@ class BraveRewardsGetAnonWalletStatusFunction void OnGetAnonWalletStatus(const uint32_t result); }; +class BraveRewardsIsInitializedFunction : public ExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("braveRewards.isInitialized", UNKNOWN) + + protected: + ~BraveRewardsIsInitializedFunction() override; + + ResponseAction Run() override; +}; + } // namespace api } // namespace extensions diff --git a/common/extensions/api/brave_rewards.json b/common/extensions/api/brave_rewards.json index fb8741227769..cfefa935e0b5 100644 --- a/common/extensions/api/brave_rewards.json +++ b/common/extensions/api/brave_rewards.json @@ -11,11 +11,26 @@ }, "events": [ { - "name": "onWalletInitialized", + "name": "walletCreated", + "type": "function", + "description": "Fired when wallet is created", + "parameters": [] + }, + { + "name": "walletCreationFailed", + "type": "function", + "description": "Fired when wallet creation failed", + "parameters": [{ + "name": "result", + "type": "integer" + } + ] + }, + { + "name": "initialized", "type": "function", "description": "Fired when wallet is initialized", - "parameters": [ - { + "parameters": [{ "name": "result", "type": "integer" } @@ -1103,6 +1118,23 @@ ] } ] + }, + { + "name": "isInitialized", + "type": "function", + "description": "Is ledger process initialized", + "parameters": [ + { + "type": "function", + "name": "callback", + "parameters": [ + { + "name": "initialized", + "type": "boolean" + } + ] + } + ] } ] } diff --git a/components/brave_new_tab_ui/actions/rewards_actions.ts b/components/brave_new_tab_ui/actions/rewards_actions.ts index 4427fc76dcbe..3c1c722617d6 100644 --- a/components/brave_new_tab_ui/actions/rewards_actions.ts +++ b/components/brave_new_tab_ui/actions/rewards_actions.ts @@ -61,3 +61,7 @@ export const onPromotionFinish = (result: NewTab.RewardsResult, promotion: NewTa export const setOnlyAnonWallet = (onlyAnonWallet: boolean) => action(types.SET_ONLY_ANON_WALLET, { onlyAnonWallet }) + +export const onCompleteReset = (success: boolean) => action(types.ON_COMPLETE_RESET, { + success +}) diff --git a/components/brave_new_tab_ui/apiEventsToStore.ts b/components/brave_new_tab_ui/apiEventsToStore.ts index 7c83758b5bb2..546386acf1f1 100644 --- a/components/brave_new_tab_ui/apiEventsToStore.ts +++ b/components/brave_new_tab_ui/apiEventsToStore.ts @@ -35,7 +35,6 @@ export function wireApiEventsToStore () { .then((initialData) => { if (initialData.preferences.showRewards) { rewardsInitData() - setRewardsFetchInterval() } binanceInitData() getActions().setInitialData(initialData) @@ -55,10 +54,16 @@ export function rewardsInitData () { getRewardsPreInitialData() .then((preInitialRewardsData) => { getActions().setPreInitialRewardsData(preInitialRewardsData) + chrome.braveRewards.getWalletExists((exists: boolean) => { + getActions().onWalletExists(exists) if (exists) { + if (!preInitialRewardsData.enabledMain) { + return + } + fetchCreatedWalletData() - getActions().onWalletExists(exists) + setRewardsFetchInterval() } }) }) @@ -83,32 +88,55 @@ function binanceInitData () { function setRewardsFetchInterval () { window.setInterval(() => { - chrome.braveRewards.getWalletExists((exists: boolean) => { - if (exists) { - fetchCreatedWalletData() + chrome.braveRewards.getRewardsMainEnabled((enabledMain: boolean) => { + if (!enabledMain) { + return } + chrome.braveRewards.getWalletExists((exists: boolean) => { + if (exists) { + fetchCreatedWalletData() + } + }) }) }, 30000) } function fetchCreatedWalletData () { - getRewardsInitialData() - .then((initialRewardsData) => { - getActions().setInitialRewardsData(initialRewardsData) - }) - .catch(e => { - console.error('Error fetching initial rewards data: ', e) + chrome.braveRewards.isInitialized((initialized: boolean) => { + if (!initialized) { + return + } + + getRewardsInitialData() + .then((initialRewardsData) => { + getActions().setInitialRewardsData(initialRewardsData) + }) + .catch(e => { + console.error('Error fetching initial rewards data: ', e) + }) }) } -chrome.braveRewards.onWalletInitialized.addListener((result: any | NewTab.RewardsResult) => { +chrome.braveRewards.walletCreated.addListener(() => { + getActions().onWalletInitialized(12) +}) + +chrome.braveRewards.walletCreationFailed.addListener((result: any | NewTab.RewardsResult) => { getActions().onWalletInitialized(result) }) +chrome.braveRewards.initialized.addListener((result: any | NewTab.RewardsResult) => { + rewardsInitData() +}) + chrome.braveRewards.onEnabledMain.addListener((enabledMain: boolean) => { - chrome.braveRewards.getAdsEnabled((enabledAds: boolean) => { - getActions().onEnabledMain(enabledMain, enabledAds) - }) + if (enabledMain) { + chrome.braveRewards.getAdsEnabled((enabledAds: boolean) => { + getActions().onEnabledMain(enabledMain, enabledAds) + }) + } else { + getActions().onEnabledMain(false, false) + } }) chrome.braveRewards.onAdsEnabled.addListener((enabled: boolean) => { @@ -122,3 +150,7 @@ chrome.braveRewards.onPromotions.addListener((result: number, promotions: NewTab chrome.braveRewards.onPromotionFinish.addListener((result: number, promotion: NewTab.Promotion) => { getActions().onPromotionFinish(result, promotion) }) + +chrome.braveRewards.onCompleteReset.addListener((properties: { success: boolean }) => { + getActions().onCompleteReset(properties.success) +}) diff --git a/components/brave_new_tab_ui/constants/rewards_types.ts b/components/brave_new_tab_ui/constants/rewards_types.ts index 2437d75af76b..dd43ad6b47ff 100644 --- a/components/brave_new_tab_ui/constants/rewards_types.ts +++ b/components/brave_new_tab_ui/constants/rewards_types.ts @@ -18,5 +18,6 @@ export const enum types { SET_INITIAL_REWARDS_DATA = '@@rewards/SET_INITIAL_REWARDS_DATA', SET_PRE_INITIAL_REWARDS_DATA = '@@rewards/SET_PRE_INITIAL_REWARDS_DATA', ON_WIDGET_POSITION_CHANGED = '@@rewards/ON_WIDGET_POSITION_CHANGED', - SET_ONLY_ANON_WALLET = '@@rewards/SET_ONLY_ANON_WALLET' + SET_ONLY_ANON_WALLET = '@@rewards/SET_ONLY_ANON_WALLET', + ON_COMPLETE_RESET = '@@rewards/ON_COMPLETE_RESET' } diff --git a/components/brave_new_tab_ui/reducers/rewards_reducer.ts b/components/brave_new_tab_ui/reducers/rewards_reducer.ts index 20f29cb14564..57618399a554 100644 --- a/components/brave_new_tab_ui/reducers/rewards_reducer.ts +++ b/components/brave_new_tab_ui/reducers/rewards_reducer.ts @@ -34,18 +34,13 @@ const rewardsReducer: Reducer = (state: NewTab.State, state.rewardsState.walletCorrupted = true break case NewTab.RewardsResult.WALLET_CREATED: + state.rewardsState.enabledMain = true state.rewardsState.walletCreated = true state.rewardsState.walletCreateFailed = false state.rewardsState.walletCreating = false state.rewardsState.walletCorrupted = false chrome.braveRewards.saveAdsSetting('adsEnabled', 'true') break - case NewTab.RewardsResult.LEDGER_OK: - state.rewardsState.walletCreateFailed = true - state.rewardsState.walletCreating = false - state.rewardsState.walletCreated = false - state.rewardsState.walletCorrupted = false - break } break } @@ -148,10 +143,7 @@ const rewardsReducer: Reducer = (state: NewTab.State, break case types.ON_WALLET_EXISTS: - if (!payload.exists || state.rewardsState.walletCreated) { - break - } - state.rewardsState.walletCreated = true + state.rewardsState.walletCreated = payload.exists break case types.SET_PRE_INITIAL_REWARDS_DATA: @@ -195,6 +187,21 @@ const rewardsReducer: Reducer = (state: NewTab.State, } } break + case types.ON_COMPLETE_RESET: + state = { ...state } + state = { + ...state, + rewardsState: { + ...state.rewardsState, + enabledMain: false, + enabledAds: false, + walletCreated: false, + walletCreating: false, + walletCreateFailed: false, + walletCorrupted: false + } + } + break default: break diff --git a/components/brave_rewards/resources/android_page/components/settingsPage.tsx b/components/brave_rewards/resources/android_page/components/settingsPage.tsx index d607b6536258..344edd6f791b 100644 --- a/components/brave_rewards/resources/android_page/components/settingsPage.tsx +++ b/components/brave_rewards/resources/android_page/components/settingsPage.tsx @@ -51,10 +51,6 @@ class SettingsPage extends React.Component { onToggle = () => { this.setState({ mainToggle: !this.state.mainToggle }) - if (this.props.rewardsData.initializing) { - return - } - this.actions.toggleEnableMain(!this.props.rewardsData.enabledMain) } 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 bdac2fc9d5a5..e01095b5cf87 100644 --- a/components/brave_rewards/resources/android_page/reducers/rewards_reducer.ts +++ b/components/brave_rewards/resources/android_page/reducers/rewards_reducer.ts @@ -15,17 +15,14 @@ const rewardsReducer: Reducer = (state: Rewards.State break } case types.TOGGLE_ENABLE_MAIN: { - if (state.initializing) { + if (state.initializing && state.enabledMain) { break } state = { ...state } const key = 'enabledMain' const enable = action.payload.enable - - if (enable) { - state.initializing = true - } + state.initializing = true state[key] = enable chrome.send('brave_rewards.saveSetting', [key, enable.toString()]) @@ -169,6 +166,11 @@ const rewardsReducer: Reducer = (state: Rewards.State break } + if (!enabled) { + state.balance = defaultState.balance + state.promotions = [] + } + state.enabledMain = enabled break } 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 ac6542feb7fa..eba0bd181c79 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 @@ -9,7 +9,9 @@ import { types } from '../constants/rewards_panel_types' export const createWallet = () => action(types.CREATE_WALLET, {}) -export const onWalletInitialized = (result: RewardsExtension.Result) => action(types.ON_WALLET_INITIALIZED, { +export const walletCreated = () => action(types.WALLET_CREATED) + +export const walletCreationFailed = (result: RewardsExtension.Result) => action(types.WALLET_CREATION_FAILED, { result }) @@ -153,3 +155,13 @@ export const onAllNotificationsDeleted = () => action(types.ON_ALL_NOTIFICATIONS export const onCompleteReset = (success: boolean) => action(types.ON_COMPLETE_RESET, { success }) + +export const toggleEnableMain = (enable: boolean) => action(types.TOGGLE_ENABLE_MAIN, { + enable +}) + +export const initialized = () => action(types.INITIALIZED) + +export const walletExists = (exists: boolean) => action(types.WALLET_EXISTS, { + exists +}) 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 977b7516e30f..f94d166896e9 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 @@ -5,8 +5,11 @@ import rewardsPanelActions from '../actions/rewardsPanelActions' // Handle all rewards events and pass to actions -chrome.braveRewards.onWalletInitialized.addListener((result: RewardsExtension.Result) => { - rewardsPanelActions.onWalletInitialized(result) +chrome.braveRewards.walletCreated.addListener(() => { + rewardsPanelActions.walletCreated() +}) +chrome.braveRewards.walletCreationFailed.addListener((result: RewardsExtension.Result) => { + rewardsPanelActions.walletCreationFailed(result) }) chrome.braveRewards.onPublisherData.addListener((windowId: number, publisher: RewardsExtension.Publisher) => { @@ -118,6 +121,10 @@ chrome.braveRewards.onCompleteReset.addListener((properties: { success: boolean rewardsPanelActions.onCompleteReset(properties.success) }) +chrome.braveRewards.initialized.addListener((result: RewardsExtension.Result) => { + rewardsPanelActions.initialized() +}) + // 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 a18ced46856b..4c6b8e4fc1b8 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 @@ -22,8 +22,9 @@ const mergeReducers = (state: RewardsExtension.State | undefined, action: any) = if (!state) { state = storage.defaultState - storage.save(state) - } else if (state !== startingState) { + } + + 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 54aa9d5f1bb8..c70672f1ab39 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 @@ -35,6 +35,10 @@ const updatePromotion = (newPromotion: RewardsExtension.Promotion, promotions: R } export const promotionPanelReducer: Reducer = (state: RewardsExtension.State, action: any) => { + if (!state) { + return + } + 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 e9adf1b8aaf8..aa8496d64952 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 @@ -38,8 +38,25 @@ const updateBadgeTextAllWindows = (windows: chrome.windows.Window[], state?: Rew } export const rewardsPanelReducer: Reducer = (state: RewardsExtension.State, action: any) => { + if (!state) { + return + } const payload = action.payload switch (action.type) { + case types.TOGGLE_ENABLE_MAIN: { + if (state.initializing && state.enabledMain) { + break + } + + state = { ...state } + const key = 'enabledMain' + const enable = action.payload.enable + state.initializing = true + + state[key] = enable + chrome.braveRewards.saveSetting(key, enable ? '1' : '0') + break + } case types.CREATE_WALLET: chrome.braveRewards.createWallet() state = { ...state } @@ -47,28 +64,34 @@ export const rewardsPanelReducer: Reducer = state.walletCreateFailed = false state.walletCreated = false state.walletCorrupted = false + state.initializing = true break - case types.ON_WALLET_INITIALIZED: { - const result: RewardsExtension.Result = payload.result + case types.WALLET_CREATED: { state = { ...state } - if (result === RewardsExtension.Result.WALLET_CREATED) { - state.walletCreated = true - state.walletCreateFailed = false - state.walletCreating = false - state.walletCorrupted = false - state.enabledMain = true - chrome.braveRewards.saveAdsSetting('adsEnabled', 'true') - chrome.storage.local.get(['is_dismissed'], function (result) { - if (result && result['is_dismissed'] === 'false') { - chrome.browserAction.setBadgeText({ - text: '' - }) - chrome.storage.local.remove(['is_dismissed']) - } - }) - } else if (result === RewardsExtension.Result.WALLET_CORRUPT) { + state.initializing = false + state.walletCreated = true + state.walletCreateFailed = false + state.walletCreating = false + state.walletCorrupted = false + state.enabledMain = true + chrome.braveRewards.saveAdsSetting('adsEnabled', 'true') + chrome.storage.local.get(['is_dismissed'], function (result) { + if (result && result['is_dismissed'] === 'false') { + chrome.browserAction.setBadgeText({ + text: '' + }) + chrome.storage.local.remove(['is_dismissed']) + } + }) + break + } + case types.WALLET_CREATION_FAILED: { + state = { ...state } + const result: RewardsExtension.Result = payload.result + state.initializing = false + if (result === RewardsExtension.Result.WALLET_CORRUPT) { state.walletCorrupted = true - } else if (result !== RewardsExtension.Result.LEDGER_OK) { + } else { state.walletCreateFailed = true state.walletCreating = false state.walletCreated = false @@ -507,6 +530,20 @@ export const rewardsPanelReducer: Reducer = } break } + case types.INITIALIZED: { + state = { + ...state, + initializing: false + } + break + } + case types.WALLET_EXISTS: { + state = { + ...state, + walletCreated: payload.exists + } + 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 c125b7fa2e67..8f56cda378c4 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/background/storage.ts +++ b/components/brave_rewards/resources/extension/brave_rewards/background/storage.ts @@ -35,7 +35,8 @@ export const defaultState: RewardsExtension.State = { balance: { total: 0, wallets: {} - } + }, + initializing: true } const cleanData = (state: RewardsExtension.State) => { @@ -60,6 +61,7 @@ export const load = (): RewardsExtension.State => { if (data) { try { state = JSON.parse(data) + state.initializing = true } catch (e) { console.error('Could not parse local storage data: ', e) } @@ -72,7 +74,3 @@ 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 1162953880d9..78b8ec71c8b1 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/components/app.tsx +++ b/components/brave_rewards/resources/extension/brave_rewards/components/app.tsx @@ -40,6 +40,16 @@ export class RewardsPanel extends React.Component { } componentDidMount () { + chrome.braveRewards.getWalletExists((exists: boolean) => { + this.props.actions.walletExists(exists) + }) + + chrome.braveRewards.isInitialized((initialized: boolean) => { + if (initialized) { + this.props.actions.initialized() + } + }) + chrome.braveRewards.onlyAnonWallet((only: boolean) => { this.setState({ onlyAnonWallet: !!only @@ -49,11 +59,10 @@ export class RewardsPanel extends React.Component { chrome.braveRewards.getRewardsMainEnabled(((enabled: boolean) => { this.props.actions.onEnabledMain(enabled) - if (enabled) { + if (enabled && !this.props.rewardsPanelData.initializing) { this.startRewards() } })) - } startRewards = () => { @@ -94,8 +103,15 @@ export class RewardsPanel extends React.Component { this.getTabData() } + if (this.props.rewardsPanelData.enabledMain && + prevProps.rewardsPanelData.initializing && + !this.props.rewardsPanelData.initializing) { + this.startRewards() + } + if (!prevProps.rewardsPanelData.enabledMain && - this.props.rewardsPanelData.enabledMain) { + this.props.rewardsPanelData.enabledMain && + !this.props.rewardsPanelData.initializing) { this.startRewards() } } @@ -237,7 +253,7 @@ export class RewardsPanel extends React.Component { } enableRewards = () => { - this.props.actions.onSettingSave('enabledMain', '1') + this.props.actions.toggleEnableMain(true) } openRewardsAddFunds = () => { 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 082a7a3ac64a..dafc540f8ef9 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx +++ b/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx @@ -62,6 +62,40 @@ export class Panel extends React.Component { }) } + if (!this.props.rewardsPanelData.initializing) { + this.startRewards() + } + } + + componentDidUpdate (prevProps: Props, prevState: State) { + const publisher: RewardsExtension.Publisher | undefined = this.getPublisher() + const newKey = publisher && publisher.publisher_key + + if (!prevState.publisherKey && newKey) { + this.setState({ + showSummary: false, + publisherKey: newKey + }) + } else if (prevState.publisherKey && !newKey) { + this.setState({ + showSummary: true, + publisherKey: null + }) + } + + if (!prevProps.rewardsPanelData.enabledMain && + this.props.rewardsPanelData.enabledMain && + !this.props.rewardsPanelData.initializing) { + this.actions.fetchPromotions() + } + + if (prevProps.rewardsPanelData.initializing && + !this.props.rewardsPanelData.initializing) { + this.startRewards() + } + } + + startRewards () { chrome.braveRewards.getACEnabled((enabled: boolean) => { this.props.actions.onEnabledAC(enabled) }) @@ -86,28 +120,6 @@ export class Panel extends React.Component { }) } - componentDidUpdate (prevProps: Props, prevState: State) { - const publisher: RewardsExtension.Publisher | undefined = this.getPublisher() - const newKey = publisher && publisher.publisher_key - - if (!prevState.publisherKey && newKey) { - this.setState({ - showSummary: false, - publisherKey: newKey - }) - } else if (prevState.publisherKey && !newKey) { - this.setState({ - showSummary: true, - publisherKey: null - }) - } - - if (!prevProps.rewardsPanelData.enabledMain && - this.props.rewardsPanelData.enabledMain) { - this.actions.fetchPromotions() - } - } - componentWillUnmount () { clearTimeout(this.delayTimer) } 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 fb14f46e2ef7..695b6b6a206e 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 @@ -4,7 +4,8 @@ export const enum types { CREATE_WALLET = '@@rewards_panel/CREATE_WALLET', - ON_WALLET_INITIALIZED = '@@rewards_panel/ON_WALLET_INITIALIZED', + WALLET_CREATED = '@@rewards_panel/WALLET_CREATED', + WALLET_CREATION_FAILED = '@@rewards_panel/WALLET_CREATION_FAILED', ON_TAB_RETRIEVED = '@@rewards_panel/ON_TAB_RETRIEVED', ON_PUBLISHER_DATA = '@@rewards_panel/ON_PUBLISHER_DATA', ON_REWARDS_PARAMETERS = '@@rewards_panel/ON_REWARDS_PARAMETERS', @@ -36,7 +37,10 @@ export const enum types { 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_COMPLETE_RESET = '@@rewards_panel/ON_COMPLETE_RESET' + ON_COMPLETE_RESET = '@@rewards_panel/ON_COMPLETE_RESET', + TOGGLE_ENABLE_MAIN = '@@rewards_panel/TOGGLE_ENABLE_MAIN', + INITIALIZED = '@@rewards_panel/INITIALIZED', + WALLET_EXISTS = '@@rewards_panel/WALLET_EXISTS' } // Note: This declaration must match the RewardsNotificationType enum in diff --git a/components/brave_rewards/resources/page/components/settingsPage.tsx b/components/brave_rewards/resources/page/components/settingsPage.tsx index c4a0d5223b90..822fcca0a907 100644 --- a/components/brave_rewards/resources/page/components/settingsPage.tsx +++ b/components/brave_rewards/resources/page/components/settingsPage.tsx @@ -45,10 +45,6 @@ class SettingsPage extends React.Component { } onToggle = () => { - if (this.props.rewardsData.initializing) { - return - } - this.actions.toggleEnableMain(!this.props.rewardsData.enabledMain) } diff --git a/components/brave_rewards/resources/page/reducers/rewards_reducer.ts b/components/brave_rewards/resources/page/reducers/rewards_reducer.ts index b55e51fd3f57..d14d97f14676 100644 --- a/components/brave_rewards/resources/page/reducers/rewards_reducer.ts +++ b/components/brave_rewards/resources/page/reducers/rewards_reducer.ts @@ -15,17 +15,14 @@ const rewardsReducer: Reducer = (state: Rewards.State break } case types.TOGGLE_ENABLE_MAIN: { - if (state.initializing) { + if (state.initializing && state.enabledMain) { break } state = { ...state } const key = 'enabledMain' const enable = action.payload.enable - - if (enable) { - state.initializing = true - } + state.initializing = true state[key] = enable chrome.send('brave_rewards.saveSetting', [key, enable.toString()]) @@ -248,6 +245,11 @@ const rewardsReducer: Reducer = (state: Rewards.State break } + if (!enabled) { + state.balance = defaultState.balance + state.promotions = [] + } + state.enabledMain = enabled break } diff --git a/components/definitions/chromel.d.ts b/components/definitions/chromel.d.ts index 6f8711d70f0f..79f309cd5a30 100644 --- a/components/definitions/chromel.d.ts +++ b/components/definitions/chromel.d.ts @@ -71,7 +71,10 @@ declare namespace chrome.braveRewards { const tipGitHubUser: (tabId: number, githubMetaData: RewardsTip.MediaMetaData) => {} const getPublisherData: (windowId: number, url: string, faviconUrl: string, publisherBlob: string | undefined) => {} const getBalanceReport: (month: number, year: number, callback: (properties: RewardsExtension.BalanceReport) => void) => {} - const onWalletInitialized: { + const walletCreated: { + addListener: (callback: () => void) => void + } + const walletCreationFailed: { addListener: (callback: (result: RewardsExtension.Result) => void) => void } const onPublisherData: { @@ -151,6 +154,10 @@ declare namespace chrome.braveRewards { const onCompleteReset: { addListener: (callback: (properties: { success: boolean }) => void) => void } + const initialized: { + addListener: (callback: (result: RewardsExtension.Result) => void) => void + } + const isInitialized: (callback: (initialized: boolean) => void) => {} } declare namespace chrome.binance { diff --git a/components/definitions/rewardsExtensions.d.ts b/components/definitions/rewardsExtensions.d.ts index 093016b7029d..2ea70596fedc 100644 --- a/components/definitions/rewardsExtensions.d.ts +++ b/components/definitions/rewardsExtensions.d.ts @@ -17,6 +17,7 @@ declare namespace RewardsExtension { recurringTips: Record[] tipAmounts: Record externalWallet?: ExternalWallet + initializing: boolean } interface ApplicationState { diff --git a/components/test/brave_rewards/page/components/app_test.tsx b/components/test/brave_rewards/page/components/app_test.tsx index 470032fe5417..97b2f37c4805 100644 --- a/components/test/brave_rewards/page/components/app_test.tsx +++ b/components/test/brave_rewards/page/components/app_test.tsx @@ -48,7 +48,8 @@ describe('rewardsPage component', () => { false, - onlyAnonWallet: () => false + onlyAnonWallet: () => false, + isInitialized: () => false }} rewardsData={rewardsInitialState.rewardsData as Rewards.State} /> 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 0526f45a48f1..07a9e759f84c 100644 --- a/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts +++ b/components/test/brave_rewards/page/reducers/wallet_reducer_test.ts @@ -52,6 +52,7 @@ describe('wallet reducer', () => { expectedState.createdTimestamp = constantDate.getTime() expectedState.enabledAds = true expectedState.enabledContribute = true + expectedState.initializing = false expect(assertion).toEqual({ rewardsData: expectedState @@ -71,6 +72,7 @@ describe('wallet reducer', () => { const expectedState: Rewards.State = { ...defaultState } expectedState.walletCreateFailed = true + expectedState.initializing = false expect(assertion).toEqual({ rewardsData: expectedState