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

Import Brave Payments data from Muon #736

Merged
merged 16 commits into from
Nov 28, 2018
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
5 changes: 4 additions & 1 deletion app/brave_generated_resources.grd
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,9 @@
<message name="IDS_SETTINGS_IMPORT_STATS_CHECKBOX" desc="Checkbox for importing stats">
Stats
</message>
<message name="IDS_SETTINGS_IMPORT_LEDGER_CHECKBOX" desc="Checkbox for importing ledger">
Brave Payments
</message>
<message name="IDS_WIDEVINE_NOT_INSTALLED_EXPLANATORY_TEXT" desc="Explanatory animated text that appears (and then disappears) in the address line when Widevine is blocked">
Widevine is not installed
</message>
Expand All @@ -170,7 +173,7 @@ By installing this extension, you are agreeing to the Google Widevine Terms of U
</message>
<!-- Brave Importer -->
<message name="IDS_IMPORT_FROM_BRAVE" desc="browser combo box: Brave">
Brave
Brave (old)
</message>
<message name="IDS_BOOKMARK_GROUP_FROM_BRAVE" desc="The group name of bookmarks from Brave">
Imported From Brave
Expand Down
7 changes: 7 additions & 0 deletions browser/brave_profile_prefs.cc
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
registry->SetDefaultPrefValue(prefs::kCloudPrintProxyEnabled, base::Value(false));
// Cloud Print: Don't allow jobs to be submitted
registry->SetDefaultPrefValue(prefs::kCloudPrintSubmitEnabled, base::Value(false));

// Importer: selected data types
registry->RegisterBooleanPref(prefs::kImportDialogCookies, true);
registry->RegisterBooleanPref(prefs::kImportDialogStats, true);
registry->RegisterBooleanPref(prefs::kImportDialogLedger, true);
// Importer: ledger (used for Brave Rewards pinned => tips)
registry->RegisterIntegerPref(kBravePaymentsPinnedItemCount, 0);
}

} // namespace brave
2 changes: 2 additions & 0 deletions browser/extensions/api/settings_private/brave_prefs_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ const PrefsUtil::TypedPrefMap& BravePrefsUtil::GetWhitelistedKeys() {
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_brave_whitelist)[::prefs::kImportDialogStats] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
(*s_brave_whitelist)[::prefs::kImportDialogLedger] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
// Default Brave shields
(*s_brave_whitelist)[kHTTPSEVerywhereControlType] =
settings_api::PrefType::PREF_TYPE_BOOLEAN;
Expand Down
8 changes: 8 additions & 0 deletions browser/importer/brave_external_process_importer_client.cc
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,12 @@ void BraveExternalProcessImporterClient::OnStatsImportReady(
bridge_->UpdateStats(stats);
}

void BraveExternalProcessImporterClient::OnLedgerImportReady(
const BraveLedger& ledger) {
if (cancelled_)
return;

bridge_->UpdateLedger(ledger);
}

BraveExternalProcessImporterClient::~BraveExternalProcessImporterClient() {}
3 changes: 3 additions & 0 deletions browser/importer/brave_external_process_importer_client.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include "net/cookies/canonical_cookie.h"

struct BraveStats;
struct BraveLedger;

class BraveExternalProcessImporterClient : public ExternalProcessImporterClient {
public:
Expand All @@ -30,6 +31,8 @@ class BraveExternalProcessImporterClient : public ExternalProcessImporterClient
const std::vector<net::CanonicalCookie>& cookies_group) override;
void OnStatsImportReady(
const BraveStats& stats) override;
void OnLedgerImportReady(
const BraveLedger& ledger) override;

private:
~BraveExternalProcessImporterClient() override;
Expand Down
16 changes: 16 additions & 0 deletions browser/importer/brave_in_process_importer_bridge.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "brave/browser/importer/brave_in_process_importer_bridge.h"
#include "chrome/browser/importer/external_process_importer_host.h"

