blob: 04c6aebc660fd2bcc1346368bddabe6e67ef4d82 [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
[email protected]45e3c122009-04-07 19:58:03190void DownloadItem::NotifyObserversDownloadOpened() {
191 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
192}
193
initial.commit09911bf2008-07-26 23:55:29194// If we've received more data than we were expecting (bad server info?), revert
195// to 'unknown size mode'.
196void DownloadItem::UpdateSize(int64 bytes_so_far) {
197 received_bytes_ = bytes_so_far;
198 if (received_bytes_ > total_bytes_)
199 total_bytes_ = 0;
200}
201
202// Updates from the download thread may have been posted while this download
203// was being cancelled in the UI thread, so we'll accept them unless we're
204// complete.
205void DownloadItem::Update(int64 bytes_so_far) {
206 if (state_ == COMPLETE) {
207 NOTREACHED();
208 return;
209 }
210 UpdateSize(bytes_so_far);
211 UpdateObservers();
212}
213
[email protected]6cade212008-12-03 00:32:22214// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29215void DownloadItem::Cancel(bool update_history) {
216 if (state_ != IN_PROGRESS) {
217 // Small downloads might be complete before this method has a chance to run.
218 return;
219 }
220 state_ = CANCELLED;
221 UpdateObservers();
222 StopProgressTimer();
223 if (update_history)
224 manager_->DownloadCancelled(id_);
225}
226
227void DownloadItem::Finished(int64 size) {
228 state_ = COMPLETE;
229 UpdateSize(size);
[email protected]22fbe5a2008-10-29 22:20:40230 UpdateObservers();
initial.commit09911bf2008-07-26 23:55:29231 StopProgressTimer();
232}
233
[email protected]9ccbb372008-10-10 18:50:32234void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29235 Cancel(true);
236 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32237 if (delete_on_disk)
238 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29239 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22240 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29241}
242
243void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59244 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14245 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29246}
247
248void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14249 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29250}
251
[email protected]e93d2822009-01-30 05:59:59252bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29253 if (total_bytes_ <= 0)
254 return false; // We never received the content_length for this download.
255
256 int64 speed = CurrentSpeed();
257 if (speed == 0)
258 return false;
259
260 *remaining =
[email protected]e93d2822009-01-30 05:59:59261 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29262 return true;
263}
264
265int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56266 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
267 int64 diff_ms = diff.InMilliseconds();
268 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29269}
270
271int DownloadItem::PercentComplete() const {
272 int percent = -1;
273 if (total_bytes_ > 0)
274 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
275 return percent;
276}
277
[email protected]7ae7c2cb2009-01-06 23:31:41278void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29279 DCHECK(!full_path.empty());
280 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41281 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29282}
283
284void DownloadItem::TogglePause() {
285 DCHECK(state_ == IN_PROGRESS);
286 manager_->PauseDownload(id_, !is_paused_);
287 is_paused_ = !is_paused_;
288 UpdateObservers();
289}
290
[email protected]7ae7c2cb2009-01-06 23:31:41291FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32292 if (safety_state_ == DownloadItem::SAFE)
293 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16294 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41295 FilePath name(original_name_);
[email protected]7a256ea2008-10-17 17:34:16296 AppendNumberToPath(&name, path_uniquifier_);
297 return name;
298 }
[email protected]9ccbb372008-10-10 18:50:32299 return original_name_;
300}
301
initial.commit09911bf2008-07-26 23:55:29302// DownloadManager implementation ----------------------------------------------
303
304// static
305void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
306 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
307 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32308 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
309
310 // The default download path is userprofile\download.
[email protected]7ae7c2cb2009-01-06 23:31:41311 FilePath default_download_path;
[email protected]cbc43fc2008-10-28 00:44:12312 if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS,
313 &default_download_path)) {
[email protected]f052118e2008-09-05 02:25:32314 NOTREACHED();
315 }
[email protected]b9636002009-03-04 00:05:25316 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
317 default_download_path);
[email protected]f052118e2008-09-05 02:25:32318
319 // If the download path is dangerous we forcefully reset it. But if we do
320 // so we set a flag to make sure we only do it once, to avoid fighting
321 // the user if he really wants it on an unsafe place such as the desktop.
322
323 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]7ae7c2cb2009-01-06 23:31:41324 FilePath current_download_dir = FilePath::FromWStringHack(
325 prefs->GetString(prefs::kDownloadDefaultDirectory));
[email protected]f052118e2008-09-05 02:25:32326 if (DownloadPathIsDangerous(current_download_dir)) {
327 prefs->SetString(prefs::kDownloadDefaultDirectory,
[email protected]7ae7c2cb2009-01-06 23:31:41328 default_download_path.ToWStringHack());
[email protected]f052118e2008-09-05 02:25:32329 }
330 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
331 }
initial.commit09911bf2008-07-26 23:55:29332}
333
334DownloadManager::DownloadManager()
335 : shutdown_needed_(false),
336 profile_(NULL),
337 file_manager_(NULL),
338 ui_loop_(MessageLoop::current()),
339 file_loop_(NULL) {
340}
341
342DownloadManager::~DownloadManager() {
343 if (shutdown_needed_)
344 Shutdown();
345}
346
347void DownloadManager::Shutdown() {
348 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
349
350 // Stop receiving download updates
351 file_manager_->RemoveDownloadManager(this);
352
353 // Stop making history service requests
354 cancelable_consumer_.CancelAllRequests();
355
356 // 'in_progress_' may contain DownloadItems that have not finished the start
357 // complete (from the history service) and thus aren't in downloads_.
358 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32359 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29360 for (; it != in_progress_.end(); ++it) {
361 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32362 if (download->safety_state() == DownloadItem::DANGEROUS) {
363 // Forget about any download that the user did not approve.
364 // Note that we cannot call download->Remove() this would invalidate our
365 // iterator.
366 to_remove.insert(download);
367 continue;
initial.commit09911bf2008-07-26 23:55:29368 }
[email protected]9ccbb372008-10-10 18:50:32369 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
370 download->Cancel(false);
371 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29372 if (download->db_handle() == kUninitializedHandle) {
373 // An invalid handle means that 'download' does not yet exist in
374 // 'downloads_', so we have to delete it here.
375 delete download;
376 }
377 }
378
[email protected]9ccbb372008-10-10 18:50:32379 // 'dangerous_finished_' contains all complete downloads that have not been
380 // approved. They should be removed.
381 it = dangerous_finished_.begin();
382 for (; it != dangerous_finished_.end(); ++it)
383 to_remove.insert(it->second);
384
385 // Remove the dangerous download that are not approved.
386 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
387 rm_it != to_remove.end(); ++rm_it) {
388 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32389 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32390 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32391 // Same as above, delete the download if it is not in 'downloads_' (as the
392 // Remove() call above won't have deleted it).
393 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32394 delete download;
395 }
396 to_remove.clear();
397
initial.commit09911bf2008-07-26 23:55:29398 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32399 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29400 STLDeleteValues(&downloads_);
401
402 file_manager_ = NULL;
403
404 // Save our file extensions to auto open.
405 SaveAutoOpens();
406
407 // Make sure the save as dialog doesn't notify us back if we're gone before
408 // it returns.
409 if (select_file_dialog_.get())
410 select_file_dialog_->ListenerDestroyed();
411
412 shutdown_needed_ = false;
413}
414
415// Issue a history query for downloads matching 'search_text'. If 'search_text'
416// is empty, return all downloads that we know about.
417void DownloadManager::GetDownloads(Observer* observer,
418 const std::wstring& search_text) {
419 DCHECK(observer);
420
421 // Return a empty list if we've not yet received the set of downloads from the
422 // history system (we'll update all observers once we get that list in
423 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
424 std::vector<DownloadItem*> download_copy;
425 if (downloads_.empty()) {
426 observer->SetDownloads(download_copy);
427 return;
428 }
429
430 // We already know all the downloads and there is no filter, so just return a
431 // copy to the observer.
432 if (search_text.empty()) {
433 download_copy.reserve(downloads_.size());
434 for (DownloadMap::iterator it = downloads_.begin();
435 it != downloads_.end(); ++it) {
436 download_copy.push_back(it->second);
437 }
438
439 // We retain ownership of the DownloadItems.
440 observer->SetDownloads(download_copy);
441 return;
442 }
443
444 // Issue a request to the history service for a list of downloads matching
445 // our search text.
446 HistoryService* hs =
447 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
448 if (hs) {
449 HistoryService::Handle h =
450 hs->SearchDownloads(search_text,
451 &cancelable_consumer_,
452 NewCallback(this,
453 &DownloadManager::OnSearchComplete));
454 cancelable_consumer_.SetClientData(hs, h, observer);
455 }
456}
457
458// Query the history service for information about all persisted downloads.
459bool DownloadManager::Init(Profile* profile) {
460 DCHECK(profile);
461 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
462 shutdown_needed_ = true;
463
464 profile_ = profile;
465 request_context_ = profile_->GetRequestContext();
466
467 // 'incognito mode' will have access to past downloads, but we won't store
468 // information about new downloads while in that mode.
469 QueryHistoryForDownloads();
470
471 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
472 if (!rdh) {
473 NOTREACHED();
474 return false;
475 }
476
477 file_manager_ = rdh->download_file_manager();
478 if (!file_manager_) {
479 NOTREACHED();
480 return false;
481 }
482
483 file_loop_ = g_browser_process->file_thread()->message_loop();
484 if (!file_loop_) {
485 NOTREACHED();
486 return false;
487 }
488
489 // Get our user preference state.
490 PrefService* prefs = profile_->GetPrefs();
491 DCHECK(prefs);
492 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
493
initial.commit09911bf2008-07-26 23:55:29494 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
495
[email protected]7ae7c2cb2009-01-06 23:31:41496 // This variable is needed to resolve which CreateDirectory we want to point
497 // to. Without it, the NewRunnableFunction cannot resolve the ambiguity.
498 // TODO(estade): when file_util::CreateDirectory(wstring) is removed,
499 // get rid of |CreateDirectoryPtr|.
500 bool (*CreateDirectoryPtr)(const FilePath&) = &file_util::CreateDirectory;
[email protected]bb69e9b32008-08-14 23:08:14501 // Ensure that the download directory specified in the preferences exists.
[email protected]7ae7c2cb2009-01-06 23:31:41502 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
503 CreateDirectoryPtr, download_path()));
initial.commit09911bf2008-07-26 23:55:29504
[email protected]2b2f8f72009-02-24 22:42:05505#if defined(OS_WIN)
506 // We use this on windows to determine possibly dangerous downloads.
507 download_util::InitializeExeTypes(&exe_types_);
508#endif
509
510 // We store any file extension that should be opened automatically at
511 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29512 std::wstring extensions_to_open =
513 prefs->GetString(prefs::kDownloadExtensionsToOpen);
514 std::vector<std::wstring> extensions;
515 SplitString(extensions_to_open, L':', &extensions);
516 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]b7f05882009-02-22 01:21:56517 if (!extensions[i].empty() && !IsExecutable(
518 FilePath::FromWStringHack(extensions[i]).value()))
519 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29520 }
521
522 return true;
523}
524
525void DownloadManager::QueryHistoryForDownloads() {
526 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
527 if (hs) {
528 hs->QueryDownloads(
529 &cancelable_consumer_,
530 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
531 }
532}
533
534// We have received a message from DownloadFileManager about a new download. We
535// create a download item and store it in our download map, and inform the
536// history system of a new download. Since this method can be called while the
537// history service thread is still reading the persistent state, we do not
538// insert the new DownloadItem into 'downloads_' or inform our observers at this
539// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
540// download creation as a callback from the history thread.
541void DownloadManager::StartDownload(DownloadCreateInfo* info) {
542 DCHECK(MessageLoop::current() == ui_loop_);
543 DCHECK(info);
544
[email protected]7d3851d82008-12-12 03:26:07545 // Freeze the user's preference for showing a Save As dialog. We're going to
546 // bounce around a bunch of threads and we don't want to worry about race
547 // conditions where the user changes this pref out from under us.
548 if (*prompt_for_download_)
549 info->save_as = true;
550
initial.commit09911bf2008-07-26 23:55:29551 // Determine the proper path for a download, by choosing either the default
552 // download directory, or prompting the user.
[email protected]7ae7c2cb2009-01-06 23:31:41553 FilePath generated_name;
initial.commit09911bf2008-07-26 23:55:29554 GenerateFilename(info, &generated_name);
[email protected]7d3851d82008-12-12 03:26:07555 if (info->save_as && !last_download_path_.empty())
initial.commit09911bf2008-07-26 23:55:29556 info->suggested_path = last_download_path_;
557 else
[email protected]7ae7c2cb2009-01-06 23:31:41558 info->suggested_path = download_path();
559 info->suggested_path = info->suggested_path.Append(generated_name);
initial.commit09911bf2008-07-26 23:55:29560
[email protected]7d3851d82008-12-12 03:26:07561 if (!info->save_as) {
562 // Let's check if this download is dangerous, based on its name.
[email protected]7ae7c2cb2009-01-06 23:31:41563 info->is_dangerous = IsDangerous(info->suggested_path.BaseName());
[email protected]e9ebf3fc2008-10-17 22:06:58564 }
565
initial.commit09911bf2008-07-26 23:55:29566 // We need to move over to the download thread because we don't want to stat
567 // the suggested path on the UI thread.
568 file_loop_->PostTask(FROM_HERE,
569 NewRunnableMethod(this,
570 &DownloadManager::CheckIfSuggestedPathExists,
571 info));
572}
573
574void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
575 DCHECK(info);
576
577 // Check writability of the suggested path. If we can't write to it, default
578 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41579 FilePath dir = info->suggested_path.DirName();
580 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32581 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29582 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29583 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41584 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29585 }
586
[email protected]7a256ea2008-10-17 17:34:16587 info->path_uniquifier = GetUniquePathNumber(info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29588
[email protected]6cade212008-12-03 00:32:22589 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58590 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41591 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32592 // Create a temporary file to hold the file until the user approves its
593 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41594 FilePath::StringType file_name;
595 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32596 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41597 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32598 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41599 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07600 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41601 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32602 }
603 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16604 } else {
605 // We know the final path, build it if necessary.
606 if (info->path_uniquifier > 0) {
607 AppendNumberToPath(&(info->suggested_path), info->path_uniquifier);
608 // Setting path_uniquifier to 0 to make sure we don't try to unique it
609 // later on.
610 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07611 } else if (info->path_uniquifier == -1) {
612 // We failed to find a unique path. We have to prompt the user.
613 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16614 }
[email protected]9ccbb372008-10-10 18:50:32615 }
616
[email protected]7d3851d82008-12-12 03:26:07617 if (!info->save_as) {
618 // Create an empty file at the suggested path so that we don't allocate the
619 // same "non-existant" path to multiple downloads.
620 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ae7c2cb2009-01-06 23:31:41621 file_util::WriteFile(info->suggested_path.ToWStringHack(), "", 0);
[email protected]7d3851d82008-12-12 03:26:07622 }
623
initial.commit09911bf2008-07-26 23:55:29624 // Now we return to the UI thread.
625 ui_loop_->PostTask(FROM_HERE,
626 NewRunnableMethod(this,
627 &DownloadManager::OnPathExistenceAvailable,
628 info));
629}
630
631void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]0f44d3e2009-03-12 23:36:30632#if defined(OS_WIN) || defined(OS_LINUX)
initial.commit09911bf2008-07-26 23:55:29633 DCHECK(MessageLoop::current() == ui_loop_);
634 DCHECK(info);
635
[email protected]7d3851d82008-12-12 03:26:07636 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29637 // We must ask the user for the place to put the download.
638 if (!select_file_dialog_.get())
639 select_file_dialog_ = SelectFileDialog::Create(this);
640
[email protected]a3a1d142008-12-19 00:42:30641 WebContents* contents = tab_util::GetWebContentsByID(
initial.commit09911bf2008-07-26 23:55:29642 info->render_process_id, info->render_view_id);
[email protected]0f44d3e2009-03-12 23:36:30643#if defined(OS_WIN)
[email protected]7ae7c2cb2009-01-06 23:31:41644 std::wstring filter =
645 win_util::GetFileFilterFromPath(info->suggested_path.value());
[email protected]0f44d3e2009-03-12 23:36:30646#elif defined(OS_LINUX)
647 std::wstring filter;
[email protected]0f44d3e2009-03-12 23:36:30648#endif
[email protected]076700e62009-04-01 18:41:23649 gfx::NativeWindow owning_window =
650 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29651 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34652 string16(),
653 info->suggested_path,
654 filter, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30655 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29656 } else {
657 // No prompting for download, just continue with the suggested name.
658 ContinueStartDownload(info, info->suggested_path);
659 }
[email protected]0f44d3e2009-03-12 23:36:30660#elif defined(OS_MACOSX)
[email protected]b7f05882009-02-22 01:21:56661 // TODO(port): port this file -- need dialogs.
662 NOTIMPLEMENTED();
663#endif
initial.commit09911bf2008-07-26 23:55:29664}
665
666void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41667 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29668 scoped_ptr<DownloadCreateInfo> infop(info);
669 info->path = target_path;
670
671 DownloadItem* download = NULL;
672 DownloadMap::iterator it = in_progress_.find(info->download_id);
673 if (it == in_progress_.end()) {
674 download = new DownloadItem(info->download_id,
675 info->path,
[email protected]7a256ea2008-10-17 17:34:16676 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29677 info->url,
[email protected]9ccbb372008-10-10 18:50:32678 info->original_name,
initial.commit09911bf2008-07-26 23:55:29679 info->start_time,
680 info->total_bytes,
681 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32682 info->request_id,
683 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29684 download->set_manager(this);
685 in_progress_[info->download_id] = download;
686 } else {
687 NOTREACHED(); // Should not exist!
688 return;
689 }
690
[email protected]6b323782009-03-27 18:43:08691 // Called before DownloadFinished in order to avoid a race condition where we
692 // attempt to open a completed download before it has been renamed.
693 file_loop_->PostTask(FROM_HERE,
694 NewRunnableMethod(file_manager_,
695 &DownloadFileManager::OnFinalDownloadName,
696 download->id(),
[email protected]8f783752009-04-01 23:33:45697 target_path,
698 this));
[email protected]6b323782009-03-27 18:43:08699
initial.commit09911bf2008-07-26 23:55:29700 // If the download already completed by the time we reached this point, then
701 // notify observers that it did.
702 PendingFinishedMap::iterator pending_it =
703 pending_finished_downloads_.find(info->download_id);
704 if (pending_it != pending_finished_downloads_.end())
705 DownloadFinished(pending_it->first, pending_it->second);
706
707 download->Rename(target_path);
708
initial.commit09911bf2008-07-26 23:55:29709 if (profile_->IsOffTheRecord()) {
710 // Fake a db handle for incognito mode, since nothing is actually stored in
711 // the database in this mode. We have to make sure that these handles don't
712 // collide with normal db handles, so we use a negative value. Eventually,
713 // they could overlap, but you'd have to do enough downloading that your ISP
714 // would likely stab you in the neck first. YMMV.
715 static int64 fake_db_handle = kUninitializedHandle - 1;
716 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
717 } else {
718 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22719 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29720 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
721 if (hs) {
722 hs->CreateDownload(
723 *info, &cancelable_consumer_,
724 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
725 }
726 }
727}
728
729// Convenience function for updating the history service for a download.
730void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
731 DCHECK(download);
732
733 // Don't store info in the database if the download was initiated while in
734 // incognito mode or if it hasn't been initialized in our database table.
735 if (download->db_handle() <= kUninitializedHandle)
736 return;
737
[email protected]6cade212008-12-03 00:32:22738 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29739 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
740 if (hs) {
741 hs->UpdateDownload(download->received_bytes(),
742 download->state(),
743 download->db_handle());
744 }
745}
746
747void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
748 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22749 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29750 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
751 if (download->db_handle() > kUninitializedHandle && hs)
752 hs->RemoveDownload(download->db_handle());
753}
754
[email protected]e93d2822009-01-30 05:59:59755void DownloadManager::RemoveDownloadsFromHistoryBetween(
756 const base::Time remove_begin,
757 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22758 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29759 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
760 if (hs)
761 hs->RemoveDownloadsBetween(remove_begin, remove_end);
762}
763
764void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
765 DownloadMap::iterator it = in_progress_.find(download_id);
766 if (it != in_progress_.end()) {
767 DownloadItem* download = it->second;
768 download->Update(size);
769 UpdateHistoryForDownload(download);
770 }
771}
772
773void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
774 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32775 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29776 // The download is done, but the user hasn't selected a final location for
777 // it yet (the Save As dialog box is probably still showing), so just keep
778 // track of the fact that this download id is complete, when the
779 // DownloadItem is constructed later we'll notify its completion then.
780 PendingFinishedMap::iterator erase_it =
781 pending_finished_downloads_.find(download_id);
782 DCHECK(erase_it == pending_finished_downloads_.end());
783 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32784 return;
initial.commit09911bf2008-07-26 23:55:29785 }
[email protected]9ccbb372008-10-10 18:50:32786
787 // Remove the id from the list of pending ids.
788 PendingFinishedMap::iterator erase_it =
789 pending_finished_downloads_.find(download_id);
790 if (erase_it != pending_finished_downloads_.end())
791 pending_finished_downloads_.erase(erase_it);
792
793 DownloadItem* download = it->second;
794 download->Finished(size);
795
796 // Clean up will happen when the history system create callback runs if we
797 // don't have a valid db_handle yet.
798 if (download->db_handle() != kUninitializedHandle) {
799 in_progress_.erase(it);
800 NotifyAboutDownloadStop();
801 UpdateHistoryForDownload(download);
802 }
803
804 // If this a dangerous download not yet validated by the user, don't do
805 // anything. When the user notifies us, it will trigger a call to
806 // ProceedWithFinishedDangerousDownload.
807 if (download->safety_state() == DownloadItem::DANGEROUS) {
808 dangerous_finished_[download_id] = download;
809 return;
810 }
811
812 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22813 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32814 // its final name before we can continue.
815 file_loop_->PostTask(FROM_HERE,
816 NewRunnableMethod(
817 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
818 download->db_handle(),
819 download->full_path(), download->original_name()));
820 return;
821 }
822 ContinueDownloadFinished(download);
823}
824
[email protected]8f783752009-04-01 23:33:45825void DownloadManager::DownloadRenamedToFinalName(int download_id,
826 const FilePath& full_path) {
827 FilePath::StringType extension = full_path.Extension();
828 // Drop the leading period.
829 if (extension.size() > 0)
830 extension = extension.substr(1);
831
832 if (extension == chrome::kExtensionFileExtension) {
833 OpenChromeExtension(full_path);
834 }
835}
836
[email protected]9ccbb372008-10-10 18:50:32837void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
838 // If this was a dangerous download, it has now been approved and must be
839 // removed from dangerous_finished_ so it does not get deleted on shutdown.
840 DownloadMap::iterator it = dangerous_finished_.find(download->id());
841 if (it != dangerous_finished_.end())
842 dangerous_finished_.erase(it);
843
844 // Notify our observers that we are complete (the call to Finished() set the
845 // state to complete but did not notify).
846 download->UpdateObservers();
847
848 // Open the download if the user or user prefs indicate it should be.
[email protected]2001fe82009-02-23 23:53:14849 FilePath::StringType extension = download->full_path().Extension();
850 // Drop the leading period.
851 if (extension.size() > 0)
852 extension = extension.substr(1);
[email protected]8f783752009-04-01 23:33:45853
854 // Handle chrome extensions explicitly and skip the shell execute.
855 if (extension == chrome::kExtensionFileExtension) {
856 // Skip the shell execute. This will be handled in
857 // DownloadRenamedToFinalName
858 return;
859 }
860
[email protected]9ccbb372008-10-10 18:50:32861 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
862 OpenDownloadInShell(download, NULL);
863}
864
865// Called on the file thread. Renames the downloaded file to its original name.
866void DownloadManager::ProceedWithFinishedDangerousDownload(
867 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41868 const FilePath& path,
869 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32870 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41871 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16872 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32873 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24874 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16875 // Make our name unique at this point, as if a dangerous file is downloading
876 // and a 2nd download is started for a file with the same name, they would
877 // have the same path. This is because we uniquify the name on download
878 // start, and at that time the first file does not exists yet, so the second
879 // file gets the same name.
880 uniquifier = GetUniquePathNumber(new_path);
881 if (uniquifier > 0)
882 AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32883 success = file_util::Move(path, new_path);
884 } else {
885 NOTREACHED();
886 }
[email protected]6cade212008-12-03 00:32:22887
[email protected]9ccbb372008-10-10 18:50:32888 ui_loop_->PostTask(FROM_HERE,
889 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16890 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32891}
892
893// Call from the file thread when the finished dangerous download was renamed.
894void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
895 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41896 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16897 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32898 DownloadMap::iterator it = downloads_.find(download_handle);
899 if (it == downloads_.end()) {
900 NOTREACHED();
901 return;
902 }
903
904 DownloadItem* download = it->second;
905 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16906 if (success) {
907 // We need to update the path uniquifier so that the UI shows the right
908 // name when calling GetFileName().
909 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32910 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16911 }
[email protected]9ccbb372008-10-10 18:50:32912
913 // Continue the download finished sequence.
914 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29915}
916
917// static
918// We have to tell the ResourceDispatcherHost to cancel the download from this
[email protected]6cade212008-12-03 00:32:22919// thread, since we can't forward tasks from the file thread to the IO thread
initial.commit09911bf2008-07-26 23:55:29920// reliably (crash on shutdown race condition).
921void DownloadManager::CancelDownloadRequest(int render_process_id,
922 int request_id) {
923 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10924 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29925 if (!io_thread || !rdh)
926 return;
927 io_thread->message_loop()->PostTask(FROM_HERE,
928 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
929 rdh,
930 render_process_id,
931 request_id));
932}
933
934// static
935void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
936 int render_process_id,
937 int request_id) {
938 rdh->CancelRequest(render_process_id, request_id, false);
939}
940
941void DownloadManager::DownloadCancelled(int32 download_id) {
942 DownloadMap::iterator it = in_progress_.find(download_id);
943 if (it == in_progress_.end())
944 return;
945 DownloadItem* download = it->second;
946
947 CancelDownloadRequest(download->render_process_id(), download->request_id());
948
949 // Clean up will happen when the history system create callback runs if we
950 // don't have a valid db_handle yet.
951 if (download->db_handle() != kUninitializedHandle) {
952 in_progress_.erase(it);
953 NotifyAboutDownloadStop();
954 UpdateHistoryForDownload(download);
955 }
956
957 // Tell the file manager to cancel the download.
958 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
959 file_loop_->PostTask(FROM_HERE,
960 NewRunnableMethod(file_manager_,
961 &DownloadFileManager::CancelDownload,
962 download->id()));
963}
964
965void DownloadManager::PauseDownload(int32 download_id, bool pause) {
966 DownloadMap::iterator it = in_progress_.find(download_id);
967 if (it != in_progress_.end()) {
968 DownloadItem* download = it->second;
969 if (pause == download->is_paused())
970 return;
971
972 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10973 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29974 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
975 if (!io_thread || !rdh)
976 return;
977
978 io_thread->message_loop()->PostTask(FROM_HERE,
979 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
980 rdh,
981 download->render_process_id(),
982 download->request_id(),
983 pause));
984 }
985}
986
987// static
988void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
989 int render_process_id,
990 int request_id,
991 bool pause) {
992 rdh->PauseRequest(render_process_id, request_id, pause);
993}
994
[email protected]7ae7c2cb2009-01-06 23:31:41995bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:32996 // TODO(jcampan): Improve me.
[email protected]2001fe82009-02-23 23:53:14997 FilePath::StringType extension = file_name.Extension();
998 // Drop the leading period.
999 if (extension.size() > 0)
1000 extension = extension.substr(1);
1001 return IsExecutable(extension);
[email protected]9ccbb372008-10-10 18:50:321002}
1003
1004void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411005 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321006 download->Rename(new_path);
1007
1008 // Update the history.
1009
1010 // No update necessary if the download was initiated while in incognito mode.
1011 if (download->db_handle() <= kUninitializedHandle)
1012 return;
1013
[email protected]6cade212008-12-03 00:32:221014 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321015 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1016 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411017 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321018}
1019
initial.commit09911bf2008-07-26 23:55:291020void DownloadManager::RemoveDownload(int64 download_handle) {
1021 DownloadMap::iterator it = downloads_.find(download_handle);
1022 if (it == downloads_.end())
1023 return;
1024
1025 // Make history update.
1026 DownloadItem* download = it->second;
1027 RemoveDownloadFromHistory(download);
1028
1029 // Remove from our tables and delete.
1030 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321031 it = dangerous_finished_.find(download->id());
1032 if (it != dangerous_finished_.end())
1033 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291034
1035 // Tell observers to refresh their views.
1036 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
[email protected]6f712872008-11-07 00:35:361037
1038 delete download;
initial.commit09911bf2008-07-26 23:55:291039}
1040
[email protected]e93d2822009-01-30 05:59:591041int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1042 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291043 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1044
initial.commit09911bf2008-07-26 23:55:291045 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281046 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291047 while (it != downloads_.end()) {
1048 DownloadItem* download = it->second;
1049 DownloadItem::DownloadState state = download->state();
1050 if (download->start_time() >= remove_begin &&
1051 (remove_end.is_null() || download->start_time() < remove_end) &&
1052 (state == DownloadItem::COMPLETE ||
1053 state == DownloadItem::CANCELLED)) {
1054 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561055 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581056
1057 // Also remove it from any completed dangerous downloads.
1058 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1059 if (dit != dangerous_finished_.end())
1060 dangerous_finished_.erase(dit);
1061
[email protected]78b8fcc92009-03-31 17:36:281062 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:291063
initial.commit09911bf2008-07-26 23:55:291064 continue;
1065 }
1066
1067 ++it;
1068 }
1069
1070 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281071 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291072 if (num_deleted > 0)
1073 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1074
[email protected]78b8fcc92009-03-31 17:36:281075 // Delete the download items after updating the observers.
1076 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1077 pending_deletes.clear();
1078
initial.commit09911bf2008-07-26 23:55:291079 return num_deleted;
1080}
1081
[email protected]e93d2822009-01-30 05:59:591082int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1083 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291084}
1085
1086// Initiate a download of a specific URL. We send the request to the
1087// ResourceDispatcherHost, and let it send us responses like a regular
1088// download.
1089void DownloadManager::DownloadUrl(const GURL& url,
1090 const GURL& referrer,
1091 WebContents* web_contents) {
1092 DCHECK(web_contents);
1093 file_manager_->DownloadUrl(url,
1094 referrer,
[email protected]4566f132009-03-12 01:55:131095 web_contents->process()->pid(),
initial.commit09911bf2008-07-26 23:55:291096 web_contents->render_view_host()->routing_id(),
1097 request_context_.get());
1098}
1099
1100void DownloadManager::NotifyAboutDownloadStart() {
[email protected]bfd04a62009-02-01 18:16:561101 NotificationService::current()->Notify(
1102 NotificationType::DOWNLOAD_START,
1103 NotificationService::AllSources(),
1104 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291105}
1106
1107void DownloadManager::NotifyAboutDownloadStop() {
[email protected]bfd04a62009-02-01 18:16:561108 NotificationService::current()->Notify(
1109 NotificationType::DOWNLOAD_STOP,
1110 NotificationService::AllSources(),
1111 NotificationService::NoDetails());
initial.commit09911bf2008-07-26 23:55:291112}
1113
[email protected]7ae7c2cb2009-01-06 23:31:411114void DownloadManager::GenerateExtension(
1115 const FilePath& file_name,
1116 const std::string& mime_type,
1117 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291118 // We're worried about three things here:
1119 //
1120 // 1) Security. Many sites let users upload content, such as buddy icons, to
1121 // their web sites. We want to mitigate the case where an attacker
1122 // supplies a malicious executable with an executable file extension but an
1123 // honest site serves the content with a benign content type, such as
1124 // image/jpeg.
1125 //
1126 // 2) Usability. If the site fails to provide a file extension, we want to
1127 // guess a reasonable file extension based on the content type.
1128 //
1129 // 3) Shell integration. Some file extensions automatically integrate with
1130 // the shell. We block these extensions to prevent a malicious web site
1131 // from integrating with the user's shell.
1132
[email protected]7ae7c2cb2009-01-06 23:31:411133 static const FilePath::CharType default_extension[] =
1134 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291135
1136 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411137 FilePath::StringType extension(
1138 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291139
[email protected]b7f05882009-02-22 01:21:561140#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291141 // Rename shell-integrated extensions.
1142 if (win_util::IsShellIntegratedExtension(extension))
1143 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561144#endif
initial.commit09911bf2008-07-26 23:55:291145
1146 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411147 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411148 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291149 if (mime_type == mime_type_from_extension) {
1150 // The hinted extension matches the mime type. It looks like a winner.
1151 generated_extension->swap(extension);
1152 return;
1153 }
1154
1155 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1156 // We want to be careful about executable extensions. The worry here is
1157 // that a trusted web site could be tricked into dropping an executable file
1158 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101159 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291160 // We couldn't find a good extension for this content type. Use a dummy
1161 // extension instead.
1162 extension.assign(default_extension);
1163 }
1164 }
1165
1166 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101167 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291168 } else {
[email protected]6cade212008-12-03 00:32:221169 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291170 // 1. New extension is not ".txt"
1171 // 2. New extension is not the same as the already existing extension.
1172 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411173 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291174 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1175 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371176 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1177 // servers, i.e. bug 5772.
[email protected]7ae7c2cb2009-01-06 23:31:411178 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101179 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171180 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411181 append_extension != extension &&
[email protected]e106457b2009-03-25 22:43:371182 !IsExecutable(append_extension) &&
1183 (append_extension != FILE_PATH_LITERAL("tar") ||
1184 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171185 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291186 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171187 }
initial.commit09911bf2008-07-26 23:55:291188 }
1189 }
1190
1191 generated_extension->swap(extension);
1192}
1193
1194void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:411195 FilePath* generated_name) {
1196 *generated_name = FilePath::FromWStringHack(
[email protected]8ac1a752008-07-31 19:40:371197 net::GetSuggestedFilename(GURL(info->url),
1198 info->content_disposition,
[email protected]7ae7c2cb2009-01-06 23:31:411199 L"download"));
1200 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291201
[email protected]7ae7c2cb2009-01-06 23:31:411202 GenerateSafeFilename(info->mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291203}
1204
1205void DownloadManager::AddObserver(Observer* observer) {
1206 observers_.AddObserver(observer);
1207 observer->ModelChanged();
1208}
1209
1210void DownloadManager::RemoveObserver(Observer* observer) {
1211 observers_.RemoveObserver(observer);
1212}
1213
1214// Post Windows Shell operations to the Download thread, to avoid blocking the
1215// user interface.
1216void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1217 DCHECK(file_manager_);
1218 file_loop_->PostTask(FROM_HERE,
1219 NewRunnableMethod(file_manager_,
1220 &DownloadFileManager::OnShowDownloadInShell,
[email protected]7ae7c2cb2009-01-06 23:31:411221 FilePath(download->full_path())));
initial.commit09911bf2008-07-26 23:55:291222}
1223
[email protected]8f783752009-04-01 23:33:451224void DownloadManager::OpenDownload(const DownloadItem* download,
1225 gfx::NativeView parent_window) {
1226 FilePath::StringType extension = download->full_path().Extension();
1227 // Drop the leading period.
1228 if (extension.size() > 0)
1229 extension = extension.substr(1);
1230
1231 // Open Chrome extensions with ExtenstionsService. For everthing else do shell
1232 // execute.
1233 if (extension == chrome::kExtensionFileExtension) {
1234 OpenChromeExtension(download->full_path());
1235 } else {
1236 OpenDownloadInShell(download, parent_window);
1237 }
1238}
1239
1240void DownloadManager::OpenChromeExtension(const FilePath& full_path) {
[email protected]d81706b82009-04-03 20:28:441241 // Temporary: Ask the user if it's okay to install the extension. This should
1242 // be replaced with the actual extension installation UI when it is avaiable.
1243#if defined(OS_WIN)
1244 if (win_util::MessageBox(GetActiveWindow(),
1245 L"Are you sure you want to install this extension?\n\n"
1246 L"This is a temporary message and it will be removed when extensions UI "
1247 L"is finalized.",
1248 l10n_util::GetString(IDS_PRODUCT_NAME).c_str(), MB_OKCANCEL) == IDOK) {
1249 ExtensionsService* extensions_service = profile_->GetExtensionsService();
1250 extensions_service->InstallExtension(full_path);
1251 }
1252#else
1253 // TODO(port): Needs CreateChromeWindow.
[email protected]8f783752009-04-01 23:33:451254 ExtensionsService* extensions_service = profile_->GetExtensionsService();
1255 extensions_service->InstallExtension(full_path);
[email protected]d81706b82009-04-03 20:28:441256#endif
1257
[email protected]8f783752009-04-01 23:33:451258}
1259
initial.commit09911bf2008-07-26 23:55:291260void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591261 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291262 DCHECK(file_manager_);
1263 file_loop_->PostTask(FROM_HERE,
1264 NewRunnableMethod(file_manager_,
1265 &DownloadFileManager::OnOpenDownloadInShell,
1266 download->full_path(), download->url(), parent_window));
1267}
1268
[email protected]7ae7c2cb2009-01-06 23:31:411269void DownloadManager::OpenFilesOfExtension(
1270 const FilePath::StringType& extension, bool open) {
initial.commit09911bf2008-07-26 23:55:291271 if (open && !IsExecutable(extension))
1272 auto_open_.insert(extension);
1273 else
1274 auto_open_.erase(extension);
1275 SaveAutoOpens();
1276}
1277
[email protected]7ae7c2cb2009-01-06 23:31:411278bool DownloadManager::ShouldOpenFileExtension(
1279 const FilePath::StringType& extension) {
[email protected]8c756ac2009-01-30 23:36:411280 // Special-case Chrome extensions as always-open.
initial.commit09911bf2008-07-26 23:55:291281 if (!IsExecutable(extension) &&
[email protected]8c756ac2009-01-30 23:36:411282 (auto_open_.find(extension) != auto_open_.end() ||
1283 extension == chrome::kExtensionFileExtension))
1284 return true;
initial.commit09911bf2008-07-26 23:55:291285 return false;
1286}
1287
[email protected]7b73d992008-12-15 20:56:461288static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291289 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461290 "text/javascript",
1291 "text/javascript;version=*",
[email protected]60ff8f912008-12-05 07:58:391292 // Some sites use binary/octet-stream to mean application/octet-stream.
1293 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461294 "binary/octet-stream"
1295};
initial.commit09911bf2008-07-26 23:55:291296
[email protected]7b73d992008-12-15 20:56:461297static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291298 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461299 "application/*+xml",
1300 "application/xml"
1301};
initial.commit09911bf2008-07-26 23:55:291302
[email protected]7b73d992008-12-15 20:56:461303// static
1304bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411305 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461306 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1307 return true;
1308 }
[email protected]bae0ea12009-02-14 01:20:411309 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461310 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1311 return false;
1312 }
1313 // We consider only other application types to be executable.
1314 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291315}
1316
[email protected]7ae7c2cb2009-01-06 23:31:411317bool DownloadManager::IsExecutable(const FilePath::StringType& extension) {
[email protected]64da0b932009-02-24 02:30:041318#if defined(OS_WIN)
1319 if (!IsStringASCII(extension))
1320 return false;
1321 std::string ascii_extension = WideToASCII(extension);
1322 StringToLowerASCII(&ascii_extension);
1323
1324 return exe_types_.find(ascii_extension) != exe_types_.end();
1325#elif defined(OS_POSIX)
1326 // TODO(port): we misght not want to call this function on other platforms.
1327 // Figure it out.
1328 NOTIMPLEMENTED();
1329 return false;
1330#endif
initial.commit09911bf2008-07-26 23:55:291331}
1332
1333void DownloadManager::ResetAutoOpenFiles() {
1334 auto_open_.clear();
1335 SaveAutoOpens();
1336}
1337
1338bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1339 return !auto_open_.empty();
1340}
1341
1342void DownloadManager::SaveAutoOpens() {
1343 PrefService* prefs = profile_->GetPrefs();
1344 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411345 FilePath::StringType extensions;
1346 for (std::set<FilePath::StringType>::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291347 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411348 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291349 }
1350 if (!extensions.empty())
1351 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561352
1353 std::wstring extensions_w;
1354#if defined(OS_WIN)
1355 extensions_w = extensions;
1356#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141357 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561358#endif
1359
1360 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291361 }
1362}
1363
[email protected]561abe62009-04-06 18:08:341364void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361365 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291366 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071367 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411368 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291369 ContinueStartDownload(info, path);
1370}
1371
1372void DownloadManager::FileSelectionCanceled(void* params) {
1373 // The user didn't pick a place to save the file, so need to cancel the
1374 // download that's already in progress to the temporary location.
1375 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1376 file_loop_->PostTask(FROM_HERE,
1377 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1378 info->download_id));
1379}
1380
[email protected]7ae7c2cb2009-01-06 23:31:411381void DownloadManager::DeleteDownload(const FilePath& path) {
1382 file_loop_->PostTask(FROM_HERE, NewRunnableFunction(
1383 &DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321384}
1385
1386
1387void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1388 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1389 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1390 download->UpdateObservers();
1391
1392 // If the download is not complete, nothing to do. The required
1393 // post-processing will be performed when it does complete.
1394 if (download->state() != DownloadItem::COMPLETE)
1395 return;
1396
1397 file_loop_->PostTask(FROM_HERE,
1398 NewRunnableMethod(this,
1399 &DownloadManager::ProceedWithFinishedDangerousDownload,
1400 download->db_handle(), download->full_path(),
1401 download->original_name()));
1402}
1403
[email protected]763f946a2009-01-06 19:04:391404void DownloadManager::GenerateSafeFilename(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411405 FilePath* file_name) {
1406 // Make sure we get the right file extension
1407 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391408 GenerateExtension(*file_name, mime_type, &extension);
1409 file_util::ReplaceExtension(file_name, extension);
1410
[email protected]2b2f8f72009-02-24 22:42:051411#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391412 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411413 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391414 DCHECK(!leaf_name.empty());
1415 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411416 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1417 *file_name = file_name->DirName();
1418 if (file_name->value() == FilePath::kCurrentDirectory) {
1419 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391420 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411421 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391422 }
1423 }
[email protected]b7f05882009-02-22 01:21:561424#elif defined(OS_POSIX)
1425 NOTIMPLEMENTED();
1426#endif
[email protected]763f946a2009-01-06 19:04:391427}
1428
initial.commit09911bf2008-07-26 23:55:291429// Operations posted to us from the history service ----------------------------
1430
1431// The history service has retrieved all download entries. 'entries' contains
1432// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1433void DownloadManager::OnQueryDownloadEntriesComplete(
1434 std::vector<DownloadCreateInfo>* entries) {
1435 for (size_t i = 0; i < entries->size(); ++i) {
1436 DownloadItem* download = new DownloadItem(entries->at(i));
1437 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1438 downloads_[download->db_handle()] = download;
1439 download->set_manager(this);
1440 }
1441 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1442}
1443
initial.commit09911bf2008-07-26 23:55:291444// Once the new DownloadItem's creation info has been committed to the history
1445// service, we associate the DownloadItem with the db handle, update our
1446// 'downloads_' map and inform observers.
1447void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1448 int64 db_handle) {
1449 DownloadMap::iterator it = in_progress_.find(info.download_id);
1450 DCHECK(it != in_progress_.end());
1451
1452 DownloadItem* download = it->second;
1453 DCHECK(download->db_handle() == kUninitializedHandle);
1454 download->set_db_handle(db_handle);
1455
1456 // Insert into our full map.
1457 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1458 downloads_[download->db_handle()] = download;
1459
1460 // The 'contents' may no longer exist if the user closed the tab before we get
1461 // this start completion event. If it does, tell the origin WebContents to
1462 // display its download shelf.
1463 TabContents* contents =
[email protected]a3a1d142008-12-19 00:42:301464 tab_util::GetWebContentsByID(info.render_process_id, info.render_view_id);
initial.commit09911bf2008-07-26 23:55:291465
1466 // If the contents no longer exists or is no longer active, we start the
1467 // download in the last active browser. This is not ideal but better than
1468 // fully hiding the download from the user. Note: non active means that the
1469 // user navigated away from the tab contents. This has nothing to do with
1470 // tab selection.
1471 if (!contents || !contents->is_active()) {
1472 Browser* last_active = BrowserList::GetLastActive();
1473 if (last_active)
1474 contents = last_active->GetSelectedTabContents();
1475 }
1476
1477 if (contents)
1478 contents->OnStartDownload(download);
1479
1480 // Inform interested objects about the new download.
1481 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1482 NotifyAboutDownloadStart();
1483
1484 // If this download has been completed before we've received the db handle,
1485 // post one final message to the history service so that it can be properly
1486 // in sync with the DownloadItem's completion status, and also inform any
1487 // observers so that they get more than just the start notification.
1488 if (download->state() != DownloadItem::IN_PROGRESS) {
1489 in_progress_.erase(it);
1490 NotifyAboutDownloadStop();
1491 UpdateHistoryForDownload(download);
1492 download->UpdateObservers();
1493 }
1494}
1495
1496// Called when the history service has retrieved the list of downloads that
1497// match the search text.
1498void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1499 std::vector<int64>* results) {
1500 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1501 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1502 if (!requestor)
1503 return;
1504
1505 std::vector<DownloadItem*> searched_downloads;
1506 for (std::vector<int64>::iterator it = results->begin();
1507 it != results->end(); ++it) {
1508 DownloadMap::iterator dit = downloads_.find(*it);
1509 if (dit != downloads_.end())
1510 searched_downloads.push_back(dit->second);
1511 }
1512
1513 requestor->SetDownloads(searched_downloads);
1514}
[email protected]905a08d2008-11-19 07:24:121515
[email protected]6cade212008-12-03 00:32:221516// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121517void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411518 last_download_path_ = FilePath();
[email protected]905a08d2008-11-19 07:24:121519}