blob: 34fe0cf9440adb6aeb8f63fbbd1e3429e9f46693 [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
[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"
31#include "chrome/common/notification_service.h"
[email protected]076700e62009-04-01 18:41:2332#include "chrome/common/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2933#include "chrome/common/pref_names.h"
34#include "chrome/common/pref_service.h"
35#include "chrome/common/stl_util-inl.h"
[email protected]46072d42008-07-28 14:49:3536#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4437#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2738#include "grit/generated_resources.h"
initial.commit09911bf2008-07-26 23:55:2939#include "net/base/mime_util.h"
40#include "net/base/net_util.h"
41#include "net/url_request/url_request_context.h"
42
[email protected]b7f05882009-02-22 01:21:5643#if defined(OS_WIN)
44// TODO(port): some of these need porting.
45#include "base/registry.h"
46#include "base/win_util.h"
47#include "chrome/browser/download/download_util.h"
48#include "chrome/common/win_util.h"
49#endif
50
[email protected]0f44d3e2009-03-12 23:36:3051#if defined(OS_LINUX)
52#include <gtk/gtk.h>
53#endif
54
initial.commit09911bf2008-07-26 23:55:2955// Periodically update our observers.
56class DownloadItemUpdateTask : public Task {
57 public:
58 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
59 void Run() { if (item_) item_->UpdateObservers(); }
60
61 private:
62 DownloadItem* item_;
63};
64
65// Update frequency (milliseconds).
66static const int kUpdateTimeMs = 1000;
67
68// Our download table ID starts at 1, so we use 0 to represent a download that
69// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2270// database handles in incognito mode starting at -1 and progressively getting
71// more negative.
initial.commit09911bf2008-07-26 23:55:2972static const int kUninitializedHandle = 0;
73
[email protected]7a256ea2008-10-17 17:34:1674// Appends the passed the number between parenthesis the path before the
75// extension.
[email protected]7ae7c2cb2009-01-06 23:31:4176static void AppendNumberToPath(FilePath* path, int number) {
77 file_util::InsertBeforeExtension(path,
78 StringPrintf(FILE_PATH_LITERAL(" (%d)"), number));
[email protected]7a256ea2008-10-17 17:34:1679}
80
81// Attempts to find a number that can be appended to that path to make it
82// unique. If |path| does not exist, 0 is returned. If it fails to find such
83// a number, -1 is returned.
[email protected]7ae7c2cb2009-01-06 23:31:4184static int GetUniquePathNumber(const FilePath& path) {
initial.commit09911bf2008-07-26 23:55:2985 const int kMaxAttempts = 100;
86
[email protected]7a256ea2008-10-17 17:34:1687 if (!file_util::PathExists(path))
88 return 0;
initial.commit09911bf2008-07-26 23:55:2989
[email protected]7ae7c2cb2009-01-06 23:31:4190 FilePath new_path;
initial.commit09911bf2008-07-26 23:55:2991 for (int count = 1; count <= kMaxAttempts; ++count) {
[email protected]7ae7c2cb2009-01-06 23:31:4192 new_path = FilePath(path);
[email protected]7a256ea2008-10-17 17:34:1693 AppendNumberToPath(&new_path, count);
initial.commit09911bf2008-07-26 23:55:2994
[email protected]7a256ea2008-10-17 17:34:1695 if (!file_util::PathExists(new_path))
96 return count;
initial.commit09911bf2008-07-26 23:55:2997 }
98
[email protected]7a256ea2008-10-17 17:34:1699 return -1;
initial.commit09911bf2008-07-26 23:55:29100}
101
[email protected]7ae7c2cb2009-01-06 23:31:41102static bool DownloadPathIsDangerous(const FilePath& download_path) {
103 FilePath desktop_dir;
[email protected]f052118e2008-09-05 02:25:32104 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
105 NOTREACHED();
106 return false;
107 }
108 return (download_path == desktop_dir);
109}
110
initial.commit09911bf2008-07-26 23:55:29111// DownloadItem implementation -------------------------------------------------
112
113// Constructor for reading from the history service.
114DownloadItem::DownloadItem(const DownloadCreateInfo& info)
115 : id_(-1),
116 full_path_(info.path),
117 url_(info.url),
118 total_bytes_(info.total_bytes),
119 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56120 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29121 state_(static_cast<DownloadState>(info.state)),
122 start_time_(info.start_time),
123 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29124 manager_(NULL),
125 is_paused_(false),
126 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56127 safety_state_(SAFE),
128 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29129 render_process_id_(-1),
130 request_id_(-1) {
131 if (state_ == IN_PROGRESS)
132 state_ = CANCELLED;
133 Init(false /* don't start progress timer */);
134}
135
136// Constructor for DownloadItem created via user action in the main thread.
137DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41138 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16139 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32140 const GURL& url,
[email protected]7ae7c2cb2009-01-06 23:31:41141 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59142 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29143 int64 download_size,
144 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32145 int request_id,
146 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29147 : id_(download_id),
148 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16149 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29150 url_(url),
151 total_bytes_(download_size),
152 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56153 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29154 state_(IN_PROGRESS),
155 start_time_(start_time),
156 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29157 manager_(NULL),
158 is_paused_(false),
159 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56160 safety_state_(is_dangerous ? DANGEROUS : SAFE),
161 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29162 render_process_id_(render_process_id),
163 request_id_(request_id) {
164 Init(true /* start progress timer */);
165}
166
167void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41168 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29169 if (start_timer)
170 StartProgressTimer();
171}
172
173DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29174 state_ = REMOVING;
175 UpdateObservers();
176}
177
178void DownloadItem::AddObserver(Observer* observer) {
179 observers_.AddObserver(observer);
180}
181
182void DownloadItem::RemoveObserver(Observer* observer) {
183 observers_.RemoveObserver(observer);
184}
185
186void DownloadItem::UpdateObservers() {
187 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
188}
189
190// If we've received more data than we were expecting (bad server info?), revert
191// to 'unknown size mode'.
192void DownloadItem::UpdateSize(int64 bytes_so_far) {
193 received_bytes_ = bytes_so_far;
194 if (received_bytes_ > total_bytes_)
195 total_bytes_ = 0;
196}
197
198// Updates from the download thread may have been posted while this download
199// was being cancelled in the UI thread, so we'll accept them unless we're
200// complete.
201void DownloadItem::Update(int64 bytes_so_far) {
202 if (state_ == COMPLETE) {
203 NOTREACHED();
204 return;
205 }
206 UpdateSize(bytes_so_far);
207 UpdateObservers();
208}
209
[email protected]6cade212008-12-03 00:32:22210// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29211void DownloadItem::Cancel(bool update_history) {
212 if (state_ != IN_PROGRESS) {
213 // Small downloads might be complete before this method has a chance to run.
214 return;
215 }
216 state_ = CANCELLED;
217 UpdateObservers();
218 StopProgressTimer();
219 if (update_history)
220 manager_->DownloadCancelled(id_);
221}
222
223void DownloadItem::Finished(int64 size) {
224 state_ = COMPLETE;
225 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40226 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29227 StopProgressTimer();
228}
229
[email protected]9ccbb372008-10-10 18:50:32230void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29231 Cancel(true);
232 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32233 if (delete_on_disk)
234 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29235 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22236 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29237}
238
239void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59240 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14241 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29242}
243
244void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14245 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29246}
247
[email protected]e93d2822009-01-30 05:59:59248bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29249 if (total_bytes_ <= 0)
250 return false; // We never received the content_length for this download.
251
252 int64 speed = CurrentSpeed();
253 if (speed == 0)
254 return false;
255
256 *remaining =
[email protected]e93d2822009-01-30 05:59:59257 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29258 return true;
259}
260
261int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56262 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
263 int64 diff_ms = diff.InMilliseconds();
264 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29265}
266
267int DownloadItem::PercentComplete() const {
268 int percent = -1;
269 if (total_bytes_ > 0)
270 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
271 return percent;
272}
273
[email protected]7ae7c2cb2009-01-06 23:31:41274void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29275 DCHECK(!full_path.empty());
276 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41277 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29278}
279
280void DownloadItem::TogglePause() {
281 DCHECK(state_ == IN_PROGRESS);
282 manager_->PauseDownload(id_, !is_paused_);
283 is_paused_ = !is_paused_;
284 UpdateObservers();
285}
286
[email protected]7ae7c2cb2009-01-06 23:31:41287FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32288 if (safety_state_ == DownloadItem::SAFE)
289 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16290 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41291 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16292 AppendNumberToPath(&name, path_uniquifier_);
293 return name;
294 }
[email protected]9ccbb372008-10-10 18:50:32295 return original_name_;
296}
297
initial.commit09911bf2008-07-26 23:55:29298// DownloadManager implementation ----------------------------------------------
299
300// static
301void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
302 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
303 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32304 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
305
306 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41307 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12308 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
309 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32310 NOTREACHED();
311 }
[email protected]b9636002009-03-04 00:05:25312 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
313 default_download_path);
[email protected]f052118e2008-09-05 02:25:32314
315 // If the download path is dangerous we forcefully reset it. But if we do
316 // so we set a flag to make sure we only do it once, to avoid fighting
317 // the user if he really wants it on an unsafe place such as the desktop.
318
319 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41320 FilePath current_download_dir = FilePath::FromWStringHack(
321 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32322 if (DownloadPathIsDangerous(current_download_dir)) {
323 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41324 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32325 }
326 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
327 }
initial.commit09911bf2008-07-26 23:55:29328}
329
330DownloadManager::DownloadManager()
331 : shutdown_needed_(false),
332 profile_(NULL),
333 file_manager_(NULL),
334 ui_loop_(MessageLoop::current()),
335 file_loop_(NULL) {
336}
337
338DownloadManager::~DownloadManager() {
339 if (shutdown_needed_)
340 Shutdown();
341}
342
343void DownloadManager::Shutdown() {
344 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
345
346 // Stop receiving download updates
347 file_manager_->RemoveDownloadManager(this);
348
349 // Stop making history service requests
350 cancelable_consumer_.CancelAllRequests();
351
352 // 'in_progress_' may contain DownloadItems that have not finished the start
353 // complete (from the history service) and thus aren't in downloads_.
354 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32355 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29356 for (; it != in_progress_.end(); ++it) {
357 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32358 if (download->safety_state() == DownloadItem::DANGEROUS) {
359 // Forget about any download that the user did not approve.
360 // Note that we cannot call download->Remove() this would invalidate our
361 // iterator.
362 to_remove.insert(download);
363 continue;
initial.commit09911bf2008-07-26 23:55:29364 }
[email protected]9ccbb372008-10-10 18:50:32365 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
366 download->Cancel(false);
367 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29368 if (download->db_handle() == kUninitializedHandle) {
369 // An invalid handle means that 'download' does not yet exist in
370 // 'downloads_', so we have to delete it here.
371 delete download;
372 }
373 }
374
[email protected]9ccbb372008-10-10 18:50:32375 // 'dangerous_finished_' contains all complete downloads that have not been
376 // approved. They should be removed.
377 it = dangerous_finished_.begin();
378 for (; it != dangerous_finished_.end(); ++it)
379 to_remove.insert(it->second);
380
381 // Remove the dangerous download that are not approved.
382 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
383 rm_it != to_remove.end(); ++rm_it) {
384 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32385 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32386 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32387 // Same as above, delete the download if it is not in 'downloads_' (as the
388 // Remove() call above won't have deleted it).
389 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32390 delete download;
391 }
392 to_remove.clear();
393
initial.commit09911bf2008-07-26 23:55:29394 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32395 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29396 STLDeleteValues(&downloads_);
397
398 file_manager_ = NULL;
399
400 // Save our file extensions to auto open.
401 SaveAutoOpens();
402
403 // Make sure the save as dialog doesn't notify us back if we're gone before
404 // it returns.
405 if (select_file_dialog_.get())
406 select_file_dialog_->ListenerDestroyed();
407
408 shutdown_needed_ = false;
409}
410
411// Issue a history query for downloads matching 'search_text'. If 'search_text'
412// is empty, return all downloads that we know about.
413void DownloadManager::GetDownloads(Observer* observer,
414 const std::wstring& search_text) {
415 DCHECK(observer);
416
417 // Return a empty list if we've not yet received the set of downloads from the
418 // history system (we'll update all observers once we get that list in
419 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
420 std::vector<DownloadItem*> download_copy;
421 if (downloads_.empty()) {
422 observer->SetDownloads(download_copy);
423 return;
424 }
425
426 // We already know all the downloads and there is no filter, so just return a
427 // copy to the observer.
428 if (search_text.empty()) {
429 download_copy.reserve(downloads_.size());
430 for (DownloadMap::iterator it = downloads_.begin();
431 it != downloads_.end(); ++it) {
432 download_copy.push_back(it->second);
433 }
434
435 // We retain ownership of the DownloadItems.
436 observer->SetDownloads(download_copy);
437 return;
438 }
439
440 // Issue a request to the history service for a list of downloads matching
441 // our search text.
442 HistoryService* hs =
443 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
444 if (hs) {
445 HistoryService::Handle h =
446 hs->SearchDownloads(search_text,
447 &cancelable_consumer_,
448 NewCallback(this,
449 &DownloadManager::OnSearchComplete));
450 cancelable_consumer_.SetClientData(hs, h, observer);
451 }
452}
453
454// Query the history service for information about all persisted downloads.
455bool DownloadManager::Init(Profile* profile) {
456 DCHECK(profile);
457 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
458 shutdown_needed_ = true;
459
460 profile_ = profile;
461 request_context_ = profile_->GetRequestContext();
462
463 // 'incognito mode' will have access to past downloads, but we won't store
464 // information about new downloads while in that mode.
465 QueryHistoryForDownloads();
466
467 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
468 if (!rdh) {
469 NOTREACHED();
470 return false;
471 }
472
473 file_manager_ = rdh->download_file_manager();
474 if (!file_manager_) {
475 NOTREACHED();
476 return false;
477 }
478
479 file_loop_ = g_browser_process->file_thread()->message_loop();
480 if (!file_loop_) {
481 NOTREACHED();
482 return false;
483 }
484
485 // Get our user preference state.
486 PrefService* prefs = profile_->GetPrefs();
487 DCHECK(prefs);
488 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
489
initial.commit09911bf2008-07-26 23:55:29490 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
491
[email protected]7ae7c2cb2009-01-06 23:31:41492 // This variable is needed to resolve which CreateDirectory we want to point
493 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
494 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
495 // get rid of |CreateDirectoryPtr|.
496 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14497 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41498 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
499 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29500
[email protected]2b2f8f72009-02-24 22:42:05501#if defined(OS_WIN)
502 // We use this on windows to determine possibly dangerous downloads.
503 download_util::InitializeExeTypes(&exe_types_);
504#endif
505
506 // We store any file extension that should be opened automatically at
507 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29508 std::wstring extensions_to_open =
509 prefs->GetString(prefs::kDownloadExtensionsToOpen);
510 std::vector<std::wstring> extensions;
511 SplitString(extensions_to_open, L':', &extensions);
512 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56513 if (!extensions[i].empty() && !IsExecutable(
514 FilePath::FromWStringHack(extensions[i]).value()))
515 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29516 }
517
518 return true;
519}
520
521void DownloadManager::QueryHistoryForDownloads() {
522 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
523 if (hs) {
524 hs->QueryDownloads(
525 &cancelable_consumer_,
526 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
527 }
528}
529
530// We have received a message from DownloadFileManager about a new download. We
531// create a download item and store it in our download map, and inform the
532// history system of a new download. Since this method can be called while the
533// history service thread is still reading the persistent state, we do not
534// insert the new DownloadItem into 'downloads_' or inform our observers at this
535// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
536// download creation as a callback from the history thread.
537void DownloadManager::StartDownload(DownloadCreateInfo* info) {
538 DCHECK(MessageLoop::current() == ui_loop_);
539 DCHECK(info);
540
[email protected]7d3851d82008-12-12 03:26:07541 // Freeze the user's preference for showing a Save As dialog. We're going to
542 // bounce around a bunch of threads and we don't want to worry about race
543 // conditions where the user changes this pref out from under us.
544 if (*prompt_for_download_)
545 info->save_as = true;
546
initial.commit09911bf2008-07-26 23:55:29547 // Determine the proper path for a download, by choosing either the default
548 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41549 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29550 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07551 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29552 info->suggested_path = last_download_path_;
553 else
[email protected]7ae7c2cb2009-01-06 23:31:41554 info->suggested_path = download_path();
555 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29556
[email protected]7d3851d82008-12-12 03:26:07557 if (!info->save_as) {
558 // Let's check if this download is dangerous, based on its name.
[email protected]7ae7c2cb2009-01-06 23:31:41559 info->is_dangerous = IsDangerous(info->suggested_path.BaseName());
[email protected]e9ebf3fc2008-10-17 22:06:58560 }
561
initial.commit09911bf2008-07-26 23:55:29562 // We need to move over to the download thread because we don't want to stat
563 // the suggested path on the UI thread.
564 file_loop_->PostTask(FROM_HERE,
565 NewRunnableMethod(this,
566 &DownloadManager::CheckIfSuggestedPathExists,
567 info));
568}
569
570void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
571 DCHECK(info);
572
573 // Check writability of the suggested path. If we can't write to it, default
574 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41575 FilePath dir = info->suggested_path.DirName();
576 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32577 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29578 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29579 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41580 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29581 }
582
[email protected]7a256ea2008-10-17 17:34:16583 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29584
[email protected]6cade212008-12-03 00:32:22585 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58586 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41587 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32588 // Create a temporary file to hold the file until the user approves its
589 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41590 FilePath::StringType file_name;
591 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32592 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41593 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32594 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41595 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07596 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41597 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32598 }
599 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16600 } else {
601 // We know the final path, build it if necessary.
602 if (info->path_uniquifier > 0) {
603 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
604 // Setting path_uniquifier to 0 to make sure we don't try to unique it
605 // later on.
606 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07607 } else if (info->path_uniquifier == -1) {
608 // We failed to find a unique path. We have to prompt the user.
609 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16610 }
[email protected]9ccbb372008-10-10 18:50:32611 }
612
[email protected]7d3851d82008-12-12 03:26:07613 if (!info->save_as) {
614 // Create an empty file at the suggested path so that we don't allocate the
615 // same "non-existant" path to multiple downloads.
616 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41617 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07618 }
619
initial.commit09911bf2008-07-26 23:55:29620 // Now we return to the UI thread.
621 ui_loop_->PostTask(FROM_HERE,
622 NewRunnableMethod(this,
623 &DownloadManager::OnPathExistenceAvailable,
624 info));
625}
626
627void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]0f44d3e2009-03-12 23:36:30628#if defined(OS_WIN) || defined(OS_LINUX)
initial.commit09911bf2008-07-26 23:55:29629 DCHECK(MessageLoop::current() == ui_loop_);
630 DCHECK(info);
631
[email protected]7d3851d82008-12-12 03:26:07632 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29633 // We must ask the user for the place to put the download.
634 if (!select_file_dialog_.get())
635 select_file_dialog_ = SelectFileDialog::Create(this);
636
[email protected]a3a1d142008-12-19 00:42:30637 WebContents* contents = tab_util::GetWebContentsByID(
initial.commit09911bf2008-07-26 23:55:29638 info->render_process_id, info->render_view_id);
[email protected]0f44d3e2009-03-12 23:36:30639#if defined(OS_WIN)
[email protected]7ae7c2cb2009-01-06 23:31:41640 std::wstring filter =
641 win_util::GetFileFilterFromPath(info->suggested_path.value());
[email protected]0f44d3e2009-03-12 23:36:30642#elif defined(OS_LINUX)
643 std::wstring filter;
[email protected]0f44d3e2009-03-12 23:36:30644#endif
[email protected]076700e62009-04-01 18:41:23645 gfx::NativeWindow owning_window =
646 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29647 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34648 string16(),
649 info->suggested_path,
650 filter, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30651 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29652 } else {
653 // No prompting for download, just continue with the suggested name.
654 ContinueStartDownload(info, info->suggested_path);
655 }
[email protected]0f44d3e2009-03-12 23:36:30656#elif defined(OS_MACOSX)
[email protected]b7f05882009-02-22 01:21:56657 // TODO(port): port this file -- need dialogs.
658 NOTIMPLEMENTED();
659#endif
initial.commit09911bf2008-07-26 23:55:29660}
661
662void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41663 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29664 scoped_ptr<DownloadCreateInfo> infop(info);
665 info->path = target_path;
666
667 DownloadItem* download = NULL;
668 DownloadMap::iterator it = in_progress_.find(info->download_id);
669 if (it == in_progress_.end()) {
670 download = new DownloadItem(info->download_id,
671 info->path,
[email protected]7a256ea2008-10-17 17:34:16672 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29673 info->url,
[email protected]9ccbb372008-10-10 18:50:32674 info->original_name,
initial.commit09911bf2008-07-26 23:55:29675 info->start_time,
676 info->total_bytes,
677 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32678 info->request_id,
679 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29680 download->set_manager(this);
681 in_progress_[info->download_id] = download;
682 } else {
683 NOTREACHED(); // Should not exist!
684 return;
685 }
686
[email protected]6b323782009-03-27 18:43:08687 // Called before DownloadFinished in order to avoid a race condition where we
688 // attempt to open a completed download before it has been renamed.
689 file_loop_->PostTask(FROM_HERE,
690 NewRunnableMethod(file_manager_,
691 &DownloadFileManager::OnFinalDownloadName,
692 download->id(),
[email protected]8f783752009-04-01 23:33:45693 target_path,
694 this));
[email protected]6b323782009-03-27 18:43:08695
initial.commit09911bf2008-07-26 23:55:29696 // If the download already completed by the time we reached this point, then
697 // notify observers that it did.
698 PendingFinishedMap::iterator pending_it =
699 pending_finished_downloads_.find(info->download_id);
700 if (pending_it != pending_finished_downloads_.end())
701 DownloadFinished(pending_it->first, pending_it->second);
702
703 download->Rename(target_path);
704
initial.commit09911bf2008-07-26 23:55:29705 if (profile_->IsOffTheRecord()) {
706 // Fake a db handle for incognito mode, since nothing is actually stored in
707 // the database in this mode. We have to make sure that these handles don't
708 // collide with normal db handles, so we use a negative value. Eventually,
709 // they could overlap, but you'd have to do enough downloading that your ISP
710 // would likely stab you in the neck first. YMMV.
711 static int64 fake_db_handle = kUninitializedHandle - 1;
712 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
713 } else {
714 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22715 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29716 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
717 if (hs) {
718 hs->CreateDownload(
719 *info, &cancelable_consumer_,
720 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
721 }
722 }
723}
724
725// Convenience function for updating the history service for a download.
726void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
727 DCHECK(download);
728
729 // Don't store info in the database if the download was initiated while in
730 // incognito mode or if it hasn't been initialized in our database table.
731 if (download->db_handle() <= kUninitializedHandle)
732 return;
733
[email protected]6cade212008-12-03 00:32:22734 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29735 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
736 if (hs) {
737 hs->UpdateDownload(download->received_bytes(),
738 download->state(),
739 download->db_handle());
740 }
741}
742
743void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
744 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22745 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29746 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
747 if (download->db_handle() > kUninitializedHandle && hs)
748 hs->RemoveDownload(download->db_handle());
749}
750
[email protected]e93d2822009-01-30 05:59:59751void DownloadManager::RemoveDownloadsFromHistoryBetween(
752 const base::Time remove_begin,
753 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22754 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29755 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
756 if (hs)
757 hs->RemoveDownloadsBetween(remove_begin, remove_end);
758}
759
760void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
761 DownloadMap::iterator it = in_progress_.find(download_id);
762 if (it != in_progress_.end()) {
763 DownloadItem* download = it->second;
764 download->Update(size);
765 UpdateHistoryForDownload(download);
766 }
767}
768
769void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
770 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32771 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29772 // The download is done, but the user hasn't selected a final location for
773 // it yet (the Save As dialog box is probably still showing), so just keep
774 // track of the fact that this download id is complete, when the
775 // DownloadItem is constructed later we'll notify its completion then.
776 PendingFinishedMap::iterator erase_it =
777 pending_finished_downloads_.find(download_id);
778 DCHECK(erase_it == pending_finished_downloads_.end());
779 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32780 return;
initial.commit09911bf2008-07-26 23:55:29781 }
[email protected]9ccbb372008-10-10 18:50:32782
783 // Remove the id from the list of pending ids.
784 PendingFinishedMap::iterator erase_it =
785 pending_finished_downloads_.find(download_id);
786 if (erase_it != pending_finished_downloads_.end())
787 pending_finished_downloads_.erase(erase_it);
788
789 DownloadItem* download = it->second;
790 download->Finished(size);
791
792 // Clean up will happen when the history system create callback runs if we
793 // don't have a valid db_handle yet.
794 if (download->db_handle() != kUninitializedHandle) {
795 in_progress_.erase(it);
796 NotifyAboutDownloadStop();
797 UpdateHistoryForDownload(download);
798 }
799
800 // If this a dangerous download not yet validated by the user, don't do
801 // anything. When the user notifies us, it will trigger a call to
802 // ProceedWithFinishedDangerousDownload.
803 if (download->safety_state() == DownloadItem::DANGEROUS) {
804 dangerous_finished_[download_id] = download;
805 return;
806 }
807
808 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22809 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32810 // its final name before we can continue.
811 file_loop_->PostTask(FROM_HERE,
812 NewRunnableMethod(
813 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
814 download->db_handle(),
815 download->full_path(), download->original_name()));
816 return;
817 }
818 ContinueDownloadFinished(download);
819}
820
[email protected]8f783752009-04-01 23:33:45821void DownloadManager::DownloadRenamedToFinalName(int download_id,
822 const FilePath& full_path) {
823 FilePath::StringType extension = full_path.Extension();
824 // Drop the leading period.
825 if (extension.size() > 0)
826 extension = extension.substr(1);
827
828 if (extension == chrome::kExtensionFileExtension) {
829 OpenChromeExtension(full_path);
830 }
831}
832
[email protected]9ccbb372008-10-10 18:50:32833void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
834 // If this was a dangerous download, it has now been approved and must be
835 // removed from dangerous_finished_ so it does not get deleted on shutdown.
836 DownloadMap::iterator it = dangerous_finished_.find(download->id());
837 if (it != dangerous_finished_.end())
838 dangerous_finished_.erase(it);
839
840 // Notify our observers that we are complete (the call to Finished() set the
841 // state to complete but did not notify).
842 download->UpdateObservers();
843
844 // Open the download if the user or user prefs indicate it should be.
[email protected]2001fe82009-02-23 23:53:14845 FilePath::StringType extension = download->full_path().Extension();
846 // Drop the leading period.
847 if (extension.size() > 0)
848 extension = extension.substr(1);
[email protected]8f783752009-04-01 23:33:45849
850 // Handle chrome extensions explicitly and skip the shell execute.
851 if (extension == chrome::kExtensionFileExtension) {
852 // Skip the shell execute. This will be handled in
853 // DownloadRenamedToFinalName
854 return;
855 }
856
[email protected]9ccbb372008-10-10 18:50:32857 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
858 OpenDownloadInShell(download, NULL);
859}
860
861// Called on the file thread. Renames the downloaded file to its original name.
862void DownloadManager::ProceedWithFinishedDangerousDownload(
863 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41864 const FilePath& path,
865 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32866 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41867 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16868 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32869 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24870 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16871 // Make our name unique at this point, as if a dangerous file is downloading
872 // and a 2nd download is started for a file with the same name, they would
873 // have the same path. This is because we uniquify the name on download
874 // start, and at that time the first file does not exists yet, so the second
875 // file gets the same name.
876 uniquifier = GetUniquePathNumber(new_path);
877 if (uniquifier > 0)
878 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32879 success = file_util::Move(path, new_path);
880 } else {
881 NOTREACHED();
882 }
[email protected]6cade212008-12-03 00:32:22883
[email protected]9ccbb372008-10-10 18:50:32884 ui_loop_->PostTask(FROM_HERE,
885 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16886 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32887}
888
889// Call from the file thread when the finished dangerous download was renamed.
890void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
891 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41892 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16893 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32894 DownloadMap::iterator it = downloads_.find(download_handle);
895 if (it == downloads_.end()) {
896 NOTREACHED();
897 return;
898 }
899
900 DownloadItem* download = it->second;
901 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16902 if (success) {
903 // We need to update the path uniquifier so that the UI shows the right
904 // name when calling GetFileName().
905 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32906 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16907 }
[email protected]9ccbb372008-10-10 18:50:32908
909 // Continue the download finished sequence.
910 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29911}
912
913// static
914// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22915// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29916// reliably (crash on shutdown race condition).
917void DownloadManager::CancelDownloadRequest(int render_process_id,
918 int request_id) {
919 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10920 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29921 if (!io_thread || !rdh)
922 return;
923 io_thread->message_loop()->PostTask(FROM_HERE,
924 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
925 rdh,
926 render_process_id,
927 request_id));
928}
929
930// static
931void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
932 int render_process_id,
933 int request_id) {
934 rdh->CancelRequest(render_process_id, request_id, false);
935}
936
937void DownloadManager::DownloadCancelled(int32 download_id) {
938 DownloadMap::iterator it = in_progress_.find(download_id);
939 if (it == in_progress_.end())
940 return;
941 DownloadItem* download = it->second;
942
943 CancelDownloadRequest(download->render_process_id(), download->request_id());
944
945 // Clean up will happen when the history system create callback runs if we
946 // don't have a valid db_handle yet.
947 if (download->db_handle() != kUninitializedHandle) {
948 in_progress_.erase(it);
949 NotifyAboutDownloadStop();
950 UpdateHistoryForDownload(download);
951 }
952
953 // Tell the file manager to cancel the download.
954 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
955 file_loop_->PostTask(FROM_HERE,
956 NewRunnableMethod(file_manager_,
957 &DownloadFileManager::CancelDownload,
958 download->id()));
959}
960
961void DownloadManager::PauseDownload(int32 download_id, bool pause) {
962 DownloadMap::iterator it = in_progress_.find(download_id);
963 if (it != in_progress_.end()) {
964 DownloadItem* download = it->second;
965 if (pause == download->is_paused())
966 return;
967
968 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10969 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29970 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
971 if (!io_thread || !rdh)
972 return;
973
974 io_thread->message_loop()->PostTask(FROM_HERE,
975 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
976 rdh,
977 download->render_process_id(),
978 download->request_id(),
979 pause));
980 }
981}
982
983// static
984void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
985 int render_process_id,
986 int request_id,
987 bool pause) {
988 rdh->PauseRequest(render_process_id, request_id, pause);
989}
990
[email protected]7ae7c2cb2009-01-06 23:31:41991bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32992 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:14993 FilePath::StringType extension = file_name.Extension();
994 // Drop the leading period.
995 if (extension.size() > 0)
996 extension = extension.substr(1);
997 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:32998}
999
1000void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411001 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321002 download->Rename(new_path);
1003
1004 // Update the history.
1005
1006 // No update necessary if the download was initiated while in incognito mode.
1007 if (download->db_handle() <= kUninitializedHandle)
1008 return;
1009
[email protected]6cade212008-12-03 00:32:221010 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321011 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1012 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411013 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321014}
1015
initial.commit09911bf2008-07-26 23:55:291016void DownloadManager::RemoveDownload(int64 download_handle) {
1017 DownloadMap::iterator it = downloads_.find(download_handle);
1018 if (it == downloads_.end())
1019 return;
1020
1021 // Make history update.
1022 DownloadItem* download = it->second;
1023 RemoveDownloadFromHistory(download);
1024
1025 // Remove from our tables and delete.
1026 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321027 it = dangerous_finished_.find(download->id());
1028 if (it != dangerous_finished_.end())
1029 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291030
1031 // Tell observers to refresh their views.
1032 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361033
1034 delete download;
initial.commit09911bf2008-07-26 23:55:291035}
1036
[email protected]e93d2822009-01-30 05:59:591037int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1038 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291039 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1040
initial.commit09911bf2008-07-26 23:55:291041 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281042 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291043 while (it != downloads_.end()) {
1044 DownloadItem* download = it->second;
1045 DownloadItem::DownloadState state = download->state();
1046 if (download->start_time() >= remove_begin &&
1047 (remove_end.is_null() || download->start_time() < remove_end) &&
1048 (state == DownloadItem::COMPLETE ||
1049 state == DownloadItem::CANCELLED)) {
1050 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561051 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581052
1053 // Also remove it from any completed dangerous downloads.
1054 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1055 if (dit != dangerous_finished_.end())
1056 dangerous_finished_.erase(dit);
1057
[email protected]78b8fcc92009-03-31 17:36:281058 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291059
initial.commit09911bf2008-07-26 23:55:291060 continue;
1061 }
1062
1063 ++it;
1064 }
1065
1066 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281067 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291068 if (num_deleted > 0)
1069 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1070
[email protected]78b8fcc92009-03-31 17:36:281071 // Delete the download items after updating the observers.
1072 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1073 pending_deletes.clear();
1074
initial.commit09911bf2008-07-26 23:55:291075 return num_deleted;
1076}
1077
[email protected]e93d2822009-01-30 05:59:591078int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1079 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291080}
1081
1082// Initiate a download of a specific URL. We send the request to the
1083// ResourceDispatcherHost, and let it send us responses like a regular
1084// download.
1085void DownloadManager::DownloadUrl(const GURL& url,
1086 const GURL& referrer,
1087 WebContents* web_contents) {
1088 DCHECK(web_contents);
1089 file_manager_->DownloadUrl(url,
1090 referrer,
[email protected]4566f132009-03-12 01:55:131091 web_contents->process()->pid(),
initial.commit09911bf2008-07-26 23:55:291092 web_contents->render_view_host()->routing_id(),
1093 request_context_.get());
1094}
1095
1096void DownloadManager::NotifyAboutDownloadStart() {
[email protected]bfd04a62009-02-01 18:16:561097 NotificationService::current()->Notify(
1098 NotificationType::DOWNLOAD_START,
1099 NotificationService::AllSources(),
1100 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291101}
1102
1103void DownloadManager::NotifyAboutDownloadStop() {
[email protected]bfd04a62009-02-01 18:16:561104 NotificationService::current()->Notify(
1105 NotificationType::DOWNLOAD_STOP,
1106 NotificationService::AllSources(),
1107 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291108}
1109
[email protected]7ae7c2cb2009-01-06 23:31:411110void DownloadManager::GenerateExtension(
1111 const FilePath& file_name,
1112 const std::string& mime_type,
1113 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291114 // We're worried about three things here:
1115 //
1116 // 1) Security. Many sites let users upload content, such as buddy icons, to
1117 // their web sites. We want to mitigate the case where an attacker
1118 // supplies a malicious executable with an executable file extension but an
1119 // honest site serves the content with a benign content type, such as
1120 // image/jpeg.
1121 //
1122 // 2) Usability. If the site fails to provide a file extension, we want to
1123 // guess a reasonable file extension based on the content type.
1124 //
1125 // 3) Shell integration. Some file extensions automatically integrate with
1126 // the shell. We block these extensions to prevent a malicious web site
1127 // from integrating with the user's shell.
1128
[email protected]7ae7c2cb2009-01-06 23:31:411129 static const FilePath::CharType default_extension[] =
1130 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291131
1132 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411133 FilePath::StringType extension(
1134 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291135
[email protected]b7f05882009-02-22 01:21:561136#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291137 // Rename shell-integrated extensions.
1138 if (win_util::IsShellIntegratedExtension(extension))
1139 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561140#endif
initial.commit09911bf2008-07-26 23:55:291141
1142 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411143 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411144 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291145 if (mime_type == mime_type_from_extension) {
1146 // The hinted extension matches the mime type. It looks like a winner.
1147 generated_extension->swap(extension);
1148 return;
1149 }
1150
1151 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1152 // We want to be careful about executable extensions. The worry here is
1153 // that a trusted web site could be tricked into dropping an executable file
1154 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101155 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291156 // We couldn't find a good extension for this content type. Use a dummy
1157 // extension instead.
1158 extension.assign(default_extension);
1159 }
1160 }
1161
1162 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101163 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291164 } else {
[email protected]6cade212008-12-03 00:32:221165 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291166 // 1. New extension is not ".txt"
1167 // 2. New extension is not the same as the already existing extension.
1168 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411169 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291170 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1171 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371172 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1173 // servers, i.e. bug 5772.
[email protected]7ae7c2cb2009-01-06 23:31:411174 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101175 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171176 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411177 append_extension != extension &&
[email protected]e106457b2009-03-25 22:43:371178 !IsExecutable(append_extension) &&
1179 (append_extension != FILE_PATH_LITERAL("tar") ||
1180 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171181 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291182 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171183 }
initial.commit09911bf2008-07-26 23:55:291184 }
1185 }
1186
1187 generated_extension->swap(extension);
1188}
1189
1190void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411191 FilePath* generated_name) {
1192 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371193 net::GetSuggestedFilename(GURL(info->url),
1194 info->content_disposition,
[email protected]7ae7c2cb2009-01-06 23:31:411195 L"download"));
1196 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291197
[email protected]7ae7c2cb2009-01-06 23:31:411198 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291199}
1200
1201void DownloadManager::AddObserver(Observer* observer) {
1202 observers_.AddObserver(observer);
1203 observer->ModelChanged();
1204}
1205
1206void DownloadManager::RemoveObserver(Observer* observer) {
1207 observers_.RemoveObserver(observer);
1208}
1209
1210// Post Windows Shell operations to the Download thread, to avoid blocking the
1211// user interface.
1212void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1213 DCHECK(file_manager_);
1214 file_loop_->PostTask(FROM_HERE,
1215 NewRunnableMethod(file_manager_,
1216 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411217 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291218}
1219
[email protected]8f783752009-04-01 23:33:451220void DownloadManager::OpenDownload(const DownloadItem* download,
1221 gfx::NativeView parent_window) {
1222 FilePath::StringType extension = download->full_path().Extension();
1223 // Drop the leading period.
1224 if (extension.size() > 0)
1225 extension = extension.substr(1);
1226
1227 // Open Chrome extensions with ExtenstionsService. For everthing else do shell
1228 // execute.
1229 if (extension == chrome::kExtensionFileExtension) {
1230 OpenChromeExtension(download->full_path());
1231 } else {
1232 OpenDownloadInShell(download, parent_window);
1233 }
1234}
1235
1236void DownloadManager::OpenChromeExtension(const FilePath& full_path) {
[email protected]d81706b82009-04-03 20:28:441237 // Temporary: Ask the user if it's okay to install the extension. This should
1238 // be replaced with the actual extension installation UI when it is avaiable.
1239#if defined(OS_WIN)
1240 if (win_util::MessageBox(GetActiveWindow(),
1241 L"Are you sure you want to install this extension?\n\n"
1242 L"This is a temporary message and it will be removed when extensions UI "
1243 L"is finalized.",
1244 l10n_util::GetString(IDS_PRODUCT_NAME).c_str(), MB_OKCANCEL) == IDOK) {
1245 ExtensionsService* extensions_service = profile_->GetExtensionsService();
1246 extensions_service->InstallExtension(full_path);
1247 }
1248#else
1249 // TODO(port): Needs CreateChromeWindow.
[email protected]8f783752009-04-01 23:33:451250 ExtensionsService* extensions_service = profile_->GetExtensionsService();
1251 extensions_service->InstallExtension(full_path);
[email protected]d81706b82009-04-03 20:28:441252#endif
1253
[email protected]8f783752009-04-01 23:33:451254}
1255
initial.commit09911bf2008-07-26 23:55:291256void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591257 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291258 DCHECK(file_manager_);
1259 file_loop_->PostTask(FROM_HERE,
1260 NewRunnableMethod(file_manager_,
1261 &DownloadFileManager::OnOpenDownloadInShell,
1262 download->full_path(), download->url(), parent_window));
1263}
1264
[email protected]7ae7c2cb2009-01-06 23:31:411265void DownloadManager::OpenFilesOfExtension(
1266 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291267 if (open && !IsExecutable(extension))
1268 auto_open_.insert(extension);
1269 else
1270 auto_open_.erase(extension);
1271 SaveAutoOpens();
1272}
1273
[email protected]7ae7c2cb2009-01-06 23:31:411274bool DownloadManager::ShouldOpenFileExtension(
1275 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411276 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291277 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411278 (auto_open_.find(extension) != auto_open_.end() ||
1279 extension == chrome::kExtensionFileExtension))
1280 return true;
initial.commit09911bf2008-07-26 23:55:291281 return false;
1282}
1283
[email protected]7b73d992008-12-15 20:56:461284static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291285 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461286 "text/javascript",
1287 "text/javascript;version=*",
[email protected]60ff8f912008-12-05 07:58:391288 // Some sites use binary/octet-stream to mean application/octet-stream.
1289 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461290 "binary/octet-stream"
1291};
initial.commit09911bf2008-07-26 23:55:291292
[email protected]7b73d992008-12-15 20:56:461293static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291294 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461295 "application/*+xml",
1296 "application/xml"
1297};
initial.commit09911bf2008-07-26 23:55:291298
[email protected]7b73d992008-12-15 20:56:461299// static
1300bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411301 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461302 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1303 return true;
1304 }
[email protected]bae0ea12009-02-14 01:20:411305 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461306 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1307 return false;
1308 }
1309 // We consider only other application types to be executable.
1310 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291311}
1312
[email protected]7ae7c2cb2009-01-06 23:31:411313bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]64da0b932009-02-24 02:30:041314#if defined(OS_WIN)
1315 if (!IsStringASCII(extension))
1316 return false;
1317 std::string ascii_extension = WideToASCII(extension);
1318 StringToLowerASCII(&ascii_extension);
1319
1320 return exe_types_.find(ascii_extension) != exe_types_.end();
1321#elif defined(OS_POSIX)
1322 // TODO(port): we misght not want to call this function on other platforms.
1323 // Figure it out.
1324 NOTIMPLEMENTED();
1325 return false;
1326#endif
initial.commit09911bf2008-07-26 23:55:291327}
1328
1329void DownloadManager::ResetAutoOpenFiles() {
1330 auto_open_.clear();
1331 SaveAutoOpens();
1332}
1333
1334bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1335 return !auto_open_.empty();
1336}
1337
1338void DownloadManager::SaveAutoOpens() {
1339 PrefService* prefs = profile_->GetPrefs();
1340 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411341 FilePath::StringType extensions;
1342 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291343 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411344 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291345 }
1346 if (!extensions.empty())
1347 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561348
1349 std::wstring extensions_w;
1350#if defined(OS_WIN)
1351 extensions_w = extensions;
1352#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141353 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561354#endif
1355
1356 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291357 }
1358}
1359
[email protected]561abe62009-04-06 18:08:341360void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361361 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291362 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071363 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411364 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291365 ContinueStartDownload(info, path);
1366}
1367
1368void DownloadManager::FileSelectionCanceled(void* params) {
1369 // The user didn't pick a place to save the file, so need to cancel the
1370 // download that's already in progress to the temporary location.
1371 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1372 file_loop_->PostTask(FROM_HERE,
1373 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1374 info->download_id));
1375}
1376
[email protected]7ae7c2cb2009-01-06 23:31:411377void DownloadManager::DeleteDownload(const FilePath& path) {
1378 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1379 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321380}
1381
1382
1383void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1384 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1385 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1386 download->UpdateObservers();
1387
1388 // If the download is not complete, nothing to do. The required
1389 // post-processing will be performed when it does complete.
1390 if (download->state() != DownloadItem::COMPLETE)
1391 return;
1392
1393 file_loop_->PostTask(FROM_HERE,
1394 NewRunnableMethod(this,
1395 &DownloadManager::ProceedWithFinishedDangerousDownload,
1396 download->db_handle(), download->full_path(),
1397 download->original_name()));
1398}
1399
[email protected]763f946a2009-01-06 19:04:391400void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411401 FilePath* file_name) {
1402 // Make sure we get the right file extension
1403 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391404 GenerateExtension(*file_name, mime_type, &extension);
1405 file_util::ReplaceExtension(file_name, extension);
1406
[email protected]2b2f8f72009-02-24 22:42:051407#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391408 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411409 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391410 DCHECK(!leaf_name.empty());
1411 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411412 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1413 *file_name = file_name->DirName();
1414 if (file_name->value() == FilePath::kCurrentDirectory) {
1415 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391416 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411417 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391418 }
1419 }
[email protected]b7f05882009-02-22 01:21:561420#elif defined(OS_POSIX)
1421 NOTIMPLEMENTED();
1422#endif
[email protected]763f946a2009-01-06 19:04:391423}
1424
initial.commit09911bf2008-07-26 23:55:291425// Operations posted to us from the history service ----------------------------
1426
1427// The history service has retrieved all download entries. 'entries' contains
1428// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1429void DownloadManager::OnQueryDownloadEntriesComplete(
1430 std::vector<DownloadCreateInfo>* entries) {
1431 for (size_t i = 0; i < entries->size(); ++i) {
1432 DownloadItem* download = new DownloadItem(entries->at(i));
1433 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1434 downloads_[download->db_handle()] = download;
1435 download->set_manager(this);
1436 }
1437 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1438}
1439
initial.commit09911bf2008-07-26 23:55:291440// Once the new DownloadItem's creation info has been committed to the history
1441// service, we associate the DownloadItem with the db handle, update our
1442// 'downloads_' map and inform observers.
1443void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1444 int64 db_handle) {
1445 DownloadMap::iterator it = in_progress_.find(info.download_id);
1446 DCHECK(it != in_progress_.end());
1447
1448 DownloadItem* download = it->second;
1449 DCHECK(download->db_handle() == kUninitializedHandle);
1450 download->set_db_handle(db_handle);
1451
1452 // Insert into our full map.
1453 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1454 downloads_[download->db_handle()] = download;
1455
1456 // The 'contents' may no longer exist if the user closed the tab before we get
1457 // this start completion event. If it does, tell the origin WebContents to
1458 // display its download shelf.
1459 TabContents* contents =
[email protected]a3a1d142008-12-19 00:42:301460 tab_util::GetWebContentsByID(info.render_process_id, info.render_view_id);
initial.commit09911bf2008-07-26 23:55:291461
1462 // If the contents no longer exists or is no longer active, we start the
1463 // download in the last active browser. This is not ideal but better than
1464 // fully hiding the download from the user. Note: non active means that the
1465 // user navigated away from the tab contents. This has nothing to do with
1466 // tab selection.
1467 if (!contents || !contents->is_active()) {
1468 Browser* last_active = BrowserList::GetLastActive();
1469 if (last_active)
1470 contents = last_active->GetSelectedTabContents();
1471 }
1472
1473 if (contents)
1474 contents->OnStartDownload(download);
1475
1476 // Inform interested objects about the new download.
1477 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1478 NotifyAboutDownloadStart();
1479
1480 // If this download has been completed before we've received the db handle,
1481 // post one final message to the history service so that it can be properly
1482 // in sync with the DownloadItem's completion status, and also inform any
1483 // observers so that they get more than just the start notification.
1484 if (download->state() != DownloadItem::IN_PROGRESS) {
1485 in_progress_.erase(it);
1486 NotifyAboutDownloadStop();
1487 UpdateHistoryForDownload(download);
1488 download->UpdateObservers();
1489 }
1490}
1491
1492// Called when the history service has retrieved the list of downloads that
1493// match the search text.
1494void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1495 std::vector<int64>* results) {
1496 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1497 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1498 if (!requestor)
1499 return;
1500
1501 std::vector<DownloadItem*> searched_downloads;
1502 for (std::vector<int64>::iterator it = results->begin();
1503 it != results->end(); ++it) {
1504 DownloadMap::iterator dit = downloads_.find(*it);
1505 if (dit != downloads_.end())
1506 searched_downloads.push_back(dit->second);
1507 }
1508
1509 requestor->SetDownloads(searched_downloads);
1510}
[email protected]905a08d2008-11-19 07:24:121511
[email protected]6cade212008-12-03 00:32:221512// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121513void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411514 last_download_path_ = FilePath();
[email protected]905a08d2008-11-19 07:24:121515}