File: scheduled_notification_manager.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 (437 lines) | stat: -rw-r--r-- 16,423 bytes parent folder | download | duplicates (7)
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
// 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/notifications/scheduler/internal/scheduled_notification_manager.h"

#include <algorithm>
#include <map>
#include <unordered_set>
#include <utility>
#include <vector>

#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ref.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/notifications/scheduler/internal/icon_store.h"
#include "chrome/browser/notifications/scheduler/internal/notification_entry.h"
#include "chrome/browser/notifications/scheduler/internal/scheduler_config.h"
#include "chrome/browser/notifications/scheduler/internal/scheduler_utils.h"
#include "chrome/browser/notifications/scheduler/internal/stats.h"
#include "chrome/browser/notifications/scheduler/public/notification_params.h"
#include "chrome/browser/notifications/scheduler/public/notification_scheduler_constant.h"
#include "chrome/grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

namespace notifications {
namespace {

// Comparator used to sort notification entries based on creation time.
bool CreateTimeCompare(const NotificationEntry* lhs,
                       const NotificationEntry* rhs) {
  DCHECK(lhs && rhs);
  return lhs->create_time < rhs->create_time;
}

// Vailidates notification entry. Returns false if the entry should be deleted.
bool ValidateNotificationEntry(const NotificationEntry& entry) {
  // Check the deliver time window.
  return (entry.schedule_params.deliver_time_start.has_value() &&
          entry.schedule_params.deliver_time_end.has_value() &&
          entry.schedule_params.deliver_time_end > base::Time::Now() &&
          entry.schedule_params.deliver_time_end >=
              entry.schedule_params.deliver_time_start);
}

class ScheduledNotificationManagerImpl : public ScheduledNotificationManager {
 public:
  using NotificationStore = std::unique_ptr<CollectionStore<NotificationEntry>>;

  ScheduledNotificationManagerImpl(
      NotificationStore notification_store,
      std::unique_ptr<IconStore> icon_store,
      const std::vector<SchedulerClientType>& clients,
      const SchedulerConfig& config)
      : notification_store_(std::move(notification_store)),
        icon_store_(std::move(icon_store)),
        clients_(clients.begin(), clients.end()),
        config_(config) {}
  ScheduledNotificationManagerImpl(const ScheduledNotificationManagerImpl&) =
      delete;
  ScheduledNotificationManagerImpl& operator=(
      const ScheduledNotificationManagerImpl&) = delete;

