Skip to content

Commit

Permalink
Merge pull request #1044 from brave/rewards-backup-notification
Browse files Browse the repository at this point in the history
Add rewards notification to backup wallet
  • Loading branch information
NejcZdovc committed Dec 18, 2018
1 parent 0ebfad5 commit 1d317a7
Show file tree
Hide file tree
Showing 18 changed files with 160 additions and 6 deletions.
10 changes: 10 additions & 0 deletions browser/ui/webui/brave_rewards_ui.cc
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ class RewardsDOMHandler : public WebUIMessageHandler,
void CheckImported(const base::ListValue* args);
void GetAdsData(const base::ListValue* args);
void SaveAdsSetting(const base::ListValue* args);
void SetBackupCompleted(const base::ListValue* args);

// RewardsServiceObserver implementation
void OnWalletInitialized(brave_rewards::RewardsService* rewards_service,
Expand Down Expand Up @@ -212,6 +213,9 @@ void RewardsDOMHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback("brave_rewards.saveAdsSetting",
base::BindRepeating(&RewardsDOMHandler::SaveAdsSetting,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("brave_rewards.setBackupCompleted",
base::BindRepeating(&RewardsDOMHandler::SetBackupCompleted,
base::Unretained(this)));
}

void RewardsDOMHandler::Init() {
Expand Down Expand Up @@ -740,6 +744,12 @@ void RewardsDOMHandler::SaveAdsSetting(const base::ListValue* args) {
}
}

void RewardsDOMHandler::SetBackupCompleted(const base::ListValue *args) {
if (web_ui()->CanCallJavascript() && rewards_service_) {
rewards_service_->SetBackupCompleted();
}
}

} // namespace

BraveRewardsUI::BraveRewardsUI(content::WebUI* web_ui, const std::string& name)
Expand Down
9 changes: 8 additions & 1 deletion common/pref_names.cc
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,12 @@ const char kReferralCheckedForPromoCodeFile[] = "brave.referral.checked_for_prom
const char kHTTPSEVerywhereControlType[] = "brave.https_everywhere_default";
const char kNoScriptControlType[] = "brave.no_script_default";
const char kRewardsNotifications[] = "brave.rewards.notifications";
const char kRewardsNotificationTimerInterval[] = "brave.rewards.notification_timer_interval";
const char kRewardsBackupNotificationFrequency[] =
"brave.rewards.backup_notification_frequency";
const char kRewardsBackupNotificationInterval[] =
"brave.rewards.backup_notification_interval";
const char kRewardsBackupSucceeded[] = "brave.rewards.backup_succeeded";
const char kRewardsUserHasFunded[] = "brave.rewards.user_has_funded";
const char kMigratedMuonProfile[] = "brave.muon.migrated_profile";
const char kBravePaymentsPinnedItemCount[] = "brave.muon.import_pinned_item_count";
const char kBravePaymentsPinnedItemCount[] = "brave.muon.import_pinned_item_count";
5 changes: 5 additions & 0 deletions common/pref_names.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ extern const char kReferralCheckedForPromoCodeFile[];
extern const char kHTTPSEVerywhereControlType[];
extern const char kNoScriptControlType[];
extern const char kRewardsNotifications[];
extern const char kRewardsNotificationTimerInterval[];
extern const char kRewardsBackupNotificationFrequency[];
extern const char kRewardsBackupNotificationInterval[];
extern const char kRewardsBackupSucceeded[];
extern const char kRewardsUserHasFunded[];
extern const char kMigratedMuonProfile[];
extern const char kBravePaymentsPinnedItemCount[];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class RewardsNotificationService {
REWARDS_NOTIFICATION_FAILED_CONTRIBUTION,
REWARDS_NOTIFICATION_IMPENDING_CONTRIBUTION,
REWARDS_NOTIFICATION_INSUFFICIENT_FUNDS,
REWARDS_NOTIFICATION_BACKUP_WALLET,
};

struct RewardsNotification {
Expand Down
9 changes: 9 additions & 0 deletions components/brave_rewards/browser/rewards_service.cc
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include "brave/components/brave_rewards/browser/rewards_service.h"

#include "base/logging.h"
#include "base/time/time.h"
#include "brave/common/pref_names.h"
#include "brave/components/brave_rewards/browser/buildflags/buildflags.h"
#include "brave/components/brave_rewards/browser/rewards_notification_service_impl.h"
Expand Down Expand Up @@ -41,6 +42,14 @@ void RewardsService::RemoveObserver(RewardsServiceObserver* observer) {
// static
void RewardsService::RegisterProfilePrefs(PrefRegistrySimple* registry) {
registry->RegisterStringPref(kRewardsNotifications, "");
registry->RegisterTimeDeltaPref(kRewardsNotificationTimerInterval,
base::TimeDelta::FromDays(1));
registry->RegisterTimeDeltaPref(kRewardsBackupNotificationFrequency,
base::TimeDelta::FromDays(7));
registry->RegisterTimeDeltaPref(kRewardsBackupNotificationInterval,
base::TimeDelta::FromDays(7));
registry->RegisterBooleanPref(kRewardsBackupSucceeded, false);
registry->RegisterBooleanPref(kRewardsUserHasFunded, false);
}

} // namespace brave_rewards
1 change: 1 addition & 0 deletions components/brave_rewards/browser/rewards_service.h
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ class RewardsService : public KeyedService {
virtual RewardsNotificationService* GetNotificationService() const = 0;
virtual bool CheckImported() = 0;
virtual void SetLedgerClient(std::unique_ptr<ledger::Ledger> new_ledger) = 0;
virtual void SetBackupCompleted() = 0;

void AddObserver(RewardsServiceObserver* observer);
void RemoveObserver(RewardsServiceObserver* observer);
Expand Down
69 changes: 67 additions & 2 deletions components/brave_rewards/browser/rewards_service_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
#include "base/files/file_util.h"
#include "base/files/important_file_writer.h"
#include "base/guid.h"
#include "base/logging.h"
#include "base/i18n/time_formatting.h"
#include "base/logging.h"
#include "base/sequenced_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
Expand Down Expand Up @@ -327,6 +327,7 @@ RewardsServiceImpl::RewardsServiceImpl(Profile* profile)

RewardsServiceImpl::~RewardsServiceImpl() {
file_task_runner_->DeleteSoon(FROM_HERE, publisher_info_backend_.release());
StopNotificationTimers();
}

void RewardsServiceImpl::Init() {
Expand All @@ -338,6 +339,32 @@ void RewardsServiceImpl::Init() {
ledger_->Initialize();
}

void RewardsServiceImpl::MaybeShowBackupNotification() {
PrefService* pref_service = profile_->GetPrefs();
bool user_has_funded = pref_service->GetBoolean(kRewardsUserHasFunded);
bool backup_succeeded = pref_service->GetBoolean(kRewardsBackupSucceeded);
if (user_has_funded && !backup_succeeded) {
base::Time now = base::Time::Now();
base::Time boot_timestamp =
base::Time::FromDoubleT(ledger_->GetBootStamp());
base::TimeDelta backup_notification_frequency =
pref_service->GetTimeDelta(kRewardsBackupNotificationFrequency);
base::TimeDelta backup_notification_interval =
pref_service->GetTimeDelta(kRewardsBackupNotificationInterval);
base::TimeDelta elapsed = now - boot_timestamp;
if (elapsed > backup_notification_interval) {
base::TimeDelta next_backup_notification_interval =
backup_notification_interval + backup_notification_frequency;
pref_service->SetTimeDelta(kRewardsBackupNotificationInterval,
next_backup_notification_interval);
RewardsNotificationService::RewardsNotificationArgs args;
notification_service_->AddNotification(
RewardsNotificationService::REWARDS_NOTIFICATION_BACKUP_WALLET, args,
"rewards_notification_backup_wallet");
}
}
}

void RewardsServiceImpl::CreateWallet() {
if (ready().is_signaled()) {
ledger_->CreateWallet();
Expand Down Expand Up @@ -571,6 +598,7 @@ void RewardsServiceImpl::OnWalletInitialized(ledger::Result result) {
if (result == ledger::Result::WALLET_CREATED) {
SetRewardsMainEnabled(true);
SetAutoContribute(true);
StartNotificationTimers();
result = ledger::Result::LEDGER_OK;
}

Expand Down Expand Up @@ -649,6 +677,9 @@ void RewardsServiceImpl::OnLedgerStateLoaded(
handler->OnLedgerStateLoaded(data.empty() ? ledger::Result::LEDGER_ERROR
: ledger::Result::LEDGER_OK,
data);
if (ledger_->GetRewardsMainEnabled()) {
StartNotificationTimers();
}
}

void RewardsServiceImpl::LoadPublisherState(
Expand Down Expand Up @@ -936,8 +967,10 @@ void RewardsServiceImpl::TriggerOnWalletInitialized(int error_code) {

void RewardsServiceImpl::TriggerOnWalletProperties(int error_code,
std::unique_ptr<ledger::WalletInfo> wallet_info) {
std::unique_ptr<brave_rewards::WalletProperties> wallet_properties;
if (wallet_info && wallet_info->balance_ > 0)
profile_->GetPrefs()->SetBoolean(kRewardsUserHasFunded, true);

std::unique_ptr<brave_rewards::WalletProperties> wallet_properties;
for (auto& observer : observers_) {
if (wallet_info) {
wallet_properties.reset(new brave_rewards::WalletProperties);
Expand Down Expand Up @@ -1622,6 +1655,34 @@ RewardsNotificationService* RewardsServiceImpl::GetNotificationService() const {
return notification_service_.get();
}

void RewardsServiceImpl::StartNotificationTimers() {
// Startup timer, begins after 3-second delay.
notification_startup_timer_ = std::make_unique<base::OneShotTimer>();
notification_startup_timer_->Start(
FROM_HERE, base::TimeDelta::FromSeconds(3), this,
&RewardsServiceImpl::OnNotificationTimerFired);
DCHECK(notification_startup_timer_->IsRunning());

// Periodic timer, runs once per day by default.
PrefService* pref_service = profile_->GetPrefs();
base::TimeDelta periodic_timer_interval =
pref_service->GetTimeDelta(kRewardsNotificationTimerInterval);
notification_periodic_timer_ = std::make_unique<base::RepeatingTimer>();
notification_periodic_timer_->Start(
FROM_HERE, periodic_timer_interval, this,
&RewardsServiceImpl::OnNotificationTimerFired);
DCHECK(notification_periodic_timer_->IsRunning());
}

void RewardsServiceImpl::StopNotificationTimers() {
notification_startup_timer_.reset();
notification_periodic_timer_.reset();
}

void RewardsServiceImpl::OnNotificationTimerFired() {
MaybeShowBackupNotification();
}

std::unique_ptr<ledger::LogStream> RewardsServiceImpl::Log(
const char* file,
int line,
Expand Down Expand Up @@ -1694,6 +1755,10 @@ bool RewardsServiceImpl::CheckImported() {
return pinned_item_count > 0;
}

void RewardsServiceImpl::SetBackupCompleted() {
profile_->GetPrefs()->SetBoolean(kRewardsBackupSucceeded, true);
}

void RewardsServiceImpl::OnDonate(
const std::string& publisher_key,
int amount,
Expand Down
11 changes: 10 additions & 1 deletion components/brave_rewards/browser/rewards_service_impl.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
#include "base/files/file_path.h"
#include "base/observer_list.h"
#include "base/memory/weak_ptr.h"
#include "base/timer/timer.h"
#include "bat/ledger/ledger_client.h"
#include "brave/components/brave_rewards/browser/rewards_service.h"
#include "chrome/browser/bitmap_fetcher/bitmap_fetcher_service.h"
Expand All @@ -35,6 +34,8 @@
#endif

namespace base {
class OneShotTimer;
class RepeatingTimer;
class SequencedTaskRunner;
} // namespace base

Expand Down Expand Up @@ -128,6 +129,7 @@ class RewardsServiceImpl : public RewardsService,
std::string publisher_key, bool excluded, uint64_t windowId) override;
RewardsNotificationService* GetNotificationService() const override;
bool CheckImported() override;
void SetBackupCompleted() override;

static void HandleFlags(const std::string& options);
void OnWalletProperties(ledger::Result result,
Expand Down Expand Up @@ -199,6 +201,7 @@ class RewardsServiceImpl : public RewardsService,
ledger::Result result,
std::unique_ptr<ledger::PublisherInfo> info,
uint64_t windowId);
void MaybeShowBackupNotification();

// ledger::LedgerClient
std::string GenerateGUID() const override;
Expand Down Expand Up @@ -283,6 +286,10 @@ class RewardsServiceImpl : public RewardsService,
// URLFetcherDelegate impl
void OnURLFetchComplete(const net::URLFetcher* source) override;

void StartNotificationTimers();
void StopNotificationTimers();
void OnNotificationTimerFired();

Profile* profile_; // NOT OWNED
std::unique_ptr<ledger::Ledger> ledger_;
#if BUILDFLAG(ENABLE_EXTENSIONS)
Expand All @@ -306,6 +313,8 @@ class RewardsServiceImpl : public RewardsService,
std::map<uint32_t, std::unique_ptr<base::OneShotTimer>> timers_;
std::vector<std::string> current_media_fetchers_;
std::vector<BitmapFetcherService::RequestId> request_ids_;
std::unique_ptr<base::OneShotTimer> notification_startup_timer_;
std::unique_ptr<base::RepeatingTimer> notification_periodic_timer_;

uint32_t next_timer_id_;

Expand Down
2 changes: 2 additions & 0 deletions components/brave_rewards/browser/test_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,8 @@ class MockLedgerClient : public ledger::Ledger {
MOCK_METHOD1(RemoveRecurring, void(const std::string& publisher_key));

MOCK_METHOD0(GetDefaultContributionAmount, double());

MOCK_CONST_METHOD0(GetBootStamp, uint64_t());
};

std::unique_ptr<Profile> CreateBraveRewardsProfile(const base::FilePath& path);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,14 @@
"message": "You have a grant waiting for you.",
"description": "Description for new grant notification"
},
"backupWalletTitle": {
"message": "Backup Wallet",
"description": "Notification title when we ask user to backup wallet"
},
"backupWalletNotification": {
"message": "Please backup your Brave wallet.",
"description": "Description for backup wallet notification"
},
"braveRewardsCreatingText": {
"message": "Creating wallet",
"description": "Used in a button displaying wallet creation process"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ export const getMessage = (message: string, substitutions?: string[]): string =>

export const getUIMessages = (): Record<string, string> => {
const strings = [
'backupWalletNotification',
'backupWalletTitle',
'braveAdsTitle',
'braveContributeTitle',
'braveRewards',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,11 +192,23 @@ export class Panel extends React.Component<Props, State> {

const notification: RewardsExtension.Notification = notifications[currentNotification]

// Note: This declaration must match the RewardsNotificationType enum in
// brave/components/brave_rewards/browser/rewards_notification_service.h
enum RewardsNotificationType {
REWARDS_NOTIFICATION_INVALID = 0,
REWARDS_NOTIFICATION_AUTO_CONTRIBUTE,
REWARDS_NOTIFICATION_GRANT,
REWARDS_NOTIFICATION_FAILED_CONTRIBUTION,
REWARDS_NOTIFICATION_IMPENDING_CONTRIBUTION,
REWARDS_NOTIFICATION_INSUFFICIENT_FUNDS,
REWARDS_NOTIFICATION_BACKUP_WALLET,
}

let type: NotificationType = ''
let text = ''
let isAlert = ''
switch (notification.type) {
case 1:
case RewardsNotificationType.REWARDS_NOTIFICATION_AUTO_CONTRIBUTE:
{
if (!notification.args ||
!Array.isArray(notification.args) ||
Expand Down Expand Up @@ -228,10 +240,17 @@ export class Panel extends React.Component<Props, State> {
type = 'contribute'
break
}
case 2:
case RewardsNotificationType.REWARDS_NOTIFICATION_GRANT:
type = 'grant'
text = getMessage('grantNotification')
break
case RewardsNotificationType.REWARDS_NOTIFICATION_BACKUP_WALLET:
type = 'backupWallet'
text = getMessage('backupWalletNotification')
break
default:
type = ''
break
}

if (isAlert) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ class PageWallet extends React.Component<Props, State> {
try {
await clipboardCopy(backupKey)
console.log('Copy successful')
chrome.send('brave_rewards.setBackupCompleted')
} catch (e) {
console.log('Copy failed')
}
Expand All @@ -91,6 +92,7 @@ class PageWallet extends React.Component<Props, State> {
win.document.body.innerText = utils.constructBackupString(backupKey) // this should be text, not HTML
win.print()
win.close()
chrome.send('brave_rewards.setBackupCompleted')
}
}
}
Expand All @@ -107,6 +109,7 @@ class PageWallet extends React.Component<Props, State> {
a.download = backupFileText
a.click()
window.URL.revokeObjectURL(url)
chrome.send('brave_rewards.setBackupCompleted')
}

onModalBackupOnRestore = (key: string | MouseEvent) => {
Expand Down
2 changes: 2 additions & 0 deletions vendor/bat-native-ledger/include/bat/ledger/ledger.h
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,8 @@ class LEDGER_EXPORT Ledger {
const uint32_t date) = 0;
virtual void RemoveRecurring(const std::string& publisher_key) = 0;
virtual double GetDefaultContributionAmount() = 0;

virtual uint64_t GetBootStamp() const = 0;
};

} // namespace ledger
Expand Down
4 changes: 4 additions & 0 deletions vendor/bat-native-ledger/src/bat_state.cc
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,10 @@ void BatState::SetCurrency(const std::string &currency) {
SaveState();
}

uint64_t BatState::GetBootStamp() const {
return state_->bootStamp_;
}

void BatState::SetBootStamp(uint64_t stamp) {
state_->bootStamp_ = stamp;
SaveState();
Expand Down
Loading

0 comments on commit 1d317a7

Please sign in to comment.