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"
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/values.h"
17 #include "chrome/browser/profiles/profile.h"
18 #include "chrome/browser/profiles/profile_downloader_delegate.h"
19 #include "chrome/browser/profiles/profile_manager.h"
20 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
21 #include "chrome/browser/signin/signin_manager_factory.h"
22 #include "components/signin/core/browser/profile_oauth2_token_service.h"
23 #include "components/signin/core/browser/signin_manager.h"
24 #include "components/signin/core/common/profile_management_switches.h"
25 #include "content/public/browser/browser_thread.h"
26 #include "google_apis/gaia/gaia_constants.h"
27 #include "google_apis/gaia/gaia_urls.h"
28 #include "net/base/load_flags.h"
29 #include "net/url_request/url_fetcher.h"
30 #include "net/url_request/url_request_status.h"
31 #include "skia/ext/image_operations.h"
34 using content::BrowserThread
;
38 // Template for optional authorization header when using an OAuth access token.
39 const char kAuthorizationHeader
[] =
40 "Authorization: Bearer %s";
42 // Path in JSON dictionary to user's photo thumbnail URL.
43 const char kPhotoThumbnailURLPath
[] = "picture";
45 // Path in JSON dictionary to user's hosted domain.
46 const char kHostedDomainPath
[] = "hd";
48 // From the user info API, this field corresponds to the full name of the user.
49 const char kFullNamePath
[] = "name";
51 const char kGivenNamePath
[] = "given_name";
53 // Path in JSON dictionary to user's preferred locale.
54 const char kLocalePath
[] = "locale";
56 // Path format for specifying thumbnail's size.
57 const char kThumbnailSizeFormat
[] = "s%d-c";
58 // Default thumbnail size.
59 const int kDefaultThumbnailSize
= 64;
61 // Separator of URL path components.
62 const char kURLPathSeparator
= '/';
64 // Photo ID of the Picasa Web Albums profile picture (base64 of 0).
65 const char kPicasaPhotoId
[] = "AAAAAAAAAAA";
67 // Photo version of the default PWA profile picture (base64 of 1).
68 const char kDefaultPicasaPhotoVersion
[] = "AAAAAAAAAAE";
70 // The minimum number of path components in profile picture URL.
71 const size_t kProfileImageURLPathComponentsCount
= 6;
73 // Index of path component with photo ID.
74 const int kPhotoIdPathComponentIndex
= 2;
76 // Index of path component with photo version.
77 const int kPhotoVersionPathComponentIndex
= 3;
79 // Given an image URL this function builds a new URL set to |size|.
80 // For example, if |size| was set to 256 and |old_url| was either:
81 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/photo.jpg
83 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/s64-c/photo.jpg
84 // then return value in |new_url| would be:
85 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/s256-c/photo.jpg
86 bool GetImageURLWithSize(const GURL
& old_url
, int size
, GURL
* new_url
) {
88 std::vector
<std::string
> components
;
89 base::SplitString(old_url
.path(), kURLPathSeparator
, &components
);
90 if (components
.size() == 0)
93 const std::string
& old_spec
= old_url
.spec();
94 std::string
default_size_component(
95 base::StringPrintf(kThumbnailSizeFormat
, kDefaultThumbnailSize
));
96 std::string
new_size_component(
97 base::StringPrintf(kThumbnailSizeFormat
, size
));
99 size_t pos
= old_spec
.find(default_size_component
);
100 size_t end
= std::string::npos
;
101 if (pos
!= std::string::npos
) {
102 // The default size is already specified in the URL so it needs to be
103 // replaced with the new size.
104 end
= pos
+ default_size_component
.size();
106 // The default size is not in the URL so try to insert it before the last
108 const std::string
& file_name
= old_url
.ExtractFileName();
109 if (!file_name
.empty()) {
110 pos
= old_spec
.find(file_name
);
115 if (pos
!= std::string::npos
) {
116 std::string new_spec
= old_spec
.substr(0, pos
) + new_size_component
+
117 old_spec
.substr(end
);
118 *new_url
= GURL(new_spec
);
119 return new_url
->is_valid();
122 // We can't set the image size, just use the default size.
129 // Parses the entry response and gets the name and profile image URL.
130 // |data| should be the JSON formatted data return by the response.
131 // Returns false to indicate a parsing error.
132 bool ProfileDownloader::ParseProfileJSON(base::DictionaryValue
* root_dictionary
,
133 base::string16
* full_name
,
134 base::string16
* given_name
,
137 std::string
* profile_locale
,
138 base::string16
* hosted_domain
) {
142 DCHECK(profile_locale
);
143 DCHECK(hosted_domain
);
145 *full_name
= base::string16();
146 *given_name
= base::string16();
147 *url
= std::string();
148 *profile_locale
= std::string();
149 *hosted_domain
= base::string16();
151 root_dictionary
->GetString(kFullNamePath
, full_name
);
152 root_dictionary
->GetString(kGivenNamePath
, given_name
);
153 root_dictionary
->GetString(kLocalePath
, profile_locale
);
154 root_dictionary
->GetString(kHostedDomainPath
, hosted_domain
);
156 std::string url_string
;
157 if (root_dictionary
->GetString(kPhotoThumbnailURLPath
, &url_string
)) {
159 if (!GetImageURLWithSize(GURL(url_string
), image_size
, &new_url
)) {
160 LOG(ERROR
) << "GetImageURLWithSize failed for url: " << url_string
;
163 *url
= new_url
.spec();
166 // The profile data is considered valid as long as it has a name or a picture.
167 return !full_name
->empty() || !url
->empty();
171 bool ProfileDownloader::IsDefaultProfileImageURL(const std::string
& url
) {
175 GURL
image_url_object(url
);
176 DCHECK(image_url_object
.is_valid());
177 VLOG(1) << "URL to check for default image: " << image_url_object
.spec();
178 std::vector
<std::string
> path_components
;
179 base::SplitString(image_url_object
.path(),
183 if (path_components
.size() < kProfileImageURLPathComponentsCount
)
186 const std::string
& photo_id
= path_components
[kPhotoIdPathComponentIndex
];
187 const std::string
& photo_version
=
188 path_components
[kPhotoVersionPathComponentIndex
];
190 // Check that the ID and version match the default Picasa profile photo.
191 return photo_id
== kPicasaPhotoId
&&
192 photo_version
== kDefaultPicasaPhotoVersion
;
195 ProfileDownloader::ProfileDownloader(ProfileDownloaderDelegate
* delegate
)
196 : OAuth2TokenService::Consumer("profile_downloader"),
198 picture_status_(PICTURE_FAILED
) {
202 void ProfileDownloader::Start() {
203 StartForAccount(std::string());
206 void ProfileDownloader::StartForAccount(const std::string
& account_id
) {
207 VLOG(1) << "Starting profile downloader...";
208 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
210 ProfileOAuth2TokenService
* service
=
211 ProfileOAuth2TokenServiceFactory::GetForProfile(
212 delegate_
->GetBrowserProfile());
214 // This can happen in some test paths.
215 LOG(WARNING
) << "User has no token service";
216 delegate_
->OnProfileDownloadFailure(
217 this, ProfileDownloaderDelegate::TOKEN_ERROR
);
221 SigninManagerBase
* signin_manager
=
222 SigninManagerFactory::GetForProfile(delegate_
->GetBrowserProfile());
225 signin_manager
->GetAuthenticatedAccountId() : account_id
;
226 if (service
->RefreshTokenIsAvailable(account_id_
)) {
227 StartFetchingOAuth2AccessToken();
229 service
->AddObserver(this);
233 base::string16
ProfileDownloader::GetProfileHostedDomain() const {
234 return profile_hosted_domain_
;
237 base::string16
ProfileDownloader::GetProfileFullName() const {
238 return profile_full_name_
;
241 base::string16
ProfileDownloader::GetProfileGivenName() const {
242 return profile_given_name_
;
245 std::string
ProfileDownloader::GetProfileLocale() const {
246 return profile_locale_
;
249 SkBitmap
ProfileDownloader::GetProfilePicture() const {
250 return profile_picture_
;
253 ProfileDownloader::PictureStatus
ProfileDownloader::GetProfilePictureStatus()
255 return picture_status_
;
258 std::string
ProfileDownloader::GetProfilePictureURL() const {
262 void ProfileDownloader::StartFetchingImage() {
263 VLOG(1) << "Fetching user entry with token: " << auth_token_
;
264 gaia_client_
.reset(new gaia::GaiaOAuthClient(
265 delegate_
->GetBrowserProfile()->GetRequestContext()));
266 gaia_client_
->GetUserInfo(auth_token_
, 0, this);
269 void ProfileDownloader::StartFetchingOAuth2AccessToken() {
270 Profile
* profile
= delegate_
->GetBrowserProfile();
271 OAuth2TokenService::ScopeSet scopes
;
272 scopes
.insert(GaiaConstants::kGoogleUserInfoProfile
);
273 // Increase scope to get hd attribute to determine if lock should be enabled.
274 if (switches::IsNewProfileManagement())
275 scopes
.insert(GaiaConstants::kGoogleUserInfoEmail
);
276 ProfileOAuth2TokenService
* token_service
=
277 ProfileOAuth2TokenServiceFactory::GetForProfile(profile
);
278 oauth2_access_token_request_
= token_service
->StartRequest(
279 account_id_
, scopes
, this);
282 ProfileDownloader::~ProfileDownloader() {
283 // Ensures PO2TS observation is cleared when ProfileDownloader is destructed
284 // before refresh token is available.
285 ProfileOAuth2TokenService
* service
=
286 ProfileOAuth2TokenServiceFactory::GetForProfile(
287 delegate_
->GetBrowserProfile());
289 service
->RemoveObserver(this);
292 void ProfileDownloader::OnGetUserInfoResponse(
293 scoped_ptr
<base::DictionaryValue
> user_info
) {
294 std::string image_url
;
295 if (!ParseProfileJSON(user_info
.get(),
297 &profile_given_name_
,
299 delegate_
->GetDesiredImageSideLength(),
301 &profile_hosted_domain_
)) {
302 delegate_
->OnProfileDownloadFailure(
303 this, ProfileDownloaderDelegate::SERVICE_ERROR
);
306 if (!delegate_
->NeedsProfilePicture()) {
307 VLOG(1) << "Skipping profile picture download";
308 delegate_
->OnProfileDownloadSuccess(this);
311 if (IsDefaultProfileImageURL(image_url
)) {
312 VLOG(1) << "User has default profile picture";
313 picture_status_
= PICTURE_DEFAULT
;
314 delegate_
->OnProfileDownloadSuccess(this);
317 if (!image_url
.empty() && image_url
== delegate_
->GetCachedPictureURL()) {
318 VLOG(1) << "Picture URL matches cached picture URL";
319 picture_status_
= PICTURE_CACHED
;
320 delegate_
->OnProfileDownloadSuccess(this);
323 VLOG(1) << "Fetching profile image from " << image_url
;
324 picture_url_
= image_url
;
325 profile_image_fetcher_
.reset(net::URLFetcher::Create(
326 GURL(image_url
), net::URLFetcher::GET
, this));
327 profile_image_fetcher_
->SetRequestContext(
328 delegate_
->GetBrowserProfile()->GetRequestContext());
329 profile_image_fetcher_
->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES
|
330 net::LOAD_DO_NOT_SAVE_COOKIES
);
331 if (!auth_token_
.empty()) {
332 profile_image_fetcher_
->SetExtraRequestHeaders(
333 base::StringPrintf(kAuthorizationHeader
, auth_token_
.c_str()));
335 profile_image_fetcher_
->Start();
338 void ProfileDownloader::OnOAuthError() {
339 LOG(WARNING
) << "OnOAuthError: Fetching profile data failed";
340 delegate_
->OnProfileDownloadFailure(
341 this, ProfileDownloaderDelegate::SERVICE_ERROR
);
344 void ProfileDownloader::OnNetworkError(int response_code
) {
345 LOG(WARNING
) << "OnNetworkError: Fetching profile data failed";
346 DVLOG(1) << " Response code: " << response_code
;
347 delegate_
->OnProfileDownloadFailure(
348 this, ProfileDownloaderDelegate::NETWORK_ERROR
);
351 void ProfileDownloader::OnURLFetchComplete(const net::URLFetcher
* source
) {
352 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
354 source
->GetResponseAsString(&data
);
356 source
->GetStatus().status() != net::URLRequestStatus::SUCCESS
;
357 if (network_error
|| source
->GetResponseCode() != 200) {
358 LOG(WARNING
) << "Fetching profile data failed";
359 DVLOG(1) << " Status: " << source
->GetStatus().status();
360 DVLOG(1) << " Error: " << source
->GetStatus().error();
361 DVLOG(1) << " Response code: " << source
->GetResponseCode();
362 DVLOG(1) << " Url: " << source
->GetURL().spec();
363 delegate_
->OnProfileDownloadFailure(this, network_error
?
364 ProfileDownloaderDelegate::NETWORK_ERROR
:
365 ProfileDownloaderDelegate::SERVICE_ERROR
);
369 VLOG(1) << "Decoding the image...";
370 scoped_refptr
<ImageDecoder
> image_decoder
= new ImageDecoder(
371 this, data
, ImageDecoder::DEFAULT_CODEC
);
372 scoped_refptr
<base::MessageLoopProxy
> task_runner
=
373 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI
);
374 image_decoder
->Start(task_runner
);
377 void ProfileDownloader::OnImageDecoded(const ImageDecoder
* decoder
,
378 const SkBitmap
& decoded_image
) {
379 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
380 int image_size
= delegate_
->GetDesiredImageSideLength();
381 profile_picture_
= skia::ImageOperations::Resize(
383 skia::ImageOperations::RESIZE_BEST
,
386 picture_status_
= PICTURE_SUCCESS
;
387 delegate_
->OnProfileDownloadSuccess(this);
390 void ProfileDownloader::OnDecodeImageFailed(const ImageDecoder
* decoder
) {
391 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
392 delegate_
->OnProfileDownloadFailure(
393 this, ProfileDownloaderDelegate::IMAGE_DECODE_FAILED
);
396 void ProfileDownloader::OnRefreshTokenAvailable(const std::string
& account_id
) {
397 ProfileOAuth2TokenService
* service
=
398 ProfileOAuth2TokenServiceFactory::GetForProfile(
399 delegate_
->GetBrowserProfile());
400 if (account_id
!= account_id_
)
403 service
->RemoveObserver(this);
404 StartFetchingOAuth2AccessToken();
407 // Callback for OAuth2TokenService::Request on success. |access_token| is the
408 // token used to start fetching user data.
409 void ProfileDownloader::OnGetTokenSuccess(
410 const OAuth2TokenService::Request
* request
,
411 const std::string
& access_token
,
412 const base::Time
& expiration_time
) {
413 DCHECK_EQ(request
, oauth2_access_token_request_
.get());
414 oauth2_access_token_request_
.reset();
415 auth_token_
= access_token
;
416 StartFetchingImage();
419 // Callback for OAuth2TokenService::Request on failure.
420 void ProfileDownloader::OnGetTokenFailure(
421 const OAuth2TokenService::Request
* request
,
422 const GoogleServiceAuthError
& error
) {
423 DCHECK_EQ(request
, oauth2_access_token_request_
.get());
424 oauth2_access_token_request_
.reset();
425 LOG(WARNING
) << "ProfileDownloader: token request using refresh token failed:"
427 delegate_
->OnProfileDownloadFailure(
428 this, ProfileDownloaderDelegate::TOKEN_ERROR
);