blob: a550a30fd799623480686353f4ec56084be68e92 [file] [log] [blame]
[email protected]6ce7f612012-09-05 23:53:071// 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"
[email protected]bb1fb2b2013-05-31 00:21:018#include "base/i18n/case_conversion.h"
[email protected]6ce7f612012-09-05 23:53:079#include "base/json/json_string_value_serializer.h"
[email protected]bb1fb2b2013-05-31 00:21:0110#include "base/metrics/histogram.h"
[email protected]3853a4c2013-02-11 17:15:5711#include "base/prefs/pref_service.h"
[email protected]6ce7f612012-09-05 23:53:0712#include "base/string16.h"
13#include "base/string_util.h"
14#include "base/time.h"
15#include "base/utf_string_conversions.h"
16#include "chrome/browser/autocomplete/autocomplete_input.h"
17#include "chrome/browser/autocomplete/autocomplete_match.h"
18#include "chrome/browser/autocomplete/autocomplete_provider_listener.h"
[email protected]bb1fb2b2013-05-31 00:21:0119#include "chrome/browser/autocomplete/history_url_provider.h"
20#include "chrome/browser/autocomplete/search_provider.h"
21#include "chrome/browser/autocomplete/url_prefix.h"
22#include "chrome/browser/metrics/variations/variations_http_header_provider.h"
23#include "chrome/browser/net/url_fixer_upper.h"
24#include "chrome/browser/omnibox/omnibox_field_trial.h"
[email protected]6ce7f612012-09-05 23:53:0725#include "chrome/browser/profiles/profile.h"
[email protected]bb1fb2b2013-05-31 00:21:0126#include "chrome/browser/search/search.h"
[email protected]6ce7f612012-09-05 23:53:0727#include "chrome/browser/search_engines/template_url_service.h"
28#include "chrome/browser/search_engines/template_url_service_factory.h"
[email protected]bb1fb2b2013-05-31 00:21:0129#include "chrome/browser/sync/profile_sync_service.h"
30#include "chrome/browser/sync/profile_sync_service_factory.h"
[email protected]a00008d42012-09-15 05:07:5831#include "chrome/common/pref_names.h"
[email protected]6ce7f612012-09-05 23:53:0732#include "chrome/common/url_constants.h"
33#include "googleurl/src/gurl.h"
[email protected]bb1fb2b2013-05-31 00:21:0134#include "net/base/escape.h"
[email protected]6ce7f612012-09-05 23:53:0735#include "net/base/load_flags.h"
[email protected]bb1fb2b2013-05-31 00:21:0136#include "net/base/net_util.h"
37#include "net/http/http_request_headers.h"
[email protected]6ce7f612012-09-05 23:53:0738#include "net/http/http_response_headers.h"
39#include "net/url_request/url_fetcher.h"
40#include "net/url_request/url_request_status.h"
41
42namespace {
[email protected]bb1fb2b2013-05-31 00:21:0143
44// TODO(hfung): The histogram code was copied and modified from
45// search_provider.cc. Refactor and consolidate the code.
46// We keep track in a histogram how many suggest requests we send, how
47// many suggest requests we invalidate (e.g., due to a user typing
48// another character), and how many replies we receive.
49// *** ADD NEW ENUMS AFTER ALL PREVIOUSLY DEFINED ONES! ***
50// (excluding the end-of-list enum value)
51// We do not want values of existing enums to change or else it screws
52// up the statistics.
53enum ZeroSuggestRequestsHistogramValue {
54 ZERO_SUGGEST_REQUEST_SENT = 1,
55 ZERO_SUGGEST_REQUEST_INVALIDATED,
56 ZERO_SUGGEST_REPLY_RECEIVED,
57 ZERO_SUGGEST_MAX_REQUEST_HISTOGRAM_VALUE
58};
59
60void LogOmniboxZeroSuggestRequest(
61 ZeroSuggestRequestsHistogramValue request_value) {
62 UMA_HISTOGRAM_ENUMERATION("Omnibox.ZeroSuggestRequests", request_value,
63 ZERO_SUGGEST_MAX_REQUEST_HISTOGRAM_VALUE);
64}
65
66// The maximum relevance of the top match from this provider.
67const int kDefaultVerbatimZeroSuggestRelevance = 1300;
68
69// Relevance value to use if it was not set explicitly by the server.
70const int kDefaultZeroSuggestRelevance = 100;
71
[email protected]6ce7f612012-09-05 23:53:0772} // namespace
73
[email protected]a00008d42012-09-15 05:07:5874// static
75ZeroSuggestProvider* ZeroSuggestProvider::Create(
76 AutocompleteProviderListener* listener,
77 Profile* profile) {
[email protected]bb1fb2b2013-05-31 00:21:0178 return new ZeroSuggestProvider(listener, profile);
[email protected]6ce7f612012-09-05 23:53:0779}
80
[email protected]6ce7f612012-09-05 23:53:0781void ZeroSuggestProvider::Start(const AutocompleteInput& input,
82 bool /*minimal_changes*/) {
[email protected]bb1fb2b2013-05-31 00:21:0183 CheckIfTextModfied(input.text());
84 // Clear results only if the user text was modified.
85 Stop(user_text_modified_);
86 ConvertResultsToAutocompleteMatches(input.text(), false);
87 // listener_->OnProviderUpdate() does not need to be called because this
88 // function is only called in the synchronous pass when a user has performed
89 // an action (such as typing a character in the omnobox).
90}
91
92void ZeroSuggestProvider::Stop(bool clear_cached_results) {
93 if (have_pending_request_)
94 LogOmniboxZeroSuggestRequest(ZERO_SUGGEST_REQUEST_INVALIDATED);
95 have_pending_request_ = false;
96 fetcher_.reset();
97 done_ = true;
98 if (clear_cached_results) {
99 query_matches_map_.clear();
100 navigation_results_.clear();
101 current_query_.clear();
102 matches_.clear();
103 }
104}
105
106void ZeroSuggestProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
107 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
108 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
109 new_entry.set_provider(AsOmniboxEventProviderType());
110 new_entry.set_provider_done(done_);
111 std::vector<uint32> field_trial_hashes;
112 OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes);
113 for (size_t i = 0; i < field_trial_hashes.size(); ++i) {
114 if (field_trial_triggered_)
115 new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]);
116 if (field_trial_triggered_in_session_) {
117 new_entry.mutable_field_trial_triggered_in_session()->Add(
118 field_trial_hashes[i]);
119 }
120 }
121}
122
123void ZeroSuggestProvider::ResetSession() {
124 // The user has started editing in the omnibox, so leave
125 // |field_trial_triggered_in_session_| unchanged and set
126 // |field_trial_triggered_| to false since zero suggest is inactive now.
127 field_trial_triggered_ = false;
128}
129
130void ZeroSuggestProvider::OnURLFetchComplete(const net::URLFetcher* source) {
131 have_pending_request_ = false;
132 LogOmniboxZeroSuggestRequest(ZERO_SUGGEST_REPLY_RECEIVED);
133
134 std::string json_data;
135 source->GetResponseAsString(&json_data);
136 const bool request_succeeded =
137 source->GetStatus().is_success() && source->GetResponseCode() == 200;
138
139 bool have_results = false;
140 if (request_succeeded) {
141 JSONStringValueSerializer deserializer(json_data);
142 deserializer.set_allow_trailing_comma(true);
143 scoped_ptr<Value> data(deserializer.Deserialize(NULL, NULL));
144 if (data.get()) {
145 ParseSuggestResults(*data.get());
146 have_results = !query_matches_map_.empty() ||
147 !navigation_results_.empty();
148 }
149 }
150 done_ = true;
151
152 if (have_results) {
153 ConvertResultsToAutocompleteMatches(original_user_text_, true);
154 listener_->OnProviderUpdate(true);
155 }
[email protected]6ce7f612012-09-05 23:53:07156}
157
158void ZeroSuggestProvider::StartZeroSuggest(const GURL& url,
159 const string16& user_text) {
[email protected]bb1fb2b2013-05-31 00:21:01160 Stop(true);
161 field_trial_triggered_ = false;
162 field_trial_triggered_in_session_ = false;
163 if (!ShouldRunZeroSuggest(url))
[email protected]6ce7f612012-09-05 23:53:07164 return;
[email protected]bb1fb2b2013-05-31 00:21:01165 verbatim_relevance_ = kDefaultVerbatimZeroSuggestRelevance;
[email protected]6ce7f612012-09-05 23:53:07166 done_ = false;
[email protected]bb1fb2b2013-05-31 00:21:01167 original_user_text_ = user_text;
[email protected]6ce7f612012-09-05 23:53:07168 current_query_ = url.spec();
[email protected]bb1fb2b2013-05-31 00:21:01169 current_url_match_ = MatchForCurrentURL();
170 user_text_modified_ = false;
[email protected]6ce7f612012-09-05 23:53:07171 // TODO(jered): Consider adding locally-sourced zero-suggestions here too.
172 // These may be useful on the NTP or more relevant to the user than server
173 // suggestions, if based on local browsing history.
174 Run();
175}
176
[email protected]bb1fb2b2013-05-31 00:21:01177ZeroSuggestProvider::ZeroSuggestProvider(
178 AutocompleteProviderListener* listener,
179 Profile* profile)
180 : AutocompleteProvider(listener, profile,
181 AutocompleteProvider::TYPE_ZERO_SUGGEST),
182 template_url_service_(TemplateURLServiceFactory::GetForProfile(profile)),
183 user_text_modified_(false),
184 have_pending_request_(false),
185 verbatim_relevance_(kDefaultVerbatimZeroSuggestRelevance),
186 field_trial_triggered_(false),
187 field_trial_triggered_in_session_(false) {
[email protected]6ce7f612012-09-05 23:53:07188}
189
190ZeroSuggestProvider::~ZeroSuggestProvider() {
191}
192
[email protected]bb1fb2b2013-05-31 00:21:01193bool ZeroSuggestProvider::ShouldRunZeroSuggest(const GURL& url) const {
194 if (!url.is_valid())
[email protected]6ce7f612012-09-05 23:53:07195 return false;
196
[email protected]bb1fb2b2013-05-31 00:21:01197 // Do not query non-http URLs. There will be no useful suggestions for https
198 // or chrome URLs.
199 if (url.scheme() != chrome::kHttpScheme)
200 return false;
[email protected]6ce7f612012-09-05 23:53:07201
[email protected]bb1fb2b2013-05-31 00:21:01202 // Don't enable ZeroSuggest until InstantExtended works with ZeroSuggest.
203 if (chrome::IsInstantExtendedAPIEnabled())
204 return false;
205
206 // Don't run if there's no profile or in incognito mode.
207 if (profile_ == NULL || profile_->IsOffTheRecord())
208 return false;
209
210 // Don't run if we can't get preferences or search suggest is not enabled.
211 PrefService* prefs = profile_->GetPrefs();
212 if (prefs == NULL || !prefs->GetBoolean(prefs::kSearchSuggestEnabled))
213 return false;
214
215 ProfileSyncService* service =
216 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile_);
217 browser_sync::SyncPrefs sync_prefs(prefs);
218 // The user has needs to have Chrome Sync enabled (for permissions to
219 // transmit their current URL) and be in the field trial.
220 if (!OmniboxFieldTrial::InZeroSuggestFieldTrial() ||
221 service == NULL ||
222 !service->IsSyncEnabledAndLoggedIn() ||
223 !sync_prefs.HasKeepEverythingSynced()) {
224 return false;
225 }
[email protected]6ce7f612012-09-05 23:53:07226 return true;
227}
228
[email protected]bb1fb2b2013-05-31 00:21:01229void ZeroSuggestProvider::FillResults(
230 const Value& root_val,
231 int* verbatim_relevance,
232 SearchProvider::SuggestResults* suggest_results,
233 SearchProvider::NavigationResults* navigation_results) {
234 string16 query;
235 const ListValue* root_list = NULL;
236 const ListValue* results = NULL;
237 const ListValue* relevances = NULL;
238 // The response includes the query, which should be empty for ZeroSuggest
239 // responses.
240 if (!root_val.GetAsList(&root_list) || !root_list->GetString(0, &query) ||
241 (!query.empty()) || !root_list->GetList(1, &results))
242 return;
243
244 // 3rd element: Description list.
245 const ListValue* descriptions = NULL;
246 root_list->GetList(2, &descriptions);
247
248 // 4th element: Disregard the query URL list for now.
249
250 // Reset suggested relevance information from the provider.
251 *verbatim_relevance = kDefaultVerbatimZeroSuggestRelevance;
252
253 // 5th element: Optional key-value pairs from the Suggest server.
254 const ListValue* types = NULL;
255 const DictionaryValue* extras = NULL;
256 if (root_list->GetDictionary(4, &extras)) {
257 extras->GetList("google:suggesttype", &types);
258
259 // Discard this list if its size does not match that of the suggestions.
260 if (extras->GetList("google:suggestrelevance", &relevances) &&
261 relevances->GetSize() != results->GetSize())
262 relevances = NULL;
263 extras->GetInteger("google:verbatimrelevance", verbatim_relevance);
264
265 // Check if the active suggest field trial (if any) has triggered.
266 bool triggered = false;
267 extras->GetBoolean("google:fieldtrialtriggered", &triggered);
268 field_trial_triggered_ |= triggered;
269 field_trial_triggered_in_session_ |= triggered;
270 }
271
272 // Clear the previous results now that new results are available.
273 suggest_results->clear();
274 navigation_results->clear();
275
276 string16 result, title;
277 std::string type;
278 for (size_t index = 0; results->GetString(index, &result); ++index) {
279 // Google search may return empty suggestions for weird input characters,
280 // they make no sense at all and can cause problems in our code.
281 if (result.empty())
282 continue;
283
284 int relevance = kDefaultZeroSuggestRelevance;
285
286 // Apply valid suggested relevance scores; discard invalid lists.
287 if (relevances != NULL && !relevances->GetInteger(index, &relevance))
288 relevances = NULL;
289 if (types && types->GetString(index, &type) && (type == "NAVIGATION")) {
290 // Do not blindly trust the URL coming from the server to be valid.
291 GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(result), std::string()));
292 if (url.is_valid()) {
293 if (descriptions != NULL)
294 descriptions->GetString(index, &title);
295 navigation_results->push_back(SearchProvider::NavigationResult(
296 *this, url, title, false, relevance));
297 }
298 } else {
299 suggest_results->push_back(SearchProvider::SuggestResult(
300 result, false, relevance));
301 }
302 }
303}
304
305void ZeroSuggestProvider::AddSuggestResultsToMap(
306 const SearchProvider::SuggestResults& results,
307 const string16& provider_keyword,
308 SearchProvider::MatchMap* map) {
309 for (size_t i = 0; i < results.size(); ++i) {
310 AddMatchToMap(results[i].suggestion(),
311 provider_keyword,
312 results[i].relevance(),
313 AutocompleteMatchType::SEARCH_SUGGEST, i, map);
314 }
315}
316
317void ZeroSuggestProvider::AddMatchToMap(const string16& query_string,
318 const string16& provider_keyword,
319 int relevance,
320 AutocompleteMatch::Type type,
321 int accepted_suggestion,
322 SearchProvider::MatchMap* map) {
323 // Pass in query_string as the input_text since we don't want any bolding.
324 AutocompleteMatch match = SearchProvider::CreateSearchSuggestion(
325 profile_, this, AutocompleteInput(),
326 query_string, query_string, relevance, type, accepted_suggestion,
327 false, provider_keyword);
328 if (!match.destination_url.is_valid())
329 return;
330
331 // Try to add |match| to |map|. If a match for |query_string| is already in
332 // |map|, replace it if |match| is more relevant.
333 // NOTE: Keep this ToLower() call in sync with url_database.cc.
334 const std::pair<SearchProvider::MatchMap::iterator, bool> i = map->insert(
335 std::pair<string16, AutocompleteMatch>(
336 base::i18n::ToLower(query_string), match));
337 // NOTE: We purposefully do a direct relevance comparison here instead of
338 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items added
339 // first" rather than "items alphabetically first" when the scores are equal.
340 // The only case this matters is when a user has results with the same score
341 // that differ only by capitalization; because the history system returns
342 // results sorted by recency, this means we'll pick the most recent such
343 // result even if the precision of our relevance score is too low to
344 // distinguish the two.
345 if (!i.second && (match.relevance > i.first->second.relevance))
346 i.first->second = match;
347}
348
349AutocompleteMatch ZeroSuggestProvider::NavigationToMatch(
350 const SearchProvider::NavigationResult& navigation) {
351 AutocompleteMatch match(this, navigation.relevance(), false,
352 AutocompleteMatchType::NAVSUGGEST);
353 match.destination_url = navigation.url();
354
355 const std::string languages(
356 profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
357 match.contents = net::FormatUrl(navigation.url(), languages,
358 net::kFormatUrlOmitAll, net::UnescapeRule::SPACES, NULL, NULL, NULL);
359 match.fill_into_edit +=
360 AutocompleteInput::FormattedStringWithEquivalentMeaning(navigation.url(),
361 match.contents);
362 match.inline_autocomplete_offset = string16::npos;
363
364 AutocompleteMatch::ClassifyLocationInString(string16::npos, 0,
365 match.contents.length(), ACMatchClassification::URL,
366 &match.contents_class);
367 match.description = navigation.description();
368 return match;
369}
370
371void ZeroSuggestProvider::Run() {
372 have_pending_request_ = false;
373 const int kFetcherID = 1;
374
375 const TemplateURL* default_provider =
376 template_url_service_->GetDefaultSearchProvider();
377 // TODO(hfung): Generalize if the default provider supports zero suggest.
378 // Only make the request if we know that the provider supports zero suggest
379 // (currently only the prepopulated Google provider).
380 if (default_provider == NULL || !default_provider->SupportsReplacement() ||
381 default_provider->prepopulate_id() != 1) {
382 Stop(true);
383 return;
384 }
385 string16 prefix;
386 TemplateURLRef::SearchTermsArgs search_term_args(prefix);
387 search_term_args.zero_prefix_url = current_query_;
388 std::string req_url = default_provider->suggestions_url_ref().
389 ReplaceSearchTerms(search_term_args);
390 GURL suggest_url(req_url);
391 // Make sure we are sending the suggest request through HTTPS.
392 if (!suggest_url.SchemeIs(chrome::kHttpsScheme)) {
393 Stop(true);
394 return;
395 }
396
397 fetcher_.reset(
398 net::URLFetcher::Create(kFetcherID,
399 suggest_url,
400 net::URLFetcher::GET, this));
401 fetcher_->SetRequestContext(profile_->GetRequestContext());
402 fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES);
403 // Add Chrome experiment state to the request headers.
404 net::HttpRequestHeaders headers;
405 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->AppendHeaders(
406 fetcher_->GetOriginalURL(), profile_->IsOffTheRecord(), false, &headers);
407 fetcher_->SetExtraRequestHeaders(headers.ToString());
408
409 fetcher_->Start();
410 have_pending_request_ = true;
411 LogOmniboxZeroSuggestRequest(ZERO_SUGGEST_REQUEST_SENT);
412}
413
414void ZeroSuggestProvider::CheckIfTextModfied(const string16& user_text) {
415 if (!user_text.empty() && user_text != current_url_match_.contents)
416 user_text_modified_ = true;
417}
418
419void ZeroSuggestProvider::ParseSuggestResults(const Value& root_val) {
420 SearchProvider::SuggestResults suggest_results;
421 FillResults(root_val, &verbatim_relevance_,
422 &suggest_results, &navigation_results_);
423
424 query_matches_map_.clear();
425 const TemplateURL* default_provider =
426 template_url_service_->GetDefaultSearchProvider();
427 AddSuggestResultsToMap(suggest_results, default_provider->keyword(),
428 &query_matches_map_);
429}
430
431void ZeroSuggestProvider::ConvertResultsToAutocompleteMatches(
432 string16 user_text, bool update_histograms) {
433 matches_.clear();
434
435 const TemplateURL* default_provider =
[email protected]6ce7f612012-09-05 23:53:07436 template_url_service_->GetDefaultSearchProvider();
437 // Fail if we can't set the clickthrough URL for query suggestions.
[email protected]bb1fb2b2013-05-31 00:21:01438 if (default_provider == NULL || !default_provider->SupportsReplacement())
[email protected]6ce7f612012-09-05 23:53:07439 return;
[email protected]6ce7f612012-09-05 23:53:07440
[email protected]bb1fb2b2013-05-31 00:21:01441 const int num_query_results = query_matches_map_.size();
442 const int num_nav_results = navigation_results_.size();
443 const int num_results = num_query_results + num_nav_results;
444 if (update_histograms) {
445 UMA_HISTOGRAM_COUNTS("ZeroSuggest.QueryResults", num_query_results);
446 UMA_HISTOGRAM_COUNTS("ZeroSuggest.URLResults", num_nav_results);
447 UMA_HISTOGRAM_COUNTS("ZeroSuggest.AllResults", num_results);
448 }
449
450 if (num_results == 0 || user_text_modified_)
451 return;
452
453 // TODO(jered): Rip this out once the first match is decoupled from the
454 // current typing in the omnibox.
455 // If the user text is empty, we can autocomplete to the URL. Otherwise,
456 // don't modify the omnibox text.
457 current_url_match_.inline_autocomplete_offset = user_text.empty() ?
458 0 : string16::npos;
459 matches_.push_back(current_url_match_);
460
461 for (SearchProvider::MatchMap::const_iterator it = query_matches_map_.begin();
462 it != query_matches_map_.end(); ++it) {
463 matches_.push_back(it->second);
464 }
465
466 for (SearchProvider::NavigationResults::const_iterator it =
467 navigation_results_.begin();
468 it != navigation_results_.end(); ++it) {
469 matches_.push_back(NavigationToMatch(*it));
[email protected]6ce7f612012-09-05 23:53:07470 }
471}
472
[email protected]bb1fb2b2013-05-31 00:21:01473AutocompleteMatch ZeroSuggestProvider::MatchForCurrentURL() {
474 AutocompleteInput input(ASCIIToUTF16(current_query_), string16::npos,
475 string16(), GURL(current_query_),
476 false, false, true, AutocompleteInput::ALL_MATCHES);
[email protected]6ce7f612012-09-05 23:53:07477
[email protected]bb1fb2b2013-05-31 00:21:01478 AutocompleteMatch match(
479 HistoryURLProvider::SuggestExactInput(this, input, true));
480 match.is_history_what_you_typed_match = false;
[email protected]6ce7f612012-09-05 23:53:07481
[email protected]bb1fb2b2013-05-31 00:21:01482 // The placeholder suggestion for the current URL has high relevance so
483 // that it is in the first suggestion slot and inline autocompleted. It
484 // gets dropped as soon as the user types something.
485 match.relevance = verbatim_relevance_;
[email protected]6ce7f612012-09-05 23:53:07486
[email protected]bb1fb2b2013-05-31 00:21:01487 return match;
[email protected]6ce7f612012-09-05 23:53:07488}