1 // Copyright 2013 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.
5 #include "chrome/browser/android/popular_sites.h"
8 #include "base/files/file_path.h"
9 #include "base/files/file_util.h"
10 #include "base/json/json_reader.h"
11 #include "base/path_service.h"
12 #include "base/task_runner_util.h"
13 #include "base/values.h"
14 #include "chrome/browser/net/file_downloader.h"
15 #include "chrome/common/chrome_paths.h"
16 #include "content/public/browser/browser_thread.h"
18 using content::BrowserThread
;
22 const char kPopularSitesFilename
[] = "ntp-popular-sites.json";
23 const char kPopularSitesURL
[] =
24 "https://www.gstatic.com/chrome/ntp/suggested_sites_IN_0.json";
26 base::FilePath
GetPopularSitesPath() {
28 PathService::Get(chrome::DIR_USER_DATA
, &dir
);
29 return dir
.AppendASCII(kPopularSitesFilename
);
32 scoped_ptr
<std::vector
<PopularSites::Site
>> ReadAndParseJsonFile(
33 const base::FilePath
& path
) {
35 if (!base::ReadFileToString(path
, &json
)) {
36 DLOG(WARNING
) << "Failed reading file";
40 scoped_ptr
<base::Value
> value
=
41 base::JSONReader::Read(json
, base::JSON_ALLOW_TRAILING_COMMAS
);
42 base::ListValue
* list
;
43 if (!value
|| !value
->GetAsList(&list
)) {
44 DLOG(WARNING
) << "Failed parsing json";
48 scoped_ptr
<std::vector
<PopularSites::Site
>> sites(
49 new std::vector
<PopularSites::Site
>);
50 for (size_t i
= 0; i
< list
->GetSize(); i
++) {
51 base::DictionaryValue
* item
;
52 if (!list
->GetDictionary(i
, &item
))
56 if (!item
->GetString("title", &title
) || !item
->GetString("url", &url
))
58 sites
->push_back(PopularSites::Site(title
, GURL(url
)));
66 PopularSites::Site::Site(const base::string16
& title
, const GURL
& url
)
67 : title(title
), url(url
) {}
69 PopularSites::PopularSites(net::URLRequestContextGetter
* request_context
,
70 const FinishedCallback
& callback
)
71 : callback_(callback
), weak_ptr_factory_(this) {
72 base::FilePath path
= GetPopularSitesPath();
73 downloader_
.reset(new FileDownloader(
74 GURL(kPopularSitesURL
), path
, request_context
,
75 base::Bind(&PopularSites::OnDownloadDone
, base::Unretained(this), path
)));
78 PopularSites::~PopularSites() {}
80 void PopularSites::OnDownloadDone(const base::FilePath
& path
, bool success
) {
82 base::PostTaskAndReplyWithResult(
83 BrowserThread::GetBlockingPool()->GetTaskRunnerWithShutdownBehavior(
84 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN
).get(),
86 base::Bind(&ReadAndParseJsonFile
, path
),
87 base::Bind(&PopularSites::OnJsonParsed
,
88 weak_ptr_factory_
.GetWeakPtr()));
90 DLOG(WARNING
) << "Download failed";
97 void PopularSites::OnJsonParsed(scoped_ptr
<std::vector
<Site
>> sites
) {
102 callback_
.Run(!!sites
);