File: menu_notification_service.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (326 lines) | stat: -rw-r--r-- 13,400 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
// Copyright 2023 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/ui/safety_hub/menu_notification_service.h"

#include <memory>
#include <utility>

#include "base/functional/bind.h"
#include "base/functional/callback_forward.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/ui/safety_hub/menu_notification.h"
#include "chrome/browser/ui/safety_hub/notification_permission_review_service.h"
#include "chrome/browser/ui/safety_hub/revoked_permissions_service.h"
#include "chrome/browser/ui/safety_hub/safe_browsing_result.h"
#include "chrome/browser/ui/safety_hub/safety_hub_constants.h"
#include "chrome/browser/ui/safety_hub/safety_hub_prefs.h"
#include "chrome/browser/ui/safety_hub/safety_hub_service.h"
#include "chrome/common/chrome_features.h"
#include "components/prefs/pref_service.h"
#include "components/safe_browsing/core/common/safe_browsing_prefs.h"

#if BUILDFLAG(IS_ANDROID)
#include "chrome/browser/ui/safety_hub/password_status_check_result_android.h"
#else  // BUILDFLAG(IS_ANDROID)
#include "chrome/browser/ui/safety_hub/extensions_result.h"
#endif  // BUILDFLAG(IS_ANDROID)
namespace {
SafetyHubModuleInfoElement::SafetyHubModuleInfoElement() = default;
SafetyHubModuleInfoElement::~SafetyHubModuleInfoElement() = default;

SafetyHubModuleInfoElement::SafetyHubModuleInfoElement(
    MenuNotificationPriority priority,
    base::TimeDelta interval,
    base::RepeatingCallback<
        std::optional<std::unique_ptr<SafetyHubService::Result>>()>
        result_getter,
    std::unique_ptr<SafetyHubMenuNotification> notification)
    : priority(priority),
      interval(interval),
      result_getter(result_getter),
      notification(std::move(notification)) {}
}  // namespace

SafetyHubMenuNotificationService::SafetyHubMenuNotificationService(
    PrefService* pref_service,
    RevokedPermissionsService* revoked_permissions_service,
    NotificationPermissionsReviewService* notification_permissions_service,
#if !BUILDFLAG(IS_ANDROID)
    PasswordStatusCheckService* password_check_service,
    SafetyHubHatsService* safety_hub_hats_service,
#endif  // !BUILDFLAG(IS_ANDROID)
    Profile* profile) {
  pref_service_ = std::move(pref_service);
#if !BUILDFLAG(IS_ANDROID)
  safety_hub_hats_service_ = safety_hub_hats_service;
#endif  // !BUILDFLAG(IS_ANDROID)
  const base::Value::Dict& stored_notifications =
      pref_service_->GetDict(safety_hub_prefs::kMenuNotificationsPrefsKey);

  pref_dict_key_map_ = {
      {safety_hub::SafetyHubModuleType::UNUSED_SITE_PERMISSIONS,
       "unused-site-permissions"},
      {safety_hub::SafetyHubModuleType::NOTIFICATION_PERMISSIONS,
       "notification-permissions"},
      {safety_hub::SafetyHubModuleType::SAFE_BROWSING, "safe-browsing"},
  };

  // TODO(crbug.com/40267370): Make the interval for each service finch
  // configurable.
  // The Safety Hub services will be available whenever the |GetCachedResult|
  // method is called, so it is safe to use |base::Unretained| here.
  SetInfoElement(
      safety_hub::SafetyHubModuleType::UNUSED_SITE_PERMISSIONS,
      MenuNotificationPriority::LOW,
      features::kRevokedPermissionsNotificationInterval.Get(),
      base::BindRepeating(&SafetyHubService::GetCachedResult,
                          base::Unretained(revoked_permissions_service)),
      stored_notifications);
  SetInfoElement(
      safety_hub::SafetyHubModuleType::NOTIFICATION_PERMISSIONS,
      MenuNotificationPriority::LOW,
      features::kNotificationPermissionsNotificationInterval.Get(),
      base::BindRepeating(&SafetyHubService::GetCachedResult,
                          base::Unretained(notification_permissions_service)),
      stored_notifications);
  SetInfoElement(safety_hub::SafetyHubModuleType::SAFE_BROWSING,
                 MenuNotificationPriority::MEDIUM,
                 features::kSafeBrowsingNotificationInterval.Get(),
                 base::BindRepeating(&SafetyHubSafeBrowsingResult::GetResult,
                                     base::Unretained(pref_service)),
                 stored_notifications);

// Extensions are not available on Android, so we cannot fetch any information
// about them. Passwords are handled by GMS Core on Android and our
// PasswordStatusCheckService is not compatible with GMS Core.
#if !BUILDFLAG(IS_ANDROID)
  pref_dict_key_map_.emplace(safety_hub::SafetyHubModuleType::EXTENSIONS,
                             "extensions");
  SetInfoElement(
      safety_hub::SafetyHubModuleType::EXTENSIONS,
      MenuNotificationPriority::LOW, base::Days(10),
      base::BindRepeating(&SafetyHubExtensionsResult::GetResult, profile, true),
      stored_notifications);

  // PasswordStatusCheckService might be null for some profiles and testing. Add
  // the info item only if the service is available.
  if (password_check_service) {
    pref_dict_key_map_.emplace(safety_hub::SafetyHubModuleType::PASSWORDS,
                               "passwords");
    SetInfoElement(
        safety_hub::SafetyHubModuleType::PASSWORDS,
        MenuNotificationPriority::HIGH,
        features::kPasswordCheckNotificationInterval.Get(),
        base::BindRepeating(&PasswordStatusCheckService::GetCachedResult,
                            base::Unretained(password_check_service)),
        stored_notifications);
  }
#else   // !BUILDFLAG(IS_ANDROID)
  if (base::FeatureList::IsEnabled(features::kSafetyHub) &&
      base::FeatureList::IsEnabled(features::kSafetyHubFollowup)) {
    pref_dict_key_map_.emplace(safety_hub::SafetyHubModuleType::PASSWORDS,
                               "passwords");
    SetInfoElement(
        safety_hub::SafetyHubModuleType::PASSWORDS,
        MenuNotificationPriority::HIGH,
        features::kPasswordCheckNotificationInterval.Get(),
        base::BindRepeating(&PasswordStatusCheckResultAndroid::GetResult,
                            base::Unretained(pref_service)),
        stored_notifications);
  }
#endif  // !BUILDFLAG(IS_ANDROID)

  // Listen for changes to the Safe Browsing pref to accommodate the trigger
  // logic.
  registrar_.Init(pref_service);
  registrar_.Add(
      prefs::kSafeBrowsingEnabled,
      base::BindRepeating(
          &SafetyHubMenuNotificationService::OnSafeBrowsingPrefUpdate,
          base::Unretained(this)));
}

