blob: 4fe4d5a550909d30e1bc9a9a5d8f150857b175d2 [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]da74e5ae22010-07-14 16:12:3787void DeleteDownloadedFile(const FilePath& path) {
88 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));
89
90 // Make sure we only delete files.
91 if (!file_util::DirectoryExists(path))
92 file_util::Delete(path, false);
93}
94
[email protected]21ca982c2010-01-26 22:49:5595} // namespace
96
initial.commit09911bf2008-07-26 23:55:2997// DownloadItem implementation -------------------------------------------------
98
99// Constructor for reading from the history service.
100DownloadItem::DownloadItem(const DownloadCreateInfo& info)
101 : id_(-1),
102 full_path_(info.path),
103 url_(info.url),
[email protected]e435d6b72009-07-25 03:15:58104 referrer_url_(info.referrer_url),
105 mime_type_(info.mime_type),
[email protected]d4a71882010-06-25 16:36:41106 original_mime_type_(info.original_mime_type),
initial.commit09911bf2008-07-26 23:55:29107 total_bytes_(info.total_bytes),
108 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56109 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29110 state_(static_cast<DownloadState>(info.state)),
111 start_time_(info.start_time),
112 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29113 manager_(NULL),
114 is_paused_(false),
115 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56116 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28117 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56118 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29119 render_process_id_(-1),
[email protected]6aa4a1c02010-01-15 18:49:58120 request_id_(-1),
121 save_as_(false),
[email protected]b0ab1d42010-02-24 19:29:28122 is_otr_(false),
[email protected]5748eb82010-01-20 15:12:37123 is_extension_install_(info.is_extension_install),
[email protected]6aa4a1c02010-01-15 18:49:58124 name_finalized_(false),
125 is_temporary_(false) {
initial.commit09911bf2008-07-26 23:55:29126 if (state_ == IN_PROGRESS)
127 state_ = CANCELLED;
128 Init(false /* don't start progress timer */);
129}
130
131// Constructor for DownloadItem created via user action in the main thread.
132DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41133 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16134 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32135 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42136 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58137 const std::string& mime_type,
[email protected]d4a71882010-06-25 16:36:41138 const std::string& original_mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41139 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59140 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29141 int64 download_size,
142 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32143 int request_id,
[email protected]67f373a2009-09-22 02:44:51144 bool is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57145 bool save_as,
[email protected]b0ab1d42010-02-24 19:29:28146 bool is_otr,
[email protected]6aa4a1c02010-01-15 18:49:58147 bool is_extension_install,
148 bool is_temporary)
initial.commit09911bf2008-07-26 23:55:29149 : id_(download_id),
150 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16151 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29152 url_(url),
[email protected]494c06e2009-07-25 01:06:42153 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58154 mime_type_(mime_type),
[email protected]d4a71882010-06-25 16:36:41155 original_mime_type_(original_mime_type),
initial.commit09911bf2008-07-26 23:55:29156 total_bytes_(download_size),
157 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56158 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29159 state_(IN_PROGRESS),
160 start_time_(start_time),
161 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29162 manager_(NULL),
163 is_paused_(false),
164 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56165 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28166 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56167 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29168 render_process_id_(render_process_id),
[email protected]67f373a2009-09-22 02:44:51169 request_id_(request_id),
[email protected]a60c8ae2009-12-25 06:50:57170 save_as_(save_as),
[email protected]b0ab1d42010-02-24 19:29:28171 is_otr_(is_otr),
[email protected]6aa4a1c02010-01-15 18:49:58172 is_extension_install_(is_extension_install),
173 name_finalized_(false),
174 is_temporary_(is_temporary) {
initial.commit09911bf2008-07-26 23:55:29175 Init(true /* start progress timer */);
176}
177
178void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41179 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29180 if (start_timer)
181 StartProgressTimer();
182}
183
184DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29185 state_ = REMOVING;
186 UpdateObservers();
187}
188
189void DownloadItem::AddObserver(Observer* observer) {
190 observers_.AddObserver(observer);
191}
192
193void DownloadItem::RemoveObserver(Observer* observer) {
194 observers_.RemoveObserver(observer);
195}
196
197void DownloadItem::UpdateObservers() {
198 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
199}
200
[email protected]6aa4a1c02010-01-15 18:49:58201void DownloadItem::NotifyObserversDownloadFileCompleted() {
202 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadFileCompleted(this));
203}
204
[email protected]45e3c122009-04-07 19:58:03205void DownloadItem::NotifyObserversDownloadOpened() {
206 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
207}
208
initial.commit09911bf2008-07-26 23:55:29209// If we've received more data than we were expecting (bad server info?), revert
210// to 'unknown size mode'.
211void DownloadItem::UpdateSize(int64 bytes_so_far) {
212 received_bytes_ = bytes_so_far;
213 if (received_bytes_ > total_bytes_)
214 total_bytes_ = 0;
215}
216
217// Updates from the download thread may have been posted while this download
218// was being cancelled in the UI thread, so we'll accept them unless we're
219// complete.
220void DownloadItem::Update(int64 bytes_so_far) {
221 if (state_ == COMPLETE) {
222 NOTREACHED();
223 return;
224 }
225 UpdateSize(bytes_so_far);
226 UpdateObservers();
227}
228
[email protected]6cade212008-12-03 00:32:22229// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29230void DownloadItem::Cancel(bool update_history) {
231 if (state_ != IN_PROGRESS) {
232 // Small downloads might be complete before this method has a chance to run.
233 return;
234 }
235 state_ = CANCELLED;
236 UpdateObservers();
237 StopProgressTimer();
238 if (update_history)
239 manager_->DownloadCancelled(id_);
240}
241
242void DownloadItem::Finished(int64 size) {
243 state_ = COMPLETE;
244 UpdateSize(size);
initial.commit09911bf2008-07-26 23:55:29245 StopProgressTimer();
246}
247
[email protected]9ccbb372008-10-10 18:50:32248void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29249 Cancel(true);
250 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32251 if (delete_on_disk)
252 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29253 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22254 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29255}
256
257void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59258 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14259 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29260}
261
262void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14263 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29264}
265
[email protected]e93d2822009-01-30 05:59:59266bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29267 if (total_bytes_ <= 0)
268 return false; // We never received the content_length for this download.
269
270 int64 speed = CurrentSpeed();
271 if (speed == 0)
272 return false;
273
274 *remaining =
[email protected]e93d2822009-01-30 05:59:59275 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29276 return true;
277}
278
279int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56280 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
281 int64 diff_ms = diff.InMilliseconds();
282 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29283}
284
285int DownloadItem::PercentComplete() const {
286 int percent = -1;
287 if (total_bytes_ > 0)
288 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
289 return percent;
290}
291
[email protected]7ae7c2cb2009-01-06 23:31:41292void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29293 DCHECK(!full_path.empty());
294 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41295 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29296}
297
298void DownloadItem::TogglePause() {
299 DCHECK(state_ == IN_PROGRESS);
300 manager_->PauseDownload(id_, !is_paused_);
301 is_paused_ = !is_paused_;
302 UpdateObservers();
303}
304
[email protected]7ae7c2cb2009-01-06 23:31:41305FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32306 if (safety_state_ == DownloadItem::SAFE)
307 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16308 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41309 FilePath name(original_name_);
[email protected]5a2388a2010-03-26 16:13:39310 download_util::AppendNumberToPath(&name, path_uniquifier_);
[email protected]7a256ea2008-10-17 17:34:16311 return name;
312 }
[email protected]9ccbb372008-10-10 18:50:32313 return original_name_;
314}
315
initial.commit09911bf2008-07-26 23:55:29316// DownloadManager implementation ----------------------------------------------
317
318// static
319void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
320 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
[email protected]20ce516d2010-06-18 02:20:04321 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, "");
[email protected]f052118e2008-09-05 02:25:32322 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
323
324 // The default download path is userprofile\download.
[email protected]290c9702010-03-09 04:01:36325 const FilePath& default_download_path =
326 download_util::GetDefaultDownloadDirectory();
[email protected]b9636002009-03-04 00:05:25327 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
328 default_download_path);
[email protected]f052118e2008-09-05 02:25:32329
330 // If the download path is dangerous we forcefully reset it. But if we do
331 // so we set a flag to make sure we only do it once, to avoid fighting
332 // the user if he really wants it on an unsafe place such as the desktop.
333
334 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]38233e62010-04-26 04:43:36335 FilePath current_download_dir = prefs->GetFilePath(
336 prefs::kDownloadDefaultDirectory);
[email protected]290c9702010-03-09 04:01:36337 if (download_util::DownloadPathIsDangerous(current_download_dir)) {
[email protected]38233e62010-04-26 04:43:36338 prefs->SetFilePath(prefs::kDownloadDefaultDirectory,
339 default_download_path);
[email protected]f052118e2008-09-05 02:25:32340 }
341 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
342 }
initial.commit09911bf2008-07-26 23:55:29343}
344
345DownloadManager::DownloadManager()
346 : shutdown_needed_(false),
347 profile_(NULL),
[email protected]d2a8fb72010-01-21 05:31:42348 file_manager_(NULL),
349 fake_db_handle_(kUninitializedHandle - 1) {
initial.commit09911bf2008-07-26 23:55:29350}
351
352DownloadManager::~DownloadManager() {
[email protected]b0ab1d42010-02-24 19:29:28353 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
354
initial.commit09911bf2008-07-26 23:55:29355 if (shutdown_needed_)
356 Shutdown();
357}
358
359void DownloadManager::Shutdown() {
360 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
361
362 // Stop receiving download updates
363 file_manager_->RemoveDownloadManager(this);
364
365 // Stop making history service requests
366 cancelable_consumer_.CancelAllRequests();
367
368 // 'in_progress_' may contain DownloadItems that have not finished the start
369 // complete (from the history service) and thus aren't in downloads_.
370 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32371 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29372 for (; it != in_progress_.end(); ++it) {
373 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32374 if (download->safety_state() == DownloadItem::DANGEROUS) {
375 // Forget about any download that the user did not approve.
376 // Note that we cannot call download->Remove() this would invalidate our
377 // iterator.
378 to_remove.insert(download);
379 continue;
initial.commit09911bf2008-07-26 23:55:29380 }
[email protected]9ccbb372008-10-10 18:50:32381 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
382 download->Cancel(false);
383 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29384 if (download->db_handle() == kUninitializedHandle) {
385 // An invalid handle means that 'download' does not yet exist in
386 // 'downloads_', so we have to delete it here.
387 delete download;
388 }
389 }
390
[email protected]9ccbb372008-10-10 18:50:32391 // 'dangerous_finished_' contains all complete downloads that have not been
392 // approved. They should be removed.
393 it = dangerous_finished_.begin();
394 for (; it != dangerous_finished_.end(); ++it)
395 to_remove.insert(it->second);
396
397 // Remove the dangerous download that are not approved.
398 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
399 rm_it != to_remove.end(); ++rm_it) {
400 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32401 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32402 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32403 // Same as above, delete the download if it is not in 'downloads_' (as the
404 // Remove() call above won't have deleted it).
405 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32406 delete download;
407 }
408 to_remove.clear();
409
initial.commit09911bf2008-07-26 23:55:29410 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32411 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29412 STLDeleteValues(&downloads_);
413
414 file_manager_ = NULL;
415
416 // Save our file extensions to auto open.
417 SaveAutoOpens();
418
419 // Make sure the save as dialog doesn't notify us back if we're gone before
420 // it returns.
421 if (select_file_dialog_.get())
422 select_file_dialog_->ListenerDestroyed();
423
424 shutdown_needed_ = false;
425}
426
427// Issue a history query for downloads matching 'search_text'. If 'search_text'
428// is empty, return all downloads that we know about.
429void DownloadManager::GetDownloads(Observer* observer,
430 const std::wstring& search_text) {
[email protected]b0ab1d42010-02-24 19:29:28431 std::vector<DownloadItem*> otr_downloads;
432
433 if (profile_->IsOffTheRecord() && search_text.empty()) {
434 // List all incognito downloads and add that to the downloads the parent
435 // profile lists.
436 otr_downloads.reserve(downloads_.size());
437 for (DownloadMap::iterator it = downloads_.begin();
438 it != downloads_.end(); ++it) {
439 DownloadItem* download = it->second;
440 if (download->is_otr() && !download->is_extension_install() &&
441 !download->is_temporary()) {
442 otr_downloads.push_back(download);
443 }
444 }
445 }
446
447 profile_->GetOriginalProfile()->GetDownloadManager()->
448 DoGetDownloads(observer, search_text, otr_downloads);
449}
450
451void DownloadManager::DoGetDownloads(
452 Observer* observer,
453 const std::wstring& search_text,
454 std::vector<DownloadItem*>& otr_downloads) {
initial.commit09911bf2008-07-26 23:55:29455 DCHECK(observer);
456
457 // Return a empty list if we've not yet received the set of downloads from the
458 // history system (we'll update all observers once we get that list in
459 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
initial.commit09911bf2008-07-26 23:55:29460 if (downloads_.empty()) {
[email protected]b0ab1d42010-02-24 19:29:28461 observer->SetDownloads(otr_downloads);
initial.commit09911bf2008-07-26 23:55:29462 return;
463 }
464
[email protected]b0ab1d42010-02-24 19:29:28465 std::vector<DownloadItem*> download_copy;
initial.commit09911bf2008-07-26 23:55:29466 // We already know all the downloads and there is no filter, so just return a
467 // copy to the observer.
468 if (search_text.empty()) {
469 download_copy.reserve(downloads_.size());
470 for (DownloadMap::iterator it = downloads_.begin();
471 it != downloads_.end(); ++it) {
[email protected]67f373a2009-09-22 02:44:51472 if (it->second->db_handle() > kUninitializedHandle)
473 download_copy.push_back(it->second);
initial.commit09911bf2008-07-26 23:55:29474 }
475
[email protected]b0ab1d42010-02-24 19:29:28476 // Merge sort based on start time.
477 std::vector<DownloadItem*> merged_downloads;
478 std::merge(otr_downloads.begin(), otr_downloads.end(),
479 download_copy.begin(), download_copy.end(),
480 std::back_inserter(merged_downloads),
481 CompareStartTime);
482
initial.commit09911bf2008-07-26 23:55:29483 // We retain ownership of the DownloadItems.
[email protected]b0ab1d42010-02-24 19:29:28484 observer->SetDownloads(merged_downloads);
initial.commit09911bf2008-07-26 23:55:29485 return;
486 }
487
[email protected]b0ab1d42010-02-24 19:29:28488 DCHECK(otr_downloads.empty());
489
initial.commit09911bf2008-07-26 23:55:29490 // Issue a request to the history service for a list of downloads matching
491 // our search text.
492 HistoryService* hs =
493 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
494 if (hs) {
495 HistoryService::Handle h =
[email protected]e53668962010-06-23 15:35:25496 hs->SearchDownloads(WideToUTF16(search_text),
initial.commit09911bf2008-07-26 23:55:29497 &cancelable_consumer_,
498 NewCallback(this,
499 &DownloadManager::OnSearchComplete));
500 cancelable_consumer_.SetClientData(hs, h, observer);
501 }
502}
503
[email protected]6aa4a1c02010-01-15 18:49:58504void DownloadManager::GetTemporaryDownloads(Observer* observer,
505 const FilePath& dir_path) {
506 DCHECK(observer);
507
508 std::vector<DownloadItem*> download_copy;
509
510 for (DownloadMap::iterator it = downloads_.begin();
511 it != downloads_.end(); ++it) {
512 if (it->second->is_temporary() &&
513 it->second->full_path().DirName() == dir_path)
514 download_copy.push_back(it->second);
515 }
516
517 observer->SetDownloads(download_copy);
518}
519
[email protected]8ddbd66a2010-05-21 16:38:34520void DownloadManager::GetAllDownloads(Observer* observer,
521 const FilePath& dir_path) {
522 DCHECK(observer);
523
524 std::vector<DownloadItem*> download_copy;
525
526 for (DownloadMap::iterator it = downloads_.begin();
527 it != downloads_.end(); ++it) {
528 if (!it->second->is_temporary() &&
529 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
530 download_copy.push_back(it->second);
531 }
532
533 observer->SetDownloads(download_copy);
534}
535
[email protected]c4a530b2010-03-08 17:33:03536void DownloadManager::GetCurrentDownloads(Observer* observer,
537 const FilePath& dir_path) {
538 DCHECK(observer);
539
540 std::vector<DownloadItem*> download_copy;
541
542 for (DownloadMap::iterator it = downloads_.begin();
543 it != downloads_.end(); ++it) {
544 if (!it->second->is_temporary() &&
545 (it->second->state() == DownloadItem::IN_PROGRESS ||
546 it->second->safety_state() == DownloadItem::DANGEROUS) &&
547 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
548 download_copy.push_back(it->second);
549 }
550
551 observer->SetDownloads(download_copy);
552}
553
initial.commit09911bf2008-07-26 23:55:29554// Query the history service for information about all persisted downloads.
555bool DownloadManager::Init(Profile* profile) {
556 DCHECK(profile);
557 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
558 shutdown_needed_ = true;
559
560 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31561 request_context_getter_ = profile_->GetRequestContext();
initial.commit09911bf2008-07-26 23:55:29562
563 // 'incognito mode' will have access to past downloads, but we won't store
564 // information about new downloads while in that mode.
565 QueryHistoryForDownloads();
566
[email protected]024f2f02010-04-30 22:51:46567 // Cleans up entries only when called for the first time. Subsequent calls are
568 // a no op.
569 CleanUpInProgressHistoryEntries();
570
initial.commit09911bf2008-07-26 23:55:29571 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
572 if (!rdh) {
573 NOTREACHED();
574 return false;
575 }
576
577 file_manager_ = rdh->download_file_manager();
578 if (!file_manager_) {
579 NOTREACHED();
580 return false;
581 }
582
initial.commit09911bf2008-07-26 23:55:29583 // Get our user preference state.
584 PrefService* prefs = profile_->GetPrefs();
585 DCHECK(prefs);
586 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
587
initial.commit09911bf2008-07-26 23:55:29588 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
589
[email protected]bb69e9b32008-08-14 23:08:14590 // Ensure that the download directory specified in the preferences exists.
[email protected]d83d03aa2009-11-02 21:44:37591 ChromeThread::PostTask(
592 ChromeThread::FILE, FROM_HERE,
[email protected]309b7642009-12-09 03:08:50593 NewRunnableFunction(&file_util::CreateDirectory, download_path()));
initial.commit09911bf2008-07-26 23:55:29594
[email protected]2b2f8f72009-02-24 22:42:05595 // We store any file extension that should be opened automatically at
596 // download completion in this pref.
[email protected]ddd231e2010-06-29 20:35:19597 std::string extensions_to_open =
initial.commit09911bf2008-07-26 23:55:29598 prefs->GetString(prefs::kDownloadExtensionsToOpen);
[email protected]ddd231e2010-06-29 20:35:19599 std::vector<std::string> extensions;
600 SplitString(extensions_to_open, ':', &extensions);
601
initial.commit09911bf2008-07-26 23:55:29602 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]ddd231e2010-06-29 20:35:19603#if defined(OS_POSIX)
604 FilePath path(extensions[i]);
605#elif defined(OS_WIN)
606 FilePath path(UTF8ToWide(extensions[i]));
607#endif
608 if (!extensions[i].empty() && !IsExecutableFile(path))
609 auto_open_.insert(path.value());
initial.commit09911bf2008-07-26 23:55:29610 }
611
[email protected]b0ab1d42010-02-24 19:29:28612 other_download_manager_observer_.reset(
613 new OtherDownloadManagerObserver(this));
614
initial.commit09911bf2008-07-26 23:55:29615 return true;
616}
617
618void DownloadManager::QueryHistoryForDownloads() {
619 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
620 if (hs) {
621 hs->QueryDownloads(
622 &cancelable_consumer_,
623 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
624 }
625}
626
[email protected]024f2f02010-04-30 22:51:46627void DownloadManager::CleanUpInProgressHistoryEntries() {
628 static bool already_cleaned_up = false;
629
630 if (!already_cleaned_up) {
631 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
632 if (hs) {
633 hs->CleanUpInProgressEntries();
634 already_cleaned_up = true;
635 }
636 }
637}
638
initial.commit09911bf2008-07-26 23:55:29639// We have received a message from DownloadFileManager about a new download. We
640// create a download item and store it in our download map, and inform the
641// history system of a new download. Since this method can be called while the
642// history service thread is still reading the persistent state, we do not
643// insert the new DownloadItem into 'downloads_' or inform our observers at this
644// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
645// download creation as a callback from the history thread.
646void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37647 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29648 DCHECK(info);
649
[email protected]a60c8ae2009-12-25 06:50:57650 // Check whether this download is for an extension install or not.
651 if (!info->save_as) { // Allow extensions to be explicitly saved.
652 if (UserScript::HasUserScriptFileExtension(info->url) ||
653 info->mime_type == Extension::kMimeType)
654 info->is_extension_install = true;
655 }
656
[email protected]7d3851d82008-12-12 03:26:07657 // Freeze the user's preference for showing a Save As dialog. We're going to
658 // bounce around a bunch of threads and we don't want to worry about race
659 // conditions where the user changes this pref out from under us.
[email protected]7bc4f702009-09-25 22:12:38660 if (*prompt_for_download_) {
[email protected]486d25442010-03-18 17:34:26661 // But never obey the preference for the following scenarios:
662 // 1) Extension installation. Note that we only care here about the case
663 // where an extension is installed, not when one is downloaded with
664 // "save as...".
665 // 2) Drag-out download. Since we will save to the destination folder that
666 // is dropped to, we should not pop up a Save As dialog.
667 if (!info->is_extension_install && info->save_info.file_path.empty())
[email protected]7bc4f702009-09-25 22:12:38668 info->save_as = true;
669 }
[email protected]7d3851d82008-12-12 03:26:07670
[email protected]8af9d032010-02-10 00:00:32671 if (info->save_info.file_path.empty()) {
672 // Determine the proper path for a download, by either one of the following:
673 // 1) using the default download directory.
674 // 2) prompting the user.
675 FilePath generated_name;
676 GenerateFileNameFromInfo(info, &generated_name);
677 if (info->save_as && !last_download_path_.empty())
678 info->suggested_path = last_download_path_;
679 else
680 info->suggested_path = download_path();
681 info->suggested_path = info->suggested_path.Append(generated_name);
682 } else {
683 info->suggested_path = info->save_info.file_path;
684 }
initial.commit09911bf2008-07-26 23:55:29685
[email protected]8af9d032010-02-10 00:00:32686 if (!info->save_as && info->save_info.file_path.empty()) {
[email protected]4289d9b2009-07-25 21:17:34687 // Downloads can be marked as dangerous for two reasons:
688 // a) They have a dangerous-looking filename
689 // b) They are an extension that is not from the gallery
690 if (IsDangerous(info->suggested_path.BaseName()))
691 info->is_dangerous = true;
[email protected]a60c8ae2009-12-25 06:50:57692 else if (info->is_extension_install &&
[email protected]b7c2f252009-12-08 00:47:23693 !ExtensionsService::IsDownloadFromGallery(info->url,
694 info->referrer_url)) {
[email protected]4289d9b2009-07-25 21:17:34695 info->is_dangerous = true;
696 }
[email protected]e9ebf3fc2008-10-17 22:06:58697 }
698
initial.commit09911bf2008-07-26 23:55:29699 // We need to move over to the download thread because we don't want to stat
700 // the suggested path on the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37701 ChromeThread::PostTask(
702 ChromeThread::FILE, FROM_HERE,
703 NewRunnableMethod(
704 this, &DownloadManager::CheckIfSuggestedPathExists, info));
initial.commit09911bf2008-07-26 23:55:29705}
706
707void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
708 DCHECK(info);
709
710 // Check writability of the suggested path. If we can't write to it, default
711 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41712 FilePath dir = info->suggested_path.DirName();
713 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32714 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29715 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29716 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41717 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29718 }
719
[email protected]8af9d032010-02-10 00:00:32720 // Do not add the path uniquifier if we are saving to a specific path as in
721 // the drag-out case.
[email protected]5a2388a2010-03-26 16:13:39722 if (info->save_info.file_path.empty()) {
723 info->path_uniquifier = download_util::GetUniquePathNumber(
724 info->suggested_path);
725 }
initial.commit09911bf2008-07-26 23:55:29726
[email protected]6cade212008-12-03 00:32:22727 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58728 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41729 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32730 // Create a temporary file to hold the file until the user approves its
731 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41732 FilePath::StringType file_name;
733 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32734 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41735 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32736 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41737 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07738 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41739 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32740 }
741 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16742 } else {
743 // We know the final path, build it if necessary.
744 if (info->path_uniquifier > 0) {
[email protected]5a2388a2010-03-26 16:13:39745 download_util::AppendNumberToPath(&(info->suggested_path),
746 info->path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16747 // Setting path_uniquifier to 0 to make sure we don't try to unique it
748 // later on.
749 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07750 } else if (info->path_uniquifier == -1) {
751 // We failed to find a unique path. We have to prompt the user.
752 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16753 }
[email protected]9ccbb372008-10-10 18:50:32754 }
755
[email protected]8af9d032010-02-10 00:00:32756 if (!info->save_as && info->save_info.file_path.empty()) {
[email protected]7d3851d82008-12-12 03:26:07757 // Create an empty file at the suggested path so that we don't allocate the
758 // same "non-existant" path to multiple downloads.
759 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ff3f632009-10-13 18:43:35760 file_util::WriteFile(info->suggested_path, "", 0);
[email protected]7d3851d82008-12-12 03:26:07761 }
762
initial.commit09911bf2008-07-26 23:55:29763 // Now we return to the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37764 ChromeThread::PostTask(
765 ChromeThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29766 NewRunnableMethod(this,
767 &DownloadManager::OnPathExistenceAvailable,
768 info));
769}
770
771void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37772 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29773 DCHECK(info);
774
[email protected]7d3851d82008-12-12 03:26:07775 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29776 // We must ask the user for the place to put the download.
777 if (!select_file_dialog_.get())
778 select_file_dialog_ = SelectFileDialog::Create(this);
779
[email protected]76543b92009-08-31 17:27:45780 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
781 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08782 SelectFileDialog::FileTypeInfo file_type_info;
783 file_type_info.extensions.resize(1);
784 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24785 if (!file_type_info.extensions[0][0].empty())
786 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08787 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23788 gfx::NativeWindow owning_window =
789 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29790 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34791 string16(),
792 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08793 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30794 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29795 } else {
796 // No prompting for download, just continue with the suggested name.
797 ContinueStartDownload(info, info->suggested_path);
798 }
799}
800
801void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41802 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29803 scoped_ptr<DownloadCreateInfo> infop(info);
804 info->path = target_path;
805
806 DownloadItem* download = NULL;
807 DownloadMap::iterator it = in_progress_.find(info->download_id);
808 if (it == in_progress_.end()) {
809 download = new DownloadItem(info->download_id,
810 info->path,
[email protected]7a256ea2008-10-17 17:34:16811 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29812 info->url,
[email protected]494c06e2009-07-25 01:06:42813 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58814 info->mime_type,
[email protected]d4a71882010-06-25 16:36:41815 info->original_mime_type,
[email protected]9ccbb372008-10-10 18:50:32816 info->original_name,
initial.commit09911bf2008-07-26 23:55:29817 info->start_time,
818 info->total_bytes,
[email protected]76543b92009-08-31 17:27:45819 info->child_id,
[email protected]9ccbb372008-10-10 18:50:32820 info->request_id,
[email protected]67f373a2009-09-22 02:44:51821 info->is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57822 info->save_as,
[email protected]b0ab1d42010-02-24 19:29:28823 profile_->IsOffTheRecord(),
[email protected]6aa4a1c02010-01-15 18:49:58824 info->is_extension_install,
[email protected]8af9d032010-02-10 00:00:32825 !info->save_info.file_path.empty());
initial.commit09911bf2008-07-26 23:55:29826 download->set_manager(this);
827 in_progress_[info->download_id] = download;
828 } else {
829 NOTREACHED(); // Should not exist!
830 return;
831 }
832
[email protected]6b323782009-03-27 18:43:08833 // Called before DownloadFinished in order to avoid a race condition where we
834 // attempt to open a completed download before it has been renamed.
[email protected]d83d03aa2009-11-02 21:44:37835 ChromeThread::PostTask(
836 ChromeThread::FILE, FROM_HERE,
837 NewRunnableMethod(
838 file_manager_, &DownloadFileManager::OnFinalDownloadName,
839 download->id(), target_path, this));
[email protected]6b323782009-03-27 18:43:08840
initial.commit09911bf2008-07-26 23:55:29841 // If the download already completed by the time we reached this point, then
842 // notify observers that it did.
843 PendingFinishedMap::iterator pending_it =
844 pending_finished_downloads_.find(info->download_id);
845 if (pending_it != pending_finished_downloads_.end())
846 DownloadFinished(pending_it->first, pending_it->second);
847
848 download->Rename(target_path);
849
[email protected]67f373a2009-09-22 02:44:51850 // Do not store the download in the history database for a few special cases:
851 // - incognito mode (that is the point of this mode)
852 // - extensions (users don't think of extension installation as 'downloading')
[email protected]6aa4a1c02010-01-15 18:49:58853 // - temporary download, like in drag-and-drop
[email protected]67f373a2009-09-22 02:44:51854 // We have to make sure that these handles don't collide with normal db
855 // handles, so we use a negative value. Eventually, they could overlap, but
856 // you'd have to do enough downloading that your ISP would likely stab you in
857 // the neck first. YMMV.
[email protected]b0ab1d42010-02-24 19:29:28858 if (download->is_otr() || download->is_extension_install() ||
[email protected]6aa4a1c02010-01-15 18:49:58859 download->is_temporary()) {
[email protected]d2a8fb72010-01-21 05:31:42860 OnCreateDownloadEntryComplete(*info, fake_db_handle_.GetNext());
initial.commit09911bf2008-07-26 23:55:29861 } else {
862 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22863 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29864 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
865 if (hs) {
866 hs->CreateDownload(
867 *info, &cancelable_consumer_,
868 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
869 }
870 }
[email protected]6a7fb042010-02-01 16:30:47871
872 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29873}
874
875// Convenience function for updating the history service for a download.
876void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
877 DCHECK(download);
878
879 // Don't store info in the database if the download was initiated while in
880 // incognito mode or if it hasn't been initialized in our database table.
881 if (download->db_handle() <= kUninitializedHandle)
882 return;
883
[email protected]6cade212008-12-03 00:32:22884 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29885 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
886 if (hs) {
887 hs->UpdateDownload(download->received_bytes(),
888 download->state(),
889 download->db_handle());
890 }
891}
892
893void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
894 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22895 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29896 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
897 if (download->db_handle() > kUninitializedHandle && hs)
898 hs->RemoveDownload(download->db_handle());
899}
900
[email protected]e93d2822009-01-30 05:59:59901void DownloadManager::RemoveDownloadsFromHistoryBetween(
902 const base::Time remove_begin,
903 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22904 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29905 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
906 if (hs)
907 hs->RemoveDownloadsBetween(remove_begin, remove_end);
908}
909
910void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
911 DownloadMap::iterator it = in_progress_.find(download_id);
912 if (it != in_progress_.end()) {
913 DownloadItem* download = it->second;
914 download->Update(size);
915 UpdateHistoryForDownload(download);
916 }
[email protected]6a7fb042010-02-01 16:30:47917 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29918}
919
920void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
921 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32922 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29923 // The download is done, but the user hasn't selected a final location for
924 // it yet (the Save As dialog box is probably still showing), so just keep
925 // track of the fact that this download id is complete, when the
926 // DownloadItem is constructed later we'll notify its completion then.
927 PendingFinishedMap::iterator erase_it =
928 pending_finished_downloads_.find(download_id);
929 DCHECK(erase_it == pending_finished_downloads_.end());
930 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32931 return;
initial.commit09911bf2008-07-26 23:55:29932 }
[email protected]9ccbb372008-10-10 18:50:32933
934 // Remove the id from the list of pending ids.
935 PendingFinishedMap::iterator erase_it =
936 pending_finished_downloads_.find(download_id);
937 if (erase_it != pending_finished_downloads_.end())
938 pending_finished_downloads_.erase(erase_it);
939
940 DownloadItem* download = it->second;
941 download->Finished(size);
942
943 // Clean up will happen when the history system create callback runs if we
944 // don't have a valid db_handle yet.
945 if (download->db_handle() != kUninitializedHandle) {
946 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32947 UpdateHistoryForDownload(download);
948 }
949
[email protected]6a7fb042010-02-01 16:30:47950 UpdateAppIcon();
951
[email protected]9ccbb372008-10-10 18:50:32952 // If this a dangerous download not yet validated by the user, don't do
953 // anything. When the user notifies us, it will trigger a call to
954 // ProceedWithFinishedDangerousDownload.
955 if (download->safety_state() == DownloadItem::DANGEROUS) {
956 dangerous_finished_[download_id] = download;
957 return;
958 }
959
960 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22961 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32962 // its final name before we can continue.
[email protected]d83d03aa2009-11-02 21:44:37963 ChromeThread::PostTask(
964 ChromeThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32965 NewRunnableMethod(
966 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
967 download->db_handle(),
968 download->full_path(), download->original_name()));
969 return;
970 }
971 ContinueDownloadFinished(download);
972}
973
[email protected]8f783752009-04-01 23:33:45974void DownloadManager::DownloadRenamedToFinalName(int download_id,
975 const FilePath& full_path) {
[email protected]6aa4a1c02010-01-15 18:49:58976 DownloadMap::iterator it = downloads_.begin();
977 while (it != downloads_.end()) {
978 DownloadItem* download = it->second;
979 if (download->id() == download_id) {
980 // The download file is meant to be completed if both the filename is
981 // finalized and the file data is downloaded. The ordering of these two
982 // actions is indeterministic. Thus, if we are still in downloading the
983 // file, delay the notification.
984 download->set_name_finalized(true);
985 if (download->state() == DownloadItem::COMPLETE)
986 download->NotifyObserversDownloadFileCompleted();
987 return;
988 }
989 it++;
990 }
[email protected]8f783752009-04-01 23:33:45991}
992
[email protected]9ccbb372008-10-10 18:50:32993void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
994 // If this was a dangerous download, it has now been approved and must be
995 // removed from dangerous_finished_ so it does not get deleted on shutdown.
996 DownloadMap::iterator it = dangerous_finished_.find(download->id());
997 if (it != dangerous_finished_.end())
998 dangerous_finished_.erase(it);
999
[email protected]0aad67b2009-07-15 20:34:281000 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]a60c8ae2009-12-25 06:50:571001 if (download->is_extension_install()) {
[email protected]d4a71882010-06-25 16:36:411002 OpenChromeExtension(download->full_path(),
1003 download->url(),
1004 download->referrer_url(),
1005 download->original_mime_type());
[email protected]0aad67b2009-07-15 20:34:281006 download->set_auto_opened(true);
1007 } else if (download->open_when_complete() ||
[email protected]6aa4a1c02010-01-15 18:49:581008 ShouldOpenFileBasedOnExtension(download->full_path()) ||
1009 download->is_temporary()) {
1010 // If the download is temporary, like in drag-and-drop, do not open it but
1011 // we still need to set it auto-opened so that it can be removed from the
1012 // download shelf.
1013 if (!download->is_temporary())
1014 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:281015 download->set_auto_opened(true);
1016 }
[email protected]9ccbb372008-10-10 18:50:321017
[email protected]0aad67b2009-07-15 20:34:281018 // Notify our observers that we are complete (the call to Finished() set the
1019 // state to complete but did not notify).
1020 download->UpdateObservers();
[email protected]6aa4a1c02010-01-15 18:49:581021
1022 // The download file is meant to be completed if both the filename is
1023 // finalized and the file data is downloaded. The ordering of these two
1024 // actions is indeterministic. Thus, if the filename is not finalized yet,
1025 // delay the notification.
1026 if (download->name_finalized())
1027 download->NotifyObserversDownloadFileCompleted();
[email protected]0aad67b2009-07-15 20:34:281028}
[email protected]eccb9d12009-10-28 05:40:091029
[email protected]9ccbb372008-10-10 18:50:321030// Called on the file thread. Renames the downloaded file to its original name.
1031void DownloadManager::ProceedWithFinishedDangerousDownload(
1032 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:411033 const FilePath& path,
1034 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:321035 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:411036 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:161037 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:321038 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:241039 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:161040 // Make our name unique at this point, as if a dangerous file is downloading
1041 // and a 2nd download is started for a file with the same name, they would
1042 // have the same path. This is because we uniquify the name on download
1043 // start, and at that time the first file does not exists yet, so the second
1044 // file gets the same name.
[email protected]5a2388a2010-03-26 16:13:391045 uniquifier = download_util::GetUniquePathNumber(new_path);
[email protected]7a256ea2008-10-17 17:34:161046 if (uniquifier > 0)
[email protected]5a2388a2010-03-26 16:13:391047 download_util::AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:321048 success = file_util::Move(path, new_path);
1049 } else {
1050 NOTREACHED();
1051 }
[email protected]6cade212008-12-03 00:32:221052
[email protected]d83d03aa2009-11-02 21:44:371053 ChromeThread::PostTask(
1054 ChromeThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:321055 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:161056 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:321057}
1058
1059// Call from the file thread when the finished dangerous download was renamed.
1060void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
1061 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:411062 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:161063 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:321064 DownloadMap::iterator it = downloads_.find(download_handle);
1065 if (it == downloads_.end()) {
1066 NOTREACHED();
1067 return;
1068 }
1069
1070 DownloadItem* download = it->second;
1071 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:161072 if (success) {
1073 // We need to update the path uniquifier so that the UI shows the right
1074 // name when calling GetFileName().
1075 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:321076 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:161077 }
[email protected]9ccbb372008-10-10 18:50:321078
1079 // Continue the download finished sequence.
1080 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:291081}
1082
1083// static
initial.commit09911bf2008-07-26 23:55:291084void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
1085 int render_process_id,
1086 int request_id) {
[email protected]d85cf072009-10-27 03:59:311087 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
initial.commit09911bf2008-07-26 23:55:291088 rdh->CancelRequest(render_process_id, request_id, false);
1089}
1090
1091void DownloadManager::DownloadCancelled(int32 download_id) {
1092 DownloadMap::iterator it = in_progress_.find(download_id);
1093 if (it == in_progress_.end())
1094 return;
1095 DownloadItem* download = it->second;
1096
initial.commit09911bf2008-07-26 23:55:291097 // Clean up will happen when the history system create callback runs if we
1098 // don't have a valid db_handle yet.
1099 if (download->db_handle() != kUninitializedHandle) {
1100 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291101 UpdateHistoryForDownload(download);
1102 }
1103
[email protected]d7d1c5c2009-08-05 23:52:501104 DownloadCancelledInternal(download_id,
1105 download->render_process_id(),
1106 download->request_id());
[email protected]6a7fb042010-02-01 16:30:471107 UpdateAppIcon();
[email protected]d7d1c5c2009-08-05 23:52:501108}
1109
1110void DownloadManager::DownloadCancelledInternal(int download_id,
1111 int render_process_id,
1112 int request_id) {
[email protected]d85cf072009-10-27 03:59:311113 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
1114 ChromeThread::PostTask(
1115 ChromeThread::IO, FROM_HERE,
1116 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
1117 g_browser_process->resource_dispatcher_host(),
1118 render_process_id,
1119 request_id));
[email protected]d7d1c5c2009-08-05 23:52:501120
initial.commit09911bf2008-07-26 23:55:291121 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:501122 file_manager_->RemoveDownload(download_id, this); // On the UI thread
[email protected]d83d03aa2009-11-02 21:44:371123 ChromeThread::PostTask(
1124 ChromeThread::FILE, FROM_HERE,
1125 NewRunnableMethod(
1126 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:291127}
1128
1129void DownloadManager::PauseDownload(int32 download_id, bool pause) {
1130 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:311131 if (it == in_progress_.end())
1132 return;
initial.commit09911bf2008-07-26 23:55:291133
[email protected]d85cf072009-10-27 03:59:311134 DownloadItem* download = it->second;
1135 if (pause == download->is_paused())
1136 return;
initial.commit09911bf2008-07-26 23:55:291137
[email protected]d85cf072009-10-27 03:59:311138 // Inform the ResourceDispatcherHost of the new pause state.
1139 ChromeThread::PostTask(
1140 ChromeThread::IO, FROM_HERE,
1141 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
1142 g_browser_process->resource_dispatcher_host(),
1143 download->render_process_id(),
1144 download->request_id(),
1145 pause));
initial.commit09911bf2008-07-26 23:55:291146}
1147
1148// static
1149void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
1150 int render_process_id,
1151 int request_id,
1152 bool pause) {
1153 rdh->PauseRequest(render_process_id, request_id, pause);
1154}
1155
[email protected]7ae7c2cb2009-01-06 23:31:411156bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:321157 // TODO(jcampan): Improve me.
[email protected]eccb9d12009-10-28 05:40:091158 return IsExecutableFile(file_name);
[email protected]9ccbb372008-10-10 18:50:321159}
1160
[email protected]6a7fb042010-02-01 16:30:471161void DownloadManager::UpdateAppIcon() {
1162 int64 total_bytes = 0;
1163 int64 received_bytes = 0;
1164 int download_count = 0;
1165 bool progress_known = true;
1166
1167 for (DownloadMap::iterator i = in_progress_.begin();
1168 i != in_progress_.end();
1169 ++i) {
1170 ++download_count;
1171 const DownloadItem* item = i->second;
1172 if (item->total_bytes() > 0) {
1173 total_bytes += item->total_bytes();
1174 received_bytes += item->received_bytes();
1175 } else {
1176 // This download didn't specify a Content-Length, so the combined progress
1177 // bar neeeds to be indeterminate.
1178 progress_known = false;
1179 }
1180 }
1181
1182 float progress = 0;
1183 if (progress_known && download_count)
1184 progress = (float)received_bytes / total_bytes;
1185
1186 download_util::UpdateAppIconDownloadProgress(download_count,
1187 progress_known,
1188 progress);
1189}
1190
[email protected]9ccbb372008-10-10 18:50:321191void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411192 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321193 download->Rename(new_path);
1194
1195 // Update the history.
1196
1197 // No update necessary if the download was initiated while in incognito mode.
1198 if (download->db_handle() <= kUninitializedHandle)
1199 return;
1200
[email protected]6cade212008-12-03 00:32:221201 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321202 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1203 if (hs)
[email protected]e53668962010-06-23 15:35:251204 hs->UpdateDownloadPath(new_path, download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321205}
1206
initial.commit09911bf2008-07-26 23:55:291207void DownloadManager::RemoveDownload(int64 download_handle) {
1208 DownloadMap::iterator it = downloads_.find(download_handle);
1209 if (it == downloads_.end())
1210 return;
1211
1212 // Make history update.
1213 DownloadItem* download = it->second;
1214 RemoveDownloadFromHistory(download);
1215
1216 // Remove from our tables and delete.
1217 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321218 it = dangerous_finished_.find(download->id());
1219 if (it != dangerous_finished_.end())
1220 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291221
1222 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:281223 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:361224
1225 delete download;
initial.commit09911bf2008-07-26 23:55:291226}
1227
[email protected]e93d2822009-01-30 05:59:591228int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1229 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291230 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1231
initial.commit09911bf2008-07-26 23:55:291232 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281233 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291234 while (it != downloads_.end()) {
1235 DownloadItem* download = it->second;
1236 DownloadItem::DownloadState state = download->state();
1237 if (download->start_time() >= remove_begin &&
1238 (remove_end.is_null() || download->start_time() < remove_end) &&
1239 (state == DownloadItem::COMPLETE ||
1240 state == DownloadItem::CANCELLED)) {
1241 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561242 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581243
1244 // Also remove it from any completed dangerous downloads.
1245 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1246 if (dit != dangerous_finished_.end())
1247 dangerous_finished_.erase(dit);
1248
[email protected]78b8fcc92009-03-31 17:36:281249 pending_deletes.push_back(download);
[email protected]b0ab1d42010-02-24 19:29:281250 // Observer interface.
initial.commit09911bf2008-07-26 23:55:291251
initial.commit09911bf2008-07-26 23:55:291252 continue;
1253 }
1254
1255 ++it;
1256 }
1257
1258 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281259 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291260 if (num_deleted > 0)
[email protected]b0ab1d42010-02-24 19:29:281261 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291262
[email protected]78b8fcc92009-03-31 17:36:281263 // Delete the download items after updating the observers.
1264 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1265 pending_deletes.clear();
1266
initial.commit09911bf2008-07-26 23:55:291267 return num_deleted;
1268}
1269
[email protected]e93d2822009-01-30 05:59:591270int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1271 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291272}
1273
[email protected]d41355e6f2009-04-07 21:21:121274int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:461275 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
1276 // This is an incognito downloader. Clear All should clear main download
1277 // manager as well.
1278 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
1279 }
[email protected]d41355e6f2009-04-07 21:21:121280 // The null times make the date range unbounded.
1281 return RemoveDownloadsBetween(base::Time(), base::Time());
1282}
1283
initial.commit09911bf2008-07-26 23:55:291284// Initiate a download of a specific URL. We send the request to the
1285// ResourceDispatcherHost, and let it send us responses like a regular
1286// download.
1287void DownloadManager::DownloadUrl(const GURL& url,
1288 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501289 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341290 TabContents* tab_contents) {
[email protected]6aa4a1c02010-01-15 18:49:581291 file_manager_->DownloadUrl(url,
1292 referrer,
1293 referrer_charset,
[email protected]8af9d032010-02-10 00:00:321294 DownloadSaveInfo(),
[email protected]8cb5d5b2010-02-09 11:36:161295 tab_contents->GetRenderProcessHost()->id(),
[email protected]6aa4a1c02010-01-15 18:49:581296 tab_contents->render_view_host()->routing_id(),
1297 request_context_getter_);
1298}
1299
1300void DownloadManager::DownloadUrlToFile(const GURL& url,
1301 const GURL& referrer,
1302 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:321303 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:581304 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:341305 DCHECK(tab_contents);
initial.commit09911bf2008-07-26 23:55:291306 file_manager_->DownloadUrl(url,
1307 referrer,
[email protected]be180c802009-10-23 06:33:311308 referrer_charset,
[email protected]8af9d032010-02-10 00:00:321309 save_info,
[email protected]8cb5d5b2010-02-09 11:36:161310 tab_contents->GetRenderProcessHost()->id(),
[email protected]57c6a652009-05-04 07:58:341311 tab_contents->render_view_host()->routing_id(),
[email protected]be180c802009-10-23 06:33:311312 request_context_getter_);
initial.commit09911bf2008-07-26 23:55:291313}
1314
[email protected]7ae7c2cb2009-01-06 23:31:411315void DownloadManager::GenerateExtension(
1316 const FilePath& file_name,
1317 const std::string& mime_type,
1318 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291319 // We're worried about three things here:
1320 //
1321 // 1) Security. Many sites let users upload content, such as buddy icons, to
1322 // their web sites. We want to mitigate the case where an attacker
1323 // supplies a malicious executable with an executable file extension but an
1324 // honest site serves the content with a benign content type, such as
1325 // image/jpeg.
1326 //
1327 // 2) Usability. If the site fails to provide a file extension, we want to
1328 // guess a reasonable file extension based on the content type.
1329 //
1330 // 3) Shell integration. Some file extensions automatically integrate with
1331 // the shell. We block these extensions to prevent a malicious web site
1332 // from integrating with the user's shell.
1333
[email protected]7ae7c2cb2009-01-06 23:31:411334 static const FilePath::CharType default_extension[] =
1335 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291336
1337 // See if our file name already contains an extension.
[email protected]63597e4e2010-07-08 17:49:051338 FilePath::StringType extension = file_name.Extension();
1339 if (!extension.empty())
1340 extension.erase(extension.begin()); // Erase preceding '.'.
initial.commit09911bf2008-07-26 23:55:291341
[email protected]b7f05882009-02-22 01:21:561342#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291343 // Rename shell-integrated extensions.
1344 if (win_util::IsShellIntegratedExtension(extension))
1345 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561346#endif
initial.commit09911bf2008-07-26 23:55:291347
1348 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411349 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411350 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291351 if (mime_type == mime_type_from_extension) {
1352 // The hinted extension matches the mime type. It looks like a winner.
1353 generated_extension->swap(extension);
1354 return;
1355 }
1356
[email protected]eccb9d12009-10-28 05:40:091357 if (IsExecutableExtension(extension) && !IsExecutableMimeType(mime_type)) {
initial.commit09911bf2008-07-26 23:55:291358 // We want to be careful about executable extensions. The worry here is
1359 // that a trusted web site could be tricked into dropping an executable file
1360 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101361 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291362 // We couldn't find a good extension for this content type. Use a dummy
1363 // extension instead.
1364 extension.assign(default_extension);
1365 }
1366 }
1367
1368 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101369 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291370 } else {
[email protected]6cade212008-12-03 00:32:221371 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291372 // 1. New extension is not ".txt"
1373 // 2. New extension is not the same as the already existing extension.
1374 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411375 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291376 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1377 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371378 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1379 // servers, i.e. bug 5772.
[email protected]e32642f62009-09-11 21:58:291380 // 5. The original extension is not ".tgz" & the new extension is not "gz".
[email protected]7ae7c2cb2009-01-06 23:31:411381 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101382 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171383 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411384 append_extension != extension &&
[email protected]eccb9d12009-10-28 05:40:091385 !IsExecutableExtension(append_extension) &&
[email protected]e32642f62009-09-11 21:58:291386 !(append_extension == FILE_PATH_LITERAL("gz") &&
1387 extension == FILE_PATH_LITERAL("tgz")) &&
[email protected]e106457b2009-03-25 22:43:371388 (append_extension != FILE_PATH_LITERAL("tar") ||
1389 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171390 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291391 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171392 }
initial.commit09911bf2008-07-26 23:55:291393 }
1394 }
1395
1396 generated_extension->swap(extension);
1397}
1398
[email protected]6aa4a1c02010-01-15 18:49:581399void DownloadManager::GenerateFileNameFromInfo(DownloadCreateInfo* info,
1400 FilePath* generated_name) {
1401 GenerateFileName(GURL(info->url),
1402 info->content_disposition,
1403 info->referrer_charset,
1404 info->mime_type,
1405 generated_name);
1406}
1407
1408void DownloadManager::GenerateFileName(const GURL& url,
1409 const std::string& content_disposition,
1410 const std::string& referrer_charset,
1411 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411412 FilePath* generated_name) {
[email protected]630947c2009-11-04 18:37:311413 std::wstring default_name =
1414 l10n_util::GetString(IDS_DEFAULT_DOWNLOAD_FILENAME);
1415#if defined(OS_WIN)
1416 FilePath default_file_path(default_name);
1417#elif defined(OS_POSIX)
1418 FilePath default_file_path(base::SysWideToNativeMB(default_name));
1419#endif
1420
[email protected]6aa4a1c02010-01-15 18:49:581421 *generated_name = net::GetSuggestedFilename(GURL(url),
1422 content_disposition,
1423 referrer_charset,
[email protected]630947c2009-11-04 18:37:311424 default_file_path);
1425
[email protected]7ae7c2cb2009-01-06 23:31:411426 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291427
[email protected]6aa4a1c02010-01-15 18:49:581428 GenerateSafeFileName(mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291429}
1430
1431void DownloadManager::AddObserver(Observer* observer) {
1432 observers_.AddObserver(observer);
1433 observer->ModelChanged();
1434}
1435
1436void DownloadManager::RemoveObserver(Observer* observer) {
1437 observers_.RemoveObserver(observer);
1438}
1439
1440// Post Windows Shell operations to the Download thread, to avoid blocking the
1441// user interface.
1442void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1443 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371444 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581445#if defined(OS_MACOSX)
1446 // Mac needs to run this operation on the UI thread.
1447 platform_util::ShowItemInFolder(download->full_path());
1448#else
[email protected]d83d03aa2009-11-02 21:44:371449 ChromeThread::PostTask(
1450 ChromeThread::FILE, FROM_HERE,
1451 NewRunnableMethod(
1452 file_manager_, &DownloadFileManager::OnShowDownloadInShell,
1453 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581454#endif
initial.commit09911bf2008-07-26 23:55:291455}
1456
[email protected]8f783752009-04-01 23:33:451457void DownloadManager::OpenDownload(const DownloadItem* download,
1458 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401459 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451460 // execute.
[email protected]a60c8ae2009-12-25 06:50:571461 if (download->is_extension_install()) {
[email protected]d4a71882010-06-25 16:36:411462 OpenChromeExtension(download->full_path(),
1463 download->url(),
1464 download->referrer_url(),
1465 download->original_mime_type());
[email protected]8f783752009-04-01 23:33:451466 } else {
1467 OpenDownloadInShell(download, parent_window);
1468 }
1469}
1470
[email protected]d4a71882010-06-25 16:36:411471void DownloadManager::OpenChromeExtension(
1472 const FilePath& full_path,
1473 const GURL& download_url,
1474 const GURL& referrer_url,
1475 const std::string& original_mime_type) {
[email protected]6ef635e42009-07-26 06:16:121476 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351477 ExtensionsService* service = profile_->GetExtensionsService();
1478 if (service) {
[email protected]91e1bd82009-09-03 22:04:401479 NotificationService* nservice = NotificationService::current();
[email protected]6dfbbf82010-03-12 23:09:161480 GURL nonconst_download_url = download_url;
1481 nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
1482 Source<DownloadManager>(this),
1483 Details<GURL>(&nonconst_download_url));
1484
1485 scoped_refptr<CrxInstaller> installer(
1486 new CrxInstaller(service->install_directory(),
1487 service,
1488 new ExtensionInstallUI(profile_)));
1489 installer->set_delete_source(true);
1490
[email protected]a050d712009-11-06 00:40:101491 if (UserScript::HasUserScriptFileExtension(download_url)) {
[email protected]6dfbbf82010-03-12 23:09:161492 installer->InstallUserScript(full_path, download_url);
[email protected]6657afa62009-11-04 02:15:201493 } else {
[email protected]be18e1582010-06-03 21:50:421494 bool is_gallery_download =
1495 ExtensionsService::IsDownloadFromGallery(download_url, referrer_url);
[email protected]d4a71882010-06-25 16:36:411496 installer->set_original_mime_type(original_mime_type);
1497 installer->set_apps_require_extension_mime_type(true);
[email protected]6dfbbf82010-03-12 23:09:161498 installer->set_allow_privilege_increase(true);
1499 installer->set_original_url(download_url);
[email protected]9f72aa02010-06-25 10:01:051500 installer->set_limit_web_extent_to_download_host(!is_gallery_download);
[email protected]6dfbbf82010-03-12 23:09:161501 installer->InstallCrx(full_path);
[email protected]6657afa62009-11-04 02:15:201502 }
[email protected]21ca982c2010-01-26 22:49:551503 } else {
1504 TabContents* contents = NULL;
[email protected]a65bce4e2010-06-09 16:00:151505 // Get last active normal browser of profile.
1506 Browser* last_active = BrowserList::FindBrowserWithType(profile_,
[email protected]074e4f42010-06-23 16:12:061507 Browser::TYPE_NORMAL, true);
[email protected]21ca982c2010-01-26 22:49:551508 if (last_active)
1509 contents = last_active->GetSelectedTabContents();
1510 if (contents) {
1511 contents->AddInfoBar(
1512 new SimpleAlertInfoBarDelegate(contents,
1513 l10n_util::GetString(
1514 IDS_EXTENSION_INCOGNITO_INSTALL_INFOBAR_LABEL),
1515 ResourceBundle::GetSharedInstance().GetBitmapNamed(
[email protected]938e1f92010-04-01 18:09:421516 IDR_INFOBAR_PLUGIN_INSTALL),
1517 true));
[email protected]21ca982c2010-01-26 22:49:551518 }
[email protected]2a464a92009-08-01 17:58:351519 }
[email protected]8f783752009-04-01 23:33:451520}
1521
initial.commit09911bf2008-07-26 23:55:291522void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591523 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291524 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371525 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581526#if defined(OS_MACOSX)
1527 // Mac OS X requires opening downloads on the UI thread.
1528 platform_util::OpenItem(download->full_path());
1529#else
[email protected]d83d03aa2009-11-02 21:44:371530 ChromeThread::PostTask(
1531 ChromeThread::FILE, FROM_HERE,
1532 NewRunnableMethod(
1533 file_manager_, &DownloadFileManager::OnOpenDownloadInShell,
1534 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581535#endif
initial.commit09911bf2008-07-26 23:55:291536}
1537
[email protected]eccb9d12009-10-28 05:40:091538void DownloadManager::OpenFilesBasedOnExtension(
1539 const FilePath& path, bool open) {
1540 FilePath::StringType extension = path.Extension();
1541 if (extension.empty())
1542 return;
1543 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1544 extension.erase(0, 1);
1545 if (open && !IsExecutableExtension(extension))
initial.commit09911bf2008-07-26 23:55:291546 auto_open_.insert(extension);
1547 else
1548 auto_open_.erase(extension);
1549 SaveAutoOpens();
1550}
1551
[email protected]eccb9d12009-10-28 05:40:091552bool DownloadManager::ShouldOpenFileBasedOnExtension(
1553 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:091554 FilePath::StringType extension = path.Extension();
1555 if (extension.empty())
1556 return false;
1557 if (IsExecutableExtension(extension))
1558 return false;
[email protected]92e11c82010-01-13 06:39:561559 if (Extension::IsExtension(path))
1560 return false;
[email protected]eccb9d12009-10-28 05:40:091561 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1562 extension.erase(0, 1);
[email protected]92e11c82010-01-13 06:39:561563 if (auto_open_.find(extension) != auto_open_.end())
[email protected]8c756ac2009-01-30 23:36:411564 return true;
initial.commit09911bf2008-07-26 23:55:291565 return false;
1566}
1567
[email protected]7b73d992008-12-15 20:56:461568static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291569 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461570 "text/javascript",
1571 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241572 // Registry files can cause critical changes to the MS OS behavior.
1573 // Addition of this mimetype also addresses bug 7337.
1574 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391575 // Some sites use binary/octet-stream to mean application/octet-stream.
1576 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461577 "binary/octet-stream"
1578};
initial.commit09911bf2008-07-26 23:55:291579
[email protected]7b73d992008-12-15 20:56:461580static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291581 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461582 "application/*+xml",
1583 "application/xml"
1584};
initial.commit09911bf2008-07-26 23:55:291585
[email protected]7b73d992008-12-15 20:56:461586// static
1587bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411588 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461589 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1590 return true;
1591 }
[email protected]bae0ea12009-02-14 01:20:411592 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461593 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1594 return false;
1595 }
1596 // We consider only other application types to be executable.
1597 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291598}
1599
[email protected]eccb9d12009-10-28 05:40:091600bool DownloadManager::IsExecutableFile(const FilePath& path) const {
1601 return IsExecutableExtension(path.Extension());
1602}
1603
1604bool DownloadManager::IsExecutableExtension(
[email protected]6aa4a1c02010-01-15 18:49:581605 const FilePath::StringType& extension) {
[email protected]eccb9d12009-10-28 05:40:091606 if (extension.empty())
1607 return false;
[email protected]64da0b932009-02-24 02:30:041608 if (!IsStringASCII(extension))
1609 return false;
[email protected]a0a9577b2009-05-27 23:52:321610#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041611 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131612#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321613 std::string ascii_extension = extension;
1614#endif
[email protected]64da0b932009-02-24 02:30:041615
[email protected]eccb9d12009-10-28 05:40:091616 // Strip out leading dot if it's still there
1617 if (ascii_extension[0] == FilePath::kExtensionSeparator)
1618 ascii_extension.erase(0, 1);
1619
[email protected]6aa4a1c02010-01-15 18:49:581620 return download_util::IsExecutableExtension(ascii_extension);
initial.commit09911bf2008-07-26 23:55:291621}
1622
1623void DownloadManager::ResetAutoOpenFiles() {
1624 auto_open_.clear();
1625 SaveAutoOpens();
1626}
1627
1628bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1629 return !auto_open_.empty();
1630}
1631
1632void DownloadManager::SaveAutoOpens() {
1633 PrefService* prefs = profile_->GetPrefs();
1634 if (prefs) {
[email protected]ddd231e2010-06-29 20:35:191635 std::string extensions;
[email protected]eccb9d12009-10-28 05:40:091636 for (AutoOpenSet::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291637 it != auto_open_.end(); ++it) {
[email protected]ddd231e2010-06-29 20:35:191638#if defined(OS_POSIX)
1639 std::string this_extension = *it;
1640#elif defined(OS_WIN)
1641 std::string this_extension = base::SysWideToUTF8(*it);
1642#endif
1643 extensions += this_extension + ":";
initial.commit09911bf2008-07-26 23:55:291644 }
1645 if (!extensions.empty())
1646 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561647
[email protected]ddd231e2010-06-29 20:35:191648 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions);
initial.commit09911bf2008-07-26 23:55:291649 }
1650}
1651
[email protected]561abe62009-04-06 18:08:341652void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361653 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291654 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071655 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411656 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291657 ContinueStartDownload(info, path);
1658}
1659
1660void DownloadManager::FileSelectionCanceled(void* params) {
1661 // The user didn't pick a place to save the file, so need to cancel the
1662 // download that's already in progress to the temporary location.
1663 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501664 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451665 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501666 info->request_id);
initial.commit09911bf2008-07-26 23:55:291667}
1668
[email protected]7ae7c2cb2009-01-06 23:31:411669void DownloadManager::DeleteDownload(const FilePath& path) {
[email protected]d83d03aa2009-11-02 21:44:371670 ChromeThread::PostTask(
1671 ChromeThread::FILE, FROM_HERE,
[email protected]da74e5ae22010-07-14 16:12:371672 NewRunnableFunction(&DeleteDownloadedFile, path));
[email protected]9ccbb372008-10-10 18:50:321673}
1674
[email protected]9ccbb372008-10-10 18:50:321675void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1676 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1677 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1678 download->UpdateObservers();
1679
1680 // If the download is not complete, nothing to do. The required
1681 // post-processing will be performed when it does complete.
1682 if (download->state() != DownloadItem::COMPLETE)
1683 return;
1684
[email protected]d83d03aa2009-11-02 21:44:371685 ChromeThread::PostTask(
1686 ChromeThread::FILE, FROM_HERE,
1687 NewRunnableMethod(
1688 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
1689 download->db_handle(), download->full_path(),
1690 download->original_name()));
[email protected]9ccbb372008-10-10 18:50:321691}
1692
[email protected]6aa4a1c02010-01-15 18:49:581693void DownloadManager::GenerateSafeFileName(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411694 FilePath* file_name) {
1695 // Make sure we get the right file extension
1696 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391697 GenerateExtension(*file_name, mime_type, &extension);
[email protected]1bdaa60c2010-06-01 01:57:431698 *file_name = file_name->ReplaceExtension(extension);
[email protected]763f946a2009-01-06 19:04:391699
[email protected]2b2f8f72009-02-24 22:42:051700#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391701 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411702 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391703 DCHECK(!leaf_name.empty());
1704 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411705 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1706 *file_name = file_name->DirName();
1707 if (file_name->value() == FilePath::kCurrentDirectory) {
1708 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391709 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411710 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391711 }
1712 }
[email protected]b7f05882009-02-22 01:21:561713#endif
[email protected]763f946a2009-01-06 19:04:391714}
1715
initial.commit09911bf2008-07-26 23:55:291716// Operations posted to us from the history service ----------------------------
1717
1718// The history service has retrieved all download entries. 'entries' contains
1719// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1720void DownloadManager::OnQueryDownloadEntriesComplete(
1721 std::vector<DownloadCreateInfo>* entries) {
1722 for (size_t i = 0; i < entries->size(); ++i) {
1723 DownloadItem* download = new DownloadItem(entries->at(i));
1724 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1725 downloads_[download->db_handle()] = download;
1726 download->set_manager(this);
1727 }
[email protected]b0ab1d42010-02-24 19:29:281728 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291729}
1730
initial.commit09911bf2008-07-26 23:55:291731// Once the new DownloadItem's creation info has been committed to the history
1732// service, we associate the DownloadItem with the db handle, update our
1733// 'downloads_' map and inform observers.
1734void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1735 int64 db_handle) {
1736 DownloadMap::iterator it = in_progress_.find(info.download_id);
1737 DCHECK(it != in_progress_.end());
1738
1739 DownloadItem* download = it->second;
[email protected]d2a8fb72010-01-21 05:31:421740
1741 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1742 // call this function with an invalid |db_handle|. For instance, this can
1743 // happen when the history database is offline. We cannot have multiple
1744 // DownloadItems with the same invalid db_handle, so we need to assign a
1745 // unique |db_handle| here.
1746 if (db_handle == kUninitializedHandle)
1747 db_handle = fake_db_handle_.GetNext();
1748
initial.commit09911bf2008-07-26 23:55:291749 DCHECK(download->db_handle() == kUninitializedHandle);
1750 download->set_db_handle(db_handle);
1751
1752 // Insert into our full map.
1753 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1754 downloads_[download->db_handle()] = download;
1755
[email protected]5e595482009-05-06 20:16:531756 // Show in the appropropriate browser UI.
1757 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291758
1759 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281760 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291761
1762 // If this download has been completed before we've received the db handle,
1763 // post one final message to the history service so that it can be properly
1764 // in sync with the DownloadItem's completion status, and also inform any
1765 // observers so that they get more than just the start notification.
1766 if (download->state() != DownloadItem::IN_PROGRESS) {
1767 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291768 UpdateHistoryForDownload(download);
1769 download->UpdateObservers();
1770 }
[email protected]6a7fb042010-02-01 16:30:471771
1772 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:291773}
1774
1775// Called when the history service has retrieved the list of downloads that
1776// match the search text.
1777void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1778 std::vector<int64>* results) {
1779 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1780 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1781 if (!requestor)
1782 return;
1783
1784 std::vector<DownloadItem*> searched_downloads;
1785 for (std::vector<int64>::iterator it = results->begin();
1786 it != results->end(); ++it) {
1787 DownloadMap::iterator dit = downloads_.find(*it);
1788 if (dit != downloads_.end())
1789 searched_downloads.push_back(dit->second);
1790 }
1791
1792 requestor->SetDownloads(searched_downloads);
1793}
[email protected]905a08d2008-11-19 07:24:121794
[email protected]5e595482009-05-06 20:16:531795void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1796 DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341797 // The 'contents' may no longer exist if the user closed the tab before we
1798 // get this start completion event. If it does, tell the origin TabContents
1799 // to display its download shelf.
[email protected]76543b92009-08-31 17:27:451800 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1801 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531802
1803 // If the contents no longer exists, we start the download in the last active
1804 // browser. This is not ideal but better than fully hiding the download from
1805 // the user.
1806 if (!contents) {
1807 Browser* last_active = BrowserList::GetLastActive();
1808 if (last_active)
1809 contents = last_active->GetSelectedTabContents();
1810 }
1811
1812 if (contents)
1813 contents->OnStartDownload(download);
1814}
1815
[email protected]6cade212008-12-03 00:32:221816// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121817void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411818 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381819}
[email protected]b0ab1d42010-02-24 19:29:281820
1821void DownloadManager::NotifyModelChanged() {
1822 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1823}
1824
1825// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1826
1827DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1828 DownloadManager* observing_download_manager)
1829 : observing_download_manager_(observing_download_manager),
1830 observed_download_manager_(NULL) {
1831 if (observing_download_manager->profile_->GetOriginalProfile() ==
1832 observing_download_manager->profile_) {
1833 return;
1834 }
1835
1836 observed_download_manager_ = observing_download_manager_->
1837 profile_->GetOriginalProfile()->GetDownloadManager();
1838 observed_download_manager_->AddObserver(this);
1839}
1840
1841DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1842 if (observed_download_manager_)
1843 observed_download_manager_->RemoveObserver(this);
1844}
1845
1846void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1847 observing_download_manager_->NotifyModelChanged();
1848}
1849
1850void DownloadManager::OtherDownloadManagerObserver::SetDownloads(
1851 std::vector<DownloadItem*>& downloads) {
1852}
1853
1854void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1855 observed_download_manager_ = NULL;
1856}