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

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

Issue 2660883002: Introduce a Doodle Fetcher for NTP (Closed)
Patch Set: Revert and refactor condition for running requests 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 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);
101 fetcher_->SetAutomaticallyRetryOnNetworkChanges(1);
102 fetcher_->Start();
103 }
104
105 void DoodleFetcher::OnURLFetchComplete(const URLFetcher* source) {
106 DCHECK_EQ(fetcher_.get(), source);
107
108 std::string json_string;
109 if (!(source->GetStatus().is_success() &&
110 source->GetResponseCode() == net::HTTP_OK &&
111 source->GetResponseAsString(&json_string))) {
112 RespondToAllCallbacks(DoodleState::DOWNLOAD_ERROR, base::nullopt);
113 return;
114 }
115
116 json_parsing_callback_.Run(
117 StripSafetyPreamble(std::move(json_string)),
118 base::Bind(&DoodleFetcher::OnJsonParsed, weak_ptr_factory_.GetWeakPtr()),
119 base::Bind(&DoodleFetcher::OnJsonParseFailed,
120 weak_ptr_factory_.GetWeakPtr()));
121 }
122
123 void DoodleFetcher::OnJsonParsed(std::unique_ptr<base::Value> json) {
124 std::unique_ptr<base::DictionaryValue> config =
125 base::DictionaryValue::From(std::move(json));
126 if (!config.get()) {
127 DLOG(WARNING) << "Doodle JSON is not valid";
128 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
129 return;
130 }
131
132 const base::DictionaryValue* ddljson = nullptr;
133 if (!config->GetDictionary("ddljson", &ddljson)) {
134 DLOG(WARNING) << "Doodle JSON reponse did not contain 'ddljson' key.";
135 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
136 return;
137 }
138
139 DoodleConfig doodle;
140 if (!ParseDoodle(*ddljson, &doodle)) {
141 RespondToAllCallbacks(DoodleState::NO_DOODLE, base::nullopt);
142 return;
143 }
144
145 RespondToAllCallbacks(DoodleState::AVAILABLE, std::move(doodle));
146 }
147
148 void DoodleFetcher::OnJsonParseFailed(const std::string& error_message) {
149 DLOG(WARNING) << "JSON parsing failed: " << error_message;
150 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
151 }
152
153 bool DoodleFetcher::ParseDoodle(const base::DictionaryValue& ddljson,
154 DoodleConfig* doodle) const {
155 if (!ParseImage(ddljson, "large_image", &doodle->large_image)) {
156 return false;
157 }
158 ParseImage(ddljson, "transparent_large_image",
159 &doodle->transparent_large_image);
160 ParseImage(ddljson, "large_cta_image", &doodle->large_cta_image);
161 ParseBaseInformation(ddljson, doodle);
162 return true;
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
196 // The JSON doesn't guarantee the number to fit into an int.
197 double ttl = 0; // Expires immediately if the parameter is missing.
198 if (!ddljson.GetDouble("time_to_live_ms", &ttl) || ttl < 0) {
199 DLOG(WARNING) << "No valid Doodle image TTL present in ddljson!";
200 ttl = 0;
201 }
202 if (ttl > kMaxTimeToLiveMS) {
203 ttl = kMaxTimeToLiveMS;
204 DLOG(WARNING) << "Clamping Doodle image TTL to 30 days!";
205 }
206 config->expiry_date = clock_->Now() + base::TimeDelta::FromMillisecondsD(ttl);
207 }
208
209 GURL DoodleFetcher::ParseRelativeUrl(const base::DictionaryValue& dict_value,
210 const std::string& key) const {
211 std::string str_url;
212 dict_value.GetString(key, &str_url);
213 if (str_url.empty()) {
214 return GURL();
215 }
216 return GetGoogleBaseUrl().Resolve(str_url);
217 }
218
219 void DoodleFetcher::RespondToAllCallbacks(
220 DoodleState state,
221 const base::Optional<DoodleConfig>& config) {
222 std::unique_ptr<net::URLFetcher> free_fetcher = std::move(fetcher_);
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