1 // Copyright 2014 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.
5 #ifndef COMPONENTS_GCM_DRIVER_GCM_CLIENT_IMPL_H_
6 #define COMPONENTS_GCM_DRIVER_GCM_CLIENT_IMPL_H_
12 #include "base/compiler_specific.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/stl_util.h"
16 #include "components/gcm_driver/gcm_client.h"
17 #include "components/gcm_driver/gcm_stats_recorder_impl.h"
18 #include "google_apis/gcm/base/mcs_message.h"
19 #include "google_apis/gcm/engine/gcm_store.h"
20 #include "google_apis/gcm/engine/gservices_settings.h"
21 #include "google_apis/gcm/engine/mcs_client.h"
22 #include "google_apis/gcm/engine/registration_request.h"
23 #include "google_apis/gcm/engine/unregistration_request.h"
24 #include "google_apis/gcm/protocol/android_checkin.pb.h"
25 #include "google_apis/gcm/protocol/checkin.pb.h"
26 #include "net/base/net_log.h"
27 #include "net/url_request/url_request_context_getter.h"
37 class DataMessageStanza
;
38 } // namespace mcs_proto
41 class HttpNetworkSession
;
47 class ConnectionFactory
;
48 class GCMClientImplTest
;
50 // Helper class for building GCM internals. Allows tests to inject fake versions
52 class GCMInternalsBuilder
{
54 GCMInternalsBuilder();
55 virtual ~GCMInternalsBuilder();
57 virtual scoped_ptr
<base::Clock
> BuildClock();
58 virtual scoped_ptr
<MCSClient
> BuildMCSClient(
59 const std::string
& version
,
61 ConnectionFactory
* connection_factory
,
63 GCMStatsRecorder
* recorder
);
64 virtual scoped_ptr
<ConnectionFactory
> BuildConnectionFactory(
65 const std::vector
<GURL
>& endpoints
,
66 const net::BackoffEntry::Policy
& backoff_policy
,
67 scoped_refptr
<net::HttpNetworkSession
> network_session
,
69 GCMStatsRecorder
* recorder
);
72 // Implements the GCM Client. It is used to coordinate MCS Client (communication
73 // with MCS) and other pieces of GCM infrastructure like Registration and
74 // Checkins. It also allows for registering user delegates that host
75 // applications that send and receive messages.
77 : public GCMClient
, public GCMStatsRecorder::Delegate
,
78 public ConnectionFactory::ConnectionListener
{
80 explicit GCMClientImpl(scoped_ptr
<GCMInternalsBuilder
> internals_builder
);
81 virtual ~GCMClientImpl();
83 // GCMClient implementation.
84 virtual void Initialize(
85 const ChromeBuildInfo
& chrome_build_info
,
86 const base::FilePath
& store_path
,
87 const std::vector
<std::string
>& account_ids
,
88 const scoped_refptr
<base::SequencedTaskRunner
>& blocking_task_runner
,
89 const scoped_refptr
<net::URLRequestContextGetter
>&
90 url_request_context_getter
,
91 scoped_ptr
<Encryptor
> encryptor
,
92 GCMClient::Delegate
* delegate
) OVERRIDE
;
93 virtual void Start() OVERRIDE
;
94 virtual void Stop() OVERRIDE
;
95 virtual void CheckOut() OVERRIDE
;
96 virtual void Register(const std::string
& app_id
,
97 const std::vector
<std::string
>& sender_ids
) OVERRIDE
;
98 virtual void Unregister(const std::string
& app_id
) OVERRIDE
;
99 virtual void Send(const std::string
& app_id
,
100 const std::string
& receiver_id
,
101 const OutgoingMessage
& message
) OVERRIDE
;
102 virtual void SetRecording(bool recording
) OVERRIDE
;
103 virtual void ClearActivityLogs() OVERRIDE
;
104 virtual GCMStatistics
GetStatistics() const OVERRIDE
;
106 // GCMStatsRecorder::Delegate implemenation.
107 virtual void OnActivityRecorded() OVERRIDE
;
109 // ConnectionFactory::ConnectionListener implementation.
110 virtual void OnConnected(const GURL
& current_server
,
111 const net::IPEndPoint
& ip_endpoint
) OVERRIDE
;
112 virtual void OnDisconnected() OVERRIDE
;
115 // State representation of the GCMClient.
116 // Any change made to this enum should have corresponding change in the
117 // GetStateString(...) function.
123 // GCM store loading is in progress.
125 // Initial device checkin is in progress.
126 INITIAL_DEVICE_CHECKIN
,
127 // Ready to accept requests.
131 // The check-in info for the user. Returned by the server.
133 CheckinInfo() : android_id(0), secret(0) {}
134 bool IsValid() const { return android_id
!= 0 && secret
!= 0; }
144 // Collection of pending registration requests. Keys are app IDs, while values
145 // are pending registration requests to obtain a registration ID for
146 // requesting application.
147 typedef std::map
<std::string
, RegistrationRequest
*>
148 PendingRegistrationRequests
;
150 // Collection of pending unregistration requests. Keys are app IDs, while
151 // values are pending unregistration requests to disable the registration ID
152 // currently assigned to the application.
153 typedef std::map
<std::string
, UnregistrationRequest
*>
154 PendingUnregistrationRequests
;
156 friend class GCMClientImplTest
;
158 // Returns text representation of the enum State.
159 std::string
GetStateString() const;
161 // Callbacks for the MCSClient.
162 // Receives messages and dispatches them to relevant user delegates.
163 void OnMessageReceivedFromMCS(const gcm::MCSMessage
& message
);
164 // Receives confirmation of sent messages or information about errors.
165 void OnMessageSentToMCS(int64 user_serial_number
,
166 const std::string
& app_id
,
167 const std::string
& message_id
,
168 MCSClient::MessageSendStatus status
);
169 // Receives information about mcs_client_ errors.
172 // Runs after GCM Store load is done to trigger continuation of the
174 void OnLoadCompleted(scoped_ptr
<GCMStore::LoadResult
> result
);
175 // Initializes mcs_client_, which handles the connection to MCS.
176 void InitializeMCSClient(scoped_ptr
<GCMStore::LoadResult
> result
);
177 // Complets the first time device checkin.
178 void OnFirstTimeDeviceCheckinCompleted(const CheckinInfo
& checkin_info
);
179 // Starts a login on mcs_client_.
180 void StartMCSLogin();
181 // Resets state to before initialization.
183 // Sets state to ready. This will initiate the MCS login and notify the
187 // Starts a first time device checkin.
189 // Completes the device checkin request by parsing the |checkin_response|.
190 // Function also cleans up the pending checkin.
191 void OnCheckinCompleted(
192 const checkin_proto::AndroidCheckinResponse
& checkin_response
);
194 // Callback passed to GCMStore::SetGServicesSettings.
195 void SetGServicesSettingsCallback(bool success
);
197 // Schedules next periodic device checkin and makes sure there is at most one
198 // pending checkin at a time. This function is meant to be called after a
199 // successful checkin.
200 void SchedulePeriodicCheckin();
201 // Gets the time until next checkin.
202 base::TimeDelta
GetTimeToNextCheckin() const;
203 // Callback for setting last checkin time in the |gcm_store_|.
204 void SetLastCheckinTimeCallback(bool success
);
206 // Callback for persisting device credentials in the |gcm_store_|.
207 void SetDeviceCredentialsCallback(bool success
);
209 // Callback for persisting registration info in the |gcm_store_|.
210 void UpdateRegistrationCallback(bool success
);
212 // Completes the registration request.
213 void OnRegisterCompleted(const std::string
& app_id
,
214 const std::vector
<std::string
>& sender_ids
,
215 RegistrationRequest::Status status
,
216 const std::string
& registration_id
);
218 // Completes the unregistration request.
219 void OnUnregisterCompleted(const std::string
& app_id
,
220 UnregistrationRequest::Status status
);
222 // Completes the GCM store destroy request.
223 void OnGCMStoreDestroyed(bool success
);
225 // Handles incoming data message and dispatches it the delegate of this class.
226 void HandleIncomingMessage(const gcm::MCSMessage
& message
);
228 // Fires OnMessageReceived event on the delegate of this class, based on the
229 // details in |data_message_stanza| and |message_data|.
230 void HandleIncomingDataMessage(
231 const mcs_proto::DataMessageStanza
& data_message_stanza
,
232 MessageData
& message_data
);
234 // Fires OnMessageSendError event on the delegate of this calss, based on the
235 // details in |data_message_stanza| and |message_data|.
236 void HandleIncomingSendError(
237 const mcs_proto::DataMessageStanza
& data_message_stanza
,
238 MessageData
& message_data
);
240 // Builder for the GCM internals (mcs client, etc.).
241 scoped_ptr
<GCMInternalsBuilder
> internals_builder_
;
243 // Recorder that logs GCM activities.
244 GCMStatsRecorderImpl recorder_
;
246 // State of the GCM Client Implementation.
249 GCMClient::Delegate
* delegate_
;
251 // Device checkin info (android ID and security token used by device).
252 CheckinInfo device_checkin_info_
;
254 // Clock used for timing of retry logic. Passed in for testing. Owned by
256 scoped_ptr
<base::Clock
> clock_
;
258 // Information about the chrome build.
259 // TODO(fgorski): Check if it can be passed in constructor and made const.
260 ChromeBuildInfo chrome_build_info_
;
262 // Persistent data store for keeping device credentials, messages and user to
263 // serial number mappings.
264 scoped_ptr
<GCMStore
> gcm_store_
;
266 scoped_refptr
<net::HttpNetworkSession
> network_session_
;
267 net::BoundNetLog net_log_
;
268 scoped_ptr
<ConnectionFactory
> connection_factory_
;
269 scoped_refptr
<net::URLRequestContextGetter
> url_request_context_getter_
;
271 // Controls receiving and sending of packets and reliable message queueing.
272 scoped_ptr
<MCSClient
> mcs_client_
;
274 scoped_ptr
<CheckinRequest
> checkin_request_
;
275 std::vector
<std::string
> account_ids_
;
277 // Cached registration info.
278 RegistrationInfoMap registrations_
;
280 // Currently pending registration requests. GCMClientImpl owns the
281 // RegistrationRequests.
282 PendingRegistrationRequests pending_registration_requests_
;
283 STLValueDeleter
<PendingRegistrationRequests
>
284 pending_registration_requests_deleter_
;
286 // Currently pending unregistration requests. GCMClientImpl owns the
287 // UnregistrationRequests.
288 PendingUnregistrationRequests pending_unregistration_requests_
;
289 STLValueDeleter
<PendingUnregistrationRequests
>
290 pending_unregistration_requests_deleter_
;
292 // G-services settings that were provided by MCS.
293 GServicesSettings gservices_settings_
;
295 // Time of the last successful checkin.
296 base::Time last_checkin_time_
;
298 // Factory for creating references when scheduling periodic checkin.
299 base::WeakPtrFactory
<GCMClientImpl
> periodic_checkin_ptr_factory_
;
301 // Factory for creating references in callbacks.
302 base::WeakPtrFactory
<GCMClientImpl
> weak_ptr_factory_
;
304 DISALLOW_COPY_AND_ASSIGN(GCMClientImpl
);
309 #endif // COMPONENTS_GCM_DRIVER_GCM_CLIENT_IMPL_H_