File: app_time_controller.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 (598 lines) | stat: -rw-r--r-- 22,537 bytes parent folder | download | duplicates (5)
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
// Copyright 2019 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/child_accounts/time_limits/app_time_controller.h"

#include <string>

#include "ash/constants/notifier_catalogs.h"
#include "ash/public/cpp/notification_utils.h"
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/ash/app_list/arc/arc_app_utils.h"
#include "chrome/browser/ash/child_accounts/constants/child_account_constants.h"
#include "chrome/browser/ash/child_accounts/time_limits/app_activity_registry.h"
#include "chrome/browser/ash/child_accounts/time_limits/app_service_wrapper.h"
#include "chrome/browser/ash/child_accounts/time_limits/app_time_limit_utils.h"
#include "chrome/browser/ash/child_accounts/time_limits/app_time_limits_allowlist_policy_wrapper.h"
#include "chrome/browser/ash/child_accounts/time_limits/app_time_policy_helpers.h"
#include "chrome/browser/ash/child_accounts/time_limits/app_types.h"
#include "chrome/browser/extensions/launch_util.h"
#include "chrome/browser/notifications/notification_display_service.h"
#include "chrome/browser/notifications/notification_display_service_factory.h"
#include "chrome/browser/notifications/notification_handler.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/ash/experiences/arc/app/arc_app_constants.h"
#include "chromeos/ui/vector_icons/vector_icons.h"
#include "components/prefs/pref_change_registrar.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/services/app_service/public/cpp/app_launch_util.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/time_format.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/vector_icon_types.h"
#include "ui/message_center/public/cpp/notification.h"
#include "ui/message_center/public/cpp/notification_delegate.h"
#include "ui/message_center/public/cpp/notifier_id.h"

