Upstream version 5.34.104.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/gcm_client.h"
21 #include "google_apis/gcm/protocol/android_checkin.pb.h"
22 #include "net/base/net_log.h"
23 #include "net/url_request/url_request_context_getter.h"
24
25 namespace base {
26 class Clock;
27 }  // namespace base
28
29 namespace net {
30 class HttpNetworkSession;
31 }  // namespace net
32
33 namespace gcm {
34
35 class CheckinRequest;
36 class ConnectionFactory;
37 class GCMClientImplTest;
38 class UnregistrationRequest;
39
40 // Implements the GCM Client. It is used to coordinate MCS Client (communication
41 // with MCS) and other pieces of GCM infrastructure like Registration and
42 // Checkins. It also allows for registering user delegates that host
43 // applications that send and receive messages.
44 class GCM_EXPORT GCMClientImpl : public GCMClient {
45  public:
46   GCMClientImpl();
47   virtual ~GCMClientImpl();
48
49   // Overridden from GCMClient:
50   virtual void Initialize(
51       const checkin_proto::ChromeBuildProto& chrome_build_proto,
52       const base::FilePath& store_path,
53       const scoped_refptr<base::SequencedTaskRunner>& blocking_task_runner,
54       const scoped_refptr<net::URLRequestContextGetter>&
55           url_request_context_getter,
56       Delegate* delegate) OVERRIDE;
57   virtual void CheckOut() OVERRIDE;
58   virtual void Register(const std::string& app_id,
59                         const std::string& cert,
60                         const std::vector<std::string>& sender_ids) OVERRIDE;
61   virtual void Unregister(const std::string& app_id) OVERRIDE;
62   virtual void Send(const std::string& app_id,
63                     const std::string& receiver_id,
64                     const OutgoingMessage& message) OVERRIDE;
65   virtual bool IsReady() const OVERRIDE;
66
67  private:
68   // State representation of the GCMClient.
69   enum State {
70     // Uninitialized.
71     UNINITIALIZED,
72     // GCM store loading is in progress.
73     LOADING,
74     // Initial device checkin is in progress.
75     INITIAL_DEVICE_CHECKIN,
76     // Ready to accept requests.
77     READY,
78   };
79
80   // The check-in info for the user. Returned by the server.
81   struct GCM_EXPORT CheckinInfo {
82     CheckinInfo() : android_id(0), secret(0) {}
83     bool IsValid() const { return android_id != 0 && secret != 0; }
84     void Reset() {
85       android_id = 0;
86       secret = 0;
87     }
88
89     uint64 android_id;
90     uint64 secret;
91   };
92
93   // Collection of pending registration requests. Keys are app IDs, while values
94   // are pending registration requests to obtain a registration ID for
95   // requesting application.
96   typedef std::map<std::string, RegistrationRequest*>
97       PendingRegistrations;
98
99   // Collection of pending unregistration requests. Keys are app IDs, while
100   // values are pending unregistration requests to disable the registration ID
101   // currently assigned to the application.
102   typedef std::map<std::string, UnregistrationRequest*>
103       PendingUnregistrations;
104
105   friend class GCMClientImplTest;
106
107   // Callbacks for the MCSClient.
108   // Receives messages and dispatches them to relevant user delegates.
109   void OnMessageReceivedFromMCS(const gcm::MCSMessage& message);
110   // Receives confirmation of sent messages or information about errors.
111   void OnMessageSentToMCS(int64 user_serial_number,
112                           const std::string& app_id,
113                           const std::string& message_id,
114                           MCSClient::MessageSendStatus status);
115   // Receives information about mcs_client_ errors.
116   void OnMCSError();
117
118   // Runs after GCM Store load is done to trigger continuation of the
119   // initialization.
120   void OnLoadCompleted(scoped_ptr<GCMStore::LoadResult> result);
121   // Initializes mcs_client_, which handles the connection to MCS.
122   void InitializeMCSClient(scoped_ptr<GCMStore::LoadResult> result);
123   // Complets the first time device checkin.
124   void OnFirstTimeDeviceCheckinCompleted(const CheckinInfo& checkin_info);
125   // Starts a login on mcs_client_.
126   void StartMCSLogin();
127   // Resets state to before initialization.
128   void ResetState();
129   // Sets state to ready. This will initiate the MCS login and notify the
130   // delegates.
131   void OnReady();
132
133   // Starts a first time device checkin.
134   void StartCheckin(const CheckinInfo& checkin_info);
135   // Completes the device checkin request.
136   // |android_id| and |security_token| are expected to be non-zero or an error
137   // is triggered. Function also cleans up the pending checkin.
138   void OnCheckinCompleted(uint64 android_id,
139                           uint64 security_token);
140
141   // Callback for persisting device credentials in the |gcm_store_|.
142   void SetDeviceCredentialsCallback(bool success);
143
144   // Completes the registration request.
145   void OnRegisterCompleted(const std::string& app_id,
146                            RegistrationRequest::Status status,
147                            const std::string& registration_id);
148
149   // Completes the unregistration request.
150   void OnUnregisterCompleted(const std::string& app_id, bool status);
151
152   // Handles incoming data message and dispatches it the a relevant user
153   // delegate.
154   void HandleIncomingMessage(const gcm::MCSMessage& message);
155
156   // Fires OnMessageSendError event on |delegate|, with specified |app_id| and
157   // message ID obtained from |incoming_message| if one is available.
158   void NotifyDelegateOnMessageSendError(
159       GCMClient::Delegate* delegate,
160       const std::string& app_id,
161       const IncomingMessage& incoming_message);
162
163   // For testing purpose only.
164   // Sets an |mcs_client_| for testing. Takes the ownership of |mcs_client|.
165   // TODO(fgorski): Remove this method. Create GCMEngineFactory that will create
166   // components of the engine.
167   void SetMCSClientForTesting(scoped_ptr<MCSClient> mcs_client);
168
169   // State of the GCM Client Implementation.
170   State state_;
171
172   Delegate* delegate_;
173
174   // Device checkin info (android ID and security token used by device).
175   CheckinInfo device_checkin_info_;
176
177   // Clock used for timing of retry logic. Passed in for testing. Owned by
178   // GCMClientImpl.
179   scoped_ptr<base::Clock> clock_;
180
181   // Information about the chrome build.
182   // TODO(fgorski): Check if it can be passed in constructor and made const.
183   checkin_proto::ChromeBuildProto chrome_build_proto_;
184
185   // Persistent data store for keeping device credentials, messages and user to
186   // serial number mappings.
187   scoped_ptr<GCMStore> gcm_store_;
188
189   scoped_refptr<net::HttpNetworkSession> network_session_;
190   net::BoundNetLog net_log_;
191   scoped_ptr<ConnectionFactory> connection_factory_;
192   scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
193
194   // Controls receiving and sending of packets and reliable message queueing.
195   scoped_ptr<MCSClient> mcs_client_;
196
197   scoped_ptr<CheckinRequest> checkin_request_;
198
199   // Currently pending registrations. GCMClientImpl owns the
200   // RegistrationRequests.
201   PendingRegistrations pending_registrations_;
202   STLValueDeleter<PendingRegistrations> pending_registrations_deleter_;
203
204   // Currently pending unregistrations. GCMClientImpl owns the
205   // UnregistrationRequests.
206   PendingUnregistrations pending_unregistrations_;
207   STLValueDeleter<PendingUnregistrations> pending_unregistrations_deleter_;
208
209   // Factory for creating references in callbacks.
210   base::WeakPtrFactory<GCMClientImpl> weak_ptr_factory_;
211
212   DISALLOW_COPY_AND_ASSIGN(GCMClientImpl);
213 };
214
215 }  // namespace gcm
216
217 #endif  // GOOGLE_APIS_GCM_GCM_CLIENT_IMPL_H_