Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(138)

Side by Side Diff: components/ntp_snippets/remote/ntp_snippets_json_request.h

Issue 2578173002: NTP: Extract JSON requests from Fetcher. (Closed)
Patch Set: Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2016 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 #ifndef COMPONENTS_NTP_SNIPPETS_REMOTE_NTP_SNIPPETS_JSON_REQUEST_H_
6 #define COMPONENTS_NTP_SNIPPETS_REMOTE_NTP_SNIPPETS_JSON_REQUEST_H_
7
8 #include <memory>
9 #include <string>
10 #include <utility>
11
12 #include "base/callback.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/optional.h"
15 #include "components/ntp_snippets/remote/ntp_snippets_request_params.h"
16 #include "components/ntp_snippets/status.h"
17 #include "components/translate/core/browser/language_model.h"
18 #include "google_apis/gaia/oauth2_token_service.h"
19 #include "net/http/http_request_headers.h"
20
21 namespace base {
22 class Value;
23 class TickClock;
24 } // namespace base
25
26 class FetchAPI;
27 class Personalization;
28
29 namespace ntp_snippets {
30 class UserClassifier;
31
32 namespace internal {
33
34 // Enumeration listing all possible variants of dealing with personalization.
35 enum class Personalization { kPersonal, kNonPersonal, kBoth };
36
37 // Enumeration listing all possible outcomes for fetch attempts. Used for UMA
38 // histograms, so do not change existing values. Insert new values at the end,
39 // and update the histogram definition.
40 enum class FetchResult {
41 SUCCESS,
42 DEPRECATED_EMPTY_HOSTS,
43 URL_REQUEST_STATUS_ERROR,
44 HTTP_ERROR,
45 JSON_PARSE_ERROR,
46 INVALID_SNIPPET_CONTENT_ERROR,
47 OAUTH_TOKEN_ERROR,
48 INTERACTIVE_QUOTA_ERROR,
49 NON_INTERACTIVE_QUOTA_ERROR,
50 RESULT_MAX
51 };
52
53 enum FetchAPI {
54 CHROME_READER_API,
55 CHROME_CONTENT_SUGGESTIONS_API,
56 };
57
58 // A single request to query snippets.
59 class NTPSnippetsJsonRequest : public net::URLFetcherDelegate {
60 public:
61 // Callbacks for JSON parsing, needed because the parsing is platform-
62 // dependent.
63 using SuccessCallback =
64 base::Callback<void(std::unique_ptr<base::Value> result)>;
65 using ErrorCallback = base::Callback<void(const std::string& error)>;
66 using ParseJSONCallback =
67 base::Callback<void(const std::string& raw_json_string,
68 const SuccessCallback& success_callback,
69 const ErrorCallback& error_callback)>;
70
71 // A client can expect error_details only, if there was any error during the
72 // fetching or parsing. In successful cases, it will be an empty string.
73 using CompletedCallback =
74 base::OnceCallback<void(std::unique_ptr<base::Value> result,
75 FetchResult result_code,
76 const std::string& error_details)>;
77
78 // Builds authenticated and non-authenticated NTPSnippetsJsonRequests.
79 class Builder {
80 public:
81 Builder();
82 Builder(Builder&&);
83 ~Builder();
84
85 // Builds a Request object that contains all data to fetch new snippets.
86 std::unique_ptr<NTPSnippetsJsonRequest> Build() const;
87
88 Builder& SetAuthentication(const std::string& account_id,
89 const std::string& auth_header);
90 Builder& SetCreationTime(base::TimeTicks creation_time);
91 Builder& SetFetchAPI(FetchAPI fetch_api);
92 // The language_model borrowed from the fetcher needs to stay alive until
93 // the request body is built.
94 Builder& SetLanguageModel(const translate::LanguageModel* language_model);
95 Builder& SetParams(const NTPSnippetsRequestParams& params);
96 Builder& SetParseJsonCallback(ParseJSONCallback callback);
97 Builder& SetPersonalization(Personalization personalization);
98 // The tick_clock borrowed from the fetcher will be injected into the
99 // request. It will be used at build time and after the fetch returned.
100 // It has to be alive until the request is destroyed.
101 Builder& SetTickClock(base::TickClock* tick_clock);
102 Builder& SetUrl(const GURL& url);
103 Builder& SetUrlRequestContextGetter(
104 const scoped_refptr<net::URLRequestContextGetter>& context_getter);
105 Builder& SetUserClassifier(const UserClassifier& user_classifier);
106
107 // These preview methods allow to inspect the Request without exposing it
108 // publicly.
109 // TODO(fhorschig): Remove these when moving the Builder to
110 // snippets::internal and trigger the request to intercept the request.
111 std::string PreviewRequestBodyForTesting() { return BuildBody(); }
112 std::string PreviewRequestHeadersForTesting() { return BuildHeaders(); }
113 Builder& SetUserClassForTesting(const std::string& user_class) {
114 user_class_ = user_class;
115 return *this;
116 }
117
118 private:
119 std::string BuildHeaders() const;
120 std::string BuildBody() const;
121 std::unique_ptr<net::URLFetcher> BuildURLFetcher(
122 net::URLFetcherDelegate* request,
123 const std::string& headers,
124 const std::string& body) const;
125
126 bool ReturnOnlyPersonalizedResults() const {
127 return !obfuscated_gaia_id_.empty() &&
128 personalization_ == Personalization::kPersonal;
129 }
130
131 void PrepareLanguages(
132 translate::LanguageModel::LanguageInfo* ui_language,
133 translate::LanguageModel::LanguageInfo* other_top_language) const;
134
135 // Only required, if the request needs to be sent.
136 std::string auth_header_;
137 base::TickClock* tick_clock_;
138 FetchAPI fetch_api_;
139 NTPSnippetsRequestParams params_;
140 NTPSnippetsJsonRequest::ParseJSONCallback parse_json_callback_;
141 Personalization personalization_;
142 GURL url_;
143 scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
144
145 // Optional properties.
146 std::string obfuscated_gaia_id_;
147 std::string user_class_;
148 const translate::LanguageModel* language_model_;
149
150 DISALLOW_COPY_AND_ASSIGN(Builder);
151 };
152
153 NTPSnippetsJsonRequest(base::Optional<Category> exclusive_category,
154 base::TickClock* tick_clock,
155 const ParseJSONCallback& callback);
156 NTPSnippetsJsonRequest(NTPSnippetsJsonRequest&&);
157 ~NTPSnippetsJsonRequest() override;
158
159 void Start(CompletedCallback callback);
160
161 const base::Optional<Category>& exclusive_category() const {
162 return exclusive_category_;
163 }
164
165 base::TimeDelta GetFetchDuration() const;
166 std::string GetResponseString() const;
167
168 private:
169 friend class Builder;
170
171 // URLFetcherDelegate implementation.
172 void OnURLFetchComplete(const net::URLFetcher* source) override;
173
174 void ParseJsonResponse();
175 void OnJsonParsed(std::unique_ptr<base::Value> result);
176 void OnJsonError(const std::string& error);
177
178 // The fetcher for downloading the snippets. Only non-null if a fetch is
179 // currently ongoing.
180 std::unique_ptr<net::URLFetcher> url_fetcher_;
181
182 // If set, only return results for this category.
183 base::Optional<Category> exclusive_category_;
184
185 // Use the TickClock from the Fetcher to measure the fetch time. It will be
186 // used on creation and after the fetch returned. It has to be alive until the
187 // request is destroyed.
188 base::TickClock* tick_clock_;
189 base::TimeTicks creation_time_;
190
191 // This callback is called to parse a json string. It contains callbacks for
192 // error and success cases.
193 ParseJSONCallback parse_json_callback_;
194
195 // The callback to notify when URLFetcher finished and results are available.
196 CompletedCallback request_completed_callback_;
197
198 base::WeakPtrFactory<NTPSnippetsJsonRequest> weak_ptr_factory_;
199
200 DISALLOW_COPY_AND_ASSIGN(NTPSnippetsJsonRequest);
201 };
202
203 } // namespace internal
204
205 } // namespace ntp_snippets
206
207 #endif // COMPONENTS_NTP_SNIPPETS_REMOTE_NTP_SNIPPETS_JSON_REQUEST_H_
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698