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.h"
21 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
22 #include "content/public/browser/browser_thread.h"
23 #include "google_apis/gaia/gaia_constants.h"
24 #include "google_apis/gaia/gaia_urls.h"
25 #include "net/base/load_flags.h"
26 #include "net/url_request/url_fetcher.h"
27 #include "net/url_request/url_request_status.h"
28 #include "skia/ext/image_operations.h"
31 using content::BrowserThread
;
35 // Template for optional authorization header when using an OAuth access token.
36 const char kAuthorizationHeader
[] =
37 "Authorization: Bearer %s";
39 // URL requesting user info.
40 const char kUserEntryURL
[] =
41 "https://www.googleapis.com/oauth2/v1/userinfo?alt=json";
43 // OAuth scope for the user info API.
44 // For more info, see https://developers.google.com/accounts/docs/OAuth2LoginV1.
45 const char kAPIScope
[] = "https://www.googleapis.com/auth/userinfo.profile";
47 // Path in JSON dictionary to user's photo thumbnail URL.
48 const char kPhotoThumbnailURLPath
[] = "picture";
50 // From the user info API, this field corresponds to the full name of the user.
51 const char kFullNamePath
[] = "name";
53 const char kGivenNamePath
[] = "given_name";
55 // Path in JSON dictionary to user's preferred locale.
56 const char kLocalePath
[] = "locale";
58 // Path format for specifying thumbnail's size.
59 const char kThumbnailSizeFormat
[] = "s%d-c";
60 // Default thumbnail size.
61 const int kDefaultThumbnailSize
= 64;
63 // Separator of URL path components.
64 const char kURLPathSeparator
= '/';
66 // Photo ID of the Picasa Web Albums profile picture (base64 of 0).
67 const char kPicasaPhotoId
[] = "AAAAAAAAAAA";
69 // Photo version of the default PWA profile picture (base64 of 1).
70 const char kDefaultPicasaPhotoVersion
[] = "AAAAAAAAAAE";
72 // The minimum number of path components in profile picture URL.
73 const size_t kProfileImageURLPathComponentsCount
= 6;
75 // Index of path component with photo ID.
76 const int kPhotoIdPathComponentIndex
= 2;
78 // Index of path component with photo version.
79 const int kPhotoVersionPathComponentIndex
= 3;
81 // Given an image URL this function builds a new URL set to |size|.
82 // For example, if |size| was set to 256 and |old_url| was either:
83 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/photo.jpg
85 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/s64-c/photo.jpg
86 // then return value in |new_url| would be:
87 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/s256-c/photo.jpg
88 bool GetImageURLWithSize(const GURL
& old_url
, int size
, GURL
* new_url
) {
90 std::vector
<std::string
> components
;
91 base::SplitString(old_url
.path(), kURLPathSeparator
, &components
);
92 if (components
.size() == 0)
95 const std::string
& old_spec
= old_url
.spec();
96 std::string
default_size_component(
97 base::StringPrintf(kThumbnailSizeFormat
, kDefaultThumbnailSize
));
98 std::string
new_size_component(
99 base::StringPrintf(kThumbnailSizeFormat
, size
));
101 size_t pos
= old_spec
.find(default_size_component
);
102 size_t end
= std::string::npos
;
103 if (pos
!= std::string::npos
) {
104 // The default size is already specified in the URL so it needs to be
105 // replaced with the new size.
106 end
= pos
+ default_size_component
.size();
108 // The default size is not in the URL so try to insert it before the last
110 const std::string
& file_name
= old_url
.ExtractFileName();
111 if (!file_name
.empty()) {
112 pos
= old_spec
.find(file_name
);
117 if (pos
!= std::string::npos
) {
118 std::string new_spec
= old_spec
.substr(0, pos
) + new_size_component
+
119 old_spec
.substr(end
);
120 *new_url
= GURL(new_spec
);
121 return new_url
->is_valid();
124 // We can't set the image size, just use the default size.
131 // Parses the entry response and gets the name and profile image URL.
132 // |data| should be the JSON formatted data return by the response.
133 // Returns false to indicate a parsing error.
134 bool ProfileDownloader::ParseProfileJSON(const std::string
& data
,
135 base::string16
* full_name
,
136 base::string16
* given_name
,
139 std::string
* profile_locale
) {
143 DCHECK(profile_locale
);
145 *full_name
= base::string16();
146 *given_name
= base::string16();
147 *url
= std::string();
148 *profile_locale
= std::string();
151 std::string error_message
;
152 scoped_ptr
<base::Value
> root_value(base::JSONReader::ReadAndReturnError(
153 data
, base::JSON_PARSE_RFC
, &error_code
, &error_message
));
155 LOG(ERROR
) << "Error while parsing user entry response: "
159 if (!root_value
->IsType(base::Value::TYPE_DICTIONARY
)) {
160 LOG(ERROR
) << "JSON root is not a dictionary: "
161 << root_value
->GetType();
164 base::DictionaryValue
* root_dictionary
=
165 static_cast<base::DictionaryValue
*>(root_value
.get());
167 root_dictionary
->GetString(kFullNamePath
, full_name
);
168 root_dictionary
->GetString(kGivenNamePath
, given_name
);
169 root_dictionary
->GetString(kLocalePath
, profile_locale
);
171 std::string url_string
;
172 if (root_dictionary
->GetString(kPhotoThumbnailURLPath
, &url_string
)) {
174 if (!GetImageURLWithSize(GURL(url_string
), image_size
, &new_url
)) {
175 LOG(ERROR
) << "GetImageURLWithSize failed for url: " << url_string
;
178 *url
= new_url
.spec();
181 // The profile data is considered valid as long as it has a name or a picture.
182 return !full_name
->empty() || !url
->empty();
186 bool ProfileDownloader::IsDefaultProfileImageURL(const std::string
& url
) {
190 GURL
image_url_object(url
);
191 DCHECK(image_url_object
.is_valid());
192 VLOG(1) << "URL to check for default image: " << image_url_object
.spec();
193 std::vector
<std::string
> path_components
;
194 base::SplitString(image_url_object
.path(),
198 if (path_components
.size() < kProfileImageURLPathComponentsCount
)
201 const std::string
& photo_id
= path_components
[kPhotoIdPathComponentIndex
];
202 const std::string
& photo_version
=
203 path_components
[kPhotoVersionPathComponentIndex
];
205 // Check that the ID and version match the default Picasa profile photo.
206 return photo_id
== kPicasaPhotoId
&&
207 photo_version
== kDefaultPicasaPhotoVersion
;
210 ProfileDownloader::ProfileDownloader(ProfileDownloaderDelegate
* delegate
)
211 : OAuth2TokenService::Consumer("profile_downloader"),
213 picture_status_(PICTURE_FAILED
) {
217 void ProfileDownloader::Start() {
218 StartForAccount(std::string());
221 void ProfileDownloader::StartForAccount(const std::string
& account_id
) {
222 VLOG(1) << "Starting profile downloader...";
223 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
225 ProfileOAuth2TokenService
* service
=
226 ProfileOAuth2TokenServiceFactory::GetForProfile(
227 delegate_
->GetBrowserProfile());
229 // This can happen in some test paths.
230 LOG(WARNING
) << "User has no token service";
231 delegate_
->OnProfileDownloadFailure(
232 this, ProfileDownloaderDelegate::TOKEN_ERROR
);
237 account_id
.empty() ? service
->GetPrimaryAccountId() : account_id
;
238 if (service
->RefreshTokenIsAvailable(account_id_
)) {
239 StartFetchingOAuth2AccessToken();
241 service
->AddObserver(this);
245 base::string16
ProfileDownloader::GetProfileFullName() const {
246 return profile_full_name_
;
249 base::string16
ProfileDownloader::GetProfileGivenName() const {
250 return profile_given_name_
;
253 std::string
ProfileDownloader::GetProfileLocale() const {
254 return profile_locale_
;
257 SkBitmap
ProfileDownloader::GetProfilePicture() const {
258 return profile_picture_
;
261 ProfileDownloader::PictureStatus
ProfileDownloader::GetProfilePictureStatus()
263 return picture_status_
;
266 std::string
ProfileDownloader::GetProfilePictureURL() const {
270 void ProfileDownloader::StartFetchingImage() {
271 VLOG(1) << "Fetching user entry with token: " << auth_token_
;
272 user_entry_fetcher_
.reset(net::URLFetcher::Create(
273 GURL(kUserEntryURL
), net::URLFetcher::GET
, this));
274 user_entry_fetcher_
->SetRequestContext(
275 delegate_
->GetBrowserProfile()->GetRequestContext());
276 user_entry_fetcher_
->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES
|
277 net::LOAD_DO_NOT_SAVE_COOKIES
);
278 if (!auth_token_
.empty()) {
279 user_entry_fetcher_
->SetExtraRequestHeaders(
280 base::StringPrintf(kAuthorizationHeader
, auth_token_
.c_str()));
282 user_entry_fetcher_
->Start();
285 void ProfileDownloader::StartFetchingOAuth2AccessToken() {
286 Profile
* profile
= delegate_
->GetBrowserProfile();
287 OAuth2TokenService::ScopeSet scopes
;
288 scopes
.insert(kAPIScope
);
289 ProfileOAuth2TokenService
* token_service
=
290 ProfileOAuth2TokenServiceFactory::GetForProfile(profile
);
291 oauth2_access_token_request_
= token_service
->StartRequest(
292 account_id_
, scopes
, this);
295 ProfileDownloader::~ProfileDownloader() {
296 // Ensures PO2TS observation is cleared when ProfileDownloader is destructed
297 // before refresh token is available.
298 ProfileOAuth2TokenService
* service
=
299 ProfileOAuth2TokenServiceFactory::GetForProfile(
300 delegate_
->GetBrowserProfile());
302 service
->RemoveObserver(this);
305 void ProfileDownloader::OnURLFetchComplete(const net::URLFetcher
* source
) {
306 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
308 source
->GetResponseAsString(&data
);
310 source
->GetStatus().status() != net::URLRequestStatus::SUCCESS
;
311 if (network_error
|| source
->GetResponseCode() != 200) {
312 LOG(WARNING
) << "Fetching profile data failed";
313 DVLOG(1) << " Status: " << source
->GetStatus().status();
314 DVLOG(1) << " Error: " << source
->GetStatus().error();
315 DVLOG(1) << " Response code: " << source
->GetResponseCode();
316 DVLOG(1) << " Url: " << source
->GetURL().spec();
317 delegate_
->OnProfileDownloadFailure(this, network_error
?
318 ProfileDownloaderDelegate::NETWORK_ERROR
:
319 ProfileDownloaderDelegate::SERVICE_ERROR
);
323 if (source
== user_entry_fetcher_
.get()) {
324 std::string image_url
;
325 if (!ParseProfileJSON(data
,
327 &profile_given_name_
,
329 delegate_
->GetDesiredImageSideLength(),
331 delegate_
->OnProfileDownloadFailure(
332 this, ProfileDownloaderDelegate::SERVICE_ERROR
);
335 if (!delegate_
->NeedsProfilePicture()) {
336 VLOG(1) << "Skipping profile picture download";
337 delegate_
->OnProfileDownloadSuccess(this);
340 if (IsDefaultProfileImageURL(image_url
)) {
341 VLOG(1) << "User has default profile picture";
342 picture_status_
= PICTURE_DEFAULT
;
343 delegate_
->OnProfileDownloadSuccess(this);
346 if (!image_url
.empty() && image_url
== delegate_
->GetCachedPictureURL()) {
347 VLOG(1) << "Picture URL matches cached picture URL";
348 picture_status_
= PICTURE_CACHED
;
349 delegate_
->OnProfileDownloadSuccess(this);
352 VLOG(1) << "Fetching profile image from " << image_url
;
353 picture_url_
= image_url
;
354 profile_image_fetcher_
.reset(net::URLFetcher::Create(
355 GURL(image_url
), net::URLFetcher::GET
, this));
356 profile_image_fetcher_
->SetRequestContext(
357 delegate_
->GetBrowserProfile()->GetRequestContext());
358 profile_image_fetcher_
->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES
|
359 net::LOAD_DO_NOT_SAVE_COOKIES
);
360 if (!auth_token_
.empty()) {
361 profile_image_fetcher_
->SetExtraRequestHeaders(
362 base::StringPrintf(kAuthorizationHeader
, auth_token_
.c_str()));
364 profile_image_fetcher_
->Start();
365 } else if (source
== profile_image_fetcher_
.get()) {
366 VLOG(1) << "Decoding the image...";
367 scoped_refptr
<ImageDecoder
> image_decoder
= new ImageDecoder(
368 this, data
, ImageDecoder::DEFAULT_CODEC
);
369 scoped_refptr
<base::MessageLoopProxy
> task_runner
=
370 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI
);
371 image_decoder
->Start(task_runner
);
375 void ProfileDownloader::OnImageDecoded(const ImageDecoder
* decoder
,
376 const SkBitmap
& decoded_image
) {
377 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
378 int image_size
= delegate_
->GetDesiredImageSideLength();
379 profile_picture_
= skia::ImageOperations::Resize(
381 skia::ImageOperations::RESIZE_BEST
,
384 picture_status_
= PICTURE_SUCCESS
;
385 delegate_
->OnProfileDownloadSuccess(this);
388 void ProfileDownloader::OnDecodeImageFailed(const ImageDecoder
* decoder
) {
389 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
390 delegate_
->OnProfileDownloadFailure(
391 this, ProfileDownloaderDelegate::IMAGE_DECODE_FAILED
);
394 void ProfileDownloader::OnRefreshTokenAvailable(const std::string
& account_id
) {
395 ProfileOAuth2TokenService
* service
=
396 ProfileOAuth2TokenServiceFactory::GetForProfile(
397 delegate_
->GetBrowserProfile());
398 if (account_id
!= account_id_
)
401 service
->RemoveObserver(this);
402 StartFetchingOAuth2AccessToken();
405 // Callback for OAuth2TokenService::Request on success. |access_token| is the
406 // token used to start fetching user data.
407 void ProfileDownloader::OnGetTokenSuccess(
408 const OAuth2TokenService::Request
* request
,
409 const std::string
& access_token
,
410 const base::Time
& expiration_time
) {
411 DCHECK_EQ(request
, oauth2_access_token_request_
.get());
412 oauth2_access_token_request_
.reset();
413 auth_token_
= access_token
;
414 StartFetchingImage();
417 // Callback for OAuth2TokenService::Request on failure.
418 void ProfileDownloader::OnGetTokenFailure(
419 const OAuth2TokenService::Request
* request
,
420 const GoogleServiceAuthError
& error
) {
421 DCHECK_EQ(request
, oauth2_access_token_request_
.get());
422 oauth2_access_token_request_
.reset();
423 LOG(WARNING
) << "ProfileDownloader: token request using refresh token failed:"
425 delegate_
->OnProfileDownloadFailure(
426 this, ProfileDownloaderDelegate::TOKEN_ERROR
);