diff --git a/BUILD.gn b/BUILD.gn index 1dfc5e74ec90..f3c642e0b9a5 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -25,13 +25,13 @@ source_set("bat-native-ledger") { sources = [ "include/bat/ledger/ledger.h", - "src/bat_balance.cc", - "src/bat_balance.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_webrequest.cc", - "src/bat_client_webrequest.h", - "src/bat_client_webrequest_chromium.cc", - "src/bat_client_webrequest_chromium.h", + "src/bat_client.h", "src/bat_get_media.cc", "src/bat_get_media.h", "src/bat_helper.cc", @@ -40,7 +40,12 @@ source_set("bat-native-ledger") { "src/bat_helper_platform.h", "src/bat_publishers.cc", "src/bat_publishers.h", - "src/ledger.cc", + "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/include/bat/ledger/ledger.h b/include/bat/ledger/ledger.h index ee9f25be414e..6198ef2b8781 100644 --- a/include/bat/ledger/ledger.h +++ b/include/bat/ledger/ledger.h @@ -5,70 +5,47 @@ #ifndef BAT_LEDGER_LEDGER_H_ #define BAT_LEDGER_LEDGER_H_ -#include -#include #include -namespace braveledger_bat_client { -class BatClient; -} +#include "bat/ledger/ledger_client.h" -namespace braveledger_bat_helper { -struct FETCH_CALLBACK_EXTRA_DATA_ST; -struct MEDIA_PUBLISHER_INFO; -} - -namespace braveledger_bat_get_media { -class BatGetMedia; -} - -namespace braveledger_bat_publishers { -class BatPublishers; -} - -namespace braveledger_ledger { +namespace ledger { class Ledger { public: - Ledger(); - ~Ledger(); + Ledger() = default; + virtual ~Ledger() = default; // Not copyable, not assignable Ledger(const Ledger&) = delete; Ledger& operator=(const Ledger&) = delete; - void createWallet(); - void initSynopsis(); - void saveVisit(const std::string& publisher, const uint64_t& duration, bool ignoreMinTime); - void saveVisitCallback(const std::string& publisher, const uint64_t& verifiedTimestamp); - void favIconUpdated(const std::string& publisher, const std::string& favicon_url); - void setPublisherInclude(const std::string& publisher, const bool& include); - void setPublisherDeleted(const std::string& publisher, const bool& deleted); - void setPublisherPinPercentage(const std::string& publisher, const bool& pinPercentage); - void setPublisherMinVisitTime(const uint64_t& duration); // In milliseconds - void setPublisherMinVisits(const unsigned int& visits); - void setPublisherAllowNonVerified(const bool& allow); - void setContributionAmount(const double& amount); - void OnMediaRequest(const std::string& url, const std::string& urlQuery, const std::string& type, bool privateTab); - std::string getBATAddress(); - std::string getBTCAddress(); - std::string getETHAddress(); - std::string getLTCAddress(); - void getBalance(); - void run(const uint64_t& delayTime); -private: - bool isBatClientExist(); - bool isBatPublisherExist(); - void publisherInfoCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - void walletPropertiesCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - void reconcileCallback(const std::string& viewingId); - void OnMediaRequestCallback(const uint64_t& duration, const braveledger_bat_helper::MEDIA_PUBLISHER_INFO& mediaPublisherInfo); - void processMedia(const std::map& parts, std::string type); - std::unique_ptr bat_client_; - std::unique_ptr bat_publishers_; - std::unique_ptr bat_get_media_; + static Ledger* CreateInstance(LedgerClient* client); + + virtual void CreateWallet() = 0; + virtual void Reconcile() = 0; + virtual void SaveVisit(const std::string& publisher, + uint64_t duration, + bool ignoreMinTime) = 0; + virtual void OnMediaRequest(const std::string& url, + const std::string& urlQuery, + const std::string& type) = 0; + virtual void SetPublisherInclude(const std::string& publisher, + bool include) = 0; + virtual void SetPublisherDeleted(const std::string& publisher, + bool deleted) = 0; + virtual void SetPublisherPinPercentage(const std::string& publisher, + bool pinPercentage) = 0; + virtual void SetPublisherMinVisitTime(uint64_t duration_in_milliseconds) = 0; + virtual void SetPublisherMinVisits(unsigned int visits) = 0; + virtual void SetPublisherAllowNonVerified(bool allow) = 0; + virtual void SetContributionAmount(double amount) = 0; + virtual const std::string& GetBATAddress() const = 0; + virtual const std::string& GetBTCAddress() const = 0; + virtual const std::string& GetETHAddress() const = 0; + virtual const std::string& GetLTCAddress() const = 0; }; -} // namespace braveledger_ledger +} // namespace ledger #endif // BAT_LEDGER_LEDGER_H_ diff --git a/include/bat/ledger/ledger_callback_handler.h b/include/bat/ledger/ledger_callback_handler.h new file mode 100644 index 000000000000..efb413dfc525 --- /dev/null +++ b/include/bat/ledger/ledger_callback_handler.h @@ -0,0 +1,36 @@ +/* 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_CALLBACK_HANDLER_ +#define BAT_LEDGER_LEDGER_CALLBACK_HANDLER_ + +#include + +namespace ledger { + +enum Result { + OK = 0, + ERROR = 1, + // some more useful result codes should go here +}; + +// LedgerCallbackHandler must not be destroyed if they have pending callbacks +class LedgerCallbackHandler { + public: + virtual ~LedgerCallbackHandler() = default; + + virtual void OnLedgerStateLoaded(Result result, + const std::string& data) {}; + virtual void OnPublisherStateLoaded(Result result, + const std::string& data) {}; + virtual void OnPublisherStateSaved(Result result) {}; + virtual void OnLedgerStateSaved(Result result) {}; + virtual void OnURLRequestResponse(uint64_t request_id, + int response_code, + const std::string& response) {}; +}; + +} // namespace ledger + +#endif // BAT_LEDGER_LEDGER_CALLBACK_HANDLER_ diff --git a/include/bat/ledger/ledger_client.h b/include/bat/ledger/ledger_client.h new file mode 100644 index 000000000000..551261d51401 --- /dev/null +++ b/include/bat/ledger/ledger_client.h @@ -0,0 +1,54 @@ +/* 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_CLIENT_H_ +#define BAT_LEDGER_LEDGER_CLIENT_H_ + +#include + +#include "bat/ledger/ledger_callback_handler.h" +#include "bat/ledger/ledger_task_runner.h" +#include "bat/ledger/ledger_url_loader.h" + +namespace ledger { + +enum URL_METHOD { + GET = 0, + PUT = 1, + POST = 2 +}; + +class LedgerClient { + public: + virtual ~LedgerClient() = default; + + // called when the wallet creation has completed + virtual std::string GenerateGUID() const = 0; + virtual void OnWalletCreated(Result result) = 0; + virtual void OnReconcileComplete(Result result, + const std::string& viewing_id) = 0; + virtual void LoadLedgerState(LedgerCallbackHandler* handler) = 0; + virtual void LoadPublisherState(LedgerCallbackHandler* handler) = 0; + virtual void SaveLedgerState(const std::string& ledger_state, + LedgerCallbackHandler* handler) = 0; + virtual void SavePublisherState(const std::string& publisher_state, + LedgerCallbackHandler* handler) = 0; + virtual std::unique_ptr 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 and RunTask are temporary workarounds for leveldb + // and we should replace them with a ledger_client api for reading/writing + // individual records + virtual void RunIOTask(std::unique_ptr task) = 0; + // If any callbacks are made from inside RunIOTask you must use + // RunTask to return back to the calling thread + virtual void RunTask(std::unique_ptr task) = 0; +}; + +} // namespace ledger + +#endif // BAT_LEDGER_LEDGER_CLIENT_H_ diff --git a/include/bat/ledger/ledger_task_runner.h b/include/bat/ledger/ledger_task_runner.h new file mode 100644 index 000000000000..74fb8f46796f --- /dev/null +++ b/include/bat/ledger/ledger_task_runner.h @@ -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/. */ + +#ifndef BAT_LEDGER_LEDGER_TASK_RUNNER_ +#define BAT_LEDGER_LEDGER_TASK_RUNNER_ + +#include + +namespace ledger { + +class LedgerTaskRunner { + public: + virtual ~LedgerTaskRunner() = default; + virtual void Run() = 0; +}; + +} // namespace ledger + +#endif // BAT_LEDGER_LEDGER_TASK_RUNNER_ diff --git a/include/bat/ledger/ledger_url_loader.h b/include/bat/ledger/ledger_url_loader.h new file mode 100644 index 000000000000..ddfbd92d4515 --- /dev/null +++ b/include/bat/ledger/ledger_url_loader.h @@ -0,0 +1,21 @@ +/* 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 + +namespace ledger { + +class 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/src/bat/ledger/ledger.cc b/src/bat/ledger/ledger.cc new file mode 100644 index 000000000000..e30c3bab6c89 --- /dev/null +++ b/src/bat/ledger/ledger.cc @@ -0,0 +1,16 @@ +/* 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 "bat/ledger/ledger.h" + +#include "ledger_impl.h" + +namespace ledger { + +// static +ledger::Ledger* Ledger::CreateInstance(LedgerClient* client) { + return new bat_ledger::LedgerImpl(client); +} + +} diff --git a/src/bat_balance.cc b/src/bat_balance.cc deleted file mode 100644 index 0cd3085c3cd5..000000000000 --- a/src/bat_balance.cc +++ /dev/null @@ -1,30 +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 "bat_balance.h" - -#include "bat_helper.h" -#include "static_values.h" - -namespace braveledger_bat_balance { - -std::string BatBalance::buildURL(const std::string& path, const std::string& prefix) { - std::string url; - if (braveledger_ledger::g_isProduction) { - url = BALANCE_PRODUCTION_SERVER; - } else { - url = BALANCE_STAGING_SERVER; - } - - return url + prefix + path; -} - -void BatBalance::getWalletProperties(const std::string& paymentInfo, braveledger_bat_client_webrequest::FetchCallback callback, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { - - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)WALLET_PROPERTIES + paymentInfo + WALLET_PROPERTIES_END, ""), - callback, std::vector(), "", "", extraData, braveledger_bat_client_webrequest::URL_METHOD::GET); -} - -} // namespace braveledger_bat_balance diff --git a/src/bat_balance.h b/src/bat_balance.h deleted file mode 100644 index 3529824f2f2f..000000000000 --- a/src/bat_balance.h +++ /dev/null @@ -1,32 +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 BRAVELEDGER_BAT_BALANCE_H_ -#define BRAVELEDGER_BAT_BALANCE_H_ - -#include - -#include "bat_client_webrequest.h" - -namespace braveledger_bat_helper { -struct FETCH_CALLBACK_EXTRA_DATA_ST; -} - -namespace braveledger_bat_balance { - -class BatBalance { - public: - BatBalance() = default; - ~BatBalance() = default; - void getWalletProperties(const std::string& paymentInfo, - braveledger_bat_client_webrequest::FetchCallback callback, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - - private: - std::string buildURL(const std::string& path, const std::string& prefix); -}; - -} // namespace braveledger_bat_balance - -#endif // BRAVELEDGER_BAT_BALANCE_H_ diff --git a/src/bat_client.cc b/src/bat_client.cc index 2082675096dd..aba90dd28021 100644 --- a/src/bat_client.cc +++ b/src/bat_client.cc @@ -7,6 +7,7 @@ #include #include +#include "ledger_impl.h" #include "bat_helper.h" #include "rapidjson_bat_helper.h" #include "static_values.h" @@ -14,9 +15,25 @@ #include "anon/anon.h" #include "wally_bip39.h" +using namespace std::placeholders; + namespace braveledger_bat_client { -BatClient::BatClient(bool useProxy) : +// namespace { +// std::string GetBalanceURL(const std::string& path, const std::string& prefix) { +// std::string url; +// if (braveledger_ledger::g_isProduction) { +// url = BALANCE_PRODUCTION_SERVER; +// } else { +// url = BALANCE_STAGING_SERVER; +// } + +// return url + prefix + path; +// } +// } + +BatClient::BatClient(bat_ledger::LedgerImpl* ledger, bool useProxy) : + ledger_(ledger), useProxy_(useProxy), state_(new braveledger_bat_helper::CLIENT_STATE_ST()), publisherTimestamp_(0), @@ -40,33 +57,34 @@ std::string BatClient::buildURL(const std::string& path, const std::string& pref return url + prefix + path; } -void BatClient::loadStateOrRegisterPersona() { - - - auto runnable = braveledger_bat_helper::bat_mem_fun_binder2(*this, &BatClient::loadStateOrRegisterPersonaCallback); - braveledger_bat_helper::loadState(runnable); - LOG(ERROR) << "BatClient::loadStateOrRegisterPersona exit"; -} - -void BatClient::loadStateOrRegisterPersonaCallback(bool result, const braveledger_bat_helper::CLIENT_STATE_ST& state) { - if (!result) { +void BatClient::loadStateOrRegisterPersonaCallback(bool success, const std::string& data) { + if (!success) { LOG(ERROR) << "!!!here1"; registerPersona(); return; } + + braveledger_bat_helper::CLIENT_STATE_ST state; + braveledger_bat_helper::loadFromJson(state, data.c_str()); + LOG(ERROR) << "!!!bat address == " << state.walletInfo_.addressBAT_; LOG(ERROR) << "!!!card address == " << state.walletInfo_.addressCARD_ID_; + state_.reset(new braveledger_bat_helper::CLIENT_STATE_ST(state)); publisherTimestamp(false); + ledger_->OnWalletCreated(ledger::Result::OK); } void BatClient::registerPersona() { - // We should use simple callbacks on iOS - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::requestCredentialsCallback); - - braveledger_bat_helper::batClientWebRequest->run(buildURL(REGISTER_PERSONA, PREFIX_V2), runnable, - std::vector(), "", "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), - braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(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, + braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST())); } void BatClient::requestCredentialsCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST&) { @@ -76,7 +94,7 @@ void BatClient::requestCredentialsCallback(bool result, const std::string& respo return; } if (state_->personaId_.empty()) { - state_->personaId_ = braveledger_bat_helper::GenerateGUID(); + state_->personaId_ = ledger_->GenerateGUID(); } // Anonize2 limit is 31 octets state_->userId_ = state_->personaId_; @@ -92,7 +110,7 @@ void BatClient::requestCredentialsCallback(bool result, const std::string& respo std::vector publicKey; std::vector newSecretKey; braveledger_bat_helper::getPublicKeyFromSeed(secretKey, publicKey, newSecretKey); - std::string label = braveledger_bat_helper::GenerateGUID(); + std::string label = ledger_->GenerateGUID(); std::string publicKeyHex = braveledger_bat_helper::uint8ToHex(publicKey); std::string keys[3] = {"currency", "label", "publicKey"}; std::string values[3] = {CURRENCY, label, publicKeyHex}; @@ -117,11 +135,16 @@ void BatClient::requestCredentialsCallback(bool result, const std::string& respo headers.push_back("Content-Type: application/json; charset=UTF-8"); // We should use simple callbacks on iOS - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::registerPersonaCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)REGISTER_PERSONA + "/" + state_->userId_, PREFIX_V2), - runnable, + auto request_id = ledger_->LoadURL( + buildURL((std::string)REGISTER_PERSONA + "/" + state_->userId_, PREFIX_V2), headers, payloadStringify, "application/json; charset=utf-8", - braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), braveledger_bat_client_webrequest::URL_METHOD::POST); + ledger::URL_METHOD::POST, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::registerPersonaCallback, + this, + _1, + _2, + braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST())); } std::string BatClient::getAnonizeProof(const std::string& registrarVK, const std::string& id, std::string& preFlight) { @@ -142,9 +165,12 @@ std::string BatClient::getAnonizeProof(const std::string& registrarVK, const std return proof; } -void BatClient::registerPersonaCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::registerPersonaCallback(bool result, + const std::string& response, + const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { if (!result) { - // TODO errors handling + // TODO error handling + ledger_->OnWalletCreated(ledger::Result::ERROR); return; } @@ -166,32 +192,38 @@ void BatClient::registerPersonaCallback(bool result, const std::string& response // TODO debug //getPromotionCaptcha(); // + ledger_->OnWalletCreated(ledger::Result::OK); } -void BatClient::publisherTimestamp( bool saveState) { +void BatClient::publisherTimestamp( bool save_state) { // We should use simple callbacks on iOS - braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST extraData; - extraData.boolean1 = saveState; + braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST extra_data; + extra_data.boolean1 = save_state; - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::publisherTimestampCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL(PUBLISHER_TIMESTAMP, PREFIX_V3),runnable, std::vector(), "", "", extraData, - braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL(PUBLISHER_TIMESTAMP, PREFIX_V3), std::vector(), "", "", + ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::publisherTimestampCallback, + this, + _1, + _2, + extra_data)); } void BatClient::publisherTimestampCallback(bool result, const std::string& response, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { + const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extra_data) { + LOG(ERROR) << "response " << response; if (!result) { // TODO errors handling return; } braveledger_bat_helper::getJSONPublisherTimeStamp(response, publisherTimestamp_); - if (!extraData.boolean1) { - LOG(ERROR) << "BatClient::publisherTimestampCallback !extraData.boolean1"; + if (!extra_data.boolean1) { + LOG(ERROR) << "BatClient::publisherTimestampCallback !extra_data.boolean1"; } else { - std::lock_guard guard(state_mutex_); - braveledger_bat_helper::saveState(*state_); + saveState(); } } @@ -199,56 +231,72 @@ uint64_t BatClient::getPublisherTimestamp() { return publisherTimestamp_; } -void BatClient::publisherInfo(const std::string& publisher, braveledger_bat_client_webrequest::FetchCallback callback, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { - braveledger_bat_helper::batClientWebRequest->run(buildURL(PUBLISHER_INFO + publisher, PREFIX_V3), - callback, std::vector(), "", "", extraData, braveledger_bat_client_webrequest::URL_METHOD::GET); +std::unique_ptr BatClient::publisherInfo( + const std::string& publisher, + ledger::LedgerCallbackHandler* handler){ + return ledger_->LoadURL(buildURL(PUBLISHER_INFO + publisher, PREFIX_V3), + std::vector(), "", "", ledger::URL_METHOD::GET, handler); } void BatClient::setContributionAmount(const double& amount) { std::lock_guard guard(state_mutex_); state_->fee_amount_ = amount; - braveledger_bat_helper::saveState(*state_); + saveState(); } -std::string BatClient::getBATAddress() { +const std::string& BatClient::getBATAddress() const { return state_->walletInfo_.addressBAT_; } -std::string BatClient::getBTCAddress() { +const std::string& BatClient::getBTCAddress() const { return state_->walletInfo_.addressBTC_; } -std::string BatClient::getETHAddress() { +const std::string& BatClient::getETHAddress() const { return state_->walletInfo_.addressETH_; } -std::string BatClient::getLTCAddress() { +const std::string& BatClient::getLTCAddress() const { return state_->walletInfo_.addressLTC_; } -void BatClient::getWalletProperties (braveledger_bat_client_webrequest::FetchCallback callback, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { - balance_.getWalletProperties(state_->walletInfo_.paymentId_, callback, extraData); -} +// void BatClient::getWalletProperties(const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +// auto request_id = ledger_->LoadURL( +// GetBalanceURL((std::string)WALLET_PROPERTIES + state_->walletInfo_.paymentId_ + WALLET_PROPERTIES_END, ""), +// std::vector(), +// "", +// "", +// ledger::URL_METHOD::GET, &handler_); +// handler_.AddRequestHandler(std::move(request_id), +// std::bind(&BatClient::publisherTimestampCallback, +// this, +// _1, +// _2, +// extra_data)); +// } bool BatClient::isReadyForReconcile() { // TODO real check of reconcile timestamp return true; } -void BatClient::reconcile(const std::string& viewingId, braveledger_bat_helper::SimpleCallback callback) { +void BatClient::reconcile(const std::string& viewingId) { //FETCH_CALLBACK_EXTRA_DATA_ST extraData; currentReconcile_->viewingId_ = viewingId; - currentReconcile_->ledgerCallback_ = callback; - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::reconcileCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)RECONCILE_CONTRIBUTION + state_->userId_, PREFIX_V2), runnable, - std::vector(), "", "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), - braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL((std::string)RECONCILE_CONTRIBUTION + state_->userId_, PREFIX_V2), + std::vector(), "", "", + ledger::URL_METHOD::GET, + &handler_); + + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::reconcileCallback, + this, + _1, + _2)); } -void BatClient::reconcileCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::reconcileCallback(bool result, const std::string& response) { LOG(ERROR) << "!!!reconcileCallback response == " + response; if (!result) { // TODO errors handling @@ -265,13 +313,17 @@ void BatClient::currentReconcile() { std::string path = (std::string)WALLET_PROPERTIES + state_->walletInfo_.paymentId_ + "?refresh=true&amount=" + amount.str() + "&altcurrency=" + state_->fee_currency_; //FETCH_CALLBACK_EXTRA_DATA_ST extraData; - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::currentReconcileCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL(path, ""), runnable, - std::vector(), "", "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), - braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL(path, ""), + std::vector(), "", "", + ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::currentReconcileCallback, + this, + _1, + _2)); } -void BatClient::currentReconcileCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::currentReconcileCallback(bool result, const std::string& response) { //LOG(ERROR) << "!!!currentReconcileCallback response == " << response; if (!result) { // TODO errors handling @@ -324,13 +376,18 @@ void BatClient::currentReconcileCallback(bool result, const std::string& respons headers.push_back("Content-Type: application/json; charset=UTF-8"); std::string path = (std::string)WALLET_PROPERTIES + state_->walletInfo_.paymentId_; - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::reconcilePayloadCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL(path, ""), runnable, + auto request_id = ledger_->LoadURL(buildURL(path, ""), headers, payloadStringify, "application/json; charset=utf-8", - braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), braveledger_bat_client_webrequest::URL_METHOD::PUT); + ledger::URL_METHOD::PUT, + &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::reconcilePayloadCallback, + this, + _1, + _2)); } -void BatClient::reconcilePayloadCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::reconcilePayloadCallback(bool result, const std::string& response) { //LOG(ERROR) << "!!!response == " << response; if (!result) { // TODO errors handling @@ -348,15 +405,20 @@ void BatClient::reconcilePayloadCallback(bool result, const std::string& respons std::lock_guard guard(transactions_access_mutex_); state_->transactions_.push_back(transaction); } - braveledger_bat_helper::saveState(*state_); + saveState(); // TODO set a new timestamp for the next reconcile // TODO self.state.updateStamp var in old lib braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST stExtraData; stExtraData.boolean1 = true; - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::updateRulesCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL(UPDATE_RULES_V1, ""),runnable, - std::vector(), "", "", stExtraData, braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL(UPDATE_RULES_V1, ""), + std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::updateRulesCallback, + this, + _1, + _2, + stExtraData)); } void BatClient::updateRulesCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { @@ -367,10 +429,15 @@ void BatClient::updateRulesCallback(bool result, const std::string& response, co } state_->ruleset_ = response; - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::updateRulesV2Callback); - braveledger_bat_helper::batClientWebRequest->run(buildURL(UPDATE_RULES_V2, ""),runnable, - std::vector(), "", "", extraData, - braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL(UPDATE_RULES_V2, ""), + std::vector(), "", "", + ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::updateRulesV2Callback, + this, + _1, + _2, + extraData)); } void BatClient::updateRulesV2Callback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { @@ -389,14 +456,17 @@ void BatClient::updateRulesV2Callback(bool result, const std::string& response, } void BatClient::registerViewing() { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::registerViewingCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)REGISTER_VIEWING, PREFIX_V2), - runnable, - std::vector(), "", "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), - braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL((std::string)REGISTER_VIEWING, PREFIX_V2), + std::vector(), "", "", + ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::registerViewingCallback, + this, + _1, + _2)); } -void BatClient::registerViewingCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::registerViewingCallback(bool result, const std::string& response) { LOG(ERROR) << "!!!response registerViewingCallback == " << response; if (!result) { // TODO errors handling @@ -418,15 +488,20 @@ void BatClient::registerViewingCallback(bool result, const std::string& response } void BatClient::viewingCredentials(const std::string& proofStringified, const std::string& anonizeViewingId) { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::viewingCredentialsCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)REGISTER_VIEWING + "/" + anonizeViewingId, PREFIX_V2), runnable, - std::vector(), proofStringified, "application/json; charset=utf-8", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), - braveledger_bat_client_webrequest::URL_METHOD::POST); + auto request_id = ledger_->LoadURL(buildURL((std::string)REGISTER_VIEWING + "/" + anonizeViewingId, PREFIX_V2), + std::vector(), proofStringified, "application/json; charset=utf-8", + ledger::URL_METHOD::POST, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::viewingCredentialsCallback, + this, + _1, + _2)); } -void BatClient::viewingCredentialsCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::viewingCredentialsCallback(bool result, const std::string& response) { //LOG(ERROR) << "!!!response viewingCredentialsCallback == " << response; if (!result) { + ledger_->OnReconcileComplete(ledger::Result::ERROR, currentReconcile_->viewingId_); // TODO errors handling return; } @@ -458,9 +533,8 @@ void BatClient::viewingCredentialsCallback(bool result, const std::string& respo } } - braveledger_bat_helper::saveState(*state_); - braveledger_bat_helper::run_runnable(currentReconcile_->ledgerCallback_, std::cref(currentReconcile_->viewingId_)); - + saveState(); + ledger_->OnReconcileComplete(ledger::Result::OK, currentReconcile_->viewingId_); //LOG(ERROR) << "!!!response masterUserToken == " << currentReconcile_.masterUserToken_; } @@ -481,7 +555,7 @@ void BatClient::votePublishers(const std::vector& publishers, const for (size_t i = 0; i < publishers.size(); i++) { vote(publishers[i], viewingId); } - braveledger_bat_helper::saveState(*state_); + saveState(); } void BatClient::vote(const std::string& publisher, const std::string& viewingId) { @@ -556,9 +630,14 @@ void BatClient::prepareBatch(const braveledger_bat_helper::BALLOT_ST& ballot, co extraData.string1 = ballot.viewingId_; extraData.string2 = ballot.surveyorId_; - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::prepareBatchCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)SURVEYOR_BATCH_VOTING + transaction.anonizeViewingId_, PREFIX_V2), - runnable, std::vector(), "", "", extraData, braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL((std::string)SURVEYOR_BATCH_VOTING + transaction.anonizeViewingId_, PREFIX_V2), + std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::prepareBatchCallback, + this, + _1, + _2, + extraData)); } void BatClient::prepareBatchCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { @@ -591,7 +670,7 @@ void BatClient::prepareBatchCallback(bool result, const std::string& response, c } } - braveledger_bat_helper::saveState(*state_); + saveState(); proofBatch(batchProof); LOG(ERROR) << "!!! 2 batchProof.size() == " << batchProof.size(); } @@ -649,9 +728,14 @@ void BatClient::prepareBallot(const braveledger_bat_helper::BALLOT_ST& ballot, c extraData.string1 = ballot.viewingId_; extraData.string2 = ballot.surveyorId_; - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::prepareBallotCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)SURVEYOR_VOTING + surveyorIdEncoded + "/" + transaction.anonizeViewingId_, PREFIX_V2), runnable, - std::vector(), "", "", extraData, braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL((std::string)SURVEYOR_VOTING + surveyorIdEncoded + "/" + transaction.anonizeViewingId_, PREFIX_V2), + std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::prepareBallotCallback, + this, + _1, + _2, + extraData)); } void BatClient::prepareBallotCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { @@ -677,7 +761,7 @@ void BatClient::prepareBallotCallback(bool result, const std::string& response, } } } - braveledger_bat_helper::saveState(*state_); + saveState(); } void BatClient::commitBallot(const braveledger_bat_helper::BALLOT_ST& ballot, const braveledger_bat_helper::TRANSACTION_ST& transaction) { @@ -715,14 +799,16 @@ void BatClient::commitBallot(const braveledger_bat_helper::BALLOT_ST& ballot, co std::string values[1] = {anonProof}; std::string payload = braveledger_bat_helper::stringify(keys, values, 1); - braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST extraData; - - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::commitBallotCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)SURVEYOR_VOTING + surveyorIdEncoded, PREFIX_V2),runnable, - std::vector(), payload, "", extraData, braveledger_bat_client_webrequest::URL_METHOD::PUT); + auto request_id = ledger_->LoadURL(buildURL((std::string)SURVEYOR_VOTING + surveyorIdEncoded, PREFIX_V2), + std::vector(), payload, "", ledger::URL_METHOD::PUT, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::commitBallotCallback, + this, + _1, + _2)); } -void BatClient::commitBallotCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::commitBallotCallback(bool result, const std::string& response) { LOG(ERROR) << "!!!!commitBallotCallback response == " << response; // TODO add ballots to transaction, saveState, remove ballots from vector of ballots @@ -749,6 +835,12 @@ std::string BatClient::getWalletPassphrase() { return passPhrase; } +void BatClient::saveState() { + std::string data; + braveledger_bat_helper::saveToJsonString(*state_, data); + ledger_->SaveLedgerState(data, this); +} + void BatClient::recoverWallet(const std::string& passPhrase) { std::vector newSeed; newSeed.resize(32); @@ -768,27 +860,35 @@ void BatClient::recoverWallet(const std::string& passPhrase) { braveledger_bat_helper::getPublicKeyFromSeed(secretKey, publicKey, newSecretKey); std::string publicKeyHex = braveledger_bat_helper::uint8ToHex(publicKey); - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::recoverWalletPublicKeyCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)RECOVER_WALLET_PUBLIC_KEY + publicKeyHex, ""), - runnable, std::vector(), "", "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), - braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL((std::string)RECOVER_WALLET_PUBLIC_KEY + publicKeyHex, ""), + std::vector(), "", "", + ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::recoverWalletPublicKeyCallback, + this, + _1, + _2)); + } -void BatClient::recoverWalletPublicKeyCallback(bool result, const std::string& response, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::recoverWalletPublicKeyCallback(bool result, const std::string& response) { //LOG(ERROR) << "!!!recoverWalletPublicKeyCallback == " << response; std::string recoveryId; braveledger_bat_helper::getJSONValue("paymentId", response, recoveryId); - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::recoverWalletCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)RECOVER_WALLET + recoveryId, ""), - runnable, std::vector(), "", "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL((std::string)RECOVER_WALLET + recoveryId, ""), + std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::recoverWalletCallback, + this, + _1, + _2)); } -void BatClient::recoverWalletCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::recoverWalletCallback(bool result, const std::string& response) { //LOG(ERROR) << "!!!recoverWalletCallback == " << response; braveledger_bat_helper::getJSONWalletInfo(response, state_->walletInfo_, state_->fee_currency_, state_->fee_amount_, state_->days_); - braveledger_bat_helper::saveState(*state_); + saveState(); } void BatClient::getPromotion(const std::string& lang, const std::string& forPaymentId) { @@ -810,12 +910,16 @@ void BatClient::getPromotion(const std::string& lang, const std::string& forPaym } } - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::getPromotionCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)GET_SET_PROMOTION + arguments, ""), - runnable, std::vector(), "", "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL((std::string)GET_SET_PROMOTION + arguments, ""), + std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::getPromotionCallback, + this, + _1, + _2)); } -void BatClient::getPromotionCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::getPromotionCallback(bool result, const std::string& response) { LOG(ERROR) << "!!!getPromotionCallback == " << response; } @@ -824,23 +928,31 @@ void BatClient::setPromotion(const std::string& promotionId, const std::string& std::string values[2] = {promotionId, captchaResponse}; std::string payload = braveledger_bat_helper::stringify(keys, values, 2); - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::setPromotionCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)GET_SET_PROMOTION + "/" + state_->walletInfo_.paymentId_, ""), - runnable, std::vector(), payload, "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), braveledger_bat_client_webrequest::URL_METHOD::PUT); + auto request_id = ledger_->LoadURL(buildURL((std::string)GET_SET_PROMOTION + "/" + state_->walletInfo_.paymentId_, ""), + std::vector(), payload, "", ledger::URL_METHOD::PUT, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::setPromotionCallback, + this, + _1, + _2)); } -void BatClient::setPromotionCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::setPromotionCallback(bool result, const std::string& response) { LOG(ERROR) << "!!!setPromotionCallback == " << response; } void BatClient::getPromotionCaptcha() { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::getPromotionCaptchaCallback); - braveledger_bat_helper::batClientWebRequest->run(buildURL((std::string)GET_PROMOTION_CAPTCHA + state_->walletInfo_.paymentId_, ""), - runnable, std::vector(), "", "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), - braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request_id = ledger_->LoadURL(buildURL((std::string)GET_PROMOTION_CAPTCHA + state_->walletInfo_.paymentId_, ""), + std::vector(), "", "", + ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request_id), + std::bind(&BatClient::getPromotionCaptchaCallback, + this, + _1, + _2)); } -void BatClient::getPromotionCaptchaCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatClient::getPromotionCaptchaCallback(bool result, const std::string& response) { LOG(ERROR) << "!!!getPromotionCaptchaCallback == " << response; } diff --git a/src/bat_client.h b/src/bat_client.h index 0be552bfcbf4..724a3cc0c011 100644 --- a/src/bat_client.h +++ b/src/bat_client.h @@ -9,34 +9,37 @@ #include #include -#include "bat_balance.h" -#include "bat_client_webrequest.h" +#include "bat/ledger/ledger_callback_handler.h" +#include "bat/ledger/ledger_url_loader.h" #include "bat_helper.h" +#include "url_request_handler.h" + +namespace bat_ledger { +class LedgerImpl; +} namespace braveledger_bat_client { -class BatClient { +class BatClient : public ledger::LedgerCallbackHandler { public: + explicit BatClient(bat_ledger::LedgerImpl* ledger, bool useProxy = true); + ~BatClient() override; - explicit BatClient( bool useProxy = true); - ~BatClient(); - - void loadStateOrRegisterPersona(); + void loadStateOrRegisterPersonaCallback(bool success, const std::string& data); void requestCredentialsCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); void registerPersonaCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - void publisherTimestampCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); + void publisherTimestampCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extra_data); uint64_t getPublisherTimestamp(); - void publisherInfo(const std::string& publisher, braveledger_bat_client_webrequest::FetchCallback callback, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); + std::unique_ptr publisherInfo( + const std::string& publisher, + ledger::LedgerCallbackHandler* handler); void setContributionAmount(const double& amount); - std::string getBATAddress(); - std::string getBTCAddress(); - std::string getETHAddress(); - std::string getLTCAddress(); - void getWalletProperties(braveledger_bat_client_webrequest::FetchCallback callback, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); + const std::string& getBATAddress() const; + const std::string& getBTCAddress() const; + const std::string& getETHAddress() const; + const std::string& getLTCAddress() const; bool isReadyForReconcile(); - void reconcile(const std::string& viewingId, braveledger_bat_helper::SimpleCallback callback); + void reconcile(const std::string& viewingId); unsigned int ballots(const std::string& viewingId); void votePublishers(const std::vector& publishers, const std::string& viewingId); void prepareBallots(); @@ -45,13 +48,15 @@ class BatClient { void getPromotion(const std::string& lang, const std::string& forPaymentId); void setPromotion(const std::string& promotionId, const std::string& captchaResponse); void getPromotionCaptcha(); + void getWalletProperties(const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); private: - void getPromotionCaptchaCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - void getPromotionCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - void setPromotionCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - void recoverWalletPublicKeyCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - void recoverWalletCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); + void saveState(); + void getPromotionCaptchaCallback(bool result, const std::string& response); + void getPromotionCallback(bool result, const std::string& response); + void setPromotionCallback(bool result, const std::string& response); + void recoverWalletPublicKeyCallback(bool result, const std::string& response); + void recoverWalletCallback(bool result, const std::string& response); void prepareBatch(const braveledger_bat_helper::BALLOT_ST& ballot, const braveledger_bat_helper::TRANSACTION_ST& transaction); void prepareBatchCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); void proofBatch(const std::vector& batchProof); @@ -59,32 +64,33 @@ class BatClient { void prepareBallot(const braveledger_bat_helper::BALLOT_ST& ballot, const braveledger_bat_helper::TRANSACTION_ST& transaction); void commitBallot(const braveledger_bat_helper::BALLOT_ST& ballot, const braveledger_bat_helper::TRANSACTION_ST& transaction); void prepareBallotCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - void commitBallotCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); + void commitBallotCallback(bool result, const std::string& response); void vote(const std::string& publisher, const std::string& viewingId); - void loadStateOrRegisterPersonaCallback(bool result, const braveledger_bat_helper::CLIENT_STATE_ST& state); void registerPersona(); void publisherTimestamp(bool saveState = true); - void reconcileCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); + void reconcileCallback(bool result, const std::string& response); void currentReconcile(); - void currentReconcileCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - void reconcilePayloadCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); + void currentReconcileCallback(bool result, const std::string& response); + void reconcilePayloadCallback(bool result, const std::string& response); void updateRulesCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); void updateRulesV2Callback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); void registerViewing(); - void registerViewingCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); + void registerViewingCallback(bool result, const std::string& response); void viewingCredentials(const std::string& proofStringified, const std::string& anonizeViewingId); - void viewingCredentialsCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); + void viewingCredentialsCallback(bool result, const std::string& response); std::string getAnonizeProof(const std::string& registrarVK, const std::string& id, std::string& preFlight); std::string buildURL(const std::string& path, const std::string& prefix); + bat_ledger::LedgerImpl* ledger_; // NOT OWNED bool useProxy_; std::unique_ptr state_; uint64_t publisherTimestamp_; std::mutex state_mutex_; std::mutex transactions_access_mutex_; std::mutex ballots_access_mutex_; - braveledger_bat_balance::BatBalance balance_; std::unique_ptr currentReconcile_; + + bat_ledger::URLRequestHandler handler_; }; } // namespace braveledger_bat_client diff --git a/src/bat_client_webrequest.cc b/src/bat_client_webrequest.cc deleted file mode 100644 index 5084fc169020..000000000000 --- a/src/bat_client_webrequest.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "bat_client_webrequest.h" - -namespace braveledger_bat_client_webrequest { - -// TODO: implement - -} // namespace braveledger_bat_client_webreque diff --git a/src/bat_client_webrequest.h b/src/bat_client_webrequest.h deleted file mode 100644 index 99f602699df0..000000000000 --- a/src/bat_client_webrequest.h +++ /dev/null @@ -1,50 +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 BRAVELEDGER_BAT_CLIENT_WEBREQUEST_H_ -#define BRAVELEDGER_BAT_CLIENT_WEBREQUEST_H_ - -#include -#include - -// TODO(bridiver) - hacky temp workaround -#if defined CHROMIUM_BUILD -#include "base/callback.h" -#endif - -namespace braveledger_bat_helper { -struct FETCH_CALLBACK_EXTRA_DATA_ST; -} - -namespace braveledger_bat_client_webrequest { - -enum URL_METHOD { - GET = 0, - PUT = 1, - POST = 2 -}; - -using FetchCallbackSignature = void (bool, const std::string&, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST&); -// TODO(bridiver) - another hacky temp workaround -#if !defined CHROMIUM_BUILD -using FetchCallback = std::function; -#else -using FetchCallback = base::Callback; -#endif - -// platform-dependent implementation -class BatClientWebRequest { - public: - BatClientWebRequest() = default; - virtual void run(const std::string& url, FetchCallback callback, - const std::vector& headers, const std::string& content, - const std::string& contentType, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData, - const URL_METHOD& method) = 0; - virtual void Stop() = 0; - virtual void Start() = 0; -}; - -} // namespace braveledger_bat_client_webrequest - -#endif // BRAVELEDGER_BAT_CLIENT_WEBREQUEST_H_ diff --git a/src/bat_client_webrequest_chromium.cc b/src/bat_client_webrequest_chromium.cc deleted file mode 100644 index aeb627dc756a..000000000000 --- a/src/bat_client_webrequest_chromium.cc +++ /dev/null @@ -1,122 +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 "bat_client_webrequest_chromium.h" - -#include "base/logging.h" -#include "bat_helper.h" -#include "chrome/browser/browser_process.h" -#include "content/public/browser/browser_thread.h" -#include "net/base/elements_upload_data_stream.h" -#include "net/base/upload_bytes_element_reader.h" -#include "net/base/upload_data_stream.h" -#include "net/base/upload_element_reader.h" -#include "net/url_request/url_fetcher.h" -#include "net/url_request/url_request_context.h" -#include "net/url_request/url_request_context_builder.h" -#include "net/url_request/url_request_context_getter.h" - -namespace braveledger_bat_client_webrequest { - - BatClientWebRequestChromium::BatClientWebRequestChromium() : running_(false) { - } - - BatClientWebRequestChromium::~BatClientWebRequestChromium() { - } - - BatClientWebRequestChromium::URL_FETCH_REQUEST::URL_FETCH_REQUEST() {} - BatClientWebRequestChromium::URL_FETCH_REQUEST::~URL_FETCH_REQUEST() {} - - std::unique_ptr BatClientWebRequestChromium::CreateUploadStream(const std::string& stream) { - std::vector buffer(stream.begin(),stream.end()); - - return net::ElementsUploadDataStream::CreateWithReader( - std::unique_ptr(new net::UploadOwnedBytesElementReader(&buffer)), 0); - } - - void BatClientWebRequestChromium::Start() { - running_ = true; - } - - void BatClientWebRequestChromium::Stop() { - running_ = false; - url_fetchers_.clear(); - } - - void BatClientWebRequestChromium::runOnThread(const std::string& url, - FetchCallback callback, - const std::vector& headers, - const std::string& content, const std::string& contentType, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData, - const URL_METHOD& method) { - if (!running_) - return; - - LOG(ERROR) << "BatClientWebRequestChromium::runOnThread"; - url_fetchers_.push_back(std::make_unique()); - net::URLFetcher::RequestType requestType = net::URLFetcher::GET; - switch (method) - { - case URL_METHOD::GET: - requestType = net::URLFetcher::GET; - break; - case URL_METHOD::POST: - requestType = net::URLFetcher::POST; - break; - case URL_METHOD::PUT: - LOG(ERROR) << "!!!in PUT"; - requestType = net::URLFetcher::PUT; - break; - } - /*if (!content.empty()) { - requestType = net::URLFetcher::POST; - }*/ - url_fetchers_.back()->url_fetcher_ = net::URLFetcher::Create(GURL(url), requestType, this); - url_fetchers_.back()->callback_ = callback; - url_fetchers_.back()->extraData_.reset(new braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(extraData)); - //LOG(ERROR) << "!!!on runOnThread == " + url; - url_fetchers_.back()->url_fetcher_->SetRequestContext(g_browser_process->system_request_context()); - for (size_t i = 0; i < headers.size(); i++) { - url_fetchers_.back()->url_fetcher_->AddExtraRequestHeader(headers[i]); - } - if (!content.empty()) { - url_fetchers_.back()->url_fetcher_->SetUploadStreamFactory( - contentType, - base::Bind(&BatClientWebRequestChromium::CreateUploadStream, base::Unretained(this), content)); - } - url_fetchers_.back()->url_fetcher_->Start(); - } - - void BatClientWebRequestChromium::run(const std::string& url, - FetchCallback callback, - const std::vector& headers, const std::string& content, - const std::string& contentType, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData, - const URL_METHOD& method) { - - LOG(ERROR) << "!!!web_request URL == " + url; - content::BrowserThread::PostTask( - content::BrowserThread::UI, FROM_HERE, - base::Bind(&BatClientWebRequestChromium::runOnThread, - base::Unretained(this), url, callback, headers, content, contentType, - extraData, method)); - } - - void BatClientWebRequestChromium::OnURLFetchComplete(const net::URLFetcher* source) { - //LOG(ERROR) << "!!!OnURLFetchComplete"; - int response_code = source->GetResponseCode(); - bool failure = response_code == net::URLFetcher::ResponseCode::RESPONSE_CODE_INVALID || - !source->GetStatus().is_success(); - if (failure) { - LOG(ERROR) << "Ledger fetcher HTTP error: " << response_code; - } - std::string response; - source->GetResponseAsString(&response); - - if (url_fetchers_.size()) { - url_fetchers_.front()->callback_.Run(!failure, response, *url_fetchers_.front()->extraData_); - url_fetchers_.pop_front(); - } - } - -} // namespace braveledger_bat_client_webrequest diff --git a/src/bat_client_webrequest_chromium.h b/src/bat_client_webrequest_chromium.h deleted file mode 100644 index 69875951479f..000000000000 --- a/src/bat_client_webrequest_chromium.h +++ /dev/null @@ -1,73 +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 BRAVELEDGER_BAT_CLIENT_WEBREQUEST_CHROMIUM_H_ -#define BRAVELEDGER_BAT_CLIENT_WEBREQUEST_CHROMIUM_H_ - -#include -#include -#include - -#include "bat_client_webrequest.h" -#include "net/url_request/url_fetcher_delegate.h" - -// We have to implement another fetcher class for iOS -namespace net { -class URLFetcher; -class UploadDataStream; -} - -namespace braveledger_bat_client_webrequest { - -class BatClientWebRequestChromium: public BatClientWebRequest, - public net::URLFetcherDelegate { - public: - struct URL_FETCH_REQUEST { - URL_FETCH_REQUEST(); - ~URL_FETCH_REQUEST(); - - std::unique_ptr url_fetcher_; - FetchCallback callback_; - std::unique_ptr extraData_; - }; - - BatClientWebRequestChromium(); - ~BatClientWebRequestChromium() final; - - void run(const std::string& url, FetchCallback callback, - const std::vector& headers, const std::string& content, - const std::string& contentType, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData, - const URL_METHOD& method) override; - void Stop() override; - void Start() override; - - void OnURLFetchComplete(const net::URLFetcher* source) final; - void OnURLFetchDownloadProgress(const net::URLFetcher* source, - int64_t current, - int64_t total, - int64_t current_network_bytes) final { - } - - void OnURLFetchUploadProgress(const net::URLFetcher* source, - int64_t current, - int64_t total) final { - } - - private: - void runOnThread(const std::string& url, FetchCallback callback, - const std::vector& headers, const std::string& content, - const std::string& contentType, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData, - const URL_METHOD& method); - - std::unique_ptr CreateUploadStream(const std::string& stream); - - std::list> url_fetchers_; - bool running_; - - // std::unique_ptr url_fetcher_; -}; - -} // namespace braveledger_bat_client_webrequest - -#endif // BRAVELEDGER_BAT_CLIENT_WEBREQUEST_CHROMIUM_H_ diff --git a/src/bat_get_media.cc b/src/bat_get_media.cc index f6253bb2609d..fd750a7c1ae4 100644 --- a/src/bat_get_media.cc +++ b/src/bat_get_media.cc @@ -9,16 +9,18 @@ #include "bat_get_media.h" #include "bat_helper.h" +#include "ledger_impl.h" #include "leveldb/db.h" #include "rapidjson_bat_helper.h" #include "static_values.h" #include "third_party/leveldatabase/env_chromium.h" +using namespace std::placeholders; + namespace braveledger_bat_get_media { -// TODO(bridiver) - revisit this class for possible delegation to deal with -// threading and file location issues -BatGetMedia::BatGetMedia(): +BatGetMedia::BatGetMedia(bat_ledger::LedgerImpl* ledger): + ledger_(ledger), level_db_(nullptr) { } @@ -54,7 +56,7 @@ bool BatGetMedia::Init() { } void BatGetMedia::getPublisherFromMediaProps(const std::string& mediaId, const std::string& mediaKey, const std::string& providerName, - const uint64_t& duration, const braveledger_bat_helper::TWITCH_EVENT_INFO& twitchEventInfo, braveledger_bat_helper::GetMediaPublisherInfoCallback callback) { + uint64_t duration, const braveledger_bat_helper::TWITCH_EVENT_INFO& twitchEventInfo, braveledger_bat_helper::GetMediaPublisherInfoCallback callback) { // Check if the publisher's info is already cached if (EnsureInitialized()) { @@ -82,7 +84,7 @@ void BatGetMedia::getPublisherFromMediaProps(const std::string& mediaId, const s } } - braveledger_bat_helper::run_runnable(callback, std::cref(realDuration), std::cref(publisherInfo) ); + ledger_->RunTask(std::bind(callback, realDuration, publisherInfo)); return; } } @@ -97,16 +99,23 @@ void BatGetMedia::getPublisherFromMediaProps(const std::string& mediaId, const s extraData.string1 = providerName; extraData.string2 = mediaURL; { + // TODO(bridiver) - need to find out what is going on with mapCallbacks_ + // it's keyed to the mediaKey, but every lookup just gets the last entry + // which doesn't seem right to me std::lock_guard guard(callbacks_access_mutex_); DCHECK(mapCallbacks_.find(mediaKey) == mapCallbacks_.end()); mapCallbacks_[mediaKey] = callback; } if (YOUTUBE_MEDIA_TYPE == providerName) { - - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatGetMedia::getPublisherFromMediaPropsCallback); - braveledger_bat_helper::batClientWebRequest->run((std::string)YOUTUBE_PROVIDER_URL + "?format=json&url=" + mediaURLEncoded, - runnable, std::vector(), "", "", extraData, braveledger_bat_client_webrequest::URL_METHOD::GET); - + // TODO(bridiver) - this is also an issue because we're making these calls from the IO thread + auto request = ledger_->LoadURL((std::string)YOUTUBE_PROVIDER_URL + "?format=json&url=" + mediaURLEncoded, + std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request), + std::bind(&BatGetMedia::getPublisherFromMediaPropsCallback, + this, + _1, + _2, + extraData)); } else if (TWITCH_MEDIA_TYPE == providerName) { braveledger_bat_helper::MEDIA_PUBLISHER_INFO publisherInfo; publisherInfo.favIconURL_ = ""; @@ -142,7 +151,8 @@ void BatGetMedia::getPublisherFromMediaProps(const std::string& mediaId, const s braveledger_bat_helper::GetMediaPublisherInfoCallback callback = iter->second; mapCallbacks_.erase(iter); - braveledger_bat_helper::run_runnable (callback, std::cref(realDuration), std::cref(publisherInfo) ); + // TODO(bridiver) - why are we using a different callback here than the one that was passed in? + ledger_->RunTask(std::bind(callback, realDuration, publisherInfo)); } } } @@ -246,9 +256,14 @@ void BatGetMedia::getPublisherFromMediaPropsCallback(bool result, const std::str newExtraData.string3 = publisherURL; newExtraData.string4 = publisherName; - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatGetMedia::getPublisherInfoCallback); - braveledger_bat_helper::batClientWebRequest->run(publisherURL, runnable, - std::vector(), "", "", newExtraData, braveledger_bat_client_webrequest::URL_METHOD::GET); + auto request = ledger_->LoadURL(publisherURL, + std::vector(), "", "", ledger::URL_METHOD::GET, &handler_); + handler_.AddRequestHandler(std::move(request), + std::bind(&BatGetMedia::getPublisherInfoCallback, + this, + _1, + _2, + newExtraData)); } } @@ -294,8 +309,8 @@ void BatGetMedia::getPublisherInfoCallback(bool result, const std::string& respo std::string medPubJson; braveledger_bat_helper::saveToJsonString(publisherInfo, medPubJson); - auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatGetMedia::saveMediaPublisherInfo, extraData.string5, medPubJson); - braveledger_bat_helper::PostTask(runnable); + auto io_task = std::bind(&BatGetMedia::saveMediaPublisherInfo, this, extraData.string5, medPubJson); + ledger_->RunIOTask(io_task); { std::lock_guard guard(callbacks_access_mutex_); @@ -304,7 +319,7 @@ void BatGetMedia::getPublisherInfoCallback(bool result, const std::string& respo DCHECK(iter != mapCallbacks_.end()); braveledger_bat_helper::GetMediaPublisherInfoCallback callback = iter->second; mapCallbacks_.erase(iter); - braveledger_bat_helper::run_runnable (callback, std::cref(extraData.value1), std::cref(publisherInfo) ); + callback(extraData.value1, publisherInfo); } } } diff --git a/src/bat_get_media.h b/src/bat_get_media.h index 3f3d5116fabb..808e9ab81eee 100644 --- a/src/bat_get_media.h +++ b/src/bat_get_media.h @@ -10,6 +10,11 @@ #include #include "bat_helper.h" +#include "url_request_handler.h" + +namespace bat_ledger { +class LedgerImpl; +} namespace leveldb { class DB; @@ -20,11 +25,11 @@ namespace braveledger_bat_get_media { class BatGetMedia { public: - BatGetMedia(); + BatGetMedia(bat_ledger::LedgerImpl* ledger); ~BatGetMedia(); void getPublisherFromMediaProps(const std::string& mediaId, const std::string& mediaKey, const std::string& providerName, - const uint64_t& duration, const braveledger_bat_helper::TWITCH_EVENT_INFO& twitchEventInfo, braveledger_bat_helper::GetMediaPublisherInfoCallback callback); + uint64_t duration, const braveledger_bat_helper::TWITCH_EVENT_INFO& twitchEventInfo, braveledger_bat_helper::GetMediaPublisherInfoCallback callback); private: bool Init(); @@ -38,9 +43,12 @@ class BatGetMedia { uint64_t getTwitchDuration(const braveledger_bat_helper::TWITCH_EVENT_INFO& oldEventInfo, const braveledger_bat_helper::TWITCH_EVENT_INFO& newEventInfo); std::string getTwitchStatus(const braveledger_bat_helper::TWITCH_EVENT_INFO& oldEventInfo, const braveledger_bat_helper::TWITCH_EVENT_INFO& newEventInfo); + bat_ledger::LedgerImpl* ledger_; // NOT OWNED std::unique_ptr level_db_; std::map mapCallbacks_; std::mutex callbacks_access_mutex_; + + bat_ledger::URLRequestHandler handler_; }; } // namespace braveledger_bat_get_media diff --git a/src/bat_helper.cc b/src/bat_helper.cc index bc428bc744b8..9f21d0b11a95 100644 --- a/src/bat_helper.cc +++ b/src/bat_helper.cc @@ -1510,46 +1510,6 @@ namespace braveledger_bat_helper { return time(0); } - void saveState(const CLIENT_STATE_ST& state) { - - std::string data; - braveledger_bat_helper::saveToJsonString(state, data); - //LOG(ERROR) << "!!!saveState == " << data; - - std::string ledger_state_file_path; - std::string root; - braveledger_bat_helper::getHomeDir(root); - braveledger_bat_helper::appendPath(root, LEDGER_STATE_FILENAME, ledger_state_file_path); - - auto runnable = braveledger_bat_helper::bat_fun_binder(&braveledger_bat_helper::writeFileNoReturn, ledger_state_file_path, data); - braveledger_bat_helper::PostTask(runnable); - } - - void loadState(ReadStateCallback callback) { - - auto runnable = braveledger_bat_helper::bat_fun_binder(&braveledger_bat_helper::readStateFile, callback); - braveledger_bat_helper::PostTask(runnable); - } - - void savePublisherState(const PUBLISHER_STATE_ST& state) { - std::string data; - braveledger_bat_helper::saveToJsonString(state, data); - - std::string ledger_pub_state_file_path; - std::string root; - braveledger_bat_helper::getHomeDir(root); - braveledger_bat_helper::appendPath(root, LEDGER_PUBLISHER_STATE_FILENAME, ledger_pub_state_file_path); - - auto runnable = braveledger_bat_helper::bat_fun_binder(&braveledger_bat_helper::writeFileNoReturn, ledger_pub_state_file_path, data); - braveledger_bat_helper::PostTask(runnable); - } - - void loadPublisherState(ReadPublisherStateCallback callback) { - - auto runnable = braveledger_bat_helper::bat_fun_binder(&braveledger_bat_helper::readPublisherStateFile, callback); - braveledger_bat_helper::PostTask(runnable); - } - void getUrlQueryParts(const std::string& query, std::map& parts) { std::vector vars; split(vars, query, '&'); @@ -1656,52 +1616,4 @@ namespace braveledger_bat_helper { return duration; } - void readStateFile(ReadStateCallback callback) { - std::string file_path; - std::string root; - braveledger_bat_helper::getHomeDir(root); - std::ostringstream data; - - braveledger_bat_helper::appendPath(root, LEDGER_STATE_FILENAME, file_path); - bool succeded = braveledger_bat_helper::readFile(file_path, data); - if (succeded) - { - CLIENT_STATE_ST state; - braveledger_bat_helper::loadFromJson(state, data.str()); - braveledger_bat_helper::run_runnable (callback, true, std::cref(state)); - } - else - { - CLIENT_STATE_ST temp; - braveledger_bat_helper::run_runnable(callback, false, std::cref(temp)); - } - } - - - void readPublisherStateFile(ReadPublisherStateCallback callback) { - std::string file_path; - std::string root; - braveledger_bat_helper::getHomeDir(root); - std::ostringstream data; - - braveledger_bat_helper::appendPath(root, LEDGER_PUBLISHER_STATE_FILENAME, file_path); - bool succeded = braveledger_bat_helper::readFile(file_path, data); - if (succeded) - { - PUBLISHER_STATE_ST state; - braveledger_bat_helper::loadFromJson(state, data.str()); - braveledger_bat_helper::run_runnable(callback, true, std::cref(state)); - } - else - { - PUBLISHER_STATE_ST temp; - braveledger_bat_helper::run_runnable(callback, false, std::cref(temp)); - } - } - - void writeFileNoReturn(const std::string & path, const std::string& data) - { - //ignoring return - writeFile(path, data); - } } // namespace braveledger_bat_helper diff --git a/src/bat_helper.h b/src/bat_helper.h index fefad58719b9..1905f9b20ca0 100644 --- a/src/bat_helper.h +++ b/src/bat_helper.h @@ -307,9 +307,13 @@ namespace braveledger_bat_helper { std::map rates_; std::string amount_; std::string currency_; - SimpleCallback ledgerCallback_; }; + using GetMediaPublisherInfoSignature = void(uint64_t, const braveledger_bat_helper::MEDIA_PUBLISHER_INFO&); + using SaveVisitSignature = void(const std::string&, uint64_t); + using GetMediaPublisherInfoCallback = std::function; + using SaveVisitCallback = std::function; + bool getJSONValue(const std::string& fieldName, const std::string& json, std::string & value); bool getJSONList(const std::string& fieldName, const std::string& json, std::vector & value); @@ -359,14 +363,6 @@ namespace braveledger_bat_helper { uint64_t currentTime(); - void saveState(const CLIENT_STATE_ST& state); - - void loadState(ReadStateCallback callback); - - void savePublisherState(const PUBLISHER_STATE_ST& state); - - void loadPublisherState(ReadPublisherStateCallback callback); - void getUrlQueryParts(const std::string& query, std::map& parts); void getTwitchParts(const std::string& query, std::vector>& parts); @@ -376,14 +372,6 @@ namespace braveledger_bat_helper { std::string getMediaKey(const std::string& mediaId, const std::string& type); uint64_t getMediaDuration(const std::map& data, const std::string& mediaKey, const std::string& type); - - void readStateFile(ReadStateCallback callback); - - void readPublisherStateFile(ReadPublisherStateCallback callback); - - //temporary solution: to run ( void writeFile(args) ) as a Chromium Task - void writeFileNoReturn(const std::string & path, const std::string& data); - } // namespace braveledger_bat_helper #endif // BRAVELEDGER_BAT_HELPER_H_ diff --git a/src/bat_helper_platform.cc b/src/bat_helper_platform.cc index e51bc753b7a7..56c48439b05d 100644 --- a/src/bat_helper_platform.cc +++ b/src/bat_helper_platform.cc @@ -5,9 +5,10 @@ #include "bat_helper_platform.h" #if defined CHROMIUM_BUILD -#include "base/guid.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/path_service.h" #include "base/logging.h" -#include "base/sequenced_task_runner.h" #include "base/strings/utf_string_conversions.h" #include "base/task_scheduler/post_task.h" #include "url/url_canon_stdstring.h" @@ -18,9 +19,6 @@ namespace braveledger_bat_helper { -#if defined CHROMIUM_BUILD - std::unique_ptr batClientWebRequest(new BatClientWebRequestChromium); -#endif scoped_refptr task_runner_; void DecodeURLChars(const std::string& input, std::string& output) { @@ -33,16 +31,6 @@ namespace braveledger_bat_helper { #endif } - std::string GenerateGUID() - { -#if defined CHROMIUM_BUILD - return base::GenerateGUID(); -#else - //TODO: to implement - return "please implement"; -#endif - } - void encodeURIComponent(const std::string & instr, std::string & outstr) { #if defined CHROMIUM_BUILD @@ -79,39 +67,4 @@ namespace braveledger_bat_helper { #endif } - bool writeFile(const std::string & path, const std::string& data) - { -#if defined CHROMIUM_BUILD - base::FilePath dirToSave (path.c_str()); - - int succeded = base::WriteFile(dirToSave, data.c_str(), data.length()); - LOG(ERROR) << "writeToFile to: " << dirToSave << " : " << data.length() << " : " << succeded; - assert(succeded != -1); - return (succeded != -1) ? true : false; -#else - //TODO: to implement - assert(false); - return false; -#endif - } - - - bool readFile(const std::string & path, std::ostringstream & ss) - { -#if defined CHROMIUM_BUILD - bool succeded = false; - base::FilePath path_to_file (path.c_str()); - base::PathExists(path_to_file); - if (base::PathExists(path_to_file)) { - std::string str; - succeded = base::ReadFileToString(path_to_file, &str); - ss << str; - } - return succeded; -#else - assert(false); - return false; -#endif - } - } // namespace braveledger_bat_helper diff --git a/src/bat_helper_platform.h b/src/bat_helper_platform.h index f68a8afe7e67..c8841f1984b7 100644 --- a/src/bat_helper_platform.h +++ b/src/bat_helper_platform.h @@ -5,176 +5,17 @@ #ifndef BRAVELEDGER_BAT_HELPER_PLATFORM_H_ #define BRAVELEDGER_BAT_HELPER_PLATFORM_H_ -#include "bat_client_webrequest.h" +#include #if defined CHROMIUM_BUILD -#include - -#include "base/bind.h" -#include "base/callback.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" #include "base/logging.h" -#include "base/path_service.h" -#include "base/task_scheduler/post_task.h" -#include "bat_client_webrequest_chromium.h" - -using braveledger_bat_client_webrequest::BatClientWebRequestChromium; #else -#include -#include -#include -#endif - -namespace braveledger_bat_helper { - - struct FETCH_CALLBACK_EXTRA_DATA_ST; - struct CLIENT_STATE_ST; - struct PUBLISHER_STATE_ST; - struct MEDIA_PUBLISHER_INFO; - - using ReadStateCallbackSignature = void (bool, const CLIENT_STATE_ST&); - using ReadPublisherStateCallbackSignature = void (bool, const PUBLISHER_STATE_ST&); - using SimpleCallbackSignature = void (const std::string&); - using GetMediaPublisherInfoSignature = void(const uint64_t&, const braveledger_bat_helper::MEDIA_PUBLISHER_INFO&); - using SaveVisitSignature = void(const std::string&, const uint64_t&); - -#if defined CHROMIUM_BUILD - using ReadStateCallback = base::Callback; - using ReadPublisherStateCallback = base::Callback; - using SimpleCallback = base::Callback; - using GetMediaPublisherInfoCallback = base::Callback; - using SaveVisitCallback = base::Callback; - - //Binds a member function of an instance of the type (Base) which has a signature (Signature) to a callback wrapper. - template - decltype(auto) bat_mem_fun_binder(BaseType & instance, Signature BaseType::* ptr_to_mem, Args... args) - { - return base::Bind(ptr_to_mem, base::Unretained(&instance), args...); - } - - template - decltype(auto) bat_fun_binder(Signature ptr_to_fun, Args... args) - { - return base::Bind(ptr_to_fun, args...); - } - - //working with Chromium Callback.Run() - template - decltype(auto) run_runnable(Runnable & runnable, Args... args) - { - return runnable.Run(args...); - } - -#define bat_mem_fun_binder1 bat_mem_fun_binder -#define bat_mem_fun_binder2 bat_mem_fun_binder -#define bat_mem_fun_binder3 bat_mem_fun_binder - -#define bat_fun_binder1 bat_fun_binder -#define bat_fun_binder2 bat_fun_binder -#define bat_fun_binder3 bat_fun_binder - - extern std::unique_ptr batClientWebRequest; - extern scoped_refptr task_runner_; - - template - void PostTask(Runnable runnable) - { - // TODO(bridiver) - this is a super hacky temporary workaround to fix - // CalledOnValidThread errors and avoid creating a new task runner for - // every task - if (!task_runner_.get()) { - task_runner_ = - base::CreateSequencedTaskRunnerWithTraits({ - base::MayBlock(), - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN }); - } - task_runner_->PostTask(FROM_HERE, runnable); - } - -#else - using ReadStateCallback = std::function; - using ReadPublisherStateCallback = std::function ; - using SimpleCallback = std::function; - using GetMediaPublisherInfoCallback = std::function; - using SaveVisitCallback = std::function; - - //Binds a member function of an instance of the type (Base) which has a signature (Signature) to a callback wrapper. - template - decltype(auto) bat_mem_fun_binder(BaseType & instance, Signature BaseType::* ptr_to_mem, Args ... args) - { - return std::bind(ptr_to_mem, &instance, args...); - } - - template - decltype(auto) bat_mem_fun_binder1(BaseType & instance, Signature BaseType::* ptr_to_mem) - { - using namespace std::placeholders; - return std::bind(ptr_to_mem, &instance, _1); - } - - template - decltype(auto) bat_mem_fun_binder2(BaseType & instance, Signature BaseType::* ptr_to_mem) - { - using namespace std::placeholders; - return std::bind(ptr_to_mem, &instance, _1, _2); - } - - template - decltype(auto) bat_mem_fun_binder3(BaseType & instance, Signature BaseType::* ptr_to_mem) - { - using namespace std::placeholders; - return std::bind(ptr_to_mem, &instance, _1, _2, _3); - } - - template - decltype(auto) bat_fun_binder(Signature ptr_to_fun, Args... args) - { - return std::bind(ptr_to_fun, args...); - } - - template - decltype(auto) bat_fun_binder1(Signature ptr_to_fun) - { - using namespace std::placeholders; - return std::bind(ptr_to_fun, _1); - } - - template - decltype(auto) bat_fun_binder2(Signature ptr_to_fun) - { - using namespace std::placeholders; - return std::bind(ptr_to_fun, _1, _2); - } - - template - decltype(auto) bat_fun_binder3(Signature ptr_to_fun) - { - using namespace std::placeholders; - return std::bind(ptr_to_fun, _1, _2, _3); - } - - //working with C++ function.operator() - template - decltype(auto) run_runnable(Runnable & runnable, Args ... args) - { - return runnable(args...); - } - - template - void PostTask(Runnable runnable, Args ... args) - { - //TODO: implement! - runnable(args...); - } - - // Chromium debug macros redefined - //TODO: implement! +// Chromium debug macros redefined +//TODO: implement! #define DCHECK assert #define LOG(LEVEL) std::cerr<< std::endl<< #LEVEL << ": " - #endif - std::string GenerateGUID(); +namespace braveledger_bat_helper { void encodeURIComponent(const std::string & instr, std::string & outstr); @@ -184,11 +25,6 @@ namespace braveledger_bat_helper { void appendPath(const std::string& root, const std::string& leaf, std::string & path); - //overwrites file if exist - bool writeFile(const std::string & path, const std::string& data); - - bool readFile(const std::string & path, std::ostringstream & ss); - } // namespace braveledger_bat_helper #endif //BRAVELEDGER_BAT_HELPER_PLATFORM_H_ diff --git a/src/bat_publishers.cc b/src/bat_publishers.cc index 267a4a027f26..58ef63ef7a0f 100644 --- a/src/bat_publishers.cc +++ b/src/bat_publishers.cc @@ -8,6 +8,7 @@ #include #include "bat_helper.h" +#include "ledger_impl.h" #include "leveldb/db.h" #include "rapidjson_bat_helper.h" #include "static_values.h" @@ -41,7 +42,8 @@ void CloseDB(leveldb::DB* db) { } -BatPublishers::BatPublishers(): +BatPublishers::BatPublishers(bat_ledger::LedgerImpl* ledger): + ledger_(ledger), level_db_(nullptr), state_(new braveledger_bat_helper::PUBLISHER_STATE_ST) { calcScoreConsts(); @@ -49,9 +51,8 @@ BatPublishers::BatPublishers(): BatPublishers::~BatPublishers() { if (level_db_.get()) { - auto runnable = braveledger_bat_helper::bat_fun_binder(&CloseDB, - level_db_.release()); - braveledger_bat_helper::PostTask(runnable); + auto io_task = std::bind(&CloseDB, level_db_.release()); + ledger_->RunIOTask(io_task); } } @@ -113,24 +114,11 @@ void BatPublishers::loadPublishers() { delete it; } -void BatPublishers::loadStateCallback(bool result, const braveledger_bat_helper::PUBLISHER_STATE_ST& state) { - if (!result) { - return; - } - state_.reset(new braveledger_bat_helper::PUBLISHER_STATE_ST(state)); - calcScoreConsts(); -} - void BatPublishers::initSynopsis() { - - braveledger_bat_helper::ReadPublisherStateCallback runnable1 = braveledger_bat_helper::bat_mem_fun_binder2(*this, &BatPublishers::loadStateCallback); - braveledger_bat_helper::loadPublisherState(runnable1); - - auto runnable2 = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::loadPublishers); - braveledger_bat_helper::PostTask(runnable2); + ledger_->LoadPublisherState(this); } -void BatPublishers::saveVisitInternal(const std::string& publisher, const uint64_t& duration, +void BatPublishers::saveVisitInternal(const std::string& publisher, uint64_t duration, braveledger_bat_helper::SaveVisitCallback callback) { double currentScore = concaveScore(duration); @@ -163,7 +151,7 @@ void BatPublishers::saveVisitInternal(const std::string& publisher, const uint64 assert(status.ok()); } - braveledger_bat_helper::run_runnable (callback, publisher, std::cref(verifiedTimestamp) ); + ledger_->RunTask(std::bind(callback, publisher, verifiedTimestamp)); synopsisNormalizerInternal(); } @@ -174,8 +162,12 @@ void BatPublishers::saveVisit(std::string publisher, uint64_t duration, braveled } // TODO checks if the publisher verified, disabled and etc - auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::saveVisitInternal, publisher, duration, callback); - braveledger_bat_helper::PostTask(runnable); + auto io_task = std::bind(&BatPublishers::saveVisitInternal, + this, + publisher, + duration, + callback); + ledger_->RunIOTask(io_task); } void BatPublishers::setPublisherTimestampVerifiedInternal(const std::string& publisher, @@ -206,8 +198,8 @@ void BatPublishers::setPublisherTimestampVerifiedInternal(const std::string& pub } void BatPublishers::setPublisherTimestampVerified(std::string publisher, uint64_t verifiedTimestamp, bool verified) { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::setPublisherTimestampVerifiedInternal, publisher, verifiedTimestamp, verified); - braveledger_bat_helper::PostTask(runnable); + auto io_task = std::bind(&BatPublishers::setPublisherTimestampVerifiedInternal, this, publisher, verifiedTimestamp, verified); + ledger_->RunIOTask(io_task); } void BatPublishers::setPublisherFavIconInternal(const std::string& publisher, const std::string& favicon_url) { @@ -234,8 +226,8 @@ void BatPublishers::setPublisherFavIconInternal(const std::string& publisher, co } void BatPublishers::setPublisherFavIcon(std::string publisher, std::string favicon_url) { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::setPublisherFavIconInternal, publisher, favicon_url); - braveledger_bat_helper::PostTask(runnable); + auto io_task = std::bind(&BatPublishers::setPublisherFavIconInternal, this, publisher, favicon_url); + ledger_->RunIOTask(io_task); } void BatPublishers::setPublisherIncludeInternal(const std::string& publisher, const bool& include) { @@ -265,8 +257,8 @@ void BatPublishers::setPublisherIncludeInternal(const std::string& publisher, co } void BatPublishers::setPublisherInclude(std::string publisher, bool include) { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::setPublisherIncludeInternal, publisher, include); - braveledger_bat_helper::PostTask(runnable); + auto io_task = std::bind(&BatPublishers::setPublisherIncludeInternal, this, publisher, include); + ledger_->RunIOTask(io_task); } void BatPublishers::setPublisherDeletedInternal(const std::string& publisher, const bool& deleted) { @@ -296,8 +288,8 @@ void BatPublishers::setPublisherDeletedInternal(const std::string& publisher, co } void BatPublishers::setPublisherDeleted(std::string publisher, bool deleted) { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::setPublisherDeletedInternal, publisher, deleted); - braveledger_bat_helper::PostTask(runnable); + auto io_task = std::bind(&BatPublishers::setPublisherDeletedInternal, this, publisher, deleted); + ledger_->RunIOTask(io_task); } void BatPublishers::setPublisherPinPercentageInternal(const std::string& publisher, const bool& pinPercentage) { @@ -327,25 +319,25 @@ void BatPublishers::setPublisherPinPercentageInternal(const std::string& publish } void BatPublishers::setPublisherPinPercentage(std::string publisher, bool pinPercentage) { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::setPublisherPinPercentageInternal, publisher, pinPercentage); - braveledger_bat_helper::PostTask(runnable); + auto io_task = std::bind(&BatPublishers::setPublisherPinPercentageInternal, this, publisher, pinPercentage); + ledger_->RunIOTask(io_task); } void BatPublishers::setPublisherMinVisitTime(const uint64_t& duration) { // In milliseconds state_->min_pubslisher_duration_ = duration; //TODO: conversion from 'const uint64_t' to 'unsigned int', possible loss of data - braveledger_bat_helper::savePublisherState(*state_); + saveState(); synopsisNormalizer(); } void BatPublishers::setPublisherMinVisits(const unsigned int& visits) { state_->min_visits_ = visits; - braveledger_bat_helper::savePublisherState(*state_); + saveState(); synopsisNormalizer(); } void BatPublishers::setPublisherAllowNonVerified(const bool& allow) { state_->allow_non_verified_ = allow; - braveledger_bat_helper::savePublisherState(*state_); + saveState(); synopsisNormalizer(); } @@ -453,8 +445,8 @@ void BatPublishers::synopsisNormalizerInternal() { } void BatPublishers::synopsisNormalizer() { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::synopsisNormalizerInternal); - braveledger_bat_helper::PostTask(runnable); + auto io_task = std::bind(&BatPublishers::synopsisNormalizerInternal, this); + ledger_->RunIOTask(io_task); } std::vector BatPublishers::winners(const unsigned int& ballots) { @@ -515,4 +507,38 @@ double BatPublishers::concaveScore(const uint64_t& duration) { return (std::sqrt(b2_ + a4_ * duration) - b_) / (double)a2_; } +void BatPublishers::saveState() { + std::string data; + braveledger_bat_helper::saveToJsonString(*state_, data); + ledger_->SavePublisherState(data, this); +} + +void BatPublishers::loadState(bool success, const std::string& data) { + if (!success) { + // TODO error handling + return; + } + + braveledger_bat_helper::PUBLISHER_STATE_ST state; + braveledger_bat_helper::loadFromJson(state, data.c_str()); + state_.reset(new braveledger_bat_helper::PUBLISHER_STATE_ST(state)); + calcScoreConsts(); +} + +void BatPublishers::OnLedgerStateLoaded(ledger::Result result, + const std::string& data) { + +} + +void BatPublishers::OnPublisherStateLoaded(ledger::Result result, + const std::string& data) { + if (result != ledger::Result::OK) { + LOG(ERROR) << "Could not load publisher state"; + return; + // TODO - error handling + } + auto io_task = std::bind(&BatPublishers::loadPublishers, this); + ledger_->RunIOTask(io_task); +} + } // namespace braveledger_bat_publisher diff --git a/src/bat_publishers.h b/src/bat_publishers.h index 3972c8b043d1..bffbbf3316bd 100644 --- a/src/bat_publishers.h +++ b/src/bat_publishers.h @@ -11,8 +11,13 @@ #include #include +#include "bat/ledger/ledger_callback_handler.h" #include "bat_helper.h" +namespace bat_ledger { +class LedgerImpl; +} + namespace leveldb { class DB; } @@ -23,16 +28,16 @@ struct PUBLISHER_STATE_ST; namespace braveledger_bat_publishers { -class BatPublishers { +class BatPublishers : public ledger::LedgerCallbackHandler { public: - BatPublishers(); + BatPublishers(bat_ledger::LedgerImpl* ledger); - ~BatPublishers(); + ~BatPublishers() override; void initSynopsis(); - void saveVisit(std::string publisher, uint64_t duration, braveledger_bat_helper::SaveVisitCallback callback, bool ignoreMinTime); + void saveVisit(std::string publisher, uint64_t duration, braveledger_bat_helper::SaveVisitCallback callback, bool ignoreMinTime); void setPublisherTimestampVerified(std::string publisher, uint64_t verifiedTimestamp, bool verified); @@ -56,15 +61,25 @@ class BatPublishers { bool isEligableForContribution(const braveledger_bat_helper::PUBLISHER_DATA_ST& publisherData); + void loadState(bool success, const std::string& data); + private: + // LedgerCallbackHandler impl + void OnLedgerStateLoaded(ledger::Result result, + const std::string& data) override; + void OnPublisherStateLoaded(ledger::Result result, + const std::string& data) override; + double concaveScore(const uint64_t& duration); + void saveState(); + bool Init(); bool EnsureInitialized(); void loadPublishers(); - void saveVisitInternal(const std::string& publisher, const uint64_t& duration, + void saveVisitInternal(const std::string& publisher, uint64_t duration, braveledger_bat_helper::SaveVisitCallback callback); void setPublisherFavIconInternal(const std::string& publisher, const std::string& favicon_url); @@ -78,8 +93,6 @@ class BatPublishers { void setPublisherPinPercentageInternal(const std::string& publisher, const bool& pinPercentage); - void loadStateCallback(bool result, const braveledger_bat_helper::PUBLISHER_STATE_ST& state); - void calcScoreConsts(); void synopsisNormalizer(); @@ -88,6 +101,8 @@ class BatPublishers { bool isPublisherVisible(const braveledger_bat_helper::PUBLISHER_ST& publisher_st); + bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::vector topN(); std::map publishers_; diff --git a/src/ledger.cc b/src/ledger.cc deleted file mode 100644 index 0eb0504d637a..000000000000 --- a/src/ledger.cc +++ /dev/null @@ -1,345 +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 "bat/ledger/ledger.h" - -#include "bat_client.h" -#include "bat_get_media.h" -#include "bat_helper.h" -#include "bat_publishers.h" -#include "static_values.h" - -#include "rapidjson_bat_helper.h" - -using namespace braveledger_bat_client; -using namespace braveledger_bat_publishers; -using namespace braveledger_bat_get_media; - -namespace braveledger_ledger { - - Ledger::Ledger() : - bat_get_media_(new BatGetMedia()) { - // TODO(bridiver) super hacky workaround for web requests sent after Ledger is destroyed - braveledger_bat_helper::batClientWebRequest->Start(); - } - - Ledger::~Ledger() { - // TODO(bridiver) super hacky workaround for web requests sent after Ledger is destroyed - braveledger_bat_helper::batClientWebRequest->Stop(); - } - - void Ledger::createWallet() { - initSynopsis(); - if (!bat_client_) { - bat_client_.reset (new BatClient()); - } - LOG(ERROR) << "here 2"; - bat_client_->loadStateOrRegisterPersona(); - } - - void Ledger::initSynopsis() { - if (!bat_publishers_) { - bat_publishers_.reset(new BatPublishers()); - } - bat_publishers_->initSynopsis(); - } - - bool Ledger::isBatClientExist() { - if (!bat_client_) { - LOG(ERROR) << "ledger bat_client is not exist"; - - return false; - } - - return true; - } - - bool Ledger::isBatPublisherExist() { - if (!bat_publishers_) { - LOG(ERROR) << "ledger bat_publisher is not exist"; - return false; - } - - return true; - } - - void Ledger::getBalance() { - if (!isBatClientExist()) { - assert(false); - - return; - } - braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST extraData; - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &Ledger::walletPropertiesCallback); - bat_client_->getWalletProperties(runnable, extraData); - } - - void Ledger::walletPropertiesCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { - if (!result) { - // TODO errors handling - return; - } - braveledger_bat_helper::WALLET_PROPERTIES_ST walletProperties; - braveledger_bat_helper::loadFromJson(walletProperties, response); - // TODO send the balance to the UI via observer or callback - } - - void Ledger::saveVisit(const std::string& publisher, const uint64_t& duration, bool ignoreMinTime) { - // TODO debug - //bat_client_->recoverWallet(bat_client_->getWalletPassphrase()); - // - if (!isBatPublisherExist()) { - assert(false); - - return; - } - auto runnable = braveledger_bat_helper::bat_mem_fun_binder2(*this, &Ledger::saveVisitCallback); - bat_publishers_->saveVisit(publisher, duration, runnable, ignoreMinTime); - } - - void Ledger::saveVisitCallback(const std::string& publisher, const uint64_t& verifiedTimestamp) { - if (!isBatClientExist()) { - assert(false); - - return; - } - uint64_t publisherTimestamp = bat_client_->getPublisherTimestamp(); - if (publisherTimestamp <= verifiedTimestamp) { - //to do debug - LOG(ERROR) << "!!!reconcile"; - run(0); - // - return; - } - braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST extraData; - extraData.value1 = publisherTimestamp; - extraData.string1 = publisher; - // Update publisher verified or not flag - //LOG(ERROR) << "!!!getting publisher info"; - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &Ledger::publisherInfoCallback); - bat_client_->publisherInfo(publisher, runnable, extraData); - } - - void Ledger::publisherInfoCallback(bool result, const std::string& response, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { - //LOG(ERROR) << "!!!got publisher info"; - if (!result) { - // TODO errors handling - return; - } - bool verified = false; - braveledger_bat_helper::getJSONPublisherVerified(response, verified); - if (!isBatPublisherExist()) { - assert(false); - - return; - } - bat_publishers_->setPublisherTimestampVerified(extraData.string1, extraData.value1, verified); - //to do debug - //LOG(ERROR) << "!!!reconcile"; - //run(0); - // - } - - void Ledger::favIconUpdated(const std::string& publisher, const std::string& favicon_url) { - if (!isBatPublisherExist()) { - assert(false); - - return; - } - bat_publishers_->setPublisherFavIcon(publisher, favicon_url); - } - - void Ledger::setPublisherInclude(const std::string& publisher, const bool& include) { - if (!isBatPublisherExist()) { - assert(false); - - return; - } - bat_publishers_->setPublisherInclude(publisher, include); - } - - void Ledger::setPublisherDeleted(const std::string& publisher, const bool& deleted) { - if (!isBatPublisherExist()) { - assert(false); - - return; - } - bat_publishers_->setPublisherDeleted(publisher, deleted); - } - - void Ledger::setPublisherPinPercentage(const std::string& publisher, const bool& pinPercentage) { - if (!isBatPublisherExist()) { - assert(false); - - return; - } - bat_publishers_->setPublisherPinPercentage(publisher, pinPercentage); - } - - void Ledger::setPublisherMinVisitTime(const uint64_t& duration) { // In milliseconds - if (!isBatPublisherExist()) { - assert(false); - - return; - } - bat_publishers_->setPublisherMinVisitTime(duration); - } - - void Ledger::setPublisherMinVisits(const unsigned int& visits) { - if (!isBatPublisherExist()) { - assert(false); - - return; - } - bat_publishers_->setPublisherMinVisits(visits); - } - - void Ledger::setPublisherAllowNonVerified(const bool& allow) { - if (!isBatPublisherExist()) { - assert(false); - - return; - } - bat_publishers_->setPublisherAllowNonVerified(allow); - } - - void Ledger::setContributionAmount(const double& amount) { - if (!isBatClientExist()) { - assert(false); - - return; - } - bat_client_->setContributionAmount(amount); - } - - std::string Ledger::getBATAddress() { - if (!isBatClientExist()) { - assert(false); - - return ""; - } - return bat_client_->getBATAddress(); - } - - std::string Ledger::getBTCAddress() { - if (!isBatClientExist()) { - assert(false); - - return ""; - } - return bat_client_->getBTCAddress(); - } - - std::string Ledger::getETHAddress() { - if (!isBatClientExist()) { - assert(false); - - return ""; - } - return bat_client_->getETHAddress(); - } - - std::string Ledger::getLTCAddress() { - if (!isBatClientExist()) { - assert(false); - - return ""; - } - return bat_client_->getLTCAddress(); - } - - void Ledger::run(const uint64_t& delayTime) { - // That function should be triggeres from the main process periodically to make payments - if (!isBatClientExist()) { - assert(false); - - return; - } - if (bat_client_->isReadyForReconcile()) { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder1(*this, &Ledger::reconcileCallback); - bat_client_->reconcile(braveledger_bat_helper::GenerateGUID(), runnable); - } - } - - void Ledger::reconcileCallback(const std::string& viewingId) { - if (!isBatClientExist() || !isBatPublisherExist()) { - assert(false); - - return; - } - LOG(ERROR) << "!!!in reconcile callback"; - unsigned int ballotsCount = bat_client_->ballots(""); - LOG(ERROR) << "!!!ballotsCount == " << ballotsCount; - std::vector winners = bat_publishers_->winners(ballotsCount); - std::vector publishers; - for (size_t i = 0; i < winners.size(); i++) { - if (!bat_publishers_->isEligableForContribution(winners[i].publisher_data_)) { - continue; - } - publishers.push_back(winners[i].publisher_data_.publisherKey_); - } - bat_client_->votePublishers(publishers, ""/*, viewingId*/); - // TODO call prepareBallots by timeouts like in js library - bat_client_->prepareBallots(); - } - - void Ledger::OnMediaRequest(const std::string& url, const std::string& urlQuery, const std::string& type, bool privateTab) { - // Don't track private tabs - if (privateTab) { - return; - } - //LOG(ERROR) << "!!!media url == " << url; - //LOG(ERROR) << "!!!media urlQuery == " << urlQuery; - //LOG(ERROR) << "!!!media url type == " << type; - std::map parts; - std::vector> twitchParts; - if (YOUTUBE_MEDIA_TYPE == type) { - braveledger_bat_helper::getUrlQueryParts(urlQuery, parts); - processMedia(parts, type); - } else if (TWITCH_MEDIA_TYPE == type) { - braveledger_bat_helper::getTwitchParts(urlQuery, twitchParts); - for (size_t i = 0; i < twitchParts.size(); i++) { - processMedia(twitchParts[i], type); - } - } - } - - void Ledger::processMedia(const std::map& parts, std::string type) { - std::string mediaId = braveledger_bat_helper::getMediaId(parts, type); - //LOG(ERROR) << "!!!mediaId == " << mediaId; - if (mediaId.empty()) { - return; - } - std::string mediaKey = braveledger_bat_helper::getMediaKey(mediaId, type); - //LOG(ERROR) << "!!!mediaKey == " << mediaKey; - uint64_t duration = 0; - braveledger_bat_helper::TWITCH_EVENT_INFO twitchEventInfo; - if (YOUTUBE_MEDIA_TYPE == type) { - duration = braveledger_bat_helper::getMediaDuration(parts, mediaKey, type); - //LOG(ERROR) << "!!!duration == " << duration; - } else if (TWITCH_MEDIA_TYPE == type) { - std::map::const_iterator iter = parts.find("event"); - if (iter != parts.end()) { - twitchEventInfo.event_ = iter->second; - } - iter = parts.find("time"); - if (iter != parts.end()) { - twitchEventInfo.time_ = iter->second; - } - } - - braveledger_bat_helper::GetMediaPublisherInfoCallback runnable1 = braveledger_bat_helper::bat_mem_fun_binder2(*this, &Ledger::OnMediaRequestCallback); - - auto runnable2 = braveledger_bat_helper::bat_mem_fun_binder(*bat_get_media_, &BatGetMedia::getPublisherFromMediaProps, - mediaId, mediaKey, type, duration, twitchEventInfo, runnable1); - - braveledger_bat_helper::PostTask(runnable2); - } - - void Ledger::OnMediaRequestCallback(const uint64_t& duration, const braveledger_bat_helper::MEDIA_PUBLISHER_INFO& mediaPublisherInfo) { - saveVisit(mediaPublisherInfo.publisher_, duration, true); - } - -} // namespace braveledger_ledger diff --git a/src/ledger_impl.cc b/src/ledger_impl.cc new file mode 100644 index 000000000000..ce2d43150a59 --- /dev/null +++ b/src/ledger_impl.cc @@ -0,0 +1,281 @@ +/* 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_impl.h" + +#include "bat_client.h" +#include "bat_get_media.h" +#include "bat_helper.h" +#include "bat_publishers.h" +#include "static_values.h" + +#include "rapidjson_bat_helper.h" + +using namespace braveledger_bat_client; +using namespace braveledger_bat_publishers; +using namespace braveledger_bat_get_media; +using namespace std::placeholders; + +namespace bat_ledger { + +LedgerImpl::LedgerImpl(ledger::LedgerClient* client) : + ledger_client_(client), + bat_client_(new BatClient(this)), + bat_publishers_(new BatPublishers(this)), + bat_get_media_(new BatGetMedia(this)) { +} + +LedgerImpl::~LedgerImpl() { +} + +void LedgerImpl::CreateWallet() { + initSynopsis(); // fix race condition here + LoadLedgerState(this); +} + +void LedgerImpl::LoadLedgerState(ledger::LedgerCallbackHandler* handler) { + ledger_client_->LoadLedgerState(handler); +} + +void LedgerImpl::LoadPublisherState(ledger::LedgerCallbackHandler* handler) { + ledger_client_->LoadPublisherState(handler); +} + +void LedgerImpl::SaveLedgerState(const std::string& data, + ledger::LedgerCallbackHandler* handler) { + ledger_client_->SaveLedgerState(data, handler); +} + +void LedgerImpl::SavePublisherState(const std::string& data, + ledger::LedgerCallbackHandler* handler) { + ledger_client_->SavePublisherState(data, handler); +} + +std::string LedgerImpl::GenerateGUID() const { + return ledger_client_->GenerateGUID(); +} + +void LedgerImpl::OnLedgerStateLoaded(ledger::Result result, + const std::string& data) { + bat_client_->loadStateOrRegisterPersonaCallback(result == ledger::Result::OK, data); +} + +void LedgerImpl::OnWalletCreated(ledger::Result result) { + ledger_client_->OnWalletCreated(result); +} + +std::unique_ptr 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::initSynopsis() { + bat_publishers_->initSynopsis(); +} + +// void LedgerImpl::walletPropertiesCallback(bool success, +// const std::string& response) { +// if (!success) { +// // TODO errors handling +// return; +// } +// braveledger_bat_helper::WALLET_PROPERTIES_ST walletProperties; +// braveledger_bat_helper::loadFromJson(walletProperties, response); +// // TODO send the balance to the UI via observer or callback +// } + +void LedgerImpl::SaveVisit(const std::string& publisher, uint64_t duration, bool ignoreMinTime) { + // TODO debug + //bat_client_->recoverWallet(bat_client_->getWalletPassphrase()); + // + auto callback = std::bind(&LedgerImpl::saveVisitCallback, this, _1, _2); + bat_publishers_->saveVisit(publisher, duration, callback, ignoreMinTime); +} + +void LedgerImpl::RunIOTask(LedgerTaskRunnerImpl::Task io_task) { + std::unique_ptr task_runner( + new LedgerTaskRunnerImpl(io_task)); + ledger_client_->RunIOTask(std::move(task_runner)); +} + +void LedgerImpl::RunTask(LedgerTaskRunnerImpl::Task task) { + std::unique_ptr task_runner( + new LedgerTaskRunnerImpl(task)); + ledger_client_->RunTask(std::move(task_runner)); +} + +void LedgerImpl::saveVisitCallback(const std::string& publisher, + uint64_t verifiedTimestamp) { + uint64_t publisherTimestamp = bat_client_->getPublisherTimestamp(); + if (publisherTimestamp <= verifiedTimestamp) { + //to do debug + LOG(ERROR) << "!!!reconcile"; + Reconcile(); + // + return; + } + + // Update publisher verified or not flag + //LOG(ERROR) << "!!!getting publisher info"; + auto request = bat_client_->publisherInfo(publisher, &handler_); + handler_.AddRequestHandler(std::move(request), + std::bind(&LedgerImpl::publisherInfoCallback, + this, + publisher, + publisherTimestamp, + _1, + _2)); +} + +void LedgerImpl::publisherInfoCallback(const std::string& publisher, + uint64_t publisher_timestamp, + bool success, + const std::string& response) { + //LOG(ERROR) << "!!!got publisher info"; + if (!success) { + // TODO errors handling + return; + } + bool verified = false; + braveledger_bat_helper::getJSONPublisherVerified(response, verified); + bat_publishers_->setPublisherTimestampVerified(publisher, publisher_timestamp, verified); + //to do debug + //LOG(ERROR) << "!!!reconcile"; + //run(0); + // +} + +void LedgerImpl::SetPublisherInclude(const std::string& publisher, bool include) { + bat_publishers_->setPublisherInclude(publisher, include); +} + +void LedgerImpl::SetPublisherDeleted(const std::string& publisher, bool deleted) { + bat_publishers_->setPublisherDeleted(publisher, deleted); +} + +void LedgerImpl::SetPublisherPinPercentage(const std::string& publisher, bool pinPercentage) { + bat_publishers_->setPublisherPinPercentage(publisher, pinPercentage); +} + +void LedgerImpl::SetPublisherMinVisitTime(uint64_t duration) { // In milliseconds + bat_publishers_->setPublisherMinVisitTime(duration); +} + +void LedgerImpl::SetPublisherMinVisits(unsigned int visits) { + bat_publishers_->setPublisherMinVisits(visits); +} + +void LedgerImpl::SetPublisherAllowNonVerified(bool allow) { + bat_publishers_->setPublisherAllowNonVerified(allow); +} + +void LedgerImpl::SetContributionAmount(double amount) { + bat_client_->setContributionAmount(amount); +} + +const std::string& LedgerImpl::GetBATAddress() const { + return bat_client_->getBATAddress(); +} + +const std::string& LedgerImpl::GetBTCAddress() const { + return bat_client_->getBTCAddress(); +} + +const std::string& LedgerImpl::GetETHAddress() const { + return bat_client_->getETHAddress(); +} + +const std::string& LedgerImpl::GetLTCAddress() const { + return bat_client_->getLTCAddress(); +} + +void LedgerImpl::Reconcile() { + // That function should be triggeres from the main process periodically to make payments + if (bat_client_->isReadyForReconcile()) { + bat_client_->reconcile(GenerateGUID()); + } +} + +void LedgerImpl::OnReconcileComplete(ledger::Result result, + const std::string& viewing_id) { + ledger_client_->OnReconcileComplete(result, viewing_id); + if (result != ledger::Result::OK) { + // error handling + return; + } + LOG(ERROR) << "!!!in reconcile callback"; + unsigned int ballotsCount = bat_client_->ballots(""); + LOG(ERROR) << "!!!ballotsCount == " << ballotsCount; + std::vector winners = bat_publishers_->winners(ballotsCount); + std::vector publishers; + for (size_t i = 0; i < winners.size(); i++) { + if (!bat_publishers_->isEligableForContribution(winners[i].publisher_data_)) { + continue; + } + publishers.push_back(winners[i].publisher_data_.publisherKey_); + } + bat_client_->votePublishers(publishers, viewing_id); + // TODO call prepareBallots by timeouts like in js library + bat_client_->prepareBallots(); +} + +void LedgerImpl::OnMediaRequest(const std::string& url, + const std::string& urlQuery, + const std::string& type) { + //LOG(ERROR) << "!!!media url == " << url; + //LOG(ERROR) << "!!!media urlQuery == " << urlQuery; + //LOG(ERROR) << "!!!media url type == " << type; + std::map parts; + std::vector> twitchParts; + if (YOUTUBE_MEDIA_TYPE == type) { + braveledger_bat_helper::getUrlQueryParts(urlQuery, parts); + processMedia(parts, type); + } else if (TWITCH_MEDIA_TYPE == type) { + braveledger_bat_helper::getTwitchParts(urlQuery, twitchParts); + for (size_t i = 0; i < twitchParts.size(); i++) { + processMedia(twitchParts[i], type); + } + } +} + +void LedgerImpl::processMedia(const std::map& parts, const std::string& type) { + std::string mediaId = braveledger_bat_helper::getMediaId(parts, type); + //LOG(ERROR) << "!!!mediaId == " << mediaId; + if (mediaId.empty()) { + return; + } + std::string mediaKey = braveledger_bat_helper::getMediaKey(mediaId, type); + //LOG(ERROR) << "!!!mediaKey == " << mediaKey; + uint64_t duration = 0; + braveledger_bat_helper::TWITCH_EVENT_INFO twitchEventInfo; + if (YOUTUBE_MEDIA_TYPE == type) { + duration = braveledger_bat_helper::getMediaDuration(parts, mediaKey, type); + //LOG(ERROR) << "!!!duration == " << duration; + } else if (TWITCH_MEDIA_TYPE == type) { + std::map::const_iterator iter = parts.find("event"); + if (iter != parts.end()) { + twitchEventInfo.event_ = iter->second; + } + iter = parts.find("time"); + if (iter != parts.end()) { + twitchEventInfo.time_ = iter->second; + } + } + + braveledger_bat_helper::GetMediaPublisherInfoCallback callback = std::bind(&LedgerImpl::OnMediaRequestCallback, this, _1, _2); + auto io_task = std::bind(&BatGetMedia::getPublisherFromMediaProps, + bat_get_media_.get(), mediaId, mediaKey, type, duration, twitchEventInfo, callback); + RunIOTask(io_task); +} + +void LedgerImpl::OnMediaRequestCallback(uint64_t duration, const braveledger_bat_helper::MEDIA_PUBLISHER_INFO& mediaPublisherInfo) { + SaveVisit(mediaPublisherInfo.publisher_, duration, true); +} + +} // namespace bat_ledger diff --git a/src/ledger_impl.h b/src/ledger_impl.h new file mode 100644 index 000000000000..ceead260d1a6 --- /dev/null +++ b/src/ledger_impl.h @@ -0,0 +1,112 @@ +/* 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_IMPL_H_ +#define BAT_LEDGER_LEDGER_IMPL_H_ + +#include +#include +#include + +#include "bat/ledger/ledger.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" + +namespace braveledger_bat_client { +class BatClient; +} + +namespace braveledger_bat_get_media { +class BatGetMedia; +} + +namespace braveledger_bat_publishers { +class BatPublishers; +} + +namespace bat_ledger { + +class LedgerImpl : public ledger::Ledger, + public ledger::LedgerCallbackHandler { + public: + LedgerImpl(ledger::LedgerClient* client); + ~LedgerImpl() override; + + // Not copyable, not assignable + LedgerImpl(const LedgerImpl&) = delete; + LedgerImpl& operator=(const LedgerImpl&) = delete; + + std::string GenerateGUID() const; + void Reconcile() override; + void CreateWallet() override; + void SaveVisit(const std::string& publisher, + uint64_t duration, + bool ignoreMinTime) override; + void OnMediaRequest(const std::string& url, + const std::string& urlQuery, + const std::string& type) override; + void SetPublisherInclude(const std::string& publisher, bool include) override; + void SetPublisherDeleted(const std::string& publisher, bool deleted) override; + void SetPublisherPinPercentage(const std::string& publisher, + bool pinPercentage) override; + void SetPublisherMinVisitTime(uint64_t duration_in_milliseconds) override; + void SetPublisherMinVisits(unsigned int visits) override; + void SetPublisherAllowNonVerified(bool allow) override; + void SetContributionAmount(double amount) override; + const std::string& GetBATAddress() const override; + const std::string& GetBTCAddress() const override; + const std::string& GetETHAddress() const override; + const std::string& GetLTCAddress() const override; + + void SaveLedgerState(const std::string& data, + ledger::LedgerCallbackHandler* handler); + void SavePublisherState(const std::string& data, + ledger::LedgerCallbackHandler* handler); + void LoadLedgerState(ledger::LedgerCallbackHandler* handler); + void LoadPublisherState(ledger::LedgerCallbackHandler* handler); + + void OnWalletCreated(ledger::Result); + + std::unique_ptr 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); + void OnReconcileComplete(ledger::Result result, + const std::string& viewing_id); + void RunIOTask(LedgerTaskRunnerImpl::Task task); + void RunTask(LedgerTaskRunnerImpl::Task task); + + private: + void initSynopsis(); + void processMedia(const std::map& parts, + const std::string& type); + void publisherInfoCallback(const std::string& publisher, + uint64_t publisher_timestamp, + bool success, + const std::string& response); + void saveVisitCallback(const std::string& publisher, + uint64_t verifiedTimestamp); + void OnMediaRequestCallback(uint64_t duration, + const braveledger_bat_helper::MEDIA_PUBLISHER_INFO& mediaPublisherInfo); + + // LedgerCallbackHandler impl + void OnLedgerStateLoaded(ledger::Result result, + const std::string& data) override; + + ledger::LedgerClient* ledger_client_; + std::unique_ptr bat_client_; + std::unique_ptr bat_publishers_; + std::unique_ptr bat_get_media_; + + URLRequestHandler handler_; + }; +} // namespace bat_ledger + +#endif // BAT_LEDGER_LEDGER_IMPL_H_ diff --git a/src/ledger_task_runner_impl.cc b/src/ledger_task_runner_impl.cc new file mode 100644 index 000000000000..fd55935b2536 --- /dev/null +++ b/src/ledger_task_runner_impl.cc @@ -0,0 +1,16 @@ +/* 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() { + task_(); + } + +} // namespace ledger diff --git a/src/ledger_task_runner_impl.h b/src/ledger_task_runner_impl.h new file mode 100644 index 000000000000..798eea0c3338 --- /dev/null +++ b/src/ledger_task_runner_impl.h @@ -0,0 +1,29 @@ +/* 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 "bat/ledger/ledger_task_runner.h" + +namespace bat_ledger { + +class LedgerTaskRunnerImpl : public ledger::LedgerTaskRunner { + public: + using Task = std::function; + + LedgerTaskRunnerImpl(Task task); + ~LedgerTaskRunnerImpl() override; + + void Run() override; + + private: + Task task_; +}; + +} // namespace ledger + +#endif // BAT_LEDGER_LEDGER_IO_TASK_RUNNER_IMPL_ diff --git a/src/test/mock_ledger_client.cc b/src/test/mock_ledger_client.cc new file mode 100644 index 000000000000..63b32ebb8fae --- /dev/null +++ b/src/test/mock_ledger_client.cc @@ -0,0 +1,81 @@ +/* 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 "mock_ledger_client.h" + +#include "bat/ledger/ledger.h" + +namespace bat_ledger { + +static uint64_t next_id = 1; + +MockLedgerClient::MockLedgerClient() : + ledger_(ledger::Ledger::CreateInstance(this)) { +} + +MockLedgerClient::~MockLedgerClient() { +} + +void MockLedgerClient::CreateWallet() { + ledger_->CreateWallet(); +} + +std::string MockLedgerClient::GenerateGUID() const { + return "guid"; +} + +void MockLedgerClient::Shutdown() { + ledger_.reset(); +} + +void MockLedgerClient::OnWalletCreated(ledger::Result result) { +} + +void MockLedgerClient::OnReconcileComplete(ledger::Result result, + const std::string& viewing_id) { +} + +void MockLedgerClient::LoadLedgerState( + ledger::LedgerCallbackHandler* handler) { + handler->OnLedgerStateLoaded(ledger::Result::OK, ledger_state_); +} + +void MockLedgerClient::LoadPublisherState( + ledger::LedgerCallbackHandler* handler) { + handler->OnLedgerStateLoaded(ledger::Result::OK, publisher_state_); +} + +void MockLedgerClient::SaveLedgerState(const std::string& ledger_state, + ledger::LedgerCallbackHandler* handler) { + ledger_state_ = ledger_state; + handler->OnLedgerStateSaved(ledger::Result::OK); +} + +void MockLedgerClient::SavePublisherState(const std::string& publisher_state, + ledger::LedgerCallbackHandler* handler) { + publisher_state_ = publisher_state; + handler->OnPublisherStateSaved(ledger::Result::OK); +} + +uint64_t 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, 200, "{}"); + return next_id++; +} + +void MockLedgerClient::RunIOTask( + std::unique_ptr task) { + task->Run(); +} + +void MockLedgerClient::RunTask( + std::unique_ptr task) { + task->Run(); +} + +} // namespace payments diff --git a/src/test/mock_ledger_client.h b/src/test/mock_ledger_client.h new file mode 100644 index 000000000000..438702013585 --- /dev/null +++ b/src/test/mock_ledger_client.h @@ -0,0 +1,55 @@ +/* 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_MOCK_LEDGER_CLIENT_ +#define BAT_LEDGER_MOCK_LEDGER_CLIENT_ + +#include "bat/ledger/ledger_client.h" + +namespace ledger { +class Ledger; +class LedgerCallbackHandler; +} + +namespace bat_ledger { + +class MockLedgerClient : public ledger::LedgerClient { + public: + MockLedgerClient(); + ~MockLedgerClient() override; + + // KeyedService: + void Shutdown() override; + + void CreateWallet() override; + + protected: + // ledger::LedgerClient + std::string GenerateGUID() const override; + void OnWalletCreated(ledger::Result result) override; + void OnReconcileComplete(ledger::Result result, + const std::string& viewing_id) 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; + uint64_t 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; + void RunIOTask(std::unique_ptr task) override; + void RunTask(std::unique_ptr task) override; + + std::unique_ptr ledger_; + std::string ledger_state_; + std::string publisher_state_; +}; + +} // namespace history + +#endif //BAT_LEDGER_MOCK_LEDGER_CLIENT_ diff --git a/src/url_request_handler.cc b/src/url_request_handler.cc new file mode 100644 index 000000000000..042977007cc3 --- /dev/null +++ b/src/url_request_handler.cc @@ -0,0 +1,52 @@ +/* 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" + +namespace bat_ledger { + +URLRequestHandler::URLRequestHandler() {} + +URLRequestHandler::~URLRequestHandler() { + Clear(); +} + +void URLRequestHandler::Clear() { + request_handlers_.clear(); +} + +void URLRequestHandler::OnURLRequestResponse(uint64_t request_id, + int response_code, + const std::string& response) { + if (!RunRequestHandler(request_id, response_code == 200, response)) { + LOG(ERROR) << "no request handler found for " << request_id; + 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) { + 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); + return true; +} + +} // namespace bat_ledger diff --git a/src/url_request_handler.h b/src/url_request_handler.h new file mode 100644 index 000000000000..30523e8b5de2 --- /dev/null +++ b/src/url_request_handler.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 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; + + 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); + + private: + // LedgerCallbackHandler impl + void OnURLRequestResponse(uint64_t request_id, + int response_code, + const std::string& response) override; + + std::map request_handlers_; + }; +} // namespace bat_ledger + +#endif // BAT_LEDGER_URL_REQUEST_HANDLER_H_