[Chromoting] Add app_remoting/internal to .gitignore
[chromium-blink-merge.git] / components / omnibox / base_search_provider.cc
bloba18b66c2e26c79041a53e8865af383cdfdb94f4d
1 // Copyright 2014 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.
5 #include "components/omnibox/base_search_provider.h"
7 #include "base/i18n/case_conversion.h"
8 #include "base/strings/string_util.h"
9 #include "base/strings/utf_string_conversions.h"
10 #include "components/metrics/proto/omnibox_event.pb.h"
11 #include "components/metrics/proto/omnibox_input_type.pb.h"
12 #include "components/omnibox/autocomplete_provider_client.h"
13 #include "components/omnibox/autocomplete_provider_listener.h"
14 #include "components/omnibox/omnibox_field_trial.h"
15 #include "components/omnibox/suggestion_answer.h"
16 #include "components/search_engines/template_url.h"
17 #include "components/search_engines/template_url_prepopulate_data.h"
18 #include "components/search_engines/template_url_service.h"
19 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
20 #include "net/url_request/url_fetcher.h"
21 #include "net/url_request/url_fetcher_delegate.h"
22 #include "url/gurl.h"
24 using metrics::OmniboxEventProto;
26 // SuggestionDeletionHandler -------------------------------------------------
28 // This class handles making requests to the server in order to delete
29 // personalized suggestions.
30 class SuggestionDeletionHandler : public net::URLFetcherDelegate {
31 public:
32 typedef base::Callback<void(bool, SuggestionDeletionHandler*)>
33 DeletionCompletedCallback;
35 SuggestionDeletionHandler(
36 const std::string& deletion_url,
37 net::URLRequestContextGetter* request_context,
38 const DeletionCompletedCallback& callback);
40 ~SuggestionDeletionHandler() override;
42 private:
43 // net::URLFetcherDelegate:
44 void OnURLFetchComplete(const net::URLFetcher* source) override;
46 scoped_ptr<net::URLFetcher> deletion_fetcher_;
47 DeletionCompletedCallback callback_;
49 DISALLOW_COPY_AND_ASSIGN(SuggestionDeletionHandler);
52 SuggestionDeletionHandler::SuggestionDeletionHandler(
53 const std::string& deletion_url,
54 net::URLRequestContextGetter* request_context,
55 const DeletionCompletedCallback& callback) : callback_(callback) {
56 GURL url(deletion_url);
57 DCHECK(url.is_valid());
59 deletion_fetcher_.reset(net::URLFetcher::Create(
60 BaseSearchProvider::kDeletionURLFetcherID,
61 url,
62 net::URLFetcher::GET,
63 this));
64 deletion_fetcher_->SetRequestContext(request_context);
65 deletion_fetcher_->Start();
68 SuggestionDeletionHandler::~SuggestionDeletionHandler() {
71 void SuggestionDeletionHandler::OnURLFetchComplete(
72 const net::URLFetcher* source) {
73 DCHECK(source == deletion_fetcher_.get());
74 callback_.Run(
75 source->GetStatus().is_success() && (source->GetResponseCode() == 200),
76 this);
79 // BaseSearchProvider ---------------------------------------------------------
81 // static
82 const int BaseSearchProvider::kDefaultProviderURLFetcherID = 1;
83 const int BaseSearchProvider::kKeywordProviderURLFetcherID = 2;
84 const int BaseSearchProvider::kDeletionURLFetcherID = 3;
86 BaseSearchProvider::BaseSearchProvider(
87 TemplateURLService* template_url_service,
88 scoped_ptr<AutocompleteProviderClient> client,
89 AutocompleteProvider::Type type)
90 : AutocompleteProvider(type),
91 template_url_service_(template_url_service),
92 client_(client.Pass()),
93 field_trial_triggered_(false),
94 field_trial_triggered_in_session_(false) {
97 // static
98 bool BaseSearchProvider::ShouldPrefetch(const AutocompleteMatch& match) {
99 return match.GetAdditionalInfo(kShouldPrefetchKey) == kTrue;
102 // static
103 AutocompleteMatch BaseSearchProvider::CreateSearchSuggestion(
104 const base::string16& suggestion,
105 AutocompleteMatchType::Type type,
106 bool from_keyword_provider,
107 const TemplateURL* template_url,
108 const SearchTermsData& search_terms_data) {
109 // These calls use a number of default values. For instance, they assume
110 // that if this match is from a keyword provider, then the user is in keyword
111 // mode. They also assume the caller knows what it's doing and we set
112 // this match to look as if it was received/created synchronously.
113 SearchSuggestionParser::SuggestResult suggest_result(
114 suggestion, type, suggestion, base::string16(), base::string16(),
115 base::string16(), base::string16(), nullptr, std::string(),
116 std::string(), from_keyword_provider, 0, false, false, base::string16());
117 suggest_result.set_received_after_last_keystroke(false);
118 return CreateSearchSuggestion(
119 NULL, AutocompleteInput(), from_keyword_provider, suggest_result,
120 template_url, search_terms_data, 0, false);
123 void BaseSearchProvider::DeleteMatch(const AutocompleteMatch& match) {
124 DCHECK(match.deletable);
125 if (!match.GetAdditionalInfo(BaseSearchProvider::kDeletionUrlKey).empty()) {
126 deletion_handlers_.push_back(new SuggestionDeletionHandler(
127 match.GetAdditionalInfo(BaseSearchProvider::kDeletionUrlKey),
128 client_->RequestContext(),
129 base::Bind(&BaseSearchProvider::OnDeletionComplete,
130 base::Unretained(this))));
133 TemplateURL* template_url =
134 match.GetTemplateURL(template_url_service_, false);
135 // This may be NULL if the template corresponding to the keyword has been
136 // deleted or there is no keyword set.
137 if (template_url != NULL) {
138 client_->DeleteMatchingURLsForKeywordFromHistory(template_url->id(),
139 match.contents);
142 // Immediately update the list of matches to show the match was deleted,
143 // regardless of whether the server request actually succeeds.
144 DeleteMatchFromMatches(match);
147 void BaseSearchProvider::AddProviderInfo(ProvidersInfo* provider_info) const {
148 provider_info->push_back(metrics::OmniboxEventProto_ProviderInfo());
149 metrics::OmniboxEventProto_ProviderInfo& new_entry = provider_info->back();
150 new_entry.set_provider(AsOmniboxEventProviderType());
151 new_entry.set_provider_done(done_);
152 std::vector<uint32> field_trial_hashes;
153 OmniboxFieldTrial::GetActiveSuggestFieldTrialHashes(&field_trial_hashes);
154 for (size_t i = 0; i < field_trial_hashes.size(); ++i) {
155 if (field_trial_triggered_)
156 new_entry.mutable_field_trial_triggered()->Add(field_trial_hashes[i]);
157 if (field_trial_triggered_in_session_) {
158 new_entry.mutable_field_trial_triggered_in_session()->Add(
159 field_trial_hashes[i]);
164 // static
165 const char BaseSearchProvider::kRelevanceFromServerKey[] =
166 "relevance_from_server";
167 const char BaseSearchProvider::kShouldPrefetchKey[] = "should_prefetch";
168 const char BaseSearchProvider::kSuggestMetadataKey[] = "suggest_metadata";
169 const char BaseSearchProvider::kDeletionUrlKey[] = "deletion_url";
170 const char BaseSearchProvider::kTrue[] = "true";
171 const char BaseSearchProvider::kFalse[] = "false";
173 BaseSearchProvider::~BaseSearchProvider() {}
175 void BaseSearchProvider::SetDeletionURL(const std::string& deletion_url,
176 AutocompleteMatch* match) {
177 if (deletion_url.empty())
178 return;
179 if (!template_url_service_)
180 return;
181 GURL url =
182 template_url_service_->GetDefaultSearchProvider()->GenerateSearchURL(
183 template_url_service_->search_terms_data());
184 url = url.GetOrigin().Resolve(deletion_url);
185 if (url.is_valid()) {
186 match->RecordAdditionalInfo(BaseSearchProvider::kDeletionUrlKey,
187 url.spec());
188 match->deletable = true;
192 // static
193 AutocompleteMatch BaseSearchProvider::CreateSearchSuggestion(
194 AutocompleteProvider* autocomplete_provider,
195 const AutocompleteInput& input,
196 const bool in_keyword_mode,
197 const SearchSuggestionParser::SuggestResult& suggestion,
198 const TemplateURL* template_url,
199 const SearchTermsData& search_terms_data,
200 int accepted_suggestion,
201 bool append_extra_query_params) {
202 AutocompleteMatch match(autocomplete_provider, suggestion.relevance(), false,
203 suggestion.type());
205 if (!template_url)
206 return match;
207 match.keyword = template_url->keyword();
208 match.contents = suggestion.match_contents();
209 match.contents_class = suggestion.match_contents_class();
210 match.answer_contents = suggestion.answer_contents();
211 match.answer_type = suggestion.answer_type();
212 match.answer = SuggestionAnswer::copy(suggestion.answer());
213 if (suggestion.type() == AutocompleteMatchType::SEARCH_SUGGEST_INFINITE) {
214 match.RecordAdditionalInfo(
215 kACMatchPropertyInputText, base::UTF16ToUTF8(input.text()));
216 match.RecordAdditionalInfo(
217 kACMatchPropertyContentsPrefix,
218 base::UTF16ToUTF8(suggestion.match_contents_prefix()));
219 match.RecordAdditionalInfo(
220 kACMatchPropertyContentsStartIndex,
221 static_cast<int>(
222 suggestion.suggestion().length() - match.contents.length()));
225 if (!suggestion.annotation().empty())
226 match.description = suggestion.annotation();
228 // suggestion.match_contents() should have already been collapsed.
229 match.allowed_to_be_default_match =
230 (!in_keyword_mode || suggestion.from_keyword_provider()) &&
231 (base::CollapseWhitespace(input.text(), false) ==
232 suggestion.match_contents());
234 // When the user forced a query, we need to make sure all the fill_into_edit
235 // values preserve that property. Otherwise, if the user starts editing a
236 // suggestion, non-Search results will suddenly appear.
237 if (input.type() == metrics::OmniboxInputType::FORCED_QUERY)
238 match.fill_into_edit.assign(base::ASCIIToUTF16("?"));
239 if (suggestion.from_keyword_provider())
240 match.fill_into_edit.append(match.keyword + base::char16(' '));
241 // We only allow inlinable navsuggestions that were received before the
242 // last keystroke because we don't want asynchronous inline autocompletions.
243 if (!input.prevent_inline_autocomplete() &&
244 !suggestion.received_after_last_keystroke() &&
245 (!in_keyword_mode || suggestion.from_keyword_provider()) &&
246 StartsWith(suggestion.suggestion(), input.text(), false)) {
247 match.inline_autocompletion =
248 suggestion.suggestion().substr(input.text().length());
249 match.allowed_to_be_default_match = true;
251 match.fill_into_edit.append(suggestion.suggestion());
253 const TemplateURLRef& search_url = template_url->url_ref();
254 DCHECK(search_url.SupportsReplacement(search_terms_data));
255 match.search_terms_args.reset(
256 new TemplateURLRef::SearchTermsArgs(suggestion.suggestion()));
257 match.search_terms_args->original_query = input.text();
258 match.search_terms_args->accepted_suggestion = accepted_suggestion;
259 match.search_terms_args->enable_omnibox_start_margin = true;
260 match.search_terms_args->suggest_query_params =
261 suggestion.suggest_query_params();
262 match.search_terms_args->append_extra_query_params =
263 append_extra_query_params;
264 // This is the destination URL sans assisted query stats. This must be set
265 // so the AutocompleteController can properly de-dupe; the controller will
266 // eventually overwrite it before it reaches the user.
267 match.destination_url =
268 GURL(search_url.ReplaceSearchTerms(*match.search_terms_args.get(),
269 search_terms_data));
271 // Search results don't look like URLs.
272 match.transition = suggestion.from_keyword_provider() ?
273 ui::PAGE_TRANSITION_KEYWORD : ui::PAGE_TRANSITION_GENERATED;
275 return match;
278 // static
279 bool BaseSearchProvider::ZeroSuggestEnabled(
280 const GURL& suggest_url,
281 const TemplateURL* template_url,
282 OmniboxEventProto::PageClassification page_classification,
283 const SearchTermsData& search_terms_data,
284 AutocompleteProviderClient* client) {
285 if (!OmniboxFieldTrial::InZeroSuggestFieldTrial())
286 return false;
288 // Make sure we are sending the suggest request through HTTPS to prevent
289 // exposing the current page URL or personalized results without encryption.
290 if (!suggest_url.SchemeIs(url::kHttpsScheme))
291 return false;
293 // Don't show zero suggest on the NTP.
294 // TODO(hfung): Experiment with showing MostVisited zero suggest on NTP
295 // under the conditions described in crbug.com/305366.
296 if ((page_classification ==
297 OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS) ||
298 (page_classification ==
299 OmniboxEventProto::INSTANT_NTP_WITH_OMNIBOX_AS_STARTING_FOCUS))
300 return false;
302 // Don't run if in incognito mode.
303 if (client->IsOffTheRecord())
304 return false;
306 // Don't run if we can't get preferences or search suggest is not enabled.
307 if (!client->SearchSuggestEnabled())
308 return false;
310 // Only make the request if we know that the provider supports zero suggest
311 // (currently only the prepopulated Google provider).
312 if (template_url == NULL ||
313 !template_url->SupportsReplacement(search_terms_data) ||
314 TemplateURLPrepopulateData::GetEngineType(
315 *template_url, search_terms_data) != SEARCH_ENGINE_GOOGLE)
316 return false;
318 return true;
321 // static
322 bool BaseSearchProvider::CanSendURL(
323 const GURL& current_page_url,
324 const GURL& suggest_url,
325 const TemplateURL* template_url,
326 OmniboxEventProto::PageClassification page_classification,
327 const SearchTermsData& search_terms_data,
328 AutocompleteProviderClient* client) {
329 if (!ZeroSuggestEnabled(suggest_url, template_url, page_classification,
330 search_terms_data, client))
331 return false;
333 if (!current_page_url.is_valid())
334 return false;
336 // Only allow HTTP URLs or HTTPS URLs for the same domain as the search
337 // provider.
338 if ((current_page_url.scheme() != url::kHttpScheme) &&
339 ((current_page_url.scheme() != url::kHttpsScheme) ||
340 !net::registry_controlled_domains::SameDomainOrHost(
341 current_page_url, suggest_url,
342 net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES)))
343 return false;
345 if (!client->TabSyncEnabledAndUnencrypted())
346 return false;
348 return true;
351 void BaseSearchProvider::AddMatchToMap(
352 const SearchSuggestionParser::SuggestResult& result,
353 const std::string& metadata,
354 int accepted_suggestion,
355 bool mark_as_deletable,
356 bool in_keyword_mode,
357 MatchMap* map) {
358 AutocompleteMatch match = CreateSearchSuggestion(
359 this, GetInput(result.from_keyword_provider()), in_keyword_mode, result,
360 GetTemplateURL(result.from_keyword_provider()),
361 template_url_service_->search_terms_data(), accepted_suggestion,
362 ShouldAppendExtraParams(result));
363 if (!match.destination_url.is_valid())
364 return;
365 match.search_terms_args->bookmark_bar_pinned = client_->ShowBookmarkBar();
366 match.RecordAdditionalInfo(kRelevanceFromServerKey,
367 result.relevance_from_server() ? kTrue : kFalse);
368 match.RecordAdditionalInfo(kShouldPrefetchKey,
369 result.should_prefetch() ? kTrue : kFalse);
370 SetDeletionURL(result.deletion_url(), &match);
371 if (mark_as_deletable)
372 match.deletable = true;
373 // Metadata is needed only for prefetching queries.
374 if (result.should_prefetch())
375 match.RecordAdditionalInfo(kSuggestMetadataKey, metadata);
377 // Try to add |match| to |map|. If a match for this suggestion is
378 // already in |map|, replace it if |match| is more relevant.
379 // NOTE: Keep this ToLower() call in sync with url_database.cc.
380 MatchKey match_key(
381 std::make_pair(base::i18n::ToLower(result.suggestion()),
382 match.search_terms_args->suggest_query_params));
383 const std::pair<MatchMap::iterator, bool> i(
384 map->insert(std::make_pair(match_key, match)));
386 bool should_prefetch = result.should_prefetch();
387 if (!i.second) {
388 // NOTE: We purposefully do a direct relevance comparison here instead of
389 // using AutocompleteMatch::MoreRelevant(), so that we'll prefer "items
390 // added first" rather than "items alphabetically first" when the scores
391 // are equal. The only case this matters is when a user has results with
392 // the same score that differ only by capitalization; because the history
393 // system returns results sorted by recency, this means we'll pick the most
394 // recent such result even if the precision of our relevance score is too
395 // low to distinguish the two.
396 if (match.relevance > i.first->second.relevance) {
397 match.duplicate_matches.insert(match.duplicate_matches.end(),
398 i.first->second.duplicate_matches.begin(),
399 i.first->second.duplicate_matches.end());
400 i.first->second.duplicate_matches.clear();
401 match.duplicate_matches.push_back(i.first->second);
402 i.first->second = match;
403 } else {
404 i.first->second.duplicate_matches.push_back(match);
405 if (match.keyword == i.first->second.keyword) {
406 // Old and new matches are from the same search provider. It is okay to
407 // record one match's prefetch data onto a different match (for the same
408 // query string) for the following reasons:
409 // 1. Because the suggest server only sends down a query string from
410 // which we construct a URL, rather than sending a full URL, and because
411 // we construct URLs from query strings in the same way every time, the
412 // URLs for the two matches will be the same. Therefore, we won't end up
413 // prefetching something the server didn't intend.
414 // 2. Presumably the server sets the prefetch bit on a match it things
415 // is sufficiently relevant that the user is likely to choose it.
416 // Surely setting the prefetch bit on a match of even higher relevance
417 // won't violate this assumption.
418 should_prefetch |= ShouldPrefetch(i.first->second);
419 i.first->second.RecordAdditionalInfo(kShouldPrefetchKey,
420 should_prefetch ? kTrue : kFalse);
421 if (should_prefetch)
422 i.first->second.RecordAdditionalInfo(kSuggestMetadataKey, metadata);
425 // Copy over answer data from lower-ranking item, if necessary.
426 // This depends on the lower-ranking item always being added last - see
427 // use of push_back above.
428 AutocompleteMatch& more_relevant_match = i.first->second;
429 const AutocompleteMatch& less_relevant_match =
430 more_relevant_match.duplicate_matches.back();
431 if (less_relevant_match.answer && !more_relevant_match.answer) {
432 more_relevant_match.answer_type = less_relevant_match.answer_type;
433 more_relevant_match.answer_contents = less_relevant_match.answer_contents;
434 more_relevant_match.answer =
435 SuggestionAnswer::copy(less_relevant_match.answer.get());
440 bool BaseSearchProvider::ParseSuggestResults(
441 const base::Value& root_val,
442 int default_result_relevance,
443 bool is_keyword_result,
444 SearchSuggestionParser::Results* results) {
445 if (!SearchSuggestionParser::ParseSuggestResults(
446 root_val, GetInput(is_keyword_result),
447 client_->SchemeClassifier(), default_result_relevance,
448 client_->AcceptLanguages(), is_keyword_result, results))
449 return false;
451 for (const GURL& url : results->answers_image_urls)
452 client_->PrefetchImage(url);
454 field_trial_triggered_ |= results->field_trial_triggered;
455 field_trial_triggered_in_session_ |= results->field_trial_triggered;
456 return true;
459 void BaseSearchProvider::DeleteMatchFromMatches(
460 const AutocompleteMatch& match) {
461 for (ACMatches::iterator i(matches_.begin()); i != matches_.end(); ++i) {
462 // Find the desired match to delete by checking the type and contents.
463 // We can't check the destination URL, because the autocomplete controller
464 // may have reformulated that. Not that while checking for matching
465 // contents works for personalized suggestions, if more match types gain
466 // deletion support, this algorithm may need to be re-examined.
467 if (i->contents == match.contents && i->type == match.type) {
468 matches_.erase(i);
469 break;
474 void BaseSearchProvider::OnDeletionComplete(
475 bool success, SuggestionDeletionHandler* handler) {
476 RecordDeletionResult(success);
477 SuggestionDeletionHandlers::iterator it = std::find(
478 deletion_handlers_.begin(), deletion_handlers_.end(), handler);
479 DCHECK(it != deletion_handlers_.end());
480 deletion_handlers_.erase(it);