download_item.h revision a93a17c8d99d686bd4a1511e5504e5e6cc9fcadf
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/files/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 GURL;
32
33namespace base {
34class FilePath;
35class Time;
36class TimeDelta;
37}
38
39namespace content {
40
41class BrowserContext;
42class DownloadId;
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  // Reason for deleting the download.  Passed to Delete().
71  enum DeleteReason {
72    DELETE_DUE_TO_BROWSER_SHUTDOWN = 0,
73    DELETE_DUE_TO_USER_DISCARD
74  };
75
76  // How the final target path should be used.
77  enum TargetDisposition {
78    TARGET_DISPOSITION_OVERWRITE, // Overwrite if the target already exists.
79    TARGET_DISPOSITION_PROMPT     // Prompt the user for the actual
80                                  // target. Implies
81                                  // TARGET_DISPOSITION_OVERWRITE.
82  };
83
84  static const char kEmptyFileHash[];
85
86  // Interface that observers of a particular download must implement in order
87  // to receive updates to the download's status.
88  class CONTENT_EXPORT Observer {
89   public:
90    virtual void OnDownloadUpdated(DownloadItem* download) {}
91    virtual void OnDownloadOpened(DownloadItem* download) {}
92    virtual void OnDownloadRemoved(DownloadItem* download) {}
93
94    // Called when the download is being destroyed. This happens after
95    // every OnDownloadRemoved() as well as when the DownloadManager is going
96    // down.
97    virtual void OnDownloadDestroyed(DownloadItem* download) {}
98
99   protected:
100    virtual ~Observer() {}
101  };
102
103  virtual ~DownloadItem() {}
104
105  // Observation ---------------------------------------------------------------
106
107  virtual void AddObserver(DownloadItem::Observer* observer) = 0;
108  virtual void RemoveObserver(DownloadItem::Observer* observer) = 0;
109  virtual void UpdateObservers() = 0;
110
111  // User Actions --------------------------------------------------------------
112
113  // Called when the user has validated the download of a dangerous file.
114  virtual void DangerousDownloadValidated() = 0;
115
116  // Pause a download.  Will have no effect if the download is already
117  // paused.
118  virtual void Pause() = 0;
119
120  // Resume a download that has been paused or interrupted. Will have no effect
121  // if the download is neither.
122  virtual void Resume() = 0;
123
124  // Cancel the download operation. We need to distinguish between cancels at
125  // exit (DownloadManager destructor) from user interface initiated cancels
126  // because at exit, the history system may not exist, and any updates to it
127  // require AddRef'ing the DownloadManager in the destructor which results in
128  // a DCHECK failure. Set |user_cancel| to false when canceling from at
129  // exit to prevent this crash. This may result in a difference between the
130  // downloaded file's size on disk, and what the history system's last record
131  // of it is. At worst, we'll end up re-downloading a small portion of the file
132  // when resuming a download (assuming the server supports byte ranges).
133  virtual void Cancel(bool user_cancel) = 0;
134
135  // Deletes the file from disk and removes the download from the views and
136  // history.
137  virtual void Delete(DeleteReason reason) = 0;
138
139  // Removes the download from the views and history.
140  virtual void Remove() = 0;
141
142  // Open the file associated with this download.  If the download is
143  // still in progress, marks the download to be opened when it is complete.
144  virtual void OpenDownload() = 0;
145
146  // Show the download via the OS shell.
147  virtual void ShowDownloadInShell() = 0;
148
149  // State accessors -----------------------------------------------------------
150
151  virtual int32 GetId() const = 0;
152  virtual DownloadId GetGlobalId() const = 0;
153  virtual DownloadState GetState() const = 0;
154
155  // Only valid if |GetState() == DownloadItem::INTERRUPTED|.
156  virtual DownloadInterruptReason GetLastReason() const = 0;
157
158  virtual bool IsPaused() const = 0;
159  virtual bool IsTemporary() const = 0;
160
161  //    Convenience routines for accessing GetState() results conceptually -----
162
163  // Returns true if the download needs more data.
164  virtual bool IsPartialDownload() const = 0;
165
166  // Returns true if the download is still receiving data.
167  virtual bool IsInProgress() const = 0;
168
169  // Returns true if the download has been cancelled or was interrupted.
170  virtual bool IsCancelled() const = 0;
171
172  // Returns true if the download was interrupted.
173  virtual bool IsInterrupted() const = 0;
174
175  // Returns true if we have all the data and know the final file name.
176  virtual bool IsComplete() 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 user-verified target file path for the download.
221  // This returns the same path as GetTargetFilePath() for safe downloads
222  // but does not for dangerous downloads until the name is verified.
223  virtual base::FilePath GetUserVerifiedFilePath() const = 0;
224
225  // Returns the file-name that should be reported to the user. If a display
226  // name has been explicitly set using SetDisplayName(), this function returns
227  // that display name. Otherwise returns the final target filename.
228  virtual base::FilePath GetFileNameToReportUser() const = 0;
229
230  virtual TargetDisposition GetTargetDisposition() const = 0;
231
232  // Final hash of completely downloaded file; not valid if
233  // GetState() != COMPLETED.
234  virtual const std::string& GetHash() const = 0;
235
236  // Intermediate hash state, for persisting partial downloads.
237  virtual const std::string& GetHashState() const = 0;
238
239  // True if the file associated with the download has been removed by
240  // external action.
241  virtual bool GetFileExternallyRemoved() const = 0;
242
243  // True if the file that will be written by the download is dangerous
244  // and we will require a call to DangerousDownloadValidated() to complete.
245  // False if the download is safe or that function has been called.
246  virtual bool IsDangerous() const = 0;
247
248  // Why |safety_state_| is not SAFE.
249  virtual DownloadDangerType GetDangerType() const = 0;
250
251  //    Progress State accessors -----------------------------------------------
252
253  // Simple calculation of the amount of time remaining to completion. Fills
254  // |*remaining| with the amount of time remaining if successful. Fails and
255  // returns false if we do not have the number of bytes or the speed so can
256  // not estimate.
257  virtual bool TimeRemaining(base::TimeDelta* remaining) const = 0;
258
259  // Simple speed estimate in bytes/s
260  virtual int64 CurrentSpeed() const = 0;
261
262  // Rough percent complete, -1 means we don't know (== we didn't receive a
263  // total size).
264  virtual int PercentComplete() const = 0;
265
266  // Returns true if this download has saved all of its data.
267  virtual bool AllDataSaved() const = 0;
268
269  virtual int64 GetTotalBytes() const = 0;
270  virtual int64 GetReceivedBytes() const = 0;
271  virtual base::Time GetStartTime() const = 0;
272  virtual base::Time GetEndTime() const = 0;
273
274  //    Open/Show State accessors ----------------------------------------------
275
276  // Returns true if it is OK to open a folder which this file is inside.
277  virtual bool CanShowInFolder() = 0;
278
279  // Returns true if it is OK to open the download.
280  virtual bool CanOpenDownload() = 0;
281
282  // Tests if a file type should be opened automatically.
283  virtual bool ShouldOpenFileBasedOnExtension() = 0;
284
285  // Returns true if the download will be auto-opened when complete.
286  virtual bool GetOpenWhenComplete() const = 0;
287
288  // Returns true if the download has been auto-opened by the system.
289  virtual bool GetAutoOpened() = 0;
290
291  // Returns true if the download has been opened.
292  virtual bool GetOpened() const = 0;
293
294  //    Misc State accessors ---------------------------------------------------
295
296  virtual BrowserContext* GetBrowserContext() const = 0;
297  virtual WebContents* GetWebContents() const = 0;
298
299  // External state transitions/setters ----------------------------------------
300  // TODO(rdsmith): These should all be removed; the download item should
301  // control its own state transitions.
302
303  // Called if a check of the download contents was performed and the results of
304  // the test are available. This should only be called after AllDataSaved() is
305  // true.
306  virtual void OnContentCheckCompleted(DownloadDangerType danger_type) = 0;
307
308  // Mark the download to be auto-opened when completed.
309  virtual void SetOpenWhenComplete(bool open) = 0;
310
311  // Mark the download as temporary (not visible in persisted store or
312  // SearchDownloads(), removed from main UI upon completion).
313  virtual void SetIsTemporary(bool temporary) = 0;
314
315  // Mark the download as having been opened (without actually opening it).
316  virtual void SetOpened(bool opened) = 0;
317
318  // Set a display name for the download that will be independent of the target
319  // filename. If |name| is not empty, then GetFileNameToReportUser() will
320  // return |name|. Has no effect on the final target filename.
321  virtual void SetDisplayName(const base::FilePath& name) = 0;
322
323  // Debug/testing -------------------------------------------------------------
324  virtual std::string DebugString(bool verbose) const = 0;
325};
326
327}  // namespace content
328
329#endif  // CONTENT_PUBLIC_BROWSER_DOWNLOAD_ITEM_H_
330