most_visited_handler.cc revision f2477e01787aa58f445919b809d89e252beef54f
1// Copyright (c) 2012 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/ui/webui/ntp/most_visited_handler.h"
6
7#include <set>
8
9#include "base/bind.h"
10#include "base/bind_helpers.h"
11#include "base/command_line.h"
12#include "base/md5.h"
13#include "base/memory/scoped_vector.h"
14#include "base/memory/singleton.h"
15#include "base/metrics/histogram.h"
16#include "base/prefs/pref_service.h"
17#include "base/prefs/scoped_user_pref_update.h"
18#include "base/strings/string16.h"
19#include "base/strings/string_number_conversions.h"
20#include "base/strings/utf_string_conversions.h"
21#include "base/threading/thread.h"
22#include "base/values.h"
23#include "chrome/browser/chrome_notification_types.h"
24#include "chrome/browser/history/most_visited_tiles_experiment.h"
25#include "chrome/browser/history/page_usage_data.h"
26#include "chrome/browser/history/top_sites.h"
27#include "chrome/browser/profiles/profile.h"
28#include "chrome/browser/ui/browser.h"
29#include "chrome/browser/ui/browser_finder.h"
30#include "chrome/browser/ui/tabs/tab_strip_model.h"
31#include "chrome/browser/ui/tabs/tab_strip_model_utils.h"
32#include "chrome/browser/ui/webui/favicon_source.h"
33#include "chrome/browser/ui/webui/ntp/new_tab_ui.h"
34#include "chrome/browser/ui/webui/ntp/ntp_stats.h"
35#include "chrome/browser/ui/webui/ntp/thumbnail_list_source.h"
36#include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
37#include "chrome/common/pref_names.h"
38#include "chrome/common/url_constants.h"
39#include "components/user_prefs/pref_registry_syncable.h"
40#include "content/public/browser/navigation_controller.h"
41#include "content/public/browser/navigation_entry.h"
42#include "content/public/browser/notification_source.h"
43#include "content/public/browser/url_data_source.h"
44#include "content/public/browser/user_metrics.h"
45#include "content/public/browser/web_contents.h"
46#include "content/public/browser/web_ui.h"
47#include "grit/chromium_strings.h"
48#include "grit/generated_resources.h"
49#include "grit/locale_settings.h"
50#include "ui/base/l10n/l10n_util.h"
51#include "url/gurl.h"
52
53using content::UserMetricsAction;
54
55MostVisitedHandler::MostVisitedHandler()
56    : got_first_most_visited_request_(false),
57      most_visited_viewed_(false),
58      user_action_logged_(false),
59      weak_ptr_factory_(this) {
60}
61
62MostVisitedHandler::~MostVisitedHandler() {
63  if (!user_action_logged_ && most_visited_viewed_) {
64    const GURL ntp_url = GURL(chrome::kChromeUINewTabURL);
65    int action_id = NTP_FOLLOW_ACTION_OTHER;
66    content::NavigationEntry* entry =
67        web_ui()->GetWebContents()->GetController().GetLastCommittedEntry();
68    if (entry && (entry->GetURL() != ntp_url)) {
69      action_id =
70          content::PageTransitionStripQualifier(entry->GetTransitionType());
71    }
72
73    UMA_HISTOGRAM_ENUMERATION("NewTabPage.MostVisitedAction", action_id,
74                              NUM_NTP_FOLLOW_ACTIONS);
75  }
76}
77
78void MostVisitedHandler::RegisterMessages() {
79  Profile* profile = Profile::FromWebUI(web_ui());
80  // Set up our sources for thumbnail and favicon data.
81  content::URLDataSource::Add(profile, new ThumbnailSource(profile, false));
82  content::URLDataSource::Add(profile, new ThumbnailSource(profile, true));
83
84  // Set up our sources for top-sites data.
85  content::URLDataSource::Add(profile, new ThumbnailListSource(profile));
86
87#if defined(OS_ANDROID)
88  // Register chrome://touch-icon as a data source for touch icons or favicons.
89  content::URLDataSource::Add(profile,
90                              new FaviconSource(profile, FaviconSource::ANY));
91#endif
92  // Register chrome://favicon as a data source for favicons.
93  content::URLDataSource::Add(
94      profile, new FaviconSource(profile, FaviconSource::FAVICON));
95
96  history::TopSites* ts = profile->GetTopSites();
97  if (ts) {
98    // TopSites updates itself after a delay. This is especially noticable when
99    // your profile is empty. Ask TopSites to update itself when we're about to
100    // show the new tab page.
101    ts->SyncWithHistory();
102
103    // Register for notification when TopSites changes so that we can update
104    // ourself.
105    registrar_.Add(this, chrome::NOTIFICATION_TOP_SITES_CHANGED,
106                   content::Source<history::TopSites>(ts));
107  }
108
109  // We pre-emptively make a fetch for the most visited pages so we have the
110  // results sooner.
111  StartQueryForMostVisited();
112
113  web_ui()->RegisterMessageCallback("getMostVisited",
114      base::Bind(&MostVisitedHandler::HandleGetMostVisited,
115                 base::Unretained(this)));
116
117  // Register ourselves for any most-visited item blacklisting.
118  web_ui()->RegisterMessageCallback("blacklistURLFromMostVisited",
119      base::Bind(&MostVisitedHandler::HandleBlacklistUrl,
120                 base::Unretained(this)));
121  web_ui()->RegisterMessageCallback("removeURLsFromMostVisitedBlacklist",
122      base::Bind(&MostVisitedHandler::HandleRemoveUrlsFromBlacklist,
123                 base::Unretained(this)));
124  web_ui()->RegisterMessageCallback("clearMostVisitedURLsBlacklist",
125      base::Bind(&MostVisitedHandler::HandleClearBlacklist,
126                 base::Unretained(this)));
127  web_ui()->RegisterMessageCallback("mostVisitedAction",
128      base::Bind(&MostVisitedHandler::HandleMostVisitedAction,
129                 base::Unretained(this)));
130  web_ui()->RegisterMessageCallback("mostVisitedSelected",
131      base::Bind(&MostVisitedHandler::HandleMostVisitedSelected,
132                 base::Unretained(this)));
133}
134
135void MostVisitedHandler::HandleGetMostVisited(const ListValue* args) {
136  if (!got_first_most_visited_request_) {
137    // If our initial data is already here, return it.
138    SendPagesValue();
139    got_first_most_visited_request_ = true;
140  } else {
141    StartQueryForMostVisited();
142  }
143}
144
145void MostVisitedHandler::SendPagesValue() {
146  if (pages_value_) {
147    Profile* profile = Profile::FromWebUI(web_ui());
148    const DictionaryValue* url_blacklist =
149        profile->GetPrefs()->GetDictionary(prefs::kNtpMostVisitedURLsBlacklist);
150    bool has_blacklisted_urls = !url_blacklist->empty();
151    history::TopSites* ts = profile->GetTopSites();
152    if (ts) {
153      has_blacklisted_urls = ts->HasBlacklistedItems();
154
155      MaybeRemovePageValues();
156    }
157
158    base::FundamentalValue has_blacklisted_urls_value(has_blacklisted_urls);
159    web_ui()->CallJavascriptFunction("ntp.setMostVisitedPages",
160                                     *pages_value_,
161                                     has_blacklisted_urls_value);
162    pages_value_.reset();
163  }
164}
165
166void MostVisitedHandler::StartQueryForMostVisited() {
167  history::TopSites* ts = Profile::FromWebUI(web_ui())->GetTopSites();
168  if (ts) {
169    ts->GetMostVisitedURLs(
170        base::Bind(&MostVisitedHandler::OnMostVisitedUrlsAvailable,
171                   weak_ptr_factory_.GetWeakPtr()), false);
172  }
173}
174
175void MostVisitedHandler::HandleBlacklistUrl(const ListValue* args) {
176  std::string url = UTF16ToUTF8(ExtractStringValue(args));
177  BlacklistUrl(GURL(url));
178}
179
180void MostVisitedHandler::HandleRemoveUrlsFromBlacklist(const ListValue* args) {
181  DCHECK(args->GetSize() != 0);
182
183  for (ListValue::const_iterator iter = args->begin();
184       iter != args->end(); ++iter) {
185    std::string url;
186    bool r = (*iter)->GetAsString(&url);
187    if (!r) {
188      NOTREACHED();
189      return;
190    }
191    content::RecordAction(UserMetricsAction("MostVisited_UrlRemoved"));
192    history::TopSites* ts = Profile::FromWebUI(web_ui())->GetTopSites();
193    if (ts)
194      ts->RemoveBlacklistedURL(GURL(url));
195  }
196}
197
198void MostVisitedHandler::HandleClearBlacklist(const ListValue* args) {
199  content::RecordAction(UserMetricsAction("MostVisited_BlacklistCleared"));
200
201  history::TopSites* ts = Profile::FromWebUI(web_ui())->GetTopSites();
202  if (ts)
203    ts->ClearBlacklistedURLs();
204}
205
206void MostVisitedHandler::HandleMostVisitedAction(const base::ListValue* args) {
207  DCHECK(args);
208
209  double action_id;
210  if (!args->GetDouble(0, &action_id))
211    NOTREACHED();
212
213  UMA_HISTOGRAM_ENUMERATION("NewTabPage.MostVisitedAction",
214                            static_cast<int>(action_id),
215                            NUM_NTP_FOLLOW_ACTIONS);
216  most_visited_viewed_ = true;
217  user_action_logged_ = true;
218}
219
220void MostVisitedHandler::HandleMostVisitedSelected(
221    const base::ListValue* args) {
222  most_visited_viewed_ = true;
223}
224
225void MostVisitedHandler::SetPagesValueFromTopSites(
226    const history::MostVisitedURLList& data) {
227  pages_value_.reset(new ListValue);
228
229  history::MostVisitedURLList top_sites(data);
230  history::MostVisitedTilesExperiment::MaybeShuffle(&top_sites);
231
232  for (size_t i = 0; i < top_sites.size(); i++) {
233    const history::MostVisitedURL& url = top_sites[i];
234    DictionaryValue* page_value = new DictionaryValue();
235    if (url.url.is_empty()) {
236      page_value->SetBoolean("filler", true);
237      pages_value_->Append(page_value);
238      continue;
239    }
240
241    NewTabUI::SetUrlTitleAndDirection(page_value,
242                                      url.title,
243                                      url.url);
244    pages_value_->Append(page_value);
245  }
246}
247
248void MostVisitedHandler::OnMostVisitedUrlsAvailable(
249    const history::MostVisitedURLList& data) {
250  SetPagesValueFromTopSites(data);
251  if (got_first_most_visited_request_) {
252    SendPagesValue();
253  }
254}
255
256void MostVisitedHandler::Observe(int type,
257                                 const content::NotificationSource& source,
258                                 const content::NotificationDetails& details) {
259  DCHECK_EQ(type, chrome::NOTIFICATION_TOP_SITES_CHANGED);
260
261  // Most visited urls changed, query again.
262  StartQueryForMostVisited();
263}
264
265void MostVisitedHandler::BlacklistUrl(const GURL& url) {
266  history::TopSites* ts = Profile::FromWebUI(web_ui())->GetTopSites();
267  if (ts)
268    ts->AddBlacklistedURL(url);
269  content::RecordAction(UserMetricsAction("MostVisited_UrlBlacklisted"));
270}
271
272std::string MostVisitedHandler::GetDictionaryKeyForUrl(const std::string& url) {
273  return base::MD5String(url);
274}
275
276void MostVisitedHandler::MaybeRemovePageValues() {
277// The code below uses APIs not available on Android and the experiment should
278// not run there.
279#if !defined(OS_ANDROID)
280  if (!history::MostVisitedTilesExperiment::IsDontShowOpenURLsEnabled())
281    return;
282
283  TabStripModel* tab_strip_model = chrome::FindBrowserWithWebContents(
284      web_ui()->GetWebContents())->tab_strip_model();
285  history::TopSites* top_sites = Profile::FromWebUI(web_ui())->GetTopSites();
286  if (!tab_strip_model || !top_sites) {
287    NOTREACHED();
288    return;
289  }
290
291  std::set<std::string> open_urls;
292  chrome::GetOpenUrls(*tab_strip_model, *top_sites, &open_urls);
293  history::MostVisitedTilesExperiment::RemovePageValuesMatchingOpenTabs(
294      open_urls,
295      pages_value_.get());
296#endif
297}
298
299// static
300void MostVisitedHandler::RegisterProfilePrefs(
301    user_prefs::PrefRegistrySyncable* registry) {
302  registry->RegisterDictionaryPref(
303      prefs::kNtpMostVisitedURLsBlacklist,
304      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
305}
306