- add sources.
[platform/framework/web/crosswalk.git] / src / content / browser / download / download_item_impl.h
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 #ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_H_
6 #define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_H_
7
8 #include <string>
9
10 #include "base/basictypes.h"
11 #include "base/callback_forward.h"
12 #include "base/files/file_path.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/observer_list.h"
16 #include "base/time/time.h"
17 #include "base/timer/timer.h"
18 #include "content/browser/download/download_net_log_parameters.h"
19 #include "content/browser/download/download_request_handle.h"
20 #include "content/common/content_export.h"
21 #include "content/public/browser/download_destination_observer.h"
22 #include "content/public/browser/download_item.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/net_log.h"
25 #include "url/gurl.h"
26
27 namespace content {
28 class DownloadFile;
29 class DownloadItemImplDelegate;
30
31 // See download_item.h for usage.
32 class CONTENT_EXPORT DownloadItemImpl
33     : public DownloadItem,
34       public DownloadDestinationObserver {
35  public:
36   enum ResumeMode {
37     RESUME_MODE_INVALID = 0,
38     RESUME_MODE_IMMEDIATE_CONTINUE,
39     RESUME_MODE_IMMEDIATE_RESTART,
40     RESUME_MODE_USER_CONTINUE,
41     RESUME_MODE_USER_RESTART
42   };
43
44   // The maximum number of attempts we will make to resume automatically.
45   static const int kMaxAutoResumeAttempts;
46
47   // Note that it is the responsibility of the caller to ensure that a
48   // DownloadItemImplDelegate passed to a DownloadItemImpl constructor
49   // outlives the DownloadItemImpl.
50
51   // Constructing from persistent store:
52   // |bound_net_log| is constructed externally for our use.
53   DownloadItemImpl(DownloadItemImplDelegate* delegate,
54                    uint32 id,
55                    const base::FilePath& current_path,
56                    const base::FilePath& target_path,
57                    const std::vector<GURL>& url_chain,
58                    const GURL& referrer_url,
59                    const base::Time& start_time,
60                    const base::Time& end_time,
61                    const std::string& etag,
62                    const std::string& last_modified,
63                    int64 received_bytes,
64                    int64 total_bytes,
65                    DownloadItem::DownloadState state,
66                    DownloadDangerType danger_type,
67                    DownloadInterruptReason interrupt_reason,
68                    bool opened,
69                    const net::BoundNetLog& bound_net_log);
70
71   // Constructing for a regular download.
72   // |bound_net_log| is constructed externally for our use.
73   DownloadItemImpl(DownloadItemImplDelegate* delegate,
74                    uint32 id,
75                    const DownloadCreateInfo& info,
76                    const net::BoundNetLog& bound_net_log);
77
78   // Constructing for the "Save Page As..." feature:
79   // |bound_net_log| is constructed externally for our use.
80   DownloadItemImpl(DownloadItemImplDelegate* delegate,
81                    uint32 id,
82                    const base::FilePath& path,
83                    const GURL& url,
84                    const std::string& mime_type,
85                    scoped_ptr<DownloadRequestHandleInterface> request_handle,
86                    const net::BoundNetLog& bound_net_log);
87
88   virtual ~DownloadItemImpl();
89
90   // DownloadItem
91   virtual void AddObserver(DownloadItem::Observer* observer) OVERRIDE;
92   virtual void RemoveObserver(DownloadItem::Observer* observer) OVERRIDE;
93   virtual void UpdateObservers() OVERRIDE;
94   virtual void ValidateDangerousDownload() OVERRIDE;
95   virtual void StealDangerousDownload(const AcquireFileCallback& callback)
96       OVERRIDE;
97   virtual void Pause() OVERRIDE;
98   virtual void Resume() OVERRIDE;
99   virtual void Cancel(bool user_cancel) OVERRIDE;
100   virtual void Remove() OVERRIDE;
101   virtual void OpenDownload() OVERRIDE;
102   virtual void ShowDownloadInShell() OVERRIDE;
103   virtual uint32 GetId() const OVERRIDE;
104   virtual DownloadState GetState() const OVERRIDE;
105   virtual DownloadInterruptReason GetLastReason() const OVERRIDE;
106   virtual bool IsPaused() const OVERRIDE;
107   virtual bool IsTemporary() const OVERRIDE;
108   virtual bool CanResume() const OVERRIDE;
109   virtual bool IsDone() const OVERRIDE;
110   virtual const GURL& GetURL() const OVERRIDE;
111   virtual const std::vector<GURL>& GetUrlChain() const OVERRIDE;
112   virtual const GURL& GetOriginalUrl() const OVERRIDE;
113   virtual const GURL& GetReferrerUrl() const OVERRIDE;
114   virtual std::string GetSuggestedFilename() const OVERRIDE;
115   virtual std::string GetContentDisposition() const OVERRIDE;
116   virtual std::string GetMimeType() const OVERRIDE;
117   virtual std::string GetOriginalMimeType() const OVERRIDE;
118   virtual std::string GetRemoteAddress() const OVERRIDE;
119   virtual bool HasUserGesture() const OVERRIDE;
120   virtual PageTransition GetTransitionType() const OVERRIDE;
121   virtual const std::string& GetLastModifiedTime() const OVERRIDE;
122   virtual const std::string& GetETag() const OVERRIDE;
123   virtual bool IsSavePackageDownload() const OVERRIDE;
124   virtual const base::FilePath& GetFullPath() const OVERRIDE;
125   virtual const base::FilePath& GetTargetFilePath() const OVERRIDE;
126   virtual const base::FilePath& GetForcedFilePath() const OVERRIDE;
127   virtual base::FilePath GetFileNameToReportUser() const OVERRIDE;
128   virtual TargetDisposition GetTargetDisposition() const OVERRIDE;
129   virtual const std::string& GetHash() const OVERRIDE;
130   virtual const std::string& GetHashState() const OVERRIDE;
131   virtual bool GetFileExternallyRemoved() const OVERRIDE;
132   virtual void DeleteFile() OVERRIDE;
133   virtual bool IsDangerous() const OVERRIDE;
134   virtual DownloadDangerType GetDangerType() const OVERRIDE;
135   virtual bool TimeRemaining(base::TimeDelta* remaining) const OVERRIDE;
136   virtual int64 CurrentSpeed() const OVERRIDE;
137   virtual int PercentComplete() const OVERRIDE;
138   virtual bool AllDataSaved() const OVERRIDE;
139   virtual int64 GetTotalBytes() const OVERRIDE;
140   virtual int64 GetReceivedBytes() const OVERRIDE;
141   virtual base::Time GetStartTime() const OVERRIDE;
142   virtual base::Time GetEndTime() const OVERRIDE;
143   virtual bool CanShowInFolder() OVERRIDE;
144   virtual bool CanOpenDownload() OVERRIDE;
145   virtual bool ShouldOpenFileBasedOnExtension() OVERRIDE;
146   virtual bool GetOpenWhenComplete() const OVERRIDE;
147   virtual bool GetAutoOpened() OVERRIDE;
148   virtual bool GetOpened() const OVERRIDE;
149   virtual BrowserContext* GetBrowserContext() const OVERRIDE;
150   virtual WebContents* GetWebContents() const OVERRIDE;
151   virtual void OnContentCheckCompleted(DownloadDangerType danger_type) OVERRIDE;
152   virtual void SetOpenWhenComplete(bool open) OVERRIDE;
153   virtual void SetIsTemporary(bool temporary) OVERRIDE;
154   virtual void SetOpened(bool opened) OVERRIDE;
155   virtual void SetDisplayName(const base::FilePath& name) OVERRIDE;
156   virtual std::string DebugString(bool verbose) const OVERRIDE;
157
158   // All remaining public interfaces virtual to allow for DownloadItemImpl
159   // mocks.
160
161   // Determines the resume mode for an interrupted download. Requires
162   // last_reason_ to be set, but doesn't require the download to be in
163   // INTERRUPTED state.
164   virtual ResumeMode GetResumeMode() const;
165
166   // State transition operations on regular downloads --------------------------
167
168   // Start the download.
169   // |download_file| is the associated file on the storage medium.
170   // |req_handle| is the new request handle associated with the download.
171   virtual void Start(scoped_ptr<DownloadFile> download_file,
172                      scoped_ptr<DownloadRequestHandleInterface> req_handle);
173
174   // Needed because of intertwining with DownloadManagerImpl -------------------
175
176   // TODO(rdsmith): Unwind DownloadManagerImpl and DownloadItemImpl,
177   // removing these from the public interface.
178
179   // Notify observers that this item is being removed by the user.
180   virtual void NotifyRemoved();
181
182   virtual void OnDownloadedFileRemoved();
183
184   // Provide a weak pointer reference to a DownloadDestinationObserver
185   // for use by download destinations.
186   virtual base::WeakPtr<DownloadDestinationObserver>
187       DestinationObserverAsWeakPtr();
188
189   // Get the download's BoundNetLog.
190   virtual const net::BoundNetLog& GetBoundNetLog() const;
191
192   // DownloadItemImpl routines only needed by SavePackage ----------------------
193
194   // Called by SavePackage to set the total number of bytes on the item.
195   virtual void SetTotalBytes(int64 total_bytes);
196
197   virtual void OnAllDataSaved(const std::string& final_hash);
198
199   // Called by SavePackage to display progress when the DownloadItem
200   // should be considered complete.
201   virtual void MarkAsComplete();
202
203   // DownloadDestinationObserver
204   virtual void DestinationUpdate(int64 bytes_so_far,
205                                  int64 bytes_per_sec,
206                                  const std::string& hash_state) OVERRIDE;
207   virtual void DestinationError(DownloadInterruptReason reason) OVERRIDE;
208   virtual void DestinationCompleted(const std::string& final_hash) OVERRIDE;
209
210  private:
211   // Fine grained states of a download. Note that active downloads are created
212   // in IN_PROGRESS_INTERNAL state. However, downloads creates via history can
213   // be created in COMPLETE_INTERNAL, CANCELLED_INTERNAL and
214   // INTERRUPTED_INTERNAL.
215
216   enum DownloadInternalState {
217     // Includes both before and after file name determination, and paused
218     // downloads.
219     // TODO(rdsmith): Put in state variable for file name determination.
220     // Transitions from:
221     //   <Initial creation>    Active downloads are created in this state.
222     //   RESUMING_INTERNAL
223     // Transitions to:
224     //   COMPLETING_INTERNAL   On final rename completion.
225     //   CANCELLED_INTERNAL    On cancel.
226     //   INTERRUPTED_INTERNAL  On interrupt.
227     //   COMPLETE_INTERNAL     On SavePackage download completion.
228     IN_PROGRESS_INTERNAL,
229
230     // Between commit point (dispatch of download file release) and completed.
231     // Embedder may be opening the file in this state.
232     // Transitions from:
233     //   IN_PROGRESS_INTERNAL
234     // Transitions to:
235     //   COMPLETE_INTERNAL     On successful completion.
236     COMPLETING_INTERNAL,
237
238     // After embedder has had a chance to auto-open.  User may now open
239     // or auto-open based on extension.
240     // Transitions from:
241     //   COMPLETING_INTERNAL
242     //   IN_PROGRESS_INTERNAL  SavePackage only.
243     //   <Initial creation>    Completed persisted downloads.
244     // Transitions to:
245     //   <none>                Terminal state.
246     COMPLETE_INTERNAL,
247
248     // User has cancelled the download.
249     // Transitions from:
250     //   IN_PROGRESS_INTERNAL
251     //   INTERRUPTED_INTERNAL
252     //   RESUMING_INTERNAL
253     //   <Initial creation>    Canceleld persisted downloads.
254     // Transitions to:
255     //   <none>                Terminal state.
256     CANCELLED_INTERNAL,
257
258     // An error has interrupted the download.
259     // Transitions from:
260     //   IN_PROGRESS_INTERNAL
261     //   RESUMING_INTERNAL
262     //   <Initial creation>    Interrupted persisted downloads.
263     // Transitions to:
264     //   RESUMING_INTERNAL     On resumption.
265     INTERRUPTED_INTERNAL,
266
267     // A request to resume this interrupted download is in progress.
268     // Transitions from:
269     //   INTERRUPTED_INTERNAL
270     // Transitions to:
271     //   IN_PROGRESS_INTERNAL  Once a server response is received from a
272     //                         resumption.
273     //   INTERRUPTED_INTERNAL  If the resumption request fails.
274     //   CANCELLED_INTERNAL    On cancel.
275     RESUMING_INTERNAL,
276
277     MAX_DOWNLOAD_INTERNAL_STATE,
278   };
279
280   // Used with TransitionTo() to indicate whether or not to call
281   // UpdateObservers() after the state transition.
282   enum ShouldUpdateObservers {
283     UPDATE_OBSERVERS,
284     DONT_UPDATE_OBSERVERS
285   };
286
287   // Normal progression of a download ------------------------------------------
288
289   // These are listed in approximately chronological order.  There are also
290   // public methods involved in normal download progression; see
291   // the implementation ordering in download_item_impl.cc.
292
293   // Construction common to all constructors. |active| should be true for new
294   // downloads and false for downloads from the history.
295   // |download_type| indicates to the net log system what kind of download
296   // this is.
297   void Init(bool active, DownloadType download_type);
298
299   // Called when the target path has been determined. |target_path| is the
300   // suggested target path. |disposition| indicates how the target path should
301   // be used (see TargetDisposition). |danger_type| is the danger level of
302   // |target_path| as determined by the caller. |intermediate_path| is the path
303   // to use to store the download until OnDownloadCompleting() is called.
304   virtual void OnDownloadTargetDetermined(
305       const base::FilePath& target_path,
306       TargetDisposition disposition,
307       DownloadDangerType danger_type,
308       const base::FilePath& intermediate_path);
309
310   // Callback from file thread when we initialize the DownloadFile.
311   void OnDownloadFileInitialized(DownloadInterruptReason result);
312
313   void OnDownloadRenamedToIntermediateName(
314       DownloadInterruptReason reason, const base::FilePath& full_path);
315
316   // If all pre-requisites have been met, complete download processing, i.e. do
317   // internal cleanup, file rename, and potentially auto-open.  (Dangerous
318   // downloads still may block on user acceptance after this point.)
319   void MaybeCompleteDownload();
320
321   // Called when the download is ready to complete.
322   // This may perform final rename if necessary and will eventually call
323   // DownloadItem::Completed().
324   void OnDownloadCompleting();
325
326   void OnDownloadRenamedToFinalName(DownloadInterruptReason reason,
327                                     const base::FilePath& full_path);
328
329   // Called if the embedder took over opening a download, to indicate that
330   // the download has been opened.
331   void DelayedDownloadOpened(bool auto_opened);
332
333   // Called when the entire download operation (including renaming etc)
334   // is completed.
335   void Completed();
336
337   // Callback invoked when the URLRequest for a download resumption has started.
338   void OnResumeRequestStarted(DownloadItem* item, net::Error error);
339
340   // Helper routines -----------------------------------------------------------
341
342   // Indicate that an error has occurred on the download.
343   void Interrupt(DownloadInterruptReason reason);
344
345   // Destroy the DownloadFile object.  If |destroy_file| is true, the file is
346   // destroyed with it.  Otherwise, DownloadFile::Detach() is called before
347   // object destruction to prevent file destruction. Destroying the file also
348   // resets |current_path_|.
349   void ReleaseDownloadFile(bool destroy_file);
350
351   // Check if a download is ready for completion.  The callback provided
352   // may be called at some point in the future if an external entity
353   // state has change s.t. this routine should be checked again.
354   bool IsDownloadReadyForCompletion(const base::Closure& state_change_notify);
355
356   // Call to transition state; all state transitions should go through this.
357   // |notify_action| specifies whether or not to call UpdateObservers() after
358   // the state transition.
359   void TransitionTo(DownloadInternalState new_state,
360                     ShouldUpdateObservers notify_action);
361
362   // Set the |danger_type_| and invoke obserers if necessary.
363   void SetDangerType(DownloadDangerType danger_type);
364
365   void SetFullPath(const base::FilePath& new_path);
366
367   void AutoResumeIfValid();
368
369   void ResumeInterruptedDownload();
370
371   static DownloadState InternalToExternalState(
372       DownloadInternalState internal_state);
373   static DownloadInternalState ExternalToInternalState(
374       DownloadState external_state);
375
376   // Debugging routines --------------------------------------------------------
377   static const char* DebugDownloadStateString(DownloadInternalState state);
378   static const char* DebugResumeModeString(ResumeMode mode);
379
380   // Will be false for save package downloads retrieved from the history.
381   // TODO(rdsmith): Replace with a generalized enum for "download source".
382   const bool is_save_package_download_;
383
384   // The handle to the request information.  Used for operations outside the
385   // download system.
386   scoped_ptr<DownloadRequestHandleInterface> request_handle_;
387
388   uint32 download_id_;
389
390   // Display name for the download. If this is empty, then the display name is
391   // considered to be |target_path_.BaseName()|.
392   base::FilePath display_name_;
393
394   // Full path to the downloaded or downloading file. This is the path to the
395   // physical file, if one exists. The final target path is specified by
396   // |target_path_|. |current_path_| can be empty if the in-progress path hasn't
397   // been determined.
398   base::FilePath current_path_;
399
400   // Target path of an in-progress download. We may be downloading to a
401   // temporary or intermediate file (specified by |current_path_|.  Once the
402   // download completes, we will rename the file to |target_path_|.
403   base::FilePath target_path_;
404
405   // Whether the target should be overwritten, uniquified or prompted for.
406   TargetDisposition target_disposition_;
407
408   // The chain of redirects that leading up to and including the final URL.
409   std::vector<GURL> url_chain_;
410
411   // The URL of the page that initiated the download.
412   GURL referrer_url_;
413
414   // Filename suggestion from DownloadSaveInfo. It could, among others, be the
415   // suggested filename in 'download' attribute of an anchor. Details:
416   // http://www.whatwg.org/specs/web-apps/current-work/#downloading-hyperlinks
417   std::string suggested_filename_;
418
419   // If non-empty, contains an externally supplied path that should be used as
420   // the target path.
421   base::FilePath forced_file_path_;
422
423   // Page transition that triggerred the download.
424   PageTransition transition_type_;
425
426   // Whether the download was triggered with a user gesture.
427   bool has_user_gesture_;
428
429   // Information from the request.
430   // Content-disposition field from the header.
431   std::string content_disposition_;
432
433   // Mime-type from the header.  Subject to change.
434   std::string mime_type_;
435
436   // The value of the content type header sent with the downloaded item.  It
437   // may be different from |mime_type_|, which may be set based on heuristics
438   // which may look at the file extension and first few bytes of the file.
439   std::string original_mime_type_;
440
441   // The remote IP address where the download was fetched from.  Copied from
442   // DownloadCreateInfo::remote_address.
443   std::string remote_address_;
444
445   // Total bytes expected.
446   int64 total_bytes_;
447
448   // Current received bytes.
449   int64 received_bytes_;
450
451   // Current speed. Calculated by the DownloadFile.
452   int64 bytes_per_sec_;
453
454   // Sha256 hash of the content.  This might be empty either because
455   // the download isn't done yet or because the hash isn't needed
456   // (ChromeDownloadManagerDelegate::GenerateFileHash() returned false).
457   std::string hash_;
458
459   // A blob containing the state of the hash algorithm.  Only valid while the
460   // download is in progress.
461   std::string hash_state_;
462
463   // Server's time stamp for the file.
464   std::string last_modified_time_;
465
466   // Server's ETAG for the file.
467   std::string etag_;
468
469   // Last reason.
470   DownloadInterruptReason last_reason_;
471
472   // Start time for recording statistics.
473   base::TimeTicks start_tick_;
474
475   // The current state of this download.
476   DownloadInternalState state_;
477
478   // Current danger type for the download.
479   DownloadDangerType danger_type_;
480
481   // The views of this item in the download shelf and download contents.
482   ObserverList<Observer> observers_;
483
484   // Time the download was started.
485   base::Time start_time_;
486
487   // Time the download completed.
488   base::Time end_time_;
489
490   // Our delegate.
491   DownloadItemImplDelegate* delegate_;
492
493   // In progress downloads may be paused by the user, we note it here.
494   bool is_paused_;
495
496   // The number of times this download has been resumed automatically.
497   int auto_resume_count_;
498
499   // A flag for indicating if the download should be opened at completion.
500   bool open_when_complete_;
501
502   // A flag for indicating if the downloaded file is externally removed.
503   bool file_externally_removed_;
504
505   // True if the download was auto-opened. We set this rather than using
506   // an observer as it's frequently possible for the download to be auto opened
507   // before the observer is added.
508   bool auto_opened_;
509
510   // True if the item was downloaded temporarily.
511   bool is_temporary_;
512
513   // True if we've saved all the data for the download.
514   bool all_data_saved_;
515
516   // Error return from DestinationError.  Stored separately from
517   // last_reason_ so that we can avoid handling destination errors until
518   // after file name determination has occurred.
519   DownloadInterruptReason destination_error_;
520
521   // Did the user open the item either directly or indirectly (such as by
522   // setting always open files of this type)? The shelf also sets this field
523   // when the user closes the shelf before the item has been opened but should
524   // be treated as though the user opened it.
525   bool opened_;
526
527   // Did the delegate delay calling Complete on this download?
528   bool delegate_delayed_complete_;
529
530   // DownloadFile associated with this download.  Note that this
531   // pointer may only be used or destroyed on the FILE thread.
532   // This pointer will be non-null only while the DownloadItem is in
533   // the IN_PROGRESS state.
534   scoped_ptr<DownloadFile> download_file_;
535
536   // Net log to use for this download.
537   const net::BoundNetLog bound_net_log_;
538
539   base::WeakPtrFactory<DownloadItemImpl> weak_ptr_factory_;
540
541   DISALLOW_COPY_AND_ASSIGN(DownloadItemImpl);
542 };
543
544 }  // namespace content
545
546 #endif  // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_H_