push_notification_manager.cc 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2022 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. #include "components/optimization_guide/core/push_notification_manager.h"
  5. #include "base/callback_helpers.h"
  6. #include "base/metrics/histogram_functions.h"
  7. #include "components/optimization_guide/core/optimization_guide_features.h"
  8. namespace optimization_guide {
  9. PushNotificationManager::PushNotificationManager() = default;
  10. PushNotificationManager::~PushNotificationManager() = default;
  11. void PushNotificationManager::SetDelegate(
  12. PushNotificationManager::Delegate* delegate) {
  13. delegate_ = delegate;
  14. }
  15. void PushNotificationManager::OnDelegateReady() {
  16. DCHECK(delegate_);
  17. DCHECK(features::IsPushNotificationsEnabled());
  18. }
  19. void PushNotificationManager::OnNewPushNotification(
  20. const proto::HintNotificationPayload& notification) {
  21. if (!notification.has_hint_key())
  22. return;
  23. if (!notification.has_key_representation())
  24. return;
  25. DispatchPayload(notification);
  26. }
  27. void PushNotificationManager::AddObserver(
  28. PushNotificationManager::Observer* observer) {
  29. observers_.AddObserver(observer);
  30. }
  31. void PushNotificationManager::RemoveObserver(
  32. PushNotificationManager::Observer* observer) {
  33. observers_.RemoveObserver(observer);
  34. }
  35. void PushNotificationManager::DispatchPayload(
  36. const proto::HintNotificationPayload& notification) {
  37. // No custom payload or optimization type.
  38. if (!notification.has_payload() || !notification.has_optimization_type()) {
  39. return;
  40. }
  41. base::UmaHistogramEnumeration(
  42. "OptimizationGuide.PushNotifications.ReceivedNotificationType",
  43. notification.optimization_type(),
  44. static_cast<optimization_guide::proto::OptimizationType>(
  45. optimization_guide::proto::OptimizationType_ARRAYSIZE));
  46. for (Observer& observer : observers_) {
  47. observer.OnNotificationPayload(notification.optimization_type(),
  48. notification.payload());
  49. }
  50. delegate_->RemoveFetchedEntriesByHintKeys(base::DoNothing(),
  51. notification.key_representation(),
  52. {notification.hint_key()});
  53. }
  54. } // namespace optimization_guide