download_item.h revision 5821806d5e7f356e8fa4b058a389a808ea183019
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/file_path.h"
25#include "base/string16.h"
26#include "base/supports_user_data.h"
27#include "content/public/browser/download_danger_type.h"
28#include "content/public/browser/download_interrupt_reasons.h"
29#include "content/public/common/page_transition_types.h"
30
31class FilePath;
32class GURL;
33
34namespace base {
35class Time;
36class TimeDelta;
37}
38
39namespace content {
40
41class BrowserContext;
42class DownloadId;
43class DownloadManager;
44class WebContents;
45struct DownloadCreateInfo;
46struct DownloadPersistentStoreInfo;
47
48// One DownloadItem per download. This is the model class that stores all the
49// state for a download. Multiple views, such as a tab's download shelf and the
50// Destination tab's download view, may refer to a given DownloadItem.
51//
52// This is intended to be used only on the UI thread.
53class CONTENT_EXPORT DownloadItem : public base::SupportsUserData {
54 public:
55  enum DownloadState {
56    // Download is actively progressing.
57    IN_PROGRESS = 0,
58
59    // Download is completely finished.
60    COMPLETE,
61
62    // Download has been cancelled.
63    CANCELLED,
64
65    // This state indicates that the download has been interrupted.
66    INTERRUPTED,
67
68    // Maximum value.
69    MAX_DOWNLOAD_STATE
70  };
71
72  enum SafetyState {
73    SAFE = 0,
74    DANGEROUS,
75    DANGEROUS_BUT_VALIDATED  // Dangerous but the user confirmed the download.
76  };
77
78  // Reason for deleting the download.  Passed to Delete().
79  enum DeleteReason {
80    DELETE_DUE_TO_BROWSER_SHUTDOWN = 0,
81    DELETE_DUE_TO_USER_DISCARD
82  };
83
84  // How the final target path should be used.
85  enum TargetDisposition {
86    TARGET_DISPOSITION_OVERWRITE, // Overwrite if the target already exists.
87    TARGET_DISPOSITION_PROMPT     // Prompt the user for the actual
88                                  // target. Implies
89                                  // TARGET_DISPOSITION_OVERWRITE.
90  };
91
92  // A fake download table ID which represents a download that has started,
93  // but is not yet in the table.
94  static const int kUninitializedHandle;
95
96  static const char kEmptyFileHash[];
97
98  // Interface that observers of a particular download must implement in order
99  // to receive updates to the download's status.
100  class CONTENT_EXPORT Observer {
101   public:
102    virtual void OnDownloadUpdated(DownloadItem* download) {}
103    virtual void OnDownloadOpened(DownloadItem* download) {}
104    virtual void OnDownloadRemoved(DownloadItem* download) {}
105
106    // Called when the download is being destroyed. This happens after
107    // every OnDownloadRemoved() as well as when the DownloadManager is going
108    // down.
109    virtual void OnDownloadDestroyed(DownloadItem* download) {}
110
111   protected:
112    virtual ~Observer() {}
113  };
114
115  virtual ~DownloadItem() {}
116
117  // Observation ---------------------------------------------------------------
118
119  virtual void AddObserver(DownloadItem::Observer* observer) = 0;
120  virtual void RemoveObserver(DownloadItem::Observer* observer) = 0;
121  virtual void UpdateObservers() = 0;
122
123  // User Actions --------------------------------------------------------------
124
125  // Called when the user has validated the download of a dangerous file.
126  virtual void DangerousDownloadValidated() = 0;
127
128  // Allow the user to temporarily pause a download or resume a paused download.
129  virtual void TogglePause() = 0;
130
131  // Cancel the download operation. We need to distinguish between cancels at
132  // exit (DownloadManager destructor) from user interface initiated cancels
133  // because at exit, the history system may not exist, and any updates to it
134  // require AddRef'ing the DownloadManager in the destructor which results in
135  // a DCHECK failure. Set |user_cancel| to false when canceling from at
136  // exit to prevent this crash. This may result in a difference between the
137  // downloaded file's size on disk, and what the history system's last record
138  // of it is. At worst, we'll end up re-downloading a small portion of the file
139  // when resuming a download (assuming the server supports byte ranges).
140  virtual void Cancel(bool user_cancel) = 0;
141
142  // Deletes the file from disk and removes the download from the views and
143  // history.
144  virtual void Delete(DeleteReason reason) = 0;
145
146  // Removes the download from the views and history.
147  virtual void Remove() = 0;
148
149  // Open the file associated with this download.  If the download is
150  // still in progress, marks the download to be opened when it is complete.
151  virtual void OpenDownload() = 0;
152
153  // Show the download via the OS shell.
154  virtual void ShowDownloadInShell() = 0;
155
156  // State accessors -----------------------------------------------------------
157
158  virtual int32 GetId() const = 0;
159  virtual DownloadId GetGlobalId() const = 0;
160  virtual int64 GetDbHandle() const = 0;
161  virtual DownloadState GetState() const = 0;
162
163  // Only valid if |GetState() == DownloadItem::INTERRUPTED|.
164  virtual DownloadInterruptReason GetLastReason() const = 0;
165
166  virtual bool IsPaused() const = 0;
167  virtual bool IsTemporary() const = 0;
168  virtual bool IsPersisted() const = 0;
169
170  //    Convenience routines for accessing GetState() results conceptually -----
171
172  // Returns true if the download needs more data.
173  virtual bool IsPartialDownload() const = 0;
174
175  // Returns true if the download is still receiving data.
176  virtual bool IsInProgress() const = 0;
177
178  // Returns true if the download has been cancelled or was interrupted.
179  virtual bool IsCancelled() const = 0;
180
181  // Returns true if the download was interrupted.
182  virtual bool IsInterrupted() const = 0;
183
184  // Returns true if we have all the data and know the final file name.
185  virtual bool IsComplete() const = 0;
186
187  //    Origin State accessors -------------------------------------------------
188
189  virtual const GURL& GetURL() const = 0;
190  virtual const std::vector<GURL>& GetUrlChain() const = 0;
191  virtual const GURL& GetOriginalUrl() const = 0;
192  virtual const GURL& GetReferrerUrl() const = 0;
193  virtual std::string GetSuggestedFilename() const = 0;
194  virtual std::string GetContentDisposition() const = 0;
195  virtual std::string GetMimeType() const = 0;
196  virtual std::string GetOriginalMimeType() const = 0;
197  virtual std::string GetRemoteAddress() const = 0;
198  virtual bool HasUserGesture() const = 0;
199  virtual PageTransition GetTransitionType() const = 0;
200  virtual const std::string& GetLastModifiedTime() const = 0;
201  virtual const std::string& GetETag() const = 0;
202  virtual bool IsSavePackageDownload() const = 0;
203
204  //    Destination State accessors --------------------------------------------
205
206  // Full path to the downloaded or downloading file. This is the path to the
207  // physical file, if one exists. It should be considered a hint; changes to
208  // this value and renames of the file on disk are not atomic with each other.
209  // May be empty if the in-progress path hasn't been determined yet.
210  virtual const FilePath& GetFullPath() const = 0;
211
212  // Target path of an in-progress download. We may be downloading to a
213  // temporary or intermediate file (specified by GetFullPath()); this is the
214  // name we will use once the download completes.
215  // May be empty if the target path hasn't yet been determined.
216  virtual const FilePath& GetTargetFilePath() const = 0;
217
218  // If the download forced a path rather than requesting name determination,
219  // return the path requested.
220  virtual const FilePath& GetForcedFilePath() const = 0;
221
222  // Returns the user-verified target file path for the download.
223  // This returns the same path as GetTargetFilePath() for safe downloads
224  // but does not for dangerous downloads until the name is verified.
225  virtual FilePath GetUserVerifiedFilePath() const = 0;
226
227  // Returns the file-name that should be reported to the user. If a display
228  // name has been explicitly set using SetDisplayName(), this function returns
229  // that display name. Otherwise returns the final target filename.
230  virtual FilePath GetFileNameToReportUser() const = 0;
231
232  virtual TargetDisposition GetTargetDisposition() const = 0;
233
234  // Final hash of completely downloaded file; not valid if
235  // GetState() != COMPLETED.
236  virtual const std::string& GetHash() const = 0;
237
238  // Intermediate hash state, for persisting partial downloads.
239  virtual const std::string& GetHashState() const = 0;
240
241  // True if the file associated with the download has been removed by
242  // external action.
243  virtual bool GetFileExternallyRemoved() const = 0;
244
245  // The safety state of the download.  |GetSafetyState() == DANGEROUS|
246  // may represent a potentially dangerous download, and may occur even
247  // if |IsDangerous() == false|.
248  virtual SafetyState GetSafetyState() const = 0;
249
250  // True if the file that will be written by the download is dangerous
251  // and we will require user intervention to complete the download.
252  virtual bool IsDangerous() const = 0;
253
254  // Why |safety_state_| is not SAFE.
255  virtual DownloadDangerType GetDangerType() const = 0;
256
257  //    Progress State accessors -----------------------------------------------
258
259  // Simple calculation of the amount of time remaining to completion. Fills
260  // |*remaining| with the amount of time remaining if successful. Fails and
261  // returns false if we do not have the number of bytes or the speed so can
262  // not estimate.
263  virtual bool TimeRemaining(base::TimeDelta* remaining) const = 0;
264
265  // Simple speed estimate in bytes/s
266  virtual int64 CurrentSpeed() const = 0;
267
268  // Rough percent complete, -1 means we don't know (== we didn't receive a
269  // total size).
270  virtual int PercentComplete() const = 0;
271
272  // Returns true if this download has saved all of its data.
273  virtual bool AllDataSaved() const = 0;
274
275  virtual int64 GetTotalBytes() const = 0;
276  virtual int64 GetReceivedBytes() const = 0;
277  virtual base::Time GetStartTime() const = 0;
278  virtual base::Time GetEndTime() const = 0;
279
280  //    Open/Show State accessors ----------------------------------------------
281
282  // Returns true if it is OK to open a folder which this file is inside.
283  virtual bool CanShowInFolder() = 0;
284
285  // Returns true if it is OK to open the download.
286  virtual bool CanOpenDownload() = 0;
287
288  // Tests if a file type should be opened automatically.
289  virtual bool ShouldOpenFileBasedOnExtension() = 0;
290
291  // Returns true if the download will be auto-opened when complete.
292  virtual bool GetOpenWhenComplete() const = 0;
293
294  // Returns true if the download has been auto-opened by the system.
295  virtual bool GetAutoOpened() = 0;
296
297  // Returns true if the download has been opened.
298  virtual bool GetOpened() const = 0;
299
300  //    Misc State accessors ---------------------------------------------------
301
302  virtual DownloadPersistentStoreInfo GetPersistentStoreInfo() const = 0;
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 FilePath& name) = 0;
329
330  // Debug/testing -------------------------------------------------------------
331  virtual std::string DebugString(bool verbose) const = 0;
332  virtual void MockDownloadOpenForTesting() = 0;
333};
334
335}  // namespace content
336
337#endif  // CONTENT_PUBLIC_BROWSER_DOWNLOAD_ITEM_H_
338