From 72c4a8399e0c0f7a76bde4812496fd38a6b35755 Mon Sep 17 00:00:00 2001 From: Nejc Zdovc Date: Wed, 16 Jan 2019 07:00:44 +0100 Subject: [PATCH 1/2] Merge pull request #921 from brave/publisher-refactor Refactors database --- browser/ui/webui/brave_rewards_ui.cc | 8 +- .../browser/publisher_info_database.cc | 875 +++++++++++------- .../browser/publisher_info_database.h | 71 +- .../publisher_info_database_unittest.cc | 408 ++++++++ .../rewards_notification_service_impl.cc | 2 +- .../brave_rewards/browser/rewards_service.h | 6 +- .../browser/rewards_service_impl.cc | 242 +++-- .../browser/rewards_service_impl.h | 44 +- .../reducers/rewards_panel_reducer.ts | 21 +- .../brave_rewards/components/panel.tsx | 3 +- .../ui/reducers/publishers_reducer.ts | 20 +- components/definitions/rewardsExtensions.d.ts | 17 +- .../bat_ledger_client_mojo_proxy.cc | 135 ++- .../bat_ledger/bat_ledger_client_mojo_proxy.h | 26 +- .../services/bat_ledger/bat_ledger_impl.cc | 35 +- .../services/bat_ledger/bat_ledger_impl.h | 8 - .../public/cpp/ledger_client_mojo_proxy.cc | 146 ++- .../public/cpp/ledger_client_mojo_proxy.h | 47 +- .../public/interfaces/bat_ledger.mojom | 19 +- .../reducers/rewards_panel_reducer_test.ts | 69 +- test/BUILD.gn | 1 + .../include/bat/ledger/ledger.h | 34 +- .../include/bat/ledger/ledger_client.h | 19 +- .../include/bat/ledger/pending_contribution.h | 2 +- .../include/bat/ledger/publisher_info.h | 25 +- .../src/bat/ledger/ledger.cc | 50 +- .../bat-native-ledger/src/bat_contribution.cc | 210 +++-- .../bat-native-ledger/src/bat_contribution.h | 8 +- vendor/bat-native-ledger/src/bat_get_media.cc | 17 +- vendor/bat-native-ledger/src/bat_helper.cc | 5 +- .../bat-native-ledger/src/bat_publishers.cc | 324 +++---- vendor/bat-native-ledger/src/bat_publishers.h | 37 +- vendor/bat-native-ledger/src/ledger_impl.cc | 101 +- vendor/bat-native-ledger/src/ledger_impl.h | 43 +- .../src/rapidjson_bat_helper.h | 4 +- 35 files changed, 2066 insertions(+), 1016 deletions(-) create mode 100644 components/brave_rewards/browser/publisher_info_database_unittest.cc diff --git a/browser/ui/webui/brave_rewards_ui.cc b/browser/ui/webui/brave_rewards_ui.cc index d04cda9028e8..65dd60781735 100644 --- a/browser/ui/webui/brave_rewards_ui.cc +++ b/browser/ui/webui/brave_rewards_ui.cc @@ -65,7 +65,7 @@ class RewardsDOMHandler : public WebUIMessageHandler, void GetReconcileStamp(const base::ListValue* args); void GetAddresses(const base::ListValue* args); void SaveSetting(const base::ListValue* args); - void OnGetCurrentContributeList( + void OnContentSiteList( std::unique_ptr, uint32_t record); void OnGetAllBalanceReports( @@ -543,10 +543,10 @@ void RewardsDOMHandler::GetAddresses(const base::ListValue* args) { void RewardsDOMHandler::OnAutoContributePropsReady( std::unique_ptr props) { - rewards_service_->GetCurrentContributeList(0, 0, + rewards_service_->GetContentSiteList(0, 0, props->contribution_min_time, props->reconcile_stamp, props->contribution_non_verified, - base::Bind(&RewardsDOMHandler::OnGetCurrentContributeList, + base::Bind(&RewardsDOMHandler::OnContentSiteList, weak_factory_.GetWeakPtr())); } @@ -659,7 +659,7 @@ void RewardsDOMHandler::RestorePublishers(const base::ListValue *args) { } } -void RewardsDOMHandler::OnGetCurrentContributeList( +void RewardsDOMHandler::OnContentSiteList( std::unique_ptr list, uint32_t record) { if (web_ui()->CanCallJavascript()) { diff --git a/components/brave_rewards/browser/publisher_info_database.cc b/components/brave_rewards/browser/publisher_info_database.cc index 385251f2a6a3..7530d511bc36 100644 --- a/components/brave_rewards/browser/publisher_info_database.cc +++ b/components/brave_rewards/browser/publisher_info_database.cc @@ -17,12 +17,13 @@ #include "sql/statement.h" #include "sql/transaction.h" #include "content_site.h" +#include "recurring_donation.h" namespace brave_rewards { namespace { -const int kCurrentVersionNumber = 3; +const int kCurrentVersionNumber = 4; const int kCompatibleVersionNumber = 1; } // namespace @@ -39,26 +40,32 @@ PublisherInfoDatabase::~PublisherInfoDatabase() { bool PublisherInfoDatabase::Init() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (initialized_) + if (initialized_) { return true; + } - if (!db_.Open(db_path_)) + if (!db_.Open(db_path_)) { return false; + } // TODO - add error delegate sql::Transaction committer(&db_); - if (!committer.Begin()) + if (!committer.Begin()) { return false; + } - if (!meta_table_.Init(&db_, GetCurrentVersion(), kCompatibleVersionNumber)) + if (!meta_table_.Init(&db_, GetCurrentVersion(), kCompatibleVersionNumber)) { return false; + } + if (!CreatePublisherInfoTable() || !CreateContributionInfoTable() || !CreateActivityInfoTable() || !CreateMediaPublisherInfoTable() || !CreateRecurringDonationTable() || - !CreatePendingContributionsTable()) + !CreatePendingContributionsTable()) { return false; + } CreateContributionInfoIndex(); CreateActivityInfoIndex(); @@ -67,11 +74,13 @@ bool PublisherInfoDatabase::Init() { // Version check. sql::InitStatus version_status = EnsureCurrentVersion(); - if (version_status != sql::INIT_OK) + if (version_status != sql::INIT_OK) { return version_status; + } - if (!committer.Commit()) + if (!committer.Commit()) { return false; + } memory_pressure_listener_.reset(new base::MemoryPressureListener( base::Bind(&PublisherInfoDatabase::OnMemoryPressure, @@ -81,15 +90,20 @@ bool PublisherInfoDatabase::Init() { return initialized_; } +/** + * + * CONTRIBUTION INFO + * + */ + bool PublisherInfoDatabase::CreateContributionInfoTable() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); const char* name = "contribution_info"; - if (GetDB().DoesTableExist(name)) + if (GetDB().DoesTableExist(name)) { return true; + } - // Note: revise implementation for InsertOrUpdatePublisherInfo() if you add - // any new constraints to the schema. std::string sql; sql.append("CREATE TABLE "); sql.append(name); @@ -105,6 +119,7 @@ bool PublisherInfoDatabase::CreateContributionInfoTable() { " FOREIGN KEY (publisher_id)" " REFERENCES publisher_info (publisher_id)" " ON DELETE CASCADE)"); + return GetDB().Execute(sql.c_str()); } @@ -116,118 +131,103 @@ bool PublisherInfoDatabase::CreateContributionInfoIndex() { "ON contribution_info (publisher_id)"); } -bool PublisherInfoDatabase::CreatePublisherInfoTable() { +bool PublisherInfoDatabase::InsertContributionInfo( + const brave_rewards::ContributionInfo& info) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - const char* name = "publisher_info"; - if (GetDB().DoesTableExist(name)) - return true; + bool initialized = Init(); + DCHECK(initialized); - // Update InsertOrUpdatePublisherInfo() if you add anything here - std::string sql; - sql.append("CREATE TABLE "); - sql.append(name); - sql.append( - "(" - "publisher_id LONGVARCHAR PRIMARY KEY NOT NULL UNIQUE," - "verified BOOLEAN DEFAULT 0 NOT NULL," - "excluded INTEGER DEFAULT 0 NOT NULL," - "name TEXT NOT NULL," - "favIcon TEXT NOT NULL," - "url TEXT NOT NULL," - "provider TEXT NOT NULL)"); - return GetDB().Execute(sql.c_str()); -} + if (!initialized) { + return false; + } -bool PublisherInfoDatabase::CreateActivityInfoTable() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE, + "INSERT INTO contribution_info " + "(publisher_id, probi, date, " + "category, month, year) " + "VALUES (?, ?, ?, ?, ?, ?)")); - const char* name = "activity_info"; - if (GetDB().DoesTableExist(name)) - return true; + statement.BindString(0, info.publisher_key); + statement.BindString(1, info.probi); + statement.BindInt64(2, info.date); + statement.BindInt(3, info.category); + statement.BindInt(4, info.month); + statement.BindInt(5, info.year); - // Update InsertOrUpdatePublisherInfo() if you add anything here - std::string sql; - sql.append("CREATE TABLE "); - sql.append(name); - sql.append( - "(" - "publisher_id LONGVARCHAR NOT NULL," - "duration INTEGER DEFAULT 0 NOT NULL," - "score DOUBLE DEFAULT 0 NOT NULL," - "percent INTEGER DEFAULT 0 NOT NULL," - "weight DOUBLE DEFAULT 0 NOT NULL," - "category INTEGER NOT NULL," - "month INTEGER NOT NULL," - "year INTEGER NOT NULL," - "reconcile_stamp INTEGER DEFAULT 0 NOT NULL," - "CONSTRAINT fk_activity_info_publisher_id" - " FOREIGN KEY (publisher_id)" - " REFERENCES publisher_info (publisher_id)" - " ON DELETE CASCADE)"); - return GetDB().Execute(sql.c_str()); + return statement.Run(); } -bool PublisherInfoDatabase::CreateActivityInfoIndex() { +void PublisherInfoDatabase::GetTips(ledger::PublisherInfoList* list, + ledger::ACTIVITY_MONTH month, + int year) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return GetDB().Execute( - "CREATE INDEX IF NOT EXISTS activity_info_publisher_id_index " - "ON activity_info (publisher_id)"); -} + bool initialized = Init(); + DCHECK(initialized); -bool PublisherInfoDatabase::CreateMediaPublisherInfoTable() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + if (!initialized) { + return; + } - const char* name = "media_publisher_info"; - if (GetDB().DoesTableExist(name)) - return true; + sql::Statement info_sql(db_.GetUniqueStatement( + "SELECT pi.publisher_id, pi.name, pi.url, pi.favIcon, " + "ci.probi, ci.date, pi.verified, pi.provider " + "FROM contribution_info as ci " + "INNER JOIN publisher_info AS pi ON ci.publisher_id = pi.publisher_id " + "AND ci.month = ? AND ci.year = ? " + "AND (ci.category = ? OR ci.category = ?)")); - // Update InsertOrUpdateMediaPublisherInfo() if you add anything here - std::string sql; - sql.append("CREATE TABLE "); - sql.append(name); - sql.append( - "(" - "media_key TEXT NOT NULL PRIMARY KEY UNIQUE," - "publisher_id LONGVARCHAR NOT NULL," - "CONSTRAINT fk_media_publisher_info_publisher_id" - " FOREIGN KEY (publisher_id)" - " REFERENCES publisher_info (publisher_id)" - " ON DELETE CASCADE)"); - return GetDB().Execute(sql.c_str()); + info_sql.BindInt(0, month); + info_sql.BindInt(1, year); + info_sql.BindInt(2, ledger::REWARDS_CATEGORY::DIRECT_DONATION); + info_sql.BindInt(3, ledger::REWARDS_CATEGORY::TIPPING); + + while (info_sql.Step()) { + std::string id(info_sql.ColumnString(0)); + + ledger::PublisherInfo publisher(id, ledger::ACTIVITY_MONTH::ANY, -1); + + publisher.name = info_sql.ColumnString(1); + publisher.url = info_sql.ColumnString(2); + publisher.favicon_url = info_sql.ColumnString(3); + publisher.weight = info_sql.ColumnDouble(4); + publisher.reconcile_stamp = info_sql.ColumnInt64(5); + publisher.verified = info_sql.ColumnBool(6); + publisher.provider = info_sql.ColumnString(7); + + list->push_back(publisher); + } } -bool PublisherInfoDatabase::CreateRecurringDonationTable() { +/** + * + * PUBLISHER INFO + * + */ + +bool PublisherInfoDatabase::CreatePublisherInfoTable() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - const char* name = "recurring_donation"; - if (GetDB().DoesTableExist(name)) + const char* name = "publisher_info"; + if (GetDB().DoesTableExist(name)) { return true; + } - // Note: revise implementation for InsertOrUpdatePublisherInfo() if you add - // any new constraints to the schema. std::string sql; sql.append("CREATE TABLE "); sql.append(name); sql.append( "(" - "publisher_id LONGVARCHAR NOT NULL PRIMARY KEY UNIQUE," - "amount DOUBLE DEFAULT 0 NOT NULL," - "added_date INTEGER DEFAULT 0 NOT NULL," - "CONSTRAINT fk_recurring_donation_publisher_id" - " FOREIGN KEY (publisher_id)" - " REFERENCES publisher_info (publisher_id)" - " ON DELETE CASCADE)"); - return GetDB().Execute(sql.c_str()); -} - -bool PublisherInfoDatabase::CreateRecurringDonationIndex() { - DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + "publisher_id LONGVARCHAR PRIMARY KEY NOT NULL UNIQUE," + "verified BOOLEAN DEFAULT 0 NOT NULL," + "excluded INTEGER DEFAULT 0 NOT NULL," + "name TEXT NOT NULL," + "favIcon TEXT NOT NULL," + "url TEXT NOT NULL," + "provider TEXT NOT NULL)"); - return GetDB().Execute( - "CREATE INDEX IF NOT EXISTS recurring_donation_publisher_id_index " - "ON recurring_donation (publisher_id)"); + return GetDB().Execute(sql.c_str()); } bool PublisherInfoDatabase::InsertOrUpdatePublisherInfo( @@ -237,15 +237,16 @@ bool PublisherInfoDatabase::InsertOrUpdatePublisherInfo( bool initialized = Init(); DCHECK(initialized); - if (!initialized) + if (!initialized || info.id.empty()) { return false; + } sql::Statement publisher_info_statement( GetDB().GetCachedStatement(SQL_FROM_HERE, - "INSERT OR REPLACE INTO publisher_info " - "(publisher_id, verified, excluded, " - "name, url, provider, favIcon) " - "VALUES (?, ?, ?, ?, ?, ?, ?)")); + "INSERT OR REPLACE INTO publisher_info " + "(publisher_id, verified, excluded, " + "name, url, provider, favIcon) " + "VALUES (?, ?, ?, ?, ?, ?, ?)")); publisher_info_statement.BindString(0, info.id); publisher_info_statement.BindBool(1, info.verified); @@ -255,110 +256,71 @@ bool PublisherInfoDatabase::InsertOrUpdatePublisherInfo( publisher_info_statement.BindString(5, info.provider); publisher_info_statement.BindString(6, info.favicon_url); - if (!publisher_info_statement.Run()) { - return false; - } - - if (info.month == ledger::PUBLISHER_MONTH::ANY || info.year == -1) { - return true; - } - - sql::Statement activity_get( - db_.GetUniqueStatement("SELECT publisher_id FROM activity_info WHERE " - "publisher_id=? AND category=? " - "AND month=? AND year=? AND reconcile_stamp=?")); - - activity_get.BindString(0, info.id); - activity_get.BindInt(1, info.category); - activity_get.BindInt(2, info.month); - activity_get.BindInt(3, info.year); - activity_get.BindInt64(4, info.reconcile_stamp); - - if (activity_get.Step()) { - sql::Statement activity_info_update( - GetDB().GetCachedStatement(SQL_FROM_HERE, - "UPDATE activity_info SET " - "duration=?, score=?, percent=?, " - "weight=? WHERE " - "publisher_id=? AND category=? " - "AND month=? AND year=? AND reconcile_stamp=?")); - - activity_info_update.BindInt64(0, (int)info.duration); - activity_info_update.BindDouble(1, info.score); - activity_info_update.BindInt64(2, (int)info.percent); - activity_info_update.BindDouble(3, info.weight); - activity_info_update.BindString(4, info.id); - activity_info_update.BindInt(5, info.category); - activity_info_update.BindInt(6, info.month); - activity_info_update.BindInt(7, info.year); - activity_info_update.BindInt64(8, info.reconcile_stamp); - - return activity_info_update.Run(); - } - - sql::Statement activity_info_insert( - GetDB().GetCachedStatement(SQL_FROM_HERE, - "INSERT INTO activity_info " - "(publisher_id, duration, score, percent, " - "weight, category, month, year, reconcile_stamp) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")); - - activity_info_insert.BindString(0, info.id); - activity_info_insert.BindInt64(1, (int)info.duration); - activity_info_insert.BindDouble(2, info.score); - activity_info_insert.BindInt64(3, (int)info.percent); - activity_info_insert.BindDouble(4, info.weight); - activity_info_insert.BindInt(5, info.category); - activity_info_insert.BindInt(6, info.month); - activity_info_insert.BindInt(7, info.year); - activity_info_insert.BindInt64(8, info.reconcile_stamp); - - return activity_info_insert.Run(); + return publisher_info_statement.Run(); } -bool PublisherInfoDatabase::InsertOrUpdateMediaPublisherInfo( - const std::string& media_key, const std::string& publisher_id) { +std::unique_ptr +PublisherInfoDatabase::GetPublisherInfo(const std::string& publisher_key) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); bool initialized = Init(); DCHECK(initialized); - if (!initialized) - return false; + if (!initialized) { + return nullptr; + } - sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE, - "INSERT OR REPLACE INTO media_publisher_info " - "(media_key, publisher_id) " - "VALUES (?, ?)")); + sql::Statement info_sql(db_.GetUniqueStatement( + "SELECT publisher_id, name, url, favIcon, provider, verified, excluded " + "FROM publisher_info WHERE publisher_id=?")); - statement.BindString(0, media_key); - statement.BindString(1, publisher_id); + info_sql.BindString(0, publisher_key); - return statement.Run(); + if (info_sql.Step()) { + std::unique_ptr info; + info.reset(new ledger::PublisherInfo()); + info->id = info_sql.ColumnString(0); + info->name = info_sql.ColumnString(1); + info->url = info_sql.ColumnString(2); + info->favicon_url = info_sql.ColumnString(3); + info->provider = info_sql.ColumnString(4); + info->verified = info_sql.ColumnBool(5); + info->excluded = static_cast( + info_sql.ColumnInt(6)); + + return info; + } + + return nullptr; } std::unique_ptr -PublisherInfoDatabase::GetMediaPublisherInfo(const std::string& media_key) { +PublisherInfoDatabase::GetPanelPublisher( + const ledger::ActivityInfoFilter& filter) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); bool initialized = Init(); DCHECK(initialized); - std::unique_ptr info; - - if (!initialized) - return info; + if (!initialized) { + return nullptr; + } - sql::Statement info_sql( - db_.GetUniqueStatement("SELECT pi.publisher_id, pi.name, pi.url, pi.favIcon, " - "pi.provider, pi.verified, pi.excluded " - "FROM media_publisher_info as mpi " - "INNER JOIN publisher_info AS pi ON mpi.publisher_id = pi.publisher_id " - "WHERE mpi.media_key=?")); + sql::Statement info_sql(db_.GetUniqueStatement( + "SELECT pi.publisher_id, pi.name, pi.url, pi.favIcon, pi.provider, " + "pi.verified, pi.excluded, ai.percent FROM publisher_info AS pi " + "LEFT JOIN activity_info AS ai ON pi.publisher_id = ai.publisher_id " + "WHERE pi.publisher_id=? AND ((ai.month = ? " + "AND ai.year = ? AND ai.reconcile_stamp = ?) OR " + "ai.percent IS NULL) LIMIT 1")); - info_sql.BindString(0, media_key); + info_sql.BindString(0, filter.id); + info_sql.BindInt(1, filter.month); + info_sql.BindInt(2, filter.year); + info_sql.BindInt64(3, filter.reconcile_stamp); if (info_sql.Step()) { + std::unique_ptr info; info.reset(new ledger::PublisherInfo()); info->id = info_sql.ColumnString(0); info->name = info_sql.ColumnString(1); @@ -366,287 +328,438 @@ PublisherInfoDatabase::GetMediaPublisherInfo(const std::string& media_key) { info->favicon_url = info_sql.ColumnString(3); info->provider = info_sql.ColumnString(4); info->verified = info_sql.ColumnBool(5); - info->excluded = static_cast(info_sql.ColumnInt(6)); + info->excluded = static_cast( + info_sql.ColumnInt(6)); + info->percent = info_sql.ColumnInt(7); + + return info; } - return info; + + return nullptr; } -bool PublisherInfoDatabase::Find(int start, - int limit, - const ledger::PublisherInfoFilter& filter, - ledger::PublisherInfoList* list) { +bool PublisherInfoDatabase::RestorePublishers() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - CHECK(list); - bool initialized = Init(); DCHECK(initialized); - if (!initialized) + if (!initialized) { return false; + } - std::string query = "SELECT ai.publisher_id, ai.duration, ai.score, ai.percent, " - "ai.weight, pi.verified, pi.excluded, ai.category, ai.month, ai.year, pi.name, " - "pi.url, pi.provider, pi.favIcon, ai.reconcile_stamp " - "FROM activity_info AS ai " - "INNER JOIN publisher_info AS pi ON ai.publisher_id = pi.publisher_id " - "WHERE 1 = 1"; + sql::Statement restore_q(db_.GetUniqueStatement( + "UPDATE publisher_info SET excluded=? WHERE excluded=?")); - query+= BuildClauses(start, limit, filter); + restore_q.BindInt(0, static_cast( + ledger::PUBLISHER_EXCLUDE::DEFAULT)); + restore_q.BindInt(1, static_cast( + ledger::PUBLISHER_EXCLUDE::EXCLUDED)); - sql::Statement info_sql(db_.GetUniqueStatement(query.c_str())); - - BindFilter(info_sql, filter); + return restore_q.Run(); +} - while (info_sql.Step()) { - std::string id(info_sql.ColumnString(0)); - ledger::PUBLISHER_MONTH month( - static_cast(info_sql.ColumnInt(8))); - int year(info_sql.ColumnInt(9)); +/** + * + * ACTIVITY INFO + * + */ +bool PublisherInfoDatabase::CreateActivityInfoTable() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - ledger::PublisherInfo info(id, month, year); - info.duration = info_sql.ColumnInt64(1); + const char* name = "activity_info"; + if (GetDB().DoesTableExist(name)) { + return true; + } - info.score = info_sql.ColumnDouble(2); - info.percent = info_sql.ColumnInt64(3); - info.weight = info_sql.ColumnDouble(4); - info.verified = info_sql.ColumnBool(5); - info.name = info_sql.ColumnString(10); - info.url = info_sql.ColumnString(11); - info.provider = info_sql.ColumnString(12); - info.favicon_url = info_sql.ColumnString(13); - info.reconcile_stamp = info_sql.ColumnInt64(14); + std::string sql; + sql.append("CREATE TABLE "); + sql.append(name); + sql.append( + "(" + "publisher_id LONGVARCHAR NOT NULL," + "duration INTEGER DEFAULT 0 NOT NULL," + "visits INTEGER DEFAULT 0 NOT NULL," + "score DOUBLE DEFAULT 0 NOT NULL," + "percent INTEGER DEFAULT 0 NOT NULL," + "weight DOUBLE DEFAULT 0 NOT NULL," + "month INTEGER NOT NULL," + "year INTEGER NOT NULL," + "reconcile_stamp INTEGER DEFAULT 0 NOT NULL," + "CONSTRAINT activity_unique " + "UNIQUE (publisher_id, month, year, reconcile_stamp) " + "CONSTRAINT fk_activity_info_publisher_id" + " FOREIGN KEY (publisher_id)" + " REFERENCES publisher_info (publisher_id)" + " ON DELETE CASCADE)"); - info.excluded = static_cast(info_sql.ColumnInt(6)); - info.category = - static_cast(info_sql.ColumnInt(7)); + return GetDB().Execute(sql.c_str()); +} - list->push_back(info); - } +bool PublisherInfoDatabase::CreateActivityInfoIndex() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - return list; + return GetDB().Execute( + "CREATE INDEX IF NOT EXISTS activity_info_publisher_id_index " + "ON activity_info (publisher_id)"); } -int PublisherInfoDatabase::Count(const ledger::PublisherInfoFilter& filter) { +bool PublisherInfoDatabase::InsertOrUpdateActivityInfo( + const ledger::PublisherInfo& info) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); bool initialized = Init(); DCHECK(initialized); - if (!initialized) + if (!initialized) { + return false; + } + + LOG(ERROR) << "NEJC 1"; + + if (!InsertOrUpdatePublisherInfo(info)) { return false; + } - std::string query = "SELECT COUNT(ai.publisher_id) " - "FROM activity_info AS ai " - "INNER JOIN publisher_info AS pi ON ai.publisher_id = pi.publisher_id " - "WHERE 1 = 1"; + LOG(ERROR) << "NEJC 2"; - query+= BuildClauses(0, 0, filter); + LOG(ERROR) << info.year; - sql::Statement publisher_count(db_.GetUniqueStatement(query.c_str())); + sql::Statement activity_info_insert( + GetDB().GetCachedStatement(SQL_FROM_HERE, + "INSERT OR REPLACE INTO activity_info " + "(publisher_id, duration, score, percent, " + "weight, month, year, reconcile_stamp, visits) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")); - BindFilter(publisher_count, filter); + activity_info_insert.BindString(0, info.id); + activity_info_insert.BindInt64(1, static_cast(info.duration)); + activity_info_insert.BindDouble(2, info.score); + activity_info_insert.BindInt64(3, static_cast(info.percent)); + activity_info_insert.BindDouble(4, info.weight); + activity_info_insert.BindInt(5, info.month); + activity_info_insert.BindInt(6, info.year); + activity_info_insert.BindInt64(7, info.reconcile_stamp); + activity_info_insert.BindInt64(8, info.visits); - if (!publisher_count.Step()) - return 0; + LOG(ERROR) << "NEJC 3"; - return publisher_count.ColumnInt(0); + return activity_info_insert.Run(); } -std::string PublisherInfoDatabase::BuildClauses(int start, - int limit, - const ledger::PublisherInfoFilter& filter) { - std::string clauses = ""; +bool PublisherInfoDatabase::GetActivityList( + int start, + int limit, + const ledger::ActivityInfoFilter& filter, + ledger::PublisherInfoList* list) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - if (!filter.id.empty()) - clauses += " AND ai.publisher_id = ?"; + CHECK(list); - if (filter.category != ledger::PUBLISHER_CATEGORY::ALL_CATEGORIES) - clauses += " AND ai.category = ?"; + bool initialized = Init(); + DCHECK(initialized); - if (filter.month != ledger::PUBLISHER_MONTH::ANY) - clauses += " AND ai.month = ?"; + if (!initialized) { + return false; + } - if (filter.year > 0) - clauses += " AND ai.year = ?"; + std::string query = "SELECT ai.publisher_id, ai.duration, ai.score, " + "ai.percent, ai.weight, pi.verified, pi.excluded, " + "ai.month, ai.year, pi.name, pi.url, pi.provider, " + "pi.favIcon, ai.reconcile_stamp " + "FROM activity_info AS ai " + "INNER JOIN publisher_info AS pi " + "ON ai.publisher_id = pi.publisher_id " + "WHERE 1 = 1"; + + if (!filter.id.empty()) { + query += " AND ai.publisher_id = ?"; + } - if (filter.reconcile_stamp > 0) - clauses += " AND ai.reconcile_stamp = ?"; + if (filter.month != ledger::ACTIVITY_MONTH::ANY) { + query += " AND ai.month = ?"; + } - if (filter.min_duration > 0) - clauses += " AND ai.duration >= ?"; + if (filter.year > 0) { + query += " AND ai.year = ?"; + } - if (filter.excluded != ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL && + if (filter.reconcile_stamp > 0) { + query += " AND ai.reconcile_stamp = ?"; + } + + if (filter.min_duration > 0) { + query += " AND ai.duration >= ?"; + } + + if (filter.excluded != ledger::EXCLUDE_FILTER::FILTER_ALL && filter.excluded != - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED) - clauses += " AND pi.excluded = ?"; + ledger::EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED) { + query += " AND pi.excluded = ?"; + } if (filter.excluded == - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED) - clauses += " AND pi.excluded != ?"; + ledger::EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED) { + query += " AND pi.excluded != ?"; + } if (filter.percent > 0) { - clauses += " AND ai.percent >= ?"; + query += " AND ai.percent >= ?"; } if (!filter.non_verified) { - clauses += " AND pi.verified = 1"; + query += " AND pi.verified = 1"; } for (const auto& it : filter.order_by) { - clauses += " ORDER BY " + it.first; - clauses += (it.second ? " ASC" : " DESC"); + query += " ORDER BY " + it.first; + query += (it.second ? " ASC" : " DESC"); } if (limit > 0) { - clauses += " LIMIT " + std::to_string(limit); + query += " LIMIT " + std::to_string(limit); if (start > 1) { - clauses += " OFFSET " + std::to_string(start); + query += " OFFSET " + std::to_string(start); } } - return clauses; -} + sql::Statement info_sql(db_.GetUniqueStatement(query.c_str())); -void PublisherInfoDatabase::BindFilter(sql::Statement& statement, - const ledger::PublisherInfoFilter& filter) { int column = 0; - if (!filter.id.empty()) - statement.BindString(column++, filter.id); - - if (filter.category != ledger::PUBLISHER_CATEGORY::ALL_CATEGORIES) - statement.BindInt(column++, filter.category); + if (!filter.id.empty()) { + info_sql.BindString(column++, filter.id); + } - if (filter.month != ledger::PUBLISHER_MONTH::ANY) - statement.BindInt(column++, filter.month); + if (filter.month != ledger::ACTIVITY_MONTH::ANY) { + info_sql.BindInt(column++, filter.month); + } - if (filter.year > 0) - statement.BindInt(column++, filter.year); + if (filter.year > 0) { + info_sql.BindInt(column++, filter.year); + } - if (filter.reconcile_stamp > 0) - statement.BindInt64(column++, filter.reconcile_stamp); + if (filter.reconcile_stamp > 0) { + info_sql.BindInt64(column++, filter.reconcile_stamp); + } - if (filter.min_duration > 0) - statement.BindInt(column++, filter.min_duration); + if (filter.min_duration > 0) { + info_sql.BindInt(column++, filter.min_duration); + } - if (filter.excluded != ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL && + if (filter.excluded != ledger::EXCLUDE_FILTER::FILTER_ALL && filter.excluded != - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED) - statement.BindInt(column++, filter.excluded); + ledger::EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED) { + info_sql.BindInt(column++, filter.excluded); + } if (filter.excluded == - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED) - statement.BindInt(column++, ledger::PUBLISHER_EXCLUDE::EXCLUDED); + ledger::EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED) { + info_sql.BindInt(column++, ledger::PUBLISHER_EXCLUDE::EXCLUDED); + } + + if (filter.percent > 0) { + info_sql.BindInt(column++, filter.percent); + } + + while (info_sql.Step()) { + std::string id(info_sql.ColumnString(0)); + ledger::ACTIVITY_MONTH month( + static_cast(info_sql.ColumnInt(7))); + int year(info_sql.ColumnInt(8)); - if (filter.percent > 0) - statement.BindInt(column++, filter.percent); + ledger::PublisherInfo info(id, month, year); + info.duration = info_sql.ColumnInt64(1); + + info.score = info_sql.ColumnDouble(2); + info.percent = info_sql.ColumnInt64(3); + info.weight = info_sql.ColumnDouble(4); + info.verified = info_sql.ColumnBool(5); + info.name = info_sql.ColumnString(9); + info.url = info_sql.ColumnString(10); + info.provider = info_sql.ColumnString(11); + info.favicon_url = info_sql.ColumnString(12); + info.reconcile_stamp = info_sql.ColumnInt64(13); + + info.excluded = static_cast( + info_sql.ColumnInt(6)); + + list->push_back(info); + } + + return list; } -bool PublisherInfoDatabase::InsertContributionInfo(const brave_rewards::ContributionInfo& info) { +/** + * + * MEDIA PUBLISHER INFO + * + */ +bool PublisherInfoDatabase::CreateMediaPublisherInfoTable() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + const char* name = "media_publisher_info"; + if (GetDB().DoesTableExist(name)) { + return true; + } + + std::string sql; + sql.append("CREATE TABLE "); + sql.append(name); + sql.append( + "(" + "media_key TEXT NOT NULL PRIMARY KEY UNIQUE," + "publisher_id LONGVARCHAR NOT NULL," + "CONSTRAINT fk_media_publisher_info_publisher_id" + " FOREIGN KEY (publisher_id)" + " REFERENCES publisher_info (publisher_id)" + " ON DELETE CASCADE)"); + + return GetDB().Execute(sql.c_str()); +} + +bool PublisherInfoDatabase::InsertOrUpdateMediaPublisherInfo( + const std::string& media_key, const std::string& publisher_id) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); bool initialized = Init(); DCHECK(initialized); - if (!initialized) + if (!initialized || media_key.empty() || publisher_id.empty()) { return false; + } - sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE, - "INSERT INTO contribution_info " - "(publisher_id, probi, date, " - "category, month, year) " - "VALUES (?, ?, ?, ?, ?, ?)")); + sql::Statement statement(GetDB().GetCachedStatement( + SQL_FROM_HERE, + "INSERT OR REPLACE INTO media_publisher_info " + "(media_key, publisher_id) " + "VALUES (?, ?)")); - statement.BindString(0, info.publisher_key); - statement.BindString(1, info.probi); - statement.BindInt64(2, info.date); - statement.BindInt(3, info.category); - statement.BindInt(4, info.month); - statement.BindInt(5, info.year); + statement.BindString(0, media_key); + statement.BindString(1, publisher_id); return statement.Run(); } -bool PublisherInfoDatabase::InsertOrUpdateRecurringDonation(const brave_rewards::RecurringDonation& info) { +std::unique_ptr +PublisherInfoDatabase::GetMediaPublisherInfo(const std::string& media_key) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); bool initialized = Init(); DCHECK(initialized); - if (!initialized) - return false; + if (!initialized) { + return nullptr; + } - sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE, - "INSERT OR REPLACE INTO recurring_donation " - "(publisher_id, amount, added_date) " - "VALUES (?, ?, ?)")); + sql::Statement info_sql(db_.GetUniqueStatement( + "SELECT pi.publisher_id, pi.name, pi.url, pi.favIcon, " + "pi.provider, pi.verified, pi.excluded " + "FROM media_publisher_info as mpi " + "INNER JOIN publisher_info AS pi ON mpi.publisher_id = pi.publisher_id " + "WHERE mpi.media_key=?")); - statement.BindString(0, info.publisher_key); - statement.BindDouble(1, info.amount); - statement.BindInt64(2, info.added_date); + info_sql.BindString(0, media_key); - return statement.Run(); + if (info_sql.Step()) { + std::unique_ptr info(new ledger::PublisherInfo()); + info->id = info_sql.ColumnString(0); + info->name = info_sql.ColumnString(1); + info->url = info_sql.ColumnString(2); + info->favicon_url = info_sql.ColumnString(3); + info->provider = info_sql.ColumnString(4); + info->verified = info_sql.ColumnBool(5); + info->excluded = static_cast( + info_sql.ColumnInt(6)); + + return info; + } + + return nullptr; } -void PublisherInfoDatabase::GetRecurringDonations(ledger::PublisherInfoList* list) { +/** + * + * RECURRING DONATION + * + */ +bool PublisherInfoDatabase::CreateRecurringDonationTable() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - bool initialized = Init(); - DCHECK(initialized); + const char* name = "recurring_donation"; + if (GetDB().DoesTableExist(name)) { + return true; + } - if (!initialized) - return; + std::string sql; + sql.append("CREATE TABLE "); + sql.append(name); + sql.append( + "(" + "publisher_id LONGVARCHAR NOT NULL PRIMARY KEY UNIQUE," + "amount DOUBLE DEFAULT 0 NOT NULL," + "added_date INTEGER DEFAULT 0 NOT NULL," + "CONSTRAINT fk_recurring_donation_publisher_id" + " FOREIGN KEY (publisher_id)" + " REFERENCES publisher_info (publisher_id)" + " ON DELETE CASCADE)"); - sql::Statement info_sql( - db_.GetUniqueStatement("SELECT pi.publisher_id, pi.name, pi.url, pi.favIcon, " - "rd.amount, rd.added_date, pi.verified, pi.provider " - "FROM recurring_donation as rd " - "INNER JOIN publisher_info AS pi ON rd.publisher_id = pi.publisher_id ")); + return GetDB().Execute(sql.c_str()); +} - while (info_sql.Step()) { - std::string id(info_sql.ColumnString(0)); +bool PublisherInfoDatabase::CreateRecurringDonationIndex() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - ledger::PublisherInfo publisher(id, ledger::PUBLISHER_MONTH::ANY, -1); + return GetDB().Execute( + "CREATE INDEX IF NOT EXISTS recurring_donation_publisher_id_index " + "ON recurring_donation (publisher_id)"); +} - publisher.name = info_sql.ColumnString(1); - publisher.url = info_sql.ColumnString(2); - publisher.favicon_url = info_sql.ColumnString(3); - publisher.weight = info_sql.ColumnDouble(4); - publisher.reconcile_stamp = info_sql.ColumnInt64(5); - publisher.verified = info_sql.ColumnBool(6); - publisher.provider = info_sql.ColumnString(7); +bool PublisherInfoDatabase::InsertOrUpdateRecurringDonation( + const brave_rewards::RecurringDonation& info) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - list->push_back(publisher); + bool initialized = Init(); + DCHECK(initialized); + + if (!initialized || info.publisher_key.empty()) { + return false; } + + sql::Statement statement(GetDB().GetCachedStatement( + SQL_FROM_HERE, + "INSERT OR REPLACE INTO recurring_donation " + "(publisher_id, amount, added_date) " + "VALUES (?, ?, ?)")); + + statement.BindString(0, info.publisher_key); + statement.BindDouble(1, info.amount); + statement.BindInt64(2, info.added_date); + + return statement.Run(); } -void PublisherInfoDatabase::GetTips(ledger::PublisherInfoList* list, ledger::PUBLISHER_MONTH month, int year) { +void PublisherInfoDatabase::GetRecurringDonations( + ledger::PublisherInfoList* list) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); bool initialized = Init(); DCHECK(initialized); - if (!initialized) + if (!initialized) { return; + } - sql::Statement info_sql( - db_.GetUniqueStatement("SELECT pi.publisher_id, pi.name, pi.url, pi.favIcon, " - "ci.probi, ci.date, pi.verified, pi.provider " - "FROM contribution_info as ci " - "INNER JOIN publisher_info AS pi ON ci.publisher_id = pi.publisher_id " - "AND ci.month = ? AND ci.year = ? " - "AND (ci.category = ? OR ci.category = ?)")); - - info_sql.BindInt(0, month); - info_sql.BindInt(1, year); - info_sql.BindInt(2, ledger::PUBLISHER_CATEGORY::DIRECT_DONATION); - info_sql.BindInt(3, ledger::PUBLISHER_CATEGORY::TIPPING); + sql::Statement info_sql(db_.GetUniqueStatement( + "SELECT pi.publisher_id, pi.name, pi.url, pi.favIcon, " + "rd.amount, rd.added_date, pi.verified, pi.provider " + "FROM recurring_donation as rd " + "INNER JOIN publisher_info AS pi ON rd.publisher_id = pi.publisher_id ")); while (info_sql.Step()) { std::string id(info_sql.ColumnString(0)); - ledger::PublisherInfo publisher(id, ledger::PUBLISHER_MONTH::ANY, -1); + ledger::PublisherInfo publisher(id, ledger::ACTIVITY_MONTH::ANY, -1); publisher.name = info_sql.ColumnString(1); publisher.url = info_sql.ColumnString(2); @@ -666,10 +779,12 @@ bool PublisherInfoDatabase::RemoveRecurring(const std::string& publisher_key) { bool initialized = Init(); DCHECK(initialized); - if (!initialized) + if (!initialized) { return false; + } - sql::Statement statement(GetDB().GetCachedStatement(SQL_FROM_HERE, + sql::Statement statement(GetDB().GetCachedStatement( + SQL_FROM_HERE, "DELETE FROM recurring_donation WHERE publisher_id = ?")); statement.BindString(0, publisher_key); @@ -677,6 +792,11 @@ bool PublisherInfoDatabase::RemoveRecurring(const std::string& publisher_key) { return statement.Run(); } +/** + * + * PENDING CONTRIBUTION + * + */ bool PublisherInfoDatabase::CreatePendingContributionsTable() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -767,7 +887,6 @@ double PublisherInfoDatabase::GetReservedAmount() { return amount; } - // static int PublisherInfoDatabase::GetCurrentVersion() { return kCurrentVersionNumber; @@ -865,6 +984,49 @@ bool PublisherInfoDatabase::MigrateV2toV3() { return CreatePendingContributionsIndex(); } +bool PublisherInfoDatabase::MigrateV3toV4() { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + + // Activity info + const char* activity = "activity_info"; + if (GetDB().DoesTableExist(activity)) { + std::string sql = "ALTER TABLE activity_info RENAME TO activity_info_old;"; + + if (!GetDB().Execute(sql.c_str())) { + return false; + } + + if (!CreateActivityInfoTable()) { + return false; + } + + if (!CreateActivityInfoIndex()) { + return false; + } + + std::string columns = "publisher_id, " + "duration, " + "score, " + "percent, " + "weight, " + "month, " + "year, " + "reconcile_stamp"; + + sql = "PRAGMA foreign_keys=off;"; + sql.append("INSERT INTO activity_info (" + columns + ") " + "SELECT " + columns + " " + "FROM activity_info_old;"); + sql.append("UPDATE activity_info SET visits=5;"); + sql.append("DROP TABLE activity_info_old;"); + sql.append("PRAGMA foreign_keys=on;"); + + return GetDB().Execute(sql.c_str()); + } + + return false; +} + sql::InitStatus PublisherInfoDatabase::EnsureCurrentVersion() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); @@ -891,8 +1053,15 @@ sql::InitStatus PublisherInfoDatabase::EnsureCurrentVersion() { } } + // to version 4 + if (old_version < 4 && cur_version < 5) { + if (!MigrateV3toV4()) { + LOG(ERROR) << "DB: Error with MigrateV3toV4"; + } + } + meta_table_.SetVersionNumber(cur_version); return sql::INIT_OK; } -} // namespace history +} // namespace brave_rewards diff --git a/components/brave_rewards/browser/publisher_info_database.h b/components/brave_rewards/browser/publisher_info_database.h index 76ea55f790bd..45a0cfe19244 100644 --- a/components/brave_rewards/browser/publisher_info_database.h +++ b/components/brave_rewards/browser/publisher_info_database.h @@ -36,25 +36,45 @@ class PublisherInfoDatabase { db_.set_error_callback(error_callback); } - bool InsertOrUpdatePublisherInfo(const ledger::PublisherInfo& info); - bool InsertOrUpdateMediaPublisherInfo(const std::string& media_key, const std::string& publisher_id); bool InsertContributionInfo(const brave_rewards::ContributionInfo& info); - bool InsertOrUpdateRecurringDonation(const brave_rewards::RecurringDonation& info); - bool Find(int start, - int limit, - const ledger::PublisherInfoFilter& filter, - ledger::PublisherInfoList* list); - int Count(const ledger::PublisherInfoFilter& filter); + void GetTips(ledger::PublisherInfoList* list, + ledger::ACTIVITY_MONTH month, + int year); + + bool InsertOrUpdatePublisherInfo(const ledger::PublisherInfo& info); + + std::unique_ptr GetPublisherInfo( + const std::string& media_key); + + std::unique_ptr GetPanelPublisher( + const ledger::ActivityInfoFilter& filter); + + bool RestorePublishers(); + + bool InsertOrUpdateActivityInfo(const ledger::PublisherInfo& info); + + bool GetActivityList(int start, + int limit, + const ledger::ActivityInfoFilter& filter, + ledger::PublisherInfoList* list); + + bool InsertOrUpdateMediaPublisherInfo(const std::string& media_key, + const std::string& publisher_id); std::unique_ptr GetMediaPublisherInfo( const std::string& media_key); + + bool InsertOrUpdateRecurringDonation( + const brave_rewards::RecurringDonation& info); + void GetRecurringDonations(ledger::PublisherInfoList* list); - void GetTips(ledger::PublisherInfoList* list, ledger::PUBLISHER_MONTH month, int year); + bool RemoveRecurring(const std::string& publisher_key); bool InsertPendingContribution(const ledger::PendingContributionList& list); double GetReservedAmount(); + // Returns the current version of the publisher info database static int GetCurrentVersion(); @@ -64,34 +84,43 @@ class PublisherInfoDatabase { std::string GetDiagnosticInfo(int extended_error, sql::Statement* statement); - private: + sql::Database& GetDB(); + bool Init(); - void OnMemoryPressure( - base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level); + + private: + bool CreateContributionInfoTable(); + + bool CreateContributionInfoIndex(); + bool CreatePublisherInfoTable(); - bool CreateMediaPublisherInfoTable(); + bool CreateActivityInfoTable(); - bool CreateContributionInfoIndex(); + bool CreateActivityInfoIndex(); + + bool CreateMediaPublisherInfoTable(); + bool CreateRecurringDonationTable(); + bool CreateRecurringDonationIndex(); bool CreatePendingContributionsTable(); bool CreatePendingContributionsIndex(); - std::string BuildClauses(int start, - int limit, - const ledger::PublisherInfoFilter& filter); - void BindFilter(sql::Statement& statement, - const ledger::PublisherInfoFilter& filter); + void OnMemoryPressure( + base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level); - sql::Database& GetDB(); sql::MetaTable& GetMetaTable(); - sql::InitStatus EnsureCurrentVersion(); bool MigrateV1toV2(); + bool MigrateV2toV3(); + bool MigrateV3toV4(); + + sql::InitStatus EnsureCurrentVersion(); + sql::Database db_; sql::MetaTable meta_table_; const base::FilePath db_path_; diff --git a/components/brave_rewards/browser/publisher_info_database_unittest.cc b/components/brave_rewards/browser/publisher_info_database_unittest.cc new file mode 100644 index 000000000000..14966c230bdb --- /dev/null +++ b/components/brave_rewards/browser/publisher_info_database_unittest.cc @@ -0,0 +1,408 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include +#include + +#include "brave/components/brave_rewards/browser/publisher_info_database.h" + +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "sql/database.h" +#include "sql/statement.h" +#include "third_party/sqlite/sqlite3.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +// npm run test -- brave_unit_tests --filter=PublisherInfoDatabaseTest.* + +namespace brave_rewards { + +class PublisherInfoDatabaseTest : public ::testing::Test { + protected: + PublisherInfoDatabaseTest() { + } + + ~PublisherInfoDatabaseTest() override { + } + + sql::Database& GetDB() { + return publisher_info_database_->GetDB(); + } + + void CreateTempDatabase(base::ScopedTempDir* temp_dir, + base::FilePath* db_file) { + ASSERT_TRUE(temp_dir->CreateUniqueTempDir()); + *db_file = temp_dir->GetPath().AppendASCII("PublisherInfoDatabaseTest.db"); + sql::Database::Delete(*db_file); + + publisher_info_database_ = + std::make_unique(*db_file); + ASSERT_NE(publisher_info_database_, nullptr); + } + + int CountTableRows(const std::string& table) { + std::string sql = "SELECT COUNT(*) FROM " + table; + sql::Statement s(GetDB().GetUniqueStatement(sql.c_str())); + + if (!s.Step()) { + return -1; + } + + return static_cast(s.ColumnInt64(0)); + } + + std::unique_ptr publisher_info_database_; +}; + +TEST_F(PublisherInfoDatabaseTest, InsertContributionInfo) { + /** + * Good path + */ + base::ScopedTempDir temp_dir; + base::FilePath db_file; + CreateTempDatabase(&temp_dir, &db_file); + + ContributionInfo info; + info.probi = "12345678901234567890123456789012345678901234"; + info.month = ledger::ACTIVITY_MONTH::JANUARY; + info.year = 1970; + info.category = ledger::REWARDS_CATEGORY::AUTO_CONTRIBUTE; + info.date = base::Time::Now().ToJsTime(); + info.publisher_key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + bool success = publisher_info_database_->InsertContributionInfo(info); + EXPECT_TRUE(success); + + std::string query = "SELECT * FROM contribution_info WHERE publisher_id=?"; + sql::Statement info_sql(GetDB().GetUniqueStatement(query.c_str())); + + info_sql.BindString(0, info.publisher_key); + + EXPECT_TRUE(info_sql.Step()); + EXPECT_EQ(CountTableRows("contribution_info"), 1); + EXPECT_EQ(info_sql.ColumnString(0), info.publisher_key); + EXPECT_EQ(info_sql.ColumnString(1), info.probi); + EXPECT_EQ(info_sql.ColumnInt64(2), info.date); + EXPECT_EQ(info_sql.ColumnInt(3), info.category); + EXPECT_EQ(info_sql.ColumnInt(4), info.month); + EXPECT_EQ(info_sql.ColumnInt(5), info.year); +} + +TEST_F(PublisherInfoDatabaseTest, InsertOrUpdatePublisherInfo) { + /** + * Good path + */ + base::ScopedTempDir temp_dir; + base::FilePath db_file; + CreateTempDatabase(&temp_dir, &db_file); + + ledger::PublisherInfo info; + info.id = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + info.verified = false; + info.excluded = ledger::PUBLISHER_EXCLUDE::DEFAULT; + info.name = "name"; + info.url = "https://brave.com"; + info.provider = ""; + info.favicon_url = ""; + + bool success = publisher_info_database_->InsertOrUpdatePublisherInfo(info); + EXPECT_TRUE(success); + + std::string query = "SELECT * FROM publisher_info WHERE publisher_id=?"; + sql::Statement info_sql(GetDB().GetUniqueStatement(query.c_str())); + + info_sql.BindString(0, info.id); + + EXPECT_TRUE(info_sql.Step()); + EXPECT_EQ(CountTableRows("publisher_info"), 1); + EXPECT_EQ(info_sql.ColumnString(0), info.id); + EXPECT_EQ(info_sql.ColumnBool(1), info.verified); + EXPECT_EQ(static_cast(info_sql.ColumnInt(2)), + info.excluded); + EXPECT_EQ(info_sql.ColumnString(3), info.name); + EXPECT_EQ(info_sql.ColumnString(4), info.favicon_url); + EXPECT_EQ(info_sql.ColumnString(5), info.url); + EXPECT_EQ(info_sql.ColumnString(6), info.provider); + + /** + * Make sure that second insert is update and not insert + */ + info.verified = true; + info.excluded = ledger::PUBLISHER_EXCLUDE::ALL; + info.name = "updated"; + info.url = "https://clifton.com"; + info.provider = ""; + info.favicon_url = "1"; + + success = publisher_info_database_->InsertOrUpdatePublisherInfo(info); + EXPECT_TRUE(success); + + query = "SELECT * FROM publisher_info WHERE publisher_id=?"; + sql::Statement info_sql_1(GetDB().GetUniqueStatement(query.c_str())); + + info_sql_1.BindString(0, info.id); + + EXPECT_TRUE(info_sql_1.Step()); + EXPECT_EQ(CountTableRows("publisher_info"), 1); + EXPECT_EQ(info_sql_1.ColumnString(0), info.id); + EXPECT_EQ(info_sql_1.ColumnBool(1), info.verified); + EXPECT_EQ(static_cast(info_sql_1.ColumnInt(2)), + info.excluded); + EXPECT_EQ(info_sql_1.ColumnString(3), info.name); + EXPECT_EQ(info_sql_1.ColumnString(4), info.favicon_url); + EXPECT_EQ(info_sql_1.ColumnString(5), info.url); + EXPECT_EQ(info_sql_1.ColumnString(6), info.provider); + + /** + * Publisher key is missing + */ + info.id = ""; + + success = publisher_info_database_->InsertOrUpdatePublisherInfo(info); + EXPECT_FALSE(success); + + query = "SELECT * FROM publisher_info WHERE publisher_id=?"; + sql::Statement info_sql_2(GetDB().GetUniqueStatement(query.c_str())); + + info_sql_2.BindString(0, info.id); + + EXPECT_FALSE(info_sql_2.Step()); +} + +TEST_F(PublisherInfoDatabaseTest, InsertOrUpdateActivityInfo) { + /** + * Good path + */ + base::ScopedTempDir temp_dir; + base::FilePath db_file; + CreateTempDatabase(&temp_dir, &db_file); + + ledger::PublisherInfo info; + info.id = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + info.verified = false; + info.excluded = ledger::PUBLISHER_EXCLUDE::DEFAULT; + info.name = "name"; + info.url = "https://brave.com"; + info.provider = ""; + info.favicon_url = ""; + info.duration = 10; + info.score = 1.1; + info.percent = 100; + info.weight = 1.5; + info.month = ledger::ACTIVITY_MONTH::JANUARY; + info.year = 1970; + info.reconcile_stamp = 0; + info.visits = 1; + + bool success = publisher_info_database_->InsertOrUpdateActivityInfo(info); + EXPECT_TRUE(success); + + std::string query = "SELECT * FROM activity_info WHERE publisher_id=?"; + sql::Statement info_sql(GetDB().GetUniqueStatement(query.c_str())); + + info_sql.BindString(0, info.id); + + EXPECT_TRUE(info_sql.Step()); + EXPECT_EQ(CountTableRows("activity_info"), 1); + EXPECT_EQ(info_sql.ColumnString(0), info.id); + EXPECT_EQ(static_cast(info_sql.ColumnInt64(1)), info.duration); + EXPECT_EQ(info_sql.ColumnInt64(2), info.visits); + EXPECT_EQ(info_sql.ColumnDouble(3), info.score); + EXPECT_EQ(info_sql.ColumnInt64(4), info.percent); + EXPECT_EQ(info_sql.ColumnDouble(5), info.weight); + EXPECT_EQ(info_sql.ColumnInt(6), info.month); + EXPECT_EQ(info_sql.ColumnInt(7), info.year); + EXPECT_EQ(static_cast(info_sql.ColumnInt64(8)), + info.reconcile_stamp); + + /** + * Make sure that second insert is update and not insert, + * month, year and stamp is unique key + */ + info.verified = true; + info.excluded = ledger::PUBLISHER_EXCLUDE::ALL; + info.name = "update"; + info.url = "https://slo-tech.com"; + info.provider = "1"; + info.favicon_url = "1"; + info.duration = 11; + info.score = 2.1; + info.percent = 200; + info.weight = 2.5; + info.visits = 2; + + success = publisher_info_database_->InsertOrUpdateActivityInfo(info); + EXPECT_TRUE(success); + + query = "SELECT * FROM activity_info WHERE publisher_id=?"; + sql::Statement info_sql_1(GetDB().GetUniqueStatement(query.c_str())); + + info_sql_1.BindString(0, info.id); + + EXPECT_TRUE(info_sql_1.Step()); + EXPECT_EQ(CountTableRows("activity_info"), 1); + EXPECT_EQ(info_sql_1.ColumnString(0), info.id); + EXPECT_EQ(static_cast(info_sql_1.ColumnInt64(1)), info.duration); + EXPECT_EQ(info_sql_1.ColumnInt64(2), info.visits); + EXPECT_EQ(info_sql_1.ColumnDouble(3), info.score); + EXPECT_EQ(info_sql_1.ColumnInt64(4), info.percent); + EXPECT_EQ(info_sql_1.ColumnDouble(5), info.weight); + EXPECT_EQ(info_sql_1.ColumnInt(6), info.month); + EXPECT_EQ(info_sql_1.ColumnInt(7), info.year); + EXPECT_EQ(static_cast(info_sql_1.ColumnInt64(8)), + info.reconcile_stamp); + +} + +TEST_F(PublisherInfoDatabaseTest, InsertOrUpdateMediaPublisherInfo) { + /** + * Good path + */ + base::ScopedTempDir temp_dir; + base::FilePath db_file; + CreateTempDatabase(&temp_dir, &db_file); + + std::string publisher_id = "id"; + std::string media_key = "key"; + + bool success = publisher_info_database_->InsertOrUpdateMediaPublisherInfo( + media_key, + publisher_id); + EXPECT_TRUE(success); + + std::string query = + "SELECT * FROM media_publisher_info WHERE media_key=?"; + sql::Statement info_sql(GetDB().GetUniqueStatement(query.c_str())); + + info_sql.BindString(0, media_key); + + EXPECT_TRUE(info_sql.Step()); + EXPECT_EQ(CountTableRows("media_publisher_info"), 1); + EXPECT_EQ(info_sql.ColumnString(0), media_key); + EXPECT_EQ(info_sql.ColumnString(1), publisher_id); + + /** + * Make sure that second insert is update and not insert + */ + publisher_id = "id_new"; + + success = publisher_info_database_->InsertOrUpdateMediaPublisherInfo( + media_key, + publisher_id); + EXPECT_TRUE(success); + + query = "SELECT * FROM media_publisher_info WHERE media_key=?"; + sql::Statement info_sql_1(GetDB().GetUniqueStatement(query.c_str())); + + info_sql_1.BindString(0, media_key); + + EXPECT_TRUE(info_sql_1.Step()); + EXPECT_EQ(CountTableRows("media_publisher_info"), 1); + EXPECT_EQ(info_sql_1.ColumnString(0), media_key); + EXPECT_EQ(info_sql_1.ColumnString(1), publisher_id); + + /** + * Publisher key is missing + */ + media_key = "missing"; + success = publisher_info_database_->InsertOrUpdateMediaPublisherInfo( + media_key, + ""); + EXPECT_FALSE(success); + + query = "SELECT * FROM media_publisher_info WHERE media_key=?"; + sql::Statement info_sql_2(GetDB().GetUniqueStatement(query.c_str())); + + info_sql_2.BindString(0, media_key); + + EXPECT_FALSE(info_sql_2.Step()); + + /** + * Media key is missing + */ + publisher_id = "new_stuff"; + success = publisher_info_database_->InsertOrUpdateMediaPublisherInfo( + "", + publisher_id); + EXPECT_FALSE(success); + + query = "SELECT * FROM media_publisher_info WHERE publisher_id=?"; + sql::Statement info_sql_3(GetDB().GetUniqueStatement(query.c_str())); + + info_sql_3.BindString(0, publisher_id); + + EXPECT_FALSE(info_sql_3.Step()); +} + +TEST_F(PublisherInfoDatabaseTest, InsertOrUpdateRecurringDonation) { + /** + * Good path + */ + base::ScopedTempDir temp_dir; + base::FilePath db_file; + CreateTempDatabase(&temp_dir, &db_file); + + brave_rewards::RecurringDonation info; + info.publisher_key = "key"; + info.amount = 20; + info.added_date = base::Time::Now().ToJsTime(); + + bool success = publisher_info_database_->InsertOrUpdateRecurringDonation( + info); + EXPECT_TRUE(success); + + std::string query = "SELECT * FROM recurring_donation WHERE publisher_id=?"; + sql::Statement info_sql(GetDB().GetUniqueStatement(query.c_str())); + + info_sql.BindString(0, info.publisher_key); + + EXPECT_TRUE(info_sql.Step()); + EXPECT_EQ(CountTableRows("recurring_donation"), 1); + EXPECT_EQ(info_sql.ColumnString(0), info.publisher_key); + EXPECT_EQ(info_sql.ColumnDouble(1), info.amount); + EXPECT_EQ(info_sql.ColumnInt64(2), info.added_date); + + /** + * Make sure that second insert is update and not insert + */ + info.amount = 30; + + success = publisher_info_database_->InsertOrUpdateRecurringDonation(info); + EXPECT_TRUE(success); + + query ="SELECT * FROM recurring_donation WHERE publisher_id=?"; + sql::Statement info_sql_1(GetDB().GetUniqueStatement(query.c_str())); + + info_sql_1.BindString(0, info.publisher_key); + + EXPECT_TRUE(info_sql_1.Step()); + EXPECT_EQ(CountTableRows("recurring_donation"), 1); + EXPECT_EQ(info_sql_1.ColumnString(0), info.publisher_key); + EXPECT_EQ(info_sql_1.ColumnDouble(1), info.amount); + EXPECT_EQ(info_sql_1.ColumnInt64(2), info.added_date); + + /** + * Publisher key is missing + */ + info.publisher_key = ""; + success = publisher_info_database_->InsertOrUpdateRecurringDonation(info); + EXPECT_FALSE(success); + + query = "SELECT * FROM recurring_donation WHERE publisher_id=?"; + sql::Statement info_sql_2(GetDB().GetUniqueStatement(query.c_str())); + + info_sql_2.BindString(0, info.publisher_key); + + EXPECT_FALSE(info_sql_2.Step()); +} + +TEST_F(PublisherInfoDatabaseTest, InsertPendingContribution) { + +} + +} // namespace brave_rewards diff --git a/components/brave_rewards/browser/rewards_notification_service_impl.cc b/components/brave_rewards/browser/rewards_notification_service_impl.cc index cf4237ac5186..b1674048d2f8 100644 --- a/components/brave_rewards/browser/rewards_notification_service_impl.cc +++ b/components/brave_rewards/browser/rewards_notification_service_impl.cc @@ -312,7 +312,7 @@ void RewardsNotificationServiceImpl::OnReconcileComplete( const std::string& probi) { if ((result == ledger::Result::LEDGER_OK && category == - std::to_string(ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE)) || + std::to_string(ledger::REWARDS_CATEGORY::AUTO_CONTRIBUTE)) || result == ledger::Result::LEDGER_ERROR || result == ledger::Result::NOT_ENOUGH_FUNDS || result == ledger::Result::TIP_ERROR) { diff --git a/components/brave_rewards/browser/rewards_service.h b/components/brave_rewards/browser/rewards_service.h index 8b8cc520e6bb..9ba514111219 100644 --- a/components/brave_rewards/browser/rewards_service.h +++ b/components/brave_rewards/browser/rewards_service.h @@ -38,7 +38,7 @@ bool IsMediaLink(const GURL& url, class RewardsNotificationService; class RewardsServiceObserver; -using GetCurrentContributeListCallback = +using GetContentSiteListCallback = base::Callback, uint32_t /* next_record */)>; using GetAllBalanceReportsCallback = base::Callback -LoadMediaPublisherInfoListOnFileTaskRunner( +LoadPublisherInfoOnFileTaskRunner( + const std::string publisher_key, + PublisherInfoDatabase* backend) { + if (!backend) + return nullptr; + + return backend->GetPublisherInfo(publisher_key); +} + +std::unique_ptr +LoadMediaPublisherInfoOnFileTaskRunner( const std::string media_key, PublisherInfoDatabase* backend) { std::unique_ptr info; if (!backend) return info; - info = backend->GetMediaPublisherInfo(media_key); - return info; + return backend->GetMediaPublisherInfo(media_key); } bool SavePublisherInfoOnFileTaskRunner( @@ -199,19 +208,39 @@ bool SavePublisherInfoOnFileTaskRunner( return false; } -ledger::PublisherInfoList LoadPublisherInfoListOnFileTaskRunner( +bool SaveActivityInfoOnFileTaskRunner( + const ledger::PublisherInfo publisher_info, + PublisherInfoDatabase* backend) { + if (backend && backend->InsertOrUpdateActivityInfo(publisher_info)) + return true; + + return false; +} + +ledger::PublisherInfoList GetActivityListOnFileTaskRunner( uint32_t start, uint32_t limit, - ledger::PublisherInfoFilter filter, + ledger::ActivityInfoFilter filter, PublisherInfoDatabase* backend) { ledger::PublisherInfoList list; if (!backend) return list; - ignore_result(backend->Find(start, limit, filter, &list)); + ignore_result(backend->GetActivityList(start, limit, filter, &list)); return list; } +std::unique_ptr GetPanelPublisherInfoOnFileTaskRunner( + ledger::ActivityInfoFilter filter, + PublisherInfoDatabase* backend) { + ledger::PublisherInfoList list; + if (!backend) { + return nullptr; + } + + return backend->GetPanelPublisher(filter); +} + // `callback` has a WeakPtr so this won't crash if the file finishes // writing after RewardsServiceImpl has been destroyed void PostWriteCallback( @@ -224,20 +253,6 @@ void PostWriteCallback( base::Bind(callback, write_success)); } -void GetContentSiteListInternal( - uint32_t start, - uint32_t limit, - const GetCurrentContributeListCallback& callback, - const ledger::PublisherInfoList& publisher_list, - uint32_t next_record) { - std::unique_ptr site_list(new ContentSiteList); - for (ledger::PublisherInfoList::const_iterator it = - publisher_list.begin(); it != publisher_list.end(); ++it) { - site_list->push_back(PublisherInfoToContentSite(*it)); - } - callback.Run(std::move(site_list), next_record); -} - time_t GetCurrentTimestamp() { return base::Time::NowFromSystemTime().ToTimeT(); } @@ -404,52 +419,44 @@ void RewardsServiceImpl::CreateWallet() { } } -void RewardsServiceImpl::GetCurrentContributeList( +void RewardsServiceImpl::GetContentSiteList( uint32_t start, uint32_t limit, uint64_t min_visit_time, uint64_t reconcile_stamp, bool allow_non_verified, - const GetCurrentContributeListCallback& callback) { - if (!Connected()) { - return; - } - - ledger::PublisherInfoFilter filter; - filter.category = ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE; - filter.month = ledger::PUBLISHER_MONTH::ANY; + const GetContentSiteListCallback& callback) { + ledger::ActivityInfoFilter filter; + filter.month = ledger::ACTIVITY_MONTH::ANY; filter.year = -1; filter.min_duration = min_visit_time; filter.order_by.push_back(std::pair("ai.percent", false)); filter.reconcile_stamp = reconcile_stamp; filter.excluded = - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED; + ledger::EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED; filter.percent = 1; filter.non_verified = allow_non_verified; - bat_ledger_->GetPublisherInfoList(start, limit, - filter.ToJson(), - base::BindOnce(&RewardsServiceImpl::OnGetPublisherInfoList, AsWeakPtr(), - start, - limit, - callback)); + GetActivityInfoList(start, limit, + filter, + std::bind(&RewardsServiceImpl::OnGetContentSiteList, + this, + callback, + std::placeholders::_1, + std::placeholders::_2)); } -void RewardsServiceImpl::OnGetPublisherInfoList( - uint32_t start, uint32_t limit, - const GetCurrentContributeListCallback& callback, - const std::vector& publisher_info_list, +void RewardsServiceImpl::OnGetContentSiteList( + const GetContentSiteListCallback& callback, + const ledger::PublisherInfoList& list, uint32_t next_record) { - ledger::PublisherInfoList list; - - for (const auto& i : publisher_info_list) { - ledger::PublisherInfo info; - info.loadFromJson(i); - list.push_back(info); + std::unique_ptr site_list(new ContentSiteList); + for (ledger::PublisherInfoList::const_iterator it = + list.begin(); it != list.end(); ++it) { + site_list->push_back(PublisherInfoToContentSite(*it)); } - GetContentSiteListInternal(start, limit, callback, std::move(list), - next_record); + callback.Run(std::move(site_list), next_record); } void RewardsServiceImpl::OnLoad(SessionID tab_id, const GURL& url) { @@ -593,11 +600,33 @@ void RewardsServiceImpl::OnXHRLoad(SessionID tab_id, data.ToJson()); } +void RewardsServiceImpl::LoadPublisherInfo( + const std::string& publisher_key, + ledger::PublisherInfoCallback callback) { + base::PostTaskAndReplyWithResult(file_task_runner_.get(), FROM_HERE, + base::Bind(&LoadPublisherInfoOnFileTaskRunner, + publisher_key, publisher_info_backend_.get()), + base::Bind(&RewardsServiceImpl::OnPublisherInfoLoaded, + AsWeakPtr(), + callback)); +} + +void RewardsServiceImpl::OnPublisherInfoLoaded( + ledger::PublisherInfoCallback callback, + std::unique_ptr info) { + if (!info) { + callback(ledger::Result::NOT_FOUND, nullptr); + return; + } + + callback(ledger::Result::LEDGER_OK, std::move(info)); +} + void RewardsServiceImpl::LoadMediaPublisherInfo( const std::string& media_key, ledger::PublisherInfoCallback callback) { base::PostTaskAndReplyWithResult(file_task_runner_.get(), FROM_HERE, - base::Bind(&LoadMediaPublisherInfoListOnFileTaskRunner, + base::Bind(&LoadMediaPublisherInfoOnFileTaskRunner, media_key, publisher_info_backend_.get()), base::Bind(&RewardsServiceImpl::OnMediaPublisherInfoLoaded, AsWeakPtr(), @@ -611,7 +640,7 @@ void RewardsServiceImpl::OnMediaPublisherInfoLoaded( return; if (!info) { - callback(ledger::Result::NOT_FOUND, std::move(info)); + callback(ledger::Result::NOT_FOUND, nullptr); return; } @@ -763,7 +792,7 @@ void RewardsServiceImpl::OnGrantFinish(ledger::Result result, void RewardsServiceImpl::OnReconcileComplete(ledger::Result result, const std::string& viewing_id, - ledger::PUBLISHER_CATEGORY category, + ledger::REWARDS_CATEGORY category, const std::string& probi) { if (result == ledger::Result::LEDGER_OK) { auto now = base::Time::Now(); @@ -900,8 +929,7 @@ void RewardsServiceImpl::LoadNicewareList( LOG(ERROR) << "Failed to read in niceware list"; } callback(data.empty() ? ledger::Result::LEDGER_ERROR - : ledger::Result::LEDGER_OK, - data); + : ledger::Result::LEDGER_OK, data); } void RewardsServiceImpl::SavePublisherInfo( @@ -931,20 +959,45 @@ void RewardsServiceImpl::OnPublisherInfoSaved( TriggerOnContentSiteUpdated(); } -void RewardsServiceImpl::LoadPublisherInfo( - ledger::PublisherInfoFilter filter, +void RewardsServiceImpl::SaveActivityInfo( + std::unique_ptr publisher_info, + ledger::PublisherInfoCallback callback) { + ledger::PublisherInfo info_copy = *publisher_info; + base::PostTaskAndReplyWithResult(file_task_runner_.get(), FROM_HERE, + base::Bind(&SaveActivityInfoOnFileTaskRunner, + info_copy, + publisher_info_backend_.get()), + base::Bind(&RewardsServiceImpl::OnActivityInfoSaved, + AsWeakPtr(), + callback, + base::Passed(std::move(publisher_info)))); + +} + +void RewardsServiceImpl::OnActivityInfoSaved( + ledger::PublisherInfoCallback callback, + std::unique_ptr info, + bool success) { + callback(success ? ledger::Result::LEDGER_OK + : ledger::Result::LEDGER_ERROR, std::move(info)); + + TriggerOnContentSiteUpdated(); +} + +void RewardsServiceImpl::LoadActivityInfo( + ledger::ActivityInfoFilter filter, ledger::PublisherInfoCallback callback) { base::PostTaskAndReplyWithResult(file_task_runner_.get(), FROM_HERE, - base::Bind(&LoadPublisherInfoListOnFileTaskRunner, + base::Bind(&GetActivityListOnFileTaskRunner, // set limit to 2 to make sure there is // only 1 valid result for the filter 0, 2, filter, publisher_info_backend_.get()), - base::Bind(&RewardsServiceImpl::OnPublisherInfoLoaded, + base::Bind(&RewardsServiceImpl::OnActivityInfoLoaded, AsWeakPtr(), callback)); } -void RewardsServiceImpl::OnPublisherInfoLoaded( +void RewardsServiceImpl::OnActivityInfoLoaded( ledger::PublisherInfoCallback callback, const ledger::PublisherInfoList list) { if (!Connected()) { @@ -965,13 +1018,37 @@ void RewardsServiceImpl::OnPublisherInfoLoaded( std::make_unique(list[0])); } -void RewardsServiceImpl::LoadPublisherInfoList( +void RewardsServiceImpl::LoadPanelPublisherInfo( + ledger::ActivityInfoFilter filter, + ledger::PublisherInfoCallback callback) { + base::PostTaskAndReplyWithResult(file_task_runner_.get(), FROM_HERE, + base::Bind(&GetPanelPublisherInfoOnFileTaskRunner, + filter, + publisher_info_backend_.get()), + base::Bind(&RewardsServiceImpl::OnPanelPublisherInfoLoaded, + AsWeakPtr(), + callback)); +} + +void RewardsServiceImpl::OnPanelPublisherInfoLoaded( + ledger::PublisherInfoCallback callback, + std::unique_ptr publisher_info) { + if (!publisher_info) { + callback(ledger::Result::NOT_FOUND, + std::unique_ptr()); + return; + } + + callback(ledger::Result::LEDGER_OK, std::move(publisher_info)); +} + +void RewardsServiceImpl::GetActivityInfoList( uint32_t start, uint32_t limit, - ledger::PublisherInfoFilter filter, + ledger::ActivityInfoFilter filter, ledger::PublisherInfoListCallback callback) { base::PostTaskAndReplyWithResult(file_task_runner_.get(), FROM_HERE, - base::Bind(&LoadPublisherInfoListOnFileTaskRunner, + base::Bind(&GetActivityListOnFileTaskRunner, start, limit, filter, publisher_info_backend_.get()), base::Bind(&RewardsServiceImpl::OnPublisherInfoListLoaded, @@ -1762,7 +1839,7 @@ void RewardsServiceImpl::OnDonate(const std::string& publisher_key, int amount, ledger::PublisherInfo publisher( publisher_key, - ledger::PUBLISHER_MONTH::ANY, + ledger::ACTIVITY_MONTH::ANY, -1); bat_ledger_->DoDirectDonation(publisher.ToJson(), amount, "BAT"); @@ -1776,8 +1853,8 @@ bool SaveContributionInfoOnFileTaskRunner(const brave_rewards::ContributionInfo return false; } -void RewardsServiceImpl::OnContributionInfoSaved(const ledger::PUBLISHER_CATEGORY category, bool success) { - if (success && category == ledger::PUBLISHER_CATEGORY::DIRECT_DONATION) { +void RewardsServiceImpl::OnContributionInfoSaved(const ledger::REWARDS_CATEGORY category, bool success) { + if (success && category == ledger::REWARDS_CATEGORY::DIRECT_DONATION) { TipsUpdated(); } } @@ -1787,7 +1864,7 @@ void RewardsServiceImpl::SaveContributionInfo(const std::string& probi, const int year, const uint32_t date, const std::string& publisher_key, - const ledger::PUBLISHER_CATEGORY category) { + const ledger::REWARDS_CATEGORY category) { brave_rewards::ContributionInfo info; info.probi = probi; @@ -2153,7 +2230,7 @@ void RewardsServiceImpl::OnDonate( ledger::PublisherInfo info; info.id = publisher_key; - info.month = ledger::PUBLISHER_MONTH::ANY; + info.month = ledger::ACTIVITY_MONTH::ANY; info.year = -1; info.verified = site->verified; info.excluded = ledger::PUBLISHER_EXCLUDE::DEFAULT; @@ -2254,4 +2331,33 @@ void RewardsServiceImpl::GetPendingContributionsTotal( callback); } +bool RestorePublisherOnFileTaskRunner(PublisherInfoDatabase* backend) { + if (!backend) { + return false; + } + + return backend->RestorePublishers(); +} + +void RewardsServiceImpl::OnRestorePublishers(ledger::OnRestoreCallback callback) { + base::PostTaskAndReplyWithResult( + file_task_runner_.get(), + FROM_HERE, + base::Bind(&RestorePublisherOnFileTaskRunner, + publisher_info_backend_.get()), + base::Bind(&RewardsServiceImpl::OnRestorePublishersInternal, + AsWeakPtr(), + callback)); +} + +void RewardsServiceImpl::OnRestorePublishersInternal( + ledger::OnRestoreCallback callback, + bool result) { + callback(result); + + if (result) { + TriggerOnContentSiteUpdated(); + } +} + } // namespace brave_rewards diff --git a/components/brave_rewards/browser/rewards_service_impl.h b/components/brave_rewards/browser/rewards_service_impl.h index 76634749d535..f3fcab236d99 100644 --- a/components/brave_rewards/browser/rewards_service_impl.h +++ b/components/brave_rewards/browser/rewards_service_impl.h @@ -89,13 +89,17 @@ class RewardsServiceImpl : public RewardsService, void GetNumExcludedSites( const GetNumExcludedSitesCallback& callback) override; void RecoverWallet(const std::string passPhrase) const override; - void GetCurrentContributeList( + void GetContentSiteList( uint32_t start, uint32_t limit, uint64_t min_visit_time, uint64_t reconcile_stamp, bool allow_non_verified, - const GetCurrentContributeListCallback& callback) override; + const GetContentSiteListCallback& callback) override; + void OnGetContentSiteList( + const GetContentSiteListCallback& callback, + const ledger::PublisherInfoList& list, + uint32_t next_record); void OnLoad(SessionID tab_id, const GURL& url) override; void OnUnload(SessionID tab_id) override; void OnShow(SessionID tab_id) override; @@ -126,6 +130,9 @@ class RewardsServiceImpl : public RewardsService, const GetPublisherAllowNonVerifiedCallback& callback) override; void GetPublisherAllowVideos( const GetPublisherAllowVideosCallback& callback) override; + void LoadPublisherInfo( + const std::string& publisher_key, + ledger::PublisherInfoCallback callback) override; void LoadMediaPublisherInfo( const std::string& media_key, ledger::PublisherInfoCallback callback) override; @@ -195,9 +202,14 @@ class RewardsServiceImpl : public RewardsService, void OnPublisherInfoSaved(ledger::PublisherInfoCallback callback, std::unique_ptr info, bool success); - void OnPublisherInfoLoaded(ledger::PublisherInfoCallback callback, + void OnActivityInfoSaved(ledger::PublisherInfoCallback callback, + std::unique_ptr info, + bool success); + void OnActivityInfoLoaded(ledger::PublisherInfoCallback callback, const ledger::PublisherInfoList list); void OnMediaPublisherInfoSaved(bool success); + void OnPublisherInfoLoaded(ledger::PublisherInfoCallback callback, + std::unique_ptr info); void OnMediaPublisherInfoLoaded(ledger::PublisherInfoCallback callback, std::unique_ptr info); void OnPublisherInfoListLoaded(uint32_t start, @@ -215,7 +227,7 @@ class RewardsServiceImpl : public RewardsService, std::unique_ptr info); void OnDonate(const std::string& publisher_key, int amount, bool recurring, const ledger::PublisherInfo* publisher_info = NULL) override; - void OnContributionInfoSaved(const ledger::PUBLISHER_CATEGORY category, bool success); + void OnContributionInfoSaved(const ledger::REWARDS_CATEGORY category, bool success); void OnRecurringDonationSaved(bool success); void SaveRecurringDonation(const std::string& publisher_key, const int amount); void OnRecurringDonationsData(const ledger::PublisherInfoListCallback callback, @@ -232,6 +244,8 @@ class RewardsServiceImpl : public RewardsService, uint64_t windowId); void MaybeShowBackupNotification(uint64_t boot_stamp); void MaybeShowAddFundsNotification(uint64_t reconcile_stamp); + void OnRestorePublishersInternal(ledger::OnRestoreCallback callback, + bool result); // ledger::LedgerClient std::string GenerateGUID() const override; @@ -243,7 +257,7 @@ class RewardsServiceImpl : public RewardsService, const std::vector& grants) override; void OnReconcileComplete(ledger::Result result, const std::string& viewing_id, - ledger::PUBLISHER_CATEGORY category, + ledger::REWARDS_CATEGORY category, const std::string& probi) override; void OnGrantFinish(ledger::Result result, const ledger::Grant& grant) override; @@ -256,12 +270,16 @@ class RewardsServiceImpl : public RewardsService, void SavePublisherInfo(std::unique_ptr publisher_info, ledger::PublisherInfoCallback callback) override; - void LoadPublisherInfo(ledger::PublisherInfoFilter filter, + void SaveActivityInfo(std::unique_ptr publisher_info, + ledger::PublisherInfoCallback callback) override; + void LoadActivityInfo(ledger::ActivityInfoFilter filter, ledger::PublisherInfoCallback callback) override; - void LoadPublisherInfoList( + void LoadPanelPublisherInfo(ledger::ActivityInfoFilter filter, + ledger::PublisherInfoCallback callback) override; + void GetActivityInfoList( uint32_t start, uint32_t limit, - ledger::PublisherInfoFilter filter, + ledger::ActivityInfoFilter filter, ledger::PublisherInfoListCallback callback) override; void SavePublishersList(const std::string& publishers_list, ledger::LedgerCallbackHandler* handler) override; @@ -303,12 +321,16 @@ class RewardsServiceImpl : public RewardsService, const int year, const uint32_t date, const std::string& publisher_key, - const ledger::PUBLISHER_CATEGORY category) override; + const ledger::REWARDS_CATEGORY category) override; void GetRecurringDonations(ledger::PublisherInfoListCallback callback) override; std::unique_ptr Log( const char* file, int line, const ledger::LogLevel log_level) const override; + void OnRestorePublishers(ledger::OnRestoreCallback callback) override; + void OnPanelPublisherInfoLoaded( + ledger::PublisherInfoCallback callback, + std::unique_ptr publisher_info); void SavePendingContribution( const ledger::PendingContributionList& list) override; @@ -328,10 +350,6 @@ class RewardsServiceImpl : public RewardsService, // Mojo Proxy methods void OnPublisherBannerMojoProxy(const std::string& banner); - void OnGetPublisherInfoList(uint32_t start, uint32_t limit, - const GetCurrentContributeListCallback& callback, - const std::vector& publisher_info_list, - uint32_t next_record); void OnGetAllBalanceReports( const GetAllBalanceReportsCallback& callback, const base::flat_map& json_reports); diff --git a/components/brave_rewards/resources/extension/brave_rewards/background/reducers/rewards_panel_reducer.ts b/components/brave_rewards/resources/extension/brave_rewards/background/reducers/rewards_panel_reducer.ts index c1dd1e9eb912..44687bbcd2c6 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/background/reducers/rewards_panel_reducer.ts +++ b/components/brave_rewards/resources/extension/brave_rewards/background/reducers/rewards_panel_reducer.ts @@ -25,8 +25,6 @@ const getWindowId = (id: number) => { return `id_${id}` } -let currentPublishers: string[] = [] - export const rewardsPanelReducer = (state: RewardsExtension.State | undefined, action: any) => { if (state === undefined) { state = storage.load() @@ -73,16 +71,19 @@ export const rewardsPanelReducer = (state: RewardsExtension.State | undefined, a break } - chrome.braveRewards.getPublisherData(tab.windowId, tab.url, tab.favIconUrl || '') const id = getWindowId(tab.windowId) - let publishers: Record = state.publishers + const publishers: Record = state.publishers + const publisher = publishers[id] + chrome.braveRewards.getPublisherData(tab.windowId, tab.url, tab.favIconUrl || '') + if (!publisher || (publisher && publisher.tabUrl !== tab.url)) { + if (publisher) { + delete publishers[id] + } - if (publishers[id] && currentPublishers[id] !== tab.url) { - delete publishers[id] + publishers[id] = { + tabUrl: tab.url + } } - - currentPublishers[id] = tab.url - state = { ...state, publishers @@ -98,7 +99,7 @@ export const rewardsPanelReducer = (state: RewardsExtension.State | undefined, a if (publisher && !publisher.publisher_key) { delete publishers[id] } else { - publishers[id] = publisher + publishers[id] = { ...publishers[id], ...publisher } } state = { diff --git a/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx b/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx index 7c5bd697c5d1..cc6fa1724815 100644 --- a/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx +++ b/components/brave_rewards/resources/extension/brave_rewards/components/panel.tsx @@ -188,9 +188,10 @@ export class Panel extends React.Component { return } const tabId = tabs[0].id - if (tabId === undefined || !publisher) { + if (tabId === undefined || !publisher || !publisher.publisher_key) { return } + chrome.braveRewards.donateToSite(tabId, publisher.publisher_key) window.close() }) diff --git a/components/brave_rewards/resources/ui/reducers/publishers_reducer.ts b/components/brave_rewards/resources/ui/reducers/publishers_reducer.ts index 5d264611d65d..d62e4c9b1e56 100644 --- a/components/brave_rewards/resources/ui/reducers/publishers_reducer.ts +++ b/components/brave_rewards/resources/ui/reducers/publishers_reducer.ts @@ -34,15 +34,17 @@ const publishersReducer: Reducer = (state: Rewards.St state.numExcludedSites = parseInt(newNum, 10) - if (previousNum < newNum) { - // On a new excluded publisher, add to excluded state - if (!state.excluded.includes(publisherKey)) { - state.excluded.push(publisherKey) - } - } else { - // Remove the publisher from excluded if it has been re-included - if (state.excluded.includes(publisherKey)) { - state.excluded = state.excluded.filter((key: string) => key !== publisherKey) + if (publisherKey.length > 0) { + if (previousNum < newNum) { + // On a new excluded publisher, add to excluded state + if (!state.excluded.includes(publisherKey)) { + state.excluded.push(publisherKey) + } + } else { + // Remove the publisher from excluded if it has been re-included + if (state.excluded.includes(publisherKey)) { + state.excluded = state.excluded.filter((key: string) => key !== publisherKey) + } } } diff --git a/components/definitions/rewardsExtensions.d.ts b/components/definitions/rewardsExtensions.d.ts index ceeeca73a0ee..1cd27753a782 100644 --- a/components/definitions/rewardsExtensions.d.ts +++ b/components/definitions/rewardsExtensions.d.ts @@ -22,14 +22,15 @@ declare namespace RewardsExtension { } interface Publisher { - excluded: boolean - favicon_url: string - publisher_key: string - name: string - percentage: number - provider: string - url: string - verified: boolean + excluded?: boolean + favicon_url?: string + publisher_key?: string + name?: string + percentage?: number + provider?: string + tabUrl?: string + url?: string + verified?: boolean } export interface Grant { 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 bb2cca4e40bb..e2be5e50ba00 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc +++ b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.cc @@ -4,6 +4,8 @@ #include "brave/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h" +#include + #include "base/logging.h" #include "mojo/public/cpp/bindings/map.h" @@ -19,7 +21,7 @@ ledger::Result ToLedgerResult(int32_t result) { return (ledger::Result)result; } -int32_t ToMojomPublisherCategory(ledger::PUBLISHER_CATEGORY category) { +int32_t ToMojomPublisherCategory(ledger::REWARDS_CATEGORY category) { return (int32_t)category; } @@ -144,7 +146,7 @@ void BatLedgerClientMojoProxy::OnRecoverWallet(ledger::Result result, void BatLedgerClientMojoProxy::OnReconcileComplete(ledger::Result result, const std::string& viewing_id, - ledger::PUBLISHER_CATEGORY category, + ledger::REWARDS_CATEGORY category, const std::string& probi) { if (!Connected()) return; @@ -311,7 +313,7 @@ void OnLoadPublisherInfo(const ledger::PublisherInfoCallback& callback, } void BatLedgerClientMojoProxy::LoadPublisherInfo( - ledger::PublisherInfoFilter filter, + const std::string& publisher_key, ledger::PublisherInfoCallback callback) { if (!Connected()) { callback(ledger::Result::LEDGER_ERROR, @@ -319,36 +321,33 @@ void BatLedgerClientMojoProxy::LoadPublisherInfo( return; } - bat_ledger_client_->LoadPublisherInfo(filter.ToJson(), + bat_ledger_client_->LoadPublisherInfo(publisher_key, base::BindOnce(&OnLoadPublisherInfo, std::move(callback))); } -void OnLoadPublisherInfoList(const ledger::PublisherInfoListCallback& callback, - const std::vector& publisher_info_list, - uint32_t next_record) { - ledger::PublisherInfoList list; +void OnLoadPanelPublisherInfo(const ledger::PublisherInfoCallback& callback, + int32_t result, const std::string& publisher_info) { + std::unique_ptr info; - for (const auto& publisher_info : publisher_info_list) { - ledger::PublisherInfo info; - info.loadFromJson(publisher_info); - list.push_back(info); + if (!publisher_info.empty()) { + info.reset(new ledger::PublisherInfo()); + info->loadFromJson(publisher_info); } - callback(list, next_record); + callback(ToLedgerResult(result), std::move(info)); } -void BatLedgerClientMojoProxy::LoadPublisherInfoList( - uint32_t start, - uint32_t limit, - ledger::PublisherInfoFilter filter, - ledger::PublisherInfoListCallback callback) { +void BatLedgerClientMojoProxy::LoadPanelPublisherInfo( + ledger::ActivityInfoFilter filter, + ledger::PublisherInfoCallback callback) { if (!Connected()) { - callback(std::vector(), 0); + callback(ledger::Result::LEDGER_ERROR, + std::unique_ptr()); return; } - bat_ledger_client_->LoadPublisherInfoList(start, limit, filter.ToJson(), - base::BindOnce(&OnLoadPublisherInfoList, std::move(callback))); + bat_ledger_client_->LoadPanelPublisherInfo(filter.ToJson(), + base::BindOnce(&OnLoadPanelPublisherInfo, std::move(callback))); } void OnLoadMediaPublisherInfo(const ledger::PublisherInfoCallback& callback, @@ -484,7 +483,7 @@ void BatLedgerClientMojoProxy::SaveContributionInfo(const std::string& probi, const int year, const uint32_t date, const std::string& publisher_key, - const ledger::PUBLISHER_CATEGORY category) { + const ledger::REWARDS_CATEGORY category) { if (!Connected()) return; @@ -548,6 +547,98 @@ void BatLedgerClientMojoProxy::SavePendingContribution( bat_ledger_client_->SavePendingContribution(list.ToJson()); } +void OnLoadActivityInfo(const ledger::PublisherInfoCallback& callback, + int32_t result, const std::string& publisher_info) { + std::unique_ptr info; + if (!publisher_info.empty()) { + info.reset(new ledger::PublisherInfo()); + info->loadFromJson(publisher_info); + } + callback(ToLedgerResult(result), std::move(info)); +} + +void BatLedgerClientMojoProxy::LoadActivityInfo( + ledger::ActivityInfoFilter filter, + ledger::PublisherInfoCallback callback) { + if (!Connected()) { + callback(ledger::Result::LEDGER_ERROR, + std::unique_ptr()); + return; + } + + bat_ledger_client_->LoadPublisherInfo(filter.ToJson(), + base::BindOnce(&OnLoadActivityInfo, std::move(callback))); +} + +void OnSaveActivityInfo(const ledger::PublisherInfoCallback& callback, + int32_t result, const std::string& publisher_info) { + std::unique_ptr info; + if (!publisher_info.empty()) { + info.reset(new ledger::PublisherInfo()); + info->loadFromJson(publisher_info); + } + callback(ToLedgerResult(result), std::move(info)); +} + +void BatLedgerClientMojoProxy::SaveActivityInfo( + std::unique_ptr publisher_info, + ledger::PublisherInfoCallback callback) { + if (!Connected()) { + callback(ledger::Result::LEDGER_ERROR, + std::unique_ptr()); + return; + } + + std::string json_info = publisher_info ? publisher_info->ToJson() : ""; + bat_ledger_client_->SaveActivityInfo(json_info, + base::BindOnce(&OnSaveActivityInfo, std::move(callback))); +} + +void OnRestorePublishersDone(const ledger::OnRestoreCallback& callback, + bool result) { + callback(result); +} + +void BatLedgerClientMojoProxy::OnRestorePublishers( + ledger::OnRestoreCallback callback) { + if (!Connected()) { + callback(false); + return; + } + + bat_ledger_client_->OnRestorePublishers( + base::BindOnce(&OnRestorePublishersDone, std::move(callback))); +} + +void OnGetActivityInfoList(const ledger::PublisherInfoListCallback& callback, + const std::vector& publisher_info_list, + uint32_t next_record) { + ledger::PublisherInfoList list; + + for (const auto& publisher_info : publisher_info_list) { + ledger::PublisherInfo info; + info.loadFromJson(publisher_info); + list.push_back(info); + } + + callback(list, next_record); +} + +void BatLedgerClientMojoProxy::GetActivityInfoList(uint32_t start, + uint32_t limit, + ledger::ActivityInfoFilter filter, + ledger::PublisherInfoListCallback callback) { + if (!Connected()) { + callback(std::vector(), 0); + return; + } + + bat_ledger_client_->GetActivityInfoList(start, + limit, + filter.ToJson(), + base::BindOnce(&OnGetActivityInfoList, std::move(callback))); +} + bool BatLedgerClientMojoProxy::Connected() const { return bat_ledger_client_.is_bound(); } 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 2b8a16f5be0b..916ab58d0aeb 100644 --- a/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h +++ b/components/services/bat_ledger/bat_ledger_client_mojo_proxy.h @@ -34,7 +34,7 @@ class BatLedgerClientMojoProxy : public ledger::LedgerClient, const std::vector& grants) override; void OnReconcileComplete(ledger::Result result, const std::string& viewing_id, - ledger::PUBLISHER_CATEGORY category, + ledger::REWARDS_CATEGORY category, const std::string& probi) override; void OnGrantFinish(ledger::Result result, const ledger::Grant& grant) override; @@ -47,13 +47,10 @@ class BatLedgerClientMojoProxy : public ledger::LedgerClient, void SavePublisherInfo(std::unique_ptr publisher_info, ledger::PublisherInfoCallback callback) override; - void LoadPublisherInfo(ledger::PublisherInfoFilter filter, + void LoadPublisherInfo(const std::string& publisher_key, ledger::PublisherInfoCallback callback) override; - void LoadPublisherInfoList( - uint32_t start, - uint32_t limit, - ledger::PublisherInfoFilter filter, - ledger::PublisherInfoListCallback callback) override; + void LoadPanelPublisherInfo(ledger::ActivityInfoFilter filter, + ledger::PublisherInfoCallback callback) override; void SavePublishersList(const std::string& publishers_list, ledger::LedgerCallbackHandler* handler) override; void SetTimer(uint64_t time_offset, uint32_t& timer_id) override; @@ -78,7 +75,7 @@ class BatLedgerClientMojoProxy : public ledger::LedgerClient, const int year, const uint32_t date, const std::string& publisher_key, - const ledger::PUBLISHER_CATEGORY category) override; + const ledger::REWARDS_CATEGORY category) override; void GetRecurringDonations(ledger::PublisherInfoListCallback callback) override; std::unique_ptr Log(const char* file, int line, ledger::LogLevel level) const override; void LoadMediaPublisherInfo( @@ -98,6 +95,19 @@ class BatLedgerClientMojoProxy : public ledger::LedgerClient, void SavePendingContribution( const ledger::PendingContributionList& list) override; + void LoadActivityInfo(ledger::ActivityInfoFilter filter, + ledger::PublisherInfoCallback callback) override; + + void SaveActivityInfo(std::unique_ptr publisher_info, + ledger::PublisherInfoCallback callback) override; + + void OnRestorePublishers(ledger::OnRestoreCallback callback) override; + + void GetActivityInfoList(uint32_t start, + uint32_t limit, + ledger::ActivityInfoFilter filter, + ledger::PublisherInfoListCallback callback) override; + private: bool Connected() const; diff --git a/components/services/bat_ledger/bat_ledger_impl.cc b/components/services/bat_ledger/bat_ledger_impl.cc index 5887b2e1839e..f78082170456 100644 --- a/components/services/bat_ledger/bat_ledger_impl.cc +++ b/components/services/bat_ledger/bat_ledger_impl.cc @@ -18,16 +18,16 @@ ledger::PUBLISHER_EXCLUDE ToLedgerPublisherExclude(int32_t exclude) { return (ledger::PUBLISHER_EXCLUDE)exclude; } -ledger::PUBLISHER_MONTH ToLedgerPublisherMonth(int32_t month) { - return (ledger::PUBLISHER_MONTH)month; +ledger::ACTIVITY_MONTH ToLedgerPublisherMonth(int32_t month) { + return (ledger::ACTIVITY_MONTH)month; } ledger::ReportType ToLedgerReportType(int32_t type) { return (ledger::ReportType)type; } -ledger::PUBLISHER_CATEGORY ToLedgerPublisherCategory(int32_t category) { - return (ledger::PUBLISHER_CATEGORY)category; +ledger::REWARDS_CATEGORY ToLedgerPublisherCategory(int32_t category) { + return (ledger::REWARDS_CATEGORY)category; } } // anonymous namespace @@ -297,33 +297,6 @@ void BatLedgerImpl::GetPublisherBanner(const std::string& publisher_id, std::bind(BatLedgerImpl::OnGetPublisherBanner, holder, _1)); } -// static -void BatLedgerImpl::OnGetPublisherInfoList( - CallbackHolder* holder, - const ledger::PublisherInfoList& list, - uint32_t next_record) { - std::vector publisher_info_list; - for (const auto& info : list) { - publisher_info_list.push_back(info.ToJson()); - } - - if (holder->is_valid()) - std::move(holder->get()).Run(publisher_info_list, next_record); - delete holder; -} - -void BatLedgerImpl::GetPublisherInfoList(uint32_t start, uint32_t limit, - const std::string& filter, - GetPublisherInfoListCallback callback) { - // delete in OnGetPublisherInfoList - auto* holder = new CallbackHolder( - AsWeakPtr(), std::move(callback)); - ledger::PublisherInfoFilter publisher_info_filter; - publisher_info_filter.loadFromJson(filter); - ledger_->GetPublisherInfoList(start, limit, publisher_info_filter, - std::bind(BatLedgerImpl::OnGetPublisherInfoList, holder, _1, _2)); -} - void BatLedgerImpl::GetContributionAmount( GetContributionAmountCallback callback) { std::move(callback).Run(ledger_->GetContributionAmount()); diff --git a/components/services/bat_ledger/bat_ledger_impl.h b/components/services/bat_ledger/bat_ledger_impl.h index 8d88c568bc01..b55c7efb49c6 100644 --- a/components/services/bat_ledger/bat_ledger_impl.h +++ b/components/services/bat_ledger/bat_ledger_impl.h @@ -106,9 +106,6 @@ class BatLedgerImpl : public mojom::BatLedger, GetContributionAmountCallback callback) override; void GetPublisherBanner(const std::string& publisher_id, GetPublisherBannerCallback callback) override; - void GetPublisherInfoList(uint32_t start, uint32_t limit, - const std::string& filter, - GetPublisherInfoListCallback callback) override; void DoDirectDonation(const std::string& publisher_info, int32_t amount, const std::string& currency) override; @@ -144,11 +141,6 @@ class BatLedgerImpl : public mojom::BatLedger, CallbackHolder* holder, std::unique_ptr banner); - static void OnGetPublisherInfoList( - CallbackHolder* holder, - const ledger::PublisherInfoList& list, - uint32_t next_record); - std::unique_ptr bat_ledger_client_mojo_proxy_; std::unique_ptr ledger_; 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 a6b7d0cb145a..33079b93b8f9 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 @@ -21,8 +21,8 @@ ledger::Result ToLedgerResult(int32_t result) { return (ledger::Result)result; } -ledger::PUBLISHER_CATEGORY ToLedgerPublisherCategory(int32_t category) { - return (ledger::PUBLISHER_CATEGORY)category; +ledger::REWARDS_CATEGORY ToLedgerPublisherCategory(int32_t category) { + return (ledger::REWARDS_CATEGORY)category; } ledger::Grant ToLedgerGrant(const std::string& grant_json) { @@ -267,43 +267,34 @@ void LedgerClientMojoProxy::OnLoadPublisherInfo( } void LedgerClientMojoProxy::LoadPublisherInfo( - const std::string& filter, + const std::string& publisher_key, LoadPublisherInfoCallback callback) { // deleted in OnLoadPublisherInfo auto* holder = new CallbackHolder( AsWeakPtr(), std::move(callback)); - ledger::PublisherInfoFilter publisher_info_filter; - publisher_info_filter.loadFromJson(filter); - ledger_client_->LoadPublisherInfo(publisher_info_filter, + ledger_client_->LoadPublisherInfo(publisher_key, std::bind(LedgerClientMojoProxy::OnLoadPublisherInfo, holder, _1, _2)); } // static -void LedgerClientMojoProxy::OnLoadPublisherInfoList( - CallbackHolder* holder, - const ledger::PublisherInfoList& list, - uint32_t next_record) { - std::vector publisher_info_list; - for (const auto& info : list) { - publisher_info_list.push_back(info.ToJson()); - } - +void LedgerClientMojoProxy::OnLoadPanelPublisherInfo( + CallbackHolder* holder, + ledger::Result result, std::unique_ptr info) { + std::string json_info = info ? info->ToJson() : ""; if (holder->is_valid()) - std::move(holder->get()).Run(publisher_info_list, next_record); + std::move(holder->get()).Run(ToMojomResult(result), json_info); delete holder; } -void LedgerClientMojoProxy::LoadPublisherInfoList(uint32_t start, - uint32_t limit, - const std::string& filter, - LoadPublisherInfoListCallback callback) { - // deleted in OnLoadPublisherInfoList - auto* holder = new CallbackHolder( +void LedgerClientMojoProxy::LoadPanelPublisherInfo(const std::string& filter, + LoadPanelPublisherInfoCallback callback) { + // deleted in OnLoadPanelPublisherInfo + auto* holder = new CallbackHolder( AsWeakPtr(), std::move(callback)); - ledger::PublisherInfoFilter publisher_info_filter; + ledger::ActivityInfoFilter publisher_info_filter; publisher_info_filter.loadFromJson(filter); - ledger_client_->LoadPublisherInfoList(start, limit, publisher_info_filter, - std::bind(LedgerClientMojoProxy::OnLoadPublisherInfoList, + ledger_client_->LoadPanelPublisherInfo(publisher_info_filter, + std::bind(LedgerClientMojoProxy::OnLoadPanelPublisherInfo, holder, _1, _2)); } @@ -498,4 +489,109 @@ void LedgerClientMojoProxy::SavePendingContribution(const std::string& list) { ledger_client_->SavePendingContribution(contribution_list); } +// static +void LedgerClientMojoProxy::OnLoadActivityInfo( + CallbackHolder* holder, + ledger::Result result, + std::unique_ptr info) { + std::string json_info = info ? info->ToJson() : ""; + if (holder->is_valid()) + std::move(holder->get()).Run(ToMojomResult(result), json_info); + delete holder; +} + +void LedgerClientMojoProxy::LoadActivityInfo( + const std::string& filter, + LoadActivityInfoCallback callback) { + // deleted in OnLoadActivityInfo + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + ledger::ActivityInfoFilter publisher_info_filter; + publisher_info_filter.loadFromJson(filter); + ledger_client_->LoadActivityInfo(publisher_info_filter, + std::bind(LedgerClientMojoProxy::OnLoadActivityInfo, holder, _1, _2)); +} + +// static +void LedgerClientMojoProxy::OnSaveActivityInfo( + CallbackHolder* holder, + ledger::Result result, + std::unique_ptr info) { + std::string json_info = info ? info->ToJson() : ""; + if (holder->is_valid()) + std::move(holder->get()).Run(ToMojomResult(result), json_info); + delete holder; +} + +void LedgerClientMojoProxy::SaveActivityInfo( + const std::string& publisher_info, + SaveActivityInfoCallback callback) { + // deleted in OnSaveActivityInfo + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + std::unique_ptr info; + if (!publisher_info.empty()) { + info.reset(new ledger::PublisherInfo()); + info->loadFromJson(publisher_info); + } + + ledger_client_->SaveActivityInfo(std::move(info), + std::bind(LedgerClientMojoProxy::OnSaveActivityInfo, holder, _1, _2)); +} + +// static +void LedgerClientMojoProxy::OnRestorePublishersDone( + CallbackHolder* holder, + bool result) { + if (holder->is_valid()) + std::move(holder->get()).Run(result); + delete holder; +} + +void LedgerClientMojoProxy::OnRestorePublishers( + OnRestorePublishersCallback callback) { + // deleted in OnRestorePublishersDone + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + + ledger_client_->OnRestorePublishers( + std::bind(LedgerClientMojoProxy::OnRestorePublishersDone, holder, _1)); +} + +// static +void LedgerClientMojoProxy::OnGetActivityInfoList( + CallbackHolder* holder, + const ledger::PublisherInfoList& publisher_info_list, + uint32_t next_record) { + std::vector list; + for (const auto& publisher_info : publisher_info_list) { + list.push_back(publisher_info.ToJson()); + } + + if (holder->is_valid()) + std::move(holder->get()).Run(list, next_record); + delete holder; +} + +void LedgerClientMojoProxy::GetActivityInfoList(uint32_t start, + uint32_t limit, + const std::string& filter, + GetActivityInfoListCallback callback) { + // deleted in OnGetActivityInfoList + auto* holder = new CallbackHolder( + AsWeakPtr(), std::move(callback)); + + ledger::ActivityInfoFilter publisher_info_filter; + publisher_info_filter.loadFromJson(filter); + + ledger_client_->GetActivityInfoList(start, + limit, + publisher_info_filter, + std::bind(LedgerClientMojoProxy::OnGetActivityInfoList, + holder, + _1, + _2)); + +} + } // 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 b0d75d3d4569..4896331f53dc 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 @@ -44,11 +44,10 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, void SavePublisherInfo(const std::string& publisher_info, SavePublisherInfoCallback callback) override; - void LoadPublisherInfo(const std::string& filter, + void LoadPublisherInfo(const std::string& publisher_key, LoadPublisherInfoCallback callback) override; - void LoadPublisherInfoList(uint32_t start, uint32_t limit, - const std::string& filter, - LoadPublisherInfoListCallback callback) override; + void LoadPanelPublisherInfo(const std::string& filter, + LoadPanelPublisherInfoCallback callback) override; void LoadMediaPublisherInfo(const std::string& media_key, LoadMediaPublisherInfoCallback callback) override; @@ -90,6 +89,19 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, void SavePendingContribution( const std::string& list) override; + void LoadActivityInfo(const std::string& filter, + LoadActivityInfoCallback callback) override; + + void SaveActivityInfo(const std::string& publisher_info, + SaveActivityInfoCallback callback) override; + + void OnRestorePublishers(OnRestorePublishersCallback callback) override; + + void GetActivityInfoList(uint32_t start, + uint32_t limit, + const std::string& filter, + GetActivityInfoListCallback callback) override; + private: // workaround to pass base::OnceCallback into std::bind // also serves as a wrapper for passing ledger::LedgerCallbackHandler* @@ -129,10 +141,10 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, ledger::Result result, std::unique_ptr info); - static void OnLoadPublisherInfoList( - CallbackHolder* holder, - const ledger::PublisherInfoList& list, - uint32_t next_record); + static void OnLoadPanelPublisherInfo( + CallbackHolder* holder, + ledger::Result result, + std::unique_ptr info); static void OnLoadMediaPublisherInfo( CallbackHolder* holder, @@ -162,6 +174,25 @@ class LedgerClientMojoProxy : public mojom::BatLedgerClient, bool success, const std::string& response, const std::map& headers); + static void OnLoadActivityInfo( + CallbackHolder* holder, + ledger::Result result, + std::unique_ptr info); + + static void OnSaveActivityInfo( + CallbackHolder* holder, + ledger::Result result, + std::unique_ptr info); + + static void OnRestorePublishersDone( + CallbackHolder* holder, + bool result); + + static void OnGetActivityInfoList( + CallbackHolder* holder, + const ledger::PublisherInfoList& publisher_info_list, + uint32_t next_record); + 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 ed4064cee78f..ba4d1fe587eb 100644 --- a/components/services/bat_ledger/public/interfaces/bat_ledger.mojom +++ b/components/services/bat_ledger/public/interfaces/bat_ledger.mojom @@ -31,9 +31,6 @@ interface BatLedger { GetAutoContribute() => (bool auto_contribute); GetReconcileStamp() => (uint64 reconcile_stamp); - GetPublisherInfoList(uint32 start, uint32 limit, string filter) => ( - array publisher_info_list, uint32 next_record); - OnLoad(string visit_data, uint64 current_time); OnUnload(uint32 tab_id, uint64 current_time); OnShow(uint32 tab_id, uint64 current_time); @@ -120,9 +117,9 @@ interface BatLedgerClient { SavePublisherInfo(string publisher_info) => (int32 result, string publisher_info); - LoadPublisherInfo(string filter) => (int32 result, string publisher_info); - LoadPublisherInfoList(uint32 start, uint32 limit, string filter) => ( - array publisher_info_list, uint32 next_record); + LoadPublisherInfo(string publisher_key) => (int32 result, string publisher_info); + LoadPanelPublisherInfo(string filter) => (int32 result, + string publisher_info); LoadMediaPublisherInfo(string media_key) => (int32 result, string publisher_info); @@ -156,4 +153,14 @@ interface BatLedgerClient { uint64 window_id); SavePendingContribution(string list); + + LoadActivityInfo(string filter) => (int32 result, string publisher_info); + + SaveActivityInfo(string publisher_info) => (int32 result, + string publisher_info); + + OnRestorePublishers() => (bool result); + + GetActivityInfoList(uint32 start, uint32 limit, string filter) => ( + array publisher_info_list, uint32 next_record); }; diff --git a/components/test/brave_rewards/extension/brave_rewards/background/reducers/rewards_panel_reducer_test.ts b/components/test/brave_rewards/extension/brave_rewards/background/reducers/rewards_panel_reducer_test.ts index a1b4eefcac46..18fb93099216 100644 --- a/components/test/brave_rewards/extension/brave_rewards/background/reducers/rewards_panel_reducer_test.ts +++ b/components/test/brave_rewards/extension/brave_rewards/background/reducers/rewards_panel_reducer_test.ts @@ -21,15 +21,8 @@ describe('rewards panel reducer', () => { describe('ON_TAB_RETRIEVED', () => { describe('persist publisher info', () => { - it.skip('url is the same', () => { + it('url is the same', () => { const initState: Rewards.State = { ...defaultState, walletCreated: true } - const expectedState1: Rewards.State = { ...defaultState, walletCreated: true } - const expectedState2: Rewards.State = { - ...defaultState, - walletCreated: true, - publishers: { 1: 'clifton.io' } - } - const payload = { tab: { url: 'https://clifton.io', @@ -40,6 +33,16 @@ describe('rewards panel reducer', () => { } // first visit + const expectedState1: Rewards.State = { + ...defaultState, + walletCreated: true, + publishers: { + id_1: { + tabUrl: 'https://clifton.io' + } + } + } + let state = reducers({ rewardsPanelData: initState }, { type: types.ON_TAB_RETRIEVED, payload @@ -48,9 +51,25 @@ describe('rewards panel reducer', () => { expect(state.rewardsPanelData).toEqual(expectedState1) // imitates ON_PUBLISHER_DATA - state.rewardsPanelData.publishers = { id_1: 'clifton.io' } + state.rewardsPanelData.publishers = { + id_1: { + tabUrl: 'https://clifton.io', + name: 'Clifton' + } + } // second visit + const expectedState2: Rewards.State = { + ...defaultState, + walletCreated: true, + publishers: { + id_1: { + tabUrl: 'https://clifton.io', + name: 'Clifton' + } + } + } + state = reducers(state, { type: types.ON_TAB_RETRIEVED, payload @@ -61,9 +80,18 @@ describe('rewards panel reducer', () => { it('url is not the same', () => { const initState: Rewards.State = { ...defaultState, walletCreated: true } - const expectedState: Rewards.State = { ...defaultState, walletCreated: true } // first visit + const expectedState1: Rewards.State = { + ...defaultState, + walletCreated: true, + publishers: { + id_1: { + tabUrl: 'https://clifton.io' + } + } + } + let state = reducers({ rewardsPanelData: initState }, { type: types.ON_TAB_RETRIEVED, payload: { @@ -76,12 +104,27 @@ describe('rewards panel reducer', () => { } }) - expect(state.rewardsPanelData).toEqual(expectedState) + expect(state.rewardsPanelData).toEqual(expectedState1) // imitates ON_PUBLISHER_DATA - state.rewardsPanelData.publishers = { id_1: 'clifton.io' } + state.rewardsPanelData.publishers = { + id_1: { + tabUrl: 'clifton.io', + name: 'Clifton' + } + } // second visit + const expectedState2: Rewards.State = { + ...defaultState, + walletCreated: true, + publishers: { + id_1: { + tabUrl: 'https://brave.com' + } + } + } + state = reducers(state, { type: types.ON_TAB_RETRIEVED, payload: { @@ -94,7 +137,7 @@ describe('rewards panel reducer', () => { } }) - expect(state.rewardsPanelData).toEqual(expectedState) + expect(state.rewardsPanelData).toEqual(expectedState2) }) }) }) diff --git a/test/BUILD.gn b/test/BUILD.gn index b378de3b1b69..00f8ff73d419 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -88,6 +88,7 @@ test("brave_unit_tests") { sources += [ "//brave/vendor/bat-native-ledger/src/bat_get_media_unittest.cc", "//brave/vendor/bat-native-ledger/src/test/niceware_partial_unittest.cc", + "//brave/components/brave_rewards/browser/publisher_info_database_unittest.cc", "//brave/vendor/bat-native-usermodel/test/usermodel_unittest.cc", "//brave/components/brave_rewards/browser/rewards_service_impl_unittest.cc", ] diff --git a/vendor/bat-native-ledger/include/bat/ledger/ledger.h b/vendor/bat-native-ledger/include/bat/ledger/ledger.h index 21abe661e01e..578ee2f4cf7d 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger.h @@ -28,7 +28,7 @@ LEDGER_EXPORT struct VisitData { const std::string& _domain, const std::string& _path, uint32_t _tab_id, - PUBLISHER_MONTH _local_month, + ACTIVITY_MONTH _local_month, int _local_year, const std::string& name, const std::string& url, @@ -44,7 +44,7 @@ LEDGER_EXPORT struct VisitData { std::string domain; std::string path; uint32_t tab_id; - PUBLISHER_MONTH local_month; + ACTIVITY_MONTH local_month; int local_year; std::string name; std::string url; @@ -57,8 +57,8 @@ LEDGER_EXPORT struct PaymentData { PaymentData(const std::string& _publisher_id, const double& _value, const int64_t& _timestamp, - PUBLISHER_CATEGORY _category, - PUBLISHER_MONTH _local_month, + REWARDS_CATEGORY _category, + ACTIVITY_MONTH _local_month, int _local_year); PaymentData(const PaymentData& data); ~PaymentData(); @@ -66,8 +66,8 @@ LEDGER_EXPORT struct PaymentData { std::string publisher_id; double value; int64_t timestamp; - PUBLISHER_CATEGORY category; - PUBLISHER_MONTH local_month; + REWARDS_CATEGORY category; + ACTIVITY_MONTH local_month; int local_year; }; @@ -122,15 +122,19 @@ class LEDGER_EXPORT Ledger { virtual void SetPublisherInfo(std::unique_ptr publisher_info, PublisherInfoCallback callback) = 0; - virtual void GetPublisherInfo(const ledger::PublisherInfoFilter& filter, + virtual void SetActivityInfo(std::unique_ptr publisher_info, + PublisherInfoCallback callback) = 0; + virtual void GetPublisherInfo(const std::string& publisher_key, + PublisherInfoCallback callback) = 0; + virtual void GetActivityInfo(const ledger::ActivityInfoFilter& filter, PublisherInfoCallback callback) = 0; virtual void SetMediaPublisherInfo(const std::string& media_key, const std::string& publisher_id) = 0; virtual void GetMediaPublisherInfo(const std::string& media_key, PublisherInfoCallback callback) = 0; virtual std::vector GetRecurringDonationPublisherInfo() = 0; - virtual void GetPublisherInfoList(uint32_t start, uint32_t limit, - const ledger::PublisherInfoFilter& filter, + virtual void GetActivityInfoList(uint32_t start, uint32_t limit, + const ledger::ActivityInfoFilter& filter, PublisherInfoListCallback callback) = 0; virtual void SetRewardsMainEnabled(bool enabled) = 0; @@ -141,7 +145,7 @@ class LEDGER_EXPORT Ledger { virtual void SetContributionAmount(double amount) = 0; virtual void SetUserChangedContribution() = 0; virtual void SetAutoContribute(bool enabled) = 0; - virtual void SetBalanceReport(PUBLISHER_MONTH month, + virtual void SetBalanceReport(ACTIVITY_MONTH month, int year, const ledger::BalanceReportInfo& report_info) = 0; @@ -164,7 +168,7 @@ class LEDGER_EXPORT Ledger { virtual void SolveGrantCaptcha(const std::string& solution) const = 0; virtual void GetGrantCaptcha() const = 0; virtual std::string GetWalletPassphrase() const = 0; - virtual bool GetBalanceReport(PUBLISHER_MONTH month, + virtual bool GetBalanceReport(ACTIVITY_MONTH month, int year, ledger::BalanceReportInfo* report_info) const = 0; virtual std::map GetAllBalanceReports() const = 0; @@ -181,16 +185,16 @@ class LEDGER_EXPORT Ledger { virtual void RestorePublishers() = 0; virtual bool IsWalletCreated() const = 0; virtual void GetPublisherActivityFromUrl(uint64_t windowId, const ledger::VisitData& visit_data) = 0; - virtual void SetBalanceReportItem(PUBLISHER_MONTH month, + virtual void SetBalanceReportItem(ACTIVITY_MONTH month, int year, ledger::ReportType type, const std::string& probi) = 0; virtual void GetPublisherBanner(const std::string& publisher_id, ledger::PublisherBannerCallback callback) = 0; virtual double GetBalance() = 0; virtual void OnReconcileCompleteSuccess(const std::string& viewing_id, - const ledger::PUBLISHER_CATEGORY category, + const ledger::REWARDS_CATEGORY category, const std::string& probi, - const ledger::PUBLISHER_MONTH month, + const ledger::ACTIVITY_MONTH month, const int year, const uint32_t date) = 0; virtual void RemoveRecurring(const std::string& publisher_key) = 0; @@ -202,4 +206,4 @@ class LEDGER_EXPORT Ledger { } // namespace ledger -#endif // BAT_LEDGER_LEDGER_H_ +#endif // BAT_LEDGER_LEDGER_H_ \ No newline at end of file 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 e132b21978bf..2547294b4e96 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h +++ b/vendor/bat-native-ledger/include/bat/ledger/ledger_client.h @@ -56,6 +56,7 @@ using RecurringRemoveCallback = std::function; using FetchIconCallback = std::function; using LoadURLCallback = std::function& headers)>; +using OnRestoreCallback = std::function; class LEDGER_EXPORT LedgerClient { public: @@ -69,7 +70,7 @@ class LEDGER_EXPORT LedgerClient { std::unique_ptr) = 0; virtual void OnReconcileComplete(Result result, const std::string& viewing_id, - ledger::PUBLISHER_CATEGORY category, + ledger::REWARDS_CATEGORY category, const std::string& probi) = 0; virtual void LoadLedgerState(LedgerCallbackHandler* handler) = 0; @@ -89,14 +90,20 @@ class LEDGER_EXPORT LedgerClient { virtual void SavePublisherInfo(std::unique_ptr publisher_info, PublisherInfoCallback callback) = 0; - virtual void LoadPublisherInfo(PublisherInfoFilter filter, + virtual void SaveActivityInfo(std::unique_ptr publisher_info, PublisherInfoCallback callback) = 0; + virtual void LoadPublisherInfo(const std::string& publisher_key, + PublisherInfoCallback callback) = 0; + virtual void LoadActivityInfo(ActivityInfoFilter filter, + PublisherInfoCallback callback) = 0; + virtual void LoadPanelPublisherInfo(ActivityInfoFilter filter, + PublisherInfoCallback callback) = 0; virtual void LoadMediaPublisherInfo(const std::string& media_key, PublisherInfoCallback callback) = 0; virtual void SaveMediaPublisherInfo(const std::string& media_key, const std::string& publisher_id) = 0; - virtual void LoadPublisherInfoList(uint32_t start, uint32_t limit, - PublisherInfoFilter filter, + virtual void GetActivityInfoList(uint32_t start, uint32_t limit, + ActivityInfoFilter filter, PublisherInfoListCallback callback) = 0; // TODO this can be removed @@ -118,7 +125,7 @@ class LEDGER_EXPORT LedgerClient { const int year, const uint32_t date, const std::string& publisher_key, - const ledger::PUBLISHER_CATEGORY category) = 0; + const ledger::REWARDS_CATEGORY category) = 0; virtual void GetRecurringDonations(ledger::PublisherInfoListCallback callback) = 0; virtual void OnRemoveRecurring(const std::string& publisher_key, ledger::RecurringRemoveCallback callback) = 0; @@ -148,6 +155,8 @@ class LEDGER_EXPORT LedgerClient { const char* file, int line, const ledger::LogLevel log_level) const = 0; + + virtual void OnRestorePublishers(ledger::OnRestoreCallback callback) = 0; }; } // namespace ledger diff --git a/vendor/bat-native-ledger/include/bat/ledger/pending_contribution.h b/vendor/bat-native-ledger/include/bat/ledger/pending_contribution.h index a5782edef381..491fb1aafab9 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/pending_contribution.h +++ b/vendor/bat-native-ledger/include/bat/ledger/pending_contribution.h @@ -24,7 +24,7 @@ LEDGER_EXPORT struct PendingContribution { double amount = 0; uint64_t added_date = 0; std::string viewing_id; - PUBLISHER_CATEGORY category; + REWARDS_CATEGORY category; }; LEDGER_EXPORT struct PendingContributionList { diff --git a/vendor/bat-native-ledger/include/bat/ledger/publisher_info.h b/vendor/bat-native-ledger/include/bat/ledger/publisher_info.h index a52291678110..6c164431c9c0 100644 --- a/vendor/bat-native-ledger/include/bat/ledger/publisher_info.h +++ b/vendor/bat-native-ledger/include/bat/ledger/publisher_info.h @@ -13,7 +13,7 @@ namespace ledger { -LEDGER_EXPORT enum PUBLISHER_CATEGORY { +LEDGER_EXPORT enum REWARDS_CATEGORY { AUTO_CONTRIBUTE = 1 << 1, // 2 TIPPING = 1 << 2, DIRECT_DONATION = 1 << 3, // 8 @@ -21,7 +21,7 @@ LEDGER_EXPORT enum PUBLISHER_CATEGORY { ALL_CATEGORIES = (1 << 5) - 1, }; -LEDGER_EXPORT enum PUBLISHER_MONTH { +LEDGER_EXPORT enum ACTIVITY_MONTH { ANY = -1, JANUARY = 1, FEBRUARY = 2, @@ -44,7 +44,7 @@ LEDGER_EXPORT enum PUBLISHER_EXCLUDE { INCLUDED = 2 // user manually changed it to include and is overriding server flags }; -LEDGER_EXPORT enum PUBLISHER_EXCLUDE_FILTER { +LEDGER_EXPORT enum EXCLUDE_FILTER { FILTER_ALL = -1, FILTER_DEFAULT = 0, FILTER_EXCLUDED = 1, @@ -52,19 +52,18 @@ LEDGER_EXPORT enum PUBLISHER_EXCLUDE_FILTER { FILTER_ALL_EXCEPT_EXCLUDED = 3 }; -LEDGER_EXPORT struct PublisherInfoFilter { - PublisherInfoFilter(); - PublisherInfoFilter(const PublisherInfoFilter& filter); - ~PublisherInfoFilter(); +LEDGER_EXPORT struct ActivityInfoFilter { + ActivityInfoFilter(); + ActivityInfoFilter(const ActivityInfoFilter& filter); + ~ActivityInfoFilter(); const std::string ToJson() const; bool loadFromJson(const std::string& json); std::string id; - int category; - PUBLISHER_MONTH month; + ACTIVITY_MONTH month; int year; - PUBLISHER_EXCLUDE_FILTER excluded; + EXCLUDE_FILTER excluded; uint32_t percent; std::vector> order_by; uint64_t min_duration; @@ -108,7 +107,7 @@ LEDGER_EXPORT struct PublisherBanner { LEDGER_EXPORT struct PublisherInfo { PublisherInfo(); - PublisherInfo(const std::string& publisher_id, PUBLISHER_MONTH month, int year); + PublisherInfo(const std::string& publisher_id, ACTIVITY_MONTH month, int year); PublisherInfo(const PublisherInfo& info); ~PublisherInfo(); @@ -125,8 +124,8 @@ LEDGER_EXPORT struct PublisherInfo { uint32_t percent; double weight; PUBLISHER_EXCLUDE excluded; - PUBLISHER_CATEGORY category; - PUBLISHER_MONTH month; + REWARDS_CATEGORY category; + ACTIVITY_MONTH month; int year; uint64_t reconcile_stamp; bool verified; diff --git a/vendor/bat-native-ledger/src/bat/ledger/ledger.cc b/vendor/bat-native-ledger/src/bat/ledger/ledger.cc index 36e34777c28d..6f83e513fdbc 100644 --- a/vendor/bat-native-ledger/src/bat/ledger/ledger.cc +++ b/vendor/bat-native-ledger/src/bat/ledger/ledger.cc @@ -25,7 +25,7 @@ VisitData::VisitData(const std::string& _tld, const std::string& _domain, const std::string& _path, uint32_t _tab_id, - PUBLISHER_MONTH _local_month, + ACTIVITY_MONTH _local_month, int _local_year, const std::string& _name, const std::string& _url, @@ -86,7 +86,7 @@ bool VisitData::loadFromJson(const std::string& json) { domain = d["domain"].GetString(); path = d["path"].GetString(); tab_id = d["tab_id"].GetUint(); - local_month = (PUBLISHER_MONTH)d["local_month"].GetInt(); + local_month = (ACTIVITY_MONTH)d["local_month"].GetInt(); local_year = d["local_year"].GetInt(); name = d["name"].GetString(); url = d["url"].GetString(); @@ -100,13 +100,13 @@ bool VisitData::loadFromJson(const std::string& json) { PaymentData::PaymentData(): value(0), timestamp(0), - category(PUBLISHER_CATEGORY::TIPPING) {} + category(REWARDS_CATEGORY::TIPPING) {} PaymentData::PaymentData(const std::string& _publisher_id, const double& _value, const int64_t& _timestamp, - PUBLISHER_CATEGORY _category, - PUBLISHER_MONTH _local_month, + REWARDS_CATEGORY _category, + ACTIVITY_MONTH _local_month, int _local_year): publisher_id(_publisher_id), value(_value), @@ -125,19 +125,17 @@ PaymentData::PaymentData(const PaymentData& data): PaymentData::~PaymentData() {} -PublisherInfoFilter::PublisherInfoFilter() : - category(PUBLISHER_CATEGORY::ALL_CATEGORIES), - month(PUBLISHER_MONTH::ANY), +ActivityInfoFilter::ActivityInfoFilter() : + month(ACTIVITY_MONTH::ANY), year(-1), - excluded(PUBLISHER_EXCLUDE_FILTER::FILTER_DEFAULT), + excluded(EXCLUDE_FILTER::FILTER_DEFAULT), percent(0), min_duration(0), reconcile_stamp(0), non_verified(true) {} -PublisherInfoFilter::PublisherInfoFilter(const PublisherInfoFilter& filter) : +ActivityInfoFilter::ActivityInfoFilter(const ActivityInfoFilter& filter) : id(filter.id), - category(filter.category), month(filter.month), year(filter.year), excluded(filter.excluded), @@ -147,15 +145,15 @@ PublisherInfoFilter::PublisherInfoFilter(const PublisherInfoFilter& filter) : reconcile_stamp(filter.reconcile_stamp), non_verified(filter.non_verified) {} -PublisherInfoFilter::~PublisherInfoFilter() {} +ActivityInfoFilter::~ActivityInfoFilter() {} -const std::string PublisherInfoFilter::ToJson() const { +const std::string ActivityInfoFilter::ToJson() const { std::string json; braveledger_bat_helper::saveToJsonString(*this, json); return json; } -bool PublisherInfoFilter::loadFromJson(const std::string& json) { +bool ActivityInfoFilter::loadFromJson(const std::string& json) { rapidjson::Document d; d.Parse(json.c_str()); @@ -163,7 +161,6 @@ bool PublisherInfoFilter::loadFromJson(const std::string& json) { bool error = d.HasParseError(); if (false == error) { error = !(d.HasMember("id") && d["id"].IsString() && - d.HasMember("category") && d["category"].IsInt() && d.HasMember("month") && d["month"].IsInt() && d.HasMember("year") && d["year"].IsInt() && d.HasMember("excluded") && d["excluded"].IsInt() && @@ -176,10 +173,9 @@ bool PublisherInfoFilter::loadFromJson(const std::string& json) { if (false == error) { id = d["id"].GetString(); - category = d["category"].GetInt(); - month = (PUBLISHER_MONTH)d["month"].GetInt(); + month = (ACTIVITY_MONTH)d["month"].GetInt(); year = d["year"].GetInt(); - excluded = (PUBLISHER_EXCLUDE_FILTER)d["excluded"].GetInt(); + excluded = (EXCLUDE_FILTER)d["excluded"].GetInt(); percent = d["percent"].GetUint(); min_duration = d["min_duration"].GetUint64(); reconcile_stamp = d["reconcile_stamp"].GetUint64(); @@ -263,8 +259,8 @@ PublisherInfo::PublisherInfo() : percent(0u), weight(.0), excluded(PUBLISHER_EXCLUDE::DEFAULT), - category(PUBLISHER_CATEGORY::AUTO_CONTRIBUTE), - month(PUBLISHER_MONTH::ANY), + category(REWARDS_CATEGORY::AUTO_CONTRIBUTE), + month(ACTIVITY_MONTH::ANY), year(-1), reconcile_stamp(0), verified(false), @@ -274,7 +270,7 @@ PublisherInfo::PublisherInfo() : favicon_url("") {} PublisherInfo::PublisherInfo(const std::string& publisher_id, - PUBLISHER_MONTH _month, + ACTIVITY_MONTH _month, int _year) : id(publisher_id), duration(0u), @@ -283,7 +279,7 @@ PublisherInfo::PublisherInfo(const std::string& publisher_id, percent(0u), weight(.0), excluded(PUBLISHER_EXCLUDE::DEFAULT), - category(PUBLISHER_CATEGORY::AUTO_CONTRIBUTE), + category(REWARDS_CATEGORY::AUTO_CONTRIBUTE), month(_month), year(_year), reconcile_stamp(0), @@ -319,7 +315,7 @@ bool PublisherInfo::operator<(const PublisherInfo& rhs) const { } bool PublisherInfo::is_valid() const { - return !id.empty() && year > 0 && month != PUBLISHER_MONTH::ANY; + return !id.empty() && year > 0 && month != ACTIVITY_MONTH::ANY; } const std::string PublisherInfo::ToJson() const { @@ -362,8 +358,8 @@ bool PublisherInfo::loadFromJson(const std::string& json) { percent = d["percent"].GetUint(); weight = d["weight"].GetDouble(); excluded = (PUBLISHER_EXCLUDE)d["excluded"].GetInt(); - category = (PUBLISHER_CATEGORY)d["category"].GetInt(); - month = (PUBLISHER_MONTH)d["month"].GetInt(); + category = (REWARDS_CATEGORY)d["category"].GetInt(); + month = (ACTIVITY_MONTH)d["month"].GetInt(); year = d["year"].GetInt(); reconcile_stamp = d["reconcile_stamp"].GetUint64(); verified = d["verified"].GetBool(); @@ -386,7 +382,7 @@ bool PublisherInfo::loadFromJson(const std::string& json) { return !error; } -const PublisherInfo invalid("", PUBLISHER_MONTH::ANY, -1); +const PublisherInfo invalid("", ACTIVITY_MONTH::ANY, -1); const std::string ContributionInfo::ToJson() const { std::string json; @@ -700,7 +696,7 @@ bool PendingContribution::loadFromJson(const std::string& json) { amount = d["amount"].GetDouble(); added_date = d["added_date"].GetUint64(); viewing_id = d["viewing_id"].GetString(); - category = static_cast(d["category"].GetInt()); + category = static_cast(d["category"].GetInt()); } return !error; diff --git a/vendor/bat-native-ledger/src/bat_contribution.cc b/vendor/bat-native-ledger/src/bat_contribution.cc index 81f2ea6bb717..7e0fe904f3e0 100644 --- a/vendor/bat-native-ledger/src/bat_contribution.cc +++ b/vendor/bat-native-ledger/src/bat_contribution.cc @@ -7,19 +7,18 @@ #include #include #include +#include #include "anon/anon.h" #include "bat_contribution.h" #include "ledger_impl.h" #include "rapidjson_bat_helper.h" -using namespace std::placeholders; - namespace braveledger_bat_contribution { static bool winners_votes_compare( const braveledger_bat_helper::WINNERS_ST& first, - const braveledger_bat_helper::WINNERS_ST& second){ + const braveledger_bat_helper::WINNERS_ST& second) { return (first.votes_ < second.votes_); } @@ -46,7 +45,8 @@ void BatContribution::OnStartUp() { for (const auto& value : currentReconciles) { braveledger_bat_helper::CURRENT_RECONCILE reconcile = value.second; - if (reconcile.retry_step_ == braveledger_bat_helper::ContributionRetry::STEP_FINAL) { + if (reconcile.retry_step_ == + braveledger_bat_helper::ContributionRetry::STEP_FINAL) { ledger_->RemoveReconcileById(reconcile.viewingId_); } else { DoRetry(reconcile.viewingId_); @@ -115,7 +115,7 @@ ledger::PublisherInfoList BatContribution::GetVerifiedListAuto( (static_cast(publisher.percent) / 100) * ac_amount; contribution.publisher_key = publisher.id; contribution.viewing_id = viewing_id; - contribution.category = ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE; + contribution.category = ledger::REWARDS_CATEGORY::AUTO_CONTRIBUTE; non_verified_bat += contribution.amount; non_verified.list_.push_back(contribution); @@ -150,7 +150,7 @@ ledger::PublisherInfoList BatContribution::GetVerifiedListRecurring( contribution.amount = publisher.weight; contribution.publisher_key = publisher.id; contribution.viewing_id = viewing_id; - contribution.category = ledger::PUBLISHER_CATEGORY::RECURRING_DONATION; + contribution.category = ledger::REWARDS_CATEGORY::RECURRING_DONATION; non_verified.list_.push_back(contribution); } @@ -164,14 +164,14 @@ ledger::PublisherInfoList BatContribution::GetVerifiedListRecurring( } void BatContribution::ReconcilePublisherList( - ledger::PUBLISHER_CATEGORY category, + ledger::REWARDS_CATEGORY category, const ledger::PublisherInfoList& list, uint32_t next_record) { std::string viewing_id = ledger_->GenerateGUID(); ledger::PublisherInfoList verified_list; double budget = 0.0; - if (category == ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE) { + if (category == ledger::REWARDS_CATEGORY::AUTO_CONTRIBUTE) { ledger::PublisherInfoList normalized_list; ledger_->NormalizeContributeWinners(&normalized_list, false, list, 0); std::sort(normalized_list.begin(), normalized_list.end()); @@ -209,8 +209,11 @@ void BatContribution::OnTimerReconcile() { } ledger_->GetRecurringDonations( - std::bind(&BatContribution::ReconcilePublisherList, this, - ledger::PUBLISHER_CATEGORY::RECURRING_DONATION, _1, _2)); + std::bind(&BatContribution::ReconcilePublisherList, + this, + ledger::REWARDS_CATEGORY::RECURRING_DONATION, + std::placeholders::_1, + std::placeholders::_2)); } bool BatContribution::ShouldStartAutoContribute() { @@ -228,29 +231,28 @@ void BatContribution::StartAutoContribute() { } uint64_t current_reconcile_stamp = ledger_->GetReconcileStamp(); - ledger::PublisherInfoFilter filter = ledger_->CreatePublisherFilter( + ledger::ActivityInfoFilter filter = ledger_->CreateActivityFilter( "", - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - ledger::PUBLISHER_MONTH::ANY, + ledger::ACTIVITY_MONTH::ANY, -1, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED, + ledger::EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED, true, current_reconcile_stamp, ledger_->GetPublisherAllowNonVerified()); - ledger_->GetPublisherInfoList( + ledger_->GetActivityInfoList( 0, 0, filter, std::bind(&BatContribution::ReconcilePublisherList, this, - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - _1, - _2)); + ledger::REWARDS_CATEGORY::AUTO_CONTRIBUTE, + std::placeholders::_1, + std::placeholders::_2)); } void BatContribution::StartReconcile( const std::string& viewing_id, - const ledger::PUBLISHER_CATEGORY category, + const ledger::REWARDS_CATEGORY category, const braveledger_bat_helper::PublisherList& list, const braveledger_bat_helper::Directions& directions, double budget) { @@ -265,7 +267,7 @@ void BatContribution::StartReconcile( double fee = .0; double balance = ledger_->GetBalance(); - if (category == ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE) { + if (category == ledger::REWARDS_CATEGORY::AUTO_CONTRIBUTE) { if (list.size() == 0 || budget > balance || budget == 0) { if (list.size() == 0 || budget == 0) { @@ -291,7 +293,7 @@ void BatContribution::StartReconcile( fee = budget; } - if (category == ledger::PUBLISHER_CATEGORY::RECURRING_DONATION) { + if (category == ledger::REWARDS_CATEGORY::RECURRING_DONATION) { double ac_amount = ledger_->GetContributionAmount(); // don't use ac amount if ac is disabled @@ -311,7 +313,7 @@ void BatContribution::StartReconcile( "You do not have enough funds to do recurring and auto contribution"; OnReconcileComplete(ledger::Result::NOT_ENOUGH_FUNDS, viewing_id, - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE); + ledger::REWARDS_CATEGORY::AUTO_CONTRIBUTE); return; } @@ -319,7 +321,7 @@ void BatContribution::StartReconcile( fee = budget; } - if (category == ledger::PUBLISHER_CATEGORY::DIRECT_DONATION) { + if (category == ledger::REWARDS_CATEGORY::DIRECT_DONATION) { for (const auto& direction : directions) { if (direction.publisher_key_.empty()) { BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << @@ -363,13 +365,18 @@ void BatContribution::StartReconcile( } void BatContribution::Reconcile(const std::string& viewing_id) { - ledger_->AddReconcileStep(viewing_id, - braveledger_bat_helper::ContributionRetry::STEP_RECONCILE); + ledger_->AddReconcileStep( + viewing_id, + braveledger_bat_helper::ContributionRetry::STEP_RECONCILE); std::string url = braveledger_bat_helper::buildURL( (std::string)RECONCILE_CONTRIBUTION + ledger_->GetUserId(), PREFIX_V2); - auto callback = std::bind(&BatContribution::ReconcileCallback, this, - viewing_id, _1, _2, _3); + auto callback = std::bind(&BatContribution::ReconcileCallback, + this, + viewing_id, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3); ledger_->LoadURL(url, std::vector(), "", @@ -388,7 +395,8 @@ void BatContribution::ReconcileCallback( auto reconcile = ledger_->GetReconcileById(viewing_id); if (!result || reconcile.viewingId_.empty()) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_RECONCILE, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_RECONCILE, + viewing_id); return; } @@ -397,7 +405,8 @@ void BatContribution::ReconcileCallback( response, reconcile.surveyorInfo_.surveyorId_); if (!success) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_RECONCILE, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_RECONCILE, + viewing_id); return; } @@ -413,8 +422,9 @@ void BatContribution::ReconcileCallback( } void BatContribution::CurrentReconcile(const std::string& viewing_id) { - ledger_->AddReconcileStep(viewing_id, - braveledger_bat_helper::ContributionRetry::STEP_CURRENT); + ledger_->AddReconcileStep( + viewing_id, + braveledger_bat_helper::ContributionRetry::STEP_CURRENT); std::ostringstream amount; auto reconcile = ledger_->GetReconcileById(viewing_id); @@ -429,8 +439,12 @@ void BatContribution::CurrentReconcile(const std::string& viewing_id) { "&altcurrency=" + currency; - auto callback =std::bind(&BatContribution::CurrentReconcileCallback, this, - viewing_id, _1, _2, _3); + auto callback = std::bind(&BatContribution::CurrentReconcileCallback, + this, + viewing_id, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3); ledger_->LoadURL( braveledger_bat_helper::buildURL(path, PREFIX_V2), std::vector(), @@ -448,7 +462,8 @@ void BatContribution::CurrentReconcileCallback( ledger_->LogResponse(__func__, result, response, headers); if (!result) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_CURRENT, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_CURRENT, + viewing_id); return; } @@ -457,14 +472,16 @@ void BatContribution::CurrentReconcileCallback( bool success = braveledger_bat_helper::getJSONRates(response, reconcile.rates_); if (!success) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_CURRENT, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_CURRENT, + viewing_id); return; } braveledger_bat_helper::UNSIGNED_TX unsigned_tx; success = braveledger_bat_helper::getJSONUnsignedTx(response, unsigned_tx); if (!success) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_CURRENT, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_CURRENT, + viewing_id); return; } @@ -472,7 +489,8 @@ void BatContribution::CurrentReconcileCallback( unsigned_tx.currency_.empty() && unsigned_tx.destination_.empty()) { // We don't have any unsigned transactions - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_CURRENT, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_CURRENT, + viewing_id); return; } @@ -492,8 +510,9 @@ void BatContribution::CurrentReconcileCallback( } void BatContribution::ReconcilePayload(const std::string& viewing_id) { - ledger_->AddReconcileStep(viewing_id, - braveledger_bat_helper::ContributionRetry::STEP_PAYLOAD); + ledger_->AddReconcileStep( + viewing_id, + braveledger_bat_helper::ContributionRetry::STEP_PAYLOAD); auto reconcile = ledger_->GetReconcileById(viewing_id); braveledger_bat_helper::WALLET_INFO_ST wallet_info = ledger_->GetWalletInfo(); @@ -544,8 +563,12 @@ void BatContribution::ReconcilePayload(const std::string& viewing_id) { wallet_header.push_back("Content-Type: application/json; charset=UTF-8"); std::string path = (std::string)WALLET_PROPERTIES + ledger_->GetPaymentId(); - auto callback = std::bind(&BatContribution::ReconcilePayloadCallback, this, - viewing_id, _1, _2, _3); + auto callback = std::bind(&BatContribution::ReconcilePayloadCallback, + this, + viewing_id, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3); ledger_->LoadURL( braveledger_bat_helper::buildURL(path, PREFIX_V2), wallet_header, @@ -563,7 +586,8 @@ void BatContribution::ReconcilePayloadCallback( ledger_->LogResponse(__func__, result, response, headers); if (!result) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_PAYLOAD, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_PAYLOAD, + viewing_id); return; } @@ -573,7 +597,8 @@ void BatContribution::ReconcilePayloadCallback( bool success = braveledger_bat_helper::getJSONTransaction(response, transaction); if (!success) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_PAYLOAD, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_PAYLOAD, + viewing_id); return; } @@ -591,10 +616,15 @@ void BatContribution::ReconcilePayloadCallback( } void BatContribution::RegisterViewing(const std::string& viewing_id) { - ledger_->AddReconcileStep(viewing_id, - braveledger_bat_helper::ContributionRetry::STEP_REGISTER); - auto callback = std::bind(&BatContribution::RegisterViewingCallback, this, - viewing_id, _1, _2, _3); + ledger_->AddReconcileStep( + viewing_id, + braveledger_bat_helper::ContributionRetry::STEP_REGISTER); + auto callback = std::bind(&BatContribution::RegisterViewingCallback, + this, + viewing_id, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3); ledger_->LoadURL( braveledger_bat_helper::buildURL( (std::string)REGISTER_VIEWING, PREFIX_V2), @@ -613,7 +643,8 @@ void BatContribution::RegisterViewingCallback( ledger_->LogResponse(__func__, result, response, headers); if (!result) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_REGISTER, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_REGISTER, + viewing_id); return; } @@ -624,7 +655,8 @@ void BatContribution::RegisterViewingCallback( reconcile.registrarVK_); DCHECK(!reconcile.registrarVK_.empty()); if (!success || reconcile.registrarVK_.empty()) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_REGISTER, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_REGISTER, + viewing_id); return; } @@ -651,8 +683,9 @@ void BatContribution::RegisterViewingCallback( } void BatContribution::ViewingCredentials(const std::string& viewing_id) { - ledger_->AddReconcileStep(viewing_id, - braveledger_bat_helper::ContributionRetry::STEP_VIEWING); + ledger_->AddReconcileStep( + viewing_id, + braveledger_bat_helper::ContributionRetry::STEP_VIEWING); auto reconcile = ledger_->GetReconcileById(viewing_id); std::string keys[1] = {"proof"}; @@ -667,8 +700,12 @@ void BatContribution::ViewingCredentials(const std::string& viewing_id) { reconcile.anonizeViewingId_, PREFIX_V2); - auto callback = std::bind(&BatContribution::ViewingCredentialsCallback, this, - viewing_id, _1, _2, _3); + auto callback = std::bind(&BatContribution::ViewingCredentialsCallback, + this, + viewing_id, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3); ledger_->LoadURL(url, std::vector(), proof_stringified, @@ -685,7 +722,8 @@ void BatContribution::ViewingCredentialsCallback( ledger_->LogResponse(__func__, result, response, headers); if (!result) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_VIEWING, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_VIEWING, + viewing_id); return; } @@ -696,7 +734,8 @@ void BatContribution::ViewingCredentialsCallback( response, verification); if (!success) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_VIEWING, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_VIEWING, + viewing_id); return; } @@ -724,7 +763,8 @@ void BatContribution::ViewingCredentialsCallback( response, surveyors); if (!success) { - AddRetry(braveledger_bat_helper::ContributionRetry::STEP_VIEWING, viewing_id); + AddRetry(braveledger_bat_helper::ContributionRetry::STEP_VIEWING, + viewing_id); return; } @@ -757,12 +797,12 @@ void BatContribution::OnReconcileComplete(ledger::Result result, int category, const std::string& probi) { // Start the timer again if it wasn't a direct donation - if (category == ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE) { + if (category == ledger::REWARDS_CATEGORY::AUTO_CONTRIBUTE) { ResetReconcileStamp(); } // Trigger auto contribute after recurring donation - if (category == ledger::PUBLISHER_CATEGORY::RECURRING_DONATION) { + if (category == ledger::REWARDS_CATEGORY::RECURRING_DONATION) { StartAutoContribute(); } @@ -798,17 +838,17 @@ void BatContribution::GetReconcileWinners(const std::string& viewing_id) { const auto reconcile = ledger_->GetReconcileById(viewing_id); switch (reconcile.category_) { - case ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE: { + case ledger::REWARDS_CATEGORY::AUTO_CONTRIBUTE: { GetContributeWinners(ballots_count, viewing_id, reconcile.list_); break; } - case ledger::PUBLISHER_CATEGORY::RECURRING_DONATION: { + case ledger::REWARDS_CATEGORY::RECURRING_DONATION: { GetDonationWinners(ballots_count, viewing_id, reconcile.list_); break; } - case ledger::PUBLISHER_CATEGORY::DIRECT_DONATION: { + case ledger::REWARDS_CATEGORY::DIRECT_DONATION: { // Direct one-time contribution braveledger_bat_helper::WINNERS_ST winner; winner.votes_ = ballots_count; @@ -843,8 +883,9 @@ void BatContribution::GetContributeWinners( } braveledger_bat_helper::WINNERS_ST winner; - winner.votes_ = (unsigned int)std::lround( - (double) item.percent_* (double)ballots / 100.0); + winner.votes_ = static_cast(std::lround( + static_cast(item.percent_) * + static_cast(ballots) / 100.0)); total_votes += winner.votes_; winner.publisher_data_.id_ = item.id_; @@ -886,7 +927,8 @@ void BatContribution::GetDonationWinners( braveledger_bat_helper::WINNERS_ST winner; double percent = item.weight_ / reconcile.fee_; - winner.votes_ = (unsigned int)std::lround(percent * (double)ballots); + winner.votes_ = static_cast(std::lround(percent * + static_cast(ballots))); total_votes += winner.votes_; winner.publisher_data_.id_ = item.id_; winner.publisher_data_.duration_ = 0; @@ -925,8 +967,9 @@ void BatContribution::VotePublishers( VotePublisher(publishers[i], viewing_id); } - ledger_->AddReconcileStep(viewing_id, - braveledger_bat_helper::ContributionRetry::STEP_FINAL); + ledger_->AddReconcileStep( + viewing_id, + braveledger_bat_helper::ContributionRetry::STEP_FINAL); PrepareBallots(); } @@ -1018,8 +1061,11 @@ void BatContribution::PrepareBatch( "/" + transaction.anonizeViewingId_, PREFIX_V2); - auto callback = std::bind(&BatContribution::PrepareBatchCallback, this, - _1, _2, _3); + auto callback = std::bind(&BatContribution::PrepareBatchCallback, + this, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3); ledger_->LoadURL(url, std::vector(), "", @@ -1279,8 +1325,12 @@ void BatContribution::VoteBatch() { std::string url = braveledger_bat_helper::buildURL( (std::string)SURVEYOR_BATCH_VOTING , PREFIX_V2); - auto callback = std::bind(&BatContribution::VoteBatchCallback, this, - batch_votes.publisher_, _1, _2, _3); + auto callback = std::bind(&BatContribution::VoteBatchCallback, + this, + batch_votes.publisher_, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3); ledger_->LoadURL(url, std::vector(), payload, @@ -1370,7 +1420,7 @@ void BatContribution::OnTimer(uint32_t timer_id) { return; } - for(std::pair const& value: retry_timers_) { + for (std::pair const& value : retry_timers_) { if (value.second == timer_id) { std::string viewing_id = value.first; DoRetry(viewing_id); @@ -1407,12 +1457,12 @@ void BatContribution::SetTimer(uint32_t& timer_id, uint64_t start_timer_in) { void BatContribution::OnReconcileCompleteSuccess( const std::string& viewing_id, - ledger::PUBLISHER_CATEGORY category, + ledger::REWARDS_CATEGORY category, const std::string& probi, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year, uint32_t date) { - if (category == ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE) { + if (category == ledger::REWARDS_CATEGORY::AUTO_CONTRIBUTE) { ledger_->SetBalanceReportItem(month, year, ledger::ReportType::AUTO_CONTRIBUTION, @@ -1421,7 +1471,7 @@ void BatContribution::OnReconcileCompleteSuccess( return; } - if (category == ledger::PUBLISHER_CATEGORY::DIRECT_DONATION) { + if (category == ledger::REWARDS_CATEGORY::DIRECT_DONATION) { ledger_->SetBalanceReportItem(month, year, ledger::ReportType::DONATION, @@ -1440,7 +1490,7 @@ void BatContribution::OnReconcileCompleteSuccess( return; } - if (category == ledger::PUBLISHER_CATEGORY::RECURRING_DONATION) { + if (category == ledger::REWARDS_CATEGORY::RECURRING_DONATION) { auto reconcile = ledger_->GetReconcileById(viewing_id); ledger_->SetBalanceReportItem(month, year, @@ -1508,7 +1558,7 @@ uint64_t BatContribution::GetRetryTimer( reconcile.retry_step_ = step; if (phase == 1) { - // TODO get size from the list + // TODO(nejczdovc) get size from the list if (reconcile.retry_level_ < 5) { if (ledger::short_retries) { return phase_one_debug_timers[reconcile.retry_level_]; @@ -1522,7 +1572,7 @@ uint64_t BatContribution::GetRetryTimer( } if (phase == 2) { - // TODO get size from the list + // TODO(nejczdovc) get size from the list if (reconcile.retry_level_ > 2) { if (ledger::short_retries) { return phase_two_debug_timers[2]; @@ -1535,14 +1585,14 @@ uint64_t BatContribution::GetRetryTimer( } else { return phase_two_timers[reconcile.retry_level_]; } - } } return 0; } -int BatContribution::GetRetryPhase(braveledger_bat_helper::ContributionRetry step) { +int BatContribution::GetRetryPhase( + braveledger_bat_helper::ContributionRetry step) { int phase = 0; switch (step) { diff --git a/vendor/bat-native-ledger/src/bat_contribution.h b/vendor/bat-native-ledger/src/bat_contribution.h index 081b7da65170..069fe0f35e1b 100644 --- a/vendor/bat-native-ledger/src/bat_contribution.h +++ b/vendor/bat-native-ledger/src/bat_contribution.h @@ -110,7 +110,7 @@ class BatContribution { // We determinate which contribution we want to do and do appropriate actions void StartReconcile( const std::string &viewing_id, - const ledger::PUBLISHER_CATEGORY category, + const ledger::REWARDS_CATEGORY category, const braveledger_bat_helper::PublisherList& list, const braveledger_bat_helper::Directions& directions = {}, double budget = 0); @@ -124,9 +124,9 @@ class BatContribution { // Does final stage in contribution // Sets reports and contribution info void OnReconcileCompleteSuccess(const std::string& viewing_id, - ledger::PUBLISHER_CATEGORY category, + ledger::REWARDS_CATEGORY category, const std::string& probi, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year, uint32_t date); @@ -150,7 +150,7 @@ class BatContribution { double& budget); // Entry point for contribution where we have publisher info list - void ReconcilePublisherList(ledger::PUBLISHER_CATEGORY category, + void ReconcilePublisherList(ledger::REWARDS_CATEGORY category, const ledger::PublisherInfoList& list, uint32_t next_record); diff --git a/vendor/bat-native-ledger/src/bat_get_media.cc b/vendor/bat-native-ledger/src/bat_get_media.cc index c8b9f59104ae..d4f08112258b 100644 --- a/vendor/bat-native-ledger/src/bat_get_media.cc +++ b/vendor/bat-native-ledger/src/bat_get_media.cc @@ -106,7 +106,7 @@ void BatGetMedia::getPublisherInfoDataCallback(const std::string& mediaId, return; } - if (!publisher_info.get()) { + if (!publisher_info && !publisher_info.get()) { std::string mediaURL = getMediaURL(mediaId, providerName); if (providerName == YOUTUBE_MEDIA_TYPE) { auto callback = std::bind( @@ -549,12 +549,12 @@ void BatGetMedia::onMediaUserActivity(ledger::Result result, const std::string& providerType, const std::string& media_key) { if (result != ledger::Result::LEDGER_OK && - result != ledger::Result::NOT_FOUND) { + result != ledger::Result::NOT_FOUND) { onMediaActivityError(visit_data, providerType, windowId); return; } - if (result == ledger::Result::NOT_FOUND) { + if (!info || result == ledger::Result::NOT_FOUND) { fetchDataFromUrl(visit_data.url, std::bind(&BatGetMedia::onGetChannelIdFromUserPage, this, windowId, @@ -591,16 +591,15 @@ void BatGetMedia::fetchPublisherDataFromDB(uint64_t windowId, const ledger::VisitData& visit_data, const std::string& providerType, const std::string& publisher_key) { - auto filter = ledger_->CreatePublisherFilter( + auto filter = ledger_->CreateActivityFilter( publisher_key, - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - ledger::PUBLISHER_MONTH::ANY, + ledger::ACTIVITY_MONTH::ANY, -1, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL, + ledger::EXCLUDE_FILTER::FILTER_ALL, false, ledger_->GetReconcileStamp(), true); - ledger_->GetPublisherInfo(filter, + ledger_->GetPanelPublisherInfo(filter, std::bind(&BatGetMedia::onFetchPublisherFromDBResponse, this, _1, _2, windowId, visit_data, providerType, publisher_key)); } @@ -702,7 +701,7 @@ void BatGetMedia::onMediaPublisherActivity(ledger::Result result, return; } - if (result == ledger::Result::NOT_FOUND) { + if (!info || result == ledger::Result::NOT_FOUND) { ledger::TwitchEventInfo twitchEventInfo; getPublisherInfoDataCallback(media_id, media_key, diff --git a/vendor/bat-native-ledger/src/bat_helper.cc b/vendor/bat-native-ledger/src/bat_helper.cc index c95207a9467b..a5af942031ed 100644 --- a/vendor/bat-native-ledger/src/bat_helper.cc +++ b/vendor/bat-native-ledger/src/bat_helper.cc @@ -2617,15 +2617,12 @@ static bool ignore_ = false; } void saveToJson(JsonWriter & writer, - const ledger::PublisherInfoFilter& info) { + const ledger::ActivityInfoFilter& info) { writer.StartObject(); writer.String("id"); writer.String(info.id.c_str()); - writer.String("category"); - writer.Int(info.category); - writer.String("month"); writer.Int(info.month); diff --git a/vendor/bat-native-ledger/src/bat_publishers.cc b/vendor/bat-native-ledger/src/bat_publishers.cc index 64c4ae479ff4..aeb9f6bf0b5f 100644 --- a/vendor/bat-native-ledger/src/bat_publishers.cc +++ b/vendor/bat-native-ledger/src/bat_publishers.cc @@ -87,84 +87,76 @@ void BatPublishers::saveVisit(const std::string& publisher_id, return; } - auto filter = CreatePublisherFilter(publisher_id, - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - ledger::PUBLISHER_MONTH::ANY, + auto filter = CreateActivityFilter(publisher_id, + ledger::ACTIVITY_MONTH::ANY, -1, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL, + ledger::EXCLUDE_FILTER::FILTER_ALL, false, ledger_->GetReconcileStamp(), true); - ledger::PublisherInfoCallback callbackGetPublishers = std::bind(&BatPublishers::saveVisitInternal, this, + ledger::PublisherInfoCallback callbackGetPublishers = + std::bind(&BatPublishers::saveVisitInternal, this, publisher_id, visit_data, duration, 0, _1, _2); - ledger_->GetPublisherInfo(filter, callbackGetPublishers); + ledger_->GetActivityInfo(filter, callbackGetPublishers); } -ledger::PublisherInfoFilter BatPublishers::CreatePublisherFilter( +ledger::ActivityInfoFilter BatPublishers::CreateActivityFilter( const std::string &publisher_id, - ledger::PUBLISHER_CATEGORY category, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year) { - return CreatePublisherFilter(publisher_id, - category, - month, - year, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL, - true, - 0, - true); + return CreateActivityFilter(publisher_id, + month, + year, + ledger::EXCLUDE_FILTER::FILTER_ALL, + true, + 0, + true); } -ledger::PublisherInfoFilter BatPublishers::CreatePublisherFilter( +ledger::ActivityInfoFilter BatPublishers::CreateActivityFilter( const std::string& publisher_id, - ledger::PUBLISHER_CATEGORY category, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year, - ledger::PUBLISHER_EXCLUDE_FILTER excluded) { - return CreatePublisherFilter(publisher_id, - category, - month, - year, - excluded, - true, - 0, - true); -} - -ledger::PublisherInfoFilter BatPublishers::CreatePublisherFilter( + ledger::EXCLUDE_FILTER excluded) { + return CreateActivityFilter(publisher_id, + month, + year, + excluded, + true, + 0, + true); +} + +ledger::ActivityInfoFilter BatPublishers::CreateActivityFilter( const std::string &publisher_id, - ledger::PUBLISHER_CATEGORY category, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year, bool min_duration) { - return CreatePublisherFilter(publisher_id, - category, - month, - year, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL, - min_duration, - 0, - true); + return CreateActivityFilter(publisher_id, + month, + year, + ledger::EXCLUDE_FILTER::FILTER_ALL, + min_duration, + 0, + true); } -ledger::PublisherInfoFilter BatPublishers::CreatePublisherFilter( +ledger::ActivityInfoFilter BatPublishers::CreateActivityFilter( const std::string& publisher_id, - ledger::PUBLISHER_CATEGORY category, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year, - ledger::PUBLISHER_EXCLUDE_FILTER excluded, + ledger::EXCLUDE_FILTER excluded, bool min_duration, const uint64_t& currentReconcileStamp, bool non_verified) { - ledger::PublisherInfoFilter filter; + ledger::ActivityInfoFilter filter; filter.id = publisher_id; - filter.category = category; filter.month = month; filter.year = year; filter.excluded = excluded; @@ -176,7 +168,7 @@ ledger::PublisherInfoFilter BatPublishers::CreatePublisherFilter( } std::string BatPublishers::GetBalanceReportName( - const ledger::PUBLISHER_MONTH month, + const ledger::ACTIVITY_MONTH month, int year) { return std::to_string(year) + "_" + std::to_string(month); } @@ -211,15 +203,6 @@ void BatPublishers::saveVisitInternal( visit_data.local_year)); } - // set duration to 0 if you don't have sufficient visit time - // or if you set ac to only verified and site is not verified - // or if auto contribute if off - if ((!ignoreMinTime(publisher_id) && duration < getPublisherMinVisitTime()) || - (!ledger_->GetPublisherAllowNonVerified() && !verified) || - !ledger_->GetAutoContribute()) { - duration = 0; - } - std::string fav_icon = visit_data.favicon_url; if (verified && fav_icon.length() > 0) { ledger_->FetchFavIcon(fav_icon, @@ -234,28 +217,53 @@ void BatPublishers::saveVisitInternal( publisher_info->name = visit_data.name; publisher_info->provider = visit_data.provider; publisher_info->url = visit_data.url; - publisher_info->visits += 1; - publisher_info->category = ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE; - if (!isExcluded(publisher_info->id, publisher_info->excluded)) { - publisher_info->duration += duration; - } else { + publisher_info->verified = verified; + + bool excluded = isExcluded(publisher_info->id, publisher_info->excluded); + bool ignore_time = ignoreMinTime(publisher_id); + if (duration == 0) { + ignore_time = false; + } + + std::unique_ptr panel_info = nullptr; + + if (excluded) { publisher_info->excluded = ledger::PUBLISHER_EXCLUDE::EXCLUDED; - if (new_visit) { - publisher_info->duration = 0; // don't log auto-excluded - } } - publisher_info->score += concaveScore(duration); - publisher_info->verified = verified; - publisher_info->reconcile_stamp = ledger_->GetReconcileStamp(); - auto media_info = std::make_unique(*publisher_info); + // for new visits that are excluded or are not long enough or ac is off + bool min_duration_new = duration < getPublisherMinVisitTime() && + !ignore_time; + bool min_duration_ok = duration > getPublisherMinVisitTime() || ignore_time; + bool verified_new = !ledger_->GetPublisherAllowNonVerified() && !verified; + bool verified_old = ((!ledger_->GetPublisherAllowNonVerified() && verified) || + ledger_->GetPublisherAllowNonVerified()); - ledger_->SetPublisherInfo(std::move(publisher_info), - std::bind(&onVisitSavedDummy, _1, _2)); + if (new_visit && + (excluded || + !ledger_->GetAutoContribute() || + min_duration_new || + verified_new)) { + panel_info = std::make_unique(*publisher_info); + ledger_->SetPublisherInfo(std::move(publisher_info), + std::bind(&onVisitSavedDummy, _1, _2)); + } else if (!excluded && + ledger_->GetAutoContribute() && + min_duration_ok && + verified_old) { + publisher_info->visits += 1; + publisher_info->duration += duration; + publisher_info->score += concaveScore(duration); + publisher_info->reconcile_stamp = ledger_->GetReconcileStamp(); - if (window_id > 0) { + panel_info = std::make_unique(*publisher_info); + ledger_->SetActivityInfo(std::move(publisher_info), + std::bind(&onVisitSavedDummy, _1, _2)); + } + + if (panel_info && window_id > 0) { onPublisherActivity(ledger::Result::LEDGER_OK, - std::move(media_info), + std::move(panel_info), window_id, visit_data); } @@ -264,16 +272,7 @@ void BatPublishers::saveVisitInternal( void BatPublishers::onFetchFavIcon(const std::string& publisher_key, bool success, const std::string& favicon_url) { - uint64_t currentReconcileStamp = ledger_->GetReconcileStamp(); - auto filter = ledger_->CreatePublisherFilter(publisher_key, - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - ledger::PUBLISHER_MONTH::ANY, - -1, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL, - false, - currentReconcileStamp, - true); - ledger_->GetPublisherInfo(filter, + ledger_->GetPublisherInfo(publisher_key, std::bind(&BatPublishers::onFetchFavIconDBResponse, this, _1, _2, favicon_url)); } @@ -310,38 +309,29 @@ std::unique_ptr BatPublishers::onPublisherInfoUpdated( } void BatPublishers::setExclude(const std::string& publisher_id, const ledger::PUBLISHER_EXCLUDE& exclude) { - uint64_t currentReconcileStamp = ledger_->GetReconcileStamp(); - auto filter = CreatePublisherFilter(publisher_id, - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - ledger::PUBLISHER_MONTH::ANY, - -1, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL, - false, - currentReconcileStamp, - true); - ledger_->GetPublisherInfo(filter, std::bind(&BatPublishers::onSetExcludeInternal, - this, exclude, _1, _2)); + ledger_->GetPublisherInfo(publisher_id, + std::bind(&BatPublishers::onSetExcludeInternal, + this, + exclude, + _1, + _2)); } void BatPublishers::setPanelExclude(const std::string& publisher_id, const ledger::PUBLISHER_EXCLUDE& exclude, uint64_t windowId) { - uint64_t currentReconcileStamp = ledger_->GetReconcileStamp(); - auto filter = CreatePublisherFilter(publisher_id, - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - ledger::PUBLISHER_MONTH::ANY, - -1, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL, - false, - currentReconcileStamp, - true); - ledger_->GetPublisherInfo(filter, std::bind( - &BatPublishers::onSetPanelExcludeInternal, - this, exclude, windowId, _1, _2)); + ledger_->GetPublisherInfo(publisher_id, + std::bind(&BatPublishers::onSetPanelExcludeInternal, + this, + exclude, + windowId, + _1, + _2)); } -void BatPublishers::onSetExcludeInternal(ledger::PUBLISHER_EXCLUDE exclude, - ledger::Result result, - std::unique_ptr publisher_info) { +void BatPublishers::onSetExcludeInternal( + ledger::PUBLISHER_EXCLUDE exclude, + ledger::Result result, + std::unique_ptr publisher_info) { if (result != ledger::Result::LEDGER_OK && result != ledger::Result::NOT_FOUND) { return; @@ -352,20 +342,22 @@ void BatPublishers::onSetExcludeInternal(ledger::PUBLISHER_EXCLUDE exclude, return; } - publisher_info->year = -1; if (publisher_info->excluded == ledger::PUBLISHER_EXCLUDE::DEFAULT || publisher_info->excluded == ledger::PUBLISHER_EXCLUDE::INCLUDED) { publisher_info->excluded = ledger::PUBLISHER_EXCLUDE::EXCLUDED; } else { publisher_info->excluded = ledger::PUBLISHER_EXCLUDE::INCLUDED; } - publisher_info->month = ledger::PUBLISHER_MONTH::ANY; + setNumExcludedSitesInternal(exclude); std::string publisherKey = publisher_info->id; ledger_->SetPublisherInfo(std::move(publisher_info), - std::bind(&BatPublishers::onSetPublisherInfo, this, _1, _2)); + std::bind(&BatPublishers::onSetPublisherInfo, + this, + _1, + _2)); OnExcludedSitesChanged(publisherKey); } @@ -392,49 +384,43 @@ void BatPublishers::onSetPanelExcludeInternal(ledger::PUBLISHER_EXCLUDE exclude, return; } - publisher_info->year = -1; if (publisher_info->excluded == ledger::PUBLISHER_EXCLUDE::DEFAULT || publisher_info->excluded == ledger::PUBLISHER_EXCLUDE::INCLUDED) { publisher_info->excluded = ledger::PUBLISHER_EXCLUDE::EXCLUDED; } else { publisher_info->excluded = ledger::PUBLISHER_EXCLUDE::INCLUDED; } - publisher_info->month = ledger::PUBLISHER_MONTH::ANY; + setNumExcludedSitesInternal(exclude); ledger::VisitData visit_data; std::string publisherKey = publisher_info->id; ledger_->SetPublisherInfo(std::move(publisher_info), - std::bind(&BatPublishers::onPublisherActivity, this, _1, _2, - windowId, visit_data)); + std::bind(&BatPublishers::onPublisherActivity, + this, + _1, + _2, + windowId, + visit_data)); OnExcludedSitesChanged(publisherKey); } -void BatPublishers::restorePublishers() { - uint64_t currentReconcileStamp = ledger_->GetReconcileStamp(); - auto filter = CreatePublisherFilter("", - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - ledger::PUBLISHER_MONTH::ANY, - -1, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_EXCLUDED, - false, - currentReconcileStamp, - true); - ledger_->GetPublisherInfoList(0, 0, filter, std::bind(&BatPublishers::onRestorePublishersInternal, - this, _1, _2)); +void BatPublishers::RestorePublishers() { + ledger_->OnRestorePublishers( + std::bind(&BatPublishers::OnRestorePublishersInternal, + this, + _1)); } -void BatPublishers::onRestorePublishersInternal(const ledger::PublisherInfoList& publisherInfoList, uint32_t /* next_record */) { - if (publisherInfoList.size() == 0) { - return; - } - - for (size_t i = 0; i < publisherInfoList.size(); i++) { - // Set to PUBLISHER_EXCLUDE::DEFAULT (0) - setExclude(publisherInfoList[i].id, - ledger::PUBLISHER_EXCLUDE::DEFAULT); +void BatPublishers::OnRestorePublishersInternal(bool success) { + if (success) { + setNumExcludedSites(0); + OnExcludedSitesChanged(""); + } else { + BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << + "Could not restore publishers."; } } @@ -563,8 +549,8 @@ void BatPublishers::synopsisNormalizerInternal( if (saveData) { std::unique_ptr publisher_info; publisher_info.reset(new ledger::PublisherInfo(list[i])); - ledger_->SetPublisherInfo(std::move(publisher_info), - std::bind(&onVisitSavedDummy, _1, _2)); + ledger_->SetActivityInfo(std::move(publisher_info), + std::bind(&onVisitSavedDummy, _1, _2)); } if (newList) { newList->push_back(list[i]); @@ -573,18 +559,25 @@ void BatPublishers::synopsisNormalizerInternal( } void BatPublishers::synopsisNormalizer(const ledger::PublisherInfo& info) { - auto filter = CreatePublisherFilter("", - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - ledger::PUBLISHER_MONTH::ANY, + auto filter = CreateActivityFilter("", + ledger::ACTIVITY_MONTH::ANY, -1, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED, + ledger::EXCLUDE_FILTER::FILTER_ALL_EXCEPT_EXCLUDED, true, ledger_->GetReconcileStamp(), ledger_->GetPublisherAllowNonVerified()); // TODO SZ: We pull the whole list currently, I don't think it consumes lots of RAM, but could. // We need to limit it and iterate. - ledger_->GetPublisherInfoList(0, 0, filter, std::bind(&BatPublishers::synopsisNormalizerInternal, this, - nullptr, true, _1, _2)); + ledger_->GetActivityInfoList( + 0, + 0, + filter, + std::bind(&BatPublishers::synopsisNormalizerInternal, + this, + nullptr, + true, + _1, + _2)); } bool BatPublishers::isVerified(const std::string& publisher_id) { @@ -643,7 +636,7 @@ void BatPublishers::clearAllBalanceReports() { saveState(); } -void BatPublishers::setBalanceReport(ledger::PUBLISHER_MONTH month, +void BatPublishers::setBalanceReport(ledger::ACTIVITY_MONTH month, int year, const ledger::BalanceReportInfo& report_info) { braveledger_bat_helper::REPORT_BALANCE_ST report_balance; @@ -669,7 +662,7 @@ void BatPublishers::setBalanceReport(ledger::PUBLISHER_MONTH month, saveState(); } -bool BatPublishers::getBalanceReport(ledger::PUBLISHER_MONTH month, +bool BatPublishers::getBalanceReport(ledger::ACTIVITY_MONTH month, int year, ledger::BalanceReportInfo* report_info) { std::string name = GetBalanceReportName(month, year); @@ -743,9 +736,6 @@ void BatPublishers::OnPublisherStateSaved(ledger::Result result) { // TODO - error handling return; } - // SZ: We don't need to normalize on state save, all normalizing is done on AUTO_CONTRIBUTE publishers - // save visit - //synopsisNormalizer(); } std::vector BatPublishers::GetRecurringDonationList() { @@ -802,11 +792,10 @@ void BatPublishers::getPublisherActivityFromUrl(uint64_t windowId, const ledger: return; } - auto filter = CreatePublisherFilter(visit_data.domain, - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - ledger::PUBLISHER_MONTH::ANY, + auto filter = CreateActivityFilter(visit_data.domain, + ledger::ACTIVITY_MONTH::ANY, -1, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL, + ledger::EXCLUDE_FILTER::FILTER_ALL, false, ledger_->GetReconcileStamp(), true); @@ -820,8 +809,13 @@ void BatPublishers::getPublisherActivityFromUrl(uint64_t windowId, const ledger: new_data.url = visit_data.url; new_data.favicon_url = ""; - ledger_->GetPublisherInfo(filter, - std::bind(&BatPublishers::onPublisherActivity, this, _1, _2, windowId, new_data)); + ledger_->GetPanelPublisherInfo(filter, + std::bind(&BatPublishers::onPublisherActivity, + this, + _1, + _2, + windowId, + new_data)); } void BatPublishers::onPublisherActivity(ledger::Result result, @@ -846,7 +840,7 @@ void BatPublishers::OnExcludedSitesChanged(const std::string& publisher_id) { ledger_->OnExcludedSitesChanged(publisher_id); } -void BatPublishers::setBalanceReportItem(ledger::PUBLISHER_MONTH month, +void BatPublishers::setBalanceReportItem(ledger::ACTIVITY_MONTH month, int year, ledger::ReportType type, const std::string& probi) { @@ -899,16 +893,6 @@ void BatPublishers::getPublisherBanner(const std::string& publisher_id, } } - uint64_t currentReconcileStamp = ledger_->GetReconcileStamp(); - auto filter = CreatePublisherFilter(publisher_id, - ledger::PUBLISHER_CATEGORY::AUTO_CONTRIBUTE, - ledger::PUBLISHER_MONTH::ANY, - -1, - ledger::PUBLISHER_EXCLUDE_FILTER::FILTER_ALL, - false, - currentReconcileStamp, - true); - ledger::PublisherInfoCallback callbackGetPublisher = std::bind(&BatPublishers::onPublisherBanner, this, callback, @@ -916,7 +900,7 @@ void BatPublishers::getPublisherBanner(const std::string& publisher_id, _1, _2); - ledger_->GetPublisherInfo(filter, callbackGetPublisher); + ledger_->GetPublisherInfo(publisher_id, callbackGetPublisher); } void BatPublishers::onPublisherBanner(ledger::PublisherBannerCallback callback, @@ -926,7 +910,7 @@ void BatPublishers::onPublisherBanner(ledger::PublisherBannerCallback callback, auto new_banner = std::make_unique(banner); - if (result != ledger::Result::LEDGER_OK) { + if (!publisher_info || result != ledger::Result::LEDGER_OK) { callback(std::move(new_banner)); return; } diff --git a/vendor/bat-native-ledger/src/bat_publishers.h b/vendor/bat-native-ledger/src/bat_publishers.h index e701bf3d4135..c383e8018441 100644 --- a/vendor/bat-native-ledger/src/bat_publishers.h +++ b/vendor/bat-native-ledger/src/bat_publishers.h @@ -38,7 +38,6 @@ class BatPublishers : public ledger::LedgerCallbackHandler { void saveVisit(const std::string& publisher_id, const ledger::VisitData& visit_data, const uint64_t& duration); - bool saveVisitAllowed() const; void AddRecurringPayment(const std::string& publisher_id, const double& value); @@ -54,14 +53,14 @@ class BatPublishers : public ledger::LedgerCallbackHandler { void setPanelExclude(const std::string& publisher_id, const ledger::PUBLISHER_EXCLUDE& exclude, uint64_t windowId); - void restorePublishers(); + void RestorePublishers(); void setPublisherAllowNonVerified(const bool& allow); void setPublisherAllowVideos(const bool& allow); - void setBalanceReport(ledger::PUBLISHER_MONTH month, + void setBalanceReport(ledger::ACTIVITY_MONTH month, int year, const ledger::BalanceReportInfo& report_info); - bool getBalanceReport(ledger::PUBLISHER_MONTH month, + bool getBalanceReport(ledger::ACTIVITY_MONTH month, int year, ledger::BalanceReportInfo* report_info); std::map getAllBalanceReports(); @@ -76,7 +75,7 @@ class BatPublishers : public ledger::LedgerCallbackHandler { std::unique_ptr onPublisherInfoUpdated( ledger::Result result, std::unique_ptr); - std::string GetBalanceReportName(ledger::PUBLISHER_MONTH month, int year); + std::string GetBalanceReportName(ledger::ACTIVITY_MONTH month, int year); std::vector GetRecurringDonationList(); void RefreshPublishersList(const std::string & pubs_list); @@ -89,37 +88,33 @@ class BatPublishers : public ledger::LedgerCallbackHandler { void getPublisherBanner(const std::string& publisher_id, ledger::PublisherBannerCallback callback); - void setBalanceReportItem(ledger::PUBLISHER_MONTH month, + void setBalanceReportItem(ledger::ACTIVITY_MONTH month, int year, ledger::ReportType type, const std::string& probi); - ledger::PublisherInfoFilter CreatePublisherFilter( + ledger::ActivityInfoFilter CreateActivityFilter( const std::string& publisher_id, - ledger::PUBLISHER_CATEGORY category, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year); - ledger::PublisherInfoFilter CreatePublisherFilter( + ledger::ActivityInfoFilter CreateActivityFilter( const std::string& publisher_id, - ledger::PUBLISHER_CATEGORY category, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year, - ledger::PUBLISHER_EXCLUDE_FILTER excluded); + ledger::EXCLUDE_FILTER excluded); - ledger::PublisherInfoFilter CreatePublisherFilter( + ledger::ActivityInfoFilter CreateActivityFilter( const std::string& publisher_id, - ledger::PUBLISHER_CATEGORY category, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year, bool min_duration); - ledger::PublisherInfoFilter CreatePublisherFilter( + ledger::ActivityInfoFilter CreateActivityFilter( const std::string& publisher_id, - ledger::PUBLISHER_CATEGORY category, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year, - ledger::PUBLISHER_EXCLUDE_FILTER excluded, + ledger::EXCLUDE_FILTER excluded, bool min_duration, const uint64_t& currentReconcileStamp, bool non_verified); @@ -174,7 +169,7 @@ class BatPublishers : public ledger::LedgerCallbackHandler { ledger::Result result, std::unique_ptr publisher_info); - void onRestorePublishersInternal(const ledger::PublisherInfoList& publisherInfoList, uint32_t /* next_record */); + void OnRestorePublishersInternal(bool success); double concaveScore(const uint64_t& duration); diff --git a/vendor/bat-native-ledger/src/ledger_impl.cc b/vendor/bat-native-ledger/src/ledger_impl.cc index da0b9fe69937..f3198e65b5d4 100644 --- a/vendor/bat-native-ledger/src/ledger_impl.cc +++ b/vendor/bat-native-ledger/src/ledger_impl.cc @@ -298,8 +298,23 @@ std::string LedgerImpl::URIEncode(const std::string& value) { void LedgerImpl::SetPublisherInfo(std::unique_ptr info, ledger::PublisherInfoCallback callback) { - ledger_client_->SavePublisherInfo(std::move(info), - std::bind(&LedgerImpl::OnSetPublisherInfo, this, callback, _1, _2)); + ledger_client_->SavePublisherInfo( + std::move(info), + std::bind(&LedgerImpl::OnSetPublisherInfo, + this, + callback, + _1, + _2)); +} + +void LedgerImpl::SetActivityInfo(std::unique_ptr info, + ledger::PublisherInfoCallback callback) { + ledger_client_->SaveActivityInfo(std::move(info), + std::bind(&LedgerImpl::OnSetPublisherInfo, + this, + callback, + _1, + _2)); } void LedgerImpl::SetMediaPublisherInfo(const std::string& media_key, @@ -328,7 +343,11 @@ void LedgerImpl::SetPublisherPanelExclude(const std::string& publisher_id, } void LedgerImpl::RestorePublishers() { - bat_publishers_->restorePublishers(); + bat_publishers_->RestorePublishers(); +} + +void LedgerImpl::OnRestorePublishers(ledger::OnRestoreCallback callback) { + ledger_client_->OnRestorePublishers(callback); } void LedgerImpl::LoadNicewareList(ledger::GetNicewareListCallback callback) { @@ -346,10 +365,20 @@ std::vector LedgerImpl::GetRecurringDonationPublisherI return bat_publishers_->GetRecurringDonationList(); } -void LedgerImpl::GetPublisherInfo( - const ledger::PublisherInfoFilter& filter, +void LedgerImpl::GetPublisherInfo(const std::string& publisher_key, + ledger::PublisherInfoCallback callback) { + ledger_client_->LoadPublisherInfo(publisher_key, callback); +} + +void LedgerImpl::GetActivityInfo(const ledger::ActivityInfoFilter& filter, + ledger::PublisherInfoCallback callback) { + ledger_client_->LoadActivityInfo(filter, callback); +} + +void LedgerImpl::GetPanelPublisherInfo( + const ledger::ActivityInfoFilter& filter, ledger::PublisherInfoCallback callback) { - ledger_client_->LoadPublisherInfo(filter, callback); + ledger_client_->LoadPanelPublisherInfo(filter, callback); } void LedgerImpl::GetMediaPublisherInfo(const std::string& media_key, @@ -357,10 +386,12 @@ void LedgerImpl::GetMediaPublisherInfo(const std::string& media_key, ledger_client_->LoadMediaPublisherInfo(media_key, callback); } -void LedgerImpl::GetPublisherInfoList(uint32_t start, uint32_t limit, - const ledger::PublisherInfoFilter& filter, - ledger::PublisherInfoListCallback callback) { - ledger_client_->LoadPublisherInfoList(start, limit, filter, callback); +void LedgerImpl::GetActivityInfoList( + uint32_t start, + uint32_t limit, + const ledger::ActivityInfoFilter& filter, + ledger::PublisherInfoListCallback callback) { + ledger_client_->GetActivityInfoList(start, limit, filter, callback); } void LedgerImpl::SetRewardsMainEnabled(bool enabled) { @@ -477,7 +508,7 @@ void LedgerImpl::OnReconcileComplete(ledger::Result result, ledger_client_->OnReconcileComplete( result, viewing_id, - (ledger::PUBLISHER_CATEGORY)reconcile.category_, + (ledger::REWARDS_CATEGORY)reconcile.category_, probi); } @@ -586,7 +617,7 @@ void LedgerImpl::OnGrantFinish(ledger::Result result, const braveledger_bat_help ledger_client_->OnGrantFinish(result, newGrant); } -bool LedgerImpl::GetBalanceReport(ledger::PUBLISHER_MONTH month, +bool LedgerImpl::GetBalanceReport(ledger::ACTIVITY_MONTH month, int year, ledger::BalanceReportInfo* report_info) const { return bat_publishers_->getBalanceReport(month, year, report_info); @@ -596,7 +627,7 @@ std::map LedgerImpl::GetAllBalanceReport return bat_publishers_->getAllBalanceReports(); } -void LedgerImpl::SetBalanceReport(ledger::PUBLISHER_MONTH month, +void LedgerImpl::SetBalanceReport(ledger::ACTIVITY_MONTH month, int year, const ledger::BalanceReportInfo& report_info) { bat_publishers_->setBalanceReport(month, year, report_info); @@ -625,7 +656,7 @@ void LedgerImpl::DoDirectDonation(const ledger::PublisherInfo& publisher, ledger::PendingContribution contribution; contribution.publisher_key = publisher.id; contribution.amount = amount; - contribution.category = ledger::PUBLISHER_CATEGORY::DIRECT_DONATION; + contribution.category = ledger::REWARDS_CATEGORY::DIRECT_DONATION; ledger::PendingContributionList list; list.list_ = std::vector { contribution }; @@ -639,7 +670,7 @@ void LedgerImpl::DoDirectDonation(const ledger::PublisherInfo& publisher, auto direction_list = std::vector { direction }; braveledger_bat_helper::PublisherList list; bat_contribution_->StartReconcile(GenerateGUID(), - ledger::PUBLISHER_CATEGORY::DIRECT_DONATION, + ledger::REWARDS_CATEGORY::DIRECT_DONATION, list, direction_list); } @@ -785,7 +816,7 @@ void LedgerImpl::OnExcludedSitesChanged(const std::string& publisher_id) { ledger_client_->OnExcludedSitesChanged(publisher_id); } -void LedgerImpl::SetBalanceReportItem(ledger::PUBLISHER_MONTH month, +void LedgerImpl::SetBalanceReportItem(ledger::ACTIVITY_MONTH month, int year, ledger::ReportType type, const std::string& probi) { @@ -807,13 +838,13 @@ double LedgerImpl::GetBalance() { return bat_state_->GetBalance(); } -void LedgerImpl::OnReconcileCompleteSuccess(const std::string& viewing_id, - const ledger::PUBLISHER_CATEGORY category, - const std::string& probi, - const ledger::PUBLISHER_MONTH month, - const int year, - const uint32_t date) { - +void LedgerImpl::OnReconcileCompleteSuccess( + const std::string& viewing_id, + const ledger::REWARDS_CATEGORY category, + const std::string& probi, + const ledger::ACTIVITY_MONTH month, + const int year, + const uint32_t date) { bat_contribution_->OnReconcileCompleteSuccess(viewing_id, category, probi, @@ -838,23 +869,21 @@ void LedgerImpl::OnRemovedRecurring(ledger::Result result) { } } -ledger::PublisherInfoFilter LedgerImpl::CreatePublisherFilter( +ledger::ActivityInfoFilter LedgerImpl::CreateActivityFilter( const std::string& publisher_id, - ledger::PUBLISHER_CATEGORY category, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year, - ledger::PUBLISHER_EXCLUDE_FILTER excluded, + ledger::EXCLUDE_FILTER excluded, bool min_duration, const uint64_t& currentReconcileStamp, bool non_verified) { - return bat_publishers_->CreatePublisherFilter(publisher_id, - category, - month, - year, - excluded, - min_duration, - currentReconcileStamp, - non_verified); + return bat_publishers_->CreateActivityFilter(publisher_id, + month, + year, + excluded, + min_duration, + currentReconcileStamp, + non_verified); } @@ -1046,7 +1075,7 @@ void LedgerImpl::SaveContributionInfo(const std::string& probi, const int year, const uint32_t date, const std::string& publisher_key, - const ledger::PUBLISHER_CATEGORY category) { + const ledger::REWARDS_CATEGORY category) { ledger_client_->SaveContributionInfo(probi, month, year, diff --git a/vendor/bat-native-ledger/src/ledger_impl.h b/vendor/bat-native-ledger/src/ledger_impl.h index d6b4e3c40e75..ec5dd324939a 100644 --- a/vendor/bat-native-ledger/src/ledger_impl.h +++ b/vendor/bat-native-ledger/src/ledger_impl.h @@ -56,18 +56,27 @@ class LedgerImpl : public ledger::Ledger, void SetPublisherInfo(std::unique_ptr publisher_info, ledger::PublisherInfoCallback callback) override; - void GetPublisherInfo(const ledger::PublisherInfoFilter& filter, + void SetActivityInfo(std::unique_ptr publisher_info, + ledger::PublisherInfoCallback callback) override; + void GetPublisherInfo(const std::string& publisher_key, ledger::PublisherInfoCallback callback) override; + void GetActivityInfo(const ledger::ActivityInfoFilter& filter, + ledger::PublisherInfoCallback callback) override; + void GetPanelPublisherInfo(const ledger::ActivityInfoFilter& filter, + ledger::PublisherInfoCallback callback); void GetMediaPublisherInfo(const std::string& media_key, - ledger::PublisherInfoCallback callback) override; + ledger::PublisherInfoCallback callback) override; void SetMediaPublisherInfo(const std::string& media_key, - const std::string& publisher_id) override; + const std::string& publisher_id) override; std::vector GetRecurringDonationPublisherInfo() override; - void GetPublisherInfoList(uint32_t start, uint32_t limit, - const ledger::PublisherInfoFilter& filter, - ledger::PublisherInfoListCallback callback) override; + void GetActivityInfoList(uint32_t start, + uint32_t limit, + const ledger::ActivityInfoFilter& filter, + ledger::PublisherInfoListCallback callback) override; - void DoDirectDonation(const ledger::PublisherInfo& publisher, int amount, const std::string& currency) override; + void DoDirectDonation(const ledger::PublisherInfo& publisher, + int amount, + const std::string& currency) override; void SetRewardsMainEnabled(bool enabled) override; void SetPublisherMinVisitTime(uint64_t duration_in_seconds) override; @@ -78,7 +87,7 @@ class LedgerImpl : public ledger::Ledger, void SetUserChangedContribution() override; bool GetUserChangedContribution(); void SetAutoContribute(bool enabled) override; - void SetBalanceReport(ledger::PUBLISHER_MONTH month, + void SetBalanceReport(ledger::ACTIVITY_MONTH month, int year, const ledger::BalanceReportInfo& report_info) override; @@ -98,7 +107,7 @@ class LedgerImpl : public ledger::Ledger, bool GetPublisherAllowVideos() const override; double GetContributionAmount() const override; bool GetAutoContribute() const override; - bool GetBalanceReport(ledger::PUBLISHER_MONTH month, + bool GetBalanceReport(ledger::ACTIVITY_MONTH month, int year, ledger::BalanceReportInfo* report_info) const override; std::map GetAllBalanceReports() const override; @@ -157,6 +166,7 @@ class LedgerImpl : public ledger::Ledger, const ledger::PUBLISHER_EXCLUDE& exclude, uint64_t windowId) override; void RestorePublishers() override; + void OnRestorePublishers(ledger::OnRestoreCallback callback); bool IsWalletCreated() const override; void GetPublisherActivityFromUrl(uint64_t windowId, const ledger::VisitData& visit_data) override; void GetMediaActivityFromUrl(uint64_t windowId, @@ -166,7 +176,7 @@ class LedgerImpl : public ledger::Ledger, std::unique_ptr info, uint64_t windowId); void OnExcludedSitesChanged(const std::string& publisher_id); - void SetBalanceReportItem(ledger::PUBLISHER_MONTH month, + void SetBalanceReportItem(ledger::ACTIVITY_MONTH month, int year, ledger::ReportType type, const std::string& probi) override; @@ -180,19 +190,18 @@ class LedgerImpl : public ledger::Ledger, ledger::PublisherBannerCallback callback) override; double GetBalance() override; void OnReconcileCompleteSuccess(const std::string& viewing_id, - const ledger::PUBLISHER_CATEGORY category, + const ledger::REWARDS_CATEGORY category, const std::string& probi, - const ledger::PUBLISHER_MONTH month, + const ledger::ACTIVITY_MONTH month, const int year, const uint32_t date) override; void GetRecurringDonations(ledger::PublisherInfoListCallback callback); void RemoveRecurring(const std::string& publisher_key) override; - ledger::PublisherInfoFilter CreatePublisherFilter( + ledger::ActivityInfoFilter CreateActivityFilter( const std::string& publisher_id, - ledger::PUBLISHER_CATEGORY category, - ledger::PUBLISHER_MONTH month, + ledger::ACTIVITY_MONTH month, int year, - ledger::PUBLISHER_EXCLUDE_FILTER excluded, + ledger::EXCLUDE_FILTER excluded, bool min_duration, const uint64_t& currentReconcileStamp, bool non_verified); @@ -266,7 +275,7 @@ class LedgerImpl : public ledger::Ledger, const int year, const uint32_t date, const std::string& publisher_key, - const ledger::PUBLISHER_CATEGORY category); + const ledger::REWARDS_CATEGORY category); void NormalizeContributeWinners( ledger::PublisherInfoList* newList, diff --git a/vendor/bat-native-ledger/src/rapidjson_bat_helper.h b/vendor/bat-native-ledger/src/rapidjson_bat_helper.h index c973d55c1ab4..98a8967410a2 100644 --- a/vendor/bat-native-ledger/src/rapidjson_bat_helper.h +++ b/vendor/bat-native-ledger/src/rapidjson_bat_helper.h @@ -18,7 +18,7 @@ struct ContributionInfo; struct Grant; struct PublisherBanner; struct PublisherInfo; -struct PublisherInfoFilter; +struct ActivityInfoFilter; struct VisitData; struct WalletInfo; @@ -59,7 +59,7 @@ void saveToJson(JsonWriter & writer, const ledger::ContributionInfo&); void saveToJson(JsonWriter & writer, const ledger::Grant&); void saveToJson(JsonWriter & writer, const ledger::PublisherBanner&); void saveToJson(JsonWriter & writer, const ledger::PublisherInfo&); -void saveToJson(JsonWriter & writer, const ledger::PublisherInfoFilter&); +void saveToJson(JsonWriter & writer, const ledger::ActivityInfoFilter&); void saveToJson(JsonWriter & writer, const ledger::VisitData&); void saveToJson(JsonWriter & writer, const ledger::WalletInfo&); void saveToJson(JsonWriter & writer, const ledger::PendingContribution&); From 86b06f00ef8c8b24b1837abe476f7371b324364a Mon Sep 17 00:00:00 2001 From: Nejc Zdovc Date: Wed, 16 Jan 2019 07:09:08 +0100 Subject: [PATCH 2/2] Merge pull request #1355 from brave/publisher-refactor-normalize Fixes restore normalize --- vendor/bat-native-ledger/src/bat_publishers.cc | 7 ++++--- vendor/bat-native-ledger/src/bat_publishers.h | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/vendor/bat-native-ledger/src/bat_publishers.cc b/vendor/bat-native-ledger/src/bat_publishers.cc index aeb9f6bf0b5f..99cb8ad02ef7 100644 --- a/vendor/bat-native-ledger/src/bat_publishers.cc +++ b/vendor/bat-native-ledger/src/bat_publishers.cc @@ -303,7 +303,7 @@ std::unique_ptr BatPublishers::onPublisherInfoUpdated( return info; } - synopsisNormalizer(*info); + synopsisNormalizer(); return info; } @@ -367,7 +367,7 @@ void BatPublishers::onSetPublisherInfo(ledger::Result result, if (result != ledger::Result::LEDGER_OK) { return; } - synopsisNormalizer(*publisher_info); + synopsisNormalizer(); } void BatPublishers::onSetPanelExcludeInternal(ledger::PUBLISHER_EXCLUDE exclude, @@ -418,6 +418,7 @@ void BatPublishers::OnRestorePublishersInternal(bool success) { if (success) { setNumExcludedSites(0); OnExcludedSitesChanged(""); + synopsisNormalizer(); } else { BLOG(ledger_, ledger::LogLevel::LOG_ERROR) << "Could not restore publishers."; @@ -558,7 +559,7 @@ void BatPublishers::synopsisNormalizerInternal( } } -void BatPublishers::synopsisNormalizer(const ledger::PublisherInfo& info) { +void BatPublishers::synopsisNormalizer() { auto filter = CreateActivityFilter("", ledger::ACTIVITY_MONTH::ANY, -1, diff --git a/vendor/bat-native-ledger/src/bat_publishers.h b/vendor/bat-native-ledger/src/bat_publishers.h index c383e8018441..531e80bb02a9 100644 --- a/vendor/bat-native-ledger/src/bat_publishers.h +++ b/vendor/bat-native-ledger/src/bat_publishers.h @@ -177,7 +177,7 @@ class BatPublishers : public ledger::LedgerCallbackHandler { void calcScoreConsts(); - void synopsisNormalizer(const ledger::PublisherInfo& info); + void synopsisNormalizer(); void synopsisNormalizerInternal(ledger::PublisherInfoList* newList, bool saveData, const ledger::PublisherInfoList& list, uint32_t /* next_record */);