diff --git a/BUILD.gn b/BUILD.gn index 217319c..b504165 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -1,50 +1,41 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. +# 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/. if (is_android) { import("//build/config/android/rules.gni") } +if (is_android) { + dep_base = rebase_path("..", "//") +} else { + dep_base = rebase_path("../..", "//") +} + +config("internal_config") { + include_dirs = [ "../src" ] + defines = [ "BRAVE_LEDGER_LIB" ] +} + +source_set("bat-native-ledger") { + configs += [ ":internal_config" ] -static_library("braveLedger") { sources = [ - "src/ledger.cc", "src/bat_client.cc", - "src/bat_client_webrequest.cc", + "src/bat_client_webrequest_chromium.cc", "src/bat_get_media.cc", "src/bat_helper.cc", - "src/bat_publisher.cc", + "src/bat_helper_platform.cc", + "src/bat_publishers.cc", "src/bat_balance.cc", - "src/tweetnacl.cc", - ] - - include_dirs = [ - "src", - "//anonize2/anon", - "//anonize2/relic/include", - "//anonize2/relic/include/low", - "//bip39wally-core/include" + "src/ledger.cc", ] deps = [ - "//base", "//net", - "//anonize2", - "//bip39wally-core", - "//v8", - "//net:net_utility_services", - "//net:net_with_v8", - "//v8:v8_libplatform", + "//third_party/leveldatabase", + rebase_path("bat-native-anonize:anonize2", dep_base), + rebase_path("bip39wally-core-native:bip39wally-core", dep_base), + rebase_path("bat-native-tweetnacl:tweetnacl", dep_base), + rebase_path("bat-native-rapidjson", dep_base), ] - - include_dirs += [ - "//base", - "//net/url_request", - "//url", - "//content/public/browser", - "//third_party/leveldatabase/src/include", - "//v8", - ] - - defines = [ "LEDGER_LIBRARY" ] } diff --git a/src/bat_balance.cc b/src/bat_balance.cc index bb49ed4..c0ae21a 100644 --- a/src/bat_balance.cc +++ b/src/bat_balance.cc @@ -3,11 +3,12 @@ * 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) { @@ -21,9 +22,9 @@ std::string BatBalance::buildURL(const std::string& path, const std::string& pre void BatBalance::getWalletProperties(const std::string& paymentInfo, braveledger_bat_helper::FetchCallback callback, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { - + batClientWebRequest_.run(buildURL((std::string)WALLET_PROPERTIES + paymentInfo + WALLET_PROPERTIES_END, ""), callback, std::vector(), "", "", extraData, braveledger_bat_helper::URL_METHOD::GET); } -} //namespace braveledger_bat_balance +} // namespace braveledger_bat_balance diff --git a/src/bat_balance.h b/src/bat_balance.h index 21c0b72..52afa50 100644 --- a/src/bat_balance.h +++ b/src/bat_balance.h @@ -13,25 +13,24 @@ #include "bat_client_webrequest.h" #endif -#include "bat_helper.h" +namespace braveledger_bat_helper { +struct FETCH_CALLBACK_EXTRA_DATA_ST; +} -namespace braveledger_bat_balance -{ +namespace braveledger_bat_balance { class BatBalance { -public: + public: BatBalance() = default; ~BatBalance() = default; - void getWalletProperties(const std::string& paymentInfo, braveledger_bat_helper::FetchCallback callback, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); -private: + private: std::string buildURL(const std::string& path, const std::string& prefix); - braveledger_bat_client_webrequest::BatClientWebRequest batClientWebRequest_; }; -} //namespace braveledger_bat_balance +} // namespace braveledger_bat_balance #endif // BRAVELEDGER_BAT_BALANCE_H_ diff --git a/src/bat_client.cc b/src/bat_client.cc index abd8927..3e5ba70 100644 --- a/src/bat_client.cc +++ b/src/bat_client.cc @@ -2,26 +2,27 @@ * 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.h" #include #include - -#include "static_values.h" #include "bat_helper.h" -#include "bat_client.h" - -//anonize -#include "anon.h" +#include "rapidjson_bat_helper.h" +#include "static_values.h" -//wally +#include "anon/anon.h" #include "wally_bip39.h" namespace braveledger_bat_client { -BatClient::BatClient( bool useProxy): +BatClient::BatClient(bool useProxy) : useProxy_(useProxy), - publisherTimestamp_(0) { + state_(new braveledger_bat_helper::CLIENT_STATE_ST()), + publisherTimestamp_(0), + currentReconcile_(new braveledger_bat_helper::CURRENT_RECONCILE) { + // Enable emscripten calls + //braveledger_bat_helper::readEmscripten(); initAnonize(); } @@ -43,7 +44,7 @@ void BatClient::loadStateOrRegisterPersona() { auto runnable = braveledger_bat_helper::bat_mem_fun_binder2(*this, &BatClient::loadStateOrRegisterPersonaCallback); - braveledger_bat_helper::loadState(runnable); + braveledger_bat_helper::loadState(runnable); LOG(ERROR) << "BatClient::loadStateOrRegisterPersona exit"; } @@ -51,18 +52,17 @@ void BatClient::loadStateOrRegisterPersonaCallback(bool result, const braveledge if (!result) { LOG(ERROR) << "!!!here1"; registerPersona(); - return; } LOG(ERROR) << "!!!bat address == " << state.walletInfo_.addressBAT_; LOG(ERROR) << "!!!card address == " << state.walletInfo_.addressCARD_ID_; - state_ = state; + state_.reset(new braveledger_bat_helper::CLIENT_STATE_ST(state)); publisherTimestamp(false); } void BatClient::registerPersona() { // We should use simple callbacks on iOS - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::requestCredentialsCallback); + auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::requestCredentialsCallback); batClientWebRequest_.run(buildURL(REGISTER_PERSONA, PREFIX_V2), runnable, std::vector(), "", "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), @@ -75,20 +75,20 @@ void BatClient::requestCredentialsCallback(bool result, const std::string& respo // TODO errors handling return; } - if (state_.personaId_.empty()) { - state_.personaId_ = braveledger_bat_helper::GenerateGUID(); + if (state_->personaId_.empty()) { + state_->personaId_ = braveledger_bat_helper::GenerateGUID(); } // Anonize2 limit is 31 octets - state_.userId_ = state_.personaId_; - state_.userId_.erase(std::remove(state_.userId_.begin(), state_.userId_.end(), '-'), state_.userId_.end()); - state_.userId_.erase(12, 1); + state_->userId_ = state_->personaId_; + state_->userId_.erase(std::remove(state_->userId_.begin(), state_->userId_.end(), '-'), state_->userId_.end()); + state_->userId_.erase(12, 1); - braveledger_bat_helper::getJSONValue(REGISTRARVK_FIELDNAME, response, state_.registrarVK_); - DCHECK(!state_.registrarVK_.empty()); - std::string proof = getAnonizeProof(state_.registrarVK_, state_.userId_, state_.preFlight_); + braveledger_bat_helper::getJSONValue(REGISTRARVK_FIELDNAME, response, state_->registrarVK_); + DCHECK(!state_->registrarVK_.empty()); + std::string proof = getAnonizeProof(state_->registrarVK_, state_->userId_, state_->preFlight_); - state_.walletInfo_.keyInfoSeed_ = braveledger_bat_helper::generateSeed(); - std::vector secretKey = braveledger_bat_helper::getHKDF(state_.walletInfo_.keyInfoSeed_); + state_->walletInfo_.keyInfoSeed_ = braveledger_bat_helper::generateSeed(); + std::vector secretKey = braveledger_bat_helper::getHKDF(state_->walletInfo_.keyInfoSeed_); std::vector publicKey; std::vector newSecretKey; braveledger_bat_helper::getPublicKeyFromSeed(secretKey, publicKey, newSecretKey); @@ -115,10 +115,10 @@ void BatClient::requestCredentialsCallback(bool result, const std::string& respo //LOG(ERROR) << "!!!payloadStringify == " << payloadStringify; std::vector headers; 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); - batClientWebRequest_.run(buildURL((std::string)REGISTER_PERSONA + "/" + state_.userId_, PREFIX_V2), + batClientWebRequest_.run(buildURL((std::string)REGISTER_PERSONA + "/" + state_->userId_, PREFIX_V2), runnable, headers, payloadStringify, "application/json; charset=utf-8", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), braveledger_bat_helper::URL_METHOD::POST); @@ -150,17 +150,17 @@ void BatClient::registerPersonaCallback(bool result, const std::string& response std::string verification; braveledger_bat_helper::getJSONValue(VERIFICATION_FIELDNAME, response, verification); - const char* masterUserToken = registerUserFinal(state_.userId_.c_str(), verification.c_str(), - state_.preFlight_.c_str(), state_.registrarVK_.c_str()); + const char* masterUserToken = registerUserFinal(state_->userId_.c_str(), verification.c_str(), + state_->preFlight_.c_str(), state_->registrarVK_.c_str()); if (nullptr != masterUserToken) { - state_.masterUserToken_ = masterUserToken; + state_->masterUserToken_ = masterUserToken; free((void*)masterUserToken); } LOG(ERROR) << "!!!registerPersonaCallback response == " << response; - braveledger_bat_helper::getJSONWalletInfo(response, state_.walletInfo_, state_.fee_currency_, state_.fee_amount_, state_.days_); - state_.bootStamp_ = braveledger_bat_helper::currentTime() * 1000; - state_.reconcileStamp_ = state_.bootStamp_ + state_.days_ * 24 * 60 * 60 * 1000; + braveledger_bat_helper::getJSONWalletInfo(response, state_->walletInfo_, state_->fee_currency_, state_->fee_amount_, state_->days_); + state_->bootStamp_ = braveledger_bat_helper::currentTime() * 1000; + state_->reconcileStamp_ = state_->bootStamp_ + state_->days_ * 24 * 60 * 60 * 1000; publisherTimestamp(); // TODO debug @@ -186,12 +186,12 @@ void BatClient::publisherTimestampCallback(bool result, const std::string& respo } braveledger_bat_helper::getJSONPublisherTimeStamp(response, publisherTimestamp_); if (!extraData.boolean1) { - LOG(ERROR) << "BatClient::publisherTimestampCallback !extraData.boolean1"; + LOG(ERROR) << "BatClient::publisherTimestampCallback !extraData.boolean1"; } else { std::lock_guard guard(state_mutex_); - braveledger_bat_helper::saveState(state_); + braveledger_bat_helper::saveState(*state_); } } @@ -207,29 +207,29 @@ void BatClient::publisherInfo(const std::string& publisher, braveledger_bat_help void BatClient::setContributionAmount(const double& amount) { std::lock_guard guard(state_mutex_); - state_.fee_amount_ = amount; - braveledger_bat_helper::saveState(state_); + state_->fee_amount_ = amount; + braveledger_bat_helper::saveState(*state_); } std::string BatClient::getBATAddress() { - return state_.walletInfo_.addressBAT_; + return state_->walletInfo_.addressBAT_; } std::string BatClient::getBTCAddress() { - return state_.walletInfo_.addressBTC_; + return state_->walletInfo_.addressBTC_; } std::string BatClient::getETHAddress() { - return state_.walletInfo_.addressETH_; + return state_->walletInfo_.addressETH_; } std::string BatClient::getLTCAddress() { - return state_.walletInfo_.addressLTC_; + return state_->walletInfo_.addressLTC_; } -void BatClient::getWalletProperties (braveledger_bat_helper::FetchCallback callback, +void BatClient::getWalletProperties (braveledger_bat_helper::FetchCallback callback, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { - balance_.getWalletProperties(state_.walletInfo_.paymentId_, callback, extraData); + balance_.getWalletProperties(state_->walletInfo_.paymentId_, callback, extraData); } bool BatClient::isReadyForReconcile() { @@ -239,11 +239,11 @@ bool BatClient::isReadyForReconcile() { void BatClient::reconcile(const std::string& viewingId, braveledger_bat_helper::SimpleCallback callback) { //FETCH_CALLBACK_EXTRA_DATA_ST extraData; - currentReconcile_.viewingId_ = viewingId; - currentReconcile_.ledgerCallback_ = callback; + currentReconcile_->viewingId_ = viewingId; + currentReconcile_->ledgerCallback_ = callback; auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::reconcileCallback); - batClientWebRequest_.run(buildURL((std::string)RECONCILE_CONTRIBUTION + state_.userId_, PREFIX_V2), runnable, + batClientWebRequest_.run(buildURL((std::string)RECONCILE_CONTRIBUTION + state_->userId_, PREFIX_V2), runnable, std::vector(), "", "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), braveledger_bat_helper::URL_METHOD::GET); } @@ -254,15 +254,15 @@ void BatClient::reconcileCallback(bool result, const std::string& response, cons // TODO errors handling return; } - //currentReconcile_.viewingId_ = extraData.string1; - braveledger_bat_helper::getJSONValue(SURVEYOR_ID, response, currentReconcile_.surveyorInfo_.surveyorId_); + //currentReconcile_->viewingId_ = extraData.string1; + braveledger_bat_helper::getJSONValue(SURVEYOR_ID, response, currentReconcile_->surveyorInfo_.surveyorId_); currentReconcile(); } void BatClient::currentReconcile() { std::ostringstream amount; - amount << state_.fee_amount_; - std::string path = (std::string)WALLET_PROPERTIES + state_.walletInfo_.paymentId_ + "?refresh=true&amount=" + amount.str() + "&altcurrency=" + state_.fee_currency_; + amount << state_->fee_amount_; + 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); @@ -278,16 +278,16 @@ void BatClient::currentReconcileCallback(bool result, const std::string& respons return; } - braveledger_bat_helper::getJSONRates(response, currentReconcile_.rates_); - //LOG(ERROR) << "!!!rates == " << currentReconcile_.rates_.size(); + braveledger_bat_helper::getJSONRates(response, currentReconcile_->rates_); + //LOG(ERROR) << "!!!rates == " << currentReconcile_->rates_.size(); braveledger_bat_helper::UNSIGNED_TX unsignedTx; braveledger_bat_helper::getJSONUnsignedTx(response, unsignedTx); if (unsignedTx.amount_.empty() && unsignedTx.currency_.empty() && unsignedTx.destination_.empty()) { // We don't have any unsigned transactions return; } - currentReconcile_.amount_ = unsignedTx.amount_; - currentReconcile_.currency_ = unsignedTx.currency_; + currentReconcile_->amount_ = unsignedTx.amount_; + currentReconcile_->currency_ = unsignedTx.currency_; //std::string keysDenomination[2] = {"amount", "currency"}; //std::string valuesDenomination[2] = {unsignedTx.amount_, unsignedTx.currency_}; @@ -299,11 +299,11 @@ void BatClient::currentReconcileCallback(bool result, const std::string& respons std::string headerDigest = "SHA-256=" + braveledger_bat_helper::getBase64(braveledger_bat_helper::getSHA256(octets)); std::string headerKeys[1] = {"digest"}; std::string headerValues[1] = {headerDigest}; - std::vector secretKey = braveledger_bat_helper::getHKDF(state_.walletInfo_.keyInfoSeed_); + std::vector secretKey = braveledger_bat_helper::getHKDF(state_->walletInfo_.keyInfoSeed_); std::vector publicKey; std::vector newSecretKey; braveledger_bat_helper::getPublicKeyFromSeed(secretKey, publicKey, newSecretKey); - //LOG(ERROR) << "!!!state_.walletInfo_.keyInfoSeed_.size == " << state_.walletInfo_.keyInfoSeed_.size(); + //LOG(ERROR) << "!!!state_->walletInfo_.keyInfoSeed_.size == " << state_->walletInfo_.keyInfoSeed_.size(); //LOG(ERROR) << "!!!secretKey.size == " << secretKey.size(); //LOG(ERROR) << "!!!newSecretKey.size == " << newSecretKey.size(); std::string headerSignature = braveledger_bat_helper::sign(headerKeys, headerValues, 1, "primary", newSecretKey); @@ -315,14 +315,14 @@ void BatClient::currentReconcileCallback(bool result, const std::string& respons reconcilePayload.request_signedtx_headers_signature_ = headerSignature; reconcilePayload.request_signedtx_body_ = unsignedTx; reconcilePayload.request_signedtx_octets_ = octets; - reconcilePayload.request_viewingId_ = currentReconcile_.viewingId_; - reconcilePayload.request_surveyorId_ = currentReconcile_.surveyorInfo_.surveyorId_; + reconcilePayload.request_viewingId_ = currentReconcile_->viewingId_; + reconcilePayload.request_surveyorId_ = currentReconcile_->surveyorInfo_.surveyorId_; std::string payloadStringify = braveledger_bat_helper::stringifyReconcilePayloadSt(reconcilePayload); //LOG(ERROR) << "!!!payloadStringify == " << payloadStringify; std::vector headers; headers.push_back("Content-Type: application/json; charset=UTF-8"); - std::string path = (std::string)WALLET_PROPERTIES + state_.walletInfo_.paymentId_; + std::string path = (std::string)WALLET_PROPERTIES + state_->walletInfo_.paymentId_; auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::reconcilePayloadCallback); batClientWebRequest_.run(buildURL(path, ""), runnable, @@ -338,17 +338,17 @@ void BatClient::reconcilePayloadCallback(bool result, const std::string& respons } braveledger_bat_helper::TRANSACTION_ST transaction; braveledger_bat_helper::getJSONTransaction(response, transaction); - transaction.viewingId_ = currentReconcile_.viewingId_; - transaction.surveyorId_ = currentReconcile_.surveyorInfo_.surveyorId_; - transaction.contribution_rates_ = currentReconcile_.rates_; - transaction.contribution_fiat_amount_ = currentReconcile_.amount_; - transaction.contribution_fiat_currency_ = currentReconcile_.currency_; + transaction.viewingId_ = currentReconcile_->viewingId_; + transaction.surveyorId_ = currentReconcile_->surveyorInfo_.surveyorId_; + transaction.contribution_rates_ = currentReconcile_->rates_; + transaction.contribution_fiat_amount_ = currentReconcile_->amount_; + transaction.contribution_fiat_currency_ = currentReconcile_->currency_; { std::lock_guard guard(transactions_access_mutex_); - state_.transactions_.push_back(transaction); + state_->transactions_.push_back(transaction); } - braveledger_bat_helper::saveState(state_); + braveledger_bat_helper::saveState(*state_); // 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; @@ -365,7 +365,7 @@ void BatClient::updateRulesCallback(bool result, const std::string& response, co // TODO errors handling return; } - state_.ruleset_ = response; + state_->ruleset_ = response; auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::updateRulesV2Callback); batClientWebRequest_.run(buildURL(UPDATE_RULES_V2, ""),runnable, @@ -380,7 +380,7 @@ void BatClient::updateRulesV2Callback(bool result, const std::string& response, return; } // TODO parse the return rulesetV2 - state_.rulesetV2_ = response; + state_->rulesetV2_ = response; // We are doing a reconcile if the boolean is true if (extraData.boolean1) { // Register viewingId @@ -403,18 +403,18 @@ void BatClient::registerViewingCallback(bool result, const std::string& response return; } - braveledger_bat_helper::getJSONValue(REGISTRARVK_FIELDNAME, response, currentReconcile_.registrarVK_); - DCHECK(!currentReconcile_.registrarVK_.empty()); - currentReconcile_.anonizeViewingId_ = currentReconcile_.viewingId_; - currentReconcile_.anonizeViewingId_.erase(std::remove(currentReconcile_.anonizeViewingId_.begin(), currentReconcile_.anonizeViewingId_.end(), '-'), currentReconcile_.anonizeViewingId_.end()); - currentReconcile_.anonizeViewingId_.erase(12, 1); - std::string proof = getAnonizeProof(currentReconcile_.registrarVK_, currentReconcile_.anonizeViewingId_, currentReconcile_.preFlight_); + braveledger_bat_helper::getJSONValue(REGISTRARVK_FIELDNAME, response, currentReconcile_->registrarVK_); + DCHECK(!currentReconcile_->registrarVK_.empty()); + currentReconcile_->anonizeViewingId_ = currentReconcile_->viewingId_; + currentReconcile_->anonizeViewingId_.erase(std::remove(currentReconcile_->anonizeViewingId_.begin(), currentReconcile_->anonizeViewingId_.end(), '-'), currentReconcile_->anonizeViewingId_.end()); + currentReconcile_->anonizeViewingId_.erase(12, 1); + std::string proof = getAnonizeProof(currentReconcile_->registrarVK_, currentReconcile_->anonizeViewingId_, currentReconcile_->preFlight_); //LOG(ERROR) << "!!!proof1 == " << proof; std::string keys[1] = {"proof"}; std::string values[1] = {proof}; std::string proofStringified = braveledger_bat_helper::stringify(keys, values, 1); - viewingCredentials(proofStringified, currentReconcile_.anonizeViewingId_); + viewingCredentials(proofStringified, currentReconcile_->anonizeViewingId_); } void BatClient::viewingCredentials(const std::string& proofStringified, const std::string& anonizeViewingId) { @@ -434,11 +434,11 @@ void BatClient::viewingCredentialsCallback(bool result, const std::string& respo std::string verification; braveledger_bat_helper::getJSONValue(VERIFICATION_FIELDNAME, response, verification); //LOG(ERROR) << "!!!response verification == " << verification; - const char* masterUserToken = registerUserFinal(currentReconcile_.anonizeViewingId_.c_str(), verification.c_str(), - currentReconcile_.preFlight_.c_str(), currentReconcile_.registrarVK_.c_str()); + const char* masterUserToken = registerUserFinal(currentReconcile_->anonizeViewingId_.c_str(), verification.c_str(), + currentReconcile_->preFlight_.c_str(), currentReconcile_->registrarVK_.c_str()); if (nullptr != masterUserToken) { - currentReconcile_.masterUserToken_ = masterUserToken; + currentReconcile_->masterUserToken_ = masterUserToken; free((void*)masterUserToken); } @@ -447,30 +447,30 @@ void BatClient::viewingCredentialsCallback(bool result, const std::string& respo // Save the rest values to transactions { std::lock_guard guard(transactions_access_mutex_); - for (size_t i = 0; i < state_.transactions_.size(); i++) { - if (state_.transactions_[i].viewingId_ != currentReconcile_.viewingId_) { + for (size_t i = 0; i < state_->transactions_.size(); i++) { + if (state_->transactions_[i].viewingId_ != currentReconcile_->viewingId_) { continue; } - state_.transactions_[i].anonizeViewingId_ = currentReconcile_.anonizeViewingId_; - state_.transactions_[i].registrarVK_ = currentReconcile_.registrarVK_; - state_.transactions_[i].masterUserToken_ = currentReconcile_.masterUserToken_; - state_.transactions_[i].surveyorIds_ = surveyors; + state_->transactions_[i].anonizeViewingId_ = currentReconcile_->anonizeViewingId_; + state_->transactions_[i].registrarVK_ = currentReconcile_->registrarVK_; + state_->transactions_[i].masterUserToken_ = currentReconcile_->masterUserToken_; + state_->transactions_[i].surveyorIds_ = surveyors; } } - braveledger_bat_helper::saveState(state_); - braveledger_bat_helper::run_runnable (currentReconcile_.ledgerCallback_, std::cref(currentReconcile_.viewingId_) ); - - //LOG(ERROR) << "!!!response masterUserToken == " << currentReconcile_.masterUserToken_; + braveledger_bat_helper::saveState(*state_); + braveledger_bat_helper::run_runnable(currentReconcile_->ledgerCallback_, std::cref(currentReconcile_->viewingId_)); + + //LOG(ERROR) << "!!!response masterUserToken == " << currentReconcile_.masterUserToken_; } unsigned int BatClient::ballots(const std::string& viewingId) { std::lock_guard guard(transactions_access_mutex_); unsigned int count = 0; - for (size_t i = 0; i < state_.transactions_.size(); i++) { - if (state_.transactions_[i].votes_ < state_.transactions_[i].surveyorIds_.size() - && (state_.transactions_[i].viewingId_ == viewingId || 0 == viewingId.length())) { - count += state_.transactions_[i].surveyorIds_.size() - state_.transactions_[i].votes_; + for (size_t i = 0; i < state_->transactions_.size(); i++) { + if (state_->transactions_[i].votes_ < state_->transactions_[i].surveyorIds_.size() + && (state_->transactions_[i].viewingId_ == viewingId || 0 == viewingId.length())) { + count += state_->transactions_[i].surveyorIds_.size() - state_->transactions_[i].votes_; } } @@ -481,7 +481,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_); + braveledger_bat_helper::saveState(*state_); } void BatClient::vote(const std::string& publisher, const std::string& viewingId) { @@ -493,26 +493,26 @@ void BatClient::vote(const std::string& publisher, const std::string& viewingId) { std::lock_guard guard(transactions_access_mutex_); int i = 0; - for (i = state_.transactions_.size() - 1; i >=0; i--) { - if (state_.transactions_[i].votes_ >= state_.transactions_[i].surveyorIds_.size()) { + for (i = state_->transactions_.size() - 1; i >=0; i--) { + if (state_->transactions_[i].votes_ >= state_->transactions_[i].surveyorIds_.size()) { continue; } - if (state_.transactions_[i].viewingId_ == viewingId || viewingId.empty()) { + if (state_->transactions_[i].viewingId_ == viewingId || viewingId.empty()) { break; } } if (i < 0) { return; } - ballot.viewingId_ = state_.transactions_[i].viewingId_; - ballot.surveyorId_ = state_.transactions_[i].surveyorIds_[state_.transactions_[i].votes_]; + ballot.viewingId_ = state_->transactions_[i].viewingId_; + ballot.surveyorId_ = state_->transactions_[i].surveyorIds_[state_->transactions_[i].votes_]; ballot.publisher_ = publisher; - ballot.offset_ = state_.transactions_[i].votes_; - state_.transactions_[i].votes_++; - //LOG(ERROR) << "!!!prepared ballout " << publisher << ", votes == " << state_.transactions_[i].votes_; + ballot.offset_ = state_->transactions_[i].votes_; + state_->transactions_[i].votes_++; + //LOG(ERROR) << "!!!prepared ballout " << publisher << ", votes == " << state_->transactions_[i].votes_; } std::lock_guard guard(ballots_access_mutex_); - state_.ballots_.push_back(ballot); + state_->ballots_.push_back(ballot); } void BatClient::prepareBallots() { @@ -520,24 +520,24 @@ void BatClient::prepareBallots() { //std::vector batchProof; { std::lock_guard guard(ballots_access_mutex_); - for (int i = state_.ballots_.size() - 1; i >= 0; i--) { + for (int i = state_->ballots_.size() - 1; i >= 0; i--) { bool breakTheLoop = false; std::lock_guard guard(transactions_access_mutex_); - for (size_t j = 0; j < state_.transactions_.size(); j++) { + for (size_t j = 0; j < state_->transactions_.size(); j++) { // TODO check on valid credentials for transaction - if (state_.transactions_[j].viewingId_ == state_.ballots_[i].viewingId_ - /*&& (state_.ballots_[i].prepareBallot_.empty() || 0 == state_.ballots_[i].delayStamp_ - || state_.ballots_[i].delayStamp_ <= currentTime)*/) { + if (state_->transactions_[j].viewingId_ == state_->ballots_[i].viewingId_ + /*&& (state_->ballots_[i].prepareBallot_.empty() || 0 == state_->ballots_[i].delayStamp_ + || state_->ballots_[i].delayStamp_ <= currentTime)*/) { // TODO check on ballot.prepareBallot and call commitBallot if it exist - if (state_.ballots_[i].prepareBallot_.empty()) { - prepareBatch(state_.ballots_[i], state_.transactions_[j]); - //prepareBallot(state_.ballots_[i], state_.transactions_[j]); + if (state_->ballots_[i].prepareBallot_.empty()) { + prepareBatch(state_->ballots_[i], state_->transactions_[j]); + //prepareBallot(state_->ballots_[i], state_->transactions_[j]); breakTheLoop = true; break; } //BATCH_PROOF batchProofEl; - //batchProofEl.transaction_ = state_.transactions_[j]; - //batchProofEl.ballot_ = state_.ballots_[i]; + //batchProofEl.transaction_ = state_->transactions_[j]; + //batchProofEl.ballot_ = state_->ballots_[i]; //batchProof.push_back(batchProofEl); } } @@ -573,17 +573,17 @@ void BatClient::prepareBatchCallback(bool result, const std::string& response, c continue; } std::lock_guard guard(ballots_access_mutex_); - for (int i = state_.ballots_.size() - 1; i >= 0; i--) { + for (int i = state_->ballots_.size() - 1; i >= 0; i--) { std::string survId; braveledger_bat_helper::getJSONValue("surveyorId", surveyors[j], survId); - if (state_.ballots_[i].surveyorId_ == survId) { + if (state_->ballots_[i].surveyorId_ == survId) { std::lock_guard guard(transactions_access_mutex_); - for (size_t k = 0; k < state_.transactions_.size(); k++) { - if (state_.transactions_[k].viewingId_ == state_.ballots_[i].viewingId_) { - state_.ballots_[i].prepareBallot_ = surveyors[j]; + for (size_t k = 0; k < state_->transactions_.size(); k++) { + if (state_->transactions_[k].viewingId_ == state_->ballots_[i].viewingId_) { + state_->ballots_[i].prepareBallot_ = surveyors[j]; braveledger_bat_helper::BATCH_PROOF batchProofEl; - batchProofEl.transaction_ = state_.transactions_[k]; - batchProofEl.ballot_ = state_.ballots_[i]; + batchProofEl.transaction_ = state_->transactions_[k]; + batchProofEl.ballot_ = state_->ballots_[i]; batchProof.push_back(batchProofEl); } } @@ -591,18 +591,18 @@ void BatClient::prepareBatchCallback(bool result, const std::string& response, c } } - braveledger_bat_helper::saveState(state_); + braveledger_bat_helper::saveState(*state_); proofBatch(batchProof); LOG(ERROR) << "!!! 2 batchProof.size() == " << batchProof.size(); } void BatClient::proofBatch(const std::vector& batchProof) { for (size_t i = 0; i < batchProof.size(); i++) { - braveledger_bat_helper::SURVEYOR_ST surveyor; - braveledger_bat_helper::loadFromJson(surveyor, batchProof[i].ballot_.prepareBallot_); - + braveledger_bat_helper::SURVEYOR_ST surveyor; + braveledger_bat_helper::loadFromJson(surveyor, batchProof[i].ballot_.prepareBallot_); + std::string surveyorIdEncoded; - braveledger_bat_helper::encodeURIComponent(surveyor.surveyorId_, surveyorIdEncoded); + braveledger_bat_helper::encodeURIComponent(surveyor.surveyorId_, surveyorIdEncoded); std::string signatureToSend; LOG(ERROR) << "!!!full signature == " << surveyor.signature_; @@ -630,9 +630,9 @@ void BatClient::proofBatch(const std::vector guard(ballots_access_mutex_); - for (size_t j = 0; j < state_.ballots_.size(); j++) { - if (state_.ballots_[j].surveyorId_ == batchProof[i].ballot_.surveyorId_) { - state_.ballots_[j].proofBallot_ = anonProof; + for (size_t j = 0; j < state_->ballots_.size(); j++) { + if (state_->ballots_[j].surveyorId_ == batchProof[i].ballot_.surveyorId_) { + state_->ballots_[j].proofBallot_ = anonProof; } } } @@ -642,9 +642,9 @@ void BatClient::proofBatch(const std::vector guard(ballots_access_mutex_); - for (int i = state_.ballots_.size() - 1; i >= 0; i--) { - if (state_.ballots_[i].viewingId_ == extraData.string1 - && state_.ballots_[i].surveyorId_ == extraData.string2) { - state_.ballots_[i].prepareBallot_ = response; + for (int i = state_->ballots_.size() - 1; i >= 0; i--) { + if (state_->ballots_[i].viewingId_ == extraData.string1 + && state_->ballots_[i].surveyorId_ == extraData.string2) { + state_->ballots_[i].prepareBallot_ = response; // TODO make random from 1 second to 3 hours. - state_.ballots_[i].delayStamp_ = braveledger_bat_helper::currentTime() * 1000; + state_->ballots_[i].delayStamp_ = braveledger_bat_helper::currentTime() * 1000; // TODO debug, just calling commitBallot here for testing purposes { std::lock_guard guard(transactions_access_mutex_); - for (size_t j = 0; j < state_.transactions_.size(); j++) { - if (state_.transactions_[j].viewingId_ == state_.ballots_[i].viewingId_) { - commitBallot(state_.ballots_[i], state_.transactions_[j]); + for (size_t j = 0; j < state_->transactions_.size(); j++) { + if (state_->transactions_[j].viewingId_ == state_->ballots_[i].viewingId_) { + commitBallot(state_->ballots_[i], state_->transactions_[j]); } } } @@ -677,11 +677,11 @@ void BatClient::prepareBallotCallback(bool result, const std::string& response, } } } - braveledger_bat_helper::saveState(state_); + braveledger_bat_helper::saveState(*state_); } void BatClient::commitBallot(const braveledger_bat_helper::BALLOT_ST& ballot, const braveledger_bat_helper::TRANSACTION_ST& transaction) { - braveledger_bat_helper::SURVEYOR_ST surveyor; + braveledger_bat_helper::SURVEYOR_ST surveyor; braveledger_bat_helper::loadFromJson(surveyor, ballot.prepareBallot_); std::string surveyorIdEncoded; @@ -729,14 +729,14 @@ void BatClient::commitBallotCallback(bool result, const std::string& response, c } std::string BatClient::getWalletPassphrase() { - DCHECK(state_.walletInfo_.keyInfoSeed_.size()); + DCHECK(state_->walletInfo_.keyInfoSeed_.size()); std::string passPhrase; - if (0 == state_.walletInfo_.keyInfoSeed_.size()) { + if (0 == state_->walletInfo_.keyInfoSeed_.size()) { return passPhrase; } char* words = nullptr; - int result = bip39_mnemonic_from_bytes(nullptr, &state_.walletInfo_.keyInfoSeed_.front(), - state_.walletInfo_.keyInfoSeed_.size(), &words); + int result = bip39_mnemonic_from_bytes(nullptr, &state_->walletInfo_.keyInfoSeed_.front(), + state_->walletInfo_.keyInfoSeed_.size(), &words); LOG(ERROR) << "!!!getWalletPassphrase result == " << result << ", !!!words == " << words; if (0 != result) { DCHECK(false); @@ -760,9 +760,9 @@ void BatClient::recoverWallet(const std::string& passPhrase) { return; } - state_.walletInfo_.keyInfoSeed_ = newSeed; + state_->walletInfo_.keyInfoSeed_ = newSeed; - std::vector secretKey = braveledger_bat_helper::getHKDF(state_.walletInfo_.keyInfoSeed_); + std::vector secretKey = braveledger_bat_helper::getHKDF(state_->walletInfo_.keyInfoSeed_); std::vector publicKey; std::vector newSecretKey; braveledger_bat_helper::getPublicKeyFromSeed(secretKey, publicKey, newSecretKey); @@ -787,14 +787,14 @@ void BatClient::recoverWalletPublicKeyCallback(bool result, const std::string& r void BatClient::recoverWalletCallback(bool result, const std::string& response, const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { //LOG(ERROR) << "!!!recoverWalletCallback == " << response; - braveledger_bat_helper::getJSONWalletInfo(response, state_.walletInfo_, state_.fee_currency_, state_.fee_amount_, state_.days_); - braveledger_bat_helper::saveState(state_); + braveledger_bat_helper::getJSONWalletInfo(response, state_->walletInfo_, state_->fee_currency_, state_->fee_amount_, state_->days_); + braveledger_bat_helper::saveState(*state_); } void BatClient::getPromotion(const std::string& lang, const std::string& forPaymentId) { std::string paymentId = forPaymentId; if (paymentId.empty()) { - paymentId = state_.walletInfo_.paymentId_; + paymentId = state_->walletInfo_.paymentId_; } std::string arguments; if (!paymentId.empty() || !lang.empty()) { @@ -825,7 +825,7 @@ void BatClient::setPromotion(const std::string& promotionId, const std::string& std::string payload = braveledger_bat_helper::stringify(keys, values, 2); auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::setPromotionCallback); - batClientWebRequest_.run(buildURL((std::string)GET_SET_PROMOTION + "/" + state_.walletInfo_.paymentId_, ""), + 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_helper::URL_METHOD::PUT); } @@ -834,9 +834,8 @@ void BatClient::setPromotionCallback(bool result, const std::string& response, c } void BatClient::getPromotionCaptcha() { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatClient::getPromotionCaptchaCallback); - batClientWebRequest_.run(buildURL((std::string)GET_PROMOTION_CAPTCHA + state_.walletInfo_.paymentId_, ""), + batClientWebRequest_.run(buildURL((std::string)GET_PROMOTION_CAPTCHA + state_->walletInfo_.paymentId_, ""), runnable, std::vector(), "", "", braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST(), braveledger_bat_helper::URL_METHOD::GET); } @@ -845,4 +844,4 @@ void BatClient::getPromotionCaptchaCallback(bool result, const std::string& resp LOG(ERROR) << "!!!getPromotionCaptchaCallback == " << response; } -} //namespace braveledger_bat_client +} // namespace braveledger_bat_client diff --git a/src/bat_client.h b/src/bat_client.h index de98144..6218aba 100644 --- a/src/bat_client.h +++ b/src/bat_client.h @@ -9,7 +9,6 @@ #include #include - #if defined CHROMIUM_BUILD #include "bat_client_webrequest_chromium.h" #else @@ -17,139 +16,92 @@ #endif #include "bat_balance.h" -#include "bat_helper.h" +#include "bat_helper_platform.h" + +namespace braveledger_bat_helper { +struct BALLOT_ST; +struct BATCH_PROOF; +struct FETCH_CALLBACK_EXTRA_DATA_ST; +struct TRANSACTION_ST; +struct CURRENT_RECONCILE; +struct CLIENT_STATE_ST; +} namespace braveledger_bat_client { class BatClient { -public: + public: explicit BatClient( bool useProxy = true); ~BatClient(); void loadStateOrRegisterPersona(); - 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); - uint64_t getPublisherTimestamp(); - void publisherInfo(const std::string& publisher, braveledger_bat_helper::FetchCallback callback, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - + const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); void setContributionAmount(const double& amount); - std::string getBATAddress(); - std::string getBTCAddress(); - std::string getETHAddress(); - std::string getLTCAddress(); - void getWalletProperties(braveledger_bat_helper::FetchCallback callback, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - + const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); bool isReadyForReconcile(); - void reconcile(const std::string& viewingId, braveledger_bat_helper::SimpleCallback callback); - unsigned int ballots(const std::string& viewingId); - void votePublishers(const std::vector& publishers, const std::string& viewingId); - void prepareBallots(); - std::string getWalletPassphrase(); - void recoverWallet(const std::string& passPhrase); - void getPromotion(const std::string& lang, const std::string& forPaymentId); - void setPromotion(const std::string& promotionId, const std::string& captchaResponse); - void getPromotionCaptcha(); -private: + 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 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); - void prepareVoteBatch(const std::vector& batchProof); - 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 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 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 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 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); - 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); bool useProxy_; - braveledger_bat_client_webrequest::BatClientWebRequest batClientWebRequest_; - - braveledger_bat_helper::CLIENT_STATE_ST state_; - + 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_; - - braveledger_bat_helper::CURRENT_RECONCILE currentReconcile_; + std::unique_ptr currentReconcile_; }; -} // namespace braveledger_bat_client + +} // namespace braveledger_bat_client #endif // BRAVELEDGER_BAT_CLIENT_H_ diff --git a/src/bat_client_webrequest.cc b/src/bat_client_webrequest.cc index 81aadf7..5084fc1 100644 --- a/src/bat_client_webrequest.cc +++ b/src/bat_client_webrequest.cc @@ -1,8 +1,7 @@ #include "bat_client_webrequest.h" - namespace braveledger_bat_client_webrequest { - //TODO: implement +// TODO: implement -} //namespace braveledger_bat_client_webreque \ No newline at end of file +} // namespace braveledger_bat_client_webreque diff --git a/src/bat_client_webrequest.h b/src/bat_client_webrequest.h index 27503b6..fcd889a 100644 --- a/src/bat_client_webrequest.h +++ b/src/bat_client_webrequest.h @@ -5,28 +5,30 @@ #ifndef BRAVELEDGER_BAT_CLIENT_WEBREQUEST_H_ #define BRAVELEDGER_BAT_CLIENT_WEBREQUEST_H_ - #include #include -#include "bat_helper.h" +#include "bat_helper_platform.h" +#include "url_method.h" + +namespace braveledger_bat_helper { +struct FETCH_CALLBACK_EXTRA_DATA_ST; +} namespace braveledger_bat_client_webrequest { - //platform-dependent implementation - class BatClientWebRequest - { - public: - BatClientWebRequest() = default; - - void run(const std::string& url, braveledger_bat_helper::FetchCallback callback, +// platform-dependent implementation +class BatClientWebRequest { + public: + BatClientWebRequest() = default; + void run(const std::string& url, braveledger_bat_helper::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 braveledger_bat_helper::URL_METHOD& method) { - //TODO: implement! - } - }; + //TODO: implement! + } +}; -} //namespace braveledger_bat_client_webrequest +} // 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 index ebbd918..c2458a8 100644 --- a/src/bat_client_webrequest_chromium.cc +++ b/src/bat_client_webrequest_chromium.cc @@ -3,18 +3,20 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "bat_client_webrequest_chromium.h" -#include "url_fetcher.h" -#include "url_request_context.h" -#include "url_request_context_getter.h" -#include "url_request_context_builder.h" -#include "logging.h" + +#include "base/logging.h" #include "chrome/browser/browser_process.h" -#include "browser_thread.h" -#include "net/base/upload_data_stream.h" -#include "net/base/upload_element_reader.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" +#include "bat_helper.h" namespace braveledger_bat_client_webrequest { @@ -24,13 +26,13 @@ namespace braveledger_bat_client_webrequest { BatClientWebRequest::~BatClientWebRequest() { } - BatClientWebRequest::URL_FETCH_REQUEST::URL_FETCH_REQUEST(){} - BatClientWebRequest::URL_FETCH_REQUEST::~URL_FETCH_REQUEST(){} + BatClientWebRequest::URL_FETCH_REQUEST::URL_FETCH_REQUEST() {} + BatClientWebRequest::URL_FETCH_REQUEST::~URL_FETCH_REQUEST() {} std::unique_ptr BatClientWebRequest::CreateUploadStream(const std::string& stream) { std::vector buffer(stream.begin(),stream.end()); - return net::ElementsUploadDataStream::CreateWithReader( + return net::ElementsUploadDataStream::CreateWithReader( std::unique_ptr(new net::UploadOwnedBytesElementReader(&buffer)), 0); } @@ -61,7 +63,7 @@ namespace braveledger_bat_client_webrequest { }*/ url_fetchers_.back()->url_fetcher_ = net::URLFetcher::Create(GURL(url), requestType, this); url_fetchers_.back()->callback_ = callback; - url_fetchers_.back()->extraData_ = extraData; + 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++) { @@ -102,9 +104,9 @@ namespace braveledger_bat_client_webrequest { std::lock_guard guard(fetcher_mutex_); if (url_fetchers_.size()) { - url_fetchers_.front()->callback_.Run(!failure, response, url_fetchers_.front()->extraData_); + url_fetchers_.front()->callback_.Run(!failure, response, *url_fetchers_.front()->extraData_); url_fetchers_.pop_front(); } } -} //namespace braveledger_bat_client_webrequest +} // namespace braveledger_bat_client_webrequest diff --git a/src/bat_client_webrequest_chromium.h b/src/bat_client_webrequest_chromium.h index e2bfb64..c9483b5 100644 --- a/src/bat_client_webrequest_chromium.h +++ b/src/bat_client_webrequest_chromium.h @@ -10,64 +10,68 @@ #include #include -#include "url_fetcher_delegate.h" #include "base/callback.h" +#include "net/url_request/url_fetcher_delegate.h" -#include "bat_helper.h" +#include "bat_helper_platform.h" +#include "url_method.h" +namespace braveledger_bat_helper { +struct FETCH_CALLBACK_EXTRA_DATA_ST; +} // We have to implement another fetcher class for iOS namespace net { - class URLFetcher; - class UploadDataStream; +class URLFetcher; +class UploadDataStream; } namespace braveledger_bat_client_webrequest { - class BatClientWebRequest: public net::URLFetcherDelegate { - public: - struct URL_FETCH_REQUEST { - URL_FETCH_REQUEST(); - ~URL_FETCH_REQUEST(); +class BatClientWebRequest: public net::URLFetcherDelegate { + public: + struct URL_FETCH_REQUEST { + URL_FETCH_REQUEST(); + ~URL_FETCH_REQUEST(); - std::unique_ptr url_fetcher_; - braveledger_bat_helper::FetchCallback callback_; - braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST extraData_; - }; + std::unique_ptr url_fetcher_; + braveledger_bat_helper::FetchCallback callback_; + std::unique_ptr extraData_; + }; - BatClientWebRequest(); - ~BatClientWebRequest() final; + BatClientWebRequest(); + ~BatClientWebRequest() final; - void run(const std::string& url, braveledger_bat_helper::FetchCallback callback, + void run(const std::string& url, braveledger_bat_helper::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 braveledger_bat_helper::URL_METHOD& method); - 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 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 { - } + void OnURLFetchUploadProgress(const net::URLFetcher* source, + int64_t current, + int64_t total) final { + } - private: - void runOnThread(const std::string& url, braveledger_bat_helper::FetchCallback callback, + private: + void runOnThread(const std::string& url, braveledger_bat_helper::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 braveledger_bat_helper::URL_METHOD& method); - std::unique_ptr CreateUploadStream(const std::string& stream); + std::unique_ptr CreateUploadStream(const std::string& stream); - std::list> url_fetchers_; - std::mutex fetcher_mutex_; - //std::unique_ptr url_fetcher_; - }; + std::list> url_fetchers_; + std::mutex fetcher_mutex_; + // std::unique_ptr url_fetcher_; +}; -} //namespace braveledger_bat_client_webrequest +} // 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 f4cf146..40a0079 100644 --- a/src/bat_get_media.cc +++ b/src/bat_get_media.cc @@ -2,36 +2,38 @@ * 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_get_media.h" + #include #include "bat_get_media.h" +#include "bat_helper.h" #include "static_values.h" -//leveldb #include "leveldb/db.h" - +#include "rapidjson_bat_helper.h" namespace braveledger_bat_get_media { BatGetMedia::BatGetMedia(): - level_db_(nullptr) { + level_db_(nullptr) { auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatGetMedia::openMediaPublishersDB); braveledger_bat_helper::PostTask(runnable); } BatGetMedia::~BatGetMedia() { - if (nullptr != level_db_) { + if (nullptr != level_db_) { delete level_db_; } } void BatGetMedia::openMediaPublishersDB() { - std::string dbPath; std::string root; braveledger_bat_helper::getHomeDir(root); - braveledger_bat_helper::appendPath(root, MEDIA_CACHE_DB_NAME, dbPath); + braveledger_bat_helper::appendPath(root, MEDIA_CACHE_DB_NAME, dbPath); leveldb::Options options; options.create_if_missing = true; @@ -47,42 +49,42 @@ void BatGetMedia::openMediaPublishersDB() { } 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) { + const 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 - DCHECK(level_db_); - if (level_db_) { + // Check if the publisher's info is already cached + DCHECK(level_db_); + if (level_db_) { std::string value; - leveldb::Status status = level_db_->Get(leveldb::ReadOptions(), mediaKey, &value); - if (!value.empty()) { + leveldb::Status status = level_db_->Get(leveldb::ReadOptions(), mediaKey, &value); + if (!value.empty()) { braveledger_bat_helper::MEDIA_PUBLISHER_INFO publisherInfo; braveledger_bat_helper::loadFromJson(publisherInfo, value); - //LOG(ERROR) << "!!!from JSON " << publisherInfo.publisherName_; + //LOG(ERROR) << "!!!from JSON " << publisherInfo.publisherName_; - uint64_t realDuration = duration; - if (TWITCH_MEDIA_TYPE == providerName) { - realDuration = getTwitchDuration(publisherInfo.twitchEventInfo_, twitchEventInfo); - //LOG(ERROR) << "!!!realDuration == " << realDuration; + uint64_t realDuration = duration; + if (TWITCH_MEDIA_TYPE == providerName) { + realDuration = getTwitchDuration(publisherInfo.twitchEventInfo_, twitchEventInfo); + //LOG(ERROR) << "!!!realDuration == " << realDuration; braveledger_bat_helper::TWITCH_EVENT_INFO oldInfo = publisherInfo.twitchEventInfo_; - publisherInfo.twitchEventInfo_ = twitchEventInfo; - publisherInfo.twitchEventInfo_.status_ = getTwitchStatus(oldInfo, twitchEventInfo); + publisherInfo.twitchEventInfo_ = twitchEventInfo; + publisherInfo.twitchEventInfo_.status_ = getTwitchStatus(oldInfo, twitchEventInfo); std::string medPubJson; - braveledger_bat_helper::saveToJson(publisherInfo, medPubJson); - saveMediaPublisherInfo(mediaKey, medPubJson); - + braveledger_bat_helper::saveToJsonString(publisherInfo, medPubJson); + saveMediaPublisherInfo(mediaKey, medPubJson); + if (0 == realDuration) { - return; - } - } - + return; + } + } + braveledger_bat_helper::run_runnable(callback, std::cref(realDuration), std::cref(publisherInfo) ); - return; - } + return; + } } - std::string mediaURL = getMediaURL(mediaId, providerName); - std::string mediaURLEncoded; + std::string mediaURL = getMediaURL(mediaId, providerName); + std::string mediaURLEncoded; braveledger_bat_helper::encodeURIComponent(mediaURL, mediaURLEncoded); braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST extraData; @@ -91,103 +93,103 @@ void BatGetMedia::getPublisherFromMediaProps(const std::string& mediaId, const s extraData.string1 = providerName; extraData.string2 = mediaURL; { - std::lock_guard guard(callbacks_access_mutex_); - DCHECK(mapCallbacks_.find(mediaKey) == mapCallbacks_.end()); - mapCallbacks_[mediaKey] = callback; + 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); - batClientWebRequest_.run((std::string)YOUTUBE_PROVIDER_URL + "?format=json&url=" + mediaURLEncoded, + batClientWebRequest_.run((std::string)YOUTUBE_PROVIDER_URL + "?format=json&url=" + mediaURLEncoded, runnable, std::vector(), "", "", extraData, braveledger_bat_helper::URL_METHOD::GET); - } else if (TWITCH_MEDIA_TYPE == providerName) { + } else if (TWITCH_MEDIA_TYPE == providerName) { braveledger_bat_helper::MEDIA_PUBLISHER_INFO publisherInfo; - publisherInfo.favIconURL_ = ""; - publisherInfo.channelName_ = getMediaURL(mediaId, providerName); - publisherInfo.publisherURL_ = publisherInfo.channelName_ + "/videos"; - publisherInfo.publisher_ = providerName + "#author:"; - size_t pos = publisherInfo.channelName_.rfind("/"); - if (pos != std::string::npos && pos < publisherInfo.channelName_.length() - 1) { - publisherInfo.publisher_ += publisherInfo.channelName_.substr(pos + 1); - //LOG(ERROR) << "!!!publisher == " << publisherInfo.publisher_; - } - publisherInfo.publisherName_ = publisherInfo.publisher_; - publisherInfo.twitchEventInfo_ = twitchEventInfo; - publisherInfo.twitchEventInfo_.status_ = getTwitchStatus(braveledger_bat_helper::TWITCH_EVENT_INFO(), twitchEventInfo); - //LOG(ERROR) << "!!!publisherURL_ == " << publisherInfo.publisherURL_; - //LOG(ERROR) << "!!!channelName_ == " << publisherInfo.channelName_; + publisherInfo.favIconURL_ = ""; + publisherInfo.channelName_ = getMediaURL(mediaId, providerName); + publisherInfo.publisherURL_ = publisherInfo.channelName_ + "/videos"; + publisherInfo.publisher_ = providerName + "#author:"; + size_t pos = publisherInfo.channelName_.rfind("/"); + if (pos != std::string::npos && pos < publisherInfo.channelName_.length() - 1) { + publisherInfo.publisher_ += publisherInfo.channelName_.substr(pos + 1); + //LOG(ERROR) << "!!!publisher == " << publisherInfo.publisher_; + } + publisherInfo.publisherName_ = publisherInfo.publisher_; + publisherInfo.twitchEventInfo_ = twitchEventInfo; + publisherInfo.twitchEventInfo_.status_ = getTwitchStatus(braveledger_bat_helper::TWITCH_EVENT_INFO(), twitchEventInfo); + //LOG(ERROR) << "!!!publisherURL_ == " << publisherInfo.publisherURL_; + //LOG(ERROR) << "!!!channelName_ == " << publisherInfo.channelName_; std::string medPubJson; - braveledger_bat_helper::saveToJson(publisherInfo, medPubJson); - saveMediaPublisherInfo(mediaKey, medPubJson); + braveledger_bat_helper::saveToJsonString(publisherInfo, medPubJson); + saveMediaPublisherInfo(mediaKey, medPubJson); - uint64_t realDuration = getTwitchDuration(braveledger_bat_helper::TWITCH_EVENT_INFO(), twitchEventInfo); - //LOG(ERROR) << "!!!realDuration == " << realDuration; - if (0 == realDuration) { - return; - } + uint64_t realDuration = getTwitchDuration(braveledger_bat_helper::TWITCH_EVENT_INFO(), twitchEventInfo); + //LOG(ERROR) << "!!!realDuration == " << realDuration; + if (0 == realDuration) { + return; + } - { - std::lock_guard guard(callbacks_access_mutex_); + { + std::lock_guard guard(callbacks_access_mutex_); - std::map::iterator iter = mapCallbacks_.find(extraData.string5); - DCHECK(iter != mapCallbacks_.end()); + std::map::iterator iter = mapCallbacks_.find(extraData.string5); + DCHECK(iter != mapCallbacks_.end()); braveledger_bat_helper::GetMediaPublisherInfoCallback callback = iter->second; - mapCallbacks_.erase(iter); + mapCallbacks_.erase(iter); braveledger_bat_helper::run_runnable (callback, std::cref(realDuration), std::cref(publisherInfo) ); - } - } + } + } } std::string BatGetMedia::getTwitchStatus(const braveledger_bat_helper::TWITCH_EVENT_INFO& oldEventInfo, const braveledger_bat_helper::TWITCH_EVENT_INFO& newEventInfo) { - std::string status = "playing"; - - if ( - ( - newEventInfo.event_ == "video_pause" && - oldEventInfo.event_ != "video_pause" - ) || // User clicked pause (we need to exclude seeking while paused) - ( - newEventInfo.event_ == "video_pause" && - oldEventInfo.event_ == "video_pause" && - oldEventInfo.status_ == "playing" - ) || // User clicked pause as soon as he clicked play - ( - newEventInfo.event_ == "player_click_vod_seek" && - oldEventInfo.status_ == "paused" - ) // Seeking a video while it is paused - ) { - status = "paused"; - } - - // User pauses a video, then seeks it and plays it again - if (newEventInfo.event_ == "video_pause" && - oldEventInfo.event_ == "player_click_vod_seek" && - oldEventInfo.status_ == "paused") { - status = "playing"; - } - - //LOG(ERROR) << "!!!video status == " << status; - - return status; + std::string status = "playing"; + + if ( + ( + newEventInfo.event_ == "video_pause" && + oldEventInfo.event_ != "video_pause" + ) || // User clicked pause (we need to exclude seeking while paused) + ( + newEventInfo.event_ == "video_pause" && + oldEventInfo.event_ == "video_pause" && + oldEventInfo.status_ == "playing" + ) || // User clicked pause as soon as he clicked play + ( + newEventInfo.event_ == "player_click_vod_seek" && + oldEventInfo.status_ == "paused" + ) // Seeking a video while it is paused + ) { + status = "paused"; + } + + // User pauses a video, then seeks it and plays it again + if (newEventInfo.event_ == "video_pause" && + oldEventInfo.event_ == "player_click_vod_seek" && + oldEventInfo.status_ == "paused") { + status = "playing"; + } + + //LOG(ERROR) << "!!!video status == " << status; + + return status; } uint64_t BatGetMedia::getTwitchDuration(const braveledger_bat_helper::TWITCH_EVENT_INFO& oldEventInfo, const braveledger_bat_helper::TWITCH_EVENT_INFO& newEventInfo) { - // Remove duplicated events - if (oldEventInfo.event_ == newEventInfo.event_ && - oldEventInfo.time_ == newEventInfo.time_) { - return 0; - } + // Remove duplicated events + if (oldEventInfo.event_ == newEventInfo.event_ && + oldEventInfo.time_ == newEventInfo.time_) { + return 0; + } - if (newEventInfo.event_ == "video-play") { // Start event - return TWITCH_MINIMUM_SECONDS * 1000; - } + if (newEventInfo.event_ == "video-play") { // Start event + return TWITCH_MINIMUM_SECONDS * 1000; + } //TODO: check if converted properly - double time = 0; - std::stringstream tempTime(newEventInfo.time_); + double time = 0; + std::stringstream tempTime(newEventInfo.time_); double currentTime = 0; tempTime >> currentTime; std::stringstream tempOld(oldEventInfo.time_); @@ -195,119 +197,119 @@ uint64_t BatGetMedia::getTwitchDuration(const braveledger_bat_helper::TWITCH_EVE tempOld >> oldTime; if (oldEventInfo.event_ == "video-play") { - time = currentTime - oldTime - TWITCH_MINIMUM_SECONDS; - } else if (newEventInfo.event_ == "minute-watched" || // Minute watched - newEventInfo.event_ == "buffer-empty" || // Run out of buffer - newEventInfo.event_ == "video_error" || // Video has some problems - newEventInfo.event_ == "video_end" || // Video ended - (newEventInfo.event_ == "player_click_vod_seek" && oldEventInfo.status_ == "paused") || // Vod seek - ( - newEventInfo.event_ == "video_pause" && - ( - ( - oldEventInfo.event_ != "video_pause" && - oldEventInfo.event_ != "player_click_vod_seek" - ) || - oldEventInfo.status_ == "playing" - ) - ) // User paused video - ) { - time = currentTime - oldTime; + time = currentTime - oldTime - TWITCH_MINIMUM_SECONDS; + } else if (newEventInfo.event_ == "minute-watched" || // Minute watched + newEventInfo.event_ == "buffer-empty" || // Run out of buffer + newEventInfo.event_ == "video_error" || // Video has some problems + newEventInfo.event_ == "video_end" || // Video ended + (newEventInfo.event_ == "player_click_vod_seek" && oldEventInfo.status_ == "paused") || // Vod seek + ( + newEventInfo.event_ == "video_pause" && + ( + ( + oldEventInfo.event_ != "video_pause" && + oldEventInfo.event_ != "player_click_vod_seek" + ) || + oldEventInfo.status_ == "playing" + ) + ) // User paused video + ) { + time = currentTime - oldTime; } if (time < 0) { - return 0; + return 0; } if (time > TWITCH_MAXIMUM_SECONDS_CHUNK) { - time = TWITCH_MAXIMUM_SECONDS_CHUNK; + time = TWITCH_MAXIMUM_SECONDS_CHUNK; } return (uint64_t)(time * 1000.0); } -void BatGetMedia::getPublisherFromMediaPropsCallback(bool result, const std::string& response, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { +void BatGetMedia::getPublisherFromMediaPropsCallback(bool result, const std::string& response, + const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { //LOG(ERROR) << "!!!!getPublisherFromMediaPropsCallback response == " << response; if (YOUTUBE_MEDIA_TYPE == extraData.string1) { std::string publisherURL; braveledger_bat_helper::getJSONValue("author_url", response, publisherURL); std::string publisherName; braveledger_bat_helper::getJSONValue("author_name", response, publisherName); - //LOG(ERROR) << "!!!!publisherURL == " << publisherURL; - //LOG(ERROR) << "!!!!publisherName == " << publisherName; + //LOG(ERROR) << "!!!!publisherURL == " << publisherURL; + //LOG(ERROR) << "!!!!publisherName == " << publisherName; braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST newExtraData(extraData); - newExtraData.string3 = publisherURL; - newExtraData.string4 = publisherName; + newExtraData.string3 = publisherURL; + newExtraData.string4 = publisherName; auto runnable = braveledger_bat_helper::bat_mem_fun_binder3(*this, &BatGetMedia::getPublisherInfoCallback); batClientWebRequest_.run(publisherURL, runnable, - std::vector(), "", "", newExtraData, braveledger_bat_helper::URL_METHOD::GET); - } + std::vector(), "", "", newExtraData, braveledger_bat_helper::URL_METHOD::GET); + } } -void BatGetMedia::getPublisherInfoCallback(bool result, const std::string& response, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { - //LOG(ERROR) << "!!!!getPublisherInfoCallback == " << response; - if (YOUTUBE_MEDIA_TYPE == extraData.string1) { - size_t pos = response.find("
", pos); - if (posEnd != std::string::npos) { - favIconURL = response.substr(pos + 10, posEnd - pos - 10); - //LOG(ERROR) << "!!!publisher's picture try == " << favIconURL; - } - } - } else { - break; - } - pos++; - if (pos > response.length() - 1) { - pos = std::string::npos; - } - } while (favIconURL.find("photo.jpg") == std::string::npos); - //LOG(ERROR) << "publisher's picture URL == " << favIconURL; - std::string channelName = extraData.string3 + "/videos"; - pos = extraData.string3.rfind("/"); - std::string publisher = extraData.string1 + "#channel:"; - if (pos != std::string::npos && pos < extraData.string3.length() - 1) { - publisher += extraData.string3.substr(pos + 1); - //LOG(ERROR) << "!!!publisher == " << publisher; - } +void BatGetMedia::getPublisherInfoCallback(bool result, const std::string& response, + const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData) { + //LOG(ERROR) << "!!!!getPublisherInfoCallback == " << response; + if (YOUTUBE_MEDIA_TYPE == extraData.string1) { + size_t pos = response.find("
", pos); + if (posEnd != std::string::npos) { + favIconURL = response.substr(pos + 10, posEnd - pos - 10); + //LOG(ERROR) << "!!!publisher's picture try == " << favIconURL; + } + } + } else { + break; + } + pos++; + if (pos > response.length() - 1) { + pos = std::string::npos; + } + } while (favIconURL.find("photo.jpg") == std::string::npos); + //LOG(ERROR) << "publisher's picture URL == " << favIconURL; + std::string channelName = extraData.string3 + "/videos"; + pos = extraData.string3.rfind("/"); + std::string publisher = extraData.string1 + "#channel:"; + if (pos != std::string::npos && pos < extraData.string3.length() - 1) { + publisher += extraData.string3.substr(pos + 1); + //LOG(ERROR) << "!!!publisher == " << publisher; + } braveledger_bat_helper::MEDIA_PUBLISHER_INFO publisherInfo; - publisherInfo.publisherName_ = extraData.string4; - publisherInfo.publisherURL_ = extraData.string3; - publisherInfo.favIconURL_ = favIconURL; - publisherInfo.channelName_ = channelName; - publisherInfo.publisher_ = publisher; + publisherInfo.publisherName_ = extraData.string4; + publisherInfo.publisherURL_ = extraData.string3; + publisherInfo.favIconURL_ = favIconURL; + publisherInfo.channelName_ = channelName; + publisherInfo.publisher_ = publisher; std::string medPubJson; - braveledger_bat_helper::saveToJson(publisherInfo, medPubJson); + braveledger_bat_helper::saveToJsonString(publisherInfo, medPubJson); auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatGetMedia::saveMediaPublisherInfo, std::cref(extraData.string5), std::cref(medPubJson) ); braveledger_bat_helper::PostTask(runnable); - { - std::lock_guard guard(callbacks_access_mutex_); + { + std::lock_guard guard(callbacks_access_mutex_); - std::map::iterator iter = mapCallbacks_.find(extraData.string5); - DCHECK(iter != mapCallbacks_.end()); + std::map::iterator iter = mapCallbacks_.find(extraData.string5); + DCHECK(iter != mapCallbacks_.end()); braveledger_bat_helper::GetMediaPublisherInfoCallback callback = iter->second; - mapCallbacks_.erase(iter); + mapCallbacks_.erase(iter); braveledger_bat_helper::run_runnable (callback, std::cref(extraData.value1), std::cref(publisherInfo) ); - } - } + } + } } void BatGetMedia::saveMediaPublisherInfo(const std::string& mediaKey, const std::string& stringifiedPublisher) { - if (!level_db_) { + if (!level_db_) { DCHECK(false); - return; + return; } // Save the publisher to the database @@ -316,17 +318,16 @@ void BatGetMedia::saveMediaPublisherInfo(const std::string& mediaKey, const std: } std::string BatGetMedia::getMediaURL(const std::string& mediaId, const std::string& providerName) { - std::string res; + std::string res; - DCHECK(!mediaId.empty()); - if (YOUTUBE_MEDIA_TYPE == providerName) { - res = "https://www.youtube.com/watch?v=" + mediaId; - } else if (TWITCH_MEDIA_TYPE == providerName) { - res = "https://www.twitch.tv/" + mediaId; - } + DCHECK(!mediaId.empty()); + if (YOUTUBE_MEDIA_TYPE == providerName) { + res = "https://www.youtube.com/watch?v=" + mediaId; + } else if (TWITCH_MEDIA_TYPE == providerName) { + res = "https://www.twitch.tv/" + mediaId; + } - return res; + return res; } -} //namespace braveledger_bat_get_media - +} // namespace braveledger_bat_get_media diff --git a/src/bat_get_media.h b/src/bat_get_media.h index 93e1e71..f67831c 100644 --- a/src/bat_get_media.h +++ b/src/bat_get_media.h @@ -9,56 +9,50 @@ #include #include - #if defined CHROMIUM_BUILD #include "bat_client_webrequest_chromium.h" #else #include "bat_client_webrequest.h" #endif -#include "bat_helper.h" +namespace braveledger_bat_helper { +struct FETCH_CALLBACK_EXTRA_DATA_ST; +struct MEDIA_PUBLISHER_INFO; +struct TWITCH_EVENT_INFO; +} namespace leveldb { - class DB; +class DB; } namespace braveledger_bat_get_media { - class BatGetMedia { - public: - - BatGetMedia(); - ~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); - - private: - void openMediaPublishersDB(); - - std::string getMediaURL(const std::string& mediaId, const std::string& providerName); - - void getPublisherFromMediaPropsCallback(bool result, const std::string& response, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - - void getPublisherInfoCallback(bool result, const std::string& response, - const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); - - void saveMediaPublisherInfo(const std::string& mediaKey, const std::string& stringifiedPublisher); - - 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); +class BatGetMedia { + public: - leveldb::DB* level_db_; + BatGetMedia(); + ~BatGetMedia(); - braveledger_bat_client_webrequest::BatClientWebRequest batClientWebRequest_; + 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); - std::map mapCallbacks_; + private: + void openMediaPublishersDB(); + std::string getMediaURL(const std::string& mediaId, const std::string& providerName); + void getPublisherFromMediaPropsCallback(bool result, const std::string& response, + const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); + void getPublisherInfoCallback(bool result, const std::string& response, + const braveledger_bat_helper::FETCH_CALLBACK_EXTRA_DATA_ST& extraData); + void saveMediaPublisherInfo(const std::string& mediaKey, const std::string& stringifiedPublisher); + 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); - std::mutex callbacks_access_mutex_; - }; + leveldb::DB* level_db_; + braveledger_bat_client_webrequest::BatClientWebRequest batClientWebRequest_; + std::map mapCallbacks_; + std::mutex callbacks_access_mutex_; +}; -} //namespace braveledger_bat_get_media +} // namespace braveledger_bat_get_media -#endif // BRAVELEDGER_BAT_GET_MEDIA_H_ \ No newline at end of file +#endif // BRAVELEDGER_BAT_GET_MEDIA_H_ diff --git a/src/bat_helper.cc b/src/bat_helper.cc index 72f0f98..118d70d 100644 --- a/src/bat_helper.cc +++ b/src/bat_helper.cc @@ -2,6 +2,7 @@ * 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_helper.h" #include #include @@ -11,24 +12,14 @@ #include #include -//tweetnacl -#include "tweetnacl.h" - -//boringssl -#include +#include #include +#include #include -#include - - -//rapidjson -#include "rapidjson/document.h" -#include "rapidjson/error/en.h" - -#include "bat_helper.h" +#include "rapidjson_bat_helper.h" #include "static_values.h" - +#include "tweetnacl.h" namespace braveledger_bat_helper { @@ -44,8 +35,19 @@ namespace braveledger_bat_helper { ///////////////////////////////////////////////////////////////////////////// WALLET_INFO_ST::WALLET_INFO_ST() {} + WALLET_INFO_ST::WALLET_INFO_ST(const WALLET_INFO_ST& other) { + paymentId_ = other.paymentId_; + addressBAT_ = other.addressBAT_; + addressBTC_ = other.addressBTC_; + addressCARD_ID_ = other.addressCARD_ID_; + addressETH_ = other.addressETH_; + addressLTC_ = other.addressLTC_; + keyInfoSeed_ = other.keyInfoSeed_; + } + WALLET_INFO_ST::~WALLET_INFO_ST() {} + bool WALLET_INFO_ST::loadFromJson(const std::string & json) { rapidjson::Document d; @@ -67,7 +69,7 @@ namespace braveledger_bat_helper { //convert keyInfoSeed and check error std::string sKeyInfoSeed = d["keyInfoSeed"].GetString(); error = ! getFromBase64(sKeyInfoSeed, keyInfoSeed_); - + if (false == error) { paymentId_ = d["paymentId"].GetString(); @@ -75,37 +77,37 @@ namespace braveledger_bat_helper { addressBTC_ = d["addressBTC"].GetString(); addressCARD_ID_ = d["addressCARD_ID"].GetString(); addressETH_ = d["addressETH"].GetString(); - addressLTC_ = d["addressLTC"].GetString(); + addressLTC_ = d["addressLTC"].GetString(); } return !error; } - - void WALLET_INFO_ST::saveToJson(JsonWriter & writer) const - { + + void saveToJson(JsonWriter & writer, const WALLET_INFO_ST& data) + { writer.StartObject(); writer.String("paymentId"); - writer.String(paymentId_.c_str()); + writer.String(data.paymentId_.c_str()); writer.String("addressBAT"); - writer.String(addressBAT_.c_str()); + writer.String(data.addressBAT_.c_str()); writer.String("addressBTC"); - writer.String(addressBTC_.c_str()); + writer.String(data.addressBTC_.c_str()); writer.String("addressCARD_ID"); - writer.String(addressCARD_ID_.c_str()); + writer.String(data.addressCARD_ID_.c_str()); writer.String("addressETH"); - writer.String(addressETH_.c_str()); + writer.String(data.addressETH_.c_str()); writer.String("addressLTC"); - writer.String(addressLTC_.c_str()); + writer.String(data.addressLTC_.c_str()); writer.String("keyInfoSeed"); - writer.String(getBase64 (keyInfoSeed_).c_str()); + writer.String(getBase64(data.keyInfoSeed_).c_str()); - writer.EndObject(); + writer.EndObject(); } ///////////////////////////////////////////////////////////////////////////// @@ -122,7 +124,7 @@ namespace braveledger_bat_helper { bool TRANSACTION_BALLOT_ST::loadFromJson(const std::string & json) { rapidjson::Document d; - d.Parse(json.c_str()); + d.Parse(json.c_str()); //has parser errors or wrong types bool error = d.HasParseError(); @@ -130,8 +132,8 @@ namespace braveledger_bat_helper { { error = !( d["publisher"].IsString() && d["offset"].IsUint() ); - } - + } + if (false == error) { publisher_ = d["publisher"].GetString(); @@ -139,19 +141,19 @@ namespace braveledger_bat_helper { } return !error; - } - - void TRANSACTION_BALLOT_ST::saveToJson(JsonWriter & writer) const - { + } + + void saveToJson(JsonWriter & writer, const TRANSACTION_BALLOT_ST& data) + { writer.StartObject(); writer.String("publisher"); - writer.String(publisher_.c_str()); + writer.String(data.publisher_.c_str()); writer.String("offset"); - writer.Uint(offset_); + writer.Uint(data.offset_); - writer.EndObject(); + writer.EndObject(); } ///////////////////////////////////////////////////////////////////////////// @@ -215,15 +217,15 @@ namespace braveledger_bat_helper { d["altCurrency"].IsString() && d["probi"].IsString() && d["votes"].IsUint() && - d["ballots"].IsArray()); - } - + d["ballots"].IsArray()); + } + if (false == error) { viewingId_ = d["viewingId"].GetString(); surveyorId_ = d["surveyorId"].GetString(); contribution_fiat_amount_ = d["contribution_fiat_amount"].GetString(); - contribution_fiat_currency_ = d["contribution_fiat_currency"].GetString(); + contribution_fiat_currency_ = d["contribution_fiat_currency"].GetString(); contribution_altcurrency_ = d["contribution_altcurrency"].GetString(); contribution_probi_ = d["contribution_probi"].GetString(); contribution_fee_ = d["contribution_fee"].GetString(); @@ -236,17 +238,17 @@ namespace braveledger_bat_helper { altCurrency_ = d["altCurrency"].GetString(); probi_ = d["probi"].GetString(); votes_ = d["votes"].GetUint(); - + for ( auto & i : d["rates"].GetObject()) { contribution_rates_.insert(std::make_pair(i.name.GetString(), i.value.GetDouble() )); - } + } for (auto & i : d["surveyorIds"].GetArray()) { surveyorIds_.push_back(i.GetString()); - } - + } + for (const auto & i : d["ballots"].GetArray() ) { rapidjson::StringBuffer sb; @@ -260,28 +262,28 @@ namespace braveledger_bat_helper { } return !error; - } + } + - - void TRANSACTION_ST::saveToJson(JsonWriter & writer) const + void saveToJson(JsonWriter & writer, const TRANSACTION_ST& data) { writer.StartObject(); writer.String("viewingId"); - writer.String(viewingId_.c_str()); + writer.String(data.viewingId_.c_str()); writer.String("surveyorId"); - writer.String(surveyorId_.c_str()); + writer.String(data.surveyorId_.c_str()); writer.String("contribution_fiat_amount"); - writer.String(contribution_fiat_amount_.c_str()); + writer.String(data.contribution_fiat_amount_.c_str()); writer.String("contribution_fiat_currency"); - writer.String(contribution_fiat_currency_.c_str()); + writer.String(data.contribution_fiat_currency_.c_str()); writer.String("rates"); writer.StartObject(); - for (auto & p : contribution_rates_) + for (auto & p : data.contribution_rates_) { writer.String(p.first.c_str()); writer.Double(p.second); @@ -289,55 +291,55 @@ namespace braveledger_bat_helper { writer.EndObject(); writer.String("contribution_altcurrency"); - writer.String(contribution_altcurrency_.c_str()); + writer.String(data.contribution_altcurrency_.c_str()); writer.String("contribution_probi"); - writer.String(contribution_probi_.c_str()); + writer.String(data.contribution_probi_.c_str()); writer.String("contribution_fee"); - writer.String(contribution_fee_.c_str()); + writer.String(data.contribution_fee_.c_str()); writer.String("submissionStamp"); - writer.String(submissionStamp_.c_str()); + writer.String(data.submissionStamp_.c_str()); writer.String("submissionId"); - writer.String(submissionId_.c_str()); + writer.String(data.submissionId_.c_str()); writer.String("anonizeViewingId"); - writer.String(anonizeViewingId_.c_str()); + writer.String(data.anonizeViewingId_.c_str()); writer.String("registrarVK"); - writer.String(registrarVK_.c_str()); + writer.String(data.registrarVK_.c_str()); writer.String("masterUserToken"); - writer.String(masterUserToken_.c_str()); + writer.String(data.masterUserToken_.c_str()); writer.String("surveyorIds"); writer.StartArray(); - for (auto & i : surveyorIds_) + for (auto & i : data.surveyorIds_) { writer.String(i.c_str()); } writer.EndArray(); writer.String("satoshis"); - writer.String(satoshis_.c_str()); + writer.String(data.satoshis_.c_str()); writer.String("altCurrency"); - writer.String(altCurrency_.c_str()); + writer.String(data.altCurrency_.c_str()); writer.String("probi"); - writer.String(probi_.c_str()); + writer.String(data.probi_.c_str()); writer.String("votes"); - writer.Uint(votes_); + writer.Uint(data.votes_); /* TODO: clarify if it needs to be serialized writer.String("ballots"); writer.StartArray(); - for (auto & i : ballots_) + for (auto & i : data.ballots_) { - i.saveToJson(writer); + saveToJson(writer, i); } writer.EndArray(); */ @@ -378,7 +380,7 @@ namespace braveledger_bat_helper { d["prepareBallot"].IsString() && d["delayStamp"].IsUint64() ); } - + if (false == error) { viewingId_ = d["viewingId"].GetString(); @@ -390,29 +392,29 @@ namespace braveledger_bat_helper { } return !error; - } - - void BALLOT_ST::saveToJson(JsonWriter & writer) const + } + + void saveToJson(JsonWriter & writer, const BALLOT_ST& data) { writer.StartObject(); writer.String("viewingId"); - writer.String(viewingId_.c_str()); + writer.String(data.viewingId_.c_str()); writer.String("surveyorId"); - writer.String(surveyorId_.c_str()); + writer.String(data.surveyorId_.c_str()); writer.String("publisher"); - writer.String(publisher_.c_str()); + writer.String(data.publisher_.c_str()); writer.String("offset"); - writer.Uint(offset_); + writer.Uint(data.offset_); writer.String("prepareBallot"); - writer.String(prepareBallot_.c_str()); + writer.String(data.prepareBallot_.c_str()); writer.String("delayStamp"); - writer.Uint64(delayStamp_); + writer.Uint64(data.delayStamp_); writer.EndObject(); } @@ -425,6 +427,25 @@ namespace braveledger_bat_helper { fee_amount_(0), days_(0) {} + CLIENT_STATE_ST::CLIENT_STATE_ST(const CLIENT_STATE_ST& other) { + walletInfo_ = other.walletInfo_; + bootStamp_ = other.bootStamp_; + reconcileStamp_ = other.reconcileStamp_; + personaId_ = other.personaId_; + userId_ = other.userId_; + registrarVK_ = other.registrarVK_; + masterUserToken_ = other.masterUserToken_; + preFlight_ = other.preFlight_; + fee_currency_ = other.fee_currency_; + settings_ = other.settings_; + fee_amount_ = other.fee_amount_; + days_ = other.days_; + transactions_ = other.transactions_; + ballots_ = other.ballots_; + ruleset_ = other.ruleset_; + rulesetV2_ = other.rulesetV2_; + } + CLIENT_STATE_ST::~CLIENT_STATE_ST() {} bool CLIENT_STATE_ST::loadFromJson(const std::string & json) @@ -451,14 +472,14 @@ namespace braveledger_bat_helper { d["transactions"].IsArray() && d["ballots"].IsArray() ); } - + if (false == error) { { auto & i = d["walletInfo"]; rapidjson::StringBuffer sb; rapidjson::Writer writer(sb); - i.Accept(writer); + i.Accept(writer); walletInfo_.loadFromJson(sb.GetString()); } @@ -494,73 +515,73 @@ namespace braveledger_bat_helper { BALLOT_ST b; b.loadFromJson(sb.GetString()); ballots_.push_back(b); - } + } } return !error; } - - void CLIENT_STATE_ST::saveToJson(JsonWriter & writer) const + + void saveToJson(JsonWriter & writer, const CLIENT_STATE_ST& data) { writer.StartObject(); writer.String("walletInfo"); - walletInfo_.saveToJson(writer); + saveToJson(writer, data.walletInfo_); writer.String("bootStamp"); - writer.Uint64(bootStamp_); + writer.Uint64(data.bootStamp_); writer.String("reconcileStamp"); - writer.Uint64(reconcileStamp_); + writer.Uint64(data.reconcileStamp_); writer.String("personaId"); - writer.String(personaId_.c_str()); + writer.String(data.personaId_.c_str()); writer.String("userId"); - writer.String(userId_.c_str()); + writer.String(data.userId_.c_str()); writer.String("registrarVK"); - writer.String(registrarVK_.c_str()); + writer.String(data.registrarVK_.c_str()); writer.String("masterUserToken"); - writer.String(masterUserToken_.c_str()); + writer.String(data.masterUserToken_.c_str()); writer.String("preFlight"); - writer.String(preFlight_.c_str()); + writer.String(data.preFlight_.c_str()); writer.String("fee_currency"); - writer.String(fee_currency_.c_str()); + writer.String(data.fee_currency_.c_str()); writer.String("settings"); - writer.String(settings_.c_str()); + writer.String(data.settings_.c_str()); writer.String("fee_amount"); - writer.Double(fee_amount_); + writer.Double(data.fee_amount_); writer.String("days"); - writer.Uint(days_); + writer.Uint(data.days_); writer.String("transactions"); writer.StartArray(); - for (auto & t : transactions_) + for (auto & t : data.transactions_) { - t.saveToJson(writer); + saveToJson(writer, t); } writer.EndArray(); writer.String("ballots"); writer.StartArray(); - for (auto & b : ballots_) + for (auto & b : data.ballots_) { - b.saveToJson(writer); + saveToJson(writer, b); } writer.EndArray(); writer.String("ruleset"); - writer.String(ruleset_.c_str()); + writer.String(data.ruleset_.c_str()); writer.String("rulesetV2"); - writer.String(rulesetV2_.c_str()); + writer.String(data.rulesetV2_.c_str()); writer.EndObject(); } @@ -577,40 +598,40 @@ namespace braveledger_bat_helper { { rapidjson::Document d; d.Parse(json.c_str()); - + //has parser errors or wrong types - bool error = d.HasParseError(); + bool error = d.HasParseError(); if (false == error) { error = !(d["min_pubslisher_duration"].IsUint() && d["min_visits"].IsUint() && d["allow_non_verified"].IsBool()); } - + if (false == error) { min_pubslisher_duration_ = d["min_pubslisher_duration"].GetUint(); min_visits_ = d["min_visits"].GetUint(); allow_non_verified_ = d["allow_non_verified"].GetBool(); } - + return !error; - } - - void PUBLISHER_STATE_ST::saveToJson(JsonWriter & writer) const - { + } + + void saveToJson(JsonWriter & writer, const PUBLISHER_STATE_ST& data) + { writer.StartObject(); - + writer.String("min_pubslisher_duration"); - writer.Uint(min_pubslisher_duration_); + writer.Uint(data.min_pubslisher_duration_); writer.String("min_visits"); - writer.Uint(min_visits_); + writer.Uint(data.min_visits_); writer.String("allow_non_verified"); - writer.Bool(allow_non_verified_); - - writer.EndObject(); + writer.Bool(data.allow_non_verified_); + + writer.EndObject(); } ///////////////////////////////////////////////////////////////////////////// @@ -679,48 +700,48 @@ namespace braveledger_bat_helper { deleted_ = d["deleted"].GetBool(); weight_ = d["weight"].GetDouble(); } - + return !error; } - - void PUBLISHER_ST::saveToJson(JsonWriter & writer) const + + void saveToJson(JsonWriter & writer, const PUBLISHER_ST& data) { writer.StartObject(); //TODO: uint64 or string writer.String("duration"); - writer.Uint64(duration_); + writer.Uint64(data.duration_); writer.String("favicon_url"); - writer.String(favicon_url_.c_str()); + writer.String(data.favicon_url_.c_str()); writer.String("score"); - writer.Double(score_); + writer.Double(data.score_); writer.String("visits"); - writer.Uint(visits_); + writer.Uint(data.visits_); writer.String("verified"); - writer.Bool(verified_); + writer.Bool(data.verified_); writer.String("exclude"); - writer.Bool(exclude_); + writer.Bool(data.exclude_); writer.String("pinPercentage"); - writer.Bool(pinPercentage_); + writer.Bool(data.pinPercentage_); //TODO: uint64 or string writer.String("verifiedTimeStamp"); - writer.Uint64(verifiedTimeStamp_); + writer.Uint64(data.verifiedTimeStamp_); writer.String("percent"); - writer.Uint(percent_); + writer.Uint(data.percent_); writer.String("deleted"); - writer.Bool(deleted_); + writer.Bool(data.deleted_); writer.String("weight"); - writer.Double(weight_); + writer.Double(data.weight_); writer.EndObject(); } @@ -776,7 +797,7 @@ namespace braveledger_bat_helper { { altcurrency_ = d["altcurrency"].GetString(); balance_ = d["balance"].GetDouble(); - + for (auto & i : d["rates"].GetObject()) { rates_.insert(std::make_pair(i.name.GetString(), i.value.GetDouble())); @@ -798,7 +819,7 @@ namespace braveledger_bat_helper { parameters_days_ = d["parameters"]["adFree"]["days"].GetUint(); } return !error; - } + } ///////////////////////////////////////////////////////////////////////////// FETCH_CALLBACK_EXTRA_DATA_ST::FETCH_CALLBACK_EXTRA_DATA_ST(): @@ -859,25 +880,25 @@ namespace braveledger_bat_helper { return !error; } - - void SURVEYOR_ST::saveToJson(JsonWriter & writer) const + + void saveToJson(JsonWriter & writer, const SURVEYOR_ST& data) { writer.StartObject(); writer.String("signature"); - writer.String(signature_.c_str()); + writer.String(data.signature_.c_str()); writer.String("surveyorId"); - writer.String(surveyorId_.c_str()); + writer.String(data.surveyorId_.c_str()); writer.String("surveyVK"); - writer.String(surveyVK_.c_str()); + writer.String(data.surveyVK_.c_str()); writer.String("registrarVK"); - writer.String(registrarVK_.c_str()); + writer.String(data.registrarVK_.c_str()); writer.String("surveySK"); - writer.String(surveySK_.c_str()); + writer.String(data.surveySK_.c_str()); writer.EndObject(); } @@ -939,33 +960,33 @@ namespace braveledger_bat_helper { return !error; } - void MEDIA_PUBLISHER_INFO::saveToJson(JsonWriter & writer) const + void saveToJson(JsonWriter & writer, const MEDIA_PUBLISHER_INFO& data) { writer.StartObject(); writer.String("publisherName"); - writer.String(publisherName_.c_str()); + writer.String(data.publisherName_.c_str()); writer.String("publisherURL"); - writer.String(publisherURL_.c_str()); + writer.String(data.publisherURL_.c_str()); writer.String("favIconURL"); - writer.String(favIconURL_.c_str()); + writer.String(data.favIconURL_.c_str()); writer.String("channelName"); - writer.String(channelName_.c_str()); + writer.String(data.channelName_.c_str()); writer.String("publisher"); - writer.String(publisher_.c_str()); + writer.String(data.publisher_.c_str()); writer.String("twitch_event"); - writer.String(twitchEventInfo_.event_.c_str()); + writer.String(data.twitchEventInfo_.event_.c_str()); writer.String("twitch_time"); - writer.String(twitchEventInfo_.time_.c_str()); + writer.String(data.twitchEventInfo_.time_.c_str()); writer.String("twitch_status"); - writer.String(twitchEventInfo_.status_.c_str()); + writer.String(data.twitchEventInfo_.status_.c_str()); writer.EndObject(); } @@ -995,10 +1016,10 @@ namespace braveledger_bat_helper { //has parser errors or wrong types bool error = d.HasParseError() || ( false == d.HasMember(fieldName.c_str()) ); if (false == error) - { + { value = d[fieldName.c_str()].GetString(); } - return !error; + return !error; } bool getJSONList(const std::string& fieldName, const std::string& json, std::vector & value) { @@ -1019,7 +1040,7 @@ namespace braveledger_bat_helper { bool getJSONTwitchProperties(const std::string& json, std::vector>& parts) { rapidjson::Document d; - d.Parse(json.c_str()); + d.Parse(json.c_str()); //has parser errors or wrong types bool error = d.HasParseError(); @@ -1029,14 +1050,14 @@ namespace braveledger_bat_helper { { const char * event_field = "event"; std::map eventmap; - - auto obj = i.GetObject(); + + auto obj = i.GetObject(); if (obj.HasMember(event_field)) { eventmap[event_field] = obj[event_field].GetString(); } - const char * props_field = "properties"; + const char * props_field = "properties"; if (obj.HasMember(props_field)) { eventmap[props_field] = ""; @@ -1061,7 +1082,7 @@ namespace braveledger_bat_helper { } //for (auto & i : d.GetArray()) } - return !error; + return !error; } bool getJSONBatchSurveyors(const std::string& json, std::vector& surveyors) { @@ -1076,13 +1097,13 @@ namespace braveledger_bat_helper { { rapidjson::StringBuffer sb; rapidjson::Writer writer(sb); - i.Accept(writer); + i.Accept(writer); std::string surveyor = sb.GetString(); surveyors.push_back(surveyor); } } return !error; - } + } bool getJSONRates(const std::string& json, std::map& rates) { rapidjson::Document d; @@ -1149,7 +1170,7 @@ namespace braveledger_bat_helper { { unsignedTx.amount_ = d["unsignedTx"]["denomination"]["amount"].GetString(); unsignedTx.currency_ = d["unsignedTx"]["denomination"]["currency"].GetString(); - unsignedTx.destination_ = d["unsignedTx"]["destination"].GetString(); + unsignedTx.destination_ = d["unsignedTx"]["destination"].GetString(); } return !error; } @@ -1169,12 +1190,12 @@ namespace braveledger_bat_helper { if (false == error) { - verified = d["properties"]["verified"].GetBool(); + verified = d["properties"]["verified"].GetBool(); } return !error; } - bool getJSONWalletInfo(const std::string& json, WALLET_INFO_ST& walletInfo, + bool getJSONWalletInfo(const std::string& json, WALLET_INFO_ST& walletInfo, std::string& fee_currency, double& fee_amount, unsigned int& days) { rapidjson::Document d; d.Parse(json.c_str()); @@ -1224,7 +1245,7 @@ namespace braveledger_bat_helper { { publisherTimestamp = d["timestamp"].GetUint64(); } - return !error; + return !error; } std::vector generateSeed() { @@ -1234,14 +1255,14 @@ namespace braveledger_bat_helper { std::random_device r; std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()}; auto rand = std::bind(std::uniform_int_distribution<>(0, UCHAR_MAX), std::mt19937(seed)); - - std::generate_n(vSeed.begin(), SEED_LENGTH, rand); + + std::generate_n(vSeed.begin(), SEED_LENGTH, rand); return vSeed; } std::vector getHKDF(const std::vector& seed) { DCHECK(!seed.empty()); - std::vector out(SEED_LENGTH); + std::vector out(SEED_LENGTH); int hkdfRes = HKDF(&out.front(), SEED_LENGTH, EVP_sha512(), &seed.front(), seed.size(), braveledger_ledger::g_hkdfSalt, SALT_LENGTH, nullptr, 0); @@ -1259,7 +1280,7 @@ namespace braveledger_bat_helper { crypto_sign_keypair(&publicKey.front(), &secretKey.front(), 1); - DCHECK(!publicKey.empty() && !secretKey.empty()); + DCHECK(!publicKey.empty() && !secretKey.empty()); } std::string uint8ToHex(const std::vector& in) { @@ -1276,20 +1297,20 @@ namespace braveledger_bat_helper { rapidjson::StringBuffer buffer; JsonWriter writer(buffer); writer.StartObject(); - + for (unsigned int i = 0; i < size; i++) { writer.String(keys[i].c_str()); writer.String(values[i].c_str()); } - + writer.EndObject(); return buffer.GetString(); } std::string stringifyUnsignedTx(const UNSIGNED_TX& unsignedTx) { rapidjson::StringBuffer buffer; - JsonWriter writer(buffer); + JsonWriter writer(buffer); writer.StartObject(); writer.String("denomination"); @@ -1299,14 +1320,14 @@ namespace braveledger_bat_helper { writer.String(unsignedTx.amount_.c_str()); writer.String("currency"); - writer.String(unsignedTx.currency_.c_str()); + writer.String(unsignedTx.currency_.c_str()); writer.EndObject(); writer.String("destination"); writer.String(unsignedTx.destination_.c_str()); writer.EndObject(); - return buffer.GetString(); + return buffer.GetString(); } std::string stringifyRequestCredentialsSt(const REQUEST_CREDENTIALS_ST& request_credentials) { @@ -1317,7 +1338,7 @@ namespace braveledger_bat_helper { writer.String("requestType"); writer.String(request_credentials.requestType_.c_str()); - + writer.String("request"); writer.StartObject(); //request @@ -1436,8 +1457,8 @@ namespace braveledger_bat_helper { return res; } - bool getFromBase64(const std::string& in, std::vector & out) { - bool succeded = true; + bool getFromBase64(const std::string& in, std::vector & out) { + bool succeded = true; size_t size = 0; if (!EVP_DecodedLength(&size, in.length())) { DCHECK(false); @@ -1456,7 +1477,7 @@ namespace braveledger_bat_helper { { succeded = false; out.clear(); - } + } } return succeded; } @@ -1487,13 +1508,12 @@ namespace braveledger_bat_helper { uint64_t currentTime() { return time(0); - } - + } void saveState(const CLIENT_STATE_ST& state) { - + std::string data; - braveledger_bat_helper::saveToJson(state, data); + braveledger_bat_helper::saveToJsonString(state, data); //LOG(ERROR) << "!!!saveState == " << data; std::string ledger_state_file_path; @@ -1501,31 +1521,31 @@ namespace braveledger_bat_helper { 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, std::cref(ledger_state_file_path), std::cref(data)); + auto runnable = braveledger_bat_helper::bat_fun_binder(&braveledger_bat_helper::writeFileNoReturn, std::cref(ledger_state_file_path), std::cref(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::saveToJson(state, 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); - + 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, std::cref(ledger_pub_state_file_path), std::cref(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); } @@ -1562,7 +1582,7 @@ namespace braveledger_bat_helper { else { LOG(ERROR) << "getTwitchParts failed in getFromBase64"; - } + } } } @@ -1634,8 +1654,7 @@ namespace braveledger_bat_helper { } return duration; - } - + } void readStateFile(ReadStateCallback callback) { std::string file_path; @@ -1649,7 +1668,7 @@ namespace braveledger_bat_helper { { CLIENT_STATE_ST state; braveledger_bat_helper::loadFromJson(state, data.str()); - braveledger_bat_helper::run_runnable (callback, true, std::cref(state)); + braveledger_bat_helper::run_runnable (callback, true, std::cref(state)); } else { @@ -1685,6 +1704,4 @@ namespace braveledger_bat_helper { //ignoring return writeFile(path, data); } - -} //namespace braveledger_bat_helper - +} // namespace braveledger_bat_helper diff --git a/src/bat_helper.h b/src/bat_helper.h index 186f1b8..22cd20b 100644 --- a/src/bat_helper.h +++ b/src/bat_helper.h @@ -9,35 +9,13 @@ #include #include -#include "static_values.h" #include "bat_helper_platform.h" - -#include "rapidjson/writer.h" -#include "rapidjson/stringbuffer.h" +#include "static_values.h" +#include "url_method.h" namespace braveledger_bat_helper { - using JsonWriter = rapidjson::Writer; - - template void saveToJson(const T& t, std::string & json) - { - rapidjson::StringBuffer buffer; - JsonWriter writer(buffer); - t.saveToJson(writer); - json = buffer.GetString(); - } - - //return: parsing status: true = succeded, false = failed - template bool loadFromJson( T& t, const std::string & json) - { - bool succeded = t.loadFromJson(json); - if (!succeded) { - LOG(ERROR) << "Failed to parse:" << json << std::endl; - } - return succeded; - } - - struct REQUEST_CREDENTIALS_ST { + struct REQUEST_CREDENTIALS_ST { REQUEST_CREDENTIALS_ST(); ~REQUEST_CREDENTIALS_ST(); @@ -75,13 +53,12 @@ namespace braveledger_bat_helper { struct WALLET_INFO_ST { WALLET_INFO_ST(); + WALLET_INFO_ST(const WALLET_INFO_ST&); ~WALLET_INFO_ST(); //load from json string bool loadFromJson(const std::string & json); - //save to json string - void saveToJson(JsonWriter & writer) const; std::string paymentId_; std::string addressBAT_; std::string addressBTC_; @@ -96,11 +73,8 @@ namespace braveledger_bat_helper { ~TRANSACTION_BALLOT_ST(); //load from json string - bool loadFromJson(const std::string & json); + bool loadFromJson(const std::string & json); - //save to json string - void saveToJson(JsonWriter & writer) const; - std::string publisher_; unsigned int offset_ = 0u; }; @@ -113,9 +87,6 @@ namespace braveledger_bat_helper { //load from json string bool loadFromJson(const std::string & json); - //save to json string - void saveToJson(JsonWriter & writer) const; - std::string viewingId_; std::string surveyorId_; std::string contribution_fiat_amount_; @@ -145,8 +116,6 @@ namespace braveledger_bat_helper { //load from json string bool loadFromJson(const std::string & json); - //save to json string - void saveToJson(JsonWriter & writer) const; std::string viewingId_; std::string surveyorId_; std::string publisher_; @@ -158,14 +127,12 @@ namespace braveledger_bat_helper { struct CLIENT_STATE_ST { CLIENT_STATE_ST(); + CLIENT_STATE_ST(const CLIENT_STATE_ST&); ~CLIENT_STATE_ST(); - + //load from json string bool loadFromJson(const std::string & json); - //save to json string - void saveToJson(JsonWriter & writer) const; - WALLET_INFO_ST walletInfo_; uint64_t bootStamp_ = 0u; uint64_t reconcileStamp_ = 0u; @@ -191,8 +158,6 @@ namespace braveledger_bat_helper { //load from json string bool loadFromJson(const std::string & json); - //save to json string - void saveToJson(JsonWriter & writer) const; unsigned int min_pubslisher_duration_ = braveledger_ledger::_default_min_pubslisher_duration; // In milliseconds unsigned int min_visits_ = 1u; bool allow_non_verified_ = true; @@ -206,9 +171,6 @@ namespace braveledger_bat_helper { //load from json string bool loadFromJson(const std::string & json); - //save to json string - void saveToJson(JsonWriter & writer) const; - uint64_t duration_ = 0u; std::string favicon_url_; double score_ = .0; @@ -290,9 +252,6 @@ namespace braveledger_bat_helper { //load from json string bool loadFromJson(const std::string & json); - //save to json string - void saveToJson(JsonWriter & writer) const; - std::string signature_; std::string surveyorId_; std::string surveyVK_; @@ -300,14 +259,12 @@ namespace braveledger_bat_helper { std::string surveySK_; }; - - - // The struct is serialized/deserialized from/into JSON as part of MEDIA_PUBLISHER_INFO + // The struct is serialized/deserialized from/into JSON as part of MEDIA_PUBLISHER_INFO struct TWITCH_EVENT_INFO { TWITCH_EVENT_INFO(); TWITCH_EVENT_INFO(const TWITCH_EVENT_INFO&); ~TWITCH_EVENT_INFO(); - + std::string event_; std::string time_; std::string status_; @@ -321,9 +278,6 @@ namespace braveledger_bat_helper { //load from json string bool loadFromJson(const std::string & json); - //save to json string - void saveToJson(JsonWriter & writer) const; - std::string publisherName_; std::string publisherURL_; std::string favIconURL_; @@ -340,12 +294,6 @@ namespace braveledger_bat_helper { BALLOT_ST ballot_; }; - enum URL_METHOD { - GET = 0, - PUT = 1, - POST = 2 - }; - struct CURRENT_RECONCILE { CURRENT_RECONCILE(); ~CURRENT_RECONCILE(); @@ -360,9 +308,8 @@ namespace braveledger_bat_helper { std::map rates_; std::string amount_; std::string currency_; - SimpleCallback ledgerCallback_; + SimpleCallback ledgerCallback_; }; - bool getJSONValue(const std::string& fieldName, const std::string& json, std::string & value); @@ -373,13 +320,13 @@ namespace braveledger_bat_helper { bool getJSONPublisherTimeStamp(const std::string& json, uint64_t& publisherTimestamp); - bool getJSONPublisherVerified(const std::string& json, bool& verified); + bool getJSONPublisherVerified(const std::string& json, bool& verified); bool getJSONUnsignedTx(const std::string& json, UNSIGNED_TX& unsignedTx); bool getJSONTransaction(const std::string& json, TRANSACTION_ST& transaction); - bool getJSONRates(const std::string& json, std::map& rates); + bool getJSONRates(const std::string& json, std::map& rates); bool getJSONTwitchProperties(const std::string& json, std::vector>& parts); @@ -397,9 +344,9 @@ namespace braveledger_bat_helper { std::string stringifyRequestCredentialsSt(const REQUEST_CREDENTIALS_ST& request_credentials); - std::string stringifyReconcilePayloadSt(const RECONCILE_PAYLOAD_ST& reconcile_payload); + std::string stringifyReconcilePayloadSt(const RECONCILE_PAYLOAD_ST& reconcile_payload); - std::string stringifyUnsignedTx(const UNSIGNED_TX& unsignedTx); + std::string stringifyUnsignedTx(const UNSIGNED_TX& unsignedTx); std::vector getSHA256(const std::string& in); @@ -409,7 +356,7 @@ namespace braveledger_bat_helper { // Sign using ed25519 algorithm std::string sign(std::string* keys, std::string* values, const unsigned int& size, - const std::string& keyId, const std::vector& secretKey); + const std::string& keyId, const std::vector& secretKey); uint64_t currentTime(); @@ -419,7 +366,7 @@ namespace braveledger_bat_helper { void savePublisherState(const PUBLISHER_STATE_ST& state); - void loadPublisherState(ReadPublisherStateCallback callback); + void loadPublisherState(ReadPublisherStateCallback callback); void getUrlQueryParts(const std::string& query, std::map& parts); @@ -429,16 +376,16 @@ 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); - + uint64_t getMediaDuration(const std::map& data, const std::string& mediaKey, const std::string& type); + void readStateFile(ReadStateCallback callback); - - void readPublisherStateFile(ReadPublisherStateCallback 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 +} // namespace braveledger_bat_helper #endif // BRAVELEDGER_BAT_HELPER_H_ diff --git a/src/bat_helper_platform.cc b/src/bat_helper_platform.cc index 6c636b8..1f3e43d 100644 --- a/src/bat_helper_platform.cc +++ b/src/bat_helper_platform.cc @@ -2,22 +2,20 @@ * 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_helper_platform.h" #if defined CHROMIUM_BUILD +#include "base/guid.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_util.h" #include "url/url_canon_stdstring.h" -#include "base/guid.h" +#include "url/url_util.h" #endif -#include "bat_helper_platform.h" #include "static_values.h" - namespace braveledger_bat_helper { void DecodeURLChars(const std::string& input, std::string& output) { @@ -26,11 +24,10 @@ namespace braveledger_bat_helper { url::DecodeURLEscapeSequences(input.c_str(), input.length(), &canonOutput); output = base::UTF16ToUTF8(base::StringPiece16(canonOutput.data(), canonOutput.length())); #else - //TODO: to implement + //TODO: to implement #endif } - std::string GenerateGUID() { #if defined CHROMIUM_BUILD @@ -53,7 +50,6 @@ namespace braveledger_bat_helper { #endif } - void getHomeDir(std::string& home) { #if defined CHROMIUM_BUILD @@ -81,12 +77,12 @@ namespace braveledger_bat_helper { bool writeFile(const std::string & path, const std::string& data) { #if defined CHROMIUM_BUILD - base::FilePath dirToSave (path.c_str()); + 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; + return (succeded != -1) ? true : false; #else //TODO: to implement assert(false); @@ -97,20 +93,20 @@ namespace braveledger_bat_helper { bool readFile(const std::string & path, std::ostringstream & ss) { -#if defined CHROMIUM_BUILD - bool succeded = false; +#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 + ss << str; + } + return succeded; +#else assert(false); return false; #endif } -} //namespace braveledger_bat_helper \ No newline at end of file +} // namespace braveledger_bat_helper diff --git a/src/bat_helper_platform.h b/src/bat_helper_platform.h index 0658d0d..505dd4b 100644 --- a/src/bat_helper_platform.h +++ b/src/bat_helper_platform.h @@ -6,16 +6,14 @@ #define BRAVELEDGER_BAT_HELPER_PLATFORM_H_ #if defined CHROMIUM_BUILD -#include "base/task_scheduler/post_task.h" #include "base/bind.h" #include "base/callback.h" -#include "base/logging.h" #include "base/files/file_path.h" -#include "base/path_service.h" #include "base/files/file_util.h" - +#include "base/logging.h" +#include "base/path_service.h" +#include "base/task_scheduler/post_task.h" #else - #include #include #include @@ -35,7 +33,6 @@ namespace braveledger_bat_helper { 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 FetchCallback = base::Callback; using ReadStateCallback = base::Callback; @@ -44,7 +41,7 @@ namespace braveledger_bat_helper { 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. + //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) { @@ -89,7 +86,7 @@ namespace braveledger_bat_helper { 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. + //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) { @@ -144,7 +141,7 @@ namespace braveledger_bat_helper { return std::bind(ptr_to_fun, _1, _2, _3); } - //working with C++ function.operator() + //working with C++ function.operator() template decltype(auto) run_runnable(Runnable & runnable, Args ... args) { @@ -180,6 +177,6 @@ namespace braveledger_bat_helper { bool readFile(const std::string & path, std::ostringstream & ss); -} //namespace braveledger_bat_helper +} // namespace braveledger_bat_helper #endif //BRAVELEDGER_BAT_HELPER_PLATFORM_H_ diff --git a/src/bat_publishers.cc b/src/bat_publishers.cc index 301c45a..aa52626 100644 --- a/src/bat_publishers.cc +++ b/src/bat_publishers.cc @@ -2,13 +2,17 @@ * 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_publishers.h" + #include #include #include "bat_helper.h" -#include "bat_publishers.h" #include "static_values.h" +#include "leveldb/db.h" +#include "rapidjson_bat_helper.h" + /* foo.bar.example.com QLD = 'bar' RLD = 'foo.bar' @@ -30,7 +34,7 @@ static bool winners_votes_compare(const braveledger_bat_helper::WINNERS_ST& firs namespace braveledger_bat_publishers { BatPublishers::BatPublishers(): - level_db_(nullptr) { + level_db_(nullptr), state_(new braveledger_bat_helper::PUBLISHER_STATE_ST) { calcScoreConsts(); } @@ -40,19 +44,19 @@ BatPublishers::~BatPublishers() { void BatPublishers::calcScoreConsts() { //TODO: check Warning C4244 '=': conversion from 'double' to 'unsigned int', possible loss of data - a_ = 1.0 / (braveledger_ledger::_d * 2.0) - state_.min_pubslisher_duration_; + a_ = 1.0 / (braveledger_ledger::_d * 2.0) - state_->min_pubslisher_duration_; a2_ = a_ * 2; a4_ = a2_ * 2; - b_ = state_.min_pubslisher_duration_ - a_; + b_ = state_->min_pubslisher_duration_ - a_; b2_ = b_ * b_; } void BatPublishers::openPublishersDB() { - std::string pubDbPath; + std::string pubDbPath; std::string root; braveledger_bat_helper::getHomeDir(root); - braveledger_bat_helper::appendPath(root, PUBLISHERS_DB_NAME, pubDbPath); - + braveledger_bat_helper::appendPath(root, PUBLISHERS_DB_NAME, pubDbPath); + level_db_.reset(nullptr); //release the existing db connection leveldb::Options options; options.create_if_missing = true; @@ -95,14 +99,14 @@ void BatPublishers::loadStateCallback(bool result, const braveledger_bat_helper: if (!result) { return; } - state_ = state; + 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); + braveledger_bat_helper::loadPublisherState(runnable1); auto runnable2 = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::loadPublishers); braveledger_bat_helper::PostTask(runnable2); @@ -122,14 +126,14 @@ void BatPublishers::saveVisitInternal(const std::string& publisher, const uint64 publisher_st.duration_ = duration; publisher_st.score_ = currentScore; publisher_st.visits_ = 1; - publishers_[publisher] = publisher_st; - braveledger_bat_helper::saveToJson(publisher_st, stringifiedPublisher); + publishers_[publisher] = publisher_st; + braveledger_bat_helper::saveToJsonString(publisher_st, stringifiedPublisher); } else { iter->second.duration_ += duration; iter->second.score_ += currentScore; iter->second.visits_ += 1; - verifiedTimestamp = iter->second.verifiedTimeStamp_; - braveledger_bat_helper::saveToJson(iter->second, stringifiedPublisher); + verifiedTimestamp = iter->second.verifiedTimeStamp_; + braveledger_bat_helper::saveToJsonString(iter->second, stringifiedPublisher); } if (!level_db_) { assert(false); @@ -141,14 +145,15 @@ void BatPublishers::saveVisitInternal(const std::string& publisher, const uint64 leveldb::Status status = level_db_->Put(leveldb::WriteOptions(), publisher, stringifiedPublisher); assert(status.ok()); } - + braveledger_bat_helper::run_runnable (callback, publisher, std::cref(verifiedTimestamp) ); + synopsisNormalizerInternal(); } void BatPublishers::saveVisit(const std::string& publisher, const uint64_t& duration, braveledger_bat_helper::SaveVisitCallback callback, bool ignoreMinTime) { - if (!ignoreMinTime && duration < state_.min_pubslisher_duration_) { + if (!ignoreMinTime && duration < state_->min_pubslisher_duration_) { return; } @@ -169,8 +174,8 @@ void BatPublishers::setPublisherTimestampVerifiedInternal(const std::string& pub return; } else { iter->second.verified_ = verified; - iter->second.verifiedTimeStamp_ = verifiedTimestamp; - braveledger_bat_helper::saveToJson(iter->second, stringifiedPublisher); + iter->second.verifiedTimeStamp_ = verifiedTimestamp; + braveledger_bat_helper::saveToJsonString(iter->second, stringifiedPublisher); } if (!level_db_) { assert(false); @@ -187,7 +192,6 @@ void BatPublishers::setPublisherTimestampVerifiedInternal(const std::string& pub void BatPublishers::setPublisherTimestampVerified(const std::string& publisher, const uint64_t& verifiedTimestamp, const bool& verified) { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::setPublisherTimestampVerifiedInternal, publisher, verifiedTimestamp, verified); braveledger_bat_helper::PostTask(runnable); } @@ -199,11 +203,11 @@ void BatPublishers::setPublisherFavIconInternal(const std::string& publisher, co if (publishers_.end() == iter) { braveledger_bat_helper::PUBLISHER_ST publisher_st; publisher_st.favicon_url_ = favicon_url; - publishers_[publisher] = publisher_st; - braveledger_bat_helper::saveToJson(publisher_st, stringifiedPublisher); + publishers_[publisher] = publisher_st; + braveledger_bat_helper::saveToJsonString(publisher_st, stringifiedPublisher); } else { - iter->second.favicon_url_ = favicon_url; - braveledger_bat_helper::saveToJson(iter->second, stringifiedPublisher); + iter->second.favicon_url_ = favicon_url; + braveledger_bat_helper::saveToJsonString(iter->second, stringifiedPublisher); } if (!level_db_) { assert(false); @@ -217,7 +221,6 @@ void BatPublishers::setPublisherFavIconInternal(const std::string& publisher, co } void BatPublishers::setPublisherFavIcon(const std::string& publisher, const std::string& favicon_url) { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::setPublisherFavIconInternal, publisher, favicon_url); braveledger_bat_helper::PostTask(runnable); } @@ -230,11 +233,11 @@ void BatPublishers::setPublisherIncludeInternal(const std::string& publisher, co if (publishers_.end() == iter) { braveledger_bat_helper::PUBLISHER_ST publisher_st; publisher_st.exclude_ = !include; - publishers_[publisher] = publisher_st; - braveledger_bat_helper::saveToJson(publisher_st, stringifiedPublisher); + publishers_[publisher] = publisher_st; + braveledger_bat_helper::saveToJsonString(publisher_st, stringifiedPublisher); } else { - iter->second.exclude_ = !include; - braveledger_bat_helper::saveToJson(iter->second, stringifiedPublisher); + iter->second.exclude_ = !include; + braveledger_bat_helper::saveToJsonString(iter->second, stringifiedPublisher); } if (!level_db_) { assert(false); @@ -250,7 +253,6 @@ void BatPublishers::setPublisherIncludeInternal(const std::string& publisher, co } void BatPublishers::setPublisherInclude(const std::string& publisher, const bool& include) { - auto runnable = braveledger_bat_helper::bat_mem_fun_binder(*this, &BatPublishers::setPublisherIncludeInternal, publisher, include); braveledger_bat_helper::PostTask(runnable); } @@ -263,11 +265,11 @@ void BatPublishers::setPublisherDeletedInternal(const std::string& publisher, co if (publishers_.end() == iter) { braveledger_bat_helper::PUBLISHER_ST publisher_st; publisher_st.deleted_ = deleted; - publishers_[publisher] = publisher_st; - braveledger_bat_helper::saveToJson(publisher_st, stringifiedPublisher); + publishers_[publisher] = publisher_st; + braveledger_bat_helper::saveToJsonString(publisher_st, stringifiedPublisher); } else { - iter->second.deleted_ = deleted; - braveledger_bat_helper::saveToJson(iter->second, stringifiedPublisher); + iter->second.deleted_ = deleted; + braveledger_bat_helper::saveToJsonString(iter->second, stringifiedPublisher); } if (!level_db_) { assert(false); @@ -294,11 +296,11 @@ void BatPublishers::setPublisherPinPercentageInternal(const std::string& publish if (publishers_.end() == iter) { braveledger_bat_helper::PUBLISHER_ST publisher_st; publisher_st.pinPercentage_ = pinPercentage; - publishers_[publisher] = publisher_st; - braveledger_bat_helper::saveToJson(publisher_st, stringifiedPublisher); + publishers_[publisher] = publisher_st; + braveledger_bat_helper::saveToJsonString(publisher_st, stringifiedPublisher); } else { - iter->second.pinPercentage_ = pinPercentage; - braveledger_bat_helper::saveToJson(iter->second, stringifiedPublisher); + iter->second.pinPercentage_ = pinPercentage; + braveledger_bat_helper::saveToJsonString(iter->second, stringifiedPublisher); } if (!level_db_) { assert(false); @@ -318,20 +320,20 @@ void BatPublishers::setPublisherPinPercentage(const std::string& publisher, cons } 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_); + state_->min_pubslisher_duration_ = duration; //TODO: conversion from 'const uint64_t' to 'unsigned int', possible loss of data + braveledger_bat_helper::savePublisherState(*state_); synopsisNormalizer(); } void BatPublishers::setPublisherMinVisits(const unsigned int& visits) { - state_.min_visits_ = visits; - braveledger_bat_helper::savePublisherState(state_); + state_->min_visits_ = visits; + braveledger_bat_helper::savePublisherState(*state_); synopsisNormalizer(); } void BatPublishers::setPublisherAllowNonVerified(const bool& allow) { - state_.allow_non_verified_ = allow; - braveledger_bat_helper::savePublisherState(state_); + state_->allow_non_verified_ = allow; + braveledger_bat_helper::savePublisherState(*state_); synopsisNormalizer(); } @@ -362,13 +364,13 @@ std::vector BatPublishers::getPublish } bool BatPublishers::isPublisherVisible(const braveledger_bat_helper::PUBLISHER_ST& publisher_st) { - if (publisher_st.deleted_ || (!state_.allow_non_verified_ && !publisher_st.verified_)) { + if (publisher_st.deleted_ || (!state_->allow_non_verified_ && !publisher_st.verified_)) { return false; } return publisher_st.score_ > 0 && - publisher_st.duration_ >= state_.min_pubslisher_duration_ && - publisher_st.visits_ >= state_.min_visits_; + publisher_st.duration_ >= state_->min_pubslisher_duration_ && + publisher_st.visits_ >= state_->min_visits_; } void BatPublishers::synopsisNormalizerInternal() { @@ -445,7 +447,6 @@ void BatPublishers::synopsisNormalizer() { std::vector BatPublishers::winners(const unsigned int& ballots) { std::vector res; - std::vector top = topN(); unsigned int totalVotes = 0; std::vector votes; @@ -478,8 +479,8 @@ std::vector BatPublishers::topN() { std::lock_guard guard(publishers_map_mutex_); for (std::map::const_iterator iter = publishers_.begin(); iter != publishers_.end(); iter++) { if (0 == iter->second.score_ - || state_.min_pubslisher_duration_ > iter->second.duration_ - || state_.min_visits_ > iter->second.visits_) { + || state_->min_pubslisher_duration_ > iter->second.duration_ + || state_->min_visits_ > iter->second.visits_) { continue; } braveledger_bat_helper::PUBLISHER_DATA_ST publisherData; @@ -502,4 +503,4 @@ double BatPublishers::concaveScore(const uint64_t& duration) { return (std::sqrt(b2_ + a4_ * duration) - b_) / (double)a2_; } -} //namespace braveledger_bat_publisher +} // namespace braveledger_bat_publisher diff --git a/src/bat_publishers.h b/src/bat_publishers.h index a7d91c0..27e7ab8 100644 --- a/src/bat_publishers.h +++ b/src/bat_publishers.h @@ -7,103 +7,109 @@ #include #include +#include #include #include -#include #include "bat_helper.h" -#include "leveldb/db.h" +namespace leveldb { +class DB; +} + +namespace braveledger_bat_helper { +struct PUBLISHER_STATE_ST; +} namespace braveledger_bat_publishers { - class BatPublishers { - public: +class BatPublishers { + public: - BatPublishers(); + BatPublishers(); - ~BatPublishers(); + ~BatPublishers(); - void initSynopsis(); + void initSynopsis(); void saveVisit(const std::string& publisher, const uint64_t& duration, braveledger_bat_helper::SaveVisitCallback callback, bool ignoreMinTime); - void setPublisherTimestampVerified(const std::string& publisher, - const uint64_t& verifiedTimestamp, const bool& verified); + void setPublisherTimestampVerified(const std::string& publisher, + const uint64_t& verifiedTimestamp, const bool& verified); - void setPublisherFavIcon(const std::string& publisher, const std::string& favicon_url); + void setPublisherFavIcon(const std::string& publisher, const std::string& favicon_url); - void setPublisherInclude(const std::string& publisher, const bool& include); + void setPublisherInclude(const std::string& publisher, const bool& include); - void setPublisherDeleted(const std::string& publisher, const bool& deleted); + void setPublisherDeleted(const std::string& publisher, const bool& deleted); - void setPublisherPinPercentage(const std::string& publisher, const bool& pinPercentage); + void setPublisherPinPercentage(const std::string& publisher, const bool& pinPercentage); - void setPublisherMinVisitTime(const uint64_t& duration); // In milliseconds + void setPublisherMinVisitTime(const uint64_t& duration); // In milliseconds - void setPublisherMinVisits(const unsigned int& visits); + void setPublisherMinVisits(const unsigned int& visits); - void setPublisherAllowNonVerified(const bool& allow); + void setPublisherAllowNonVerified(const bool& allow); - std::vector getPublishersData(); + std::vector getPublishersData(); - std::vector winners(const unsigned int& ballots); + std::vector winners(const unsigned int& ballots); - bool isEligableForContribution(const braveledger_bat_helper::PUBLISHER_DATA_ST& publisherData); + bool isEligableForContribution(const braveledger_bat_helper::PUBLISHER_DATA_ST& publisherData); - private: - double concaveScore(const uint64_t& duration); + private: + double concaveScore(const uint64_t& duration); - void openPublishersDB(); + void openPublishersDB(); - void loadPublishers(); + void loadPublishers(); - void saveVisitInternal(const std::string& publisher, const uint64_t& duration, - braveledger_bat_helper::SaveVisitCallback callback); + void saveVisitInternal(const std::string& publisher, const uint64_t& duration, + braveledger_bat_helper::SaveVisitCallback callback); - void setPublisherFavIconInternal(const std::string& publisher, const std::string& favicon_url); + void setPublisherFavIconInternal(const std::string& publisher, const std::string& favicon_url); - void setPublisherTimestampVerifiedInternal(const std::string& publisher, - const uint64_t& verifiedTimestamp, const bool& verified); + void setPublisherTimestampVerifiedInternal(const std::string& publisher, + const uint64_t& verifiedTimestamp, const bool& verified); - void setPublisherDeletedInternal(const std::string& publisher, const bool& deleted); + void setPublisherDeletedInternal(const std::string& publisher, const bool& deleted); - void setPublisherIncludeInternal(const std::string& publisher, const bool& include); + void setPublisherIncludeInternal(const std::string& publisher, const bool& include); - void setPublisherPinPercentageInternal(const std::string& publisher, const bool& pinPercentage); + void setPublisherPinPercentageInternal(const std::string& publisher, const bool& pinPercentage); - void loadStateCallback(bool result, const braveledger_bat_helper::PUBLISHER_STATE_ST& state); + void loadStateCallback(bool result, const braveledger_bat_helper::PUBLISHER_STATE_ST& state); - void calcScoreConsts(); + void calcScoreConsts(); - void synopsisNormalizer(); + void synopsisNormalizer(); - void synopsisNormalizerInternal(); + void synopsisNormalizerInternal(); - bool isPublisherVisible(const braveledger_bat_helper::PUBLISHER_ST& publisher_st); + bool isPublisherVisible(const braveledger_bat_helper::PUBLISHER_ST& publisher_st); - std::vector topN(); + std::vector topN(); - std::map publishers_; + std::map publishers_; - std::mutex publishers_map_mutex_; + std::mutex publishers_map_mutex_; - std::unique_ptr level_db_; + std::unique_ptr level_db_; - braveledger_bat_helper::PUBLISHER_STATE_ST state_; + std::unique_ptr state_; - unsigned int a_; + unsigned int a_; - unsigned int a2_; + unsigned int a2_; - unsigned int a4_; + unsigned int a4_; - unsigned int b_; + unsigned int b_; - unsigned int b2_; - }; + unsigned int b2_; +}; -} //namespace braveledger_bat_publishers +} // namespace braveledger_bat_publishers #endif // BRAVELEDGER_BAT_PUBLISHERS_H_ diff --git a/src/ledger.cc b/src/ledger.cc index 2ab2e27..e79778f 100644 --- a/src/ledger.cc +++ b/src/ledger.cc @@ -3,13 +3,14 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "bat_helper.h" -#include "ledger.h" #include "bat_client.h" #include "bat_get_media.h" +#include "bat_helper.h" #include "bat_publishers.h" +#include "ledger.h" #include "static_values.h" +#include "rapidjson_bat_helper.h" using namespace braveledger_bat_client; using namespace braveledger_bat_publishers; @@ -22,7 +23,7 @@ namespace braveledger_ledger { bat_get_media_ = new BatGetMedia(); } - Ledger::~Ledger() { + Ledger::~Ledger() { if (bat_get_media_) { delete bat_get_media_; } @@ -330,11 +331,11 @@ namespace braveledger_ledger { } if (!bat_get_media_) { return; - } + } 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, + auto runnable2 = braveledger_bat_helper::bat_mem_fun_binder(*bat_get_media_, &BatGetMedia::getPublisherFromMediaProps, std::cref(mediaId), std::cref(mediaKey), type, std::cref(duration), std::cref(twitchEventInfo), runnable1); braveledger_bat_helper::PostTask(runnable2); @@ -344,5 +345,4 @@ namespace braveledger_ledger { saveVisit(mediaPublisherInfo.publisher_, duration, true); } -} //namespace braveledger_ledger - +} // namespace braveledger_ledger diff --git a/src/ledger.h b/src/ledger.h index 4e9a34d..9ba82d0 100644 --- a/src/ledger.h +++ b/src/ledger.h @@ -5,91 +5,62 @@ #ifndef BRAVELEDGER_LEDGER_H_ #define BRAVELEDGER_LEDGER_H_ - -#include #include #include +#include -#include "bat_helper.h" #include "bat_client.h" -#include "bat_publishers.h" #include "bat_get_media.h" +#include "bat_publishers.h" +namespace braveledger_bat_helper { + struct FETCH_CALLBACK_EXTRA_DATA_ST; + struct MEDIA_PUBLISHER_INFO; +} namespace braveledger_ledger { - class Ledger { - public: - Ledger(); - - ~Ledger(); - - // 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, const std::string& type); - - std::unique_ptr bat_client_; - - std::unique_ptr bat_publishers_; - - braveledger_bat_get_media::BatGetMedia* bat_get_media_; - }; - -} //namespace braveledger_ledger +class Ledger { + public: + Ledger(); + ~Ledger(); + + // 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, const std::string& type); + std::unique_ptr bat_client_; + std::unique_ptr bat_publishers_; + braveledger_bat_get_media::BatGetMedia* bat_get_media_; +}; + +} // namespace braveledger_ledger #endif // BRAVELEDGER_LEDGER_H_ diff --git a/src/rapidjson_bat_helper.h b/src/rapidjson_bat_helper.h new file mode 100644 index 0000000..583e781 --- /dev/null +++ b/src/rapidjson_bat_helper.h @@ -0,0 +1,59 @@ +/* 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_RAPIDJSON_BAT_HELPER_H_ +#define BRAVELEDGER_RAPIDJSON_BAT_HELPER_H_ + +#include "rapidjson/document.h" +#include "rapidjson/error/en.h" +#include "rapidjson/stringbuffer.h" +#include "rapidjson/writer.h" + +namespace braveledger_bat_helper { + +struct BALLOT_ST; +struct CLIENT_STATE_ST; +struct MEDIA_PUBLISHER_INFO; +struct PUBLISHER_ST; +struct PUBLISHER_STATE_ST; +struct SURVEYOR_ST; +struct TRANSACTION_BALLOT_ST; +struct TRANSACTION_ST; +struct TWITCH_EVENT_INFO; +struct WALLET_INFO_ST; + +using JsonWriter = rapidjson::Writer; + +void saveToJson(JsonWriter & writer, const BALLOT_ST&); +void saveToJson(JsonWriter & writer, const CLIENT_STATE_ST&); +void saveToJson(JsonWriter & writer, const MEDIA_PUBLISHER_INFO&); +void saveToJson(JsonWriter & writer, const PUBLISHER_ST&); +void saveToJson(JsonWriter & writer, const PUBLISHER_STATE_ST&); +void saveToJson(JsonWriter & writer, const SURVEYOR_ST&); +void saveToJson(JsonWriter & writer, const TRANSACTION_BALLOT_ST&); +void saveToJson(JsonWriter & writer, const TRANSACTION_ST&); +void saveToJson(JsonWriter & writer, const TWITCH_EVENT_INFO&); +void saveToJson(JsonWriter & writer, const WALLET_INFO_ST&); + +template +void saveToJsonString(const T& t, std::string& json) { + rapidjson::StringBuffer buffer; + JsonWriter writer(buffer); + saveToJson(writer, t); + json = buffer.GetString(); +} + +//return: parsing status: true = succeded, false = failed +template +bool loadFromJson(T& t, const std::string& json) { + bool succeded = t.loadFromJson(json); + if (!succeded) { + LOG(ERROR) << "Failed to parse:" << json << std::endl; + } + return succeded; +} + +} // namespace braveledger_bat_helper + +#endif // BRAVELEDGER_RAPIDJSON_BAT_HELPER_H_ diff --git a/src/static_values.h b/src/static_values.h index 9091053..ece19dc 100644 --- a/src/static_values.h +++ b/src/static_values.h @@ -1,7 +1,6 @@ /* 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/. */ - + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef BRAVELEDGER_STATIC_VALUES_H_ #define BRAVELEDGER_STATIC_VALUES_H_ @@ -24,13 +23,13 @@ #define WALLET_PROPERTIES_END "/balance" #define RECONCILE_CONTRIBUTION "/surveyor/contribution/current/" #define SURVEYOR_VOTING "/surveyor/voting/" -#define SURVEYOR_BATCH_VOTING "/batch/surveyor/voting/" +#define SURVEYOR_BATCH_VOTING "/batch/surveyor/voting/" #define UPDATE_RULES_V1 "/v1/publisher/ruleset?consequential=true" #define UPDATE_RULES_V2 "/v2/publisher/ruleset?limit=512&excludedOnly=false" #define RECOVER_WALLET_PUBLIC_KEY "/v2/wallet?publicKey=" #define RECOVER_WALLET "/v2/wallet/" -#define GET_SET_PROMOTION "/v1/grants" -#define GET_PROMOTION_CAPTCHA "/v1/captchas/" +#define GET_SET_PROMOTION "/v1/grants" +#define GET_PROMOTION_CAPTCHA "/v1/captchas/" #define REGISTRARVK_FIELDNAME "registrarVK" #define VERIFICATION_FIELDNAME "verification" @@ -48,18 +47,18 @@ #define PUBLISHERS_DB_NAME "d2c799cd-f37f-4230-9a04-ca23ba5be240" #define MEDIA_CACHE_DB_NAME "9956db89-9105-420b-9ad4-49348bc536af" -#define YOUTUBE_MEDIA_TYPE "youtube" -#define TWITCH_MEDIA_TYPE "twitch" -#define YOUTUBE_PROVIDER_NAME "YouTube" -#define YOUTUBE_PROVIDER_URL "https://www.youtube.com/oembed" +#define YOUTUBE_MEDIA_TYPE "youtube" +#define TWITCH_MEDIA_TYPE "twitch" +#define YOUTUBE_PROVIDER_NAME "YouTube" +#define YOUTUBE_PROVIDER_URL "https://www.youtube.com/oembed" #define SEED_LENGTH 32 #define SALT_LENGTH 64 -#define TWITCH_MINIMUM_SECONDS 10 -#define TWITCH_MAXIMUM_SECONDS_CHUNK 120 +#define TWITCH_MINIMUM_SECONDS 10 +#define TWITCH_MAXIMUM_SECONDS_CHUNK 120 -#define VOTE_BATCH_SIZE 10 +#define VOTE_BATCH_SIZE 10 namespace braveledger_ledger { @@ -81,8 +80,8 @@ static const uint64_t _milliseconds_second = 1000; static const unsigned int _twitch_events_array_size = 8; // Important: set _twitch_events_array_size as a correct array size when you modify items in _twitch_events static const std::string _twitch_events[] = {"buffer-empty", "buffer-refill", "video_end", - "minute-watched", "video_pause", "player_click_vod_seek", "video-play", "video_error"}; + "minute-watched", "video_pause", "player_click_vod_seek", "video-play", "video_error"}; -} //namespace braveledger_ledger +} // namespace braveledger_ledger #endif // BRAVELEDGER_STATIC_VALUES_H_ diff --git a/src/url_method.h b/src/url_method.h new file mode 100644 index 0000000..df8b918 --- /dev/null +++ b/src/url_method.h @@ -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/. */ + +#ifndef BRAVELEDGER_URL_HELPER_H_ +#define BRAVELEDGER_URL_HELPER_H_ + +namespace braveledger_bat_helper { + enum URL_METHOD { + GET = 0, + PUT = 1, + POST = 2 + }; +} // namespace braveledger_bat_helper + +#endif // BRAVELEDGER_URL_HELPER_H_