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

Side by Side Diff: components/doodle/doodle_fetcher.cc

Issue 2660883002: Introduce a Doodle Fetcher for NTP (Closed)
Patch Set: Inline JSON responses in tests Created 3 years, 10 months 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 2017 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 "components/doodle/doodle_fetcher.h"
6
7 #include <utility>
8
9 #include "base/strings/string_number_conversions.h"
10 #include "base/time/clock.h"
11 #include "base/time/default_clock.h"
12 #include "base/time/time.h"
13 #include "base/values.h"
14 #include "components/google/core/browser/google_url_tracker.h"
15 #include "components/google/core/browser/google_util.h"
16 #include "net/base/load_flags.h"
17 #include "net/http/http_status_code.h"
18 #include "net/url_request/url_fetcher.h"
19 #include "url/gurl.h"
Marc Treib 2017/02/10 10:28:47 nit: already included in the header
fhorschig 2017/02/13 09:20:57 Gone.
20
21 using net::URLFetcher;
22
23 namespace doodle {
24
25 namespace {
26
27 const double kMaxTimeToLiveMS = 30.0 * 24 * 60 * 60 * 1000; // 30 days
28
29 const char kDoodleConfigPath[] = "/async/ddljson";
30
31 std::string StripSafetyPreamble(const std::string& json) {
32 // The response may start with )]}'. Ignore this.
33 const char kResponsePreamble[] = ")]}'";
34
35 base::StringPiece json_sp(json);
36 if (json_sp.starts_with(kResponsePreamble)) {
37 json_sp.remove_prefix(strlen(kResponsePreamble));
38 }
39
40 return json_sp.as_string();
41 }
42
43 DoodleType ParseDoodleType(const base::DictionaryValue& ddljson) {
44 std::string type_str;
45 ddljson.GetString("doodle_type", &type_str);
46 if (type_str == "SIMPLE") {
47 return DoodleType::SIMPLE;
48 }
49 if (type_str == "RANDOM") {
50 return DoodleType::RANDOM;
51 }
52 if (type_str == "VIDEO") {
53 return DoodleType::VIDEO;
54 }
55 if (type_str == "INTERACTIVE") {
56 return DoodleType::INTERACTIVE;
57 }
58 if (type_str == "INLINE_INTERACTIVE") {
59 return DoodleType::INLINE_INTERACTIVE;
60 }
61 if (type_str == "SLIDESHOW") {
62 return DoodleType::SLIDESHOW;
63 }
64 return DoodleType::UNKNOWN;
65 }
66
67 } // namespace
68
69 DoodleImage::DoodleImage()
70 : height(0), width(0), is_animated_gif(false), is_cta(false) {}
71 DoodleImage::~DoodleImage() = default;
72
73 DoodleConfig::DoodleConfig() : doodle_type(DoodleType::UNKNOWN) {}
74 DoodleConfig::DoodleConfig(const DoodleConfig& config) = default;
75 DoodleConfig::~DoodleConfig() = default;
76
77 DoodleFetcher::DoodleFetcher(net::URLRequestContextGetter* download_context,
78 GoogleURLTracker* google_url_tracker,
79 const ParseJSONCallback& json_parsing_callback)
80 : download_context_(download_context),
81 json_parsing_callback_(json_parsing_callback),
82 google_url_tracker_(google_url_tracker),
83 clock_(new base::DefaultClock()),
84 weak_ptr_factory_(this) {
85 DCHECK(google_url_tracker_);
86 }
87
88 DoodleFetcher::~DoodleFetcher() {}
Marc Treib 2017/02/10 10:28:47 nit: = default
fhorschig 2017/02/13 09:20:57 Done.
89
90 void DoodleFetcher::FetchDoodle(FinishedCallback callback) {
91 callbacks_.push_back(std::move(callback));
92 if (callbacks_.size() > 1) {
Marc Treib 2017/02/10 10:28:47 Would "if (fetcher_)" be a more straightforward wa
fhorschig 2017/02/13 09:20:57 Hmm, yes. Changed condition and the fetcher_ to be
93 // If there was already another callback, a request is still running.
94 return;
95 }
96 DCHECK(!fetcher_.get());
97 fetcher_ = URLFetcher::Create(GetGoogleBaseUrl().Resolve(kDoodleConfigPath),
98 URLFetcher::GET, this);
99 fetcher_->SetRequestContext(download_context_);
100 fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
101 net::LOAD_DO_NOT_SAVE_COOKIES);
102 fetcher_->SetAutomaticallyRetryOnNetworkChanges(1);
103 fetcher_->Start();
104 }
105
106 // net::URLFetcherDelegate implementation.
Marc Treib 2017/02/10 10:28:48 nit: comment not required here (there's one in the
fhorschig 2017/02/13 09:20:57 Gone.
107 void DoodleFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
Marc Treib 2017/02/10 10:28:47 nit: There's a "using net::URLFetcher" above, so t
fhorschig 2017/02/13 09:20:57 net:: Gone. (I like the using for readability of t
108 DCHECK_EQ(fetcher_.get(), source);
109 std::unique_ptr<net::URLFetcher> free_fetcher = std::move(fetcher_);
110
111 std::string json_string;
112 if (!(source->GetStatus().is_success() &&
113 source->GetResponseCode() == net::HTTP_OK &&
114 source->GetResponseAsString(&json_string))) {
115 RespondToAllCallbacks(DoodleState::DOWNLOAD_ERROR, base::nullopt);
116 return;
117 }
118
119 json_parsing_callback_.Run(
120 StripSafetyPreamble(std::move(json_string)),
121 base::Bind(&DoodleFetcher::OnJsonParsed, weak_ptr_factory_.GetWeakPtr()),
122 base::Bind(&DoodleFetcher::OnJsonParseFailed,
123 weak_ptr_factory_.GetWeakPtr()));
124 }
125
126 void DoodleFetcher::OnJsonParsed(std::unique_ptr<base::Value> json) {
127 std::unique_ptr<base::DictionaryValue> dict =
128 base::DictionaryValue::From(std::move(json));
129 if (!dict.get()) {
130 DLOG(WARNING) << "Doodle JSON is not valid";
131 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
132 return;
133 }
134
135 ParseDoodle(std::move(dict));
136 }
137
138 void DoodleFetcher::OnJsonParseFailed(const std::string& error_message) {
139 DLOG(WARNING) << "JSON parsing failed: " << error_message;
140 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
141 }
142
143 void DoodleFetcher::ParseDoodle(std::unique_ptr<base::DictionaryValue> config) {
Marc Treib 2017/02/10 10:28:47 nit: This is different from the other "Parse*" met
fhorschig 2017/02/13 09:20:57 Done. |OnJsonParsed| is where callback are called
144 const base::DictionaryValue* ddljson = nullptr;
145 if (!config->GetDictionary("ddljson", &ddljson)) {
146 DLOG(WARNING) << "Doodle JSON reponse did not contain 'ddljson' key.";
147 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
148 return;
149 }
150
151 DoodleConfig result;
152
153 if (!ParseImage(*ddljson, "large_image", &result.large_image)) {
154 RespondToAllCallbacks(DoodleState::NO_DOODLE, base::nullopt);
155 return;
156 }
157 ParseImage(*ddljson, "transparent_large_image",
158 &result.transparent_large_image);
159 ParseImage(*ddljson, "large_cta_image", &result.large_cta_image);
160 ParseBaseInformation(*ddljson, &result);
161
162 RespondToAllCallbacks(DoodleState::AVAILABLE, std::move(result));
163 }
164
165 bool DoodleFetcher::ParseImage(const base::DictionaryValue& image_parent,
166 const std::string& image_name,
167 DoodleImage* image) const {
168 DCHECK(image);
169 const base::DictionaryValue* image_dict = nullptr;
170 if (!image_parent.GetDictionary(image_name, &image_dict)) {
171 return false;
172 }
173 image->url = ParseRelativeUrl(*image_dict, "url");
174 if (!image->url.is_valid()) {
175 DLOG(WARNING) << "Image URL for \"" << image_name << "\" is invalid.";
176 return false;
177 }
178 image_dict->GetInteger("height", &image->height);
179 image_dict->GetInteger("width", &image->width);
180 image_dict->GetBoolean("is_animated_gif", &image->is_animated_gif);
181 image_dict->GetBoolean("is_cta", &image->is_cta);
182 return true;
183 }
184
185 void DoodleFetcher::ParseBaseInformation(const base::DictionaryValue& ddljson,
186 DoodleConfig* config) const {
187 config->search_url = ParseRelativeUrl(ddljson, "search_url");
188 config->target_url = ParseRelativeUrl(ddljson, "target_url");
189 config->fullpage_interactive_url =
190 ParseRelativeUrl(ddljson, "fullpage_interactive_url");
191
192 config->doodle_type = ParseDoodleType(ddljson);
193 ddljson.GetString("alt_text", &config->alt_text);
194 ddljson.GetString("interactive_html", &config->interactive_html);
195 ddljson.GetString("interactive_js", &config->interactive_js);
196
197 // The JSON doesn't guarantee the number to fit into an int.
198 double ttl = 0; // Expires immediately if the parameter is missing.
199 if (!ddljson.GetDouble("time_to_live_ms", &ttl) || ttl < 0) {
200 DLOG(WARNING) << "No valid Doodle image TTL present in ddljson!";
201 ttl = 0;
202 }
203 if (ttl > kMaxTimeToLiveMS) {
204 ttl = kMaxTimeToLiveMS;
205 DLOG(WARNING) << "Clamping Doodle image TTL to 30 days!";
206 }
207 config->expiry_date = clock_->Now() + base::TimeDelta::FromMillisecondsD(ttl);
208 }
209
210 GURL DoodleFetcher::ParseRelativeUrl(const base::DictionaryValue& dict_value,
211 const std::string& key) const {
212 std::string str_url;
213 dict_value.GetString(key, &str_url);
214 if (str_url.empty()) {
215 return GURL();
216 }
217 return GetGoogleBaseUrl().Resolve(str_url);
218 }
219
220 void DoodleFetcher::RespondToAllCallbacks(
221 DoodleState state,
222 const base::Optional<DoodleConfig>& config) {
223 for (auto& callback : callbacks_) {
224 std::move(callback).Run(state, config);
225 }
226 callbacks_.clear();
227 }
228
229 GURL DoodleFetcher::GetGoogleBaseUrl() const {
230 GURL cmd_line_url = google_util::CommandLineGoogleBaseURL();
231 if (cmd_line_url.is_valid()) {
232 return cmd_line_url;
233 }
234 return google_url_tracker_->google_url();
235 }
236
237 } // namespace doodle
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698