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

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

Powered by Google App Engine
This is Rietveld 408576698