blob: da878b0f2687bf7823138c1062daaa22da64b5f1 [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"
initial.commit09911bf2008-07-26 23:55:2912#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1413#include "base/rand_util.h"
[email protected]92926d92010-09-02 18:35:0614#include "base/stl_util-inl.h"
[email protected]2594c2b2010-11-08 23:04:2615#include "base/stringprintf.h"
[email protected]1b5044d2009-02-24 00:04:1416#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2917#include "base/task.h"
[email protected]ce7f62e32010-08-10 23:43:5918#include "base/utf_string_conversions.h"
[email protected]d2a8fb72010-01-21 05:31:4219#include "build/build_config.h"
initial.commit09911bf2008-07-26 23:55:2920#include "chrome/browser/browser_list.h"
21#include "chrome/browser/browser_process.h"
[email protected]facac1532010-10-11 22:59:5022#include "chrome/browser/browser_thread.h"
[email protected]cd448092010-12-06 23:49:1323#include "chrome/browser/download/download_extensions.h"
[email protected]6c69796d2010-07-16 21:41:1624#include "chrome/browser/download/download_file_manager.h"
[email protected]82f37b02010-07-29 22:04:5725#include "chrome/browser/download/download_history.h"
[email protected]6c69796d2010-07-16 21:41:1626#include "chrome/browser/download/download_item.h"
[email protected]e5dc4222010-08-30 22:16:3227#include "chrome/browser/download/download_prefs.h"
[email protected]073ed7b2010-09-27 09:20:0228#include "chrome/browser/download/download_status_updater.h"
[email protected]e9ef0a62009-08-11 22:50:1329#include "chrome/browser/download/download_util.h"
[email protected]eaa7dd182010-12-14 11:09:0030#include "chrome/browser/extensions/extension_service.h"
[email protected]a0835ac2010-09-13 19:40:0831#include "chrome/browser/history/download_create_info.h"
[email protected]be180c802009-10-23 06:33:3132#include "chrome/browser/net/chrome_url_request_context.h"
[email protected]14a000d2010-04-29 21:44:2433#include "chrome/browser/platform_util.h"
[email protected]8ecad5e2010-12-02 21:18:3334#include "chrome/browser/profiles/profile.h"
[email protected]8c8657d62009-01-16 18:31:2635#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2536#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]8e2b6472010-12-15 22:19:4837#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]21ca982c2010-01-26 22:49:5538#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]57c6a652009-05-04 07:58:3439#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]d2a8fb72010-01-21 05:31:4240#include "chrome/browser/tab_contents/tab_util.h"
[email protected]7b5dc002010-11-16 23:08:1041#include "chrome/browser/ui/browser.h"
initial.commit09911bf2008-07-26 23:55:2942#include "chrome/common/chrome_paths.h"
[email protected]91e1bd82009-09-03 22:04:4043#include "chrome/common/notification_type.h"
initial.commit09911bf2008-07-26 23:55:2944#include "chrome/common/pref_names.h"
[email protected]46072d42008-07-28 14:49:3545#include "googleurl/src/gurl.h"
[email protected]34ac8f32009-02-22 23:03:2746#include "grit/generated_resources.h"
[email protected]21ca982c2010-01-26 22:49:5547#include "grit/theme_resources.h"
initial.commit09911bf2008-07-26 23:55:2948#include "net/base/mime_util.h"
49#include "net/base/net_util.h"
initial.commit09911bf2008-07-26 23:55:2950
[email protected]b7f05882009-02-22 01:21:5651#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2552#include "app/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3253#endif
54
[email protected]073ed7b2010-09-27 09:20:0255DownloadManager::DownloadManager(DownloadStatusUpdater* status_updater)
initial.commit09911bf2008-07-26 23:55:2956 : shutdown_needed_(false),
57 profile_(NULL),
[email protected]073ed7b2010-09-27 09:20:0258 file_manager_(NULL),
[email protected]a3d2bc42010-10-06 14:08:4959 status_updater_(status_updater->AsWeakPtr()) {
[email protected]073ed7b2010-09-27 09:20:0260 if (status_updater_)
61 status_updater_->AddDelegate(this);
initial.commit09911bf2008-07-26 23:55:2962}
63
64DownloadManager::~DownloadManager() {
[email protected]326a6a92010-09-10 20:21:1365 DCHECK(!shutdown_needed_);
[email protected]073ed7b2010-09-27 09:20:0266 if (status_updater_)
67 status_updater_->RemoveDelegate(this);
initial.commit09911bf2008-07-26 23:55:2968}
69
70void DownloadManager::Shutdown() {
[email protected]da6e3922010-11-24 21:45:5071 VLOG(20) << __FUNCTION__ << "()"
72 << " shutdown_needed_ = " << shutdown_needed_;
[email protected]326a6a92010-09-10 20:21:1373 if (!shutdown_needed_)
74 return;
75 shutdown_needed_ = false;
initial.commit09911bf2008-07-26 23:55:2976
[email protected]326a6a92010-09-10 20:21:1377 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
78
79 if (file_manager_) {
[email protected]ca4b5fa32010-10-09 12:42:1880 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
[email protected]326a6a92010-09-10 20:21:1381 NewRunnableMethod(file_manager_,
82 &DownloadFileManager::OnDownloadManagerShutdown,
[email protected]dc7cdcb92010-12-14 06:40:5483 make_scoped_refptr(this)));
[email protected]326a6a92010-09-10 20:21:1384 }
initial.commit09911bf2008-07-26 23:55:2985
[email protected]f04182f32010-12-10 19:12:0786 AssertContainersConsistent();
87
88 // Go through all downloads in downloads_. Dangerous ones we need to
89 // remove on disk, and in progress ones we need to cancel.
[email protected]57fd1252010-12-23 17:24:0990 for (DownloadSet::iterator it = downloads_.begin(); it != downloads_.end();) {
[email protected]f04182f32010-12-10 19:12:0791 DownloadItem* download = *it;
92
93 // Save iterator from potential erases in this set done by called code.
94 // Iterators after an erasure point are still valid for lists and
95 // associative containers such as sets.
96 it++;
97
98 if (download->safety_state() == DownloadItem::DANGEROUS &&
99 (download->state() == DownloadItem::IN_PROGRESS ||
100 download->state() == DownloadItem::COMPLETE)) {
101 // The user hasn't accepted it, so we need to remove it
102 // from the disk. This may or may not result in it being
103 // removed from the DownloadManager queues and deleted
104 // (specifically, DownloadManager::RemoveDownload only
105 // removes and deletes it if it's known to the history service)
106 // so the only thing we know after calling this function is that
107 // the download was deleted if-and-only-if it was removed
108 // from all queues.
109 download->Remove(true);
110 } else if (download->state() == DownloadItem::IN_PROGRESS) {
111 download->Cancel(false);
112 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29113 }
114 }
115
[email protected]f04182f32010-12-10 19:12:07116 // At this point, all dangerous downloads have had their files removed
117 // and all in progress downloads have been cancelled. We can now delete
118 // anything left.
119 STLDeleteElements(&downloads_);
[email protected]9ccbb372008-10-10 18:50:32120
[email protected]f04182f32010-12-10 19:12:07121 // And clear all non-owning containers.
initial.commit09911bf2008-07-26 23:55:29122 in_progress_.clear();
[email protected]57fd1252010-12-23 17:24:09123#if !defined(NDEBUG)
124 save_page_as_downloads_.clear();
125#endif
initial.commit09911bf2008-07-26 23:55:29126
127 file_manager_ = NULL;
128
initial.commit09911bf2008-07-26 23:55:29129 // Make sure the save as dialog doesn't notify us back if we're gone before
130 // it returns.
131 if (select_file_dialog_.get())
132 select_file_dialog_->ListenerDestroyed();
133
[email protected]82f37b02010-07-29 22:04:57134 download_history_.reset();
135
[email protected]2c93f6f2010-11-08 20:41:17136 request_context_getter_ = NULL;
137
initial.commit09911bf2008-07-26 23:55:29138 shutdown_needed_ = false;
139}
140
[email protected]82f37b02010-07-29 22:04:57141void DownloadManager::GetTemporaryDownloads(
142 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
143 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58144
[email protected]f04182f32010-12-10 19:12:07145 for (DownloadMap::iterator it = history_downloads_.begin();
146 it != history_downloads_.end(); ++it) {
[email protected]6aa4a1c02010-01-15 18:49:58147 if (it->second->is_temporary() &&
148 it->second->full_path().DirName() == dir_path)
[email protected]82f37b02010-07-29 22:04:57149 result->push_back(it->second);
[email protected]6aa4a1c02010-01-15 18:49:58150 }
[email protected]6aa4a1c02010-01-15 18:49:58151}
152
[email protected]82f37b02010-07-29 22:04:57153void DownloadManager::GetAllDownloads(
154 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
155 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34156
[email protected]f04182f32010-12-10 19:12:07157 for (DownloadMap::iterator it = history_downloads_.begin();
158 it != history_downloads_.end(); ++it) {
[email protected]8ddbd66a2010-05-21 16:38:34159 if (!it->second->is_temporary() &&
160 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57161 result->push_back(it->second);
[email protected]8ddbd66a2010-05-21 16:38:34162 }
[email protected]8ddbd66a2010-05-21 16:38:34163}
164
[email protected]82f37b02010-07-29 22:04:57165void DownloadManager::GetCurrentDownloads(
166 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
167 DCHECK(result);
[email protected]c4a530b2010-03-08 17:33:03168
[email protected]f04182f32010-12-10 19:12:07169 for (DownloadMap::iterator it = history_downloads_.begin();
170 it != history_downloads_.end(); ++it) {
[email protected]c4a530b2010-03-08 17:33:03171 if (!it->second->is_temporary() &&
172 (it->second->state() == DownloadItem::IN_PROGRESS ||
173 it->second->safety_state() == DownloadItem::DANGEROUS) &&
174 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57175 result->push_back(it->second);
[email protected]c4a530b2010-03-08 17:33:03176 }
[email protected]f7e9fd62010-09-28 15:45:06177
178 // If we have a parent profile, let it add its downloads to the results.
179 Profile* original_profile = profile_->GetOriginalProfile();
180 if (original_profile != profile_)
181 original_profile->GetDownloadManager()->GetCurrentDownloads(dir_path,
182 result);
[email protected]c4a530b2010-03-08 17:33:03183}
184
[email protected]d3b12902010-08-16 23:39:42185void DownloadManager::SearchDownloads(const string16& query,
186 std::vector<DownloadItem*>* result) {
187 DCHECK(result);
188
189 string16 query_lower(l10n_util::ToLower(query));
190
[email protected]f04182f32010-12-10 19:12:07191 for (DownloadMap::iterator it = history_downloads_.begin();
192 it != history_downloads_.end(); ++it) {
[email protected]d3b12902010-08-16 23:39:42193 DownloadItem* download_item = it->second;
194
195 if (download_item->is_temporary() || download_item->is_extension_install())
196 continue;
197
198 // Display Incognito downloads only in Incognito window, and vice versa.
199 // The Incognito Downloads page will get the list of non-Incognito downloads
200 // from its parent profile.
201 if (profile_->IsOffTheRecord() != download_item->is_otr())
202 continue;
203
204 if (download_item->MatchesQuery(query_lower))
205 result->push_back(download_item);
206 }
207
208 // If we have a parent profile, let it add its downloads to the results.
209 Profile* original_profile = profile_->GetOriginalProfile();
210 if (original_profile != profile_)
211 original_profile->GetDownloadManager()->SearchDownloads(query, result);
212}
213
initial.commit09911bf2008-07-26 23:55:29214// Query the history service for information about all persisted downloads.
215bool DownloadManager::Init(Profile* profile) {
216 DCHECK(profile);
217 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
218 shutdown_needed_ = true;
219
220 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31221 request_context_getter_ = profile_->GetRequestContext();
[email protected]d3b12902010-08-16 23:39:42222 download_history_.reset(new DownloadHistory(profile));
[email protected]82f37b02010-07-29 22:04:57223 download_history_->Load(
224 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
[email protected]024f2f02010-04-30 22:51:46225
[email protected]e5dc4222010-08-30 22:16:32226 download_prefs_.reset(new DownloadPrefs(profile_->GetPrefs()));
227
[email protected]2941c2392010-07-15 22:54:30228 // In test mode, there may be no ResourceDispatcherHost. In this case it's
229 // safe to avoid setting |file_manager_| because we only call a small set of
230 // functions, none of which need it.
initial.commit09911bf2008-07-26 23:55:29231 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]2941c2392010-07-15 22:54:30232 if (rdh) {
233 file_manager_ = rdh->download_file_manager();
234 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29235 }
236
[email protected]b0ab1d42010-02-24 19:29:28237 other_download_manager_observer_.reset(
238 new OtherDownloadManagerObserver(this));
239
initial.commit09911bf2008-07-26 23:55:29240 return true;
241}
242
initial.commit09911bf2008-07-26 23:55:29243// We have received a message from DownloadFileManager about a new download. We
244// create a download item and store it in our download map, and inform the
245// history system of a new download. Since this method can be called while the
246// history service thread is still reading the persistent state, we do not
[email protected]f04182f32010-12-10 19:12:07247// insert the new DownloadItem into 'history_downloads_' or inform our
248// observers at this point. OnCreateDatabaseEntryComplete() handles that
249// finalization of the the download creation as a callback from the
250// history thread.
initial.commit09911bf2008-07-26 23:55:29251void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]ca4b5fa32010-10-09 12:42:18252 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29253 DCHECK(info);
254
[email protected]a60c8ae2009-12-25 06:50:57255 // Check whether this download is for an extension install or not.
[email protected]e6875c12010-07-18 11:14:13256 // Allow extensions to be explicitly saved.
257 if (!info->prompt_user_for_save_location) {
[email protected]a60c8ae2009-12-25 06:50:57258 if (UserScript::HasUserScriptFileExtension(info->url) ||
259 info->mime_type == Extension::kMimeType)
260 info->is_extension_install = true;
261 }
262
[email protected]8af9d032010-02-10 00:00:32263 if (info->save_info.file_path.empty()) {
[email protected]2941c2392010-07-15 22:54:30264 FilePath generated_name;
[email protected]7ba53e12010-08-05 17:14:00265 download_util::GenerateFileNameFromInfo(info, &generated_name);
[email protected]2941c2392010-07-15 22:54:30266
267 // Freeze the user's preference for showing a Save As dialog. We're going
268 // to bounce around a bunch of threads and we don't want to worry about race
269 // conditions where the user changes this pref out from under us.
[email protected]e5dc4222010-08-30 22:16:32270 if (download_prefs_->prompt_for_download()) {
[email protected]2941c2392010-07-15 22:54:30271 // But ignore the user's preference for the following scenarios:
272 // 1) Extension installation. Note that we only care here about the case
273 // where an extension is installed, not when one is downloaded with
274 // "save as...".
275 // 2) Filetypes marked "always open." If the user just wants this file
276 // opened, don't bother asking where to keep it.
277 if (!info->is_extension_install &&
278 !ShouldOpenFileBasedOnExtension(generated_name))
[email protected]e6875c12010-07-18 11:14:13279 info->prompt_user_for_save_location = true;
[email protected]2941c2392010-07-15 22:54:30280 }
281
[email protected]8af9d032010-02-10 00:00:32282 // Determine the proper path for a download, by either one of the following:
283 // 1) using the default download directory.
284 // 2) prompting the user.
[email protected]ccea03c2010-12-17 03:31:50285 if (info->prompt_user_for_save_location && !last_download_path_.empty()) {
[email protected]8af9d032010-02-10 00:00:32286 info->suggested_path = last_download_path_;
[email protected]80dc3612010-07-27 19:35:08287 } else {
[email protected]e5dc4222010-08-30 22:16:32288 info->suggested_path = download_prefs_->download_path();
[email protected]80dc3612010-07-27 19:35:08289 }
[email protected]8af9d032010-02-10 00:00:32290 info->suggested_path = info->suggested_path.Append(generated_name);
291 } else {
292 info->suggested_path = info->save_info.file_path;
293 }
initial.commit09911bf2008-07-26 23:55:29294
[email protected]e6875c12010-07-18 11:14:13295 if (!info->prompt_user_for_save_location &&
296 info->save_info.file_path.empty()) {
[email protected]d3071992010-10-08 15:24:07297 info->is_dangerous = download_util::IsDangerous(info, profile());
[email protected]e9ebf3fc2008-10-17 22:06:58298 }
299
initial.commit09911bf2008-07-26 23:55:29300 // We need to move over to the download thread because we don't want to stat
301 // the suggested path on the UI thread.
[email protected]5a3b97e2010-10-05 09:49:11302 // We can only access preferences on the UI thread, so check the download path
303 // now and pass the value to the FILE thread.
[email protected]ca4b5fa32010-10-09 12:42:18304 BrowserThread::PostTask(
305 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37306 NewRunnableMethod(
[email protected]5a3b97e2010-10-05 09:49:11307 this,
308 &DownloadManager::CheckIfSuggestedPathExists,
309 info,
310 download_prefs()->download_path()));
initial.commit09911bf2008-07-26 23:55:29311}
312
[email protected]5a3b97e2010-10-05 09:49:11313void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info,
314 const FilePath& default_path) {
[email protected]ca4b5fa32010-10-09 12:42:18315 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
initial.commit09911bf2008-07-26 23:55:29316 DCHECK(info);
317
[email protected]5a3b97e2010-10-05 09:49:11318 // Make sure the default download directory exists.
319 // TODO(phajdan.jr): only create the directory when we're sure the user
320 // is going to save there and not to another directory of his choice.
321 file_util::CreateDirectory(default_path);
322
initial.commit09911bf2008-07-26 23:55:29323 // Check writability of the suggested path. If we can't write to it, default
324 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41325 FilePath dir = info->suggested_path.DirName();
326 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32327 if (!file_util::PathIsWritable(dir)) {
[email protected]da6e3922010-11-24 21:45:50328 VLOG(1) << "Unable to write to directory \"" << dir.value() << "\"";
[email protected]e6875c12010-07-18 11:14:13329 info->prompt_user_for_save_location = true;
initial.commit09911bf2008-07-26 23:55:29330 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41331 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29332 }
333
[email protected]6cade212008-12-03 00:32:22334 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58335 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41336 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32337 // Create a temporary file to hold the file until the user approves its
338 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41339 FilePath::StringType file_name;
340 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32341 while (path.empty()) {
[email protected]2594c2b2010-11-08 23:04:26342 base::SStringPrintf(
343 &file_name,
344 FILE_PATH_LITERAL("unconfirmed %d.crdownload"),
345 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41346 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07347 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41348 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32349 }
350 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16351 } else {
[email protected]594cd7d2010-07-21 03:23:56352 // Do not add the path uniquifier if we are saving to a specific path as in
353 // the drag-out case.
354 if (info->save_info.file_path.empty()) {
355 info->path_uniquifier = download_util::GetUniquePathNumberWithCrDownload(
356 info->suggested_path);
357 }
[email protected]7a256ea2008-10-17 17:34:16358 // We know the final path, build it if necessary.
359 if (info->path_uniquifier > 0) {
[email protected]5a2388a2010-03-26 16:13:39360 download_util::AppendNumberToPath(&(info->suggested_path),
361 info->path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16362 // Setting path_uniquifier to 0 to make sure we don't try to unique it
363 // later on.
364 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07365 } else if (info->path_uniquifier == -1) {
366 // We failed to find a unique path. We have to prompt the user.
[email protected]da6e3922010-11-24 21:45:50367 VLOG(1) << "Unable to find a unique path for suggested path \""
368 << info->suggested_path.value() << "\"";
[email protected]e6875c12010-07-18 11:14:13369 info->prompt_user_for_save_location = true;
[email protected]7a256ea2008-10-17 17:34:16370 }
[email protected]9ccbb372008-10-10 18:50:32371 }
372
[email protected]594cd7d2010-07-21 03:23:56373 // Create an empty file at the suggested path so that we don't allocate the
374 // same "non-existant" path to multiple downloads.
375 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]e6875c12010-07-18 11:14:13376 if (!info->prompt_user_for_save_location &&
377 info->save_info.file_path.empty()) {
[email protected]594cd7d2010-07-21 03:23:56378 if (info->is_dangerous)
379 file_util::WriteFile(info->suggested_path, "", 0);
380 else
381 file_util::WriteFile(download_util::GetCrDownloadPath(
382 info->suggested_path), "", 0);
[email protected]7d3851d82008-12-12 03:26:07383 }
384
[email protected]ca4b5fa32010-10-09 12:42:18385 BrowserThread::PostTask(
386 BrowserThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29387 NewRunnableMethod(this,
388 &DownloadManager::OnPathExistenceAvailable,
389 info));
390}
391
392void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]da6e3922010-11-24 21:45:50393 VLOG(20) << __FUNCTION__ << "()" << " info = " << info->DebugString();
[email protected]ca4b5fa32010-10-09 12:42:18394 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29395 DCHECK(info);
396
[email protected]e6875c12010-07-18 11:14:13397 if (info->prompt_user_for_save_location) {
initial.commit09911bf2008-07-26 23:55:29398 // We must ask the user for the place to put the download.
399 if (!select_file_dialog_.get())
400 select_file_dialog_ = SelectFileDialog::Create(this);
401
[email protected]76543b92009-08-31 17:27:45402 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
403 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08404 SelectFileDialog::FileTypeInfo file_type_info;
405 file_type_info.extensions.resize(1);
406 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24407 if (!file_type_info.extensions[0][0].empty())
408 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08409 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23410 gfx::NativeWindow owning_window =
411 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29412 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34413 string16(),
414 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08415 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30416 owning_window, info);
[email protected]ac167ce2010-11-24 17:59:48417 FOR_EACH_OBSERVER(Observer, observers_, SelectFileDialogDisplayed());
initial.commit09911bf2008-07-26 23:55:29418 } else {
419 // No prompting for download, just continue with the suggested name.
[email protected]c2e76012010-12-23 21:10:29420 AttachDownloadItem(info, info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29421 }
422}
423
[email protected]c2e76012010-12-23 21:10:29424void DownloadManager::CreateDownloadItem(DownloadCreateInfo* info) {
425 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
426
427 DownloadItem* download = new DownloadItem(this, *info,
428 profile_->IsOffTheRecord());
429 DCHECK(!ContainsKey(in_progress_, info->download_id));
430 downloads_.insert(download);
431}
432
433void DownloadManager::AttachDownloadItem(DownloadCreateInfo* info,
[email protected]a850ba42010-09-10 22:00:30434 const FilePath& target_path) {
[email protected]ca4b5fa32010-10-09 12:42:18435 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]aa033af2010-07-27 18:16:39436
initial.commit09911bf2008-07-26 23:55:29437 scoped_ptr<DownloadCreateInfo> infop(info);
438 info->path = target_path;
439
[email protected]c2e76012010-12-23 21:10:29440 // NOTE(ahendrickson) We will be adding a new map |active_downloads_|, into
441 // which we will be adding the download as soon as it's created. This will
442 // make this loop unnecessary.
443 // Eventually |active_downloads_| will replace |in_progress_|, but we don't
444 // want to change the semantics yet.
[email protected]aa033af2010-07-27 18:16:39445 DCHECK(!ContainsKey(in_progress_, info->download_id));
[email protected]c2e76012010-12-23 21:10:29446 DownloadItem* download = NULL;
447 for (std::set<DownloadItem*>::iterator i = downloads_.begin();
448 i != downloads_.end(); ++i) {
449 DownloadItem* item = (*i);
450 if (item && (item->id() == info->download_id)) {
451 download = item;
452 break;
453 }
454 }
455 DCHECK(download != NULL);
456 download->SetFileCheckResults(info->path,
457 info->is_dangerous,
458 info->path_uniquifier,
459 info->prompt_user_for_save_location,
460 info->is_extension_install,
461 info->original_name);
[email protected]aa033af2010-07-27 18:16:39462 in_progress_[info->download_id] = download;
initial.commit09911bf2008-07-26 23:55:29463
[email protected]aa033af2010-07-27 18:16:39464 bool download_finished = ContainsKey(pending_finished_downloads_,
465 info->download_id);
[email protected]594cd7d2010-07-21 03:23:56466
[email protected]da6e3922010-11-24 21:45:50467 VLOG(20) << __FUNCTION__ << "()"
[email protected]c2e76012010-12-23 21:10:29468 << " target_path = \"" << target_path.value() << "\""
[email protected]da6e3922010-11-24 21:45:50469 << " download_finished = " << download_finished
[email protected]c2e76012010-12-23 21:10:29470 << " info = " << info->DebugString()
471 << " download = " << download->DebugString(true);
[email protected]da6e3922010-11-24 21:45:50472
[email protected]594cd7d2010-07-21 03:23:56473 if (download_finished || info->is_dangerous) {
474 // The download has already finished or the download is not safe.
475 // We can now rename the file to its final name (or its tentative name
476 // in dangerous download cases).
[email protected]ca4b5fa32010-10-09 12:42:18477 BrowserThread::PostTask(
478 BrowserThread::FILE, FROM_HERE,
[email protected]594cd7d2010-07-21 03:23:56479 NewRunnableMethod(
[email protected]0d7e79fa2010-10-08 23:35:47480 file_manager_, &DownloadFileManager::OnFinalDownloadName,
[email protected]dc7cdcb92010-12-14 06:40:54481 download->id(), target_path, !info->is_dangerous,
482 make_scoped_refptr(this)));
[email protected]594cd7d2010-07-21 03:23:56483 } else {
484 // The download hasn't finished and it is a safe download. We need to
485 // rename it to its intermediate '.crdownload' path.
486 FilePath download_path = download_util::GetCrDownloadPath(target_path);
[email protected]ca4b5fa32010-10-09 12:42:18487 BrowserThread::PostTask(
488 BrowserThread::FILE, FROM_HERE,
[email protected]594cd7d2010-07-21 03:23:56489 NewRunnableMethod(
[email protected]0d7e79fa2010-10-08 23:35:47490 file_manager_, &DownloadFileManager::OnIntermediateDownloadName,
[email protected]dc7cdcb92010-12-14 06:40:54491 download->id(), download_path, make_scoped_refptr(this)));
[email protected]44b94b82010-11-08 20:49:18492 download->Rename(download_path);
[email protected]594cd7d2010-07-21 03:23:56493 }
494
495 if (download_finished) {
496 // If the download already completed by the time we reached this point, then
497 // notify observers that it did.
[email protected]a850ba42010-09-10 22:00:30498 OnAllDataSaved(info->download_id,
499 pending_finished_downloads_[info->download_id]);
[email protected]594cd7d2010-07-21 03:23:56500 }
initial.commit09911bf2008-07-26 23:55:29501
[email protected]82f37b02010-07-29 22:04:57502 download_history_->AddEntry(*info, download,
503 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
[email protected]6a7fb042010-02-01 16:30:47504
505 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29506}
507
initial.commit09911bf2008-07-26 23:55:29508void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
509 DownloadMap::iterator it = in_progress_.find(download_id);
510 if (it != in_progress_.end()) {
511 DownloadItem* download = it->second;
512 download->Update(size);
[email protected]82f37b02010-07-29 22:04:57513 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29514 }
[email protected]6a7fb042010-02-01 16:30:47515 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29516}
517
[email protected]a850ba42010-09-10 22:00:30518void DownloadManager::OnAllDataSaved(int32 download_id, int64 size) {
[email protected]da6e3922010-11-24 21:45:50519 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
520 << " size = " << size;
initial.commit09911bf2008-07-26 23:55:29521 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32522 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29523 // The download is done, but the user hasn't selected a final location for
524 // it yet (the Save As dialog box is probably still showing), so just keep
525 // track of the fact that this download id is complete, when the
526 // DownloadItem is constructed later we'll notify its completion then.
527 PendingFinishedMap::iterator erase_it =
528 pending_finished_downloads_.find(download_id);
529 DCHECK(erase_it == pending_finished_downloads_.end());
530 pending_finished_downloads_[download_id] = size;
[email protected]da6e3922010-11-24 21:45:50531 VLOG(20) << __FUNCTION__ << "()" << " Added download_id = " << download_id
532 << " to pending_finished_downloads_";
[email protected]9ccbb372008-10-10 18:50:32533 return;
initial.commit09911bf2008-07-26 23:55:29534 }
[email protected]9ccbb372008-10-10 18:50:32535
536 // Remove the id from the list of pending ids.
537 PendingFinishedMap::iterator erase_it =
538 pending_finished_downloads_.find(download_id);
[email protected]da6e3922010-11-24 21:45:50539 if (erase_it != pending_finished_downloads_.end()) {
[email protected]9ccbb372008-10-10 18:50:32540 pending_finished_downloads_.erase(erase_it);
[email protected]da6e3922010-11-24 21:45:50541 VLOG(20) << __FUNCTION__ << "()" << " Removed download_id = " << download_id
542 << " from pending_finished_downloads_";
543 }
[email protected]9ccbb372008-10-10 18:50:32544
545 DownloadItem* download = it->second;
[email protected]da6e3922010-11-24 21:45:50546
547 VLOG(20) << __FUNCTION__ << "()"
548 << " download = " << download->DebugString(true);
549
[email protected]a850ba42010-09-10 22:00:30550 download->OnAllDataSaved(size);
[email protected]9ccbb372008-10-10 18:50:32551
552 // Clean up will happen when the history system create callback runs if we
553 // don't have a valid db_handle yet.
[email protected]82f37b02010-07-29 22:04:57554 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
[email protected]9ccbb372008-10-10 18:50:32555 in_progress_.erase(it);
[email protected]82f37b02010-07-29 22:04:57556 download_history_->UpdateEntry(download);
[email protected]9ccbb372008-10-10 18:50:32557 }
558
[email protected]6a7fb042010-02-01 16:30:47559 UpdateAppIcon();
560
[email protected]9ccbb372008-10-10 18:50:32561 // If this a dangerous download not yet validated by the user, don't do
562 // anything. When the user notifies us, it will trigger a call to
563 // ProceedWithFinishedDangerousDownload.
564 if (download->safety_state() == DownloadItem::DANGEROUS) {
[email protected]9ccbb372008-10-10 18:50:32565 return;
566 }
567
568 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22569 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32570 // its final name before we can continue.
[email protected]ca4b5fa32010-10-09 12:42:18571 BrowserThread::PostTask(
572 BrowserThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32573 NewRunnableMethod(
574 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
575 download->db_handle(),
[email protected]44b94b82010-11-08 20:49:18576 download->full_path(), download->target_name()));
[email protected]9ccbb372008-10-10 18:50:32577 return;
578 }
[email protected]594cd7d2010-07-21 03:23:56579
[email protected]9246de32010-11-10 22:58:47580 download->OnSafeDownloadFinished(file_manager_);
[email protected]9ccbb372008-10-10 18:50:32581}
582
[email protected]8f783752009-04-01 23:33:45583void DownloadManager::DownloadRenamedToFinalName(int download_id,
584 const FilePath& full_path) {
[email protected]da6e3922010-11-24 21:45:50585 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
586 << " full_path = \"" << full_path.value() << "\"";
[email protected]ca4b5fa32010-10-09 12:42:18587 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]2e030682010-07-23 19:45:36588 DownloadItem* item = GetDownloadItem(download_id);
589 if (!item)
590 return;
[email protected]9246de32010-11-10 22:58:47591 item->OnDownloadRenamedToFinalName(full_path);
[email protected]8f783752009-04-01 23:33:45592}
593
[email protected]9ccbb372008-10-10 18:50:32594// Called on the file thread. Renames the downloaded file to its original name.
595void DownloadManager::ProceedWithFinishedDangerousDownload(
596 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41597 const FilePath& path,
598 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32599 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41600 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16601 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32602 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24603 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16604 // Make our name unique at this point, as if a dangerous file is downloading
605 // and a 2nd download is started for a file with the same name, they would
606 // have the same path. This is because we uniquify the name on download
607 // start, and at that time the first file does not exists yet, so the second
608 // file gets the same name.
[email protected]5a2388a2010-03-26 16:13:39609 uniquifier = download_util::GetUniquePathNumber(new_path);
[email protected]7a256ea2008-10-17 17:34:16610 if (uniquifier > 0)
[email protected]5a2388a2010-03-26 16:13:39611 download_util::AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32612 success = file_util::Move(path, new_path);
613 } else {
614 NOTREACHED();
615 }
[email protected]6cade212008-12-03 00:32:22616
[email protected]ca4b5fa32010-10-09 12:42:18617 BrowserThread::PostTask(
618 BrowserThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32619 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16620 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32621}
622
623// Call from the file thread when the finished dangerous download was renamed.
624void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
625 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41626 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16627 int new_path_uniquifier) {
[email protected]da6e3922010-11-24 21:45:50628 VLOG(20) << __FUNCTION__ << "()" << " download_handle = " << download_handle
629 << " success = " << success
630 << " new_path = \"" << new_path.value() << "\""
631 << " new_path_uniquifier = " << new_path_uniquifier;
[email protected]f04182f32010-12-10 19:12:07632 DownloadMap::iterator it = history_downloads_.find(download_handle);
633 if (it == history_downloads_.end()) {
[email protected]9ccbb372008-10-10 18:50:32634 NOTREACHED();
635 return;
636 }
637
638 DownloadItem* download = it->second;
639 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16640 if (success) {
641 // We need to update the path uniquifier so that the UI shows the right
[email protected]44b94b82010-11-08 20:49:18642 // name when calling GetFileNameToReportUser().
[email protected]7a256ea2008-10-17 17:34:16643 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32644 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16645 }
[email protected]9ccbb372008-10-10 18:50:32646
647 // Continue the download finished sequence.
[email protected]f04182f32010-12-10 19:12:07648 download->Finished();
initial.commit09911bf2008-07-26 23:55:29649}
650
initial.commit09911bf2008-07-26 23:55:29651void DownloadManager::DownloadCancelled(int32 download_id) {
652 DownloadMap::iterator it = in_progress_.find(download_id);
653 if (it == in_progress_.end())
654 return;
655 DownloadItem* download = it->second;
656
[email protected]da6e3922010-11-24 21:45:50657 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
658 << " download = " << download->DebugString(true);
659
initial.commit09911bf2008-07-26 23:55:29660 // Clean up will happen when the history system create callback runs if we
661 // don't have a valid db_handle yet.
[email protected]82f37b02010-07-29 22:04:57662 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
initial.commit09911bf2008-07-26 23:55:29663 in_progress_.erase(it);
[email protected]82f37b02010-07-29 22:04:57664 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29665 }
666
[email protected]d7d1c5c2009-08-05 23:52:50667 DownloadCancelledInternal(download_id,
668 download->render_process_id(),
669 download->request_id());
[email protected]6a7fb042010-02-01 16:30:47670 UpdateAppIcon();
[email protected]d7d1c5c2009-08-05 23:52:50671}
672
673void DownloadManager::DownloadCancelledInternal(int download_id,
674 int render_process_id,
675 int request_id) {
[email protected]d85cf072009-10-27 03:59:31676 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
[email protected]ca4b5fa32010-10-09 12:42:18677 BrowserThread::PostTask(
678 BrowserThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26679 NewRunnableFunction(&download_util::CancelDownloadRequest,
[email protected]d85cf072009-10-27 03:59:31680 g_browser_process->resource_dispatcher_host(),
681 render_process_id,
682 request_id));
[email protected]d7d1c5c2009-08-05 23:52:50683
[email protected]ca4b5fa32010-10-09 12:42:18684 BrowserThread::PostTask(
685 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37686 NewRunnableMethod(
687 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29688}
689
690void DownloadManager::PauseDownload(int32 download_id, bool pause) {
691 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:31692 if (it == in_progress_.end())
693 return;
initial.commit09911bf2008-07-26 23:55:29694
[email protected]d85cf072009-10-27 03:59:31695 DownloadItem* download = it->second;
696 if (pause == download->is_paused())
697 return;
initial.commit09911bf2008-07-26 23:55:29698
[email protected]ca4b5fa32010-10-09 12:42:18699 BrowserThread::PostTask(
700 BrowserThread::IO, FROM_HERE,
[email protected]e2abdeb22010-09-03 19:56:15701 NewRunnableMethod(this,
702 &DownloadManager::PauseDownloadRequest,
703 g_browser_process->resource_dispatcher_host(),
[email protected]7ba53e12010-08-05 17:14:00704 download->render_process_id(),
705 download->request_id(),
706 pause));
[email protected]9ccbb372008-10-10 18:50:32707}
708
[email protected]6a7fb042010-02-01 16:30:47709void DownloadManager::UpdateAppIcon() {
[email protected]073ed7b2010-09-27 09:20:02710 if (status_updater_)
711 status_updater_->Update();
[email protected]6a7fb042010-02-01 16:30:47712}
713
[email protected]9ccbb372008-10-10 18:50:32714void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41715 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32716 download->Rename(new_path);
[email protected]82f37b02010-07-29 22:04:57717 download_history_->UpdateDownloadPath(download, new_path);
[email protected]9ccbb372008-10-10 18:50:32718}
719
[email protected]e2abdeb22010-09-03 19:56:15720void DownloadManager::PauseDownloadRequest(ResourceDispatcherHost* rdh,
721 int render_process_id,
722 int request_id,
723 bool pause) {
[email protected]ca4b5fa32010-10-09 12:42:18724 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
[email protected]e2abdeb22010-09-03 19:56:15725 rdh->PauseRequest(render_process_id, request_id, pause);
726}
727
initial.commit09911bf2008-07-26 23:55:29728void DownloadManager::RemoveDownload(int64 download_handle) {
[email protected]f04182f32010-12-10 19:12:07729 DownloadMap::iterator it = history_downloads_.find(download_handle);
730 if (it == history_downloads_.end())
initial.commit09911bf2008-07-26 23:55:29731 return;
732
733 // Make history update.
734 DownloadItem* download = it->second;
[email protected]82f37b02010-07-29 22:04:57735 download_history_->RemoveEntry(download);
initial.commit09911bf2008-07-26 23:55:29736
737 // Remove from our tables and delete.
[email protected]f04182f32010-12-10 19:12:07738 history_downloads_.erase(it);
739 int downloads_count = downloads_.erase(download);
740 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29741
742 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:28743 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:36744
745 delete download;
initial.commit09911bf2008-07-26 23:55:29746}
747
[email protected]e93d2822009-01-30 05:59:59748int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
749 const base::Time remove_end) {
[email protected]82f37b02010-07-29 22:04:57750 download_history_->RemoveEntriesBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29751
[email protected]a312a442010-12-15 23:40:33752 // All downloads visible to the user will be in the history,
753 // so scan that map.
[email protected]f04182f32010-12-10 19:12:07754 DownloadMap::iterator it = history_downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:28755 std::vector<DownloadItem*> pending_deletes;
[email protected]f04182f32010-12-10 19:12:07756 while (it != history_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29757 DownloadItem* download = it->second;
758 DownloadItem::DownloadState state = download->state();
759 if (download->start_time() >= remove_begin &&
760 (remove_end.is_null() || download->start_time() < remove_end) &&
761 (state == DownloadItem::COMPLETE ||
762 state == DownloadItem::CANCELLED)) {
763 // Remove from the map and move to the next in the list.
[email protected]f04182f32010-12-10 19:12:07764 history_downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:58765
766 // Also remove it from any completed dangerous downloads.
[email protected]78b8fcc92009-03-31 17:36:28767 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29768
initial.commit09911bf2008-07-26 23:55:29769 continue;
770 }
771
772 ++it;
773 }
774
[email protected]a312a442010-12-15 23:40:33775 // If we aren't deleting anything, we're done.
[email protected]57fd1252010-12-23 17:24:09776 if (pending_deletes.empty())
777 return 0;
initial.commit09911bf2008-07-26 23:55:29778
[email protected]a312a442010-12-15 23:40:33779 // Remove the chosen downloads from the main owning container.
780 for (std::vector<DownloadItem*>::iterator it = pending_deletes.begin();
781 it != pending_deletes.end(); it++) {
782 downloads_.erase(*it);
783 }
784
785 // Tell observers to refresh their views.
786 NotifyModelChanged();
787
788 // Delete the download items themselves.
[email protected]57fd1252010-12-23 17:24:09789 int num_deleted = static_cast<int>(pending_deletes.size());
790
[email protected]78b8fcc92009-03-31 17:36:28791 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
792 pending_deletes.clear();
793
initial.commit09911bf2008-07-26 23:55:29794 return num_deleted;
795}
796
[email protected]e93d2822009-01-30 05:59:59797int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
798 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29799}
800
[email protected]d41355e6f2009-04-07 21:21:12801int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:46802 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
803 // This is an incognito downloader. Clear All should clear main download
804 // manager as well.
805 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
806 }
[email protected]d41355e6f2009-04-07 21:21:12807 // The null times make the date range unbounded.
808 return RemoveDownloadsBetween(base::Time(), base::Time());
809}
810
[email protected]ec4826a2010-09-21 09:15:59811void DownloadManager::SavePageAsDownloadStarted(DownloadItem* download_item) {
[email protected]57fd1252010-12-23 17:24:09812#if !defined(NDEBUG)
813 save_page_as_downloads_.insert(download_item);
814#endif
[email protected]f04182f32010-12-10 19:12:07815 downloads_.insert(download_item);
[email protected]ec4826a2010-09-21 09:15:59816}
817
initial.commit09911bf2008-07-26 23:55:29818// Initiate a download of a specific URL. We send the request to the
819// ResourceDispatcherHost, and let it send us responses like a regular
820// download.
821void DownloadManager::DownloadUrl(const GURL& url,
822 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50823 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34824 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26825 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
826 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58827}
828
829void DownloadManager::DownloadUrlToFile(const GURL& url,
830 const GURL& referrer,
831 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32832 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58833 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34834 DCHECK(tab_contents);
[email protected]ca4b5fa32010-10-09 12:42:18835 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26836 NewRunnableFunction(&download_util::DownloadUrl,
837 url,
838 referrer,
839 referrer_charset,
840 save_info,
841 g_browser_process->resource_dispatcher_host(),
842 tab_contents->GetRenderProcessHost()->id(),
843 tab_contents->render_view_host()->routing_id(),
844 request_context_getter_));
initial.commit09911bf2008-07-26 23:55:29845}
846
initial.commit09911bf2008-07-26 23:55:29847void DownloadManager::AddObserver(Observer* observer) {
848 observers_.AddObserver(observer);
849 observer->ModelChanged();
850}
851
852void DownloadManager::RemoveObserver(Observer* observer) {
853 observers_.RemoveObserver(observer);
854}
855
[email protected]eccb9d12009-10-28 05:40:09856bool DownloadManager::ShouldOpenFileBasedOnExtension(
857 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:09858 FilePath::StringType extension = path.Extension();
859 if (extension.empty())
860 return false;
[email protected]cd448092010-12-06 23:49:13861 if (!download_util::IsFileExtensionSafe(extension))
[email protected]eccb9d12009-10-28 05:40:09862 return false;
[email protected]92e11c82010-01-13 06:39:56863 if (Extension::IsExtension(path))
864 return false;
[email protected]eccb9d12009-10-28 05:40:09865 DCHECK(extension[0] == FilePath::kExtensionSeparator);
866 extension.erase(0, 1);
[email protected]e5dc4222010-08-30 22:16:32867 return download_prefs_->IsAutoOpenEnabledForExtension(extension);
initial.commit09911bf2008-07-26 23:55:29868}
869
[email protected]073ed7b2010-09-27 09:20:02870bool DownloadManager::IsDownloadProgressKnown() {
871 for (DownloadMap::iterator i = in_progress_.begin();
872 i != in_progress_.end(); ++i) {
873 if (i->second->total_bytes() <= 0)
874 return false;
875 }
876
877 return true;
878}
879
880int64 DownloadManager::GetInProgressDownloadCount() {
881 return in_progress_.size();
882}
883
884int64 DownloadManager::GetReceivedDownloadBytes() {
885 DCHECK(IsDownloadProgressKnown());
886 int64 received_bytes = 0;
887 for (DownloadMap::iterator i = in_progress_.begin();
888 i != in_progress_.end(); ++i) {
889 received_bytes += i->second->received_bytes();
890 }
891 return received_bytes;
892}
893
894int64 DownloadManager::GetTotalDownloadBytes() {
895 DCHECK(IsDownloadProgressKnown());
896 int64 total_bytes = 0;
897 for (DownloadMap::iterator i = in_progress_.begin();
898 i != in_progress_.end(); ++i) {
899 total_bytes += i->second->total_bytes();
900 }
901 return total_bytes;
902}
903
[email protected]561abe62009-04-06 18:08:34904void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:36905 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:29906 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]e6875c12010-07-18 11:14:13907 if (info->prompt_user_for_save_location)
[email protected]7ae7c2cb2009-01-06 23:31:41908 last_download_path_ = path.DirName();
[email protected]c2e76012010-12-23 21:10:29909 AttachDownloadItem(info, path);
initial.commit09911bf2008-07-26 23:55:29910}
911
912void DownloadManager::FileSelectionCanceled(void* params) {
913 // The user didn't pick a place to save the file, so need to cancel the
914 // download that's already in progress to the temporary location.
915 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:50916 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:45917 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:50918 info->request_id);
initial.commit09911bf2008-07-26 23:55:29919}
920
[email protected]9ccbb372008-10-10 18:50:32921void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
922 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
923 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
924 download->UpdateObservers();
925
926 // If the download is not complete, nothing to do. The required
927 // post-processing will be performed when it does complete.
928 if (download->state() != DownloadItem::COMPLETE)
929 return;
930
[email protected]ca4b5fa32010-10-09 12:42:18931 BrowserThread::PostTask(
932 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37933 NewRunnableMethod(
934 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
935 download->db_handle(), download->full_path(),
[email protected]44b94b82010-11-08 20:49:18936 download->target_name()));
[email protected]9ccbb372008-10-10 18:50:32937}
938
initial.commit09911bf2008-07-26 23:55:29939// Operations posted to us from the history service ----------------------------
940
941// The history service has retrieved all download entries. 'entries' contains
942// 'DownloadCreateInfo's in sorted order (by ascending start_time).
943void DownloadManager::OnQueryDownloadEntriesComplete(
944 std::vector<DownloadCreateInfo>* entries) {
945 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:39946 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]f04182f32010-12-10 19:12:07947 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
948 downloads_.insert(download);
949 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:50950 VLOG(20) << __FUNCTION__ << "()" << i << ">"
951 << " download = " << download->DebugString(true);
initial.commit09911bf2008-07-26 23:55:29952 }
[email protected]b0ab1d42010-02-24 19:29:28953 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:29954}
955
initial.commit09911bf2008-07-26 23:55:29956// Once the new DownloadItem's creation info has been committed to the history
957// service, we associate the DownloadItem with the db handle, update our
[email protected]f04182f32010-12-10 19:12:07958// 'history_downloads_' map and inform observers.
[email protected]9f5cb562010-11-08 22:06:59959void DownloadManager::OnCreateDownloadEntryComplete(
[email protected]76d8b622010-11-11 19:50:05960 DownloadCreateInfo info,
[email protected]9f5cb562010-11-08 22:06:59961 int64 db_handle) {
initial.commit09911bf2008-07-26 23:55:29962 DownloadMap::iterator it = in_progress_.find(info.download_id);
963 DCHECK(it != in_progress_.end());
964
965 DownloadItem* download = it->second;
[email protected]da6e3922010-11-24 21:45:50966 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
967 << " download_id = " << info.download_id
968 << " download = " << download->DebugString(true);
[email protected]d2a8fb72010-01-21 05:31:42969
970 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
971 // call this function with an invalid |db_handle|. For instance, this can
972 // happen when the history database is offline. We cannot have multiple
973 // DownloadItems with the same invalid db_handle, so we need to assign a
974 // unique |db_handle| here.
[email protected]82f37b02010-07-29 22:04:57975 if (db_handle == DownloadHistory::kUninitializedHandle)
976 db_handle = download_history_->GetNextFakeDbHandle();
[email protected]d2a8fb72010-01-21 05:31:42977
[email protected]82f37b02010-07-29 22:04:57978 DCHECK(download->db_handle() == DownloadHistory::kUninitializedHandle);
initial.commit09911bf2008-07-26 23:55:29979 download->set_db_handle(db_handle);
980
981 // Insert into our full map.
[email protected]f04182f32010-12-10 19:12:07982 DCHECK(history_downloads_.find(download->db_handle()) ==
983 history_downloads_.end());
984 history_downloads_[download->db_handle()] = download;
initial.commit09911bf2008-07-26 23:55:29985
[email protected]5e595482009-05-06 20:16:53986 // Show in the appropropriate browser UI.
987 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:29988
989 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:28990 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:29991
992 // If this download has been completed before we've received the db handle,
993 // post one final message to the history service so that it can be properly
994 // in sync with the DownloadItem's completion status, and also inform any
995 // observers so that they get more than just the start notification.
996 if (download->state() != DownloadItem::IN_PROGRESS) {
997 in_progress_.erase(it);
[email protected]82f37b02010-07-29 22:04:57998 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29999 download->UpdateObservers();
1000 }
[email protected]6a7fb042010-02-01 16:30:471001
1002 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:291003}
1004
[email protected]5e595482009-05-06 20:16:531005void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1006 DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341007 // The 'contents' may no longer exist if the user closed the tab before we
1008 // get this start completion event. If it does, tell the origin TabContents
1009 // to display its download shelf.
[email protected]76543b92009-08-31 17:27:451010 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1011 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531012
1013 // If the contents no longer exists, we start the download in the last active
1014 // browser. This is not ideal but better than fully hiding the download from
1015 // the user.
1016 if (!contents) {
1017 Browser* last_active = BrowserList::GetLastActive();
1018 if (last_active)
1019 contents = last_active->GetSelectedTabContents();
1020 }
1021
1022 if (contents)
1023 contents->OnStartDownload(download);
1024}
1025
[email protected]6cade212008-12-03 00:32:221026// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121027void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411028 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381029}
[email protected]b0ab1d42010-02-24 19:29:281030
1031void DownloadManager::NotifyModelChanged() {
1032 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1033}
1034
[email protected]2e030682010-07-23 19:45:361035DownloadItem* DownloadManager::GetDownloadItem(int id) {
[email protected]f04182f32010-12-10 19:12:071036 for (DownloadMap::iterator it = history_downloads_.begin();
1037 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:361038 DownloadItem* item = it->second;
1039 if (item->id() == id)
1040 return item;
1041 }
1042 return NULL;
1043}
1044
[email protected]57fd1252010-12-23 17:24:091045// Confirm that everything in all maps is also in |downloads_|, and that
1046// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:071047void DownloadManager::AssertContainersConsistent() const {
1048#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:091049 // Turn everything into sets.
1050 DownloadSet in_progress_set, history_set;
1051 const DownloadMap* input_maps[] = {&in_progress_, &history_downloads_};
1052 DownloadSet* local_sets[] = {&in_progress_set, &history_set};
1053 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(local_sets));
1054 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
1055 for (DownloadMap::const_iterator it = input_maps[i]->begin();
1056 it != input_maps[i]->end(); it++) {
1057 local_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:071058 }
1059 }
[email protected]57fd1252010-12-23 17:24:091060
1061 // Check if each set is fully present in downloads, and create a union.
1062 const DownloadSet* all_sets[] = {&in_progress_set, &history_set,
1063 &save_page_as_downloads_};
1064 DownloadSet downloads_union;
1065 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
1066 DownloadSet remainder;
1067 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
1068 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
1069 downloads_.begin(), downloads_.end(),
1070 insert_it);
1071 DCHECK(remainder.empty());
1072 std::insert_iterator<DownloadSet>
1073 insert_union(downloads_union, downloads_union.end());
1074 std::set_union(downloads_union.begin(), downloads_union.end(),
1075 all_sets[i]->begin(), all_sets[i]->end(),
1076 insert_union);
1077 }
1078
1079 // Is everything in downloads_ present in one of the other sets?
1080 DownloadSet remainder;
1081 std::insert_iterator<DownloadSet>
1082 insert_remainder(remainder, remainder.begin());
1083 std::set_difference(downloads_.begin(), downloads_.end(),
1084 downloads_union.begin(), downloads_union.end(),
1085 insert_remainder);
1086 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071087#endif
1088}
1089
[email protected]b0ab1d42010-02-24 19:29:281090// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1091
1092DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1093 DownloadManager* observing_download_manager)
1094 : observing_download_manager_(observing_download_manager),
1095 observed_download_manager_(NULL) {
1096 if (observing_download_manager->profile_->GetOriginalProfile() ==
1097 observing_download_manager->profile_) {
1098 return;
1099 }
1100
1101 observed_download_manager_ = observing_download_manager_->
1102 profile_->GetOriginalProfile()->GetDownloadManager();
1103 observed_download_manager_->AddObserver(this);
1104}
1105
1106DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1107 if (observed_download_manager_)
1108 observed_download_manager_->RemoveObserver(this);
1109}
1110
1111void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1112 observing_download_manager_->NotifyModelChanged();
1113}
1114
[email protected]b0ab1d42010-02-24 19:29:281115void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1116 observed_download_manager_ = NULL;
1117}