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

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

Issue 2660883002: Introduce a Doodle Fetcher for NTP (Closed)
Patch Set: Address comments 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;
88
89 void DoodleFetcher::FetchDoodle(FinishedCallback callback) {
90 callbacks_.push_back(std::move(callback));
91 if (fetcher_) {
92 return; // The callback will be called for the existing request's results.
93 }
94 DCHECK(!fetcher_.get());
Marc Treib 2017/02/13 09:48:40 nit: Now the DCHECK isn't required anymore, since
fhorschig 2017/02/13 11:01:25 Reverted condition as discussed.
95 fetcher_ = URLFetcher::Create(GetGoogleBaseUrl().Resolve(kDoodleConfigPath),
96 URLFetcher::GET, this);
97 fetcher_->SetRequestContext(download_context_);
98 fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
99 net::LOAD_DO_NOT_SAVE_COOKIES);
100 fetcher_->SetAutomaticallyRetryOnNetworkChanges(1);
101 fetcher_->Start();
102 }
103
104 void DoodleFetcher::OnURLFetchComplete(const URLFetcher* source) {
105 DCHECK_EQ(fetcher_.get(), source);
106
107 std::string json_string;
108 if (!(source->GetStatus().is_success() &&
109 source->GetResponseCode() == net::HTTP_OK &&
110 source->GetResponseAsString(&json_string))) {
111 RespondToAllCallbacks(DoodleState::DOWNLOAD_ERROR, base::nullopt);
112 return;
113 }
114
115 json_parsing_callback_.Run(
116 StripSafetyPreamble(std::move(json_string)),
117 base::Bind(&DoodleFetcher::OnJsonParsed, weak_ptr_factory_.GetWeakPtr()),
118 base::Bind(&DoodleFetcher::OnJsonParseFailed,
119 weak_ptr_factory_.GetWeakPtr()));
120 }
121
122 void DoodleFetcher::OnJsonParsed(std::unique_ptr<base::Value> json) {
123 std::unique_ptr<base::DictionaryValue> config =
124 base::DictionaryValue::From(std::move(json));
125 if (!config.get()) {
126 DLOG(WARNING) << "Doodle JSON is not valid";
127 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
128 return;
129 }
130
131 const base::DictionaryValue* ddljson = nullptr;
132 if (!config->GetDictionary("ddljson", &ddljson)) {
133 DLOG(WARNING) << "Doodle JSON reponse did not contain 'ddljson' key.";
134 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
135 return;
136 }
137
138 base::Optional<DoodleConfig> doodle = ParseDoodle(*ddljson);
139 if (doodle.has_value()) {
Marc Treib 2017/02/13 09:48:40 nit: I'd swap this around - if there *isn't* a val
fhorschig 2017/02/13 11:01:25 Okay.
140 RespondToAllCallbacks(DoodleState::AVAILABLE, std::move(doodle));
141 return;
142 }
143
144 RespondToAllCallbacks(DoodleState::NO_DOODLE, base::nullopt);
145 }
146
147 void DoodleFetcher::OnJsonParseFailed(const std::string& error_message) {
148 DLOG(WARNING) << "JSON parsing failed: " << error_message;
149 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
150 }
151
152 base::Optional<DoodleConfig> DoodleFetcher::ParseDoodle(
153 const base::DictionaryValue& ddljson) {
154 DoodleConfig result;
155
156 if (!ParseImage(ddljson, "large_image", &result.large_image)) {
157 return base::nullopt;
158 }
159 ParseImage(ddljson, "transparent_large_image",
160 &result.transparent_large_image);
161 ParseImage(ddljson, "large_cta_image", &result.large_cta_image);
162 ParseBaseInformation(ddljson, &result);
163 return result;
164 }
165
166 bool DoodleFetcher::ParseImage(const base::DictionaryValue& image_parent,
167 const std::string& image_name,
168 DoodleImage* image) const {
169 DCHECK(image);
170 const base::DictionaryValue* image_dict = nullptr;
171 if (!image_parent.GetDictionary(image_name, &image_dict)) {
172 return false;
173 }
174 image->url = ParseRelativeUrl(*image_dict, "url");
175 if (!image->url.is_valid()) {
176 DLOG(WARNING) << "Image URL for \"" << image_name << "\" is invalid.";
177 return false;
178 }
179 image_dict->GetInteger("height", &image->height);
180 image_dict->GetInteger("width", &image->width);
181 image_dict->GetBoolean("is_animated_gif", &image->is_animated_gif);
182 image_dict->GetBoolean("is_cta", &image->is_cta);
183 return true;
184 }
185
186 void DoodleFetcher::ParseBaseInformation(const base::DictionaryValue& ddljson,
187 DoodleConfig* config) const {
188 config->search_url = ParseRelativeUrl(ddljson, "search_url");
189 config->target_url = ParseRelativeUrl(ddljson, "target_url");
190 config->fullpage_interactive_url =
191 ParseRelativeUrl(ddljson, "fullpage_interactive_url");
192
193 config->doodle_type = ParseDoodleType(ddljson);
194 ddljson.GetString("alt_text", &config->alt_text);
195 ddljson.GetString("interactive_html", &config->interactive_html);
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 std::unique_ptr<net::URLFetcher> free_fetcher = std::move(fetcher_);
Marc Treib 2017/02/13 09:48:40 This doesn't really belong here IMO - the fetcher
fhorschig 2017/02/13 11:01:26 Moved up again as discussed.
Marc Treib 2017/02/13 11:12:49 Nope, it's still here ;P
fhorschig 2017/02/13 13:06:21 Weird. Moved up again. (And double-checked)
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