Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update BAP UI (uplift to 1.20.x) #7798

Merged
merged 4 commits into from
Feb 15, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/resources/brave_generated_resources_ja.xtb
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,9 @@
<translation id="5318548116565208315">アバター「ボンボン・コーン」</translation>
<translation id="1959966725083452288">アバター「ボンボン・ロイヤル」</translation>
<translation id="2039034364578911089">アバター「ボンボン・ニンジャ」</translation>
<translation id="239760341987199724">Brave をデフォルト ブラウザに設定する</translation>
<translation id="9218430445555521422">デフォルトとして設定</translation>
<translation id="3479552764303398839">後で</translation>
<translation id="1872784258300710671">Braveは完全に匿名の製品分析を使い、特定の機能が全体でどの程度使われているか予測します</translation>
<translation id="8712637175834984815">閉じる</translation>
<translation id="4394049700291259645">無効にする</translation>
Expand Down
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
5 changes: 5 additions & 0 deletions browser/ui/brave_actions/brave_action_view_controller.cc
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ bool BraveActionViewController::TriggerPopupWithUrl(
PopupShowAction show_action,
const GURL& popup_url,
bool grant_tab_permissions) {
// If this extension is currently showing a popup, hide it. This behavior is
// a bit different than ExtensionActionViewController, which will hide any
// popup, regardless of extension. Consider duplicating the original behavior.
HidePopup();

std::unique_ptr<extensions::ExtensionViewHost> host =
extensions::ExtensionViewHostFactory::CreatePopupHost(popup_url,
browser_);
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
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
16 changes: 15 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,20 @@ 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;
bool ok = base::Time::FromUTCExploded(cutoff_exploded, &cutoff);
DCHECK(ok);
if (ok && base::Time::Now() >= cutoff) {
return true;
}
}
return false;
}

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

Expand Down Expand Up @@ -3005,7 +3019,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
94 changes: 94 additions & 0 deletions components/brave_rewards/browser/test/rewards_browsertest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@

#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/browser/extensions/api/brave_action_api.h"
#include "brave/common/brave_paths.h"
#include "brave/components/brave_rewards/browser/rewards_service_impl.h"
#include "brave/components/brave_rewards/browser/test/common/rewards_browsertest_context_helper.h"
Expand All @@ -23,12 +26,27 @@
#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;
bool ok = base::Time::FromUTCExploded(
base::Time::Exploded{
.year = year, .month = month, .day_of_month = day_of_month},
&time);
DCHECK(ok);
return time;
}

} // namespace

namespace rewards_browsertest {

class RewardsBrowserTest : public InProcessBrowserTest {
Expand Down Expand Up @@ -109,6 +127,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 +458,68 @@ 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, 12); }, 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);
}
}

IN_PROC_BROWSER_TEST_F(RewardsBrowserTest, BAPPopup) {
// Open the rewards popup.
content::WebContents* popup_contents = context_helper_->OpenRewardsPopup();
ASSERT_TRUE(popup_contents);

// Attempt to open the BAP deprecation popup at the same time. The rewards
// panel popup should close. If both popups are shown at the same time, this
// test will crash on exit.
std::string error;
bool popup_shown = extensions::BraveActionAPI::ShowActionUI(
browser(), brave_rewards_extension_id,
std::make_unique<std::string>("brave_rewards_panel.html#bap-deprecation"),
&error);
EXPECT_TRUE(popup_shown);
}

} // namespace rewards_browsertest
Loading