download_item.h revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
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// Each download is represented by a DownloadItem, and all DownloadItems
6// are owned by the DownloadManager which maintains a global list of all
7// downloads. DownloadItems are created when a user initiates a download,
8// and exist for the duration of the browser life time.
9//
10// Download observers:
11//   DownloadItem::Observer:
12//     - allows observers to receive notifications about one download from start
13//       to completion
14// Use AddObserver() / RemoveObserver() on the appropriate download object to
15// receive state updates.
16
17#ifndef CONTENT_PUBLIC_BROWSER_DOWNLOAD_ITEM_H_
18#define CONTENT_PUBLIC_BROWSER_DOWNLOAD_ITEM_H_
19
20#include <map>
21#include <string>
22#include <vector>
23
24#include "base/callback_forward.h"
25#include "base/files/file_path.h"
26#include "base/strings/string16.h"
27#include "base/supports_user_data.h"
28#include "content/public/browser/download_danger_type.h"
29#include "content/public/browser/download_interrupt_reasons.h"
30#include "content/public/common/page_transition_types.h"
31
32class GURL;
33
34namespace base {
35class FilePath;
36class Time;
37class TimeDelta;
38}
39
40namespace content {
41
42class BrowserContext;
43class DownloadManager;
44class WebContents;
45
46// One DownloadItem per download. This is the model class that stores all the
47// state for a download. Multiple views, such as a tab's download shelf and the
48// Destination tab's download view, may refer to a given DownloadItem.
49//
50// This is intended to be used only on the UI thread.
51class CONTENT_EXPORT DownloadItem : public base::SupportsUserData {
52 public:
53  enum DownloadState {
54    // Download is actively progressing.
55    IN_PROGRESS = 0,
56
57    // Download is completely finished.
58    COMPLETE,
59
60    // Download has been cancelled.
61    CANCELLED,
62
63    // This state indicates that the download has been interrupted.
64    INTERRUPTED,
65
66    // Maximum value.
67    MAX_DOWNLOAD_STATE
68  };
69
70  // How the final target path should be used.
71  enum TargetDisposition {
72    TARGET_DISPOSITION_OVERWRITE, // Overwrite if the target already exists.
73    TARGET_DISPOSITION_PROMPT     // Prompt the user for the actual
74                                  // target. Implies
75                                  // TARGET_DISPOSITION_OVERWRITE.
76  };
77
78  // Callback used with AcquireFileAndDeleteDownload().
79  typedef base::Callback<void(const base::FilePath&)> AcquireFileCallback;
80
81  static const uint32 kInvalidId;
82
83  static const char kEmptyFileHash[];
84
85  // Interface that observers of a particular download must implement in order
86  // to receive updates to the download's status.
87  class CONTENT_EXPORT Observer {
88   public:
89    virtual void OnDownloadUpdated(DownloadItem* download) {}
90    virtual void OnDownloadOpened(DownloadItem* download) {}
91    virtual void OnDownloadRemoved(DownloadItem* download) {}
92
93    // Called when the download is being destroyed. This happens after
94    // every OnDownloadRemoved() as well as when the DownloadManager is going
95    // down.
96    virtual void OnDownloadDestroyed(DownloadItem* download) {}
97
98   protected:
99    virtual ~Observer() {}
100  };
101
102  virtual ~DownloadItem() {}
103
104  // Observation ---------------------------------------------------------------
105
106  virtual void AddObserver(DownloadItem::Observer* observer) = 0;
107  virtual void RemoveObserver(DownloadItem::Observer* observer) = 0;
108  virtual void UpdateObservers() = 0;
109
110  // User Actions --------------------------------------------------------------
111
112  // Called when the user has validated the download of a dangerous file.
113  virtual void ValidateDangerousDownload() = 0;
114
115  // Called to acquire a dangerous download and remove the DownloadItem from
116  // views and history. |callback| will be invoked on the UI thread with the
117  // path to the downloaded file. The caller is responsible for cleanup.
118  // Note: It is important for |callback| to be valid since the downloaded file
119  // will not be cleaned up if the callback fails.
120  virtual void StealDangerousDownload(const AcquireFileCallback& callback) = 0;
121
122  // Pause a download.  Will have no effect if the download is already
123  // paused.
124  virtual void Pause() = 0;
125
126  // Resume a download that has been paused or interrupted. Will have no effect
127  // if the download is neither.
128  virtual void Resume() = 0;
129
130  // Cancel the download operation. We need to distinguish between cancels at
131  // exit (DownloadManager destructor) from user interface initiated cancels
132  // because at exit, the history system may not exist, and any updates to it
133  // require AddRef'ing the DownloadManager in the destructor which results in
134  // a DCHECK failure. Set |user_cancel| to false when canceling from at
135  // exit to prevent this crash. This may result in a difference between the
136  // downloaded file's size on disk, and what the history system's last record
137  // of it is. At worst, we'll end up re-downloading a small portion of the file
138  // when resuming a download (assuming the server supports byte ranges).
139  virtual void Cancel(bool user_cancel) = 0;
140
141  // Removes the download from the views and history. If the download was
142  // in-progress or interrupted, then the intermediate file will also be
143  // deleted.
144  virtual void Remove() = 0;
145
146  // Open the file associated with this download.  If the download is
147  // still in progress, marks the download to be opened when it is complete.
148  virtual void OpenDownload() = 0;
149
150  // Show the download via the OS shell.
151  virtual void ShowDownloadInShell() = 0;
152
153  // State accessors -----------------------------------------------------------
154
155  virtual uint32 GetId() const = 0;
156  virtual DownloadState GetState() const = 0;
157
158  // Returns the most recent interrupt reason for this download. Returns
159  // DOWNLOAD_INTERRUPT_REASON_NONE if there is no previous interrupt reason.
160  // Cancelled downloads return DOWNLOAD_INTERRUPT_REASON_USER_CANCELLED. If
161  // the download was resumed, then the return value is the interrupt reason
162  // prior to resumption.
163  virtual DownloadInterruptReason GetLastReason() const = 0;
164
165  virtual bool IsPaused() const = 0;
166  virtual bool IsTemporary() const = 0;
167
168  // Returns true if the download can be resumed. A download can be resumed if
169  // an in-progress download was paused or if an interrupted download requires
170  // user-interaction to resume.
171  virtual bool CanResume() const = 0;
172
173  // Returns true if the download is in a terminal state. This includes
174  // completed downloads, cancelled downloads, and interrupted downloads that
175  // can't be resumed.
176  virtual bool IsDone() const = 0;
177
178  //    Origin State accessors -------------------------------------------------
179
180  virtual const GURL& GetURL() const = 0;
181  virtual const std::vector<GURL>& GetUrlChain() const = 0;
182  virtual const GURL& GetOriginalUrl() const = 0;
183  virtual const GURL& GetReferrerUrl() const = 0;
184  virtual std::string GetSuggestedFilename() const = 0;
185  virtual std::string GetContentDisposition() const = 0;
186  virtual std::string GetMimeType() const = 0;
187  virtual std::string GetOriginalMimeType() const = 0;
188  virtual std::string GetRemoteAddress() const = 0;
189  virtual bool HasUserGesture() const = 0;
190  virtual PageTransition GetTransitionType() const = 0;
191  virtual const std::string& GetLastModifiedTime() const = 0;
192  virtual const std::string& GetETag() const = 0;
193  virtual bool IsSavePackageDownload() const = 0;
194
195  //    Destination State accessors --------------------------------------------
196
197  // Full path to the downloaded or downloading file. This is the path to the
198  // physical file, if one exists. It should be considered a hint; changes to
199  // this value and renames of the file on disk are not atomic with each other.
200  // May be empty if the in-progress path hasn't been determined yet or if the
201  // download was interrupted.
202  //
203  // DO NOT USE THIS METHOD to access the target path of the DownloadItem. Use
204  // GetTargetFilePath() instead. While the download is in progress, the
205  // intermediate file named by GetFullPath() may be renamed or disappear
206  // completely on the FILE thread. The path may also be reset to empty when the
207  // download is interrupted.
208  virtual const base::FilePath& GetFullPath() const = 0;
209
210  // Target path of an in-progress download. We may be downloading to a
211  // temporary or intermediate file (specified by GetFullPath()); this is the
212  // name we will use once the download completes.
213  // May be empty if the target path hasn't yet been determined.
214  virtual const base::FilePath& GetTargetFilePath() const = 0;
215
216  // If the download forced a path rather than requesting name determination,
217  // return the path requested.
218  virtual const base::FilePath& GetForcedFilePath() const = 0;
219
220  // Returns the file-name that should be reported to the user. If a display
221  // name has been explicitly set using SetDisplayName(), this function returns
222  // that display name. Otherwise returns the final target filename.
223  virtual base::FilePath GetFileNameToReportUser() const = 0;
224
225  virtual TargetDisposition GetTargetDisposition() const = 0;
226
227  // Final hash of completely downloaded file; not valid if
228  // GetState() != COMPLETED.
229  virtual const std::string& GetHash() const = 0;
230
231  // Intermediate hash state, for persisting partial downloads.
232  virtual const std::string& GetHashState() const = 0;
233
234  // True if the file associated with the download has been removed by
235  // external action.
236  virtual bool GetFileExternallyRemoved() const = 0;
237
238  // If the file is successfully deleted, then GetFileExternallyRemoved() will
239  // become true, GetFullPath() will become empty, and
240  // DownloadItem::OnDownloadUpdated() will be called. Does nothing if
241  // GetState() == COMPLETE or GetFileExternallyRemoved() is already true or
242  // GetFullPath() is already empty. The callback is always run, and it is
243  // always run asynchronously. It will be passed true if the file is
244  // successfully deleted or if GetFilePath() was already empty or if
245  // GetFileExternallyRemoved() was already true. The callback will be passed
246  // false if the DownloadItem was not yet complete or if the file could not be
247  // deleted for any reason.
248  virtual void DeleteFile(const base::Callback<void(bool)>& callback) = 0;
249
250  // True if the file that will be written by the download is dangerous
251  // and we will require a call to ValidateDangerousDownload() to complete.
252  // False if the download is safe or that function has been called.
253  virtual bool IsDangerous() const = 0;
254
255  // Why |safety_state_| is not SAFE.
256  virtual DownloadDangerType GetDangerType() const = 0;
257
258  //    Progress State accessors -----------------------------------------------
259
260  // Simple calculation of the amount of time remaining to completion. Fills
261  // |*remaining| with the amount of time remaining if successful. Fails and
262  // returns false if we do not have the number of bytes or the speed so can
263  // not estimate.
264  virtual bool TimeRemaining(base::TimeDelta* remaining) const = 0;
265
266  // Simple speed estimate in bytes/s
267  virtual int64 CurrentSpeed() const = 0;
268
269  // Rough percent complete, -1 means we don't know (== we didn't receive a
270  // total size).
271  virtual int PercentComplete() const = 0;
272
273  // Returns true if this download has saved all of its data.
274  virtual bool AllDataSaved() const = 0;
275
276  virtual int64 GetTotalBytes() const = 0;
277  virtual int64 GetReceivedBytes() const = 0;
278  virtual base::Time GetStartTime() const = 0;
279  virtual base::Time GetEndTime() const = 0;
280
281  //    Open/Show State accessors ----------------------------------------------
282
283  // Returns true if it is OK to open a folder which this file is inside.
284  virtual bool CanShowInFolder() = 0;
285
286  // Returns true if it is OK to open the download.
287  virtual bool CanOpenDownload() = 0;
288
289  // Tests if a file type should be opened automatically.
290  virtual bool ShouldOpenFileBasedOnExtension() = 0;
291
292  // Returns true if the download will be auto-opened when complete.
293  virtual bool GetOpenWhenComplete() const = 0;
294
295  // Returns true if the download has been auto-opened by the system.
296  virtual bool GetAutoOpened() = 0;
297
298  // Returns true if the download has been opened.
299  virtual bool GetOpened() const = 0;
300
301  //    Misc State accessors ---------------------------------------------------
302
303  virtual BrowserContext* GetBrowserContext() const = 0;
304  virtual WebContents* GetWebContents() const = 0;
305
306  // External state transitions/setters ----------------------------------------
307  // TODO(rdsmith): These should all be removed; the download item should
308  // control its own state transitions.
309
310  // Called if a check of the download contents was performed and the results of
311  // the test are available. This should only be called after AllDataSaved() is
312  // true.
313  virtual void OnContentCheckCompleted(DownloadDangerType danger_type) = 0;
314
315  // Mark the download to be auto-opened when completed.
316  virtual void SetOpenWhenComplete(bool open) = 0;
317
318  // Mark the download as temporary (not visible in persisted store or
319  // SearchDownloads(), removed from main UI upon completion).
320  virtual void SetIsTemporary(bool temporary) = 0;
321
322  // Mark the download as having been opened (without actually opening it).
323  virtual void SetOpened(bool opened) = 0;
324
325  // Set a display name for the download that will be independent of the target
326  // filename. If |name| is not empty, then GetFileNameToReportUser() will
327  // return |name|. Has no effect on the final target filename.
328  virtual void SetDisplayName(const base::FilePath& name) = 0;
329
330  // Debug/testing -------------------------------------------------------------
331  virtual std::string DebugString(bool verbose) const = 0;
332};
333
334}  // namespace content
335
336#endif  // CONTENT_PUBLIC_BROWSER_DOWNLOAD_ITEM_H_
337