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 CLOUD_PRINT_GCP20_PROTOTYPE_CLOUD_REQUESTER_H_
6#define CLOUD_PRINT_GCP20_PROTOTYPE_CLOUD_REQUESTER_H_
7
8#include <string>
9#include <vector>
10
11#include "base/basictypes.h"
12#include "base/callback.h"
13#include "base/memory/weak_ptr.h"
14#include "base/values.h"
15#include "cloud_print/gcp20/prototype/cloud_print_request.h"
16#include "cloud_print/gcp20/prototype/cloud_print_response_parser.h"
17#include "cloud_print/gcp20/prototype/local_settings.h"
18#include "google_apis/gaia/gaia_oauth_client.h"
19
20class CloudPrintURLRequestContextGetter;
21class GURL;
22class URLRequestContextGetter;
23
24extern const char kCloudPrintUrl[];
25
26// Class for requesting CloudPrint server and parsing responses.
27class CloudPrintRequester : public base::SupportsWeakPtr<CloudPrintRequester>,
28                            public gaia::GaiaOAuthClient::Delegate,
29                            public CloudPrintRequest::Delegate {
30 public:
31  class Delegate {
32   public:
33    Delegate() {}
34    virtual ~Delegate() {}
35
36    // Invoked when server respond for registration-start query and response is
37    // successfully parsed.
38    virtual void OnRegistrationStartResponseParsed(
39        const std::string& registration_token,
40        const std::string& complete_invite_url,
41        const std::string& device_id) = 0;
42
43    // Invoked when server responded for registration-getAuthCode query and
44    // response is successfully parsed.
45    virtual void OnRegistrationFinished(
46        const std::string& refresh_token,
47        const std::string& access_token,
48        int access_token_expires_in_seconds) = 0;
49
50    // Invoked when XMPP JID was received and it has to be saved.
51    virtual void OnXmppJidReceived(const std::string& xmpp_jid) = 0;
52
53    // Invoked when access_token was received after UpdateAccesstoken() call.
54    virtual void OnAccesstokenReceviced(const std::string& access_token,
55                                        int expires_in_seconds) = 0;
56
57    // Invoked when server respond with |"success" = false| or we cannot parse
58    // response.
59    virtual void OnRegistrationError(const std::string& description) = 0;
60
61    // Invoked when network connection cannot be established.
62    virtual void OnNetworkError() = 0;
63
64    // Invoked when server error is received or cannot parse json response.
65    virtual void OnServerError(const std::string& description) = 0;
66
67    // Invoked when authorization failed.
68    virtual void OnAuthError() = 0;
69
70    // Invoked when access_token is needed.
71    virtual std::string GetAccessToken() = 0;
72
73    // Invoked when fetch response was received.
74    virtual void OnPrintJobsAvailable(
75        const std::vector<cloud_print_response_parser::Job>& jobs) = 0;
76
77    // Invoked when printjob is finally downloaded and available for printing.
78    virtual void OnPrintJobDownloaded(
79        const cloud_print_response_parser::Job& job) = 0;
80
81    // Invoked when printjob is marked as done on CloudPrint server.
82    virtual void OnPrintJobDone() = 0;
83
84    // Invoked when local settings response was received.
85    virtual void OnLocalSettingsReceived(
86        LocalSettings::State state,
87        const LocalSettings& settings) = 0;
88
89    // Invoked when CURRENT local settings was updated on server.
90    virtual void OnLocalSettingsUpdated() = 0;
91  };
92
93  // Creates and initializes object.
94  CloudPrintRequester(scoped_refptr<base::SingleThreadTaskRunner> task_runner,
95                      Delegate* delegate);
96
97  // Destroys the object.
98  virtual ~CloudPrintRequester();
99
100  // Returns |true| if either |gaia| or |request| is awaiting for response.
101  bool IsBusy() const;
102
103  // Creates query to server for starting registration.
104  void StartRegistration(const std::string& proxy_id,
105                         const std::string& device_name,
106                         const std::string& user,
107                         const LocalSettings& settings,
108                         const std::string& cdd);
109
110  // Creates request for completing registration and receiving refresh token.
111  void CompleteRegistration();
112
113  // Creates request for fetching printjobs.
114  void FetchPrintJobs(const std::string& device_id);
115
116  // Creates request for updating accesstoken.
117  // TODO(maksymb): Handle expiration of accesstoken.
118  void UpdateAccesstoken(const std::string& refresh_token);
119
120  // Creates chain of requests for requesting printjob.
121  void RequestPrintJob(const cloud_print_response_parser::Job& job);
122
123  // Reports server that printjob has been printed.
124  void SendPrintJobDone(const std::string& job_id);
125
126  // Requests /printer API to receive local settings.
127  void RequestLocalSettings(const std::string& device_id);
128
129  // Updates local settings on server.
130  void SendLocalSettings(const std::string& device_id,
131                         const LocalSettings& settings);
132
133 private:
134  typedef base::Callback<void(const std::string&)> ParserCallback;
135
136  // CloudPrintRequester::Delegate methods:
137  virtual void OnFetchComplete(const std::string& response) OVERRIDE;
138  virtual void OnFetchError(const std::string& server_api,
139                            int server_code,
140                            int server_http_code) OVERRIDE;
141  virtual void OnFetchTimeoutReached() OVERRIDE;
142
143  // gaia::GaiaOAuthClient::Delegate methods:
144  virtual void OnGetTokensResponse(const std::string& refresh_token,
145                                   const std::string& access_token,
146                                   int expires_in_seconds) OVERRIDE;
147  virtual void OnRefreshTokenResponse(const std::string& access_token,
148                                      int expires_in_seconds) OVERRIDE;
149  virtual void OnOAuthError() OVERRIDE;
150  virtual void OnNetworkError(int response_code) OVERRIDE;
151
152  // Creates GET request.
153  scoped_ptr<CloudPrintRequest> CreateGet(const GURL& url,
154                                          const ParserCallback& callback);
155
156  // Creates POST request.
157  scoped_ptr<CloudPrintRequest> CreatePost(const GURL& url,
158                                           const std::string& content,
159                                           const std::string& mimetype,
160                                           const ParserCallback& callback);
161
162  // Deletes all info about current request.
163  void EraseRequest();
164
165  // Parses register-start server response.
166  void ParseRegisterStart(const std::string& response);
167
168  // Parses register-complete server response. Initializes gaia (OAuth client)
169  // and receives refresh token.
170  void ParseRegisterComplete(const std::string& response);
171
172  // Parses fetch printjobs server response.
173  void ParseFetch(const std::string& response);
174
175  // Invoked after receiving printjob ticket.
176  void ParseGetPrintJobTicket(const std::string& response);
177
178  // Invoked after receiving printjob file.
179  void ParseGetPrintJobData(const std::string& response);
180
181  // Invoked after marking printjob as DONE.
182  void ParsePrintJobDone(const std::string& response);
183
184  // Invoked after marking printjob as IN_PROGRESS.
185  void ParsePrintJobInProgress(const std::string& response);
186
187  // Invoked after receiving local_settings.
188  void ParseLocalSettings(const std::string& response);
189
190  // Invoked after updating current local_settings.
191  void ParseLocalSettingUpdated(const std::string& response);
192
193  // |request| contains |NULL| if no server response is awaiting. Otherwise wait
194  // until callback will be called will be called and close connection.
195  scoped_ptr<CloudPrintRequest> request_;
196
197  // Contains information about current printjob. Information is filled by
198  // CloudPrint server responses.
199  scoped_ptr<cloud_print_response_parser::Job> current_print_job_;
200
201  // CloudPrint context getter.
202  scoped_refptr<net::URLRequestContextGetter> context_getter_;
203
204  // URL for completing registration and receiving OAuth account.
205  std::string polling_url_;
206
207  // OAuth client information (client_id, client_secret, etc).
208  gaia::OAuthClientInfo oauth_client_info_;
209
210  // OAuth client.
211  scoped_ptr<gaia::GaiaOAuthClient> gaia_;
212
213  ParserCallback parser_callback_;
214
215  Delegate* delegate_;
216
217  DISALLOW_COPY_AND_ASSIGN(CloudPrintRequester);
218};
219
220#endif  // CLOUD_PRINT_GCP20_PROTOTYPE_CLOUD_REQUESTER_H_
221
222