download_item_impl.h revision eb525c5499e34cc9c4b825d6d9e75bb07cc06ace
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_id.h" 23#include "content/public/browser/download_item.h" 24#include "googleurl/src/gurl.h" 25#include "net/base/net_errors.h" 26#include "net/base/net_log.h" 27 28namespace content { 29class DownloadFile; 30class DownloadItemImplDelegate; 31 32// See download_item.h for usage. 33class CONTENT_EXPORT DownloadItemImpl 34 : public DownloadItem, 35 public DownloadDestinationObserver { 36 public: 37 enum ResumeMode { 38 RESUME_MODE_INVALID = 0, 39 RESUME_MODE_IMMEDIATE_CONTINUE, 40 RESUME_MODE_IMMEDIATE_RESTART, 41 RESUME_MODE_USER_CONTINUE, 42 RESUME_MODE_USER_RESTART 43 }; 44 45 // The maximum number of attempts we will make to resume automatically. 46 static const int kMaxAutoResumeAttempts; 47 48 // Note that it is the responsibility of the caller to ensure that a 49 // DownloadItemImplDelegate passed to a DownloadItemImpl constructor 50 // outlives the DownloadItemImpl. 51 52 // Constructing from persistent store: 53 // |bound_net_log| is constructed externally for our use. 54 DownloadItemImpl(DownloadItemImplDelegate* delegate, 55 DownloadId download_id, 56 const base::FilePath& current_path, 57 const base::FilePath& target_path, 58 const std::vector<GURL>& url_chain, 59 const GURL& referrer_url, 60 const base::Time& start_time, 61 const base::Time& end_time, 62 int64 received_bytes, 63 int64 total_bytes, 64 DownloadItem::DownloadState state, 65 DownloadDangerType danger_type, 66 DownloadInterruptReason interrupt_reason, 67 bool opened, 68 const net::BoundNetLog& bound_net_log); 69 70 // Constructing for a regular download. 71 // |bound_net_log| is constructed externally for our use. 72 DownloadItemImpl(DownloadItemImplDelegate* delegate, 73 DownloadId download_id, 74 const DownloadCreateInfo& info, 75 const net::BoundNetLog& bound_net_log); 76 77 // Constructing for the "Save Page As..." feature: 78 // |bound_net_log| is constructed externally for our use. 79 DownloadItemImpl(DownloadItemImplDelegate* delegate, 80 DownloadId download_id, 81 const base::FilePath& path, 82 const GURL& url, 83 const std::string& mime_type, 84 scoped_ptr<DownloadRequestHandleInterface> request_handle, 85 const net::BoundNetLog& bound_net_log); 86 87 virtual ~DownloadItemImpl(); 88 89 // DownloadItem 90 virtual void AddObserver(DownloadItem::Observer* observer) OVERRIDE; 91 virtual void RemoveObserver(DownloadItem::Observer* observer) OVERRIDE; 92 virtual void UpdateObservers() OVERRIDE; 93 virtual void ValidateDangerousDownload() OVERRIDE; 94 virtual void StealDangerousDownload(const AcquireFileCallback& callback) 95 OVERRIDE; 96 virtual void Pause() OVERRIDE; 97 virtual void Resume() OVERRIDE; 98 virtual void Cancel(bool user_cancel) OVERRIDE; 99 virtual void Remove() OVERRIDE; 100 virtual void OpenDownload() OVERRIDE; 101 virtual void ShowDownloadInShell() OVERRIDE; 102 virtual int32 GetId() const OVERRIDE; 103 virtual DownloadId GetGlobalId() 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 bool IsDangerous() const OVERRIDE; 133 virtual DownloadDangerType GetDangerType() const OVERRIDE; 134 virtual bool TimeRemaining(base::TimeDelta* remaining) const OVERRIDE; 135 virtual int64 CurrentSpeed() const OVERRIDE; 136 virtual int PercentComplete() const OVERRIDE; 137 virtual bool AllDataSaved() const OVERRIDE; 138 virtual int64 GetTotalBytes() const OVERRIDE; 139 virtual int64 GetReceivedBytes() const OVERRIDE; 140 virtual base::Time GetStartTime() const OVERRIDE; 141 virtual base::Time GetEndTime() const OVERRIDE; 142 virtual bool CanShowInFolder() OVERRIDE; 143 virtual bool CanOpenDownload() OVERRIDE; 144 virtual bool ShouldOpenFileBasedOnExtension() OVERRIDE; 145 virtual bool GetOpenWhenComplete() const OVERRIDE; 146 virtual bool GetAutoOpened() OVERRIDE; 147 virtual bool GetOpened() const OVERRIDE; 148 virtual BrowserContext* GetBrowserContext() const OVERRIDE; 149 virtual WebContents* GetWebContents() const OVERRIDE; 150 virtual void OnContentCheckCompleted(DownloadDangerType danger_type) OVERRIDE; 151 virtual void SetOpenWhenComplete(bool open) OVERRIDE; 152 virtual void SetIsTemporary(bool temporary) OVERRIDE; 153 virtual void SetOpened(bool opened) OVERRIDE; 154 virtual void SetDisplayName(const base::FilePath& name) OVERRIDE; 155 virtual std::string DebugString(bool verbose) const OVERRIDE; 156 157 // All remaining public interfaces virtual to allow for DownloadItemImpl 158 // mocks. 159 160 // Determines the resume mode for an interrupted download. Requires 161 // last_reason_ to be set, but doesn't require the download to be in 162 // INTERRUPTED state. 163 virtual ResumeMode GetResumeMode() const; 164 165 // State transition operations on regular downloads -------------------------- 166 167 // Start the download. 168 // |download_file| is the associated file on the storage medium. 169 // |req_handle| is the new request handle associated with the download. 170 virtual void Start(scoped_ptr<DownloadFile> download_file, 171 scoped_ptr<DownloadRequestHandleInterface> req_handle); 172 173 // Needed because of intertwining with DownloadManagerImpl ------------------- 174 175 // TODO(rdsmith): Unwind DownloadManagerImpl and DownloadItemImpl, 176 // removing these from the public interface. 177 178 // Notify observers that this item is being removed by the user. 179 virtual void NotifyRemoved(); 180 181 virtual void OnDownloadedFileRemoved(); 182 183 // Provide a weak pointer reference to a DownloadDestinationObserver 184 // for use by download destinations. 185 virtual base::WeakPtr<DownloadDestinationObserver> 186 DestinationObserverAsWeakPtr(); 187 188 // Get the download's BoundNetLog. 189 virtual const net::BoundNetLog& GetBoundNetLog() const; 190 191 // DownloadItemImpl routines only needed by SavePackage ---------------------- 192 193 // Called by SavePackage to set the total number of bytes on the item. 194 virtual void SetTotalBytes(int64 total_bytes); 195 196 virtual void OnAllDataSaved(const std::string& final_hash); 197 198 // Called by SavePackage to display progress when the DownloadItem 199 // should be considered complete. 200 virtual void MarkAsComplete(); 201 202 // DownloadDestinationObserver 203 virtual void DestinationUpdate(int64 bytes_so_far, 204 int64 bytes_per_sec, 205 const std::string& hash_state) OVERRIDE; 206 virtual void DestinationError(DownloadInterruptReason reason) OVERRIDE; 207 virtual void DestinationCompleted(const std::string& final_hash) OVERRIDE; 208 209 private: 210 // Fine grained states of a download. Note that active downloads are created 211 // in IN_PROGRESS_INTERNAL state. However, downloads creates via history can 212 // be created in COMPLETE_INTERNAL, CANCELLED_INTERNAL and 213 // INTERRUPTED_INTERNAL. 214 215 enum DownloadInternalState { 216 // Includes both before and after file name determination, and paused 217 // downloads. 218 // TODO(rdsmith): Put in state variable for file name determination. 219 // Transitions from: 220 // <Initial creation> Active downloads are created in this state. 221 // RESUMING_INTERNAL 222 // Transitions to: 223 // COMPLETING_INTERNAL On final rename completion. 224 // CANCELLED_INTERNAL On cancel. 225 // INTERRUPTED_INTERNAL On interrupt. 226 // COMPLETE_INTERNAL On SavePackage download completion. 227 IN_PROGRESS_INTERNAL, 228 229 // Between commit point (dispatch of download file release) and completed. 230 // Embedder may be opening the file in this state. 231 // Transitions from: 232 // IN_PROGRESS_INTERNAL 233 // Transitions to: 234 // COMPLETE_INTERNAL On successful completion. 235 COMPLETING_INTERNAL, 236 237 // After embedder has had a chance to auto-open. User may now open 238 // or auto-open based on extension. 239 // Transitions from: 240 // COMPLETING_INTERNAL 241 // IN_PROGRESS_INTERNAL SavePackage only. 242 // <Initial creation> Completed persisted downloads. 243 // Transitions to: 244 // <none> Terminal state. 245 COMPLETE_INTERNAL, 246 247 // User has cancelled the download. 248 // Transitions from: 249 // IN_PROGRESS_INTERNAL 250 // INTERRUPTED_INTERNAL 251 // RESUMING_INTERNAL 252 // <Initial creation> Canceleld persisted downloads. 253 // Transitions to: 254 // <none> Terminal state. 255 CANCELLED_INTERNAL, 256 257 // An error has interrupted the download. 258 // Transitions from: 259 // IN_PROGRESS_INTERNAL 260 // RESUMING_INTERNAL 261 // <Initial creation> Interrupted persisted downloads. 262 // Transitions to: 263 // RESUMING_INTERNAL On resumption. 264 INTERRUPTED_INTERNAL, 265 266 // A request to resume this interrupted download is in progress. 267 // Transitions from: 268 // INTERRUPTED_INTERNAL 269 // Transitions to: 270 // IN_PROGRESS_INTERNAL Once a server response is received from a 271 // resumption. 272 // INTERRUPTED_INTERNAL If the resumption request fails. 273 // CANCELLED_INTERNAL On cancel. 274 RESUMING_INTERNAL, 275 276 MAX_DOWNLOAD_INTERNAL_STATE, 277 }; 278 279 // Used with TransitionTo() to indicate whether or not to call 280 // UpdateObservers() after the state transition. 281 enum ShouldUpdateObservers { 282 UPDATE_OBSERVERS, 283 DONT_UPDATE_OBSERVERS 284 }; 285 286 // Normal progression of a download ------------------------------------------ 287 288 // These are listed in approximately chronological order. There are also 289 // public methods involved in normal download progression; see 290 // the implementation ordering in download_item_impl.cc. 291 292 // Construction common to all constructors. |active| should be true for new 293 // downloads and false for downloads from the history. 294 // |download_type| indicates to the net log system what kind of download 295 // this is. 296 void Init(bool active, DownloadType download_type); 297 298 // Called when the target path has been determined. |target_path| is the 299 // suggested target path. |disposition| indicates how the target path should 300 // be used (see TargetDisposition). |danger_type| is the danger level of 301 // |target_path| as determined by the caller. |intermediate_path| is the path 302 // to use to store the download until OnDownloadCompleting() is called. 303 virtual void OnDownloadTargetDetermined( 304 const base::FilePath& target_path, 305 TargetDisposition disposition, 306 DownloadDangerType danger_type, 307 const base::FilePath& intermediate_path); 308 309 // Callback from file thread when we initialize the DownloadFile. 310 void OnDownloadFileInitialized(DownloadInterruptReason result); 311 312 void OnDownloadRenamedToIntermediateName( 313 DownloadInterruptReason reason, const base::FilePath& full_path); 314 315 // If all pre-requisites have been met, complete download processing, i.e. do 316 // internal cleanup, file rename, and potentially auto-open. (Dangerous 317 // downloads still may block on user acceptance after this point.) 318 void MaybeCompleteDownload(); 319 320 // Called when the download is ready to complete. 321 // This may perform final rename if necessary and will eventually call 322 // DownloadItem::Completed(). 323 void OnDownloadCompleting(); 324 325 void OnDownloadRenamedToFinalName(DownloadInterruptReason reason, 326 const base::FilePath& full_path); 327 328 // Called if the embedder took over opening a download, to indicate that 329 // the download has been opened. 330 void DelayedDownloadOpened(bool auto_opened); 331 332 // Called when the entire download operation (including renaming etc) 333 // is completed. 334 void Completed(); 335 336 // Callback invoked when the URLRequest for a download resumption has started. 337 void OnResumeRequestStarted(DownloadItem* item, net::Error error); 338 339 // Helper routines ----------------------------------------------------------- 340 341 // Indicate that an error has occurred on the download. 342 void Interrupt(DownloadInterruptReason reason); 343 344 // Destroy the DownloadFile object. If |destroy_file| is true, the file is 345 // destroyed with it. Otherwise, DownloadFile::Detach() is called before 346 // object destruction to prevent file destruction. Destroying the file also 347 // resets |current_path_|. 348 void ReleaseDownloadFile(bool destroy_file); 349 350 // Check if a download is ready for completion. The callback provided 351 // may be called at some point in the future if an external entity 352 // state has change s.t. this routine should be checked again. 353 bool IsDownloadReadyForCompletion(const base::Closure& state_change_notify); 354 355 // Call to transition state; all state transitions should go through this. 356 // |notify_action| specifies whether or not to call UpdateObservers() after 357 // the state transition. 358 void TransitionTo(DownloadInternalState new_state, 359 ShouldUpdateObservers notify_action); 360 361 // Set the |danger_type_| and invoke obserers if necessary. 362 void SetDangerType(DownloadDangerType danger_type); 363 364 void SetFullPath(const base::FilePath& new_path); 365 366 void AutoResumeIfValid(); 367 368 void ResumeInterruptedDownload(); 369 370 static DownloadState InternalToExternalState( 371 DownloadInternalState internal_state); 372 static DownloadInternalState ExternalToInternalState( 373 DownloadState external_state); 374 375 // Debugging routines -------------------------------------------------------- 376 static const char* DebugDownloadStateString(DownloadInternalState state); 377 static const char* DebugResumeModeString(ResumeMode mode); 378 379 // Will be false for save package downloads retrieved from the history. 380 // TODO(rdsmith): Replace with a generalized enum for "download source". 381 const bool is_save_package_download_; 382 383 // The handle to the request information. Used for operations outside the 384 // download system. 385 scoped_ptr<DownloadRequestHandleInterface> request_handle_; 386 387 // Download ID assigned by DownloadResourceHandler. 388 DownloadId 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_ 547