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

Unified 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: Fix comments Created 5 years, 3 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 side-by-side diff with in-line comments
Download patch
Index: chrome/browser/interests/interests_fetcher.cc
diff --git a/chrome/browser/interests/interests_fetcher.cc b/chrome/browser/interests/interests_fetcher.cc
new file mode 100644
index 0000000000000000000000000000000000000000..230a78ebe5b2510219e6bce4cb35ade1403d7463
--- /dev/null
+++ b/chrome/browser/interests/interests_fetcher.cc
@@ -0,0 +1,221 @@
+// Copyright 2015 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "chrome/browser/interests/interests_fetcher.h"
+
+#include "base/command_line.h"
+#include "base/json/json_reader.h"
+#include "base/logging.h"
+#include "base/strings/stringprintf.h"
+#include "base/values.h"
+#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
+#include "chrome/browser/signin/signin_manager_factory.h"
+#include "chrome/common/chrome_switches.h"
+#include "components/signin/core/browser/profile_oauth2_token_service.h"
+#include "net/base/load_flags.h"
+#include "net/http/http_status_code.h"
+#include "net/url_request/url_fetcher.h"
+#include "net/url_request/url_request_context_getter.h"
+#include "net/url_request/url_request_status.h"
+
+namespace {
+
+const int kNumRetries = 1;
+const char kIdInterests[] = "interests";
+const char kIdInterestName[] = "name";
+const char kIdInterestImageUrl[] = "imageUrl";
+const char kIdInterestRelevance[] = "relevance";
+
+const char kApiScope[] = "https://www.googleapis.com/auth/googlenow";
+
+const char kAuthorizationHeaderFormat[] = "Authorization: Bearer %s";
+
+std::vector<InterestsFetcher::Interest> EmptyResponse() {
+ return std::vector<InterestsFetcher::Interest>();
+}
+
+GURL GetInterestsURL() {
+ const base::CommandLine* command_line =
+ base::CommandLine::ForCurrentProcess();
+ GURL interests_url(
+ command_line->GetSwitchValueASCII(switches::kInterestsURL));
+ return interests_url;
+}
+
+} // namespace
+
+InterestsFetcher::InterestsFetcher(
+ OAuth2TokenService* oauth2_token_service,
+ const std::string& account_id,
+ net::URLRequestContextGetter* url_request_context)
+ : OAuth2TokenService::Consumer("interests_fetcher"),
+ token_service_(oauth2_token_service),
+ account_id_(account_id),
+ url_request_context_(url_request_context),
+ access_token_expired_(false) {
+}
+
+InterestsFetcher::~InterestsFetcher() {}
+
+// static
+scoped_ptr<InterestsFetcher>
+InterestsFetcher::CreateFromProfile(Profile* profile) {
+ ProfileOAuth2TokenService* token_service =
+ ProfileOAuth2TokenServiceFactory::GetForProfile(profile);
+
+ SigninManagerBase* signin = SigninManagerFactory::GetForProfile(profile);
+
+ return make_scoped_ptr(new InterestsFetcher(
+ token_service,
+ signin->GetAuthenticatedAccountId(),
+ profile->GetRequestContext()));
+}
+
+void InterestsFetcher::Start(
+ const InterestsFetcher::InterestsCallback& callback) {
+ DCHECK(callback_.is_null());
+ callback_ = callback;
+ StartOAuth2Request();
+}
+
+void InterestsFetcher::StartOAuth2Request(){
+ oauth_request_ =
+ token_service_->StartRequest(account_id_, GetApiScopes(), this);
+}
+
+void InterestsFetcher::OnGetTokenFailure(
+ const OAuth2TokenService::Request* request,
+ const GoogleServiceAuthError& error) {
+ DLOG(WARNING) << error.ToString();
+
+ callback_.Run(EmptyResponse());
+}
+
+void InterestsFetcher::OnGetTokenSuccess(
+ const OAuth2TokenService::Request* request,
+ const std::string& access_token,
+ const base::Time& expiration_time) {
+
+ access_token_ = access_token;
+ fetcher_ = CreateFetcher();
+
+ // Setup fetcher
+ fetcher_->SetRequestContext(url_request_context_);
+ fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
+ net::LOAD_DO_NOT_SAVE_COOKIES);
+ fetcher_->SetAutomaticallyRetryOnNetworkChanges(kNumRetries);
+
+ // Add oauth access token
jochen (gone - plz use gerrit) 2015/10/02 13:51:00 please no comments of the form // Do foo DoFoo()
PEConn 2015/10/05 14:12:04 Done.
+ fetcher_->AddExtraRequestHeader(
+ base::StringPrintf(kAuthorizationHeaderFormat, access_token_.c_str()));
+
+ fetcher_->Start();
+
jochen (gone - plz use gerrit) 2015/10/02 13:51:00 no empty line here
PEConn 2015/10/05 14:12:04 Done.
+}
+
+scoped_ptr<net::URLFetcher> InterestsFetcher::CreateFetcher() {
+ return net::URLFetcher::Create(0, GetInterestsURL(), net::URLFetcher::GET,
+ this);
+}
+
+void InterestsFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
+
+ const net::URLRequestStatus& status = source->GetStatus();
+ if (!status.is_success()) {
+ LOG(WARNING) << "Network error " << status.error();
+ callback_.Run(EmptyResponse());
+ return;
+ }
+
+ int response_code = source->GetResponseCode();
+ // If we get an authorization error, refresh token and retry once.
+ if (response_code == net::HTTP_UNAUTHORIZED && !access_token_expired_) {
+ access_token_expired_ = true;
+ token_service_->InvalidateAccessToken(account_id_, GetApiScopes(),
+ access_token_);
+ StartOAuth2Request();
+ return;
+ }
+
+ if (response_code != net::HTTP_OK) {
+ LOG(WARNING) << "HTTP error " << response_code;
jochen (gone - plz use gerrit) 2015/10/02 13:51:00 VLOG(2), here and everywhere
PEConn 2015/10/05 14:12:04 Done.
+ callback_.Run(EmptyResponse());
+ return;
+ }
+
+ std::string response_body;
+ source->GetResponseAsString(&response_body);
+
+ callback_.Run(ExtractInterests(response_body));
+}
+
+std::vector<InterestsFetcher::Interest> InterestsFetcher::ExtractInterests(
+ const std::string& response) {
+ scoped_ptr<base::Value> value = base::JSONReader::Read(response);
+
+ const base::DictionaryValue* dict = nullptr;
+ if (!value || !value->GetAsDictionary(&dict)) {
+ DLOG(WARNING) << "ExtractInterests failed to parse global dictionary";
+ return EmptyResponse();
+ }
+
+ const base::ListValue* interests_list = nullptr;
+ std::vector<Interest> res;
+
+ if (!dict->GetList(kIdInterests, &interests_list)) {
+ DLOG(WARNING) << "ExtractInterests failed to parse interests list";
+ return EmptyResponse();
+ }
+
+ for (const base::Value* entry : *interests_list) {
+ const base::DictionaryValue* interest_dict = nullptr;
+ if (!entry->GetAsDictionary(&interest_dict)) {
+ DLOG(WARNING) << "ExtractInterests failed to parse interest dictionary";
+ return EmptyResponse();
+ }
+
+ std::string name;
+ if (!interest_dict->GetString(kIdInterestName, &name)) {
+ DLOG(WARNING) << "ExtractInterests failed to parse interest name";
+ return EmptyResponse();
+ }
+
+ std::string image_url;
+ if (!interest_dict->GetString(kIdInterestImageUrl, &image_url)) {
+ // image_url is allowed to be missing.
+ //
+ // However this is still logged as a warning, since, currently, the server
+ // should always provide an image_url.
+ DLOG(WARNING) << "ExtractInterests failed to parse interest image URL";
+ }
+
+ double relevance;
+ if (!interest_dict->GetDouble(kIdInterestRelevance, &relevance)) {
+ DLOG(WARNING) << "ExtractInterests failed to parse interest relevance";
+ return EmptyResponse();
+ }
+
+ res.push_back(Interest{name, GURL(image_url), relevance});
+ }
+
+ return res;
+}
+
+OAuth2TokenService::ScopeSet InterestsFetcher::GetApiScopes() {
+ OAuth2TokenService::ScopeSet scopes;
+ scopes.insert(kApiScope);
+ return scopes;
+}
+
+InterestsFetcher::Interest::Interest(const std::string& name,
jochen (gone - plz use gerrit) 2015/10/02 13:51:00 i'd recommend to use the same order in the cc file
PEConn 2015/10/05 14:12:04 Done.
+ const GURL& image_url, float relevance)
+ : name(name), image_url(image_url), relevance(relevance) {}
+
+InterestsFetcher::Interest::~Interest() {}
+
+bool InterestsFetcher::Interest::operator==(const Interest& interest) const {
+ return name == interest.name &&
+ image_url == interest.image_url &&
+ relevance == interest.relevance;
+}

Powered by Google App Engine
This is Rietveld 408576698