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.
5 #ifndef CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_H_
6 #define CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_H_
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"
29 class DownloadItemImplDelegate
;
31 // See download_item.h for usage.
32 class CONTENT_EXPORT DownloadItemImpl
33 : public DownloadItem
,
34 public DownloadDestinationObserver
{
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
44 // The maximum number of attempts we will make to resume automatically.
45 static const int kMaxAutoResumeAttempts
;
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.
51 // Constructing from persistent store:
52 // |bound_net_log| is constructed externally for our use.
53 DownloadItemImpl(DownloadItemImplDelegate
* delegate
,
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
,
65 DownloadItem::DownloadState state
,
66 DownloadDangerType danger_type
,
67 DownloadInterruptReason interrupt_reason
,
69 const net::BoundNetLog
& bound_net_log
);
71 // Constructing for a regular download.
72 // |bound_net_log| is constructed externally for our use.
73 DownloadItemImpl(DownloadItemImplDelegate
* delegate
,
75 const DownloadCreateInfo
& info
,
76 const net::BoundNetLog
& bound_net_log
);
78 // Constructing for the "Save Page As..." feature:
79 // |bound_net_log| is constructed externally for our use.
80 DownloadItemImpl(DownloadItemImplDelegate
* delegate
,
82 const base::FilePath
& path
,
84 const std::string
& mime_type
,
85 scoped_ptr
<DownloadRequestHandleInterface
> request_handle
,
86 const net::BoundNetLog
& bound_net_log
);
88 virtual ~DownloadItemImpl();
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
)
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
;
158 // All remaining public interfaces virtual to allow for DownloadItemImpl
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;
166 // State transition operations on regular downloads --------------------------
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
);
174 // Needed because of intertwining with DownloadManagerImpl -------------------
176 // TODO(rdsmith): Unwind DownloadManagerImpl and DownloadItemImpl,
177 // removing these from the public interface.
179 // Notify observers that this item is being removed by the user.
180 virtual void NotifyRemoved();
182 virtual void OnDownloadedFileRemoved();
184 // Provide a weak pointer reference to a DownloadDestinationObserver
185 // for use by download destinations.
186 virtual base::WeakPtr
<DownloadDestinationObserver
>
187 DestinationObserverAsWeakPtr();
189 // Get the download's BoundNetLog.
190 virtual const net::BoundNetLog
& GetBoundNetLog() const;
192 // DownloadItemImpl routines only needed by SavePackage ----------------------
194 // Called by SavePackage to set the total number of bytes on the item.
195 virtual void SetTotalBytes(int64 total_bytes
);
197 virtual void OnAllDataSaved(const std::string
& final_hash
);
199 // Called by SavePackage to display progress when the DownloadItem
200 // should be considered complete.
201 virtual void MarkAsComplete();
203 // DownloadDestinationObserver
204 virtual void DestinationUpdate(int64 bytes_so_far
,
206 const std::string
& hash_state
) OVERRIDE
;
207 virtual void DestinationError(DownloadInterruptReason reason
) OVERRIDE
;
208 virtual void DestinationCompleted(const std::string
& final_hash
) OVERRIDE
;
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.
216 enum DownloadInternalState
{
217 // Includes both before and after file name determination, and paused
219 // TODO(rdsmith): Put in state variable for file name determination.
221 // <Initial creation> Active downloads are created in this state.
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
,
230 // Between commit point (dispatch of download file release) and completed.
231 // Embedder may be opening the file in this state.
233 // IN_PROGRESS_INTERNAL
235 // COMPLETE_INTERNAL On successful completion.
238 // After embedder has had a chance to auto-open. User may now open
239 // or auto-open based on extension.
241 // COMPLETING_INTERNAL
242 // IN_PROGRESS_INTERNAL SavePackage only.
243 // <Initial creation> Completed persisted downloads.
245 // <none> Terminal state.
248 // User has cancelled the download.
250 // IN_PROGRESS_INTERNAL
251 // INTERRUPTED_INTERNAL
253 // <Initial creation> Canceleld persisted downloads.
255 // <none> Terminal state.
258 // An error has interrupted the download.
260 // IN_PROGRESS_INTERNAL
262 // <Initial creation> Interrupted persisted downloads.
264 // RESUMING_INTERNAL On resumption.
265 INTERRUPTED_INTERNAL
,
267 // A request to resume this interrupted download is in progress.
269 // INTERRUPTED_INTERNAL
271 // IN_PROGRESS_INTERNAL Once a server response is received from a
273 // INTERRUPTED_INTERNAL If the resumption request fails.
274 // CANCELLED_INTERNAL On cancel.
277 MAX_DOWNLOAD_INTERNAL_STATE
,
280 // Used with TransitionTo() to indicate whether or not to call
281 // UpdateObservers() after the state transition.
282 enum ShouldUpdateObservers
{
284 DONT_UPDATE_OBSERVERS
287 // Normal progression of a download ------------------------------------------
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.
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
297 void Init(bool active
, DownloadType download_type
);
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
);
310 // Callback from file thread when we initialize the DownloadFile.
311 void OnDownloadFileInitialized(DownloadInterruptReason result
);
313 void OnDownloadRenamedToIntermediateName(
314 DownloadInterruptReason reason
, const base::FilePath
& full_path
);
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();
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();
326 void OnDownloadRenamedToFinalName(DownloadInterruptReason reason
,
327 const base::FilePath
& full_path
);
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
);
333 // Called when the entire download operation (including renaming etc)
337 // Callback invoked when the URLRequest for a download resumption has started.
338 void OnResumeRequestStarted(DownloadItem
* item
, net::Error error
);
340 // Helper routines -----------------------------------------------------------
342 // Indicate that an error has occurred on the download.
343 void Interrupt(DownloadInterruptReason reason
);
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
);
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
);
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
);
362 // Set the |danger_type_| and invoke obserers if necessary.
363 void SetDangerType(DownloadDangerType danger_type
);
365 void SetFullPath(const base::FilePath
& new_path
);
367 void AutoResumeIfValid();
369 void ResumeInterruptedDownload();
371 static DownloadState
InternalToExternalState(
372 DownloadInternalState internal_state
);
373 static DownloadInternalState
ExternalToInternalState(
374 DownloadState external_state
);
376 // Debugging routines --------------------------------------------------------
377 static const char* DebugDownloadStateString(DownloadInternalState state
);
378 static const char* DebugResumeModeString(ResumeMode mode
);
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_
;
384 // The handle to the request information. Used for operations outside the
386 scoped_ptr
<DownloadRequestHandleInterface
> request_handle_
;
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_
;
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
398 base::FilePath current_path_
;
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_
;
405 // Whether the target should be overwritten, uniquified or prompted for.
406 TargetDisposition target_disposition_
;
408 // The chain of redirects that leading up to and including the final URL.
409 std::vector
<GURL
> url_chain_
;
411 // The URL of the page that initiated the download.
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_
;
419 // If non-empty, contains an externally supplied path that should be used as
421 base::FilePath forced_file_path_
;
423 // Page transition that triggerred the download.
424 PageTransition transition_type_
;
426 // Whether the download was triggered with a user gesture.
427 bool has_user_gesture_
;
429 // Information from the request.
430 // Content-disposition field from the header.
431 std::string content_disposition_
;
433 // Mime-type from the header. Subject to change.
434 std::string mime_type_
;
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_
;
441 // The remote IP address where the download was fetched from. Copied from
442 // DownloadCreateInfo::remote_address.
443 std::string remote_address_
;
445 // Total bytes expected.
448 // Current received bytes.
449 int64 received_bytes_
;
451 // Current speed. Calculated by the DownloadFile.
452 int64 bytes_per_sec_
;
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).
459 // A blob containing the state of the hash algorithm. Only valid while the
460 // download is in progress.
461 std::string hash_state_
;
463 // Server's time stamp for the file.
464 std::string last_modified_time_
;
466 // Server's ETAG for the file.
470 DownloadInterruptReason last_reason_
;
472 // Start time for recording statistics.
473 base::TimeTicks start_tick_
;
475 // The current state of this download.
476 DownloadInternalState state_
;
478 // Current danger type for the download.
479 DownloadDangerType danger_type_
;
481 // The views of this item in the download shelf and download contents.
482 ObserverList
<Observer
> observers_
;
484 // Time the download was started.
485 base::Time start_time_
;
487 // Time the download completed.
488 base::Time end_time_
;
491 DownloadItemImplDelegate
* delegate_
;
493 // In progress downloads may be paused by the user, we note it here.
496 // The number of times this download has been resumed automatically.
497 int auto_resume_count_
;
499 // A flag for indicating if the download should be opened at completion.
500 bool open_when_complete_
;
502 // A flag for indicating if the downloaded file is externally removed.
503 bool file_externally_removed_
;
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.
510 // True if the item was downloaded temporarily.
513 // True if we've saved all the data for the download.
514 bool all_data_saved_
;
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_
;
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.
527 // Did the delegate delay calling Complete on this download?
528 bool delegate_delayed_complete_
;
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_
;
536 // Net log to use for this download.
537 const net::BoundNetLog bound_net_log_
;
539 base::WeakPtrFactory
<DownloadItemImpl
> weak_ptr_factory_
;
541 DISALLOW_COPY_AND_ASSIGN(DownloadItemImpl
);
544 } // namespace content
546 #endif // CONTENT_BROWSER_DOWNLOAD_DOWNLOAD_ITEM_IMPL_H_