 private:
  // NotificationManager implementation.
  void Init(InitCallback callback) override {
    icon_store_->InitAndLoadKeys(base::BindOnce(
        &ScheduledNotificationManagerImpl::OnIconStoreInitialized,
        weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void ScheduleNotification(
      std::unique_ptr<NotificationParams> notification_params,
      ScheduleCallback callback) override {
    DCHECK(notification_params);
    std::string guid = notification_params->guid;
    DCHECK(!guid.empty());
    auto type = notification_params->type;
    stats::LogNotificationLifeCycleEvent(
        stats::NotificationLifeCycleEvent::kScheduleRequest, type);

    if (!clients_.count(type) ||
        (notifications_.count(type) && notifications_[type].count(guid))) {
      // TODO(xingliu): Report duplicate guid failure.
      std::move(callback).Run(false);
      return;
    }

    bool valid = ValidateNotificationParams(*notification_params);
    DCHECK(valid) << "Invalid notification parameters.";
    if (!valid) {
      stats::LogNotificationLifeCycleEvent(
          stats::NotificationLifeCycleEvent::kInvalidInput, type);
      std::move(callback).Run(false);
      return;
    }

    if (notification_params->enable_ihnr_buttons) {
      CreateInhrButtonsPair(&notification_params->notification_data.buttons);
    }

    auto entry =
        std::make_unique<NotificationEntry>(notification_params->type, guid);
    auto icon_bundles = std::move(notification_params->notification_data.icons);
    entry->notification_data =
        std::move(notification_params->notification_data);
    entry->schedule_params = std::move(notification_params->schedule_params);
    icon_store_->AddIcons(
        std::move(icon_bundles),
        base::BindOnce(&ScheduledNotificationManagerImpl::OnIconsAdded,
                       weak_ptr_factory_.GetWeakPtr(), std::move(entry),
                       std::move(callback)));
  }

  void DisplayNotification(const std::string& guid,
                           DisplayCallback callback) override {
    NotificationEntry* entry = nullptr;
    for (auto it = notifications_.begin(); it != notifications_.end(); it++) {
      if (it->second.count(guid)) {
        entry = it->second[guid].get();
        break;
      }
    }

    if (!entry) {
      std::move(callback).Run(nullptr);
      return;
    }

    std::vector<std::string> keys;
    for (const auto& pair : entry->icons_uuid) {
      keys.emplace_back(pair.second);
    }
    icon_store_->LoadIcons(
        std::move(keys),
        base::BindOnce(&ScheduledNotificationManagerImpl::OnIconsLoaded,
                       weak_ptr_factory_.GetWeakPtr(), entry->type, entry->guid,
                       std::move(callback)));
  }

  void GetAllNotifications(Notifications* notifications) const override {
    DCHECK(notifications);
    notifications->clear();

    for (auto it = notifications_.begin(); it != notifications_.end(); it++) {
      auto type = it->first;
      for (const auto& pair : it->second) {
        (*notifications)[type].emplace_back(pair.second.get());
      }
    }

    // Sort by creation time for each notification type.
    for (auto it = notifications->begin(); it != notifications->end(); ++it) {
      std::sort(it->second.begin(), it->second.end(), &CreateTimeCompare);
    }
  }

  void GetNotifications(
      SchedulerClientType type,
      std::vector<const NotificationEntry*>* notifications) const override {
    DCHECK(notifications);
    notifications->clear();
    const auto it = notifications_.find(type);
    if (it == notifications_.end())
      return;
    for (const auto& pair : it->second)
      notifications->emplace_back(pair.second.get());
  }

  void DeleteNotifications(SchedulerClientType type) override {
    if (!notifications_.count(type))
      return;

    auto it = notifications_[type].begin();
    while (it != notifications_[type].end()) {
      const auto& entry = *it->second;
      ++it;
      DeleteNotification(entry, false /*should_delete_in_memory*/);
    }
    notifications_.erase(type);
  }

  void OnIconStoreInitialized(InitCallback callback,
                              bool success,
                              IconStore::LoadedIconKeys loaded_keys) {
    if (!success) {
      std::move(callback).Run(false);
      return;
    }

    notification_store_->InitAndLoad(base::BindOnce(
        &ScheduledNotificationManagerImpl::OnNotificationStoreInitialized,
        weak_ptr_factory_.GetWeakPtr(), std::move(callback),
        std::move(loaded_keys)));
  }

  void OnNotificationStoreInitialized(
      InitCallback callback,
      std::unique_ptr<std::vector<std::string>> loaded_icon_keys,
      bool success,
      CollectionStore<NotificationEntry>::Entries entries) {
    if (!success) {
      std::move(callback).Run(false);
      return;
    }

    FilterNotificationEntries(std::move(entries));
    FilterIconEntries(std::move(loaded_icon_keys));
    std::move(callback).Run(true);
  }

  void FilterIconEntries(
      std::unique_ptr<std::vector<std::string>> uuids_from_icon_store) {
    std::unordered_set<std::string> icons_uuid_from_entries;
    for (const auto& client_pair : notifications_) {
      for (const auto& notification : client_pair.second) {
        for (const auto& icon : notification.second->icons_uuid) {
          icons_uuid_from_entries.emplace(icon.second);
        }
      }
    }
    std::vector<std::string> icons_to_delete;
    for (const auto& loaded_icon_key : *uuids_from_icon_store.get()) {
      if (!base::Contains(icons_uuid_from_entries, loaded_icon_key)) {
        icons_to_delete.emplace_back(loaded_icon_key);
      }
    }
    icon_store_->DeleteIcons(icons_to_delete, /*callback=*/base::DoNothing());
  }

  // Filters and loads notification into memory.
  void FilterNotificationEntries(
      CollectionStore<NotificationEntry>::Entries entries) {
    for (auto it = entries.begin(); it != entries.end(); it++) {
      auto* entry = it->get();
      // Prune expired notifications. Also delete them in db.
      bool expired = entry->create_time + config_->notification_expiration <=
                     base::Time::Now();
      bool valid = ValidateNotificationEntry(*entry);
      bool deprecated_client = !base::Contains(clients_, entry->type);
      if (expired || deprecated_client || !valid) {
        DeleteNotification(*entry, false /*should_delete_in_memory*/);
      } else {
        notifications_[entry->type].emplace(entry->guid, std::move(*it));
      }
    }
  }

  void OnIconsAdded(std::unique_ptr<NotificationEntry> entry,
                    ScheduleCallback schedule_callback,
                    IconStore::IconTypeUuidMap icons_uuid_map,
                    bool success) {
    if (!success) {
      std::move(schedule_callback).Run(false);
      return;
    }

    entry->icons_uuid = std::move(icons_uuid_map);
    const auto* entry_ptr = entry.get();
    notification_store_->Add(
        entry_ptr->guid, *entry_ptr,
        base::BindOnce(&ScheduledNotificationManagerImpl::OnNotificationAdded,
                       weak_ptr_factory_.GetWeakPtr(), std::move(entry),
                       std::move(schedule_callback)));
  }

  void OnNotificationAdded(std::unique_ptr<NotificationEntry> entry,
                           ScheduleCallback schedule_callback,
                           bool success) {
    // Delete the icons when failed to add to notification database.
    if (!success) {
      std::vector<std::string> icons_to_delete;
      for (const auto& uuid : entry->icons_uuid) {
        icons_to_delete.emplace_back(uuid.second);
      }
      icon_store_->DeleteIcons(std::move(icons_to_delete),
                               /*callback=*/base::DoNothing());
      std::move(schedule_callback).Run(false);
      return;
    }

    auto type = entry->type;
    auto guid = entry->guid;
    notifications_[type][guid] = std::move(entry);

    stats::LogNotificationLifeCycleEvent(
        stats::NotificationLifeCycleEvent::kScheduled, type);
    std::move(schedule_callback).Run(true);
  }

  void OnIconsLoaded(SchedulerClientType client_type,
                     const std::string& guid,
                     DisplayCallback display_callback,
                     bool success,
                     IconStore::LoadedIconsMap loaded_icons_map) {
    auto* entry_ptr = FindNotificationEntry(client_type, guid);
    if (!entry_ptr) {
      std::move(display_callback).Run(nullptr);
      return;
    }

    if (!success) {
      DeleteNotification(*entry_ptr, true /*should_delete_in_memory*/);
      std::move(display_callback).Run(nullptr);
      return;
    }

    // Glue the icon data to entry.
    std::unique_ptr<NotificationEntry> entry =
        std::move(notifications_[client_type][guid]);
    DCHECK(entry);
    for (const auto& pair : entry->icons_uuid) {
      auto icon_bundle = IconBundle(std::move(loaded_icons_map[pair.second]));
      entry->notification_data.icons.emplace(pair.first,
                                             std::move(icon_bundle));
    }

    // Before moving out the entry, delete it from container and disk.
    DeleteNotification(*entry.get(), true /*should_delete_in_memory*/);

    std::move(display_callback).Run(std::move(entry));
  }

  NotificationEntry* FindNotificationEntry(SchedulerClientType type,
                                           const std::string& guid) {
    if (!notifications_.count(type) || !notifications_[type].count(guid))
      return nullptr;
    return notifications_[type][guid].get();
  }

  // Delete NotitificationEntry from memory and disk.
  void DeleteNotification(const NotificationEntry& entry,
                          bool should_delete_in_memory) {
    // Deletes icon first.
    std::vector<std::string> icons_to_delete;
    for (const auto& icon_id : entry.icons_uuid) {
      icons_to_delete.emplace_back(icon_id.second);
    }
    icon_store_->DeleteIcons(std::move(icons_to_delete),
                             /*callback=*/base::DoNothing());

    auto guid = entry.guid;
    auto type = entry.type;

    // Deletes notification entry.
    notification_store_->Delete(guid, /*callback=*/base::DoNothing());

    if (should_delete_in_memory) {
      notifications_[type].erase(guid);
      if (notifications_[type].empty())
        notifications_.erase(type);
    }
  }

  // Create two default buttons {Helpful, Unhelpful} for notification.
  void CreateInhrButtonsPair(std::vector<NotificationData::Button>* buttons) {
    buttons->clear();
    NotificationData::Button helpful_button;
    helpful_button.type = ActionButtonType::kHelpful;
    helpful_button.id = notifications::kDefaultHelpfulButtonId;
    helpful_button.text =
        l10n_util::GetStringUTF16(IDS_NOTIFICATION_DEFAULT_HELPFUL_BUTTON_TEXT);
    buttons->emplace_back(std::move(helpful_button));

    NotificationData::Button unhelpful_button;
    unhelpful_button.type = ActionButtonType::kUnhelpful;
    unhelpful_button.id = notifications::kDefaultUnhelpfulButtonId;
    unhelpful_button.text = l10n_util::GetStringUTF16(
        IDS_NOTIFICATION_DEFAULT_UNHELPFUL_BUTTON_TEXT);
    buttons->emplace_back(std::move(unhelpful_button));
  }

  // Vailidates notification parameters. Returns false if the parameters are
  // invalid.
  bool ValidateNotificationParams(const NotificationParams& params) {
    // Validate time window. Currently we only support deliver notification
    // according to a time window, the deliver window should before the
    // expiration duration of notification data in config.
    if (!params.schedule_params.deliver_time_start.has_value() ||
        !params.schedule_params.deliver_time_end.has_value() ||
        params.schedule_params.deliver_time_start.value() >
            params.schedule_params.deliver_time_end.value() ||
        params.schedule_params.deliver_time_end.value() - base::Time::Now() >=
            config_->notification_expiration) {
      return false;
    }

    // Validate ihnr buttons option. Custom buttons will be overwritten.
    if (params.enable_ihnr_buttons &&
        !params.notification_data.buttons.empty()) {
      return false;
    }

    // Validate icon bundle data is correct: icon resource id should never be
    // persisted to disk,since it can change in different versions. Client
    // should overwrite with Android resource id in BeforeShowNotification
    // callback if it is required.
    for (const auto& icon_bundle_map : params.notification_data.icons) {
      const auto& icon_bundle = icon_bundle_map.second;
      if (icon_bundle.resource_id)
        return false;
    }

    return true;
  }

  NotificationStore notification_store_;
  std::unique_ptr<IconStore> icon_store_;
  const std::unordered_set<SchedulerClientType> clients_;
  std::map<SchedulerClientType,
           std::map<std::string, std::unique_ptr<NotificationEntry>>>
      notifications_;
  const raw_ref<const SchedulerConfig, DanglingUntriaged> config_;
  base::WeakPtrFactory<ScheduledNotificationManagerImpl> weak_ptr_factory_{
      this};
};

}  // namespace

// static
std::unique_ptr<ScheduledNotificationManager>
ScheduledNotificationManager::Create(
    std::unique_ptr<CollectionStore<NotificationEntry>> notification_store,
    std::unique_ptr<IconStore> icon_store,
    const std::vector<SchedulerClientType>& clients,
    const SchedulerConfig& config) {
  return std::make_unique<ScheduledNotificationManagerImpl>(
      std::move(notification_store), std::move(icon_store), clients, config);
}

ScheduledNotificationManager::ScheduledNotificationManager() = default;

ScheduledNotificationManager::~ScheduledNotificationManager() = default;

}  // namespace notifications