[safe-browsing] Database full hash matches like prefix match.
[chromium-blink-merge.git] / chrome / browser / autocomplete / base_search_provider.h
blob2e26ab0635ff4b156cb8d514e32998c6b8a62206
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.
4 //
5 // This class contains common functionality for search-based autocomplete
6 // providers. Search provider and zero suggest provider both use it for common
7 // functionality.
9 #ifndef CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_
10 #define CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_
12 #include <map>
13 #include <string>
14 #include <utility>
15 #include <vector>
17 #include "base/memory/scoped_vector.h"
18 #include "base/strings/string16.h"
19 #include "chrome/browser/autocomplete/autocomplete_input.h"
20 #include "chrome/browser/autocomplete/autocomplete_match.h"
21 #include "chrome/browser/autocomplete/autocomplete_provider.h"
22 #include "net/url_request/url_fetcher_delegate.h"
24 class AutocompleteProviderListener;
25 class GURL;
26 class Profile;
27 class SuggestionDeletionHandler;
28 class TemplateURL;
30 namespace base {
31 class ListValue;
32 class Value;
35 // Base functionality for receiving suggestions from a search engine.
36 // This class is abstract and should only be used as a base for other
37 // autocomplete providers utilizing its functionality.
38 class BaseSearchProvider : public AutocompleteProvider,
39 public net::URLFetcherDelegate {
40 public:
41 // ID used in creating URLFetcher for default provider's suggest results.
42 static const int kDefaultProviderURLFetcherID;
44 // ID used in creating URLFetcher for keyword provider's suggest results.
45 static const int kKeywordProviderURLFetcherID;
47 // ID used in creating URLFetcher for deleting suggestion results.
48 static const int kDeletionURLFetcherID;
50 BaseSearchProvider(AutocompleteProviderListener* listener,
51 Profile* profile,
52 AutocompleteProvider::Type type);
54 // Returns whether |match| is flagged as a query that should be prefetched.
55 static bool ShouldPrefetch(const AutocompleteMatch& match);
57 // Returns a simpler AutocompleteMatch suitable for persistence like in
58 // ShortcutsDatabase.
59 // NOTE: Use with care. Most likely you want the other CreateSearchSuggestion
60 // with protected access.
61 static AutocompleteMatch CreateSearchSuggestion(
62 const base::string16& suggestion,
63 AutocompleteMatchType::Type type,
64 bool from_keyword_provider,
65 const TemplateURL* template_url);
67 // AutocompleteProvider:
68 virtual void Stop(bool clear_cached_results) OVERRIDE;
69 virtual void DeleteMatch(const AutocompleteMatch& match) OVERRIDE;
70 virtual void AddProviderInfo(ProvidersInfo* provider_info) const OVERRIDE;
72 bool field_trial_triggered_in_session() const {
73 return field_trial_triggered_in_session_;
76 void set_in_app_list() { in_app_list_ = true; }
78 protected:
79 // The following keys are used to record additional information on matches.
81 // We annotate our AutocompleteMatches with whether their relevance scores
82 // were server-provided using this key in the |additional_info| field.
83 static const char kRelevanceFromServerKey[];
85 // Indicates whether the server said a match should be prefetched.
86 static const char kShouldPrefetchKey[];
88 // Used to store metadata from the server response, which is needed for
89 // prefetching.
90 static const char kSuggestMetadataKey[];
92 // Used to store a deletion request url for server-provided suggestions.
93 static const char kDeletionUrlKey[];
95 // These are the values for the above keys.
96 static const char kTrue[];
97 static const char kFalse[];
99 virtual ~BaseSearchProvider();
101 // The Result classes are intermediate representations of AutocompleteMatches,
102 // simply containing relevance-ranked search and navigation suggestions.
103 // They may be cached to provide some synchronous matches while requests for
104 // new suggestions from updated input are in flight.
105 // TODO(msw) Extend these classes to generate their corresponding matches and
106 // other requisite data, in order to consolidate and simplify the
107 // highly fragmented SearchProvider logic for each Result type.
108 class Result {
109 public:
110 Result(bool from_keyword_provider,
111 int relevance,
112 bool relevance_from_server);
113 virtual ~Result();
115 bool from_keyword_provider() const { return from_keyword_provider_; }
117 const base::string16& match_contents() const { return match_contents_; }
118 const ACMatchClassifications& match_contents_class() const {
119 return match_contents_class_;
122 int relevance() const { return relevance_; }
123 void set_relevance(int relevance) { relevance_ = relevance; }
125 bool relevance_from_server() const { return relevance_from_server_; }
126 void set_relevance_from_server(bool relevance_from_server) {
127 relevance_from_server_ = relevance_from_server;
130 // Returns if this result is inlineable against the current input |input|.
131 // Non-inlineable results are stale.
132 virtual bool IsInlineable(const base::string16& input) const = 0;
134 // Returns the default relevance value for this result (which may
135 // be left over from a previous omnibox input) given the current
136 // input and whether the current input caused a keyword provider
137 // to be active.
138 virtual int CalculateRelevance(const AutocompleteInput& input,
139 bool keyword_provider_requested) const = 0;
141 protected:
142 // The contents to be displayed and its style info.
143 base::string16 match_contents_;
144 ACMatchClassifications match_contents_class_;
146 // True if the result came from the keyword provider.
147 bool from_keyword_provider_;
149 // The relevance score.
150 int relevance_;
152 private:
153 // Whether this result's relevance score was fully or partly calculated
154 // based on server information, and thus is assumed to be more accurate.
155 // This is ultimately used in
156 // SearchProvider::ConvertResultsToAutocompleteMatches(), see comments
157 // there.
158 bool relevance_from_server_;
161 class SuggestResult : public Result {
162 public:
163 SuggestResult(const base::string16& suggestion,
164 AutocompleteMatchType::Type type,
165 const base::string16& match_contents,
166 const base::string16& match_contents_prefix,
167 const base::string16& annotation,
168 const std::string& suggest_query_params,
169 const std::string& deletion_url,
170 bool from_keyword_provider,
171 int relevance,
172 bool relevance_from_server,
173 bool should_prefetch,
174 const base::string16& input_text);
175 virtual ~SuggestResult();
177 const base::string16& suggestion() const { return suggestion_; }
178 AutocompleteMatchType::Type type() const { return type_; }
179 const base::string16& match_contents_prefix() const {
180 return match_contents_prefix_;
182 const base::string16& annotation() const { return annotation_; }
183 const std::string& suggest_query_params() const {
184 return suggest_query_params_;
186 const std::string& deletion_url() const { return deletion_url_; }
187 bool should_prefetch() const { return should_prefetch_; }
189 // Fills in |match_contents_class_| to reflect how |match_contents_| should
190 // be displayed and bolded against the current |input_text|. If
191 // |allow_bolding_all| is false and |match_contents_class_| would have all
192 // of |match_contents_| bolded, do nothing.
193 void ClassifyMatchContents(const bool allow_bolding_all,
194 const base::string16& input_text);
196 // Result:
197 virtual bool IsInlineable(const base::string16& input) const OVERRIDE;
198 virtual int CalculateRelevance(
199 const AutocompleteInput& input,
200 bool keyword_provider_requested) const OVERRIDE;
202 private:
203 // The search terms to be used for this suggestion.
204 base::string16 suggestion_;
206 AutocompleteMatchType::Type type_;
208 // The contents to be displayed as prefix of match contents.
209 // Used for postfix suggestions to display a leading ellipsis (or some
210 // equivalent character) to indicate omitted text.
211 // Only used to pass this information to about:omnibox's "Additional Info".
212 base::string16 match_contents_prefix_;
214 // Optional annotation for the |match_contents_| for disambiguation.
215 // This may be displayed in the autocomplete match contents, but is defined
216 // separately to facilitate different formatting.
217 base::string16 annotation_;
219 // Optional additional parameters to be added to the search URL.
220 std::string suggest_query_params_;
222 // Optional deletion URL provided with suggestions. Fetching this URL
223 // should result in some reasonable deletion behaviour on the server,
224 // e.g. deleting this term out of a user's server-side search history.
225 std::string deletion_url_;
227 // Should this result be prefetched?
228 bool should_prefetch_;
231 class NavigationResult : public Result {
232 public:
233 // |provider| is necessary to use StringForURLDisplay() in order to
234 // compute |formatted_url_|.
235 NavigationResult(const AutocompleteProvider& provider,
236 const GURL& url,
237 const base::string16& description,
238 bool from_keyword_provider,
239 int relevance,
240 bool relevance_from_server,
241 const base::string16& input_text,
242 const std::string& languages);
243 virtual ~NavigationResult();
245 const GURL& url() const { return url_; }
246 const base::string16& description() const { return description_; }
247 const base::string16& formatted_url() const { return formatted_url_; }
249 // Fills in |match_contents_| and |match_contents_class_| to reflect how
250 // the URL should be displayed and bolded against the current |input_text|
251 // and user |languages|. If |allow_bolding_nothing| is false and
252 // |match_contents_class_| would result in an entirely unbolded
253 // |match_contents_|, do nothing.
254 void CalculateAndClassifyMatchContents(const bool allow_bolding_nothing,
255 const base::string16& input_text,
256 const std::string& languages);
258 // Result:
259 virtual bool IsInlineable(const base::string16& input) const OVERRIDE;
260 virtual int CalculateRelevance(
261 const AutocompleteInput& input,
262 bool keyword_provider_requested) const OVERRIDE;
264 private:
265 // The suggested url for navigation.
266 GURL url_;
268 // The properly formatted ("fixed up") URL string with equivalent meaning
269 // to the one in |url_|.
270 base::string16 formatted_url_;
272 // The suggested navigational result description; generally the site name.
273 base::string16 description_;
276 typedef std::vector<SuggestResult> SuggestResults;
277 typedef std::vector<NavigationResult> NavigationResults;
278 typedef std::pair<base::string16, std::string> MatchKey;
279 typedef std::map<MatchKey, AutocompleteMatch> MatchMap;
280 typedef ScopedVector<SuggestionDeletionHandler> SuggestionDeletionHandlers;
282 // A simple structure bundling most of the information (including
283 // both SuggestResults and NavigationResults) returned by a call to
284 // the suggest server.
286 // This has to be declared after the typedefs since it relies on some of them.
287 struct Results {
288 Results();
289 ~Results();
291 // Clears |suggest_results| and |navigation_results| and resets
292 // |verbatim_relevance| to -1 (implies unset).
293 void Clear();
295 // Returns whether any of the results (including verbatim) have
296 // server-provided scores.
297 bool HasServerProvidedScores() const;
299 // Query suggestions sorted by relevance score.
300 SuggestResults suggest_results;
302 // Navigational suggestions sorted by relevance score.
303 NavigationResults navigation_results;
305 // The server supplied verbatim relevance scores. Negative values
306 // indicate that there is no suggested score; a value of 0
307 // suppresses the verbatim result.
308 int verbatim_relevance;
310 // The JSON metadata associated with this server response.
311 std::string metadata;
313 private:
314 DISALLOW_COPY_AND_ASSIGN(Results);
317 // Returns an AutocompleteMatch with the given |autocomplete_provider|
318 // for the search |suggestion|, which represents a search via |template_url|.
319 // If |template_url| is NULL, returns a match with an invalid destination URL.
321 // |input| is the original user input. Text in the input is used to highlight
322 // portions of the match contents to distinguish locally-typed text from
323 // suggested text.
325 // |input| is also necessary for various other details, like whether we should
326 // allow inline autocompletion and what the transition type should be.
327 // |accepted_suggestion| and |omnibox_start_margin| are used to generate
328 // Assisted Query Stats.
329 // |append_extra_query_params| should be set if |template_url| is the default
330 // search engine, so the destination URL will contain any
331 // command-line-specified query params.
332 // |from_app_list| should be set if the search was made from the app list.
333 static AutocompleteMatch CreateSearchSuggestion(
334 AutocompleteProvider* autocomplete_provider,
335 const AutocompleteInput& input,
336 const SuggestResult& suggestion,
337 const TemplateURL* template_url,
338 int accepted_suggestion,
339 int omnibox_start_margin,
340 bool append_extra_query_params,
341 bool from_app_list);
343 // Parses JSON response received from the provider, stripping XSSI
344 // protection if needed. Returns the parsed data if successful, NULL
345 // otherwise.
346 static scoped_ptr<base::Value> DeserializeJsonData(std::string json_data);
348 // Returns whether the requirements for requesting zero suggest results
349 // are met. The requirements are
350 // * The user is enrolled in a zero suggest experiment.
351 // * The user is not on the NTP.
352 // * The suggest request is sent over HTTPS. This avoids leaking the current
353 // page URL or personal data in unencrypted network traffic.
354 // * The user has suggest enabled in their settings and is not in incognito
355 // mode. (Incognito disables suggest entirely.)
356 // * The user's suggest provider is Google. We might want to allow other
357 // providers to see this data someday, but for now this has only been
358 // implemented for Google.
359 static bool ZeroSuggestEnabled(
360 const GURL& suggest_url,
361 const TemplateURL* template_url,
362 AutocompleteInput::PageClassification page_classification,
363 Profile* profile);
365 // Returns whether we can send the URL of the current page in any suggest
366 // requests. Doing this requires that all the following hold:
367 // * ZeroSuggestEnabled() is true, so we meet the requirements above.
368 // * The current URL is HTTP, or HTTPS with the same domain as the suggest
369 // server. Non-HTTP[S] URLs (e.g. FTP/file URLs) may contain sensitive
370 // information. HTTPS URLs may also contain sensitive information, but if
371 // they're on the same domain as the suggest server, then the relevant
372 // entity could have already seen/logged this data.
373 // * The user is OK in principle with sending URLs of current pages to their
374 // provider. Today, there is no explicit setting that controls this, but if
375 // the user has tab sync enabled and tab sync is unencrypted, then they're
376 // already sending this data to Google for sync purposes. Thus we use this
377 // setting as a proxy for "it's OK to send such data". In the future,
378 // especially if we want to support suggest providers other than Google, we
379 // may change this to be a standalone setting or part of some explicit
380 // general opt-in.
381 static bool CanSendURL(
382 const GURL& current_page_url,
383 const GURL& suggest_url,
384 const TemplateURL* template_url,
385 AutocompleteInput::PageClassification page_classification,
386 Profile* profile);
388 // net::URLFetcherDelegate:
389 virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE;
391 // Creates an AutocompleteMatch from |result| to search for the query in
392 // |result|. Adds the created match to |map|; if such a match
393 // already exists, whichever one has lower relevance is eliminated.
394 // |metadata| and |accepted_suggestion| are used for generating an
395 // AutocompleteMatch.
396 // |mark_as_deletable| indicates whether the match should be marked deletable.
397 // NOTE: Any result containing a deletion URL is always marked deletable.
398 void AddMatchToMap(const SuggestResult& result,
399 const std::string& metadata,
400 int accepted_suggestion,
401 bool mark_as_deletable,
402 MatchMap* map);
404 // Parses results from the suggest server and updates the appropriate suggest
405 // and navigation result lists in |results|. |is_keyword_result| indicates
406 // whether the response was received from the keyword provider.
407 // Returns whether the appropriate result list members were updated.
408 bool ParseSuggestResults(const base::Value& root_val,
409 bool is_keyword_result,
410 Results* results);
412 // Called at the end of ParseSuggestResults to rank the |results|.
413 virtual void SortResults(bool is_keyword,
414 const base::ListValue* relevances,
415 Results* results);
417 // Returns the TemplateURL corresponding to the keyword or default
418 // provider based on the value of |is_keyword|.
419 virtual const TemplateURL* GetTemplateURL(bool is_keyword) const = 0;
421 // Returns the AutocompleteInput for keyword provider or default provider
422 // based on the value of |is_keyword|.
423 virtual const AutocompleteInput GetInput(bool is_keyword) const = 0;
425 // Returns a pointer to a Results object, which will hold suggest results.
426 virtual Results* GetResultsToFill(bool is_keyword) = 0;
428 // Returns whether the destination URL corresponding to the given |result|
429 // should contain command-line-specified query params.
430 virtual bool ShouldAppendExtraParams(const SuggestResult& result) const = 0;
432 // Stops the suggest query.
433 // NOTE: This does not update |done_|. Callers must do so.
434 virtual void StopSuggest() = 0;
436 // Clears the current results.
437 virtual void ClearAllResults() = 0;
439 // Returns the relevance to use if it was not explicitly set by the server.
440 virtual int GetDefaultResultRelevance() const = 0;
442 // Records in UMA whether the deletion request resulted in success.
443 virtual void RecordDeletionResult(bool success) = 0;
445 // Records UMA statistics about a suggest server response.
446 virtual void LogFetchComplete(bool succeeded, bool is_keyword) = 0;
448 // Returns whether the |fetcher| is for the keyword provider.
449 virtual bool IsKeywordFetcher(const net::URLFetcher* fetcher) const = 0;
451 // Updates |matches_| from the latest results; applies calculated relevances
452 // if suggested relevances cause undesriable behavior. Updates |done_|.
453 virtual void UpdateMatches() = 0;
455 // Whether a field trial, if any, has triggered in the most recent
456 // autocomplete query. This field is set to true only if the suggestion
457 // provider has completed and the response contained
458 // '"google:fieldtrialtriggered":true'.
459 bool field_trial_triggered_;
461 // Same as above except that it is maintained across the current Omnibox
462 // session.
463 bool field_trial_triggered_in_session_;
465 // The number of suggest results that haven't yet arrived. If it's greater
466 // than 0, it indicates that one of the URLFetchers is still running.
467 int suggest_results_pending_;
469 private:
470 friend class SearchProviderTest;
471 FRIEND_TEST_ALL_PREFIXES(SearchProviderTest, TestDeleteMatch);
473 // Removes the deleted |match| from the list of |matches_|.
474 void DeleteMatchFromMatches(const AutocompleteMatch& match);
476 // This gets called when we have requested a suggestion deletion from the
477 // server to handle the results of the deletion. It will be called after the
478 // deletion request completes.
479 void OnDeletionComplete(bool success,
480 SuggestionDeletionHandler* handler);
482 // Each deletion handler in this vector corresponds to an outstanding request
483 // that a server delete a personalized suggestion. Making this a ScopedVector
484 // causes us to auto-cancel all such requests on shutdown.
485 SuggestionDeletionHandlers deletion_handlers_;
487 // True if this provider's results are being displayed in the app list. By
488 // default this is false, meaning that the results will be shown in the
489 // omnibox.
490 bool in_app_list_;
492 DISALLOW_COPY_AND_ASSIGN(BaseSearchProvider);
495 #endif // CHROME_BROWSER_AUTOCOMPLETE_BASE_SEARCH_PROVIDER_H_