Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / profiles / profile_downloader.cc
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.
4
5 #include "chrome/browser/profiles/profile_downloader.h"
6
7 #include <string>
8 #include <vector>
9
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"
31 #include "url/gurl.h"
32
33 using content::BrowserThread;
34
35 namespace {
36
37 // Template for optional authorization header when using an OAuth access token.
38 const char kAuthorizationHeader[] =
39     "Authorization: Bearer %s";
40
41 // Path in JSON dictionary to user's photo thumbnail URL.
42 const char kPhotoThumbnailURLPath[] = "image.url";
43
44 // From the user info API, this field corresponds to the full name of the user.
45 const char kFullNamePath[] = "displayName";
46
47 const char kGivenNamePath[] = "name.givenName";
48
49 // Path in JSON dictionary to user's preferred locale.
50 const char kLocalePath[] = "language";
51
52 // Path format for specifying thumbnail's size.
53 const char kThumbnailSizeFormat[] = "s%d-c";
54 // Default thumbnail size.
55 const int kDefaultThumbnailSize = 64;
56
57 // Separator of URL path components.
58 const char kURLPathSeparator = '/';
59
60 // Photo ID of the Picasa Web Albums profile picture (base64 of 0).
61 const char kPicasaPhotoId[] = "AAAAAAAAAAA";
62
63 // Photo version of the default PWA profile picture (base64 of 1).
64 const char kDefaultPicasaPhotoVersion[] = "AAAAAAAAAAE";
65
66 // The minimum number of path components in profile picture URL.
67 const size_t kProfileImageURLPathComponentsCount = 6;
68
69 // Index of path component with photo ID.
70 const int kPhotoIdPathComponentIndex = 2;
71
72 // Index of path component with photo version.
73 const int kPhotoVersionPathComponentIndex = 3;
74
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
78 //   or
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) {
83   DCHECK(new_url);
84   std::vector<std::string> components;
85   base::SplitString(old_url.path(), kURLPathSeparator, &components);
86   if (components.size() == 0)
87     return false;
88
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));
94
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();
101   } else {
102     // The default size is not in the URL so try to insert it before the last
103     // component.
104     const std::string& file_name = old_url.ExtractFileName();
105     if (!file_name.empty()) {
106       pos = old_spec.find(file_name);
107       end = pos - 1;
108     }
109   }
110
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();
116   }
117
118   // We can't set the image size, just use the default size.
119   *new_url = old_url;
120   return true;
121 }
122
123 }  // namespace
124
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,
131                                          std::string* url,
132                                          int image_size,
133                                          std::string* profile_locale) {
134   DCHECK(full_name);
135   DCHECK(given_name);
136   DCHECK(url);
137   DCHECK(profile_locale);
138
139   *full_name = base::string16();
140   *given_name = base::string16();
141   *url = std::string();
142   *profile_locale = std::string();
143
144   root_dictionary->GetString(kFullNamePath, full_name);
145   root_dictionary->GetString(kGivenNamePath, given_name);
146   root_dictionary->GetString(kLocalePath, profile_locale);
147
148   std::string url_string;
149   if (root_dictionary->GetString(kPhotoThumbnailURLPath, &url_string)) {
150     GURL new_url;
151     if (!GetImageURLWithSize(GURL(url_string), image_size, &new_url)) {
152       LOG(ERROR) << "GetImageURLWithSize failed for url: " << url_string;
153       return false;
154     }
155     *url = new_url.spec();
156   }
157
158   // The profile data is considered valid as long as it has a name or a picture.
159   return !full_name->empty() || !url->empty();
160 }
161
162 // static
163 bool ProfileDownloader::IsDefaultProfileImageURL(const std::string& url) {
164   if (url.empty())
165     return true;
166
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(),
172                     kURLPathSeparator,
173                     &path_components);
174
175   if (path_components.size() < kProfileImageURLPathComponentsCount)
176     return false;
177
178   const std::string& photo_id = path_components[kPhotoIdPathComponentIndex];
179   const std::string& photo_version =
180       path_components[kPhotoVersionPathComponentIndex];
181
182   // Check that the ID and version match the default Picasa profile photo.
183   return photo_id == kPicasaPhotoId &&
184          photo_version == kDefaultPicasaPhotoVersion;
185 }
186
187 ProfileDownloader::ProfileDownloader(ProfileDownloaderDelegate* delegate)
188     : OAuth2TokenService::Consumer("profile_downloader"),
189       delegate_(delegate),
190       picture_status_(PICTURE_FAILED) {
191   DCHECK(delegate_);
192 }
193
194 void ProfileDownloader::Start() {
195   StartForAccount(std::string());
196 }
197
198 void ProfileDownloader::StartForAccount(const std::string& account_id) {
199   VLOG(1) << "Starting profile downloader...";
200   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
201
202   ProfileOAuth2TokenService* service =
203       ProfileOAuth2TokenServiceFactory::GetForProfile(
204           delegate_->GetBrowserProfile());
205   if (!service) {
206     // This can happen in some test paths.
207     LOG(WARNING) << "User has no token service";
208     delegate_->OnProfileDownloadFailure(
209         this, ProfileDownloaderDelegate::TOKEN_ERROR);
210     return;
211   }
212
213   SigninManagerBase* signin_manager =
214       SigninManagerFactory::GetForProfile(delegate_->GetBrowserProfile());
215   account_id_ =
216       account_id.empty() ?
217           signin_manager->GetAuthenticatedAccountId() : account_id;
218   if (service->RefreshTokenIsAvailable(account_id_)) {
219     StartFetchingOAuth2AccessToken();
220   } else {
221     service->AddObserver(this);
222   }
223 }
224
225 base::string16 ProfileDownloader::GetProfileFullName() const {
226   return profile_full_name_;
227 }
228
229 base::string16 ProfileDownloader::GetProfileGivenName() const {
230   return profile_given_name_;
231 }
232
233 std::string ProfileDownloader::GetProfileLocale() const {
234   return profile_locale_;
235 }
236
237 SkBitmap ProfileDownloader::GetProfilePicture() const {
238   return profile_picture_;
239 }
240
241 ProfileDownloader::PictureStatus ProfileDownloader::GetProfilePictureStatus()
242     const {
243   return picture_status_;
244 }
245
246 std::string ProfileDownloader::GetProfilePictureURL() const {
247   return picture_url_;
248 }
249
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);
256 }
257
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);
266 }
267
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());
274   if (service)
275     service->RemoveObserver(this);
276 }
277
278 void ProfileDownloader::OnGetUserInfoResponse(
279     scoped_ptr<base::DictionaryValue> user_info) {
280     std::string image_url;
281     if (!ParseProfileJSON(user_info.get(),
282                           &profile_full_name_,
283                           &profile_given_name_,
284                           &image_url,
285                           delegate_->GetDesiredImageSideLength(),
286                           &profile_locale_)) {
287       delegate_->OnProfileDownloadFailure(
288           this, ProfileDownloaderDelegate::SERVICE_ERROR);
289       return;
290     }
291     if (!delegate_->NeedsProfilePicture()) {
292       VLOG(1) << "Skipping profile picture download";
293       delegate_->OnProfileDownloadSuccess(this);
294       return;
295     }
296     if (IsDefaultProfileImageURL(image_url)) {
297       VLOG(1) << "User has default profile picture";
298       picture_status_ = PICTURE_DEFAULT;
299       delegate_->OnProfileDownloadSuccess(this);
300       return;
301     }
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);
306       return;
307     }
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()));
319     }
320     profile_image_fetcher_->Start();
321 }
322
323 void ProfileDownloader::OnOAuthError() {
324   LOG(WARNING) << "OnOAuthError: Fetching profile data failed";
325   delegate_->OnProfileDownloadFailure(
326       this, ProfileDownloaderDelegate::SERVICE_ERROR);
327 }
328
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);
334 }
335
336 void ProfileDownloader::OnURLFetchComplete(const net::URLFetcher* source) {
337   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
338   std::string data;
339   source->GetResponseAsString(&data);
340   bool network_error =
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);
351     return;
352   }
353
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);
360 }
361
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(
367       decoded_image,
368       skia::ImageOperations::RESIZE_BEST,
369       image_size,
370       image_size);
371   picture_status_ = PICTURE_SUCCESS;
372   delegate_->OnProfileDownloadSuccess(this);
373 }
374
375 void ProfileDownloader::OnDecodeImageFailed(const ImageDecoder* decoder) {
376   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
377   delegate_->OnProfileDownloadFailure(
378       this, ProfileDownloaderDelegate::IMAGE_DECODE_FAILED);
379 }
380
381 void ProfileDownloader::OnRefreshTokenAvailable(const std::string& account_id) {
382   ProfileOAuth2TokenService* service =
383       ProfileOAuth2TokenServiceFactory::GetForProfile(
384           delegate_->GetBrowserProfile());
385   if (account_id != account_id_)
386     return;
387
388   service->RemoveObserver(this);
389   StartFetchingOAuth2AccessToken();
390 }
391
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();
402 }
403
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:"
411                << error.ToString();
412   delegate_->OnProfileDownloadFailure(
413       this, ProfileDownloaderDelegate::TOKEN_ERROR);
414 }