Revert "Reland c91b178b07b0d - Delete dead signin code (SigninGlobalError)"
[chromium-blink-merge.git] / chrome / browser / profiles / profile_downloader.cc
bloba424f7950412bb6eadc1fd34276554bed86014fd
1 // Copyright (c) 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/profiles/profile_downloader.h"
7 #include <string>
8 #include <vector>
10 #include "base/json/json_reader.h"
11 #include "base/logging.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/strings/string_split.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/values.h"
18 #include "chrome/browser/profiles/profile.h"
19 #include "chrome/browser/profiles/profile_downloader_delegate.h"
20 #include "chrome/browser/profiles/profile_manager.h"
21 #include "chrome/browser/signin/account_fetcher_service_factory.h"
22 #include "chrome/browser/signin/account_tracker_service_factory.h"
23 #include "chrome/browser/signin/chrome_signin_client_factory.h"
24 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
25 #include "chrome/browser/signin/signin_manager_factory.h"
26 #include "components/signin/core/browser/account_fetcher_service.h"
27 #include "components/signin/core/browser/profile_oauth2_token_service.h"
28 #include "components/signin/core/browser/signin_client.h"
29 #include "components/signin/core/browser/signin_manager.h"
30 #include "components/signin/core/common/profile_management_switches.h"
31 #include "content/public/browser/browser_thread.h"
32 #include "google_apis/gaia/gaia_constants.h"
33 #include "net/base/load_flags.h"
34 #include "net/url_request/url_fetcher.h"
35 #include "net/url_request/url_request_status.h"
36 #include "skia/ext/image_operations.h"
37 #include "url/gurl.h"
39 using content::BrowserThread;
41 namespace {
43 // Template for optional authorization header when using an OAuth access token.
44 const char kAuthorizationHeader[] =
45 "Authorization: Bearer %s";
47 // Path format for specifying thumbnail's size.
48 const char kThumbnailSizeFormat[] = "s%d-c";
49 // Default thumbnail size.
50 const int kDefaultThumbnailSize = 64;
52 // Separator of URL path components.
53 const char kURLPathSeparator = '/';
55 // Photo ID of the Picasa Web Albums profile picture (base64 of 0).
56 const char kPicasaPhotoId[] = "AAAAAAAAAAA";
58 // Photo version of the default PWA profile picture (base64 of 1).
59 const char kDefaultPicasaPhotoVersion[] = "AAAAAAAAAAE";
61 // The minimum number of path components in profile picture URL.
62 const size_t kProfileImageURLPathComponentsCount = 6;
64 // Index of path component with photo ID.
65 const int kPhotoIdPathComponentIndex = 2;
67 // Index of path component with photo version.
68 const int kPhotoVersionPathComponentIndex = 3;
70 // Given an image URL this function builds a new URL set to |size|.
71 // For example, if |size| was set to 256 and |old_url| was either:
72 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/photo.jpg
73 // or
74 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/s64-c/photo.jpg
75 // then return value in |new_url| would be:
76 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/s256-c/photo.jpg
77 bool GetImageURLWithSize(const GURL& old_url, int size, GURL* new_url) {
78 DCHECK(new_url);
79 std::vector<std::string> components = base::SplitString(
80 old_url.path(), std::string(1, kURLPathSeparator),
81 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
82 if (components.size() == 0)
83 return false;
85 const std::string& old_spec = old_url.spec();
86 std::string default_size_component(
87 base::StringPrintf(kThumbnailSizeFormat, kDefaultThumbnailSize));
88 std::string new_size_component(
89 base::StringPrintf(kThumbnailSizeFormat, size));
91 size_t pos = old_spec.find(default_size_component);
92 size_t end = std::string::npos;
93 if (pos != std::string::npos) {
94 // The default size is already specified in the URL so it needs to be
95 // replaced with the new size.
96 end = pos + default_size_component.size();
97 } else {
98 // The default size is not in the URL so try to insert it before the last
99 // component.
100 const std::string& file_name = old_url.ExtractFileName();
101 if (!file_name.empty()) {
102 pos = old_spec.find(file_name);
103 end = pos - 1;
107 if (pos != std::string::npos) {
108 std::string new_spec = old_spec.substr(0, pos) + new_size_component +
109 old_spec.substr(end);
110 *new_url = GURL(new_spec);
111 return new_url->is_valid();
114 // We can't set the image size, just use the default size.
115 *new_url = old_url;
116 return true;
119 } // namespace
121 // static
122 bool ProfileDownloader::IsDefaultProfileImageURL(const std::string& url) {
123 if (url.empty())
124 return true;
126 GURL image_url_object(url);
127 DCHECK(image_url_object.is_valid());
128 VLOG(1) << "URL to check for default image: " << image_url_object.spec();
129 std::vector<std::string> path_components = base::SplitString(
130 image_url_object.path(), std::string(1, kURLPathSeparator),
131 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
133 if (path_components.size() < kProfileImageURLPathComponentsCount)
134 return false;
136 const std::string& photo_id = path_components[kPhotoIdPathComponentIndex];
137 const std::string& photo_version =
138 path_components[kPhotoVersionPathComponentIndex];
140 // Check that the ID and version match the default Picasa profile photo.
141 return photo_id == kPicasaPhotoId &&
142 photo_version == kDefaultPicasaPhotoVersion;
145 ProfileDownloader::ProfileDownloader(ProfileDownloaderDelegate* delegate)
146 : OAuth2TokenService::Consumer("profile_downloader"),
147 delegate_(delegate),
148 picture_status_(PICTURE_FAILED),
149 account_tracker_service_(
150 AccountTrackerServiceFactory::GetForProfile(
151 delegate_->GetBrowserProfile())),
152 waiting_for_account_info_(false) {
153 DCHECK(delegate_);
154 account_tracker_service_->AddObserver(this);
157 void ProfileDownloader::Start() {
158 StartForAccount(std::string());
161 void ProfileDownloader::StartForAccount(const std::string& account_id) {
162 VLOG(1) << "Starting profile downloader...";
163 DCHECK_CURRENTLY_ON(BrowserThread::UI);
165 ProfileOAuth2TokenService* service =
166 ProfileOAuth2TokenServiceFactory::GetForProfile(
167 delegate_->GetBrowserProfile());
168 if (!service) {
169 // This can happen in some test paths.
170 LOG(WARNING) << "User has no token service";
171 delegate_->OnProfileDownloadFailure(
172 this, ProfileDownloaderDelegate::TOKEN_ERROR);
173 return;
176 SigninManagerBase* signin_manager =
177 SigninManagerFactory::GetForProfile(delegate_->GetBrowserProfile());
178 account_id_ =
179 account_id.empty() ?
180 signin_manager->GetAuthenticatedAccountId() : account_id;
181 if (service->RefreshTokenIsAvailable(account_id_))
182 StartFetchingOAuth2AccessToken();
183 else
184 service->AddObserver(this);
187 base::string16 ProfileDownloader::GetProfileHostedDomain() const {
188 return base::UTF8ToUTF16(account_info_.hosted_domain);
191 base::string16 ProfileDownloader::GetProfileFullName() const {
192 return base::UTF8ToUTF16(account_info_.full_name);
195 base::string16 ProfileDownloader::GetProfileGivenName() const {
196 return base::UTF8ToUTF16(account_info_.given_name);
199 std::string ProfileDownloader::GetProfileLocale() const {
200 return account_info_.locale;
203 SkBitmap ProfileDownloader::GetProfilePicture() const {
204 return profile_picture_;
207 ProfileDownloader::PictureStatus ProfileDownloader::GetProfilePictureStatus()
208 const {
209 return picture_status_;
212 std::string ProfileDownloader::GetProfilePictureURL() const {
213 GURL url;
214 if (GetImageURLWithSize(GURL(account_info_.picture_url),
215 delegate_->GetDesiredImageSideLength(),
216 &url)) {
217 return url.spec();
219 return account_info_.picture_url;
222 void ProfileDownloader::StartFetchingImage() {
223 VLOG(1) << "Fetching user entry with token: " << auth_token_;
224 account_info_ = account_tracker_service_->GetAccountInfo(account_id_);
226 if (delegate_->IsPreSignin()) {
227 AccountFetcherServiceFactory::GetForProfile(delegate_->GetBrowserProfile())
228 ->FetchUserInfoBeforeSignin(account_id_);
231 if (account_info_.IsValid())
232 FetchImageData();
233 else
234 waiting_for_account_info_ = true;
237 void ProfileDownloader::StartFetchingOAuth2AccessToken() {
238 Profile* profile = delegate_->GetBrowserProfile();
239 OAuth2TokenService::ScopeSet scopes;
240 scopes.insert(GaiaConstants::kGoogleUserInfoProfile);
241 // Increase scope to get hd attribute to determine if lock should be enabled.
242 if (switches::IsNewProfileManagement())
243 scopes.insert(GaiaConstants::kGoogleUserInfoEmail);
244 ProfileOAuth2TokenService* token_service =
245 ProfileOAuth2TokenServiceFactory::GetForProfile(profile);
246 oauth2_access_token_request_ = token_service->StartRequest(
247 account_id_, scopes, this);
250 ProfileDownloader::~ProfileDownloader() {
251 // Ensures PO2TS observation is cleared when ProfileDownloader is destructed
252 // before refresh token is available.
253 ProfileOAuth2TokenService* service =
254 ProfileOAuth2TokenServiceFactory::GetForProfile(
255 delegate_->GetBrowserProfile());
256 if (service)
257 service->RemoveObserver(this);
259 account_tracker_service_->RemoveObserver(this);
262 void ProfileDownloader::FetchImageData() {
263 DCHECK(account_info_.IsValid());
264 std::string image_url_with_size = GetProfilePictureURL();
266 if (!delegate_->NeedsProfilePicture()) {
267 VLOG(1) << "Skipping profile picture download";
268 delegate_->OnProfileDownloadSuccess(this);
269 return;
271 if (IsDefaultProfileImageURL(image_url_with_size)) {
272 VLOG(1) << "User has default profile picture";
273 picture_status_ = PICTURE_DEFAULT;
274 delegate_->OnProfileDownloadSuccess(this);
275 return;
277 if (!image_url_with_size.empty() &&
278 image_url_with_size == delegate_->GetCachedPictureURL()) {
279 VLOG(1) << "Picture URL matches cached picture URL";
280 picture_status_ = PICTURE_CACHED;
281 delegate_->OnProfileDownloadSuccess(this);
282 return;
285 VLOG(1) << "Fetching profile image from " << image_url_with_size;
286 profile_image_fetcher_ = net::URLFetcher::Create(
287 GURL(image_url_with_size), net::URLFetcher::GET, this);
288 profile_image_fetcher_->SetRequestContext(
289 delegate_->GetBrowserProfile()->GetRequestContext());
290 profile_image_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
291 net::LOAD_DO_NOT_SAVE_COOKIES);
293 if (!auth_token_.empty()) {
294 profile_image_fetcher_->SetExtraRequestHeaders(
295 base::StringPrintf(kAuthorizationHeader, auth_token_.c_str()));
298 profile_image_fetcher_->Start();
301 void ProfileDownloader::OnURLFetchComplete(const net::URLFetcher* source) {
302 DCHECK_CURRENTLY_ON(BrowserThread::UI);
303 std::string data;
304 source->GetResponseAsString(&data);
305 bool network_error =
306 source->GetStatus().status() != net::URLRequestStatus::SUCCESS;
307 if (network_error || source->GetResponseCode() != 200) {
308 LOG(WARNING) << "Fetching profile data failed";
309 DVLOG(1) << " Status: " << source->GetStatus().status();
310 DVLOG(1) << " Error: " << source->GetStatus().error();
311 DVLOG(1) << " Response code: " << source->GetResponseCode();
312 DVLOG(1) << " Url: " << source->GetURL().spec();
313 profile_image_fetcher_.reset();
314 delegate_->OnProfileDownloadFailure(this, network_error ?
315 ProfileDownloaderDelegate::NETWORK_ERROR :
316 ProfileDownloaderDelegate::SERVICE_ERROR);
317 } else {
318 profile_image_fetcher_.reset();
319 VLOG(1) << "Decoding the image...";
320 ImageDecoder::Start(this, data);
324 void ProfileDownloader::OnImageDecoded(const SkBitmap& decoded_image) {
325 DCHECK_CURRENTLY_ON(BrowserThread::UI);
326 int image_size = delegate_->GetDesiredImageSideLength();
327 profile_picture_ = skia::ImageOperations::Resize(
328 decoded_image,
329 skia::ImageOperations::RESIZE_BEST,
330 image_size,
331 image_size);
332 picture_status_ = PICTURE_SUCCESS;
333 delegate_->OnProfileDownloadSuccess(this);
336 void ProfileDownloader::OnDecodeImageFailed() {
337 DCHECK_CURRENTLY_ON(BrowserThread::UI);
338 delegate_->OnProfileDownloadFailure(
339 this, ProfileDownloaderDelegate::IMAGE_DECODE_FAILED);
342 void ProfileDownloader::OnRefreshTokenAvailable(const std::string& account_id) {
343 ProfileOAuth2TokenService* service =
344 ProfileOAuth2TokenServiceFactory::GetForProfile(
345 delegate_->GetBrowserProfile());
346 if (account_id != account_id_)
347 return;
349 service->RemoveObserver(this);
350 StartFetchingOAuth2AccessToken();
353 // Callback for OAuth2TokenService::Request on success. |access_token| is the
354 // token used to start fetching user data.
355 void ProfileDownloader::OnGetTokenSuccess(
356 const OAuth2TokenService::Request* request,
357 const std::string& access_token,
358 const base::Time& expiration_time) {
359 DCHECK_EQ(request, oauth2_access_token_request_.get());
360 oauth2_access_token_request_.reset();
361 auth_token_ = access_token;
362 StartFetchingImage();
365 // Callback for OAuth2TokenService::Request on failure.
366 void ProfileDownloader::OnGetTokenFailure(
367 const OAuth2TokenService::Request* request,
368 const GoogleServiceAuthError& error) {
369 DCHECK_EQ(request, oauth2_access_token_request_.get());
370 oauth2_access_token_request_.reset();
371 LOG(WARNING) << "ProfileDownloader: token request using refresh token failed:"
372 << error.ToString();
373 delegate_->OnProfileDownloadFailure(
374 this, ProfileDownloaderDelegate::TOKEN_ERROR);
377 void ProfileDownloader::OnAccountUpdated(
378 const AccountTrackerService::AccountInfo& info) {
379 if (info.account_id == account_id_ && info.IsValid()) {
380 account_info_ = info;
382 // If the StartFetchingImage was called before we had valid info, the
383 // downloader has been waiting so we need to fetch the image data now.
384 if (waiting_for_account_info_) {
385 FetchImageData();
386 waiting_for_account_info_ = false;