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/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_tracker_service_factory.h"
22 #include "chrome/browser/signin/chrome_signin_client_factory.h"
23 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
24 #include "chrome/browser/signin/signin_manager_factory.h"
25 #include "components/signin/core/browser/profile_oauth2_token_service.h"
26 #include "components/signin/core/browser/signin_client.h"
27 #include "components/signin/core/browser/signin_manager.h"
28 #include "components/signin/core/common/profile_management_switches.h"
29 #include "content/public/browser/browser_thread.h"
30 #include "google_apis/gaia/gaia_constants.h"
31 #include "net/base/load_flags.h"
32 #include "net/url_request/url_fetcher.h"
33 #include "net/url_request/url_request_status.h"
34 #include "skia/ext/image_operations.h"
37 using content::BrowserThread
;
41 // Template for optional authorization header when using an OAuth access token.
42 const char kAuthorizationHeader
[] =
43 "Authorization: Bearer %s";
45 // Path format for specifying thumbnail's size.
46 const char kThumbnailSizeFormat
[] = "s%d-c";
47 // Default thumbnail size.
48 const int kDefaultThumbnailSize
= 64;
50 // Separator of URL path components.
51 const char kURLPathSeparator
= '/';
53 // Photo ID of the Picasa Web Albums profile picture (base64 of 0).
54 const char kPicasaPhotoId
[] = "AAAAAAAAAAA";
56 // Photo version of the default PWA profile picture (base64 of 1).
57 const char kDefaultPicasaPhotoVersion
[] = "AAAAAAAAAAE";
59 // The minimum number of path components in profile picture URL.
60 const size_t kProfileImageURLPathComponentsCount
= 6;
62 // Index of path component with photo ID.
63 const int kPhotoIdPathComponentIndex
= 2;
65 // Index of path component with photo version.
66 const int kPhotoVersionPathComponentIndex
= 3;
68 // Given an image URL this function builds a new URL set to |size|.
69 // For example, if |size| was set to 256 and |old_url| was either:
70 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/photo.jpg
72 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/s64-c/photo.jpg
73 // then return value in |new_url| would be:
74 // https://example.com/--Abc/AAAAAAAAAAI/AAAAAAAAACQ/Efg/s256-c/photo.jpg
75 bool GetImageURLWithSize(const GURL
& old_url
, int size
, GURL
* new_url
) {
77 std::vector
<std::string
> components
= base::SplitString(
78 old_url
.path(), std::string(1, kURLPathSeparator
),
79 base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
80 if (components
.size() == 0)
83 const std::string
& old_spec
= old_url
.spec();
84 std::string
default_size_component(
85 base::StringPrintf(kThumbnailSizeFormat
, kDefaultThumbnailSize
));
86 std::string
new_size_component(
87 base::StringPrintf(kThumbnailSizeFormat
, size
));
89 size_t pos
= old_spec
.find(default_size_component
);
90 size_t end
= std::string::npos
;
91 if (pos
!= std::string::npos
) {
92 // The default size is already specified in the URL so it needs to be
93 // replaced with the new size.
94 end
= pos
+ default_size_component
.size();
96 // The default size is not in the URL so try to insert it before the last
98 const std::string
& file_name
= old_url
.ExtractFileName();
99 if (!file_name
.empty()) {
100 pos
= old_spec
.find(file_name
);
105 if (pos
!= std::string::npos
) {
106 std::string new_spec
= old_spec
.substr(0, pos
) + new_size_component
+
107 old_spec
.substr(end
);
108 *new_url
= GURL(new_spec
);
109 return new_url
->is_valid();
112 // We can't set the image size, just use the default size.
120 bool ProfileDownloader::IsDefaultProfileImageURL(const std::string
& url
) {
124 GURL
image_url_object(url
);
125 DCHECK(image_url_object
.is_valid());
126 VLOG(1) << "URL to check for default image: " << image_url_object
.spec();
127 std::vector
<std::string
> path_components
= base::SplitString(
128 image_url_object
.path(), std::string(1, kURLPathSeparator
),
129 base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
131 if (path_components
.size() < kProfileImageURLPathComponentsCount
)
134 const std::string
& photo_id
= path_components
[kPhotoIdPathComponentIndex
];
135 const std::string
& photo_version
=
136 path_components
[kPhotoVersionPathComponentIndex
];
138 // Check that the ID and version match the default Picasa profile photo.
139 return photo_id
== kPicasaPhotoId
&&
140 photo_version
== kDefaultPicasaPhotoVersion
;
143 ProfileDownloader::ProfileDownloader(ProfileDownloaderDelegate
* delegate
)
144 : OAuth2TokenService::Consumer("profile_downloader"),
146 picture_status_(PICTURE_FAILED
),
147 account_tracker_service_(
148 AccountTrackerServiceFactory::GetForProfile(
149 delegate_
->GetBrowserProfile())),
150 waiting_for_account_info_(false) {
152 account_tracker_service_
->AddObserver(this);
155 void ProfileDownloader::Start() {
156 StartForAccount(std::string());
159 void ProfileDownloader::StartForAccount(const std::string
& account_id
) {
160 VLOG(1) << "Starting profile downloader...";
161 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
163 ProfileOAuth2TokenService
* service
=
164 ProfileOAuth2TokenServiceFactory::GetForProfile(
165 delegate_
->GetBrowserProfile());
167 // This can happen in some test paths.
168 LOG(WARNING
) << "User has no token service";
169 delegate_
->OnProfileDownloadFailure(
170 this, ProfileDownloaderDelegate::TOKEN_ERROR
);
174 SigninManagerBase
* signin_manager
=
175 SigninManagerFactory::GetForProfile(delegate_
->GetBrowserProfile());
178 signin_manager
->GetAuthenticatedAccountId() : account_id
;
179 if (service
->RefreshTokenIsAvailable(account_id_
))
180 StartFetchingOAuth2AccessToken();
182 service
->AddObserver(this);
185 base::string16
ProfileDownloader::GetProfileHostedDomain() const {
186 return base::UTF8ToUTF16(account_info_
.hosted_domain
);
189 base::string16
ProfileDownloader::GetProfileFullName() const {
190 return base::UTF8ToUTF16(account_info_
.full_name
);
193 base::string16
ProfileDownloader::GetProfileGivenName() const {
194 return base::UTF8ToUTF16(account_info_
.given_name
);
197 std::string
ProfileDownloader::GetProfileLocale() const {
198 return account_info_
.locale
;
201 SkBitmap
ProfileDownloader::GetProfilePicture() const {
202 return profile_picture_
;
205 ProfileDownloader::PictureStatus
ProfileDownloader::GetProfilePictureStatus()
207 return picture_status_
;
210 std::string
ProfileDownloader::GetProfilePictureURL() const {
212 if (GetImageURLWithSize(GURL(account_info_
.picture_url
),
213 delegate_
->GetDesiredImageSideLength(),
217 return account_info_
.picture_url
;
220 void ProfileDownloader::StartFetchingImage() {
221 VLOG(1) << "Fetching user entry with token: " << auth_token_
;
222 account_info_
= account_tracker_service_
->GetAccountInfo(account_id_
);
224 if (account_info_
.IsValid())
227 waiting_for_account_info_
= true;
230 void ProfileDownloader::StartFetchingOAuth2AccessToken() {
231 Profile
* profile
= delegate_
->GetBrowserProfile();
232 OAuth2TokenService::ScopeSet scopes
;
233 scopes
.insert(GaiaConstants::kGoogleUserInfoProfile
);
234 // Increase scope to get hd attribute to determine if lock should be enabled.
235 if (switches::IsNewProfileManagement())
236 scopes
.insert(GaiaConstants::kGoogleUserInfoEmail
);
237 ProfileOAuth2TokenService
* token_service
=
238 ProfileOAuth2TokenServiceFactory::GetForProfile(profile
);
239 oauth2_access_token_request_
= token_service
->StartRequest(
240 account_id_
, scopes
, this);
243 ProfileDownloader::~ProfileDownloader() {
244 // Ensures PO2TS observation is cleared when ProfileDownloader is destructed
245 // before refresh token is available.
246 ProfileOAuth2TokenService
* service
=
247 ProfileOAuth2TokenServiceFactory::GetForProfile(
248 delegate_
->GetBrowserProfile());
250 service
->RemoveObserver(this);
252 account_tracker_service_
->RemoveObserver(this);
255 void ProfileDownloader::FetchImageData() {
256 DCHECK(account_info_
.IsValid());
257 std::string image_url_with_size
= GetProfilePictureURL();
259 if (!delegate_
->NeedsProfilePicture()) {
260 VLOG(1) << "Skipping profile picture download";
261 delegate_
->OnProfileDownloadSuccess(this);
264 if (IsDefaultProfileImageURL(image_url_with_size
)) {
265 VLOG(1) << "User has default profile picture";
266 picture_status_
= PICTURE_DEFAULT
;
267 delegate_
->OnProfileDownloadSuccess(this);
270 if (!image_url_with_size
.empty() &&
271 image_url_with_size
== delegate_
->GetCachedPictureURL()) {
272 VLOG(1) << "Picture URL matches cached picture URL";
273 picture_status_
= PICTURE_CACHED
;
274 delegate_
->OnProfileDownloadSuccess(this);
278 VLOG(1) << "Fetching profile image from " << image_url_with_size
;
279 profile_image_fetcher_
= net::URLFetcher::Create(
280 GURL(image_url_with_size
), net::URLFetcher::GET
, this);
281 profile_image_fetcher_
->SetRequestContext(
282 delegate_
->GetBrowserProfile()->GetRequestContext());
283 profile_image_fetcher_
->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES
|
284 net::LOAD_DO_NOT_SAVE_COOKIES
);
286 if (!auth_token_
.empty()) {
287 profile_image_fetcher_
->SetExtraRequestHeaders(
288 base::StringPrintf(kAuthorizationHeader
, auth_token_
.c_str()));
291 profile_image_fetcher_
->Start();
294 void ProfileDownloader::OnURLFetchComplete(const net::URLFetcher
* source
) {
295 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
297 source
->GetResponseAsString(&data
);
299 source
->GetStatus().status() != net::URLRequestStatus::SUCCESS
;
300 if (network_error
|| source
->GetResponseCode() != 200) {
301 LOG(WARNING
) << "Fetching profile data failed";
302 DVLOG(1) << " Status: " << source
->GetStatus().status();
303 DVLOG(1) << " Error: " << source
->GetStatus().error();
304 DVLOG(1) << " Response code: " << source
->GetResponseCode();
305 DVLOG(1) << " Url: " << source
->GetURL().spec();
306 profile_image_fetcher_
.reset();
307 delegate_
->OnProfileDownloadFailure(this, network_error
?
308 ProfileDownloaderDelegate::NETWORK_ERROR
:
309 ProfileDownloaderDelegate::SERVICE_ERROR
);
311 profile_image_fetcher_
.reset();
312 VLOG(1) << "Decoding the image...";
313 ImageDecoder::Start(this, data
);
317 void ProfileDownloader::OnImageDecoded(const SkBitmap
& decoded_image
) {
318 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
319 int image_size
= delegate_
->GetDesiredImageSideLength();
320 profile_picture_
= skia::ImageOperations::Resize(
322 skia::ImageOperations::RESIZE_BEST
,
325 picture_status_
= PICTURE_SUCCESS
;
326 delegate_
->OnProfileDownloadSuccess(this);
329 void ProfileDownloader::OnDecodeImageFailed() {
330 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
331 delegate_
->OnProfileDownloadFailure(
332 this, ProfileDownloaderDelegate::IMAGE_DECODE_FAILED
);
335 void ProfileDownloader::OnRefreshTokenAvailable(const std::string
& account_id
) {
336 ProfileOAuth2TokenService
* service
=
337 ProfileOAuth2TokenServiceFactory::GetForProfile(
338 delegate_
->GetBrowserProfile());
339 if (account_id
!= account_id_
)
342 service
->RemoveObserver(this);
343 StartFetchingOAuth2AccessToken();
346 // Callback for OAuth2TokenService::Request on success. |access_token| is the
347 // token used to start fetching user data.
348 void ProfileDownloader::OnGetTokenSuccess(
349 const OAuth2TokenService::Request
* request
,
350 const std::string
& access_token
,
351 const base::Time
& expiration_time
) {
352 DCHECK_EQ(request
, oauth2_access_token_request_
.get());
353 oauth2_access_token_request_
.reset();
354 auth_token_
= access_token
;
355 StartFetchingImage();
358 // Callback for OAuth2TokenService::Request on failure.
359 void ProfileDownloader::OnGetTokenFailure(
360 const OAuth2TokenService::Request
* request
,
361 const GoogleServiceAuthError
& error
) {
362 DCHECK_EQ(request
, oauth2_access_token_request_
.get());
363 oauth2_access_token_request_
.reset();
364 LOG(WARNING
) << "ProfileDownloader: token request using refresh token failed:"
366 delegate_
->OnProfileDownloadFailure(
367 this, ProfileDownloaderDelegate::TOKEN_ERROR
);
370 void ProfileDownloader::OnAccountUpdated(
371 const AccountTrackerService::AccountInfo
& info
) {
372 if (info
.account_id
== account_id_
&& info
.IsValid()) {
373 account_info_
= info
;
375 // If the StartFetchingImage was called before we had valid info, the
376 // downloader has been waiting so we need to fetch the image data now.
377 if (waiting_for_account_info_
) {
379 waiting_for_account_info_
= false;