download_item.h revision b2df76ea8fec9e32f6f3718986dba0d95315b29c
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.  Will have no effect if the download is not
121  // paused.
122  virtual void Resume() = 0;
123
124  // Resume a download that's been interrupted.  No-op if the download
125  // has not been interrupted.
126  virtual void ResumeInterruptedDownload() = 0;
127
128  // Cancel the download operation. We need to distinguish between cancels at
129  // exit (DownloadManager destructor) from user interface initiated cancels
130  // because at exit, the history system may not exist, and any updates to it
131  // require AddRef'ing the DownloadManager in the destructor which results in
132  // a DCHECK failure. Set |user_cancel| to false when canceling from at
133  // exit to prevent this crash. This may result in a difference between the
134  // downloaded file's size on disk, and what the history system's last record
135  // of it is. At worst, we'll end up re-downloading a small portion of the file
136  // when resuming a download (assuming the server supports byte ranges).
137  virtual void Cancel(bool user_cancel) = 0;
138
139  // Deletes the file from disk and removes the download from the views and
140  // history.
141  virtual void Delete(DeleteReason reason) = 0;
142
143  // Removes the download from the views and history.
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 int32 GetId() const = 0;
156  virtual DownloadId GetGlobalId() const = 0;
157  virtual DownloadState GetState() const = 0;
158
159  // Only valid if |GetState() == DownloadItem::INTERRUPTED|.
160  virtual DownloadInterruptReason GetLastReason() const = 0;
161
162  virtual bool IsPaused() const = 0;
163  virtual bool IsTemporary() const = 0;
164
165  //    Convenience routines for accessing GetState() results conceptually -----
166
167  // Returns true if the download needs more data.
168  virtual bool IsPartialDownload() const = 0;
169
170  // Returns true if the download is still receiving data.
171  virtual bool IsInProgress() const = 0;
172
173  // Returns true if the download has been cancelled or was interrupted.
174  virtual bool IsCancelled() const = 0;
175
176  // Returns true if the download was interrupted.
177  virtual bool IsInterrupted() const = 0;
178
179  // Returns true if we have all the data and know the final file name.
180  virtual bool IsComplete() const = 0;
181
182  //    Origin State accessors -------------------------------------------------
183
184  virtual const GURL& GetURL() const = 0;
185  virtual const std::vector<GURL>& GetUrlChain() const = 0;
186  virtual const GURL& GetOriginalUrl() const = 0;
187  virtual const GURL& GetReferrerUrl() const = 0;
188  virtual std::string GetSuggestedFilename() const = 0;
189  virtual std::string GetContentDisposition() const = 0;
190  virtual std::string GetMimeType() const = 0;
191  virtual std::string GetOriginalMimeType() const = 0;
192  virtual std::string GetRemoteAddress() const = 0;
193  virtual bool HasUserGesture() const = 0;
194  virtual PageTransition GetTransitionType() const = 0;
195  virtual const std::string& GetLastModifiedTime() const = 0;
196  virtual const std::string& GetETag() const = 0;
197  virtual bool IsSavePackageDownload() const = 0;
198
199  //    Destination State accessors --------------------------------------------
200
201  // Full path to the downloaded or downloading file. This is the path to the
202  // physical file, if one exists. It should be considered a hint; changes to
203  // this value and renames of the file on disk are not atomic with each other.
204  // May be empty if the in-progress path hasn't been determined yet or if the
205  // download was interrupted.
206  //
207  // DO NOT USE THIS METHOD to access the target path of the DownloadItem. Use
208  // GetTargetFilePath() instead. While the download is in progress, the
209  // intermediate file named by GetFullPath() may be renamed or disappear
210  // completely on the FILE thread. The path may also be reset to empty when the
211  // download is interrupted.
212  virtual const base::FilePath& GetFullPath() const = 0;
213
214  // Target path of an in-progress download. We may be downloading to a
215  // temporary or intermediate file (specified by GetFullPath()); this is the
216  // name we will use once the download completes.
217  // May be empty if the target path hasn't yet been determined.
218  virtual const base::FilePath& GetTargetFilePath() const = 0;
219
220  // If the download forced a path rather than requesting name determination,
221  // return the path requested.
222  virtual const base::FilePath& GetForcedFilePath() const = 0;
223
224  // Returns the user-verified target file path for the download.
225  // This returns the same path as GetTargetFilePath() for safe downloads
226  // but does not for dangerous downloads until the name is verified.
227  virtual base::FilePath GetUserVerifiedFilePath() const = 0;
228
229  // Returns the file-name that should be reported to the user. If a display
230  // name has been explicitly set using SetDisplayName(), this function returns
231  // that display name. Otherwise returns the final target filename.
232  virtual base::FilePath GetFileNameToReportUser() const = 0;
233
234  virtual TargetDisposition GetTargetDisposition() const = 0;
235
236  // Final hash of completely downloaded file; not valid if
237  // GetState() != COMPLETED.
238  virtual const std::string& GetHash() const = 0;
239
240  // Intermediate hash state, for persisting partial downloads.
241  virtual const std::string& GetHashState() const = 0;
242
243  // True if the file associated with the download has been removed by
244  // external action.
245  virtual bool GetFileExternallyRemoved() const = 0;
246
247  // True if the file that will be written by the download is dangerous
248  // and we will require a call to DangerousDownloadValidated() to complete.
249  // False if the download is safe or that function has been called.
250  virtual bool IsDangerous() const = 0;
251
252  // Why |safety_state_| is not SAFE.
253  virtual DownloadDangerType GetDangerType() const = 0;
254
255  //    Progress State accessors -----------------------------------------------
256
257  // Simple calculation of the amount of time remaining to completion. Fills
258  // |*remaining| with the amount of time remaining if successful. Fails and
259  // returns false if we do not have the number of bytes or the speed so can
260  // not estimate.
261  virtual bool TimeRemaining(base::TimeDelta* remaining) const = 0;
262
263  // Simple speed estimate in bytes/s
264  virtual int64 CurrentSpeed() const = 0;
265
266  // Rough percent complete, -1 means we don't know (== we didn't receive a
267  // total size).
268  virtual int PercentComplete() const = 0;
269
270  // Returns true if this download has saved all of its data.
271  virtual bool AllDataSaved() const = 0;
272
273  virtual int64 GetTotalBytes() const = 0;
274  virtual int64 GetReceivedBytes() const = 0;
275  virtual base::Time GetStartTime() const = 0;
276  virtual base::Time GetEndTime() const = 0;
277
278  //    Open/Show State accessors ----------------------------------------------
279
280  // Returns true if it is OK to open a folder which this file is inside.
281  virtual bool CanShowInFolder() = 0;
282
283  // Returns true if it is OK to open the download.
284  virtual bool CanOpenDownload() = 0;
285
286  // Tests if a file type should be opened automatically.
287  virtual bool ShouldOpenFileBasedOnExtension() = 0;
288
289  // Returns true if the download will be auto-opened when complete.
290  virtual bool GetOpenWhenComplete() const = 0;
291
292  // Returns true if the download has been auto-opened by the system.
293  virtual bool GetAutoOpened() = 0;
294
295  // Returns true if the download has been opened.
296  virtual bool GetOpened() const = 0;
297
298  //    Misc State accessors ---------------------------------------------------
299
300  virtual BrowserContext* GetBrowserContext() const = 0;
301  virtual WebContents* GetWebContents() const = 0;
302
303  // External state transitions/setters ----------------------------------------
304  // TODO(rdsmith): These should all be removed; the download item should
305  // control its own state transitions.
306
307  // Called if a check of the download contents was performed and the results of
308  // the test are available. This should only be called after AllDataSaved() is
309  // true.
310  virtual void OnContentCheckCompleted(DownloadDangerType danger_type) = 0;
311
312  // Mark the download to be auto-opened when completed.
313  virtual void SetOpenWhenComplete(bool open) = 0;
314
315  // Mark the download as temporary (not visible in persisted store or
316  // SearchDownloads(), removed from main UI upon completion).
317  virtual void SetIsTemporary(bool temporary) = 0;
318
319  // Mark the download as having been opened (without actually opening it).
320  virtual void SetOpened(bool opened) = 0;
321
322  // Set a display name for the download that will be independent of the target
323  // filename. If |name| is not empty, then GetFileNameToReportUser() will
324  // return |name|. Has no effect on the final target filename.
325  virtual void SetDisplayName(const base::FilePath& name) = 0;
326
327  // Debug/testing -------------------------------------------------------------
328  virtual std::string DebugString(bool verbose) const = 0;
329};
330
331}  // namespace content
332
333#endif  // CONTENT_PUBLIC_BROWSER_DOWNLOAD_ITEM_H_
334