blob: 71b6ea64fa6217b98be4493d741887021270bfaf [file] [log] [blame]
[email protected]21ca982c2010-01-26 22:49:551// Copyright (c) 2010 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]cdaa8652008-09-13 02:48:595#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
[email protected]21ca982c2010-01-26 22:49:558#include "app/resource_bundle.h"
[email protected]2041cf342010-02-19 03:15:599#include "base/callback.h"
initial.commit09911bf2008-07-26 23:55:2910#include "base/file_util.h"
11#include "base/logging.h"
12#include "base/message_loop.h"
13#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1414#include "base/rand_util.h"
[email protected]807204142009-05-05 03:31:4415#include "base/stl_util-inl.h"
initial.commit09911bf2008-07-26 23:55:2916#include "base/string_util.h"
[email protected]1b5044d2009-02-24 00:04:1417#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2918#include "base/task.h"
19#include "base/thread.h"
20#include "base/timer.h"
[email protected]d2a8fb72010-01-21 05:31:4221#include "build/build_config.h"
initial.commit09911bf2008-07-26 23:55:2922#include "chrome/browser/browser_list.h"
23#include "chrome/browser/browser_process.h"
[email protected]d83d03aa2009-11-02 21:44:3724#include "chrome/browser/chrome_thread.h"
[email protected]cdaa8652008-09-13 02:48:5925#include "chrome/browser/download/download_file.h"
[email protected]e9ef0a62009-08-11 22:50:1326#include "chrome/browser/download/download_util.h"
[email protected]866930682009-08-18 22:53:4727#include "chrome/browser/extensions/crx_installer.h"
[email protected]2a464a92009-08-01 17:58:3528#include "chrome/browser/extensions/extension_install_ui.h"
[email protected]8f783752009-04-01 23:33:4529#include "chrome/browser/extensions/extensions_service.h"
[email protected]be180c802009-10-23 06:33:3130#include "chrome/browser/net/chrome_url_request_context.h"
[email protected]14a000d2010-04-29 21:44:2431#include "chrome/browser/platform_util.h"
[email protected]052313b2010-02-19 09:43:0832#include "chrome/browser/pref_service.h"
initial.commit09911bf2008-07-26 23:55:2933#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2634#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2535#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3236#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]21ca982c2010-01-26 22:49:5537#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]57c6a652009-05-04 07:58:3438#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]d2a8fb72010-01-21 05:31:4239#include "chrome/browser/tab_contents/tab_util.h"
[email protected]4a0380c2009-07-26 07:25:3240#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2941#include "chrome/common/chrome_paths.h"
[email protected]5b1a0e22009-05-26 19:00:5842#include "chrome/common/extensions/extension.h"
[email protected]6657afa62009-11-04 02:15:2043#include "chrome/common/extensions/user_script.h"
[email protected]91e1bd82009-09-03 22:04:4044#include "chrome/common/notification_service.h"
45#include "chrome/common/notification_type.h"
initial.commit09911bf2008-07-26 23:55:2946#include "chrome/common/pref_names.h"
[email protected]46072d42008-07-28 14:49:3547#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4448#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2749#include "grit/generated_resources.h"
[email protected]21ca982c2010-01-26 22:49:5550#include "grit/theme_resources.h"
initial.commit09911bf2008-07-26 23:55:2951#include "net/base/mime_util.h"
52#include "net/base/net_util.h"
53#include "net/url_request/url_request_context.h"
54
[email protected]b7f05882009-02-22 01:21:5655#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2556#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5657#include "base/registry.h"
58#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3259#endif
60
[email protected]21ca982c2010-01-26 22:49:5561namespace {
62
initial.commit09911bf2008-07-26 23:55:2963// Periodically update our observers.
64class DownloadItemUpdateTask : public Task {
65 public:
66 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
67 void Run() { if (item_) item_->UpdateObservers(); }
68
69 private:
70 DownloadItem* item_;
71};
72
73// Update frequency (milliseconds).
[email protected]21ca982c2010-01-26 22:49:5574const int kUpdateTimeMs = 1000;
initial.commit09911bf2008-07-26 23:55:2975
76// Our download table ID starts at 1, so we use 0 to represent a download that
77// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2278// database handles in incognito mode starting at -1 and progressively getting
79// more negative.
[email protected]21ca982c2010-01-26 22:49:5580const int kUninitializedHandle = 0;
initial.commit09911bf2008-07-26 23:55:2981
[email protected]b0ab1d42010-02-24 19:29:2882// Used to sort download items based on descending start time.
83bool CompareStartTime(DownloadItem* first, DownloadItem* second) {
84 return first->start_time() > second->start_time();
85}
86
[email protected]21ca982c2010-01-26 22:49:5587} // namespace
88
initial.commit09911bf2008-07-26 23:55:2989// DownloadItem implementation -------------------------------------------------
90
91// Constructor for reading from the history service.
92DownloadItem::DownloadItem(const DownloadCreateInfo& info)
93 : id_(-1),
94 full_path_(info.path),
95 url_(info.url),
[email protected]e435d6b72009-07-25 03:15:5896 referrer_url_(info.referrer_url),
97 mime_type_(info.mime_type),
initial.commit09911bf2008-07-26 23:55:2998 total_bytes_(info.total_bytes),
99 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56100 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29101 state_(static_cast<DownloadState>(info.state)),
102 start_time_(info.start_time),
103 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29104 manager_(NULL),
105 is_paused_(false),
106 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56107 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28108 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56109 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29110 render_process_id_(-1),
[email protected]6aa4a1c02010-01-15 18:49:58111 request_id_(-1),
112 save_as_(false),
[email protected]b0ab1d42010-02-24 19:29:28113 is_otr_(false),
[email protected]5748eb82010-01-20 15:12:37114 is_extension_install_(info.is_extension_install),
[email protected]6aa4a1c02010-01-15 18:49:58115 name_finalized_(false),
116 is_temporary_(false) {
initial.commit09911bf2008-07-26 23:55:29117 if (state_ == IN_PROGRESS)
118 state_ = CANCELLED;
119 Init(false /* don't start progress timer */);
120}
121
122// Constructor for DownloadItem created via user action in the main thread.
123DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41124 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16125 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32126 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42127 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58128 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41129 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59130 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29131 int64 download_size,
132 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32133 int request_id,
[email protected]67f373a2009-09-22 02:44:51134 bool is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57135 bool save_as,
[email protected]b0ab1d42010-02-24 19:29:28136 bool is_otr,
[email protected]6aa4a1c02010-01-15 18:49:58137 bool is_extension_install,
138 bool is_temporary)
initial.commit09911bf2008-07-26 23:55:29139 : id_(download_id),
140 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16141 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29142 url_(url),
[email protected]494c06e2009-07-25 01:06:42143 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58144 mime_type_(mime_type),
initial.commit09911bf2008-07-26 23:55:29145 total_bytes_(download_size),
146 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56147 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29148 state_(IN_PROGRESS),
149 start_time_(start_time),
150 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29151 manager_(NULL),
152 is_paused_(false),
153 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56154 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28155 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56156 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29157 render_process_id_(render_process_id),
[email protected]67f373a2009-09-22 02:44:51158 request_id_(request_id),
[email protected]a60c8ae2009-12-25 06:50:57159 save_as_(save_as),
[email protected]b0ab1d42010-02-24 19:29:28160 is_otr_(is_otr),
[email protected]6aa4a1c02010-01-15 18:49:58161 is_extension_install_(is_extension_install),
162 name_finalized_(false),
163 is_temporary_(is_temporary) {
initial.commit09911bf2008-07-26 23:55:29164 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]6aa4a1c02010-01-15 18:49:58190void DownloadItem::NotifyObserversDownloadFileCompleted() {
191 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadFileCompleted(this));
192}
193
[email protected]45e3c122009-04-07 19:58:03194void DownloadItem::NotifyObserversDownloadOpened() {
195 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
196}
197
initial.commit09911bf2008-07-26 23:55:29198// If we've received more data than we were expecting (bad server info?), revert
199// to 'unknown size mode'.
200void DownloadItem::UpdateSize(int64 bytes_so_far) {
201 received_bytes_ = bytes_so_far;
202 if (received_bytes_ > total_bytes_)
203 total_bytes_ = 0;
204}
205
206// Updates from the download thread may have been posted while this download
207// was being cancelled in the UI thread, so we'll accept them unless we're
208// complete.
209void DownloadItem::Update(int64 bytes_so_far) {
210 if (state_ == COMPLETE) {
211 NOTREACHED();
212 return;
213 }
214 UpdateSize(bytes_so_far);
215 UpdateObservers();
216}
217
[email protected]6cade212008-12-03 00:32:22218// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29219void DownloadItem::Cancel(bool update_history) {
220 if (state_ != IN_PROGRESS) {
221 // Small downloads might be complete before this method has a chance to run.
222 return;
223 }
224 state_ = CANCELLED;
225 UpdateObservers();
226 StopProgressTimer();
227 if (update_history)
228 manager_->DownloadCancelled(id_);
229}
230
231void DownloadItem::Finished(int64 size) {
232 state_ = COMPLETE;
233 UpdateSize(size);
initial.commit09911bf2008-07-26 23:55:29234 StopProgressTimer();
235}
236
[email protected]9ccbb372008-10-10 18:50:32237void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29238 Cancel(true);
239 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32240 if (delete_on_disk)
241 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29242 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22243 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29244}
245
246void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59247 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14248 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29249}
250
251void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14252 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29253}
254
[email protected]e93d2822009-01-30 05:59:59255bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29256 if (total_bytes_ <= 0)
257 return false; // We never received the content_length for this download.
258
259 int64 speed = CurrentSpeed();
260 if (speed == 0)
261 return false;
262
263 *remaining =
[email protected]e93d2822009-01-30 05:59:59264 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29265 return true;
266}
267
268int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56269 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
270 int64 diff_ms = diff.InMilliseconds();
271 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29272}
273
274int DownloadItem::PercentComplete() const {
275 int percent = -1;
276 if (total_bytes_ > 0)
277 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
278 return percent;
279}
280
[email protected]7ae7c2cb2009-01-06 23:31:41281void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29282 DCHECK(!full_path.empty());
283 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41284 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29285}
286
287void DownloadItem::TogglePause() {
288 DCHECK(state_ == IN_PROGRESS);
289 manager_->PauseDownload(id_, !is_paused_);
290 is_paused_ = !is_paused_;
291 UpdateObservers();
292}
293
[email protected]7ae7c2cb2009-01-06 23:31:41294FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32295 if (safety_state_ == DownloadItem::SAFE)
296 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16297 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41298 FilePath name(original_name_);
[email protected]5a2388a2010-03-26 16:13:39299 download_util::AppendNumberToPath(&name, path_uniquifier_);
[email protected]7a256ea2008-10-17 17:34:16300 return name;
301 }
[email protected]9ccbb372008-10-10 18:50:32302 return original_name_;
303}
304
initial.commit09911bf2008-07-26 23:55:29305// DownloadManager implementation ----------------------------------------------
306
307// static
308void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
309 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
310 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32311 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
312
313 // The default download path is userprofile\download.
[email protected]290c9702010-03-09 04:01:36314 const FilePath& default_download_path =
315 download_util::GetDefaultDownloadDirectory();
[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]38233e62010-04-26 04:43:36324 FilePath current_download_dir = prefs->GetFilePath(
325 prefs::kDownloadDefaultDirectory);
[email protected]290c9702010-03-09 04:01:36326 if (download_util::DownloadPathIsDangerous(current_download_dir)) {
[email protected]38233e62010-04-26 04:43:36327 prefs->SetFilePath(prefs::kDownloadDefaultDirectory,
328 default_download_path);
[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),
[email protected]d2a8fb72010-01-21 05:31:42337 file_manager_(NULL),
338 fake_db_handle_(kUninitializedHandle - 1) {
initial.commit09911bf2008-07-26 23:55:29339}
340
341DownloadManager::~DownloadManager() {
[email protected]b0ab1d42010-02-24 19:29:28342 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
343
initial.commit09911bf2008-07-26 23:55:29344 if (shutdown_needed_)
345 Shutdown();
346}
347
348void DownloadManager::Shutdown() {
349 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
350
351 // Stop receiving download updates
352 file_manager_->RemoveDownloadManager(this);
353
354 // Stop making history service requests
355 cancelable_consumer_.CancelAllRequests();
356
357 // 'in_progress_' may contain DownloadItems that have not finished the start
358 // complete (from the history service) and thus aren't in downloads_.
359 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32360 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29361 for (; it != in_progress_.end(); ++it) {
362 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32363 if (download->safety_state() == DownloadItem::DANGEROUS) {
364 // Forget about any download that the user did not approve.
365 // Note that we cannot call download->Remove() this would invalidate our
366 // iterator.
367 to_remove.insert(download);
368 continue;
initial.commit09911bf2008-07-26 23:55:29369 }
[email protected]9ccbb372008-10-10 18:50:32370 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
371 download->Cancel(false);
372 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29373 if (download->db_handle() == kUninitializedHandle) {
374 // An invalid handle means that 'download' does not yet exist in
375 // 'downloads_', so we have to delete it here.
376 delete download;
377 }
378 }
379
[email protected]9ccbb372008-10-10 18:50:32380 // 'dangerous_finished_' contains all complete downloads that have not been
381 // approved. They should be removed.
382 it = dangerous_finished_.begin();
383 for (; it != dangerous_finished_.end(); ++it)
384 to_remove.insert(it->second);
385
386 // Remove the dangerous download that are not approved.
387 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
388 rm_it != to_remove.end(); ++rm_it) {
389 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32390 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32391 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32392 // Same as above, delete the download if it is not in 'downloads_' (as the
393 // Remove() call above won't have deleted it).
394 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32395 delete download;
396 }
397 to_remove.clear();
398
initial.commit09911bf2008-07-26 23:55:29399 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32400 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29401 STLDeleteValues(&downloads_);
402
403 file_manager_ = NULL;
404
405 // Save our file extensions to auto open.
406 SaveAutoOpens();
407
408 // Make sure the save as dialog doesn't notify us back if we're gone before
409 // it returns.
410 if (select_file_dialog_.get())
411 select_file_dialog_->ListenerDestroyed();
412
413 shutdown_needed_ = false;
414}
415
416// Issue a history query for downloads matching 'search_text'. If 'search_text'
417// is empty, return all downloads that we know about.
418void DownloadManager::GetDownloads(Observer* observer,
419 const std::wstring& search_text) {
[email protected]b0ab1d42010-02-24 19:29:28420 std::vector<DownloadItem*> otr_downloads;
421
422 if (profile_->IsOffTheRecord() && search_text.empty()) {
423 // List all incognito downloads and add that to the downloads the parent
424 // profile lists.
425 otr_downloads.reserve(downloads_.size());
426 for (DownloadMap::iterator it = downloads_.begin();
427 it != downloads_.end(); ++it) {
428 DownloadItem* download = it->second;
429 if (download->is_otr() && !download->is_extension_install() &&
430 !download->is_temporary()) {
431 otr_downloads.push_back(download);
432 }
433 }
434 }
435
436 profile_->GetOriginalProfile()->GetDownloadManager()->
437 DoGetDownloads(observer, search_text, otr_downloads);
438}
439
440void DownloadManager::DoGetDownloads(
441 Observer* observer,
442 const std::wstring& search_text,
443 std::vector<DownloadItem*>& otr_downloads) {
initial.commit09911bf2008-07-26 23:55:29444 DCHECK(observer);
445
446 // Return a empty list if we've not yet received the set of downloads from the
447 // history system (we'll update all observers once we get that list in
448 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
initial.commit09911bf2008-07-26 23:55:29449 if (downloads_.empty()) {
[email protected]b0ab1d42010-02-24 19:29:28450 observer->SetDownloads(otr_downloads);
initial.commit09911bf2008-07-26 23:55:29451 return;
452 }
453
[email protected]b0ab1d42010-02-24 19:29:28454 std::vector<DownloadItem*> download_copy;
initial.commit09911bf2008-07-26 23:55:29455 // We already know all the downloads and there is no filter, so just return a
456 // copy to the observer.
457 if (search_text.empty()) {
458 download_copy.reserve(downloads_.size());
459 for (DownloadMap::iterator it = downloads_.begin();
460 it != downloads_.end(); ++it) {
[email protected]67f373a2009-09-22 02:44:51461 if (it->second->db_handle() > kUninitializedHandle)
462 download_copy.push_back(it->second);
initial.commit09911bf2008-07-26 23:55:29463 }
464
[email protected]b0ab1d42010-02-24 19:29:28465 // Merge sort based on start time.
466 std::vector<DownloadItem*> merged_downloads;
467 std::merge(otr_downloads.begin(), otr_downloads.end(),
468 download_copy.begin(), download_copy.end(),
469 std::back_inserter(merged_downloads),
470 CompareStartTime);
471
initial.commit09911bf2008-07-26 23:55:29472 // We retain ownership of the DownloadItems.
[email protected]b0ab1d42010-02-24 19:29:28473 observer->SetDownloads(merged_downloads);
initial.commit09911bf2008-07-26 23:55:29474 return;
475 }
476
[email protected]b0ab1d42010-02-24 19:29:28477 DCHECK(otr_downloads.empty());
478
initial.commit09911bf2008-07-26 23:55:29479 // Issue a request to the history service for a list of downloads matching
480 // our search text.
481 HistoryService* hs =
482 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
483 if (hs) {
484 HistoryService::Handle h =
485 hs->SearchDownloads(search_text,
486 &cancelable_consumer_,
487 NewCallback(this,
488 &DownloadManager::OnSearchComplete));
489 cancelable_consumer_.SetClientData(hs, h, observer);
490 }
491}
492
[email protected]6aa4a1c02010-01-15 18:49:58493void DownloadManager::GetTemporaryDownloads(Observer* observer,
494 const FilePath& dir_path) {
495 DCHECK(observer);
496
497 std::vector<DownloadItem*> download_copy;
498
499 for (DownloadMap::iterator it = downloads_.begin();
500 it != downloads_.end(); ++it) {
501 if (it->second->is_temporary() &&
502 it->second->full_path().DirName() == dir_path)
503 download_copy.push_back(it->second);
504 }
505
506 observer->SetDownloads(download_copy);
507}
508
[email protected]8ddbd66a2010-05-21 16:38:34509void DownloadManager::GetAllDownloads(Observer* observer,
510 const FilePath& dir_path) {
511 DCHECK(observer);
512
513 std::vector<DownloadItem*> download_copy;
514
515 for (DownloadMap::iterator it = downloads_.begin();
516 it != downloads_.end(); ++it) {
517 if (!it->second->is_temporary() &&
518 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
519 download_copy.push_back(it->second);
520 }
521
522 observer->SetDownloads(download_copy);
523}
524
[email protected]c4a530b2010-03-08 17:33:03525void DownloadManager::GetCurrentDownloads(Observer* observer,
526 const FilePath& dir_path) {
527 DCHECK(observer);
528
529 std::vector<DownloadItem*> download_copy;
530
531 for (DownloadMap::iterator it = downloads_.begin();
532 it != downloads_.end(); ++it) {
533 if (!it->second->is_temporary() &&
534 (it->second->state() == DownloadItem::IN_PROGRESS ||
535 it->second->safety_state() == DownloadItem::DANGEROUS) &&
536 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
537 download_copy.push_back(it->second);
538 }
539
540 observer->SetDownloads(download_copy);
541}
542
initial.commit09911bf2008-07-26 23:55:29543// Query the history service for information about all persisted downloads.
544bool DownloadManager::Init(Profile* profile) {
545 DCHECK(profile);
546 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
547 shutdown_needed_ = true;
548
549 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31550 request_context_getter_ = profile_->GetRequestContext();
initial.commit09911bf2008-07-26 23:55:29551
552 // 'incognito mode' will have access to past downloads, but we won't store
553 // information about new downloads while in that mode.
554 QueryHistoryForDownloads();
555
[email protected]024f2f02010-04-30 22:51:46556 // Cleans up entries only when called for the first time. Subsequent calls are
557 // a no op.
558 CleanUpInProgressHistoryEntries();
559
initial.commit09911bf2008-07-26 23:55:29560 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
561 if (!rdh) {
562 NOTREACHED();
563 return false;
564 }
565
566 file_manager_ = rdh->download_file_manager();
567 if (!file_manager_) {
568 NOTREACHED();
569 return false;
570 }
571
initial.commit09911bf2008-07-26 23:55:29572 // Get our user preference state.
573 PrefService* prefs = profile_->GetPrefs();
574 DCHECK(prefs);
575 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
576
initial.commit09911bf2008-07-26 23:55:29577 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
578
[email protected]bb69e9b32008-08-14 23:08:14579 // Ensure that the download directory specified in the preferences exists.
[email protected]d83d03aa2009-11-02 21:44:37580 ChromeThread::PostTask(
581 ChromeThread::FILE, FROM_HERE,
[email protected]309b7642009-12-09 03:08:50582 NewRunnableFunction(&file_util::CreateDirectory, download_path()));
initial.commit09911bf2008-07-26 23:55:29583
[email protected]2b2f8f72009-02-24 22:42:05584 // We store any file extension that should be opened automatically at
585 // download completion in this pref.
initial.commit09911bf2008-07-26 23:55:29586 std::wstring extensions_to_open =
587 prefs->GetString(prefs::kDownloadExtensionsToOpen);
588 std::vector<std::wstring> extensions;
589 SplitString(extensions_to_open, L':', &extensions);
590 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]eccb9d12009-10-28 05:40:09591 if (!extensions[i].empty() && !IsExecutableFile(
592 FilePath::FromWStringHack(extensions[i])))
[email protected]b7f05882009-02-22 01:21:56593 auto_open_.insert(FilePath::FromWStringHack(extensions[i]).value());
initial.commit09911bf2008-07-26 23:55:29594 }
595
[email protected]b0ab1d42010-02-24 19:29:28596 other_download_manager_observer_.reset(
597 new OtherDownloadManagerObserver(this));
598
initial.commit09911bf2008-07-26 23:55:29599 return true;
600}
601
602void DownloadManager::QueryHistoryForDownloads() {
603 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
604 if (hs) {
605 hs->QueryDownloads(
606 &cancelable_consumer_,
607 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
608 }
609}
610
[email protected]024f2f02010-04-30 22:51:46611void DownloadManager::CleanUpInProgressHistoryEntries() {
612 static bool already_cleaned_up = false;
613
614 if (!already_cleaned_up) {
615 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
616 if (hs) {
617 hs->CleanUpInProgressEntries();
618 already_cleaned_up = true;
619 }
620 }
621}
622
initial.commit09911bf2008-07-26 23:55:29623// We have received a message from DownloadFileManager about a new download. We
624// create a download item and store it in our download map, and inform the
625// history system of a new download. Since this method can be called while the
626// history service thread is still reading the persistent state, we do not
627// insert the new DownloadItem into 'downloads_' or inform our observers at this
628// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
629// download creation as a callback from the history thread.
630void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37631 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29632 DCHECK(info);
633
[email protected]a60c8ae2009-12-25 06:50:57634 // Check whether this download is for an extension install or not.
635 if (!info->save_as) { // Allow extensions to be explicitly saved.
636 if (UserScript::HasUserScriptFileExtension(info->url) ||
637 info->mime_type == Extension::kMimeType)
638 info->is_extension_install = true;
639 }
640
[email protected]7d3851d82008-12-12 03:26:07641 // Freeze the user's preference for showing a Save As dialog. We're going to
642 // bounce around a bunch of threads and we don't want to worry about race
643 // conditions where the user changes this pref out from under us.
[email protected]7bc4f702009-09-25 22:12:38644 if (*prompt_for_download_) {
[email protected]486d25442010-03-18 17:34:26645 // But never obey the preference for the following scenarios:
646 // 1) Extension installation. Note that we only care here about the case
647 // where an extension is installed, not when one is downloaded with
648 // "save as...".
649 // 2) Drag-out download. Since we will save to the destination folder that
650 // is dropped to, we should not pop up a Save As dialog.
651 if (!info->is_extension_install && info->save_info.file_path.empty())
[email protected]7bc4f702009-09-25 22:12:38652 info->save_as = true;
653 }
[email protected]7d3851d82008-12-12 03:26:07654
[email protected]8af9d032010-02-10 00:00:32655 if (info->save_info.file_path.empty()) {
656 // Determine the proper path for a download, by either one of the following:
657 // 1) using the default download directory.
658 // 2) prompting the user.
659 FilePath generated_name;
660 GenerateFileNameFromInfo(info, &generated_name);
661 if (info->save_as && !last_download_path_.empty())
662 info->suggested_path = last_download_path_;
663 else
664 info->suggested_path = download_path();
665 info->suggested_path = info->suggested_path.Append(generated_name);
666 } else {
667 info->suggested_path = info->save_info.file_path;
668 }
initial.commit09911bf2008-07-26 23:55:29669
[email protected]8af9d032010-02-10 00:00:32670 if (!info->save_as && info->save_info.file_path.empty()) {
[email protected]4289d9b2009-07-25 21:17:34671 // Downloads can be marked as dangerous for two reasons:
672 // a) They have a dangerous-looking filename
673 // b) They are an extension that is not from the gallery
674 if (IsDangerous(info->suggested_path.BaseName()))
675 info->is_dangerous = true;
[email protected]a60c8ae2009-12-25 06:50:57676 else if (info->is_extension_install &&
[email protected]b7c2f252009-12-08 00:47:23677 !ExtensionsService::IsDownloadFromGallery(info->url,
678 info->referrer_url)) {
[email protected]4289d9b2009-07-25 21:17:34679 info->is_dangerous = true;
680 }
[email protected]e9ebf3fc2008-10-17 22:06:58681 }
682
initial.commit09911bf2008-07-26 23:55:29683 // We need to move over to the download thread because we don't want to stat
684 // the suggested path on the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37685 ChromeThread::PostTask(
686 ChromeThread::FILE, FROM_HERE,
687 NewRunnableMethod(
688 this, &DownloadManager::CheckIfSuggestedPathExists, info));
initial.commit09911bf2008-07-26 23:55:29689}
690
691void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
692 DCHECK(info);
693
694 // Check writability of the suggested path. If we can't write to it, default
695 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41696 FilePath dir = info->suggested_path.DirName();
697 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32698 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29699 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29700 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41701 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29702 }
703
[email protected]8af9d032010-02-10 00:00:32704 // Do not add the path uniquifier if we are saving to a specific path as in
705 // the drag-out case.
[email protected]5a2388a2010-03-26 16:13:39706 if (info->save_info.file_path.empty()) {
707 info->path_uniquifier = download_util::GetUniquePathNumber(
708 info->suggested_path);
709 }
initial.commit09911bf2008-07-26 23:55:29710
[email protected]6cade212008-12-03 00:32:22711 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58712 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41713 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32714 // Create a temporary file to hold the file until the user approves its
715 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41716 FilePath::StringType file_name;
717 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32718 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41719 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32720 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41721 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07722 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41723 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32724 }
725 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16726 } else {
727 // We know the final path, build it if necessary.
728 if (info->path_uniquifier > 0) {
[email protected]5a2388a2010-03-26 16:13:39729 download_util::AppendNumberToPath(&(info->suggested_path),
730 info->path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16731 // Setting path_uniquifier to 0 to make sure we don't try to unique it
732 // later on.
733 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07734 } else if (info->path_uniquifier == -1) {
735 // We failed to find a unique path. We have to prompt the user.
736 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16737 }
[email protected]9ccbb372008-10-10 18:50:32738 }
739
[email protected]8af9d032010-02-10 00:00:32740 if (!info->save_as && info->save_info.file_path.empty()) {
[email protected]7d3851d82008-12-12 03:26:07741 // Create an empty file at the suggested path so that we don't allocate the
742 // same "non-existant" path to multiple downloads.
743 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ff3f632009-10-13 18:43:35744 file_util::WriteFile(info->suggested_path, "", 0);
[email protected]7d3851d82008-12-12 03:26:07745 }
746
initial.commit09911bf2008-07-26 23:55:29747 // Now we return to the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37748 ChromeThread::PostTask(
749 ChromeThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29750 NewRunnableMethod(this,
751 &DownloadManager::OnPathExistenceAvailable,
752 info));
753}
754
755void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37756 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29757 DCHECK(info);
758
[email protected]7d3851d82008-12-12 03:26:07759 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29760 // We must ask the user for the place to put the download.
761 if (!select_file_dialog_.get())
762 select_file_dialog_ = SelectFileDialog::Create(this);
763
[email protected]76543b92009-08-31 17:27:45764 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
765 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08766 SelectFileDialog::FileTypeInfo file_type_info;
767 file_type_info.extensions.resize(1);
768 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24769 if (!file_type_info.extensions[0][0].empty())
770 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08771 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23772 gfx::NativeWindow owning_window =
773 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29774 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34775 string16(),
776 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08777 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30778 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29779 } else {
780 // No prompting for download, just continue with the suggested name.
781 ContinueStartDownload(info, info->suggested_path);
782 }
783}
784
785void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41786 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29787 scoped_ptr<DownloadCreateInfo> infop(info);
788 info->path = target_path;
789
790 DownloadItem* download = NULL;
791 DownloadMap::iterator it = in_progress_.find(info->download_id);
792 if (it == in_progress_.end()) {
793 download = new DownloadItem(info->download_id,
794 info->path,
[email protected]7a256ea2008-10-17 17:34:16795 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29796 info->url,
[email protected]494c06e2009-07-25 01:06:42797 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58798 info->mime_type,
[email protected]9ccbb372008-10-10 18:50:32799 info->original_name,
initial.commit09911bf2008-07-26 23:55:29800 info->start_time,
801 info->total_bytes,
[email protected]76543b92009-08-31 17:27:45802 info->child_id,
[email protected]9ccbb372008-10-10 18:50:32803 info->request_id,
[email protected]67f373a2009-09-22 02:44:51804 info->is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57805 info->save_as,
[email protected]b0ab1d42010-02-24 19:29:28806 profile_->IsOffTheRecord(),
[email protected]6aa4a1c02010-01-15 18:49:58807 info->is_extension_install,
[email protected]8af9d032010-02-10 00:00:32808 !info->save_info.file_path.empty());
initial.commit09911bf2008-07-26 23:55:29809 download->set_manager(this);
810 in_progress_[info->download_id] = download;
811 } else {
812 NOTREACHED(); // Should not exist!
813 return;
814 }
815
[email protected]6b323782009-03-27 18:43:08816 // Called before DownloadFinished in order to avoid a race condition where we
817 // attempt to open a completed download before it has been renamed.
[email protected]d83d03aa2009-11-02 21:44:37818 ChromeThread::PostTask(
819 ChromeThread::FILE, FROM_HERE,
820 NewRunnableMethod(
821 file_manager_, &DownloadFileManager::OnFinalDownloadName,
822 download->id(), target_path, this));
[email protected]6b323782009-03-27 18:43:08823
initial.commit09911bf2008-07-26 23:55:29824 // If the download already completed by the time we reached this point, then
825 // notify observers that it did.
826 PendingFinishedMap::iterator pending_it =
827 pending_finished_downloads_.find(info->download_id);
828 if (pending_it != pending_finished_downloads_.end())
829 DownloadFinished(pending_it->first, pending_it->second);
830
831 download->Rename(target_path);
832
[email protected]67f373a2009-09-22 02:44:51833 // Do not store the download in the history database for a few special cases:
834 // - incognito mode (that is the point of this mode)
835 // - extensions (users don't think of extension installation as 'downloading')
[email protected]6aa4a1c02010-01-15 18:49:58836 // - temporary download, like in drag-and-drop
[email protected]67f373a2009-09-22 02:44:51837 // We have to make sure that these handles don't collide with normal db
838 // handles, so we use a negative value. Eventually, they could overlap, but
839 // you'd have to do enough downloading that your ISP would likely stab you in
840 // the neck first. YMMV.
[email protected]b0ab1d42010-02-24 19:29:28841 if (download->is_otr() || download->is_extension_install() ||
[email protected]6aa4a1c02010-01-15 18:49:58842 download->is_temporary()) {
[email protected]d2a8fb72010-01-21 05:31:42843 OnCreateDownloadEntryComplete(*info, fake_db_handle_.GetNext());
initial.commit09911bf2008-07-26 23:55:29844 } else {
845 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22846 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29847 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
848 if (hs) {
849 hs->CreateDownload(
850 *info, &cancelable_consumer_,
851 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
852 }
853 }
[email protected]6a7fb042010-02-01 16:30:47854
855 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29856}
857
858// Convenience function for updating the history service for a download.
859void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
860 DCHECK(download);
861
862 // Don't store info in the database if the download was initiated while in
863 // incognito mode or if it hasn't been initialized in our database table.
864 if (download->db_handle() <= kUninitializedHandle)
865 return;
866
[email protected]6cade212008-12-03 00:32:22867 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29868 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
869 if (hs) {
870 hs->UpdateDownload(download->received_bytes(),
871 download->state(),
872 download->db_handle());
873 }
874}
875
876void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
877 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22878 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29879 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
880 if (download->db_handle() > kUninitializedHandle && hs)
881 hs->RemoveDownload(download->db_handle());
882}
883
[email protected]e93d2822009-01-30 05:59:59884void DownloadManager::RemoveDownloadsFromHistoryBetween(
885 const base::Time remove_begin,
886 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22887 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29888 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
889 if (hs)
890 hs->RemoveDownloadsBetween(remove_begin, remove_end);
891}
892
893void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
894 DownloadMap::iterator it = in_progress_.find(download_id);
895 if (it != in_progress_.end()) {
896 DownloadItem* download = it->second;
897 download->Update(size);
898 UpdateHistoryForDownload(download);
899 }
[email protected]6a7fb042010-02-01 16:30:47900 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29901}
902
903void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
904 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32905 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29906 // The download is done, but the user hasn't selected a final location for
907 // it yet (the Save As dialog box is probably still showing), so just keep
908 // track of the fact that this download id is complete, when the
909 // DownloadItem is constructed later we'll notify its completion then.
910 PendingFinishedMap::iterator erase_it =
911 pending_finished_downloads_.find(download_id);
912 DCHECK(erase_it == pending_finished_downloads_.end());
913 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32914 return;
initial.commit09911bf2008-07-26 23:55:29915 }
[email protected]9ccbb372008-10-10 18:50:32916
917 // Remove the id from the list of pending ids.
918 PendingFinishedMap::iterator erase_it =
919 pending_finished_downloads_.find(download_id);
920 if (erase_it != pending_finished_downloads_.end())
921 pending_finished_downloads_.erase(erase_it);
922
923 DownloadItem* download = it->second;
924 download->Finished(size);
925
926 // Clean up will happen when the history system create callback runs if we
927 // don't have a valid db_handle yet.
928 if (download->db_handle() != kUninitializedHandle) {
929 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32930 UpdateHistoryForDownload(download);
931 }
932
[email protected]6a7fb042010-02-01 16:30:47933 UpdateAppIcon();
934
[email protected]9ccbb372008-10-10 18:50:32935 // If this a dangerous download not yet validated by the user, don't do
936 // anything. When the user notifies us, it will trigger a call to
937 // ProceedWithFinishedDangerousDownload.
938 if (download->safety_state() == DownloadItem::DANGEROUS) {
939 dangerous_finished_[download_id] = download;
940 return;
941 }
942
943 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22944 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32945 // its final name before we can continue.
[email protected]d83d03aa2009-11-02 21:44:37946 ChromeThread::PostTask(
947 ChromeThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32948 NewRunnableMethod(
949 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
950 download->db_handle(),
951 download->full_path(), download->original_name()));
952 return;
953 }
954 ContinueDownloadFinished(download);
955}
956
[email protected]8f783752009-04-01 23:33:45957void DownloadManager::DownloadRenamedToFinalName(int download_id,
958 const FilePath& full_path) {
[email protected]6aa4a1c02010-01-15 18:49:58959 DownloadMap::iterator it = downloads_.begin();
960 while (it != downloads_.end()) {
961 DownloadItem* download = it->second;
962 if (download->id() == download_id) {
963 // The download file is meant to be completed if both the filename is
964 // finalized and the file data is downloaded. The ordering of these two
965 // actions is indeterministic. Thus, if we are still in downloading the
966 // file, delay the notification.
967 download->set_name_finalized(true);
968 if (download->state() == DownloadItem::COMPLETE)
969 download->NotifyObserversDownloadFileCompleted();
970 return;
971 }
972 it++;
973 }
[email protected]8f783752009-04-01 23:33:45974}
975
[email protected]9ccbb372008-10-10 18:50:32976void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
977 // If this was a dangerous download, it has now been approved and must be
978 // removed from dangerous_finished_ so it does not get deleted on shutdown.
979 DownloadMap::iterator it = dangerous_finished_.find(download->id());
980 if (it != dangerous_finished_.end())
981 dangerous_finished_.erase(it);
982
[email protected]0aad67b2009-07-15 20:34:28983 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]a60c8ae2009-12-25 06:50:57984 if (download->is_extension_install()) {
[email protected]494c06e2009-07-25 01:06:42985 OpenChromeExtension(download->full_path(), download->url(),
986 download->referrer_url());
[email protected]0aad67b2009-07-15 20:34:28987 download->set_auto_opened(true);
988 } else if (download->open_when_complete() ||
[email protected]6aa4a1c02010-01-15 18:49:58989 ShouldOpenFileBasedOnExtension(download->full_path()) ||
990 download->is_temporary()) {
991 // If the download is temporary, like in drag-and-drop, do not open it but
992 // we still need to set it auto-opened so that it can be removed from the
993 // download shelf.
994 if (!download->is_temporary())
995 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28996 download->set_auto_opened(true);
997 }
[email protected]9ccbb372008-10-10 18:50:32998
[email protected]0aad67b2009-07-15 20:34:28999 // Notify our observers that we are complete (the call to Finished() set the
1000 // state to complete but did not notify).
1001 download->UpdateObservers();
[email protected]6aa4a1c02010-01-15 18:49:581002
1003 // The download file is meant to be completed if both the filename is
1004 // finalized and the file data is downloaded. The ordering of these two
1005 // actions is indeterministic. Thus, if the filename is not finalized yet,
1006 // delay the notification.
1007 if (download->name_finalized())
1008 download->NotifyObserversDownloadFileCompleted();
[email protected]0aad67b2009-07-15 20:34:281009}
[email protected]eccb9d12009-10-28 05:40:091010
[email protected]9ccbb372008-10-10 18:50:321011// Called on the file thread. Renames the downloaded file to its original name.
1012void DownloadManager::ProceedWithFinishedDangerousDownload(
1013 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:411014 const FilePath& path,
1015 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:321016 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:411017 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:161018 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:321019 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:241020 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:161021 // Make our name unique at this point, as if a dangerous file is downloading
1022 // and a 2nd download is started for a file with the same name, they would
1023 // have the same path. This is because we uniquify the name on download
1024 // start, and at that time the first file does not exists yet, so the second
1025 // file gets the same name.
[email protected]5a2388a2010-03-26 16:13:391026 uniquifier = download_util::GetUniquePathNumber(new_path);
[email protected]7a256ea2008-10-17 17:34:161027 if (uniquifier > 0)
[email protected]5a2388a2010-03-26 16:13:391028 download_util::AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:321029 success = file_util::Move(path, new_path);
1030 } else {
1031 NOTREACHED();
1032 }
[email protected]6cade212008-12-03 00:32:221033
[email protected]d83d03aa2009-11-02 21:44:371034 ChromeThread::PostTask(
1035 ChromeThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:321036 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:161037 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:321038}
1039
1040// Call from the file thread when the finished dangerous download was renamed.
1041void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
1042 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:411043 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:161044 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:321045 DownloadMap::iterator it = downloads_.find(download_handle);
1046 if (it == downloads_.end()) {
1047 NOTREACHED();
1048 return;
1049 }
1050
1051 DownloadItem* download = it->second;
1052 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:161053 if (success) {
1054 // We need to update the path uniquifier so that the UI shows the right
1055 // name when calling GetFileName().
1056 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:321057 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:161058 }
[email protected]9ccbb372008-10-10 18:50:321059
1060 // Continue the download finished sequence.
1061 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:291062}
1063
1064// static
initial.commit09911bf2008-07-26 23:55:291065void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
1066 int render_process_id,
1067 int request_id) {
[email protected]d85cf072009-10-27 03:59:311068 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
initial.commit09911bf2008-07-26 23:55:291069 rdh->CancelRequest(render_process_id, request_id, false);
1070}
1071
1072void DownloadManager::DownloadCancelled(int32 download_id) {
1073 DownloadMap::iterator it = in_progress_.find(download_id);
1074 if (it == in_progress_.end())
1075 return;
1076 DownloadItem* download = it->second;
1077
initial.commit09911bf2008-07-26 23:55:291078 // Clean up will happen when the history system create callback runs if we
1079 // don't have a valid db_handle yet.
1080 if (download->db_handle() != kUninitializedHandle) {
1081 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291082 UpdateHistoryForDownload(download);
1083 }
1084
[email protected]d7d1c5c2009-08-05 23:52:501085 DownloadCancelledInternal(download_id,
1086 download->render_process_id(),
1087 download->request_id());
[email protected]6a7fb042010-02-01 16:30:471088 UpdateAppIcon();
[email protected]d7d1c5c2009-08-05 23:52:501089}
1090
1091void DownloadManager::DownloadCancelledInternal(int download_id,
1092 int render_process_id,
1093 int request_id) {
[email protected]d85cf072009-10-27 03:59:311094 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
1095 ChromeThread::PostTask(
1096 ChromeThread::IO, FROM_HERE,
1097 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
1098 g_browser_process->resource_dispatcher_host(),
1099 render_process_id,
1100 request_id));
[email protected]d7d1c5c2009-08-05 23:52:501101
initial.commit09911bf2008-07-26 23:55:291102 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:501103 file_manager_->RemoveDownload(download_id, this); // On the UI thread
[email protected]d83d03aa2009-11-02 21:44:371104 ChromeThread::PostTask(
1105 ChromeThread::FILE, FROM_HERE,
1106 NewRunnableMethod(
1107 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:291108}
1109
1110void DownloadManager::PauseDownload(int32 download_id, bool pause) {
1111 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:311112 if (it == in_progress_.end())
1113 return;
initial.commit09911bf2008-07-26 23:55:291114
[email protected]d85cf072009-10-27 03:59:311115 DownloadItem* download = it->second;
1116 if (pause == download->is_paused())
1117 return;
initial.commit09911bf2008-07-26 23:55:291118
[email protected]d85cf072009-10-27 03:59:311119 // Inform the ResourceDispatcherHost of the new pause state.
1120 ChromeThread::PostTask(
1121 ChromeThread::IO, FROM_HERE,
1122 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
1123 g_browser_process->resource_dispatcher_host(),
1124 download->render_process_id(),
1125 download->request_id(),
1126 pause));
initial.commit09911bf2008-07-26 23:55:291127}
1128
1129// static
1130void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
1131 int render_process_id,
1132 int request_id,
1133 bool pause) {
1134 rdh->PauseRequest(render_process_id, request_id, pause);
1135}
1136
[email protected]7ae7c2cb2009-01-06 23:31:411137bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:321138 // TODO(jcampan): Improve me.
[email protected]eccb9d12009-10-28 05:40:091139 return IsExecutableFile(file_name);
[email protected]9ccbb372008-10-10 18:50:321140}
1141
[email protected]6a7fb042010-02-01 16:30:471142void DownloadManager::UpdateAppIcon() {
1143 int64 total_bytes = 0;
1144 int64 received_bytes = 0;
1145 int download_count = 0;
1146 bool progress_known = true;
1147
1148 for (DownloadMap::iterator i = in_progress_.begin();
1149 i != in_progress_.end();
1150 ++i) {
1151 ++download_count;
1152 const DownloadItem* item = i->second;
1153 if (item->total_bytes() > 0) {
1154 total_bytes += item->total_bytes();
1155 received_bytes += item->received_bytes();
1156 } else {
1157 // This download didn't specify a Content-Length, so the combined progress
1158 // bar neeeds to be indeterminate.
1159 progress_known = false;
1160 }
1161 }
1162
1163 float progress = 0;
1164 if (progress_known && download_count)
1165 progress = (float)received_bytes / total_bytes;
1166
1167 download_util::UpdateAppIconDownloadProgress(download_count,
1168 progress_known,
1169 progress);
1170}
1171
[email protected]9ccbb372008-10-10 18:50:321172void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411173 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321174 download->Rename(new_path);
1175
1176 // Update the history.
1177
1178 // No update necessary if the download was initiated while in incognito mode.
1179 if (download->db_handle() <= kUninitializedHandle)
1180 return;
1181
[email protected]6cade212008-12-03 00:32:221182 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321183 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1184 if (hs)
[email protected]7ae7c2cb2009-01-06 23:31:411185 hs->UpdateDownloadPath(new_path.ToWStringHack(), download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321186}
1187
initial.commit09911bf2008-07-26 23:55:291188void DownloadManager::RemoveDownload(int64 download_handle) {
1189 DownloadMap::iterator it = downloads_.find(download_handle);
1190 if (it == downloads_.end())
1191 return;
1192
1193 // Make history update.
1194 DownloadItem* download = it->second;
1195 RemoveDownloadFromHistory(download);
1196
1197 // Remove from our tables and delete.
1198 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321199 it = dangerous_finished_.find(download->id());
1200 if (it != dangerous_finished_.end())
1201 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291202
1203 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:281204 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:361205
1206 delete download;
initial.commit09911bf2008-07-26 23:55:291207}
1208
[email protected]e93d2822009-01-30 05:59:591209int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1210 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291211 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1212
initial.commit09911bf2008-07-26 23:55:291213 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281214 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291215 while (it != downloads_.end()) {
1216 DownloadItem* download = it->second;
1217 DownloadItem::DownloadState state = download->state();
1218 if (download->start_time() >= remove_begin &&
1219 (remove_end.is_null() || download->start_time() < remove_end) &&
1220 (state == DownloadItem::COMPLETE ||
1221 state == DownloadItem::CANCELLED)) {
1222 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561223 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581224
1225 // Also remove it from any completed dangerous downloads.
1226 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1227 if (dit != dangerous_finished_.end())
1228 dangerous_finished_.erase(dit);
1229
[email protected]78b8fcc92009-03-31 17:36:281230 pending_deletes.push_back(download);
[email protected]b0ab1d42010-02-24 19:29:281231 // Observer interface.
initial.commit09911bf2008-07-26 23:55:291232
initial.commit09911bf2008-07-26 23:55:291233 continue;
1234 }
1235
1236 ++it;
1237 }
1238
1239 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281240 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291241 if (num_deleted > 0)
[email protected]b0ab1d42010-02-24 19:29:281242 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291243
[email protected]78b8fcc92009-03-31 17:36:281244 // Delete the download items after updating the observers.
1245 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1246 pending_deletes.clear();
1247
initial.commit09911bf2008-07-26 23:55:291248 return num_deleted;
1249}
1250
[email protected]e93d2822009-01-30 05:59:591251int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1252 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291253}
1254
[email protected]d41355e6f2009-04-07 21:21:121255int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:461256 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
1257 // This is an incognito downloader. Clear All should clear main download
1258 // manager as well.
1259 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
1260 }
[email protected]d41355e6f2009-04-07 21:21:121261 // The null times make the date range unbounded.
1262 return RemoveDownloadsBetween(base::Time(), base::Time());
1263}
1264
initial.commit09911bf2008-07-26 23:55:291265// Initiate a download of a specific URL. We send the request to the
1266// ResourceDispatcherHost, and let it send us responses like a regular
1267// download.
1268void DownloadManager::DownloadUrl(const GURL& url,
1269 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501270 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341271 TabContents* tab_contents) {
[email protected]6aa4a1c02010-01-15 18:49:581272 file_manager_->DownloadUrl(url,
1273 referrer,
1274 referrer_charset,
[email protected]8af9d032010-02-10 00:00:321275 DownloadSaveInfo(),
[email protected]8cb5d5b2010-02-09 11:36:161276 tab_contents->GetRenderProcessHost()->id(),
[email protected]6aa4a1c02010-01-15 18:49:581277 tab_contents->render_view_host()->routing_id(),
1278 request_context_getter_);
1279}
1280
1281void DownloadManager::DownloadUrlToFile(const GURL& url,
1282 const GURL& referrer,
1283 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:321284 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:581285 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:341286 DCHECK(tab_contents);
initial.commit09911bf2008-07-26 23:55:291287 file_manager_->DownloadUrl(url,
1288 referrer,
[email protected]be180c802009-10-23 06:33:311289 referrer_charset,
[email protected]8af9d032010-02-10 00:00:321290 save_info,
[email protected]8cb5d5b2010-02-09 11:36:161291 tab_contents->GetRenderProcessHost()->id(),
[email protected]57c6a652009-05-04 07:58:341292 tab_contents->render_view_host()->routing_id(),
[email protected]be180c802009-10-23 06:33:311293 request_context_getter_);
initial.commit09911bf2008-07-26 23:55:291294}
1295
[email protected]7ae7c2cb2009-01-06 23:31:411296void DownloadManager::GenerateExtension(
1297 const FilePath& file_name,
1298 const std::string& mime_type,
1299 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291300 // We're worried about three things here:
1301 //
1302 // 1) Security. Many sites let users upload content, such as buddy icons, to
1303 // their web sites. We want to mitigate the case where an attacker
1304 // supplies a malicious executable with an executable file extension but an
1305 // honest site serves the content with a benign content type, such as
1306 // image/jpeg.
1307 //
1308 // 2) Usability. If the site fails to provide a file extension, we want to
1309 // guess a reasonable file extension based on the content type.
1310 //
1311 // 3) Shell integration. Some file extensions automatically integrate with
1312 // the shell. We block these extensions to prevent a malicious web site
1313 // from integrating with the user's shell.
1314
[email protected]7ae7c2cb2009-01-06 23:31:411315 static const FilePath::CharType default_extension[] =
1316 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291317
1318 // See if our file name already contains an extension.
[email protected]7ae7c2cb2009-01-06 23:31:411319 FilePath::StringType extension(
1320 file_util::GetFileExtensionFromPath(file_name));
initial.commit09911bf2008-07-26 23:55:291321
[email protected]b7f05882009-02-22 01:21:561322#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291323 // Rename shell-integrated extensions.
1324 if (win_util::IsShellIntegratedExtension(extension))
1325 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561326#endif
initial.commit09911bf2008-07-26 23:55:291327
1328 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411329 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411330 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291331 if (mime_type == mime_type_from_extension) {
1332 // The hinted extension matches the mime type. It looks like a winner.
1333 generated_extension->swap(extension);
1334 return;
1335 }
1336
[email protected]eccb9d12009-10-28 05:40:091337 if (IsExecutableExtension(extension) && !IsExecutableMimeType(mime_type)) {
initial.commit09911bf2008-07-26 23:55:291338 // We want to be careful about executable extensions. The worry here is
1339 // that a trusted web site could be tricked into dropping an executable file
1340 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101341 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291342 // We couldn't find a good extension for this content type. Use a dummy
1343 // extension instead.
1344 extension.assign(default_extension);
1345 }
1346 }
1347
1348 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101349 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291350 } else {
[email protected]6cade212008-12-03 00:32:221351 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291352 // 1. New extension is not ".txt"
1353 // 2. New extension is not the same as the already existing extension.
1354 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411355 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291356 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1357 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371358 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1359 // servers, i.e. bug 5772.
[email protected]e32642f62009-09-11 21:58:291360 // 5. The original extension is not ".tgz" & the new extension is not "gz".
[email protected]7ae7c2cb2009-01-06 23:31:411361 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101362 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171363 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411364 append_extension != extension &&
[email protected]eccb9d12009-10-28 05:40:091365 !IsExecutableExtension(append_extension) &&
[email protected]e32642f62009-09-11 21:58:291366 !(append_extension == FILE_PATH_LITERAL("gz") &&
1367 extension == FILE_PATH_LITERAL("tgz")) &&
[email protected]e106457b2009-03-25 22:43:371368 (append_extension != FILE_PATH_LITERAL("tar") ||
1369 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171370 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291371 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171372 }
initial.commit09911bf2008-07-26 23:55:291373 }
1374 }
1375
1376 generated_extension->swap(extension);
1377}
1378
[email protected]6aa4a1c02010-01-15 18:49:581379void DownloadManager::GenerateFileNameFromInfo(DownloadCreateInfo* info,
1380 FilePath* generated_name) {
1381 GenerateFileName(GURL(info->url),
1382 info->content_disposition,
1383 info->referrer_charset,
1384 info->mime_type,
1385 generated_name);
1386}
1387
1388void DownloadManager::GenerateFileName(const GURL& url,
1389 const std::string& content_disposition,
1390 const std::string& referrer_charset,
1391 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411392 FilePath* generated_name) {
[email protected]630947c2009-11-04 18:37:311393 std::wstring default_name =
1394 l10n_util::GetString(IDS_DEFAULT_DOWNLOAD_FILENAME);
1395#if defined(OS_WIN)
1396 FilePath default_file_path(default_name);
1397#elif defined(OS_POSIX)
1398 FilePath default_file_path(base::SysWideToNativeMB(default_name));
1399#endif
1400
[email protected]6aa4a1c02010-01-15 18:49:581401 *generated_name = net::GetSuggestedFilename(GURL(url),
1402 content_disposition,
1403 referrer_charset,
[email protected]630947c2009-11-04 18:37:311404 default_file_path);
1405
[email protected]7ae7c2cb2009-01-06 23:31:411406 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291407
[email protected]6aa4a1c02010-01-15 18:49:581408 GenerateSafeFileName(mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291409}
1410
1411void DownloadManager::AddObserver(Observer* observer) {
1412 observers_.AddObserver(observer);
1413 observer->ModelChanged();
1414}
1415
1416void DownloadManager::RemoveObserver(Observer* observer) {
1417 observers_.RemoveObserver(observer);
1418}
1419
1420// Post Windows Shell operations to the Download thread, to avoid blocking the
1421// user interface.
1422void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1423 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371424 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581425#if defined(OS_MACOSX)
1426 // Mac needs to run this operation on the UI thread.
1427 platform_util::ShowItemInFolder(download->full_path());
1428#else
[email protected]d83d03aa2009-11-02 21:44:371429 ChromeThread::PostTask(
1430 ChromeThread::FILE, FROM_HERE,
1431 NewRunnableMethod(
1432 file_manager_, &DownloadFileManager::OnShowDownloadInShell,
1433 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581434#endif
initial.commit09911bf2008-07-26 23:55:291435}
1436
[email protected]8f783752009-04-01 23:33:451437void DownloadManager::OpenDownload(const DownloadItem* download,
1438 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401439 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451440 // execute.
[email protected]a60c8ae2009-12-25 06:50:571441 if (download->is_extension_install()) {
[email protected]494c06e2009-07-25 01:06:421442 OpenChromeExtension(download->full_path(), download->url(),
1443 download->referrer_url());
[email protected]8f783752009-04-01 23:33:451444 } else {
1445 OpenDownloadInShell(download, parent_window);
1446 }
1447}
1448
[email protected]c1e432a2009-07-22 21:21:481449void DownloadManager::OpenChromeExtension(const FilePath& full_path,
[email protected]494c06e2009-07-25 01:06:421450 const GURL& download_url,
1451 const GURL& referrer_url) {
[email protected]6ef635e42009-07-26 06:16:121452 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351453 ExtensionsService* service = profile_->GetExtensionsService();
1454 if (service) {
[email protected]91e1bd82009-09-03 22:04:401455 NotificationService* nservice = NotificationService::current();
[email protected]6dfbbf82010-03-12 23:09:161456 GURL nonconst_download_url = download_url;
1457 nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
1458 Source<DownloadManager>(this),
1459 Details<GURL>(&nonconst_download_url));
1460
1461 scoped_refptr<CrxInstaller> installer(
1462 new CrxInstaller(service->install_directory(),
1463 service,
1464 new ExtensionInstallUI(profile_)));
1465 installer->set_delete_source(true);
1466
[email protected]a050d712009-11-06 00:40:101467 if (UserScript::HasUserScriptFileExtension(download_url)) {
[email protected]6dfbbf82010-03-12 23:09:161468 installer->InstallUserScript(full_path, download_url);
[email protected]6657afa62009-11-04 02:15:201469 } else {
[email protected]be18e1582010-06-03 21:50:421470 bool is_gallery_download =
1471 ExtensionsService::IsDownloadFromGallery(download_url, referrer_url);
[email protected]6dfbbf82010-03-12 23:09:161472 installer->set_allow_privilege_increase(true);
1473 installer->set_original_url(download_url);
[email protected]be18e1582010-06-03 21:50:421474 installer->set_force_web_origin_to_download_url(!is_gallery_download);
[email protected]6dfbbf82010-03-12 23:09:161475 installer->InstallCrx(full_path);
[email protected]6657afa62009-11-04 02:15:201476 }
[email protected]21ca982c2010-01-26 22:49:551477 } else {
1478 TabContents* contents = NULL;
1479 Browser* last_active = BrowserList::GetLastActiveWithProfile(profile_);
1480 if (last_active)
1481 contents = last_active->GetSelectedTabContents();
1482 if (contents) {
1483 contents->AddInfoBar(
1484 new SimpleAlertInfoBarDelegate(contents,
1485 l10n_util::GetString(
1486 IDS_EXTENSION_INCOGNITO_INSTALL_INFOBAR_LABEL),
1487 ResourceBundle::GetSharedInstance().GetBitmapNamed(
[email protected]938e1f92010-04-01 18:09:421488 IDR_INFOBAR_PLUGIN_INSTALL),
1489 true));
[email protected]21ca982c2010-01-26 22:49:551490 }
[email protected]2a464a92009-08-01 17:58:351491 }
[email protected]8f783752009-04-01 23:33:451492}
1493
initial.commit09911bf2008-07-26 23:55:291494void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591495 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291496 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371497 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581498#if defined(OS_MACOSX)
1499 // Mac OS X requires opening downloads on the UI thread.
1500 platform_util::OpenItem(download->full_path());
1501#else
[email protected]d83d03aa2009-11-02 21:44:371502 ChromeThread::PostTask(
1503 ChromeThread::FILE, FROM_HERE,
1504 NewRunnableMethod(
1505 file_manager_, &DownloadFileManager::OnOpenDownloadInShell,
1506 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581507#endif
initial.commit09911bf2008-07-26 23:55:291508}
1509
[email protected]eccb9d12009-10-28 05:40:091510void DownloadManager::OpenFilesBasedOnExtension(
1511 const FilePath& path, bool open) {
1512 FilePath::StringType extension = path.Extension();
1513 if (extension.empty())
1514 return;
1515 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1516 extension.erase(0, 1);
1517 if (open && !IsExecutableExtension(extension))
initial.commit09911bf2008-07-26 23:55:291518 auto_open_.insert(extension);
1519 else
1520 auto_open_.erase(extension);
1521 SaveAutoOpens();
1522}
1523
[email protected]eccb9d12009-10-28 05:40:091524bool DownloadManager::ShouldOpenFileBasedOnExtension(
1525 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:091526 FilePath::StringType extension = path.Extension();
1527 if (extension.empty())
1528 return false;
1529 if (IsExecutableExtension(extension))
1530 return false;
[email protected]92e11c82010-01-13 06:39:561531 if (Extension::IsExtension(path))
1532 return false;
[email protected]eccb9d12009-10-28 05:40:091533 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1534 extension.erase(0, 1);
[email protected]92e11c82010-01-13 06:39:561535 if (auto_open_.find(extension) != auto_open_.end())
[email protected]8c756ac2009-01-30 23:36:411536 return true;
initial.commit09911bf2008-07-26 23:55:291537 return false;
1538}
1539
[email protected]7b73d992008-12-15 20:56:461540static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291541 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461542 "text/javascript",
1543 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241544 // Registry files can cause critical changes to the MS OS behavior.
1545 // Addition of this mimetype also addresses bug 7337.
1546 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391547 // Some sites use binary/octet-stream to mean application/octet-stream.
1548 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461549 "binary/octet-stream"
1550};
initial.commit09911bf2008-07-26 23:55:291551
[email protected]7b73d992008-12-15 20:56:461552static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291553 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461554 "application/*+xml",
1555 "application/xml"
1556};
initial.commit09911bf2008-07-26 23:55:291557
[email protected]7b73d992008-12-15 20:56:461558// static
1559bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411560 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461561 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1562 return true;
1563 }
[email protected]bae0ea12009-02-14 01:20:411564 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461565 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1566 return false;
1567 }
1568 // We consider only other application types to be executable.
1569 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291570}
1571
[email protected]eccb9d12009-10-28 05:40:091572bool DownloadManager::IsExecutableFile(const FilePath& path) const {
1573 return IsExecutableExtension(path.Extension());
1574}
1575
1576bool DownloadManager::IsExecutableExtension(
[email protected]6aa4a1c02010-01-15 18:49:581577 const FilePath::StringType& extension) {
[email protected]eccb9d12009-10-28 05:40:091578 if (extension.empty())
1579 return false;
[email protected]64da0b932009-02-24 02:30:041580 if (!IsStringASCII(extension))
1581 return false;
[email protected]a0a9577b2009-05-27 23:52:321582#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041583 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131584#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321585 std::string ascii_extension = extension;
1586#endif
[email protected]64da0b932009-02-24 02:30:041587
[email protected]eccb9d12009-10-28 05:40:091588 // Strip out leading dot if it's still there
1589 if (ascii_extension[0] == FilePath::kExtensionSeparator)
1590 ascii_extension.erase(0, 1);
1591
[email protected]6aa4a1c02010-01-15 18:49:581592 return download_util::IsExecutableExtension(ascii_extension);
initial.commit09911bf2008-07-26 23:55:291593}
1594
1595void DownloadManager::ResetAutoOpenFiles() {
1596 auto_open_.clear();
1597 SaveAutoOpens();
1598}
1599
1600bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1601 return !auto_open_.empty();
1602}
1603
1604void DownloadManager::SaveAutoOpens() {
1605 PrefService* prefs = profile_->GetPrefs();
1606 if (prefs) {
[email protected]7ae7c2cb2009-01-06 23:31:411607 FilePath::StringType extensions;
[email protected]eccb9d12009-10-28 05:40:091608 for (AutoOpenSet::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291609 it != auto_open_.end(); ++it) {
[email protected]7ae7c2cb2009-01-06 23:31:411610 extensions += *it + FILE_PATH_LITERAL(":");
initial.commit09911bf2008-07-26 23:55:291611 }
1612 if (!extensions.empty())
1613 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561614
1615 std::wstring extensions_w;
1616#if defined(OS_WIN)
1617 extensions_w = extensions;
1618#elif defined(OS_POSIX)
[email protected]1b5044d2009-02-24 00:04:141619 extensions_w = base::SysNativeMBToWide(extensions);
[email protected]b7f05882009-02-22 01:21:561620#endif
1621
1622 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions_w);
initial.commit09911bf2008-07-26 23:55:291623 }
1624}
1625
[email protected]561abe62009-04-06 18:08:341626void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361627 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291628 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071629 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411630 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291631 ContinueStartDownload(info, path);
1632}
1633
1634void DownloadManager::FileSelectionCanceled(void* params) {
1635 // The user didn't pick a place to save the file, so need to cancel the
1636 // download that's already in progress to the temporary location.
1637 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501638 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451639 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501640 info->request_id);
initial.commit09911bf2008-07-26 23:55:291641}
1642
[email protected]7ae7c2cb2009-01-06 23:31:411643void DownloadManager::DeleteDownload(const FilePath& path) {
[email protected]d83d03aa2009-11-02 21:44:371644 ChromeThread::PostTask(
1645 ChromeThread::FILE, FROM_HERE,
1646 NewRunnableFunction(&DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321647}
1648
1649
1650void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1651 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1652 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1653 download->UpdateObservers();
1654
1655 // If the download is not complete, nothing to do. The required
1656 // post-processing will be performed when it does complete.
1657 if (download->state() != DownloadItem::COMPLETE)
1658 return;
1659
[email protected]d83d03aa2009-11-02 21:44:371660 ChromeThread::PostTask(
1661 ChromeThread::FILE, FROM_HERE,
1662 NewRunnableMethod(
1663 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
1664 download->db_handle(), download->full_path(),
1665 download->original_name()));
[email protected]9ccbb372008-10-10 18:50:321666}
1667
[email protected]6aa4a1c02010-01-15 18:49:581668void DownloadManager::GenerateSafeFileName(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411669 FilePath* file_name) {
1670 // Make sure we get the right file extension
1671 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391672 GenerateExtension(*file_name, mime_type, &extension);
[email protected]1bdaa60c2010-06-01 01:57:431673 *file_name = file_name->ReplaceExtension(extension);
[email protected]763f946a2009-01-06 19:04:391674
[email protected]2b2f8f72009-02-24 22:42:051675#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391676 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411677 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391678 DCHECK(!leaf_name.empty());
1679 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411680 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1681 *file_name = file_name->DirName();
1682 if (file_name->value() == FilePath::kCurrentDirectory) {
1683 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391684 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411685 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391686 }
1687 }
[email protected]b7f05882009-02-22 01:21:561688#endif
[email protected]763f946a2009-01-06 19:04:391689}
1690
initial.commit09911bf2008-07-26 23:55:291691// Operations posted to us from the history service ----------------------------
1692
1693// The history service has retrieved all download entries. 'entries' contains
1694// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1695void DownloadManager::OnQueryDownloadEntriesComplete(
1696 std::vector<DownloadCreateInfo>* entries) {
1697 for (size_t i = 0; i < entries->size(); ++i) {
1698 DownloadItem* download = new DownloadItem(entries->at(i));
1699 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1700 downloads_[download->db_handle()] = download;
1701 download->set_manager(this);
1702 }
[email protected]b0ab1d42010-02-24 19:29:281703 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291704}
1705
initial.commit09911bf2008-07-26 23:55:291706// Once the new DownloadItem's creation info has been committed to the history
1707// service, we associate the DownloadItem with the db handle, update our
1708// 'downloads_' map and inform observers.
1709void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1710 int64 db_handle) {
1711 DownloadMap::iterator it = in_progress_.find(info.download_id);
1712 DCHECK(it != in_progress_.end());
1713
1714 DownloadItem* download = it->second;
[email protected]d2a8fb72010-01-21 05:31:421715
1716 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1717 // call this function with an invalid |db_handle|. For instance, this can
1718 // happen when the history database is offline. We cannot have multiple
1719 // DownloadItems with the same invalid db_handle, so we need to assign a
1720 // unique |db_handle| here.
1721 if (db_handle == kUninitializedHandle)
1722 db_handle = fake_db_handle_.GetNext();
1723
initial.commit09911bf2008-07-26 23:55:291724 DCHECK(download->db_handle() == kUninitializedHandle);
1725 download->set_db_handle(db_handle);
1726
1727 // Insert into our full map.
1728 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1729 downloads_[download->db_handle()] = download;
1730
[email protected]5e595482009-05-06 20:16:531731 // Show in the appropropriate browser UI.
1732 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291733
1734 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281735 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291736
1737 // If this download has been completed before we've received the db handle,
1738 // post one final message to the history service so that it can be properly
1739 // in sync with the DownloadItem's completion status, and also inform any
1740 // observers so that they get more than just the start notification.
1741 if (download->state() != DownloadItem::IN_PROGRESS) {
1742 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291743 UpdateHistoryForDownload(download);
1744 download->UpdateObservers();
1745 }
[email protected]6a7fb042010-02-01 16:30:471746
1747 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:291748}
1749
1750// Called when the history service has retrieved the list of downloads that
1751// match the search text.
1752void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1753 std::vector<int64>* results) {
1754 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1755 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1756 if (!requestor)
1757 return;
1758
1759 std::vector<DownloadItem*> searched_downloads;
1760 for (std::vector<int64>::iterator it = results->begin();
1761 it != results->end(); ++it) {
1762 DownloadMap::iterator dit = downloads_.find(*it);
1763 if (dit != downloads_.end())
1764 searched_downloads.push_back(dit->second);
1765 }
1766
1767 requestor->SetDownloads(searched_downloads);
1768}
[email protected]905a08d2008-11-19 07:24:121769
[email protected]5e595482009-05-06 20:16:531770void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1771 DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341772 // The 'contents' may no longer exist if the user closed the tab before we
1773 // get this start completion event. If it does, tell the origin TabContents
1774 // to display its download shelf.
[email protected]76543b92009-08-31 17:27:451775 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1776 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531777
1778 // If the contents no longer exists, we start the download in the last active
1779 // browser. This is not ideal but better than fully hiding the download from
1780 // the user.
1781 if (!contents) {
1782 Browser* last_active = BrowserList::GetLastActive();
1783 if (last_active)
1784 contents = last_active->GetSelectedTabContents();
1785 }
1786
1787 if (contents)
1788 contents->OnStartDownload(download);
1789}
1790
[email protected]6cade212008-12-03 00:32:221791// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121792void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411793 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381794}
[email protected]b0ab1d42010-02-24 19:29:281795
1796void DownloadManager::NotifyModelChanged() {
1797 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1798}
1799
1800// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1801
1802DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1803 DownloadManager* observing_download_manager)
1804 : observing_download_manager_(observing_download_manager),
1805 observed_download_manager_(NULL) {
1806 if (observing_download_manager->profile_->GetOriginalProfile() ==
1807 observing_download_manager->profile_) {
1808 return;
1809 }
1810
1811 observed_download_manager_ = observing_download_manager_->
1812 profile_->GetOriginalProfile()->GetDownloadManager();
1813 observed_download_manager_->AddObserver(this);
1814}
1815
1816DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1817 if (observed_download_manager_)
1818 observed_download_manager_->RemoveObserver(this);
1819}
1820
1821void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1822 observing_download_manager_->NotifyModelChanged();
1823}
1824
1825void DownloadManager::OtherDownloadManagerObserver::SetDownloads(
1826 std::vector<DownloadItem*>& downloads) {
1827}
1828
1829void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1830 observed_download_manager_ = NULL;
1831}