blob: fe4a46330bea3f550a6f88bf411f5a3bb49a40a8 [file] [log] [blame]
[email protected]21ca982c2010-01-26 22:49:551// Copyright (c) 2010 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]cdaa8652008-09-13 02:48:595#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]a92b8642009-05-05 23:38:567#include "app/l10n_util.h"
[email protected]21ca982c2010-01-26 22:49:558#include "app/resource_bundle.h"
[email protected]2041cf342010-02-19 03:15:599#include "base/callback.h"
initial.commit09911bf2008-07-26 23:55:2910#include "base/file_util.h"
11#include "base/logging.h"
12#include "base/message_loop.h"
13#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1414#include "base/rand_util.h"
[email protected]807204142009-05-05 03:31:4415#include "base/stl_util-inl.h"
initial.commit09911bf2008-07-26 23:55:2916#include "base/string_util.h"
[email protected]1b5044d2009-02-24 00:04:1417#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2918#include "base/task.h"
19#include "base/thread.h"
20#include "base/timer.h"
[email protected]d2a8fb72010-01-21 05:31:4221#include "build/build_config.h"
initial.commit09911bf2008-07-26 23:55:2922#include "chrome/browser/browser_list.h"
23#include "chrome/browser/browser_process.h"
[email protected]d83d03aa2009-11-02 21:44:3724#include "chrome/browser/chrome_thread.h"
[email protected]cdaa8652008-09-13 02:48:5925#include "chrome/browser/download/download_file.h"
[email protected]e9ef0a62009-08-11 22:50:1326#include "chrome/browser/download/download_util.h"
[email protected]866930682009-08-18 22:53:4727#include "chrome/browser/extensions/crx_installer.h"
[email protected]2a464a92009-08-01 17:58:3528#include "chrome/browser/extensions/extension_install_ui.h"
[email protected]8f783752009-04-01 23:33:4529#include "chrome/browser/extensions/extensions_service.h"
[email protected]be180c802009-10-23 06:33:3130#include "chrome/browser/net/chrome_url_request_context.h"
[email protected]14a000d2010-04-29 21:44:2431#include "chrome/browser/platform_util.h"
[email protected]052313b2010-02-19 09:43:0832#include "chrome/browser/pref_service.h"
initial.commit09911bf2008-07-26 23:55:2933#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2634#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2535#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]e3c404b2008-12-23 01:07:3236#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]21ca982c2010-01-26 22:49:5537#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]57c6a652009-05-04 07:58:3438#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]d2a8fb72010-01-21 05:31:4239#include "chrome/browser/tab_contents/tab_util.h"
[email protected]4a0380c2009-07-26 07:25:3240#include "chrome/common/chrome_constants.h"
initial.commit09911bf2008-07-26 23:55:2941#include "chrome/common/chrome_paths.h"
[email protected]5b1a0e22009-05-26 19:00:5842#include "chrome/common/extensions/extension.h"
[email protected]6657afa62009-11-04 02:15:2043#include "chrome/common/extensions/user_script.h"
[email protected]91e1bd82009-09-03 22:04:4044#include "chrome/common/notification_service.h"
45#include "chrome/common/notification_type.h"
initial.commit09911bf2008-07-26 23:55:2946#include "chrome/common/pref_names.h"
[email protected]46072d42008-07-28 14:49:3547#include "googleurl/src/gurl.h"
[email protected]d81706b82009-04-03 20:28:4448#include "grit/chromium_strings.h"
[email protected]34ac8f32009-02-22 23:03:2749#include "grit/generated_resources.h"
[email protected]21ca982c2010-01-26 22:49:5550#include "grit/theme_resources.h"
initial.commit09911bf2008-07-26 23:55:2951#include "net/base/mime_util.h"
52#include "net/base/net_util.h"
53#include "net/url_request/url_request_context.h"
54
[email protected]b7f05882009-02-22 01:21:5655#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2556#include "app/win_util.h"
[email protected]b7f05882009-02-22 01:21:5657#include "base/registry.h"
58#include "base/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3259#endif
60
[email protected]21ca982c2010-01-26 22:49:5561namespace {
62
initial.commit09911bf2008-07-26 23:55:2963// Periodically update our observers.
64class DownloadItemUpdateTask : public Task {
65 public:
66 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
67 void Run() { if (item_) item_->UpdateObservers(); }
68
69 private:
70 DownloadItem* item_;
71};
72
73// Update frequency (milliseconds).
[email protected]21ca982c2010-01-26 22:49:5574const int kUpdateTimeMs = 1000;
initial.commit09911bf2008-07-26 23:55:2975
76// Our download table ID starts at 1, so we use 0 to represent a download that
77// has started, but has not yet had its data persisted in the table. We use fake
[email protected]6cade212008-12-03 00:32:2278// database handles in incognito mode starting at -1 and progressively getting
79// more negative.
[email protected]21ca982c2010-01-26 22:49:5580const int kUninitializedHandle = 0;
initial.commit09911bf2008-07-26 23:55:2981
[email protected]b0ab1d42010-02-24 19:29:2882// Used to sort download items based on descending start time.
83bool CompareStartTime(DownloadItem* first, DownloadItem* second) {
84 return first->start_time() > second->start_time();
85}
86
[email protected]21ca982c2010-01-26 22:49:5587} // namespace
88
initial.commit09911bf2008-07-26 23:55:2989// DownloadItem implementation -------------------------------------------------
90
91// Constructor for reading from the history service.
92DownloadItem::DownloadItem(const DownloadCreateInfo& info)
93 : id_(-1),
94 full_path_(info.path),
95 url_(info.url),
[email protected]e435d6b72009-07-25 03:15:5896 referrer_url_(info.referrer_url),
97 mime_type_(info.mime_type),
[email protected]d4a71882010-06-25 16:36:4198 original_mime_type_(info.original_mime_type),
initial.commit09911bf2008-07-26 23:55:2999 total_bytes_(info.total_bytes),
100 received_bytes_(info.received_bytes),
[email protected]b7f05882009-02-22 01:21:56101 start_tick_(base::TimeTicks()),
initial.commit09911bf2008-07-26 23:55:29102 state_(static_cast<DownloadState>(info.state)),
103 start_time_(info.start_time),
104 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29105 manager_(NULL),
106 is_paused_(false),
107 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56108 safety_state_(SAFE),
[email protected]0aad67b2009-07-15 20:34:28109 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56110 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29111 render_process_id_(-1),
[email protected]6aa4a1c02010-01-15 18:49:58112 request_id_(-1),
113 save_as_(false),
[email protected]b0ab1d42010-02-24 19:29:28114 is_otr_(false),
[email protected]5748eb82010-01-20 15:12:37115 is_extension_install_(info.is_extension_install),
[email protected]6aa4a1c02010-01-15 18:49:58116 name_finalized_(false),
117 is_temporary_(false) {
initial.commit09911bf2008-07-26 23:55:29118 if (state_ == IN_PROGRESS)
119 state_ = CANCELLED;
120 Init(false /* don't start progress timer */);
121}
122
123// Constructor for DownloadItem created via user action in the main thread.
124DownloadItem::DownloadItem(int32 download_id,
[email protected]7ae7c2cb2009-01-06 23:31:41125 const FilePath& path,
[email protected]7a256ea2008-10-17 17:34:16126 int path_uniquifier,
[email protected]f6b48532009-02-12 01:56:32127 const GURL& url,
[email protected]494c06e2009-07-25 01:06:42128 const GURL& referrer_url,
[email protected]e435d6b72009-07-25 03:15:58129 const std::string& mime_type,
[email protected]d4a71882010-06-25 16:36:41130 const std::string& original_mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:41131 const FilePath& original_name,
[email protected]e93d2822009-01-30 05:59:59132 const base::Time start_time,
initial.commit09911bf2008-07-26 23:55:29133 int64 download_size,
134 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32135 int request_id,
[email protected]67f373a2009-09-22 02:44:51136 bool is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57137 bool save_as,
[email protected]b0ab1d42010-02-24 19:29:28138 bool is_otr,
[email protected]6aa4a1c02010-01-15 18:49:58139 bool is_extension_install,
140 bool is_temporary)
initial.commit09911bf2008-07-26 23:55:29141 : id_(download_id),
142 full_path_(path),
[email protected]7a256ea2008-10-17 17:34:16143 path_uniquifier_(path_uniquifier),
initial.commit09911bf2008-07-26 23:55:29144 url_(url),
[email protected]494c06e2009-07-25 01:06:42145 referrer_url_(referrer_url),
[email protected]e435d6b72009-07-25 03:15:58146 mime_type_(mime_type),
[email protected]d4a71882010-06-25 16:36:41147 original_mime_type_(original_mime_type),
initial.commit09911bf2008-07-26 23:55:29148 total_bytes_(download_size),
149 received_bytes_(0),
[email protected]b7f05882009-02-22 01:21:56150 start_tick_(base::TimeTicks::Now()),
initial.commit09911bf2008-07-26 23:55:29151 state_(IN_PROGRESS),
152 start_time_(start_time),
153 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29154 manager_(NULL),
155 is_paused_(false),
156 open_when_complete_(false),
[email protected]b7f05882009-02-22 01:21:56157 safety_state_(is_dangerous ? DANGEROUS : SAFE),
[email protected]0aad67b2009-07-15 20:34:28158 auto_opened_(false),
[email protected]b7f05882009-02-22 01:21:56159 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29160 render_process_id_(render_process_id),
[email protected]67f373a2009-09-22 02:44:51161 request_id_(request_id),
[email protected]a60c8ae2009-12-25 06:50:57162 save_as_(save_as),
[email protected]b0ab1d42010-02-24 19:29:28163 is_otr_(is_otr),
[email protected]6aa4a1c02010-01-15 18:49:58164 is_extension_install_(is_extension_install),
165 name_finalized_(false),
166 is_temporary_(is_temporary) {
initial.commit09911bf2008-07-26 23:55:29167 Init(true /* start progress timer */);
168}
169
170void DownloadItem::Init(bool start_timer) {
[email protected]7ae7c2cb2009-01-06 23:31:41171 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29172 if (start_timer)
173 StartProgressTimer();
174}
175
176DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29177 state_ = REMOVING;
178 UpdateObservers();
179}
180
181void DownloadItem::AddObserver(Observer* observer) {
182 observers_.AddObserver(observer);
183}
184
185void DownloadItem::RemoveObserver(Observer* observer) {
186 observers_.RemoveObserver(observer);
187}
188
189void DownloadItem::UpdateObservers() {
190 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
191}
192
[email protected]6aa4a1c02010-01-15 18:49:58193void DownloadItem::NotifyObserversDownloadFileCompleted() {
194 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadFileCompleted(this));
195}
196
[email protected]45e3c122009-04-07 19:58:03197void DownloadItem::NotifyObserversDownloadOpened() {
198 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadOpened(this));
199}
200
initial.commit09911bf2008-07-26 23:55:29201// If we've received more data than we were expecting (bad server info?), revert
202// to 'unknown size mode'.
203void DownloadItem::UpdateSize(int64 bytes_so_far) {
204 received_bytes_ = bytes_so_far;
205 if (received_bytes_ > total_bytes_)
206 total_bytes_ = 0;
207}
208
209// Updates from the download thread may have been posted while this download
210// was being cancelled in the UI thread, so we'll accept them unless we're
211// complete.
212void DownloadItem::Update(int64 bytes_so_far) {
213 if (state_ == COMPLETE) {
214 NOTREACHED();
215 return;
216 }
217 UpdateSize(bytes_so_far);
218 UpdateObservers();
219}
220
[email protected]6cade212008-12-03 00:32:22221// Triggered by a user action.
initial.commit09911bf2008-07-26 23:55:29222void DownloadItem::Cancel(bool update_history) {
223 if (state_ != IN_PROGRESS) {
224 // Small downloads might be complete before this method has a chance to run.
225 return;
226 }
227 state_ = CANCELLED;
228 UpdateObservers();
229 StopProgressTimer();
230 if (update_history)
231 manager_->DownloadCancelled(id_);
232}
233
234void DownloadItem::Finished(int64 size) {
235 state_ = COMPLETE;
236 UpdateSize(size);
initial.commit09911bf2008-07-26 23:55:29237 StopProgressTimer();
238}
239
[email protected]9ccbb372008-10-10 18:50:32240void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29241 Cancel(true);
242 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32243 if (delete_on_disk)
244 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29245 manager_->RemoveDownload(db_handle_);
[email protected]6cade212008-12-03 00:32:22246 // We have now been deleted.
initial.commit09911bf2008-07-26 23:55:29247}
248
249void DownloadItem::StartProgressTimer() {
[email protected]e93d2822009-01-30 05:59:59250 update_timer_.Start(base::TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
[email protected]2d316662008-09-03 18:18:14251 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29252}
253
254void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14255 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29256}
257
[email protected]e93d2822009-01-30 05:59:59258bool DownloadItem::TimeRemaining(base::TimeDelta* remaining) const {
initial.commit09911bf2008-07-26 23:55:29259 if (total_bytes_ <= 0)
260 return false; // We never received the content_length for this download.
261
262 int64 speed = CurrentSpeed();
263 if (speed == 0)
264 return false;
265
266 *remaining =
[email protected]e93d2822009-01-30 05:59:59267 base::TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
initial.commit09911bf2008-07-26 23:55:29268 return true;
269}
270
271int64 DownloadItem::CurrentSpeed() const {
[email protected]b7f05882009-02-22 01:21:56272 base::TimeDelta diff = base::TimeTicks::Now() - start_tick_;
273 int64 diff_ms = diff.InMilliseconds();
274 return diff_ms == 0 ? 0 : received_bytes_ * 1000 / diff_ms;
initial.commit09911bf2008-07-26 23:55:29275}
276
277int DownloadItem::PercentComplete() const {
278 int percent = -1;
279 if (total_bytes_ > 0)
280 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
281 return percent;
282}
283
[email protected]7ae7c2cb2009-01-06 23:31:41284void DownloadItem::Rename(const FilePath& full_path) {
initial.commit09911bf2008-07-26 23:55:29285 DCHECK(!full_path.empty());
286 full_path_ = full_path;
[email protected]7ae7c2cb2009-01-06 23:31:41287 file_name_ = full_path_.BaseName();
initial.commit09911bf2008-07-26 23:55:29288}
289
290void DownloadItem::TogglePause() {
291 DCHECK(state_ == IN_PROGRESS);
292 manager_->PauseDownload(id_, !is_paused_);
293 is_paused_ = !is_paused_;
294 UpdateObservers();
295}
296
[email protected]7ae7c2cb2009-01-06 23:31:41297FilePath DownloadItem::GetFileName() const {
[email protected]9ccbb372008-10-10 18:50:32298 if (safety_state_ == DownloadItem::SAFE)
299 return file_name_;
[email protected]7a256ea2008-10-17 17:34:16300 if (path_uniquifier_ > 0) {
[email protected]7ae7c2cb2009-01-06 23:31:41301 FilePath name(original_name_);
[email protected]5a2388a2010-03-26 16:13:39302 download_util::AppendNumberToPath(&name, path_uniquifier_);
[email protected]7a256ea2008-10-17 17:34:16303 return name;
304 }
[email protected]9ccbb372008-10-10 18:50:32305 return original_name_;
306}
307
initial.commit09911bf2008-07-26 23:55:29308// DownloadManager implementation ----------------------------------------------
309
310// static
311void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
312 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
[email protected]20ce516d2010-06-18 02:20:04313 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, "");
[email protected]f052118e2008-09-05 02:25:32314 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
315
316 // The default download path is userprofile\download.
[email protected]290c9702010-03-09 04:01:36317 const FilePath& default_download_path =
318 download_util::GetDefaultDownloadDirectory();
[email protected]b9636002009-03-04 00:05:25319 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
320 default_download_path);
[email protected]f052118e2008-09-05 02:25:32321
322 // If the download path is dangerous we forcefully reset it. But if we do
323 // so we set a flag to make sure we only do it once, to avoid fighting
324 // the user if he really wants it on an unsafe place such as the desktop.
325
326 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]38233e62010-04-26 04:43:36327 FilePath current_download_dir = prefs->GetFilePath(
328 prefs::kDownloadDefaultDirectory);
[email protected]290c9702010-03-09 04:01:36329 if (download_util::DownloadPathIsDangerous(current_download_dir)) {
[email protected]38233e62010-04-26 04:43:36330 prefs->SetFilePath(prefs::kDownloadDefaultDirectory,
331 default_download_path);
[email protected]f052118e2008-09-05 02:25:32332 }
333 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
334 }
initial.commit09911bf2008-07-26 23:55:29335}
336
337DownloadManager::DownloadManager()
338 : shutdown_needed_(false),
339 profile_(NULL),
[email protected]d2a8fb72010-01-21 05:31:42340 file_manager_(NULL),
341 fake_db_handle_(kUninitializedHandle - 1) {
initial.commit09911bf2008-07-26 23:55:29342}
343
344DownloadManager::~DownloadManager() {
[email protected]b0ab1d42010-02-24 19:29:28345 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
346
initial.commit09911bf2008-07-26 23:55:29347 if (shutdown_needed_)
348 Shutdown();
349}
350
351void DownloadManager::Shutdown() {
352 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
353
354 // Stop receiving download updates
355 file_manager_->RemoveDownloadManager(this);
356
357 // Stop making history service requests
358 cancelable_consumer_.CancelAllRequests();
359
360 // 'in_progress_' may contain DownloadItems that have not finished the start
361 // complete (from the history service) and thus aren't in downloads_.
362 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32363 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29364 for (; it != in_progress_.end(); ++it) {
365 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32366 if (download->safety_state() == DownloadItem::DANGEROUS) {
367 // Forget about any download that the user did not approve.
368 // Note that we cannot call download->Remove() this would invalidate our
369 // iterator.
370 to_remove.insert(download);
371 continue;
initial.commit09911bf2008-07-26 23:55:29372 }
[email protected]9ccbb372008-10-10 18:50:32373 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
374 download->Cancel(false);
375 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29376 if (download->db_handle() == kUninitializedHandle) {
377 // An invalid handle means that 'download' does not yet exist in
378 // 'downloads_', so we have to delete it here.
379 delete download;
380 }
381 }
382
[email protected]9ccbb372008-10-10 18:50:32383 // 'dangerous_finished_' contains all complete downloads that have not been
384 // approved. They should be removed.
385 it = dangerous_finished_.begin();
386 for (; it != dangerous_finished_.end(); ++it)
387 to_remove.insert(it->second);
388
389 // Remove the dangerous download that are not approved.
390 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
391 rm_it != to_remove.end(); ++rm_it) {
392 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32393 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32394 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32395 // Same as above, delete the download if it is not in 'downloads_' (as the
396 // Remove() call above won't have deleted it).
397 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32398 delete download;
399 }
400 to_remove.clear();
401
initial.commit09911bf2008-07-26 23:55:29402 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32403 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29404 STLDeleteValues(&downloads_);
405
406 file_manager_ = NULL;
407
408 // Save our file extensions to auto open.
409 SaveAutoOpens();
410
411 // Make sure the save as dialog doesn't notify us back if we're gone before
412 // it returns.
413 if (select_file_dialog_.get())
414 select_file_dialog_->ListenerDestroyed();
415
416 shutdown_needed_ = false;
417}
418
419// Issue a history query for downloads matching 'search_text'. If 'search_text'
420// is empty, return all downloads that we know about.
421void DownloadManager::GetDownloads(Observer* observer,
422 const std::wstring& search_text) {
[email protected]b0ab1d42010-02-24 19:29:28423 std::vector<DownloadItem*> otr_downloads;
424
425 if (profile_->IsOffTheRecord() && search_text.empty()) {
426 // List all incognito downloads and add that to the downloads the parent
427 // profile lists.
428 otr_downloads.reserve(downloads_.size());
429 for (DownloadMap::iterator it = downloads_.begin();
430 it != downloads_.end(); ++it) {
431 DownloadItem* download = it->second;
432 if (download->is_otr() && !download->is_extension_install() &&
433 !download->is_temporary()) {
434 otr_downloads.push_back(download);
435 }
436 }
437 }
438
439 profile_->GetOriginalProfile()->GetDownloadManager()->
440 DoGetDownloads(observer, search_text, otr_downloads);
441}
442
443void DownloadManager::DoGetDownloads(
444 Observer* observer,
445 const std::wstring& search_text,
446 std::vector<DownloadItem*>& otr_downloads) {
initial.commit09911bf2008-07-26 23:55:29447 DCHECK(observer);
448
449 // Return a empty list if we've not yet received the set of downloads from the
450 // history system (we'll update all observers once we get that list in
451 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
initial.commit09911bf2008-07-26 23:55:29452 if (downloads_.empty()) {
[email protected]b0ab1d42010-02-24 19:29:28453 observer->SetDownloads(otr_downloads);
initial.commit09911bf2008-07-26 23:55:29454 return;
455 }
456
[email protected]b0ab1d42010-02-24 19:29:28457 std::vector<DownloadItem*> download_copy;
initial.commit09911bf2008-07-26 23:55:29458 // We already know all the downloads and there is no filter, so just return a
459 // copy to the observer.
460 if (search_text.empty()) {
461 download_copy.reserve(downloads_.size());
462 for (DownloadMap::iterator it = downloads_.begin();
463 it != downloads_.end(); ++it) {
[email protected]67f373a2009-09-22 02:44:51464 if (it->second->db_handle() > kUninitializedHandle)
465 download_copy.push_back(it->second);
initial.commit09911bf2008-07-26 23:55:29466 }
467
[email protected]b0ab1d42010-02-24 19:29:28468 // Merge sort based on start time.
469 std::vector<DownloadItem*> merged_downloads;
470 std::merge(otr_downloads.begin(), otr_downloads.end(),
471 download_copy.begin(), download_copy.end(),
472 std::back_inserter(merged_downloads),
473 CompareStartTime);
474
initial.commit09911bf2008-07-26 23:55:29475 // We retain ownership of the DownloadItems.
[email protected]b0ab1d42010-02-24 19:29:28476 observer->SetDownloads(merged_downloads);
initial.commit09911bf2008-07-26 23:55:29477 return;
478 }
479
[email protected]b0ab1d42010-02-24 19:29:28480 DCHECK(otr_downloads.empty());
481
initial.commit09911bf2008-07-26 23:55:29482 // Issue a request to the history service for a list of downloads matching
483 // our search text.
484 HistoryService* hs =
485 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
486 if (hs) {
487 HistoryService::Handle h =
[email protected]e53668962010-06-23 15:35:25488 hs->SearchDownloads(WideToUTF16(search_text),
initial.commit09911bf2008-07-26 23:55:29489 &cancelable_consumer_,
490 NewCallback(this,
491 &DownloadManager::OnSearchComplete));
492 cancelable_consumer_.SetClientData(hs, h, observer);
493 }
494}
495
[email protected]6aa4a1c02010-01-15 18:49:58496void DownloadManager::GetTemporaryDownloads(Observer* observer,
497 const FilePath& dir_path) {
498 DCHECK(observer);
499
500 std::vector<DownloadItem*> download_copy;
501
502 for (DownloadMap::iterator it = downloads_.begin();
503 it != downloads_.end(); ++it) {
504 if (it->second->is_temporary() &&
505 it->second->full_path().DirName() == dir_path)
506 download_copy.push_back(it->second);
507 }
508
509 observer->SetDownloads(download_copy);
510}
511
[email protected]8ddbd66a2010-05-21 16:38:34512void DownloadManager::GetAllDownloads(Observer* observer,
513 const FilePath& dir_path) {
514 DCHECK(observer);
515
516 std::vector<DownloadItem*> download_copy;
517
518 for (DownloadMap::iterator it = downloads_.begin();
519 it != downloads_.end(); ++it) {
520 if (!it->second->is_temporary() &&
521 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
522 download_copy.push_back(it->second);
523 }
524
525 observer->SetDownloads(download_copy);
526}
527
[email protected]c4a530b2010-03-08 17:33:03528void DownloadManager::GetCurrentDownloads(Observer* observer,
529 const FilePath& dir_path) {
530 DCHECK(observer);
531
532 std::vector<DownloadItem*> download_copy;
533
534 for (DownloadMap::iterator it = downloads_.begin();
535 it != downloads_.end(); ++it) {
536 if (!it->second->is_temporary() &&
537 (it->second->state() == DownloadItem::IN_PROGRESS ||
538 it->second->safety_state() == DownloadItem::DANGEROUS) &&
539 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
540 download_copy.push_back(it->second);
541 }
542
543 observer->SetDownloads(download_copy);
544}
545
initial.commit09911bf2008-07-26 23:55:29546// Query the history service for information about all persisted downloads.
547bool DownloadManager::Init(Profile* profile) {
548 DCHECK(profile);
549 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
550 shutdown_needed_ = true;
551
552 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31553 request_context_getter_ = profile_->GetRequestContext();
initial.commit09911bf2008-07-26 23:55:29554
555 // 'incognito mode' will have access to past downloads, but we won't store
556 // information about new downloads while in that mode.
557 QueryHistoryForDownloads();
558
[email protected]024f2f02010-04-30 22:51:46559 // Cleans up entries only when called for the first time. Subsequent calls are
560 // a no op.
561 CleanUpInProgressHistoryEntries();
562
initial.commit09911bf2008-07-26 23:55:29563 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
564 if (!rdh) {
565 NOTREACHED();
566 return false;
567 }
568
569 file_manager_ = rdh->download_file_manager();
570 if (!file_manager_) {
571 NOTREACHED();
572 return false;
573 }
574
initial.commit09911bf2008-07-26 23:55:29575 // Get our user preference state.
576 PrefService* prefs = profile_->GetPrefs();
577 DCHECK(prefs);
578 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
579
initial.commit09911bf2008-07-26 23:55:29580 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
581
[email protected]bb69e9b32008-08-14 23:08:14582 // Ensure that the download directory specified in the preferences exists.
[email protected]d83d03aa2009-11-02 21:44:37583 ChromeThread::PostTask(
584 ChromeThread::FILE, FROM_HERE,
[email protected]309b7642009-12-09 03:08:50585 NewRunnableFunction(&file_util::CreateDirectory, download_path()));
initial.commit09911bf2008-07-26 23:55:29586
[email protected]2b2f8f72009-02-24 22:42:05587 // We store any file extension that should be opened automatically at
588 // download completion in this pref.
[email protected]ddd231e2010-06-29 20:35:19589 std::string extensions_to_open =
initial.commit09911bf2008-07-26 23:55:29590 prefs->GetString(prefs::kDownloadExtensionsToOpen);
[email protected]ddd231e2010-06-29 20:35:19591 std::vector<std::string> extensions;
592 SplitString(extensions_to_open, ':', &extensions);
593
initial.commit09911bf2008-07-26 23:55:29594 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]ddd231e2010-06-29 20:35:19595#if defined(OS_POSIX)
596 FilePath path(extensions[i]);
597#elif defined(OS_WIN)
598 FilePath path(UTF8ToWide(extensions[i]));
599#endif
600 if (!extensions[i].empty() && !IsExecutableFile(path))
601 auto_open_.insert(path.value());
initial.commit09911bf2008-07-26 23:55:29602 }
603
[email protected]b0ab1d42010-02-24 19:29:28604 other_download_manager_observer_.reset(
605 new OtherDownloadManagerObserver(this));
606
initial.commit09911bf2008-07-26 23:55:29607 return true;
608}
609
610void DownloadManager::QueryHistoryForDownloads() {
611 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
612 if (hs) {
613 hs->QueryDownloads(
614 &cancelable_consumer_,
615 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
616 }
617}
618
[email protected]024f2f02010-04-30 22:51:46619void DownloadManager::CleanUpInProgressHistoryEntries() {
620 static bool already_cleaned_up = false;
621
622 if (!already_cleaned_up) {
623 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
624 if (hs) {
625 hs->CleanUpInProgressEntries();
626 already_cleaned_up = true;
627 }
628 }
629}
630
initial.commit09911bf2008-07-26 23:55:29631// We have received a message from DownloadFileManager about a new download. We
632// create a download item and store it in our download map, and inform the
633// history system of a new download. Since this method can be called while the
634// history service thread is still reading the persistent state, we do not
635// insert the new DownloadItem into 'downloads_' or inform our observers at this
636// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
637// download creation as a callback from the history thread.
638void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37639 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29640 DCHECK(info);
641
[email protected]a60c8ae2009-12-25 06:50:57642 // Check whether this download is for an extension install or not.
643 if (!info->save_as) { // Allow extensions to be explicitly saved.
644 if (UserScript::HasUserScriptFileExtension(info->url) ||
645 info->mime_type == Extension::kMimeType)
646 info->is_extension_install = true;
647 }
648
[email protected]7d3851d82008-12-12 03:26:07649 // Freeze the user's preference for showing a Save As dialog. We're going to
650 // bounce around a bunch of threads and we don't want to worry about race
651 // conditions where the user changes this pref out from under us.
[email protected]7bc4f702009-09-25 22:12:38652 if (*prompt_for_download_) {
[email protected]486d25442010-03-18 17:34:26653 // But never obey the preference for the following scenarios:
654 // 1) Extension installation. Note that we only care here about the case
655 // where an extension is installed, not when one is downloaded with
656 // "save as...".
657 // 2) Drag-out download. Since we will save to the destination folder that
658 // is dropped to, we should not pop up a Save As dialog.
659 if (!info->is_extension_install && info->save_info.file_path.empty())
[email protected]7bc4f702009-09-25 22:12:38660 info->save_as = true;
661 }
[email protected]7d3851d82008-12-12 03:26:07662
[email protected]8af9d032010-02-10 00:00:32663 if (info->save_info.file_path.empty()) {
664 // Determine the proper path for a download, by either one of the following:
665 // 1) using the default download directory.
666 // 2) prompting the user.
667 FilePath generated_name;
668 GenerateFileNameFromInfo(info, &generated_name);
669 if (info->save_as && !last_download_path_.empty())
670 info->suggested_path = last_download_path_;
671 else
672 info->suggested_path = download_path();
673 info->suggested_path = info->suggested_path.Append(generated_name);
674 } else {
675 info->suggested_path = info->save_info.file_path;
676 }
initial.commit09911bf2008-07-26 23:55:29677
[email protected]8af9d032010-02-10 00:00:32678 if (!info->save_as && info->save_info.file_path.empty()) {
[email protected]4289d9b2009-07-25 21:17:34679 // Downloads can be marked as dangerous for two reasons:
680 // a) They have a dangerous-looking filename
681 // b) They are an extension that is not from the gallery
682 if (IsDangerous(info->suggested_path.BaseName()))
683 info->is_dangerous = true;
[email protected]a60c8ae2009-12-25 06:50:57684 else if (info->is_extension_install &&
[email protected]b7c2f252009-12-08 00:47:23685 !ExtensionsService::IsDownloadFromGallery(info->url,
686 info->referrer_url)) {
[email protected]4289d9b2009-07-25 21:17:34687 info->is_dangerous = true;
688 }
[email protected]e9ebf3fc2008-10-17 22:06:58689 }
690
initial.commit09911bf2008-07-26 23:55:29691 // We need to move over to the download thread because we don't want to stat
692 // the suggested path on the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37693 ChromeThread::PostTask(
694 ChromeThread::FILE, FROM_HERE,
695 NewRunnableMethod(
696 this, &DownloadManager::CheckIfSuggestedPathExists, info));
initial.commit09911bf2008-07-26 23:55:29697}
698
699void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
700 DCHECK(info);
701
702 // Check writability of the suggested path. If we can't write to it, default
703 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41704 FilePath dir = info->suggested_path.DirName();
705 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32706 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29707 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29708 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41709 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29710 }
711
[email protected]8af9d032010-02-10 00:00:32712 // Do not add the path uniquifier if we are saving to a specific path as in
713 // the drag-out case.
[email protected]5a2388a2010-03-26 16:13:39714 if (info->save_info.file_path.empty()) {
715 info->path_uniquifier = download_util::GetUniquePathNumber(
716 info->suggested_path);
717 }
initial.commit09911bf2008-07-26 23:55:29718
[email protected]6cade212008-12-03 00:32:22719 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58720 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41721 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32722 // Create a temporary file to hold the file until the user approves its
723 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41724 FilePath::StringType file_name;
725 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32726 while (path.empty()) {
[email protected]7ae7c2cb2009-01-06 23:31:41727 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.download"),
[email protected]9ccbb372008-10-10 18:50:32728 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41729 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07730 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41731 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32732 }
733 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16734 } else {
735 // We know the final path, build it if necessary.
736 if (info->path_uniquifier > 0) {
[email protected]5a2388a2010-03-26 16:13:39737 download_util::AppendNumberToPath(&(info->suggested_path),
738 info->path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16739 // Setting path_uniquifier to 0 to make sure we don't try to unique it
740 // later on.
741 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07742 } else if (info->path_uniquifier == -1) {
743 // We failed to find a unique path. We have to prompt the user.
744 info->save_as = true;
[email protected]7a256ea2008-10-17 17:34:16745 }
[email protected]9ccbb372008-10-10 18:50:32746 }
747
[email protected]8af9d032010-02-10 00:00:32748 if (!info->save_as && info->save_info.file_path.empty()) {
[email protected]7d3851d82008-12-12 03:26:07749 // Create an empty file at the suggested path so that we don't allocate the
750 // same "non-existant" path to multiple downloads.
751 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]7ff3f632009-10-13 18:43:35752 file_util::WriteFile(info->suggested_path, "", 0);
[email protected]7d3851d82008-12-12 03:26:07753 }
754
initial.commit09911bf2008-07-26 23:55:29755 // Now we return to the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37756 ChromeThread::PostTask(
757 ChromeThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29758 NewRunnableMethod(this,
759 &DownloadManager::OnPathExistenceAvailable,
760 info));
761}
762
763void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37764 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29765 DCHECK(info);
766
[email protected]7d3851d82008-12-12 03:26:07767 if (info->save_as) {
initial.commit09911bf2008-07-26 23:55:29768 // We must ask the user for the place to put the download.
769 if (!select_file_dialog_.get())
770 select_file_dialog_ = SelectFileDialog::Create(this);
771
[email protected]76543b92009-08-31 17:27:45772 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
773 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08774 SelectFileDialog::FileTypeInfo file_type_info;
775 file_type_info.extensions.resize(1);
776 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24777 if (!file_type_info.extensions[0][0].empty())
778 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08779 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23780 gfx::NativeWindow owning_window =
781 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29782 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34783 string16(),
784 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08785 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30786 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29787 } else {
788 // No prompting for download, just continue with the suggested name.
789 ContinueStartDownload(info, info->suggested_path);
790 }
791}
792
793void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41794 const FilePath& target_path) {
initial.commit09911bf2008-07-26 23:55:29795 scoped_ptr<DownloadCreateInfo> infop(info);
796 info->path = target_path;
797
798 DownloadItem* download = NULL;
799 DownloadMap::iterator it = in_progress_.find(info->download_id);
800 if (it == in_progress_.end()) {
801 download = new DownloadItem(info->download_id,
802 info->path,
[email protected]7a256ea2008-10-17 17:34:16803 info->path_uniquifier,
initial.commit09911bf2008-07-26 23:55:29804 info->url,
[email protected]494c06e2009-07-25 01:06:42805 info->referrer_url,
[email protected]e435d6b72009-07-25 03:15:58806 info->mime_type,
[email protected]d4a71882010-06-25 16:36:41807 info->original_mime_type,
[email protected]9ccbb372008-10-10 18:50:32808 info->original_name,
initial.commit09911bf2008-07-26 23:55:29809 info->start_time,
810 info->total_bytes,
[email protected]76543b92009-08-31 17:27:45811 info->child_id,
[email protected]9ccbb372008-10-10 18:50:32812 info->request_id,
[email protected]67f373a2009-09-22 02:44:51813 info->is_dangerous,
[email protected]a60c8ae2009-12-25 06:50:57814 info->save_as,
[email protected]b0ab1d42010-02-24 19:29:28815 profile_->IsOffTheRecord(),
[email protected]6aa4a1c02010-01-15 18:49:58816 info->is_extension_install,
[email protected]8af9d032010-02-10 00:00:32817 !info->save_info.file_path.empty());
initial.commit09911bf2008-07-26 23:55:29818 download->set_manager(this);
819 in_progress_[info->download_id] = download;
820 } else {
821 NOTREACHED(); // Should not exist!
822 return;
823 }
824
[email protected]6b323782009-03-27 18:43:08825 // Called before DownloadFinished in order to avoid a race condition where we
826 // attempt to open a completed download before it has been renamed.
[email protected]d83d03aa2009-11-02 21:44:37827 ChromeThread::PostTask(
828 ChromeThread::FILE, FROM_HERE,
829 NewRunnableMethod(
830 file_manager_, &DownloadFileManager::OnFinalDownloadName,
831 download->id(), target_path, this));
[email protected]6b323782009-03-27 18:43:08832
initial.commit09911bf2008-07-26 23:55:29833 // If the download already completed by the time we reached this point, then
834 // notify observers that it did.
835 PendingFinishedMap::iterator pending_it =
836 pending_finished_downloads_.find(info->download_id);
837 if (pending_it != pending_finished_downloads_.end())
838 DownloadFinished(pending_it->first, pending_it->second);
839
840 download->Rename(target_path);
841
[email protected]67f373a2009-09-22 02:44:51842 // Do not store the download in the history database for a few special cases:
843 // - incognito mode (that is the point of this mode)
844 // - extensions (users don't think of extension installation as 'downloading')
[email protected]6aa4a1c02010-01-15 18:49:58845 // - temporary download, like in drag-and-drop
[email protected]67f373a2009-09-22 02:44:51846 // We have to make sure that these handles don't collide with normal db
847 // handles, so we use a negative value. Eventually, they could overlap, but
848 // you'd have to do enough downloading that your ISP would likely stab you in
849 // the neck first. YMMV.
[email protected]b0ab1d42010-02-24 19:29:28850 if (download->is_otr() || download->is_extension_install() ||
[email protected]6aa4a1c02010-01-15 18:49:58851 download->is_temporary()) {
[email protected]d2a8fb72010-01-21 05:31:42852 OnCreateDownloadEntryComplete(*info, fake_db_handle_.GetNext());
initial.commit09911bf2008-07-26 23:55:29853 } else {
854 // Update the history system with the new download.
[email protected]6cade212008-12-03 00:32:22855 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29856 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
857 if (hs) {
858 hs->CreateDownload(
859 *info, &cancelable_consumer_,
860 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
861 }
862 }
[email protected]6a7fb042010-02-01 16:30:47863
864 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29865}
866
867// Convenience function for updating the history service for a download.
868void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
869 DCHECK(download);
870
871 // Don't store info in the database if the download was initiated while in
872 // incognito mode or if it hasn't been initialized in our database table.
873 if (download->db_handle() <= kUninitializedHandle)
874 return;
875
[email protected]6cade212008-12-03 00:32:22876 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29877 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
878 if (hs) {
879 hs->UpdateDownload(download->received_bytes(),
880 download->state(),
881 download->db_handle());
882 }
883}
884
885void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
886 DCHECK(download);
[email protected]6cade212008-12-03 00:32:22887 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29888 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
889 if (download->db_handle() > kUninitializedHandle && hs)
890 hs->RemoveDownload(download->db_handle());
891}
892
[email protected]e93d2822009-01-30 05:59:59893void DownloadManager::RemoveDownloadsFromHistoryBetween(
894 const base::Time remove_begin,
895 const base::Time remove_end) {
[email protected]6cade212008-12-03 00:32:22896 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
initial.commit09911bf2008-07-26 23:55:29897 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
898 if (hs)
899 hs->RemoveDownloadsBetween(remove_begin, remove_end);
900}
901
902void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
903 DownloadMap::iterator it = in_progress_.find(download_id);
904 if (it != in_progress_.end()) {
905 DownloadItem* download = it->second;
906 download->Update(size);
907 UpdateHistoryForDownload(download);
908 }
[email protected]6a7fb042010-02-01 16:30:47909 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29910}
911
912void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
913 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32914 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29915 // The download is done, but the user hasn't selected a final location for
916 // it yet (the Save As dialog box is probably still showing), so just keep
917 // track of the fact that this download id is complete, when the
918 // DownloadItem is constructed later we'll notify its completion then.
919 PendingFinishedMap::iterator erase_it =
920 pending_finished_downloads_.find(download_id);
921 DCHECK(erase_it == pending_finished_downloads_.end());
922 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32923 return;
initial.commit09911bf2008-07-26 23:55:29924 }
[email protected]9ccbb372008-10-10 18:50:32925
926 // Remove the id from the list of pending ids.
927 PendingFinishedMap::iterator erase_it =
928 pending_finished_downloads_.find(download_id);
929 if (erase_it != pending_finished_downloads_.end())
930 pending_finished_downloads_.erase(erase_it);
931
932 DownloadItem* download = it->second;
933 download->Finished(size);
934
935 // Clean up will happen when the history system create callback runs if we
936 // don't have a valid db_handle yet.
937 if (download->db_handle() != kUninitializedHandle) {
938 in_progress_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32939 UpdateHistoryForDownload(download);
940 }
941
[email protected]6a7fb042010-02-01 16:30:47942 UpdateAppIcon();
943
[email protected]9ccbb372008-10-10 18:50:32944 // If this a dangerous download not yet validated by the user, don't do
945 // anything. When the user notifies us, it will trigger a call to
946 // ProceedWithFinishedDangerousDownload.
947 if (download->safety_state() == DownloadItem::DANGEROUS) {
948 dangerous_finished_[download_id] = download;
949 return;
950 }
951
952 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22953 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32954 // its final name before we can continue.
[email protected]d83d03aa2009-11-02 21:44:37955 ChromeThread::PostTask(
956 ChromeThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32957 NewRunnableMethod(
958 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
959 download->db_handle(),
960 download->full_path(), download->original_name()));
961 return;
962 }
963 ContinueDownloadFinished(download);
964}
965
[email protected]8f783752009-04-01 23:33:45966void DownloadManager::DownloadRenamedToFinalName(int download_id,
967 const FilePath& full_path) {
[email protected]6aa4a1c02010-01-15 18:49:58968 DownloadMap::iterator it = downloads_.begin();
969 while (it != downloads_.end()) {
970 DownloadItem* download = it->second;
971 if (download->id() == download_id) {
972 // The download file is meant to be completed if both the filename is
973 // finalized and the file data is downloaded. The ordering of these two
974 // actions is indeterministic. Thus, if we are still in downloading the
975 // file, delay the notification.
976 download->set_name_finalized(true);
977 if (download->state() == DownloadItem::COMPLETE)
978 download->NotifyObserversDownloadFileCompleted();
979 return;
980 }
981 it++;
982 }
[email protected]8f783752009-04-01 23:33:45983}
984
[email protected]9ccbb372008-10-10 18:50:32985void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
986 // If this was a dangerous download, it has now been approved and must be
987 // removed from dangerous_finished_ so it does not get deleted on shutdown.
988 DownloadMap::iterator it = dangerous_finished_.find(download->id());
989 if (it != dangerous_finished_.end())
990 dangerous_finished_.erase(it);
991
[email protected]0aad67b2009-07-15 20:34:28992 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]a60c8ae2009-12-25 06:50:57993 if (download->is_extension_install()) {
[email protected]d4a71882010-06-25 16:36:41994 OpenChromeExtension(download->full_path(),
995 download->url(),
996 download->referrer_url(),
997 download->original_mime_type());
[email protected]0aad67b2009-07-15 20:34:28998 download->set_auto_opened(true);
999 } else if (download->open_when_complete() ||
[email protected]6aa4a1c02010-01-15 18:49:581000 ShouldOpenFileBasedOnExtension(download->full_path()) ||
1001 download->is_temporary()) {
1002 // If the download is temporary, like in drag-and-drop, do not open it but
1003 // we still need to set it auto-opened so that it can be removed from the
1004 // download shelf.
1005 if (!download->is_temporary())
1006 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:281007 download->set_auto_opened(true);
1008 }
[email protected]9ccbb372008-10-10 18:50:321009
[email protected]0aad67b2009-07-15 20:34:281010 // Notify our observers that we are complete (the call to Finished() set the
1011 // state to complete but did not notify).
1012 download->UpdateObservers();
[email protected]6aa4a1c02010-01-15 18:49:581013
1014 // The download file is meant to be completed if both the filename is
1015 // finalized and the file data is downloaded. The ordering of these two
1016 // actions is indeterministic. Thus, if the filename is not finalized yet,
1017 // delay the notification.
1018 if (download->name_finalized())
1019 download->NotifyObserversDownloadFileCompleted();
[email protected]0aad67b2009-07-15 20:34:281020}
[email protected]eccb9d12009-10-28 05:40:091021
[email protected]9ccbb372008-10-10 18:50:321022// Called on the file thread. Renames the downloaded file to its original name.
1023void DownloadManager::ProceedWithFinishedDangerousDownload(
1024 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:411025 const FilePath& path,
1026 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:321027 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:411028 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:161029 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:321030 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:241031 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:161032 // Make our name unique at this point, as if a dangerous file is downloading
1033 // and a 2nd download is started for a file with the same name, they would
1034 // have the same path. This is because we uniquify the name on download
1035 // start, and at that time the first file does not exists yet, so the second
1036 // file gets the same name.
[email protected]5a2388a2010-03-26 16:13:391037 uniquifier = download_util::GetUniquePathNumber(new_path);
[email protected]7a256ea2008-10-17 17:34:161038 if (uniquifier > 0)
[email protected]5a2388a2010-03-26 16:13:391039 download_util::AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:321040 success = file_util::Move(path, new_path);
1041 } else {
1042 NOTREACHED();
1043 }
[email protected]6cade212008-12-03 00:32:221044
[email protected]d83d03aa2009-11-02 21:44:371045 ChromeThread::PostTask(
1046 ChromeThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:321047 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:161048 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:321049}
1050
1051// Call from the file thread when the finished dangerous download was renamed.
1052void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
1053 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:411054 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:161055 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:321056 DownloadMap::iterator it = downloads_.find(download_handle);
1057 if (it == downloads_.end()) {
1058 NOTREACHED();
1059 return;
1060 }
1061
1062 DownloadItem* download = it->second;
1063 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:161064 if (success) {
1065 // We need to update the path uniquifier so that the UI shows the right
1066 // name when calling GetFileName().
1067 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:321068 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:161069 }
[email protected]9ccbb372008-10-10 18:50:321070
1071 // Continue the download finished sequence.
1072 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:291073}
1074
1075// static
initial.commit09911bf2008-07-26 23:55:291076void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
1077 int render_process_id,
1078 int request_id) {
[email protected]d85cf072009-10-27 03:59:311079 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
initial.commit09911bf2008-07-26 23:55:291080 rdh->CancelRequest(render_process_id, request_id, false);
1081}
1082
1083void DownloadManager::DownloadCancelled(int32 download_id) {
1084 DownloadMap::iterator it = in_progress_.find(download_id);
1085 if (it == in_progress_.end())
1086 return;
1087 DownloadItem* download = it->second;
1088
initial.commit09911bf2008-07-26 23:55:291089 // Clean up will happen when the history system create callback runs if we
1090 // don't have a valid db_handle yet.
1091 if (download->db_handle() != kUninitializedHandle) {
1092 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291093 UpdateHistoryForDownload(download);
1094 }
1095
[email protected]d7d1c5c2009-08-05 23:52:501096 DownloadCancelledInternal(download_id,
1097 download->render_process_id(),
1098 download->request_id());
[email protected]6a7fb042010-02-01 16:30:471099 UpdateAppIcon();
[email protected]d7d1c5c2009-08-05 23:52:501100}
1101
1102void DownloadManager::DownloadCancelledInternal(int download_id,
1103 int render_process_id,
1104 int request_id) {
[email protected]d85cf072009-10-27 03:59:311105 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
1106 ChromeThread::PostTask(
1107 ChromeThread::IO, FROM_HERE,
1108 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
1109 g_browser_process->resource_dispatcher_host(),
1110 render_process_id,
1111 request_id));
[email protected]d7d1c5c2009-08-05 23:52:501112
initial.commit09911bf2008-07-26 23:55:291113 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:501114 file_manager_->RemoveDownload(download_id, this); // On the UI thread
[email protected]d83d03aa2009-11-02 21:44:371115 ChromeThread::PostTask(
1116 ChromeThread::FILE, FROM_HERE,
1117 NewRunnableMethod(
1118 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:291119}
1120
1121void DownloadManager::PauseDownload(int32 download_id, bool pause) {
1122 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:311123 if (it == in_progress_.end())
1124 return;
initial.commit09911bf2008-07-26 23:55:291125
[email protected]d85cf072009-10-27 03:59:311126 DownloadItem* download = it->second;
1127 if (pause == download->is_paused())
1128 return;
initial.commit09911bf2008-07-26 23:55:291129
[email protected]d85cf072009-10-27 03:59:311130 // Inform the ResourceDispatcherHost of the new pause state.
1131 ChromeThread::PostTask(
1132 ChromeThread::IO, FROM_HERE,
1133 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
1134 g_browser_process->resource_dispatcher_host(),
1135 download->render_process_id(),
1136 download->request_id(),
1137 pause));
initial.commit09911bf2008-07-26 23:55:291138}
1139
1140// static
1141void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
1142 int render_process_id,
1143 int request_id,
1144 bool pause) {
1145 rdh->PauseRequest(render_process_id, request_id, pause);
1146}
1147
[email protected]7ae7c2cb2009-01-06 23:31:411148bool DownloadManager::IsDangerous(const FilePath& file_name) {
[email protected]9ccbb372008-10-10 18:50:321149 // TODO(jcampan): Improve me.
[email protected]eccb9d12009-10-28 05:40:091150 return IsExecutableFile(file_name);
[email protected]9ccbb372008-10-10 18:50:321151}
1152
[email protected]6a7fb042010-02-01 16:30:471153void DownloadManager::UpdateAppIcon() {
1154 int64 total_bytes = 0;
1155 int64 received_bytes = 0;
1156 int download_count = 0;
1157 bool progress_known = true;
1158
1159 for (DownloadMap::iterator i = in_progress_.begin();
1160 i != in_progress_.end();
1161 ++i) {
1162 ++download_count;
1163 const DownloadItem* item = i->second;
1164 if (item->total_bytes() > 0) {
1165 total_bytes += item->total_bytes();
1166 received_bytes += item->received_bytes();
1167 } else {
1168 // This download didn't specify a Content-Length, so the combined progress
1169 // bar neeeds to be indeterminate.
1170 progress_known = false;
1171 }
1172 }
1173
1174 float progress = 0;
1175 if (progress_known && download_count)
1176 progress = (float)received_bytes / total_bytes;
1177
1178 download_util::UpdateAppIconDownloadProgress(download_count,
1179 progress_known,
1180 progress);
1181}
1182
[email protected]9ccbb372008-10-10 18:50:321183void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:411184 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:321185 download->Rename(new_path);
1186
1187 // Update the history.
1188
1189 // No update necessary if the download was initiated while in incognito mode.
1190 if (download->db_handle() <= kUninitializedHandle)
1191 return;
1192
[email protected]6cade212008-12-03 00:32:221193 // FIXME(paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
[email protected]9ccbb372008-10-10 18:50:321194 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1195 if (hs)
[email protected]e53668962010-06-23 15:35:251196 hs->UpdateDownloadPath(new_path, download->db_handle());
[email protected]9ccbb372008-10-10 18:50:321197}
1198
initial.commit09911bf2008-07-26 23:55:291199void DownloadManager::RemoveDownload(int64 download_handle) {
1200 DownloadMap::iterator it = downloads_.find(download_handle);
1201 if (it == downloads_.end())
1202 return;
1203
1204 // Make history update.
1205 DownloadItem* download = it->second;
1206 RemoveDownloadFromHistory(download);
1207
1208 // Remove from our tables and delete.
1209 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:321210 it = dangerous_finished_.find(download->id());
1211 if (it != dangerous_finished_.end())
1212 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:291213
1214 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:281215 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:361216
1217 delete download;
initial.commit09911bf2008-07-26 23:55:291218}
1219
[email protected]e93d2822009-01-30 05:59:591220int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
1221 const base::Time remove_end) {
initial.commit09911bf2008-07-26 23:55:291222 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
1223
initial.commit09911bf2008-07-26 23:55:291224 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:281225 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:291226 while (it != downloads_.end()) {
1227 DownloadItem* download = it->second;
1228 DownloadItem::DownloadState state = download->state();
1229 if (download->start_time() >= remove_begin &&
1230 (remove_end.is_null() || download->start_time() < remove_end) &&
1231 (state == DownloadItem::COMPLETE ||
1232 state == DownloadItem::CANCELLED)) {
1233 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:561234 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:581235
1236 // Also remove it from any completed dangerous downloads.
1237 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
1238 if (dit != dangerous_finished_.end())
1239 dangerous_finished_.erase(dit);
1240
[email protected]78b8fcc92009-03-31 17:36:281241 pending_deletes.push_back(download);
[email protected]b0ab1d42010-02-24 19:29:281242 // Observer interface.
initial.commit09911bf2008-07-26 23:55:291243
initial.commit09911bf2008-07-26 23:55:291244 continue;
1245 }
1246
1247 ++it;
1248 }
1249
1250 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:281251 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:291252 if (num_deleted > 0)
[email protected]b0ab1d42010-02-24 19:29:281253 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291254
[email protected]78b8fcc92009-03-31 17:36:281255 // Delete the download items after updating the observers.
1256 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
1257 pending_deletes.clear();
1258
initial.commit09911bf2008-07-26 23:55:291259 return num_deleted;
1260}
1261
[email protected]e93d2822009-01-30 05:59:591262int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
1263 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:291264}
1265
[email protected]d41355e6f2009-04-07 21:21:121266int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:461267 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
1268 // This is an incognito downloader. Clear All should clear main download
1269 // manager as well.
1270 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
1271 }
[email protected]d41355e6f2009-04-07 21:21:121272 // The null times make the date range unbounded.
1273 return RemoveDownloadsBetween(base::Time(), base::Time());
1274}
1275
initial.commit09911bf2008-07-26 23:55:291276// Initiate a download of a specific URL. We send the request to the
1277// ResourceDispatcherHost, and let it send us responses like a regular
1278// download.
1279void DownloadManager::DownloadUrl(const GURL& url,
1280 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501281 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341282 TabContents* tab_contents) {
[email protected]6aa4a1c02010-01-15 18:49:581283 file_manager_->DownloadUrl(url,
1284 referrer,
1285 referrer_charset,
[email protected]8af9d032010-02-10 00:00:321286 DownloadSaveInfo(),
[email protected]8cb5d5b2010-02-09 11:36:161287 tab_contents->GetRenderProcessHost()->id(),
[email protected]6aa4a1c02010-01-15 18:49:581288 tab_contents->render_view_host()->routing_id(),
1289 request_context_getter_);
1290}
1291
1292void DownloadManager::DownloadUrlToFile(const GURL& url,
1293 const GURL& referrer,
1294 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:321295 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:581296 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:341297 DCHECK(tab_contents);
initial.commit09911bf2008-07-26 23:55:291298 file_manager_->DownloadUrl(url,
1299 referrer,
[email protected]be180c802009-10-23 06:33:311300 referrer_charset,
[email protected]8af9d032010-02-10 00:00:321301 save_info,
[email protected]8cb5d5b2010-02-09 11:36:161302 tab_contents->GetRenderProcessHost()->id(),
[email protected]57c6a652009-05-04 07:58:341303 tab_contents->render_view_host()->routing_id(),
[email protected]be180c802009-10-23 06:33:311304 request_context_getter_);
initial.commit09911bf2008-07-26 23:55:291305}
1306
[email protected]7ae7c2cb2009-01-06 23:31:411307void DownloadManager::GenerateExtension(
1308 const FilePath& file_name,
1309 const std::string& mime_type,
1310 FilePath::StringType* generated_extension) {
initial.commit09911bf2008-07-26 23:55:291311 // We're worried about three things here:
1312 //
1313 // 1) Security. Many sites let users upload content, such as buddy icons, to
1314 // their web sites. We want to mitigate the case where an attacker
1315 // supplies a malicious executable with an executable file extension but an
1316 // honest site serves the content with a benign content type, such as
1317 // image/jpeg.
1318 //
1319 // 2) Usability. If the site fails to provide a file extension, we want to
1320 // guess a reasonable file extension based on the content type.
1321 //
1322 // 3) Shell integration. Some file extensions automatically integrate with
1323 // the shell. We block these extensions to prevent a malicious web site
1324 // from integrating with the user's shell.
1325
[email protected]7ae7c2cb2009-01-06 23:31:411326 static const FilePath::CharType default_extension[] =
1327 FILE_PATH_LITERAL("download");
initial.commit09911bf2008-07-26 23:55:291328
1329 // See if our file name already contains an extension.
[email protected]63597e4e2010-07-08 17:49:051330 FilePath::StringType extension = file_name.Extension();
1331 if (!extension.empty())
1332 extension.erase(extension.begin()); // Erase preceding '.'.
initial.commit09911bf2008-07-26 23:55:291333
[email protected]b7f05882009-02-22 01:21:561334#if defined(OS_WIN)
initial.commit09911bf2008-07-26 23:55:291335 // Rename shell-integrated extensions.
1336 if (win_util::IsShellIntegratedExtension(extension))
1337 extension.assign(default_extension);
[email protected]b7f05882009-02-22 01:21:561338#endif
initial.commit09911bf2008-07-26 23:55:291339
1340 std::string mime_type_from_extension;
[email protected]bae0ea12009-02-14 01:20:411341 net::GetMimeTypeFromFile(file_name,
[email protected]7ae7c2cb2009-01-06 23:31:411342 &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291343 if (mime_type == mime_type_from_extension) {
1344 // The hinted extension matches the mime type. It looks like a winner.
1345 generated_extension->swap(extension);
1346 return;
1347 }
1348
[email protected]eccb9d12009-10-28 05:40:091349 if (IsExecutableExtension(extension) && !IsExecutableMimeType(mime_type)) {
initial.commit09911bf2008-07-26 23:55:291350 // We want to be careful about executable extensions. The worry here is
1351 // that a trusted web site could be tricked into dropping an executable file
1352 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101353 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291354 // We couldn't find a good extension for this content type. Use a dummy
1355 // extension instead.
1356 extension.assign(default_extension);
1357 }
1358 }
1359
1360 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101361 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291362 } else {
[email protected]6cade212008-12-03 00:32:221363 // Append extension generated from the mime type if:
initial.commit09911bf2008-07-26 23:55:291364 // 1. New extension is not ".txt"
1365 // 2. New extension is not the same as the already existing extension.
1366 // 3. New extension is not executable. This action mitigates the case when
[email protected]7ae7c2cb2009-01-06 23:31:411367 // an executable is hidden in a benign file extension;
initial.commit09911bf2008-07-26 23:55:291368 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1369 // application/x-javascript.
[email protected]e106457b2009-03-25 22:43:371370 // 4. New extension is not ".tar" for .gz files. For misconfigured web
1371 // servers, i.e. bug 5772.
[email protected]e32642f62009-09-11 21:58:291372 // 5. The original extension is not ".tgz" & the new extension is not "gz".
[email protected]7ae7c2cb2009-01-06 23:31:411373 FilePath::StringType append_extension;
[email protected]a9bb6f692008-07-30 16:40:101374 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
[email protected]3f156552009-02-09 19:44:171375 if (append_extension != FILE_PATH_LITERAL("txt") &&
[email protected]7ae7c2cb2009-01-06 23:31:411376 append_extension != extension &&
[email protected]eccb9d12009-10-28 05:40:091377 !IsExecutableExtension(append_extension) &&
[email protected]e32642f62009-09-11 21:58:291378 !(append_extension == FILE_PATH_LITERAL("gz") &&
1379 extension == FILE_PATH_LITERAL("tgz")) &&
[email protected]e106457b2009-03-25 22:43:371380 (append_extension != FILE_PATH_LITERAL("tar") ||
1381 extension != FILE_PATH_LITERAL("gz"))) {
[email protected]3f156552009-02-09 19:44:171382 extension += FILE_PATH_LITERAL(".");
initial.commit09911bf2008-07-26 23:55:291383 extension += append_extension;
[email protected]3f156552009-02-09 19:44:171384 }
initial.commit09911bf2008-07-26 23:55:291385 }
1386 }
1387
1388 generated_extension->swap(extension);
1389}
1390
[email protected]6aa4a1c02010-01-15 18:49:581391void DownloadManager::GenerateFileNameFromInfo(DownloadCreateInfo* info,
1392 FilePath* generated_name) {
1393 GenerateFileName(GURL(info->url),
1394 info->content_disposition,
1395 info->referrer_charset,
1396 info->mime_type,
1397 generated_name);
1398}
1399
1400void DownloadManager::GenerateFileName(const GURL& url,
1401 const std::string& content_disposition,
1402 const std::string& referrer_charset,
1403 const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411404 FilePath* generated_name) {
[email protected]630947c2009-11-04 18:37:311405 std::wstring default_name =
1406 l10n_util::GetString(IDS_DEFAULT_DOWNLOAD_FILENAME);
1407#if defined(OS_WIN)
1408 FilePath default_file_path(default_name);
1409#elif defined(OS_POSIX)
1410 FilePath default_file_path(base::SysWideToNativeMB(default_name));
1411#endif
1412
[email protected]6aa4a1c02010-01-15 18:49:581413 *generated_name = net::GetSuggestedFilename(GURL(url),
1414 content_disposition,
1415 referrer_charset,
[email protected]630947c2009-11-04 18:37:311416 default_file_path);
1417
[email protected]7ae7c2cb2009-01-06 23:31:411418 DCHECK(!generated_name->empty());
initial.commit09911bf2008-07-26 23:55:291419
[email protected]6aa4a1c02010-01-15 18:49:581420 GenerateSafeFileName(mime_type, generated_name);
initial.commit09911bf2008-07-26 23:55:291421}
1422
1423void DownloadManager::AddObserver(Observer* observer) {
1424 observers_.AddObserver(observer);
1425 observer->ModelChanged();
1426}
1427
1428void DownloadManager::RemoveObserver(Observer* observer) {
1429 observers_.RemoveObserver(observer);
1430}
1431
1432// Post Windows Shell operations to the Download thread, to avoid blocking the
1433// user interface.
1434void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1435 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371436 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581437#if defined(OS_MACOSX)
1438 // Mac needs to run this operation on the UI thread.
1439 platform_util::ShowItemInFolder(download->full_path());
1440#else
[email protected]d83d03aa2009-11-02 21:44:371441 ChromeThread::PostTask(
1442 ChromeThread::FILE, FROM_HERE,
1443 NewRunnableMethod(
1444 file_manager_, &DownloadFileManager::OnShowDownloadInShell,
1445 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:581446#endif
initial.commit09911bf2008-07-26 23:55:291447}
1448
[email protected]8f783752009-04-01 23:33:451449void DownloadManager::OpenDownload(const DownloadItem* download,
1450 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:401451 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:451452 // execute.
[email protected]a60c8ae2009-12-25 06:50:571453 if (download->is_extension_install()) {
[email protected]d4a71882010-06-25 16:36:411454 OpenChromeExtension(download->full_path(),
1455 download->url(),
1456 download->referrer_url(),
1457 download->original_mime_type());
[email protected]8f783752009-04-01 23:33:451458 } else {
1459 OpenDownloadInShell(download, parent_window);
1460 }
1461}
1462
[email protected]d4a71882010-06-25 16:36:411463void DownloadManager::OpenChromeExtension(
1464 const FilePath& full_path,
1465 const GURL& download_url,
1466 const GURL& referrer_url,
1467 const std::string& original_mime_type) {
[email protected]6ef635e42009-07-26 06:16:121468 // We don't support extensions in OTR mode.
[email protected]2a464a92009-08-01 17:58:351469 ExtensionsService* service = profile_->GetExtensionsService();
1470 if (service) {
[email protected]91e1bd82009-09-03 22:04:401471 NotificationService* nservice = NotificationService::current();
[email protected]6dfbbf82010-03-12 23:09:161472 GURL nonconst_download_url = download_url;
1473 nservice->Notify(NotificationType::EXTENSION_READY_FOR_INSTALL,
1474 Source<DownloadManager>(this),
1475 Details<GURL>(&nonconst_download_url));
1476
1477 scoped_refptr<CrxInstaller> installer(
1478 new CrxInstaller(service->install_directory(),
1479 service,
1480 new ExtensionInstallUI(profile_)));
1481 installer->set_delete_source(true);
1482
[email protected]a050d712009-11-06 00:40:101483 if (UserScript::HasUserScriptFileExtension(download_url)) {
[email protected]6dfbbf82010-03-12 23:09:161484 installer->InstallUserScript(full_path, download_url);
[email protected]6657afa62009-11-04 02:15:201485 } else {
[email protected]be18e1582010-06-03 21:50:421486 bool is_gallery_download =
1487 ExtensionsService::IsDownloadFromGallery(download_url, referrer_url);
[email protected]d4a71882010-06-25 16:36:411488 installer->set_original_mime_type(original_mime_type);
1489 installer->set_apps_require_extension_mime_type(true);
[email protected]6dfbbf82010-03-12 23:09:161490 installer->set_allow_privilege_increase(true);
1491 installer->set_original_url(download_url);
[email protected]9f72aa02010-06-25 10:01:051492 installer->set_limit_web_extent_to_download_host(!is_gallery_download);
[email protected]6dfbbf82010-03-12 23:09:161493 installer->InstallCrx(full_path);
[email protected]6657afa62009-11-04 02:15:201494 }
[email protected]21ca982c2010-01-26 22:49:551495 } else {
1496 TabContents* contents = NULL;
[email protected]a65bce4e2010-06-09 16:00:151497 // Get last active normal browser of profile.
1498 Browser* last_active = BrowserList::FindBrowserWithType(profile_,
[email protected]074e4f42010-06-23 16:12:061499 Browser::TYPE_NORMAL, true);
[email protected]21ca982c2010-01-26 22:49:551500 if (last_active)
1501 contents = last_active->GetSelectedTabContents();
1502 if (contents) {
1503 contents->AddInfoBar(
1504 new SimpleAlertInfoBarDelegate(contents,
1505 l10n_util::GetString(
1506 IDS_EXTENSION_INCOGNITO_INSTALL_INFOBAR_LABEL),
1507 ResourceBundle::GetSharedInstance().GetBitmapNamed(
[email protected]938e1f92010-04-01 18:09:421508 IDR_INFOBAR_PLUGIN_INSTALL),
1509 true));
[email protected]21ca982c2010-01-26 22:49:551510 }
[email protected]2a464a92009-08-01 17:58:351511 }
[email protected]8f783752009-04-01 23:33:451512}
1513
initial.commit09911bf2008-07-26 23:55:291514void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:591515 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:291516 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:371517 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:581518#if defined(OS_MACOSX)
1519 // Mac OS X requires opening downloads on the UI thread.
1520 platform_util::OpenItem(download->full_path());
1521#else
[email protected]d83d03aa2009-11-02 21:44:371522 ChromeThread::PostTask(
1523 ChromeThread::FILE, FROM_HERE,
1524 NewRunnableMethod(
1525 file_manager_, &DownloadFileManager::OnOpenDownloadInShell,
1526 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:581527#endif
initial.commit09911bf2008-07-26 23:55:291528}
1529
[email protected]eccb9d12009-10-28 05:40:091530void DownloadManager::OpenFilesBasedOnExtension(
1531 const FilePath& path, bool open) {
1532 FilePath::StringType extension = path.Extension();
1533 if (extension.empty())
1534 return;
1535 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1536 extension.erase(0, 1);
1537 if (open && !IsExecutableExtension(extension))
initial.commit09911bf2008-07-26 23:55:291538 auto_open_.insert(extension);
1539 else
1540 auto_open_.erase(extension);
1541 SaveAutoOpens();
1542}
1543
[email protected]eccb9d12009-10-28 05:40:091544bool DownloadManager::ShouldOpenFileBasedOnExtension(
1545 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:091546 FilePath::StringType extension = path.Extension();
1547 if (extension.empty())
1548 return false;
1549 if (IsExecutableExtension(extension))
1550 return false;
[email protected]92e11c82010-01-13 06:39:561551 if (Extension::IsExtension(path))
1552 return false;
[email protected]eccb9d12009-10-28 05:40:091553 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1554 extension.erase(0, 1);
[email protected]92e11c82010-01-13 06:39:561555 if (auto_open_.find(extension) != auto_open_.end())
[email protected]8c756ac2009-01-30 23:36:411556 return true;
initial.commit09911bf2008-07-26 23:55:291557 return false;
1558}
1559
[email protected]7b73d992008-12-15 20:56:461560static const char* kExecutableWhiteList[] = {
initial.commit09911bf2008-07-26 23:55:291561 // JavaScript is just as powerful as EXE.
[email protected]7b73d992008-12-15 20:56:461562 "text/javascript",
1563 "text/javascript;version=*",
[email protected]54d8d452009-04-08 17:29:241564 // Registry files can cause critical changes to the MS OS behavior.
1565 // Addition of this mimetype also addresses bug 7337.
1566 "text/x-registry",
[email protected]60ff8f912008-12-05 07:58:391567 // Some sites use binary/octet-stream to mean application/octet-stream.
1568 // See http://code.google.com/p/chromium/issues/detail?id=1573
[email protected]7b73d992008-12-15 20:56:461569 "binary/octet-stream"
1570};
initial.commit09911bf2008-07-26 23:55:291571
[email protected]7b73d992008-12-15 20:56:461572static const char* kExecutableBlackList[] = {
initial.commit09911bf2008-07-26 23:55:291573 // These application types are not executable.
[email protected]7b73d992008-12-15 20:56:461574 "application/*+xml",
1575 "application/xml"
1576};
initial.commit09911bf2008-07-26 23:55:291577
[email protected]7b73d992008-12-15 20:56:461578// static
1579bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
[email protected]bae0ea12009-02-14 01:20:411580 for (size_t i = 0; i < arraysize(kExecutableWhiteList); ++i) {
[email protected]7b73d992008-12-15 20:56:461581 if (net::MatchesMimeType(kExecutableWhiteList[i], mime_type))
1582 return true;
1583 }
[email protected]bae0ea12009-02-14 01:20:411584 for (size_t i = 0; i < arraysize(kExecutableBlackList); ++i) {
[email protected]7b73d992008-12-15 20:56:461585 if (net::MatchesMimeType(kExecutableBlackList[i], mime_type))
1586 return false;
1587 }
1588 // We consider only other application types to be executable.
1589 return net::MatchesMimeType("application/*", mime_type);
initial.commit09911bf2008-07-26 23:55:291590}
1591
[email protected]eccb9d12009-10-28 05:40:091592bool DownloadManager::IsExecutableFile(const FilePath& path) const {
1593 return IsExecutableExtension(path.Extension());
1594}
1595
1596bool DownloadManager::IsExecutableExtension(
[email protected]6aa4a1c02010-01-15 18:49:581597 const FilePath::StringType& extension) {
[email protected]eccb9d12009-10-28 05:40:091598 if (extension.empty())
1599 return false;
[email protected]64da0b932009-02-24 02:30:041600 if (!IsStringASCII(extension))
1601 return false;
[email protected]a0a9577b2009-05-27 23:52:321602#if defined(OS_WIN)
[email protected]64da0b932009-02-24 02:30:041603 std::string ascii_extension = WideToASCII(extension);
[email protected]e9ef0a62009-08-11 22:50:131604#elif defined(OS_POSIX)
[email protected]a0a9577b2009-05-27 23:52:321605 std::string ascii_extension = extension;
1606#endif
[email protected]64da0b932009-02-24 02:30:041607
[email protected]eccb9d12009-10-28 05:40:091608 // Strip out leading dot if it's still there
1609 if (ascii_extension[0] == FilePath::kExtensionSeparator)
1610 ascii_extension.erase(0, 1);
1611
[email protected]6aa4a1c02010-01-15 18:49:581612 return download_util::IsExecutableExtension(ascii_extension);
initial.commit09911bf2008-07-26 23:55:291613}
1614
1615void DownloadManager::ResetAutoOpenFiles() {
1616 auto_open_.clear();
1617 SaveAutoOpens();
1618}
1619
1620bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1621 return !auto_open_.empty();
1622}
1623
1624void DownloadManager::SaveAutoOpens() {
1625 PrefService* prefs = profile_->GetPrefs();
1626 if (prefs) {
[email protected]ddd231e2010-06-29 20:35:191627 std::string extensions;
[email protected]eccb9d12009-10-28 05:40:091628 for (AutoOpenSet::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:291629 it != auto_open_.end(); ++it) {
[email protected]ddd231e2010-06-29 20:35:191630#if defined(OS_POSIX)
1631 std::string this_extension = *it;
1632#elif defined(OS_WIN)
1633 std::string this_extension = base::SysWideToUTF8(*it);
1634#endif
1635 extensions += this_extension + ":";
initial.commit09911bf2008-07-26 23:55:291636 }
1637 if (!extensions.empty())
1638 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561639
[email protected]ddd231e2010-06-29 20:35:191640 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions);
initial.commit09911bf2008-07-26 23:55:291641 }
1642}
1643
[email protected]561abe62009-04-06 18:08:341644void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361645 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291646 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]7d3851d82008-12-12 03:26:071647 if (info->save_as)
[email protected]7ae7c2cb2009-01-06 23:31:411648 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291649 ContinueStartDownload(info, path);
1650}
1651
1652void DownloadManager::FileSelectionCanceled(void* params) {
1653 // The user didn't pick a place to save the file, so need to cancel the
1654 // download that's already in progress to the temporary location.
1655 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501656 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451657 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501658 info->request_id);
initial.commit09911bf2008-07-26 23:55:291659}
1660
[email protected]7ae7c2cb2009-01-06 23:31:411661void DownloadManager::DeleteDownload(const FilePath& path) {
[email protected]d83d03aa2009-11-02 21:44:371662 ChromeThread::PostTask(
1663 ChromeThread::FILE, FROM_HERE,
1664 NewRunnableFunction(&DownloadFileManager::DeleteFile, FilePath(path)));
[email protected]9ccbb372008-10-10 18:50:321665}
1666
1667
1668void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1669 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1670 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1671 download->UpdateObservers();
1672
1673 // If the download is not complete, nothing to do. The required
1674 // post-processing will be performed when it does complete.
1675 if (download->state() != DownloadItem::COMPLETE)
1676 return;
1677
[email protected]d83d03aa2009-11-02 21:44:371678 ChromeThread::PostTask(
1679 ChromeThread::FILE, FROM_HERE,
1680 NewRunnableMethod(
1681 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
1682 download->db_handle(), download->full_path(),
1683 download->original_name()));
[email protected]9ccbb372008-10-10 18:50:321684}
1685
[email protected]6aa4a1c02010-01-15 18:49:581686void DownloadManager::GenerateSafeFileName(const std::string& mime_type,
[email protected]7ae7c2cb2009-01-06 23:31:411687 FilePath* file_name) {
1688 // Make sure we get the right file extension
1689 FilePath::StringType extension;
[email protected]763f946a2009-01-06 19:04:391690 GenerateExtension(*file_name, mime_type, &extension);
[email protected]1bdaa60c2010-06-01 01:57:431691 *file_name = file_name->ReplaceExtension(extension);
[email protected]763f946a2009-01-06 19:04:391692
[email protected]2b2f8f72009-02-24 22:42:051693#if defined(OS_WIN)
[email protected]763f946a2009-01-06 19:04:391694 // Prepend "_" to the file name if it's a reserved name
[email protected]7ae7c2cb2009-01-06 23:31:411695 FilePath::StringType leaf_name = file_name->BaseName().value();
[email protected]763f946a2009-01-06 19:04:391696 DCHECK(!leaf_name.empty());
1697 if (win_util::IsReservedName(leaf_name)) {
[email protected]7ae7c2cb2009-01-06 23:31:411698 leaf_name = FilePath::StringType(FILE_PATH_LITERAL("_")) + leaf_name;
1699 *file_name = file_name->DirName();
1700 if (file_name->value() == FilePath::kCurrentDirectory) {
1701 *file_name = FilePath(leaf_name);
[email protected]763f946a2009-01-06 19:04:391702 } else {
[email protected]7ae7c2cb2009-01-06 23:31:411703 *file_name = file_name->Append(leaf_name);
[email protected]763f946a2009-01-06 19:04:391704 }
1705 }
[email protected]b7f05882009-02-22 01:21:561706#endif
[email protected]763f946a2009-01-06 19:04:391707}
1708
initial.commit09911bf2008-07-26 23:55:291709// Operations posted to us from the history service ----------------------------
1710
1711// The history service has retrieved all download entries. 'entries' contains
1712// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1713void DownloadManager::OnQueryDownloadEntriesComplete(
1714 std::vector<DownloadCreateInfo>* entries) {
1715 for (size_t i = 0; i < entries->size(); ++i) {
1716 DownloadItem* download = new DownloadItem(entries->at(i));
1717 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1718 downloads_[download->db_handle()] = download;
1719 download->set_manager(this);
1720 }
[email protected]b0ab1d42010-02-24 19:29:281721 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291722}
1723
initial.commit09911bf2008-07-26 23:55:291724// Once the new DownloadItem's creation info has been committed to the history
1725// service, we associate the DownloadItem with the db handle, update our
1726// 'downloads_' map and inform observers.
1727void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1728 int64 db_handle) {
1729 DownloadMap::iterator it = in_progress_.find(info.download_id);
1730 DCHECK(it != in_progress_.end());
1731
1732 DownloadItem* download = it->second;
[email protected]d2a8fb72010-01-21 05:31:421733
1734 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1735 // call this function with an invalid |db_handle|. For instance, this can
1736 // happen when the history database is offline. We cannot have multiple
1737 // DownloadItems with the same invalid db_handle, so we need to assign a
1738 // unique |db_handle| here.
1739 if (db_handle == kUninitializedHandle)
1740 db_handle = fake_db_handle_.GetNext();
1741
initial.commit09911bf2008-07-26 23:55:291742 DCHECK(download->db_handle() == kUninitializedHandle);
1743 download->set_db_handle(db_handle);
1744
1745 // Insert into our full map.
1746 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1747 downloads_[download->db_handle()] = download;
1748
[email protected]5e595482009-05-06 20:16:531749 // Show in the appropropriate browser UI.
1750 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291751
1752 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281753 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291754
1755 // If this download has been completed before we've received the db handle,
1756 // post one final message to the history service so that it can be properly
1757 // in sync with the DownloadItem's completion status, and also inform any
1758 // observers so that they get more than just the start notification.
1759 if (download->state() != DownloadItem::IN_PROGRESS) {
1760 in_progress_.erase(it);
initial.commit09911bf2008-07-26 23:55:291761 UpdateHistoryForDownload(download);
1762 download->UpdateObservers();
1763 }
[email protected]6a7fb042010-02-01 16:30:471764
1765 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:291766}
1767
1768// Called when the history service has retrieved the list of downloads that
1769// match the search text.
1770void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1771 std::vector<int64>* results) {
1772 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1773 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1774 if (!requestor)
1775 return;
1776
1777 std::vector<DownloadItem*> searched_downloads;
1778 for (std::vector<int64>::iterator it = results->begin();
1779 it != results->end(); ++it) {
1780 DownloadMap::iterator dit = downloads_.find(*it);
1781 if (dit != downloads_.end())
1782 searched_downloads.push_back(dit->second);
1783 }
1784
1785 requestor->SetDownloads(searched_downloads);
1786}
[email protected]905a08d2008-11-19 07:24:121787
[email protected]5e595482009-05-06 20:16:531788void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1789 DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341790 // The 'contents' may no longer exist if the user closed the tab before we
1791 // get this start completion event. If it does, tell the origin TabContents
1792 // to display its download shelf.
[email protected]76543b92009-08-31 17:27:451793 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1794 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531795
1796 // If the contents no longer exists, we start the download in the last active
1797 // browser. This is not ideal but better than fully hiding the download from
1798 // the user.
1799 if (!contents) {
1800 Browser* last_active = BrowserList::GetLastActive();
1801 if (last_active)
1802 contents = last_active->GetSelectedTabContents();
1803 }
1804
1805 if (contents)
1806 contents->OnStartDownload(download);
1807}
1808
[email protected]6cade212008-12-03 00:32:221809// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121810void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411811 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381812}
[email protected]b0ab1d42010-02-24 19:29:281813
1814void DownloadManager::NotifyModelChanged() {
1815 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1816}
1817
1818// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1819
1820DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1821 DownloadManager* observing_download_manager)
1822 : observing_download_manager_(observing_download_manager),
1823 observed_download_manager_(NULL) {
1824 if (observing_download_manager->profile_->GetOriginalProfile() ==
1825 observing_download_manager->profile_) {
1826 return;
1827 }
1828
1829 observed_download_manager_ = observing_download_manager_->
1830 profile_->GetOriginalProfile()->GetDownloadManager();
1831 observed_download_manager_->AddObserver(this);
1832}
1833
1834DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1835 if (observed_download_manager_)
1836 observed_download_manager_->RemoveObserver(this);
1837}
1838
1839void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1840 observing_download_manager_->NotifyModelChanged();
1841}
1842
1843void DownloadManager::OtherDownloadManagerObserver::SetDownloads(
1844 std::vector<DownloadItem*>& downloads) {
1845}
1846
1847void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1848 observed_download_manager_ = NULL;
1849}