1// Copyright 2014 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/supervised_user/custodian_profile_downloader_service.h"
6
7#include "base/prefs/pref_service.h"
8#include "chrome/browser/profiles/profile.h"
9#include "chrome/common/pref_names.h"
10#include "google_apis/gaia/gaia_auth_util.h"
11
12CustodianProfileDownloaderService::CustodianProfileDownloaderService(
13    Profile* custodian_profile)
14        : custodian_profile_(custodian_profile) {
15}
16
17CustodianProfileDownloaderService::~CustodianProfileDownloaderService() {}
18
19void CustodianProfileDownloaderService::Shutdown() {
20  profile_downloader_.reset();
21}
22
23void CustodianProfileDownloaderService::DownloadProfile(
24    const DownloadProfileCallback& callback) {
25  // The user must be logged in.
26  std::string username = custodian_profile_->GetPrefs()->GetString(
27      prefs::kGoogleServicesUsername);
28  if (username.empty())
29    return;
30
31  download_callback_ = callback;
32  std::string current_email = custodian_profile_->GetProfileName();
33  if (gaia::AreEmailsSame(last_downloaded_profile_email_, current_email)) {
34    // Profile was previously downloaded successfully, use it as it is unlikely
35    // that we will need to download it again.
36    OnProfileDownloadSuccess(profile_downloader_.get());
37    return;
38  }
39  // If another profile download is in progress, drop it. It's not worth
40  // queueing them up, and more likely that the one that hasn't ended yet is
41  // failing somehow than that the new one won't succeed.
42  in_progress_profile_email_ = current_email;
43  profile_downloader_.reset(new ProfileDownloader(this));
44  profile_downloader_->Start();
45}
46
47bool CustodianProfileDownloaderService::NeedsProfilePicture() const {
48  return false;
49}
50
51int CustodianProfileDownloaderService::GetDesiredImageSideLength() const {
52  return 0;
53}
54
55std::string CustodianProfileDownloaderService::GetCachedPictureURL() const {
56  return std::string();
57}
58
59Profile* CustodianProfileDownloaderService::GetBrowserProfile() {
60  DCHECK(custodian_profile_);
61  return custodian_profile_;
62}
63
64void CustodianProfileDownloaderService::OnProfileDownloadSuccess(
65    ProfileDownloader* downloader) {
66  download_callback_.Run(downloader->GetProfileFullName());
67  download_callback_.Reset();
68  last_downloaded_profile_email_ = in_progress_profile_email_;
69}
70
71void CustodianProfileDownloaderService::OnProfileDownloadFailure(
72    ProfileDownloader* downloader,
73    ProfileDownloaderDelegate::FailureReason reason) {
74  // Ignore failures; proceed without the custodian's name.
75  download_callback_.Reset();
76  profile_downloader_.reset();
77}
78