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

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

Issue 2660883002: Introduce a Doodle Fetcher for NTP (Closed)
Patch Set: Thread-safe multiple callbacks. 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
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/safe_json/safe_json_parser.h"
15 #include "net/base/load_flags.h"
16 #include "net/http/http_status_code.h"
17 #include "net/url_request/url_fetcher.h"
18 #include "url/gurl.h"
19
20 using net::URLFetcher;
21
22 namespace doodle {
23
24 const char kDoodleConfigUrl[] = "/async/ddljson?ogdeb=ct~2000000007";
25
26 namespace {
27
28 void ParseJson(
29 const std::string& json,
30 const base::Callback<void(std::unique_ptr<base::Value>)>& success_callback,
31 const base::Callback<void(const std::string&)>& error_callback) {
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 safe_json::SafeJsonParser::Parse(json_sp.as_string(), success_callback,
41 error_callback);
42 }
43
44 DoodleType ParseDoodleType(const base::DictionaryValue* ddljson) {
45 std::string type_str;
46 ddljson->GetString("doodle_type", &type_str);
47 if (type_str == "SIMPLE") {
48 return DoodleType::SIMPLE;
49 }
50 if (type_str == "RANDOM") {
51 return DoodleType::RANDOM;
52 }
53 if (type_str == "VIDEO") {
54 return DoodleType::VIDEO;
55 }
56 if (type_str == "INTERACTIVE") {
57 return DoodleType::INTERACTIVE;
58 }
59 if (type_str == "INLINE_INTERACTIVE") {
60 return DoodleType::INLINE_INTERACTIVE;
61 }
62 if (type_str == "SLIDESHOW") {
63 return DoodleType::SLIDESHOW;
64 }
65 return DoodleType::SIMPLE;
66 }
67
68 } // namespace
69
70 DoodleImage::DoodleImage()
71 : height(0),
72 width(0),
73 background_color("#ffffff"),
74 is_animated_gif(false),
75 is_cta(false) {}
76 DoodleImage::DoodleImage(const DoodleImage& image) = default;
77 DoodleImage::~DoodleImage() = default;
78
79 DoodleConfig::DoodleConfig(DoodleState doodle_state)
80 : state(doodle_state),
81 doodle_type(DoodleType::SIMPLE),
82 expiry_date(base::Time::Now()) {}
83 DoodleConfig::~DoodleConfig() = default;
84 DoodleConfig::DoodleConfig(const DoodleConfig& config) = default;
85
86 DoodleFetcher::DoodleFetcher(net::URLRequestContextGetter* download_context,
87 GURL base_url)
88 : DoodleFetcher(download_context, base_url, base::Bind(ParseJson)) {}
89
90 DoodleFetcher::DoodleFetcher(net::URLRequestContextGetter* download_context,
91 GURL base_url,
92 ParseJSONCallback json_parsing_callback)
93 : download_context_(download_context),
94 json_parsing_callback_(json_parsing_callback),
95 base_url_(base_url),
96 clock_(new base::DefaultClock()),
97 weak_ptr_factory_(this) {}
98
99 DoodleFetcher::~DoodleFetcher() {}
100
101 void DoodleFetcher::FetchDoodle(FinishedCallback callback) {
102 callback_lock_.Acquire();
Marc Treib 2017/02/01 10:55:58 Is this required? I don't see why we would ever us
fhorschig 2017/02/01 11:16:13 Removed.
103 callbacks_.push_back(std::move(callback));
104 if (callbacks_.size() > 1) {
105 callback_lock_.Release();
106 return; // With 2 or more callbacks, a fetcher is already running.
107 }
108 callback_lock_.Release();
109 fetcher_ = URLFetcher::Create(base_url_.Resolve(kDoodleConfigUrl),
110 URLFetcher::GET, this);
111 fetcher_->SetRequestContext(download_context_);
112 fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
113 net::LOAD_DO_NOT_SAVE_COOKIES);
114 fetcher_->SetAutomaticallyRetryOnNetworkChanges(1);
115 fetcher_->Start();
116 }
117
118 // net::URLFetcherDelegate implementation.
119 void DoodleFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
120 DCHECK_EQ(fetcher_.get(), source);
121 std::unique_ptr<net::URLFetcher> free_fetcher = std::move(fetcher_);
122
123 std::string json_string;
124 if (!(source->GetStatus().is_success() &&
125 source->GetResponseCode() == net::HTTP_OK &&
126 source->GetResponseAsString(&json_string))) {
127 RespondToAllCallbacks(DoodleConfig(DoodleState::DOWNLOAD_ERROR));
128 return;
129 }
130
131 ParseJson(json_string, base::Bind(&DoodleFetcher::OnJsonParsed,
132 weak_ptr_factory_.GetWeakPtr()),
133 base::Bind(&DoodleFetcher::OnJsonParseFailed,
134 weak_ptr_factory_.GetWeakPtr()));
135 }
136
137 // ParseJSONCallback Success callback
138 void DoodleFetcher::OnJsonParsed(std::unique_ptr<base::Value> json) {
139 std::unique_ptr<base::DictionaryValue> dict =
140 base::DictionaryValue::From(std::move(json));
141 if (!dict.get()) {
142 LOG(ERROR) << "Doodle JSON is not valid";
143 RespondToAllCallbacks(DoodleConfig(DoodleState::PARSING_ERROR));
144 return;
145 }
146
147 ParseDoodle(std::move(dict));
148 }
149
150 // ParseJSONCallback Failure callback
151 void DoodleFetcher::OnJsonParseFailed(const std::string& error_message) {
152 LOG(ERROR) << "JSON parsing failed: " << error_message;
153 RespondToAllCallbacks(DoodleConfig(DoodleState::PARSING_ERROR));
154 }
155
156 void DoodleFetcher::ParseDoodle(std::unique_ptr<base::DictionaryValue> config) {
157 const base::DictionaryValue* ddljson = nullptr;
158 if (!config->GetDictionary("ddljson", &ddljson)) {
159 LOG(ERROR) << "Doodle JSON reponse did not contain 'ddljson' key.";
160 RespondToAllCallbacks(DoodleConfig(DoodleState::PARSING_ERROR));
161 return;
162 }
163
164 DoodleConfig result(DoodleState::AVAILABLE);
165 ParseBaseInformation(ddljson, &result);
166
167 if (!ParseImage(ddljson, "large_image", &result.large_image)) {
168 RespondToAllCallbacks(DoodleConfig(DoodleState::NO_DOODLE));
169 return;
170 }
171 ParseImage(ddljson, "transparent_large_image",
172 &result.transparent_large_image);
173 ParseImage(ddljson, "hires_image", &result.hires_image);
174 ParseImage(ddljson, "medium_image", &result.medium_image);
175 ParseImage(ddljson, "small_image", &result.small_image);
176
177 RespondToAllCallbacks(std::move(result));
178 }
179
180 bool DoodleFetcher::ParseImage(const base::DictionaryValue* image_parent,
181 const std::string& image_name,
182 DoodleImage* image) const {
183 DCHECK(image);
184 const base::DictionaryValue* image_dict = nullptr;
185 if (!(image && image_parent &&
186 image_parent->GetDictionary(image_name, &image_dict))) {
187 return false;
188 }
189 std::string url;
190 image_dict->GetString("url", &url);
191 image->url = base_url_.Resolve(url);
192 image_dict->GetString("background_color", &image->background_color);
193 image_dict->GetInteger("height", &image->height);
194 image_dict->GetInteger("width", &image->width);
195 image_dict->GetBoolean("is_animated_gif", &image->is_animated_gif);
196 image_dict->GetBoolean("is_cta", &image->is_cta);
197 return true;
198 }
199
200 void DoodleFetcher::ParseBaseInformation(const base::DictionaryValue* ddljson,
201 DoodleConfig* config) const {
202 ParseRelativeUrl(ddljson, "search_url", &config->search_url);
203 ParseRelativeUrl(ddljson, "target_url", &config->target_url);
204 ParseRelativeUrl(ddljson, "fullpage_interactive_url",
205 &config->fullpage_interactive_url);
206
207 config->doodle_type = ParseDoodleType(ddljson);
208 ddljson->GetString("alt_text", &config->alt_text);
209
210 // TODO(fhorschig): Inject TickClock and test that.
211 // The JSON doesn't garantuee the number to fit into an int.
212 double ttl;
213 ddljson->GetDouble("time_to_live_ms", &ttl);
214 config->expiry_date = clock_->Now() + base::TimeDelta::FromMillisecondsD(ttl);
215 }
216
217 void DoodleFetcher::ParseRelativeUrl(const base::DictionaryValue* dict_value,
218 const std::string& key,
219 GURL* url) const {
220 std::string str_url;
221 dict_value->GetString(key, &str_url);
222 if (str_url.empty()) {
223 *url = GURL();
224 } else {
225 *url = base_url_.Resolve(str_url);
226 }
227 }
228
229 void DoodleFetcher::RespondToAllCallbacks(const DoodleConfig& response) {
230 callback_lock_.Acquire();
231 while (!callbacks_.empty()) {
232 std::move(callbacks_.front()).Run(response);
233 callbacks_.pop_front();
234 }
235 callback_lock_.Release();
236 }
237
238 } // namespace doodle
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698