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