Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(342)

Side by Side Diff: chrome/browser/google_apis/base_requests.h

Issue 96413002: Move c/b/google_apis to google_apis/drive. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Rebase Created 7 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
1 // Copyright (c) 2012 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 // This file provides base classes used to issue HTTP requests for Google
6 // APIs.
7
8 #ifndef CHROME_BROWSER_GOOGLE_APIS_BASE_REQUESTS_H_
9 #define CHROME_BROWSER_GOOGLE_APIS_BASE_REQUESTS_H_
10
11 #include <string>
12 #include <vector>
13
14 #include "base/callback.h"
15 #include "base/files/file_path.h"
16 #include "base/memory/weak_ptr.h"
17 #include "base/threading/thread_checker.h"
18 #include "chrome/browser/google_apis/gdata_errorcode.h"
19 #include "net/url_request/url_fetcher.h"
20 #include "net/url_request/url_fetcher_delegate.h"
21 #include "net/url_request/url_fetcher_response_writer.h"
22 #include "url/gurl.h"
23
24 namespace base {
25 class Value;
26 } // namespace base
27
28 namespace google_apis {
29
30 class RequestSender;
31
32 // Callback used to pass parsed JSON from ParseJson(). If parsing error occurs,
33 // then the passed argument is null.
34 typedef base::Callback<void(scoped_ptr<base::Value> value)> ParseJsonCallback;
35
36 // Callback used for DownloadFileRequest and ResumeUploadRequestBase.
37 typedef base::Callback<void(int64 progress, int64 total)> ProgressCallback;
38
39 // Callback used to get the content from DownloadFileRequest.
40 typedef base::Callback<void(
41 GDataErrorCode error,
42 scoped_ptr<std::string> content)> GetContentCallback;
43
44 // Parses JSON passed in |json| on |blocking_task_runner|. Runs |callback| on
45 // the calling thread when finished with either success or failure.
46 // The callback must not be null.
47 void ParseJson(base::TaskRunner* blocking_task_runner,
48 const std::string& json,
49 const ParseJsonCallback& callback);
50
51 //======================= AuthenticatedRequestInterface ======================
52
53 // An interface class for implementing a request which requires OAuth2
54 // authentication.
55 class AuthenticatedRequestInterface {
56 public:
57 // Called when re-authentication is required. See Start() for details.
58 typedef base::Callback<void(AuthenticatedRequestInterface* request)>
59 ReAuthenticateCallback;
60
61 virtual ~AuthenticatedRequestInterface() {}
62
63 // Starts the request with |access_token|. User-Agent header will be set
64 // to |custom_user_agent| if the value is not empty.
65 //
66 // |callback| is called when re-authentication is needed for a certain
67 // number of times (see kMaxReAuthenticateAttemptsPerRequest in .cc).
68 // The callback should retry by calling Start() again with a new access
69 // token, or just call OnAuthFailed() if a retry is not attempted.
70 // |callback| must not be null.
71 virtual void Start(const std::string& access_token,
72 const std::string& custom_user_agent,
73 const ReAuthenticateCallback& callback) = 0;
74
75 // Invoked when the authentication failed with an error code |code|.
76 virtual void OnAuthFailed(GDataErrorCode code) = 0;
77
78 // Gets a weak pointer to this request object. Since requests may be
79 // deleted when it is canceled by user action, for posting asynchronous tasks
80 // on the authentication request object, weak pointers have to be used.
81 // TODO(kinaba): crbug.com/134814 use more clean life time management than
82 // using weak pointers.
83 virtual base::WeakPtr<AuthenticatedRequestInterface> GetWeakPtr() = 0;
84
85 // Cancels the request. It will invoke the callback object passed in
86 // each request's constructor with error code GDATA_CANCELLED.
87 virtual void Cancel() = 0;
88 };
89
90 //=========================== ResponseWriter ==================================
91
92 // Saves the response for the request to a file or string.
93 class ResponseWriter : public net::URLFetcherResponseWriter {
94 public:
95 // If file_path is not empty, the response will be saved with file_writer_,
96 // otherwise it will be saved to data_.
97 ResponseWriter(net::URLFetcher* url_fetcher,
98 base::SequencedTaskRunner* file_task_runner,
99 const base::FilePath& file_path,
100 const GetContentCallback& get_content_callback);
101 virtual ~ResponseWriter();
102
103 const std::string& data() const { return data_; }
104
105 // Disowns the output file.
106 void DisownFile();
107
108 // URLFetcherResponseWriter overrides:
109 virtual int Initialize(const net::CompletionCallback& callback) OVERRIDE;
110 virtual int Write(net::IOBuffer* buffer,
111 int num_bytes,
112 const net::CompletionCallback& callback) OVERRIDE;
113 virtual int Finish(const net::CompletionCallback& callback) OVERRIDE;
114
115 private:
116 net::URLFetcher* url_fetcher_;
117 const GetContentCallback get_content_callback_;
118 std::string data_;
119 scoped_ptr<net::URLFetcherFileWriter> file_writer_;
120
121 DISALLOW_COPY_AND_ASSIGN(ResponseWriter);
122 };
123
124 //============================ UrlFetchRequestBase ===========================
125
126 // Base class for requests that are fetching URLs.
127 class UrlFetchRequestBase : public AuthenticatedRequestInterface,
128 public net::URLFetcherDelegate {
129 public:
130 // AuthenticatedRequestInterface overrides.
131 virtual void Start(const std::string& access_token,
132 const std::string& custom_user_agent,
133 const ReAuthenticateCallback& callback) OVERRIDE;
134 virtual base::WeakPtr<AuthenticatedRequestInterface> GetWeakPtr() OVERRIDE;
135 virtual void Cancel() OVERRIDE;
136
137 protected:
138 explicit UrlFetchRequestBase(RequestSender* sender);
139 virtual ~UrlFetchRequestBase();
140
141 // Gets URL for the request.
142 virtual GURL GetURL() const = 0;
143
144 // Returns the request type. A derived class should override this method
145 // for a request type other than HTTP GET.
146 virtual net::URLFetcher::RequestType GetRequestType() const;
147
148 // Returns the extra HTTP headers for the request. A derived class should
149 // override this method to specify any extra headers needed for the request.
150 virtual std::vector<std::string> GetExtraRequestHeaders() const;
151
152 // Used by a derived class to add any content data to the request.
153 // Returns true if |upload_content_type| and |upload_content| are updated
154 // with the content type and data for the request.
155 // Note that this and GetContentFile() cannot be used together.
156 virtual bool GetContentData(std::string* upload_content_type,
157 std::string* upload_content);
158
159 // Used by a derived class to add content data which is the whole file or
160 // a part of the file at |local_file_path|.
161 // Returns true if all the arguments are updated for the content being
162 // uploaded.
163 // Note that this and GetContentData() cannot be used together.
164 virtual bool GetContentFile(base::FilePath* local_file_path,
165 int64* range_offset,
166 int64* range_length,
167 std::string* upload_content_type);
168
169 // Used by a derived class to set an output file path if they want to save
170 // the downloaded content to a file at a specific path.
171 // Sets |get_content_callback|, which is called when some part of the response
172 // is read.
173 virtual void GetOutputFilePath(base::FilePath* local_file_path,
174 GetContentCallback* get_content_callback);
175
176 // Invoked by OnURLFetchComplete when the request completes without an
177 // authentication error. Must be implemented by a derived class.
178 virtual void ProcessURLFetchResults(const net::URLFetcher* source) = 0;
179
180 // Invoked by this base class upon an authentication error or cancel by
181 // a user request. Must be implemented by a derived class.
182 virtual void RunCallbackOnPrematureFailure(GDataErrorCode code) = 0;
183
184 // Invoked from derived classes when ProcessURLFetchResults() is completed.
185 void OnProcessURLFetchResultsComplete();
186
187 // Returns an appropriate GDataErrorCode based on the HTTP response code and
188 // the status of the URLFetcher.
189 GDataErrorCode GetErrorCode();
190
191 // Returns true if called on the thread where the constructor was called.
192 bool CalledOnValidThread();
193
194 // Returns the writer which is used to save the response for the request.
195 ResponseWriter* response_writer() const { return response_writer_; }
196
197 // Returns the task runner that should be used for blocking tasks.
198 base::SequencedTaskRunner* blocking_task_runner() const;
199
200 private:
201 // URLFetcherDelegate overrides.
202 virtual void OnURLFetchComplete(const net::URLFetcher* source) OVERRIDE;
203
204 // AuthenticatedRequestInterface overrides.
205 virtual void OnAuthFailed(GDataErrorCode code) OVERRIDE;
206
207 ReAuthenticateCallback re_authenticate_callback_;
208 int re_authenticate_count_;
209 scoped_ptr<net::URLFetcher> url_fetcher_;
210 ResponseWriter* response_writer_; // Owned by |url_fetcher_|.
211 RequestSender* sender_;
212 GDataErrorCode error_code_;
213
214 base::ThreadChecker thread_checker_;
215
216 // Note: This should remain the last member so it'll be destroyed and
217 // invalidate its weak pointers before any other members are destroyed.
218 base::WeakPtrFactory<UrlFetchRequestBase> weak_ptr_factory_;
219
220 DISALLOW_COPY_AND_ASSIGN(UrlFetchRequestBase);
221 };
222
223 //============================ EntryActionRequest ============================
224
225 // Callback type for requests that return only error status, like: Delete/Move.
226 typedef base::Callback<void(GDataErrorCode error)> EntryActionCallback;
227
228 // This class performs a simple action over a given entry (document/file).
229 // It is meant to be used for requests that return no JSON blobs.
230 class EntryActionRequest : public UrlFetchRequestBase {
231 public:
232 // |callback| is called when the request is finished either by success or by
233 // failure. It must not be null.
234 EntryActionRequest(RequestSender* sender,
235 const EntryActionCallback& callback);
236 virtual ~EntryActionRequest();
237
238 protected:
239 // Overridden from UrlFetchRequestBase.
240 virtual void ProcessURLFetchResults(const net::URLFetcher* source) OVERRIDE;
241 virtual void RunCallbackOnPrematureFailure(GDataErrorCode code) OVERRIDE;
242
243 private:
244 const EntryActionCallback callback_;
245
246 DISALLOW_COPY_AND_ASSIGN(EntryActionRequest);
247 };
248
249 //============================== GetDataRequest ==============================
250
251 // Callback type for requests that returns JSON data.
252 typedef base::Callback<void(GDataErrorCode error,
253 scoped_ptr<base::Value> json_data)> GetDataCallback;
254
255 // This class performs the request for fetching and converting the fetched
256 // content into a base::Value.
257 class GetDataRequest : public UrlFetchRequestBase {
258 public:
259 // |callback| is called when the request finishes either by success or by
260 // failure. On success, a JSON Value object is passed. It must not be null.
261 GetDataRequest(RequestSender* sender, const GetDataCallback& callback);
262 virtual ~GetDataRequest();
263
264 protected:
265 // UrlFetchRequestBase overrides.
266 virtual void ProcessURLFetchResults(const net::URLFetcher* source) OVERRIDE;
267 virtual void RunCallbackOnPrematureFailure(
268 GDataErrorCode fetch_error_code) OVERRIDE;
269
270 private:
271 // Parses JSON response.
272 void ParseResponse(GDataErrorCode fetch_error_code, const std::string& data);
273
274 // Called when ParseJsonOnBlockingPool() is completed.
275 void OnDataParsed(GDataErrorCode fetch_error_code,
276 scoped_ptr<base::Value> value);
277
278 const GetDataCallback callback_;
279
280 // Note: This should remain the last member so it'll be destroyed and
281 // invalidate its weak pointers before any other members are destroyed.
282 base::WeakPtrFactory<GetDataRequest> weak_ptr_factory_;
283
284 DISALLOW_COPY_AND_ASSIGN(GetDataRequest);
285 };
286
287
288 //=========================== InitiateUploadRequestBase=======================
289
290 // Callback type for DriveServiceInterface::InitiateUpload.
291 typedef base::Callback<void(GDataErrorCode error,
292 const GURL& upload_url)> InitiateUploadCallback;
293
294 // This class provides base implementation for performing the request for
295 // initiating the upload of a file.
296 // |callback| will be called with the obtained upload URL. The URL will be
297 // used with requests for resuming the file uploading.
298 //
299 // Here's the flow of uploading:
300 // 1) Get the upload URL with a class inheriting InitiateUploadRequestBase.
301 // 2) Upload the first 1GB (see kUploadChunkSize in drive_uploader.cc)
302 // of the target file to the upload URL
303 // 3) If there is more data to upload, go to 2).
304 //
305 class InitiateUploadRequestBase : public UrlFetchRequestBase {
306 protected:
307 // |callback| will be called with the upload URL, where upload data is
308 // uploaded to with ResumeUploadRequestBase. It must not be null.
309 // |content_type| and |content_length| should be the attributes of the
310 // uploading file.
311 InitiateUploadRequestBase(RequestSender* sender,
312 const InitiateUploadCallback& callback,
313 const std::string& content_type,
314 int64 content_length);
315 virtual ~InitiateUploadRequestBase();
316
317 // UrlFetchRequestBase overrides.
318 virtual void ProcessURLFetchResults(const net::URLFetcher* source) OVERRIDE;
319 virtual void RunCallbackOnPrematureFailure(GDataErrorCode code) OVERRIDE;
320 virtual std::vector<std::string> GetExtraRequestHeaders() const OVERRIDE;
321
322 private:
323 const InitiateUploadCallback callback_;
324 const std::string content_type_;
325 const int64 content_length_;
326
327 DISALLOW_COPY_AND_ASSIGN(InitiateUploadRequestBase);
328 };
329
330 //========================== UploadRangeRequestBase ==========================
331
332 // Struct for response to ResumeUpload and GetUploadStatus.
333 struct UploadRangeResponse {
334 UploadRangeResponse();
335 UploadRangeResponse(GDataErrorCode code,
336 int64 start_position_received,
337 int64 end_position_received);
338 ~UploadRangeResponse();
339
340 GDataErrorCode code;
341 // The values of "Range" header returned from the server. The values are
342 // used to continue uploading more data. These are set to -1 if an upload
343 // is complete.
344 // |start_position_received| is inclusive and |end_position_received| is
345 // exclusive to follow the common C++ manner, although the response from
346 // the server has "Range" header in inclusive format at both sides.
347 int64 start_position_received;
348 int64 end_position_received;
349 };
350
351 // Base class for a URL fetch request expecting the response containing the
352 // current uploading range. This class processes the response containing
353 // "Range" header and invoke OnRangeRequestComplete.
354 class UploadRangeRequestBase : public UrlFetchRequestBase {
355 protected:
356 // |upload_url| is the URL of where to upload the file to.
357 UploadRangeRequestBase(RequestSender* sender, const GURL& upload_url);
358 virtual ~UploadRangeRequestBase();
359
360 // UrlFetchRequestBase overrides.
361 virtual GURL GetURL() const OVERRIDE;
362 virtual net::URLFetcher::RequestType GetRequestType() const OVERRIDE;
363 virtual void ProcessURLFetchResults(const net::URLFetcher* source) OVERRIDE;
364 virtual void RunCallbackOnPrematureFailure(GDataErrorCode code) OVERRIDE;
365
366 // This method will be called when the request is done, regardless of
367 // whether it is succeeded or failed.
368 //
369 // 1) If there is more data to upload, |code| of |response| is set to
370 // HTTP_RESUME_INCOMPLETE, and positions are set appropriately. Also, |value|
371 // will be set to NULL.
372 // 2) If the upload is complete, |code| is set to HTTP_CREATED for a new file
373 // or HTTP_SUCCESS for an existing file. Positions are set to -1, and |value|
374 // is set to a parsed JSON value representing the uploaded file.
375 // 3) If a premature failure is found, |code| is set to a value representing
376 // the situation. Positions are set to 0, and |value| is set to NULL.
377 //
378 // See also the comments for UploadRangeResponse.
379 // Note: Subclasses should have responsibility to run some callback
380 // in this method to notify the finish status to its clients (or ignore it
381 // under its responsibility).
382 virtual void OnRangeRequestComplete(
383 const UploadRangeResponse& response, scoped_ptr<base::Value> value) = 0;
384
385 private:
386 // Called when ParseJson() is completed.
387 void OnDataParsed(GDataErrorCode code, scoped_ptr<base::Value> value);
388
389 const GURL upload_url_;
390
391 // Note: This should remain the last member so it'll be destroyed and
392 // invalidate its weak pointers before any other members are destroyed.
393 base::WeakPtrFactory<UploadRangeRequestBase> weak_ptr_factory_;
394
395 DISALLOW_COPY_AND_ASSIGN(UploadRangeRequestBase);
396 };
397
398 //========================== ResumeUploadRequestBase =========================
399
400 // This class performs the request for resuming the upload of a file.
401 // More specifically, this request uploads a chunk of data carried in |buf|
402 // of ResumeUploadResponseBase. This class is designed to share the
403 // implementation of upload resuming between GData WAPI and Drive API v2.
404 // The subclasses should implement OnRangeRequestComplete inherited by
405 // UploadRangeRequestBase, because the type of the response should be
406 // different (although the format in the server response is JSON).
407 class ResumeUploadRequestBase : public UploadRangeRequestBase {
408 protected:
409 // |start_position| is the start of range of contents currently stored in
410 // |buf|. |end_position| is the end of range of contents currently stared in
411 // |buf|. This is exclusive. For instance, if you are to upload the first
412 // 500 bytes of data, |start_position| is 0 and |end_position| is 500.
413 // |content_length| and |content_type| are the length and type of the
414 // file content to be uploaded respectively.
415 // |buf| holds current content to be uploaded.
416 // See also UploadRangeRequestBase's comment for remaining parameters
417 // meaning.
418 ResumeUploadRequestBase(RequestSender* sender,
419 const GURL& upload_location,
420 int64 start_position,
421 int64 end_position,
422 int64 content_length,
423 const std::string& content_type,
424 const base::FilePath& local_file_path);
425 virtual ~ResumeUploadRequestBase();
426
427 // UrlFetchRequestBase overrides.
428 virtual std::vector<std::string> GetExtraRequestHeaders() const OVERRIDE;
429 virtual bool GetContentFile(base::FilePath* local_file_path,
430 int64* range_offset,
431 int64* range_length,
432 std::string* upload_content_type) OVERRIDE;
433
434 private:
435 // The parameters for the request. See ResumeUploadParams for the details.
436 const int64 start_position_;
437 const int64 end_position_;
438 const int64 content_length_;
439 const std::string content_type_;
440 const base::FilePath local_file_path_;
441
442 DISALLOW_COPY_AND_ASSIGN(ResumeUploadRequestBase);
443 };
444
445 //======================== GetUploadStatusRequestBase ========================
446
447 // This class performs the request for getting the current upload status
448 // of a file.
449 // This request calls OnRangeRequestComplete() with:
450 // - HTTP_RESUME_INCOMPLETE and the range of previously uploaded data,
451 // if a file has been partially uploaded. |value| is not used.
452 // - HTTP_SUCCESS or HTTP_CREATED (up to the upload mode) and |value|
453 // for the uploaded data, if a file has been completely uploaded.
454 // See also UploadRangeRequestBase.
455 class GetUploadStatusRequestBase : public UploadRangeRequestBase {
456 public:
457 // |content_length| is the whole data size to be uploaded.
458 // See also UploadRangeRequestBase's constructor comment for other
459 // parameters.
460 GetUploadStatusRequestBase(RequestSender* sender,
461 const GURL& upload_url,
462 int64 content_length);
463 virtual ~GetUploadStatusRequestBase();
464
465 protected:
466 // UrlFetchRequestBase overrides.
467 virtual std::vector<std::string> GetExtraRequestHeaders() const OVERRIDE;
468
469 private:
470 const int64 content_length_;
471
472 DISALLOW_COPY_AND_ASSIGN(GetUploadStatusRequestBase);
473 };
474
475 //============================ DownloadFileRequest ===========================
476
477 // Callback type for receiving the completion of DownloadFileRequest.
478 typedef base::Callback<void(GDataErrorCode error,
479 const base::FilePath& temp_file)>
480 DownloadActionCallback;
481
482 // This is a base class for performing the request for downloading a file.
483 class DownloadFileRequestBase : public UrlFetchRequestBase {
484 public:
485 // download_action_callback:
486 // This callback is called when the download is complete. Must not be null.
487 //
488 // get_content_callback:
489 // This callback is called when some part of the content is
490 // read. Used to read the download content progressively. May be null.
491 //
492 // progress_callback:
493 // This callback is called for periodically reporting the number of bytes
494 // downloaded so far. May be null.
495 //
496 // download_url:
497 // Specifies the target file to download.
498 //
499 // output_file_path:
500 // Specifies the file path to save the downloaded file.
501 //
502 DownloadFileRequestBase(
503 RequestSender* sender,
504 const DownloadActionCallback& download_action_callback,
505 const GetContentCallback& get_content_callback,
506 const ProgressCallback& progress_callback,
507 const GURL& download_url,
508 const base::FilePath& output_file_path);
509 virtual ~DownloadFileRequestBase();
510
511 protected:
512 // UrlFetchRequestBase overrides.
513 virtual GURL GetURL() const OVERRIDE;
514 virtual void GetOutputFilePath(
515 base::FilePath* local_file_path,
516 GetContentCallback* get_content_callback) OVERRIDE;
517 virtual void ProcessURLFetchResults(const net::URLFetcher* source) OVERRIDE;
518 virtual void RunCallbackOnPrematureFailure(GDataErrorCode code) OVERRIDE;
519
520 // net::URLFetcherDelegate overrides.
521 virtual void OnURLFetchDownloadProgress(const net::URLFetcher* source,
522 int64 current, int64 total) OVERRIDE;
523
524 private:
525 const DownloadActionCallback download_action_callback_;
526 const GetContentCallback get_content_callback_;
527 const ProgressCallback progress_callback_;
528 const GURL download_url_;
529 const base::FilePath output_file_path_;
530
531 DISALLOW_COPY_AND_ASSIGN(DownloadFileRequestBase);
532 };
533
534 } // namespace google_apis
535
536 #endif // CHROME_BROWSER_GOOGLE_APIS_BASE_REQUESTS_H_
OLDNEW
« no previous file with comments | « chrome/browser/google_apis/auth_service_observer.h ('k') | chrome/browser/google_apis/base_requests.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698