void SafetyHubMenuNotificationService::UpdateResultGetterForTesting(
    safety_hub::SafetyHubModuleType type,
    base::RepeatingCallback<
        std::optional<std::unique_ptr<SafetyHubService::Result>>()>
        result_getter) {
  module_info_map_[type]->result_getter = result_getter;
}

SafetyHubMenuNotificationService::~SafetyHubMenuNotificationService() {
  registrar_.RemoveAll();
}

#if !BUILDFLAG(IS_ANDROID)
void SafetyHubMenuNotificationService::MaybeTriggerControlSurvey() const {
  // If any notification is not shown yet, trigger Hats survey control group.
  if (base::FeatureList::IsEnabled(features::kSafetyHubHaTSOneOffSurvey) &&
      !HasAnyNotificationBeenShown()) {
    if (!safety_hub_hats_service_) {
      return;
    }
    safety_hub_hats_service_->TriggerControlSurvey();
  }
}
#endif  // !BUILDFLAG(IS_ANDROID)

std::optional<MenuNotificationEntry>
SafetyHubMenuNotificationService::GetNotificationToShow() {
  std::optional<ResultMap> result_map = GetResultsFromAllModules();
  if (!result_map.has_value()) {
    return std::nullopt;
  }
  std::list<SafetyHubMenuNotification*> notifications_to_be_shown;
  MenuNotificationPriority cur_highest_priority = MenuNotificationPriority::LOW;
  for (auto& item : result_map.value()) {
    const SafetyHubModuleInfoElement* info_element =
        module_info_map_[item.first].get();
    SafetyHubMenuNotification* notification = info_element->notification.get();
    // The result in the ResultMap (item.second) is being moved away from and
    // thus shouldn't be used again in this method.
    notification->UpdateResult(std::move(item.second));
    int max_all_time_impressions =
        item.first == safety_hub::SafetyHubModuleType::SAFE_BROWSING ? 3 : 0;
    if (notification->ShouldBeShown(info_element->interval,
                                    max_all_time_impressions)) {
      // Notifications are first sorted by priority, and then by being
      // currently active.
      if (info_element->priority > cur_highest_priority ||
          (info_element->priority == cur_highest_priority &&
           notification->IsCurrentlyActive())) {
        cur_highest_priority = info_element->priority;
        notifications_to_be_shown.push_front(notification);
      } else {
        notifications_to_be_shown.push_back(notification);
      }
    } else {
      if (notification->IsCurrentlyActive()) {
        notification->Dismiss();
      }
    }
  }
  if (notifications_to_be_shown.empty()) {
    // The notifications should be persisted with updated results.
    SaveNotificationsToPrefs();
    return std::nullopt;
  }
  SafetyHubMenuNotification* notification_to_show =
      notifications_to_be_shown.front();
  // Dismiss all other notifications that are not shown.
  for (auto it = std::next(notifications_to_be_shown.begin());
       it != notifications_to_be_shown.end(); ++it) {
    (*it)->Dismiss();
  }
  notification_to_show->Show();

  // The information related to showing the notification needs to be persisted
  // as well.
  SaveNotificationsToPrefs();
  return MenuNotificationEntry(notification_to_show->GetNotificationCommandId(),
                               notification_to_show->GetNotificationString(),
                               notification_to_show->GetModuleType());
}

