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