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
)
197 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI
)),
198 OAuth2TokenService::Consumer("profile_downloader"),
200 picture_status_(PICTURE_FAILED
) {
204 void ProfileDownloader::Start() {
205 StartForAccount(std::string());
208 void ProfileDownloader::StartForAccount(const std::string
& account_id
) {
209 VLOG(1) << "Starting profile downloader...";
210 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
212 ProfileOAuth2TokenService
* service
=
213 ProfileOAuth2TokenServiceFactory::GetForProfile(
214 delegate_
->GetBrowserProfile());
216 // This can happen in some test paths.
217 LOG(WARNING
) << "User has no token service";
218 delegate_
->OnProfileDownloadFailure(
219 this, ProfileDownloaderDelegate::TOKEN_ERROR
);
223 SigninManagerBase
* signin_manager
=
224 SigninManagerFactory::GetForProfile(delegate_
->GetBrowserProfile());
227 signin_manager
->GetAuthenticatedAccountId() : account_id
;
228 if (service
->RefreshTokenIsAvailable(account_id_
)) {
229 StartFetchingOAuth2AccessToken();
231 service
->AddObserver(this);
235 base::string16
ProfileDownloader::GetProfileHostedDomain() const {
236 return profile_hosted_domain_
;
239 base::string16
ProfileDownloader::GetProfileFullName() const {
240 return profile_full_name_
;
243 base::string16
ProfileDownloader::GetProfileGivenName() const {
244 return profile_given_name_
;
247 std::string
ProfileDownloader::GetProfileLocale() const {
248 return profile_locale_
;
251 SkBitmap
ProfileDownloader::GetProfilePicture() const {
252 return profile_picture_
;
255 ProfileDownloader::PictureStatus
ProfileDownloader::GetProfilePictureStatus()
257 return picture_status_
;
260 std::string
ProfileDownloader::GetProfilePictureURL() const {
264 void ProfileDownloader::StartFetchingImage() {
265 VLOG(1) << "Fetching user entry with token: " << auth_token_
;
266 gaia_client_
.reset(new gaia::GaiaOAuthClient(
267 delegate_
->GetBrowserProfile()->GetRequestContext()));
268 gaia_client_
->GetUserInfo(auth_token_
, 0, this);
271 void ProfileDownloader::StartFetchingOAuth2AccessToken() {
272 Profile
* profile
= delegate_
->GetBrowserProfile();
273 OAuth2TokenService::ScopeSet scopes
;
274 scopes
.insert(GaiaConstants::kGoogleUserInfoProfile
);
275 // Increase scope to get hd attribute to determine if lock should be enabled.
276 if (switches::IsNewProfileManagement())
277 scopes
.insert(GaiaConstants::kGoogleUserInfoEmail
);
278 ProfileOAuth2TokenService
* token_service
=
279 ProfileOAuth2TokenServiceFactory::GetForProfile(profile
);
280 oauth2_access_token_request_
= token_service
->StartRequest(
281 account_id_
, scopes
, this);
284 ProfileDownloader::~ProfileDownloader() {
285 // Ensures PO2TS observation is cleared when ProfileDownloader is destructed
286 // before refresh token is available.
287 ProfileOAuth2TokenService
* service
=
288 ProfileOAuth2TokenServiceFactory::GetForProfile(
289 delegate_
->GetBrowserProfile());
291 service
->RemoveObserver(this);
294 void ProfileDownloader::OnGetUserInfoResponse(
295 scoped_ptr
<base::DictionaryValue
> user_info
) {
296 std::string image_url
;
297 if (!ParseProfileJSON(user_info
.get(),
299 &profile_given_name_
,
301 delegate_
->GetDesiredImageSideLength(),
303 &profile_hosted_domain_
)) {
304 delegate_
->OnProfileDownloadFailure(
305 this, ProfileDownloaderDelegate::SERVICE_ERROR
);
308 if (!delegate_
->NeedsProfilePicture()) {
309 VLOG(1) << "Skipping profile picture download";
310 delegate_
->OnProfileDownloadSuccess(this);
313 if (IsDefaultProfileImageURL(image_url
)) {
314 VLOG(1) << "User has default profile picture";
315 picture_status_
= PICTURE_DEFAULT
;
316 delegate_
->OnProfileDownloadSuccess(this);
319 if (!image_url
.empty() && image_url
== delegate_
->GetCachedPictureURL()) {
320 VLOG(1) << "Picture URL matches cached picture URL";
321 picture_status_
= PICTURE_CACHED
;
322 delegate_
->OnProfileDownloadSuccess(this);
325 VLOG(1) << "Fetching profile image from " << image_url
;
326 picture_url_
= image_url
;
327 profile_image_fetcher_
.reset(net::URLFetcher::Create(
328 GURL(image_url
), net::URLFetcher::GET
, this));
329 profile_image_fetcher_
->SetRequestContext(
330 delegate_
->GetBrowserProfile()->GetRequestContext());
331 profile_image_fetcher_
->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES
|
332 net::LOAD_DO_NOT_SAVE_COOKIES
);
333 if (!auth_token_
.empty()) {
334 profile_image_fetcher_
->SetExtraRequestHeaders(
335 base::StringPrintf(kAuthorizationHeader
, auth_token_
.c_str()));
337 profile_image_fetcher_
->Start();
340 void ProfileDownloader::OnOAuthError() {
341 LOG(WARNING
) << "OnOAuthError: Fetching profile data failed";
342 delegate_
->OnProfileDownloadFailure(
343 this, ProfileDownloaderDelegate::SERVICE_ERROR
);
346 void ProfileDownloader::OnNetworkError(int response_code
) {
347 LOG(WARNING
) << "OnNetworkError: Fetching profile data failed";
348 DVLOG(1) << " Response code: " << response_code
;
349 delegate_
->OnProfileDownloadFailure(
350 this, ProfileDownloaderDelegate::NETWORK_ERROR
);
353 void ProfileDownloader::OnURLFetchComplete(const net::URLFetcher
* source
) {
354 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
356 source
->GetResponseAsString(&data
);
358 source
->GetStatus().status() != net::URLRequestStatus::SUCCESS
;
359 if (network_error
|| source
->GetResponseCode() != 200) {
360 LOG(WARNING
) << "Fetching profile data failed";
361 DVLOG(1) << " Status: " << source
->GetStatus().status();
362 DVLOG(1) << " Error: " << source
->GetStatus().error();
363 DVLOG(1) << " Response code: " << source
->GetResponseCode();
364 DVLOG(1) << " Url: " << source
->GetURL().spec();
365 delegate_
->OnProfileDownloadFailure(this, network_error
?
366 ProfileDownloaderDelegate::NETWORK_ERROR
:
367 ProfileDownloaderDelegate::SERVICE_ERROR
);
371 VLOG(1) << "Decoding the image...";
372 ImageDecoder::Start(this, data
);
375 void ProfileDownloader::OnImageDecoded(const SkBitmap
& decoded_image
) {
376 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
377 int image_size
= delegate_
->GetDesiredImageSideLength();
378 profile_picture_
= skia::ImageOperations::Resize(
380 skia::ImageOperations::RESIZE_BEST
,
383 picture_status_
= PICTURE_SUCCESS
;
384 delegate_
->OnProfileDownloadSuccess(this);
387 void ProfileDownloader::OnDecodeImageFailed() {
388 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
389 delegate_
->OnProfileDownloadFailure(
390 this, ProfileDownloaderDelegate::IMAGE_DECODE_FAILED
);
393 void ProfileDownloader::OnRefreshTokenAvailable(const std::string
& account_id
) {
394 ProfileOAuth2TokenService
* service
=
395 ProfileOAuth2TokenServiceFactory::GetForProfile(
396 delegate_
->GetBrowserProfile());
397 if (account_id
!= account_id_
)
400 service
->RemoveObserver(this);
401 StartFetchingOAuth2AccessToken();
404 // Callback for OAuth2TokenService::Request on success. |access_token| is the
405 // token used to start fetching user data.
406 void ProfileDownloader::OnGetTokenSuccess(
407 const OAuth2TokenService::Request
* request
,
408 const std::string
& access_token
,
409 const base::Time
& expiration_time
) {
410 DCHECK_EQ(request
, oauth2_access_token_request_
.get());
411 oauth2_access_token_request_
.reset();
412 auth_token_
= access_token
;
413 StartFetchingImage();
416 // Callback for OAuth2TokenService::Request on failure.
417 void ProfileDownloader::OnGetTokenFailure(
418 const OAuth2TokenService::Request
* request
,
419 const GoogleServiceAuthError
& error
) {
420 DCHECK_EQ(request
, oauth2_access_token_request_
.get());
421 oauth2_access_token_request_
.reset();
422 LOG(WARNING
) << "ProfileDownloader: token request using refresh token failed:"
424 delegate_
->OnProfileDownloadFailure(
425 this, ProfileDownloaderDelegate::TOKEN_ERROR
);