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

Side by Side Diff: components/ntp_snippets/ntp_snippets_fetcher.cc

Issue 1677073002: Fetch snippets from ChromeReader and show them on the NTP (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: CR comments, modified iOS NTPSnippetServiceFactory Created 4 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 2016 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 #include "components/ntp_snippets/ntp_snippets_fetcher.h"
5
6 #include "base/files/file_path.h"
7 #include "base/files/file_util.h"
8 #include "base/path_service.h"
9 #include "base/strings/stringprintf.h"
10 #include "base/task_runner_util.h"
11 #include "components/signin/core/browser/profile_oauth2_token_service.h"
12 #include "components/signin/core/browser/signin_manager.h"
13 #include "components/signin/core/browser/signin_tracker.h"
14 #include "net/base/load_flags.h"
15 #include "net/http/http_request_headers.h"
16 #include "net/http/http_response_headers.h"
17 #include "net/http/http_status_code.h"
18 #include "net/url_request/url_fetcher.h"
19
20 using net::URLFetcher;
21 using net::URLRequestContextGetter;
22 using net::HttpRequestHeaders;
23 using net::URLRequestStatus;
24
25 namespace ntp_snippets {
26
27 const char kSnippetSuggestionsFilename[] = "ntp_snippets.json";
28 const char kApiScope[] = "https://www.googleapis.com/auth/webhistory";
29 const char kContentSnippetsServer[] =
30 "https://chromereader-pa.googleapis.com/v1/fetch";
31 const char kAuthorizationRequestHeaderFormat[] = "Bearer %s";
32
33 const char kUnpersonalizedRequestParameters[] =
34 "{ \"response_detail_level\": \"FULL_DEBUG\", \"advanced_options\": { "
35 "\"local_scoring_params\": {\"content_params\" : { "
36 "\"only_return_personalized_results\": false } }, "
37 "\"global_scoring_params\": { \"num_to_return\": 10 } } }";
38
39 base::FilePath GetSnippetsSuggestionsPath() {
40 base::FilePath dir;
41 #if defined(OS_ANDROID)
42 DCHECK(PathService::Get(base::DIR_ANDROID_APP_DATA, &dir));
43 return dir.AppendASCII(kSnippetSuggestionsFilename);
44 #else
45 NOTIMPLEMENTED();
noyau (Ping after 24h) 2016/02/17 20:19:47 Use PathService::Get(ios::FILE_LOCAL_STATE, &dir))
May 2016/02/19 14:49:01 Done.
46 return dir;
47 #endif
48 }
49
50 NTPSnippetsFetcher::NTPSnippetsFetcher(
51 scoped_refptr<base::SequencedTaskRunner> file_task_runner,
52 SigninManager* signin_manager,
53 OAuth2TokenService* token_service,
54 URLRequestContextGetter* url_request_context_getter)
55 : OAuth2TokenService::Consumer("NTP_snippets"),
56 file_task_runner_(file_task_runner),
57 url_request_context_getter_(url_request_context_getter),
58 signin_manager_(signin_manager),
59 token_service_(token_service),
60 waiting_for_refresh_token_(false),
61 weak_ptr_factory_(this) {}
62
63 NTPSnippetsFetcher::~NTPSnippetsFetcher() {
64 if (waiting_for_refresh_token_)
65 token_service_->RemoveObserver(this);
66 }
67
68 scoped_ptr<NTPSnippetsFetcher::SnippetsAvailableCallbackList::Subscription>
69 NTPSnippetsFetcher::AddCallback(const SnippetsAvailableCallback& callback) {
70 return callback_list_.Add(callback);
71 }
72
73 void NTPSnippetsFetcher::FetchSnippets(bool overwrite) {
74 if (overwrite) {
75 StartFetch();
76 } else {
77 base::PostTaskAndReplyWithResult(
78 file_task_runner_.get(), FROM_HERE,
79 base::Bind(&base::PathExists, GetSnippetsSuggestionsPath()),
80 base::Bind(&NTPSnippetsFetcher::OnFileExistsCheckDone,
81 weak_ptr_factory_.GetWeakPtr()));
82 }
83 }
84
85 void NTPSnippetsFetcher::OnFileExistsCheckDone(bool exists) {
86 if (exists) {
87 NotifyObservers();
88 } else {
89 StartFetch();
90 }
91 }
92
93 void NTPSnippetsFetcher::StartFetch() {
94 if (signin_manager_->IsAuthenticated()) {
95 StartTokenRequest();
96 } else {
97 if (!waiting_for_refresh_token_) {
98 // Wait until we get a refresh token.
99 waiting_for_refresh_token_ = true;
100 token_service_->AddObserver(this);
101 }
102 }
103 }
104
105 void NTPSnippetsFetcher::StartTokenRequest() {
106 OAuth2TokenService::ScopeSet scopes;
107 scopes.insert(kApiScope);
108 oauth_request_ = token_service_->StartRequest(
109 signin_manager_->GetAuthenticatedAccountId(), scopes, this);
110 }
111
112 void NTPSnippetsFetcher::NotifyObservers() {
113 callback_list_.Notify(GetSnippetsSuggestionsPath());
114 }
115
116 ////////////////////////////////////////////////////////////////////////////////
117 // OAuth2TokenService::Consumer overrides
118 void NTPSnippetsFetcher::OnGetTokenSuccess(
119 const OAuth2TokenService::Request* request,
120 const std::string& access_token,
121 const base::Time& expiration_time) {
122 oauth_request_.reset();
123 url_fetcher_ =
124 URLFetcher::Create(GURL(kContentSnippetsServer), URLFetcher::POST, this);
125 url_fetcher_->SetRequestContext(url_request_context_getter_);
126 url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
127 net::LOAD_DO_NOT_SAVE_COOKIES);
128 HttpRequestHeaders headers;
129 headers.SetHeader("Authorization",
130 base::StringPrintf(kAuthorizationRequestHeaderFormat,
131 access_token.c_str()));
132 headers.SetHeader("Content-Type", "application/json; charset=UTF-8");
133 url_fetcher_->SetExtraRequestHeaders(headers.ToString());
134 url_fetcher_->SetUploadData("application/json",
135 kUnpersonalizedRequestParameters);
136 url_fetcher_->SaveResponseToTemporaryFile(file_task_runner_.get());
137 url_fetcher_->Start();
138 }
139
140 void NTPSnippetsFetcher::OnGetTokenFailure(
141 const OAuth2TokenService::Request* request,
142 const GoogleServiceAuthError& error) {
143 oauth_request_.reset();
144 DLOG(ERROR) << "Unable to get token: " << error.ToString();
145 }
146
147 ////////////////////////////////////////////////////////////////////////////////
148 // OAuth2TokenService::Observer overrides
149 void NTPSnippetsFetcher::OnRefreshTokenAvailable(
150 const std::string& account_id) {
151 token_service_->RemoveObserver(this);
152 waiting_for_refresh_token_ = false;
153 StartTokenRequest();
154 }
155
156 ////////////////////////////////////////////////////////////////////////////////
157 // URLFetcherDelegate overrides
158 void NTPSnippetsFetcher::OnURLFetchComplete(const URLFetcher* source) {
159 DCHECK_EQ(url_fetcher_.get(), source);
160
161 const URLRequestStatus& status = source->GetStatus();
162 if (!status.is_success()) {
163 DLOG(WARNING) << "URLRequestStatus error " << status.error()
164 << " while trying to download " << source->GetURL().spec();
165 return;
166 }
167
168 int response_code = source->GetResponseCode();
169 if (response_code != net::HTTP_OK) {
170 DLOG(WARNING) << "HTTP error " << response_code
171 << " while trying to download " << source->GetURL().spec();
172 return;
173 }
174
175 base::FilePath response_path;
176 source->GetResponseAsFilePath(false, &response_path);
177
178 base::PostTaskAndReplyWithResult(
179 file_task_runner_.get(), FROM_HERE,
180 base::Bind(&base::Move, response_path, GetSnippetsSuggestionsPath()),
181 base::Bind(&NTPSnippetsFetcher::OnFileMoveDone,
182 weak_ptr_factory_.GetWeakPtr()));
183 }
184
185 void NTPSnippetsFetcher::OnFileMoveDone(bool success) {
186 if (!success) {
187 DLOG(WARNING) << "Could not move file to "
188 << GetSnippetsSuggestionsPath().LossyDisplayName();
189 return;
190 }
191
192 NotifyObservers();
193 }
194
195 } // namespace ntp_snippets
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698