File: push_notification_service_desktop_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 (253 lines) | stat: -rw-r--r-- 10,864 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
// 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/push_notification/push_notification_service_desktop_impl.h"

#include "base/check.h"
#include "base/functional/bind.h"
#include "chrome/browser/push_notification/metrics/push_notification_metrics.h"
#include "chrome/browser/push_notification/prefs/push_notification_prefs.h"
#include "chrome/browser/push_notification/protos/notifications_multi_login_update.pb.h"
#include "chrome/browser/push_notification/server_client/push_notification_desktop_api_call_flow_impl.h"
#include "chrome/browser/push_notification/server_client/push_notification_server_client.h"
#include "chrome/browser/push_notification/server_client/push_notification_server_client_desktop_impl.h"
#include "chromeos/ash/components/nearby/common/scheduling/nearby_scheduler_factory.h"
#include "components/gcm_driver/gcm_driver.h"
#include "components/gcm_driver/gcm_profile_service.h"
#include "components/gcm_driver/instance_id/instance_id.h"
#include "components/gcm_driver/instance_id/instance_id_driver.h"
#include "components/gcm_driver/instance_id/instance_id_profile_service.h"
#include "components/prefs/pref_service.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"

namespace {

const char kPushNotificationAppId[] = "com.google.chrome.push_notification";
const char kPushNotificationScope[] = "GCM";
const char kPushNotificationSenderId[] = "745476177629";
const char kClientId[] = "ChromeDesktop";

}  // namespace

