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

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

Issue 2660883002: Introduce a Doodle Fetcher for NTP (Closed)
Patch Set: Rebase. 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"
20
21 using net::URLFetcher;
22
23 namespace doodle {
24
25 namespace {
26
27 const double kMaxTimeToLiveMS = 24.0 * 60 * 60 * 1000; // 1 day
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) {}
Marc Treib 2017/02/08 10:51:36 DCHECK(google_url_tracker_) ? (To make the require
fhorschig 2017/02/08 18:37:25 Done.
85
86 DoodleFetcher::~DoodleFetcher() {}
87
88 void DoodleFetcher::FetchDoodle(FinishedCallback callback) {
89 callbacks_.push_back(std::move(callback));
90 if (callbacks_.size() > 1) {
91 // If there was already another callback, a request is still running.
92 return;
93 }
94 DCHECK(!fetcher_.get());
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 // net::URLFetcherDelegate implementation.
105 void DoodleFetcher::OnURLFetchComplete(const net::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> dict =
126 base::DictionaryValue::From(std::move(json));
127 if (!dict.get()) {
128 DLOG(WARNING) << "Doodle JSON is not valid";
129 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
130 return;
131 }
132
133 ParseDoodle(std::move(dict));
134 }
135
136 void DoodleFetcher::OnJsonParseFailed(const std::string& error_message) {
137 DLOG(WARNING) << "JSON parsing failed: " << error_message;
138 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
139 }
140
141 void DoodleFetcher::ParseDoodle(std::unique_ptr<base::DictionaryValue> config) {
142 const base::DictionaryValue* ddljson = nullptr;
143 if (!config->GetDictionary("ddljson", &ddljson)) {
144 DLOG(WARNING) << "Doodle JSON reponse did not contain 'ddljson' key.";
145 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
146 return;
147 }
148
149 DoodleConfig result;
150
151 if (!ParseImage(*ddljson, "large_image", &result.large_image)) {
152 RespondToAllCallbacks(DoodleState::NO_DOODLE, base::nullopt);
153 return;
154 }
155 ParseImage(*ddljson, "transparent_large_image",
156 &result.transparent_large_image);
157 ParseImage(*ddljson, "large_cta_image", &result.large_cta_image);
158 ParseBaseInformation(*ddljson, &result);
159
160 RespondToAllCallbacks(DoodleState::AVAILABLE, std::move(result));
161 }
162
163 bool DoodleFetcher::ParseImage(const base::DictionaryValue& image_parent,
164 const std::string& image_name,
165 DoodleImage* image) const {
166 DCHECK(image);
167 const base::DictionaryValue* image_dict = nullptr;
168 if (!image_parent.GetDictionary(image_name, &image_dict)) {
169 return false;
170 }
171 image->url = ParseRelativeUrl(*image_dict, "url");
172 if (!image->url.is_valid()) {
173 DLOG(WARNING) << "Image URL for \"" << image_name << "\" is invalid.";
174 return false;
175 }
176 image_dict->GetInteger("height", &image->height);
177 image_dict->GetInteger("width", &image->width);
178 image_dict->GetBoolean("is_animated_gif", &image->is_animated_gif);
179 image_dict->GetBoolean("is_cta", &image->is_cta);
180 return true;
181 }
182
183 void DoodleFetcher::ParseBaseInformation(const base::DictionaryValue& ddljson,
184 DoodleConfig* config) const {
185 config->search_url = ParseRelativeUrl(ddljson, "search_url");
186 config->target_url = ParseRelativeUrl(ddljson, "target_url");
187 config->fullpage_interactive_url =
188 ParseRelativeUrl(ddljson, "fullpage_interactive_url");
189
190 config->doodle_type = ParseDoodleType(ddljson);
191 ddljson.GetString("alt_text", &config->alt_text);
192 ddljson.GetString("interactive_html", &config->interactive_html);
193 ddljson.GetString("interactive_js", &config->interactive_js);
194
195 // The JSON doesn't guarantee the number to fit into an int.
196 double ttl = 0; // Expires immediately if the parameter is missing.
197 if (!ddljson.GetDouble("time_to_live_ms", &ttl) || ttl < 0) {
198 DLOG(WARNING) << "No valid Doodle image TTL present in ddljson!";
199 ttl = 0;
200 }
201 if (ttl > kMaxTimeToLiveMS) {
202 ttl = kMaxTimeToLiveMS;
203 DLOG(WARNING) << "Clamping Doodle image TTL to 30 days!";
Marc Treib 2017/02/08 10:51:36 nit: Comment is inaccurate now (but per my other c
fhorschig 2017/02/08 18:37:25 It's 30 days again.
204 }
205 config->expiry_date = clock_->Now() + base::TimeDelta::FromMillisecondsD(ttl);
206 }
207
208 GURL DoodleFetcher::ParseRelativeUrl(const base::DictionaryValue& dict_value,
209 const std::string& key) const {
210 std::string str_url;
211 dict_value.GetString(key, &str_url);
212 if (str_url.empty()) {
213 return GURL();
214 }
215 return GetGoogleBaseUrl().Resolve(str_url);
216 }
217
218 void DoodleFetcher::RespondToAllCallbacks(
219 DoodleState state,
220 const base::Optional<DoodleConfig>& config) {
221 for (auto& callback : callbacks_) {
222 std::move(callback).Run(state, config);
223 }
224 callbacks_.clear();
225 }
226
227 GURL DoodleFetcher::GetGoogleBaseUrl() const {
228 GURL cmd_line_url = google_util::CommandLineGoogleBaseURL();
229 if (cmd_line_url.is_valid()) {
230 return cmd_line_url;
231 }
232 return google_url_tracker_->google_url();
233 }
234
235 } // namespace doodle
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698