diff --git a/DEPS b/DEPS index 16da45f2d170..4dcd1ac99ac9 100644 --- a/DEPS +++ b/DEPS @@ -13,7 +13,7 @@ deps = { "vendor/sparkle": "https://github.com/brave/Sparkle.git@c0759cce415d7c0feae45005c8a013b1898711f0", "vendor/bat-native-rapidjson": "https://github.com/brave-intl/bat-native-rapidjson.git@86aafe2ef89835ae71c9ed7c2527e3bb3000930e", "vendor/bip39wally-core-native": "https://github.com/brave-intl/bip39wally-core-native.git@9b119931c702d55be994117eb505d56310720b1d", - "vendor/bat-native-anonize": "https://github.com/brave-intl/bat-native-anonize.git@adeff3254bb90ccdc9699040d5a4e1cd6b8393b7", + "vendor/bat-native-anonize": "https://github.com/brave-intl/bat-native-anonize.git@19fb43fd58b852fd2c6e4d4c68daa99c835f5182", "vendor/bat-native-tweetnacl": "https://github.com/brave-intl/bat-native-tweetnacl.git@1b4362968c8f22720bfb75af6f506d4ecc0f3116", "components/brave_sync/extension/brave-sync": "https://github.com/brave/sync.git@249a663a6f163f8fe5d2e96f9605760fb7627da0", "components/brave_sync/extension/brave-crypto": "https://github.com/brave/crypto@7e391cec6975106fa9f686016f494cb8a782afcd", diff --git a/app/brave_generated_resources.grd b/app/brave_generated_resources.grd index b054a6bed697..6d6c4f26ac45 100644 --- a/app/brave_generated_resources.grd +++ b/app/brave_generated_resources.grd @@ -258,6 +258,9 @@ By installing this extension, you are agreeing to the Google Widevine Terms of U Bat Ads Service + + Bat Ledger Service + Brave shields defaults diff --git a/browser/BUILD.gn b/browser/BUILD.gn index 7eea62ea21fe..d302c39321f4 100644 --- a/browser/BUILD.gn +++ b/browser/BUILD.gn @@ -116,6 +116,7 @@ source_set("browser") { "//base", "//brave/components/brave_ads/browser", "//brave/components/brave_referrals/browser", + "//brave/components/brave_rewards/browser", "//brave/components/brave_shields/browser:brave_shields", "//brave/components/brave_webtorrent/browser", "//brave/components/resources", diff --git a/browser/brave_content_browser_client.cc b/browser/brave_content_browser_client.cc index 3ecc7bf62f87..9559709120aa 100644 --- a/browser/brave_content_browser_client.cc +++ b/browser/brave_content_browser_client.cc @@ -17,6 +17,7 @@ #include "brave/common/tor/tor_launcher.mojom.h" #include "brave/common/tor/switches.h" #include "brave/components/brave_ads/browser/buildflags/buildflags.h" +#include "brave/components/brave_rewards/browser/buildflags/buildflags.h" #include "brave/components/brave_shields/browser/brave_shields_util.h" #include "brave/components/brave_shields/browser/brave_shields_web_contents_observer.h" #include "brave/components/brave_shields/common/brave_shield_constants.h" @@ -49,6 +50,10 @@ using brave_shields::BraveShieldsWebContentsObserver; #include "brave/components/services/bat_ads/public/interfaces/bat_ads.mojom.h" #endif +#if BUILDFLAG(BRAVE_REWARDS_ENABLED) +#include "brave/components/services/bat_ledger/public/interfaces/bat_ledger.mojom.h" +#endif + #if BUILDFLAG(ENABLE_EXTENSIONS) using extensions::ChromeContentBrowserClientExtensionsPart; #endif @@ -194,6 +199,10 @@ void BraveContentBrowserClient::RegisterOutOfProcessServices( (*services)[bat_ads::mojom::kServiceName] = base::BindRepeating( l10n_util::GetStringUTF16, IDS_SERVICE_BAT_ADS); #endif +#if BUILDFLAG(BRAVE_REWARDS_ENABLED) + (*services)[bat_ledger::mojom::kServiceName] = base::BindRepeating( + l10n_util::GetStringUTF16, IDS_UTILITY_PROCESS_LEDGER_NAME); +#endif } std::unique_ptr diff --git a/browser/extensions/BUILD.gn b/browser/extensions/BUILD.gn index fbccfcbb3694..35b51bf7e264 100644 --- a/browser/extensions/BUILD.gn +++ b/browser/extensions/BUILD.gn @@ -39,6 +39,7 @@ source_set("extensions") { ] deps = [ + "//base", "//brave/browser/resources:brave_extension_grit", "//brave/common/extensions/api", "//brave/components/brave_rewards/resources/extension:extension_generated_resources", diff --git a/browser/extensions/api/brave_rewards_api.cc b/browser/extensions/api/brave_rewards_api.cc index eb9ec9ff3467..97944ed53360 100644 --- a/browser/extensions/api/brave_rewards_api.cc +++ b/browser/extensions/api/brave_rewards_api.cc @@ -6,6 +6,7 @@ #include +#include "base/bind.h" #include "brave/browser/brave_rewards/donations_dialog.h" #include "brave/common/extensions/api/brave_rewards.h" #include "brave/components/brave_rewards/browser/rewards_service.h" @@ -177,11 +178,20 @@ BraveRewardsGetNonVerifiedSettingsFunction::Run() { RewardsServiceFactory::GetForProfile(profile); bool non_verified = true; - if (rewards_service_) { - non_verified = rewards_service_->GetPublisherAllowNonVerified(); + if (!rewards_service_) { + return RespondNow(OneArgument( + std::make_unique(non_verified))); } - return RespondNow(OneArgument(std::make_unique(non_verified))); + rewards_service_->GetPublisherAllowNonVerified(base::Bind( + &BraveRewardsGetNonVerifiedSettingsFunction::OnGetAllowNonVerified, + this)); + return RespondLater(); +} + +void BraveRewardsGetNonVerifiedSettingsFunction::OnGetAllowNonVerified( + bool non_verified) { + Respond(OneArgument(std::make_unique(non_verified))); } } // namespace api diff --git a/browser/extensions/api/brave_rewards_api.h b/browser/extensions/api/brave_rewards_api.h index 35a973b0d560..395c59dbd284 100644 --- a/browser/extensions/api/brave_rewards_api.h +++ b/browser/extensions/api/brave_rewards_api.h @@ -109,6 +109,9 @@ class BraveRewardsGetNonVerifiedSettingsFunction : public UIThreadExtensionFunct ~BraveRewardsGetNonVerifiedSettingsFunction() override; ResponseAction Run() override; + + private: + void OnGetAllowNonVerified(bool non_verified); }; } // namespace api diff --git a/browser/importer/brave_profile_writer.cc b/browser/importer/brave_profile_writer.cc index c5a4808645d6..1b71ce9f4123 100644 --- a/browser/importer/brave_profile_writer.cc +++ b/browser/importer/brave_profile_writer.cc @@ -300,9 +300,13 @@ void BraveProfileWriter::UpdateLedger(const BraveLedger& ledger) { } ledger_ = BraveLedger(ledger); + rewards_service_->IsWalletCreated( + base::Bind(&BraveProfileWriter::OnIsWalletCreated, AsWeakPtr())); +} +void BraveProfileWriter::OnIsWalletCreated(bool created) { // If a wallet doesn't exist, we need to create one (needed for RecoverWallet) - if (!rewards_service_->IsWalletCreated()) { + if (!created) { rewards_service_->AddObserver(this); LOG(INFO) << "Creating wallet to use for import..."; rewards_service_->CreateWallet(); diff --git a/browser/importer/brave_profile_writer.h b/browser/importer/brave_profile_writer.h index 8717618df15d..4e13e7dcb6fa 100644 --- a/browser/importer/brave_profile_writer.h +++ b/browser/importer/brave_profile_writer.h @@ -8,6 +8,7 @@ #include #include "base/macros.h" +#include "base/memory/weak_ptr.h" #include "chrome/browser/importer/profile_writer.h" #include "net/cookies/canonical_cookie.h" #include "brave/components/brave_rewards/browser/rewards_service_observer.h" @@ -19,7 +20,8 @@ class BraveInProcessImporterBridge; struct ImportedWindowState; class BraveProfileWriter : public ProfileWriter, - public brave_rewards::RewardsServiceObserver { + public brave_rewards::RewardsServiceObserver, + public base::SupportsWeakPtr{ public: explicit BraveProfileWriter(Profile* profile); @@ -32,6 +34,8 @@ class BraveProfileWriter : public ProfileWriter, void SetBridge(BraveInProcessImporterBridge* bridge); + void OnIsWalletCreated(bool created); + // brave_rewards::RewardsServiceObserver: void OnWalletInitialized(brave_rewards::RewardsService* rewards_service, int error_code) override; diff --git a/browser/profiles/BUILD.gn b/browser/profiles/BUILD.gn index 18486beff78a..50f1c3a73dd2 100644 --- a/browser/profiles/BUILD.gn +++ b/browser/profiles/BUILD.gn @@ -13,6 +13,7 @@ source_set("profiles") { "//brave/common/tor", "//brave/components/brave_ads/browser", "//brave/components/brave_sync", + "//brave/components/brave_rewards/browser", "//ui/base", ] } diff --git a/browser/profiles/brave_profile_manager.cc b/browser/profiles/brave_profile_manager.cc index 5d09e455df94..871a3c581f53 100644 --- a/browser/profiles/brave_profile_manager.cc +++ b/browser/profiles/brave_profile_manager.cc @@ -12,6 +12,7 @@ #include "brave/common/tor/pref_names.h" #include "brave/common/tor/tor_constants.h" #include "brave/components/brave_ads/browser/ads_service_factory.h" +#include "brave/components/brave_rewards/browser/rewards_service_factory.h" #include "brave/components/brave_sync/brave_sync_service_factory.h" #include "chrome/browser/browser_process.h" #include "chrome/common/chrome_constants.h" @@ -98,6 +99,7 @@ void BraveProfileManager::DoFinalInitForServices(Profile* profile, // it will only be constructed only when we open chrome:/sync/ brave_sync::BraveSyncServiceFactory::GetForProfile(profile); brave_ads::AdsServiceFactory::GetForProfile(profile); + brave_rewards::RewardsServiceFactory::GetForProfile(profile); } void BraveProfileManager::LaunchTorProcess(Profile* profile) { diff --git a/browser/ui/webui/brave_rewards_ui.cc b/browser/ui/webui/brave_rewards_ui.cc index ea568a0839dc..360b3bf5cc20 100644 --- a/browser/ui/webui/brave_rewards_ui.cc +++ b/browser/ui/webui/brave_rewards_ui.cc @@ -68,6 +68,8 @@ class RewardsDOMHandler : public WebUIMessageHandler, void OnGetCurrentContributeList( std::unique_ptr, uint32_t record); + void OnGetAllBalanceReports( + const std::map& reports); void GetBalanceReports(const base::ListValue* args); void ExcludePublisher(const base::ListValue* args); void RestorePublishers(const base::ListValue* args); @@ -81,6 +83,18 @@ class RewardsDOMHandler : public WebUIMessageHandler, void GetAdsData(const base::ListValue* args); void SaveAdsSetting(const base::ListValue* args); void SetBackupCompleted(const base::ListValue* args); + void OnGetWalletPassphrase(const std::string& pass); + void OnGetContributionAmount(double amount); + void OnGetAddresses(const std::map& addresses); + void OnGetNumExcludedSites(const std::string& publisher_id, uint32_t num); + void OnGetAutoContributeProps( + int error_code, + std::unique_ptr wallet_properties, + std::unique_ptr auto_contri_props); + void OnGetReconcileStamp(uint64_t reconcile_stamp); + void OnAutoContributePropsReady( + std::unique_ptr auto_contri_props); + void OnIsWalletCreated(bool created); // RewardsServiceObserver implementation void OnWalletInitialized(brave_rewards::RewardsService* rewards_service, @@ -230,9 +244,9 @@ void RewardsDOMHandler::Init() { rewards_service_->AddObserver(this); } -void RewardsDOMHandler::GetAllBalanceReports() { - if (rewards_service_ && web_ui()->CanCallJavascript()) { - std::map reports = rewards_service_->GetAllBalanceReports(); +void RewardsDOMHandler::OnGetAllBalanceReports( + const std::map& reports) { + if (web_ui()->CanCallJavascript()) { base::DictionaryValue newReports; if (!reports.empty()) { for (auto const& report : reports) { @@ -251,10 +265,18 @@ void RewardsDOMHandler::GetAllBalanceReports() { } } - web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.balanceReports", newReports); + web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.balanceReports", + newReports); } } +void RewardsDOMHandler::GetAllBalanceReports() { + if (rewards_service_) + rewards_service_->GetAllBalanceReports( + base::Bind(&RewardsDOMHandler::OnGetAllBalanceReports, + weak_factory_.GetWeakPtr())); +} + void RewardsDOMHandler::HandleCreateWalletRequested(const base::ListValue* args) { if (!rewards_service_) return; @@ -281,22 +303,22 @@ void RewardsDOMHandler::OnWalletInitialized( web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.walletCreateFailed"); } -void RewardsDOMHandler::OnWalletProperties( - brave_rewards::RewardsService* rewards_service, +void RewardsDOMHandler::OnGetAutoContributeProps( int error_code, - std::unique_ptr wallet_properties) { + std::unique_ptr wallet_properties, + std::unique_ptr auto_contri_props) { if (web_ui()->CanCallJavascript()) { base::DictionaryValue values; values.SetBoolean("enabledContribute", - rewards_service->GetAutoContribute()); + auto_contri_props->enabled_contribute); values.SetInteger("contributionMinTime", - rewards_service->GetPublisherMinVisitTime()); + auto_contri_props->contribution_min_time); values.SetInteger("contributionMinVisits", - rewards_service->GetPublisherMinVisits()); + auto_contri_props->contribution_min_visits); values.SetBoolean("contributionNonVerified", - rewards_service->GetPublisherAllowNonVerified()); + auto_contri_props->contribution_non_verified); values.SetBoolean("contributionVideos", - rewards_service->GetPublisherAllowVideos()); + auto_contri_props->contribution_videos); auto ui_values = std::make_unique(); @@ -351,6 +373,16 @@ void RewardsDOMHandler::OnWalletProperties( } } +void RewardsDOMHandler::OnWalletProperties( + brave_rewards::RewardsService* rewards_service, + int error_code, + std::unique_ptr wallet_properties) { + rewards_service->GetAutoContributeProps( + base::Bind(&RewardsDOMHandler::OnGetAutoContributeProps, + weak_factory_.GetWeakPtr(), error_code, + base::Passed(std::move(wallet_properties)))); +} + void RewardsDOMHandler::OnGrant( brave_rewards::RewardsService* rewards_service, unsigned int result, @@ -396,11 +428,18 @@ void RewardsDOMHandler::GetGrantCaptcha(const base::ListValue* args) { } } -void RewardsDOMHandler::GetWalletPassphrase(const base::ListValue* args) { - if (rewards_service_ && web_ui()->CanCallJavascript()) { - std::string pass = rewards_service_->GetWalletPassphrase(); +void RewardsDOMHandler::OnGetWalletPassphrase(const std::string& pass) { + if (web_ui()->CanCallJavascript()) { + web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.walletPassphrase", + base::Value(pass)); + } +} - web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.walletPassphrase", base::Value(pass)); +void RewardsDOMHandler::GetWalletPassphrase(const base::ListValue* args) { + if (rewards_service_) { + rewards_service_->GetWalletPassphrase( + base::Bind(&RewardsDOMHandler::OnGetWalletPassphrase, + weak_factory_.GetWeakPtr())); } } @@ -459,49 +498,78 @@ void RewardsDOMHandler::OnGrantFinish( } } -void RewardsDOMHandler::GetReconcileStamp(const base::ListValue* args) { - if (rewards_service_ && web_ui()->CanCallJavascript()) { - std::string stamp = std::to_string(rewards_service_->GetReconcileStamp()); - - web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.reconcileStamp", base::Value(stamp)); +void RewardsDOMHandler::OnGetReconcileStamp(uint64_t reconcile_stamp) { + if (web_ui()->CanCallJavascript()) { + std::string stamp = std::to_string(reconcile_stamp); + web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.reconcileStamp", + base::Value(stamp)); } } -void RewardsDOMHandler::GetAddresses(const base::ListValue* args) { - if (rewards_service_ && web_ui()->CanCallJavascript()) { - std::map addresses = rewards_service_->GetAddresses(); +void RewardsDOMHandler::GetReconcileStamp(const base::ListValue* args) { + if (rewards_service_) + rewards_service_->GetReconcileStamp(base::Bind( + &RewardsDOMHandler::OnGetReconcileStamp, + weak_factory_.GetWeakPtr())); +} +void RewardsDOMHandler::OnGetAddresses( + const std::map& addresses) { + if (web_ui()->CanCallJavascript()) { base::DictionaryValue data; - data.SetString("BAT", addresses["BAT"]); - data.SetString("BTC", addresses["BTC"]); - data.SetString("ETH", addresses["ETH"]); - data.SetString("LTC", addresses["LTC"]); + data.SetString("BAT", addresses.at("BAT")); + data.SetString("BTC", addresses.at("BTC")); + data.SetString("ETH", addresses.at("ETH")); + data.SetString("LTC", addresses.at("LTC")); web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.addresses", data); } } -void RewardsDOMHandler::OnContentSiteUpdated(brave_rewards::RewardsService* rewards_service) { - rewards_service_->GetCurrentContributeList( - 0, - 0, +void RewardsDOMHandler::GetAddresses(const base::ListValue* args) { + if (rewards_service_) + rewards_service_->GetAddresses(base::Bind( + &RewardsDOMHandler::OnGetAddresses, weak_factory_.GetWeakPtr())); +} + +void RewardsDOMHandler::OnAutoContributePropsReady( + std::unique_ptr props) { + rewards_service_->GetCurrentContributeList(0, 0, + props->contribution_min_time, props->reconcile_stamp, + props->contribution_non_verified, base::Bind(&RewardsDOMHandler::OnGetCurrentContributeList, - weak_factory_.GetWeakPtr())); + weak_factory_.GetWeakPtr())); } -void RewardsDOMHandler::OnExcludedSitesChanged(brave_rewards::RewardsService* rewards_service, - std::string publisher_id) { - if (rewards_service_ && web_ui()->CanCallJavascript()) { - base::DictionaryValue excludedSitesInfo; - int num = rewards_service_->GetNumExcludedSites(); +void RewardsDOMHandler::OnContentSiteUpdated( + brave_rewards::RewardsService* rewards_service) { + rewards_service_->GetAutoContributeProps( + base::Bind(&RewardsDOMHandler::OnAutoContributePropsReady, + weak_factory_.GetWeakPtr())); +} +void RewardsDOMHandler::OnGetNumExcludedSites(const std::string& publisher_id, + uint32_t num) { + if (web_ui()->CanCallJavascript()) { + base::DictionaryValue excludedSitesInfo; excludedSitesInfo.SetString("num", std::to_string(num)); excludedSitesInfo.SetString("publisherKey", publisher_id); - web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.numExcludedSites", excludedSitesInfo); + web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.numExcludedSites", + excludedSitesInfo); } } +void RewardsDOMHandler::OnExcludedSitesChanged( + brave_rewards::RewardsService* rewards_service, + std::string publisher_id) { + if (rewards_service_) + rewards_service_->GetNumExcludedSites(base::Bind( + &RewardsDOMHandler::OnGetNumExcludedSites, + weak_factory_.GetWeakPtr(), + publisher_id)); +} + void RewardsDOMHandler::OnNotificationAdded( brave_rewards::RewardsNotificationService* rewards_notification_service, const brave_rewards::RewardsNotificationService::RewardsNotification& @@ -610,20 +678,31 @@ void RewardsDOMHandler::GetBalanceReports(const base::ListValue* args) { GetAllBalanceReports(); } +void RewardsDOMHandler::OnIsWalletCreated(bool created) { + if (web_ui()->CanCallJavascript()) + web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.walletExists", + base::Value(created)); +} + void RewardsDOMHandler::WalletExists(const base::ListValue* args) { - if (rewards_service_ && web_ui()->CanCallJavascript()) { - bool exist = rewards_service_->IsWalletCreated(); + if (rewards_service_) + rewards_service_->IsWalletCreated( + base::Bind(&RewardsDOMHandler::OnIsWalletCreated, + weak_factory_.GetWeakPtr())); +} - web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.walletExists", base::Value(exist)); +void RewardsDOMHandler::OnGetContributionAmount(double amount) { + if (web_ui()->CanCallJavascript()) { + web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.contributionAmount", + base::Value(amount)); } } void RewardsDOMHandler::GetContributionAmount(const base::ListValue* args) { - if (rewards_service_ && web_ui()->CanCallJavascript()) { - double amount = rewards_service_->GetContributionAmount(); - - web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.contributionAmount", base::Value(amount)); - } + if (rewards_service_) + rewards_service_->GetContributionAmount( + base::Bind(&RewardsDOMHandler::OnGetContributionAmount, + weak_factory_.GetWeakPtr())); } void RewardsDOMHandler::OnReconcileComplete( diff --git a/components/brave_rewards/browser/BUILD.gn b/components/brave_rewards/browser/BUILD.gn index 6a5eccd10f97..47ec10694f7c 100644 --- a/components/brave_rewards/browser/BUILD.gn +++ b/components/brave_rewards/browser/BUILD.gn @@ -9,6 +9,8 @@ source_set("browser") { sources = [ "switches.cc", "switches.h", + "auto_contribution_props.cc", + "auto_contribution_props.h", "balance_report.cc", "balance_report.h", "rewards_notification_service.cc", @@ -92,7 +94,10 @@ source_set("browser") { deps += [ "//brave/vendor/bat-native-ledger", + "//brave/components/services/bat_ledger/public/cpp", + "//mojo/public/cpp/bindings", "//net", + "//services/service_manager/public/cpp", "//url", ] } diff --git a/components/brave_rewards/browser/auto_contribution_props.cc b/components/brave_rewards/browser/auto_contribution_props.cc new file mode 100644 index 000000000000..252e85b23c45 --- /dev/null +++ b/components/brave_rewards/browser/auto_contribution_props.cc @@ -0,0 +1,20 @@ +/* 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/. */ + +#include "brave/components/brave_rewards/browser/auto_contribution_props.h" + +namespace brave_rewards { + +AutoContributeProps::AutoContributeProps() + : enabled_contribute(false), + contribution_min_time(0), + contribution_min_visits(0), + contribution_non_verified(false), + contribution_videos(false), + reconcile_stamp(0) { +} + +AutoContributeProps::~AutoContributeProps() { } + +} // namespace brave_rewards diff --git a/components/brave_rewards/browser/auto_contribution_props.h b/components/brave_rewards/browser/auto_contribution_props.h new file mode 100644 index 000000000000..270573c0d773 --- /dev/null +++ b/components/brave_rewards/browser/auto_contribution_props.h @@ -0,0 +1,27 @@ +/* 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/. */ + +#ifndef BRAVE_COMPONENTS_BRAVE_REWARDS_BROWSER_AUTO_CONTRIBUTION_PROPS_H_ +#define BRAVE_COMPONENTS_BRAVE_REWARDS_BROWSER_AUTO_CONTRIBUTION_PROPS_H_ + +#include + +namespace brave_rewards { + +struct AutoContributeProps { + AutoContributeProps(); + ~AutoContributeProps(); + AutoContributeProps(const AutoContributeProps& properties) = default; + + bool enabled_contribute; + uint64_t contribution_min_time; + int32_t contribution_min_visits; + bool contribution_non_verified; + bool contribution_videos; + uint64_t reconcile_stamp; +}; + +} // namespace brave_rewards + +#endif //BRAVE_COMPONENTS_BRAVE_REWARDS_BROWSER_AUTO_CONTRIBUTION_PROPS_H_ diff --git a/components/brave_rewards/browser/rewards_service.h b/components/brave_rewards/browser/rewards_service.h index 18cd98ea56ee..5b02519c9335 100644 --- a/components/brave_rewards/browser/rewards_service.h +++ b/components/brave_rewards/browser/rewards_service.h @@ -9,8 +9,9 @@ #include "base/macros.h" #include "base/observer_list.h" -#include "brave/components/brave_rewards/browser/content_site.h" +#include "brave/components/brave_rewards/browser/auto_contribution_props.h" #include "brave/components/brave_rewards/browser/balance_report.h" +#include "brave/components/brave_rewards/browser/content_site.h" #include "brave/components/brave_rewards/browser/publisher_banner.h" #include "build/build_config.h" #include "components/sessions/core/session_id.h" @@ -22,7 +23,6 @@ class Profile; namespace ledger { struct PublisherInfo; -class Ledger; } namespace content { @@ -41,6 +41,22 @@ class RewardsServiceObserver; using GetCurrentContributeListCallback = base::Callback, uint32_t /* next_record */)>; +using GetAllBalanceReportsCallback = base::Callback&)>; +using GetWalletPassphraseCallback = base::Callback; +using GetContributionAmountCallback = base::Callback; +using GetAddressesCallback = base::Callback&)>; +using GetNumExcludedSitesCallback = base::Callback; +using GetAutoContributePropsCallback = base::Callback)>; +using GetPublisherMinVisitTimeCallback = base::Callback; +using GetPublisherMinVisitsCallback = base::Callback; +using GetPublisherAllowNonVerifiedCallback = base::Callback; +using GetPublisherAllowVideosCallback = base::Callback; +using GetAutoContributeCallback = base::Callback; +using GetReconcileStampCallback = base::Callback; +using IsWalletCreatedCallback = base::Callback; class RewardsService : public KeyedService { public: @@ -52,12 +68,17 @@ class RewardsService : public KeyedService { virtual void GetCurrentContributeList( uint32_t start, uint32_t limit, + uint64_t min_visit_time, + uint64_t reconcile_stamp, + bool allow_non_verified, const GetCurrentContributeListCallback& callback) = 0; virtual void FetchGrant(const std::string& lang, const std::string& paymentId) = 0; virtual void GetGrantCaptcha() = 0; virtual void SolveGrantCaptcha(const std::string& solution) const = 0; - virtual std::string GetWalletPassphrase() const = 0; - virtual unsigned int GetNumExcludedSites() const = 0; + virtual void GetWalletPassphrase( + const GetWalletPassphraseCallback& callback) = 0; + virtual void GetNumExcludedSites( + const GetNumExcludedSitesCallback& callback) = 0; virtual void RecoverWallet(const std::string passPhrase) const = 0; virtual void ExcludePublisher(const std::string publisherKey) const = 0; virtual void RestorePublishers() = 0; @@ -79,27 +100,35 @@ class RewardsService : public KeyedService { const GURL& referrer, const std::string& post_data) = 0; - virtual uint64_t GetReconcileStamp() const = 0; - virtual std::map GetAddresses() const = 0; + virtual void GetReconcileStamp( + const GetReconcileStampCallback& callback) = 0; + virtual void GetAddresses(const GetAddressesCallback& callback) = 0; virtual void SetRewardsMainEnabled(bool enabled) const = 0; - virtual uint64_t GetPublisherMinVisitTime() const = 0; + virtual void GetPublisherMinVisitTime( + const GetPublisherMinVisitTimeCallback& callback) = 0; virtual void SetPublisherMinVisitTime(uint64_t duration_in_seconds) const = 0; - virtual unsigned int GetPublisherMinVisits() const = 0; + virtual void GetPublisherMinVisits( + const GetPublisherMinVisitsCallback& callback) = 0; virtual void SetPublisherMinVisits(unsigned int visits) const = 0; - virtual bool GetPublisherAllowNonVerified() const = 0; + virtual void GetPublisherAllowNonVerified( + const GetPublisherAllowNonVerifiedCallback& callback) = 0; virtual void SetPublisherAllowNonVerified(bool allow) const = 0; - virtual bool GetPublisherAllowVideos() const = 0; + virtual void GetPublisherAllowVideos( + const GetPublisherAllowVideosCallback& callback) = 0; virtual void SetPublisherAllowVideos(bool allow) const = 0; virtual void SetContributionAmount(double amount) const = 0; virtual void SetUserChangedContribution() const = 0; - virtual bool GetAutoContribute() const = 0; + virtual void GetAutoContribute( + const GetAutoContributeCallback& callback) = 0; virtual void SetAutoContribute(bool enabled) const = 0; virtual void SetTimer(uint64_t time_offset, uint32_t& timer_id) = 0; - virtual std::map GetAllBalanceReports() = 0; + virtual void GetAllBalanceReports( + const GetAllBalanceReportsCallback& callback) = 0; virtual void GetCurrentBalanceReport() = 0; - virtual bool IsWalletCreated() = 0; + virtual void IsWalletCreated(const IsWalletCreatedCallback& callback) = 0; virtual void GetPublisherActivityFromUrl(uint64_t windowId, const std::string& url, const std::string& favicon_url) = 0; - virtual double GetContributionAmount() = 0; + virtual void GetContributionAmount( + const GetContributionAmountCallback& callback) = 0; virtual void GetPublisherBanner(const std::string& publisher_id) = 0; virtual void OnDonate(const std::string& publisher_key, int amount, bool recurring, const ledger::PublisherInfo* publisher_info = NULL) = 0; @@ -109,11 +138,12 @@ class RewardsService : public KeyedService { virtual void UpdateRecurringDonationsList() = 0; virtual void UpdateTipsList() = 0; virtual void SetContributionAutoInclude( - std::string publisher_key, bool excluded, uint64_t windowId) = 0; + const std::string& publisher_key, bool excluded, uint64_t windowId) = 0; virtual RewardsNotificationService* GetNotificationService() const = 0; virtual bool CheckImported() = 0; - virtual void SetLedgerClient(std::unique_ptr new_ledger) = 0; virtual void SetBackupCompleted() = 0; + virtual void GetAutoContributeProps( + const GetAutoContributePropsCallback& callback) = 0; void AddObserver(RewardsServiceObserver* observer); void RemoveObserver(RewardsServiceObserver* observer); diff --git a/components/brave_rewards/browser/rewards_service_browsertest.cc b/components/brave_rewards/browser/rewards_service_browsertest.cc index d965e4a4c2d1..9821ce7f0171 100644 --- a/components/brave_rewards/browser/rewards_service_browsertest.cc +++ b/components/brave_rewards/browser/rewards_service_browsertest.cc @@ -2,8 +2,12 @@ * 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/. */ +#include "base/run_loop.h" #include "base/path_service.h" +#include "bat/ledger/ledger.h" #include "brave/common/brave_paths.h" +#include "brave/components/brave_rewards/browser/rewards_service_impl.h" +#include "brave/components/brave_rewards/browser/rewards_service_factory.h" #include "brave/vendor/bat-native-ledger/src/bat_helper.h" #include "brave/vendor/bat-native-ledger/src/static_values.h" #include "chrome/browser/ui/browser.h" @@ -12,6 +16,10 @@ #include "content/public/test/browser_test_utils.h" #include "google_apis/gaia/mock_url_fetcher_factory.h" #include "net/url_request/url_fetcher_delegate.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +using namespace brave_rewards; namespace brave_test_resp { std::string registrarVK_; @@ -106,13 +114,38 @@ class BraveRewardsBrowserTest : public InProcessBrowserTest { InProcessBrowserTest::SetUpOnMainThread(); brave::RegisterPathProvider(); ReadTestData(); - braveledger_bat_helper::set_ignore_for_testing(true); + rewards_service_ = static_cast( + RewardsServiceFactory::GetForProfile(browser()->profile())); + rewards_service_->SetLedgerEnvForTesting(); } void TearDown() override { InProcessBrowserTest::TearDown(); } + void RunUntilIdle() { + base::RunLoop loop; + loop.RunUntilIdle(); + } + + void GetReconcileTime() { + rewards_service()->GetReconcileTime( + base::Bind(&BraveRewardsBrowserTest::OnGetReconcileTime, + base::Unretained(this))); + } + + void GetShortRetries() { + rewards_service()->GetShortRetries( + base::Bind(&BraveRewardsBrowserTest::OnGetShortRetries, + base::Unretained(this))); + } + + void GetProduction() { + rewards_service()->GetProduction( + base::Bind(&BraveRewardsBrowserTest::OnGetProduction, + base::Unretained(this))); + } + void ReadTestData() { base::FilePath path; ASSERT_TRUE(base::PathService::Get(brave::DIR_TEST_DATA, &path)); @@ -166,6 +199,13 @@ class BraveRewardsBrowserTest : public InProcessBrowserTest { ASSERT_TRUE(jsResult.ExtractBool()); } + RewardsServiceImpl* rewards_service() { return rewards_service_; } + + MOCK_METHOD1(OnGetProduction, void(bool)); + MOCK_METHOD1(OnGetReconcileTime, void(int32_t)); + MOCK_METHOD1(OnGetShortRetries, void(bool)); + + RewardsServiceImpl* rewards_service_; MockURLFetcherFactory factory; }; @@ -305,3 +345,115 @@ IN_PROC_BROWSER_TEST_F(BraveRewardsBrowserTest, ActivateSettingsModal) { content::ISOLATED_WORLD_ID_CONTENT_END); ASSERT_TRUE(modalResult.ExtractBool()); } + +IN_PROC_BROWSER_TEST_F(BraveRewardsBrowserTest, HandleFlagsSingleArg) { + testing::InSequence s; + // SetProduction(true) + EXPECT_CALL(*this, OnGetProduction(true)); + // Staging - true and 1 + EXPECT_CALL(*this, OnGetProduction(false)).Times(2); + // Staging - false and random + EXPECT_CALL(*this, OnGetProduction(true)).Times(2); + + rewards_service()->SetProduction(true); + GetProduction(); + RunUntilIdle(); + + // Staging - true + rewards_service()->SetProduction(true); + rewards_service()->HandleFlags("staging=true"); + GetProduction(); + RunUntilIdle(); + + // Staging - 1 + rewards_service()->SetProduction(true); + rewards_service()->HandleFlags("staging=1"); + GetProduction(); + RunUntilIdle(); + + // Staging - false + rewards_service()->SetProduction(false); + rewards_service()->HandleFlags("staging=false"); + GetProduction(); + RunUntilIdle(); + + // Staging - random + rewards_service()->SetProduction(false); + rewards_service()->HandleFlags("staging=werwe"); + GetProduction(); + RunUntilIdle(); + + // positive number + EXPECT_CALL(*this, OnGetReconcileTime(10)); + // negative number and string + EXPECT_CALL(*this, OnGetReconcileTime(0)).Times(2); + + // Reconcile interval - positive number + rewards_service()->SetReconcileTime(0); + rewards_service()->HandleFlags("reconcile-interval=10"); + GetReconcileTime(); + RunUntilIdle(); + + // Reconcile interval - negative number + rewards_service()->SetReconcileTime(0); + rewards_service()->HandleFlags("reconcile-interval=-1"); + GetReconcileTime(); + RunUntilIdle(); + + // Reconcile interval - string + rewards_service()->SetReconcileTime(0); + rewards_service()->HandleFlags("reconcile-interval=sdf"); + GetReconcileTime(); + RunUntilIdle(); + + EXPECT_CALL(*this, OnGetShortRetries(true)); // on + EXPECT_CALL(*this, OnGetShortRetries(false)); // off + + // Short retries - on + rewards_service()->SetShortRetries(false); + rewards_service()->HandleFlags("short-retries=true"); + GetShortRetries(); + RunUntilIdle(); + + // Short retries - off + rewards_service()->SetShortRetries(true); + rewards_service()->HandleFlags("short-retries=false"); + GetShortRetries(); + RunUntilIdle(); +} + +IN_PROC_BROWSER_TEST_F(BraveRewardsBrowserTest, HandleFlagsMultipleFlags) { + EXPECT_CALL(*this, OnGetProduction(false)); + EXPECT_CALL(*this, OnGetReconcileTime(10)); + EXPECT_CALL(*this, OnGetShortRetries(true)); + + rewards_service()->SetProduction(true); + rewards_service()->SetReconcileTime(0); + rewards_service()->SetShortRetries(false); + + rewards_service()->HandleFlags( + "staging=true,short-retries=true,reconcile-interval=10"); + + GetReconcileTime(); + GetShortRetries(); + GetProduction(); + RunUntilIdle(); +} + +IN_PROC_BROWSER_TEST_F(BraveRewardsBrowserTest, HandleFlagsWrongInput) { + EXPECT_CALL(*this, OnGetProduction(true)); + EXPECT_CALL(*this, OnGetReconcileTime(0)); + EXPECT_CALL(*this, OnGetShortRetries(false)); + + rewards_service()->SetProduction(true); + rewards_service()->SetReconcileTime(0); + rewards_service()->SetShortRetries(false); + + rewards_service()->HandleFlags( + "staging=,shortretries=true,reconcile-interval"); + + GetReconcileTime(); + GetShortRetries(); + GetProduction(); + RunUntilIdle(); +} diff --git a/components/brave_rewards/browser/rewards_service_impl.cc b/components/brave_rewards/browser/rewards_service_impl.cc index c478ce4f63fc..f834eb6bb462 100644 --- a/components/brave_rewards/browser/rewards_service_impl.cc +++ b/components/brave_rewards/browser/rewards_service_impl.cc @@ -10,6 +10,7 @@ #include "base/bind.h" #include "base/command_line.h" +#include "base/containers/flat_map.h" #include "base/files/file_util.h" #include "base/files/important_file_writer.h" #include "base/guid.h" @@ -23,11 +24,13 @@ #include "base/task_runner_util.h" #include "base/threading/sequenced_task_runner_handle.h" #include "bat/ledger/ledger.h" +#include "bat/ledger/auto_contribute_props.h" #include "bat/ledger/media_publisher_info.h" #include "bat/ledger/publisher_info.h" #include "bat/ledger/wallet_info.h" #include "brave/browser/ui/webui/brave_rewards_source.h" #include "brave/common/pref_names.h" +#include "brave/components/brave_rewards/browser/auto_contribution_props.h" #include "brave/components/brave_rewards/browser/balance_report.h" #include "brave/components/brave_rewards/browser/publisher_info_database.h" #include "brave/components/brave_rewards/browser/rewards_fetcher_service_observer.h" @@ -37,6 +40,7 @@ #include "brave/components/brave_rewards/browser/rewards_service_observer.h" #include "brave/components/brave_rewards/browser/switches.h" #include "brave/components/brave_rewards/browser/wallet_properties.h" +#include "brave/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h" #include "chrome/browser/bitmap_fetcher/bitmap_fetcher_service_factory.h" #include "chrome/browser/browser_process_impl.h" #include "chrome/browser/favicon/favicon_service_factory.h" @@ -46,13 +50,16 @@ #include "components/prefs/pref_service.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/url_data_source.h" +#include "content/public/common/service_manager_connection.h" #include "content_site.h" #include "extensions/buildflags/buildflags.h" +#include "mojo/public/cpp/bindings/map.h" #include "net/base/escape.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "net/base/url_util.h" #include "net/url_request/url_fetcher.h" #include "publisher_banner.h" +#include "services/service_manager/public/cpp/connector.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image.h" #include "url/gurl.h" @@ -106,26 +113,6 @@ class LogStreamImpl : public ledger::LogStream { namespace { -class LedgerURLLoaderImpl : public ledger::LedgerURLLoader { - public: - LedgerURLLoaderImpl(uint64_t request_id, net::URLFetcher* fetcher) : - request_id_(request_id), - fetcher_(fetcher) {} - ~LedgerURLLoaderImpl() override = default; - - void Start() override { - fetcher_->Start(); - } - - uint64_t request_id() override { - return request_id_; - } - - private: - uint64_t request_id_; - net::URLFetcher* fetcher_; // NOT OWNED -}; - ledger::PUBLISHER_MONTH GetPublisherMonth(const base::Time& time) { base::Time::Exploded exploded; time.LocalExplode(&exploded); @@ -254,8 +241,6 @@ time_t GetCurrentTimestamp() { return base::Time::NowFromSystemTime().ToTimeT(); } -static uint64_t next_id = 1; - } // namespace bool IsMediaLink(const GURL& url, @@ -282,7 +267,7 @@ const base::FilePath::StringType kPublishers_list("publishers_list"); RewardsServiceImpl::RewardsServiceImpl(Profile* profile) : profile_(profile), - ledger_(ledger::Ledger::CreateInstance(this)), + bat_ledger_client_binding_(new bat_ledger::LedgerClientMojoProxy(this)), #if BUILDFLAG(ENABLE_EXTENSIONS) extension_rewards_service_observer_( std::make_unique(profile_)), @@ -302,12 +287,55 @@ RewardsServiceImpl::RewardsServiceImpl(Profile* profile) std::make_unique(profile_)), #endif next_timer_id_(0) { + // Set up the rewards data source + content::URLDataSource::Add(profile_, + std::make_unique(profile_)); +} + +RewardsServiceImpl::~RewardsServiceImpl() { + file_task_runner_->DeleteSoon(FROM_HERE, publisher_info_backend_.release()); + StopNotificationTimers(); +} + +void RewardsServiceImpl::ConnectionClosed() { + base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(FROM_HERE, + base::BindOnce(&RewardsServiceImpl::StartLedger, AsWeakPtr()), + base::TimeDelta::FromSeconds(1)); +} + +void RewardsServiceImpl::Init() { + AddObserver(notification_service_.get()); +#if BUILDFLAG(ENABLE_EXTENSIONS) + AddObserver(extension_rewards_service_observer_.get()); + private_observers_.AddObserver(private_observer_.get()); +#endif + + StartLedger(); +} + +void RewardsServiceImpl::StartLedger() { + bat_ledger::mojom::BatLedgerClientAssociatedPtrInfo client_ptr_info; + bat_ledger_client_binding_.Bind(mojo::MakeRequest(&client_ptr_info)); + + content::ServiceManagerConnection* connection = + content::ServiceManagerConnection::GetForProcess(); + if (!connection) { + return; + } + + connection->GetConnector()->BindInterface( + bat_ledger::mojom::kServiceName, &bat_ledger_service_); + bat_ledger_service_.set_connection_error_handler( + base::Bind(&RewardsServiceImpl::ConnectionClosed, AsWeakPtr())); + + bool isProduction = true; // Environment #if defined(OFFICIAL_BUILD) - ledger::is_production = true; + isProduction = true; #else - ledger::is_production = false; + isProduction = false; #endif + SetProduction(isProduction); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); @@ -320,33 +348,19 @@ RewardsServiceImpl::RewardsServiceImpl(Profile* profile) } } - // Set up the rewards data source - content::URLDataSource::Add(profile_, - std::make_unique(profile_)); -} + bat_ledger_service_->Create(std::move(client_ptr_info), + MakeRequest(&bat_ledger_)); -RewardsServiceImpl::~RewardsServiceImpl() { - file_task_runner_->DeleteSoon(FROM_HERE, publisher_info_backend_.release()); - StopNotificationTimers(); -} - -void RewardsServiceImpl::Init() { - AddObserver(notification_service_.get()); -#if BUILDFLAG(ENABLE_EXTENSIONS) - AddObserver(extension_rewards_service_observer_.get()); - private_observers_.AddObserver(private_observer_.get()); -#endif - ledger_->Initialize(); + bat_ledger_->Initialize(); } -void RewardsServiceImpl::MaybeShowBackupNotification() { +void RewardsServiceImpl::MaybeShowBackupNotification(uint64_t boot_stamp) { 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::Time boot_timestamp = base::Time::FromDoubleT(boot_stamp); base::TimeDelta backup_notification_frequency = pref_service->GetTimeDelta(kRewardsBackupNotificationFrequency); base::TimeDelta backup_notification_interval = @@ -365,22 +379,23 @@ void RewardsServiceImpl::MaybeShowBackupNotification() { } } -void RewardsServiceImpl::MaybeShowAddFundsNotification() { +void RewardsServiceImpl::MaybeShowAddFundsNotification( + uint64_t reconcile_stamp) { // Show add funds notification if reconciliation will occur in the // next 3 days and balance is too low. base::Time now = base::Time::Now(); - if (ledger_->GetReconcileStamp() - now.ToDoubleT() < + if (reconcile_stamp - now.ToDoubleT() < 3 * base::Time::kHoursPerDay * base::Time::kSecondsPerHour) { - if (!HasSufficientBalanceToReconcile() && - ShouldShowNotificationAddFunds()) { - ShowNotificationAddFunds(); + if (ShouldShowNotificationAddFunds()) { + MaybeShowNotificationAddFunds(); } } } void RewardsServiceImpl::CreateWallet() { if (ready().is_signaled()) { - ledger_->CreateWallet(); + if (Connected()) + bat_ledger_->CreateWallet(); } else { ready().Post(FROM_HERE, base::Bind(&brave_rewards::RewardsService::CreateWallet, @@ -391,30 +406,55 @@ void RewardsServiceImpl::CreateWallet() { void RewardsServiceImpl::GetCurrentContributeList( uint32_t start, uint32_t limit, + uint64_t min_visit_time, + uint64_t reconcile_stamp, + bool allow_non_verified, const GetCurrentContributeListCallback& callback) { + if (!Connected()) { + return; + } + ledger::PublisherInfoFilter filter; filter.category = ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE; filter.month = ledger::PUBLISHER_MONTH::ANY; filter.year = -1; - filter.min_duration = ledger_->GetPublisherMinVisitTime(); + filter.min_duration = min_visit_time; filter.order_by.push_back(std::pair("ai.percent", false)); - filter.reconcile_stamp = ledger_->GetReconcileStamp(); + filter.reconcile_stamp = reconcile_stamp; filter.excluded = ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED; filter.percent = 1; - filter.non_verified = ledger_->GetPublisherAllowNonVerified(); + filter.non_verified = allow_non_verified; - ledger_->GetPublisherInfoList( - start, - limit, - filter, - std::bind(&GetContentSiteListInternal, + bat_ledger_->GetPublisherInfoList(start, limit, + filter.ToJson(), + base::BindOnce(&RewardsServiceImpl::OnGetPublisherInfoList, AsWeakPtr(), start, limit, - callback, _1, _2)); + callback)); +} + +void RewardsServiceImpl::OnGetPublisherInfoList( + uint32_t start, uint32_t limit, + const GetCurrentContributeListCallback& callback, + const std::vector& publisher_info_list, + uint32_t next_record) { + ledger::PublisherInfoList list; + + for (const auto& i : publisher_info_list) { + ledger::PublisherInfo info; + info.loadFromJson(i); + list.push_back(info); + } + + GetContentSiteListInternal(start, limit, callback, std::move(list), + next_record); } void RewardsServiceImpl::OnLoad(SessionID tab_id, const GURL& url) { + if (!Connected()) + return; + auto origin = url.GetOrigin(); const std::string baseDomain = GetDomainAndRegistry(origin.host(), INCLUDE_PRIVATE_REGISTRIES); @@ -435,36 +475,56 @@ void RewardsServiceImpl::OnLoad(SessionID tab_id, const GURL& url) { publisher_url, "", ""); - ledger_->OnLoad(data, GetCurrentTimestamp()); + bat_ledger_->OnLoad(data.ToJson(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnUnload(SessionID tab_id) { + if (!Connected()) + return; - ledger_->OnUnload(tab_id.id(), GetCurrentTimestamp()); + bat_ledger_->OnUnload(tab_id.id(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnShow(SessionID tab_id) { - ledger_->OnShow(tab_id.id(), GetCurrentTimestamp()); + if (!Connected()) + return; + + bat_ledger_->OnShow(tab_id.id(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnHide(SessionID tab_id) { - ledger_->OnHide(tab_id.id(), GetCurrentTimestamp()); + if (!Connected()) + return; + + bat_ledger_->OnHide(tab_id.id(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnForeground(SessionID tab_id) { - ledger_->OnForeground(tab_id.id(), GetCurrentTimestamp()); + if (!Connected()) + return; + + bat_ledger_->OnForeground(tab_id.id(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnBackground(SessionID tab_id) { - ledger_->OnBackground(tab_id.id(), GetCurrentTimestamp()); + if (!Connected()) + return; + + bat_ledger_->OnBackground(tab_id.id(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnMediaStart(SessionID tab_id) { - ledger_->OnMediaStart(tab_id.id(), GetCurrentTimestamp()); + if (!Connected()) + return; + + bat_ledger_->OnMediaStart(tab_id.id(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnMediaStop(SessionID tab_id) { - ledger_->OnMediaStop(tab_id.id(), GetCurrentTimestamp()); + if (!Connected()) + return; + + bat_ledger_->OnMediaStop(tab_id.id(), GetCurrentTimestamp()); } void RewardsServiceImpl::OnPostData(SessionID tab_id, @@ -472,6 +532,9 @@ void RewardsServiceImpl::OnPostData(SessionID tab_id, const GURL& first_party_url, const GURL& referrer, const std::string& post_data) { + if (!Connected()) + return; + std::string output; url::RawCanonOutputW<1024> canonOutput; url::DecodeURLEscapeSequences(post_data.c_str(), @@ -496,17 +559,20 @@ void RewardsServiceImpl::OnPostData(SessionID tab_id, "", ""); - ledger_->OnPostData(url.spec(), - first_party_url.spec(), - referrer.spec(), - output, - visit_data); + bat_ledger_->OnPostData(url.spec(), + first_party_url.spec(), + referrer.spec(), + output, + visit_data.ToJson()); } void RewardsServiceImpl::OnXHRLoad(SessionID tab_id, const GURL& url, const GURL& first_party_url, const GURL& referrer) { + if (!Connected()) + return; + std::map parts; for (net::QueryIterator it(url); !it.IsAtEnd(); it.Advance()) { @@ -518,12 +584,12 @@ void RewardsServiceImpl::OnXHRLoad(SessionID tab_id, GetPublisherMonth(now), GetPublisherYear(now), "", "", "", ""); - ledger_->OnXHRLoad(tab_id.id(), + bat_ledger_->OnXHRLoad(tab_id.id(), url.spec(), - parts, + mojo::MapToFlatMap(parts), first_party_url.spec(), referrer.spec(), - data); + data.ToJson()); } void RewardsServiceImpl::LoadMediaPublisherInfo( @@ -540,6 +606,9 @@ void RewardsServiceImpl::LoadMediaPublisherInfo( void RewardsServiceImpl::OnMediaPublisherInfoLoaded( ledger::PublisherInfoCallback callback, std::unique_ptr info) { + if (!Connected()) + return; + if (!info) { callback(ledger::Result::NOT_FOUND, std::move(info)); return; @@ -561,11 +630,17 @@ base::PostTaskAndReplyWithResult(file_task_runner_.get(), FROM_HERE, } void RewardsServiceImpl::ExcludePublisher(const std::string publisherKey) const { - ledger_->SetPublisherExclude(publisherKey, ledger::PUBLISHER_EXCLUDE::EXCLUDED); + if (!Connected()) + return; + + bat_ledger_->SetPublisherExclude(publisherKey, ledger::PUBLISHER_EXCLUDE::EXCLUDED); } void RewardsServiceImpl::RestorePublishers() { - ledger_->RestorePublishers(); + if (!Connected()) + return; + + bat_ledger_->RestorePublishers(); } void RewardsServiceImpl::OnMediaPublisherInfoSaved(bool success) { @@ -601,7 +676,7 @@ void RewardsServiceImpl::Shutdown() { } fetchers_.clear(); - ledger_.reset(); + bat_ledger_.reset(); RewardsService::Shutdown(); } @@ -612,7 +687,7 @@ void RewardsServiceImpl::OnWalletInitialized(ledger::Result result) { if (result == ledger::Result::WALLET_CREATED) { SetRewardsMainEnabled(true); SetAutoContribute(true); - StartNotificationTimers(); + StartNotificationTimers(true); result = ledger::Result::LEDGER_OK; } @@ -624,6 +699,34 @@ void RewardsServiceImpl::OnWalletProperties(ledger::Result result, TriggerOnWalletProperties(result, std::move(wallet_info)); } +void RewardsServiceImpl::OnGetAutoContributeProps( + const GetAutoContributePropsCallback& callback, + const std::string& json_props) { + ledger::AutoContributeProps props; + props.loadFromJson(json_props); + + auto auto_contri_props = + std::make_unique(); + auto_contri_props->enabled_contribute = props.enabled_contribute; + auto_contri_props->contribution_min_time = props.contribution_min_time; + auto_contri_props->contribution_min_visits = props.contribution_min_visits; + auto_contri_props->contribution_non_verified = + props.contribution_non_verified; + auto_contri_props->contribution_videos = props.contribution_videos; + auto_contri_props->reconcile_stamp = props.reconcile_stamp; + + callback.Run(std::move(auto_contri_props)); +} + +void RewardsServiceImpl::GetAutoContributeProps( + const GetAutoContributePropsCallback& callback) { + if (!Connected()) + return; + + bat_ledger_->GetAutoContributeProps(base::BindOnce( + &RewardsServiceImpl::OnGetAutoContributeProps, AsWeakPtr(), callback)); +} + void RewardsServiceImpl::OnGrant(ledger::Result result, const ledger::Grant& grant) { TriggerOnGrant(result, grant); @@ -644,10 +747,13 @@ void RewardsServiceImpl::OnGrantFinish(ledger::Result result, ledger::BalanceReportInfo report_info; auto now = base::Time::Now(); if (result == ledger::Result::LEDGER_OK) { - ledger_->SetBalanceReportItem(GetPublisherMonth(now), - GetPublisherYear(now), - ledger::ReportType::GRANT, - grant.probi); + if (!Connected()) + return; + + bat_ledger_->SetBalanceReportItem(GetPublisherMonth(now), + GetPublisherYear(now), + ledger::ReportType::GRANT, + grant.probi); } GetCurrentBalanceReport(); @@ -660,8 +766,11 @@ void RewardsServiceImpl::OnReconcileComplete(ledger::Result result, const std::string& probi) { if (result == ledger::Result::LEDGER_OK) { auto now = base::Time::Now(); + if (!Connected()) + return; + FetchWalletProperties(); - ledger_->OnReconcileCompleteSuccess(viewing_id, + bat_ledger_->OnReconcileCompleteSuccess(viewing_id, category, probi, GetPublisherMonth(now), @@ -690,12 +799,15 @@ void RewardsServiceImpl::LoadLedgerState( void RewardsServiceImpl::OnLedgerStateLoaded( ledger::LedgerCallbackHandler* handler, const std::string& data) { + if (!Connected()) + return; + handler->OnLedgerStateLoaded(data.empty() ? ledger::Result::LEDGER_ERROR : ledger::Result::LEDGER_OK, data); - if (ledger_->GetRewardsMainEnabled()) { - StartNotificationTimers(); - } + bat_ledger_->GetRewardsMainEnabled( + base::BindOnce(&RewardsServiceImpl::StartNotificationTimers, + AsWeakPtr())); } void RewardsServiceImpl::LoadPublisherState( @@ -710,6 +822,9 @@ void RewardsServiceImpl::LoadPublisherState( void RewardsServiceImpl::OnPublisherStateLoaded( ledger::LedgerCallbackHandler* handler, const std::string& data) { + if (!Connected()) + return; + handler->OnPublisherStateLoaded( data.empty() ? ledger::Result::NO_PUBLISHER_STATE : ledger::Result::LEDGER_OK, @@ -735,6 +850,9 @@ void RewardsServiceImpl::SaveLedgerState(const std::string& ledger_state, void RewardsServiceImpl::OnLedgerStateSaved( ledger::LedgerCallbackHandler* handler, bool success) { + if (!Connected()) + return; + handler->OnLedgerStateSaved(success ? ledger::Result::LEDGER_OK : ledger::Result::NO_LEDGER_STATE); } @@ -757,12 +875,18 @@ void RewardsServiceImpl::SavePublisherState(const std::string& publisher_state, void RewardsServiceImpl::OnPublisherStateSaved( ledger::LedgerCallbackHandler* handler, bool success) { + if (!Connected()) + return; + handler->OnPublisherStateSaved(success ? ledger::Result::LEDGER_OK : ledger::Result::LEDGER_ERROR); } void RewardsServiceImpl::LoadNicewareList( ledger::GetNicewareListCallback callback) { + if (!Connected()) + return; + std::string data = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_BRAVE_REWARDS_NICEWARE_LIST).as_string(); @@ -793,8 +917,10 @@ void RewardsServiceImpl::OnPublisherInfoSaved( ledger::PublisherInfoCallback callback, std::unique_ptr info, bool success) { - callback(success ? ledger::Result::LEDGER_OK - : ledger::Result::LEDGER_ERROR, std::move(info)); + if (Connected()) { + callback(success ? ledger::Result::LEDGER_OK + : ledger::Result::LEDGER_ERROR, std::move(info)); + } TriggerOnContentSiteUpdated(); } @@ -815,6 +941,10 @@ void RewardsServiceImpl::LoadPublisherInfo( void RewardsServiceImpl::OnPublisherInfoLoaded( ledger::PublisherInfoCallback callback, const ledger::PublisherInfoList list) { + if (!Connected()) { + return; + } + if (list.size() == 0) { callback(ledger::Result::NOT_FOUND, std::unique_ptr()); @@ -850,6 +980,10 @@ void RewardsServiceImpl::OnPublisherInfoListLoaded( uint32_t limit, ledger::PublisherInfoListCallback callback, const ledger::PublisherInfoList& list) { + if (!Connected()) { + return; + } + uint32_t next_record = 0; if (list.size() == limit) next_record = start + limit + 1; @@ -857,13 +991,13 @@ void RewardsServiceImpl::OnPublisherInfoListLoaded( callback(std::cref(list), next_record); } -std::unique_ptr RewardsServiceImpl::LoadURL( +void RewardsServiceImpl::LoadURL( const std::string& url, const std::vector& headers, const std::string& content, const std::string& contentType, const ledger::URL_METHOD& method, - ledger::LedgerCallbackHandler* handler) { + ledger::LoadURLCallback callback) { net::URLFetcher::RequestType request_type = URLMethodToRequestType(method); net::URLFetcher* fetcher = net::URLFetcher::Create( @@ -905,17 +1039,8 @@ std::unique_ptr RewardsServiceImpl::LoadURL( << "[ END REQUEST ]"; } - FetchCallback callback = base::Bind( - &ledger::LedgerCallbackHandler::OnURLRequestResponse, - base::Unretained(handler), - next_id, - url); fetchers_[fetcher] = callback; - - std::unique_ptr loader( - new LedgerURLLoaderImpl(next_id++, fetcher)); - - return loader; + fetcher->Start(); } void RewardsServiceImpl::OnURLFetchComplete( @@ -950,30 +1075,11 @@ void RewardsServiceImpl::OnURLFetchComplete( delete source; - callback.Run(response_code, body, headers); -} - -void RunIOTaskCallback( - base::WeakPtr rewards_service, - std::function callback) { - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&RewardsServiceImpl::OnIOTaskComplete, - rewards_service, - callback)); -} - -void RewardsServiceImpl::OnIOTaskComplete(std::function callback) { - callback(); -} - -void RewardsServiceImpl::RunIOTask( - std::unique_ptr task) { - ledger::LedgerTaskRunner::CallerThreadCallback callback = - std::bind(&RunIOTaskCallback, AsWeakPtr(), _1); + if (!Connected()) { + return; + } - file_task_runner_->PostTask(FROM_HERE, - base::BindOnce(&ledger::LedgerTaskRunner::Run, - std::move(task), std::move(callback))); + callback(response_code == 200, body, headers); } void RewardsServiceImpl::TriggerOnWalletInitialized(int error_code) { @@ -1017,7 +1123,11 @@ void RewardsServiceImpl::TriggerOnWalletProperties(int error_code, void RewardsServiceImpl::FetchWalletProperties() { if (ready().is_signaled()) { - ledger_->FetchWalletProperties(); + if (!Connected()) { + return; + } + + bat_ledger_->FetchWalletProperties(); } else { ready().Post(FROM_HERE, base::Bind(&brave_rewards::RewardsService::FetchWalletProperties, @@ -1027,7 +1137,11 @@ void RewardsServiceImpl::FetchWalletProperties() { void RewardsServiceImpl::FetchGrant(const std::string& lang, const std::string& payment_id) { - ledger_->FetchGrant(lang, payment_id); + if (!Connected()) { + return; + } + + bat_ledger_->FetchGrant(lang, payment_id); } void RewardsServiceImpl::TriggerOnGrant(ledger::Result result, @@ -1044,7 +1158,11 @@ void RewardsServiceImpl::TriggerOnGrant(ledger::Result result, } void RewardsServiceImpl::GetGrantCaptcha() { - ledger_->GetGrantCaptcha(); + if (!Connected()) { + return; + } + + bat_ledger_->GetGrantCaptcha(); } void RewardsServiceImpl::TriggerOnGrantCaptcha(const std::string& image, const std::string& hint) { @@ -1052,16 +1170,30 @@ void RewardsServiceImpl::TriggerOnGrantCaptcha(const std::string& image, const s observer.OnGrantCaptcha(this, image, hint); } -std::string RewardsServiceImpl::GetWalletPassphrase() const { - return ledger_->GetWalletPassphrase(); +void RewardsServiceImpl::GetWalletPassphrase( + const GetWalletPassphraseCallback& callback) { + if (!Connected()) { + return; + } + + bat_ledger_->GetWalletPassphrase(callback); } -unsigned int RewardsServiceImpl::GetNumExcludedSites() const { - return ledger_->GetNumExcludedSites(); +void RewardsServiceImpl::GetNumExcludedSites( + const GetNumExcludedSitesCallback& callback) { + if (!Connected()) { + return; + } + + bat_ledger_->GetNumExcludedSites(callback); } void RewardsServiceImpl::RecoverWallet(const std::string passPhrase) const { - return ledger_->RecoverWallet(passPhrase); + if (!Connected()) { + return; + } + + bat_ledger_->RecoverWallet(passPhrase); } void RewardsServiceImpl::TriggerOnRecoverWallet(ledger::Result result, @@ -1082,7 +1214,11 @@ void RewardsServiceImpl::TriggerOnRecoverWallet(ledger::Result result, } void RewardsServiceImpl::SolveGrantCaptcha(const std::string& solution) const { - return ledger_->SolveGrantCaptcha(solution); + if (!Connected()) { + return; + } + + bat_ledger_->SolveGrantCaptcha(solution); } void RewardsServiceImpl::TriggerOnGrantFinish(ledger::Result result, @@ -1098,74 +1234,141 @@ void RewardsServiceImpl::TriggerOnGrantFinish(ledger::Result result, observer.OnGrantFinish(this, result, properties); } -uint64_t RewardsServiceImpl::GetReconcileStamp() const { - return ledger_->GetReconcileStamp(); +void RewardsServiceImpl::GetReconcileStamp( + const GetReconcileStampCallback& callback) { + if (!Connected()) { + return; + } + + bat_ledger_->GetReconcileStamp(callback); +} + +void RewardsServiceImpl::OnGetAddresses(const GetAddressesCallback& callback, + const base::flat_map& addresses) { + callback.Run(mojo::FlatMapToMap(addresses)); } -std::map RewardsServiceImpl::GetAddresses() const { - std::map addresses; - addresses.emplace("BAT", ledger_->GetBATAddress()); - addresses.emplace("BTC", ledger_->GetBTCAddress()); - addresses.emplace("ETH", ledger_->GetETHAddress()); - addresses.emplace("LTC", ledger_->GetLTCAddress()); - return addresses; +void RewardsServiceImpl::GetAddresses(const GetAddressesCallback& callback) { + if (!Connected()) { + return; + } + + bat_ledger_->GetAddresses(base::BindOnce(&RewardsServiceImpl::OnGetAddresses, + AsWeakPtr(), callback)); } void RewardsServiceImpl::SetRewardsMainEnabled(bool enabled) const { - return ledger_->SetRewardsMainEnabled(enabled); + if (!Connected()) { + return; + } + + bat_ledger_->SetRewardsMainEnabled(enabled); } -uint64_t RewardsServiceImpl::GetPublisherMinVisitTime() const { - return ledger_->GetPublisherMinVisitTime(); +void RewardsServiceImpl::GetPublisherMinVisitTime( + const GetPublisherMinVisitTimeCallback& callback) { + if (!Connected()) { + return; + } + + bat_ledger_->GetPublisherMinVisitTime(callback); } void RewardsServiceImpl::SetPublisherMinVisitTime( uint64_t duration_in_seconds) const { - return ledger_->SetPublisherMinVisitTime(duration_in_seconds); + if (!Connected()) { + return; + } + + bat_ledger_->SetPublisherMinVisitTime(duration_in_seconds); } -unsigned int RewardsServiceImpl::GetPublisherMinVisits() const { - return ledger_->GetPublisherMinVisits(); +void RewardsServiceImpl::GetPublisherMinVisits( + const GetPublisherMinVisitsCallback& callback) { + if (!Connected()) { + return; + } + + bat_ledger_->GetPublisherMinVisits(callback); } void RewardsServiceImpl::SetPublisherMinVisits(unsigned int visits) const { - return ledger_->SetPublisherMinVisits(visits); + if (!Connected()) { + return; + } + + bat_ledger_->SetPublisherMinVisits(visits); } -bool RewardsServiceImpl::GetPublisherAllowNonVerified() const { - return ledger_->GetPublisherAllowNonVerified(); +void RewardsServiceImpl::GetPublisherAllowNonVerified( + const GetPublisherAllowNonVerifiedCallback& callback) { + if (!Connected()) { + return; + } + + bat_ledger_->GetPublisherAllowNonVerified(callback); } void RewardsServiceImpl::SetPublisherAllowNonVerified(bool allow) const { - return ledger_->SetPublisherAllowNonVerified(allow); + if (!Connected()) { + return; + } + + bat_ledger_->SetPublisherAllowNonVerified(allow); } -bool RewardsServiceImpl::GetPublisherAllowVideos() const { - return ledger_->GetPublisherAllowVideos(); +void RewardsServiceImpl::GetPublisherAllowVideos( + const GetPublisherAllowVideosCallback& callback) { + if (!Connected()) { + return; + } + + bat_ledger_->GetPublisherAllowVideos(callback); } void RewardsServiceImpl::SetPublisherAllowVideos(bool allow) const { - return ledger_->SetPublisherAllowVideos(allow); + if (!Connected()) { + return; + } + + bat_ledger_->SetPublisherAllowVideos(allow); } void RewardsServiceImpl::SetContributionAmount(double amount) const { - ledger_->SetUserChangedContribution(); - ledger_->SetContributionAmount(amount); + if (!Connected()) { + return; + } + + bat_ledger_->SetUserChangedContribution(); + bat_ledger_->SetContributionAmount(amount); } // TODO: remove me (and pure virtual definition) // see https://github.com/brave/brave-core/commit/c4ef62c954a64fca18ae83ff8ffd611137323420#diff-aa3505dbf36b5d03d8ba0751e0c99904R385 // and https://github.com/brave-intl/bat-native-ledger/commit/27f3ceb471d61c84052737ff201fe18cb9a6af32#diff-e303122e010480b2226895b9470891a3R135 void RewardsServiceImpl::SetUserChangedContribution() const { - ledger_->SetUserChangedContribution(); + if (!Connected()) { + return; + } + + bat_ledger_->SetUserChangedContribution(); } -bool RewardsServiceImpl::GetAutoContribute() const { - return ledger_->GetAutoContribute(); +void RewardsServiceImpl::GetAutoContribute( + const GetAutoContributeCallback& callback) { + if (!Connected()) { + return; + } + + bat_ledger_->GetAutoContribute(callback); } void RewardsServiceImpl::SetAutoContribute(bool enabled) const { - return ledger_->SetAutoContribute(enabled); + if (!Connected()) { + return; + } + + bat_ledger_->SetAutoContribute(enabled); } void RewardsServiceImpl::TriggerOnContentSiteUpdated() { @@ -1192,6 +1395,10 @@ void RewardsServiceImpl::SavePublishersList(const std::string& publishers_list, void RewardsServiceImpl::OnPublishersListSaved( ledger::LedgerCallbackHandler* handler, bool success) { + if (!Connected()) { + return; + } + handler->OnPublishersListSaved(success ? ledger::Result::LEDGER_OK : ledger::Result::LEDGER_ERROR); } @@ -1213,8 +1420,12 @@ void RewardsServiceImpl::SetTimer(uint64_t time_offset, } void RewardsServiceImpl::OnTimer(uint32_t timer_id) { - ledger_->OnTimer(timer_id); + if (!Connected()) { + return; + } + timers_.erase(timer_id); + bat_ledger_->OnTimer(timer_id); } void RewardsServiceImpl::LoadPublisherList( @@ -1229,14 +1440,25 @@ void RewardsServiceImpl::LoadPublisherList( void RewardsServiceImpl::OnPublisherListLoaded( ledger::LedgerCallbackHandler* handler, const std::string& data) { + if (!Connected()) { + return; + } + handler->OnPublisherListLoaded( data.empty() ? ledger::Result::NO_PUBLISHER_LIST : ledger::Result::LEDGER_OK, data); } -std::map RewardsServiceImpl::GetAllBalanceReports() { - std::map reports = ledger_->GetAllBalanceReports(); +void RewardsServiceImpl::OnGetAllBalanceReports( + const GetAllBalanceReportsCallback& callback, + const base::flat_map& json_reports) { + std::map reports; + for (auto const& report : json_reports) { + ledger::BalanceReportInfo info; + info.loadFromJson(report.second); + reports[report.first] = info; + } std::map newReports; for (auto const& report : reports) { @@ -1253,21 +1475,49 @@ std::map RewardsServiceImpl::GetAllBa newReports[report.first] = newReport; } - return newReports; + callback.Run(newReports); } -void RewardsServiceImpl::GetCurrentBalanceReport() { +void RewardsServiceImpl::GetAllBalanceReports( + const GetAllBalanceReportsCallback& callback) { + if (!Connected()) { + return; + } + + bat_ledger_->GetAllBalanceReports( + base::BindOnce(&RewardsServiceImpl::OnGetAllBalanceReports, + AsWeakPtr(), callback)); +} + +void RewardsServiceImpl::OnGetCurrentBalanceReport( + bool success, const std::string& json_report) { ledger::BalanceReportInfo report; - auto now = base::Time::Now(); - bool success = ledger_->GetBalanceReport(GetPublisherMonth(now), - GetPublisherYear(now), &report); + report.loadFromJson(json_report); + if (success) { TriggerOnGetCurrentBalanceReport(report); } } -bool RewardsServiceImpl::IsWalletCreated() { - return ledger_->IsWalletCreated(); +void RewardsServiceImpl::GetCurrentBalanceReport() { + auto now = base::Time::Now(); + if (!Connected()) { + return; + } + + bat_ledger_->GetBalanceReport(GetPublisherMonth(now), GetPublisherYear(now), + base::BindOnce(&RewardsServiceImpl::OnGetCurrentBalanceReport, + AsWeakPtr())); +} + +void RewardsServiceImpl::IsWalletCreated( + const IsWalletCreatedCallback& callback) { + if (!Connected()) { + callback.Run(false); + return; + } + + bat_ledger_->IsWalletCreated(callback); } void RewardsServiceImpl::GetPublisherActivityFromUrl(uint64_t windowId, @@ -1290,6 +1540,9 @@ void RewardsServiceImpl::GetPublisherActivityFromUrl(uint64_t windowId, return; } + if (!Connected()) + return; + ledger::VisitData visitData; visitData.domain = baseDomain; visitData.path = parsedUrl.PathForRequest(); @@ -1299,7 +1552,7 @@ void RewardsServiceImpl::GetPublisherActivityFromUrl(uint64_t windowId, visitData.url = origin.spec(); visitData.favicon_url = favicon_url; - ledger_->GetPublisherActivityFromUrl(windowId, visitData); + bat_ledger_->GetPublisherActivityFromUrl(windowId, visitData.ToJson()); } void RewardsServiceImpl::OnExcludedSitesChanged(const std::string& publisher_id) { @@ -1317,8 +1570,12 @@ void RewardsServiceImpl::OnPublisherActivity(ledger::Result result, TriggerOnGetPublisherActivityFromUrl(result, std::move(info), windowId); } -double RewardsServiceImpl::GetContributionAmount() { - return ledger_->GetContributionAmount(); +void RewardsServiceImpl::GetContributionAmount( + const GetContributionAmountCallback& callback) { + if (!Connected()) + return; + + bat_ledger_->GetContributionAmount(callback); } void RewardsServiceImpl::FetchFavIcon(const std::string& url, @@ -1403,12 +1660,29 @@ void RewardsServiceImpl::OnFetchFavIconCompleted(ledger::FetchIconCallback callb void RewardsServiceImpl::OnSetOnDemandFaviconComplete(const std::string& favicon_url, ledger::FetchIconCallback callback, bool success) { + if (!Connected()) + return; + callback(success, favicon_url); } void RewardsServiceImpl::GetPublisherBanner(const std::string& publisher_id) { - ledger_->GetPublisherBanner(publisher_id, - std::bind(&RewardsServiceImpl::OnPublisherBanner, this, _1)); + if (!Connected()) + return; + + bat_ledger_->GetPublisherBanner(publisher_id, + base::BindOnce(&RewardsServiceImpl::OnPublisherBannerMojoProxy, + AsWeakPtr())); +} + +void RewardsServiceImpl::OnPublisherBannerMojoProxy( + const std::string& banner) { + std::unique_ptr publisher_banner; + if (!banner.empty()) { + publisher_banner.reset(new ledger::PublisherBanner()); + publisher_banner->loadFromJson(banner); + } + OnPublisherBanner(std::move(publisher_banner)); } void RewardsServiceImpl::OnPublisherBanner(std::unique_ptr banner) { @@ -1452,12 +1726,15 @@ void RewardsServiceImpl::OnDonate(const std::string& publisher_key, int amount, return; } + if (!Connected()) + return; + ledger::PublisherInfo publisher( publisher_key, ledger::PUBLISHER_MONTH::ANY, -1); - ledger_->DoDirectDonation(publisher, amount, "BAT"); + bat_ledger_->DoDirectDonation(publisher.ToJson(), amount, "BAT"); } bool SaveContributionInfoOnFileTaskRunner(const brave_rewards::ContributionInfo info, @@ -1540,6 +1817,10 @@ ledger::PublisherInfoList GetRecurringDonationsOnFileTaskRunner(PublisherInfoDat void RewardsServiceImpl::OnRecurringDonationsData(const ledger::PublisherInfoListCallback callback, const ledger::PublisherInfoList list) { + if (!Connected()) { + return; + } + callback(list, 0); } @@ -1602,7 +1883,10 @@ void RewardsServiceImpl::OnTipsUpdatedData(const ledger::PublisherInfoList list) } void RewardsServiceImpl::RemoveRecurring(const std::string& publisher_key) { - ledger_->RemoveRecurring(publisher_key); + if (!Connected()) + return; + + bat_ledger_->RemoveRecurring(publisher_key); } void RewardsServiceImpl::TipsUpdated() { @@ -1623,7 +1907,11 @@ bool RemoveRecurringOnFileTaskRunner(const std::string publisher_key, PublisherI } void RewardsServiceImpl::OnRemovedRecurring(ledger::RecurringRemoveCallback callback, bool success) { - callback(success ? ledger::Result::LEDGER_OK : ledger::Result::LEDGER_ERROR); + if (Connected()) { + callback(success ? + ledger::Result::LEDGER_OK : ledger::Result::LEDGER_ERROR); + } + UpdateRecurringDonationsList(); } @@ -1661,9 +1949,12 @@ void RewardsServiceImpl::TriggerOnGetPublisherActivityFromUrl( windowId); } -void RewardsServiceImpl::SetContributionAutoInclude(std::string publisher_key, - bool excluded, uint64_t windowId) { - ledger_->SetPublisherPanelExclude(publisher_key, excluded ? +void RewardsServiceImpl::SetContributionAutoInclude( + const std::string& publisher_key, bool excluded, uint64_t windowId) { + if (!Connected()) + return; + + bat_ledger_->SetPublisherPanelExclude(publisher_key, excluded ? ledger::PUBLISHER_EXCLUDE::EXCLUDED : ledger::PUBLISHER_EXCLUDE::INCLUDED, windowId); } @@ -1672,7 +1963,9 @@ RewardsNotificationService* RewardsServiceImpl::GetNotificationService() const { return notification_service_.get(); } -void RewardsServiceImpl::StartNotificationTimers() { +void RewardsServiceImpl::StartNotificationTimers(bool main_enabled) { + if (!main_enabled) return; + // Startup timer, begins after 3-second delay. notification_startup_timer_ = std::make_unique(); notification_startup_timer_->Start( @@ -1697,12 +1990,21 @@ void RewardsServiceImpl::StopNotificationTimers() { } void RewardsServiceImpl::OnNotificationTimerFired() { - MaybeShowBackupNotification(); - MaybeShowAddFundsNotification(); + if (!Connected()) + return; + + bat_ledger_->GetBootStamp( + base::BindOnce(&RewardsServiceImpl::MaybeShowBackupNotification, + AsWeakPtr())); + GetReconcileStamp( + base::Bind(&RewardsServiceImpl::MaybeShowAddFundsNotification, + AsWeakPtr())); } -bool RewardsServiceImpl::HasSufficientBalanceToReconcile() const { - return (ledger_->GetBalance() >= ledger_->GetContributionAmount()); +void RewardsServiceImpl::MaybeShowNotificationAddFunds() { + bat_ledger_->HasSufficientBalanceToReconcile( + base::BindOnce(&RewardsServiceImpl::ShowNotificationAddFunds, + AsWeakPtr())); } bool RewardsServiceImpl::ShouldShowNotificationAddFunds() const { @@ -1711,7 +2013,9 @@ bool RewardsServiceImpl::ShouldShowNotificationAddFunds() const { return (next_time.is_null() || base::Time::Now() > next_time); } -void RewardsServiceImpl::ShowNotificationAddFunds() { +void RewardsServiceImpl::ShowNotificationAddFunds(bool sufficient) { + if (sufficient) return; + base::Time next_time = base::Time::Now() + base::TimeDelta::FromDays(3); profile_->GetPrefs()->SetTime(kRewardsAddFundsNotification, next_time); RewardsNotificationService::RewardsNotificationArgs args; @@ -1752,31 +2056,41 @@ void RewardsServiceImpl::HandleFlags(const std::string& options) { } if (name == "staging") { + bool is_production; std::string lower = base::ToLowerASCII(value); + if (lower == "true" || lower == "1") { - ledger::is_production = false; + is_production = false; } else { - ledger::is_production = true; + is_production = true; } + + SetProduction(is_production); continue; } if (name == "reconcile-interval") { int reconcile_int; bool success = base::StringToInt(value, &reconcile_int); + if (success && reconcile_int > 0) { - ledger::reconcile_time = reconcile_int; + SetReconcileTime(reconcile_int); } + continue; } if (name == "short-retries") { std::string lower = base::ToLowerASCII(value); + bool short_retries; + if (lower == "true" || lower == "1") { - ledger::short_retries = true; + short_retries = true; } else { - ledger::short_retries = false; + short_retries = false; } + + SetShortRetries(short_retries); } } } @@ -1820,9 +2134,46 @@ void RewardsServiceImpl::OnDonate( OnDonate(publisher_key, amount, recurring, &info); } -void RewardsServiceImpl::SetLedgerClient( - std::unique_ptr new_ledger) { - ledger_ = std::move(new_ledger); +bool RewardsServiceImpl::Connected() const { + return bat_ledger_.is_bound(); +} + +void RewardsServiceImpl::SetLedgerEnvForTesting() { + bat_ledger_service_->SetTesting(); + + // this is needed because we are using braveledger_bat_helper::buildURL + // directly in BraveRewardsBrowserTest + #if defined(OFFICIAL_BUILD) + ledger::is_production = true; + #else + ledger::is_production = false; + #endif +} + +void RewardsServiceImpl::GetProduction(const GetProductionCallback& callback) { + bat_ledger_service_->GetProduction(callback); +} + +void RewardsServiceImpl::GetReconcileTime( + const GetReconcileTimeCallback& callback) { + bat_ledger_service_->GetReconcileTime(callback); +} + +void RewardsServiceImpl::GetShortRetries( + const GetShortRetriesCallback& callback) { + bat_ledger_service_->GetShortRetries(callback); +} + +void RewardsServiceImpl::SetProduction(bool production) { + bat_ledger_service_->SetProduction(production); +} + +void RewardsServiceImpl::SetReconcileTime(int32_t time) { + bat_ledger_service_->SetReconcileTime(time); +} + +void RewardsServiceImpl::SetShortRetries(bool short_retries) { + bat_ledger_service_->SetShortRetries(short_retries); } } // namespace brave_rewards diff --git a/components/brave_rewards/browser/rewards_service_impl.h b/components/brave_rewards/browser/rewards_service_impl.h index 069810a55821..addfee321d98 100644 --- a/components/brave_rewards/browser/rewards_service_impl.h +++ b/components/brave_rewards/browser/rewards_service_impl.h @@ -16,11 +16,13 @@ #include "base/observer_list.h" #include "base/memory/weak_ptr.h" #include "bat/ledger/ledger_client.h" +#include "brave/components/services/bat_ledger/public/interfaces/bat_ledger.mojom.h" #include "brave/components/brave_rewards/browser/rewards_service.h" #include "chrome/browser/bitmap_fetcher/bitmap_fetcher_service.h" #include "content/public/browser/browser_thread.h" #include "extensions/buildflags/buildflags.h" #include "extensions/common/one_shot_event.h" +#include "mojo/public/cpp/bindings/associated_binding.h" #include "net/url_request/url_fetcher_delegate.h" #include "brave/components/brave_rewards/browser/balance_report.h" #include "brave/components/brave_rewards/browser/content_site.h" @@ -60,6 +62,10 @@ namespace brave_rewards { class PublisherInfoDatabase; class RewardsNotificationServiceImpl; +using GetProductionCallback = base::Callback; +using GetReconcileTimeCallback = base::Callback; +using GetShortRetriesCallback = base::Callback; + class RewardsServiceImpl : public RewardsService, public ledger::LedgerClient, public net::URLFetcherDelegate, @@ -72,17 +78,23 @@ class RewardsServiceImpl : public RewardsService, void Shutdown() override; void Init(); + void StartLedger(); void CreateWallet() override; void FetchWalletProperties() override; void FetchGrant(const std::string& lang, const std::string& paymentId) override; void GetGrantCaptcha() override; void SolveGrantCaptcha(const std::string& solution) const override; - std::string GetWalletPassphrase() const override; - unsigned int GetNumExcludedSites() const override; + void GetWalletPassphrase( + const GetWalletPassphraseCallback& callback) override; + void GetNumExcludedSites( + const GetNumExcludedSitesCallback& callback) override; void RecoverWallet(const std::string passPhrase) const override; void GetCurrentContributeList( uint32_t start, uint32_t limit, + uint64_t min_visit_time, + uint64_t reconcile_stamp, + bool allow_non_verified, const GetCurrentContributeListCallback& callback) override; void OnLoad(SessionID tab_id, const GURL& url) override; void OnUnload(SessionID tab_id) override; @@ -102,48 +114,60 @@ class RewardsServiceImpl : public RewardsService, const GURL& referrer, const std::string& post_data) override; std::string URIEncode(const std::string& value) override; - uint64_t GetReconcileStamp() const override; - std::map GetAddresses() const override; - bool GetAutoContribute() const override; - uint64_t GetPublisherMinVisitTime() const override; - unsigned int GetPublisherMinVisits() const override; - bool GetPublisherAllowNonVerified() const override; - bool GetPublisherAllowVideos() const override; + void GetReconcileStamp(const GetReconcileStampCallback& callback) override; + void GetAddresses(const GetAddressesCallback& callback) override; + void GetAutoContribute( + const GetAutoContributeCallback& callback) override; + void GetPublisherMinVisitTime( + const GetPublisherMinVisitTimeCallback& callback) override; + void GetPublisherMinVisits( + const GetPublisherMinVisitsCallback& callback) override; + void GetPublisherAllowNonVerified( + const GetPublisherAllowNonVerifiedCallback& callback) override; + void GetPublisherAllowVideos( + const GetPublisherAllowVideosCallback& callback) override; void LoadMediaPublisherInfo( const std::string& media_key, ledger::PublisherInfoCallback callback) override; void SaveMediaPublisherInfo(const std::string& media_key, const std::string& publisher_id) override; void ExcludePublisher(const std::string publisherKey) const override; void RestorePublishers() override; - std::map GetAllBalanceReports() override; + void GetAllBalanceReports( + const GetAllBalanceReportsCallback& callback) override; void GetCurrentBalanceReport() override; - bool IsWalletCreated() override; + void IsWalletCreated(const IsWalletCreatedCallback& callback) override; void GetPublisherActivityFromUrl(uint64_t windowId, const std::string& url, const std::string& favicon_url) override; - double GetContributionAmount() override; + void GetContributionAmount(const GetContributionAmountCallback& callback) override; void GetPublisherBanner(const std::string& publisher_id) override; void OnPublisherBanner(std::unique_ptr banner); void RemoveRecurring(const std::string& publisher_key) override; void UpdateRecurringDonationsList() override; void UpdateTipsList() override; void SetContributionAutoInclude( - std::string publisher_key, bool excluded, uint64_t windowId) override; + const 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 HandleFlags(const std::string& options); + void SetProduction(bool production); + void GetProduction(const GetProductionCallback& callback); + void SetReconcileTime(int32_t time); + void GetReconcileTime(const GetReconcileTimeCallback& callback); + void SetShortRetries(bool short_retries); + void GetShortRetries(const GetShortRetriesCallback& callback); + void OnWalletProperties(ledger::Result result, std::unique_ptr info) override; void OnDonate(const std::string& publisher_key, int amount, bool recurring, std::unique_ptr site) override; - void SetLedgerClient(std::unique_ptr new_ledger) override; + void GetAutoContributeProps( + const GetAutoContributePropsCallback& callback) override; - private: - friend void RunIOTaskCallback( - base::WeakPtr, - std::function); - typedef base::Callback& headers)> FetchCallback; + // Testing methods + void SetLedgerEnvForTesting(); + private: const extensions::OneShotEvent& ready() const { return ready_; } void OnLedgerStateSaved(ledger::LedgerCallbackHandler* handler, bool success); @@ -201,8 +225,8 @@ class RewardsServiceImpl : public RewardsService, ledger::Result result, std::unique_ptr info, uint64_t windowId); - void MaybeShowBackupNotification(); - void MaybeShowAddFundsNotification(); + void MaybeShowBackupNotification(uint64_t boot_stamp); + void MaybeShowAddFundsNotification(uint64_t reconcile_stamp); // ledger::LedgerClient std::string GenerateGUID() const override; @@ -239,14 +263,13 @@ class RewardsServiceImpl : public RewardsService, void SetTimer(uint64_t time_offset, uint32_t& timer_id) override; void LoadPublisherList(ledger::LedgerCallbackHandler* handler) override; - std::unique_ptr LoadURL(const std::string& url, + void LoadURL(const std::string& url, const std::vector& headers, const std::string& content, const std::string& contentType, const ledger::URL_METHOD& method, - ledger::LedgerCallbackHandler* handler) override; + ledger::LoadURLCallback callback) override; - void RunIOTask(std::unique_ptr task) override; void SetRewardsMainEnabled(bool enabled) const override; void SetPublisherMinVisitTime(uint64_t duration_in_seconds) const override; void SetPublisherMinVisits(unsigned int visits) const override; @@ -282,21 +305,44 @@ class RewardsServiceImpl : public RewardsService, int line, const ledger::LogLevel log_level) const override; - void OnIOTaskComplete(std::function callback); - // URLFetcherDelegate impl void OnURLFetchComplete(const net::URLFetcher* source) override; - void StartNotificationTimers(); + void StartNotificationTimers(bool main_enabled); void StopNotificationTimers(); void OnNotificationTimerFired(); - bool HasSufficientBalanceToReconcile() const; + void MaybeShowNotificationAddFunds(); bool ShouldShowNotificationAddFunds() const; - void ShowNotificationAddFunds(); + void ShowNotificationAddFunds(bool sufficient); + + // Mojo Proxy methods + void OnPublisherBannerMojoProxy(const std::string& banner); + void OnGetPublisherInfoList(uint32_t start, uint32_t limit, + const GetCurrentContributeListCallback& callback, + const std::vector& publisher_info_list, + uint32_t next_record); + void OnGetAllBalanceReports( + const GetAllBalanceReportsCallback& callback, + const base::flat_map& json_reports); + void OnGetCurrentBalanceReport( + bool success, const std::string& json_report); + void OnGetAddresses( + const GetAddressesCallback& callback, + const base::flat_map& addresses); + void OnGetAutoContributeProps( + const GetAutoContributePropsCallback& callback, + const std::string& json_props); + + bool Connected() const; + void ConnectionClosed(); Profile* profile_; // NOT OWNED - std::unique_ptr ledger_; + mojo::AssociatedBinding + bat_ledger_client_binding_; + bat_ledger::mojom::BatLedgerAssociatedPtr bat_ledger_; + bat_ledger::mojom::BatLedgerServicePtr bat_ledger_service_; + #if BUILDFLAG(ENABLE_EXTENSIONS) std::unique_ptr extension_rewards_service_observer_; @@ -314,7 +360,7 @@ class RewardsServiceImpl : public RewardsService, #endif extensions::OneShotEvent ready_; - std::map fetchers_; + std::map fetchers_; std::map> timers_; std::vector current_media_fetchers_; std::vector request_ids_; diff --git a/components/brave_rewards/browser/rewards_service_impl_unittest.cc b/components/brave_rewards/browser/rewards_service_impl_unittest.cc index 0edaa20b3585..dc47f2f3e6b7 100644 --- a/components/brave_rewards/browser/rewards_service_impl_unittest.cc +++ b/components/brave_rewards/browser/rewards_service_impl_unittest.cc @@ -14,7 +14,6 @@ #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -#include "url/gurl.h" // npm run test -- brave_unit_tests --filter=RewardsServiceTest.* @@ -55,7 +54,6 @@ class MockRewardsServiceObserver : public RewardsServiceObserver { void(RewardsService*, int, ledger::PublisherInfo*, uint64_t)); }; - class RewardsServiceTest : public testing::Test { public: RewardsServiceTest() {} @@ -67,15 +65,11 @@ class RewardsServiceTest : public testing::Test { profile_ = CreateBraveRewardsProfile(temp_dir_.GetPath()); ASSERT_TRUE(profile_.get() != NULL); rewards_service_ = static_cast( - RewardsServiceFactory::GetInstance()->GetForProfile(profile())); + RewardsServiceFactory::GetForProfile(profile())); ASSERT_TRUE(RewardsServiceFactory::GetInstance() != NULL); ASSERT_TRUE(rewards_service() != NULL); observer_.reset(new MockRewardsServiceObserver); rewards_service_->AddObserver(observer_.get()); - - auto ledger_client = std::make_unique(); - ledger_client_ = ledger_client.get(); - rewards_service()->SetLedgerClient(std::move(ledger_client)); } void TearDown() override { @@ -86,7 +80,6 @@ class RewardsServiceTest : public testing::Test { Profile* profile() { return profile_.get(); } RewardsServiceImpl* rewards_service() { return rewards_service_; } MockRewardsServiceObserver* observer() { return observer_.get(); } - MockLedgerClient* ledger_client() { return ledger_client_; } private: // Need this as a very first member to run tests in UI thread @@ -97,98 +90,12 @@ class RewardsServiceTest : public testing::Test { RewardsServiceImpl* rewards_service_; std::unique_ptr observer_; base::ScopedTempDir temp_dir_; - MockLedgerClient* ledger_client_; // not owned }; -TEST_F(RewardsServiceTest, HandleFlags) { - // Staging - true - ledger::is_production = true; - ASSERT_TRUE(ledger::is_production); - rewards_service()->HandleFlags("staging=true"); - ASSERT_FALSE(ledger::is_production); - - // Staging - 1 - ledger::is_production = true; - ASSERT_TRUE(ledger::is_production); - RewardsServiceImpl::HandleFlags("staging=1"); - ASSERT_FALSE(ledger::is_production); - - // Staging - false - ledger::is_production = true; - ASSERT_TRUE(ledger::is_production); - RewardsServiceImpl::HandleFlags("staging=false"); - ASSERT_TRUE(ledger::is_production); - - // Staging - random - ledger::is_production = true; - ASSERT_TRUE(ledger::is_production); - RewardsServiceImpl::HandleFlags("staging=werwe"); - ASSERT_TRUE(ledger::is_production); - - // Reconcile interval - positive number - ledger::reconcile_time = 0; - ASSERT_EQ(ledger::reconcile_time, 0); - RewardsServiceImpl::HandleFlags("reconcile-interval=10"); - ASSERT_EQ(ledger::reconcile_time, 10); - - // Reconcile interval - negative number - ledger::reconcile_time = 0; - ASSERT_EQ(ledger::reconcile_time, 0); - RewardsServiceImpl::HandleFlags("reconcile-interval=-1"); - ASSERT_EQ(ledger::reconcile_time, 0); - - // Reconcile interval - string - ledger::reconcile_time = 0; - ASSERT_EQ(ledger::reconcile_time, 0); - RewardsServiceImpl::HandleFlags("reconcile-interval=sdf"); - ASSERT_EQ(ledger::reconcile_time, 0); - - // Short retries - on - ledger::short_retries = false; - ASSERT_FALSE(ledger::short_retries); - RewardsServiceImpl::HandleFlags("short-retries=true"); - ASSERT_TRUE(ledger::short_retries); - - // Short retries - off - ledger::short_retries = true; - ASSERT_TRUE(ledger::short_retries); - RewardsServiceImpl::HandleFlags("short-retries=false"); - ASSERT_FALSE(ledger::short_retries); - - // Mixture of flags - ASSERT_FALSE(ledger::short_retries); - ASSERT_TRUE(ledger::is_production); - ASSERT_EQ(ledger::reconcile_time, 0); - RewardsServiceImpl::HandleFlags( - "staging=true,short-retries=true,reconcile-interval=10"); - ASSERT_TRUE(ledger::short_retries); - ASSERT_FALSE(ledger::is_production); - ASSERT_EQ(ledger::reconcile_time, 10); - - // Wrong input - ledger::short_retries = false; - ledger::reconcile_time = 0; - ledger::is_production = true; - ASSERT_FALSE(ledger::short_retries); - ASSERT_TRUE(ledger::is_production); - ASSERT_EQ(ledger::reconcile_time, 0); - RewardsServiceImpl::HandleFlags( - "staging=,shortretries=true,reconcile-interval"); - ASSERT_FALSE(ledger::short_retries); - ASSERT_TRUE(ledger::is_production); - ASSERT_EQ(ledger::reconcile_time, 0); -} - TEST_F(RewardsServiceTest, OnWalletProperties) { // We always need to call observer as we report errors back even when we have null pointer EXPECT_CALL(*observer(), OnWalletProperties(_, 1, _)).Times(1); rewards_service()->OnWalletProperties(ledger::Result::LEDGER_ERROR, nullptr); } -TEST_F(RewardsServiceTest, OnLoad) { - EXPECT_CALL(*ledger_client(), OnLoad(_, _)).Times(1); - rewards_service()->OnLoad(SessionID::FromSerializedValue(1), - GURL("https://brave.com")); -} - // add test for strange entries diff --git a/components/brave_rewards/browser/rewards_service_observer.h b/components/brave_rewards/browser/rewards_service_observer.h index aba4195d9461..30e824b34752 100644 --- a/components/brave_rewards/browser/rewards_service_observer.h +++ b/components/brave_rewards/browser/rewards_service_observer.h @@ -6,6 +6,7 @@ #define BRAVE_BROWSER_PAYMENTS_PAYMENTS_SERVICE_OBSERVER_H_ #include "base/observer_list_types.h" +#include "brave/components/brave_rewards/browser/balance_report.h" #include "brave/components/brave_rewards/browser/content_site.h" #include "brave/components/brave_rewards/browser/grant.h" #include "brave/components/brave_rewards/browser/publisher_banner.h" diff --git a/components/brave_rewards/browser/test_util.cc b/components/brave_rewards/browser/test_util.cc index 26bc1dfe4a06..37802de52878 100644 --- a/components/brave_rewards/browser/test_util.cc +++ b/components/brave_rewards/browser/test_util.cc @@ -17,10 +17,6 @@ namespace brave_rewards { -MockLedgerClient::MockLedgerClient() {} - -MockLedgerClient::~MockLedgerClient() {} - std::unique_ptr CreateBraveRewardsProfile(const base::FilePath& path) { // Bitmap fetcher service needed for rewards service BitmapFetcherServiceFactory::GetInstance(); diff --git a/components/brave_rewards/browser/test_util.h b/components/brave_rewards/browser/test_util.h index f3bd8c6ac3df..ecbd65934593 100644 --- a/components/brave_rewards/browser/test_util.h +++ b/components/brave_rewards/browser/test_util.h @@ -5,216 +5,15 @@ #ifndef BRAVE_COMPONENTS_BRAVE_REWARDS_BROWSER_TEST_UTIL_H_ #define BRAVE_COMPONENTS_BRAVE_REWARDS_BROWSER_TEST_UTIL_H_ -#include #include -#include -#include "bat/ledger/ledger.h" #include "base/files/file_path.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" class KeyedService; class Profile; namespace brave_rewards { -class MockLedgerClient : public ledger::Ledger { - public: - MockLedgerClient(); - ~MockLedgerClient() override; - - MOCK_METHOD2(OnLoad, void(const ledger::VisitData& visit_data, - const uint64_t& current_time)); - - MOCK_METHOD0(Initialize, void()); - - MOCK_METHOD0(CreateWallet, bool()); - - MOCK_METHOD1(MakePayment, void(const ledger::PaymentData& payment_data)); - - MOCK_METHOD2(AddRecurringPayment, void(const std::string& publisher_id, - const double& value)); - - MOCK_METHOD3(DoDirectDonation, void(const ledger::PublisherInfo& publisher, - const int amount, - const std::string& currency)); - - MOCK_METHOD2(OnUnload, void(uint32_t tab_id, const uint64_t& current_time)); - - MOCK_METHOD2(OnShow, void(uint32_t tab_id, const uint64_t& current_time)); - - MOCK_METHOD2(OnHide, void(uint32_t tab_id, const uint64_t& current_time)); - - MOCK_METHOD2(OnForeground, void(uint32_t tab_id, - const uint64_t& current_time)); - - MOCK_METHOD2(OnBackground, void(uint32_t tab_id, - const uint64_t& current_time)); - - MOCK_METHOD2(OnMediaStart, void(uint32_t tab_id, - const uint64_t& current_time)); - - MOCK_METHOD2(OnMediaStop, void(uint32_t tab_id, - const uint64_t& current_time)); - MOCK_METHOD6(OnXHRLoad, void( - uint32_t tab_id, - const std::string& url, - const std::map& parts, - const std::string& first_party_url, - const std::string& referrer, - const ledger::VisitData& visit_data)); - - MOCK_METHOD5(OnPostData, void( - const std::string& url, - const std::string& first_party_url, - const std::string& referrer, - const std::string& post_data, - const ledger::VisitData& visit_data)); - - MOCK_METHOD1(OnTimer, void(uint32_t timer_id)); - - MOCK_METHOD1(URIEncode, std::string(const std::string& value)); - - MOCK_METHOD2(SetPublisherInfo, - void(std::unique_ptr publisher_info, - ledger::PublisherInfoCallback callback)); - - MOCK_METHOD2(GetPublisherInfo, void(const ledger::PublisherInfoFilter& filter, - ledger::PublisherInfoCallback callback)); - - MOCK_METHOD2(SetMediaPublisherInfo, void(const std::string& media_key, - const std::string& publisher_id)); - - MOCK_METHOD2(GetMediaPublisherInfo, void( - const std::string& media_key, - ledger::PublisherInfoCallback callback)); - - MOCK_METHOD0(GetRecurringDonationPublisherInfo, - std::vector()); - - MOCK_METHOD4(GetPublisherInfoList, void( - uint32_t start, - uint32_t limit, - const ledger::PublisherInfoFilter& filter, - ledger::PublisherInfoListCallback callback)); - - MOCK_METHOD1(SetRewardsMainEnabled, void(bool enabled)); - - MOCK_METHOD1(SetPublisherMinVisitTime, void(uint64_t duration_in_seconds)); - - MOCK_METHOD1(SetPublisherMinVisits, void(unsigned int visits)); - - MOCK_METHOD1(SetPublisherAllowNonVerified, void(bool allow)); - - MOCK_METHOD1(SetPublisherAllowVideos, void(bool allow)); - - MOCK_METHOD1(SetContributionAmount, void(double amount)); - - MOCK_METHOD0(SetUserChangedContribution, void()); - - MOCK_METHOD1(SetAutoContribute, void(bool enabled)); - - MOCK_METHOD3(SetBalanceReport, void( - ledger::PUBLISHER_MONTH month, - int year, - const ledger::BalanceReportInfo& report_info)); - - MOCK_CONST_METHOD0(GetBATAddress, const std::string&()); - - MOCK_CONST_METHOD0(GetBTCAddress, const std::string&()); - - MOCK_CONST_METHOD0(GetETHAddress, const std::string&()); - - MOCK_CONST_METHOD0(GetLTCAddress, const std::string&()); - - MOCK_CONST_METHOD0(GetReconcileStamp, uint64_t()); - - MOCK_CONST_METHOD0(GetRewardsMainEnabled, bool()); - - MOCK_CONST_METHOD0(GetPublisherMinVisitTime, uint64_t()); - - MOCK_CONST_METHOD0(GetPublisherMinVisits, unsigned int()); - - MOCK_CONST_METHOD0(GetNumExcludedSites, unsigned int()); - - MOCK_CONST_METHOD0(GetPublisherAllowNonVerified, bool()); - - MOCK_CONST_METHOD0(GetPublisherAllowVideos, bool()); - - MOCK_CONST_METHOD0(GetContributionAmount, double()); - - MOCK_CONST_METHOD0(GetAutoContribute, bool()); - - MOCK_CONST_METHOD0(FetchWalletProperties, void()); - - MOCK_CONST_METHOD2(FetchGrant, void(const std::string& lang, - const std::string& paymentId)); - - MOCK_CONST_METHOD1(SolveGrantCaptcha, void(const std::string& solution)); - - MOCK_CONST_METHOD0(GetGrantCaptcha, void()); - - MOCK_CONST_METHOD0(GetWalletPassphrase, std::string()); - - MOCK_CONST_METHOD3(GetBalanceReport, bool( - ledger::PUBLISHER_MONTH month, - int year, - ledger::BalanceReportInfo* report_info)); - - MOCK_CONST_METHOD0(GetAllBalanceReports, - std::map()); - - MOCK_CONST_METHOD1(RecoverWallet, void(const std::string& passPhrase)); - - MOCK_METHOD4(SaveMediaVisit, void(const std::string& publisher_id, - const ledger::VisitData& visit_data, - const uint64_t& duration, - const uint64_t window_id)); - - MOCK_METHOD2(SetPublisherExclude, void( - const std::string& publisher_id, - const ledger::PUBLISHER_EXCLUDE& exclude)); - - MOCK_METHOD3(SetPublisherPanelExclude, void( - const std::string& publisher_id, - const ledger::PUBLISHER_EXCLUDE& exclude, - uint64_t windowId)); - - MOCK_METHOD0(RestorePublishers, void()); - - MOCK_CONST_METHOD0(IsWalletCreated, bool()); - - MOCK_METHOD2(GetPublisherActivityFromUrl, void( - uint64_t windowId, - const ledger::VisitData& visit_data)); - - MOCK_METHOD4(SetBalanceReportItem, void(ledger::PUBLISHER_MONTH month, - int year, - ledger::ReportType type, - const std::string& probi)); - - MOCK_METHOD2(GetPublisherBanner, void( - const std::string& publisher_id, - ledger::PublisherBannerCallback callback)); - - MOCK_METHOD0(GetBalance, double()); - - MOCK_METHOD6(OnReconcileCompleteSuccess, void( - const std::string& viewing_id, - const ledger::PUBLISHER_CATEGORY category, - const std::string& probi, - const ledger::PUBLISHER_MONTH month, - const int year, - const uint32_t date)); - - MOCK_METHOD1(RemoveRecurring, void(const std::string& publisher_key)); - - MOCK_METHOD0(GetDefaultContributionAmount, double()); - - MOCK_CONST_METHOD0(GetBootStamp, uint64_t()); -}; - std::unique_ptr CreateBraveRewardsProfile(const base::FilePath& path); } // namespace brave_rewards diff --git a/components/services/BUILD.gn b/components/services/BUILD.gn index 2941ff8bdde8..0543c6ba9877 100644 --- a/components/services/BUILD.gn +++ b/components/services/BUILD.gn @@ -11,6 +11,7 @@ service_manifest("brave_content_packaged_services_manifest_overlay") { packaged_services = [ "//brave/components/services/bat_ads:manifest", + "//brave/components/services/bat_ledger:manifest", ] if (!is_android) { diff --git a/components/services/bat_ledger/BUILD.gn b/components/services/bat_ledger/BUILD.gn new file mode 100644 index 000000000000..1f053e776574 --- /dev/null +++ b/components/services/bat_ledger/BUILD.gn @@ -0,0 +1,31 @@ +import("//services/service_manager/public/service_manifest.gni") + +static_library("lib") { + visibility = [ "//brave/utility" ] + + sources = [ + "bat_ledger_app.cc", + "bat_ledger_app.h", + "bat_ledger_client_mojo_proxy.cc", + "bat_ledger_client_mojo_proxy.h", + "bat_ledger_service_impl.cc", + "bat_ledger_service_impl.h", + "bat_ledger_impl.cc", + "bat_ledger_impl.h", + ] + + public_deps = [ + "//brave/components/services/bat_ledger/public/interfaces", + ] + + deps = [ + "//base", + "//brave/vendor/bat-native-ledger", + "//services/service_manager/public/cpp", + ] +} + +service_manifest("manifest") { + name = "bat_ledger" + source = "manifest.json" +} diff --git a/components/services/bat_ledger/bat_ledger_app.cc b/components/services/bat_ledger/bat_ledger_app.cc new file mode 100644 index 000000000000..699b2b78546a --- /dev/null +++ b/components/services/bat_ledger/bat_ledger_app.cc @@ -0,0 +1,48 @@ +/* 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/. */ + +#include "brave/components/services/bat_ledger/bat_ledger_app.h" + +#include "brave/components/services/bat_ledger/bat_ledger_service_impl.h" +#include "mojo/public/cpp/bindings/strong_binding.h" + +namespace bat_ledger { + +namespace { + +void OnBatLedgerServiceRequest( + service_manager::ServiceContextRefFactory* ref_factory, + bat_ledger::mojom::BatLedgerServiceRequest request) { + mojo::MakeStrongBinding( + std::make_unique(ref_factory->CreateRef()), + std::move(request)); +} + +} // namespace + +BatLedgerApp::BatLedgerApp() {} + +BatLedgerApp::~BatLedgerApp() {} + +// static +std::unique_ptr +BatLedgerApp::CreateService() { + return std::make_unique(); +} + +void BatLedgerApp::OnStart() { + ref_factory_.reset(new service_manager::ServiceContextRefFactory( + context()->CreateQuitClosure())); + registry_.AddInterface( + base::Bind(&OnBatLedgerServiceRequest, ref_factory_.get())); +} + +void BatLedgerApp::OnBindInterface( + const service_manager::BindSourceInfo& source_info, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle interface_pipe) { + registry_.BindInterface(interface_name, std::move(interface_pipe)); +} + +} // namespace bat_ledger diff --git a/components/services/bat_ledger/bat_ledger_app.h b/components/services/bat_ledger/bat_ledger_app.h new file mode 100644 index 000000000000..8d5490c9ca4a --- /dev/null +++ b/components/services/bat_ledger/bat_ledger_app.h @@ -0,0 +1,40 @@ +/* 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/. */ + +#ifndef BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_APP_H_ +#define BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_APP_H_ + +#include + +#include "services/service_manager/public/cpp/binder_registry.h" +#include "services/service_manager/public/cpp/service_context.h" +#include "services/service_manager/public/cpp/service_context_ref.h" + +namespace bat_ledger { + +class BatLedgerApp : public service_manager::Service { + public: + BatLedgerApp(); + ~BatLedgerApp() override; + + // Factory method for creating the service. + static std::unique_ptr CreateService(); + + // Lifescycle events that occur after the service has started to spinup. + void OnStart() override; + void OnBindInterface(const service_manager::BindSourceInfo& source_info, + const std::string& interface_name, + mojo::ScopedMessagePipeHandle interface_pipe) override; + + private: + // State needed to manage service lifecycle and lifecycle of bound clients. + std::unique_ptr ref_factory_; + service_manager::BinderRegistry registry_; + + DISALLOW_COPY_AND_ASSIGN(BatLedgerApp); +}; + +} // namespace rewards + +#endif // BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_APP_H_ diff --git a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc new file mode 100644 index 000000000000..abee7d060ea5 --- /dev/null +++ b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc @@ -0,0 +1,547 @@ +/* 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/. */ + +#include "brave/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h" + +#include "base/logging.h" +#include "mojo/public/cpp/bindings/map.h" + +namespace bat_ledger { + +namespace { + +int32_t ToMojomResult(ledger::Result result) { + return (int32_t)result; +} + +ledger::Result ToLedgerResult(int32_t result) { + return (ledger::Result)result; +} + +int32_t ToMojomPublisherCategory(ledger::PUBLISHER_CATEGORY category) { + return (int32_t)category; +} + +int32_t ToMojomMethod(ledger::URL_METHOD method) { + return (int32_t)method; +} + +class LogStreamImpl : public ledger::LogStream { + public: + LogStreamImpl(const char* file, + int line, + const ledger::LogLevel log_level) { + switch(log_level) { + case ledger::LogLevel::LOG_INFO: + log_message_ = std::make_unique(file, line, logging::LOG_INFO); + break; + case ledger::LogLevel::LOG_WARNING: + log_message_ = std::make_unique(file, line, logging::LOG_WARNING); + break; + case ledger::LogLevel::LOG_ERROR: + log_message_ = std::make_unique(file, line, logging::LOG_ERROR); + break; + default: + log_message_ = std::make_unique(file, line, logging::LOG_VERBOSE); + break; + } + } + + std::ostream& stream() override { + return log_message_->stream(); + } + + private: + std::unique_ptr log_message_; + DISALLOW_COPY_AND_ASSIGN(LogStreamImpl); +}; + +} // anonymous namespace + +BatLedgerClientMojoProxy::BatLedgerClientMojoProxy( + mojom::BatLedgerClientAssociatedPtrInfo client_info) { + bat_ledger_client_.Bind(std::move(client_info)); +} + +BatLedgerClientMojoProxy::~BatLedgerClientMojoProxy() { +} + +std::string BatLedgerClientMojoProxy::GenerateGUID() const { + if (!Connected()) + return ""; + + std::string guid; + bat_ledger_client_->GenerateGUID(&guid); + return guid; +} + +void OnLoadURL(const ledger::LoadURLCallback& callback, + bool success, const std::string& response, + const base::flat_map& headers) { + callback(success, response, mojo::FlatMapToMap(headers)); +} + +void BatLedgerClientMojoProxy::LoadURL( + const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::URL_METHOD& method, + ledger::LoadURLCallback callback) { + if (!Connected()) + return; + + bat_ledger_client_->LoadURL(url, headers, content, contentType, + ToMojomMethod(method), base::BindOnce(&OnLoadURL, std::move(callback))); +} + +void BatLedgerClientMojoProxy::OnWalletInitialized(ledger::Result result) { + if (!Connected()) + return; + + bat_ledger_client_->OnWalletInitialized(ToMojomResult(result)); +} + +void BatLedgerClientMojoProxy::OnWalletProperties(ledger::Result result, + std::unique_ptr info) { + if (!Connected()) + return; + + std::string json_info = info ? info->ToJson() : ""; + bat_ledger_client_->OnWalletProperties(ToMojomResult(result), json_info); +} + +void BatLedgerClientMojoProxy::OnGrant(ledger::Result result, + const ledger::Grant& grant) { + if (!Connected()) + return; + + bat_ledger_client_->OnGrant(ToMojomResult(result), grant.ToJson()); +} + +void BatLedgerClientMojoProxy::OnGrantCaptcha(const std::string& image, + const std::string& hint) { + if (!Connected()) + return; + + bat_ledger_client_->OnGrantCaptcha(image, hint); +} + +void BatLedgerClientMojoProxy::OnRecoverWallet(ledger::Result result, + double balance, const std::vector& grants) { + if (!Connected()) + return; + + std::vector grant_jsons; + for (auto const& grant : grants) { + grant_jsons.push_back(grant.ToJson()); + } + + bat_ledger_client_->OnRecoverWallet( + ToMojomResult(result), balance, grant_jsons); +} + +void BatLedgerClientMojoProxy::OnReconcileComplete(ledger::Result result, + const std::string& viewing_id, + ledger::PUBLISHER_CATEGORY category, + const std::string& probi) { + if (!Connected()) + return; + + bat_ledger_client_->OnReconcileComplete(ToMojomResult(result), viewing_id, + ToMojomPublisherCategory(category), probi); +} + +std::unique_ptr BatLedgerClientMojoProxy::Log( + const char* file, int line, ledger::LogLevel level) const { + // There's no need to proxy this + return std::make_unique(file, line, level); +} + +void BatLedgerClientMojoProxy::OnGrantFinish(ledger::Result result, + const ledger::Grant& grant) { + if (!Connected()) + return; + + bat_ledger_client_->OnGrantFinish(ToMojomResult(result), grant.ToJson()); +} + +void BatLedgerClientMojoProxy::OnLoadLedgerState(ledger::LedgerCallbackHandler* handler, + int32_t result, const std::string& data) { + handler->OnLedgerStateLoaded(ToLedgerResult(result), data); +} + +void BatLedgerClientMojoProxy::LoadLedgerState( + ledger::LedgerCallbackHandler* handler) { + if (!Connected()) { + handler->OnLedgerStateLoaded(ledger::Result::LEDGER_ERROR, ""); + return; + } + + bat_ledger_client_->LoadLedgerState( + base::BindOnce(&BatLedgerClientMojoProxy::OnLoadLedgerState, AsWeakPtr(), + base::Unretained(handler))); +} + +void BatLedgerClientMojoProxy::OnLoadPublisherState( + ledger::LedgerCallbackHandler* handler, + int32_t result, const std::string& data) { + handler->OnPublisherStateLoaded(ToLedgerResult(result), data); +} + +void BatLedgerClientMojoProxy::LoadPublisherState( + ledger::LedgerCallbackHandler* handler) { + if (!Connected()) { + handler->OnPublisherStateLoaded(ledger::Result::LEDGER_ERROR, ""); + return; + } + + bat_ledger_client_->LoadPublisherState( + base::BindOnce(&BatLedgerClientMojoProxy::OnLoadPublisherState, + AsWeakPtr(), base::Unretained(handler))); +} + +void BatLedgerClientMojoProxy::OnLoadPublisherList( + ledger::LedgerCallbackHandler* handler, + int32_t result, const std::string& data) { + handler->OnPublisherListLoaded(ToLedgerResult(result), data); +} + +void BatLedgerClientMojoProxy::LoadPublisherList( + ledger::LedgerCallbackHandler* handler) { + if (!Connected()) { + handler->OnPublisherListLoaded(ledger::Result::LEDGER_ERROR, ""); + return; + } + + bat_ledger_client_->LoadPublisherList( + base::BindOnce(&BatLedgerClientMojoProxy::OnLoadPublisherList, + AsWeakPtr(), base::Unretained(handler))); +} + +void BatLedgerClientMojoProxy::OnSaveLedgerState( + ledger::LedgerCallbackHandler* handler, + int32_t result) { + handler->OnLedgerStateSaved(ToLedgerResult(result)); +} + +void BatLedgerClientMojoProxy::SaveLedgerState( + const std::string& ledger_state, ledger::LedgerCallbackHandler* handler) { + if (!Connected()) { + handler->OnLedgerStateSaved(ledger::Result::LEDGER_ERROR); + return; + } + + bat_ledger_client_->SaveLedgerState(ledger_state, + base::BindOnce(&BatLedgerClientMojoProxy::OnSaveLedgerState, + AsWeakPtr(), base::Unretained(handler))); +} + +void BatLedgerClientMojoProxy::OnSavePublisherState( + ledger::LedgerCallbackHandler* handler, + int32_t result) { + handler->OnPublisherStateSaved(ToLedgerResult(result)); +} + +void BatLedgerClientMojoProxy::SavePublisherState( + const std::string& publisher_state, + ledger::LedgerCallbackHandler* handler) { + if (!Connected()) { + handler->OnPublisherStateSaved(ledger::Result::LEDGER_ERROR); + return; + } + + bat_ledger_client_->SavePublisherState(publisher_state, + base::BindOnce(&BatLedgerClientMojoProxy::OnSavePublisherState, + AsWeakPtr(), base::Unretained(handler))); +} + +void BatLedgerClientMojoProxy::OnSavePublishersList( + ledger::LedgerCallbackHandler* handler, + int32_t result) { + handler->OnPublishersListSaved(ToLedgerResult(result)); +} + +void BatLedgerClientMojoProxy::SavePublishersList( + const std::string& publishers_list, + ledger::LedgerCallbackHandler* handler) { + if (!Connected()) { + handler->OnPublishersListSaved(ledger::Result::LEDGER_ERROR); + return; + } + + bat_ledger_client_->SavePublishersList(publishers_list, + base::BindOnce(&BatLedgerClientMojoProxy::OnSavePublishersList, + AsWeakPtr(), base::Unretained(handler))); +} + +void OnSavePublisherInfo(const ledger::PublisherInfoCallback& callback, + int32_t result, const std::string& publisher_info) { + std::unique_ptr info; + if (!publisher_info.empty()) { + info.reset(new ledger::PublisherInfo()); + info->loadFromJson(publisher_info); + } + callback(ToLedgerResult(result), std::move(info)); +} + +void BatLedgerClientMojoProxy::SavePublisherInfo( + std::unique_ptr publisher_info, + ledger::PublisherInfoCallback callback) { + if (!Connected()) { + callback(ledger::Result::LEDGER_ERROR, + std::unique_ptr()); + return; + } + + std::string json_info = publisher_info ? publisher_info->ToJson() : ""; + bat_ledger_client_->SavePublisherInfo(json_info, + base::BindOnce(&OnSavePublisherInfo, std::move(callback))); +} + +void OnLoadPublisherInfo(const ledger::PublisherInfoCallback& callback, + int32_t result, const std::string& publisher_info) { + std::unique_ptr info; + if (!publisher_info.empty()) { + info.reset(new ledger::PublisherInfo()); + info->loadFromJson(publisher_info); + } + callback(ToLedgerResult(result), std::move(info)); +} + +void BatLedgerClientMojoProxy::LoadPublisherInfo( + ledger::PublisherInfoFilter filter, + ledger::PublisherInfoCallback callback) { + if (!Connected()) { + callback(ledger::Result::LEDGER_ERROR, + std::unique_ptr()); + return; + } + + bat_ledger_client_->LoadPublisherInfo(filter.ToJson(), + base::BindOnce(&OnLoadPublisherInfo, std::move(callback))); +} + +void OnLoadPublisherInfoList(const ledger::PublisherInfoListCallback& callback, + const std::vector& publisher_info_list, + uint32_t next_record) { + ledger::PublisherInfoList list; + + for (const auto& publisher_info : publisher_info_list) { + ledger::PublisherInfo info; + info.loadFromJson(publisher_info); + list.push_back(info); + } + + callback(list, next_record); +} + +void BatLedgerClientMojoProxy::LoadPublisherInfoList( + uint32_t start, + uint32_t limit, + ledger::PublisherInfoFilter filter, + ledger::PublisherInfoListCallback callback) { + if (!Connected()) { + callback(std::vector(), 0); + return; + } + + bat_ledger_client_->LoadPublisherInfoList(start, limit, filter.ToJson(), + base::BindOnce(&OnLoadPublisherInfoList, std::move(callback))); +} + +void OnLoadMediaPublisherInfo(const ledger::PublisherInfoCallback& callback, + int32_t result, const std::string& publisher_info) { + std::unique_ptr info; + if (!publisher_info.empty()) { + info.reset(new ledger::PublisherInfo()); + info->loadFromJson(publisher_info); + } + callback(ToLedgerResult(result), std::move(info)); +} + +void BatLedgerClientMojoProxy::LoadMediaPublisherInfo( + const std::string& media_key, + ledger::PublisherInfoCallback callback) { + if (!Connected()) { + callback(ledger::Result::LEDGER_ERROR, + std::unique_ptr()); + return; + } + + bat_ledger_client_->LoadMediaPublisherInfo(media_key, + base::BindOnce(&OnLoadMediaPublisherInfo, std::move(callback))); +} + +void BatLedgerClientMojoProxy::SetTimer(uint64_t time_offset, + uint32_t& timer_id) { + if (!Connected()) { + return; + } + + bat_ledger_client_->SetTimer(time_offset, &timer_id); // sync +} + +void BatLedgerClientMojoProxy::OnExcludedSitesChanged( + const std::string& publisher_id) { + if (!Connected()) { + return; + } + + bat_ledger_client_->OnExcludedSitesChanged(publisher_id); +} + +void BatLedgerClientMojoProxy::OnPublisherActivity(ledger::Result result, + std::unique_ptr info, + uint64_t windowId) { + if (!Connected()) { + return; + } + + std::string json_info = info ? info->ToJson() : ""; + bat_ledger_client_->OnPublisherActivity(ToMojomResult(result), + json_info, windowId); +} + +void OnFetchFavIcon(const ledger::FetchIconCallback& callback, + bool success, const std::string& favicon_url) { + callback(success, favicon_url); +} + +void BatLedgerClientMojoProxy::FetchFavIcon(const std::string& url, + const std::string& favicon_key, + ledger::FetchIconCallback callback) { + if (!Connected()) { + callback(false, ""); + return; + } + + bat_ledger_client_->FetchFavIcon(url, favicon_key, + base::BindOnce(&OnFetchFavIcon, std::move(callback))); +} + +void OnGetRecurringDonations(const ledger::PublisherInfoListCallback& callback, + const std::vector& publisher_info_list, + uint32_t next_record) { + ledger::PublisherInfoList list; + + for (const auto& publisher_info : publisher_info_list) { + ledger::PublisherInfo info; + info.loadFromJson(publisher_info); + list.push_back(info); + } + + callback(list, next_record); +} + +void BatLedgerClientMojoProxy::GetRecurringDonations( + ledger::PublisherInfoListCallback callback) { + if (!Connected()) { + callback(std::vector(), 0); + return; + } + + bat_ledger_client_->GetRecurringDonations( + base::BindOnce(&OnGetRecurringDonations, std::move(callback))); +} + +void OnLoadNicewareList(const ledger::GetNicewareListCallback& callback, + int32_t result, const std::string& data) { + callback(ToLedgerResult(result), data); +} + +void BatLedgerClientMojoProxy::LoadNicewareList( + ledger::GetNicewareListCallback callback) { + if (!Connected()) { + callback(ledger::Result::LEDGER_ERROR, ""); + return; + } + + bat_ledger_client_->LoadNicewareList( + base::BindOnce(&OnLoadNicewareList, std::move(callback))); +} + +void OnRecurringRemoved(const ledger::RecurringRemoveCallback& callback, + int32_t result) { + callback(ToLedgerResult(result)); +} + +void BatLedgerClientMojoProxy::OnRemoveRecurring( + const std::string& publisher_key, + ledger::RecurringRemoveCallback callback) { + if (!Connected()) { + callback(ledger::Result::LEDGER_ERROR); + return; + } + + bat_ledger_client_->OnRemoveRecurring(publisher_key, + base::BindOnce(&OnRecurringRemoved, std::move(callback))); +} + +void BatLedgerClientMojoProxy::SaveContributionInfo(const std::string& probi, + const int month, + const int year, + const uint32_t date, + const std::string& publisher_key, + const ledger::PUBLISHER_CATEGORY category) { + if (!Connected()) + return; + + bat_ledger_client_->SaveContributionInfo(probi, month, year, date, + publisher_key, ToMojomPublisherCategory(category)); +} + +void BatLedgerClientMojoProxy::SaveMediaPublisherInfo( + const std::string& media_key, const std::string& publisher_id) { + if (!Connected()) + return; + + bat_ledger_client_->SaveMediaPublisherInfo(media_key, publisher_id); +} + +void BatLedgerClientMojoProxy::FetchWalletProperties() { + if (!Connected()) + return; + + bat_ledger_client_->FetchWalletProperties(); +} + +void BatLedgerClientMojoProxy::FetchGrant(const std::string& lang, + const std::string& paymentId) { + if (!Connected()) + return; + + bat_ledger_client_->FetchGrant(lang, paymentId); +} + +void BatLedgerClientMojoProxy::GetGrantCaptcha() { + if (!Connected()) + return; + + bat_ledger_client_->GetGrantCaptcha(); +} + +std::string BatLedgerClientMojoProxy::URIEncode(const std::string& value) { + if (!Connected()) + return ""; + + std::string encoded_value; + bat_ledger_client_->URIEncode(value, &encoded_value); + return encoded_value; +} + +void BatLedgerClientMojoProxy::SetContributionAutoInclude( + const std::string& publisher_key, bool excluded, uint64_t windowId) { + if (!Connected()) + return; + + bat_ledger_client_->SetContributionAutoInclude( + publisher_key, excluded, windowId); +} + +bool BatLedgerClientMojoProxy::Connected() const { + return bat_ledger_client_.is_bound(); +} + +} // namespace bat_ledger diff --git a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h new file mode 100644 index 000000000000..631c3e706187 --- /dev/null +++ b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h @@ -0,0 +1,125 @@ +/* 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/. */ + +#ifndef BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_CLIENT_MOJO_PROXY_H_ +#define BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_CLIENT_MOJO_PROXY_H_ + +#include + +#include "base/memory/weak_ptr.h" +#include "bat/ledger/ledger_client.h" +#include "brave/components/services/bat_ledger/public/interfaces/bat_ledger.mojom.h" +#include "chrome/browser/bitmap_fetcher/bitmap_fetcher_service.h" + +class SkBitmap; + +namespace bat_ledger { + +class BatLedgerClientMojoProxy : public ledger::LedgerClient, + public base::SupportsWeakPtr { + public: + BatLedgerClientMojoProxy( + mojom::BatLedgerClientAssociatedPtrInfo client_info); + ~BatLedgerClientMojoProxy() override; + + std::string GenerateGUID() const override; + void OnWalletInitialized(ledger::Result result) override; + void OnWalletProperties(ledger::Result result, + std::unique_ptr info) override; + void OnGrant(ledger::Result result, const ledger::Grant& grant) override; + void OnGrantCaptcha(const std::string& image, const std::string& hint) override; + void OnRecoverWallet(ledger::Result result, + double balance, + const std::vector& grants) override; + void OnReconcileComplete(ledger::Result result, + const std::string& viewing_id, + ledger::PUBLISHER_CATEGORY category, + const std::string& probi) override; + void OnGrantFinish(ledger::Result result, + const ledger::Grant& grant) override; + void LoadLedgerState(ledger::LedgerCallbackHandler* handler) override; + void LoadPublisherState(ledger::LedgerCallbackHandler* handler) override; + void SaveLedgerState(const std::string& ledger_state, + ledger::LedgerCallbackHandler* handler) override; + void SavePublisherState(const std::string& publisher_state, + ledger::LedgerCallbackHandler* handler) override; + + void SavePublisherInfo(std::unique_ptr publisher_info, + ledger::PublisherInfoCallback callback) override; + void LoadPublisherInfo(ledger::PublisherInfoFilter filter, + ledger::PublisherInfoCallback callback) override; + void LoadPublisherInfoList( + uint32_t start, + uint32_t limit, + ledger::PublisherInfoFilter filter, + ledger::PublisherInfoListCallback callback) override; + void SavePublishersList(const std::string& publishers_list, + ledger::LedgerCallbackHandler* handler) override; + void SetTimer(uint64_t time_offset, uint32_t& timer_id) override; + void LoadPublisherList(ledger::LedgerCallbackHandler* handler) override; + + void LoadURL(const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + const ledger::URL_METHOD& method, + ledger::LoadURLCallback callback) override; + + void OnExcludedSitesChanged(const std::string& publisher_id) override; + void OnPublisherActivity(ledger::Result result, + std::unique_ptr info, + uint64_t windowId) override; + void FetchFavIcon(const std::string& url, + const std::string& favicon_key, + ledger::FetchIconCallback callback) override; + void SaveContributionInfo(const std::string& probi, + const int month, + const int year, + const uint32_t date, + const std::string& publisher_key, + const ledger::PUBLISHER_CATEGORY category) override; + void GetRecurringDonations(ledger::PublisherInfoListCallback callback) override; + std::unique_ptr Log(const char* file, int line, ledger::LogLevel level) const override; + void LoadMediaPublisherInfo( + const std::string& media_key, + ledger::PublisherInfoCallback callback) override; + void SaveMediaPublisherInfo(const std::string& media_key, const std::string& publisher_id) override; + + void FetchWalletProperties() override; + void FetchGrant(const std::string& lang, const std::string& paymentId) override; + void GetGrantCaptcha() override; + + std::string URIEncode(const std::string& value) override; + + void SetContributionAutoInclude(const std::string& publisher_key, + bool excluded, uint64_t windowId) override; + + private: + bool Connected() const; + + void LoadNicewareList(ledger::GetNicewareListCallback callback) override; + void OnRemoveRecurring(const std::string& publisher_key, + ledger::RecurringRemoveCallback callback) override; + + mojom::BatLedgerClientAssociatedPtr bat_ledger_client_; + + void OnLoadLedgerState(ledger::LedgerCallbackHandler* handler, + int32_t result, const std::string& data); + void OnLoadPublisherState(ledger::LedgerCallbackHandler* handler, + int32_t result, const std::string& data); + void OnLoadPublisherList(ledger::LedgerCallbackHandler* handler, + int32_t result, const std::string& data); + void OnSaveLedgerState(ledger::LedgerCallbackHandler* handler, + int32_t result); + void OnSavePublisherState(ledger::LedgerCallbackHandler* handler, + int32_t result); + void OnSavePublishersList(ledger::LedgerCallbackHandler* handler, + int32_t result); + + DISALLOW_COPY_AND_ASSIGN(BatLedgerClientMojoProxy); +}; + +} // namespace bat_ledger + +#endif // BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_CLIENT_MOJO_PROXY_H_ diff --git a/components/services/bat_ledger/bat_ledger_impl.cc b/components/services/bat_ledger/bat_ledger_impl.cc new file mode 100644 index 000000000000..5887b2e1839e --- /dev/null +++ b/components/services/bat_ledger/bat_ledger_impl.cc @@ -0,0 +1,363 @@ +/* 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/. */ + +#include "brave/components/services/bat_ledger/bat_ledger_impl.h" + +#include "base/containers/flat_map.h" +#include "brave/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h" +#include "mojo/public/cpp/bindings/map.h" + +using namespace std::placeholders; + +namespace bat_ledger { + +namespace { // TODO, move into a util class + +ledger::PUBLISHER_EXCLUDE ToLedgerPublisherExclude(int32_t exclude) { + return (ledger::PUBLISHER_EXCLUDE)exclude; +} + +ledger::PUBLISHER_MONTH ToLedgerPublisherMonth(int32_t month) { + return (ledger::PUBLISHER_MONTH)month; +} + +ledger::ReportType ToLedgerReportType(int32_t type) { + return (ledger::ReportType)type; +} + +ledger::PUBLISHER_CATEGORY ToLedgerPublisherCategory(int32_t category) { + return (ledger::PUBLISHER_CATEGORY)category; +} + +} // anonymous namespace + +BatLedgerImpl::BatLedgerImpl( + mojom::BatLedgerClientAssociatedPtrInfo client_info) + : bat_ledger_client_mojo_proxy_( + new BatLedgerClientMojoProxy(std::move(client_info))), + ledger_( + ledger::Ledger::CreateInstance(bat_ledger_client_mojo_proxy_.get())) { +} + +BatLedgerImpl::~BatLedgerImpl() { +} + +void BatLedgerImpl::Initialize() { + ledger_->Initialize(); +} + +void BatLedgerImpl::CreateWallet() { + ledger_->CreateWallet(); +} + +void BatLedgerImpl::FetchWalletProperties() { + ledger_->FetchWalletProperties(); +} + +void BatLedgerImpl::GetAutoContributeProps( + GetAutoContributePropsCallback callback) { + ledger::AutoContributeProps props; + ledger_->GetAutoContributeProps(props); + std::move(callback).Run(props.ToJson()); +} + +void BatLedgerImpl::GetPublisherMinVisitTime( + GetPublisherMinVisitTimeCallback callback) { + std::move(callback).Run(ledger_->GetPublisherMinVisitTime()); +} + +void BatLedgerImpl::GetPublisherMinVisits( + GetPublisherMinVisitsCallback callback) { + std::move(callback).Run(ledger_->GetPublisherMinVisits()); +} + +void BatLedgerImpl::GetPublisherAllowNonVerified( + GetPublisherAllowNonVerifiedCallback callback) { + std::move(callback).Run(ledger_->GetPublisherAllowNonVerified()); +} + +void BatLedgerImpl::GetPublisherAllowVideos( + GetPublisherAllowVideosCallback callback) { + std::move(callback).Run(ledger_->GetPublisherAllowVideos()); +} + +void BatLedgerImpl::GetAutoContribute( + GetAutoContributeCallback callback) { + std::move(callback).Run(ledger_->GetAutoContribute()); +} + +void BatLedgerImpl::GetReconcileStamp(GetReconcileStampCallback callback) { + std::move(callback).Run(ledger_->GetReconcileStamp()); +} + +void BatLedgerImpl::OnLoad(const std::string& visit_data, + uint64_t current_time) { + ledger::VisitData visitData; + if (visitData.loadFromJson(visit_data)) + ledger_->OnLoad(visitData, current_time); +} + +void BatLedgerImpl::OnUnload(uint32_t tab_id, uint64_t current_time) { + ledger_->OnUnload(tab_id, current_time); +} + +void BatLedgerImpl::OnShow(uint32_t tab_id, uint64_t current_time) { + ledger_->OnShow(tab_id, current_time); +} + +void BatLedgerImpl::OnHide(uint32_t tab_id, uint64_t current_time) { + ledger_->OnHide(tab_id, current_time); +} + +void BatLedgerImpl::OnForeground(uint32_t tab_id, uint64_t current_time) { + ledger_->OnForeground(tab_id, current_time); +} + +void BatLedgerImpl::OnBackground(uint32_t tab_id, uint64_t current_time) { + ledger_->OnBackground(tab_id, current_time); +} + +void BatLedgerImpl::OnMediaStart(uint32_t tab_id, uint64_t current_time) { + ledger_->OnMediaStart(tab_id, current_time); +} + +void BatLedgerImpl::OnMediaStop(uint32_t tab_id, uint64_t current_time) { + ledger_->OnMediaStop(tab_id, current_time); +} + +void BatLedgerImpl::OnPostData(const std::string& url, + const std::string& first_party_url, const std::string& referrer, + const std::string& post_data, const std::string& visit_data) { + ledger::VisitData visitData; + if (visitData.loadFromJson(visit_data)) + ledger_->OnPostData(url, first_party_url, referrer, post_data, visitData); +} + +void BatLedgerImpl::OnXHRLoad(uint32_t tab_id, const std::string& url, + const base::flat_map& parts, + const std::string& first_party_url, const std::string& referrer, + const std::string& visit_data) { + ledger::VisitData visitData; + if (visitData.loadFromJson(visit_data)) + ledger_->OnXHRLoad(tab_id, url, mojo::FlatMapToMap(parts), + first_party_url, referrer, visitData); +} + +void BatLedgerImpl::SetPublisherExclude(const std::string& publisher_key, + int32_t exclude) { + ledger_->SetPublisherExclude(publisher_key, + ToLedgerPublisherExclude(exclude)); +} + +void BatLedgerImpl::RestorePublishers() { + ledger_->RestorePublishers(); +} + +void BatLedgerImpl::SetBalanceReportItem(int32_t month, + int32_t year, int32_t type, const std::string& probi) { + ledger_->SetBalanceReportItem( + ToLedgerPublisherMonth(month), year, ToLedgerReportType(type), probi); +} + +void BatLedgerImpl::OnReconcileCompleteSuccess(const std::string& viewing_id, + int32_t category, const std::string& probi, int32_t month, + int32_t year, uint32_t data) { + ledger_->OnReconcileCompleteSuccess(viewing_id, + ToLedgerPublisherCategory(category), probi, + ToLedgerPublisherMonth(month), year, data); +} + +void BatLedgerImpl::FetchGrant(const std::string& lang, + const std::string& payment_id) { + ledger_->FetchGrant(lang, payment_id); +} + +void BatLedgerImpl::GetGrantCaptcha() { + ledger_->GetGrantCaptcha(); +} + +void BatLedgerImpl::GetWalletPassphrase(GetWalletPassphraseCallback callback) { + std::move(callback).Run(ledger_->GetWalletPassphrase()); +} + +void BatLedgerImpl::GetNumExcludedSites(GetNumExcludedSitesCallback callback) { + std::move(callback).Run(ledger_->GetNumExcludedSites()); +} + +void BatLedgerImpl::RecoverWallet(const std::string& passPhrase) { + ledger_->RecoverWallet(passPhrase); +} + +void BatLedgerImpl::SolveGrantCaptcha(const std::string& solution) { + ledger_->SolveGrantCaptcha(solution); +} + +void BatLedgerImpl::GetAddresses(GetAddressesCallback callback) { + std::move(callback).Run(mojo::MapToFlatMap(ledger_->GetAddresses())); +} + +void BatLedgerImpl::GetBATAddress(GetBATAddressCallback callback) { + std::move(callback).Run(ledger_->GetBATAddress()); +} + +void BatLedgerImpl::GetBTCAddress(GetBTCAddressCallback callback) { + std::move(callback).Run(ledger_->GetBTCAddress()); +} + +void BatLedgerImpl::GetETHAddress(GetETHAddressCallback callback) { + std::move(callback).Run(ledger_->GetETHAddress()); +} + +void BatLedgerImpl::GetLTCAddress(GetLTCAddressCallback callback) { + std::move(callback).Run(ledger_->GetLTCAddress()); +} + +void BatLedgerImpl::SetRewardsMainEnabled(bool enabled) { + ledger_->SetRewardsMainEnabled(enabled); +} + +void BatLedgerImpl::SetPublisherMinVisitTime(uint64_t duration_in_seconds) { + ledger_->SetPublisherMinVisitTime(duration_in_seconds); +} + +void BatLedgerImpl::SetPublisherMinVisits(uint32_t visits) { + ledger_->SetPublisherMinVisits(visits); +} + +void BatLedgerImpl::SetPublisherAllowNonVerified(bool allow) { + ledger_->SetPublisherAllowNonVerified(allow); +} + +void BatLedgerImpl::SetPublisherAllowVideos(bool allow) { + ledger_->SetPublisherAllowVideos(allow); +} + +void BatLedgerImpl::SetUserChangedContribution() { + ledger_->SetUserChangedContribution(); +} + +void BatLedgerImpl::SetContributionAmount(double amount) { + ledger_->SetContributionAmount(amount); +} + +void BatLedgerImpl::SetAutoContribute(bool enabled) { + ledger_->SetAutoContribute(enabled); +} + +void BatLedgerImpl::OnTimer(uint32_t timer_id) { + ledger_->OnTimer(timer_id); +} + +void BatLedgerImpl::GetAllBalanceReports( + GetAllBalanceReportsCallback callback) { + auto reports = ledger_->GetAllBalanceReports(); + base::flat_map out_reports; + for (auto const& report : reports) { + out_reports[report.first] = report.second.ToJson(); + } + std::move(callback).Run(out_reports); +} + +void BatLedgerImpl::GetBalanceReport(int32_t month, int32_t year, + GetBalanceReportCallback callback) { + ledger::BalanceReportInfo info; + bool result = + ledger_->GetBalanceReport(ToLedgerPublisherMonth(month), year, &info); + std::move(callback).Run(result, info.ToJson()); +} + +void BatLedgerImpl::IsWalletCreated(IsWalletCreatedCallback callback) { + std::move(callback).Run(ledger_->IsWalletCreated()); +} + +void BatLedgerImpl::GetPublisherActivityFromUrl(uint64_t window_id, + const std::string& visit_data) { + ledger::VisitData visitData; + if (visitData.loadFromJson(visit_data)) + ledger_->GetPublisherActivityFromUrl(window_id, visitData); +} + +// static +void BatLedgerImpl::OnGetPublisherBanner( + CallbackHolder* holder, + std::unique_ptr banner) { + std::string json_banner = banner.get() ? banner->ToJson() : ""; + if (holder->is_valid()) + std::move(holder->get()).Run(json_banner); + delete holder; +} + +void BatLedgerImpl::GetPublisherBanner(const std::string& publisher_id, + GetPublisherBannerCallback callback) { + // delete in OnGetPublisherBanner + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_->GetPublisherBanner(publisher_id, + std::bind(BatLedgerImpl::OnGetPublisherBanner, holder, _1)); +} + +// static +void BatLedgerImpl::OnGetPublisherInfoList( + CallbackHolder* holder, + const ledger::PublisherInfoList& list, + uint32_t next_record) { + std::vector publisher_info_list; + for (const auto& info : list) { + publisher_info_list.push_back(info.ToJson()); + } + + if (holder->is_valid()) + std::move(holder->get()).Run(publisher_info_list, next_record); + delete holder; +} + +void BatLedgerImpl::GetPublisherInfoList(uint32_t start, uint32_t limit, + const std::string& filter, + GetPublisherInfoListCallback callback) { + // delete in OnGetPublisherInfoList + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger::PublisherInfoFilter publisher_info_filter; + publisher_info_filter.loadFromJson(filter); + ledger_->GetPublisherInfoList(start, limit, publisher_info_filter, + std::bind(BatLedgerImpl::OnGetPublisherInfoList, holder, _1, _2)); +} + +void BatLedgerImpl::GetContributionAmount( + GetContributionAmountCallback callback) { + std::move(callback).Run(ledger_->GetContributionAmount()); +} + +void BatLedgerImpl::DoDirectDonation(const std::string& publisher_info, + int32_t amount, const std::string& currency) { + ledger::PublisherInfo info; + if (info.loadFromJson(publisher_info)) + ledger_->DoDirectDonation(info, amount, currency); +} + +void BatLedgerImpl::RemoveRecurring(const std::string& publisher_key) { + ledger_->RemoveRecurring(publisher_key); +} + +void BatLedgerImpl::SetPublisherPanelExclude(const std::string& publisher_key, + int32_t exclude, uint64_t window_id) { + ledger_->SetPublisherPanelExclude(publisher_key, + ToLedgerPublisherExclude(exclude), window_id); +} + +void BatLedgerImpl::GetBootStamp(GetBootStampCallback callback) { + std::move(callback).Run(ledger_->GetBootStamp()); +} + +void BatLedgerImpl::GetRewardsMainEnabled( + GetRewardsMainEnabledCallback callback) { + std::move(callback).Run(ledger_->GetRewardsMainEnabled()); +} + +void BatLedgerImpl::HasSufficientBalanceToReconcile( + HasSufficientBalanceToReconcileCallback callback) { + std::move(callback).Run(ledger_->HasSufficientBalanceToReconcile()); +} + +} // namespace bat_ledger diff --git a/components/services/bat_ledger/bat_ledger_impl.h b/components/services/bat_ledger/bat_ledger_impl.h new file mode 100644 index 000000000000..8d88c568bc01 --- /dev/null +++ b/components/services/bat_ledger/bat_ledger_impl.h @@ -0,0 +1,160 @@ +/* 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/. */ + +#ifndef BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_IMPL_H_ +#define BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_IMPL_H_ + +#include + +#include "base/memory/weak_ptr.h" +#include "bat/ledger/ledger.h" +#include "brave/components/services/bat_ledger/public/interfaces/bat_ledger.mojom.h" + +namespace bat_ledger { + +class BatLedgerClientMojoProxy; + +class BatLedgerImpl : public mojom::BatLedger, + public base::SupportsWeakPtr { + public: + explicit BatLedgerImpl( + mojom::BatLedgerClientAssociatedPtrInfo client_info); + ~BatLedgerImpl() override; + + // bat_ledger::mojom::BatLedger + void Initialize() override; + void CreateWallet() override; + void FetchWalletProperties() override; + + void GetAutoContributeProps( + GetAutoContributePropsCallback callback) override; + void GetPublisherMinVisitTime( + GetPublisherMinVisitTimeCallback callback) override; + void GetPublisherMinVisits( + GetPublisherMinVisitsCallback callback) override; + void GetPublisherAllowNonVerified( + GetPublisherAllowNonVerifiedCallback callback) override; + void GetPublisherAllowVideos( + GetPublisherAllowVideosCallback callback) override; + void GetAutoContribute(GetAutoContributeCallback callback) override; + void GetReconcileStamp(GetReconcileStampCallback callback) override; + + void OnLoad(const std::string& visit_data, uint64_t current_time) override; + void OnUnload(uint32_t tab_id, uint64_t current_time) override; + void OnShow(uint32_t tab_id, uint64_t current_time) override; + void OnHide(uint32_t tab_id, uint64_t current_time) override; + void OnForeground(uint32_t tab_id, uint64_t current_time) override; + void OnBackground(uint32_t tab_id, uint64_t current_time) override; + void OnMediaStart(uint32_t tab_id, uint64_t current_time) override; + void OnMediaStop(uint32_t tab_id, uint64_t current_time) override; + + void OnPostData(const std::string& url, + const std::string& first_party_url, const std::string& referrer, + const std::string& post_data, const std::string& visit_data) override; + void OnXHRLoad(uint32_t tab_id, const std::string& url, + const base::flat_map& parts, + const std::string& first_party_url, const std::string& referrer, + const std::string& visit_data) override; + + void SetPublisherExclude(const std::string& publisher_key, + int32_t exclude) override; + void RestorePublishers() override; + + void SetBalanceReportItem( + int32_t month, int32_t year, int32_t type, + const std::string& probi) override; + void OnReconcileCompleteSuccess(const std::string& viewing_id, + int32_t category, const std::string& probi, int32_t month, + int32_t year, uint32_t data) override; + + void FetchGrant( + const std::string& lang, const std::string& payment_id) override; + void GetGrantCaptcha() override; + void GetWalletPassphrase(GetWalletPassphraseCallback callback) override; + void GetNumExcludedSites(GetNumExcludedSitesCallback callback) override; + void RecoverWallet(const std::string& passPhrase) override; + void SolveGrantCaptcha(const std::string& solution) override; + + void GetAddresses(GetAddressesCallback callback) override; + void GetBATAddress(GetBATAddressCallback callback) override; + void GetBTCAddress(GetBTCAddressCallback callback) override; + void GetETHAddress(GetETHAddressCallback callback) override; + void GetLTCAddress(GetLTCAddressCallback callback) override; + + void SetRewardsMainEnabled(bool enabled) override; + void SetPublisherMinVisitTime(uint64_t duration_in_seconds) override; + void SetPublisherMinVisits(uint32_t visits) override; + void SetPublisherAllowNonVerified(bool allow) override; + void SetPublisherAllowVideos(bool allow) override; + void SetUserChangedContribution() override; + void SetContributionAmount(double amount) override; + void SetAutoContribute(bool enabled) override; + + void OnTimer(uint32_t timer_id) override; + + void GetAllBalanceReports(GetAllBalanceReportsCallback callback) override; + void GetBalanceReport(int32_t month, int32_t year, + GetBalanceReportCallback callback) override; + + void IsWalletCreated(IsWalletCreatedCallback callback) override; + + void GetPublisherActivityFromUrl(uint64_t window_id, + const std::string& visit_data) override; + + void GetContributionAmount( + GetContributionAmountCallback callback) override; + void GetPublisherBanner(const std::string& publisher_id, + GetPublisherBannerCallback callback) override; + void GetPublisherInfoList(uint32_t start, uint32_t limit, + const std::string& filter, + GetPublisherInfoListCallback callback) override; + + void DoDirectDonation(const std::string& publisher_info, int32_t amount, + const std::string& currency) override; + + void RemoveRecurring(const std::string& publisher_key) override; + void SetPublisherPanelExclude(const std::string& publisher_key, + int32_t exclude, uint64_t window_id) override; + void GetBootStamp(GetBootStampCallback callback) override; + void GetRewardsMainEnabled( + GetRewardsMainEnabledCallback callback) override; + void HasSufficientBalanceToReconcile( + HasSufficientBalanceToReconcileCallback callback) override; + + private: + // workaround to pass base::OnceCallback into std::bind + template + class CallbackHolder { + public: + CallbackHolder(base::WeakPtr client, + Callback callback) + : client_(client), + callback_(std::move(callback)) {} + ~CallbackHolder() = default; + bool is_valid() { return !!client_.get(); } + Callback& get() { return callback_; } + + private: + base::WeakPtr client_; + Callback callback_; + }; + + static void OnGetPublisherBanner( + CallbackHolder* holder, + std::unique_ptr banner); + + static void OnGetPublisherInfoList( + CallbackHolder* holder, + const ledger::PublisherInfoList& list, + uint32_t next_record); + + std::unique_ptr bat_ledger_client_mojo_proxy_; + std::unique_ptr ledger_; + + DISALLOW_COPY_AND_ASSIGN(BatLedgerImpl); +}; + +} // namespace bat_ledger + +#endif // BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_IMPL_H_ diff --git a/components/services/bat_ledger/bat_ledger_service_impl.cc b/components/services/bat_ledger/bat_ledger_service_impl.cc new file mode 100644 index 000000000000..bb14bfeab164 --- /dev/null +++ b/components/services/bat_ledger/bat_ledger_service_impl.cc @@ -0,0 +1,72 @@ +/* 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/. */ + +#include "brave/components/services/bat_ledger/bat_ledger_service_impl.h" + +#include "bat/ledger/ledger.h" +#include "brave/components/services/bat_ledger/bat_ledger_impl.h" +#include "brave/vendor/bat-native-ledger/src/bat_helper.h" +#include "mojo/public/cpp/bindings/strong_associated_binding.h" + +namespace { + +bool testing() { + return ledger::is_testing; +} + +} + +namespace bat_ledger { + +BatLedgerServiceImpl::BatLedgerServiceImpl( + std::unique_ptr service_ref) + : service_ref_(std::move(service_ref)), + initialized_(false) { +} + +BatLedgerServiceImpl::~BatLedgerServiceImpl() { +} + +void BatLedgerServiceImpl::Create( + mojom::BatLedgerClientAssociatedPtrInfo client_info, + mojom::BatLedgerAssociatedRequest bat_ledger) { + mojo::MakeStrongAssociatedBinding( + std::make_unique(std::move(client_info)), + std::move(bat_ledger)); + initialized_ = true; +} + +void BatLedgerServiceImpl::SetProduction(bool is_production) { + DCHECK(!initialized_ || testing()); + ledger::is_production = is_production; +} + +void BatLedgerServiceImpl::SetReconcileTime(int32_t time) { + DCHECK(!initialized_ || testing()); + ledger::reconcile_time = time; +} + +void BatLedgerServiceImpl::SetShortRetries(bool short_retries) { + DCHECK(!initialized_ || testing()); + ledger::short_retries = short_retries; +} + +void BatLedgerServiceImpl::SetTesting() { + ledger::is_testing = true; + braveledger_bat_helper::set_ignore_for_testing(true); +} + +void BatLedgerServiceImpl::GetProduction(GetProductionCallback callback) { + std::move(callback).Run(ledger::is_production); +} + +void BatLedgerServiceImpl::GetReconcileTime(GetReconcileTimeCallback callback) { + std::move(callback).Run(ledger::reconcile_time); +} + +void BatLedgerServiceImpl::GetShortRetries(GetShortRetriesCallback callback) { + std::move(callback).Run(ledger::short_retries); +} + +} // namespace bat_ledger diff --git a/components/services/bat_ledger/bat_ledger_service_impl.h b/components/services/bat_ledger/bat_ledger_service_impl.h new file mode 100644 index 000000000000..08e93fdb0e16 --- /dev/null +++ b/components/services/bat_ledger/bat_ledger_service_impl.h @@ -0,0 +1,43 @@ +/* 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/. */ + +#ifndef BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_SERVICE_IMPL_H_ +#define BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_SERVICE_IMPL_H_ + +#include + +#include "brave/components/services/bat_ledger/public/interfaces/bat_ledger.mojom.h" +#include "services/service_manager/public/cpp/service_context_ref.h" + +namespace bat_ledger { + +class BatLedgerServiceImpl : public mojom::BatLedgerService { + public: + explicit BatLedgerServiceImpl( + std::unique_ptr service_ref); + ~BatLedgerServiceImpl() override; + + // bat_ledger::mojom::BatLedgerService + void Create(mojom::BatLedgerClientAssociatedPtrInfo client_info, + mojom::BatLedgerAssociatedRequest bat_ledger) override; + + void SetProduction(bool isProduction) override; + void SetReconcileTime(int32_t time) override; + void SetShortRetries(bool short_retries) override; + void SetTesting() override; + + void GetProduction(GetProductionCallback callback) override; + void GetReconcileTime(GetReconcileTimeCallback callback) override; + void GetShortRetries(GetShortRetriesCallback callback) override; + + private: + const std::unique_ptr service_ref_; + bool initialized_; + + DISALLOW_COPY_AND_ASSIGN(BatLedgerServiceImpl); +}; + +} // namespace bat_ledger + +#endif // BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_BAT_LEDGER_SERVICE_IMPL_H_ diff --git a/components/services/bat_ledger/manifest.json b/components/services/bat_ledger/manifest.json new file mode 100644 index 000000000000..96602b8af523 --- /dev/null +++ b/components/services/bat_ledger/manifest.json @@ -0,0 +1,15 @@ +{ + "name": "bat_ledger", + "display_name": "Bat Ledger Service", + "sandbox_type": "none", + "options" : { + "instance_sharing" : "shared_instance_across_users" + }, + "interface_provider_specs": { + "service_manager:connector": { + "provides": { + "bat_ledger": [ "bat_ledger.mojom.BatLedgerService" ] + } + } + } +} diff --git a/components/services/bat_ledger/public/cpp/BUILD.gn b/components/services/bat_ledger/public/cpp/BUILD.gn new file mode 100644 index 000000000000..03a128de9f80 --- /dev/null +++ b/components/services/bat_ledger/public/cpp/BUILD.gn @@ -0,0 +1,11 @@ +source_set("cpp") { + sources = [ + "ledger_client_mojo_proxy.cc", + "ledger_client_mojo_proxy.h", + ] + + deps = [ + "//brave/components/services/bat_ledger/public/interfaces", + "//brave/vendor/bat-native-ledger", + ] +} diff --git a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc new file mode 100644 index 000000000000..a67022c51abf --- /dev/null +++ b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc @@ -0,0 +1,494 @@ +/* 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/. */ + +#include "brave/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h" + +#include "base/logging.h" +#include "mojo/public/cpp/bindings/map.h" + +using namespace std::placeholders; + +namespace bat_ledger { + +namespace { // TODO, move into a util class + +int32_t ToMojomResult(ledger::Result result) { + return (int32_t)result; +} + +ledger::Result ToLedgerResult(int32_t result) { + return (ledger::Result)result; +} + +ledger::PUBLISHER_CATEGORY ToLedgerPublisherCategory(int32_t category) { + return (ledger::PUBLISHER_CATEGORY)category; +} + +ledger::Grant ToLedgerGrant(const std::string& grant_json) { + ledger::Grant grant; + grant.loadFromJson(grant_json); + return grant; +} + +ledger::URL_METHOD ToLedgerURLMethod(int32_t method) { + return (ledger::URL_METHOD)method; +} + +} // anonymous namespace + +LedgerClientMojoProxy::LedgerClientMojoProxy( + ledger::LedgerClient* ledger_client) + : ledger_client_(ledger_client) { +} + +LedgerClientMojoProxy::~LedgerClientMojoProxy() { +} + +template +void LedgerClientMojoProxy::CallbackHolder::OnLedgerStateLoaded( + ledger::Result result, const std::string& data) { + NOTREACHED(); +} + +template <> +void LedgerClientMojoProxy::CallbackHolder< + LedgerClientMojoProxy::LoadLedgerStateCallback>::OnLedgerStateLoaded( + ledger::Result result, const std::string& data) { + if (is_valid()) + std::move(callback_).Run(ToMojomResult(result), data); + delete this; +} + +void LedgerClientMojoProxy::LoadLedgerState(LoadLedgerStateCallback callback) { + auto* holder = new CallbackHolder(AsWeakPtr(), + std::move(callback)); + ledger_client_->LoadLedgerState(holder); +} + +void LedgerClientMojoProxy::GenerateGUID(GenerateGUIDCallback callback) { + std::move(callback).Run(ledger_client_->GenerateGUID()); +} + +void LedgerClientMojoProxy::OnWalletInitialized(int32_t result) { + ledger_client_->OnWalletInitialized(ToLedgerResult(result)); +} + +void LedgerClientMojoProxy::OnWalletProperties(int32_t result, + const std::string& info) { + std::unique_ptr wallet_info; + if (!info.empty()) { + wallet_info.reset(new ledger::WalletInfo()); + wallet_info->loadFromJson(info); + } + ledger_client_->OnWalletProperties(ToLedgerResult(result), + std::move(wallet_info)); +} + +void LedgerClientMojoProxy::LoadPublisherState( + LoadPublisherStateCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_client_->LoadPublisherState(holder); +} + +template +void LedgerClientMojoProxy::CallbackHolder::OnPublisherStateLoaded( + ledger::Result result, const std::string& data) { + NOTREACHED(); +} + +template <> +void LedgerClientMojoProxy::CallbackHolder< + LedgerClientMojoProxy::LoadPublisherStateCallback>::OnPublisherStateLoaded( + ledger::Result result, const std::string& data) { + if (is_valid()) + std::move(callback_).Run(ToMojomResult(result), data); + delete this; +} + +void LedgerClientMojoProxy::LoadPublisherList( + LoadPublisherListCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_client_->LoadPublisherList(holder); +} + +template +void LedgerClientMojoProxy::CallbackHolder::OnPublisherListLoaded( + ledger::Result result, const std::string& data) { + NOTREACHED(); +} + +template <> +void LedgerClientMojoProxy::CallbackHolder< + LedgerClientMojoProxy::LoadPublisherListCallback>::OnPublisherListLoaded( + ledger::Result result, const std::string& data) { + if (is_valid()) + std::move(callback_).Run(ToMojomResult(result), data); + delete this; +} + +void LedgerClientMojoProxy::SaveLedgerState( + const std::string& ledger_state, SaveLedgerStateCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_client_->SaveLedgerState(ledger_state, holder); +} + +template +void LedgerClientMojoProxy::CallbackHolder::OnLedgerStateSaved( + ledger::Result result) { + NOTREACHED(); +} + +template <> +void LedgerClientMojoProxy::CallbackHolder< + LedgerClientMojoProxy::SaveLedgerStateCallback>::OnLedgerStateSaved( + ledger::Result result) { + if (is_valid()) + std::move(callback_).Run(ToMojomResult(result)); + delete this; +} + +void LedgerClientMojoProxy::SavePublisherState( + const std::string& publisher_state, SavePublisherStateCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_client_->SavePublisherState(publisher_state, holder); +} + +template +void LedgerClientMojoProxy::CallbackHolder::OnPublisherStateSaved( + ledger::Result result) { + NOTREACHED(); +} + +template <> +void LedgerClientMojoProxy::CallbackHolder< + LedgerClientMojoProxy::SavePublisherStateCallback>::OnPublisherStateSaved( + ledger::Result result) { + if (is_valid()) + std::move(callback_).Run(ToMojomResult(result)); + delete this; +} + +void LedgerClientMojoProxy::SavePublishersList( + const std::string& publishers_list, SavePublishersListCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_client_->SavePublishersList(publishers_list, holder); +} + +template +void LedgerClientMojoProxy::CallbackHolder::OnPublishersListSaved( + ledger::Result result) { + NOTREACHED(); +} + +template <> +void LedgerClientMojoProxy::CallbackHolder< + LedgerClientMojoProxy::SavePublishersListCallback>::OnPublishersListSaved( + ledger::Result result) { + if (is_valid()) + std::move(callback_).Run(ToMojomResult(result)); + delete this; +} + +void LedgerClientMojoProxy::OnGrant(int32_t result, const std::string& grant) { + ledger_client_->OnGrant(ToLedgerResult(result), ToLedgerGrant(grant)); +} + +void LedgerClientMojoProxy::OnGrantCaptcha(const std::string& image, + const std::string& hint) { + ledger_client_->OnGrantCaptcha(image, hint); +} + +void LedgerClientMojoProxy::OnRecoverWallet(int32_t result, double balance, + const std::vector& grants) { + std::vector ledger_grants; + for (auto const& grant : grants) { + ledger_grants.push_back(ToLedgerGrant(grant)); + } + + ledger_client_->OnRecoverWallet( + ToLedgerResult(result), balance, ledger_grants); +} + +void LedgerClientMojoProxy::OnReconcileComplete(int32_t result, + const std::string& viewing_id, + int32_t category, + const std::string& probi) { + ledger_client_->OnReconcileComplete(ToLedgerResult(result), viewing_id, + ToLedgerPublisherCategory(category), probi); +} + +void LedgerClientMojoProxy::OnGrantFinish(int32_t result, + const std::string& grant) { + ledger_client_->OnGrantFinish(ToLedgerResult(result), ToLedgerGrant(grant)); +} + +// static +void LedgerClientMojoProxy::OnSavePublisherInfo( + CallbackHolder* holder, + ledger::Result result, + std::unique_ptr info) { + std::string json_info = info ? info->ToJson() : ""; + if (holder->is_valid()) + std::move(holder->get()).Run(ToMojomResult(result), json_info); + delete holder; +} + +void LedgerClientMojoProxy::SavePublisherInfo( + const std::string& publisher_info, + SavePublisherInfoCallback callback) { + // deleted in OnSavePublisherInfo + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + std::unique_ptr info; + if (!publisher_info.empty()) { + info.reset(new ledger::PublisherInfo()); + info->loadFromJson(publisher_info); + } + + ledger_client_->SavePublisherInfo(std::move(info), + std::bind(LedgerClientMojoProxy::OnSavePublisherInfo, holder, _1, _2)); +} + +// static +void LedgerClientMojoProxy::OnLoadPublisherInfo( + CallbackHolder* holder, + ledger::Result result, + std::unique_ptr info) { + std::string json_info = info ? info->ToJson() : ""; + if (holder->is_valid()) + std::move(holder->get()).Run(ToMojomResult(result), json_info); + delete holder; +} + +void LedgerClientMojoProxy::LoadPublisherInfo( + const std::string& filter, + LoadPublisherInfoCallback callback) { + // deleted in OnLoadPublisherInfo + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger::PublisherInfoFilter publisher_info_filter; + publisher_info_filter.loadFromJson(filter); + ledger_client_->LoadPublisherInfo(publisher_info_filter, + std::bind(LedgerClientMojoProxy::OnLoadPublisherInfo, holder, _1, _2)); +} + +// static +void LedgerClientMojoProxy::OnLoadPublisherInfoList( + CallbackHolder* holder, + const ledger::PublisherInfoList& list, + uint32_t next_record) { + std::vector publisher_info_list; + for (const auto& info : list) { + publisher_info_list.push_back(info.ToJson()); + } + + if (holder->is_valid()) + std::move(holder->get()).Run(publisher_info_list, next_record); + delete holder; +} + +void LedgerClientMojoProxy::LoadPublisherInfoList(uint32_t start, + uint32_t limit, + const std::string& filter, + LoadPublisherInfoListCallback callback) { + // deleted in OnLoadPublisherInfoList + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger::PublisherInfoFilter publisher_info_filter; + publisher_info_filter.loadFromJson(filter); + ledger_client_->LoadPublisherInfoList(start, limit, publisher_info_filter, + std::bind(LedgerClientMojoProxy::OnLoadPublisherInfoList, + holder, _1, _2)); +} + +// static +void LedgerClientMojoProxy::OnLoadMediaPublisherInfo( + CallbackHolder* holder, + ledger::Result result, + std::unique_ptr info) { + std::string json_info = info ? info->ToJson() : ""; + if (holder->is_valid()) + std::move(holder->get()).Run(ToMojomResult(result), json_info); + delete holder; +} + +void LedgerClientMojoProxy::LoadMediaPublisherInfo( + const std::string& media_key, + LoadMediaPublisherInfoCallback callback) { + // deleted in OnLoadMediaPublisherInfo + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_client_->LoadMediaPublisherInfo(media_key, + std::bind(LedgerClientMojoProxy::OnLoadMediaPublisherInfo, holder, _1, _2)); +} + +void LedgerClientMojoProxy::SetTimer(uint64_t time_offset, + SetTimerCallback callback) { + uint32_t timer_id; + ledger_client_->SetTimer(time_offset, timer_id); + std::move(callback).Run(timer_id); +} + +void LedgerClientMojoProxy::OnExcludedSitesChanged( + const std::string& publisher_id) { + ledger_client_->OnExcludedSitesChanged(publisher_id); +} + +void LedgerClientMojoProxy::OnPublisherActivity(int32_t result, + const std::string& info, uint64_t window_id) { + std::unique_ptr publisher_info; + if (!info.empty()) { + publisher_info.reset(new ledger::PublisherInfo()); + publisher_info->loadFromJson(info); + } + ledger_client_->OnPublisherActivity(ToLedgerResult(result), + std::move(publisher_info), window_id); +} + +// static +void LedgerClientMojoProxy::OnFetchFavIcon( + CallbackHolder* holder, + bool success, const std::string& favicon_url) { + if (holder->is_valid()) + std::move(holder->get()).Run(success, favicon_url); + delete holder; +} + +void LedgerClientMojoProxy::FetchFavIcon(const std::string& url, + const std::string& favicon_key, FetchFavIconCallback callback) { + // deleted in OnFetchFavIcon + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_client_->FetchFavIcon(url, favicon_key, + std::bind(LedgerClientMojoProxy::OnFetchFavIcon, holder, _1, _2)); +} + +// static +void LedgerClientMojoProxy::OnGetRecurringDonations( + CallbackHolder* holder, + const ledger::PublisherInfoList& publisher_info_list, + uint32_t next_record) { + std::vector list; + for (const auto& publisher_info : publisher_info_list) { + list.push_back(publisher_info.ToJson()); + } + + if (holder->is_valid()) + std::move(holder->get()).Run(list, next_record); + delete holder; +} + +void LedgerClientMojoProxy::GetRecurringDonations( + GetRecurringDonationsCallback callback) { + // deleted in OnGetRecurringDonations + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_client_->GetRecurringDonations( + std::bind(LedgerClientMojoProxy::OnGetRecurringDonations, + holder, _1, _2)); +} + +// static +void LedgerClientMojoProxy::OnLoadNicewareList( + CallbackHolder* holder, + int32_t result, const std::string& data) { + if (holder->is_valid()) + std::move(holder->get()).Run(ToLedgerResult(result), data); + delete holder; +} + +void LedgerClientMojoProxy::LoadNicewareList( + LoadNicewareListCallback callback) { + // deleted in OnLoadNicewareList + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_client_->LoadNicewareList( + std::bind(LedgerClientMojoProxy::OnLoadNicewareList, + holder, _1, _2)); +} + +// static +void LedgerClientMojoProxy::OnRecurringRemoved( + CallbackHolder* holder, int32_t result) { + if (holder->is_valid()) + std::move(holder->get()).Run(ToLedgerResult(result)); + delete holder; +} + +void LedgerClientMojoProxy::OnRemoveRecurring(const std::string& publisher_key, + OnRemoveRecurringCallback callback) { + // deleted in OnRecurringRemoved + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_client_->OnRemoveRecurring(publisher_key, + std::bind(LedgerClientMojoProxy::OnRecurringRemoved, holder, _1)); +} + +void LedgerClientMojoProxy::SaveContributionInfo(const std::string& probi, + int32_t month, int32_t year, uint32_t date, + const std::string& publisher_key, int32_t category) { + ledger_client_->SaveContributionInfo(probi, month, year, date, publisher_key, + ToLedgerPublisherCategory(category)); +} + +void LedgerClientMojoProxy::SaveMediaPublisherInfo( + const std::string& media_key, const std::string& publisher_id) { + ledger_client_->SaveMediaPublisherInfo(media_key, publisher_id); +} + +void LedgerClientMojoProxy::FetchWalletProperties() { + ledger_client_->FetchWalletProperties(); +} + +void LedgerClientMojoProxy::FetchGrant(const std::string& lang, + const std::string& payment_id) { + ledger_client_->FetchGrant(lang, payment_id); +} + +void LedgerClientMojoProxy::GetGrantCaptcha() { + ledger_client_->GetGrantCaptcha(); +} + +void LedgerClientMojoProxy::URIEncode(const std::string& value, + URIEncodeCallback callback) { + std::move(callback).Run(ledger_client_->URIEncode(value)); +} + +void LedgerClientMojoProxy::SetContributionAutoInclude( + const std::string& publisher_key, bool excluded, uint64_t window_id) { + ledger_client_->SetContributionAutoInclude( + publisher_key, excluded, window_id); +} + +// static +void LedgerClientMojoProxy::OnLoadURL( + CallbackHolder* holder, + bool success, const std::string& response, + const std::map& headers) { + if (holder->is_valid()) + std::move(holder->get()).Run( + success, response, mojo::MapToFlatMap(headers)); + delete holder; +} + +void LedgerClientMojoProxy::LoadURL(const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + int32_t method, + LoadURLCallback callback) { + // deleted in OnLoadURL + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger_client_->LoadURL(url, headers, content, contentType, + ToLedgerURLMethod(method), + std::bind(LedgerClientMojoProxy::OnLoadURL, holder, _1, _2, _3)); +} + +} // namespace bat_ledger diff --git a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h new file mode 100644 index 000000000000..6d87b3ba2256 --- /dev/null +++ b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h @@ -0,0 +1,169 @@ +/* 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/. */ + +#ifndef BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_PUBLIC_CPP_LEDGER_CLIENT_MOJO_PROXY_H_ +#define BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_PUBLIC_CPP_LEDGER_CLIENT_MOJO_PROXY_H_ + +#include + +#include "base/memory/weak_ptr.h" +#include "bat/ledger/ledger_client.h" +#include "brave/components/services/bat_ledger/public/interfaces/bat_ledger.mojom.h" + +namespace bat_ledger { + +class LedgerClientMojoProxy : public mojom::BatLedgerClient, + public base::SupportsWeakPtr { + public: + LedgerClientMojoProxy(ledger::LedgerClient* ledger_client); + ~LedgerClientMojoProxy() override; + + // bat_ledger::mojom::BatLedgerClient + void GenerateGUID(GenerateGUIDCallback callback) override; + void LoadLedgerState(LoadLedgerStateCallback callback) override; + void OnWalletInitialized(int32_t result) override; + void OnWalletProperties(int32_t result, const std::string& info) override; + void OnGrant(int32_t result, const std::string& grant) override; + void OnGrantCaptcha(const std::string& image, + const std::string& hint) override; + void OnRecoverWallet(int32_t result, double balance, + const std::vector& grants) override; + void OnReconcileComplete(int32_t result, const std::string& viewing_id, + int32_t category, const std::string& probi) override; + void OnGrantFinish(int32_t result, const std::string& grant) override; + + void LoadPublisherState(LoadPublisherStateCallback callback) override; + void LoadPublisherList(LoadPublisherListCallback callback) override; + void SaveLedgerState(const std::string& ledger_state, + SaveLedgerStateCallback callback) override; + void SavePublisherState(const std::string& publisher_state, + SavePublisherStateCallback callback) override; + void SavePublishersList(const std::string& publishers_list, + SavePublishersListCallback callback) override; + + void SavePublisherInfo(const std::string& publisher_info, + SavePublisherInfoCallback callback) override; + void LoadPublisherInfo(const std::string& filter, + LoadPublisherInfoCallback callback) override; + void LoadPublisherInfoList(uint32_t start, uint32_t limit, + const std::string& filter, + LoadPublisherInfoListCallback callback) override; + void LoadMediaPublisherInfo(const std::string& media_key, + LoadMediaPublisherInfoCallback callback) override; + + void FetchFavIcon(const std::string& url, const std::string& favicon_key, + FetchFavIconCallback callback) override; + void GetRecurringDonations(GetRecurringDonationsCallback callback) override; + + void LoadNicewareList(LoadNicewareListCallback callback) override; + void OnRemoveRecurring(const std::string& publisher_key, + OnRemoveRecurringCallback callback) override; + + void SetTimer(uint64_t time_offset, SetTimerCallback callback) override; + void OnPublisherActivity(int32_t result, const std::string& info, + uint64_t window_id) override; + void OnExcludedSitesChanged(const std::string& publisher_id) override; + void SaveContributionInfo(const std::string& probi, int32_t month, + int32_t year, uint32_t date, const std::string& publisher_key, + int32_t category) override; + void SaveMediaPublisherInfo(const std::string& media_key, + const std::string& publisher_id) override; + void FetchWalletProperties() override; + void FetchGrant(const std::string& lang, + const std::string& payment_id) override; + void GetGrantCaptcha() override; + + void URIEncode(const std::string& value, + URIEncodeCallback callback) override; + + void SetContributionAutoInclude(const std::string& publisher_key, + bool excluded, uint64_t window_id) override; + + void LoadURL(const std::string& url, + const std::vector& headers, + const std::string& content, + const std::string& contentType, + int32_t method, + LoadURLCallback callback) override; + + private: + // workaround to pass base::OnceCallback into std::bind + // also serves as a wrapper for passing ledger::LedgerCallbackHandler* + template + class CallbackHolder : public ledger::LedgerCallbackHandler { + public: + CallbackHolder(base::WeakPtr client, + Callback callback) + : client_(client), + callback_(std::move(callback)) {} + ~CallbackHolder() = default; + bool is_valid() { return !!client_.get(); } + Callback& get() { return callback_; } + + // ledger::LedgerCallbackHandler impl + void OnLedgerStateLoaded(ledger::Result result, + const std::string& data) override; + void OnPublisherStateLoaded(ledger::Result result, + const std::string& data) override; + void OnPublisherListLoaded(ledger::Result result, + const std::string& data) override; + void OnLedgerStateSaved(ledger::Result result) override; + void OnPublisherStateSaved(ledger::Result result) override; + void OnPublishersListSaved(ledger::Result result) override; + private: + base::WeakPtr client_; + Callback callback_; + }; + + static void OnSavePublisherInfo( + CallbackHolder* holder, + ledger::Result result, + std::unique_ptr info); + + static void OnLoadPublisherInfo( + CallbackHolder* holder, + ledger::Result result, + std::unique_ptr info); + + static void OnLoadPublisherInfoList( + CallbackHolder* holder, + const ledger::PublisherInfoList& list, + uint32_t next_record); + + static void OnLoadMediaPublisherInfo( + CallbackHolder* holder, + ledger::Result result, + std::unique_ptr info); + + static void OnFetchFavIcon( + CallbackHolder* holder, + bool success, + const std::string& favicon_url); + + static void OnGetRecurringDonations( + CallbackHolder* holder, + const ledger::PublisherInfoList& publisher_info_list, + uint32_t next_record); + + static void OnLoadNicewareList( + CallbackHolder* holder, + int32_t result, const std::string& data); + + static void OnRecurringRemoved( + CallbackHolder* holder, + int32_t result); + + static void OnLoadURL( + CallbackHolder* holder, + bool success, const std::string& response, + const std::map& headers); + + ledger::LedgerClient* ledger_client_; + + DISALLOW_COPY_AND_ASSIGN(LedgerClientMojoProxy); +}; + +} // namespace bat_ledger + +#endif // BRAVE_COMPONENTS_SERVICES_BAT_LEDGER_PUBLIC_CPP_LEDGER_CLIENT_MOJO_PROXY_H_ diff --git a/components/services/bat_ledger/public/interfaces/BUILD.gn b/components/services/bat_ledger/public/interfaces/BUILD.gn new file mode 100644 index 000000000000..d085ff3d4fb0 --- /dev/null +++ b/components/services/bat_ledger/public/interfaces/BUILD.gn @@ -0,0 +1,13 @@ +import("//mojo/public/tools/bindings/mojom.gni") + +mojom("interfaces") { + support_lazy_serialization = true + + sources = [ + "bat_ledger.mojom", + ] + + public_deps = [ + "//mojo/public/mojom/base", + ] +} diff --git a/components/services/bat_ledger/public/interfaces/bat_ledger.mojom b/components/services/bat_ledger/public/interfaces/bat_ledger.mojom new file mode 100644 index 000000000000..8f2491c85814 --- /dev/null +++ b/components/services/bat_ledger/public/interfaces/bat_ledger.mojom @@ -0,0 +1,157 @@ +// 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/. +module bat_ledger.mojom; + +const string kServiceName = "bat_ledger"; + +interface BatLedgerService { + Create(associated BatLedgerClient bat_ledger_client, + associated BatLedger& bat_ledger); + SetProduction(bool isProduction); + SetReconcileTime(int32 time); + SetShortRetries(bool short_retries); + SetTesting(); + + GetProduction() => (bool production); + GetReconcileTime() => (int32 time); + GetShortRetries() => (bool short_retries); +}; + +interface BatLedger { + Initialize(); + CreateWallet(); + FetchWalletProperties(); + + GetAutoContributeProps() => (string props); + GetPublisherMinVisitTime() => (uint64 min_visit_time); + GetPublisherMinVisits() => (uint32 min_visits); + GetPublisherAllowNonVerified() => (bool allowed); + GetPublisherAllowVideos() => (bool allowed); + GetAutoContribute() => (bool auto_contribute); + GetReconcileStamp() => (uint64 reconcile_stamp); + + GetPublisherInfoList(uint32 start, uint32 limit, string filter) => ( + array publisher_info_list, uint32 next_record); + + OnLoad(string visit_data, uint64 current_time); + OnUnload(uint32 tab_id, uint64 current_time); + OnShow(uint32 tab_id, uint64 current_time); + OnHide(uint32 tab_id, uint64 current_time); + OnForeground(uint32 tab_id, uint64 current_time); + OnBackground(uint32 tab_id, uint64 current_time); + OnMediaStart(uint32 tab_id, uint64 current_time); + OnMediaStop(uint32 tab_id, uint64 current_time); + + OnPostData(string url, string first_party_url, string referrer, + string post_data, string visit_data); + OnXHRLoad(uint32 tab_id, string url, map parts, + string first_party_url, string referrer, string visit_data); + + SetPublisherExclude(string publisher_key, int32 exclude); + RestorePublishers(); + + SetBalanceReportItem(int32 month, int32 year, int32 type, string probi); + OnReconcileCompleteSuccess(string viewing_id, int32 category, string probi, + int32 month, int32 year, uint32 data); + + FetchGrant(string lang, string payment_id); + GetGrantCaptcha(); + GetWalletPassphrase() => (string wallet_passphrase); + GetNumExcludedSites() => (uint32 num_excluded_sites); + RecoverWallet(string passPhrase); + SolveGrantCaptcha(string solution); + + GetAddresses() => (map addresses); + GetBATAddress() => (string address); + GetBTCAddress() => (string address); + GetETHAddress() => (string address); + GetLTCAddress() => (string address); + + SetRewardsMainEnabled(bool enabled); + SetPublisherMinVisitTime(uint64 duration_in_seconds); + SetPublisherMinVisits(uint32 visits); + SetPublisherAllowNonVerified(bool allow); + SetPublisherAllowVideos(bool allow); + SetUserChangedContribution(); + SetContributionAmount(double amount); + SetAutoContribute(bool enabled); + + OnTimer(uint32 timer_id); + + GetAllBalanceReports() => (map reports); + GetBalanceReport(int32 month, int32 year) => (bool result, string report); + + IsWalletCreated() => (bool wallet_created); + + GetPublisherActivityFromUrl(uint64 window_id, string visit_data); + GetContributionAmount() => (double contribution_amount); + GetPublisherBanner(string publisher_id) => (string banner); + + DoDirectDonation(string publisher_info, int32 amount, string currency); + + RemoveRecurring(string publisher_key); + SetPublisherPanelExclude(string publisher_key, int32 exclude, + uint64 window_id); + GetBootStamp() => (uint64 boot_stamp); + GetRewardsMainEnabled() => (bool main_enabled); + + HasSufficientBalanceToReconcile() => (bool sufficient); +}; + +interface BatLedgerClient { + [Sync] + GenerateGUID() => (string guid); + LoadLedgerState() => (int32 result, string data); + OnWalletInitialized(int32 result); + LoadPublisherState() => (int32 result, string data); + LoadPublisherList() => (int32 result, string data); + SaveLedgerState(string ledger_state) => (int32 result); + SavePublisherState(string publisher_state) => (int32 result); + SavePublishersList(string publishers_list) => (int32 result); + + OnWalletProperties(int32 result, string info); + OnGrant(int32 result, string grant); + OnGrantCaptcha(string image, string hint); + OnRecoverWallet(int32 result, double balance, array grants); + OnReconcileComplete(int32 result, string viewing_id, int32 category, + string probi); + OnGrantFinish(int32 result, string grant); + + SavePublisherInfo(string publisher_info) => (int32 result, + string publisher_info); + LoadPublisherInfo(string filter) => (int32 result, string publisher_info); + LoadPublisherInfoList(uint32 start, uint32 limit, string filter) => ( + array publisher_info_list, uint32 next_record); + LoadMediaPublisherInfo(string media_key) => (int32 result, + string publisher_info); + + OnPublisherActivity(int32 result, string info, uint64 window_id); + FetchFavIcon(string url, string favicon_key) => (bool success, + string favicon_url); + GetRecurringDonations() => (array publisher_info_list, + uint32 next_record); + + LoadNicewareList() => (int32 result, string data); + OnRemoveRecurring(string publisher_key) => (int32 result); + + LoadURL(string url, array headers, string content, + string content_type, int32 method) => (bool success, string response, + map headers); + + [Sync] + SetTimer(uint64 time_offset) => (uint32 timer_id); + OnExcludedSitesChanged(string publisher_id); + SaveContributionInfo(string probi, int32 month, int32 year, uint32 date, + string publisher_key, int32 category); + SaveMediaPublisherInfo(string media_key, string publisher_id); + FetchWalletProperties(); + FetchGrant(string lang, string payment_id); + GetGrantCaptcha(); + + [Sync] + URIEncode(string value) => (string encoded_value); + + SetContributionAutoInclude(string publisher_key, bool excluded, + uint64 window_id); +}; diff --git a/components/services/brave_content_browser_manifest_overlay.json b/components/services/brave_content_browser_manifest_overlay.json index f508b69af3e4..a9fb49c0f9a9 100644 --- a/components/services/brave_content_browser_manifest_overlay.json +++ b/components/services/brave_content_browser_manifest_overlay.json @@ -5,6 +5,7 @@ "service_manager:connector": { "requires": { "bat_ads": [ "bat_ads" ], + "bat_ledger": [ "bat_ledger" ], "tor_launcher": [ "tor_launcher" ] } } diff --git a/patches/chrome-browser-chrome_content_utility_manifest_overlay.json.patch b/patches/chrome-browser-chrome_content_utility_manifest_overlay.json.patch deleted file mode 100644 index f4b4e8604482..000000000000 --- a/patches/chrome-browser-chrome_content_utility_manifest_overlay.json.patch +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/chrome/browser/chrome_content_utility_manifest_overlay.json b/chrome/browser/chrome_content_utility_manifest_overlay.json -index 03d7cd6b486001765096df3bfe95624fd2700c42..a5dbd36e97f36417b861c41a2bfb201a8640aba2 100644 ---- a/chrome/browser/chrome_content_utility_manifest_overlay.json -+++ b/chrome/browser/chrome_content_utility_manifest_overlay.json -@@ -10,6 +10,7 @@ - "payments.mojom.PaymentManifestParser", - "heap_profiling.mojom.ProfilingClient", - "proxy_resolver.mojom.ProxyResolverFactory", -+ "tor.mojom.TorLauncher", - "safe_json.mojom.SafeJsonParser" - ] - } diff --git a/test/BUILD.gn b/test/BUILD.gn index fb203af47597..9ff3a8d040d9 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -279,6 +279,8 @@ test("brave_browser_tests") { "//chrome/browser/extensions/updater/extension_cache_fake.h", ] + deps = [] + if (enable_widevine_cdm_component) { sources += [ "//brave/browser/ui/content_settings/brave_widevine_blocked_image_model_browsertest.cc", @@ -290,6 +292,10 @@ test("brave_browser_tests") { "//brave/components/brave_rewards/browser/rewards_notification_service_browsertest.cc", "//brave/components/brave_rewards/browser/rewards_service_browsertest.cc", ] + + deps += [ + "//brave/vendor/bat-native-ledger", + ] } if (is_win || is_linux) { @@ -316,7 +322,7 @@ test("brave_browser_tests") { } defines = [ "HAS_OUT_OF_PROC_TEST_RUNNER" ] - deps = [ + deps += [ "//chrome/browser/ui", "//ppapi/buildflags", ":brave_browser_tests_deps", diff --git a/utility/BUILD.gn b/utility/BUILD.gn index fb0110d1fcc7..d41653135e8f 100644 --- a/utility/BUILD.gn +++ b/utility/BUILD.gn @@ -19,6 +19,7 @@ source_set("utility") { defines = [] deps = [ "tor", + "//brave/components/services/bat_ledger:lib", "//chrome/common", "//chrome/utility", "//content/public/common", diff --git a/utility/brave_content_utility_client.cc b/utility/brave_content_utility_client.cc index 940727ae13f3..446eb160fe70 100644 --- a/utility/brave_content_utility_client.cc +++ b/utility/brave_content_utility_client.cc @@ -6,6 +6,7 @@ #include "brave/common/tor/tor_launcher.mojom.h" #include "brave/components/brave_ads/browser/buildflags/buildflags.h" +#include "brave/components/brave_rewards/browser/buildflags/buildflags.h" #include "brave/utility/tor/tor_launcher_service.h" #if BUILDFLAG(BRAVE_ADS_ENABLED) @@ -13,6 +14,11 @@ #include "brave/components/services/bat_ads/public/interfaces/bat_ads.mojom.h" #endif +#if BUILDFLAG(BRAVE_REWARDS_ENABLED) +#include "brave/components/services/bat_ledger/bat_ledger_app.h" +#include "brave/components/services/bat_ledger/public/interfaces/bat_ledger.mojom.h" +#endif + BraveContentUtilityClient::BraveContentUtilityClient() : ChromeContentUtilityClient() {} @@ -33,4 +39,11 @@ void BraveContentUtilityClient::RegisterServices( &bat_ads::BatAdsApp::CreateService); services->emplace(bat_ads::mojom::kServiceName, bat_ads_service); #endif + +#if BUILDFLAG(BRAVE_REWARDS_ENABLED) + service_manager::EmbeddedServiceInfo bat_ledger_info; + bat_ledger_info.factory = base::BindRepeating( + &bat_ledger::BatLedgerApp::CreateService); + services->emplace(bat_ledger::mojom::kServiceName, bat_ledger_info); +#endif } diff --git a/vendor/bat-native-ledger/BUILD.gn b/vendor/bat-native-ledger/BUILD.gn index fa63987839b0..e35410d56d10 100644 --- a/vendor/bat-native-ledger/BUILD.gn +++ b/vendor/bat-native-ledger/BUILD.gn @@ -53,8 +53,6 @@ source_set("ledger") { "include/bat/ledger/ledger.h", "include/bat/ledger/ledger_callback_handler.h", "include/bat/ledger/ledger_client.h", - "include/bat/ledger/ledger_url_loader.h", - "include/bat/ledger/ledger_task_runner.h", "src/bat/ledger/ledger.cc", "src/bat_client.cc", "src/bat_client.h", @@ -73,10 +71,6 @@ source_set("ledger") { "src/bignum.h", "src/ledger_impl.cc", "src/ledger_impl.h", - "src/ledger_task_runner_impl.cc", - "src/ledger_task_runner_impl.h", - "src/url_request_handler.cc", - "src/url_request_handler.h", ] deps = [ diff --git a/vendor/bat-native-ledger/include/bat/ledger/auto_contribute_props.h b/vendor/bat-native-ledger/include/bat/ledger/auto_contribute_props.h new file mode 100644 index 000000000000..91a59a583c91 --- /dev/null +++ b/vendor/bat-native-ledger/include/bat/ledger/auto_contribute_props.h @@ -0,0 +1,28 @@ +/* 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/. */ + +#ifndef BAT_LEDGER_AUTO_CONTRIBUTE_PROPS_ +#define BAT_LEDGER_AUTO_CONTRIBUTE_PROPS_ + +namespace ledger { + +LEDGER_EXPORT struct AutoContributeProps { + AutoContributeProps(); + ~AutoContributeProps(); + AutoContributeProps(const AutoContributeProps& properties) = default; + + const std::string ToJson() const; + bool loadFromJson(const std::string& json); + + bool enabled_contribute; + uint64_t contribution_min_time; + int32_t contribution_min_visits; + bool contribution_non_verified; + bool contribution_videos; + uint64_t reconcile_stamp; +}; + +} // namespace ledger + +#endif // BAT_LEDGER_AUTO_CONTRIBUTION_PROPS_ diff --git a/vendor/bat-native-ledger/include/bat/ledger/balance_report_info.h b/vendor/bat-native-ledger/include/bat/ledger/balance_report_info.h index b0101ef10443..cbc6147c02fc 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/balance_report_info.h +++ b/vendor/bat-native-ledger/include/bat/ledger/balance_report_info.h @@ -25,6 +25,9 @@ LEDGER_EXPORT struct BalanceReportInfo { BalanceReportInfo(const BalanceReportInfo&); ~BalanceReportInfo(); + const std::string ToJson() const; + bool loadFromJson(const std::string& json); + std::string opening_balance_ = "0"; std::string closing_balance_ = "0"; std::string deposits_ = "0"; diff --git a/vendor/bat-native-ledger/include/bat/ledger/grant.h b/vendor/bat-native-ledger/include/bat/ledger/grant.h index 9da0e708c68d..f342ed6195ae 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/grant.h +++ b/vendor/bat-native-ledger/include/bat/ledger/grant.h @@ -18,6 +18,9 @@ LEDGER_EXPORT struct Grant { ~Grant(); Grant(const Grant& properties); + const std::string ToJson() const; + bool loadFromJson(const std::string& json); + std::string altcurrency; std::string probi; std::string promotionId; diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger.h b/vendor/bat-native-ledger/include/bat/ledger/ledger.h index d2eb0f430efd..a65596916290 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger.h @@ -10,6 +10,7 @@ #include #include "bat/ledger/export.h" +#include "bat/ledger/auto_contribute_props.h" #include "bat/ledger/ledger_client.h" #include "bat/ledger/publisher_info.h" #include "bat/ledger/media_publisher_info.h" @@ -17,6 +18,7 @@ namespace ledger { extern bool is_production; +extern bool is_testing; extern int reconcile_time; // minutes extern bool short_retries; @@ -35,6 +37,9 @@ LEDGER_EXPORT struct VisitData { VisitData(const VisitData& data); ~VisitData(); + const std::string ToJson() const; + bool loadFromJson(const std::string& json); + std::string tld; std::string domain; std::string path; @@ -89,7 +94,7 @@ class LEDGER_EXPORT Ledger { virtual void MakePayment(const PaymentData& payment_data) = 0; virtual void AddRecurringPayment(const std::string& publisher_id, const double& value) = 0; virtual void DoDirectDonation(const PublisherInfo& publisher, const int amount, const std::string& currency) = 0; - virtual void OnLoad(const ledger::VisitData& visit_data, const uint64_t& current_time) = 0; + virtual void OnLoad(const VisitData& visit_data, const uint64_t& current_time) = 0; virtual void OnUnload(uint32_t tab_id, const uint64_t& current_time) = 0; virtual void OnShow(uint32_t tab_id, const uint64_t& current_time) = 0; virtual void OnHide(uint32_t tab_id, const uint64_t& current_time) = 0; @@ -141,6 +146,7 @@ class LEDGER_EXPORT Ledger { int year, const ledger::BalanceReportInfo& report_info) = 0; + virtual std::map GetAddresses() = 0; virtual const std::string& GetBATAddress() const = 0; virtual const std::string& GetBTCAddress() const = 0; virtual const std::string& GetETHAddress() const = 0; @@ -163,6 +169,7 @@ class LEDGER_EXPORT Ledger { int year, ledger::BalanceReportInfo* report_info) const = 0; virtual std::map GetAllBalanceReports() const = 0; + virtual void GetAutoContributeProps(ledger::AutoContributeProps& props) = 0; virtual void RecoverWallet(const std::string& passPhrase) const = 0; virtual void SaveMediaVisit(const std::string& publisher_id, @@ -191,6 +198,7 @@ class LEDGER_EXPORT Ledger { virtual double GetDefaultContributionAmount() = 0; virtual uint64_t GetBootStamp() const = 0; + virtual bool HasSufficientBalanceToReconcile() = 0; }; } // namespace ledger diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger_callback_handler.h b/vendor/bat-native-ledger/include/bat/ledger/ledger_callback_handler.h index 9dcc6dbb7718..40dae088e5fb 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger_callback_handler.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger_callback_handler.h @@ -49,13 +49,6 @@ class LEDGER_EXPORT LedgerCallbackHandler { virtual void OnPublisherStateLoaded(Result result, const std::string& data) {}; virtual void OnPublisherStateSaved(Result result) {}; - - virtual void OnURLRequestResponse(uint64_t request_id, - const std::string& url, - int response_code, - const std::string& response, - const std::map& headers) {}; - virtual void OnPublishersListSaved(Result result) {}; virtual void OnPublisherListLoaded(Result result, diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h b/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h index 426bcaffa83f..227aa9e4b389 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h @@ -15,8 +15,6 @@ #include "bat/ledger/balance_report_info.h" #include "bat/ledger/export.h" #include "bat/ledger/ledger_callback_handler.h" -#include "bat/ledger/ledger_task_runner.h" -#include "bat/ledger/ledger_url_loader.h" #include "bat/ledger/media_publisher_info.h" #include "bat/ledger/publisher_info.h" #include "bat/ledger/wallet_info.h" @@ -55,6 +53,8 @@ using GetNicewareListCallback = using RecurringDonationCallback = std::function; using RecurringRemoveCallback = std::function; using FetchIconCallback = std::function; +using LoadURLCallback = std::function& headers)>; class LEDGER_EXPORT LedgerClient { public: @@ -128,16 +128,14 @@ class LEDGER_EXPORT LedgerClient { virtual std::string URIEncode(const std::string& value) = 0; - virtual std::unique_ptr LoadURL( + virtual void LoadURL( const std::string& url, const std::vector& headers, const std::string& content, const std::string& contentType, const ledger::URL_METHOD& method, - ledger::LedgerCallbackHandler* handler) = 0; - // RunIOTask is a temporary workarounds for some IO tasks - virtual void RunIOTask(std::unique_ptr task) = 0; - virtual void SetContributionAutoInclude(std::string publisher_key, + ledger::LoadURLCallback callback) = 0; + virtual void SetContributionAutoInclude(const std::string& publisher_key, bool excluded, uint64_t windowId) = 0; diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger_task_runner.h b/vendor/bat-native-ledger/include/bat/ledger/ledger_task_runner.h deleted file mode 100644 index d1f986e29bde..000000000000 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger_task_runner.h +++ /dev/null @@ -1,25 +0,0 @@ -/* 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/. */ - -#ifndef BAT_LEDGER_LEDGER_TASK_RUNNER_ -#define BAT_LEDGER_LEDGER_TASK_RUNNER_ - -#include - -#include "bat/ledger/export.h" - -namespace ledger { - -class LEDGER_EXPORT LedgerTaskRunner { - public: - using CallerThreadCallback = std::function)>; - using Task = std::function; - - virtual ~LedgerTaskRunner() = default; - virtual void Run(const CallerThreadCallback& callback) = 0; -}; - -} // namespace ledger - -#endif // BAT_LEDGER_LEDGER_TASK_RUNNER_ diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger_url_loader.h b/vendor/bat-native-ledger/include/bat/ledger/ledger_url_loader.h deleted file mode 100644 index 6651816efc2e..000000000000 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger_url_loader.h +++ /dev/null @@ -1,23 +0,0 @@ -/* 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/. */ - -#ifndef BAT_LEDGER_LEDGER_URL_LOADER_ -#define BAT_LEDGER_LEDGER_URL_LOADER_ - -#include - -#include "bat/ledger/export.h" - -namespace ledger { - -class LEDGER_EXPORT LedgerURLLoader { - public: - virtual ~LedgerURLLoader() = default; - virtual void Start() = 0; - virtual uint64_t request_id() = 0; -}; - -} // namespace ledger - -#endif // BAT_LEDGER_LEDGER_URL_LOADER_ diff --git a/vendor/bat-native-ledger/include/bat/ledger/publisher_info.h b/vendor/bat-native-ledger/include/bat/ledger/publisher_info.h index b4b0051d31f0..d5da8c8d344f 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/publisher_info.h +++ b/vendor/bat-native-ledger/include/bat/ledger/publisher_info.h @@ -57,6 +57,9 @@ LEDGER_EXPORT struct PublisherInfoFilter { PublisherInfoFilter(const PublisherInfoFilter& filter); ~PublisherInfoFilter(); + const std::string ToJson() const; + bool loadFromJson(const std::string& json); + std::string id; int category; PUBLISHER_MONTH month; @@ -64,7 +67,7 @@ LEDGER_EXPORT struct PublisherInfoFilter { PUBLISHER_EXCLUDE_FILTER excluded; uint32_t percent; std::vector> order_by; - unsigned int min_duration; + uint64_t min_duration; uint64_t reconcile_stamp; bool non_verified; }; @@ -75,6 +78,9 @@ LEDGER_EXPORT struct ContributionInfo { value(value_), date(date_) {} + const std::string ToJson() const; + bool loadFromJson(const std::string& json); + std::string publisher; // Filled only for recurrent donations double value; uint64_t date; @@ -85,6 +91,9 @@ LEDGER_EXPORT struct PublisherBanner { PublisherBanner(const PublisherBanner& info); ~PublisherBanner(); + const std::string ToJson() const; + bool loadFromJson(const std::string& json); + std::string publisher_key; std::string title; std::string name; @@ -106,6 +115,9 @@ LEDGER_EXPORT struct PublisherInfo { bool operator<(const PublisherInfo& rhs) const; bool is_valid() const; + const std::string ToJson() const; + bool loadFromJson(const std::string& json); + std::string id; uint64_t duration; double score; diff --git a/vendor/bat-native-ledger/include/bat/ledger/wallet_info.h b/vendor/bat-native-ledger/include/bat/ledger/wallet_info.h index 4c678a5d45e4..9e71fe8d27a1 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/wallet_info.h +++ b/vendor/bat-native-ledger/include/bat/ledger/wallet_info.h @@ -17,6 +17,10 @@ LEDGER_EXPORT struct WalletInfo { WalletInfo(); ~WalletInfo(); WalletInfo(const WalletInfo& info); + + const std::string ToJson() const; + bool loadFromJson(const std::string& json); + std::string altcurrency_; std::string probi_; double balance_; diff --git a/vendor/bat-native-ledger/src/bat/ledger/ledger.cc b/vendor/bat-native-ledger/src/bat/ledger/ledger.cc index b4291bc560f4..10c389b8df69 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/ledger.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/ledger.cc @@ -4,15 +4,17 @@ #include "bat/ledger/ledger.h" +#include "bat_get_media.h" #include "ledger_impl.h" +#include "rapidjson_bat_helper.h" #include "rapidjson/document.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" -#include "bat_get_media.h" namespace ledger { bool is_production = true; +bool is_testing = false; int reconcile_time = 0; // minutes bool short_retries = false; @@ -54,6 +56,46 @@ VisitData::VisitData(const VisitData& data) : VisitData::~VisitData() {} +const std::string VisitData::ToJson() const { + std::string json; + braveledger_bat_helper::saveToJsonString(*this, json); + return json; +} + +bool VisitData::loadFromJson(const std::string& json) { + rapidjson::Document d; + d.Parse(json.c_str()); + + // has parser errors or wrong types + bool error = d.HasParseError(); + if (false == error) { + error = !(d.HasMember("tld") && d["tld"].IsString() && + d.HasMember("domain") && d["domain"].IsString() && + d.HasMember("path") && d["path"].IsString() && + d.HasMember("tab_id") && d["tab_id"].IsUint() && + d.HasMember("local_month") && d["local_month"].IsInt() && + d.HasMember("local_year") && d["local_year"].IsInt() && + d.HasMember("name") && d["name"].IsString() && + d.HasMember("url") && d["url"].IsString() && + d.HasMember("provider") && d["provider"].IsString() && + d.HasMember("favicon_url") && d["favicon_url"].IsString()); + } + + if (false == error) { + tld = d["tld"].GetString(); + domain = d["domain"].GetString(); + path = d["path"].GetString(); + tab_id = d["tab_id"].GetUint(); + local_month = (PUBLISHER_MONTH)d["local_month"].GetInt(); + local_year = d["local_year"].GetInt(); + name = d["name"].GetString(); + url = d["url"].GetString(); + provider = d["provider"].GetString(); + favicon_url = d["favicon_url"].GetString(); + } + + return !error; +} PaymentData::PaymentData(): value(0), @@ -92,6 +134,7 @@ PublisherInfoFilter::PublisherInfoFilter() : min_duration(0), reconcile_stamp(0), non_verified(true) {} + PublisherInfoFilter::PublisherInfoFilter(const PublisherInfoFilter& filter) : id(filter.id), category(filter.category), @@ -103,8 +146,54 @@ PublisherInfoFilter::PublisherInfoFilter(const PublisherInfoFilter& filter) : min_duration(filter.min_duration), reconcile_stamp(filter.reconcile_stamp), non_verified(filter.non_verified) {} + PublisherInfoFilter::~PublisherInfoFilter() {} +const std::string PublisherInfoFilter::ToJson() const { + std::string json; + braveledger_bat_helper::saveToJsonString(*this, json); + return json; +} + +bool PublisherInfoFilter::loadFromJson(const std::string& json) { + rapidjson::Document d; + d.Parse(json.c_str()); + + // has parser errors or wrong types + bool error = d.HasParseError(); + if (false == error) { + error = !(d.HasMember("id") && d["id"].IsString() && + d.HasMember("category") && d["category"].IsInt() && + d.HasMember("month") && d["month"].IsInt() && + d.HasMember("year") && d["year"].IsInt() && + d.HasMember("excluded") && d["excluded"].IsInt() && + d.HasMember("percent") && d["percent"].IsUint() && + d.HasMember("order_by") && d["order_by"].IsObject() && + d.HasMember("min_duration") && d["min_duration"].IsUint64() && + d.HasMember("reconcile_stamp") && d["reconcile_stamp"].IsUint64() && + d.HasMember("non_verified") && d["non_verified"].IsBool()); + } + + if (false == error) { + id = d["id"].GetString(); + category = d["category"].GetInt(); + month = (PUBLISHER_MONTH)d["month"].GetInt(); + year = d["year"].GetInt(); + excluded = (PUBLISHER_EXCLUDE_FILTER)d["excluded"].GetInt(); + percent = d["percent"].GetUint(); + min_duration = d["min_duration"].GetUint64(); + reconcile_stamp = d["reconcile_stamp"].GetUint64(); + non_verified = d["non_verified"].GetBool(); + + for (const auto& i : d["order_by"].GetObject()) { + order_by.push_back(std::make_pair(i.name.GetString(), + i.value.GetBool())); + } + } + + return !error; +} + PublisherBanner::PublisherBanner() {} PublisherBanner::PublisherBanner(const PublisherBanner& info) : @@ -121,6 +210,52 @@ PublisherBanner::PublisherBanner(const PublisherBanner& info) : PublisherBanner::~PublisherBanner() {} +const std::string PublisherBanner::ToJson() const { + std::string json; + braveledger_bat_helper::saveToJsonString(*this, json); + return json; +} + +bool PublisherBanner::loadFromJson(const std::string& json) { + rapidjson::Document d; + d.Parse(json.c_str()); + // has parser errors or wrong types + bool error = d.HasParseError(); + + if (false == error) { + error = !(d.HasMember("publisher_key") && d["publisher_key"].IsString() && + d.HasMember("title") && d["title"].IsString() && + d.HasMember("name") && d["name"].IsString() && + d.HasMember("description") && d["description"].IsString() && + d.HasMember("background") && d["name"].IsString() && + d.HasMember("logo") && d["logo"].IsString() && + d.HasMember("amounts") && d["amounts"].IsArray() && + d.HasMember("social") && d["social"].IsObject() && + d.HasMember("verified") && d["verified"].IsBool()); + } + + if (false == error) { + publisher_key = d["publisher_key"].GetString(); + title = d["title"].GetString(); + name = d["name"].GetString(); + description = d["description"].GetString(); + background = d["background"].GetString(); + logo = d["logo"].GetString(); + verified = d["verified"].GetBool(); + + for (const auto& amount : d["amounts"].GetArray()) { + amounts.push_back(amount.GetInt()); + } + + for (const auto& i : d["social"].GetObject()) { + social.insert(std::make_pair(i.name.GetString(), + i.value.GetString())); + } + } + + return !error; +} + PublisherInfo::PublisherInfo() : duration(0u), score(.0), @@ -180,15 +315,105 @@ PublisherInfo::PublisherInfo(const PublisherInfo& info) : PublisherInfo::~PublisherInfo() {} bool PublisherInfo::operator<(const PublisherInfo& rhs) const { - return score > rhs.score; - } + return score > rhs.score; +} bool PublisherInfo::is_valid() const { return !id.empty() && year > 0 && month != PUBLISHER_MONTH::ANY; } +const std::string PublisherInfo::ToJson() const { + std::string json; + braveledger_bat_helper::saveToJsonString(*this, json); + return json; +} + +bool PublisherInfo::loadFromJson(const std::string& json) { + rapidjson::Document d; + d.Parse(json.c_str()); + // has parser errors or wrong types + bool error = d.HasParseError(); + + if (false == error) { + error = !(d.HasMember("id") && d["id"].IsString() && + d.HasMember("duration") && d["duration"].IsUint64() && + d.HasMember("score") && d["score"].IsDouble() && + d.HasMember("visits") && d["visits"].IsUint() && + d.HasMember("percent") && d["percent"].IsUint() && + d.HasMember("weight") && d["weight"].IsDouble() && + d.HasMember("excluded") && d["excluded"].IsInt() && + d.HasMember("category") && d["category"].IsInt() && + d.HasMember("month") && d["month"].IsInt() && + d.HasMember("year") && d["year"].IsInt() && + d.HasMember("reconcile_stamp") && d["reconcile_stamp"].IsUint64() && + d.HasMember("verified") && d["verified"].IsBool() && + d.HasMember("name") && d["name"].IsString() && + d.HasMember("url") && d["url"].IsString() && + d.HasMember("provider") && d["provider"].IsString() && + d.HasMember("favicon_url") && d["favicon_url"].IsString() && + d.HasMember("contributions") && d["contributions"].IsArray()); + } + + if (false == error) { + id = d["id"].GetString(); + duration = d["duration"].GetUint64(); + score = d["score"].GetDouble(); + visits = d["visits"].GetUint(); + percent = d["percent"].GetUint(); + weight = d["weight"].GetDouble(); + excluded = (PUBLISHER_EXCLUDE)d["excluded"].GetInt(); + category = (PUBLISHER_CATEGORY)d["category"].GetInt(); + month = (PUBLISHER_MONTH)d["month"].GetInt(); + year = d["year"].GetInt(); + reconcile_stamp = d["reconcile_stamp"].GetUint64(); + verified = d["verified"].GetBool(); + name = d["name"].GetString(); + url = d["url"].GetString(); + provider = d["provider"].GetString(); + favicon_url = d["favicon_url"].GetString(); + + for (const auto& contribution : d["contributions"].GetArray()) { + rapidjson::StringBuffer sb; + rapidjson::Writer writer(sb); + contribution.Accept(writer); + + ContributionInfo info; + info.loadFromJson(sb.GetString()); + contributions.push_back(info); + } + } + + return !error; +} + const PublisherInfo invalid("", PUBLISHER_MONTH::ANY, -1); +const std::string ContributionInfo::ToJson() const { + std::string json; + braveledger_bat_helper::saveToJsonString(*this, json); + return json; +} + +bool ContributionInfo::loadFromJson(const std::string& json) { + rapidjson::Document d; + d.Parse(json.c_str()); + + // has parser errors or wrong types + bool error = d.HasParseError(); + if (false == error) { + error = !(d.HasMember("publisher") && d["publisher"].IsString() && + d.HasMember("value") && d["value"].IsDouble() && + d.HasMember("date") && d["date"].IsUint64()); + } + + if (false == error) { + publisher = d["publisher"].GetString(); + value = d["value"].GetDouble(); + date = d["date"].GetUint64(); + } + + return !error; +} TwitchEventInfo::TwitchEventInfo() {} @@ -205,12 +430,13 @@ ledger::Ledger* Ledger::CreateInstance(LedgerClient* client) { return new bat_ledger::LedgerImpl(client); } -WalletInfo::WalletInfo () : balance_(0), parameters_days_(0) {} +WalletInfo::WalletInfo () : balance_(0), fee_amount_(0), parameters_days_(0) {} WalletInfo::~WalletInfo () {} WalletInfo::WalletInfo (const ledger::WalletInfo &info) { altcurrency_ = info.altcurrency_; probi_ = info.probi_; balance_ = info.balance_; + fee_amount_ = info.fee_amount_; rates_ = info.rates_; parameters_choices_ = info.parameters_choices_; parameters_range_ = info.parameters_range_; @@ -218,6 +444,65 @@ WalletInfo::WalletInfo (const ledger::WalletInfo &info) { grants_ = info.grants_; } +const std::string WalletInfo::ToJson() const { + std::string json; + braveledger_bat_helper::saveToJsonString(*this, json); + return json; +} + +bool WalletInfo::loadFromJson(const std::string& json) { + rapidjson::Document d; + d.Parse(json.c_str()); + + // has parser errors or wrong types + bool error = d.HasParseError(); + if (false == error) { + error = !(d.HasMember("altcurrency_") && d["altcurrency_"].IsString() && + d.HasMember("probi_") && d["probi_"].IsString() && + d.HasMember("balance_") && d["balance_"].IsDouble() && + d.HasMember("fee_amount_") && d["fee_amount_"].IsDouble() && + d.HasMember("rates_") && d["rates_"].IsObject() && + d.HasMember("parameters_choices_") && + d["parameters_choices_"].IsArray() && + d.HasMember("parameters_range_") && d["parameters_range_"].IsArray() && + d.HasMember("parameters_days_") && d["parameters_days_"].IsUint() && + d.HasMember("grants_") && d["grants_"].IsArray()); + } + + if (false == error) { + altcurrency_ = d["altcurrency_"].GetString(); + probi_ = d["probi_"].GetString(); + balance_ = d["balance_"].GetDouble(); + fee_amount_ = d["fee_amount_"].GetDouble(); + parameters_days_ = d["parameters_days_"].GetUint(); + + for (const auto& rate : d["rates_"].GetObject()) { + rates_.insert(std::make_pair(rate.name.GetString(), + rate.value.GetDouble())); + } + + for (const auto& parameters_choice : d["parameters_choices_"].GetArray()) { + parameters_choices_.push_back(parameters_choice.GetDouble()); + } + + for (const auto& parameters_choice : d["parameters_range_"].GetArray()) { + parameters_range_.push_back(parameters_choice.GetDouble()); + } + + for (const auto& g : d["grants_"].GetArray()) { + rapidjson::StringBuffer sb; + rapidjson::Writer writer(sb); + g.Accept(writer); + + Grant grant; + grant.loadFromJson(sb.GetString()); + grants_.push_back(grant); + } + } + + return !error; +} + Grant::Grant () {} Grant::~Grant () {} Grant::Grant (const ledger::Grant &properties) { @@ -227,6 +512,36 @@ Grant::Grant (const ledger::Grant &properties) { altcurrency = properties.altcurrency; } +const std::string Grant::ToJson() const { + std::string json; + braveledger_bat_helper::saveToJsonString(*this, json); + return json; +} + +bool Grant::loadFromJson(const std::string& json) { + rapidjson::Document d; + d.Parse(json.c_str()); + + // has parser errors or wrong types + bool error = d.HasParseError(); + + if (false == error) { + error = !(d.HasMember("altcurrency") && d["altcurrency"].IsString() && + d.HasMember("probi") && d["probi"].IsString() && + d.HasMember("promotionId") && d["promotionId"].IsString() && + d.HasMember("expiryTime") && d["expiryTime"].IsUint64()); + } + + if (false == error) { + altcurrency = d["altcurrency"].GetString(); + probi = d["probi"].GetString(); + promotionId = d["promotionId"].GetString(); + expiryTime = d["expiryTime"].GetUint64(); + } + + return !error; +} + BalanceReportInfo::BalanceReportInfo(): opening_balance_("0"), closing_balance_("0"), @@ -251,6 +566,99 @@ BalanceReportInfo::BalanceReportInfo(const BalanceReportInfo& state) { BalanceReportInfo::~BalanceReportInfo() {} +const std::string BalanceReportInfo::ToJson() const { + std::string json; + braveledger_bat_helper::saveToJsonString(*this, json); + return json; +} + +bool BalanceReportInfo::loadFromJson(const std::string& json) { + rapidjson::Document d; + d.Parse(json.c_str()); + + // has parser errors or wrong types + bool error = d.HasParseError(); + + if (false == error) { + error = !( + d.HasMember("opening_balance_") && d["opening_balance_"].IsString() && + d.HasMember("closing_balance_") && d["closing_balance_"].IsString() && + d.HasMember("deposits_") && d["deposits_"].IsString() && + d.HasMember("grants_") && d["grants_"].IsString() && + d.HasMember("earning_from_ads_") && + d["earning_from_ads_"].IsString() && + d.HasMember("auto_contribute_") && d["auto_contribute_"].IsString() && + d.HasMember("recurring_donation_") && + d["recurring_donation_"].IsString() && + d.HasMember("one_time_donation_") && + d["one_time_donation_"].IsString() && + d.HasMember("total_") && d["total_"].IsString()); + } + + if (false == error) { + opening_balance_ = d["opening_balance_"].GetString(); + closing_balance_ = d["closing_balance_"].GetString(); + deposits_ = d["deposits_"].GetString(); + grants_ = d["grants_"].GetString(); + earning_from_ads_ = d["earning_from_ads_"].GetString(); + auto_contribute_ = d["auto_contribute_"].GetString(); + recurring_donation_ = d["recurring_donation_"].GetString(); + one_time_donation_ = d["one_time_donation_"].GetString(); + total_ = d["total_"].GetString(); + } + + return !error; +} + +AutoContributeProps::AutoContributeProps() + : enabled_contribute(false), + contribution_min_time(0), + contribution_min_visits(0), + contribution_non_verified(false), + contribution_videos(false), + reconcile_stamp(0) { } + +AutoContributeProps::~AutoContributeProps() { } + +const std::string AutoContributeProps::ToJson() const { + std::string json; + braveledger_bat_helper::saveToJsonString(*this, json); + return json; +} + +bool AutoContributeProps::loadFromJson(const std::string& json) { + rapidjson::Document d; + d.Parse(json.c_str()); + + // has parser errors or wrong types + bool error = d.HasParseError(); + + if (false == error) { + error = !(d.HasMember("enabled_contribute") && + d["enabled_contribute"].IsBool() && + d.HasMember("contribution_min_time") && + d["contribution_min_time"].IsUint64() && + d.HasMember("contribution_min_visits") && + d["contribution_min_visits"].IsInt() && + d.HasMember("contribution_non_verified") && + d["contribution_non_verified"].IsBool() && + d.HasMember("contribution_videos") && + d["contribution_videos"].IsBool() && + d.HasMember("reconcile_stamp") && d["reconcile_stamp"].IsUint64()); + } + + if (false == error) { + enabled_contribute = d["enabled_contribute"].GetBool(); + contribution_min_time = d["contribution_min_time"].GetUint64(); + contribution_min_visits = d["contribution_min_visits"].GetInt(); + contribution_non_verified = d["contribution_non_verified"].GetBool(); + contribution_videos = d["contribution_videos"].GetBool(); + reconcile_stamp = d["reconcile_stamp"].GetUint64(); + } + + return !error; +} + bool Ledger::IsMediaLink(const std::string& url, const std::string& first_party_url, const std::string& referrer) { return braveledger_bat_get_media::BatGetMedia::GetLinkType(url, first_party_url, referrer) == TWITCH_MEDIA_TYPE; } diff --git a/vendor/bat-native-ledger/src/bat_client.cc b/vendor/bat-native-ledger/src/bat_client.cc index eeb7c3e1ebfc..10fe0ec1aec9 100644 --- a/vendor/bat-native-ledger/src/bat_client.cc +++ b/vendor/bat-native-ledger/src/bat_client.cc @@ -28,15 +28,12 @@ BatClient::~BatClient() { } void BatClient::registerPersona() { - auto request_id = ledger_->LoadURL(braveledger_bat_helper::buildURL(REGISTER_PERSONA, PREFIX_V2), + auto callback = std::bind(&BatClient::requestCredentialsCallback, this, + _1, _2, _3); + ledger_->LoadURL( + braveledger_bat_helper::buildURL(REGISTER_PERSONA, PREFIX_V2), std::vector(), "", "", - ledger::URL_METHOD::GET, &handler_); - handler_.AddRequestHandler(std::move(request_id), - std::bind(&BatClient::requestCredentialsCallback, - this, - _1, - _2, - _3)); + ledger::URL_METHOD::GET, callback); } void BatClient::requestCredentialsCallback(bool result, const std::string& response, const std::map& headers) { @@ -109,16 +106,12 @@ void BatClient::requestCredentialsCallback(bool result, const std::string& respo registerHeaders.push_back("Content-Type: application/json; charset=UTF-8"); // We should use simple callbacks on iOS - auto request_id = ledger_->LoadURL( + auto callback = std::bind(&BatClient::registerPersonaCallback, this, + _1, _2, _3); + ledger_->LoadURL( braveledger_bat_helper::buildURL((std::string)REGISTER_PERSONA + "/" + ledger_->GetUserId(), PREFIX_V2), registerHeaders, payloadStringify, "application/json; charset=utf-8", - ledger::URL_METHOD::POST, &handler_); - handler_.AddRequestHandler(std::move(request_id), - std::bind(&BatClient::registerPersonaCallback, - this, - _1, - _2, - _3)); + ledger::URL_METHOD::POST, callback); } std::string BatClient::getAnonizeProof(const std::string& registrarVK, const std::string& id, std::string& preFlight) { @@ -195,20 +188,15 @@ void BatClient::getWalletProperties() { } std::string path = (std::string)WALLET_PROPERTIES + payment_id + WALLET_PROPERTIES_END; - auto request_id = ledger_->LoadURL( - braveledger_bat_helper::buildURL(path, PREFIX_V2, braveledger_bat_helper::SERVER_TYPES::BALANCE), - std::vector(), - "", - "", - ledger::URL_METHOD::GET, - &handler_); - - handler_.AddRequestHandler(std::move(request_id), - std::bind(&BatClient::walletPropertiesCallback, - this, - _1, - _2, - _3)); + auto callback = std::bind(&BatClient::walletPropertiesCallback, this, + _1, _2, _3); + ledger_->LoadURL( + braveledger_bat_helper::buildURL(path, PREFIX_V2, braveledger_bat_helper::SERVER_TYPES::BALANCE), + std::vector(), + "", + "", + ledger::URL_METHOD::GET, + callback); } void BatClient::walletPropertiesCallback(bool success, @@ -312,15 +300,12 @@ void BatClient::continueRecover(int result, size_t *written, std::vectorLoadURL(braveledger_bat_helper::buildURL((std::string)RECOVER_WALLET_PUBLIC_KEY + publicKeyHex, PREFIX_V2), + auto callback = std::bind(&BatClient::recoverWalletPublicKeyCallback, this, + _1, _2, _3); + ledger_->LoadURL(braveledger_bat_helper::buildURL( + (std::string)RECOVER_WALLET_PUBLIC_KEY + publicKeyHex, PREFIX_V2), std::vector(), "", "", - ledger::URL_METHOD::GET, &handler_); - handler_.AddRequestHandler(std::move(request_id), - std::bind(&BatClient::recoverWalletPublicKeyCallback, - this, - _1, - _2, - _3)); + ledger::URL_METHOD::GET, callback); } @@ -337,15 +322,11 @@ void BatClient::recoverWalletPublicKeyCallback(bool result, std::string recoveryId; braveledger_bat_helper::getJSONValue("paymentId", response, recoveryId); - auto request_id = ledger_->LoadURL(braveledger_bat_helper::buildURL((std::string)WALLET_PROPERTIES + recoveryId, PREFIX_V2), - std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); - handler_.AddRequestHandler(std::move(request_id), - std::bind(&BatClient::recoverWalletCallback, - this, - _1, - _2, - _3, - recoveryId)); + auto callback = std::bind(&BatClient::recoverWalletCallback, this, + _1, _2, _3, recoveryId); + ledger_->LoadURL(braveledger_bat_helper::buildURL( + (std::string)WALLET_PROPERTIES + recoveryId, PREFIX_V2), + std::vector(), "", "", ledger::URL_METHOD::GET, callback); } void BatClient::recoverWalletCallback(bool result, @@ -397,14 +378,10 @@ void BatClient::getGrant(const std::string& lang, const std::string& forPaymentI } } - auto request_id = ledger_->LoadURL(braveledger_bat_helper::buildURL((std::string)GET_SET_PROMOTION + arguments, PREFIX_V2), - std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); - handler_.AddRequestHandler(std::move(request_id), - std::bind(&BatClient::getGrantCallback, - this, - _1, - _2, - _3)); + auto callback = std::bind(&BatClient::getGrantCallback, this, _1, _2, _3); + ledger_->LoadURL(braveledger_bat_helper::buildURL( + (std::string)GET_SET_PROMOTION + arguments, PREFIX_V2), + std::vector(), "", "", ledger::URL_METHOD::GET, callback); } void BatClient::getGrantCallback(bool success, @@ -462,14 +439,12 @@ void BatClient::setGrant(const std::string& captchaResponse, const std::string& std::string values[2] = {promoId, captchaResponse}; std::string payload = braveledger_bat_helper::stringify(keys, values, 2); - auto request_id = ledger_->LoadURL(braveledger_bat_helper::buildURL((std::string)GET_SET_PROMOTION + "/" + ledger_->GetPaymentId(), PREFIX_V2), - std::vector(), payload, "application/json; charset=utf-8", ledger::URL_METHOD::PUT, &handler_); - handler_.AddRequestHandler(std::move(request_id), - std::bind(&BatClient::setGrantCallback, - this, - _1, - _2, - _3)); + auto callback = std::bind(&BatClient::setGrantCallback, this, _1, _2, _3); + ledger_->LoadURL(braveledger_bat_helper::buildURL( + (std::string)GET_SET_PROMOTION + "/" + ledger_->GetPaymentId(), + PREFIX_V2), + std::vector(), payload, "application/json; charset=utf-8", + ledger::URL_METHOD::PUT, callback); } void BatClient::setGrantCallback(bool success, @@ -511,15 +486,12 @@ void BatClient::setGrantCallback(bool success, void BatClient::getGrantCaptcha() { std::vector headers; headers.push_back("brave-product:brave-core"); - auto request_id = ledger_->LoadURL(braveledger_bat_helper::buildURL((std::string)GET_PROMOTION_CAPTCHA + ledger_->GetPaymentId(), PREFIX_V2), - headers, "", "", - ledger::URL_METHOD::GET, &handler_); - handler_.AddRequestHandler(std::move(request_id), - std::bind(&BatClient::getGrantCaptchaCallback, - this, - _1, - _2, - _3)); + auto callback = std::bind(&BatClient::getGrantCaptchaCallback, this, + _1, _2, _3); + ledger_->LoadURL(braveledger_bat_helper::buildURL( + (std::string)GET_PROMOTION_CAPTCHA + ledger_->GetPaymentId(), + PREFIX_V2), + headers, "", "", ledger::URL_METHOD::GET, callback); } void BatClient::getGrantCaptchaCallback(bool success, diff --git a/vendor/bat-native-ledger/src/bat_client.h b/vendor/bat-native-ledger/src/bat_client.h index 97c7a61987e7..1fe34a8c136f 100644 --- a/vendor/bat-native-ledger/src/bat_client.h +++ b/vendor/bat-native-ledger/src/bat_client.h @@ -9,11 +9,9 @@ #include #include -#include "bat/ledger/ledger_task_runner.h" -#include "bat/ledger/ledger_url_loader.h" +#include "bat/ledger/ledger_callback_handler.h" #include "bat/ledger/publisher_info.h" #include "bat_helper.h" -#include "url_request_handler.h" namespace bat_ledger { class LedgerImpl; @@ -43,8 +41,8 @@ class BatClient { void continueRecover(int result, size_t *written, std::vector& newSeed); void OnNicewareListLoaded(const std::string& pass_phrase, - ledger::Result result, - const std::string& data); + ledger::Result result, + const std::string& data); private: void getGrantCaptchaCallback(bool result, const std::string& response, @@ -60,8 +58,6 @@ class BatClient { std::string getAnonizeProof(const std::string& registrarVK, const std::string& id, std::string& preFlight); bat_ledger::LedgerImpl* ledger_; // NOT OWNED - - bat_ledger::URLRequestHandler handler_; }; } // namespace braveledger_bat_client diff --git a/vendor/bat-native-ledger/src/bat_contribution.cc b/vendor/bat-native-ledger/src/bat_contribution.cc index 890f0b542f50..c64d6a51a43e 100644 --- a/vendor/bat-native-ledger/src/bat_contribution.cc +++ b/vendor/bat-native-ledger/src/bat_contribution.cc @@ -13,6 +13,8 @@ #include "ledger_impl.h" #include "rapidjson_bat_helper.h" +using namespace std::placeholders; + namespace braveledger_bat_contribution { static bool winners_votes_compare( @@ -99,11 +101,8 @@ void BatContribution::ReconcilePublisherList( void BatContribution::OnTimerReconcile() { ledger_->GetRecurringDonations( - std::bind(&BatContribution::ReconcilePublisherList, - this, - ledger::PUBLISHER_CATEGORY::RECURRING_DONATION, - std::placeholders::_1, - std::placeholders::_2)); + std::bind(&BatContribution::ReconcilePublisherList, this, + ledger::PUBLISHER_CATEGORY::RECURRING_DONATION, _1, _2)); } void BatContribution::StartAutoContribute() { @@ -124,8 +123,8 @@ void BatContribution::StartAutoContribute() { std::bind(&BatContribution::ReconcilePublisherList, this, ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - std::placeholders::_1, - std::placeholders::_2)); + _1, + _2)); } void BatContribution::StartReconcile( @@ -248,22 +247,17 @@ void BatContribution::StartReconcile( void BatContribution::Reconcile(const std::string& viewing_id) { ledger_->AddReconcileStep(viewing_id, braveledger_bat_helper::ContributionRetry::STEP_RECONCILE); - std::string url = braveledger_bat_helper::buildURL( + std::string url = braveledger_bat_helper::buildURL( (std::string)RECONCILE_CONTRIBUTION + ledger_->GetUserId(), PREFIX_V2); - auto request_id = ledger_->LoadURL(url, + + auto callback = std::bind(&BatContribution::ReconcileCallback, this, + viewing_id, _1, _2, _3); + ledger_->LoadURL(url, std::vector(), "", "", ledger::URL_METHOD::GET, - &handler_); - - handler_.AddRequestHandler(std::move(request_id), - std::bind(&BatContribution::ReconcileCallback, - this, - viewing_id, - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3)); + callback); } void BatContribution::ReconcileCallback( @@ -321,21 +315,15 @@ void BatContribution::CurrentReconcile(const std::string& viewing_id) { "&altcurrency=" + currency; - auto request_id = ledger_->LoadURL( + auto callback =std::bind(&BatContribution::CurrentReconcileCallback, this, + viewing_id, _1, _2, _3); + ledger_->LoadURL( braveledger_bat_helper::buildURL(path, PREFIX_V2), std::vector(), "", "", ledger::URL_METHOD::GET, - &handler_); - handler_.AddRequestHandler(std::move(request_id), - std::bind( - &BatContribution::CurrentReconcileCallback, - this, - viewing_id, - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3)); + callback); } void BatContribution::CurrentReconcileCallback( @@ -442,21 +430,15 @@ void BatContribution::ReconcilePayload(const std::string& viewing_id) { wallet_header.push_back("Content-Type: application/json; charset=UTF-8"); std::string path = (std::string)WALLET_PROPERTIES + ledger_->GetPaymentId(); - auto request_id = ledger_->LoadURL( + auto callback = std::bind(&BatContribution::ReconcilePayloadCallback, this, + viewing_id, _1, _2, _3); + ledger_->LoadURL( braveledger_bat_helper::buildURL(path, PREFIX_V2), wallet_header, payload_stringify, "application/json; charset=utf-8", ledger::URL_METHOD::PUT, - &handler_); - handler_.AddRequestHandler( - std::move(request_id), - std::bind(&BatContribution::ReconcilePayloadCallback, - this, - viewing_id, - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3)); + callback); } void BatContribution::ReconcilePayloadCallback( @@ -497,22 +479,16 @@ void BatContribution::ReconcilePayloadCallback( void BatContribution::RegisterViewing(const std::string& viewing_id) { ledger_->AddReconcileStep(viewing_id, braveledger_bat_helper::ContributionRetry::STEP_REGISTER); - auto request_id = ledger_->LoadURL( + auto callback = std::bind(&BatContribution::RegisterViewingCallback, this, + viewing_id, _1, _2, _3); + ledger_->LoadURL( braveledger_bat_helper::buildURL( - (std::string)REGISTER_VIEWING, PREFIX_V2), + (std::string)REGISTER_VIEWING, PREFIX_V2), std::vector(), "", "", ledger::URL_METHOD::GET, - &handler_); - handler_.AddRequestHandler(std::move(request_id), - std::bind( - &BatContribution::RegisterViewingCallback, - this, - viewing_id, - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3)); + callback); } void BatContribution::RegisterViewingCallback( @@ -577,20 +553,14 @@ void BatContribution::ViewingCredentials(const std::string& viewing_id) { reconcile.anonizeViewingId_, PREFIX_V2); - auto request_id = ledger_->LoadURL(url, - std::vector(), - proof_stringified, - "application/json; charset=utf-8", - ledger::URL_METHOD::POST, - &handler_); - handler_.AddRequestHandler(std::move(request_id), - std::bind( - &BatContribution::ViewingCredentialsCallback, - this, - viewing_id, - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3)); + auto callback = std::bind(&BatContribution::ViewingCredentialsCallback, this, + viewing_id, _1, _2, _3); + ledger_->LoadURL(url, + std::vector(), + proof_stringified, + "application/json; charset=utf-8", + ledger::URL_METHOD::POST, + callback); } void BatContribution::ViewingCredentialsCallback( @@ -939,19 +909,14 @@ void BatContribution::PrepareBatch( "/" + transaction.anonizeViewingId_, PREFIX_V2); - auto request_id = ledger_->LoadURL(url, - std::vector(), - "", - "", - ledger::URL_METHOD::GET, - &handler_); - - handler_.AddRequestHandler(std::move(request_id), - std::bind(&BatContribution::PrepareBatchCallback, - this, - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3)); + auto callback = std::bind(&BatContribution::PrepareBatchCallback, this, + _1, _2, _3); + ledger_->LoadURL(url, + std::vector(), + "", + "", + ledger::URL_METHOD::GET, + callback); } void BatContribution::PrepareBatchCallback( @@ -1035,16 +1000,11 @@ void BatContribution::Proof() { } } - ledger_->RunIOTask(std::bind(&BatContribution::ProofBatch, - this, - batch_proof, - std::placeholders::_1)); - + ProofBatch(batch_proof); } void BatContribution::ProofBatch( - const braveledger_bat_helper::BathProofs& batch_proof, - ledger::LedgerTaskRunner::CallerThreadCallback callback) { + const braveledger_bat_helper::BathProofs& batch_proof) { std::vector proofs; for (size_t i = 0; i < batch_proof.size(); i++) { @@ -1096,12 +1056,6 @@ void BatContribution::ProofBatch( proofs.push_back(annon_proof); } - callback(std::bind(&BatContribution::ProofBatchCallback, this, batch_proof, proofs)); -} - -void BatContribution::ProofBatchCallback( - const braveledger_bat_helper::BathProofs& batch_proof, - const std::vector& proofs) { braveledger_bat_helper::Ballots ballots = ledger_->GetBallots(); for (size_t i = 0; i < batch_proof.size(); i++) { @@ -1216,20 +1170,14 @@ void BatContribution::VoteBatch() { std::string url = braveledger_bat_helper::buildURL( (std::string)SURVEYOR_BATCH_VOTING , PREFIX_V2); - - auto request_id = ledger_->LoadURL(url, - std::vector(), - payload, - "application/json; charset=utf-8", - ledger::URL_METHOD::POST, - &handler_); - handler_.AddRequestHandler(std::move(request_id), - std::bind(&BatContribution::VoteBatchCallback, - this, - batch_votes.publisher_, - std::placeholders::_1, - std::placeholders::_2, - std::placeholders::_3)); + auto callback = std::bind(&BatContribution::VoteBatchCallback, this, + batch_votes.publisher_, _1, _2, _3); + ledger_->LoadURL(url, + std::vector(), + payload, + "application/json; charset=utf-8", + ledger::URL_METHOD::POST, + callback); } void BatContribution::VoteBatchCallback( @@ -1558,4 +1506,4 @@ void BatContribution::DoRetry(const std::string& viewing_id) { } } -} // namespace braveledger_bat_contribution \ No newline at end of file +} // namespace braveledger_bat_contribution diff --git a/vendor/bat-native-ledger/src/bat_contribution.h b/vendor/bat-native-ledger/src/bat_contribution.h index 2a3bb95aac11..4619604c688e 100644 --- a/vendor/bat-native-ledger/src/bat_contribution.h +++ b/vendor/bat-native-ledger/src/bat_contribution.h @@ -9,7 +9,6 @@ #include "bat/ledger/ledger.h" #include "bat_helper.h" -#include "url_request_handler.h" // Contribution has two big phases. PHASE 1 is starting the contribution, // getting surveyors and transferring BAT from the wallet. @@ -62,13 +61,12 @@ // 5. PrepareBatch // 6. PrepareBatchCallback // 7. ProofBatch -// 8. ProofBatchCallback -// 9. SetTimer -// 10. PrepareVoteBatch -// 11. SetTimer -// 12. VoteBatch -// 13. VoteBatchCallback -// 14. SetTimer - we set timer until the whole batch is processed +// 8. SetTimer +// 9. PrepareVoteBatch +// 10. SetTimer +// 11. VoteBatch +// 12. VoteBatchCallback +// 13. SetTimer - we set timer until the whole batch is processed namespace bat_ledger { class LedgerImpl; @@ -224,12 +222,7 @@ class BatContribution { void Proof(); void ProofBatch( - const braveledger_bat_helper::BathProofs& batch_proof, - ledger::LedgerTaskRunner::CallerThreadCallback callback); - - void ProofBatchCallback( - const braveledger_bat_helper::BathProofs& batch_proof, - const std::vector& proofs); + const braveledger_bat_helper::BathProofs& batch_proof); void PrepareVoteBatch(); @@ -257,7 +250,6 @@ class BatContribution { void DoRetry(const std::string& viewing_id); bat_ledger::LedgerImpl* ledger_; // NOT OWNED - bat_ledger::URLRequestHandler handler_; uint32_t last_reconcile_timer_id_; uint32_t last_prepare_vote_batch_timer_id_; uint32_t last_vote_batch_timer_id_; diff --git a/vendor/bat-native-ledger/src/bat_get_media.cc b/vendor/bat-native-ledger/src/bat_get_media.cc index 94b0da2f3d92..344fb5704b00 100644 --- a/vendor/bat-native-ledger/src/bat_get_media.cc +++ b/vendor/bat-native-ledger/src/bat_get_media.cc @@ -113,20 +113,14 @@ void BatGetMedia::getPublisherInfoDataCallback(const std::string& mediaId, if (!publisher_info.get()) { std::string mediaURL = getMediaURL(mediaId, providerName); if (providerName == YOUTUBE_MEDIA_TYPE) { - auto request = ledger_->LoadURL((std::string)YOUTUBE_PROVIDER_URL + "?format=json&url=" + ledger_->URIEncode(mediaURL), - std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); - handler_.AddRequestHandler(std::move(request), - std::bind(&BatGetMedia::getPublisherFromMediaPropsCallback, - this, - duration, - media_key, - providerName, - mediaURL, - visit_data, - window_id, - _1, - _2, - _3)); + auto callback = std::bind( + &BatGetMedia::getPublisherFromMediaPropsCallback, this, + duration, media_key, providerName, mediaURL, visit_data, window_id, + _1, _2, _3); + ledger_->LoadURL( + (std::string)YOUTUBE_PROVIDER_URL + "?format=json&url=" + + ledger_->URIEncode(mediaURL), + std::vector(), "", "", ledger::URL_METHOD::GET, callback); } else if (providerName == TWITCH_MEDIA_TYPE) { if (mediaId.empty()) { return; @@ -167,20 +161,16 @@ void BatGetMedia::getPublisherInfoDataCallback(const std::string& mediaId, std::string oembed_url = (std::string)TWITCH_VOD_URL + media_props[media_props.size() - 1]; updated_visit_data.name = twitchMediaID; updated_visit_data.url = mediaUrl + "/videos"; - auto request = ledger_->LoadURL((std::string)TWITCH_PROVIDER_URL + "?json&url=" + ledger_->URIEncode(oembed_url), - std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); - handler_.AddRequestHandler(std::move(request), - std::bind(&BatGetMedia::getPublisherFromMediaPropsCallback, - this, - realDuration, - media_key, - providerName, - mediaUrl, - updated_visit_data, - window_id, - _1, - _2, - _3)); + + auto callback = std::bind( + &BatGetMedia::getPublisherFromMediaPropsCallback, this, + realDuration, media_key, providerName, mediaUrl, + updated_visit_data, window_id, _1, _2, _3); + ledger_->LoadURL( + (std::string)TWITCH_PROVIDER_URL + "?json&url=" + + ledger_->URIEncode(oembed_url), + std::vector(), "", "", + ledger::URL_METHOD::GET, callback); return; } @@ -363,22 +353,11 @@ void BatGetMedia::getPublisherFromMediaPropsCallback(const uint64_t& duration, std::string publisherName; braveledger_bat_helper::getJSONValue("author_name", response, publisherName); - auto request = ledger_->LoadURL(publisherURL, - std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); - handler_.AddRequestHandler(std::move(request), - std::bind(&BatGetMedia::getPublisherInfoCallback, - this, - duration, - media_key, - providerName, - mediaURL, - publisherURL, - publisherName, - visit_data, - window_id, - _1, - _2, - _3)); + auto callback = std::bind(&BatGetMedia::getPublisherInfoCallback, this, + duration, media_key, providerName, mediaURL, publisherURL, + publisherName, visit_data, window_id, _1, _2, _3); + ledger_->LoadURL(publisherURL, + std::vector(), "", "", ledger::URL_METHOD::GET, callback); return; } @@ -689,11 +668,9 @@ void BatGetMedia::onFetchPublisherFromDBResponse(ledger::Result result, } void BatGetMedia::fetchDataFromUrl(const std::string& url, FetchDataFromUrlCallback callback) { - auto request = ledger_->LoadURL(url, + ledger_->LoadURL(url, std::vector(), "", "", - ledger::URL_METHOD::GET, &handler_); - - handler_.AddRequestHandler(std::move(request), callback); + ledger::URL_METHOD::GET, callback); } void BatGetMedia::onGetChannelIdFromUserPage(uint64_t windowId, diff --git a/vendor/bat-native-ledger/src/bat_get_media.h b/vendor/bat-native-ledger/src/bat_get_media.h index cad2d7194c91..0d51411b0c64 100644 --- a/vendor/bat-native-ledger/src/bat_get_media.h +++ b/vendor/bat-native-ledger/src/bat_get_media.h @@ -11,7 +11,6 @@ #include "bat/ledger/ledger.h" #include "bat_helper.h" -#include "url_request_handler.h" namespace bat_ledger { class LedgerImpl; @@ -204,8 +203,6 @@ class BatGetMedia { bat_ledger::LedgerImpl* ledger_; // NOT OWNED - bat_ledger::URLRequestHandler handler_; - std::map twitchEvents; }; diff --git a/vendor/bat-native-ledger/src/bat_helper.cc b/vendor/bat-native-ledger/src/bat_helper.cc index 7d16ab9960d9..0a8ab7c2007e 100644 --- a/vendor/bat-native-ledger/src/bat_helper.cc +++ b/vendor/bat-native-ledger/src/bat_helper.cc @@ -2400,4 +2400,327 @@ static bool ignore_ = false; return dist(eng); } + void saveToJson(JsonWriter& writer, const ledger::VisitData& visitData) { + writer.StartObject(); + + writer.String("tld"); + writer.String(visitData.tld.c_str()); + + writer.String("domain"); + writer.String(visitData.domain.c_str()); + + writer.String("path"); + writer.String(visitData.path.c_str()); + + writer.String("tab_id"); + writer.Uint(visitData.tab_id); + + writer.String("local_month"); + writer.Int(visitData.local_month); + + writer.String("local_year"); + writer.Int(visitData.local_year); + + writer.String("name"); + writer.String(visitData.name.c_str()); + + writer.String("url"); + writer.String(visitData.url.c_str()); + + writer.String("provider"); + writer.String(visitData.provider.c_str()); + + writer.String("favicon_url"); + writer.String(visitData.favicon_url.c_str()); + + writer.EndObject(); + } + + void saveToJson(JsonWriter& writer, const ledger::BalanceReportInfo& info) { + writer.StartObject(); + + writer.String("opening_balance_"); + writer.String(info.opening_balance_.c_str()); + + writer.String("closing_balance_"); + writer.String(info.closing_balance_.c_str()); + + writer.String("deposits_"); + writer.String(info.deposits_.c_str()); + + writer.String("grants_"); + writer.String(info.grants_.c_str()); + + writer.String("earning_from_ads_"); + writer.String(info.earning_from_ads_.c_str()); + + writer.String("auto_contribute_"); + writer.String(info.auto_contribute_.c_str()); + + writer.String("recurring_donation_"); + writer.String(info.recurring_donation_.c_str()); + + writer.String("one_time_donation_"); + writer.String(info.one_time_donation_.c_str()); + + writer.String("total_"); + writer.String(info.total_.c_str()); + + writer.EndObject(); + } + + void saveToJson(JsonWriter& writer, const ledger::Grant& grant) { + writer.StartObject(); + + writer.String("altcurrency"); + writer.String(grant.altcurrency.c_str()); + + writer.String("probi"); + writer.String(grant.probi.c_str()); + + writer.String("promotionId"); + writer.String(grant.promotionId.c_str()); + + writer.String("expiryTime"); + writer.Uint64(grant.expiryTime); + + writer.EndObject(); + } + + void saveToJson(JsonWriter & writer, const ledger::PublisherInfo& info) { + writer.StartObject(); + + writer.String("id"); + writer.String(info.id.c_str()); + + writer.String("duration"); + writer.Uint64(info.duration); + + writer.String("score"); + writer.Double(info.score); + + writer.String("visits"); + writer.Uint(info.visits); + + writer.String("percent"); + writer.Uint(info.percent); + + writer.String("weight"); + writer.Double(info.weight); + + writer.String("excluded"); + writer.Int(info.excluded); + + writer.String("category"); + writer.Int(info.category); + + writer.String("month"); + writer.Int(info.month); + + writer.String("year"); + writer.Int(info.year); + + writer.String("reconcile_stamp"); + writer.Uint64(info.reconcile_stamp); + + writer.String("verified"); + writer.Bool(info.verified); + + writer.String("name"); + writer.String(info.name.c_str()); + + writer.String("url"); + writer.String(info.url.c_str()); + + writer.String("provider"); + writer.String(info.provider.c_str()); + + writer.String("favicon_url"); + writer.String(info.favicon_url.c_str()); + + writer.String("contributions"); + writer.StartArray(); + for (auto & contribution : info.contributions) { + saveToJson(writer, contribution); + } + writer.EndArray(); + + writer.EndObject(); + } + + void saveToJson(JsonWriter & writer, const ledger::ContributionInfo& info) { + writer.StartObject(); + + writer.String("publisher"); + writer.String(info.publisher.c_str()); + + writer.String("value"); + writer.Double(info.value); + + writer.String("date"); + writer.Uint64(info.date); + + writer.EndObject(); + } + + void saveToJson(JsonWriter & writer, + const ledger::PublisherBanner& banner) { + writer.StartObject(); + + writer.String("publisher_key"); + writer.String(banner.publisher_key.c_str()); + + writer.String("title"); + writer.String(banner.title.c_str()); + + writer.String("name"); + writer.String(banner.name.c_str()); + + writer.String("description"); + writer.String(banner.description.c_str()); + + writer.String("background"); + writer.String(banner.background.c_str()); + + writer.String("logo"); + writer.String(banner.logo.c_str()); + + writer.String("amounts"); + writer.StartArray(); + for (auto & amount : banner.amounts) { + writer.Int(amount); + } + writer.EndArray(); + + writer.String("social"); + writer.StartObject(); + for (auto & i : banner.social) { + writer.String(i.first.c_str()); + writer.String(i.second.c_str()); + } + writer.EndObject(); + + writer.String("verified"); + writer.Bool(banner.verified); + + writer.EndObject(); + } + + void saveToJson(JsonWriter & writer, + const ledger::PublisherInfoFilter& info) { + writer.StartObject(); + + writer.String("id"); + writer.String(info.id.c_str()); + + writer.String("category"); + writer.Int(info.category); + + writer.String("month"); + writer.Int(info.month); + + writer.String("year"); + writer.Int(info.year); + + writer.String("excluded"); + writer.Int(info.excluded); + + writer.String("percent"); + writer.Uint(info.percent); + + writer.String("min_duration"); + writer.Uint64(info.min_duration); + + writer.String("reconcile_stamp"); + writer.Uint64(info.reconcile_stamp); + + writer.String("order_by"); + writer.StartObject(); + for (auto & i : info.order_by) { + writer.String(i.first.c_str()); + writer.Bool(i.second); + } + writer.EndObject(); + + writer.String("non_verified"); + writer.Bool(info.non_verified); + + writer.EndObject(); + } + + void saveToJson(JsonWriter & writer, const ledger::WalletInfo& info) { + writer.StartObject(); + + writer.String("altcurrency_"); + writer.String(info.altcurrency_.c_str()); + + writer.String("probi_"); + writer.String(info.probi_.c_str()); + + writer.String("balance_"); + writer.Double(info.balance_); + + writer.String("fee_amount_"); + writer.Double(info.fee_amount_); + + writer.String("rates_"); + writer.StartObject(); + for (const auto& rate : info.rates_) { + writer.String(rate.first.c_str()); + writer.Double(rate.second); + } + writer.EndObject(); + + writer.String("parameters_choices_"); + writer.StartArray(); + for (const auto& choice : info.parameters_choices_) { + writer.Double(choice); + } + writer.EndArray(); + + writer.String("parameters_range_"); + writer.StartArray(); + for (const auto& range : info.parameters_range_) { + writer.Double(range); + } + writer.EndArray(); + + writer.String("parameters_days_"); + writer.Uint(info.parameters_days_); + + writer.String("grants_"); + writer.StartArray(); + for (const auto& grant : info.grants_) { + saveToJson(writer, grant); + } + writer.EndArray(); + + writer.EndObject(); + } + + void saveToJson(JsonWriter & writer, + const ledger::AutoContributeProps& props) { + writer.StartObject(); + + writer.String("enabled_contribute"); + writer.Bool(props.enabled_contribute); + + writer.String("contribution_min_time"); + writer.Uint64(props.contribution_min_time); + + writer.String("contribution_min_visits"); + writer.Int(props.contribution_min_visits); + + writer.String("contribution_non_verified"); + writer.Bool(props.contribution_non_verified); + + writer.String("contribution_videos"); + writer.Bool(props.contribution_videos); + + writer.String("reconcile_stamp"); + writer.Uint64(props.reconcile_stamp); + + writer.EndObject(); + } + } // namespace braveledger_bat_helper diff --git a/vendor/bat-native-ledger/src/ledger_impl.cc b/vendor/bat-native-ledger/src/ledger_impl.cc index a0cddaa92343..8ecb6a13046e 100644 --- a/vendor/bat-native-ledger/src/ledger_impl.cc +++ b/vendor/bat-native-ledger/src/ledger_impl.cc @@ -8,7 +8,6 @@ #include #include "ledger_impl.h" -#include "ledger_task_runner_impl.h" #include "bat_client.h" #include "bat_contribution.h" @@ -287,20 +286,14 @@ void LedgerImpl::OnWalletInitialized(ledger::Result result) { } } -std::unique_ptr LedgerImpl::LoadURL(const std::string& url, +void LedgerImpl::LoadURL(const std::string& url, const std::vector& headers, const std::string& content, const std::string& contentType, const ledger::URL_METHOD& method, - ledger::LedgerCallbackHandler* handler) { - return ledger_client_->LoadURL( - url, headers, content, contentType, method, handler); -} - -void LedgerImpl::RunIOTask(ledger::LedgerTaskRunner::Task io_task) { - std::unique_ptr task_runner( - new LedgerTaskRunnerImpl(io_task)); - ledger_client_->RunIOTask(std::move(task_runner)); + ledger::LoadURLCallback callback) { + ledger_client_->LoadURL( + url, headers, content, contentType, method, callback); } std::string LedgerImpl::URIEncode(const std::string& value) { @@ -410,6 +403,15 @@ void LedgerImpl::SetAutoContribute(bool enabled) { bat_state_->SetAutoContribute(enabled); } +void LedgerImpl::GetAutoContributeProps(ledger::AutoContributeProps& props) { + props.enabled_contribute = GetAutoContribute(); + props.contribution_min_time = GetPublisherMinVisitTime(); + props.contribution_min_visits = GetPublisherMinVisits(); + props.contribution_non_verified = GetPublisherAllowNonVerified(); + props.contribution_videos = GetPublisherAllowVideos(); + props.reconcile_stamp = GetReconcileStamp(); +} + bool LedgerImpl::GetRewardsMainEnabled() const { return bat_state_->GetRewardsMainEnabled(); } @@ -442,6 +444,15 @@ bool LedgerImpl::GetAutoContribute() const { return bat_state_->GetAutoContribute(); } +std::map LedgerImpl::GetAddresses() { + std::map addresses; + addresses.emplace("BAT", GetBATAddress()); + addresses.emplace("BTC", GetBTCAddress()); + addresses.emplace("ETH", GetETHAddress()); + addresses.emplace("LTC", GetLTCAddress()); + return addresses; +} + const std::string& LedgerImpl::GetBATAddress() const { return bat_state_->GetBATAddress(); } @@ -619,9 +630,10 @@ void LedgerImpl::OnTimer(uint32_t timer_id) { //download the list std::string url = braveledger_bat_helper::buildURL(GET_PUBLISHERS_LIST_V1, "", braveledger_bat_helper::SERVER_TYPES::PUBLISHER); - auto url_loader = LoadURL(url, std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); - handler_.AddRequestHandler(std::move(url_loader), - std::bind(&LedgerImpl::LoadPublishersListCallback,this,_1,_2,_3)); + auto callback = std::bind(&LedgerImpl::LoadPublishersListCallback, this, + _1, _2, _3); + LoadURL(url, std::vector(), "", "", + ledger::URL_METHOD::GET, callback); } else if (timer_id == last_grant_check_timer_id_) { last_grant_check_timer_id_ = 0; FetchGrant(std::string(), std::string()); @@ -1054,4 +1066,8 @@ double LedgerImpl::GetDefaultContributionAmount() { return bat_state_->GetDefaultContributionAmount(); } +bool LedgerImpl::HasSufficientBalanceToReconcile() { + return GetBalance() >= GetContributionAmount(); +} + } // namespace bat_ledger diff --git a/vendor/bat-native-ledger/src/ledger_impl.h b/vendor/bat-native-ledger/src/ledger_impl.h index a45063ec2840..3ae3d21f8880 100644 --- a/vendor/bat-native-ledger/src/ledger_impl.h +++ b/vendor/bat-native-ledger/src/ledger_impl.h @@ -13,10 +13,7 @@ #include "bat/ledger/ledger.h" #include "bat/ledger/ledger_callback_handler.h" #include "bat/ledger/ledger_client.h" -#include "bat/ledger/ledger_url_loader.h" #include "bat_helper.h" -#include "ledger_task_runner_impl.h" -#include "url_request_handler.h" #include "logging.h" namespace braveledger_bat_client { @@ -85,6 +82,7 @@ class LedgerImpl : public ledger::Ledger, int year, const ledger::BalanceReportInfo& report_info) override; + std::map GetAddresses() override; const std::string& GetBATAddress() const override; const std::string& GetBTCAddress() const override; const std::string& GetETHAddress() const override; @@ -102,6 +100,7 @@ class LedgerImpl : public ledger::Ledger, int year, ledger::BalanceReportInfo* report_info) const override; std::map GetAllBalanceReports() const override; + void GetAutoContributeProps(ledger::AutoContributeProps& props) override; void SaveLedgerState(const std::string& data); void SavePublisherState(const std::string& data, @@ -137,16 +136,15 @@ class LedgerImpl : public ledger::Ledger, void OnPublishersListSaved(ledger::Result result) override; - std::unique_ptr LoadURL(const std::string& url, + void LoadURL(const std::string& url, const std::vector& headers, const std::string& content, const std::string& contentType, const ledger::URL_METHOD& method, - ledger::LedgerCallbackHandler* handler); + ledger::LoadURLCallback callback); void OnReconcileComplete(ledger::Result result, const std::string& viewing_id, const std::string& probi = "0"); - void RunIOTask(LedgerTaskRunnerImpl::Task task); std::string URIEncode(const std::string& value) override; void SaveMediaVisit(const std::string& publisher_id, const ledger::VisitData& visit_data, @@ -282,6 +280,7 @@ class LedgerImpl : public ledger::Ledger, const braveledger_bat_helper::CurrentReconciles& GetCurrentReconciles() const; double GetDefaultContributionAmount() override; + bool HasSufficientBalanceToReconcile() override; private: void MakePayment(const ledger::PaymentData& payment_data) override; @@ -341,8 +340,6 @@ class LedgerImpl : public ledger::Ledger, bool initialized_; bool initializing_; - URLRequestHandler handler_; - //ledger::VisitData current_visit_data_; std::map current_pages_; uint64_t last_tab_active_time_; diff --git a/vendor/bat-native-ledger/src/ledger_task_runner_impl.cc b/vendor/bat-native-ledger/src/ledger_task_runner_impl.cc deleted file mode 100644 index b4fb77f0691b..000000000000 --- a/vendor/bat-native-ledger/src/ledger_task_runner_impl.cc +++ /dev/null @@ -1,16 +0,0 @@ -/* 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/. */ - -#include "ledger_task_runner_impl.h" - -namespace bat_ledger { - -LedgerTaskRunnerImpl::LedgerTaskRunnerImpl(Task task) : task_(task) {} -LedgerTaskRunnerImpl::~LedgerTaskRunnerImpl() {} - -void LedgerTaskRunnerImpl::Run(const CallerThreadCallback& callback) { - task_(std::move(callback)); -} - -} // namespace ledger diff --git a/vendor/bat-native-ledger/src/ledger_task_runner_impl.h b/vendor/bat-native-ledger/src/ledger_task_runner_impl.h deleted file mode 100644 index 3f4bc193672e..000000000000 --- a/vendor/bat-native-ledger/src/ledger_task_runner_impl.h +++ /dev/null @@ -1,28 +0,0 @@ -/* 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/. */ - -#ifndef BAT_LEDGER_LEDGER_IO_TASK_RUNNER_IMPL_ -#define BAT_LEDGER_LEDGER_IO_TASK_RUNNER_IMPL_ - -#include -#include - -#include "bat/ledger/ledger_task_runner.h" - -namespace bat_ledger { - -class LedgerTaskRunnerImpl : public ledger::LedgerTaskRunner { - public: - LedgerTaskRunnerImpl(Task task); - ~LedgerTaskRunnerImpl() override; - - void Run(const CallerThreadCallback& callback) override; - - private: - Task task_; -}; - -} // namespace ledger - -#endif // BAT_LEDGER_LEDGER_IO_TASK_RUNNER_IMPL_ diff --git a/vendor/bat-native-ledger/src/rapidjson_bat_helper.h b/vendor/bat-native-ledger/src/rapidjson_bat_helper.h index f3ecbfdab61d..4d75880c1b06 100644 --- a/vendor/bat-native-ledger/src/rapidjson_bat_helper.h +++ b/vendor/bat-native-ledger/src/rapidjson_bat_helper.h @@ -10,6 +10,20 @@ #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" +namespace ledger { + +struct AutoContributeProps; +struct BalanceReportInfo; +struct ContributionInfo; +struct Grant; +struct PublisherBanner; +struct PublisherInfo; +struct PublisherInfoFilter; +struct VisitData; +struct WalletInfo; + +} + namespace braveledger_bat_helper { struct BALLOT_ST; @@ -39,6 +53,15 @@ void saveToJson(JsonWriter & writer, const TRANSACTION_BALLOT_ST&); void saveToJson(JsonWriter & writer, const TRANSACTION_ST&); void saveToJson(JsonWriter & writer, const TWITCH_EVENT_INFO&); void saveToJson(JsonWriter & writer, const WALLET_INFO_ST&); +void saveToJson(JsonWriter & writer, const ledger::AutoContributeProps&); +void saveToJson(JsonWriter & writer, const ledger::BalanceReportInfo&); +void saveToJson(JsonWriter & writer, const ledger::ContributionInfo&); +void saveToJson(JsonWriter & writer, const ledger::Grant&); +void saveToJson(JsonWriter & writer, const ledger::PublisherBanner&); +void saveToJson(JsonWriter & writer, const ledger::PublisherInfo&); +void saveToJson(JsonWriter & writer, const ledger::PublisherInfoFilter&); +void saveToJson(JsonWriter & writer, const ledger::VisitData&); +void saveToJson(JsonWriter & writer, const ledger::WalletInfo&); template void saveToJsonString(const T& t, std::string& json) { diff --git a/vendor/bat-native-ledger/src/test/mock_ledger_client.cc b/vendor/bat-native-ledger/src/test/mock_ledger_client.cc index 341df4eed176..274d8b8eed7c 100644 --- a/vendor/bat-native-ledger/src/test/mock_ledger_client.cc +++ b/vendor/bat-native-ledger/src/test/mock_ledger_client.cc @@ -58,19 +58,13 @@ void MockLedgerClient::SavePublisherState(const std::string& publisher_state, handler->OnPublisherStateSaved(ledger::Result::OK); } -uint64_t MockLedgerClient::LoadURL(const std::string& url, +void MockLedgerClient::LoadURL(const std::string& url, const std::vector& headers, const std::string& content, const std::string& contentType, const ledger::URL_METHOD& method, - ledger::LedgerCallbackHandler* handler) { - handler->OnURLRequestResponse(next_id, url, 200, "{}"); - return next_id++; -} - -void MockLedgerClient::RunIOTask( - std::unique_ptr task) { - task->Run(); + ledger::LoadURLCallback callback) { + callback(true, "{}", {}); } } // namespace payments diff --git a/vendor/bat-native-ledger/src/test/mock_ledger_client.h b/vendor/bat-native-ledger/src/test/mock_ledger_client.h index 712b2cf04088..e9778e5b8c67 100644 --- a/vendor/bat-native-ledger/src/test/mock_ledger_client.h +++ b/vendor/bat-native-ledger/src/test/mock_ledger_client.h @@ -42,7 +42,6 @@ class MockLedgerClient : public ledger::LedgerClient { const std::string& contentType, const ledger::URL_METHOD& method, ledger::LedgerCallbackHandler* handler) override; - void RunIOTask(std::unique_ptr task) override; std::unique_ptr ledger_; std::string ledger_state_; diff --git a/vendor/bat-native-ledger/src/url_request_handler.cc b/vendor/bat-native-ledger/src/url_request_handler.cc deleted file mode 100644 index cf67f9e17a6e..000000000000 --- a/vendor/bat-native-ledger/src/url_request_handler.cc +++ /dev/null @@ -1,56 +0,0 @@ -/* 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/. */ - -#include "url_request_handler.h" - -#include "bat/ledger/ledger.h" - -namespace bat_ledger { - -URLRequestHandler::URLRequestHandler() {} - -URLRequestHandler::~URLRequestHandler() { - Clear(); -} - -void URLRequestHandler::Clear() { - request_handlers_.clear(); -} - -void URLRequestHandler::OnURLRequestResponse(uint64_t request_id, - const std::string& url, - int response_code, - const std::string& response, - const std::map& headers) { - if (!RunRequestHandler(request_id, response_code == 200, response, headers)) { - return; - } -} - -bool URLRequestHandler::AddRequestHandler( - std::unique_ptr loader, - URLRequestCallback callback) { - uint64_t request_id = loader->request_id(); - if (request_handlers_.find(request_id) != request_handlers_.end()) - return false; - - request_handlers_[request_id] = callback; - loader->Start(); - return true; -} - -bool URLRequestHandler::RunRequestHandler(uint64_t request_id, - bool success, - const std::string& response, - const std::map& headers) { - if (request_handlers_.find(request_id) == request_handlers_.end()) - return false; - - auto callback = request_handlers_[request_id]; - request_handlers_.erase(request_id); - callback(success, response, headers); - return true; -} - -} // namespace bat_ledger diff --git a/vendor/bat-native-ledger/src/url_request_handler.h b/vendor/bat-native-ledger/src/url_request_handler.h deleted file mode 100644 index 636339a9f347..000000000000 --- a/vendor/bat-native-ledger/src/url_request_handler.h +++ /dev/null @@ -1,46 +0,0 @@ -/* 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/. */ - -#ifndef BAT_LEDGER_URL_REQUEST_HANDLER_H_ -#define BAT_LEDGER_URL_REQUEST_HANDLER_H_ - -#include -#include -#include -#include - -#include "bat/ledger/ledger_callback_handler.h" -#include "bat/ledger/ledger_url_loader.h" -#include "bat_helper.h" - -namespace bat_ledger { - -class URLRequestHandler : public ledger::LedgerCallbackHandler { - public: - using URLRequestCallback = std::function& headers)>; - - URLRequestHandler(); - ~URLRequestHandler() override; - - void Clear(); - bool AddRequestHandler(std::unique_ptr loader, - URLRequestCallback callback); - bool RunRequestHandler(uint64_t request_id, - bool success, - const std::string& response, - const std::map& headers); - - private: - // LedgerCallbackHandler impl - void OnURLRequestResponse(uint64_t request_id, - const std::string& url, - int response_code, - const std::string& response, - const std::map& headers) override; - - std::map request_handlers_; - }; -} // namespace bat_ledger - -#endif // BAT_LEDGER_URL_REQUEST_HANDLER_H_