Fix search results being clipped in app list.
[chromium-blink-merge.git] / google_apis / drive / base_requests.h
bloba95d234d74f79e27a8cd9b64226228ab801e010b
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.
8 #ifndef GOOGLE_APIS_DRIVE_BASE_REQUESTS_H_
9 #define GOOGLE_APIS_DRIVE_BASE_REQUESTS_H_
11 #include <string>
12 #include <vector>
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 "google_apis/drive/drive_api_error_codes.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"
24 namespace base {
25 class Value;
26 } // namespace base
28 namespace google_apis {
30 class FileResource;
31 class RequestSender;
33 // Content type for multipart body.
34 enum MultipartType {
35 MULTIPART_RELATED,
36 MULTIPART_MIXED
39 // Pair of content type and data.
40 struct ContentTypeAndData {
41 std::string type;
42 std::string data;
45 typedef base::Callback<void(DriveApiErrorCode)> PrepareCallback;
47 // Callback used for requests that the server returns FileResource data
48 // formatted into JSON value.
49 typedef base::Callback<void(DriveApiErrorCode error,
50 scoped_ptr<FileResource> entry)>
51 FileResourceCallback;
53 // Callback used for DownloadFileRequest and ResumeUploadRequestBase.
54 typedef base::Callback<void(int64 progress, int64 total)> ProgressCallback;
56 // Callback used to get the content from DownloadFileRequest.
57 typedef base::Callback<void(
58 DriveApiErrorCode error,
59 scoped_ptr<std::string> content)> GetContentCallback;
61 // Parses JSON passed in |json|. Returns NULL on failure.
62 scoped_ptr<base::Value> ParseJson(const std::string& json);
64 // Generate multipart body. If |predetermined_boundary| is not empty, it uses
65 // the string as boundary. Otherwise it generates random boundary that does not
66 // conflict with |parts|.
67 void GenerateMultipartBody(MultipartType multipart_type,
68 const std::string& predetermined_boundary,
69 const std::vector<ContentTypeAndData>& parts,
70 ContentTypeAndData* output);
72 //======================= AuthenticatedRequestInterface ======================
74 // An interface class for implementing a request which requires OAuth2
75 // authentication.
76 class AuthenticatedRequestInterface {
77 public:
78 // Called when re-authentication is required. See Start() for details.
79 typedef base::Callback<void(AuthenticatedRequestInterface* request)>
80 ReAuthenticateCallback;
82 virtual ~AuthenticatedRequestInterface() {}
84 // Starts the request with |access_token|. User-Agent header will be set
85 // to |custom_user_agent| if the value is not empty.
87 // |callback| is called when re-authentication is needed for a certain
88 // number of times (see kMaxReAuthenticateAttemptsPerRequest in .cc).
89 // The callback should retry by calling Start() again with a new access
90 // token, or just call OnAuthFailed() if a retry is not attempted.
91 // |callback| must not be null.
92 virtual void Start(const std::string& access_token,
93 const std::string& custom_user_agent,
94 const ReAuthenticateCallback& callback) = 0;
96 // Invoked when the authentication failed with an error code |code|.
97 virtual void OnAuthFailed(DriveApiErrorCode code) = 0;
99 // Gets a weak pointer to this request object. Since requests may be
100 // deleted when it is canceled by user action, for posting asynchronous tasks
101 // on the authentication request object, weak pointers have to be used.
102 // TODO(kinaba): crbug.com/134814 use more clean life time management than
103 // using weak pointers.
104 virtual base::WeakPtr<AuthenticatedRequestInterface> GetWeakPtr() = 0;
106 // Cancels the request. It will invoke the callback object passed in
107 // each request's constructor with error code DRIVE_CANCELLED.
108 virtual void Cancel() = 0;
111 //=========================== ResponseWriter ==================================
113 // Saves the response for the request to a file or string.
114 class ResponseWriter : public net::URLFetcherResponseWriter {
115 public:
116 // If file_path is not empty, the response will be saved with file_writer_,
117 // otherwise it will be saved to data_.
118 ResponseWriter(base::SequencedTaskRunner* file_task_runner,
119 const base::FilePath& file_path,
120 const GetContentCallback& get_content_callback);
121 ~ResponseWriter() override;
123 const std::string& data() const { return data_; }
125 // Disowns the output file.
126 void DisownFile();
128 // URLFetcherResponseWriter overrides:
129 int Initialize(const net::CompletionCallback& callback) override;
130 int Write(net::IOBuffer* buffer,
131 int num_bytes,
132 const net::CompletionCallback& callback) override;
133 int Finish(const net::CompletionCallback& callback) override;
135 private:
136 void DidWrite(scoped_refptr<net::IOBuffer> buffer,
137 const net::CompletionCallback& callback,
138 int result);
140 const GetContentCallback get_content_callback_;
141 std::string data_;
142 scoped_ptr<net::URLFetcherFileWriter> file_writer_;
143 base::WeakPtrFactory<ResponseWriter> weak_ptr_factory_;
145 DISALLOW_COPY_AND_ASSIGN(ResponseWriter);
148 //============================ UrlFetchRequestBase ===========================
150 // Base class for requests that are fetching URLs.
151 class UrlFetchRequestBase : public AuthenticatedRequestInterface,
152 public net::URLFetcherDelegate {
153 public:
154 // AuthenticatedRequestInterface overrides.
155 void Start(const std::string& access_token,
156 const std::string& custom_user_agent,
157 const ReAuthenticateCallback& callback) override;
158 base::WeakPtr<AuthenticatedRequestInterface> GetWeakPtr() override;
159 void Cancel() override;
161 protected:
162 explicit UrlFetchRequestBase(RequestSender* sender);
163 ~UrlFetchRequestBase() override;
165 // Does async initialization for the request. |Start| calls this method so you
166 // don't need to call this before |Start|.
167 virtual void Prepare(const PrepareCallback& callback);
169 // Gets URL for the request.
170 virtual GURL GetURL() const = 0;
172 // Returns the request type. A derived class should override this method
173 // for a request type other than HTTP GET.
174 virtual net::URLFetcher::RequestType GetRequestType() const;
176 // Returns the extra HTTP headers for the request. A derived class should
177 // override this method to specify any extra headers needed for the request.
178 virtual std::vector<std::string> GetExtraRequestHeaders() const;
180 // Used by a derived class to add any content data to the request.
181 // Returns true if |upload_content_type| and |upload_content| are updated
182 // with the content type and data for the request.
183 // Note that this and GetContentFile() cannot be used together.
184 virtual bool GetContentData(std::string* upload_content_type,
185 std::string* upload_content);
187 // Used by a derived class to add content data which is the whole file or
188 // a part of the file at |local_file_path|.
189 // Returns true if all the arguments are updated for the content being
190 // uploaded.
191 // Note that this and GetContentData() cannot be used together.
192 virtual bool GetContentFile(base::FilePath* local_file_path,
193 int64* range_offset,
194 int64* range_length,
195 std::string* upload_content_type);
197 // Used by a derived class to set an output file path if they want to save
198 // the downloaded content to a file at a specific path.
199 // Sets |get_content_callback|, which is called when some part of the response
200 // is read.
201 virtual void GetOutputFilePath(base::FilePath* local_file_path,
202 GetContentCallback* get_content_callback);
204 // Invoked by OnURLFetchComplete when the request completes without an
205 // authentication error. Must be implemented by a derived class.
206 virtual void ProcessURLFetchResults(const net::URLFetcher* source) = 0;
208 // Invoked by this base class upon an authentication error or cancel by
209 // a user request. Must be implemented by a derived class.
210 virtual void RunCallbackOnPrematureFailure(DriveApiErrorCode code) = 0;
212 // Invoked from derived classes when ProcessURLFetchResults() is completed.
213 void OnProcessURLFetchResultsComplete();
215 // Returns an appropriate DriveApiErrorCode based on the HTTP response code
216 // and the status of the URLFetcher.
217 DriveApiErrorCode GetErrorCode();
219 // Returns true if called on the thread where the constructor was called.
220 bool CalledOnValidThread();
222 // Returns the writer which is used to save the response for the request.
223 ResponseWriter* response_writer() const { return response_writer_; }
225 // Returns the task runner that should be used for blocking tasks.
226 base::SequencedTaskRunner* blocking_task_runner() const;
228 private:
229 // Continues |Start| function after |Prepare|.
230 void StartAfterPrepare(const std::string& access_token,
231 const std::string& custom_user_agent,
232 const ReAuthenticateCallback& callback,
233 DriveApiErrorCode code);
235 // Invokes callback with |code| and request to delete the request to
236 // |sender_|.
237 void CompleteRequestWithError(DriveApiErrorCode code);
239 // URLFetcherDelegate overrides.
240 void OnURLFetchComplete(const net::URLFetcher* source) override;
242 // AuthenticatedRequestInterface overrides.
243 void OnAuthFailed(DriveApiErrorCode code) override;
245 ReAuthenticateCallback re_authenticate_callback_;
246 int re_authenticate_count_;
247 scoped_ptr<net::URLFetcher> url_fetcher_;
248 ResponseWriter* response_writer_; // Owned by |url_fetcher_|.
249 RequestSender* sender_;
250 DriveApiErrorCode error_code_;
252 base::ThreadChecker thread_checker_;
254 // Note: This should remain the last member so it'll be destroyed and
255 // invalidate its weak pointers before any other members are destroyed.
256 base::WeakPtrFactory<UrlFetchRequestBase> weak_ptr_factory_;
258 DISALLOW_COPY_AND_ASSIGN(UrlFetchRequestBase);
261 //============================ BatchableRequestBase ============================
263 class BatchableRequestBase : public UrlFetchRequestBase {
264 public:
265 explicit BatchableRequestBase(RequestSender* sender) :
266 UrlFetchRequestBase(sender) {}
268 GURL GetURL() const override = 0;
269 net::URLFetcher::RequestType GetRequestType() const override;
270 std::vector<std::string> GetExtraRequestHeaders() const override;
271 void Prepare(const PrepareCallback& callback) override;
272 bool GetContentData(std::string* upload_content_type,
273 std::string* upload_content) override;
274 void RunCallbackOnPrematureFailure(DriveApiErrorCode code) override = 0;
275 virtual void ProcessURLFetchResults(
276 DriveApiErrorCode code, const std::string& body) = 0;
278 private:
279 void ProcessURLFetchResults(const net::URLFetcher* source) final;
282 //============================ EntryActionRequest ============================
284 // Callback type for requests that return only error status, like: Delete/Move.
285 typedef base::Callback<void(DriveApiErrorCode error)> EntryActionCallback;
287 // This class performs a simple action over a given entry (document/file).
288 // It is meant to be used for requests that return no JSON blobs.
289 class EntryActionRequest : public UrlFetchRequestBase {
290 public:
291 // |callback| is called when the request is finished either by success or by
292 // failure. It must not be null.
293 EntryActionRequest(RequestSender* sender,
294 const EntryActionCallback& callback);
295 ~EntryActionRequest() override;
297 protected:
298 // Overridden from UrlFetchRequestBase.
299 void ProcessURLFetchResults(const net::URLFetcher* source) override;
300 void RunCallbackOnPrematureFailure(DriveApiErrorCode code) override;
302 private:
303 const EntryActionCallback callback_;
305 DISALLOW_COPY_AND_ASSIGN(EntryActionRequest);
308 //=========================== InitiateUploadRequestBase=======================
310 // Callback type for DriveServiceInterface::InitiateUpload.
311 typedef base::Callback<void(DriveApiErrorCode error,
312 const GURL& upload_url)> InitiateUploadCallback;
314 // This class provides base implementation for performing the request for
315 // initiating the upload of a file.
316 // |callback| will be called with the obtained upload URL. The URL will be
317 // used with requests for resuming the file uploading.
319 // Here's the flow of uploading:
320 // 1) Get the upload URL with a class inheriting InitiateUploadRequestBase.
321 // 2) Upload the first 1GB (see kUploadChunkSize in drive_uploader.cc)
322 // of the target file to the upload URL
323 // 3) If there is more data to upload, go to 2).
325 class InitiateUploadRequestBase : public UrlFetchRequestBase {
326 protected:
327 // |callback| will be called with the upload URL, where upload data is
328 // uploaded to with ResumeUploadRequestBase. It must not be null.
329 // |content_type| and |content_length| should be the attributes of the
330 // uploading file.
331 InitiateUploadRequestBase(RequestSender* sender,
332 const InitiateUploadCallback& callback,
333 const std::string& content_type,
334 int64 content_length);
335 ~InitiateUploadRequestBase() override;
337 // UrlFetchRequestBase overrides.
338 void ProcessURLFetchResults(const net::URLFetcher* source) override;
339 void RunCallbackOnPrematureFailure(DriveApiErrorCode code) override;
340 std::vector<std::string> GetExtraRequestHeaders() const override;
342 private:
343 const InitiateUploadCallback callback_;
344 const std::string content_type_;
345 const int64 content_length_;
347 DISALLOW_COPY_AND_ASSIGN(InitiateUploadRequestBase);
350 //========================== UploadRangeRequestBase ==========================
352 // Struct for response to ResumeUpload and GetUploadStatus.
353 struct UploadRangeResponse {
354 UploadRangeResponse();
355 UploadRangeResponse(DriveApiErrorCode code,
356 int64 start_position_received,
357 int64 end_position_received);
358 ~UploadRangeResponse();
360 DriveApiErrorCode code;
361 // The values of "Range" header returned from the server. The values are
362 // used to continue uploading more data. These are set to -1 if an upload
363 // is complete.
364 // |start_position_received| is inclusive and |end_position_received| is
365 // exclusive to follow the common C++ manner, although the response from
366 // the server has "Range" header in inclusive format at both sides.
367 int64 start_position_received;
368 int64 end_position_received;
371 // Base class for a URL fetch request expecting the response containing the
372 // current uploading range. This class processes the response containing
373 // "Range" header and invoke OnRangeRequestComplete.
374 class UploadRangeRequestBase : public UrlFetchRequestBase {
375 protected:
376 // |upload_url| is the URL of where to upload the file to.
377 UploadRangeRequestBase(RequestSender* sender, const GURL& upload_url);
378 ~UploadRangeRequestBase() override;
380 // UrlFetchRequestBase overrides.
381 GURL GetURL() const override;
382 net::URLFetcher::RequestType GetRequestType() const override;
383 void ProcessURLFetchResults(const net::URLFetcher* source) override;
384 void RunCallbackOnPrematureFailure(DriveApiErrorCode code) override;
386 // This method will be called when the request is done, regardless of
387 // whether it is succeeded or failed.
389 // 1) If there is more data to upload, |code| of |response| is set to
390 // HTTP_RESUME_INCOMPLETE, and positions are set appropriately. Also, |value|
391 // will be set to NULL.
392 // 2) If the upload is complete, |code| is set to HTTP_CREATED for a new file
393 // or HTTP_SUCCESS for an existing file. Positions are set to -1, and |value|
394 // is set to a parsed JSON value representing the uploaded file.
395 // 3) If a premature failure is found, |code| is set to a value representing
396 // the situation. Positions are set to 0, and |value| is set to NULL.
398 // See also the comments for UploadRangeResponse.
399 // Note: Subclasses should have responsibility to run some callback
400 // in this method to notify the finish status to its clients (or ignore it
401 // under its responsibility).
402 virtual void OnRangeRequestComplete(
403 const UploadRangeResponse& response, scoped_ptr<base::Value> value) = 0;
405 private:
406 // Called when ParseJson() is completed.
407 void OnDataParsed(DriveApiErrorCode code, scoped_ptr<base::Value> value);
409 const GURL upload_url_;
411 // Note: This should remain the last member so it'll be destroyed and
412 // invalidate its weak pointers before any other members are destroyed.
413 base::WeakPtrFactory<UploadRangeRequestBase> weak_ptr_factory_;
415 DISALLOW_COPY_AND_ASSIGN(UploadRangeRequestBase);
418 //========================== ResumeUploadRequestBase =========================
420 // This class performs the request for resuming the upload of a file.
421 // More specifically, this request uploads a chunk of data carried in |buf|
422 // of ResumeUploadResponseBase. This class is designed to share the
423 // implementation of upload resuming between GData WAPI and Drive API v2.
424 // The subclasses should implement OnRangeRequestComplete inherited by
425 // UploadRangeRequestBase, because the type of the response should be
426 // different (although the format in the server response is JSON).
427 class ResumeUploadRequestBase : public UploadRangeRequestBase {
428 protected:
429 // |start_position| is the start of range of contents currently stored in
430 // |buf|. |end_position| is the end of range of contents currently stared in
431 // |buf|. This is exclusive. For instance, if you are to upload the first
432 // 500 bytes of data, |start_position| is 0 and |end_position| is 500.
433 // |content_length| and |content_type| are the length and type of the
434 // file content to be uploaded respectively.
435 // |buf| holds current content to be uploaded.
436 // See also UploadRangeRequestBase's comment for remaining parameters
437 // meaning.
438 ResumeUploadRequestBase(RequestSender* sender,
439 const GURL& upload_location,
440 int64 start_position,
441 int64 end_position,
442 int64 content_length,
443 const std::string& content_type,
444 const base::FilePath& local_file_path);
445 ~ResumeUploadRequestBase() override;
447 // UrlFetchRequestBase overrides.
448 std::vector<std::string> GetExtraRequestHeaders() const override;
449 bool GetContentFile(base::FilePath* local_file_path,
450 int64* range_offset,
451 int64* range_length,
452 std::string* upload_content_type) override;
454 private:
455 // The parameters for the request. See ResumeUploadParams for the details.
456 const int64 start_position_;
457 const int64 end_position_;
458 const int64 content_length_;
459 const std::string content_type_;
460 const base::FilePath local_file_path_;
462 DISALLOW_COPY_AND_ASSIGN(ResumeUploadRequestBase);
465 //======================== GetUploadStatusRequestBase ========================
467 // This class performs the request for getting the current upload status
468 // of a file.
469 // This request calls OnRangeRequestComplete() with:
470 // - HTTP_RESUME_INCOMPLETE and the range of previously uploaded data,
471 // if a file has been partially uploaded. |value| is not used.
472 // - HTTP_SUCCESS or HTTP_CREATED (up to the upload mode) and |value|
473 // for the uploaded data, if a file has been completely uploaded.
474 // See also UploadRangeRequestBase.
475 class GetUploadStatusRequestBase : public UploadRangeRequestBase {
476 public:
477 // |content_length| is the whole data size to be uploaded.
478 // See also UploadRangeRequestBase's constructor comment for other
479 // parameters.
480 GetUploadStatusRequestBase(RequestSender* sender,
481 const GURL& upload_url,
482 int64 content_length);
483 ~GetUploadStatusRequestBase() override;
485 protected:
486 // UrlFetchRequestBase overrides.
487 std::vector<std::string> GetExtraRequestHeaders() const override;
489 private:
490 const int64 content_length_;
492 DISALLOW_COPY_AND_ASSIGN(GetUploadStatusRequestBase);
495 //=========================== MultipartUploadRequestBase=======================
497 // This class provides base implementation for performing the request for
498 // uploading a file by multipart body.
499 class MultipartUploadRequestBase : public BatchableRequestBase {
500 public:
501 // Set boundary. Only tests can use this method.
502 void SetBoundaryForTesting(const std::string& boundary);
504 protected:
505 // |callback| will be called with the file resource.upload URL.
506 // |content_type| and |content_length| should be the attributes of the
507 // uploading file. Other parameters are optional and can be empty or null
508 // depending on Upload URL provided by the subclasses.
509 MultipartUploadRequestBase(RequestSender* sender,
510 const std::string& metadata_json,
511 const std::string& content_type,
512 int64 content_length,
513 const base::FilePath& local_file_path,
514 const FileResourceCallback& callback,
515 const ProgressCallback& progress_callback);
516 ~MultipartUploadRequestBase() override;
518 // Overridden from UrlFetchRequestBase.
519 void Prepare(const PrepareCallback& callback) override;
520 bool GetContentData(std::string* upload_content_type,
521 std::string* upload_content) override;
522 void ProcessURLFetchResults(
523 DriveApiErrorCode code, const std::string& body) override;
524 void RunCallbackOnPrematureFailure(DriveApiErrorCode code) override;
526 // content::UrlFetcherDelegate overrides.
527 void OnURLFetchUploadProgress(const net::URLFetcher* source,
528 int64 current,
529 int64 total) override;
531 // Parses the response value and invokes |callback_| with |FileResource|.
532 void OnDataParsed(DriveApiErrorCode code, scoped_ptr<base::Value> value);
534 private:
535 // Continues to rest part of |Start| method after determining boundary string
536 // of multipart/related.
537 void OnPrepareUploadContent(const PrepareCallback& callback,
538 std::string* upload_content_type,
539 std::string* upload_content_data,
540 bool result);
542 const std::string metadata_json_;
543 const std::string content_type_;
544 const base::FilePath local_path_;
545 const FileResourceCallback callback_;
546 const ProgressCallback progress_callback_;
548 // Boundary of multipart body.
549 std::string boundary_;
551 // Upload content of multipart body.
552 std::string upload_content_type_;
553 std::string upload_content_data_;
555 // Note: This should remain the last member so it'll be destroyed and
556 // invalidate its weak pointers before any other members are destroyed.
557 base::WeakPtrFactory<MultipartUploadRequestBase> weak_ptr_factory_;
559 DISALLOW_COPY_AND_ASSIGN(MultipartUploadRequestBase);
562 //============================ DownloadFileRequest ===========================
564 // Callback type for receiving the completion of DownloadFileRequest.
565 typedef base::Callback<void(DriveApiErrorCode error,
566 const base::FilePath& temp_file)>
567 DownloadActionCallback;
569 // This is a base class for performing the request for downloading a file.
570 class DownloadFileRequestBase : public UrlFetchRequestBase {
571 public:
572 // download_action_callback:
573 // This callback is called when the download is complete. Must not be null.
575 // get_content_callback:
576 // This callback is called when some part of the content is
577 // read. Used to read the download content progressively. May be null.
579 // progress_callback:
580 // This callback is called for periodically reporting the number of bytes
581 // downloaded so far. May be null.
583 // download_url:
584 // Specifies the target file to download.
586 // output_file_path:
587 // Specifies the file path to save the downloaded file.
589 DownloadFileRequestBase(
590 RequestSender* sender,
591 const DownloadActionCallback& download_action_callback,
592 const GetContentCallback& get_content_callback,
593 const ProgressCallback& progress_callback,
594 const GURL& download_url,
595 const base::FilePath& output_file_path);
596 ~DownloadFileRequestBase() override;
598 protected:
599 // UrlFetchRequestBase overrides.
600 GURL GetURL() const override;
601 void GetOutputFilePath(base::FilePath* local_file_path,
602 GetContentCallback* get_content_callback) override;
603 void ProcessURLFetchResults(const net::URLFetcher* source) override;
604 void RunCallbackOnPrematureFailure(DriveApiErrorCode code) override;
606 // net::URLFetcherDelegate overrides.
607 void OnURLFetchDownloadProgress(const net::URLFetcher* source,
608 int64 current,
609 int64 total) override;
611 private:
612 const DownloadActionCallback download_action_callback_;
613 const GetContentCallback get_content_callback_;
614 const ProgressCallback progress_callback_;
615 const GURL download_url_;
616 const base::FilePath output_file_path_;
618 DISALLOW_COPY_AND_ASSIGN(DownloadFileRequestBase);
621 } // namespace google_apis
623 #endif // GOOGLE_APIS_DRIVE_BASE_REQUESTS_H_