Skip to content

Commit

Permalink
Uplift of #7698 (squashed) to beta
Browse files Browse the repository at this point in the history
  • Loading branch information
brave-browser-releases committed Feb 3, 2021
1 parent 640b865 commit 4d78588
Show file tree
Hide file tree
Showing 27 changed files with 698 additions and 9 deletions.
19 changes: 19 additions & 0 deletions browser/extensions/api/brave_rewards_api.cc
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,25 @@ BraveRewardsOpenBrowserActionUIFunction::Run() {
std::unique_ptr<brave_rewards::OpenBrowserActionUI::Params> params(
brave_rewards::OpenBrowserActionUI::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());

auto* profile = Profile::FromBrowserContext(browser_context());

// Start the rewards ledger process if it is not already started
auto* rewards_service = RewardsServiceFactory::GetForProfile(profile);
if (!rewards_service)
return RespondNow(Error("Rewards service is not initialized"));

rewards_service->StartProcess(base::DoNothing());

// Load the rewards extension if it is not already loaded
auto* extension_service =
extensions::ExtensionSystem::Get(profile)->extension_service();
if (!extension_service)
return RespondNow(Error("Extension service is not initialized"));

static_cast<BraveComponentLoader*>(extension_service->component_loader())
->AddRewardsExtension();

std::string error;
if (!BraveActionAPI::ShowActionUI(this,
brave_rewards_extension_id,
Expand Down
4 changes: 4 additions & 0 deletions browser/ui/webui/brave_webui_source.cc
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,10 @@ void CustomizeWebUIHTMLSource(const std::string &name,
{ "editCardsTitle", IDS_EDIT_CARDS_TITLE },
{ "tosAndPp", IDS_REWARDS_WIDGET_TOS_AND_PP}, // NOLINT
{ "rewardsWidgetStartUsing", IDS_REWARDS_WIDGET_START_USING}, // NOLINT
// Rewards BAP Deprecation Alert
{ "bapDeprecationAlertText", IDS_REWARDS_BAP_DEPRECATION_ALERT_TEXT },
{ "bapDeprecationHeader", IDS_REWARDS_BAP_DEPRECATION_HEADER },
{ "bapDeprecationOK", IDS_REWARDS_BAP_DEPRECATION_OK },
// Together Widget
{ "togetherWidgetTitle", IDS_TOGETHER_WIDGET_TITLE },
{ "togetherWidgetWelcomeTitle", IDS_TOGETHER_WIDGET_WELCOME_TITLE },
Expand Down
2 changes: 1 addition & 1 deletion components/brave_ads/browser/ads_service_impl_unittest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ class MockRewardsService : public RewardsService {

MOCK_METHOD1(DisconnectWallet, void(const std::string& wallet_type));

MOCK_METHOD0(OnlyAnonWallet, bool());
MOCK_CONST_METHOD0(OnlyAnonWallet, bool());

MOCK_METHOD1(AddPrivateObserver,
void(RewardsServicePrivateObserver* observer));
Expand Down
10 changes: 8 additions & 2 deletions components/brave_new_tab_ui/api/initialData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export type InitialData = {
export type PreInitialRewardsData = {
enabledAds: boolean
adsSupported: boolean
onlyAnonWallet: boolean
}

export type InitialRewardsData = {
Expand Down Expand Up @@ -103,18 +104,23 @@ export async function getRewardsPreInitialData (): Promise<PreInitialRewardsData
try {
const [
enabledAds,
adsSupported
adsSupported,
onlyAnonWallet
] = await Promise.all([
new Promise(resolve => chrome.braveRewards.getAdsEnabled((enabledAds: boolean) => {
resolve(enabledAds)
})),
new Promise(resolve => chrome.braveRewards.getAdsSupported((adsSupported: boolean) => {
resolve(adsSupported)
})),
new Promise(resolve => chrome.braveRewards.onlyAnonWallet((onlyAnonWallet: boolean) => {
resolve(onlyAnonWallet)
}))
])
return {
enabledAds,
adsSupported
adsSupported,
onlyAnonWallet
} as PreInitialRewardsData
} catch (err) {
throw Error(err)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */

import * as React from 'react'

import { getLocale } from '../../../../common/locale'

import { WithThemeVariables } from '../../../../brave_rewards/resources/shared/components/with_theme_variables'
import { LocaleContext } from '../../../../brave_rewards/resources/shared/lib/locale_context'
import {
BAPDeprecationAlert,
shouldShowBAPAlert,
shouldShowBAPPopup,
saveBAPAlertDismissed,
saveBAPPopupShown
} from '../../../../brave_rewards/resources/shared/components/bap_deprecation'

const locale = {
getString: getLocale
}

function modalRequestInHash () {
return /^#?bap-deprecation$/i.test(window.location.hash)
}

interface Props {
rewardsState: NewTab.RewardsWidgetState
}

// A modal that will display a BAP deprecation notice for Rewards users
// in Japan. This component is temporary and should be removed in 1.23.x
export default function BAPDeprecationModal (props: Props) {
const { onlyAnonWallet, balance } = props.rewardsState

const [popupShown, setPopupShown] = React.useState(false)

const [showModal, setShowModal] = React.useState(
modalRequestInHash() ||
shouldShowBAPAlert(onlyAnonWallet, balance.total))

React.useEffect(() => {
if (popupShown || showModal) {
return
}
if (shouldShowBAPPopup(onlyAnonWallet, balance.total)) {
setPopupShown(true)
saveBAPPopupShown()
const popupURL = 'brave_rewards_panel.html#bap-deprecation'
chrome.braveRewards.openBrowserActionUI(popupURL)
}
}, [popupShown, showModal, onlyAnonWallet, balance])

React.useEffect(() => {
if (modalRequestInHash()) {
window.location.hash = ''
}

// Attach a hashchange listener while this component is rendered. If the
// BAP deprecation popup has been opened in the brave rewards extension
// panel and the user clicks "Learn more", it will update the hash on
// this page.
const onHashChange = () => {
if (modalRequestInHash()) {
window.location.hash = ''
setShowModal(true)
}
}

window.addEventListener('hashchange', onHashChange)
return () => { window.removeEventListener('hashchange', onHashChange) }
}, [])

if (!showModal) {
return null
}

const onClose = () => {
setShowModal(false)
if (!popupShown) {
saveBAPAlertDismissed()
}
}

return (
<WithThemeVariables>
<LocaleContext.Provider value={locale}>
<BAPDeprecationAlert onClose={onClose} />
</LocaleContext.Provider>
</WithThemeVariables>
)
}
2 changes: 2 additions & 0 deletions components/brave_new_tab_ui/containers/newTab/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import BrandedWallpaperLogo from '../../components/default/brandedWallpaper/logo
import { brandedWallpaperLogoClicked } from '../../api/brandedWallpaper'
import BraveTodayHint from '../../components/default/braveToday/hint'
import BraveToday from '../../components/default/braveToday'
import BAPDeprecationModal from '../../components/default/rewards/bapDeprecationModal'

// Helpers
import VisibilityTimer from '../../helpers/visibilityTimer'
Expand Down Expand Up @@ -1157,6 +1158,7 @@ class NewTabPage extends React.Component<Props, State> {
cardsHidden={this.allWidgetsHidden()}
toggleCards={this.toggleAllCards}
/>
<BAPDeprecationModal rewardsState={this.props.newTabData.rewardsState} />
</Page.App>
)
}
Expand Down
3 changes: 2 additions & 1 deletion components/brave_new_tab_ui/reducers/rewards_reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ const rewardsReducer: Reducer<NewTab.State | undefined> = (state: NewTab.State,
rewardsState: {
...state.rewardsState,
enabledAds: preInitialRewardsDataPayload.enabledAds,
adsSupported: preInitialRewardsDataPayload.adsSupported
adsSupported: preInitialRewardsDataPayload.adsSupported,
onlyAnonWallet: preInitialRewardsDataPayload.onlyAnonWallet
}
}
break
Expand Down
2 changes: 1 addition & 1 deletion components/brave_rewards/browser/rewards_service.h
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@ class RewardsService : public KeyedService {

virtual void DisconnectWallet(const std::string& wallet_type) = 0;

virtual bool OnlyAnonWallet() = 0;
virtual bool OnlyAnonWallet() const = 0;

virtual void GetAnonWalletStatus(GetAnonWalletStatusCallback callback) = 0;

Expand Down
15 changes: 14 additions & 1 deletion components/brave_rewards/browser/rewards_service_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1489,6 +1489,19 @@ void RewardsServiceImpl::ClearState(const std::string& name) {
bool RewardsServiceImpl::GetBooleanOption(const std::string& name) const {
DCHECK(!name.empty());

if (name == ledger::option::kContributionsDisabledForBAPMigration) {
if (OnlyAnonWallet()) {
base::Time::Exploded cutoff_exploded{
.year = 2021, .month = 3, .day_of_month = 13};
base::Time cutoff;
DCHECK(base::Time::FromUTCExploded(cutoff_exploded, &cutoff));
if (base::Time::Now() >= cutoff) {
return true;
}
}
return false;
}

const auto it = kBoolOptions.find(name);
DCHECK(it != kBoolOptions.end());

Expand Down Expand Up @@ -3005,7 +3018,7 @@ void RewardsServiceImpl::ShowNotification(
callback(ledger::type::Result::LEDGER_OK);
}

bool RewardsServiceImpl::OnlyAnonWallet() {
bool RewardsServiceImpl::OnlyAnonWallet() const {
const int32_t current_country =
country_codes::GetCountryIDFromPrefs(profile_->GetPrefs());

Expand Down
2 changes: 1 addition & 1 deletion components/brave_rewards/browser/rewards_service_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ class RewardsServiceImpl : public RewardsService,

void DisconnectWallet(const std::string& wallet_type) override;

bool OnlyAnonWallet() override;
bool OnlyAnonWallet() const override;

void GetAnonWalletStatus(GetAnonWalletStatusCallback callback) override;

Expand Down
77 changes: 77 additions & 0 deletions components/brave_rewards/browser/test/rewards_browsertest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

#include "base/containers/flat_map.h"
#include "base/test/bind.h"
#include "base/time/time.h"
#include "base/time/time_override.h"
#include "bat/ledger/internal/uphold/uphold_util.h"
#include "brave/browser/brave_rewards/rewards_service_factory.h"
#include "brave/common/brave_paths.h"
Expand All @@ -23,12 +25,26 @@
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/country_codes/country_codes.h"
#include "components/network_session_configurator/common/network_switches.h"
#include "content/public/test/browser_test.h"
#include "net/dns/mock_host_resolver.h"

// npm run test -- brave_browser_tests --filter=RewardsBrowserTest.*

namespace {

base::Time GetDate(int year, int month, int day_of_month) {
base::Time time;
DCHECK(base::Time::FromUTCExploded(
base::Time::Exploded{
.year = year, .month = month, .day_of_month = day_of_month},
&time));
return time;
}

} // namespace

namespace rewards_browsertest {

class RewardsBrowserTest : public InProcessBrowserTest {
Expand Down Expand Up @@ -109,6 +125,18 @@ class RewardsBrowserTest : public InProcessBrowserTest {
return url;
}

double FetchBalance() {
double total = -1.0;
base::RunLoop run_loop;
rewards_service_->FetchBalance(base::BindLambdaForTesting(
[&](ledger::type::Result result, ledger::type::BalancePtr balance) {
total = balance ? balance->total : -1.0;
run_loop.Quit();
}));
run_loop.Run();
return total;
}

brave_rewards::RewardsServiceImpl* rewards_service_;
std::unique_ptr<net::EmbeddedTestServer> https_server_;
std::unique_ptr<RewardsBrowserTestResponse> response_;
Expand Down Expand Up @@ -428,4 +456,53 @@ IN_PROC_BROWSER_TEST_F(RewardsBrowserTest, DISABLED_UpholdLimitNoBAT) {
}
}

IN_PROC_BROWSER_TEST_F(RewardsBrowserTest, BAPCutoffNonJP) {
rewards_browsertest_util::StartProcess(rewards_service_);
rewards_browsertest_util::CreateWallet(rewards_service_);
rewards_service_->FetchPromotions();
promotion_->WaitForPromotionInitialization();
promotion_->ClaimPromotionViaCode();

{
base::subtle::ScopedTimeClockOverrides time_override(
[]() { return GetDate(2021, 3, 13); }, nullptr, nullptr);
ASSERT_EQ(FetchBalance(), 30.0);
}
}

IN_PROC_BROWSER_TEST_F(RewardsBrowserTest, BAPCutoffBefore) {
rewards_browsertest_util::StartProcess(rewards_service_);
rewards_browsertest_util::CreateWallet(rewards_service_);
rewards_service_->FetchPromotions();
promotion_->WaitForPromotionInitialization();
promotion_->ClaimPromotionViaCode();

browser()->profile()->GetPrefs()->SetInteger(
country_codes::kCountryIDAtInstall, 19024);

{
base::subtle::ScopedTimeClockOverrides time_override(
[]() { return GetDate(2021, 3, 13) - base::TimeDelta::FromSeconds(1); },
nullptr, nullptr);
ASSERT_EQ(FetchBalance(), 30.0);
}
}

IN_PROC_BROWSER_TEST_F(RewardsBrowserTest, BAPCutoffAfter) {
rewards_browsertest_util::StartProcess(rewards_service_);
rewards_browsertest_util::CreateWallet(rewards_service_);
rewards_service_->FetchPromotions();
promotion_->WaitForPromotionInitialization();
promotion_->ClaimPromotionViaCode();

browser()->profile()->GetPrefs()->SetInteger(
country_codes::kCountryIDAtInstall, 19024);

{
base::subtle::ScopedTimeClockOverrides time_override(
[]() { return GetDate(2021, 3, 13); }, nullptr, nullptr);
ASSERT_EQ(FetchBalance(), 0.0);
}
}

} // namespace rewards_browsertest
Original file line number Diff line number Diff line change
Expand Up @@ -740,5 +740,17 @@
"onboardingPanelCompleteText": {
"message": "By using Brave Rewards you are helping make the web a better place for everyone. And that’s awesome!",
"description": ""
},
"bapDeprecationHeader": {
"message": "Brave Rewards in Japan is switching to a new system!",
"description": "Header text for BAP deprecation warning message"
},
"bapDeprecationLearnMore": {
"message": "Learn more",
"description": "Link to learn more about BAP deprecation"
},
"bapDeprecationPopupText": {
"message": "Please use your BAP by March 13th. After that, BAP will be discontinued.",
"description": "Text for BAP deprecation popup"
}
}
Loading

0 comments on commit 4d78588

Please sign in to comment.