File: ambient_client_impl.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (250 lines) | stat: -rw-r--r-- 9,072 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/ambient/ambient_client_impl.h"

#include <string>
#include <utility>

#include "ash/constants/ash_features.h"
#include "ash/public/cpp/ambient/ambient_prefs.h"
#include "ash/public/cpp/image_downloader.h"
#include "base/check.h"
#include "base/functional/callback.h"
#include "chrome/browser/ash/login/demo_mode/demo_session.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "chrome/common/channel_info.h"
#include "chromeos/ash/components/browser_context_helper/browser_context_helper.h"
#include "components/account_id/account_id.h"
#include "components/prefs/pref_service.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/identity_manager/access_token_fetcher.h"
#include "components/signin/public/identity_manager/access_token_info.h"
#include "components/signin/public/identity_manager/account_info.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/scope_set.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "components/version_info/channel.h"
#include "content/public/browser/device_service.h"
#include "content/public/browser/storage_partition.h"
#include "google_apis/gaia/gaia_auth_util.h"
#include "google_apis/gaia/gaia_id.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "net/http/http_request_headers.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"

namespace {

constexpr char kPhotosOAuthScope[] = "https://www.googleapis.com/auth/photos";
constexpr char kBackdropOAuthScope[] =
    "https://www.googleapis.com/auth/cast.backdrop";

const user_manager::User* GetActiveUser() {
  return user_manager::UserManager::Get()->GetActiveUser();
}

const user_manager::User* GetPrimaryUser() {
  return user_manager::UserManager::Get()->GetPrimaryUser();
}

constexpr net::NetworkTrafficAnnotationTag kAmbientClientNetworkTag =
    net::DefineNetworkTrafficAnnotation("ambient_client", R"(
        semantics {
          sender: "Ambient photo"
          description:
            "Get ambient photo from url to store limited number of photos in "
            "the device cache. This is used to show the screensaver when the "
            "user is idle. The url can be Backdrop service to provide pictures"
            " from internal gallery, weather/time photos served by Google, or "
            "user selected album from Google photos."
          trigger:
            "Triggered by a photo refresh timer, after the device has been "
            "idle and the battery is charging."
          data: "None."
          destination: GOOGLE_OWNED_SERVICE
        }
        policy {
         cookies_allowed: NO
         setting:
           "This feature is off by default and can be overridden by users."
         policy_exception_justification:
           "This feature is set by user settings.ambient_mode.enabled pref. "
           "The user setting is per device and cannot be overriden by admin."
        })");

Profile* GetProfileForActiveUser() {
  const user_manager::User* const active_user = GetActiveUser();
  DCHECK(active_user);
  return ash::ProfileHelper::Get()->GetProfileByUser(active_user);
}

bool IsPrimaryUser() {
  return GetActiveUser() == GetPrimaryUser();
}

bool HasPrimaryAccount(const Profile* profile) {
  auto* identity_manager =
      IdentityManagerFactory::GetForProfileIfExists(profile);
  if (!identity_manager)
    return false;

  return identity_manager->HasPrimaryAccount(signin::ConsentLevel::kSignin);
}

bool IsEmailDomainSupported(const user_manager::User* user) {
  const std::string email = user->GetAccountId().GetUserEmail();
  DCHECK(!email.empty());

  constexpr char kGmailDomain[] = "gmail.com";
  constexpr char kGooglemailDomain[] = "googlemail.com";
  return (gaia::ExtractDomainName(email) == kGmailDomain ||
          gaia::ExtractDomainName(email) == kGooglemailDomain ||
          gaia::IsGoogleInternalAccountEmail(email));
}

}  // namespace

AmbientClientImpl::AmbientClientImpl() = default;

AmbientClientImpl::~AmbientClientImpl() = default;

bool AmbientClientImpl::IsAmbientModeAllowed() {
  if (is_allowed_for_testing_.has_value()) {
    return is_allowed_for_testing_.value();
  }

  if (ash::DemoSession::IsDeviceInDemoMode())
    return false;

  const user_manager::User* const active_user = GetActiveUser();
  if (!active_user || !active_user->HasGaiaAccount())
    return false;

  if (!IsPrimaryUser())
    return false;

  // When this check is removed to start supporting enterprise users,
  // please update kAmbientClientNetworkTag and network annotation tags
  // in ash/ambient package to reflect that this is an enterprise feature.
  if (!IsEmailDomainSupported(active_user))
    return false;

  auto* profile = GetProfileForActiveUser();
  if (!profile)
    return false;

  // Primary account might be missing during unittests.
  if (!HasPrimaryAccount(profile))
    return false;

  if (profile->IsOffTheRecord())
    return false;

  return true;
}

