1 // Copyright 2013 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 GOOGLE_APIS_GCM_GCM_CLIENT_IMPL_H_
6 #define GOOGLE_APIS_GCM_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 "google_apis/gcm/base/mcs_message.h"
17 #include "google_apis/gcm/engine/gcm_store.h"
18 #include "google_apis/gcm/engine/mcs_client.h"
19 #include "google_apis/gcm/engine/registration_request.h"
20 #include "google_apis/gcm/engine/unregistration_request.h"
21 #include "google_apis/gcm/gcm_client.h"
22 #include "google_apis/gcm/protocol/android_checkin.pb.h"
23 #include "net/base/net_log.h"
24 #include "net/url_request/url_request_context_getter.h"
33 class HttpNetworkSession;
39 class ConnectionFactory;
40 class GCMClientImplTest;
42 // Helper class for building GCM internals. Allows tests to inject fake versions
44 class GCM_EXPORT GCMInternalsBuilder {
46 GCMInternalsBuilder();
47 virtual ~GCMInternalsBuilder();
49 virtual scoped_ptr<base::Clock> BuildClock();
50 virtual scoped_ptr<MCSClient> BuildMCSClient(
51 const std::string& version,
53 ConnectionFactory* connection_factory,
55 virtual scoped_ptr<ConnectionFactory> BuildConnectionFactory(
56 const std::vector<GURL>& endpoints,
57 const net::BackoffEntry::Policy& backoff_policy,
58 scoped_refptr<net::HttpNetworkSession> network_session,
59 net::NetLog* net_log);
62 // Implements the GCM Client. It is used to coordinate MCS Client (communication
63 // with MCS) and other pieces of GCM infrastructure like Registration and
64 // Checkins. It also allows for registering user delegates that host
65 // applications that send and receive messages.
66 class GCM_EXPORT GCMClientImpl : public GCMClient {
68 explicit GCMClientImpl(scoped_ptr<GCMInternalsBuilder> internals_builder);
69 virtual ~GCMClientImpl();
71 // Overridden from GCMClient:
72 virtual void Initialize(
73 const checkin_proto::ChromeBuildProto& chrome_build_proto,
74 const base::FilePath& store_path,
75 const std::vector<std::string>& account_ids,
76 const scoped_refptr<base::SequencedTaskRunner>& blocking_task_runner,
77 const scoped_refptr<net::URLRequestContextGetter>&
78 url_request_context_getter,
79 Delegate* delegate) OVERRIDE;
80 virtual void Load() OVERRIDE;
81 virtual void Stop() OVERRIDE;
82 virtual void CheckOut() OVERRIDE;
83 virtual void Register(const std::string& app_id,
84 const std::vector<std::string>& sender_ids) OVERRIDE;
85 virtual void Unregister(const std::string& app_id) OVERRIDE;
86 virtual void Send(const std::string& app_id,
87 const std::string& receiver_id,
88 const OutgoingMessage& message) OVERRIDE;
89 virtual GCMStatistics GetStatistics() const OVERRIDE;
92 // State representation of the GCMClient.
93 // Any change made to this enum should have corresponding change in the
94 // GetStateString(...) function.
100 // GCM store loading is in progress.
102 // Initial device checkin is in progress.
103 INITIAL_DEVICE_CHECKIN,
104 // Ready to accept requests.
108 // The check-in info for the user. Returned by the server.
109 struct GCM_EXPORT CheckinInfo {
110 CheckinInfo() : android_id(0), secret(0) {}
111 bool IsValid() const { return android_id != 0 && secret != 0; }
121 // Collection of pending registration requests. Keys are app IDs, while values
122 // are pending registration requests to obtain a registration ID for
123 // requesting application.
124 typedef std::map<std::string, RegistrationRequest*>
125 PendingRegistrationRequests;
127 // Collection of pending unregistration requests. Keys are app IDs, while
128 // values are pending unregistration requests to disable the registration ID
129 // currently assigned to the application.
130 typedef std::map<std::string, UnregistrationRequest*>
131 PendingUnregistrationRequests;
133 friend class GCMClientImplTest;
135 // Returns text representation of the enum State.
136 std::string GetStateString() const;
138 // Callbacks for the MCSClient.
139 // Receives messages and dispatches them to relevant user delegates.
140 void OnMessageReceivedFromMCS(const gcm::MCSMessage& message);
141 // Receives confirmation of sent messages or information about errors.
142 void OnMessageSentToMCS(int64 user_serial_number,
143 const std::string& app_id,
144 const std::string& message_id,
145 MCSClient::MessageSendStatus status);
146 // Receives information about mcs_client_ errors.
149 // Runs after GCM Store load is done to trigger continuation of the
151 void OnLoadCompleted(scoped_ptr<GCMStore::LoadResult> result);
152 // Initializes mcs_client_, which handles the connection to MCS.
153 void InitializeMCSClient(scoped_ptr<GCMStore::LoadResult> result);
154 // Complets the first time device checkin.
155 void OnFirstTimeDeviceCheckinCompleted(const CheckinInfo& checkin_info);
156 // Starts a login on mcs_client_.
157 void StartMCSLogin();
158 // Resets state to before initialization.
160 // Sets state to ready. This will initiate the MCS login and notify the
164 // Starts a first time device checkin.
165 void StartCheckin(const CheckinInfo& checkin_info);
166 // Completes the device checkin request.
167 // |android_id| and |security_token| are expected to be non-zero or an error
168 // is triggered. Function also cleans up the pending checkin.
169 void OnCheckinCompleted(uint64 android_id,
170 uint64 security_token);
172 // Callback for persisting device credentials in the |gcm_store_|.
173 void SetDeviceCredentialsCallback(bool success);
175 // Callback for persisting registration info in the |gcm_store_|.
176 void UpdateRegistrationCallback(bool success);
178 // Completes the registration request.
179 void OnRegisterCompleted(const std::string& app_id,
180 const std::vector<std::string>& sender_ids,
181 RegistrationRequest::Status status,
182 const std::string& registration_id);
184 // Completes the unregistration request.
185 void OnUnregisterCompleted(const std::string& app_id,
186 UnregistrationRequest::Status status);
188 // Completes the GCM store destroy request.
189 void OnGCMStoreDestroyed(bool success);
191 // Handles incoming data message and dispatches it the delegate of this class.
192 void HandleIncomingMessage(const gcm::MCSMessage& message);
194 // Fires OnMessageReceived event on the delegate of this class, based on the
195 // details in |data_message_stanza| and |message_data|.
196 void HandleIncomingDataMessage(
197 const mcs_proto::DataMessageStanza& data_message_stanza,
198 MessageData& message_data);
200 // Fires OnMessageSendError event on the delegate of this calss, based on the
201 // details in |data_message_stanza| and |message_data|.
202 void HandleIncomingSendError(
203 const mcs_proto::DataMessageStanza& data_message_stanza,
204 MessageData& message_data);
206 // Builder for the GCM internals (mcs client, etc.).
207 scoped_ptr<GCMInternalsBuilder> internals_builder_;
209 // State of the GCM Client Implementation.
214 // Device checkin info (android ID and security token used by device).
215 CheckinInfo device_checkin_info_;
217 // Clock used for timing of retry logic. Passed in for testing. Owned by
219 scoped_ptr<base::Clock> clock_;
221 // Information about the chrome build.
222 // TODO(fgorski): Check if it can be passed in constructor and made const.
223 checkin_proto::ChromeBuildProto chrome_build_proto_;
225 // Persistent data store for keeping device credentials, messages and user to
226 // serial number mappings.
227 scoped_ptr<GCMStore> gcm_store_;
229 scoped_refptr<net::HttpNetworkSession> network_session_;
230 net::BoundNetLog net_log_;
231 scoped_ptr<ConnectionFactory> connection_factory_;
232 scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
234 // Controls receiving and sending of packets and reliable message queueing.
235 scoped_ptr<MCSClient> mcs_client_;
237 scoped_ptr<CheckinRequest> checkin_request_;
238 std::vector<std::string> account_ids_;
240 // Cached registration info.
241 RegistrationInfoMap registrations_;
243 // Currently pending registration requests. GCMClientImpl owns the
244 // RegistrationRequests.
245 PendingRegistrationRequests pending_registration_requests_;
246 STLValueDeleter<PendingRegistrationRequests>
247 pending_registration_requests_deleter_;
249 // Currently pending unregistration requests. GCMClientImpl owns the
250 // UnregistrationRequests.
251 PendingUnregistrationRequests pending_unregistration_requests_;
252 STLValueDeleter<PendingUnregistrationRequests>
253 pending_unregistration_requests_deleter_;
255 // Factory for creating references in callbacks.
256 base::WeakPtrFactory<GCMClientImpl> weak_ptr_factory_;
258 DISALLOW_COPY_AND_ASSIGN(GCMClientImpl);
263 #endif // GOOGLE_APIS_GCM_GCM_CLIENT_IMPL_H_