Upstream version 6.35.121.0
[platform/framework/web/crosswalk.git] / src / google_apis / gcm / gcm_client_impl.h
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.
4
5 #ifndef GOOGLE_APIS_GCM_GCM_CLIENT_IMPL_H_
6 #define GOOGLE_APIS_GCM_GCM_CLIENT_IMPL_H_
7
8 #include <map>
9 #include <string>
10 #include <vector>
11
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"
25
26 class GURL;
27
28 namespace base {
29 class Clock;
30 }  // namespace base
31
32 namespace net {
33 class HttpNetworkSession;
34 }  // namespace net
35
36 namespace gcm {
37
38 class CheckinRequest;
39 class ConnectionFactory;
40 class GCMClientImplTest;
41
42 // Helper class for building GCM internals. Allows tests to inject fake versions
43 // as necessary.
44 class GCM_EXPORT GCMInternalsBuilder {
45  public:
46   GCMInternalsBuilder();
47   virtual ~GCMInternalsBuilder();
48
49   virtual scoped_ptr<base::Clock> BuildClock();
50   virtual scoped_ptr<MCSClient> BuildMCSClient(
51       const std::string& version,
52       base::Clock* clock,
53       ConnectionFactory* connection_factory,
54       GCMStore* gcm_store);
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);
60 };
61
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 {
67  public:
68   explicit GCMClientImpl(scoped_ptr<GCMInternalsBuilder> internals_builder);
69   virtual ~GCMClientImpl();
70
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;
90
91  private:
92   // State representation of the GCMClient.
93   // Any change made to this enum should have corresponding change in the
94   // GetStateString(...) function.
95   enum State {
96     // Uninitialized.
97     UNINITIALIZED,
98     // Initialized,
99     INITIALIZED,
100     // GCM store loading is in progress.
101     LOADING,
102     // Initial device checkin is in progress.
103     INITIAL_DEVICE_CHECKIN,
104     // Ready to accept requests.
105     READY,
106   };
107
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; }
112     void Reset() {
113       android_id = 0;
114       secret = 0;
115     }
116
117     uint64 android_id;
118     uint64 secret;
119   };
120
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;
126
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;
132
133   friend class GCMClientImplTest;
134
135   // Returns text representation of the enum State.
136   std::string GetStateString() const;
137
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.
147   void OnMCSError();
148
149   // Runs after GCM Store load is done to trigger continuation of the
150   // initialization.
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.
159   void ResetState();
160   // Sets state to ready. This will initiate the MCS login and notify the
161   // delegates.
162   void OnReady();
163
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);
171
172   // Callback for persisting device credentials in the |gcm_store_|.
173   void SetDeviceCredentialsCallback(bool success);
174
175   // Callback for persisting registration info in the |gcm_store_|.
176   void UpdateRegistrationCallback(bool success);
177
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);
183
184   // Completes the unregistration request.
185   void OnUnregisterCompleted(const std::string& app_id,
186                              UnregistrationRequest::Status status);
187
188   // Completes the GCM store destroy request.
189   void OnGCMStoreDestroyed(bool success);
190
191   // Handles incoming data message and dispatches it the delegate of this class.
192   void HandleIncomingMessage(const gcm::MCSMessage& message);
193
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);
199
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);
205
206   // Builder for the GCM internals (mcs client, etc.).
207   scoped_ptr<GCMInternalsBuilder> internals_builder_;
208
209   // State of the GCM Client Implementation.
210   State state_;
211
212   Delegate* delegate_;
213
214   // Device checkin info (android ID and security token used by device).
215   CheckinInfo device_checkin_info_;
216
217   // Clock used for timing of retry logic. Passed in for testing. Owned by
218   // GCMClientImpl.
219   scoped_ptr<base::Clock> clock_;
220
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_;
224
225   // Persistent data store for keeping device credentials, messages and user to
226   // serial number mappings.
227   scoped_ptr<GCMStore> gcm_store_;
228
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_;
233
234   // Controls receiving and sending of packets and reliable message queueing.
235   scoped_ptr<MCSClient> mcs_client_;
236
237   scoped_ptr<CheckinRequest> checkin_request_;
238   std::vector<std::string> account_ids_;
239
240   // Cached registration info.
241   RegistrationInfoMap registrations_;
242
243   // Currently pending registration requests. GCMClientImpl owns the
244   // RegistrationRequests.
245   PendingRegistrationRequests pending_registration_requests_;
246   STLValueDeleter<PendingRegistrationRequests>
247       pending_registration_requests_deleter_;
248
249   // Currently pending unregistration requests. GCMClientImpl owns the
250   // UnregistrationRequests.
251   PendingUnregistrationRequests pending_unregistration_requests_;
252   STLValueDeleter<PendingUnregistrationRequests>
253       pending_unregistration_requests_deleter_;
254
255   // Factory for creating references in callbacks.
256   base::WeakPtrFactory<GCMClientImpl> weak_ptr_factory_;
257
258   DISALLOW_COPY_AND_ASSIGN(GCMClientImpl);
259 };
260
261 }  // namespace gcm
262
263 #endif  // GOOGLE_APIS_GCM_GCM_CLIENT_IMPL_H_