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

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

Issue 2660883002: Introduce a Doodle Fetcher for NTP (Closed)
Patch Set: Removed unnecessary constructor. 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
20 using net::URLFetcher;
21
22 namespace doodle {
23
24 namespace {
25
26 const double kMaxTimeToLiveMS = 30.0 * 24 * 60 * 60 * 1000; // 30 days
27
28 const char kDoodleConfigPath[] = "/async/ddljson";
29
30 std::string StripSafetyPreamble(const std::string& json) {
31 // The response may start with )]}'. Ignore this.
32 const char kResponsePreamble[] = ")]}'";
33
34 base::StringPiece json_sp(json);
35 if (json_sp.starts_with(kResponsePreamble)) {
36 json_sp.remove_prefix(strlen(kResponsePreamble));
37 }
38
39 return json_sp.as_string();
40 }
41
42 DoodleType ParseDoodleType(const base::DictionaryValue& ddljson) {
43 std::string type_str;
44 ddljson.GetString("doodle_type", &type_str);
45 if (type_str == "SIMPLE") {
46 return DoodleType::SIMPLE;
47 }
48 if (type_str == "RANDOM") {
49 return DoodleType::RANDOM;
50 }
51 if (type_str == "VIDEO") {
52 return DoodleType::VIDEO;
53 }
54 if (type_str == "INTERACTIVE") {
55 return DoodleType::INTERACTIVE;
56 }
57 if (type_str == "INLINE_INTERACTIVE") {
58 return DoodleType::INLINE_INTERACTIVE;
59 }
60 if (type_str == "SLIDESHOW") {
61 return DoodleType::SLIDESHOW;
62 }
63 return DoodleType::UNKNOWN;
64 }
65
66 } // namespace
67
68 DoodleImage::DoodleImage()
69 : height(0), width(0), is_animated_gif(false), is_cta(false) {}
70 DoodleImage::~DoodleImage() = default;
71
72 DoodleConfig::DoodleConfig() : doodle_type(DoodleType::UNKNOWN) {}
73 DoodleConfig::DoodleConfig(const DoodleConfig& config) = default;
74 DoodleConfig::~DoodleConfig() = default;
75
76 DoodleFetcher::DoodleFetcher(net::URLRequestContextGetter* download_context,
77 GoogleURLTracker* google_url_tracker,
78 const ParseJSONCallback& json_parsing_callback)
79 : download_context_(download_context),
80 json_parsing_callback_(json_parsing_callback),
81 google_url_tracker_(google_url_tracker),
82 clock_(new base::DefaultClock()),
83 weak_ptr_factory_(this) {
84 DCHECK(google_url_tracker_);
85 }
86
87 DoodleFetcher::~DoodleFetcher() = default;
mattm 2017/02/14 22:37:14 Just food for thought, but is it okay to leave han
Marc Treib 2017/02/15 09:07:22 IMO this is okay and actually quite a common patte
88
89 void DoodleFetcher::FetchDoodle(FinishedCallback callback) {
90 if (IsFetchInProgress()) {
91 callbacks_.push_back(std::move(callback));
92 return; // The callback will be called for the existing request's results.
93 }
94 DCHECK(!fetcher_.get());
95 callbacks_.push_back(std::move(callback));
96 fetcher_ = URLFetcher::Create(GetGoogleBaseUrl().Resolve(kDoodleConfigPath),
97 URLFetcher::GET, this);
98 fetcher_->SetRequestContext(download_context_);
99 fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
100 net::LOAD_DO_NOT_SAVE_COOKIES);
mattm 2017/02/14 22:37:14 Also LOAD_DO_NOT_SEND_AUTH_DATA
fhorschig 2017/02/15 10:49:51 Done.
101 fetcher_->SetAutomaticallyRetryOnNetworkChanges(1);
102 fetcher_->Start();
mattm 2017/02/14 22:37:14 Do you need a data_use_measurement::DataUseUserDat
Marc Treib 2017/02/15 09:07:22 Good catch! Yes, we should do that. I'd prefer doi
fhorschig 2017/02/15 10:49:51 Okay,follow-up Cl created: https://codereview.chro
103 }
104
105 void DoodleFetcher::OnURLFetchComplete(const URLFetcher* source) {
106 DCHECK_EQ(fetcher_.get(), source);
107 std::unique_ptr<net::URLFetcher> free_fetcher = std::move(fetcher_);
108
109 std::string json_string;
110 if (!(source->GetStatus().is_success() &&
111 source->GetResponseCode() == net::HTTP_OK &&
112 source->GetResponseAsString(&json_string))) {
113 RespondToAllCallbacks(DoodleState::DOWNLOAD_ERROR, base::nullopt);
114 return;
115 }
116
117 json_parsing_callback_.Run(
118 StripSafetyPreamble(std::move(json_string)),
119 base::Bind(&DoodleFetcher::OnJsonParsed, weak_ptr_factory_.GetWeakPtr()),
120 base::Bind(&DoodleFetcher::OnJsonParseFailed,
121 weak_ptr_factory_.GetWeakPtr()));
122 }
123
124 void DoodleFetcher::OnJsonParsed(std::unique_ptr<base::Value> json) {
125 std::unique_ptr<base::DictionaryValue> config =
126 base::DictionaryValue::From(std::move(json));
127 if (!config.get()) {
128 DLOG(WARNING) << "Doodle JSON is not valid";
129 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
130 return;
131 }
132
133 const base::DictionaryValue* ddljson = nullptr;
134 if (!config->GetDictionary("ddljson", &ddljson)) {
135 DLOG(WARNING) << "Doodle JSON reponse did not contain 'ddljson' key.";
136 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
137 return;
138 }
139
140 base::Optional<DoodleConfig> doodle = ParseDoodle(*ddljson);
141 if (!doodle.has_value()) {
142 RespondToAllCallbacks(DoodleState::NO_DOODLE, base::nullopt);
143 return;
144 }
145
146 RespondToAllCallbacks(DoodleState::AVAILABLE, std::move(doodle));
147 }
148
149 void DoodleFetcher::OnJsonParseFailed(const std::string& error_message) {
150 DLOG(WARNING) << "JSON parsing failed: " << error_message;
151 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
152 }
153
154 base::Optional<DoodleConfig> DoodleFetcher::ParseDoodle(
155 const base::DictionaryValue& ddljson) const {
156 DoodleConfig doodle;
157 if (!ParseImage(ddljson, "large_image", &doodle.large_image)) {
158 return base::nullopt;
159 }
160 ParseImage(ddljson, "transparent_large_image",
161 &doodle.transparent_large_image);
162 ParseImage(ddljson, "large_cta_image", &doodle.large_cta_image);
163 ParseBaseInformation(ddljson, &doodle);
164 return doodle;
165 }
166
167 bool DoodleFetcher::ParseImage(const base::DictionaryValue& image_parent,
168 const std::string& image_name,
169 DoodleImage* image) const {
170 DCHECK(image);
171 const base::DictionaryValue* image_dict = nullptr;
172 if (!image_parent.GetDictionary(image_name, &image_dict)) {
173 return false;
174 }
175 image->url = ParseRelativeUrl(*image_dict, "url");
176 if (!image->url.is_valid()) {
177 DLOG(WARNING) << "Image URL for \"" << image_name << "\" is invalid.";
178 return false;
179 }
180 image_dict->GetInteger("height", &image->height);
181 image_dict->GetInteger("width", &image->width);
182 image_dict->GetBoolean("is_animated_gif", &image->is_animated_gif);
183 image_dict->GetBoolean("is_cta", &image->is_cta);
184 return true;
185 }
186
187 void DoodleFetcher::ParseBaseInformation(const base::DictionaryValue& ddljson,
188 DoodleConfig* config) const {
189 config->search_url = ParseRelativeUrl(ddljson, "search_url");
190 config->target_url = ParseRelativeUrl(ddljson, "target_url");
191 config->fullpage_interactive_url =
192 ParseRelativeUrl(ddljson, "fullpage_interactive_url");
193
194 config->doodle_type = ParseDoodleType(ddljson);
195 ddljson.GetString("alt_text", &config->alt_text);
196 ddljson.GetString("interactive_html", &config->interactive_html);
197
198 // The JSON doesn't guarantee the number to fit into an int.
199 double ttl = 0; // Expires immediately if the parameter is missing.
mattm 2017/02/14 22:37:14 Are fetches only initiated by the user opening the
fhorschig 2017/02/15 10:49:51 The fetcher is rather simple as it only fetches th
200 if (!ddljson.GetDouble("time_to_live_ms", &ttl) || ttl < 0) {
201 DLOG(WARNING) << "No valid Doodle image TTL present in ddljson!";
202 ttl = 0;
203 }
204 if (ttl > kMaxTimeToLiveMS) {
205 ttl = kMaxTimeToLiveMS;
206 DLOG(WARNING) << "Clamping Doodle image TTL to 30 days!";
207 }
208 config->expiry_date = clock_->Now() + base::TimeDelta::FromMillisecondsD(ttl);
209 }
210
211 GURL DoodleFetcher::ParseRelativeUrl(const base::DictionaryValue& dict_value,
212 const std::string& key) const {
213 std::string str_url;
214 dict_value.GetString(key, &str_url);
215 if (str_url.empty()) {
216 return GURL();
217 }
218 return GetGoogleBaseUrl().Resolve(str_url);
219 }
220
221 void DoodleFetcher::RespondToAllCallbacks(
222 DoodleState state,
223 const base::Optional<DoodleConfig>& config) {
224 for (auto& callback : callbacks_) {
225 std::move(callback).Run(state, config);
226 }
227 callbacks_.clear();
228 }
229
230 GURL DoodleFetcher::GetGoogleBaseUrl() const {
231 GURL cmd_line_url = google_util::CommandLineGoogleBaseURL();
232 if (cmd_line_url.is_valid()) {
233 return cmd_line_url;
234 }
235 return google_url_tracker_->google_url();
236 }
237
238 } // namespace doodle
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698