blob: 5a5649c5f9c298ec0c58f240839a2d2838155e4d [file] [log] [blame]
[email protected]d41355e6f2009-04-07 21:21:121// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// 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
[email protected]cdaa8652008-09-13 02:48:595#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
7#include "base/file_util.h"
8#include "base/logging.h"
9#include "base/message_loop.h"
10#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1411#include "base/rand_util.h"
initial.commit09911bf2008-07-26 23:55:2912#include "base/string_util.h"
[email protected]1b5044d2009-02-24 00:04:1413#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2914#include "base/task.h"
15#include "base/thread.h"
16#include "base/timer.h"
initial.commit09911bf2008-07-26 23:55:2917#include "chrome/browser/browser_list.h"
18#include "chrome/browser/browser_process.h"
[email protected]cdaa8652008-09-13 02:48:5919#include "chrome/browser/download/download_file.h"
[email protected]8c756ac2009-01-30 23:36:4120#include "chrome/browser/extensions/extension.h"
[email protected]8f783752009-04-01 23:33:4521#include "chrome/browser/extensions/extensions_service.h"
initial.commit09911bf2008-07-26 23:55:2922#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2623#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2524#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3225#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]f3ec7742009-01-15 00:59:1626#include "chrome/browser/tab_contents/tab_util.h"
27#include "chrome/browser/tab_contents/web_contents.h"
[email protected]8c756ac2009-01-30 23:36:4128#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2929#include "chrome/common/chrome_paths.h"
30#include "chrome/common/l10n_util.h"
[email protected]076700e62009-04-01 18:41:2331#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2932#include "chrome/common/pref_names.h"
33#include "chrome/common/pref_service.h"
34#include "chrome/common/stl_util-inl.h"
[email protected]46072d42008-07-28 14:49:3535#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4436#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2737#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2938#include "net/base/mime_util.h"
39#include "net/base/net_util.h"
40#include "net/url_request/url_request_context.h"
41
[email protected]b7f05882009-02-22 01:21:5642#if defined(OS_WIN)
43// TODO(port): some of these need porting.
44#include "base/registry.h"
45#include "base/win_util.h"
46#include "chrome/browser/download/download_util.h"
47#include "chrome/common/win_util.h"
48#endif
49
[email protected]0f44d3e2009-03-12 23:36:3050#if defined(OS_LINUX)
51#include <gtk/gtk.h>
52#endif
53
initial.commit09911bf2008-07-26 23:55:2954// Periodically update our observers.
55class DownloadItemUpdateTask : public Task {
56 public:
57 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
58 void Run() { if (item_) item_->UpdateObservers(); }
59
60 private:
61 DownloadItem* item_;
62};
63
64// Update frequency (milliseconds).
65static const int kUpdateTimeMs = 1000;
66
67// Our download table ID starts at 1, so we use 0 to represent a download that
68// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2269// database handles in incognito mode starting at -1 and progressively getting
70// more negative.
initial.commit09911bf2008-07-26 23:55:2971static const int kUninitializedHandle = 0;
72
[email protected]7a256ea2008-10-17 17:34:1673// Appends the passed the number between parenthesis the path before the
74// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4175static void AppendNumberToPath(FilePath* path, int number) {
76 file_util::InsertBeforeExtension(path,
77 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1678}
79
80// Attempts to find a number that can be appended to that path to make it
81// unique. If |path| does not exist, 0 is returned. If it fails to find such
82// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4183static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2984 const int kMaxAttempts = 100;
85
[email protected]7a256ea2008-10-17 17:34:1686 if (!file_util::PathExists(path))
87 return 0;
initial.commit09911bf2008-07-26 23:55:2988
[email protected]7ae7c2cb2009-01-06 23:31:4189 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2990 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4191 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1692 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2993
[email protected]7a256ea2008-10-17 17:34:1694 if (!file_util::PathExists(new_path))
95 return count;
initial.commit09911bf2008-07-26 23:55:2996 }
97
[email protected]7a256ea2008-10-17 17:34:1698 return -1;
initial.commit09911bf2008-07-26 23:55:2999}
100
[email protected]7ae7c2cb2009-01-06 23:31:41101static bool DownloadPathIsDangerous(const FilePath& download_path) {
102 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32103 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
104 NOTREACHED();
105 return false;
106 }
107 return (download_path == desktop_dir);
108}
109
initial.commit09911bf2008-07-26 23:55:29110// DownloadItem implementation -------------------------------------------------
111
112// Constructor for reading from the history service.
113DownloadItem::DownloadItem(const DownloadCreateInfo& info)
114 : id_(-1),
115 full_path_(info.path),
116 url_(info.url),
117 total_bytes_(info.total_bytes),
118 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56119 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29120 state_(static_cast<DownloadState>(info.state)),
121 start_time_(info.start_time),
122 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29123 manager_(NULL),
124 is_paused_(false),
125 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56126 safety_state_(SAFE),
127 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29128 render_process_id_(-1),
129 request_id_(-1) {
130 if (state_ == IN_PROGRESS)
131 state_ = CANCELLED;
132 Init(false /* don't start progress timer */);
133}
134
135// Constructor for DownloadItem created via user action in the main thread.
136DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41137 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16138 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32139 const GURL& url,
[email protected]7ae7c2cb2009-01-06 23:31:41140 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59141 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29142 int64 download_size,
143 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32144 int request_id,
145 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29146 : id_(download_id),
147 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16148 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29149 url_(url),
150 total_bytes_(download_size),
151 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56152 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29153 state_(IN_PROGRESS),
154 start_time_(start_time),
155 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29156 manager_(NULL),
157 is_paused_(false),
158 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56159 safety_state_(is_dangerous ? DANGEROUS : SAFE),
160 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29161 render_process_id_(render_process_id),
162 request_id_(request_id) {
163 Init(true /* start progress timer */);
164}
165
166void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41167 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29168 if (start_timer)
169 StartProgressTimer();
170}
171
172DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29173 state_ = REMOVING;
174 UpdateObservers();
175}
176
177void DownloadItem::AddObserver(Observer* observer) {
178 observers_.AddObserver(observer);
179}
180
181void DownloadItem::RemoveObserver(Observer* observer) {
182 observers_.RemoveObserver(observer);
183}
184
185void DownloadItem::UpdateObservers() {
186 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
187}
188
[email protected]45e3c122009-04-07 19:58:03189void DownloadItem::NotifyObserversDownloadOpened() {
190 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
191}
192
initial.commit09911bf2008-07-26 23:55:29193// If we've received more data than we were expecting (bad server info?), revert
194// to 'unknown size mode'.
195void DownloadItem::UpdateSize(int64 bytes_so_far) {
196 received_bytes_ = bytes_so_far;
197 if (received_bytes_ > total_bytes_)
198 total_bytes_ = 0;
199}
200
201// Updates from the download thread may have been posted while this download
202// was being cancelled in the UI thread, so we'll accept them unless we're
203// complete.
204void DownloadItem::Update(int64 bytes_so_far) {
205 if (state_ == COMPLETE) {
206 NOTREACHED();
207 return;
208 }
209 UpdateSize(bytes_so_far);
210 UpdateObservers();
211}
212
[email protected]6cade212008-12-03 00:32:22213// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29214void DownloadItem::Cancel(bool update_history) {
215 if (state_ != IN_PROGRESS) {
216 // Small downloads might be complete before this method has a chance to run.
217 return;
218 }
219 state_ = CANCELLED;
220 UpdateObservers();
221 StopProgressTimer();
222 if (update_history)
223 manager_->DownloadCancelled(id_);
224}
225
226void DownloadItem::Finished(int64 size) {
227 state_ = COMPLETE;
228 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40229 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29230 StopProgressTimer();
231}
232
[email protected]9ccbb372008-10-10 18:50:32233void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29234 Cancel(true);
235 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32236 if (delete_on_disk)
237 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29238 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22239 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29240}
241
242void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59243 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14244 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29245}
246
247void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14248 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29249}
250
[email protected]e93d2822009-01-30 05:59:59251bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29252 if (total_bytes_ <= 0)
253 return false; // We never received the content_length for this download.
254
255 int64 speed = CurrentSpeed();
256 if (speed == 0)
257 return false;
258
259 *remaining =
[email protected]e93d2822009-01-30 05:59:59260 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29261 return true;
262}
263
264int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56265 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
266 int64 diff_ms = diff.InMilliseconds();
267 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29268}
269
270int DownloadItem::PercentComplete() const {
271 int percent = -1;
272 if (total_bytes_ > 0)
273 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
274 return percent;
275}
276
[email protected]7ae7c2cb2009-01-06 23:31:41277void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29278 DCHECK(!full_path.empty());
279 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41280 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29281}
282
283void DownloadItem::TogglePause() {
284 DCHECK(state_ == IN_PROGRESS);
285 manager_->PauseDownload(id_, !is_paused_);
286 is_paused_ = !is_paused_;
287 UpdateObservers();
288}
289
[email protected]7ae7c2cb2009-01-06 23:31:41290FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32291 if (safety_state_ == DownloadItem::SAFE)
292 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16293 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41294 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16295 AppendNumberToPath(&name, path_uniquifier_);
296 return name;
297 }
[email protected]9ccbb372008-10-10 18:50:32298 return original_name_;
299}
300
initial.commit09911bf2008-07-26 23:55:29301// DownloadManager implementation ----------------------------------------------
302
303// static
304void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
305 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
306 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32307 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
308
309 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41310 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12311 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
312 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32313 NOTREACHED();
314 }
[email protected]b9636002009-03-04 00:05:25315 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
316 default_download_path);
[email protected]f052118e2008-09-05 02:25:32317
318 // If the download path is dangerous we forcefully reset it. But if we do
319 // so we set a flag to make sure we only do it once, to avoid fighting
320 // the user if he really wants it on an unsafe place such as the desktop.
321
322 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41323 FilePath current_download_dir = FilePath::FromWStringHack(
324 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32325 if (DownloadPathIsDangerous(current_download_dir)) {
326 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41327 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32328 }
329 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
330 }
initial.commit09911bf2008-07-26 23:55:29331}
332
333DownloadManager::DownloadManager()
334 : shutdown_needed_(false),
335 profile_(NULL),
336 file_manager_(NULL),
337 ui_loop_(MessageLoop::current()),
338 file_loop_(NULL) {
339}
340
341DownloadManager::~DownloadManager() {
342 if (shutdown_needed_)
343 Shutdown();
344}
345
346void DownloadManager::Shutdown() {
347 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
348
349 // Stop receiving download updates
350 file_manager_->RemoveDownloadManager(this);
351
352 // Stop making history service requests
353 cancelable_consumer_.CancelAllRequests();
354
355 // 'in_progress_' may contain DownloadItems that have not finished the start
356 // complete (from the history service) and thus aren't in downloads_.
357 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32358 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29359 for (; it != in_progress_.end(); ++it) {
360 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32361 if (download->safety_state() == DownloadItem::DANGEROUS) {
362 // Forget about any download that the user did not approve.
363 // Note that we cannot call download->Remove() this would invalidate our
364 // iterator.
365 to_remove.insert(download);
366 continue;
initial.commit09911bf2008-07-26 23:55:29367 }
[email protected]9ccbb372008-10-10 18:50:32368 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
369 download->Cancel(false);
370 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29371 if (download->db_handle() == kUninitializedHandle) {
372 // An invalid handle means that 'download' does not yet exist in
373 // 'downloads_', so we have to delete it here.
374 delete download;
375 }
376 }
377
[email protected]9ccbb372008-10-10 18:50:32378 // 'dangerous_finished_' contains all complete downloads that have not been
379 // approved. They should be removed.
380 it = dangerous_finished_.begin();
381 for (; it != dangerous_finished_.end(); ++it)
382 to_remove.insert(it->second);
383
384 // Remove the dangerous download that are not approved.
385 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
386 rm_it != to_remove.end(); ++rm_it) {
387 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32388 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32389 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32390 // Same as above, delete the download if it is not in 'downloads_' (as the
391 // Remove() call above won't have deleted it).
392 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32393 delete download;
394 }
395 to_remove.clear();
396
initial.commit09911bf2008-07-26 23:55:29397 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32398 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29399 STLDeleteValues(&downloads_);
400
401 file_manager_ = NULL;
402
403 // Save our file extensions to auto open.
404 SaveAutoOpens();
405
406 // Make sure the save as dialog doesn't notify us back if we're gone before
407 // it returns.
408 if (select_file_dialog_.get())
409 select_file_dialog_->ListenerDestroyed();
410
411 shutdown_needed_ = false;
412}
413
414// Issue a history query for downloads matching 'search_text'. If 'search_text'
415// is empty, return all downloads that we know about.
416void DownloadManager::GetDownloads(Observer* observer,
417 const std::wstring& search_text) {
418 DCHECK(observer);
419
420 // Return a empty list if we've not yet received the set of downloads from the
421 // history system (we'll update all observers once we get that list in
422 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
423 std::vector<DownloadItem*> download_copy;
424 if (downloads_.empty()) {
425 observer->SetDownloads(download_copy);
426 return;
427 }
428
429 // We already know all the downloads and there is no filter, so just return a
430 // copy to the observer.
431 if (search_text.empty()) {
432 download_copy.reserve(downloads_.size());
433 for (DownloadMap::iterator it = downloads_.begin();
434 it != downloads_.end(); ++it) {
435 download_copy.push_back(it->second);
436 }
437
438 // We retain ownership of the DownloadItems.
439 observer->SetDownloads(download_copy);
440 return;
441 }
442
443 // Issue a request to the history service for a list of downloads matching
444 // our search text.
445 HistoryService* hs =
446 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
447 if (hs) {
448 HistoryService::Handle h =
449 hs->SearchDownloads(search_text,
450 &cancelable_consumer_,
451 NewCallback(this,
452 &DownloadManager::OnSearchComplete));
453 cancelable_consumer_.SetClientData(hs, h, observer);
454 }
455}
456
457// Query the history service for information about all persisted downloads.
458bool DownloadManager::Init(Profile* profile) {
459 DCHECK(profile);
460 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
461 shutdown_needed_ = true;
462
463 profile_ = profile;
464 request_context_ = profile_->GetRequestContext();
465
466 // 'incognito mode' will have access to past downloads, but we won't store
467 // information about new downloads while in that mode.
468 QueryHistoryForDownloads();
469
470 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
471 if (!rdh) {
472 NOTREACHED();
473 return false;
474 }
475
476 file_manager_ = rdh->download_file_manager();
477 if (!file_manager_) {
478 NOTREACHED();
479 return false;
480 }
481
482 file_loop_ = g_browser_process->file_thread()->message_loop();
483 if (!file_loop_) {
484 NOTREACHED();
485 return false;
486 }
487
488 // Get our user preference state.
489 PrefService* prefs = profile_->GetPrefs();
490 DCHECK(prefs);
491 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
492
initial.commit09911bf2008-07-26 23:55:29493 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
494
[email protected]7ae7c2cb2009-01-06 23:31:41495 // This variable is needed to resolve which CreateDirectory we want to point
496 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
497 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
498 // get rid of |CreateDirectoryPtr|.
499 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14500 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41501 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
502 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29503
[email protected]2b2f8f72009-02-24 22:42:05504#if defined(OS_WIN)
505 // We use this on windows to determine possibly dangerous downloads.
506 download_util::InitializeExeTypes(&exe_types_);
507#endif
508
509 // We store any file extension that should be opened automatically at
510 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29511 std::wstring extensions_to_open =
512 prefs->GetString(prefs::kDownloadExtensionsToOpen);
513 std::vector<std::wstring> extensions;
514 SplitString(extensions_to_open, L':', &extensions);
515 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56516 if (!extensions[i].empty() && !IsExecutable(
517 FilePath::FromWStringHack(extensions[i]).value()))
518 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29519 }
520
521 return true;
522}
523
524void DownloadManager::QueryHistoryForDownloads() {
525 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
526 if (hs) {
527 hs->QueryDownloads(
528 &cancelable_consumer_,
529 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
530 }
531}
532
533// We have received a message from DownloadFileManager about a new download. We
534// create a download item and store it in our download map, and inform the
535// history system of a new download. Since this method can be called while the
536// history service thread is still reading the persistent state, we do not
537// insert the new DownloadItem into 'downloads_' or inform our observers at this
538// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
539// download creation as a callback from the history thread.
540void DownloadManager::StartDownload(DownloadCreateInfo* info) {
541 DCHECK(MessageLoop::current() == ui_loop_);
542 DCHECK(info);
543
[email protected]7d3851d82008-12-12 03:26:07544 // Freeze the user's preference for showing a Save As dialog. We're going to
545 // bounce around a bunch of threads and we don't want to worry about race
546 // conditions where the user changes this pref out from under us.
547 if (*prompt_for_download_)
548 info->save_as = true;
549
initial.commit09911bf2008-07-26 23:55:29550 // Determine the proper path for a download, by choosing either the default
551 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41552 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29553 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07554 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29555 info->suggested_path = last_download_path_;
556 else
[email protected]7ae7c2cb2009-01-06 23:31:41557 info->suggested_path = download_path();
558 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29559
[email protected]7d3851d82008-12-12 03:26:07560 if (!info->save_as) {
561 // Let's check if this download is dangerous, based on its name.
[email protected]7ae7c2cb2009-01-06 23:31:41562 info->is_dangerous = IsDangerous(info->suggested_path.BaseName());
[email protected]e9ebf3fc2008-10-17 22:06:58563 }
564
initial.commit09911bf2008-07-26 23:55:29565 // We need to move over to the download thread because we don't want to stat
566 // the suggested path on the UI thread.
567 file_loop_->PostTask(FROM_HERE,
568 NewRunnableMethod(this,
569 &DownloadManager::CheckIfSuggestedPathExists,
570 info));
571}
572
573void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
574 DCHECK(info);
575
576 // Check writability of the suggested path. If we can't write to it, default
577 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41578 FilePath dir = info->suggested_path.DirName();
579 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32580 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29581 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29582 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41583 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29584 }
585
[email protected]7a256ea2008-10-17 17:34:16586 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29587
[email protected]6cade212008-12-03 00:32:22588 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58589 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41590 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32591 // Create a temporary file to hold the file until the user approves its
592 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41593 FilePath::StringType file_name;
594 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32595 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41596 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32597 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41598 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07599 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41600 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32601 }
602 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16603 } else {
604 // We know the final path, build it if necessary.
605 if (info->path_uniquifier > 0) {
606 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
607 // Setting path_uniquifier to 0 to make sure we don't try to unique it
608 // later on.
609 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07610 } else if (info->path_uniquifier == -1) {
611 // We failed to find a unique path. We have to prompt the user.
612 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16613 }
[email protected]9ccbb372008-10-10 18:50:32614 }
615
[email protected]7d3851d82008-12-12 03:26:07616 if (!info->save_as) {
617 // Create an empty file at the suggested path so that we don't allocate the
618 // same "non-existant" path to multiple downloads.
619 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41620 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07621 }
622
initial.commit09911bf2008-07-26 23:55:29623 // Now we return to the UI thread.
624 ui_loop_->PostTask(FROM_HERE,
625 NewRunnableMethod(this,
626 &DownloadManager::OnPathExistenceAvailable,
627 info));
628}
629
630void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
initial.commit09911bf2008-07-26 23:55:29631 DCHECK(MessageLoop::current() == ui_loop_);
632 DCHECK(info);
633
[email protected]7d3851d82008-12-12 03:26:07634 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29635 // We must ask the user for the place to put the download.
636 if (!select_file_dialog_.get())
637 select_file_dialog_ = SelectFileDialog::Create(this);
638
[email protected]a3a1d142008-12-19 00:42:30639 WebContents* contents = tab_util::GetWebContentsByID(
initial.commit09911bf2008-07-26 23:55:29640 info->render_process_id, info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08641 SelectFileDialog::FileTypeInfo file_type_info;
642 file_type_info.extensions.resize(1);
643 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24644 if (!file_type_info.extensions[0][0].empty())
645 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08646 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23647 gfx::NativeWindow owning_window =
648 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29649 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34650 string16(),
651 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08652 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30653 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29654 } else {
655 // No prompting for download, just continue with the suggested name.
656 ContinueStartDownload(info, info->suggested_path);
657 }
initial.commit09911bf2008-07-26 23:55:29658}
659
660void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41661 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29662 scoped_ptr<DownloadCreateInfo> infop(info);
663 info->path = target_path;
664
665 DownloadItem* download = NULL;
666 DownloadMap::iterator it = in_progress_.find(info->download_id);
667 if (it == in_progress_.end()) {
668 download = new DownloadItem(info->download_id,
669 info->path,
[email protected]7a256ea2008-10-17 17:34:16670 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29671 info->url,
[email protected]9ccbb372008-10-10 18:50:32672 info->original_name,
initial.commit09911bf2008-07-26 23:55:29673 info->start_time,
674 info->total_bytes,
675 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32676 info->request_id,
677 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29678 download->set_manager(this);
679 in_progress_[info->download_id] = download;
680 } else {
681 NOTREACHED(); // Should not exist!
682 return;
683 }
684
[email protected]6b323782009-03-27 18:43:08685 // Called before DownloadFinished in order to avoid a race condition where we
686 // attempt to open a completed download before it has been renamed.
687 file_loop_->PostTask(FROM_HERE,
688 NewRunnableMethod(file_manager_,
689 &DownloadFileManager::OnFinalDownloadName,
690 download->id(),
[email protected]8f783752009-04-01 23:33:45691 target_path,
692 this));
[email protected]6b323782009-03-27 18:43:08693
initial.commit09911bf2008-07-26 23:55:29694 // If the download already completed by the time we reached this point, then
695 // notify observers that it did.
696 PendingFinishedMap::iterator pending_it =
697 pending_finished_downloads_.find(info->download_id);
698 if (pending_it != pending_finished_downloads_.end())
699 DownloadFinished(pending_it->first, pending_it->second);
700
701 download->Rename(target_path);
702
initial.commit09911bf2008-07-26 23:55:29703 if (profile_->IsOffTheRecord()) {
704 // Fake a db handle for incognito mode, since nothing is actually stored in
705 // the database in this mode. We have to make sure that these handles don't
706 // collide with normal db handles, so we use a negative value. Eventually,
707 // they could overlap, but you'd have to do enough downloading that your ISP
708 // would likely stab you in the neck first. YMMV.
709 static int64 fake_db_handle = kUninitializedHandle - 1;
710 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
711 } else {
712 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22713 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29714 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
715 if (hs) {
716 hs->CreateDownload(
717 *info, &cancelable_consumer_,
718 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
719 }
720 }
721}
722
723// Convenience function for updating the history service for a download.
724void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
725 DCHECK(download);
726
727 // Don't store info in the database if the download was initiated while in
728 // incognito mode or if it hasn't been initialized in our database table.
729 if (download->db_handle() <= kUninitializedHandle)
730 return;
731
[email protected]6cade212008-12-03 00:32:22732 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29733 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
734 if (hs) {
735 hs->UpdateDownload(download->received_bytes(),
736 download->state(),
737 download->db_handle());
738 }
739}
740
741void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
742 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22743 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29744 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
745 if (download->db_handle() > kUninitializedHandle && hs)
746 hs->RemoveDownload(download->db_handle());
747}
748
[email protected]e93d2822009-01-30 05:59:59749void DownloadManager::RemoveDownloadsFromHistoryBetween(
750 const base::Time remove_begin,
751 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22752 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29753 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
754 if (hs)
755 hs->RemoveDownloadsBetween(remove_begin, remove_end);
756}
757
758void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
759 DownloadMap::iterator it = in_progress_.find(download_id);
760 if (it != in_progress_.end()) {
761 DownloadItem* download = it->second;
762 download->Update(size);
763 UpdateHistoryForDownload(download);
764 }
765}
766
767void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
768 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32769 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29770 // The download is done, but the user hasn't selected a final location for
771 // it yet (the Save As dialog box is probably still showing), so just keep
772 // track of the fact that this download id is complete, when the
773 // DownloadItem is constructed later we'll notify its completion then.
774 PendingFinishedMap::iterator erase_it =
775 pending_finished_downloads_.find(download_id);
776 DCHECK(erase_it == pending_finished_downloads_.end());
777 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32778 return;
initial.commit09911bf2008-07-26 23:55:29779 }
[email protected]9ccbb372008-10-10 18:50:32780
781 // Remove the id from the list of pending ids.
782 PendingFinishedMap::iterator erase_it =
783 pending_finished_downloads_.find(download_id);
784 if (erase_it != pending_finished_downloads_.end())
785 pending_finished_downloads_.erase(erase_it);
786
787 DownloadItem* download = it->second;
788 download->Finished(size);
789
790 // Clean up will happen when the history system create callback runs if we
791 // don't have a valid db_handle yet.
792 if (download->db_handle() != kUninitializedHandle) {
793 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32794 UpdateHistoryForDownload(download);
795 }
796
797 // If this a dangerous download not yet validated by the user, don't do
798 // anything. When the user notifies us, it will trigger a call to
799 // ProceedWithFinishedDangerousDownload.
800 if (download->safety_state() == DownloadItem::DANGEROUS) {
801 dangerous_finished_[download_id] = download;
802 return;
803 }
804
805 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22806 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32807 // its final name before we can continue.
808 file_loop_->PostTask(FROM_HERE,
809 NewRunnableMethod(
810 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
811 download->db_handle(),
812 download->full_path(), download->original_name()));
813 return;
814 }
815 ContinueDownloadFinished(download);
816}
817
[email protected]8f783752009-04-01 23:33:45818void DownloadManager::DownloadRenamedToFinalName(int download_id,
819 const FilePath& full_path) {
820 FilePath::StringType extension = full_path.Extension();
821 // Drop the leading period.
822 if (extension.size() > 0)
823 extension = extension.substr(1);
824
825 if (extension == chrome::kExtensionFileExtension) {
826 OpenChromeExtension(full_path);
827 }
828}
829
[email protected]9ccbb372008-10-10 18:50:32830void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
831 // If this was a dangerous download, it has now been approved and must be
832 // removed from dangerous_finished_ so it does not get deleted on shutdown.
833 DownloadMap::iterator it = dangerous_finished_.find(download->id());
834 if (it != dangerous_finished_.end())
835 dangerous_finished_.erase(it);
836
837 // Notify our observers that we are complete (the call to Finished() set the
838 // state to complete but did not notify).
839 download->UpdateObservers();
840
841 // Open the download if the user or user prefs indicate it should be.
[email protected]2001fe82009-02-23 23:53:14842 FilePath::StringType extension = download->full_path().Extension();
843 // Drop the leading period.
844 if (extension.size() > 0)
845 extension = extension.substr(1);
[email protected]8f783752009-04-01 23:33:45846
847 // Handle chrome extensions explicitly and skip the shell execute.
848 if (extension == chrome::kExtensionFileExtension) {
849 // Skip the shell execute. This will be handled in
850 // DownloadRenamedToFinalName
851 return;
852 }
853
[email protected]9ccbb372008-10-10 18:50:32854 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
855 OpenDownloadInShell(download, NULL);
856}
857
858// Called on the file thread. Renames the downloaded file to its original name.
859void DownloadManager::ProceedWithFinishedDangerousDownload(
860 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41861 const FilePath& path,
862 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32863 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41864 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16865 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32866 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24867 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16868 // Make our name unique at this point, as if a dangerous file is downloading
869 // and a 2nd download is started for a file with the same name, they would
870 // have the same path. This is because we uniquify the name on download
871 // start, and at that time the first file does not exists yet, so the second
872 // file gets the same name.
873 uniquifier = GetUniquePathNumber(new_path);
874 if (uniquifier > 0)
875 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32876 success = file_util::Move(path, new_path);
877 } else {
878 NOTREACHED();
879 }
[email protected]6cade212008-12-03 00:32:22880
[email protected]9ccbb372008-10-10 18:50:32881 ui_loop_->PostTask(FROM_HERE,
882 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16883 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32884}
885
886// Call from the file thread when the finished dangerous download was renamed.
887void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
888 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41889 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16890 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32891 DownloadMap::iterator it = downloads_.find(download_handle);
892 if (it == downloads_.end()) {
893 NOTREACHED();
894 return;
895 }
896
897 DownloadItem* download = it->second;
898 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16899 if (success) {
900 // We need to update the path uniquifier so that the UI shows the right
901 // name when calling GetFileName().
902 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32903 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16904 }
[email protected]9ccbb372008-10-10 18:50:32905
906 // Continue the download finished sequence.
907 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29908}
909
910// static
911// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22912// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29913// reliably (crash on shutdown race condition).
914void DownloadManager::CancelDownloadRequest(int render_process_id,
915 int request_id) {
916 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10917 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29918 if (!io_thread || !rdh)
919 return;
920 io_thread->message_loop()->PostTask(FROM_HERE,
921 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
922 rdh,
923 render_process_id,
924 request_id));
925}
926
927// static
928void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
929 int render_process_id,
930 int request_id) {
931 rdh->CancelRequest(render_process_id, request_id, false);
932}
933
934void DownloadManager::DownloadCancelled(int32 download_id) {
935 DownloadMap::iterator it = in_progress_.find(download_id);
936 if (it == in_progress_.end())
937 return;
938 DownloadItem* download = it->second;
939
940 CancelDownloadRequest(download->render_process_id(), download->request_id());
941
942 // Clean up will happen when the history system create callback runs if we
943 // don't have a valid db_handle yet.
944 if (download->db_handle() != kUninitializedHandle) {
945 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:29946 UpdateHistoryForDownload(download);
947 }
948
949 // Tell the file manager to cancel the download.
950 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
951 file_loop_->PostTask(FROM_HERE,
952 NewRunnableMethod(file_manager_,
953 &DownloadFileManager::CancelDownload,
954 download->id()));
955}
956
957void DownloadManager::PauseDownload(int32 download_id, bool pause) {
958 DownloadMap::iterator it = in_progress_.find(download_id);
959 if (it != in_progress_.end()) {
960 DownloadItem* download = it->second;
961 if (pause == download->is_paused())
962 return;
963
964 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10965 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29966 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
967 if (!io_thread || !rdh)
968 return;
969
970 io_thread->message_loop()->PostTask(FROM_HERE,
971 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
972 rdh,
973 download->render_process_id(),
974 download->request_id(),
975 pause));
976 }
977}
978
979// static
980void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
981 int render_process_id,
982 int request_id,
983 bool pause) {
984 rdh->PauseRequest(render_process_id, request_id, pause);
985}
986
[email protected]7ae7c2cb2009-01-06 23:31:41987bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32988 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:14989 FilePath::StringType extension = file_name.Extension();
990 // Drop the leading period.
991 if (extension.size() > 0)
992 extension = extension.substr(1);
993 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:32994}
995
996void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41997 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32998 download->Rename(new_path);
999
1000 // Update the history.
1001
1002 // No update necessary if the download was initiated while in incognito mode.
1003 if (download->db_handle() <= kUninitializedHandle)
1004 return;
1005
[email protected]6cade212008-12-03 00:32:221006 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321007 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1008 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411009 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321010}
1011
initial.commit09911bf2008-07-26 23:55:291012void DownloadManager::RemoveDownload(int64 download_handle) {
1013 DownloadMap::iterator it = downloads_.find(download_handle);
1014 if (it == downloads_.end())
1015 return;
1016
1017 // Make history update.
1018 DownloadItem* download = it->second;
1019 RemoveDownloadFromHistory(download);
1020
1021 // Remove from our tables and delete.
1022 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321023 it = dangerous_finished_.find(download->id());
1024 if (it != dangerous_finished_.end())
1025 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291026
1027 // Tell observers to refresh their views.
1028 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361029
1030 delete download;
initial.commit09911bf2008-07-26 23:55:291031}
1032
[email protected]e93d2822009-01-30 05:59:591033int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1034 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291035 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1036
initial.commit09911bf2008-07-26 23:55:291037 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281038 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291039 while (it != downloads_.end()) {
1040 DownloadItem* download = it->second;
1041 DownloadItem::DownloadState state = download->state();
1042 if (download->start_time() >= remove_begin &&
1043 (remove_end.is_null() || download->start_time() < remove_end) &&
1044 (state == DownloadItem::COMPLETE ||
1045 state == DownloadItem::CANCELLED)) {
1046 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561047 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581048
1049 // Also remove it from any completed dangerous downloads.
1050 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1051 if (dit != dangerous_finished_.end())
1052 dangerous_finished_.erase(dit);
1053
[email protected]78b8fcc92009-03-31 17:36:281054 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291055
initial.commit09911bf2008-07-26 23:55:291056 continue;
1057 }
1058
1059 ++it;
1060 }
1061
1062 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281063 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291064 if (num_deleted > 0)
1065 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1066
[email protected]78b8fcc92009-03-31 17:36:281067 // Delete the download items after updating the observers.
1068 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1069 pending_deletes.clear();
1070
initial.commit09911bf2008-07-26 23:55:291071 return num_deleted;
1072}
1073
[email protected]e93d2822009-01-30 05:59:591074int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1075 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291076}
1077
[email protected]d41355e6f2009-04-07 21:21:121078int DownloadManager::RemoveAllDownloads() {
1079 // The null times make the date range unbounded.
1080 return RemoveDownloadsBetween(base::Time(), base::Time());
1081}
1082
initial.commit09911bf2008-07-26 23:55:291083// Initiate a download of a specific URL. We send the request to the
1084// ResourceDispatcherHost, and let it send us responses like a regular
1085// download.
1086void DownloadManager::DownloadUrl(const GURL& url,
1087 const GURL& referrer,
1088 WebContents* web_contents) {
1089 DCHECK(web_contents);
1090 file_manager_->DownloadUrl(url,
1091 referrer,
[email protected]4566f132009-03-12 01:55:131092 web_contents->process()->pid(),
initial.commit09911bf2008-07-26 23:55:291093 web_contents->render_view_host()->routing_id(),
1094 request_context_.get());
1095}
1096
[email protected]7ae7c2cb2009-01-06 23:31:411097void DownloadManager::GenerateExtension(
1098 const FilePath& file_name,
1099 const std::string& mime_type,
1100 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291101 // We're worried about three things here:
1102 //
1103 // 1) Security. Many sites let users upload content, such as buddy icons, to
1104 // their web sites. We want to mitigate the case where an attacker
1105 // supplies a malicious executable with an executable file extension but an
1106 // honest site serves the content with a benign content type, such as
1107 // image/jpeg.
1108 //
1109 // 2) Usability. If the site fails to provide a file extension, we want to
1110 // guess a reasonable file extension based on the content type.
1111 //
1112 // 3) Shell integration. Some file extensions automatically integrate with
1113 // the shell. We block these extensions to prevent a malicious web site
1114 // from integrating with the user's shell.
1115
[email protected]7ae7c2cb2009-01-06 23:31:411116 static const FilePath::CharType default_extension[] =
1117 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291118
1119 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411120 FilePath::StringType extension(
1121 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291122
[email protected]b7f05882009-02-22 01:21:561123#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291124 // Rename shell-integrated extensions.
1125 if (win_util::IsShellIntegratedExtension(extension))
1126 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561127#endif
initial.commit09911bf2008-07-26 23:55:291128
1129 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411130 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411131 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291132 if (mime_type == mime_type_from_extension) {
1133 // The hinted extension matches the mime type. It looks like a winner.
1134 generated_extension->swap(extension);
1135 return;
1136 }
1137
1138 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1139 // We want to be careful about executable extensions. The worry here is
1140 // that a trusted web site could be tricked into dropping an executable file
1141 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101142 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291143 // We couldn't find a good extension for this content type. Use a dummy
1144 // extension instead.
1145 extension.assign(default_extension);
1146 }
1147 }
1148
1149 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101150 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291151 } else {
[email protected]6cade212008-12-03 00:32:221152 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291153 // 1. New extension is not ".txt"
1154 // 2. New extension is not the same as the already existing extension.
1155 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411156 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291157 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1158 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371159 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1160 // servers, i.e. bug 5772.
[email protected]7ae7c2cb2009-01-06 23:31:411161 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101162 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171163 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411164 append_extension != extension &&
[email protected]e106457b2009-03-25 22:43:371165 !IsExecutable(append_extension) &&
1166 (append_extension != FILE_PATH_LITERAL("tar") ||
1167 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171168 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291169 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171170 }
initial.commit09911bf2008-07-26 23:55:291171 }
1172 }
1173
1174 generated_extension->swap(extension);
1175}
1176
1177void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411178 FilePath* generated_name) {
1179 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371180 net::GetSuggestedFilename(GURL(info->url),
1181 info->content_disposition,
[email protected]7ae7c2cb2009-01-06 23:31:411182 L"download"));
1183 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291184
[email protected]7ae7c2cb2009-01-06 23:31:411185 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291186}
1187
1188void DownloadManager::AddObserver(Observer* observer) {
1189 observers_.AddObserver(observer);
1190 observer->ModelChanged();
1191}
1192
1193void DownloadManager::RemoveObserver(Observer* observer) {
1194 observers_.RemoveObserver(observer);
1195}
1196
1197// Post Windows Shell operations to the Download thread, to avoid blocking the
1198// user interface.
1199void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1200 DCHECK(file_manager_);
1201 file_loop_->PostTask(FROM_HERE,
1202 NewRunnableMethod(file_manager_,
1203 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411204 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291205}
1206
[email protected]8f783752009-04-01 23:33:451207void DownloadManager::OpenDownload(const DownloadItem* download,
1208 gfx::NativeView parent_window) {
1209 FilePath::StringType extension = download->full_path().Extension();
1210 // Drop the leading period.
1211 if (extension.size() > 0)
1212 extension = extension.substr(1);
1213
1214 // Open Chrome extensions with ExtenstionsService. For everthing else do shell
1215 // execute.
1216 if (extension == chrome::kExtensionFileExtension) {
1217 OpenChromeExtension(download->full_path());
1218 } else {
1219 OpenDownloadInShell(download, parent_window);
1220 }
1221}
1222
1223void DownloadManager::OpenChromeExtension(const FilePath& full_path) {
[email protected]d81706b82009-04-03 20:28:441224 // Temporary: Ask the user if it's okay to install the extension. This should
1225 // be replaced with the actual extension installation UI when it is avaiable.
1226#if defined(OS_WIN)
1227 if (win_util::MessageBox(GetActiveWindow(),
1228 L"Are you sure you want to install this extension?\n\n"
1229 L"This is a temporary message and it will be removed when extensions UI "
1230 L"is finalized.",
1231 l10n_util::GetString(IDS_PRODUCT_NAME).c_str(), MB_OKCANCEL) == IDOK) {
1232 ExtensionsService* extensions_service = profile_->GetExtensionsService();
1233 extensions_service->InstallExtension(full_path);
1234 }
1235#else
1236 // TODO(port): Needs CreateChromeWindow.
[email protected]8f783752009-04-01 23:33:451237 ExtensionsService* extensions_service = profile_->GetExtensionsService();
1238 extensions_service->InstallExtension(full_path);
[email protected]d81706b82009-04-03 20:28:441239#endif
1240
[email protected]8f783752009-04-01 23:33:451241}
1242
initial.commit09911bf2008-07-26 23:55:291243void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591244 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291245 DCHECK(file_manager_);
1246 file_loop_->PostTask(FROM_HERE,
1247 NewRunnableMethod(file_manager_,
1248 &DownloadFileManager::OnOpenDownloadInShell,
1249 download->full_path(), download->url(), parent_window));
1250}
1251
[email protected]7ae7c2cb2009-01-06 23:31:411252void DownloadManager::OpenFilesOfExtension(
1253 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291254 if (open && !IsExecutable(extension))
1255 auto_open_.insert(extension);
1256 else
1257 auto_open_.erase(extension);
1258 SaveAutoOpens();
1259}
1260
[email protected]7ae7c2cb2009-01-06 23:31:411261bool DownloadManager::ShouldOpenFileExtension(
1262 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411263 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291264 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411265 (auto_open_.find(extension) != auto_open_.end() ||
1266 extension == chrome::kExtensionFileExtension))
1267 return true;
initial.commit09911bf2008-07-26 23:55:291268 return false;
1269}
1270
[email protected]7b73d992008-12-15 20:56:461271static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291272 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461273 "text/javascript",
1274 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241275 // Registry files can cause critical changes to the MS OS behavior.
1276 // Addition of this mimetype also addresses bug 7337.
1277 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391278 // Some sites use binary/octet-stream to mean application/octet-stream.
1279 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461280 "binary/octet-stream"
1281};
initial.commit09911bf2008-07-26 23:55:291282
[email protected]7b73d992008-12-15 20:56:461283static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291284 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461285 "application/*+xml",
1286 "application/xml"
1287};
initial.commit09911bf2008-07-26 23:55:291288
[email protected]7b73d992008-12-15 20:56:461289// static
1290bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411291 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461292 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1293 return true;
1294 }
[email protected]bae0ea12009-02-14 01:20:411295 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461296 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1297 return false;
1298 }
1299 // We consider only other application types to be executable.
1300 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291301}
1302
[email protected]7ae7c2cb2009-01-06 23:31:411303bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]64da0b932009-02-24 02:30:041304#if defined(OS_WIN)
1305 if (!IsStringASCII(extension))
1306 return false;
1307 std::string ascii_extension = WideToASCII(extension);
1308 StringToLowerASCII(&ascii_extension);
1309
1310 return exe_types_.find(ascii_extension) != exe_types_.end();
1311#elif defined(OS_POSIX)
1312 // TODO(port): we misght not want to call this function on other platforms.
1313 // Figure it out.
1314 NOTIMPLEMENTED();
1315 return false;
1316#endif
initial.commit09911bf2008-07-26 23:55:291317}
1318
1319void DownloadManager::ResetAutoOpenFiles() {
1320 auto_open_.clear();
1321 SaveAutoOpens();
1322}
1323
1324bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1325 return !auto_open_.empty();
1326}
1327
1328void DownloadManager::SaveAutoOpens() {
1329 PrefService* prefs = profile_->GetPrefs();
1330 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411331 FilePath::StringType extensions;
1332 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291333 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411334 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291335 }
1336 if (!extensions.empty())
1337 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561338
1339 std::wstring extensions_w;
1340#if defined(OS_WIN)
1341 extensions_w = extensions;
1342#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141343 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561344#endif
1345
1346 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291347 }
1348}
1349
[email protected]561abe62009-04-06 18:08:341350void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361351 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291352 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071353 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411354 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291355 ContinueStartDownload(info, path);
1356}
1357
1358void DownloadManager::FileSelectionCanceled(void* params) {
1359 // The user didn't pick a place to save the file, so need to cancel the
1360 // download that's already in progress to the temporary location.
1361 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1362 file_loop_->PostTask(FROM_HERE,
1363 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1364 info->download_id));
1365}
1366
[email protected]7ae7c2cb2009-01-06 23:31:411367void DownloadManager::DeleteDownload(const FilePath& path) {
1368 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1369 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321370}
1371
1372
1373void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1374 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1375 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1376 download->UpdateObservers();
1377
1378 // If the download is not complete, nothing to do. The required
1379 // post-processing will be performed when it does complete.
1380 if (download->state() != DownloadItem::COMPLETE)
1381 return;
1382
1383 file_loop_->PostTask(FROM_HERE,
1384 NewRunnableMethod(this,
1385 &DownloadManager::ProceedWithFinishedDangerousDownload,
1386 download->db_handle(), download->full_path(),
1387 download->original_name()));
1388}
1389
[email protected]763f946a2009-01-06 19:04:391390void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411391 FilePath* file_name) {
1392 // Make sure we get the right file extension
1393 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391394 GenerateExtension(*file_name, mime_type, &extension);
1395 file_util::ReplaceExtension(file_name, extension);
1396
[email protected]2b2f8f72009-02-24 22:42:051397#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391398 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411399 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391400 DCHECK(!leaf_name.empty());
1401 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411402 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1403 *file_name = file_name->DirName();
1404 if (file_name->value() == FilePath::kCurrentDirectory) {
1405 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391406 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411407 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391408 }
1409 }
[email protected]b7f05882009-02-22 01:21:561410#elif defined(OS_POSIX)
1411 NOTIMPLEMENTED();
1412#endif
[email protected]763f946a2009-01-06 19:04:391413}
1414
initial.commit09911bf2008-07-26 23:55:291415// Operations posted to us from the history service ----------------------------
1416
1417// The history service has retrieved all download entries. 'entries' contains
1418// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1419void DownloadManager::OnQueryDownloadEntriesComplete(
1420 std::vector<DownloadCreateInfo>* entries) {
1421 for (size_t i = 0; i < entries->size(); ++i) {
1422 DownloadItem* download = new DownloadItem(entries->at(i));
1423 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1424 downloads_[download->db_handle()] = download;
1425 download->set_manager(this);
1426 }
1427 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1428}
1429
initial.commit09911bf2008-07-26 23:55:291430// Once the new DownloadItem's creation info has been committed to the history
1431// service, we associate the DownloadItem with the db handle, update our
1432// 'downloads_' map and inform observers.
1433void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1434 int64 db_handle) {
1435 DownloadMap::iterator it = in_progress_.find(info.download_id);
1436 DCHECK(it != in_progress_.end());
1437
1438 DownloadItem* download = it->second;
1439 DCHECK(download->db_handle() == kUninitializedHandle);
1440 download->set_db_handle(db_handle);
1441
1442 // Insert into our full map.
1443 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1444 downloads_[download->db_handle()] = download;
1445
1446 // The 'contents' may no longer exist if the user closed the tab before we get
1447 // this start completion event. If it does, tell the origin WebContents to
1448 // display its download shelf.
1449 TabContents* contents =
[email protected]a3a1d142008-12-19 00:42:301450 tab_util::GetWebContentsByID(info.render_process_id, info.render_view_id);
initial.commit09911bf2008-07-26 23:55:291451
[email protected]b680ad22009-04-15 23:19:421452 // If the contents no longer exists, we start the download in the last active
1453 // browser. This is not ideal but better than fully hiding the download from
1454 // the user.
1455 if (!contents) {
initial.commit09911bf2008-07-26 23:55:291456 Browser* last_active = BrowserList::GetLastActive();
1457 if (last_active)
1458 contents = last_active->GetSelectedTabContents();
1459 }
1460
1461 if (contents)
1462 contents->OnStartDownload(download);
1463
1464 // Inform interested objects about the new download.
1465 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
initial.commit09911bf2008-07-26 23:55:291466
1467 // If this download has been completed before we've received the db handle,
1468 // post one final message to the history service so that it can be properly
1469 // in sync with the DownloadItem's completion status, and also inform any
1470 // observers so that they get more than just the start notification.
1471 if (download->state() != DownloadItem::IN_PROGRESS) {
1472 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291473 UpdateHistoryForDownload(download);
1474 download->UpdateObservers();
1475 }
1476}
1477
1478// Called when the history service has retrieved the list of downloads that
1479// match the search text.
1480void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1481 std::vector<int64>* results) {
1482 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1483 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1484 if (!requestor)
1485 return;
1486
1487 std::vector<DownloadItem*> searched_downloads;
1488 for (std::vector<int64>::iterator it = results->begin();
1489 it != results->end(); ++it) {
1490 DownloadMap::iterator dit = downloads_.find(*it);
1491 if (dit != downloads_.end())
1492 searched_downloads.push_back(dit->second);
1493 }
1494
1495 requestor->SetDownloads(searched_downloads);
1496}
[email protected]905a08d2008-11-19 07:24:121497
[email protected]6cade212008-12-03 00:32:221498// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121499void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411500 last_download_path_ = FilePath();
[email protected]905a08d2008-11-19 07:24:121501}