namespace push_notification {

PushNotificationServiceDesktopImpl::PushNotificationServiceDesktopImpl(
    PrefService* pref_service,
    instance_id::InstanceIDDriver* instance_id_driver,
    signin::IdentityManager* identity_manager,
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory)
    : pref_service_(pref_service),
      instance_id_driver_(instance_id_driver),
      identity_manager_(identity_manager),
      url_loader_factory_(url_loader_factory) {
  CHECK(pref_service_);
  CHECK(instance_id_driver_);
  CHECK(identity_manager_);
  CHECK(url_loader_factory_);
  initialization_on_demand_scheduler_ =
      ash::nearby::NearbySchedulerFactory::CreateOnDemandScheduler(
          /*retry_failures=*/true, /*require_connectivity=*/true,
          prefs::kPushNotificationRegistrationAttemptBackoffSchedulerPrefName,
          pref_service_,
          base::BindRepeating(&PushNotificationServiceDesktopImpl::Initialize,
                              base::Unretained(this)),
          Feature::NEARBY_INFRA, base::DefaultClock::GetInstance());
  initialization_on_demand_scheduler_->Start();
}

PushNotificationServiceDesktopImpl::~PushNotificationServiceDesktopImpl() =
    default;

void PushNotificationServiceDesktopImpl::ShutdownHandler() {
  // Shutdown() should come before and it removes us from the list of app
  // handlers of gcm::GCMDriver so this shouldn't ever been called.
  NOTREACHED() << "The Push Notification Service should have removed itself "
                  "from the list of app handlers before this could be called.";
}

void PushNotificationServiceDesktopImpl::OnStoreReset() {
  // Reset prefs.
  pref_service_->SetString(
      prefs::kPushNotificationRepresentativeTargetIdPrefName, std::string());
}

void PushNotificationServiceDesktopImpl::OnMessage(
    const std::string& app_id,
    const gcm::IncomingMessage& message) {
  PushNotificationClientManager::PushNotificationMessage
      push_notification_message;
  push_notification_message.sender_id = message.sender_id;
  push_notification_message.message_id = message.message_id;
  push_notification_message.collapse_key = message.collapse_key;
  push_notification_message.raw_data = message.raw_data;

  for (const auto& data : message.data) {
    push_notification_message.data.insert_or_assign(data.first, data.second);
  }

  client_manager_->NotifyPushNotificationClientOfMessage(
      push_notification_message);
}

void PushNotificationServiceDesktopImpl::OnMessagesDeleted(
    const std::string& app_id) {}
void PushNotificationServiceDesktopImpl::OnSendError(
    const std::string& app_id,
    const gcm::GCMClient::SendErrorDetails& send_error_details) {
  NOTREACHED()
      << "The Push Notification Service shouldn't have sent messages upstream";
}
void PushNotificationServiceDesktopImpl::OnSendAcknowledged(
    const std::string& app_id,
    const std::string& message_id) {
  NOTREACHED()
      << "The Push Notification Service shouldn't have sent messages upstream";
}

// Intentional no-op. We don't support encryption/decryption of messages.
void PushNotificationServiceDesktopImpl::OnMessageDecryptionFailed(
    const std::string& app_id,
    const std::string& message_id,
    const std::string& error_message) {}

// PushNotificationService does not support messages from any other app.
bool PushNotificationServiceDesktopImpl::CanHandle(
    const std::string& app_id) const {
  return false;
}

void PushNotificationServiceDesktopImpl::Shutdown() {
  client_manager_.reset();
  token_.clear();
  instance_id_driver_->GetInstanceID(kPushNotificationAppId)
      ->gcm_driver()
      ->RemoveAppHandler(kPushNotificationAppId);
}

void PushNotificationServiceDesktopImpl::Initialize() {
  if (is_initialized_) {
    return;
  }

  instance_id_driver_->GetInstanceID(kPushNotificationAppId)
      ->GetToken(
          kPushNotificationSenderId, kPushNotificationScope,
          /*time_to_live=*/base::TimeDelta(), /*flags=*/{},
          base::BindOnce(&PushNotificationServiceDesktopImpl::OnTokenReceived,
                         base::Unretained(this), /*token_request_start_time=*/
                         base::TimeTicks::Now()));
}

void PushNotificationServiceDesktopImpl::OnTokenReceived(
    base::TimeTicks token_request_start_time,
    const std::string& token,
    instance_id::InstanceID::Result result) {
  if (result != instance_id::InstanceID::Result::SUCCESS) {
    LOG(ERROR) << "Failed to retrieve GCM token: " << result;
    metrics::RecordPushNotificationGcmTokenRetrievalResult(/*success=*/false);
    initialization_on_demand_scheduler_->HandleResult(/*success=*/false);
    return;
  }

  metrics::RecordPushNotificationGcmTokenRetrievalResult(/*success=*/true);
  metrics::RecordPushNotificationServiceTimeToRetrieveToken(
      /*total_retrieval_time=*/base::TimeTicks::Now() -
      token_request_start_time);
  VLOG(1) << "Successfully retrieved GCM token. ";
  token_ = token;

  // Add `PushNotificationService` as a GCM app handler.
  instance_id_driver_->GetInstanceID(kPushNotificationAppId)
      ->gcm_driver()
      ->AddAppHandler(kPushNotificationAppId, this);

  std::string representative_target_id = pref_service_->GetString(
      prefs::kPushNotificationRepresentativeTargetIdPrefName);

  // Create the `NotificationsMultiLoginUpdateRequest` proto which is used to
  // make the registration API call.
  push_notification::proto::NotificationsMultiLoginUpdateRequest request_proto;
  request_proto.mutable_target()->set_channel_type(
      push_notification::proto::ChannelType::GCM_DEVICE_PUSH);
  request_proto.mutable_target()
      ->mutable_delivery_address()
      ->mutable_gcm_device_address()
      ->set_registration_id(token_);
  request_proto.mutable_target()
      ->mutable_delivery_address()
      ->mutable_gcm_device_address()
      ->set_application_id(kPushNotificationAppId);

  // `representative_target_id` is left empty the first time we register with
  // the Push Notification Service. It is then returned to us in the response
  // proto and stored in prefs. When we have a stored representative target id,
  // we use it to help the Push Notification Service stablize the target across
  // registrations if the GCM registration token changes.
  if (!representative_target_id.empty()) {
    request_proto.mutable_target()->set_representative_target_id(
        representative_target_id);
  }
  request_proto.add_registrations();
  request_proto.set_registration_reason(
      push_notification::proto::RegistrationReason::COLLABORATOR_API_CALL);
  request_proto.set_client_id(kClientId);

  // Construct a HTTP client for the request. The HTTP client lifetime is
  // tied to a single request.
  server_client_ = PushNotificationServerClientDesktopImpl::Factory::Create(
      std::make_unique<PushNotificationDesktopApiCallFlowImpl>(),
      identity_manager_, url_loader_factory_);

  server_client_->RegisterWithPushNotificationService(
      request_proto,
      base::BindOnce(&PushNotificationServiceDesktopImpl::
                         OnPushNotificationRegistrationSuccess,
                     weak_ptr_factory_.GetWeakPtr(),
                     /*api_call_start_time=*/base::TimeTicks::Now()),
      base::BindOnce(&PushNotificationServiceDesktopImpl::
                         OnPushNotificationRegistrationFailure,
                     weak_ptr_factory_.GetWeakPtr(),
                     /*api_call_start_time=*/base::TimeTicks::Now()));
}

void PushNotificationServiceDesktopImpl::OnPushNotificationRegistrationSuccess(
    base::TimeTicks api_call_start_time,
    const proto::NotificationsMultiLoginUpdateResponse& response) {
  metrics::
      RecordPushNotificationServiceTimeToReceiveRegistrationSuccessResponse(
          /*registration_response_time=*/base::TimeTicks::Now() -
          api_call_start_time);
  metrics::RecordPushNotificationServiceRegistrationResult(/*success=*/true);
  VLOG(1) << __func__ << ": Push notification service registration successful";
  is_initialized_ = true;
  server_client_.reset();
  initialization_on_demand_scheduler_->HandleResult(/*success=*/true);
  CHECK(response.registration_results_size() == 1);
  pref_service_->SetString(
      prefs::kPushNotificationRepresentativeTargetIdPrefName,
      response.registration_results(0).target().representative_target_id());
}

void PushNotificationServiceDesktopImpl::OnPushNotificationRegistrationFailure(
    base::TimeTicks api_call_start_time,
    PushNotificationDesktopApiCallFlow::PushNotificationApiCallFlowError
        error) {
  metrics::
      RecordPushNotificationServiceTimeToReceiveRegistrationFailureResponse(
          /*registration_response_time=*/base::TimeTicks::Now() -
          api_call_start_time);
  metrics::RecordPushNotificationServiceRegistrationResult(/*success=*/false);
  LOG(ERROR) << __func__
             << ": Push notification service registration failure: " << error;
  server_client_.reset();

  // Remove ourselves as a GCM app handler since initialization failed.
  instance_id_driver_->GetInstanceID(kPushNotificationAppId)
      ->gcm_driver()
      ->RemoveAppHandler(kPushNotificationAppId);

  initialization_on_demand_scheduler_->HandleResult(/*success=*/false);
}

}  // namespace push_notification