From 2ee5944d362cf3aa01b9cffd27a9cbb7984acb2f Mon Sep 17 00:00:00 2001 From: Nejc Zdovc Date: Mon, 13 Jan 2020 10:55:42 -0800 Subject: [PATCH] Adds delays for suggestion api Resolves brave/brave-browser#7709 Resolves brave/brave-browser#6940 --- browser/ui/webui/brave_rewards_page_ui.cc | 10 + .../database/database_contribution_info.cc | 123 +++- .../database/database_contribution_info.h | 19 + .../database_contribution_info_publishers.cc | 56 +- .../database_contribution_info_publishers.h | 5 + .../database/publisher_info_database.cc | 47 ++ .../database/publisher_info_database.h | 15 + .../publisher_info_database_unittest.cc | 4 +- .../browser/rewards_service_impl.cc | 135 +++++ .../browser/rewards_service_impl.h | 28 + .../browser/rewards_service_observer.h | 1 + .../resources/page/actions/rewards_actions.ts | 2 + .../resources/page/brave_rewards_page.tsx | 7 +- .../resources/page/constants/rewards_types.ts | 3 +- .../page/reducers/publishers_reducer.ts | 3 + .../bat_ledger_client_mojo_proxy.cc | 66 +++ .../bat_ledger/bat_ledger_client_mojo_proxy.h | 20 + .../public/cpp/ledger_client_mojo_proxy.cc | 106 ++++ .../public/cpp/ledger_client_mojo_proxy.h | 36 ++ .../public/interfaces/bat_ledger.mojom | 9 + .../internal/confirmations_client_mock.h | 20 + .../include/bat/ledger/ledger_client.h | 26 + .../include/bat/ledger/mojom_structs.h | 3 + .../bat/ledger/public/interfaces/ledger.mojom | 19 +- .../internal/contribution/contribution.cc | 130 +++-- .../internal/contribution/contribution.h | 20 + .../contribution/contribution_unblinded.cc | 547 +++++++++++++----- .../contribution/contribution_unblinded.h | 88 ++- .../contribution_unblinded_unittest.cc | 53 +- .../bat/ledger/internal/ledger_client_mock.h | 20 + .../src/bat/ledger/internal/ledger_impl.cc | 54 ++ .../src/bat/ledger/internal/ledger_impl.h | 29 +- .../bat/ledger/internal/ledger_impl_mock.h | 10 + vendor/brave-ios/Ledger/BATBraveLedger.mm | 25 + .../Ledger/Generated/NativeLedgerClient.h | 5 + .../Ledger/Generated/NativeLedgerClient.mm | 15 + .../Generated/NativeLedgerClientBridge.h | 5 + 37 files changed, 1518 insertions(+), 246 deletions(-) diff --git a/browser/ui/webui/brave_rewards_page_ui.cc b/browser/ui/webui/brave_rewards_page_ui.cc index f83d236a1f89..a20514710b00 100644 --- a/browser/ui/webui/brave_rewards_page_ui.cc +++ b/browser/ui/webui/brave_rewards_page_ui.cc @@ -262,6 +262,8 @@ class RewardsDOMHandler : public WebUIMessageHandler, void OnUnblindedTokensReady( brave_rewards::RewardsService* rewards_service) override; + void ReconcileStampReset() override; + // RewardsNotificationsServiceObserver implementation void OnNotificationAdded( brave_rewards::RewardsNotificationService* rewards_notification_service, @@ -1694,6 +1696,14 @@ void RewardsDOMHandler::OnUnblindedTokensReady( web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.unblindedTokensReady"); } +void RewardsDOMHandler::ReconcileStampReset() { + if (!web_ui()->CanCallJavascript()) { + return; + } + + web_ui()->CallJavascriptFunctionUnsafe("brave_rewards.reconcileStampReset"); +} + void RewardsDOMHandler::OnGetBalanceReport( const uint32_t month, const uint32_t year, diff --git a/components/brave_rewards/browser/database/database_contribution_info.cc b/components/brave_rewards/browser/database/database_contribution_info.cc index 5c69f6655fda..3d5da72cec16 100644 --- a/components/brave_rewards/browser/database/database_contribution_info.cc +++ b/components/brave_rewards/browser/database/database_contribution_info.cc @@ -316,7 +316,7 @@ bool DatabaseContributionInfo::InsertOrUpdate( statement.BindString(0, info->contribution_id); statement.BindDouble(1, info->amount); statement.BindInt(2, static_cast(info->type)); - statement.BindInt(3, info->step); + statement.BindInt(3, static_cast(info->step)); statement.BindInt(4, info->retry_count); if (info->created_at == 0) { @@ -345,17 +345,18 @@ bool DatabaseContributionInfo::GetOneTimeTips( return false; } - const std::string query = + const std::string query = base::StringPrintf( "SELECT pi.publisher_id, pi.name, pi.url, pi.favIcon, " "ci.amount, ci.created_at, spi.status, pi.provider " - "FROM contribution_info as ci " + "FROM %s as ci " "INNER JOIN contribution_info_publishers AS cp " "ON cp.contribution_id = ci.contribution_id " "INNER JOIN publisher_info AS pi ON cp.publisher_key = pi.publisher_id " "LEFT JOIN server_publisher_info AS spi " "ON spi.publisher_key = pi.publisher_id " - "WHERE strftime('%m', datetime(ci.created_at, 'unixepoch')) = ? AND " - "strftime('%Y', datetime(ci.created_at, 'unixepoch')) = ? AND ci.type = ?"; + "WHERE strftime('%%m', datetime(ci.created_at, 'unixepoch')) = ? AND " + "strftime('%%Y', datetime(ci.created_at, 'unixepoch')) = ? AND ci.type = ?", + table_name_); sql::Statement statement(db->GetUniqueStatement(query.c_str())); @@ -394,11 +395,12 @@ bool DatabaseContributionInfo::GetContributionReport( return false; } - const std::string query = + const std::string query = base::StringPrintf( "SELECT ci.contribution_id, ci.amount, ci.type, ci.created_at " - "FROM contribution_info as ci " - "WHERE strftime('%m', datetime(ci.created_at, 'unixepoch')) = ? AND " - "strftime('%Y', datetime(ci.created_at, 'unixepoch')) = ?"; + "FROM %s as ci " + "WHERE strftime('%%m', datetime(ci.created_at, 'unixepoch')) = ? AND " + "strftime('%%Y', datetime(ci.created_at, 'unixepoch')) = ?", + table_name_); sql::Statement statement(db->GetUniqueStatement(query.c_str())); @@ -423,4 +425,107 @@ bool DatabaseContributionInfo::GetContributionReport( return true; } +bool DatabaseContributionInfo::GetNotCompletedRecords( + sql::Database* db, + ledger::ContributionInfoList* list) { + DCHECK(list && db); + if (!list || !db) { + return false; + } + + const std::string query = base::StringPrintf( + "SELECT ci.contribution_id, ci.amount, ci.type, ci.step, ci.retry_count " + "FROM %s as ci WHERE ci.step > 0", + table_name_); + + sql::Statement statement(db->GetUniqueStatement(query.c_str())); + + while (statement.Step()) { + auto info = ledger::ContributionInfo::New(); + info->contribution_id = statement.ColumnString(0); + info->amount = statement.ColumnDouble(1); + info->type = static_cast(statement.ColumnInt64(2)); + info->step = static_cast(statement.ColumnInt(3)); + info->retry_count = statement.ColumnInt(4); + publishers_->GetRecords( + db, + info->contribution_id, + &info->publishers); + + list->push_back(std::move(info)); + } + + return true; +} + +ledger::ContributionInfoPtr DatabaseContributionInfo::GetRecord( + sql::Database* db, + const std::string& contribution_id) { + DCHECK(db); + if (!db || contribution_id.empty()) { + return nullptr; + } + + const std::string query = base::StringPrintf( + "SELECT ci.contribution_id, ci.amount, ci.type, ci.step, ci.retry_count " + "FROM %s as ci " + "WHERE ci.contribution_id = ?", + table_name_); + + sql::Statement statement(db->GetUniqueStatement(query.c_str())); + + statement.BindString(0, contribution_id); + + if (!statement.Step()) { + return nullptr; + } + + auto info = ledger::ContributionInfo::New(); + info->contribution_id = statement.ColumnString(0); + info->amount = statement.ColumnDouble(1); + info->type = static_cast(statement.ColumnInt64(2)); + info->step = static_cast(statement.ColumnInt(3)); + info->retry_count = statement.ColumnInt(4); + publishers_->GetRecords( + db, + info->contribution_id, + &info->publishers); + + return info; +} + +bool DatabaseContributionInfo::UpdateStepAndCount( + sql::Database* db, + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count) { + DCHECK(db); + if (!db || contribution_id.empty()) { + return false; + } + + const std::string query = base::StringPrintf( + "UPDATE %s SET step=?, retry_count=? WHERE contribution_id = ?;", + table_name_); + + sql::Statement statement( + db->GetCachedStatement(SQL_FROM_HERE, query.c_str())); + + statement.BindInt(0, static_cast(step)); + statement.BindInt(1, retry_count); + statement.BindString(2, contribution_id); + + return statement.Run(); +} + +bool DatabaseContributionInfo::UpdateContributedAmount( + sql::Database* db, + const std::string& contribution_id, + const std::string& publisher_key) { + return publishers_->UpdateContributedAmount( + db, + contribution_id, + publisher_key); +} + } // namespace brave_rewards diff --git a/components/brave_rewards/browser/database/database_contribution_info.h b/components/brave_rewards/browser/database/database_contribution_info.h index 86035f720e16..797983125df7 100644 --- a/components/brave_rewards/browser/database/database_contribution_info.h +++ b/components/brave_rewards/browser/database/database_contribution_info.h @@ -38,6 +38,25 @@ class DatabaseContributionInfo: public DatabaseTable { const ledger::ActivityMonth month, const int year); + bool GetNotCompletedRecords( + sql::Database* db, + ledger::ContributionInfoList* list); + + ledger::ContributionInfoPtr GetRecord( + sql::Database* db, + const std::string& contribution_id); + + bool UpdateStepAndCount( + sql::Database* db, + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count); + + bool UpdateContributedAmount( + sql::Database* db, + const std::string& contribution_id, + const std::string& publisher_key); + private: bool CreateTableV2(sql::Database* db); diff --git a/components/brave_rewards/browser/database/database_contribution_info_publishers.cc b/components/brave_rewards/browser/database/database_contribution_info_publishers.cc index f0adcfd86cb5..046dfa3c3629 100644 --- a/components/brave_rewards/browser/database/database_contribution_info_publishers.cc +++ b/components/brave_rewards/browser/database/database_contribution_info_publishers.cc @@ -157,8 +157,12 @@ bool DatabaseContributionInfoPublishers::InsertOrUpdate( return false; } - const std::string query = base::StringPrintf( - "INSERT OR REPLACE INTO %s " + const std::string query_delete = base::StringPrintf( + "DELETE FROM %s WHERE contribution_id = ? AND publisher_key = ?", + table_name_); + + const std::string query_insert = base::StringPrintf( + "INSERT INTO %s " "(contribution_id, publisher_key, total_amount, contributed_amount) " "VALUES (?, ?, ?, ?)", table_name_); @@ -169,14 +173,20 @@ bool DatabaseContributionInfoPublishers::InsertOrUpdate( } for (const auto& publisher : info->publishers) { - sql::Statement statement( - db->GetCachedStatement(SQL_FROM_HERE, query.c_str())); - - statement.BindString(0, publisher->contribution_id); - statement.BindString(1, publisher->publisher_key); - statement.BindDouble(2, publisher->total_amount); - statement.BindDouble(3, publisher->contributed_amount); - statement.Run(); + sql::Statement statement_delete( + db->GetUniqueStatement(query_delete.c_str())); + + statement_delete.BindString(0, publisher->contribution_id); + statement_delete.BindString(1, publisher->publisher_key); + statement_delete.Run(); + + sql::Statement statement_insert( + db->GetUniqueStatement(query_insert.c_str())); + statement_insert.BindString(0, publisher->contribution_id); + statement_insert.BindString(1, publisher->publisher_key); + statement_insert.BindDouble(2, publisher->total_amount); + statement_insert.BindDouble(3, publisher->contributed_amount); + statement_insert.Run(); } return transaction.Commit(); @@ -252,4 +262,30 @@ bool DatabaseContributionInfoPublishers::GetPublisherInfoList( return true; } +bool DatabaseContributionInfoPublishers::UpdateContributedAmount( + sql::Database* db, + const std::string& contribution_id, + const std::string& publisher_key) { + DCHECK(db); + if (!db || contribution_id.empty() || publisher_key.empty()) { + return false; + } + + const std::string query = base::StringPrintf( + "UPDATE %s SET contributed_amount=" + "(SELECT total_amount WHERE contribution_id = ? AND publisher_key = ?) " + "WHERE contribution_id = ? AND publisher_key = ?;", + table_name_); + + sql::Statement statement( + db->GetCachedStatement(SQL_FROM_HERE, query.c_str())); + + statement.BindString(0, contribution_id); + statement.BindString(1, publisher_key); + statement.BindString(2, contribution_id); + statement.BindString(3, publisher_key); + + return statement.Run(); +} + } // namespace brave_rewards diff --git a/components/brave_rewards/browser/database/database_contribution_info_publishers.h b/components/brave_rewards/browser/database/database_contribution_info_publishers.h index 08ff6c223e6f..5a120ccdd1ae 100644 --- a/components/brave_rewards/browser/database/database_contribution_info_publishers.h +++ b/components/brave_rewards/browser/database/database_contribution_info_publishers.h @@ -37,6 +37,11 @@ class DatabaseContributionInfoPublishers: public DatabaseTable { const std::string& contribution_id, ledger::PublisherInfoList* list); + bool UpdateContributedAmount( + sql::Database* db, + const std::string& contribution_id, + const std::string& publisher_key); + private: bool CreateTableV11(sql::Database* db); diff --git a/components/brave_rewards/browser/database/publisher_info_database.cc b/components/brave_rewards/browser/database/publisher_info_database.cc index 83bd7d85a5f7..43605c70aabc 100644 --- a/components/brave_rewards/browser/database/publisher_info_database.cc +++ b/components/brave_rewards/browser/database/publisher_info_database.cc @@ -164,6 +164,53 @@ void PublisherInfoDatabase::GetContributionReport( contribution_info_->GetContributionReport(&GetDB(), list, month, year); } +void PublisherInfoDatabase::GetIncompleteContributions( + ledger::ContributionInfoList* list) { + DCHECK(list); + if (!IsInitialized() || !list) { + return; + } + + contribution_info_->GetNotCompletedRecords(&GetDB(), list); +} + +ledger::ContributionInfoPtr PublisherInfoDatabase::GetContributionInfo( + const std::string& contribution_id) { + if (!IsInitialized()) { + return nullptr; + } + + return contribution_info_->GetRecord(&GetDB(), contribution_id); +} + +bool PublisherInfoDatabase::UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count) { + if (!IsInitialized()) { + return false; + } + + return contribution_info_->UpdateStepAndCount( + &GetDB(), + contribution_id, + step, + retry_count); +} + +bool PublisherInfoDatabase::UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key) { + if (!IsInitialized()) { + return false; + } + + return contribution_info_->UpdateContributedAmount( + &GetDB(), + contribution_id, + publisher_key); +} + /** * * PUBLISHER INFO diff --git a/components/brave_rewards/browser/database/publisher_info_database.h b/components/brave_rewards/browser/database/publisher_info_database.h index d8161d4116a6..acf3c50b2191 100644 --- a/components/brave_rewards/browser/database/publisher_info_database.h +++ b/components/brave_rewards/browser/database/publisher_info_database.h @@ -147,6 +147,21 @@ class PublisherInfoDatabase { const ledger::ActivityMonth month, const int year); + void GetIncompleteContributions( + ledger::ContributionInfoList* list); + + ledger::ContributionInfoPtr GetContributionInfo( + const std::string& contribution_id); + + bool UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count); + + bool UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key); + // Vacuums the database. This will cause sqlite to defragment and collect // unused space in the file. It can be VERY SLOW. void Vacuum(); diff --git a/components/brave_rewards/browser/database/publisher_info_database_unittest.cc b/components/brave_rewards/browser/database/publisher_info_database_unittest.cc index 42f61c37c678..80e5bca7324e 100644 --- a/components/brave_rewards/browser/database/publisher_info_database_unittest.cc +++ b/components/brave_rewards/browser/database/publisher_info_database_unittest.cc @@ -162,7 +162,7 @@ TEST_F(PublisherInfoDatabaseTest, InsertOrUpdateContributionInfo) { info->contribution_id = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; info->amount = 5.0; info->type = ledger::RewardsType::AUTO_CONTRIBUTE; - info->step = -1; + info->step = ledger::ContributionStep::STEP_COMPLETED; info->retry_count = -1; info->created_at = base::Time::Now().ToJsTime(); @@ -180,7 +180,7 @@ TEST_F(PublisherInfoDatabaseTest, InsertOrUpdateContributionInfo) { EXPECT_EQ(info_sql.ColumnString(0), info->contribution_id); EXPECT_EQ(info_sql.ColumnDouble(1), info->amount); EXPECT_EQ(info_sql.ColumnInt(2), static_cast(info->type)); - EXPECT_EQ(info_sql.ColumnInt(3), info->step); + EXPECT_EQ(info_sql.ColumnInt(3), static_cast(info->step)); EXPECT_EQ(info_sql.ColumnInt(4), info->retry_count); EXPECT_EQ(info_sql.ColumnInt64(5), static_cast(info->created_at)); } diff --git a/components/brave_rewards/browser/rewards_service_impl.cc b/components/brave_rewards/browser/rewards_service_impl.cc index 245660f72c74..a723c1d154a7 100644 --- a/components/brave_rewards/browser/rewards_service_impl.cc +++ b/components/brave_rewards/browser/rewards_service_impl.cc @@ -4579,4 +4579,139 @@ void RewardsServiceImpl::OnGetContributionReport( callback(std::move(list)); } + + +ledger::ContributionInfoList GetNotCompletedContributionsOnFileTaskRunner( + PublisherInfoDatabase* backend) { + DCHECK(backend); + if (!backend) { + return {}; + } + + ledger::ContributionInfoList list; + backend->GetIncompleteContributions(&list); + return list; +} + +void RewardsServiceImpl::GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) { + base::PostTaskAndReplyWithResult( + file_task_runner_.get(), + FROM_HERE, + base::BindOnce(&GetNotCompletedContributionsOnFileTaskRunner, + publisher_info_backend_.get()), + base::BindOnce(&RewardsServiceImpl::OnGetNotCompletedContributions, + AsWeakPtr(), + callback)); +} + +void RewardsServiceImpl::OnGetNotCompletedContributions( + ledger::GetIncompleteContributionsCallback callback, + ledger::ContributionInfoList list) { + callback(std::move(list)); +} + +ledger::ContributionInfoPtr GetContributionInfoOnFileTaskRunner( + PublisherInfoDatabase* backend, + const std::string& contribution_id) { + DCHECK(backend); + if (!backend) { + return {}; + } + + return backend->GetContributionInfo(contribution_id); +} + +void RewardsServiceImpl::GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback) { + base::PostTaskAndReplyWithResult( + file_task_runner_.get(), + FROM_HERE, + base::BindOnce(&GetContributionInfoOnFileTaskRunner, + publisher_info_backend_.get(), + contribution_id), + base::BindOnce(&RewardsServiceImpl::OnGetContributionInfo, + AsWeakPtr(), + callback)); +} + +void RewardsServiceImpl::OnGetContributionInfo( + ledger::GetContributionInfoCallback callback, + ledger::ContributionInfoPtr info) { + callback(std::move(info)); +} + +ledger::Result UpdateContributionInfoStepAndCountOnFileTaskRunner( + PublisherInfoDatabase* backend, + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count) { + DCHECK(backend); + if (!backend) { + return {}; + } + + const bool success = backend->UpdateContributionInfoStepAndCount( + contribution_id, + step, + retry_count); + return success ? ledger::Result::LEDGER_OK : ledger::Result::LEDGER_ERROR; +} + +void RewardsServiceImpl::UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback) { + base::PostTaskAndReplyWithResult( + file_task_runner_.get(), + FROM_HERE, + base::BindOnce(&UpdateContributionInfoStepAndCountOnFileTaskRunner, + publisher_info_backend_.get(), + contribution_id, + step, + retry_count), + base::BindOnce(&RewardsServiceImpl::OnResult, + AsWeakPtr(), + callback)); +} + +ledger::Result UpdateContributionInfoContributedAmountOnFileTaskRunner( + PublisherInfoDatabase* backend, + const std::string& contribution_id, + const std::string& publisher_key) { + DCHECK(backend); + if (!backend) { + return {}; + } + + const bool success = backend->UpdateContributionInfoContributedAmount( + contribution_id, + publisher_key); + return success ? ledger::Result::LEDGER_OK : ledger::Result::LEDGER_ERROR; +} + +void RewardsServiceImpl::UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback) { + base::PostTaskAndReplyWithResult( + file_task_runner_.get(), + FROM_HERE, + base::BindOnce(&UpdateContributionInfoContributedAmountOnFileTaskRunner, + publisher_info_backend_.get(), + contribution_id, + publisher_key), + base::BindOnce(&RewardsServiceImpl::OnResult, + AsWeakPtr(), + callback)); +} + +void RewardsServiceImpl::ReconcileStampReset() { + for (auto& observer : observers_) { + observer.ReconcileStampReset(); + } +} + } // namespace brave_rewards diff --git a/components/brave_rewards/browser/rewards_service_impl.h b/components/brave_rewards/browser/rewards_service_impl.h index 72fc3ab52742..d075a497e59d 100644 --- a/components/brave_rewards/browser/rewards_service_impl.h +++ b/components/brave_rewards/browser/rewards_service_impl.h @@ -754,6 +754,26 @@ class RewardsServiceImpl : public RewardsService, const int year, ledger::GetContributionReportCallback callback) override; + void GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) override; + + void GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback) override; + + void UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback) override; + + void UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback) override; + + void ReconcileStampReset() override; + // end ledger::LedgerClient // Mojo Proxy methods @@ -844,6 +864,14 @@ class RewardsServiceImpl : public RewardsService, ledger::GetContributionReportCallback callback, ledger::ContributionReportInfoList list); + void OnGetNotCompletedContributions( + ledger::GetIncompleteContributionsCallback callback, + ledger::ContributionInfoList list); + + void OnGetContributionInfo( + ledger::GetContributionInfoCallback callback, + ledger::ContributionInfoPtr info); + #if defined(OS_ANDROID) ledger::Environment GetServerEnvironmentForAndroid(); void CreateWalletAttestationResult( diff --git a/components/brave_rewards/browser/rewards_service_observer.h b/components/brave_rewards/browser/rewards_service_observer.h index 79da205907fb..6f3cae18cd80 100644 --- a/components/brave_rewards/browser/rewards_service_observer.h +++ b/components/brave_rewards/browser/rewards_service_observer.h @@ -85,6 +85,7 @@ class RewardsServiceObserver : public base::CheckedObserver { const std::string& wallet_type) {} virtual void OnUnblindedTokensReady( brave_rewards::RewardsService* rewards_service) {} + virtual void ReconcileStampReset() {} // DO NOT ADD ANY MORE METHODS HERE UNLESS IT IS A BROADCAST NOTIFICATION // RewardsServiceObserver should not be used to return responses to the // caller. Method calls on RewardsService should use callbacks to return diff --git a/components/brave_rewards/resources/page/actions/rewards_actions.ts b/components/brave_rewards/resources/page/actions/rewards_actions.ts index 886825a9fc2b..e9d26f9abd4d 100644 --- a/components/brave_rewards/resources/page/actions/rewards_actions.ts +++ b/components/brave_rewards/resources/page/actions/rewards_actions.ts @@ -321,3 +321,5 @@ export const onMonthlyReport = (properties: { result: number, month: number, yea year: properties.year, report: properties.report }) + +export const onReconcileStampReset = () => action(types.ON_RECONCILE_STAMP_RESET) diff --git a/components/brave_rewards/resources/page/brave_rewards_page.tsx b/components/brave_rewards/resources/page/brave_rewards_page.tsx index 902a6c486b0c..3018910ecfdf 100644 --- a/components/brave_rewards/resources/page/brave_rewards_page.tsx +++ b/components/brave_rewards/resources/page/brave_rewards_page.tsx @@ -242,6 +242,10 @@ window.cr.define('brave_rewards', function () { getActions().onMonthlyReport(properties) } + function reconcileStampReset () { + getActions().onReconcileStampReset() + } + return { initialize, walletCreated, @@ -286,7 +290,8 @@ window.cr.define('brave_rewards', function () { disconnectWallet, onlyAnonWallet, unblindedTokensReady, - monthlyReport + monthlyReport, + reconcileStampReset } }) diff --git a/components/brave_rewards/resources/page/constants/rewards_types.ts b/components/brave_rewards/resources/page/constants/rewards_types.ts index c275e609eb95..d880ccdf583c 100644 --- a/components/brave_rewards/resources/page/constants/rewards_types.ts +++ b/components/brave_rewards/resources/page/constants/rewards_types.ts @@ -88,5 +88,6 @@ export const enum types { ONLY_ANON_WALLET = '@@rewards/ONLY_ANON_WALLET', ON_ONLY_ANON_WALLET = '@@rewards/ON_ONLY_ANON_WALLET', GET_MONTHLY_REPORT = '@@rewards/GET_MONTHLY_REPORT', - ON_MONTHLY_REPORT = '@@rewards/ON_MONTHLY_REPORT' + ON_MONTHLY_REPORT = '@@rewards/ON_MONTHLY_REPORT', + ON_RECONCILE_STAMP_RESET = '@@rewards/ON_RECONCILE_STAMP_RESET' } diff --git a/components/brave_rewards/resources/page/reducers/publishers_reducer.ts b/components/brave_rewards/resources/page/reducers/publishers_reducer.ts index e74b1d583255..09d6fc6cf85b 100644 --- a/components/brave_rewards/resources/page/reducers/publishers_reducer.ts +++ b/components/brave_rewards/resources/page/reducers/publishers_reducer.ts @@ -81,6 +81,9 @@ const publishersReducer: Reducer = (state: Rewards.St case types.GET_EXCLUDED_SITES: chrome.send('brave_rewards.getExcludedSites') break + case types.ON_RECONCILE_STAMP_RESET: + chrome.send('brave_rewards.getContributionList') + break } return state diff --git a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc index ba377ccbad88..c5e2becdfa17 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc +++ b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc @@ -1072,4 +1072,70 @@ void BatLedgerClientMojoProxy::GetContributionReport( base::BindOnce(&OnGetContributionReport, std::move(callback))); } +void OnGetNotCompletedContributions( + ledger::GetIncompleteContributionsCallback callback, + ledger::ContributionInfoList list) { + callback(std::move(list)); +} + +void BatLedgerClientMojoProxy::GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) { + bat_ledger_client_->GetIncompleteContributions( + base::BindOnce(&OnGetNotCompletedContributions, std::move(callback))); +} + +void OnGetContributionInfo( + ledger::GetContributionInfoCallback callback, + ledger::ContributionInfoPtr info) { + callback(std::move(info)); +} + +void BatLedgerClientMojoProxy::GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback) { + bat_ledger_client_->GetContributionInfo( + contribution_id, + base::BindOnce(&OnGetContributionInfo, std::move(callback))); +} + +void OnUpdateContributionInfoStepAndCount( + ledger::ResultCallback callback, + const ledger::Result result) { + callback(result); +} + +void BatLedgerClientMojoProxy::UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback) { + bat_ledger_client_->UpdateContributionInfoStepAndCount( + contribution_id, + step, + retry_count, + base::BindOnce(&OnUpdateContributionInfoStepAndCount, + std::move(callback))); +} + +void OnUpdateContributionInfoContributedAmount( + ledger::ResultCallback callback, + const ledger::Result result) { + callback(result); +} + +void BatLedgerClientMojoProxy::UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback) { + bat_ledger_client_->UpdateContributionInfoContributedAmount( + contribution_id, + publisher_key, + base::BindOnce(&OnUpdateContributionInfoContributedAmount, + std::move(callback))); +} + +void BatLedgerClientMojoProxy::ReconcileStampReset() { + bat_ledger_client_->ReconcileStampReset(); +} + } // namespace bat_ledger diff --git a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h index ae9e686ae141..817ff99f8849 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h +++ b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h @@ -244,6 +244,26 @@ class BatLedgerClientMojoProxy : public ledger::LedgerClient, const int year, ledger::GetContributionReportCallback callback) override; + void GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) override; + + void GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback) override; + + void UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback) override; + + void UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback) override; + + void ReconcileStampReset() override; + private: bool Connected() const; diff --git a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc index d20c9189c7db..f7fe6b6ac1ea 100644 --- a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc +++ b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.cc @@ -1261,4 +1261,110 @@ void LedgerClientMojoProxy::GetContributionReport( _1)); } +// static +void LedgerClientMojoProxy::OnGetNotCompletedContributions( + CallbackHolder* holder, + ledger::ContributionInfoList list) { + DCHECK(holder); + if (holder->is_valid()) { + std::move(holder->get()).Run(std::move(list)); + } + delete holder; +} + +void LedgerClientMojoProxy::GetIncompleteContributions( + GetIncompleteContributionsCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), + std::move(callback)); + ledger_client_->GetIncompleteContributions( + std::bind(LedgerClientMojoProxy::OnGetNotCompletedContributions, + holder, + _1)); +} + +// static +void LedgerClientMojoProxy::OnGetContributionInfo( + CallbackHolder* holder, + ledger::ContributionInfoPtr info) { + DCHECK(holder); + if (holder->is_valid()) { + std::move(holder->get()).Run(std::move(info)); + } + delete holder; +} + +void LedgerClientMojoProxy::GetContributionInfo( + const std::string& contribution_id, + GetContributionInfoCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), + std::move(callback)); + ledger_client_->GetContributionInfo( + contribution_id, + std::bind(LedgerClientMojoProxy::OnGetContributionInfo, + holder, + _1)); +} + +// static +void LedgerClientMojoProxy::OnUpdateContributionInfoStepAndCount( + CallbackHolder* holder, + const ledger::Result result) { + DCHECK(holder); + if (holder->is_valid()) { + std::move(holder->get()).Run(result); + } + delete holder; +} + +void LedgerClientMojoProxy::UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + UpdateContributionInfoStepAndCountCallback callback) { + auto* holder = new CallbackHolder( + AsWeakPtr(), + std::move(callback)); + ledger_client_->UpdateContributionInfoStepAndCount( + contribution_id, + step, + retry_count, + std::bind(LedgerClientMojoProxy::OnUpdateContributionInfoStepAndCount, + holder, + _1)); +} + +// static +void LedgerClientMojoProxy::OnUpdateContributionInfoContributedAmount( + CallbackHolder* holder, + const ledger::Result result) { + DCHECK(holder); + if (holder->is_valid()) { + std::move(holder->get()).Run(result); + } + delete holder; +} + +void LedgerClientMojoProxy::UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + UpdateContributionInfoContributedAmountCallback callback) { + auto* holder = + new CallbackHolder( + AsWeakPtr(), + std::move(callback)); + ledger_client_->UpdateContributionInfoContributedAmount( + contribution_id, + publisher_key, + std::bind( + LedgerClientMojoProxy::OnUpdateContributionInfoContributedAmount, + holder, + _1)); +} + +void LedgerClientMojoProxy::ReconcileStampReset() { + ledger_client_->ReconcileStampReset(); +} + } // namespace bat_ledger diff --git a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h index e9651ec060ae..08b7ff04c412 100644 --- a/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h +++ b/components/services/bat_ledger/public/cpp/ledger_client_mojo_proxy.h @@ -264,6 +264,26 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, const int year, GetContributionReportCallback callback) override; + void GetIncompleteContributions( + GetIncompleteContributionsCallback callback) override; + + void GetContributionInfo( + const std::string& contribution_id, + GetContributionInfoCallback callback) override; + + void UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + UpdateContributionInfoStepAndCountCallback callback) override; + + void UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + UpdateContributionInfoContributedAmountCallback callback) override; + + void ReconcileStampReset() override; + private: // workaround to pass base::OnceCallback into std::bind // also serves as a wrapper for passing ledger::LedgerCallbackHandler* @@ -484,6 +504,22 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, CallbackHolder* holder, ledger::ContributionReportInfoList list); + static void OnGetNotCompletedContributions( + CallbackHolder* holder, + ledger::ContributionInfoList list); + + static void OnGetContributionInfo( + CallbackHolder* holder, + ledger::ContributionInfoPtr info); + + static void OnUpdateContributionInfoStepAndCount( + CallbackHolder* holder, + const ledger::Result result); + + static void OnUpdateContributionInfoContributedAmount( + CallbackHolder* holder, + const ledger::Result result); + ledger::LedgerClient* ledger_client_; DISALLOW_COPY_AND_ASSIGN(LedgerClientMojoProxy); diff --git a/components/services/bat_ledger/public/interfaces/bat_ledger.mojom b/components/services/bat_ledger/public/interfaces/bat_ledger.mojom index 4055fbcf1673..765e2ab6b69c 100644 --- a/components/services/bat_ledger/public/interfaces/bat_ledger.mojom +++ b/components/services/bat_ledger/public/interfaces/bat_ledger.mojom @@ -299,4 +299,13 @@ interface BatLedgerClient { GetContributionReport(ledger.mojom.ActivityMonth month, int32 year) => (array list); + GetIncompleteContributions() => (array list); + + GetContributionInfo(string contribution_id) => (ledger.mojom.ContributionInfo info); + + UpdateContributionInfoStepAndCount(string contribution_id, ledger.mojom.ContributionStep step, int32 retry_count) => (ledger.mojom.Result result); + + UpdateContributionInfoContributedAmount(string contribution_id, string publisher_key) => (ledger.mojom.Result result); + + ReconcileStampReset(); }; diff --git a/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h b/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h index 3212174c8b17..1fb652fabfe0 100644 --- a/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h +++ b/vendor/bat-native-confirmations/src/bat/confirmations/internal/confirmations_client_mock.h @@ -383,6 +383,26 @@ class MockConfirmationsClient : public ConfirmationsClient { const ledger::ActivityMonth month, const int year, ledger::GetContributionReportCallback callback)); + + MOCK_METHOD1(GetIncompleteContributions, void( + ledger::GetIncompleteContributionsCallback callback)); + + MOCK_METHOD2(GetContributionInfo, void( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback)); + + MOCK_METHOD4(UpdateContributionInfoStepAndCount, void( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback)); + + MOCK_METHOD3(UpdateContributionInfoContributedAmount, void( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback)); + + MOCK_METHOD0(ReconcileStampReset, void()); }; } // namespace confirmations diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h b/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h index cb3459c8ff7e..675bac4f9020 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h @@ -82,6 +82,12 @@ using GetTransactionReportCallback = using GetContributionReportCallback = std::function; +using GetIncompleteContributionsCallback = + std::function; + +using GetContributionInfoCallback = + std::function; + class LEDGER_EXPORT LedgerClient { public: virtual ~LedgerClient() = default; @@ -335,6 +341,26 @@ class LEDGER_EXPORT LedgerClient { const ledger::ActivityMonth month, const int year, ledger::GetContributionReportCallback callback) = 0; + + virtual void GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) = 0; + + virtual void GetContributionInfo( + const std::string& contribution_id, + GetContributionInfoCallback callback) = 0; + + virtual void UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ResultCallback callback) = 0; + + virtual void UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ResultCallback callback) = 0; + + virtual void ReconcileStampReset() = 0; }; } // namespace ledger diff --git a/vendor/bat-native-ledger/include/bat/ledger/mojom_structs.h b/vendor/bat-native-ledger/include/bat/ledger/mojom_structs.h index 150e88270b8b..9a0f3cadf057 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/mojom_structs.h +++ b/vendor/bat-native-ledger/include/bat/ledger/mojom_structs.h @@ -36,6 +36,7 @@ using ClientInfoPtr = mojom::ClientInfoPtr; using ContributionInfo = mojom::ContributionInfo; using ContributionInfoPtr = mojom::ContributionInfoPtr; +using ContributionInfoList = std::vector; using ContributionPublisher = mojom::ContributionPublisher; using ContributionPublisherPtr = mojom::ContributionPublisherPtr; @@ -58,6 +59,8 @@ using ContributionQueuePublisherList = using ContributionRetry = mojom::ContributionRetry; +using ContributionStep = mojom::ContributionStep; + using Environment = ledger::mojom::Environment; using ExcludeFilter = mojom::ExcludeFilter; diff --git a/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledger.mojom b/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledger.mojom index a41390603e3b..1c9b07fce1f9 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledger.mojom +++ b/vendor/bat-native-ledger/include/bat/ledger/public/interfaces/ledger.mojom @@ -1,13 +1,24 @@ +// Copyright (c) 2019 The Brave Authors. All rights reserved. // 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/. +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. module ledger.mojom; +enum ContributionStep { + STEP_AC_TABLE_EMPTY = -4, + STEP_NOT_ENOUGH_FUNDS = -3, + STEP_FAILED = -2, + STEP_COMPLETED = -1, + STEP_NO = 0, + STEP_START = 1, + STEP_SUGGESTIONS = 2 +}; + struct ContributionInfo { string contribution_id; double amount; RewardsType type; - int32 step; + ContributionStep step; int32 retry_count; uint64 created_at; @@ -400,4 +411,4 @@ struct ContributionReportInfo { ReportType type; array publishers; uint64 created_at; -}; \ No newline at end of file +}; diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc index 4f6b8daa837d..61233bc05e04 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.cc @@ -32,6 +32,26 @@ using std::placeholders::_1; using std::placeholders::_2; using std::placeholders::_3; +namespace { + ledger::ContributionStep ConvertResultIntoContributionStep( + const ledger::Result result) { + switch (result) { + case ledger::Result::LEDGER_OK: { + return ledger::ContributionStep::STEP_COMPLETED; + } + case ledger::Result::AC_TABLE_EMPTY: { + return ledger::ContributionStep::STEP_AC_TABLE_EMPTY; + } + case ledger::Result::NOT_ENOUGH_FUNDS: { + return ledger::ContributionStep::STEP_NOT_ENOUGH_FUNDS; + } + default: { + return ledger::ContributionStep::STEP_FAILED; + } + } + } +} // namespace + namespace braveledger_contribution { Contribution::Contribution(bat_ledger::LedgerImpl* ledger) : @@ -51,6 +71,7 @@ Contribution::~Contribution() { void Contribution::Initialize() { phase_two_->Initialize(); uphold_->Initialize(); + unblinded_->Initialize(); // Resume in progress contributions ledger::CurrentReconciles currentReconciles = ledger_->GetCurrentReconciles(); @@ -353,6 +374,7 @@ void Contribution::OnTimer(uint32_t timer_id) { phase_two_->OnTimer(timer_id); unverified_->OnTimer(timer_id); uphold_->OnTimer(timer_id); + unblinded_->OnTimer(timer_id); if (timer_id == last_reconcile_timer_id_) { last_reconcile_timer_id_ = 0; @@ -364,6 +386,7 @@ void Contribution::OnTimer(uint32_t timer_id) { ProcessContributionQueue(); } + // DEPRECATED for (std::pair const& value : retry_timers_) { if (value.second == timer_id) { std::string viewing_id = value.first; @@ -394,12 +417,13 @@ void Contribution::SetTimer(uint32_t* timer_id, uint64_t start_timer_in) { } BLOG(ledger_, ledger::LogLevel::LOG_INFO) - << "Starts in " + << "Timer will start in " << start_timer_in; ledger_->SetTimer(start_timer_in, timer_id); } +// DEPRECATED void Contribution::ReconcileSuccess( const std::string& viewing_id, const double amount, @@ -427,7 +451,7 @@ void Contribution::ReconcileSuccess( info->contribution_id = viewing_id; info->amount = amount; info->type = reconcile.type; - info->step = -1; + info->step = ledger::ContributionStep::STEP_COMPLETED; info->retry_count = -1; info->created_at = now; info->publishers = std::move(publisher_list); @@ -439,6 +463,27 @@ void Contribution::ReconcileSuccess( } } +void Contribution::ContributionCompleted( + const std::string& contribution_id, + const ledger::RewardsType type, + const double amount, + const ledger::Result result) { + if (result == ledger::Result::LEDGER_OK) { + ledger_->SetBalanceReportItem( + braveledger_time_util::GetCurrentMonth(), + braveledger_time_util::GetCurrentYear(), + GetReportTypeFromRewardsType(type), + amount); + } + + ledger_->UpdateContributionInfoStepAndCount( + contribution_id, + ConvertResultIntoContributionStep(result), + -1, + [](const ledger::Result _){}); +} + +// DEPRECATED void Contribution::AddRetry( ledger::ContributionRetry step, const std::string& viewing_id, @@ -476,6 +521,7 @@ void Contribution::AddRetry( SetTimer(&retry_timers_[viewing_id], start_timer_in); } +// DEPRECATED uint64_t Contribution::GetRetryTimer( ledger::ContributionRetry step, const std::string& viewing_id, @@ -525,6 +571,7 @@ uint64_t Contribution::GetRetryTimer( return 0; } +// DEPRECATED int Contribution::GetRetryPhase(ledger::ContributionRetry step) { int phase = 0; @@ -552,6 +599,7 @@ int Contribution::GetRetryPhase(ledger::ContributionRetry step) { return phase; } +// DEPRECATED void Contribution::DoRetry(const std::string& viewing_id) { auto reconcile = ledger_->GetReconcileById(viewing_id); @@ -750,19 +798,6 @@ bool Contribution::ProcessReconcileUnblindedTokens( return false; } - auto reconcile = ledger::CurrentReconcileProperties(); - reconcile.viewing_id = ledger_->GenerateGUID(); - reconcile.fee = *fee; - reconcile.directions = directions; - reconcile.type = type; - - if (ledger_->ReconcileExists(reconcile.viewing_id)) { - BLOG(ledger_, ledger::LogLevel::LOG_ERROR) - << "Unable to reconcile with the same viewing id: " - << reconcile.viewing_id; - return false; - } - const double balance = braveledger_wallet::Balance::GetPerWalletBalance( ledger::kWalletUnBlinded, @@ -771,28 +806,53 @@ bool Contribution::ProcessReconcileUnblindedTokens( return false; } - if (balance >= *fee) { - ledger_->AddReconcile(reconcile.viewing_id, reconcile); - unblinded_->Start(reconcile.viewing_id); - return true; - } + const std::string contribution_id = ledger_->GenerateGUID(); - *fee = *fee - balance; - reconcile.fee = balance; + const uint64_t now = static_cast(base::Time::Now().ToDoubleT()); + auto contribution = ledger::ContributionInfo::New(); + contribution->contribution_id = contribution_id; + contribution->amount = *fee; + contribution->type = type; + contribution->step = ledger::ContributionStep::STEP_START; + contribution->retry_count = -1; + contribution->created_at = now; + + ledger::ReconcileDirections new_directions; + bool full_amount = true; + if (balance < *fee) { + contribution->amount = *fee - balance; + full_amount = false; + + if (type == ledger::RewardsType::RECURRING_TIP || + type == ledger::RewardsType::ONE_TIME_TIP) { + AdjustTipsAmounts( + directions, + &new_directions, + leftovers, + balance); + } + } else { + new_directions = directions; + } - if (type == ledger::RewardsType::RECURRING_TIP || - type == ledger::RewardsType::ONE_TIME_TIP) { - ledger::ReconcileDirections new_directions; - AdjustTipsAmounts(directions, - &new_directions, - leftovers, - balance); - reconcile.directions = new_directions; + ledger::ContributionPublisherList publisher_list; + for (auto& item : new_directions) { + auto publisher = ledger::ContributionPublisher::New(); + publisher->contribution_id = contribution_id; + publisher->publisher_key = item.publisher_key; + publisher->total_amount = + (item.amount_percent * contribution->amount) / 100; + publisher->contributed_amount = 0; + publisher_list.push_back(std::move(publisher)); } - ledger_->AddReconcile(reconcile.viewing_id, reconcile); - unblinded_->Start(reconcile.viewing_id); - return false; + contribution->publishers = std::move(publisher_list); + ledger_->SaveContributionInfo( + std::move(contribution), + [](const ledger::Result){}); + unblinded_->Start(contribution_id); + + return full_amount; } bool Contribution::ProcessReconcileAnonize( @@ -937,12 +997,12 @@ void Contribution::AdjustTipsAmounts( } if (item.amount_percent > reduce_fee_for) { - // anon wallet + // primary wallet const auto original_weight = item.amount_percent; item.amount_percent = reduce_fee_for; primary_directions->push_back(item); - // rest to normal wallet + // second wallet item.amount_percent = original_weight - reduce_fee_for; rest_directions->push_back(item); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h index e38cdc358974..10b70be0a588 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution.h @@ -137,11 +137,20 @@ class Contribution { // Does final stage in contribution // Sets reports and contribution info + // DEPRECATED void ReconcileSuccess( const std::string& viewing_id, const double amount, const bool delete_reconcile); + // Does final stage in contribution + // Sets reports and contribution info + void ContributionCompleted( + const std::string& contribution_id, + const ledger::RewardsType type, + const double amount, + const ledger::Result result); + void HasSufficientBalance( ledger::HasSufficientBalanceToReconcileCallback callback); @@ -154,11 +163,17 @@ class Contribution { void SetTimer(uint32_t* timer_id, uint64_t start_timer_in = 0); + // DEPRECATED void AddRetry( ledger::ContributionRetry step, const std::string& viewing_id, ledger::CurrentReconcileProperties reconcile = {}); + void UpdateContributionStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count); + // Resets reconcile stamps void ResetReconcileStamp(); @@ -204,14 +219,19 @@ class Contribution { const ledger::Result result, ledger::BalancePtr info); + // DEPRECATED uint64_t GetRetryTimer(ledger::ContributionRetry step, const std::string& viewing_id, ledger::CurrentReconcileProperties* reconcile); + // DEPRECATED int GetRetryPhase(ledger::ContributionRetry step); + // DEPRECATED void DoRetry(const std::string& viewing_id); + void CheckStep(const std::string& contribution_id); + void OnHasSufficientBalance( const ledger::PublisherInfoList& publisher_list, const uint32_t record, diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.cc index a905d886df3c..3206ef766c19 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.cc @@ -25,12 +25,7 @@ using challenge_bypass_ristretto::UnblindedToken; using challenge_bypass_ristretto::VerificationKey; using challenge_bypass_ristretto::VerificationSignature; -namespace braveledger_contribution { - -Unblinded::Unblinded(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { -} - -Unblinded::~Unblinded() = default; +namespace { std::string ConvertTypeToString(const ledger::RewardsType type) { switch (static_cast(type)) { @@ -52,27 +47,19 @@ std::string ConvertTypeToString(const ledger::RewardsType type) { } void GenerateSuggestionMock( - ledger::UnblindedTokenPtr token, + const ledger::UnblindedToken& token, const std::string& suggestion_encoded, base::Value* result) { - if (!token) { - return; - } - - result->SetStringKey("t", token->token_value); - result->SetStringKey("publicKey", token->public_key); - result->SetStringKey("signature", token->token_value); + result->SetStringKey("t", token.token_value); + result->SetStringKey("publicKey", token.public_key); + result->SetStringKey("signature", token.token_value); } void GenerateSuggestion( - ledger::UnblindedTokenPtr token, + const ledger::UnblindedToken& token, const std::string& suggestion_encoded, base::Value* result) { - if (!token) { - return; - } - - UnblindedToken unblinded = UnblindedToken::decode_base64(token->token_value); + UnblindedToken unblinded = UnblindedToken::decode_base64(token.token_value); VerificationKey verification_key = unblinded.derive_verification_key(); VerificationSignature signature = verification_key.sign(suggestion_encoded); const std::string pre_image = unblinded.preimage().encode_base64(); @@ -84,24 +71,20 @@ void GenerateSuggestion( } result->SetStringKey("t", pre_image); - result->SetStringKey("publicKey", token->public_key); + result->SetStringKey("publicKey", token.public_key); result->SetStringKey("signature", signature.encode_base64()); } -bool HasTokenExpired(ledger::UnblindedTokenPtr token) { - if (!token) { - return true; - } - +bool HasTokenExpired(const ledger::UnblindedToken& token) { const uint64_t now = static_cast(base::Time::Now().ToDoubleT()); - return token->expires_at > 0 && token->expires_at < now; + return token.expires_at > 0 && token.expires_at < now; } std::string GenerateTokenPayload( const std::string& publisher_key, const ledger::RewardsType type, - ledger::UnblindedTokenList list) { + const std::vector& list) { base::Value suggestion(base::Value::Type::DICTIONARY); suggestion.SetStringKey("type", ConvertTypeToString(type)); suggestion.SetStringKey("channel", publisher_key); @@ -115,9 +98,9 @@ std::string GenerateTokenPayload( for (auto & item : list) { base::Value token(base::Value::Type::DICTIONARY); if (ledger::is_testing) { - GenerateSuggestionMock(std::move(item), suggestion_encoded, &token); + GenerateSuggestionMock(item, suggestion_encoded, &token); } else { - GenerateSuggestion(std::move(item), suggestion_encoded, &token); + GenerateSuggestion(item, suggestion_encoded, &token); } credentials.GetList().push_back(std::move(token)); } @@ -131,176 +114,405 @@ std::string GenerateTokenPayload( return json; } -void Unblinded::Start(const std::string& viewing_id) { +bool GetStatisticalVotingWinner( + double dart, + const double amount, + const std::vector& list, + braveledger_contribution::Winners* winners) { + if (!winners) { + return false; + } + + double upper = 0.0; + for (auto& item : list) { + upper += item.total_amount / amount; + if (upper < dart) { + continue; + } + + auto iter = winners->find(item.publisher_key); + + uint32_t current_value = 0; + if (iter != winners->end()) { + current_value = winners->at(item.publisher_key); + winners->at(item.publisher_key) = current_value + 1; + } else { + winners->emplace(item.publisher_key, 1); + } + + return true; + } + + return false; +} + +void GetStatisticalVotingWinners( + uint32_t total_votes, + const double amount, + const ledger::ContributionPublisherList& list, + braveledger_contribution::Winners* winners) { + std::vector converted_list; + + for (auto& item : list) { + ledger::ContributionPublisher new_item; + new_item.total_amount = item->total_amount; + new_item.publisher_key = item->publisher_key; + converted_list.push_back(new_item); + } + + while (total_votes > 0) { + double dart = brave_base::random::Uniform_01(); + if (GetStatisticalVotingWinner(dart, amount, converted_list, winners)) { + --total_votes; + } + } +} + +int32_t GetRetryCount( + const ledger::ContributionStep step, + ledger::ContributionInfoPtr contribution) { + if (!contribution || step != contribution->step) { + return 0; + } + + return contribution->retry_count + 1; +} + +} // namespace + +namespace braveledger_contribution { + +Unblinded::Unblinded(bat_ledger::LedgerImpl* ledger) : ledger_(ledger) { +} + +Unblinded::~Unblinded() = default; + +void Unblinded::Initialize() { + auto callback = std::bind(&Unblinded::OnGetNotCompletedContributions, + this, + _1); + ledger_->GetIncompleteContributions(callback); +} + +void Unblinded::OnGetNotCompletedContributions( + ledger::ContributionInfoList list) { + if (list.size() == 0) { + return; + } + + if (!list[0]) { + return; + } + + DoRetry(std::move(list[0])); +} + +void Unblinded::Start(const std::string& contribution_id) { + GetContributionInfoAndUnblindedTokens( + contribution_id, + std::bind(&Unblinded::PrepareTokens, + this, + _1, + _2)); +} + +void Unblinded::GetContributionInfoAndUnblindedTokens( + const std::string& contribution_id, + GetContributionInfoAndUnblindedTokensCallback callback) { ledger_->GetAllUnblindedTokens( - std::bind(&Unblinded::OnUnblindedTokens, - this, - viewing_id, - _1)); + std::bind(&Unblinded::OnUnblindedTokens, + this, + _1, + contribution_id, + callback)); } void Unblinded::OnUnblindedTokens( - const std::string& viewing_id, - ledger::UnblindedTokenList list) { + ledger::UnblindedTokenList list, + const std::string& contribution_id, + GetContributionInfoAndUnblindedTokensCallback callback) { if (list.empty()) { - ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, viewing_id); + ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, nullptr); return; } - const auto reconcile = ledger_->GetReconcileById(viewing_id); + std::vector converted_list; + for (auto& item : list) { + ledger::UnblindedToken new_item; + new_item.id = item->id; + new_item.token_value = item->token_value; + new_item.public_key = item->public_key; + new_item.value = item->value; + new_item.promotion_id = item->promotion_id; + new_item.expires_at = item->expires_at; + + converted_list.push_back(new_item); + } + + ledger_->GetContributionInfo(contribution_id, + std::bind(&Unblinded::OnGetContributionInfo, + this, + _1, + converted_list, + callback)); +} + +void Unblinded::OnGetContributionInfo( + ledger::ContributionInfoPtr contribution, + const std::vector& list, + GetContributionInfoAndUnblindedTokensCallback callback) { + callback(std::move(contribution), list); +} + +void Unblinded::PrepareTokens( + ledger::ContributionInfoPtr contribution, + const std::vector& list) { + if (!contribution) { + return; + } + + const int32_t retry_count = GetRetryCount( + ledger::ContributionStep::STEP_START, + contribution->Clone()); + + ledger_->UpdateContributionInfoStepAndCount( + contribution->contribution_id, + ledger::ContributionStep::STEP_START, + retry_count, + [](const ledger::Result){}); + double current_amount = 0.0; - ledger::UnblindedTokenList token_list; + std::vector token_list; std::vector delete_list; for (auto & item : list) { - if (HasTokenExpired(item->Clone())) { - delete_list.push_back(std::to_string(item->id)); + if (HasTokenExpired(item)) { + delete_list.push_back(std::to_string(item.id)); continue; } - if (current_amount >= reconcile.fee) { + if (current_amount >= contribution->amount) { break; } - current_amount += item->value; - token_list.push_back(std::move(item)); + current_amount += item.value; + token_list.push_back(item); } if (delete_list.size() > 0) { ledger_->DeleteUnblindedTokens(delete_list, [](const ledger::Result _){}); } - if (current_amount < reconcile.fee) { - ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, viewing_id); + if (current_amount < contribution->amount) { + ContributionCompleted( + ledger::Result::NOT_ENOUGH_FUNDS, + std::move(contribution)); return; } - MakeContribution(viewing_id, std::move(token_list)); + PreparePublishers(token_list, std::move(contribution)); } -void Unblinded::MakeContribution( - const std::string& viewing_id, - ledger::UnblindedTokenList list) { - const auto reconcile = ledger_->GetReconcileById(viewing_id); - - if (reconcile.type == ledger::RewardsType::ONE_TIME_TIP || - reconcile.type == ledger::RewardsType::RECURRING_TIP) { - const auto callback = std::bind(&Unblinded::ContributionCompleted, - this, - _1, - viewing_id); - SendTokens( - reconcile.directions.front().publisher_key, - reconcile.type, - std::move(list), - callback); +void Unblinded::PreparePublishers( + const std::vector& list, + ledger::ContributionInfoPtr contribution) { + if (!contribution) { return; } - if (reconcile.type == ledger::RewardsType::AUTO_CONTRIBUTE) { - PrepareAutoContribution(viewing_id, std::move(list)); + if (contribution->type == ledger::RewardsType::AUTO_CONTRIBUTE) { + auto publisher_list = + PrepareAutoContribution(list, contribution->Clone()); + + if (publisher_list.empty()) { + ContributionCompleted( + ledger::Result::AC_TABLE_EMPTY, + std::move(contribution)); + return; + } + + contribution->publishers = std::move(publisher_list); + + ledger_->SaveContributionInfo( + contribution->Clone(), + std::bind(&Unblinded::OnPrepareAutoContribution, + this, + _1, + contribution->contribution_id)); + return; } + + ProcessTokens(contribution->contribution_id); } -bool Unblinded::GetStatisticalVotingWinner( - double dart, - const ledger::ReconcileDirections& directions, - Winners* winners) const { - if (!winners) { - return false; +ledger::ContributionPublisherList Unblinded::PrepareAutoContribution( + const std::vector& list, + ledger::ContributionInfoPtr contribution) { + if (!contribution || list.size() == 0) { + return {}; } - double upper = 0.0; - for (const auto& item : directions) { - upper += item.amount_percent / 100.0; - if (upper < dart) { + const double total_votes = static_cast(list.size()); + Winners winners; + GetStatisticalVotingWinners( + total_votes, + contribution->amount, + std::move(contribution->publishers), + &winners); + + ledger::ContributionPublisherList publisher_list; + for (auto & winner : winners) { + if (winner.second == 0) { continue; } - auto iter = winners->find(item.publisher_key); + const std::string publisher_key = winner.first; + auto publisher = ledger::ContributionPublisher::New(); + publisher->contribution_id = contribution->contribution_id; + publisher->publisher_key = publisher_key; + publisher->total_amount = + (winner.second / total_votes) * contribution->amount; + publisher->contributed_amount = 0; + publisher_list.push_back(std::move(publisher)); + } - uint32_t current_value = 0; - if (iter != winners->end()) { - current_value = winners->at(item.publisher_key); - winners->at(item.publisher_key) = current_value + 1; - } else { - winners->emplace(item.publisher_key, 1); - } + return publisher_list; +} - return true; +void Unblinded::OnPrepareAutoContribution( + const ledger::Result result, + const std::string& contribution_id) { + if (result != ledger::Result::LEDGER_OK) { + SetTimer(contribution_id); + return; } - return false; + ProcessTokens(contribution_id); } -void Unblinded::GetStatisticalVotingWinners( - uint32_t total_votes, - const ledger::ReconcileDirections& directions, - Winners* winners) const { - while (total_votes > 0) { - double dart = brave_base::random::Uniform_01(); - if (GetStatisticalVotingWinner(dart, directions, winners)) { - --total_votes; - } - } +void Unblinded::ProcessTokens(const std::string& contribution_id) { + GetContributionInfoAndUnblindedTokens( + contribution_id, + std::bind(&Unblinded::OnProcessTokens, + this, + _1, + _2)); } -void Unblinded::PrepareAutoContribution( - const std::string& viewing_id, - ledger::UnblindedTokenList list) { - if (list.size() == 0) { - ContributionCompleted(ledger::Result::AC_TABLE_EMPTY, viewing_id); +void Unblinded::OnProcessTokens( + ledger::ContributionInfoPtr contribution, + const std::vector& list) { + if (!contribution) { return; } - auto reconcile = ledger_->GetReconcileById(viewing_id); - const double total_votes = static_cast(list.size()); - Winners winners; - GetStatisticalVotingWinners(total_votes, reconcile.directions, &winners); + const int32_t retry_count = GetRetryCount( + ledger::ContributionStep::STEP_SUGGESTIONS, + contribution->Clone()); - ledger::ReconcileDirections new_directions; - uint32_t current_position = 0; - for (auto & winner : winners) { - if (winner.second == 0) { + ledger_->UpdateContributionInfoStepAndCount( + contribution->contribution_id, + ledger::ContributionStep::STEP_SUGGESTIONS, + retry_count, + [](const ledger::Result){}); + + for (auto& publisher : contribution->publishers) { + if (publisher->total_amount == publisher->contributed_amount) { continue; } - ledger::ReconcileDirectionProperties direction; - direction.publisher_key = winner.first; - direction.amount_percent = (winner.second / total_votes) * 100; - new_directions.push_back(direction); + std::vector token_list; + double current_amount = 0.0; + for (auto& item : list) { + if (current_amount >= publisher->total_amount) { + break; + } - const uint32_t new_position = current_position + winner.second; - ledger::UnblindedTokenList new_list; - for (size_t i = current_position; i < new_position; i++) { - new_list.push_back(std::move(list[i])); + current_amount += item.value; + token_list.push_back(item); } - current_position = new_position; + + auto callback = std::bind(&Unblinded::TokenProcessed, + this, + _1, + contribution->contribution_id, + publisher->publisher_key); SendTokens( - winner.first, - ledger::RewardsType::AUTO_CONTRIBUTE, - std::move(new_list), - [](const ledger::Result _){}); + publisher->publisher_key, + contribution->type, + token_list, + callback); + return; + } + + ContributionCompleted(ledger::Result::LEDGER_OK, std::move(contribution)); +} + +void Unblinded::TokenProcessed( + const ledger::Result result, + const std::string& contribution_id, + const std::string& publisher_key) { + if (result == ledger::Result::LEDGER_OK) { + auto callback = std::bind(&Unblinded::OnTokenProcessed, + this, + _1, + contribution_id); + + ledger_->UpdateContributionInfoContributedAmount( + contribution_id, + publisher_key, + callback); + return; + } + + SetTimer(contribution_id); +} + +void Unblinded::OnTokenProcessed( + const ledger::Result result, + const std::string& contribution_id) { + ledger_->GetContributionInfo( + contribution_id, + std::bind(&Unblinded::CheckIfCompleted, + this, + _1)); +} + +void Unblinded::CheckIfCompleted(ledger::ContributionInfoPtr contribution) { + if (!contribution) { + return; + } + + bool completed = true; + for (auto& publisher : contribution->publishers) { + if (publisher->total_amount == publisher->contributed_amount) { + continue; + } + + completed = false; + break; } - reconcile.directions = new_directions; - ledger_->UpdateReconcile(reconcile); + if (completed) { + ContributionCompleted(ledger::Result::LEDGER_OK, std::move(contribution)); + return; + } - ContributionCompleted(ledger::Result::LEDGER_OK, viewing_id); + SetTimer(contribution->contribution_id); } void Unblinded::SendTokens( const std::string& publisher_key, const ledger::RewardsType type, - ledger::UnblindedTokenList list, - SendTokensCallback callback) { + const std::vector& list, + ledger::ResultCallback callback) { if (publisher_key.empty() || list.empty()) { return callback(ledger::Result::LEDGER_ERROR); } std::vector token_id_list; for (auto & item : list) { - token_id_list.push_back(std::to_string(item->id)); + token_id_list.push_back(std::to_string(item.id)); } auto url_callback = std::bind(&Unblinded::OnSendTokens, @@ -314,7 +526,7 @@ void Unblinded::SendTokens( const std::string payload = GenerateTokenPayload( publisher_key, type, - std::move(list)); + list); const std::string url = braveledger_request_util::GetReedemSuggestionsUrl(); @@ -333,7 +545,7 @@ void Unblinded::OnSendTokens( const std::string& response, const std::map& headers, const std::vector& token_id_list, - SendTokensCallback callback) { + ledger::ResultCallback callback) { ledger_->LogResponse(__func__, response_status_code, response, headers); if (response_status_code != net::HTTP_OK) { callback(ledger::Result::LEDGER_ERROR); @@ -346,13 +558,76 @@ void Unblinded::OnSendTokens( void Unblinded::ContributionCompleted( const ledger::Result result, - const std::string& viewing_id) { - const auto reconcile = ledger_->GetReconcileById(viewing_id); - ledger_->ReconcileComplete( + ledger::ContributionInfoPtr contribution) { + if (!contribution) { + return; + } + + ledger_->ContributionCompleted( result, - reconcile.fee, - viewing_id, - reconcile.type); + contribution->amount, + contribution->contribution_id, + contribution->type); +} + +void Unblinded::SetTimer( + const std::string& contribution_id, + const uint64_t& start_timer_in) { + if (contribution_id.empty()) { + return; + } + + if (!retry_timers_[contribution_id]) { + retry_timers_[contribution_id] = 0u; + } + + uint64_t timer_seconds = start_timer_in; + if (ledger::short_retries) { + timer_seconds = 1; + } else if (start_timer_in == 0) { + timer_seconds = brave_base::random::Geometric(45); + } + + BLOG(ledger_, ledger::LogLevel::LOG_INFO) + << "Timer will start in " + << timer_seconds; + + ledger_->SetTimer(timer_seconds, &retry_timers_[contribution_id]); +} + +void Unblinded::OnTimer(uint32_t timer_id) { + for (std::pair const& value : retry_timers_) { + if (value.second == timer_id) { + std::string contribution_id = value.first; + CheckStep(contribution_id); + retry_timers_[contribution_id] = 0u; + } + } +} + +void Unblinded::CheckStep(const std::string& contribution_id) { + auto callback = std::bind(&Unblinded::DoRetry, + this, + _1); + ledger_->GetContributionInfo(contribution_id, callback); +} + +void Unblinded::DoRetry(ledger::ContributionInfoPtr contribution) { + if (!contribution) { + return; + } + + if (contribution->step == ledger::ContributionStep::STEP_START) { + Start(contribution->contribution_id); + return; + } + + if (contribution->step == ledger::ContributionStep::STEP_SUGGESTIONS) { + ProcessTokens(contribution->contribution_id); + return; + } + + NOTREACHED(); } } // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h index 793e25f6f3b0..0b8711ddc158 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded.h @@ -21,8 +21,9 @@ class LedgerImpl; namespace braveledger_contribution { -using SendTokensCallback = - std::function; +using GetContributionInfoAndUnblindedTokensCallback = std::function& list)>; using Winners = std::map; @@ -31,49 +32,90 @@ class Unblinded { explicit Unblinded(bat_ledger::LedgerImpl* ledger); ~Unblinded(); - void Start(const std::string& viewing_id); + void Initialize(); + + void Start(const std::string& contribution_id); + + void OnTimer(uint32_t timer_id); private: + void OnGetNotCompletedContributions( + ledger::ContributionInfoList list); + + void GetContributionInfoAndUnblindedTokens( + const std::string& contribution_id, + GetContributionInfoAndUnblindedTokensCallback callback); + void OnUnblindedTokens( - const std::string& viewing_id, - ledger::UnblindedTokenList list); + ledger::UnblindedTokenList list, + const std::string& contribution_id, + GetContributionInfoAndUnblindedTokensCallback callback); + + void OnGetContributionInfo( + ledger::ContributionInfoPtr contribution, + const std::vector& list, + GetContributionInfoAndUnblindedTokensCallback callback); + + void PrepareTokens( + ledger::ContributionInfoPtr contribution, + const std::vector& list); + + void PreparePublishers( + const std::vector& list, + ledger::ContributionInfoPtr contribution); + + ledger::ContributionPublisherList PrepareAutoContribution( + const std::vector& list, + ledger::ContributionInfoPtr contribution); - void MakeContribution( - const std::string& viewing_id, - ledger::UnblindedTokenList list); + void OnPrepareAutoContribution( + const ledger::Result result, + const std::string& contribution_id); + + void ProcessTokens(const std::string& contribution_id); - bool GetStatisticalVotingWinner( - double dart, - const ledger::ReconcileDirections& directions, - Winners* winners) const; + void OnProcessTokens( + ledger::ContributionInfoPtr contribution, + const std::vector& list); - void PrepareAutoContribution( - const std::string& viewing_id, - ledger::UnblindedTokenList list); + void TokenProcessed( + const ledger::Result result, + const std::string& contribution_id, + const std::string& publisher_key); + + void OnTokenProcessed( + const ledger::Result result, + const std::string& contribution_id); - void GetStatisticalVotingWinners( - uint32_t total_votes, - const ledger::ReconcileDirections& directions, - Winners* winners) const; + void CheckIfCompleted(ledger::ContributionInfoPtr contribution); void SendTokens( const std::string& publisher_key, const ledger::RewardsType type, - ledger::UnblindedTokenList list, - SendTokensCallback callback); + const std::vector& list, + ledger::ResultCallback callback); void OnSendTokens( const int response_status_code, const std::string& response, const std::map& headers, const std::vector& token_id_list, - SendTokensCallback callback); + ledger::ResultCallback callback); void ContributionCompleted( const ledger::Result result, - const std::string& viewing_id); + ledger::ContributionInfoPtr contribution); + + void SetTimer( + const std::string& contribution_id, + const uint64_t& start_timer_in = 0); + + void CheckStep(const std::string& contribution_id); + + void DoRetry(ledger::ContributionInfoPtr contribution); bat_ledger::LedgerImpl* ledger_; // NOT OWNED + std::map retry_timers_; }; } // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc index 8a3be3208f8d..9c04c0bc28a8 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/contribution/contribution_unblinded_unittest.cc @@ -16,6 +16,10 @@ using ::testing::_; using ::testing::Invoke; +namespace { + const char contribution_id[] = "60770beb-3cfb-4550-a5db-deccafb5c790"; +} // namespace + namespace braveledger_contribution { class UnblindedTest : public ::testing::Test { @@ -35,20 +39,26 @@ class UnblindedTest : public ::testing::Test { } void SetUp() override { - ON_CALL(*mock_ledger_impl_, GetReconcileById(_)) - .WillByDefault( - Invoke([](const std::string& viewing_id) { - ledger::CurrentReconcileProperties reconcile; - reconcile.fee = 5.0; - return reconcile; - })); + ON_CALL(*mock_ledger_impl_, GetContributionInfo(contribution_id, _)) + .WillByDefault( + Invoke([]( + const std::string& id, + ledger::GetContributionInfoCallback callback) { + auto info = ledger::ContributionInfo::New(); + info->contribution_id = contribution_id; + info->amount = 5.0; + info->type = ledger::RewardsType::ONE_TIME_TIP; + info->step = ledger::ContributionStep::STEP_NO; + info->retry_count = -1; + + callback(std::move(info)); + })); } }; TEST_F(UnblindedTest, NotEnoughFunds) { - const std::string viewing_id = "some_id"; EXPECT_CALL(*mock_ledger_impl_, - ReconcileComplete(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _, _)); + ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _)); std::vector delete_list; delete_list.push_back("1"); @@ -59,24 +69,22 @@ TEST_F(UnblindedTest, NotEnoughFunds) { Invoke([](ledger::GetAllUnblindedTokensCallback callback) { ledger::UnblindedTokenList list; - auto info = ledger::UnblindedToken::New(); - info->id = 1; - info->token_value = "asdfasdfasdfsad="; - info->value = 2; - info->expires_at = 1574133178; - list.push_back(info->Clone()); + auto info = ledger::UnblindedToken::New(); + info->id = 1; + info->token_value = "asdfasdfasdfsad="; + info->value = 2; + info->expires_at = 1574133178; + list.push_back(info->Clone()); callback(std::move(list)); })); - unblinded_->Start(viewing_id); + unblinded_->Start(contribution_id); } TEST_F(UnblindedTest, PromotionExpiredDeleteToken) { - const std::string viewing_id = "some_id"; EXPECT_CALL(*mock_ledger_impl_, - ReconcileComplete(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _, _)) - .Times(0); + ContributionCompleted(ledger::Result::LEDGER_OK, _, _, _)); std::vector delete_list; delete_list.push_back("1"); @@ -101,13 +109,12 @@ TEST_F(UnblindedTest, PromotionExpiredDeleteToken) { callback(std::move(list)); })); - unblinded_->Start(viewing_id); + unblinded_->Start(contribution_id); } TEST_F(UnblindedTest, PromotionExpiredDeleteTokensNotEnoughFunds) { - const std::string viewing_id = "some_id"; EXPECT_CALL(*mock_ledger_impl_, - ReconcileComplete(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _, _)); + ContributionCompleted(ledger::Result::NOT_ENOUGH_FUNDS, _, _, _)); std::vector delete_list; delete_list.push_back("1"); @@ -132,7 +139,7 @@ TEST_F(UnblindedTest, PromotionExpiredDeleteTokensNotEnoughFunds) { callback(std::move(list)); })); - unblinded_->Start(viewing_id); + unblinded_->Start(contribution_id); } } // namespace braveledger_contribution diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h index ce5891d95241..dcc9267a7cb0 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_client_mock.h @@ -382,6 +382,26 @@ class MockLedgerClient : public LedgerClient { const ledger::ActivityMonth month, const int year, ledger::GetContributionReportCallback callback)); + + MOCK_METHOD1(GetIncompleteContributions, void( + ledger::GetIncompleteContributionsCallback callback)); + + MOCK_METHOD2(GetContributionInfo, void( + const std::string& contribution_id, + GetContributionInfoCallback callback)); + + MOCK_METHOD4(UpdateContributionInfoStepAndCount, void( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ResultCallback callback)); + + MOCK_METHOD3(UpdateContributionInfoContributedAmount, void( + const std::string& contribution_id, + const std::string& publisher_key, + ResultCallback callback)); + + MOCK_METHOD0(ReconcileStampReset, void()); }; } // namespace ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc index a9af03171832..e65f28c1e851 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.cc @@ -661,6 +661,26 @@ void LedgerImpl::ReconcileComplete( type); } +void LedgerImpl::ContributionCompleted( + const ledger::Result result, + const double amount, + const std::string& contribution_id, + const ledger::RewardsType type) { + bat_contribution_->ContributionCompleted( + contribution_id, + type, + amount, + result); + + // TODO(https://github.com/brave/brave-browser/issues/7717) + // rename to ContributionCompleted + ledger_client_->OnReconcileComplete( + result, + contribution_id, + amount, + type); +} + void LedgerImpl::OnWalletProperties( ledger::Result result, const ledger::WalletProperties& properties) { @@ -909,6 +929,7 @@ void LedgerImpl::UpdateAdsRewards() { void LedgerImpl::ResetReconcileStamp() { bat_state_->ResetReconcileStamp(); + ledger_client_->ReconcileStampReset(); } bool LedgerImpl::UpdateReconcile( @@ -1606,4 +1627,37 @@ void LedgerImpl::GetContributionReport( ledger_client_->GetContributionReport(month, year, callback); } +void LedgerImpl::GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback) { + ledger_client_->GetIncompleteContributions(callback); +} + +void LedgerImpl::GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback) { + ledger_client_->GetContributionInfo(contribution_id, callback); +} + +void LedgerImpl::UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback) { + ledger_client_->UpdateContributionInfoStepAndCount( + contribution_id, + step, + retry_count, + callback); +} + +void LedgerImpl::UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback) { + ledger_client_->UpdateContributionInfoContributedAmount( + contribution_id, + publisher_key, + callback); +} + } // namespace bat_ledger diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h index 761edad919e3..ce871272a69b 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl.h @@ -215,13 +215,20 @@ class LedgerImpl : public ledger::Ledger, const ledger::UrlMethod method, ledger::LoadURLCallback callback); - virtual void ReconcileComplete( + // DEPRECATED + void ReconcileComplete( const ledger::Result result, const double amount, const std::string& viewing_id, const ledger::RewardsType type, const bool delete_reconcile = true); + virtual void ContributionCompleted( + const ledger::Result result, + const double amount, + const std::string& contribution_id, + const ledger::RewardsType type); + std::string URIEncode(const std::string& value) override; void SaveMediaVisit(const std::string& publisher_id, @@ -271,7 +278,7 @@ class LedgerImpl : public ledger::Ledger, const ledger::ReportType type, const double amount); - virtual ledger::CurrentReconcileProperties GetReconcileById( + ledger::CurrentReconcileProperties GetReconcileById( const std::string& viewingId); void RemoveReconcileById(const std::string& viewingId); @@ -609,6 +616,24 @@ class LedgerImpl : public ledger::Ledger, const int year, ledger::GetContributionReportCallback callback) override; + void GetIncompleteContributions( + ledger::GetIncompleteContributionsCallback callback); + + virtual void GetContributionInfo( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback); + + void UpdateContributionInfoStepAndCount( + const std::string& contribution_id, + const ledger::ContributionStep step, + const int32_t retry_count, + ledger::ResultCallback callback); + + void UpdateContributionInfoContributedAmount( + const std::string& contribution_id, + const std::string& publisher_key, + ledger::ResultCallback callback); + private: void InitializeConfirmations( ledger::InitializeCallback callback); diff --git a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h index 32c474344ac3..603e9e1f52d1 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h +++ b/vendor/bat-native-ledger/src/bat/ledger/internal/ledger_impl_mock.h @@ -194,6 +194,12 @@ class MockLedgerImpl : public LedgerImpl { const ledger::RewardsType, const bool)); + MOCK_METHOD4(ContributionCompleted, void( + const ledger::Result, + const double, + const std::string&, + const ledger::RewardsType)); + MOCK_METHOD1(URIEncode, std::string(const std::string&)); MOCK_METHOD5(SaveMediaVisit, @@ -566,6 +572,10 @@ class MockLedgerImpl : public LedgerImpl { MOCK_METHOD2(DeleteUnblindedTokensForPromotion, void(const std::string& promotion_id, ledger::ResultCallback)); + + MOCK_METHOD2(GetContributionInfo, void( + const std::string& contribution_id, + ledger::GetContributionInfoCallback callback)); }; } // namespace bat_ledger diff --git a/vendor/brave-ios/Ledger/BATBraveLedger.mm b/vendor/brave-ios/Ledger/BATBraveLedger.mm index 40d052c30a72..85e75442fb5b 100644 --- a/vendor/brave-ios/Ledger/BATBraveLedger.mm +++ b/vendor/brave-ios/Ledger/BATBraveLedger.mm @@ -2011,4 +2011,29 @@ - (void)getContributionReport:(const ledger::ActivityMonth)month year:(const uin // TODO please implement } +- (void)getIncompleteContributions:(ledger::GetIncompleteContributionsCallback)callback +{ + // TODO please implement +} + +- (void)getContributionInfo:(const std::string&)contribution_id callback:(ledger::GetContributionInfoCallback)callback +{ + // TODO please implement +} + +- (void)updateContributionInfoStepAndCount:(const std::string&)contribution_id step:(const ledger::ContributionStep)step retry_count:(const int32_t)retry_count callback:(ledger::ResultCallback)callback +{ + // TODO please implement +} + +- (void)updateContributionInfoContributedAmount:(const std::string&)contribution_id publisher_key:(const std::string&)publisher_key callback:(ledger::ResultCallback)callback +{ + // TODO please implement +} + +- (void)reconcileStampReset +{ + // TODO please implement +} + @end diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h index a7a1d0fbccde..dd6aaef81ee3 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.h @@ -99,4 +99,9 @@ class NativeLedgerClient : public ledger::LedgerClient { void UnblindedTokensReady() override; void GetTransactionReport(const ledger::ActivityMonth month, const int year, ledger::GetTransactionReportCallback callback) override; void GetContributionReport(const ledger::ActivityMonth month, const int year, ledger::GetContributionReportCallback callback) override; + void GetIncompleteContributions(ledger::GetIncompleteContributionsCallback callback) override; + void GetContributionInfo(const std::string& contribution_id, ledger::GetContributionInfoCallback callback) override; + void UpdateContributionInfoStepAndCount(const std::string& contribution_id, const ledger::ContributionStep step, const int32_t retry_count, ledger::ResultCallback callback) override; + void UpdateContributionInfoContributedAmount(const std::string& contribution_id, const std::string& publisher_key, ledger::ResultCallback callback) override; + void ReconcileStampReset() override; }; diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm index 77fdc7aa466f..dbd439e4bb3a 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClient.mm @@ -264,3 +264,18 @@ void NativeLedgerClient::GetContributionReport(const ledger::ActivityMonth month, const int year, ledger::GetContributionReportCallback callback) { [bridge_ getContributionReport:month year:year callback:callback]; } +void NativeLedgerClient::GetIncompleteContributions(ledger::GetIncompleteContributionsCallback callback) { + [bridge_ getIncompleteContributions:callback]; +} +void NativeLedgerClient::GetContributionInfo(const std::string& contribution_id, ledger::GetContributionInfoCallback callback) { + [bridge_ getContributionInfo:contribution_id callback:callback]; +} +void NativeLedgerClient::UpdateContributionInfoStepAndCount(const std::string& contribution_id, const ledger::ContributionStep step, const int32_t retry_count, ledger::ResultCallback callback) { + [bridge_ updateContributionInfoStepAndCount:contribution_id step:step retry_count:retry_count callback:callback]; +} +void NativeLedgerClient::UpdateContributionInfoContributedAmount(const std::string& contribution_id, const std::string& publisher_key, ledger::ResultCallback callback) { + [bridge_ updateContributionInfoContributedAmount:contribution_id publisher_key:publisher_key callback:callback]; +} +void NativeLedgerClient::ReconcileStampReset() { + [bridge_ reconcileStampReset]; +} diff --git a/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h b/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h index 5592e6f9abbb..5564e195dc15 100644 --- a/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h +++ b/vendor/brave-ios/Ledger/Generated/NativeLedgerClientBridge.h @@ -92,5 +92,10 @@ - (void)deleteUnblindedTokensForPromotion:(const std::string&)promotion_id callback:(ledger::ResultCallback)callback; - (void)getTransactionReport:(const ledger::ActivityMonth)month year:(const uint32_t)year callback:(ledger::GetTransactionReportCallback)callback; - (void)getContributionReport:(const ledger::ActivityMonth)month year:(const uint32_t)year callback:(ledger::GetContributionReportCallback)callback; +- (void)getIncompleteContributions:(ledger::GetIncompleteContributionsCallback)callback; +- (void)getContributionInfo:(const std::string&)contribution_id callback:(ledger::GetContributionInfoCallback)callback; +- (void)updateContributionInfoStepAndCount:(const std::string&)contribution_id step:(const ledger::ContributionStep)step retry_count:(const int32_t)retry_count callback:(ledger::ResultCallback)callback; +- (void)updateContributionInfoContributedAmount:(const std::string&)contribution_id publisher_key:(const std::string&)publisher_key callback:(ledger::ResultCallback)callback; +- (void)reconcileStampReset; @end