std::optional<ResultMap>
SafetyHubMenuNotificationService::GetResultsFromAllModules() {
  ResultMap result_map;
  for (auto const& item : module_info_map_) {
    CHECK(item.second->result_getter);
    std::optional<std::unique_ptr<SafetyHubService::Result>> result =
        item.second->result_getter.Run();
    // If one of the cached results is unavailable, no notification is shown.
    if (!result.has_value()) {
      return std::nullopt;
    }
    result_map.try_emplace(item.first, std::move(result.value()));
  }
  return result_map;
}

void SafetyHubMenuNotificationService::SaveNotificationsToPrefs() const {
  base::Value::Dict notifications;
  for (auto const& it : pref_dict_key_map_) {
    SafetyHubModuleInfoElement* info_element =
        module_info_map_.find(it.first)->second.get();
    notifications.Set(it.second, info_element->notification->ToDictValue());
  }
  pref_service_->SetDict(safety_hub_prefs::kMenuNotificationsPrefsKey,
                         std::move(notifications));
}

std::unique_ptr<SafetyHubMenuNotification>
SafetyHubMenuNotificationService::GetNotificationFromDict(
    const base::Value::Dict& dict,
    safety_hub::SafetyHubModuleType& type) const {
  // It can be assumed that all `safety_hub::SafetyHubModuleType`s are in
  // `pref_dict_key_map_`.
  const base::Value::Dict* notification_dict =
      dict.FindDict(pref_dict_key_map_.find(type)->second);
  if (!notification_dict) {
    auto new_notification = std::make_unique<SafetyHubMenuNotification>(type);
    if (type == safety_hub::SafetyHubModuleType::SAFE_BROWSING) {
      new_notification->SetOnlyShowAfter(base::Time::Now() + base::Days(1));
    }
    return new_notification;
  }
  return std::make_unique<SafetyHubMenuNotification>(*notification_dict, type);
}

void SafetyHubMenuNotificationService::SetInfoElement(
    safety_hub::SafetyHubModuleType type,
    MenuNotificationPriority priority,
    base::TimeDelta interval,
    base::RepeatingCallback<
        std::optional<std::unique_ptr<SafetyHubService::Result>>()>
        result_getter,
    const base::Value::Dict& stored_notifications) {
  module_info_map_[type] = std::make_unique<SafetyHubModuleInfoElement>(
      priority, interval, result_getter,
      GetNotificationFromDict(stored_notifications, type));
}

void SafetyHubMenuNotificationService::OnSafeBrowsingPrefUpdate() {
  module_info_map_[safety_hub::SafetyHubModuleType::SAFE_BROWSING]
      ->notification->SetOnlyShowAfter(base::Time::Now() + base::Days(1));
  module_info_map_[safety_hub::SafetyHubModuleType::SAFE_BROWSING]
      ->notification->ResetAllTimeNotificationCount();
  SaveNotificationsToPrefs();
}

void SafetyHubMenuNotificationService::DismissActiveNotification() {
  for (auto const& item : module_info_map_) {
    if (item.second->notification->IsCurrentlyActive()) {
      item.second->notification->Dismiss();
    }
  }
}

void SafetyHubMenuNotificationService::DismissActiveNotificationOfModule(
    safety_hub::SafetyHubModuleType module) {
  // Callers of this function do not know if the module is available. Do
  // nothing, if the module is not available.
  if (!module_info_map_.contains(module)) {
    return;
  }
  SafetyHubMenuNotification* notification =
      module_info_map_.at(module)->notification.get();
  if (notification->IsCurrentlyActive()) {
    notification->Dismiss();
  }
}

bool SafetyHubMenuNotificationService::HasAnyNotificationBeenShown() const {
  for (auto const& it : pref_dict_key_map_) {
    SafetyHubModuleInfoElement* info_element =
        module_info_map_.find(it.first)->second.get();
    if (info_element->notification.get()->HasAnyNotificationBeenShown()) {
      return true;
    }
  }
  return false;
}