1 // Copyright (c) 2011 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 #ifndef COMPONENTS_HISTORY_CORE_BROWSER_TOP_SITES_BACKEND_H_
6 #define COMPONENTS_HISTORY_CORE_BROWSER_TOP_SITES_BACKEND_H_
7 
8 #include <memory>
9 
10 #include "base/callback.h"
11 #include "base/files/file_path.h"
12 #include "base/macros.h"
13 #include "base/memory/ref_counted.h"
14 #include "components/history/core/browser/history_types.h"
15 
16 namespace base {
17 class CancelableTaskTracker;
18 class FilePath;
19 class SequencedTaskRunner;
20 }
21 
22 namespace history {
23 
24 class TopSitesDatabase;
25 
26 // Service used by TopSites to have db interaction happen on the DB thread.  All
27 // public methods are invoked on the ui thread and get funneled to the DB
28 // thread.
29 class TopSitesBackend : public base::RefCountedThreadSafe<TopSitesBackend> {
30  public:
31   // TODO(yiyaoliu): Remove the enums and related code when crbug/223430 is
32   // fixed.
33   // An enum representing whether the UpdateTopSites execution time related
34   // histogram should be recorded.
35   enum RecordHistogram {
36     RECORD_HISTOGRAM_YES,
37     RECORD_HISTOGRAM_NO
38   };
39 
40   using GetMostVisitedSitesCallback =
41       base::OnceCallback<void(MostVisitedURLList)>;
42 
43   TopSitesBackend();
44 
45   void Init(const base::FilePath& path);
46 
47   // Schedules the db to be shutdown.
48   void Shutdown();
49 
50   // Fetches MostVisitedURLList.
51   void GetMostVisitedSites(GetMostVisitedSitesCallback callback,
52                            base::CancelableTaskTracker* tracker);
53 
54   // Updates top sites database from the specified delta.
55   void UpdateTopSites(const TopSitesDelta& delta,
56                       const RecordHistogram record_or_not);
57 
58   // Deletes the database and recreates it.
59   void ResetDatabase();
60 
61  private:
62   friend class base::RefCountedThreadSafe<TopSitesBackend>;
63 
64   ~TopSitesBackend();
65 
66   // Invokes Init on the db_.
67   void InitDBOnDBThread(const base::FilePath& path);
68 
69   // Shuts down the db.
70   void ShutdownDBOnDBThread();
71 
72   // Does the work of getting the most visited sites.
73   MostVisitedURLList GetMostVisitedSitesOnDBThread();
74 
75   // Updates top sites.
76   void UpdateTopSitesOnDBThread(const TopSitesDelta& delta,
77                                 const RecordHistogram record_or_not);
78 
79   // Resets the database.
80   void ResetDatabaseOnDBThread(const base::FilePath& file_path);
81 
82   base::FilePath db_path_;
83 
84   std::unique_ptr<TopSitesDatabase> db_;
85   scoped_refptr<base::SequencedTaskRunner> db_task_runner_;
86 
87   DISALLOW_COPY_AND_ASSIGN(TopSitesBackend);
88 };
89 
90 }  // namespace history
91 
92 #endif  // COMPONENTS_HISTORY_CORE_BROWSER_TOP_SITES_BACKEND_H_
93