Skip to content

Commit

Permalink
Merge pull request #6338 from brave/rewards-init-1.13
Browse files Browse the repository at this point in the history
Fixes panel / NTP initialization (uplift to 1.13.x)
  • Loading branch information
LaurenWags authored Aug 5, 2020
2 parents af0b737 + 0d62687 commit df8a878
Show file tree
Hide file tree
Showing 40 changed files with 386 additions and 113 deletions.
29 changes: 27 additions & 2 deletions browser/brave_rewards/extension_rewards_service_observer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,38 @@ void ExtensionRewardsServiceObserver::OnWalletInitialized(
return;
}

// ledger::Result::WALLET_CREATED
if (result == 12) {
auto args = std::make_unique<base::ListValue>();
std::unique_ptr<extensions::Event> 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<base::ListValue> args(
extensions::api::brave_rewards::WalletCreationFailed::Create(
result).release());

std::unique_ptr<extensions::Event> 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<base::ListValue> args(
extensions::api::brave_rewards::OnWalletInitialized::Create(
extensions::api::brave_rewards::Initialized::Create(
result).release());

std::unique_ptr<extensions::Event> 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));
}
Expand Down
18 changes: 18 additions & 0 deletions browser/extensions/api/brave_rewards_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1174,5 +1174,23 @@ void BraveRewardsGetAnonWalletStatusFunction::OnGetAnonWalletStatus(
Respond(OneArgument(std::make_unique<base::Value>(static_cast<int>(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<base::Value>(initialized)));
}

} // namespace api
} // namespace extensions
10 changes: 10 additions & 0 deletions browser/extensions/api/brave_rewards_api.h
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
17 changes: 17 additions & 0 deletions browser/ui/webui/brave_rewards_page_ui.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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)));
Expand Down Expand Up @@ -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_)
Expand Down
38 changes: 35 additions & 3 deletions common/extensions/api/brave_rewards.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down Expand Up @@ -1103,6 +1118,23 @@
]
}
]
},
{
"name": "isInitialized",
"type": "function",
"description": "Is ledger process initialized",
"parameters": [
{
"type": "function",
"name": "callback",
"parameters": [
{
"name": "initialized",
"type": "boolean"
}
]
}
]
}
]
}
Expand Down
1 change: 1 addition & 0 deletions components/brave_ads/browser/ads_service_impl_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class MockRewardsService : public RewardsService {
MockRewardsService() {}
~MockRewardsService() {}

MOCK_METHOD0(IsInitialized, bool());
MOCK_METHOD1(CreateWallet, void(brave_rewards::CreateWalletCallback));
MOCK_METHOD1(
GetRewardsParameters,
Expand Down
4 changes: 4 additions & 0 deletions components/brave_new_tab_ui/actions/rewards_actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
})
62 changes: 47 additions & 15 deletions components/brave_new_tab_ui/apiEventsToStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ export function wireApiEventsToStore () {
.then((initialData) => {
if (initialData.preferences.showRewards) {
rewardsInitData()
setRewardsFetchInterval()
}
binanceInitData()
getActions().setInitialData(initialData)
Expand All @@ -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()
}
})
})
Expand All @@ -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) => {
Expand All @@ -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)
})
3 changes: 2 additions & 1 deletion components/brave_new_tab_ui/constants/rewards_types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
}
27 changes: 17 additions & 10 deletions components/brave_new_tab_ui/reducers/rewards_reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,13 @@ const rewardsReducer: Reducer<NewTab.State | undefined> = (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
}
Expand Down Expand Up @@ -148,10 +143,7 @@ const rewardsReducer: Reducer<NewTab.State | undefined> = (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:
Expand Down Expand Up @@ -195,6 +187,21 @@ const rewardsReducer: Reducer<NewTab.State | undefined> = (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
Expand Down
2 changes: 2 additions & 0 deletions components/brave_rewards/browser/rewards_service.h
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
4 changes: 4 additions & 0 deletions components/brave_rewards/browser/rewards_service_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,10 @@ void RewardsServiceImpl::ConnectionClosed() {
base::TimeDelta::FromSeconds(1));
}

bool RewardsServiceImpl::IsInitialized() {
return Connected() && ready_->is_signaled();
}

void RewardsServiceImpl::Init(
std::unique_ptr<RewardsServiceObserver> extension_observer,
std::unique_ptr<RewardsServicePrivateObserver> private_observer,
Expand Down
2 changes: 2 additions & 0 deletions components/brave_rewards/browser/rewards_service_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ class RewardsServiceImpl : public RewardsService,
// KeyedService:
void Shutdown() override;

bool IsInitialized() override;

void Init(
std::unique_ptr<RewardsServiceObserver> extension_observer,
std::unique_ptr<RewardsServicePrivateObserver> private_observer,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading

0 comments on commit df8a878

Please sign in to comment.