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

Side by Side Diff: chrome/browser/interests/interests_fetcher.cc

Issue 1317513004: Add InterestsFetcher which retrieves a user's interests from the server. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Improve handling of HTTP errors. Created 5 years, 2 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 2015 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 "chrome/browser/interests/interests_fetcher.h"
6
7 #include "base/command_line.h"
8 #include "base/json/json_reader.h"
9 #include "base/logging.h"
10 #include "base/strings/stringprintf.h"
11 #include "base/values.h"
12 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
13 #include "chrome/browser/signin/signin_manager_factory.h"
14 #include "chrome/common/chrome_switches.h"
15 #include "components/signin/core/browser/profile_oauth2_token_service.h"
16 #include "net/base/load_flags.h"
17 #include "net/http/http_status_code.h"
18 #include "net/url_request/url_fetcher.h"
19 #include "net/url_request/url_request_context_getter.h"
20 #include "net/url_request/url_request_status.h"
21
22 using net::URLFetcher;
jochen (gone - plz use gerrit) 2015/09/30 09:23:09 don't use using, always use the full name
Bernhard Bauer 2015/09/30 09:38:57 (Just for the sake of completeness: the style guid
tache 2015/09/30 17:32:02 Done.
23 using net::URLFetcherDelegate;
24 using net::URLRequestContextGetter;
25 using net::URLRequestStatus;
26
27 namespace {
28
29 const int kNumRetries = 1;
30 const char kIdInterests[] = "interests";
31 const char kIdInterestName[] = "name";
32 const char kIdInterestImageUrl[] = "imageUrl";
33 const char kIdInterestRelevance[] = "relevance";
34
35 const char kInterestsUrl[] =
36 "https://www-googleapis-stagin.sandbox.google.com/chromenow/contextdemo/"
37 "interests/";
Bernhard Bauer 2015/09/30 08:14:08 Remove the URL now?
jochen (gone - plz use gerrit) 2015/09/30 09:23:09 why not just put the URL to use there?
Bernhard Bauer 2015/09/30 09:38:57 It's an internal URL that has no place in the upst
tache 2015/09/30 17:32:02 Removed the URL.
38 const char kApiScope[] = "https://www.googleapis.com/auth/googlenow";
39
40 const char kAuthorizationHeaderFormat[] = "Authorization: Bearer %s";
41
42 std::vector<InterestsFetcher::Interest> EmptyResponse() {
43 return std::vector<InterestsFetcher::Interest>();
44 }
45
46 GURL GetInterestsURL() {
47 const base::CommandLine* command_line =
48 base::CommandLine::ForCurrentProcess();
49 GURL interests_url(
50 command_line->GetSwitchValueASCII(switches::kInterestsURL));
51 if (interests_url.is_empty())
Bernhard Bauer 2015/09/30 08:14:08 This is a no-op -- The empty GURL() constructor co
tache 2015/09/30 17:32:02 Done.
52 interests_url = GURL();
jochen (gone - plz use gerrit) 2015/09/30 09:23:09 and return it here - GURL(kInterestsUrl)
tache 2015/09/30 17:32:02 kInterestsUrl was removed.
53 return interests_url;
54 }
55
56 } // namespace
57
58 InterestsFetcher::InterestsFetcher(
59 OAuth2TokenService* oauth2_token_service,
60 const std::string& account_id,
61 net::URLRequestContextGetter* url_request_context)
62 : OAuth2TokenService::Consumer("interests_fetcher"),
63 token_service_(oauth2_token_service),
64 account_id_(account_id),
65 url_request_context_(url_request_context),
66 access_token_expired_(false) {
67 }
68
69 // static
70 scoped_ptr<InterestsFetcher>
71 InterestsFetcher::CreateFromProfile(Profile* profile) {
72 ProfileOAuth2TokenService* token_service =
73 ProfileOAuth2TokenServiceFactory::GetForProfile(profile);
74
75 SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile);
76
77 return make_scoped_ptr(new InterestsFetcher(
78 token_service,
79 signin->GetAuthenticatedAccountId(),
80 profile->GetRequestContext()));
81 }
82
83 void InterestsFetcher::Start(
84 const InterestsFetcher::InterestsCallback& callback) {
85 DCHECK(callback_.is_null());
86 callback_ = callback;
87 StartOAuth2Request();
88 }
89
90 void InterestsFetcher::StartOAuth2Request(){
91 oauth_request_ =
92 token_service_->StartRequest(account_id_, GetApiScopes(), this);
93 }
94
95 void InterestsFetcher::OnGetTokenFailure(
96 const OAuth2TokenService::Request* request,
97 const GoogleServiceAuthError& error) {
98 DLOG(WARNING) << error.ToString();
99
100 callback_.Run(EmptyResponse());
101 }
102
103 void InterestsFetcher::OnGetTokenSuccess(
104 const OAuth2TokenService::Request* request,
105 const std::string& access_token,
106 const base::Time& expiration_time) {
107
108 access_token_ = access_token;
109 fetcher_ = CreateFetcher();
110
111 // Setup fetcher
112 fetcher_->SetRequestContext(url_request_context_);
113 fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
114 net::LOAD_DO_NOT_SAVE_COOKIES);
115 fetcher_->SetAutomaticallyRetryOnNetworkChanges(kNumRetries);
116
117 // Add oauth access token
118 fetcher_->AddExtraRequestHeader(
119 base::StringPrintf(kAuthorizationHeaderFormat, access_token_.c_str()));
120
121 fetcher_->Start();
122
123 }
124
125 scoped_ptr<URLFetcher> InterestsFetcher::CreateFetcher() {
126 return URLFetcher::Create(0, GetInterestsURL(), URLFetcher::GET, this);
127 }
128
129 void InterestsFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
130
131 const URLRequestStatus& status = source->GetStatus();
132 if (!status.is_success()) {
133 LOG(WARNING) << "Network error " << status.error();
134 callback_.Run(EmptyResponse());
135 return;
136 }
137
138 int response_code = source->GetResponseCode();
139 // If we get an authorization error, refresh token and retry once.
140 if (response_code == net::HTTP_UNAUTHORIZED && !access_token_expired_) {
141 access_token_expired_ = true;
142 token_service_->InvalidateAccessToken(account_id_, GetApiScopes(),
143 access_token_);
144 StartOAuth2Request();
145 return;
146 }
147
148 if (response_code != net::HTTP_OK) {
149 LOG(WARNING) << "HTTP error " << response_code;
150 callback_.Run(EmptyResponse());
151 return;
152 }
153
154 std::string response_body;
155 source->GetResponseAsString(&response_body);
156
157 callback_.Run(ExtractInterests(response_body));
158 }
159
160 std::vector<InterestsFetcher::Interest> InterestsFetcher::ExtractInterests(
161 const std::string& response) {
162 scoped_ptr<base::Value> value = base::JSONReader::Read(response);
163
164 const base::DictionaryValue* dict = nullptr;
165 if (!value || !value->GetAsDictionary(&dict)) {
166 DLOG(WARNING) << "ExtractInterests failed to parse global dictionary";
167 return EmptyResponse();
168 }
169
170 const base::ListValue* interests_list = nullptr;
171 std::vector<Interest> res;
172
173 if (!dict->GetList(kIdInterests, &interests_list)) {
174 DLOG(WARNING) << "ExtractInterests failed to parse interests list";
175 return EmptyResponse();
176 }
177
178 for (const base::Value* entry : *interests_list) {
179 const base::DictionaryValue* interest_dict = nullptr;
180 if (!entry->GetAsDictionary(&interest_dict)) {
181 DLOG(WARNING) << "ExtractInterests failed to parse interest dictionary";
182 return EmptyResponse();
183 }
184
185 std::string name;
186 if (!interest_dict->GetString(kIdInterestName, &name)) {
187 DLOG(WARNING) << "ExtractInterests failed to parse interest name";
188 return EmptyResponse();
189 }
190
191 std::string image_url;
192 if (!interest_dict->GetString(kIdInterestImageUrl, &image_url)) {
193 // image_url is allowed to be missing.
194 //
195 // However this is still logged as a warning, since, currently, the server
196 // should always provide an image_url.
197 DLOG(WARNING) << "ExtractInterests failed to parse interest image URL";
198 }
199
200 double relevance;
201 if (!interest_dict->GetDouble(kIdInterestRelevance, &relevance)) {
202 DLOG(WARNING) << "ExtractInterests failed to parse interest relevance";
203 return EmptyResponse();
204 }
205
206 res.push_back(Interest{name, GURL(image_url), relevance});
207 }
208
209 return res;
210 }
211
212 OAuth2TokenService::ScopeSet InterestsFetcher::GetApiScopes() {
213 OAuth2TokenService::ScopeSet scopes;
214 scopes.insert(kApiScope);
215 return scopes;
216 }
217
218 InterestsFetcher::~InterestsFetcher() {}
jochen (gone - plz use gerrit) 2015/09/30 09:23:09 dtor should come right after the ctor
tache 2015/09/30 17:32:02 Done.
219
220 bool InterestsFetcher::Interest::operator==(const Interest& interest) const {
221 return name == interest.name &&
222 image_url == interest.image_url &&
223 relevance == interest.relevance;
224 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698