zero_suggest_provider.cc revision 68043e1e95eeb07d5cae7aca370b26518b0867d6
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/autocomplete/zero_suggest_provider.h"
6
7#include "base/callback.h"
8#include "base/i18n/case_conversion.h"
9#include "base/json/json_string_value_serializer.h"
10#include "base/metrics/histogram.h"
11#include "base/prefs/pref_service.h"
12#include "base/strings/string16.h"
13#include "base/strings/string_util.h"
14#include "base/strings/utf_string_conversions.h"
15#include "base/time/time.h"
16#include "chrome/browser/autocomplete/autocomplete_classifier.h"
17#include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
18#include "chrome/browser/autocomplete/autocomplete_input.h"
19#include "chrome/browser/autocomplete/autocomplete_match.h"
20#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
21#include "chrome/browser/autocomplete/history_url_provider.h"
22#include "chrome/browser/autocomplete/search_provider.h"
23#include "chrome/browser/autocomplete/url_prefix.h"
24#include "chrome/browser/google/google_util.h"
25#include "chrome/browser/history/history_types.h"
26#include "chrome/browser/history/top_sites.h"
27#include "chrome/browser/metrics/variations/variations_http_header_provider.h"
28#include "chrome/browser/omnibox/omnibox_field_trial.h"
29#include "chrome/browser/profiles/profile.h"
30#include "chrome/browser/search/search.h"
31#include "chrome/browser/search_engines/template_url_service.h"
32#include "chrome/browser/search_engines/template_url_service_factory.h"
33#include "chrome/browser/sync/profile_sync_service.h"
34#include "chrome/browser/sync/profile_sync_service_factory.h"
35#include "chrome/common/net/url_fixer_upper.h"
36#include "chrome/common/pref_names.h"
37#include "chrome/common/url_constants.h"
38#include "net/base/escape.h"
39#include "net/base/load_flags.h"
40#include "net/base/net_util.h"
41#include "net/http/http_request_headers.h"
42#include "net/http/http_response_headers.h"
43#include "net/url_request/url_fetcher.h"
44#include "net/url_request/url_request_status.h"
45#include "url/gurl.h"
46
47namespace {
48
49// TODO(hfung): The histogram code was copied and modified from
50// search_provider.cc.  Refactor and consolidate the code.
51// We keep track in a histogram how many suggest requests we send, how
52// many suggest requests we invalidate (e.g., due to a user typing
53// another character), and how many replies we receive.
54// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
55//     (excluding the end-of-list enum value)
56// We do not want values of existing enums to change or else it screws
57// up the statistics.
58enum ZeroSuggestRequestsHistogramValue {
59  ZERO_SUGGEST_REQUEST_SENT = 1,
60  ZERO_SUGGEST_REQUEST_INVALIDATED,
61  ZERO_SUGGEST_REPLY_RECEIVED,
62  ZERO_SUGGEST_MAX_REQUEST_HISTOGRAM_VALUE
63};
64
65void LogOmniboxZeroSuggestRequest(
66    ZeroSuggestRequestsHistogramValue request_value) {
67  UMA_HISTOGRAM_ENUMERATION("Omnibox.ZeroSuggestRequests", request_value,
68                            ZERO_SUGGEST_MAX_REQUEST_HISTOGRAM_VALUE);
69}
70
71// The maximum relevance of the top match from this provider.
72const int kDefaultVerbatimZeroSuggestRelevance = 1300;
73
74// Relevance value to use if it was not set explicitly by the server.
75const int kDefaultZeroSuggestRelevance = 100;
76
77}  // namespace
78
79// static
80ZeroSuggestProvider* ZeroSuggestProvider::Create(
81    AutocompleteProviderListener* listener,
82    Profile* profile) {
83  return new ZeroSuggestProvider(listener, profile);
84}
85
86void ZeroSuggestProvider::Start(const AutocompleteInput& input,
87                                bool /*minimal_changes*/) {
88}
89
90void ZeroSuggestProvider::Stop(bool clear_cached_results) {
91  if (have_pending_request_)
92    LogOmniboxZeroSuggestRequest(ZERO_SUGGEST_REQUEST_INVALIDATED);
93  have_pending_request_ = false;
94  fetcher_.reset();
95  done_ = true;
96  if (clear_cached_results) {
97    query_matches_map_.clear();
98    navigation_results_.clear();
99    current_query_.clear();
100    matches_.clear();
101  }
102}
103
104void ZeroSuggestProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
105  provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
106  metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
107  new_entry.set_provider(AsOmniboxEventProviderType());
108  new_entry.set_provider_done(done_);
109  std::vector<uint32> field_trial_hashes;
110  OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes);
111  for (size_t i = 0; i < field_trial_hashes.size(); ++i) {
112    if (field_trial_triggered_)
113      new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]);
114    if (field_trial_triggered_in_session_) {
115      new_entry.mutable_field_trial_triggered_in_session()->Add(
116          field_trial_hashes[i]);
117     }
118  }
119}
120
121void ZeroSuggestProvider::ResetSession() {
122  // The user has started editing in the omnibox, so leave
123  // |field_trial_triggered_in_session_| unchanged and set
124  // |field_trial_triggered_| to false since zero suggest is inactive now.
125  field_trial_triggered_ = false;
126  Stop(true);
127}
128
129void ZeroSuggestProvider::OnURLFetchComplete(const net::URLFetcher* source) {
130  have_pending_request_ = false;
131  LogOmniboxZeroSuggestRequest(ZERO_SUGGEST_REPLY_RECEIVED);
132
133  std::string json_data;
134  source->GetResponseAsString(&json_data);
135  const bool request_succeeded =
136      source->GetStatus().is_success() && source->GetResponseCode() == 200;
137
138  if (request_succeeded) {
139    JSONStringValueSerializer deserializer(json_data);
140    deserializer.set_allow_trailing_comma(true);
141    scoped_ptr<Value> data(deserializer.Deserialize(NULL, NULL));
142    if (data.get())
143      ParseSuggestResults(*data.get());
144  }
145  done_ = true;
146
147  ConvertResultsToAutocompleteMatches();
148  if (!matches_.empty())
149    listener_->OnProviderUpdate(true);
150}
151
152void ZeroSuggestProvider::StartZeroSuggest(
153    const GURL& url,
154    AutocompleteInput::PageClassification page_classification,
155    const string16& permanent_text) {
156  Stop(true);
157  field_trial_triggered_ = false;
158  field_trial_triggered_in_session_ = false;
159  if (!ShouldRunZeroSuggest(url))
160    return;
161  verbatim_relevance_ = kDefaultVerbatimZeroSuggestRelevance;
162  done_ = false;
163  permanent_text_ = permanent_text;
164  current_query_ = url.spec();
165  current_page_classification_ = page_classification;
166  current_url_match_ = MatchForCurrentURL();
167  // TODO(jered): Consider adding locally-sourced zero-suggestions here too.
168  // These may be useful on the NTP or more relevant to the user than server
169  // suggestions, if based on local browsing history.
170  Run();
171}
172
173ZeroSuggestProvider::ZeroSuggestProvider(
174  AutocompleteProviderListener* listener,
175  Profile* profile)
176    : AutocompleteProvider(listener, profile,
177          AutocompleteProvider::TYPE_ZERO_SUGGEST),
178      template_url_service_(TemplateURLServiceFactory::GetForProfile(profile)),
179      have_pending_request_(false),
180      verbatim_relevance_(kDefaultVerbatimZeroSuggestRelevance),
181      field_trial_triggered_(false),
182      field_trial_triggered_in_session_(false),
183      weak_ptr_factory_(this) {
184}
185
186ZeroSuggestProvider::~ZeroSuggestProvider() {
187}
188
189bool ZeroSuggestProvider::ShouldRunZeroSuggest(const GURL& url) const {
190  if (!ShouldSendURL(url))
191    return false;
192
193  // Don't run if there's no profile or in incognito mode.
194  if (profile_ == NULL || profile_->IsOffTheRecord())
195    return false;
196
197  // Don't run if we can't get preferences or search suggest is not enabled.
198  PrefService* prefs = profile_->GetPrefs();
199  if (prefs == NULL || !prefs->GetBoolean(prefs::kSearchSuggestEnabled))
200    return false;
201
202  ProfileSyncService* service =
203      ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_);
204  browser_sync::SyncPrefs sync_prefs(prefs);
205
206  // ZeroSuggest requires sending the current URL to the suggest provider, so we
207  // only want to enable it if the user is willing to have this data sent.
208  // Because tab sync involves sending the same data, we currently use
209  // "tab sync is enabled and tab sync data is unencrypted" as a proxy for
210  // "the user is OK with sending this data".  We might someday want to change
211  // this to a standalone setting or part of some other explicit general opt-in.
212  if (!OmniboxFieldTrial::InZeroSuggestFieldTrial() ||
213      service == NULL ||
214      !service->IsSyncEnabledAndLoggedIn() ||
215      !sync_prefs.GetPreferredDataTypes(syncer::UserTypes()).Has(
216          syncer::PROXY_TABS) ||
217      service->GetEncryptedDataTypes().Has(syncer::SESSIONS)) {
218    return false;
219  }
220  return true;
221}
222
223bool ZeroSuggestProvider::ShouldSendURL(const GURL& url) const {
224  if (!url.is_valid())
225    return false;
226
227  // Only allow HTTP URLs or Google HTTPS URLs (including Google search
228  // result pages).  For the latter case, Google was already sent the HTTPS
229  // URLs when requesting the page, so the information is just re-sent.
230  return (url.scheme() == content::kHttpScheme) ||
231      google_util::IsGoogleDomainUrl(url, google_util::ALLOW_SUBDOMAIN,
232                                     google_util::ALLOW_NON_STANDARD_PORTS);
233}
234
235void ZeroSuggestProvider::FillResults(
236    const Value& root_val,
237    int* verbatim_relevance,
238    SearchProvider::SuggestResults* suggest_results,
239    SearchProvider::NavigationResults* navigation_results) {
240  string16 query;
241  const ListValue* root_list = NULL;
242  const ListValue* results = NULL;
243  const ListValue* relevances = NULL;
244  // The response includes the query, which should be empty for ZeroSuggest
245  // responses.
246  if (!root_val.GetAsList(&root_list) || !root_list->GetString(0, &query) ||
247      (!query.empty()) || !root_list->GetList(1, &results))
248    return;
249
250  // 3rd element: Description list.
251  const ListValue* descriptions = NULL;
252  root_list->GetList(2, &descriptions);
253
254  // 4th element: Disregard the query URL list for now.
255
256  // Reset suggested relevance information from the provider.
257  *verbatim_relevance = kDefaultVerbatimZeroSuggestRelevance;
258
259  // 5th element: Optional key-value pairs from the Suggest server.
260  const ListValue* types = NULL;
261  const DictionaryValue* extras = NULL;
262  if (root_list->GetDictionary(4, &extras)) {
263    extras->GetList("google:suggesttype", &types);
264
265    // Discard this list if its size does not match that of the suggestions.
266    if (extras->GetList("google:suggestrelevance", &relevances) &&
267        relevances->GetSize() != results->GetSize())
268      relevances = NULL;
269    extras->GetInteger("google:verbatimrelevance", verbatim_relevance);
270
271    // Check if the active suggest field trial (if any) has triggered.
272    bool triggered = false;
273    extras->GetBoolean("google:fieldtrialtriggered", &triggered);
274    field_trial_triggered_ |= triggered;
275    field_trial_triggered_in_session_ |= triggered;
276  }
277
278  // Clear the previous results now that new results are available.
279  suggest_results->clear();
280  navigation_results->clear();
281
282  string16 result, title;
283  std::string type;
284  for (size_t index = 0; results->GetString(index, &result); ++index) {
285    // Google search may return empty suggestions for weird input characters,
286    // they make no sense at all and can cause problems in our code.
287    if (result.empty())
288      continue;
289
290    int relevance = kDefaultZeroSuggestRelevance;
291
292    // Apply valid suggested relevance scores; discard invalid lists.
293    if (relevances != NULL && !relevances->GetInteger(index, &relevance))
294      relevances = NULL;
295    if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
296      // Do not blindly trust the URL coming from the server to be valid.
297      GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(result), std::string()));
298      if (url.is_valid()) {
299        if (descriptions != NULL)
300          descriptions->GetString(index, &title);
301        navigation_results->push_back(SearchProvider::NavigationResult(
302            *this, url, title, false, relevance, relevances != NULL));
303      }
304    } else {
305      suggest_results->push_back(SearchProvider::SuggestResult(
306          result, false, relevance, relevances != NULL, false));
307    }
308  }
309}
310
311void ZeroSuggestProvider::AddSuggestResultsToMap(
312    const SearchProvider::SuggestResults& results,
313    const TemplateURL* template_url,
314    SearchProvider::MatchMap* map) {
315  for (size_t i = 0; i < results.size(); ++i) {
316    AddMatchToMap(results[i].relevance(), AutocompleteMatchType::SEARCH_SUGGEST,
317                  template_url, results[i].suggestion(), i, map);
318  }
319}
320
321void ZeroSuggestProvider::AddMatchToMap(int relevance,
322                                        AutocompleteMatch::Type type,
323                                        const TemplateURL* template_url,
324                                        const string16& query_string,
325                                        int accepted_suggestion,
326                                        SearchProvider::MatchMap* map) {
327  // Pass in query_string as the input_text since we don't want any bolding.
328  // TODO(samarth|melevin): use the actual omnibox margin here as well instead
329  // of passing in -1.
330  AutocompleteMatch match = SearchProvider::CreateSearchSuggestion(
331      this, relevance, type, template_url, query_string, query_string,
332      AutocompleteInput(), false, accepted_suggestion, -1, true);
333  if (!match.destination_url.is_valid())
334    return;
335
336  // Try to add |match| to |map|.  If a match for |query_string| is already in
337  // |map|, replace it if |match| is more relevant.
338  // NOTE: Keep this ToLower() call in sync with url_database.cc.
339  const std::pair<SearchProvider::MatchMap::iterator, bool> i(map->insert(
340      std::make_pair(base::i18n::ToLower(query_string), match)));
341  // NOTE: We purposefully do a direct relevance comparison here instead of
342  // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
343  // first" rather than "items alphabetically first" when the scores are equal.
344  // The only case this matters is when a user has results with the same score
345  // that differ only by capitalization; because the history system returns
346  // results sorted by recency, this means we'll pick the most recent such
347  // result even if the precision of our relevance score is too low to
348  // distinguish the two.
349  if (!i.second && (match.relevance > i.first->second.relevance))
350    i.first->second = match;
351}
352
353AutocompleteMatch ZeroSuggestProvider::NavigationToMatch(
354    const SearchProvider::NavigationResult& navigation) {
355  AutocompleteMatch match(this, navigation.relevance(), false,
356                          AutocompleteMatchType::NAVSUGGEST);
357  match.destination_url = navigation.url();
358
359  const std::string languages(
360      profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
361  match.contents = net::FormatUrl(navigation.url(), languages,
362      net::kFormatUrlOmitAll, net::UnescapeRule::SPACES, NULL, NULL, NULL);
363  match.fill_into_edit +=
364      AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
365          match.contents);
366
367  AutocompleteMatch::ClassifyLocationInString(string16::npos, 0,
368      match.contents.length(), ACMatchClassification::URL,
369      &match.contents_class);
370
371  match.description =
372      AutocompleteMatch::SanitizeString(navigation.description());
373  AutocompleteMatch::ClassifyLocationInString(string16::npos, 0,
374      match.description.length(), ACMatchClassification::NONE,
375      &match.description_class);
376  return match;
377}
378
379void ZeroSuggestProvider::Run() {
380  have_pending_request_ = false;
381  const int kFetcherID = 1;
382
383  const TemplateURL* default_provider =
384     template_url_service_->GetDefaultSearchProvider();
385  // TODO(hfung): Generalize if the default provider supports zero suggest.
386  // Only make the request if we know that the provider supports zero suggest
387  // (currently only the prepopulated Google provider).
388  if (default_provider == NULL || !default_provider->SupportsReplacement() ||
389      default_provider->prepopulate_id() != 1) {
390    Stop(true);
391    return;
392  }
393  string16 prefix;
394  TemplateURLRef::SearchTermsArgs search_term_args(prefix);
395  search_term_args.zero_prefix_url = current_query_;
396  std::string req_url = default_provider->suggestions_url_ref().
397      ReplaceSearchTerms(search_term_args);
398  GURL suggest_url(req_url);
399  // Make sure we are sending the suggest request through HTTPS.
400  if (!suggest_url.SchemeIs(content::kHttpsScheme)) {
401    Stop(true);
402    return;
403  }
404
405  fetcher_.reset(
406      net::URLFetcher::Create(kFetcherID,
407          suggest_url,
408          net::URLFetcher::GET, this));
409  fetcher_->SetRequestContext(profile_->GetRequestContext());
410  fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
411  // Add Chrome experiment state to the request headers.
412  net::HttpRequestHeaders headers;
413  chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
414      fetcher_->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
415  fetcher_->SetExtraRequestHeaders(headers.ToString());
416
417  fetcher_->Start();
418
419  if (OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial()) {
420    most_visited_urls_.clear();
421    history::TopSites* ts = profile_->GetTopSites();
422    if (ts) {
423      ts->GetMostVisitedURLs(
424          base::Bind(&ZeroSuggestProvider::OnMostVisitedUrlsAvailable,
425                     weak_ptr_factory_.GetWeakPtr()));
426    }
427  }
428  have_pending_request_ = true;
429  LogOmniboxZeroSuggestRequest(ZERO_SUGGEST_REQUEST_SENT);
430}
431
432void ZeroSuggestProvider::ParseSuggestResults(const Value& root_val) {
433  SearchProvider::SuggestResults suggest_results;
434  FillResults(root_val, &verbatim_relevance_,
435              &suggest_results, &navigation_results_);
436
437  query_matches_map_.clear();
438  AddSuggestResultsToMap(suggest_results,
439                         template_url_service_->GetDefaultSearchProvider(),
440                         &query_matches_map_);
441}
442
443void ZeroSuggestProvider::OnMostVisitedUrlsAvailable(
444    const history::MostVisitedURLList& urls) {
445  most_visited_urls_ = urls;
446}
447
448void ZeroSuggestProvider::ConvertResultsToAutocompleteMatches() {
449  matches_.clear();
450
451  const TemplateURL* default_provider =
452      template_url_service_->GetDefaultSearchProvider();
453  // Fail if we can't set the clickthrough URL for query suggestions.
454  if (default_provider == NULL || !default_provider->SupportsReplacement())
455    return;
456
457  const int num_query_results = query_matches_map_.size();
458  const int num_nav_results = navigation_results_.size();
459  const int num_results = num_query_results + num_nav_results;
460  UMA_HISTOGRAM_COUNTS("ZeroSuggest.QueryResults", num_query_results);
461  UMA_HISTOGRAM_COUNTS("ZeroSuggest.URLResults",  num_nav_results);
462  UMA_HISTOGRAM_COUNTS("ZeroSuggest.AllResults", num_results);
463
464  // Show Most Visited results after ZeroSuggest response is received.
465  if (OmniboxFieldTrial::InZeroSuggestMostVisitedFieldTrial()) {
466    matches_.push_back(current_url_match_);
467    int relevance = 600;
468    if (num_results > 0) {
469      UMA_HISTOGRAM_COUNTS(
470          "Omnibox.ZeroSuggest.MostVisitedResultsCounterfactual",
471          most_visited_urls_.size());
472    }
473    for (size_t i = 0; i < most_visited_urls_.size(); i++) {
474      const history::MostVisitedURL& url = most_visited_urls_[i];
475      SearchProvider::NavigationResult nav(*this, url.url, url.title, false,
476                                           relevance, true);
477      matches_.push_back(NavigationToMatch(nav));
478      --relevance;
479    }
480    return;
481  }
482
483  if (num_results == 0)
484    return;
485
486  // TODO(jered): Rip this out once the first match is decoupled from the
487  // current typing in the omnibox.
488  matches_.push_back(current_url_match_);
489
490  for (SearchProvider::MatchMap::const_iterator it(query_matches_map_.begin());
491       it != query_matches_map_.end(); ++it)
492    matches_.push_back(it->second);
493
494  for (SearchProvider::NavigationResults::const_iterator it(
495       navigation_results_.begin()); it != navigation_results_.end(); ++it)
496    matches_.push_back(NavigationToMatch(*it));
497}
498
499AutocompleteMatch ZeroSuggestProvider::MatchForCurrentURL() {
500  AutocompleteInput input(permanent_text_, string16::npos, string16(),
501                          GURL(current_query_), current_page_classification_,
502                          false, false, true, AutocompleteInput::ALL_MATCHES);
503
504  AutocompleteMatch match;
505  AutocompleteClassifierFactory::GetForProfile(profile_)->Classify(
506      permanent_text_, false, true, &match, NULL);
507  match.is_history_what_you_typed_match = false;
508  match.allowed_to_be_default_match = true;
509
510  // The placeholder suggestion for the current URL has high relevance so
511  // that it is in the first suggestion slot and inline autocompleted. It
512  // gets dropped as soon as the user types something.
513  match.relevance = verbatim_relevance_;
514
515  return match;
516}
517