blob: 6e78fb6e2b215005bf024bb546b20616e7eba187 [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 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.
initial.commit09911bf2008-07-26 23:55:294//
5// The DownloadManager object manages the process of downloading, including
6// updates to the history system and providing the information for displaying
7// the downloads view in the Destinations tab. There is one DownloadManager per
8// active profile in Chrome.
9//
10// Each download is represented by a DownloadItem, and all DownloadItems
11// are owned by the DownloadManager which maintains a global list of all
12// downloads. DownloadItems are created when a user initiates a download,
13// and exist for the duration of the browser life time.
14//
15// Download observers:
16// Objects that are interested in notifications about new downloads, or progress
17// updates for a given download must implement one of the download observer
18// interfaces:
19// DownloadItem::Observer:
20// - allows observers to receive notifications about one download from start
21// to completion
22// DownloadManager::Observer:
23// - allows observers, primarily views, to be notified when changes to the
24// set of all downloads (such as new downloads, or deletes) occur
25// Use AddObserver() / RemoveObserver() on the appropriate download object to
26// receive state updates.
27//
28// Download state persistence:
29// The DownloadManager uses the history service for storing persistent
30// information about the state of all downloads. The history system maintains a
31// separate table for this called 'downloads'. At the point that the
32// DownloadManager is constructed, we query the history service for the state of
33// all persisted downloads.
34
[email protected]cdaa8652008-09-13 02:48:5935#ifndef CHROME_BROWSER_DOWNLOAD_DOWNLOAD_MANAGER_H__
36#define CHROME_BROWSER_DOWNLOAD_DOWNLOAD_MANAGER_H__
initial.commit09911bf2008-07-26 23:55:2937
38#include <string>
initial.commit09911bf2008-07-26 23:55:2939#include <map>
40#include <set>
41#include <vector>
42
43#include "base/basictypes.h"
[email protected]23144032008-09-08 20:51:3044#include "base/hash_tables.h"
initial.commit09911bf2008-07-26 23:55:2945#include "base/observer_list.h"
46#include "base/ref_counted.h"
47#include "chrome/browser/cancelable_request.h"
48#include "chrome/browser/history/download_types.h"
49#include "chrome/browser/history/history.h"
50#include "chrome/browser/shell_dialogs.h"
51#include "chrome/common/pref_member.h"
initial.commit09911bf2008-07-26 23:55:2952
53class DownloadFileManager;
54class DownloadItem;
55class DownloadItemView;
56class DownloadManager;
[email protected]46072d42008-07-28 14:49:3557class GURL;
initial.commit09911bf2008-07-26 23:55:2958class MessageLoop;
59class PrefService;
60class Profile;
61class ResourceDispatcherHost;
initial.commit09911bf2008-07-26 23:55:2962class URLRequestContext;
63class WebContents;
64
[email protected]ab820df2008-08-26 05:55:1065namespace base {
66class Thread;
67}
initial.commit09911bf2008-07-26 23:55:2968
69// DownloadItem ----------------------------------------------------------------
70
71// One DownloadItem per download. This is the model class that stores all the
72// state for a download. Multiple views, such as a tab's download shelf and the
73// Destination tab's download view, may refer to a given DownloadItem.
74class DownloadItem {
75 public:
76 enum DownloadState {
77 IN_PROGRESS,
78 COMPLETE,
79 CANCELLED,
80 REMOVING
81 };
82
[email protected]9ccbb372008-10-10 18:50:3283 enum SafetyState {
84 SAFE = 0,
85 DANGEROUS,
86 DANGEROUS_BUT_VALIDATED // Dangerous but the user confirmed the download.
87 };
88
initial.commit09911bf2008-07-26 23:55:2989 // Interface that observers of a particular download must implement in order
90 // to receive updates to the download's status.
91 class Observer {
92 public:
93 virtual void OnDownloadUpdated(DownloadItem* download) = 0;
94 };
95
96 // Constructing from persistent store:
97 DownloadItem(const DownloadCreateInfo& info);
98
99 // Constructing from user action:
100 DownloadItem(int32 download_id,
101 const std::wstring& path,
102 const std::wstring& url,
[email protected]9ccbb372008-10-10 18:50:32103 const std::wstring& original_name,
initial.commit09911bf2008-07-26 23:55:29104 const Time start_time,
105 int64 download_size,
106 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32107 int request_id,
108 bool is_dangerous);
initial.commit09911bf2008-07-26 23:55:29109
110 ~DownloadItem();
111
112 void Init(bool start_timer);
113
114 // Public API
115
116 void AddObserver(Observer* observer);
117 void RemoveObserver(Observer* observer);
118
119 // Notify our observers periodically
120 void UpdateObservers();
121
122 // Received a new chunk of data
123 void Update(int64 bytes_so_far);
124
125 // Cancel the download operation. We need to distinguish between cancels at
126 // exit (DownloadManager destructor) from user interface initiated cancels
127 // because at exit, the history system may not exist, and any updates to it
128 // require AddRef'ing the DownloadManager in the destructor which results in
129 // a DCHECK failure. Set 'update_history' to false when canceling from at
130 // exit to prevent this crash. This may result in a difference between the
131 // downloaded file's size on disk, and what the history system's last record
132 // of it is. At worst, we'll end up re-downloading a small portion of the file
133 // when resuming a download (assuming the server supports byte ranges).
134 void Cancel(bool update_history);
135
[email protected]9ccbb372008-10-10 18:50:32136 // Download operation completed.
initial.commit09911bf2008-07-26 23:55:29137 void Finished(int64 size);
138
[email protected]9ccbb372008-10-10 18:50:32139 // The user wants to remove the download from the views and history. If
140 // |delete_file| is true, the file is deleted on the disk.
141 void Remove(bool delete_file);
initial.commit09911bf2008-07-26 23:55:29142
143 // Start/stop sending periodic updates to our observers
144 void StartProgressTimer();
145 void StopProgressTimer();
146
147 // Simple calculation of the amount of time remaining to completion. Fills
148 // |*remaining| with the amount of time remaining if successful. Fails and
149 // returns false if we do not have the number of bytes or the speed so can
150 // not estimate.
151 bool TimeRemaining(TimeDelta* remaining) const;
152
153 // Simple speed estimate in bytes/s
154 int64 CurrentSpeed() const;
155
156 // Rough percent complete, -1 means we don't know (since we didn't receive a
157 // total size).
158 int PercentComplete() const;
159
160 // Update the download's path, the actual file is renamed on the download
161 // thread.
162 void Rename(const std::wstring& full_path);
163
164 // Allow the user to temporarily pause a download or resume a paused download.
165 void TogglePause();
166
167 // Accessors
168 DownloadState state() const { return state_; }
initial.commit09911bf2008-07-26 23:55:29169 std::wstring file_name() const { return file_name_; }
[email protected]9ccbb372008-10-10 18:50:32170 void set_file_name(const std::wstring& name) { file_name_ = name; }
171 std::wstring full_path() const { return full_path_; }
172 void set_full_path(const std::wstring& path) { full_path_ = path; }
initial.commit09911bf2008-07-26 23:55:29173 std::wstring url() const { return url_; }
174 int64 total_bytes() const { return total_bytes_; }
175 void set_total_bytes(int64 total_bytes) { total_bytes_ = total_bytes; }
176 int64 received_bytes() const { return received_bytes_; }
177 int32 id() const { return id_; }
178 Time start_time() const { return start_time_; }
179 void set_db_handle(int64 handle) { db_handle_ = handle; }
180 int64 db_handle() const { return db_handle_; }
181 DownloadManager* manager() const { return manager_; }
182 void set_manager(DownloadManager* manager) { manager_ = manager; }
183 bool is_paused() const { return is_paused_; }
184 void set_is_paused(bool pause) { is_paused_ = pause; }
185 bool open_when_complete() const { return open_when_complete_; }
186 void set_open_when_complete(bool open) { open_when_complete_ = open; }
187 int render_process_id() const { return render_process_id_; }
188 int request_id() const { return request_id_; }
[email protected]9ccbb372008-10-10 18:50:32189 SafetyState safety_state() const { return safety_state_; }
190 void set_safety_state(SafetyState safety_state) {
191 safety_state_ = safety_state;
192 }
193 std::wstring original_name() const { return original_name_; }
194 void set_original_name(const std::wstring& name) { original_name_ = name; }
195
196 // Returns the file-name that should be reported to the user, which is
197 // file_name_ for safe downloads and original_name_ for dangerous ones.
198 std::wstring GetFileName() const;
initial.commit09911bf2008-07-26 23:55:29199
200 private:
201 // Internal helper for maintaining consistent received and total sizes.
202 void UpdateSize(int64 size);
203
204 // Request ID assigned by the ResourceDispatcherHost.
205 int32 id_;
206
207 // Full path to the downloaded file
208 std::wstring full_path_;
209
210 // Short display version of the file
211 std::wstring file_name_;
212
213 // The URL from whence we came, for display
214 std::wstring url_;
215
216 // Total bytes expected
217 int64 total_bytes_;
218
219 // Current received bytes
220 int64 received_bytes_;
221
222 // Start time for calculating remaining time
223 uintptr_t start_tick_;
224
225 // The current state of this download
226 DownloadState state_;
227
228 // The views of this item in the download shelf and download tab
229 ObserverList<Observer> observers_;
230
231 // Time the download was started
232 Time start_time_;
233
234 // Our persistent store handle
235 int64 db_handle_;
236
[email protected]2d316662008-09-03 18:18:14237 // Timer for regularly updating our observers
238 base::RepeatingTimer<DownloadItem> update_timer_;
initial.commit09911bf2008-07-26 23:55:29239
240 // Our owning object
241 DownloadManager* manager_;
242
243 // In progress downloads may be paused by the user, we note it here
244 bool is_paused_;
245
246 // A flag for indicating if the download should be opened at completion.
247 bool open_when_complete_;
248
[email protected]9ccbb372008-10-10 18:50:32249 // Whether the download is considered potentially safe or dangerous
250 // (executable files are typically considered dangerous).
251 SafetyState safety_state_;
252
253 // Dangerous download are given temporary names until the user approves them.
254 // This stores their original name.
255 std::wstring original_name_;
256
initial.commit09911bf2008-07-26 23:55:29257 // For canceling or pausing requests.
258 int render_process_id_;
259 int request_id_;
260
261 DISALLOW_EVIL_CONSTRUCTORS(DownloadItem);
262};
263
264
265// DownloadManager -------------------------------------------------------------
266
267// Browser's download manager: manages all downloads and destination view.
268class DownloadManager : public base::RefCountedThreadSafe<DownloadManager>,
269 public SelectFileDialog::Listener {
270 // For testing.
271 friend class DownloadManagerTest;
272
273 public:
274 DownloadManager();
275 ~DownloadManager();
276
277 static void RegisterUserPrefs(PrefService* prefs);
278
279 // Interface to implement for observers that wish to be informed of changes
280 // to the DownloadManager's collection of downloads.
281 class Observer {
282 public:
283 // New or deleted download, observers should query us for the current set
284 // of downloads.
285 virtual void ModelChanged() = 0;
286
287 // A callback once the DownloadManager has retrieved the requested set of
288 // downloads. The DownloadManagerObserver must copy the vector, but does not
289 // own the individual DownloadItems, when this call is made.
290 virtual void SetDownloads(std::vector<DownloadItem*>& downloads) = 0;
291 };
292
293 // Public API
294
295 // Begin a search for all downloads matching 'search_text'. If 'search_text'
296 // is empty, return all known downloads. The results are returned in the
297 // 'SetDownloads' observer callback.
298 void GetDownloads(Observer* observer,
299 const std::wstring& search_text);
300
301 // Returns true if initialized properly.
302 bool Init(Profile* profile);
303
304 // Schedule a query of the history service to retrieve all downloads.
305 void QueryHistoryForDownloads();
306
307 // Notifications sent from the download thread to the UI thread
308 void StartDownload(DownloadCreateInfo* info);
309 void UpdateDownload(int32 download_id, int64 size);
310 void DownloadFinished(int32 download_id, int64 size);
311
312 // Helper method for cancelling the network request associated with a
313 // download.
314 static void CancelDownloadRequest(int render_process_id, int request_id);
315
316 // Called from a view when a user clicks a UI button or link.
317 void DownloadCancelled(int32 download_id);
318 void PauseDownload(int32 download_id, bool pause);
319 void RemoveDownload(int64 download_handle);
320
321 // Remove downloads after remove_begin (inclusive) and before remove_end
322 // (exclusive). You may pass in null Time values to do an unbounded delete
323 // in either direction.
324 int RemoveDownloadsBetween(const Time remove_begin, const Time remove_end);
325
326 // Remove downloads will delete all downloads that have a timestamp that is
327 // the same or more recent than |remove_begin|. The number of downloads
328 // deleted is returned back to the caller.
329 int RemoveDownloads(const Time remove_begin);
330
331 // Download the object at the URL. Used in cases such as "Save Link As..."
332 void DownloadUrl(const GURL& url,
333 const GURL& referrer,
334 WebContents* web_contents);
335
336 // Allow objects to observe the download creation process.
337 void AddObserver(Observer* observer);
338
339 // Remove a download observer from ourself.
340 void RemoveObserver(Observer* observer);
341
342 // Methods called on completion of a query sent to the history system.
343 void OnQueryDownloadEntriesComplete(
344 std::vector<DownloadCreateInfo>* entries);
345 void OnCreateDownloadEntryComplete(DownloadCreateInfo info, int64 db_handle);
346 void OnSearchComplete(HistoryService::Handle handle,
347 std::vector<int64>* results);
348
349 // Show or Open a download via the Windows shell.
350 void ShowDownloadInShell(const DownloadItem* download);
351 void OpenDownloadInShell(const DownloadItem* download, HWND parent_window);
352
353 // The number of in progress (including paused) downloads.
354 int in_progress_count() const {
355 return static_cast<int>(in_progress_.size());
356 }
357
358 std::wstring download_path() { return *download_path_; }
359
360 // Registers this file extension for automatic opening upon download
361 // completion if 'open' is true, or prevents the extension from automatic
362 // opening if 'open' is false.
363 void OpenFilesOfExtension(const std::wstring& extension, bool open);
364
365 // Tests if a file type should be opened automatically.
366 bool ShouldOpenFileExtension(const std::wstring& extension);
367
368 // Tests if we think the server means for this mime_type to be executable.
369 static bool IsExecutableMimeType(const std::string& mime_type);
370
371 // Tests if a file type is considered executable.
372 bool IsExecutable(const std::wstring& extension);
373
374 // Resets the automatic open preference.
375 void ResetAutoOpenFiles();
376
377 // Returns true if there are automatic handlers registered for any file
378 // types.
379 bool HasAutoOpenFileTypesRegistered() const;
380
381 // Overridden from SelectFileDialog::Listener:
382 virtual void FileSelected(const std::wstring& path, void* params);
383 virtual void FileSelectionCanceled(void* params);
384
[email protected]9ccbb372008-10-10 18:50:32385 // Deletes the specified path on the file thread.
386 void DeleteDownload(const std::wstring& path);
387
388 // Called when the user has validated the donwload of a dangerous file.
389 void DangerousDownloadValidated(DownloadItem* download);
390
initial.commit09911bf2008-07-26 23:55:29391 private:
392 // Shutdown the download manager. This call is needed only after Init.
393 void Shutdown();
394
395 // Called on the download thread to check whether the suggested file path
396 // exists. We don't check if the file exists on the UI thread to avoid UI
397 // stalls from interacting with the file system.
398 void CheckIfSuggestedPathExists(DownloadCreateInfo* info);
399
400 // Called on the UI thread once the DownloadManager has determined whether the
401 // suggested file path exists.
402 void OnPathExistenceAvailable(DownloadCreateInfo* info);
403
404 // Called back after a target path for the file to be downloaded to has been
405 // determined, either automatically based on the suggested file name, or by
406 // the user in a Save As dialog box.
407 void ContinueStartDownload(DownloadCreateInfo* info,
408 const std::wstring& target_path);
409
410 // Update the history service for a particular download.
411 void UpdateHistoryForDownload(DownloadItem* download);
412 void RemoveDownloadFromHistory(DownloadItem* download);
413 void RemoveDownloadsFromHistoryBetween(const Time remove_begin,
414 const Time remove_before);
415
416 // Inform the notification service of download starts and stops.
417 void NotifyAboutDownloadStart();
418 void NotifyAboutDownloadStop();
419
420 // Create an extension based on the file name and mime type.
421 void GenerateExtension(const std::wstring& file_name,
422 const std::string& mime_type,
423 std::wstring* generated_extension);
424
425 // Create a file name based on the response from the server.
426 void GenerateFilename(DownloadCreateInfo* info, std::wstring* generated_name);
427
428 // Persist the automatic opening preference.
429 void SaveAutoOpens();
430
431 // Runs the network cancel on the IO thread.
432 static void OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
433 int render_process_id,
434 int request_id);
435
436 // Runs the pause on the IO thread.
437 static void OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
438 int render_process_id,
439 int request_id,
440 bool pause);
441
[email protected]9ccbb372008-10-10 18:50:32442 // Performs the last steps required when a download has been completed.
443 // It is necessary to break down the flow when a download is finished as
444 // dangerous downloads are downloaded to temporary files that need to be
445 // renamed on the file thread first.
446 // Invoked on the UI thread.
447 void ContinueDownloadFinished(DownloadItem* download);
448
449 // Renames a finished dangerous download from its temporary file name to its
450 // real file name.
451 // Invoked on the file thread.
452 void ProceedWithFinishedDangerousDownload(int64 download_handle,
453 const std::wstring& path,
454 const std::wstring& original_name);
455
456 // Invoked on the UI thread when a dangerous downloaded file has been renamed.
457 void DangerousDownloadRenamed(int64 download_handle,
458 bool success,
459 const std::wstring& new_path);
460
461 // Checks whether a file represents a risk if downloaded.
462 bool IsDangerous(const std::wstring& file_name);
463
464 // Changes the paths and file name of the specified |download|, propagating
465 // the change to the history system.
466 void RenameDownload(DownloadItem* download, const std::wstring& new_path);
467
initial.commit09911bf2008-07-26 23:55:29468 // 'downloads_' is map of all downloads in this profile. The key is the handle
469 // returned by the history system, which is unique across sessions. This map
470 // owns all the DownloadItems once they have been created in the history
471 // system.
472 //
473 // 'in_progress_' is a map of all downloads that are in progress and that have
474 // not yet received a valid history handle. The key is the ID assigned by the
475 // ResourceDispatcherHost, which is unique for the current session. This map
476 // does not own the DownloadItems.
477 //
[email protected]9ccbb372008-10-10 18:50:32478 // 'dangerous_finished_' is a map of dangerous download that have finished
479 // but were not yet approved by the user. Similarly to in_progress_, the key
480 // is the ID assigned by the ResourceDispatcherHost and the map does not own
481 // the DownloadItems. It is used on shutdown to delete completed downloads
482 // that have not been approved.
483 //
initial.commit09911bf2008-07-26 23:55:29484 // When a download is created through a user action, the corresponding
485 // DownloadItem* is placed in 'in_progress_' and remains there until it has
486 // received a valid handle from the history system. Once it has a valid
487 // handle, the DownloadItem* is placed in the 'downloads_' map. When the
488 // download is complete, it is removed from 'in_progress_'. Downloads from
489 // past sessions read from a persisted state from the history system are
490 // placed directly into 'downloads_' since they have valid handles in the
491 // history system.
[email protected]23144032008-09-08 20:51:30492 typedef base::hash_map<int64, DownloadItem*> DownloadMap;
initial.commit09911bf2008-07-26 23:55:29493 DownloadMap downloads_;
494 DownloadMap in_progress_;
[email protected]9ccbb372008-10-10 18:50:32495 DownloadMap dangerous_finished_;
initial.commit09911bf2008-07-26 23:55:29496
497 // True if the download manager has been initialized and requires a shutdown.
498 bool shutdown_needed_;
499
500 // Observers that want to be notified of changes to the set of downloads.
501 ObserverList<Observer> observers_;
502
503 // The current active profile.
504 Profile* profile_;
505 scoped_refptr<URLRequestContext> request_context_;
506
507 // Used for history service request management.
508 CancelableRequestConsumerT<Observer*, 0> cancelable_consumer_;
509
510 // Non-owning pointer for handling file writing on the download_thread_.
511 DownloadFileManager* file_manager_;
512
513 // A pointer to the main UI loop.
514 MessageLoop* ui_loop_;
515
516 // A pointer to the file thread's loop. The file thread lives longer than
517 // the DownloadManager, so this is safe to cache.
518 MessageLoop* file_loop_;
519
520 // User preferences
521 BooleanPrefMember prompt_for_download_;
522 StringPrefMember download_path_;
523
524 // The user's last choice for download directory. This is only used when the
525 // user wants us to prompt for a save location for each download.
526 std::wstring last_download_path_;
527
528 // Set of file extensions to open at download completion.
529 std::set<std::wstring> auto_open_;
530
531 // Set of file extensions that are executables and shouldn't be auto opened.
532 std::set<std::wstring> exe_types_;
533
534 // Keep track of downloads that are completed before the user selects the
535 // destination, so that observers are appropriately notified of completion
536 // after this determination is made.
537 // The map is of download_id->remaining size (bytes), both of which are
538 // required when calling DownloadFinished.
539 typedef std::map<int32, int64> PendingFinishedMap;
540 PendingFinishedMap pending_finished_downloads_;
541
542 // The "Save As" dialog box used to ask the user where a file should be
543 // saved.
544 scoped_refptr<SelectFileDialog> select_file_dialog_;
545
546 DISALLOW_EVIL_CONSTRUCTORS(DownloadManager);
547};
548
549
[email protected]cdaa8652008-09-13 02:48:59550#endif // CHROME_BROWSER_DOWNLOAD_DOWNLOAD_MANAGER_H__