BraveInProcessImporterBridge::BraveInProcessImporterBridge(
ProfileWriter* writer,
Expand All @@ -20,4 +21,19 @@ void BraveInProcessImporterBridge::UpdateStats(const BraveStats& stats) {
writer_->UpdateStats(stats);
}

void BraveInProcessImporterBridge::UpdateLedger(
const BraveLedger& ledger) {
writer_->SetBridge(this);
writer_->UpdateLedger(ledger);
}

void BraveInProcessImporterBridge::FinishLedgerImport () {
NotifyItemEnded(importer::LEDGER);
NotifyEnded();
}

void BraveInProcessImporterBridge::Cancel () {
host_->Cancel();
}

BraveInProcessImporterBridge::~BraveInProcessImporterBridge() {}
5 changes: 5 additions & 0 deletions browser/importer/brave_in_process_importer_bridge.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "brave/browser/importer/brave_profile_writer.h"
#include "chrome/browser/importer/in_process_importer_bridge.h"
#include "net/cookies/canonical_cookie.h"
#include "brave/browser/importer/brave_external_process_importer_host.h"

#include "base/compiler_specific.h"
#include "base/macros.h"
Expand All @@ -25,6 +26,10 @@ class BraveInProcessImporterBridge : public InProcessImporterBridge {
void SetCookies(
const std::vector<net::CanonicalCookie>& cookies) override;
void UpdateStats(const BraveStats& stats) override;
void UpdateLedger(const BraveLedger& ledger) override;

void FinishLedgerImport();
void Cancel();

private:
~BraveInProcessImporterBridge() override;
Expand Down
215 changes: 213 additions & 2 deletions browser/importer/brave_profile_writer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,17 @@
#include "brave/browser/importer/brave_profile_writer.h"
#include "brave/common/importer/brave_stats.h"
#include "brave/common/pref_names.h"
#include "brave/components/brave_rewards/browser/rewards_service.h"
#include "brave/components/brave_rewards/browser/rewards_service_factory.h"
#include "brave/components/brave_rewards/browser/wallet_properties.h"
#include "brave/utility/importer/brave_importer.h"
#include "brave/browser/importer/brave_in_process_importer_bridge.h"

#include "base/files/file_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/time/time.h"
#include "base/task/post_task.h"

#include "chrome/browser/profiles/profile.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
Expand All @@ -19,10 +27,18 @@
#include "net/url_request/url_request_context_getter.h"
#include "services/network/public/mojom/cookie_manager.mojom.h"

#include <sstream>

BraveProfileWriter::BraveProfileWriter(Profile* profile)
: ProfileWriter(profile) {}
: ProfileWriter(profile),
task_runner_(base::CreateSequencedTaskRunnerWithTraits({
base::MayBlock(), base::TaskPriority::BEST_EFFORT,
base::TaskShutdownBehavior::BLOCK_SHUTDOWN})) {
}

BraveProfileWriter::~BraveProfileWriter() {}
BraveProfileWriter::~BraveProfileWriter() {
DCHECK(!IsInObserverList());
}

void BraveProfileWriter::AddCookies(
const std::vector<net::CanonicalCookie>& cookies) {
Expand Down Expand Up @@ -63,3 +79,198 @@ void BraveProfileWriter::UpdateStats(const BraveStats& stats) {
https_upgrades + stats.httpsEverywhere_count);
}
}

void BraveProfileWriter::SetBridge(BraveInProcessImporterBridge* bridge) {
bridge_ptr_ = bridge;
}

void BraveProfileWriter::OnWalletInitialized(brave_rewards::RewardsService*
rewards_service, int error_code) {
if (error_code) {
// Cancel the import if wallet creation failed
std::ostringstream msg;
msg << "An error occurred while trying to create a "
<< "wallet to restore into (error_code=" << error_code << ")";
CancelWalletImport(msg.str());
return;
}

LOG(INFO) << "Wallet creation successful\nStarting wallet recovery...";
rewards_service->RecoverWallet(ledger_.passphrase);
}

void BraveProfileWriter::BackupWallet() {
const base::FilePath profile_default_directory = profile_->GetPath();
std::ostringstream backup_filename;
backup_filename << "ledger_import_backup_"
<< base::NumberToString((unsigned long long)base::Time::Now().ToJsTime());

LOG(INFO) << "Making backup of current \"ledger_state\" as "
<< "\"" << backup_filename.str() << "\"";

base::PostTaskAndReplyWithResult(
task_runner_.get(),
FROM_HERE,
base::Bind(&base::CopyFile,
profile_default_directory.AppendASCII("ledger_state"),
profile_default_directory.AppendASCII(backup_filename.str())),
base::Bind(&BraveProfileWriter::OnWalletBackupComplete,
this));
}

void BraveProfileWriter::OnWalletBackupComplete(bool result) {
if (!result) {
CancelWalletImport("Failed to make a backup of \"ledger_state\"");
return;
}

LOG(INFO) << "Backup complete; Recovering imported wallet...";
rewards_service_->RecoverWallet(ledger_.passphrase);
}

void BraveProfileWriter::OnWalletProperties(
brave_rewards::RewardsService* rewards_service,
int error_code,
brave_rewards::WalletProperties* properties) {
// Avoid overwriting Brave Rewards wallet if:
// - it existed BEFORE import happened
// - it has a non-zero balance
if (properties->balance > 0) {
std::ostringstream msg;
msg << "Brave Rewards wallet existed before import and "
<< "has a balance of " << properties->balance << "; skipping "
<< "Brave Payments import.";
CancelWalletImport(msg.str());
return;
} else {
LOG(INFO) << "Existing wallet does not have a balance";
}

BackupWallet();
}

void BraveProfileWriter::OnRecoverWallet(
brave_rewards::RewardsService* rewards_service,
unsigned int result,
double balance,
std::vector<brave_rewards::Grant> grants) {
rewards_service->RemoveObserver(this);

if (result) {
// Cancel the import if wallet restore failed
std::ostringstream msg;
msg << "An error occurred while trying to restore "
<< "the wallet (result=" << result << ")";
CancelWalletImport(msg.str());
return;
}

LOG(INFO) << "Wallet restore successful";
SetWalletProperties(rewards_service);

// Set the pinned item count (rewards can detect and take action)
PrefService* prefs = profile_->GetPrefs();
prefs->SetInteger(kBravePaymentsPinnedItemCount, pinned_item_count_);

// Notify the caller that import is complete
DCHECK(bridge_ptr_);
bridge_ptr_->FinishLedgerImport();
bsclifton marked this conversation as resolved.
Show resolved Hide resolved
}

void BraveProfileWriter::CancelWalletImport(std::string msg) {
if (IsInObserverList()) {
rewards_service_->RemoveObserver(this);
}
LOG(ERROR) << msg;
DCHECK(bridge_ptr_);
bridge_ptr_->Cancel();
bsclifton marked this conversation as resolved.
Show resolved Hide resolved
}

void BraveProfileWriter::SetWalletProperties(brave_rewards::RewardsService*
rewards_service) {
// Set the preferences read from session-store-1
auto* payments = &ledger_.settings.payments;
rewards_service->SetPublisherAllowVideos(payments->allow_media_publishers);
rewards_service->SetPublisherAllowNonVerified(payments->allow_non_verified);
rewards_service->SetPublisherMinVisitTime(payments->min_visit_time);
rewards_service->SetPublisherMinVisits(payments->min_visits);

// Set the excluded sites
for (const auto& publisher_key : ledger_.excluded_publishers) {
rewards_service->ExcludePublisher(publisher_key);
}

// Set the recurring tips (formerly known as pinned sites)
int sum_of_monthly_tips = 0;
pinned_item_count_ = 0;
for (const auto& publisher : ledger_.pinned_publishers) {
// NOTE: this will truncate (ex: 0.90 would be 0, not 1)
const int amount_in_bat = (int)((publisher.pin_percentage / 100.0) *
ledger_.settings.payments.contribution_amount);
if (amount_in_bat > 0) {
pinned_item_count_++;
sum_of_monthly_tips += amount_in_bat;

// Add `recurring_donation` entry
rewards_service->OnDonate(publisher.key, amount_in_bat, true);

// Add publisher to `publisher_info`
// TODO: finish me in https://github.com/brave/brave-core/pull/926
// ledger::PublisherInfo publisher_info;
// publisher_info.id = publisher.key;
// publisher_info.verified = publisher.verified;
// publisher_info.excluded = 0;
// publisher_info.name = publisher.name;
// publisher_info.url = publisher.url;
// publisher_info.provider = publisher.provider;
// publisher_info.favicon_url = "";
// publisher_info.month = -1; // ledger::PUBLISHER_MONTH::ANY;
// rewards_service->SavePublisherInfo(publisher_info);
}
}

// Adjust monthly contribution budget
// Some may have been allocated for recurring tips
bool auto_contribute_enabled = payments->enabled;
const int minimum_monthly_contribution = 10;
new_contribution_amount_ = payments->contribution_amount;
if (sum_of_monthly_tips > 0) {
new_contribution_amount_ -= sum_of_monthly_tips;
// If left over budget is too low, turn off auto-contribute
if (new_contribution_amount_ < minimum_monthly_contribution) {
LOG(INFO) << "Setting auto-contribute to false.\n"
<< "Recurring contributions take up " << sum_of_monthly_tips
<< " of the monthly " << payments->contribution_amount
<< " budget.\nThis leaves " << new_contribution_amount_
<< " which is less than the minimum monthly auto-contribute amount ("
<< minimum_monthly_contribution << ").";
auto_contribute_enabled = false;
new_contribution_amount_ = minimum_monthly_contribution;
}
}
rewards_service->SetContributionAmount(new_contribution_amount_);
rewards_service->SetAutoContribute(auto_contribute_enabled);
}

void BraveProfileWriter::UpdateLedger(const BraveLedger& ledger) {
rewards_service_ =
brave_rewards::RewardsServiceFactory::GetForProfile(profile_);
if (!rewards_service_) {
CancelWalletImport("Failed to get RewardsService for profile.");
return;
}

ledger_ = BraveLedger(ledger);

// If a wallet doesn't exist, we need to create one (needed for RecoverWallet)
if (!rewards_service_->IsWalletCreated()) {
rewards_service_->AddObserver(this);
LOG(INFO) << "Creating wallet to use for import...";
rewards_service_->CreateWallet();
return;
}

LOG(INFO) << "Wallet exists; fetching details...";
rewards_service_->AddObserver(this);
rewards_service_->FetchWalletProperties();
}
Loading