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 "content/public/browser/browser_thread.h"
25 #include "google_apis/gaia/gaia_constants.h"
26 #include "google_apis/gaia/gaia_urls.h"
27 #include "net/base/load_flags.h"
28 #include "net/url_request/url_fetcher.h"
29 #include "net/url_request/url_request_status.h"
30 #include "skia/ext/image_operations.h"
33 using content::BrowserThread
;
37 // Template for optional authorization header when using an OAuth access token.
38 const char kAuthorizationHeader
[] =
39 "Authorization: Bearer %s";
41 // Path in JSON dictionary to user's photo thumbnail URL.
42 const char kPhotoThumbnailURLPath
[] = "image.url";
44 // From the user info API, this field corresponds to the full name of the user.
45 const char kFullNamePath
[] = "displayName";
47 const char kGivenNamePath
[] = "name.givenName";
49 // Path in JSON dictionary to user's preferred locale.
50 const char kLocalePath
[] = "language";
52 // Path format for specifying thumbnail's size.
53 const char kThumbnailSizeFormat
[] = "s%d-c";
54 // Default thumbnail size.
55 const int kDefaultThumbnailSize
= 64;
57 // Separator of URL path components.
58 const char kURLPathSeparator
= '/';
60 // Photo ID of the Picasa Web Albums profile picture (base64 of 0).
61 const char kPicasaPhotoId
[] = "AAAAAAAAAAA";
63 // Photo version of the default PWA profile picture (base64 of 1).
64 const char kDefaultPicasaPhotoVersion
[] = "AAAAAAAAAAE";
66 // The minimum number of path components in profile picture URL.
67 const size_t kProfileImageURLPathComponentsCount
= 6;
69 // Index of path component with photo ID.
70 const int kPhotoIdPathComponentIndex
= 2;
72 // Index of path component with photo version.
73 const int kPhotoVersionPathComponentIndex
= 3;
75 // Given an image URL this function builds a new URL set to |size|.
76 // For example, if |size| was set to 256 and |old_url| was either:
77 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/photo.jpg
79 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/s64-c/photo.jpg
80 // then return value in |new_url| would be:
81 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/s256-c/photo.jpg
82 bool GetImageURLWithSize(const GURL
& old_url
, int size
, GURL
* new_url
) {
84 std::vector
<std::string
> components
;
85 base::SplitString(old_url
.path(), kURLPathSeparator
, &components
);
86 if (components
.size() == 0)
89 const std::string
& old_spec
= old_url
.spec();
90 std::string
default_size_component(
91 base::StringPrintf(kThumbnailSizeFormat
, kDefaultThumbnailSize
));
92 std::string
new_size_component(
93 base::StringPrintf(kThumbnailSizeFormat
, size
));
95 size_t pos
= old_spec
.find(default_size_component
);
96 size_t end
= std::string::npos
;
97 if (pos
!= std::string::npos
) {
98 // The default size is already specified in the URL so it needs to be
99 // replaced with the new size.
100 end
= pos
+ default_size_component
.size();
102 // The default size is not in the URL so try to insert it before the last
104 const std::string
& file_name
= old_url
.ExtractFileName();
105 if (!file_name
.empty()) {
106 pos
= old_spec
.find(file_name
);
111 if (pos
!= std::string::npos
) {
112 std::string new_spec
= old_spec
.substr(0, pos
) + new_size_component
+
113 old_spec
.substr(end
);
114 *new_url
= GURL(new_spec
);
115 return new_url
->is_valid();
118 // We can't set the image size, just use the default size.
125 // Parses the entry response and gets the name and profile image URL.
126 // |data| should be the JSON formatted data return by the response.
127 // Returns false to indicate a parsing error.
128 bool ProfileDownloader::ParseProfileJSON(base::DictionaryValue
* root_dictionary
,
129 base::string16
* full_name
,
130 base::string16
* given_name
,
133 std::string
* profile_locale
) {
137 DCHECK(profile_locale
);
139 *full_name
= base::string16();
140 *given_name
= base::string16();
141 *url
= std::string();
142 *profile_locale
= std::string();
144 root_dictionary
->GetString(kFullNamePath
, full_name
);
145 root_dictionary
->GetString(kGivenNamePath
, given_name
);
146 root_dictionary
->GetString(kLocalePath
, profile_locale
);
148 std::string url_string
;
149 if (root_dictionary
->GetString(kPhotoThumbnailURLPath
, &url_string
)) {
151 if (!GetImageURLWithSize(GURL(url_string
), image_size
, &new_url
)) {
152 LOG(ERROR
) << "GetImageURLWithSize failed for url: " << url_string
;
155 *url
= new_url
.spec();
158 // The profile data is considered valid as long as it has a name or a picture.
159 return !full_name
->empty() || !url
->empty();
163 bool ProfileDownloader::IsDefaultProfileImageURL(const std::string
& url
) {
167 GURL
image_url_object(url
);
168 DCHECK(image_url_object
.is_valid());
169 VLOG(1) << "URL to check for default image: " << image_url_object
.spec();
170 std::vector
<std::string
> path_components
;
171 base::SplitString(image_url_object
.path(),
175 if (path_components
.size() < kProfileImageURLPathComponentsCount
)
178 const std::string
& photo_id
= path_components
[kPhotoIdPathComponentIndex
];
179 const std::string
& photo_version
=
180 path_components
[kPhotoVersionPathComponentIndex
];
182 // Check that the ID and version match the default Picasa profile photo.
183 return photo_id
== kPicasaPhotoId
&&
184 photo_version
== kDefaultPicasaPhotoVersion
;
187 ProfileDownloader::ProfileDownloader(ProfileDownloaderDelegate
* delegate
)
188 : OAuth2TokenService::Consumer("profile_downloader"),
190 picture_status_(PICTURE_FAILED
) {
194 void ProfileDownloader::Start() {
195 StartForAccount(std::string());
198 void ProfileDownloader::StartForAccount(const std::string
& account_id
) {
199 VLOG(1) << "Starting profile downloader...";
200 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
202 ProfileOAuth2TokenService
* service
=
203 ProfileOAuth2TokenServiceFactory::GetForProfile(
204 delegate_
->GetBrowserProfile());
206 // This can happen in some test paths.
207 LOG(WARNING
) << "User has no token service";
208 delegate_
->OnProfileDownloadFailure(
209 this, ProfileDownloaderDelegate::TOKEN_ERROR
);
213 SigninManagerBase
* signin_manager
=
214 SigninManagerFactory::GetForProfile(delegate_
->GetBrowserProfile());
217 signin_manager
->GetAuthenticatedAccountId() : account_id
;
218 if (service
->RefreshTokenIsAvailable(account_id_
)) {
219 StartFetchingOAuth2AccessToken();
221 service
->AddObserver(this);
225 base::string16
ProfileDownloader::GetProfileFullName() const {
226 return profile_full_name_
;
229 base::string16
ProfileDownloader::GetProfileGivenName() const {
230 return profile_given_name_
;
233 std::string
ProfileDownloader::GetProfileLocale() const {
234 return profile_locale_
;
237 SkBitmap
ProfileDownloader::GetProfilePicture() const {
238 return profile_picture_
;
241 ProfileDownloader::PictureStatus
ProfileDownloader::GetProfilePictureStatus()
243 return picture_status_
;
246 std::string
ProfileDownloader::GetProfilePictureURL() const {
250 void ProfileDownloader::StartFetchingImage() {
251 DCHECK(!auth_token_
.empty());
252 VLOG(1) << "Fetching user entry with token: " << auth_token_
;
253 gaia_client_
.reset(new gaia::GaiaOAuthClient(
254 delegate_
->GetBrowserProfile()->GetRequestContext()));
255 gaia_client_
->GetUserInfo(auth_token_
, 0, this);
258 void ProfileDownloader::StartFetchingOAuth2AccessToken() {
259 Profile
* profile
= delegate_
->GetBrowserProfile();
260 OAuth2TokenService::ScopeSet scopes
;
261 scopes
.insert(GaiaConstants::kGoogleUserInfoProfile
);
262 ProfileOAuth2TokenService
* token_service
=
263 ProfileOAuth2TokenServiceFactory::GetForProfile(profile
);
264 oauth2_access_token_request_
= token_service
->StartRequest(
265 account_id_
, scopes
, this);
268 ProfileDownloader::~ProfileDownloader() {
269 // Ensures PO2TS observation is cleared when ProfileDownloader is destructed
270 // before refresh token is available.
271 ProfileOAuth2TokenService
* service
=
272 ProfileOAuth2TokenServiceFactory::GetForProfile(
273 delegate_
->GetBrowserProfile());
275 service
->RemoveObserver(this);
278 void ProfileDownloader::OnGetUserInfoResponse(
279 scoped_ptr
<base::DictionaryValue
> user_info
) {
280 std::string image_url
;
281 if (!ParseProfileJSON(user_info
.get(),
283 &profile_given_name_
,
285 delegate_
->GetDesiredImageSideLength(),
287 delegate_
->OnProfileDownloadFailure(
288 this, ProfileDownloaderDelegate::SERVICE_ERROR
);
291 if (!delegate_
->NeedsProfilePicture()) {
292 VLOG(1) << "Skipping profile picture download";
293 delegate_
->OnProfileDownloadSuccess(this);
296 if (IsDefaultProfileImageURL(image_url
)) {
297 VLOG(1) << "User has default profile picture";
298 picture_status_
= PICTURE_DEFAULT
;
299 delegate_
->OnProfileDownloadSuccess(this);
302 if (!image_url
.empty() && image_url
== delegate_
->GetCachedPictureURL()) {
303 VLOG(1) << "Picture URL matches cached picture URL";
304 picture_status_
= PICTURE_CACHED
;
305 delegate_
->OnProfileDownloadSuccess(this);
308 VLOG(1) << "Fetching profile image from " << image_url
;
309 picture_url_
= image_url
;
310 profile_image_fetcher_
.reset(net::URLFetcher::Create(
311 GURL(image_url
), net::URLFetcher::GET
, this));
312 profile_image_fetcher_
->SetRequestContext(
313 delegate_
->GetBrowserProfile()->GetRequestContext());
314 profile_image_fetcher_
->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES
|
315 net::LOAD_DO_NOT_SAVE_COOKIES
);
316 if (!auth_token_
.empty()) {
317 profile_image_fetcher_
->SetExtraRequestHeaders(
318 base::StringPrintf(kAuthorizationHeader
, auth_token_
.c_str()));
320 profile_image_fetcher_
->Start();
323 void ProfileDownloader::OnOAuthError() {
324 LOG(WARNING
) << "OnOAuthError: Fetching profile data failed";
325 delegate_
->OnProfileDownloadFailure(
326 this, ProfileDownloaderDelegate::SERVICE_ERROR
);
329 void ProfileDownloader::OnNetworkError(int response_code
) {
330 LOG(WARNING
) << "OnNetworkError: Fetching profile data failed";
331 DVLOG(1) << " Response code: " << response_code
;
332 delegate_
->OnProfileDownloadFailure(
333 this, ProfileDownloaderDelegate::NETWORK_ERROR
);
336 void ProfileDownloader::OnURLFetchComplete(const net::URLFetcher
* source
) {
337 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
339 source
->GetResponseAsString(&data
);
341 source
->GetStatus().status() != net::URLRequestStatus::SUCCESS
;
342 if (network_error
|| source
->GetResponseCode() != 200) {
343 LOG(WARNING
) << "Fetching profile data failed";
344 DVLOG(1) << " Status: " << source
->GetStatus().status();
345 DVLOG(1) << " Error: " << source
->GetStatus().error();
346 DVLOG(1) << " Response code: " << source
->GetResponseCode();
347 DVLOG(1) << " Url: " << source
->GetURL().spec();
348 delegate_
->OnProfileDownloadFailure(this, network_error
?
349 ProfileDownloaderDelegate::NETWORK_ERROR
:
350 ProfileDownloaderDelegate::SERVICE_ERROR
);
354 VLOG(1) << "Decoding the image...";
355 scoped_refptr
<ImageDecoder
> image_decoder
= new ImageDecoder(
356 this, data
, ImageDecoder::DEFAULT_CODEC
);
357 scoped_refptr
<base::MessageLoopProxy
> task_runner
=
358 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::UI
);
359 image_decoder
->Start(task_runner
);
362 void ProfileDownloader::OnImageDecoded(const ImageDecoder
* decoder
,
363 const SkBitmap
& decoded_image
) {
364 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
365 int image_size
= delegate_
->GetDesiredImageSideLength();
366 profile_picture_
= skia::ImageOperations::Resize(
368 skia::ImageOperations::RESIZE_BEST
,
371 picture_status_
= PICTURE_SUCCESS
;
372 delegate_
->OnProfileDownloadSuccess(this);
375 void ProfileDownloader::OnDecodeImageFailed(const ImageDecoder
* decoder
) {
376 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
377 delegate_
->OnProfileDownloadFailure(
378 this, ProfileDownloaderDelegate::IMAGE_DECODE_FAILED
);
381 void ProfileDownloader::OnRefreshTokenAvailable(const std::string
& account_id
) {
382 ProfileOAuth2TokenService
* service
=
383 ProfileOAuth2TokenServiceFactory::GetForProfile(
384 delegate_
->GetBrowserProfile());
385 if (account_id
!= account_id_
)
388 service
->RemoveObserver(this);
389 StartFetchingOAuth2AccessToken();
392 // Callback for OAuth2TokenService::Request on success. |access_token| is the
393 // token used to start fetching user data.
394 void ProfileDownloader::OnGetTokenSuccess(
395 const OAuth2TokenService::Request
* request
,
396 const std::string
& access_token
,
397 const base::Time
& expiration_time
) {
398 DCHECK_EQ(request
, oauth2_access_token_request_
.get());
399 oauth2_access_token_request_
.reset();
400 auth_token_
= access_token
;
401 StartFetchingImage();
404 // Callback for OAuth2TokenService::Request on failure.
405 void ProfileDownloader::OnGetTokenFailure(
406 const OAuth2TokenService::Request
* request
,
407 const GoogleServiceAuthError
& error
) {
408 DCHECK_EQ(request
, oauth2_access_token_request_
.get());
409 oauth2_access_token_request_
.reset();
410 LOG(WARNING
) << "ProfileDownloader: token request using refresh token failed:"
412 delegate_
->OnProfileDownloadFailure(
413 this, ProfileDownloaderDelegate::TOKEN_ERROR
);