1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "chrome/browser/android/explore_sites/record_site_click_task.h"
6 
7 #include "base/bind.h"
8 #include "chrome/browser/android/explore_sites/explore_sites_schema.h"
9 #include "components/offline_pages/core/offline_clock.h"
10 #include "sql/database.h"
11 #include "sql/meta_table.h"
12 #include "sql/statement.h"
13 #include "sql/transaction.h"
14 
15 namespace explore_sites {
16 namespace {
17 
18 static const char kRecordSiteSql[] = R"(INSERT INTO activity
19 (time, url, category_type)
20 VALUES
21 (?, ?, ?);)";
22 
23 static const char kDeleteLeastRecentActivitySql[] = R"(DELETE FROM activity
24 WHERE rowid NOT IN (SELECT rowid FROM activity ORDER BY time DESC LIMIT 200);)";
25 
RecordSiteClickTaskSync(std::string url,int category_type,sql::Database * db)26 bool RecordSiteClickTaskSync(std::string url,
27                              int category_type,
28                              sql::Database* db) {
29   if (!db || url.empty())
30     return false;
31 
32   sql::Transaction transaction(db);
33   if (!transaction.Begin())
34     return false;
35 
36   // Get current time as a unit time.
37   base::Time time_now = offline_pages::OfflineTimeNow();
38   time_t unix_time = time_now.ToTimeT();
39 
40   sql::Statement insert_activity_statement(
41       db->GetCachedStatement(SQL_FROM_HERE, kRecordSiteSql));
42   int col = 0;
43   insert_activity_statement.BindInt64(col++, unix_time);
44   insert_activity_statement.BindString(col++, url);
45   insert_activity_statement.BindInt(col++, category_type);
46   insert_activity_statement.Run();
47 
48   // Remove least recent activities if table greater than the limit.
49   sql::Statement remove_activity_statement(
50       db->GetCachedStatement(SQL_FROM_HERE, kDeleteLeastRecentActivitySql));
51   remove_activity_statement.Run();
52   return transaction.Commit();
53 }
54 }  // namespace
55 
RecordSiteClickTask(ExploreSitesStore * store,std::string url,int category_type)56 RecordSiteClickTask::RecordSiteClickTask(ExploreSitesStore* store,
57                                          std::string url,
58                                          int category_type)
59     : store_(store), url_(url), category_type_(category_type) {}
60 
61 RecordSiteClickTask::~RecordSiteClickTask() = default;
62 
Run()63 void RecordSiteClickTask::Run() {
64   store_->Execute(
65       base::BindOnce(&RecordSiteClickTaskSync, url_, category_type_),
66       base::BindOnce(&RecordSiteClickTask::FinishedExecuting,
67                      weak_ptr_factory_.GetWeakPtr()),
68       false);
69 }
70 
FinishedExecuting(bool result)71 void RecordSiteClickTask::FinishedExecuting(bool result) {
72   complete_ = true;
73   result_ = result;
74   TaskComplete();
75 }
76 }  // namespace explore_sites
77