void AmbientClientImpl::SetAmbientModeAllowedForTesting(bool allowed) {
  is_allowed_for_testing_ = allowed;
}

void AmbientClientImpl::RequestAccessToken(GetAccessTokenCallback callback) {
  auto* profile = GetProfileForActiveUser();
  DCHECK(profile);

  signin::IdentityManager* identity_manager =
      IdentityManagerFactory::GetForProfile(profile);
  DCHECK(identity_manager);

  CoreAccountInfo account_info =
      identity_manager->GetPrimaryAccountInfo(signin::ConsentLevel::kSignin);
  const signin::ScopeSet scopes{kPhotosOAuthScope, kBackdropOAuthScope};
  auto fetcher_id = base::UnguessableToken::Create();
  auto access_token_fetcher =
      identity_manager->CreateAccessTokenFetcherForAccount(
          account_info.account_id,
          /*oauth_consumer_name=*/"ChromeOS_AmbientMode", scopes,
          base::BindOnce(&AmbientClientImpl::OnGetAccessToken,
                         weak_factory_.GetWeakPtr(), std::move(callback),
                         fetcher_id, account_info.gaia),
          signin::AccessTokenFetcher::Mode::kImmediate);

  token_fetchers_.insert({fetcher_id, std::move(access_token_fetcher)});
}

void AmbientClientImpl::DownloadImage(
    const std::string& url,
    ash::ImageDownloader::DownloadCallback callback) {
  RequestAccessToken(base::BindOnce(
      [](const std::string& url,
         ash::ImageDownloader::DownloadCallback callback, const GaiaId& gaia_id,
         const std::string& access_token, const base::Time& expiration_time) {
        if (access_token.empty()) {
          std::move(callback).Run({});
          return;
        }
        const auto* user = GetActiveUser();
        DCHECK(user);
        net::HttpRequestHeaders headers;
        headers.SetHeader("Authorization", "Bearer " + access_token);
        ash::ImageDownloader::Get()->Download(
            GURL(url), kAmbientClientNetworkTag, user->GetAccountId(), headers,
            std::move(callback));
      },
      url, std::move(callback)));
}

scoped_refptr<network::SharedURLLoaderFactory>
AmbientClientImpl::GetURLLoaderFactory() {
  auto* profile = GetProfileForActiveUser();
  DCHECK(profile);

  return profile->GetURLLoaderFactory();
}

scoped_refptr<network::SharedURLLoaderFactory>
AmbientClientImpl::GetSigninURLLoaderFactory() {
  content::BrowserContext* browser_context =
      ash::BrowserContextHelper::Get()->GetSigninBrowserContext();
  CHECK(browser_context);
  Profile* profile = Profile::FromBrowserContext(browser_context);
  CHECK(profile);
  return profile->GetURLLoaderFactory();
}

void AmbientClientImpl::RequestWakeLockProvider(
    mojo::PendingReceiver<device::mojom::WakeLockProvider> receiver) {
  content::GetDeviceService().BindWakeLockProvider(std::move(receiver));
}

bool AmbientClientImpl::ShouldUseProdServer() {
  if (ash::features::IsAmbientModeDevUseProdEnabled())
    return true;

  auto channel = chrome::GetChannel();
  return channel == version_info::Channel::STABLE ||
         channel == version_info::Channel::BETA;
}

void AmbientClientImpl::OnGetAccessToken(
    GetAccessTokenCallback callback,
    base::UnguessableToken fetcher_id,

    const GaiaId& gaia_id,
    GoogleServiceAuthError error,
    signin::AccessTokenInfo access_token_info) {
  if (error.state() == GoogleServiceAuthError::NONE) {
    std::move(callback).Run(gaia_id, access_token_info.token,
                            access_token_info.expiration_time);
  } else {
    LOG(ERROR) << "Failed to retrieve token, error: " << error.ToString();
    std::move(callback).Run(/*gaia_id=*/GaiaId(),
                            /*access_token=*/std::string(),
                            /*expiration_time=*/base::Time::Now());
  }

  token_fetchers_.erase(fetcher_id);
}