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

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

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

Powered by Google App Engine
This is Rietveld 408576698