namespace ash {
namespace app_time {

const char kAppsWithTimeLimitMetric[] =
    "SupervisedUsers.PerAppTimeLimits.AppsWithTimeLimit";
const char kBlockedAppsCountMetric[] =
    "SupervisedUsers.PerAppTimeLimits.BlockedAppsCount";
const char kPolicyChangeCountMetric[] =
    "SupervisedUsers.PerAppTimeLimits.PolicyChangeCount";
const char kEngagementMetric[] = "SupervisedUsers.PerAppTimeLimits.Engagement";

namespace {

constexpr base::TimeDelta kDay = base::Hours(24);

// Family link notifier id.
constexpr char kFamilyLinkSourceId[] = "family-link";

// Time limit reaching id. This id will be appended by the application name. The
// 5 minute and one minute notifications for the same app will have the same id.
constexpr char kAppTimeLimitReachingNotificationId[] =
    "time-limit-reaching-id-";

// Time limit updated id. This id will be appended by the application name.
constexpr char kAppTimeLimitUpdateNotificationId[] = "time-limit-updated-id-";

// Used to convert |time_limit| to string. |cutoff| specifies whether the
// formatted result will be one value or two values: for example if the time
// delta is 2 hours 30 minutes: |cutoff| of <2 will result in "2 hours" and
// |cutoff| of 3 will result in "2 hours and 30 minutes".
std::u16string GetTimeLimitMessage(base::TimeDelta time_limit, int cutoff) {
  return ui::TimeFormat::Detailed(ui::TimeFormat::Format::FORMAT_DURATION,
                                  ui::TimeFormat::Length::LENGTH_LONG, cutoff,
                                  time_limit);
}

std::u16string GetNotificationTitleFor(const std::u16string& app_name,
                                       AppNotification notification) {
  switch (notification) {
    case AppNotification::kFiveMinutes:
    case AppNotification::kOneMinute:
      return l10n_util::GetStringFUTF16(
          IDS_APP_TIME_LIMIT_APP_WILL_PAUSE_SYSTEM_NOTIFICATION_TITLE,
          app_name);
    case AppNotification::kBlocked:
    case AppNotification::kAvailable:
    case AppNotification::kTimeLimitChanged:
      return l10n_util::GetStringUTF16(
          IDS_APP_TIME_LIMIT_APP_TIME_LIMIT_SET_SYSTEM_NOTIFICATION_TITLE);
    default:
      NOTREACHED();
  }
}

std::u16string GetNotificationMessageFor(
    const std::u16string& app_name,
    AppNotification notification,
    std::optional<base::TimeDelta> time_limit) {
  switch (notification) {
    case AppNotification::kFiveMinutes:
      return l10n_util::GetStringFUTF16(
          IDS_APP_TIME_LIMIT_APP_WILL_PAUSE_SYSTEM_NOTIFICATION_MESSAGE,
          GetTimeLimitMessage(base::Minutes(5), /* cutoff */ 1));
    case AppNotification::kOneMinute:
      return l10n_util::GetStringFUTF16(
          IDS_APP_TIME_LIMIT_APP_WILL_PAUSE_SYSTEM_NOTIFICATION_MESSAGE,
          GetTimeLimitMessage(base::Minutes(1), /* cutoff */ 1));
    case AppNotification::kTimeLimitChanged:
      return time_limit
                 ? l10n_util::GetStringFUTF16(
                       IDS_APP_TIME_LIMIT_APP_TIME_LIMIT_SET_SYSTEM_NOTIFICATION_MESSAGE,
                       GetTimeLimitMessage(*time_limit, /* cutoff */ 3),
                       app_name)
                 : l10n_util::GetStringFUTF16(
                       IDS_APP_TIME_LIMIT_APP_TIME_LIMIT_REMOVED_SYSTEM_NOTIFICATION_MESSAGE,
                       app_name);
    case AppNotification::kBlocked:
      return l10n_util::GetStringFUTF16(
          IDS_APP_TIME_LIMIT_APP_BLOCKED_NOTIFICATION_MESSAGE, app_name);

    case AppNotification::kAvailable:
      return l10n_util::GetStringFUTF16(
          IDS_APP_TIME_LIMIT_APP_AVAILABLE_NOTIFICATION_MESSAGE, app_name);
    default:
      NOTREACHED();
  }
}

std::string GetNotificationIdFor(const std::string& app_name,
                                 AppNotification notification) {
  std::string notification_id;
  switch (notification) {
    case AppNotification::kFiveMinutes:
    case AppNotification::kOneMinute:
      notification_id = kAppTimeLimitReachingNotificationId;
      break;
    case AppNotification::kTimeLimitChanged:
    case AppNotification::kBlocked:
    case AppNotification::kAvailable:
      notification_id = kAppTimeLimitUpdateNotificationId;
      break;
    default:
      NOTREACHED();
  }
  return base::StrCat({notification_id, app_name});
}

bool IsAppOpenedInChrome(const AppId& app_id, Profile* profile) {
  if (app_id.app_type() != apps::AppType::kChromeApp &&
      app_id.app_type() != apps::AppType::kWeb) {
    return false;
  }

  // It is a web or extension.
  const extensions::Extension* extension =
      extensions::ExtensionRegistry::Get(profile)->GetInstalledExtension(
          app_id.app_id());
  if (!extension)
    return false;

  apps::LaunchContainer launch_container = extensions::GetLaunchContainer(
      extensions::ExtensionPrefs::Get(profile), extension);
  return launch_container == apps::LaunchContainer::kLaunchContainerTab;
}

}  // namespace

AppTimeController::TestApi::TestApi(AppTimeController* controller)
    : controller_(controller) {}

AppTimeController::TestApi::~TestApi() = default;

void AppTimeController::TestApi::SetLastResetTime(base::Time time) {
  controller_->SetLastResetTime(time);
}

base::Time AppTimeController::TestApi::GetNextResetTime() const {
  return controller_->GetNextResetTime();
}

base::Time AppTimeController::TestApi::GetLastResetTime() const {
  return controller_->last_limits_reset_time_;
}

AppActivityRegistry* AppTimeController::TestApi::app_registry() {
  return controller_->app_registry_.get();
}

// static
void AppTimeController::RegisterProfilePrefs(PrefRegistrySimple* registry) {
  registry->RegisterInt64Pref(prefs::kPerAppTimeLimitsLastResetTime, 0);
  registry->RegisterDictionaryPref(prefs::kPerAppTimeLimitsPolicy);
  registry->RegisterDictionaryPref(prefs::kPerAppTimeLimitsAllowlistPolicy);
}

AppTimeController::AppTimeController(
    Profile* profile,
    base::RepeatingClosure on_policy_updated_callback)
    : profile_(profile),
      app_service_wrapper_(std::make_unique<AppServiceWrapper>(profile)),
      app_registry_(
          std::make_unique<AppActivityRegistry>(app_service_wrapper_.get(),
                                                this,
                                                profile->GetPrefs())),
      on_policy_updated_callback_(on_policy_updated_callback) {
  DCHECK(profile);
}

AppTimeController::~AppTimeController() {
  app_registry_->RemoveAppStateObserver(this);

  auto* time_zone_settings = system::TimezoneSettings::GetInstance();
  if (time_zone_settings)
    time_zone_settings->RemoveObserver(this);

  auto* system_clock_client = SystemClockClient::Get();
  if (system_clock_client)
    system_clock_client->RemoveObserver(this);
}

void AppTimeController::Init() {
  PrefService* pref_service = profile_->GetPrefs();
  RegisterProfilePrefObservers(pref_service);
  TimeLimitsAllowlistPolicyUpdated(prefs::kPerAppTimeLimitsAllowlistPolicy);
  TimeLimitsPolicyUpdated(prefs::kPerAppTimeLimitsPolicy);

  // Restore the last reset time. If reset time has have been crossed, triggers
  // AppActivityRegistry to clear up the running active times of applications.
  RestoreLastResetTime();

  // Start observing system clock client and time zone settings.
  auto* system_clock_client = SystemClockClient::Get();
  // SystemClockClient may not be initialized in some tests.
  if (system_clock_client)
    system_clock_client->AddObserver(this);

  auto* time_zone_settings = system::TimezoneSettings::GetInstance();
  if (time_zone_settings)
    time_zone_settings->AddObserver(this);

  // Start observing |app_registry_|
  app_registry_->AddAppStateObserver(this);

  // AppActivityRegistry may have missed |OnAppInstalled| calls. Notify it.
  app_registry_->SetInstalledApps(app_service_wrapper_->GetInstalledApps());

  // Record enagement metrics.
  base::UmaHistogramCounts1000(kEngagementMetric, apps_with_limit_);
}

bool AppTimeController::IsExtensionAllowlisted(
    const std::string& extension_id) const {
  return true;
}

std::optional<base::TimeDelta> AppTimeController::GetTimeLimitForApp(
    const std::string& app_service_id,
    apps::AppType app_type) const {
  const app_time::AppId app_id =
      app_service_wrapper_->AppIdFromAppServiceId(app_service_id, app_type);
  return app_registry_->GetTimeLimit(app_id);
}

void AppTimeController::RecordMetricsOnShutdown() const {
  base::UmaHistogramCounts1000(kPolicyChangeCountMetric,
                               patl_policy_update_count_);
}

void AppTimeController::SystemClockUpdated() {
  if (HasTimeCrossedResetBoundary())
    OnResetTimeReached();
}

void AppTimeController::TimezoneChanged(const icu::TimeZone& timezone) {
  // Timezone changes may not require us to reset information,
  // however, they may require updating the scheduled reset time.
  ScheduleForTimeLimitReset();
}

bool AppTimeController::HasAppTimeLimitRestriction() const {
  return apps_with_limit_ > 0;
}

void AppTimeController::RegisterProfilePrefObservers(
    PrefService* pref_service) {
  pref_registrar_ = std::make_unique<PrefChangeRegistrar>();
  pref_registrar_->Init(pref_service);

  // Adds callbacks to observe policy pref changes.
  // Using base::Unretained(this) is safe here because when |pref_registrar_|
  // gets destroyed, it will remove the observers from PrefService.
  pref_registrar_->Add(
      prefs::kPerAppTimeLimitsPolicy,
      base::BindRepeating(&AppTimeController::TimeLimitsPolicyUpdated,
                          base::Unretained(this)));
  pref_registrar_->Add(
      prefs::kPerAppTimeLimitsAllowlistPolicy,
      base::BindRepeating(&AppTimeController::TimeLimitsAllowlistPolicyUpdated,
                          base::Unretained(this)));
}

void AppTimeController::TimeLimitsPolicyUpdated(const std::string& pref_name) {
  DCHECK_EQ(pref_name, prefs::kPerAppTimeLimitsPolicy);

  const base::Value::Dict& policy =
      pref_registrar_->prefs()->GetDict(prefs::kPerAppTimeLimitsPolicy);

  std::map<AppId, AppLimit> app_limits = policy::AppLimitsFromDict(policy);

  bool updated = app_registry_->UpdateAppLimits(app_limits);

  app_registry_->SetReportingEnabled(
      policy::ActivityReportingEnabledFromDict(policy));

  std::optional<base::TimeDelta> new_reset_time =
      policy::ResetTimeFromDict(policy);
  // TODO(agawronska): Propagate the information about reset time change.
  if (new_reset_time && *new_reset_time != limits_reset_time_)
    limits_reset_time_ = *new_reset_time;

  apps_with_limit_ =
      app_registry_->GetAppsWithAppRestriction(AppRestriction::kTimeLimit)
          .size();

  if (updated) {
    patl_policy_update_count_++;

    base::UmaHistogramCounts1000(kAppsWithTimeLimitMetric, apps_with_limit_);

    int blocked_apps =
        app_registry_->GetAppsWithAppRestriction(AppRestriction::kBlocked)
            .size();

    base::UmaHistogramCounts1000(kBlockedAppsCountMetric, blocked_apps);

    on_policy_updated_callback_.Run();
  }
}

void AppTimeController::TimeLimitsAllowlistPolicyUpdated(
    const std::string& pref_name) {
  DCHECK_EQ(pref_name, prefs::kPerAppTimeLimitsAllowlistPolicy);

  const base::Value::Dict& policy = pref_registrar_->prefs()->GetDict(
      prefs::kPerAppTimeLimitsAllowlistPolicy);

  // Figure out a way to avoid cloning
  AppTimeLimitsAllowlistPolicyWrapper wrapper(&policy);

  app_registry_->OnTimeLimitAllowlistChanged(wrapper);
}

void AppTimeController::ShowAppTimeLimitNotification(
    const AppId& app_id,
    const std::optional<base::TimeDelta>& time_limit,
    AppNotification notification) {
  DCHECK_NE(AppNotification::kUnknown, notification);

  if (notification == AppNotification::kTimeLimitReached)
    return;

  const std::string app_name = app_service_wrapper_->GetAppName(app_id);
  int size_hint_in_dp = 48;
  app_service_wrapper_->GetAppIcon(
      app_id, size_hint_in_dp,
      base::BindOnce(&AppTimeController::ShowNotificationForApp,
                     weak_ptr_factory_.GetWeakPtr(), app_name, notification,
                     time_limit));
}

void AppTimeController::OnAppLimitReached(const AppId& app_id,
                                          base::TimeDelta time_limit,
                                          bool was_active) {
  bool show_dialog = was_active;
  if (app_id == GetChromeAppId() || IsAppOpenedInChrome(app_id, profile_))
    show_dialog = false;

  app_service_wrapper_->PauseApp(PauseAppInfo(app_id, time_limit, show_dialog));
}

void AppTimeController::OnAppLimitRemoved(const AppId& app_id) {
  app_service_wrapper_->ResumeApp(app_id);
}

void AppTimeController::OnAppInstalled(const AppId& app_id) {
  if (IsWebAppOrExtension(app_id))
    return;

  const base::Value::Dict& allowlist_policy = pref_registrar_->prefs()->GetDict(
      prefs::kPerAppTimeLimitsAllowlistPolicy);
  AppTimeLimitsAllowlistPolicyWrapper wrapper(&allowlist_policy);
  if (base::Contains(wrapper.GetAllowlistAppList(), app_id))
    app_registry_->SetAppAllowlisted(app_id);

  const base::Value::Dict& policy =
      pref_registrar_->prefs()->GetDict(prefs::kPerAppTimeLimitsPolicy);

  // Update the application's time limit.
  const std::map<AppId, AppLimit> limits = policy::AppLimitsFromDict(policy);
  // Update the limit for newly installed app, if it exists.
  auto result = limits.find(app_id);
  if (result == limits.end())
    return;

  app_registry_->SetAppLimit(result->first, result->second);
}

base::Time AppTimeController::GetNextResetTime() const {
  // UTC time now.
  base::Time now = base::Time::Now();

  // UTC time local midnight.
  base::Time nearest_midnight = now.LocalMidnight();

  base::Time prev_midnight;
  if (now > nearest_midnight)
    prev_midnight = nearest_midnight;
  else
    prev_midnight = nearest_midnight - base::Hours(24);

  base::Time next_reset_time = prev_midnight + limits_reset_time_;

  if (next_reset_time > now)
    return next_reset_time;

  // We have already reset for this day. The reset time is the next day.
  return next_reset_time + base::Hours(24);
}

void AppTimeController::ScheduleForTimeLimitReset() {
  if (reset_timer_.IsRunning())
    reset_timer_.Stop();

  base::TimeDelta time_until_reset = GetNextResetTime() - base::Time::Now();
  reset_timer_.Start(FROM_HERE, time_until_reset,
                     base::BindOnce(&AppTimeController::OnResetTimeReached,
                                    base::Unretained(this)));
}

void AppTimeController::OnResetTimeReached() {
  base::Time now = base::Time::Now();

  app_registry_->OnResetTimeReached(now);

  SetLastResetTime(now);

  ScheduleForTimeLimitReset();
}

void AppTimeController::RestoreLastResetTime() {
  PrefService* pref_service = profile_->GetPrefs();
  int64_t reset_time =
      pref_service->GetInt64(prefs::kPerAppTimeLimitsLastResetTime);

  if (reset_time == 0) {
    SetLastResetTime(base::Time::Now());
  } else {
    last_limits_reset_time_ =
        base::Time::FromDeltaSinceWindowsEpoch(base::Microseconds(reset_time));
  }

  if (HasTimeCrossedResetBoundary()) {
    OnResetTimeReached();
  } else {
    ScheduleForTimeLimitReset();
  }
}

void AppTimeController::SetLastResetTime(base::Time timestamp) {
  // |timestamp| needs to be adjusted to ensure that it is happening at the time
  // specified by policy.
  const base::Time nearest_midnight = timestamp.LocalMidnight();
  base::Time prev_midnight;
  if (timestamp > nearest_midnight)
    prev_midnight = nearest_midnight;
  else
    prev_midnight = nearest_midnight - base::Hours(24);

  base::Time reset_time = prev_midnight + limits_reset_time_;
  if (reset_time <= timestamp)
    last_limits_reset_time_ = reset_time;
  else
    last_limits_reset_time_ = reset_time - base::Hours(24);

  PrefService* service = profile_->GetPrefs();
  DCHECK(service);
  service->SetInt64(
      prefs::kPerAppTimeLimitsLastResetTime,
      last_limits_reset_time_.ToDeltaSinceWindowsEpoch().InMicroseconds());
  service->CommitPendingWrite();
}

bool AppTimeController::HasTimeCrossedResetBoundary() const {
  // Time after system time or timezone changed.
  base::Time now = base::Time::Now();

  return now < last_limits_reset_time_ || now >= kDay + last_limits_reset_time_;
}

void AppTimeController::OpenFamilyLinkApp() {
  const std::string app_id =
      arc::ArcPackageNameToAppId(kFamilyLinkHelperAppPackageName, profile_);

  if (app_service_wrapper_->IsAppInstalled(app_id)) {
    // Launch Family Link Help app since it is available.
    app_service_wrapper_->LaunchApp(app_id);
    return;
  }
  // No Family Link Help app installed, so try to launch Play Store to Family
  // Link Help app install page.
  DCHECK(
      apps::AppServiceProxyFactory::IsAppServiceAvailableForProfile(profile_));
  apps::AppServiceProxyFactory::GetForProfile(profile_)->LaunchAppWithUrl(
      arc::kPlayStoreAppId, ui::EF_NONE, GURL(kFamilyLinkHelperAppPlayStoreURL),
      apps::LaunchSource::kFromChromeInternal);
}

void AppTimeController::ShowNotificationForApp(
    const std::string& app_name,
    AppNotification notification,
    std::optional<base::TimeDelta> time_limit,
    std::optional<gfx::ImageSkia> icon) {
  DCHECK(notification == AppNotification::kFiveMinutes ||
         notification == AppNotification::kOneMinute ||
         notification == AppNotification::kTimeLimitChanged ||
         notification == AppNotification::kBlocked ||
         notification == AppNotification::kAvailable);

  DCHECK(notification == AppNotification::kTimeLimitChanged ||
         notification == AppNotification::kBlocked ||
         notification == AppNotification::kAvailable || time_limit.has_value());

  // Alright we have all the messages that we want.
  const std::u16string app_name_16 = base::UTF8ToUTF16(app_name);
  const std::u16string title =
      GetNotificationTitleFor(app_name_16, notification);
  const std::u16string message =
      GetNotificationMessageFor(app_name_16, notification, time_limit);
  // Family link display source.
  const std::u16string notification_source =
      l10n_util::GetStringUTF16(IDS_TIME_LIMIT_NOTIFICATION_DISPLAY_SOURCE);

  std::string notification_id = GetNotificationIdFor(app_name, notification);
  message_center::RichNotificationData option_fields;
  option_fields.fullscreen_visibility =
      message_center::FullscreenVisibility::OVER_USER;

  message_center::Notification message_center_notification =
      CreateSystemNotification(
          message_center::NOTIFICATION_TYPE_SIMPLE, notification_id, title,
          message, notification_source, GURL(),
          message_center::NotifierId(
              message_center::NotifierType::SYSTEM_COMPONENT,
              kFamilyLinkSourceId, NotificationCatalogName::kAppTime),
          option_fields,
          notification == AppNotification::kTimeLimitChanged
              ? base::MakeRefCounted<
                    message_center::HandleNotificationClickDelegate>(
                    base::BindRepeating(&AppTimeController::OpenFamilyLinkApp,
                                        weak_ptr_factory_.GetWeakPtr()))
              : base::MakeRefCounted<message_center::NotificationDelegate>(),
          chromeos::kNotificationSupervisedUserIcon,
          message_center::SystemNotificationWarningLevel::NORMAL);

  if (icon.has_value()) {
    message_center_notification.set_icon(
        ui::ImageModel::FromImageSkia(icon.value()));
  }

  auto* notification_display_service =
      NotificationDisplayServiceFactory::GetForProfile(profile_);
  if (!notification_display_service)
    return;

  // Close the existing notification with notification_id.
  notification_display_service->Close(NotificationHandler::Type::TRANSIENT,
                                      notification_id);

  notification_display_service->Display(NotificationHandler::Type::TRANSIENT,
                                        message_center_notification,
                                        /*metadata=*/nullptr);
}

}  // namespace app_time
}  // namespace ash