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

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

Issue 2660883002: Introduce a Doodle Fetcher for NTP (Closed)
Patch Set: CMD line BaseUrl. [Rebase, Weak 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
« no previous file with comments | « components/doodle/doodle_fetcher.h ('k') | components/doodle/doodle_fetcher_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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 const char kDoodleConfigPath[] = "/async/ddljson";
26
27 namespace {
28
29 std::string StripSafetyPreamble(const std::string& json) {
30 // The response may start with )]}'. Ignore this.
31 const char kResponsePreamble[] = ")]}'";
32
33 base::StringPiece json_sp(json);
34 if (json_sp.starts_with(kResponsePreamble)) {
35 json_sp.remove_prefix(strlen(kResponsePreamble));
36 }
37
38 return json_sp.as_string();
39 }
40
41 DoodleType ParseDoodleType(const base::DictionaryValue& ddljson) {
42 std::string type_str;
43 ddljson.GetString("doodle_type", &type_str);
44 if (type_str == "SIMPLE") {
45 return DoodleType::SIMPLE;
46 }
47 if (type_str == "RANDOM") {
48 return DoodleType::RANDOM;
49 }
50 if (type_str == "VIDEO") {
51 return DoodleType::VIDEO;
52 }
53 if (type_str == "INTERACTIVE") {
54 return DoodleType::INTERACTIVE;
55 }
56 if (type_str == "INLINE_INTERACTIVE") {
57 return DoodleType::INLINE_INTERACTIVE;
58 }
59 if (type_str == "SLIDESHOW") {
60 return DoodleType::SLIDESHOW;
61 }
62 return DoodleType::UNKNOWN;
63 }
64
65 } // namespace
66
67 DoodleImage::DoodleImage()
68 : height(0), width(0), is_animated_gif(false), is_cta(false) {}
69 DoodleImage::~DoodleImage() = default;
70
71 DoodleConfig::DoodleConfig() : doodle_type(DoodleType::UNKNOWN) {}
72 DoodleConfig::DoodleConfig(const DoodleConfig& config) = default;
73 DoodleConfig::~DoodleConfig() = default;
74
75 DoodleFetcher::DoodleFetcher(net::URLRequestContextGetter* download_context,
76 GoogleURLTracker* google_url_tracker,
77 const ParseJSONCallback& json_parsing_callback)
78 : download_context_(download_context),
79 json_parsing_callback_(json_parsing_callback),
80 google_url_tracker_(google_url_tracker),
81 clock_(new base::DefaultClock()),
82 weak_ptr_factory_(this) {}
83
84 DoodleFetcher::~DoodleFetcher() {}
85
86 void DoodleFetcher::FetchDoodle(FinishedCallback callback) {
87 callbacks_.push_back(std::move(callback));
88 if (callbacks_.size() > 1) {
89 // If there was already another callback, a request is still running.
90 return;
91 }
92 DCHECK(!fetcher_.get());
93 fetcher_ = URLFetcher::Create(GetGoogleBaseUrl().Resolve(kDoodleConfigPath),
94 URLFetcher::GET, this);
95 fetcher_->SetRequestContext(download_context_);
96 fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
97 net::LOAD_DO_NOT_SAVE_COOKIES);
98 fetcher_->SetAutomaticallyRetryOnNetworkChanges(1);
99 fetcher_->Start();
100 }
101
102 // net::URLFetcherDelegate implementation.
103 void DoodleFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
104 DCHECK_EQ(fetcher_.get(), source);
105 std::unique_ptr<net::URLFetcher> free_fetcher = std::move(fetcher_);
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> dict =
124 base::DictionaryValue::From(std::move(json));
125 if (!dict.get()) {
126 LOG(ERROR) << "Doodle JSON is not valid";
127 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
128 return;
129 }
130
131 ParseDoodle(std::move(dict));
132 }
133
134 void DoodleFetcher::OnJsonParseFailed(const std::string& error_message) {
135 LOG(ERROR) << "JSON parsing failed: " << error_message;
136 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
137 }
138
139 void DoodleFetcher::ParseDoodle(std::unique_ptr<base::DictionaryValue> config) {
140 const base::DictionaryValue* ddljson = nullptr;
141 if (!config->GetDictionary("ddljson", &ddljson)) {
142 LOG(ERROR) << "Doodle JSON reponse did not contain 'ddljson' key.";
143 RespondToAllCallbacks(DoodleState::PARSING_ERROR, base::nullopt);
144 return;
145 }
146
147 DoodleConfig result;
148
149 ParseBaseInformation(*ddljson, &result);
150 if (!ParseImage(*ddljson, "large_image", &result.large_image)) {
151 RespondToAllCallbacks(DoodleState::NO_DOODLE, base::nullopt);
152 return;
153 }
154 ParseImage(*ddljson, "transparent_large_image",
155 &result.transparent_large_image);
156 ParseImage(*ddljson, "large_cta_image", &result.large_cta_image);
157
158 RespondToAllCallbacks(DoodleState::AVAILABLE, std::move(result));
159 }
160
161 bool DoodleFetcher::ParseImage(const base::DictionaryValue& image_parent,
162 const std::string& image_name,
163 DoodleImage* image) const {
164 DCHECK(image);
165 const base::DictionaryValue* image_dict = nullptr;
166 if (!image_parent.GetDictionary(image_name, &image_dict)) {
167 return false;
168 }
169 image->url = ParseRelativeUrl(*image_dict, "url");
170 if (!image->url.is_valid()) {
171 return false;
172 }
173 image_dict->GetInteger("height", &image->height);
174 image_dict->GetInteger("width", &image->width);
175 image_dict->GetBoolean("is_animated_gif", &image->is_animated_gif);
176 image_dict->GetBoolean("is_cta", &image->is_cta);
177 return true;
178 }
179
180 void DoodleFetcher::ParseBaseInformation(const base::DictionaryValue& ddljson,
181 DoodleConfig* config) const {
182 config->search_url = ParseRelativeUrl(ddljson, "search_url");
183 config->target_url = ParseRelativeUrl(ddljson, "target_url");
184 config->fullpage_interactive_url =
185 ParseRelativeUrl(ddljson, "fullpage_interactive_url");
186
187 config->doodle_type = ParseDoodleType(ddljson);
188 ddljson.GetString("alt_text", &config->alt_text);
189
190 // The JSON doesn't guarantee the number to fit into an int.
191 double ttl = 0;
192 if (!ddljson.GetDouble("time_to_live_ms", &ttl)) {
193 LOG(ERROR) << "No valid Doodle image TTL present in ddljson!";
194 return;
195 }
Marc Treib 2017/02/03 15:45:48 The old search_provider_logos code also clamps the
fhorschig 2017/02/06 11:48:22 It's easy to do but hard to define "too long". The
Marc Treib 2017/02/06 17:26:35 I think just replicating the 30 day limit is fine
jshneier 2017/02/06 19:02:40 1 day should be sufficient in just about all cases
Marc Treib 2017/02/07 09:21:09 IIUC, the current behavior is: On each request fro
fhorschig 2017/02/08 09:10:23 Changed to 1 day.
Marc Treib 2017/02/08 10:51:36 TBH, I'd prefer to keep the previous numbers. Ther
fhorschig 2017/02/08 18:37:25 Done.
196 config->expiry_date = clock_->Now() + base::TimeDelta::FromMillisecondsD(ttl);
197 }
198
199 GURL DoodleFetcher::ParseRelativeUrl(const base::DictionaryValue& dict_value,
200 const std::string& key) const {
201 std::string str_url;
202 dict_value.GetString(key, &str_url);
203 if (str_url.empty()) {
204 return GURL();
205 }
206 return GetGoogleBaseUrl().Resolve(str_url);
207 }
208
209 void DoodleFetcher::RespondToAllCallbacks(DoodleState state,
210 base::Optional<DoodleConfig> config) {
211 for (auto& callback : callbacks_) {
212 std::move(callback).Run(state, std::move(config));
Marc Treib 2017/02/03 15:45:48 This will break if there's more than one callback:
fhorschig 2017/02/06 11:48:22 It's const& now. There is no need to move that at
213 }
214 callbacks_.clear();
215 }
216
217 GURL DoodleFetcher::GetGoogleBaseUrl() const {
218 // There might be no tracker without profile. The factory returns nullptr in
219 // tests, too.
220 // TODO(fhorschig): DCHECK(google_url_tracker_) and inject a fake in tests.
Marc Treib 2017/02/03 15:45:48 The nice thing is that we won't need the kDefaultG
fhorschig 2017/02/06 11:48:22 It was already gone, resp. replaced by the public
221 if (google_url_tracker_) {
222 return google_url_tracker_->google_url();
223 }
224 GURL cmd_line_url = google_util::CommandLineGoogleBaseURL();
Marc Treib 2017/02/03 15:45:48 This needs to go before the tracker.
fhorschig 2017/02/06 11:48:22 Done.
225 if (cmd_line_url.is_valid()) {
226 return cmd_line_url;
227 }
228 return GURL(GoogleURLTracker::kDefaultGoogleHomepage);
229 }
230
231 } // namespace doodle
OLDNEW
« no previous file with comments | « components/doodle/doodle_fetcher.h ('k') | components/doodle/doodle_fetcher_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698