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

Side by Side Diff: chrome/browser/android/ntp/popular_sites.cc

Issue 1957313003: Remove PopularSites' dependencies on //chrome/.... (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Rebase Created 4 years, 7 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
1 // Copyright 2015 The Chromium Authors. All rights reserved. 1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/android/ntp/popular_sites.h" 5 #include "chrome/browser/android/ntp/popular_sites.h"
6 6
7 #include <stddef.h> 7 #include <stddef.h>
8 8
9 #include "base/bind.h" 9 #include "base/bind.h"
10 #include "base/command_line.h" 10 #include "base/command_line.h"
11 #include "base/files/file_path.h" 11 #include "base/files/file_path.h"
12 #include "base/files/file_util.h" 12 #include "base/files/file_util.h"
13 #include "base/json/json_reader.h" 13 #include "base/json/json_reader.h"
14 #include "base/path_service.h"
15 #include "base/strings/string_util.h" 14 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h" 15 #include "base/strings/stringprintf.h"
17 #include "base/task_runner_util.h" 16 #include "base/task_runner_util.h"
18 #include "base/time/time.h" 17 #include "base/time/time.h"
19 #include "base/values.h" 18 #include "base/values.h"
20 #include "chrome/common/chrome_paths.h"
21 #include "components/google/core/browser/google_util.h" 19 #include "components/google/core/browser/google_util.h"
22 #include "components/ntp_tiles/pref_names.h" 20 #include "components/ntp_tiles/pref_names.h"
23 #include "components/ntp_tiles/switches.h" 21 #include "components/ntp_tiles/switches.h"
24 #include "components/pref_registry/pref_registry_syncable.h" 22 #include "components/pref_registry/pref_registry_syncable.h"
25 #include "components/prefs/pref_service.h" 23 #include "components/prefs/pref_service.h"
24 #include "components/safe_json/json_sanitizer.h"
26 #include "components/search_engines/search_engine_type.h" 25 #include "components/search_engines/search_engine_type.h"
27 #include "components/search_engines/template_url_prepopulate_data.h" 26 #include "components/search_engines/template_url_prepopulate_data.h"
28 #include "components/search_engines/template_url_service.h" 27 #include "components/search_engines/template_url_service.h"
29 #include "components/variations/service/variations_service.h" 28 #include "components/variations/service/variations_service.h"
30 #include "content/public/browser/browser_thread.h" 29 #include "content/public/browser/browser_thread.h"
30 #include "net/base/load_flags.h"
31 #include "net/http/http_status_code.h"
31 32
32 using content::BrowserThread; 33 using content::BrowserThread;
34 using net::URLFetcher;
33 using variations::VariationsService; 35 using variations::VariationsService;
34 36
35 namespace { 37 namespace {
36 38
37 const char kPopularSitesURLFormat[] = 39 const char kPopularSitesURLFormat[] =
38 "https://www.gstatic.com/chrome/ntp/suggested_sites_%s_%s.json"; 40 "https://www.gstatic.com/chrome/ntp/suggested_sites_%s_%s.json";
39 const char kPopularSitesDefaultCountryCode[] = "DEFAULT"; 41 const char kPopularSitesDefaultCountryCode[] = "DEFAULT";
40 const char kPopularSitesDefaultVersion[] = "5"; 42 const char kPopularSitesDefaultVersion[] = "5";
41 const char kPopularSitesLocalFilename[] = "suggested_sites.json"; 43 const char kPopularSitesLocalFilename[] = "suggested_sites.json";
42 const int kPopularSitesRedownloadIntervalHours = 24; 44 const int kPopularSitesRedownloadIntervalHours = 24;
(...skipping 73 matching lines...) Expand 10 before | Expand all | Expand 10 after
116 118
117 if (version.empty()) 119 if (version.empty())
118 version = variation_param_version; 120 version = variation_param_version;
119 121
120 if (version.empty()) 122 if (version.empty())
121 version = kPopularSitesDefaultVersion; 123 version = kPopularSitesDefaultVersion;
122 124
123 return version; 125 return version;
124 } 126 }
125 127
126 base::FilePath GetPopularSitesPath() { 128 std::unique_ptr<std::vector<PopularSites::Site>> ParseJson(
127 base::FilePath dir; 129 const std::string& json) {
128 PathService::Get(chrome::DIR_USER_DATA, &dir);
129 return dir.AppendASCII(kPopularSitesLocalFilename);
130 }
131
132 std::unique_ptr<std::vector<PopularSites::Site>> ReadAndParseJsonFile(
133 const base::FilePath& path) {
134 std::string json;
135 if (!base::ReadFileToString(path, &json)) {
136 DLOG(WARNING) << "Failed reading file";
137 return nullptr;
138 }
139
140 std::unique_ptr<base::Value> value = 130 std::unique_ptr<base::Value> value =
141 base::JSONReader::Read(json, base::JSON_ALLOW_TRAILING_COMMAS); 131 base::JSONReader::Read(json, base::JSON_ALLOW_TRAILING_COMMAS);
142 base::ListValue* list; 132 base::ListValue* list;
143 if (!value || !value->GetAsList(&list)) { 133 if (!value || !value->GetAsList(&list)) {
144 DLOG(WARNING) << "Failed parsing json"; 134 DLOG(WARNING) << "Failed parsing json";
145 return nullptr; 135 return nullptr;
146 } 136 }
147 137
148 std::unique_ptr<std::vector<PopularSites::Site>> sites( 138 std::unique_ptr<std::vector<PopularSites::Site>> sites(
149 new std::vector<PopularSites::Site>); 139 new std::vector<PopularSites::Site>);
(...skipping 13 matching lines...) Expand all
163 item->GetString("large_icon_url", &large_icon_url); 153 item->GetString("large_icon_url", &large_icon_url);
164 154
165 sites->push_back(PopularSites::Site(title, GURL(url), GURL(favicon_url), 155 sites->push_back(PopularSites::Site(title, GURL(url), GURL(favicon_url),
166 GURL(large_icon_url), 156 GURL(large_icon_url),
167 GURL(thumbnail_url))); 157 GURL(thumbnail_url)));
168 } 158 }
169 159
170 return sites; 160 return sites;
171 } 161 }
172 162
163 // Write |data| to a temporary file, then move it to |path|, thereby ensuring
164 // that a partial file cannot be written.
165 //
166 // TODO(sfiera): is there some helper for this somewhere?
167 bool WriteStringToFileAtomic(const std::string& data,
168 const base::FilePath& path) {
169 base::FilePath temporary_path;
170 return base::CreateTemporaryFile(&temporary_path) &&
171 base::WriteFile(temporary_path, data.data(), data.size()) &&
172 base::Move(temporary_path, path);
173 }
174
175 // Run |call| on the thread pool for blocking file operations, then call |done|
176 // with its result on the original thread.
177 template <typename T>
178 void RunBlockingTaskAndReply(const tracked_objects::Location& from_here,
179 const base::Callback<T()>& call,
180 const base::Callback<void(T)>& done) {
181 base::PostTaskAndReplyWithResult(
182 BrowserThread::GetBlockingPool()
183 ->GetTaskRunnerWithShutdownBehavior(
184 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN)
185 .get(),
186 from_here, call, done);
187 }
188
173 } // namespace 189 } // namespace
174 190
175 PopularSites::Site::Site(const base::string16& title, 191 PopularSites::Site::Site(const base::string16& title,
176 const GURL& url, 192 const GURL& url,
177 const GURL& favicon_url, 193 const GURL& favicon_url,
178 const GURL& large_icon_url, 194 const GURL& large_icon_url,
179 const GURL& thumbnail_url) 195 const GURL& thumbnail_url)
180 : title(title), 196 : title(title),
181 url(url), 197 url(url),
182 favicon_url(favicon_url), 198 favicon_url(favicon_url),
183 large_icon_url(large_icon_url), 199 large_icon_url(large_icon_url),
184 thumbnail_url(thumbnail_url) {} 200 thumbnail_url(thumbnail_url) {}
185 201
186 PopularSites::Site::Site(const Site& other) = default; 202 PopularSites::Site::Site(const Site& other) = default;
187 203
188 PopularSites::Site::~Site() {} 204 PopularSites::Site::~Site() {}
189 205
190 PopularSites::PopularSites(PrefService* prefs, 206 PopularSites::PopularSites(PrefService* prefs,
191 const TemplateURLService* template_url_service, 207 const TemplateURLService* template_url_service,
192 VariationsService* variations_service, 208 VariationsService* variations_service,
193 net::URLRequestContextGetter* download_context, 209 net::URLRequestContextGetter* download_context,
210 const base::FilePath& directory,
194 const std::string& variation_param_country, 211 const std::string& variation_param_country,
195 const std::string& variation_param_version, 212 const std::string& variation_param_version,
196 bool force_download, 213 bool force_download,
197 const FinishedCallback& callback) 214 const FinishedCallback& callback)
198 : PopularSites(prefs, 215 : PopularSites(prefs,
199 template_url_service, 216 template_url_service,
200 download_context, 217 download_context,
218 directory,
201 GetCountryToUse(prefs, 219 GetCountryToUse(prefs,
202 template_url_service, 220 template_url_service,
203 variations_service, 221 variations_service,
204 variation_param_country), 222 variation_param_country),
205 GetVersionToUse(prefs, variation_param_version), 223 GetVersionToUse(prefs, variation_param_version),
206 GURL(), 224 GURL(),
207 force_download, 225 force_download,
208 callback) {} 226 callback) {}
209 227
210 PopularSites::PopularSites(PrefService* prefs, 228 PopularSites::PopularSites(PrefService* prefs,
211 const TemplateURLService* template_url_service, 229 const TemplateURLService* template_url_service,
212 net::URLRequestContextGetter* download_context, 230 net::URLRequestContextGetter* download_context,
231 const base::FilePath& directory,
213 const GURL& url, 232 const GURL& url,
214 const FinishedCallback& callback) 233 const FinishedCallback& callback)
215 : PopularSites(prefs, 234 : PopularSites(prefs,
216 template_url_service, 235 template_url_service,
217 download_context, 236 download_context,
237 directory,
218 std::string(), 238 std::string(),
219 std::string(), 239 std::string(),
220 url, 240 url,
221 true, 241 true,
222 callback) {} 242 callback) {}
223 243
224 PopularSites::~PopularSites() {} 244 PopularSites::~PopularSites() {}
225 245
226 std::string PopularSites::GetCountry() const { 246 std::string PopularSites::GetCountry() const {
227 return prefs_->GetString(kPopularSitesCountryPref); 247 return prefs_->GetString(kPopularSitesCountryPref);
(...skipping 12 matching lines...) Expand all
240 std::string()); 260 std::string());
241 261
242 user_prefs->RegisterInt64Pref(kPopularSitesLastDownloadPref, 0); 262 user_prefs->RegisterInt64Pref(kPopularSitesLastDownloadPref, 0);
243 user_prefs->RegisterStringPref(kPopularSitesCountryPref, std::string()); 263 user_prefs->RegisterStringPref(kPopularSitesCountryPref, std::string());
244 user_prefs->RegisterStringPref(kPopularSitesVersionPref, std::string()); 264 user_prefs->RegisterStringPref(kPopularSitesVersionPref, std::string());
245 } 265 }
246 266
247 PopularSites::PopularSites(PrefService* prefs, 267 PopularSites::PopularSites(PrefService* prefs,
248 const TemplateURLService* template_url_service, 268 const TemplateURLService* template_url_service,
249 net::URLRequestContextGetter* download_context, 269 net::URLRequestContextGetter* download_context,
270 const base::FilePath& directory,
250 const std::string& country, 271 const std::string& country,
251 const std::string& version, 272 const std::string& version,
252 const GURL& override_url, 273 const GURL& override_url,
253 bool force_download, 274 bool force_download,
254 const FinishedCallback& callback) 275 const FinishedCallback& callback)
255 : callback_(callback), 276 : callback_(callback),
277 is_fallback_(false),
256 pending_country_(country), 278 pending_country_(country),
257 pending_version_(version), 279 pending_version_(version),
258 local_path_(GetPopularSitesPath()), 280 local_path_(directory.empty()
281 ? base::FilePath()
282 : directory.AppendASCII(kPopularSitesLocalFilename)),
259 prefs_(prefs), 283 prefs_(prefs),
260 template_url_service_(template_url_service), 284 template_url_service_(template_url_service),
261 download_context_(download_context), 285 download_context_(download_context),
262 weak_ptr_factory_(this) { 286 weak_ptr_factory_(this) {
287 DCHECK_CURRENTLY_ON(BrowserThread::UI);
263 const base::Time last_download_time = base::Time::FromInternalValue( 288 const base::Time last_download_time = base::Time::FromInternalValue(
264 prefs_->GetInt64(kPopularSitesLastDownloadPref)); 289 prefs_->GetInt64(kPopularSitesLastDownloadPref));
265 const base::TimeDelta time_since_last_download = 290 const base::TimeDelta time_since_last_download =
266 base::Time::Now() - last_download_time; 291 base::Time::Now() - last_download_time;
267 const base::TimeDelta redownload_interval = 292 const base::TimeDelta redownload_interval =
268 base::TimeDelta::FromHours(kPopularSitesRedownloadIntervalHours); 293 base::TimeDelta::FromHours(kPopularSitesRedownloadIntervalHours);
269 const bool download_time_is_future = base::Time::Now() < last_download_time; 294 const bool download_time_is_future = base::Time::Now() < last_download_time;
270 const bool country_changed = GetCountry() != pending_country_; 295 const bool country_changed = GetCountry() != pending_country_;
271 const bool version_changed = GetVersion() != pending_version_; 296 const bool version_changed = GetVersion() != pending_version_;
272 297
273 const bool should_redownload_if_exists = 298 const GURL url =
274 force_download || download_time_is_future || 299 override_url.is_valid() ? override_url : GetPopularSitesURL();
300
301 // No valid path to save to. Immediately post failure.
302 if (local_path_.empty()) {
303 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
304 base::Bind(callback_, false));
305 return;
306 }
307
308 // Download forced, or we need to download a new file.
309 if (force_download || download_time_is_future ||
275 (time_since_last_download > redownload_interval) || country_changed || 310 (time_since_last_download > redownload_interval) || country_changed ||
276 version_changed; 311 version_changed) {
312 FetchPopularSites(url);
313 return;
314 }
277 315
278 FetchPopularSites( 316 std::unique_ptr<std::string> file_data(new std::string);
279 override_url.is_valid() ? override_url : GetPopularSitesURL(), 317 std::string* file_data_ptr = file_data.get();
280 should_redownload_if_exists, false /* is_fallback */); 318 RunBlockingTaskAndReply(
319 FROM_HERE,
320 base::Bind(&base::ReadFileToString, local_path_, file_data_ptr),
321 base::Bind(&PopularSites::OnReadFileDone, weak_ptr_factory_.GetWeakPtr(),
322 url, base::Passed(std::move(file_data))));
Marc Treib 2016/05/11 10:20:29 There's also base::Owned which takes ownership of
sfiera 2016/05/11 14:23:53 I like the current way because a reader of OnReadF
Marc Treib 2016/05/11 14:47:25 Acknowledged.
281 } 323 }
282 324
283 GURL PopularSites::GetPopularSitesURL() const { 325 GURL PopularSites::GetPopularSitesURL() const {
284 return GURL(base::StringPrintf(kPopularSitesURLFormat, 326 return GURL(base::StringPrintf(kPopularSitesURLFormat,
285 pending_country_.c_str(), 327 pending_country_.c_str(),
286 pending_version_.c_str())); 328 pending_version_.c_str()));
287 } 329 }
288 330
289 void PopularSites::FetchPopularSites(const GURL& url, 331 void PopularSites::FetchPopularSites(const GURL& url) {
290 bool force_download, 332 fetcher_ = URLFetcher::Create(url, URLFetcher::GET, this);
291 bool is_fallback) { 333 fetcher_->SetRequestContext(download_context_);
292 downloader_.reset(new FileDownloader( 334 fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
293 url, local_path_, force_download, download_context_, 335 net::LOAD_DO_NOT_SAVE_COOKIES);
294 base::Bind(&PopularSites::OnDownloadDone, base::Unretained(this), 336 fetcher_->SetAutomaticallyRetryOnNetworkChanges(1);
295 is_fallback))); 337 fetcher_->Start();
296 } 338 }
297 339
298 void PopularSites::OnDownloadDone(bool is_fallback, 340 void PopularSites::OnDownloadFailed() {
299 FileDownloader::Result result) { 341 if (!is_fallback_) {
300 downloader_.reset(); 342 DLOG(WARNING) << "Download country site list failed";
301 switch (result) { 343 is_fallback_ = true;
302 case FileDownloader::DOWNLOADED: 344 pending_country_ = kPopularSitesDefaultCountryCode;
303 prefs_->SetInt64(kPopularSitesLastDownloadPref, 345 pending_version_ = kPopularSitesDefaultVersion;
304 base::Time::Now().ToInternalValue()); 346 // It is fine to force the download as Fallback is only triggered after
305 prefs_->SetString(kPopularSitesCountryPref, pending_country_); 347 // a failed download.
Marc Treib 2016/05/11 10:20:29 This comment is kinda obsolete now.
sfiera 2016/05/11 14:23:53 Done.
306 prefs_->SetString(kPopularSitesVersionPref, pending_version_); 348 FetchPopularSites(GetPopularSitesURL());
307 ParseSiteList(local_path_); 349 } else {
308 break; 350 DLOG(WARNING) << "Download fallback site list failed";
309 case FileDownloader::EXISTS: 351 callback_.Run(false);
310 ParseSiteList(local_path_);
311 break;
312 case FileDownloader::FAILED:
313 if (!is_fallback) {
314 DLOG(WARNING) << "Download country site list failed";
315 pending_country_ = kPopularSitesDefaultCountryCode;
316 pending_version_ = kPopularSitesDefaultVersion;
317 // It is fine to force the download as Fallback is only triggered after
318 // a failed download.
319 FetchPopularSites(GetPopularSitesURL(), true /* force_download */,
320 true /* is_fallback */);
321 } else {
322 DLOG(WARNING) << "Download fallback site list failed";
323 callback_.Run(false);
324 }
325 break;
326 } 352 }
327 } 353 }
328 354
329 void PopularSites::ParseSiteList(const base::FilePath& path) { 355 void PopularSites::OnReadFileDone(const GURL& url,
330 base::PostTaskAndReplyWithResult( 356 std::unique_ptr<std::string> data,
331 BrowserThread::GetBlockingPool() 357 bool success) {
332 ->GetTaskRunnerWithShutdownBehavior( 358 if (success) {
333 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN) 359 ParseSiteList(*data);
334 .get(), 360 } else {
335 FROM_HERE, base::Bind(&ReadAndParseJsonFile, path), 361 FetchPopularSites(url);
Marc Treib 2016/05/11 10:20:29 Add a comment? I guess this usually means the file
sfiera 2016/05/11 14:23:53 Done.
362 }
363 }
364
365 void PopularSites::OnURLFetchComplete(const net::URLFetcher* source) {
366 DCHECK_EQ(fetcher_.get(), source);
367 fetcher_.reset();
Marc Treib 2016/05/11 10:20:29 I think this may be why stuff fails: This deletes
sfiera 2016/05/11 11:06:02 Oh yeah, obviously. Now I wonder why it doesn't fa
Marc Treib 2016/05/11 11:35:28 I think there's a few more, maybe "is_msan" or som
sfiera 2016/05/11 14:23:53 Acknowledged.
368
369 std::string sketchy_json;
370 if (!(source->GetStatus().is_success() &&
371 source->GetResponseCode() == net::HTTP_OK &&
372 source->GetResponseAsString(&sketchy_json))) {
373 OnDownloadFailed();
374 return;
375 }
376
377 safe_json::JsonSanitizer::Sanitize(
378 sketchy_json, base::Bind(&PopularSites::OnJsonSanitized,
379 weak_ptr_factory_.GetWeakPtr()),
380 base::Bind(&PopularSites::OnJsonSanitizationFailed,
381 weak_ptr_factory_.GetWeakPtr()));
382 }
383
384 void PopularSites::OnJsonSanitized(const std::string& valid_minified_json) {
385 RunBlockingTaskAndReply(
386 FROM_HERE,
387 base::Bind(&WriteStringToFileAtomic, valid_minified_json, local_path_),
388 base::Bind(&PopularSites::OnFileWriteDone, weak_ptr_factory_.GetWeakPtr(),
389 valid_minified_json));
390 }
391
392 void PopularSites::OnJsonSanitizationFailed(const std::string& error_message) {
393 DLOG(WARNING) << "JSON sanitization failed: " << error_message;
394 OnDownloadFailed();
395 }
396
397 void PopularSites::OnFileWriteDone(const std::string& json, bool success) {
398 if (success) {
399 prefs_->SetInt64(kPopularSitesLastDownloadPref,
400 base::Time::Now().ToInternalValue());
401 prefs_->SetString(kPopularSitesCountryPref, pending_country_);
402 prefs_->SetString(kPopularSitesVersionPref, pending_version_);
403 ParseSiteList(json);
404 } else {
405 DLOG(WARNING) << "Could not write file to "
406 << local_path_.LossyDisplayName();
407 OnDownloadFailed();
408 }
409 }
410
411 void PopularSites::ParseSiteList(const std::string& json) {
412 RunBlockingTaskAndReply(
413 FROM_HERE, base::Bind(&ParseJson, json),
336 base::Bind(&PopularSites::OnJsonParsed, weak_ptr_factory_.GetWeakPtr())); 414 base::Bind(&PopularSites::OnJsonParsed, weak_ptr_factory_.GetWeakPtr()));
337 } 415 }
338 416
339 void PopularSites::OnJsonParsed(std::unique_ptr<std::vector<Site>> sites) { 417 void PopularSites::OnJsonParsed(std::unique_ptr<std::vector<Site>> sites) {
340 if (sites) 418 if (sites)
341 sites_.swap(*sites); 419 sites_.swap(*sites);
342 else 420 else
343 sites_.clear(); 421 sites_.clear();
344 callback_.Run(!!sites); 422 callback_.Run(!!sites);
345 } 423 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698