blob: 9b2d4b59bc091a8a62ba412b172f8a3e1b602c2d [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]1b5044d2009-02-24 00:04:1414#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2915#include "base/task.h"
[email protected]ce7f62e32010-08-10 23:43:5916#include "base/utf_string_conversions.h"
[email protected]d2a8fb72010-01-21 05:31:4217#include "build/build_config.h"
[email protected]6c69796d2010-07-16 21:41:1618#include "chrome/browser/browser.h"
initial.commit09911bf2008-07-26 23:55:2919#include "chrome/browser/browser_list.h"
20#include "chrome/browser/browser_process.h"
[email protected]d83d03aa2009-11-02 21:44:3721#include "chrome/browser/chrome_thread.h"
[email protected]6c69796d2010-07-16 21:41:1622#include "chrome/browser/download/download_file_manager.h"
[email protected]82f37b02010-07-29 22:04:5723#include "chrome/browser/download/download_history.h"
[email protected]6c69796d2010-07-16 21:41:1624#include "chrome/browser/download/download_item.h"
[email protected]e9ef0a62009-08-11 22:50:1325#include "chrome/browser/download/download_util.h"
[email protected]8f783752009-04-01 23:33:4526#include "chrome/browser/extensions/extensions_service.h"
[email protected]6c69796d2010-07-16 21:41:1627#include "chrome/browser/history/download_types.h"
[email protected]be180c802009-10-23 06:33:3128#include "chrome/browser/net/chrome_url_request_context.h"
[email protected]14a000d2010-04-29 21:44:2429#include "chrome/browser/platform_util.h"
initial.commit09911bf2008-07-26 23:55:2930#include "chrome/browser/profile.h"
[email protected]8c8657d62009-01-16 18:31:2631#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2532#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]21ca982c2010-01-26 22:49:5533#include "chrome/browser/tab_contents/infobar_delegate.h"
[email protected]57c6a652009-05-04 07:58:3434#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]d2a8fb72010-01-21 05:31:4235#include "chrome/browser/tab_contents/tab_util.h"
initial.commit09911bf2008-07-26 23:55:2936#include "chrome/common/chrome_paths.h"
[email protected]91e1bd82009-09-03 22:04:4037#include "chrome/common/notification_service.h"
38#include "chrome/common/notification_type.h"
initial.commit09911bf2008-07-26 23:55:2939#include "chrome/common/pref_names.h"
[email protected]46072d42008-07-28 14:49:3540#include "googleurl/src/gurl.h"
[email protected]34ac8f32009-02-22 23:03:2741#include "grit/generated_resources.h"
[email protected]21ca982c2010-01-26 22:49:5542#include "grit/theme_resources.h"
initial.commit09911bf2008-07-26 23:55:2943#include "net/base/mime_util.h"
44#include "net/base/net_util.h"
initial.commit09911bf2008-07-26 23:55:2945
[email protected]b7f05882009-02-22 01:21:5646#if defined(OS_WIN)
[email protected]4a0765a2009-05-08 23:12:2547#include "app/win_util.h"
[email protected]a0a9577b2009-05-27 23:52:3248#endif
49
[email protected]21ca982c2010-01-26 22:49:5550namespace {
51
[email protected]b0ab1d42010-02-24 19:29:2852// Used to sort download items based on descending start time.
53bool CompareStartTime(DownloadItem* first, DownloadItem* second) {
54 return first->start_time() > second->start_time();
55}
56
[email protected]21ca982c2010-01-26 22:49:5557} // namespace
58
initial.commit09911bf2008-07-26 23:55:2959// static
60void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
61 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
[email protected]20ce516d2010-06-18 02:20:0462 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, "");
[email protected]f052118e2008-09-05 02:25:3263 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
64
65 // The default download path is userprofile\download.
[email protected]290c9702010-03-09 04:01:3666 const FilePath& default_download_path =
67 download_util::GetDefaultDownloadDirectory();
[email protected]b9636002009-03-04 00:05:2568 prefs->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
69 default_download_path);
[email protected]80dc3612010-07-27 19:35:0870#if defined(OS_CHROMEOS)
71 // Ensure that the download directory specified in the preferences exists.
72 ChromeThread::PostTask(
73 ChromeThread::FILE, FROM_HERE,
74 NewRunnableFunction(&file_util::CreateDirectory, default_download_path));
75#endif
[email protected]f052118e2008-09-05 02:25:3276
77 // If the download path is dangerous we forcefully reset it. But if we do
78 // so we set a flag to make sure we only do it once, to avoid fighting
79 // the user if he really wants it on an unsafe place such as the desktop.
80
81 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
[email protected]38233e62010-04-26 04:43:3682 FilePath current_download_dir = prefs->GetFilePath(
83 prefs::kDownloadDefaultDirectory);
[email protected]290c9702010-03-09 04:01:3684 if (download_util::DownloadPathIsDangerous(current_download_dir)) {
[email protected]38233e62010-04-26 04:43:3685 prefs->SetFilePath(prefs::kDownloadDefaultDirectory,
86 default_download_path);
[email protected]f052118e2008-09-05 02:25:3287 }
88 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
89 }
initial.commit09911bf2008-07-26 23:55:2990}
91
92DownloadManager::DownloadManager()
93 : shutdown_needed_(false),
94 profile_(NULL),
[email protected]82f37b02010-07-29 22:04:5795 file_manager_(NULL) {
initial.commit09911bf2008-07-26 23:55:2996}
97
98DownloadManager::~DownloadManager() {
[email protected]b0ab1d42010-02-24 19:29:2899 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
100
initial.commit09911bf2008-07-26 23:55:29101 if (shutdown_needed_)
102 Shutdown();
103}
104
105void DownloadManager::Shutdown() {
106 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
107
108 // Stop receiving download updates
[email protected]2941c2392010-07-15 22:54:30109 if (file_manager_)
110 file_manager_->RemoveDownloadManager(this);
initial.commit09911bf2008-07-26 23:55:29111
initial.commit09911bf2008-07-26 23:55:29112 // 'in_progress_' may contain DownloadItems that have not finished the start
113 // complete (from the history service) and thus aren't in downloads_.
114 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32115 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29116 for (; it != in_progress_.end(); ++it) {
117 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32118 if (download->safety_state() == DownloadItem::DANGEROUS) {
119 // Forget about any download that the user did not approve.
120 // Note that we cannot call download->Remove() this would invalidate our
121 // iterator.
122 to_remove.insert(download);
123 continue;
initial.commit09911bf2008-07-26 23:55:29124 }
[email protected]9ccbb372008-10-10 18:50:32125 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
126 download->Cancel(false);
[email protected]82f37b02010-07-29 22:04:57127 download_history_->UpdateEntry(download);
128 if (download->db_handle() == DownloadHistory::kUninitializedHandle) {
initial.commit09911bf2008-07-26 23:55:29129 // An invalid handle means that 'download' does not yet exist in
130 // 'downloads_', so we have to delete it here.
131 delete download;
132 }
133 }
134
[email protected]9ccbb372008-10-10 18:50:32135 // 'dangerous_finished_' contains all complete downloads that have not been
136 // approved. They should be removed.
137 it = dangerous_finished_.begin();
138 for (; it != dangerous_finished_.end(); ++it)
139 to_remove.insert(it->second);
140
141 // Remove the dangerous download that are not approved.
142 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
143 rm_it != to_remove.end(); ++rm_it) {
144 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32145 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32146 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32147 // Same as above, delete the download if it is not in 'downloads_' (as the
148 // Remove() call above won't have deleted it).
[email protected]82f37b02010-07-29 22:04:57149 if (handle == DownloadHistory::kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32150 delete download;
151 }
152 to_remove.clear();
153
initial.commit09911bf2008-07-26 23:55:29154 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32155 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29156 STLDeleteValues(&downloads_);
157
158 file_manager_ = NULL;
159
160 // Save our file extensions to auto open.
161 SaveAutoOpens();
162
163 // Make sure the save as dialog doesn't notify us back if we're gone before
164 // it returns.
165 if (select_file_dialog_.get())
166 select_file_dialog_->ListenerDestroyed();
167
[email protected]82f37b02010-07-29 22:04:57168 download_history_.reset();
169
initial.commit09911bf2008-07-26 23:55:29170 shutdown_needed_ = false;
171}
172
[email protected]82f37b02010-07-29 22:04:57173void DownloadManager::GetTemporaryDownloads(
174 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
175 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58176
177 for (DownloadMap::iterator it = downloads_.begin();
178 it != downloads_.end(); ++it) {
179 if (it->second->is_temporary() &&
180 it->second->full_path().DirName() == dir_path)
[email protected]82f37b02010-07-29 22:04:57181 result->push_back(it->second);
[email protected]6aa4a1c02010-01-15 18:49:58182 }
[email protected]6aa4a1c02010-01-15 18:49:58183}
184
[email protected]82f37b02010-07-29 22:04:57185void DownloadManager::GetAllDownloads(
186 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
187 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34188
189 for (DownloadMap::iterator it = downloads_.begin();
190 it != downloads_.end(); ++it) {
191 if (!it->second->is_temporary() &&
192 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57193 result->push_back(it->second);
[email protected]8ddbd66a2010-05-21 16:38:34194 }
[email protected]8ddbd66a2010-05-21 16:38:34195}
196
[email protected]82f37b02010-07-29 22:04:57197void DownloadManager::GetCurrentDownloads(
198 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
199 DCHECK(result);
[email protected]c4a530b2010-03-08 17:33:03200
201 for (DownloadMap::iterator it = downloads_.begin();
202 it != downloads_.end(); ++it) {
203 if (!it->second->is_temporary() &&
204 (it->second->state() == DownloadItem::IN_PROGRESS ||
205 it->second->safety_state() == DownloadItem::DANGEROUS) &&
206 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57207 result->push_back(it->second);
[email protected]c4a530b2010-03-08 17:33:03208 }
[email protected]c4a530b2010-03-08 17:33:03209}
210
[email protected]d3b12902010-08-16 23:39:42211void DownloadManager::SearchDownloads(const string16& query,
212 std::vector<DownloadItem*>* result) {
213 DCHECK(result);
214
215 string16 query_lower(l10n_util::ToLower(query));
216
217 for (DownloadMap::iterator it = downloads_.begin();
218 it != downloads_.end(); ++it) {
219 DownloadItem* download_item = it->second;
220
221 if (download_item->is_temporary() || download_item->is_extension_install())
222 continue;
223
224 // Display Incognito downloads only in Incognito window, and vice versa.
225 // The Incognito Downloads page will get the list of non-Incognito downloads
226 // from its parent profile.
227 if (profile_->IsOffTheRecord() != download_item->is_otr())
228 continue;
229
230 if (download_item->MatchesQuery(query_lower))
231 result->push_back(download_item);
232 }
233
234 // If we have a parent profile, let it add its downloads to the results.
235 Profile* original_profile = profile_->GetOriginalProfile();
236 if (original_profile != profile_)
237 original_profile->GetDownloadManager()->SearchDownloads(query, result);
238}
239
initial.commit09911bf2008-07-26 23:55:29240// Query the history service for information about all persisted downloads.
241bool DownloadManager::Init(Profile* profile) {
242 DCHECK(profile);
243 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
244 shutdown_needed_ = true;
245
246 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31247 request_context_getter_ = profile_->GetRequestContext();
[email protected]d3b12902010-08-16 23:39:42248 download_history_.reset(new DownloadHistory(profile));
[email protected]82f37b02010-07-29 22:04:57249 download_history_->Load(
250 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
[email protected]024f2f02010-04-30 22:51:46251
[email protected]2941c2392010-07-15 22:54:30252 // In test mode, there may be no ResourceDispatcherHost. In this case it's
253 // safe to avoid setting |file_manager_| because we only call a small set of
254 // functions, none of which need it.
initial.commit09911bf2008-07-26 23:55:29255 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]2941c2392010-07-15 22:54:30256 if (rdh) {
257 file_manager_ = rdh->download_file_manager();
258 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29259 }
260
initial.commit09911bf2008-07-26 23:55:29261 // Get our user preference state.
262 PrefService* prefs = profile_->GetPrefs();
263 DCHECK(prefs);
264 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
265
initial.commit09911bf2008-07-26 23:55:29266 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
[email protected]bb69e9b32008-08-14 23:08:14267 // Ensure that the download directory specified in the preferences exists.
[email protected]d83d03aa2009-11-02 21:44:37268 ChromeThread::PostTask(
269 ChromeThread::FILE, FROM_HERE,
[email protected]309b7642009-12-09 03:08:50270 NewRunnableFunction(&file_util::CreateDirectory, download_path()));
initial.commit09911bf2008-07-26 23:55:29271
[email protected]2b2f8f72009-02-24 22:42:05272 // We store any file extension that should be opened automatically at
273 // download completion in this pref.
[email protected]ddd231e2010-06-29 20:35:19274 std::string extensions_to_open =
initial.commit09911bf2008-07-26 23:55:29275 prefs->GetString(prefs::kDownloadExtensionsToOpen);
[email protected]ddd231e2010-06-29 20:35:19276 std::vector<std::string> extensions;
277 SplitString(extensions_to_open, ':', &extensions);
278
initial.commit09911bf2008-07-26 23:55:29279 for (size_t i = 0; i < extensions.size(); ++i) {
[email protected]ddd231e2010-06-29 20:35:19280#if defined(OS_POSIX)
281 FilePath path(extensions[i]);
282#elif defined(OS_WIN)
283 FilePath path(UTF8ToWide(extensions[i]));
284#endif
285 if (!extensions[i].empty() && !IsExecutableFile(path))
286 auto_open_.insert(path.value());
initial.commit09911bf2008-07-26 23:55:29287 }
288
[email protected]b0ab1d42010-02-24 19:29:28289 other_download_manager_observer_.reset(
290 new OtherDownloadManagerObserver(this));
291
initial.commit09911bf2008-07-26 23:55:29292 return true;
293}
294
initial.commit09911bf2008-07-26 23:55:29295// We have received a message from DownloadFileManager about a new download. We
296// create a download item and store it in our download map, and inform the
297// history system of a new download. Since this method can be called while the
298// history service thread is still reading the persistent state, we do not
299// insert the new DownloadItem into 'downloads_' or inform our observers at this
300// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
301// download creation as a callback from the history thread.
302void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37303 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29304 DCHECK(info);
305
[email protected]a60c8ae2009-12-25 06:50:57306 // Check whether this download is for an extension install or not.
[email protected]e6875c12010-07-18 11:14:13307 // Allow extensions to be explicitly saved.
308 if (!info->prompt_user_for_save_location) {
[email protected]a60c8ae2009-12-25 06:50:57309 if (UserScript::HasUserScriptFileExtension(info->url) ||
310 info->mime_type == Extension::kMimeType)
311 info->is_extension_install = true;
312 }
313
[email protected]8af9d032010-02-10 00:00:32314 if (info->save_info.file_path.empty()) {
[email protected]2941c2392010-07-15 22:54:30315 FilePath generated_name;
[email protected]7ba53e12010-08-05 17:14:00316 download_util::GenerateFileNameFromInfo(info, &generated_name);
[email protected]2941c2392010-07-15 22:54:30317
318 // Freeze the user's preference for showing a Save As dialog. We're going
319 // to bounce around a bunch of threads and we don't want to worry about race
320 // conditions where the user changes this pref out from under us.
321 if (*prompt_for_download_) {
322 // But ignore the user's preference for the following scenarios:
323 // 1) Extension installation. Note that we only care here about the case
324 // where an extension is installed, not when one is downloaded with
325 // "save as...".
326 // 2) Filetypes marked "always open." If the user just wants this file
327 // opened, don't bother asking where to keep it.
328 if (!info->is_extension_install &&
329 !ShouldOpenFileBasedOnExtension(generated_name))
[email protected]e6875c12010-07-18 11:14:13330 info->prompt_user_for_save_location = true;
[email protected]2941c2392010-07-15 22:54:30331 }
332
[email protected]8af9d032010-02-10 00:00:32333 // Determine the proper path for a download, by either one of the following:
334 // 1) using the default download directory.
335 // 2) prompting the user.
[email protected]80dc3612010-07-27 19:35:08336 if (info->prompt_user_for_save_location && !last_download_path_.empty()){
[email protected]8af9d032010-02-10 00:00:32337 info->suggested_path = last_download_path_;
[email protected]80dc3612010-07-27 19:35:08338 } else {
[email protected]8af9d032010-02-10 00:00:32339 info->suggested_path = download_path();
[email protected]80dc3612010-07-27 19:35:08340 }
[email protected]8af9d032010-02-10 00:00:32341 info->suggested_path = info->suggested_path.Append(generated_name);
342 } else {
343 info->suggested_path = info->save_info.file_path;
344 }
initial.commit09911bf2008-07-26 23:55:29345
[email protected]e6875c12010-07-18 11:14:13346 if (!info->prompt_user_for_save_location &&
347 info->save_info.file_path.empty()) {
[email protected]4289d9b2009-07-25 21:17:34348 // Downloads can be marked as dangerous for two reasons:
349 // a) They have a dangerous-looking filename
350 // b) They are an extension that is not from the gallery
[email protected]7ba53e12010-08-05 17:14:00351 if (IsExecutableFile(info->suggested_path.BaseName()))
[email protected]4289d9b2009-07-25 21:17:34352 info->is_dangerous = true;
[email protected]a60c8ae2009-12-25 06:50:57353 else if (info->is_extension_install &&
[email protected]b7c2f252009-12-08 00:47:23354 !ExtensionsService::IsDownloadFromGallery(info->url,
355 info->referrer_url)) {
[email protected]4289d9b2009-07-25 21:17:34356 info->is_dangerous = true;
357 }
[email protected]e9ebf3fc2008-10-17 22:06:58358 }
359
initial.commit09911bf2008-07-26 23:55:29360 // We need to move over to the download thread because we don't want to stat
361 // the suggested path on the UI thread.
[email protected]d83d03aa2009-11-02 21:44:37362 ChromeThread::PostTask(
363 ChromeThread::FILE, FROM_HERE,
364 NewRunnableMethod(
365 this, &DownloadManager::CheckIfSuggestedPathExists, info));
initial.commit09911bf2008-07-26 23:55:29366}
367
368void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
[email protected]aa033af2010-07-27 18:16:39369 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::FILE));
initial.commit09911bf2008-07-26 23:55:29370 DCHECK(info);
371
372 // Check writability of the suggested path. If we can't write to it, default
373 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41374 FilePath dir = info->suggested_path.DirName();
375 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32376 if (!file_util::PathIsWritable(dir)) {
[email protected]e6875c12010-07-18 11:14:13377 info->prompt_user_for_save_location = true;
initial.commit09911bf2008-07-26 23:55:29378 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41379 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29380 }
381
[email protected]6cade212008-12-03 00:32:22382 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58383 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41384 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32385 // Create a temporary file to hold the file until the user approves its
386 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41387 FilePath::StringType file_name;
388 FilePath path;
[email protected]9ccbb372008-10-10 18:50:32389 while (path.empty()) {
[email protected]594cd7d2010-07-21 03:23:56390 SStringPrintf(&file_name, FILE_PATH_LITERAL("unconfirmed %d.crdownload"),
[email protected]9ccbb372008-10-10 18:50:32391 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41392 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07393 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41394 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32395 }
396 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16397 } else {
[email protected]594cd7d2010-07-21 03:23:56398 // Do not add the path uniquifier if we are saving to a specific path as in
399 // the drag-out case.
400 if (info->save_info.file_path.empty()) {
401 info->path_uniquifier = download_util::GetUniquePathNumberWithCrDownload(
402 info->suggested_path);
403 }
[email protected]7a256ea2008-10-17 17:34:16404 // We know the final path, build it if necessary.
405 if (info->path_uniquifier > 0) {
[email protected]5a2388a2010-03-26 16:13:39406 download_util::AppendNumberToPath(&(info->suggested_path),
407 info->path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16408 // Setting path_uniquifier to 0 to make sure we don't try to unique it
409 // later on.
410 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07411 } else if (info->path_uniquifier == -1) {
412 // We failed to find a unique path. We have to prompt the user.
[email protected]e6875c12010-07-18 11:14:13413 info->prompt_user_for_save_location = true;
[email protected]7a256ea2008-10-17 17:34:16414 }
[email protected]9ccbb372008-10-10 18:50:32415 }
416
[email protected]594cd7d2010-07-21 03:23:56417 // Create an empty file at the suggested path so that we don't allocate the
418 // same "non-existant" path to multiple downloads.
419 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]e6875c12010-07-18 11:14:13420 if (!info->prompt_user_for_save_location &&
421 info->save_info.file_path.empty()) {
[email protected]594cd7d2010-07-21 03:23:56422 if (info->is_dangerous)
423 file_util::WriteFile(info->suggested_path, "", 0);
424 else
425 file_util::WriteFile(download_util::GetCrDownloadPath(
426 info->suggested_path), "", 0);
[email protected]7d3851d82008-12-12 03:26:07427 }
428
[email protected]d83d03aa2009-11-02 21:44:37429 ChromeThread::PostTask(
430 ChromeThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29431 NewRunnableMethod(this,
432 &DownloadManager::OnPathExistenceAvailable,
433 info));
434}
435
436void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]d83d03aa2009-11-02 21:44:37437 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
initial.commit09911bf2008-07-26 23:55:29438 DCHECK(info);
439
[email protected]e6875c12010-07-18 11:14:13440 if (info->prompt_user_for_save_location) {
initial.commit09911bf2008-07-26 23:55:29441 // We must ask the user for the place to put the download.
442 if (!select_file_dialog_.get())
443 select_file_dialog_ = SelectFileDialog::Create(this);
444
[email protected]76543b92009-08-31 17:27:45445 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
446 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08447 SelectFileDialog::FileTypeInfo file_type_info;
448 file_type_info.extensions.resize(1);
449 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24450 if (!file_type_info.extensions[0][0].empty())
451 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08452 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23453 gfx::NativeWindow owning_window =
454 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29455 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34456 string16(),
457 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08458 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30459 owning_window, info);
initial.commit09911bf2008-07-26 23:55:29460 } else {
461 // No prompting for download, just continue with the suggested name.
462 ContinueStartDownload(info, info->suggested_path);
463 }
464}
465
466void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
[email protected]7ae7c2cb2009-01-06 23:31:41467 const FilePath& target_path) {
[email protected]aa033af2010-07-27 18:16:39468 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
469
initial.commit09911bf2008-07-26 23:55:29470 scoped_ptr<DownloadCreateInfo> infop(info);
471 info->path = target_path;
472
[email protected]aa033af2010-07-27 18:16:39473 DownloadItem* download = new DownloadItem(this, *info,
474 profile_->IsOffTheRecord());
475 DCHECK(!ContainsKey(in_progress_, info->download_id));
476 in_progress_[info->download_id] = download;
initial.commit09911bf2008-07-26 23:55:29477
[email protected]aa033af2010-07-27 18:16:39478 bool download_finished = ContainsKey(pending_finished_downloads_,
479 info->download_id);
[email protected]594cd7d2010-07-21 03:23:56480
481 if (download_finished || info->is_dangerous) {
482 // The download has already finished or the download is not safe.
483 // We can now rename the file to its final name (or its tentative name
484 // in dangerous download cases).
485 ChromeThread::PostTask(
486 ChromeThread::FILE, FROM_HERE,
487 NewRunnableMethod(
488 file_manager_, &DownloadFileManager::OnFinalDownloadName,
489 download->id(), target_path, !info->is_dangerous, this));
490 } else {
491 // The download hasn't finished and it is a safe download. We need to
492 // rename it to its intermediate '.crdownload' path.
493 FilePath download_path = download_util::GetCrDownloadPath(target_path);
494 ChromeThread::PostTask(
495 ChromeThread::FILE, FROM_HERE,
496 NewRunnableMethod(
497 file_manager_, &DownloadFileManager::OnIntermediateDownloadName,
498 download->id(), download_path, this));
499 download->set_need_final_rename(true);
500 }
501
502 if (download_finished) {
503 // If the download already completed by the time we reached this point, then
504 // notify observers that it did.
[email protected]aa033af2010-07-27 18:16:39505 DownloadFinished(info->download_id,
506 pending_finished_downloads_[info->download_id]);
[email protected]594cd7d2010-07-21 03:23:56507 }
initial.commit09911bf2008-07-26 23:55:29508
509 download->Rename(target_path);
510
[email protected]82f37b02010-07-29 22:04:57511 download_history_->AddEntry(*info, download,
512 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
[email protected]6a7fb042010-02-01 16:30:47513
514 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29515}
516
initial.commit09911bf2008-07-26 23:55:29517void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
518 DownloadMap::iterator it = in_progress_.find(download_id);
519 if (it != in_progress_.end()) {
520 DownloadItem* download = it->second;
521 download->Update(size);
[email protected]82f37b02010-07-29 22:04:57522 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29523 }
[email protected]6a7fb042010-02-01 16:30:47524 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:29525}
526
527void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
528 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32529 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29530 // The download is done, but the user hasn't selected a final location for
531 // it yet (the Save As dialog box is probably still showing), so just keep
532 // track of the fact that this download id is complete, when the
533 // DownloadItem is constructed later we'll notify its completion then.
534 PendingFinishedMap::iterator erase_it =
535 pending_finished_downloads_.find(download_id);
536 DCHECK(erase_it == pending_finished_downloads_.end());
537 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32538 return;
initial.commit09911bf2008-07-26 23:55:29539 }
[email protected]9ccbb372008-10-10 18:50:32540
541 // Remove the id from the list of pending ids.
542 PendingFinishedMap::iterator erase_it =
543 pending_finished_downloads_.find(download_id);
544 if (erase_it != pending_finished_downloads_.end())
545 pending_finished_downloads_.erase(erase_it);
546
547 DownloadItem* download = it->second;
548 download->Finished(size);
549
550 // Clean up will happen when the history system create callback runs if we
551 // don't have a valid db_handle yet.
[email protected]82f37b02010-07-29 22:04:57552 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
[email protected]9ccbb372008-10-10 18:50:32553 in_progress_.erase(it);
[email protected]82f37b02010-07-29 22:04:57554 download_history_->UpdateEntry(download);
[email protected]9ccbb372008-10-10 18:50:32555 }
556
[email protected]6a7fb042010-02-01 16:30:47557 UpdateAppIcon();
558
[email protected]9ccbb372008-10-10 18:50:32559 // If this a dangerous download not yet validated by the user, don't do
560 // anything. When the user notifies us, it will trigger a call to
561 // ProceedWithFinishedDangerousDownload.
562 if (download->safety_state() == DownloadItem::DANGEROUS) {
563 dangerous_finished_[download_id] = download;
564 return;
565 }
566
567 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
[email protected]6cade212008-12-03 00:32:22568 // We first need to rename the downloaded file from its temporary name to
[email protected]9ccbb372008-10-10 18:50:32569 // its final name before we can continue.
[email protected]d83d03aa2009-11-02 21:44:37570 ChromeThread::PostTask(
571 ChromeThread::FILE, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32572 NewRunnableMethod(
573 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
574 download->db_handle(),
575 download->full_path(), download->original_name()));
576 return;
577 }
[email protected]594cd7d2010-07-21 03:23:56578
579 if (download->need_final_rename()) {
580 ChromeThread::PostTask(
581 ChromeThread::FILE, FROM_HERE,
582 NewRunnableMethod(
583 file_manager_, &DownloadFileManager::OnFinalDownloadName,
584 download->id(), download->full_path(), false, this));
585 return;
586 }
587
[email protected]9ccbb372008-10-10 18:50:32588 ContinueDownloadFinished(download);
589}
590
[email protected]8f783752009-04-01 23:33:45591void DownloadManager::DownloadRenamedToFinalName(int download_id,
592 const FilePath& full_path) {
[email protected]aa033af2010-07-27 18:16:39593 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
594
[email protected]2e030682010-07-23 19:45:36595 DownloadItem* item = GetDownloadItem(download_id);
596 if (!item)
597 return;
598 item->OnNameFinalized();
[email protected]594cd7d2010-07-21 03:23:56599
[email protected]2e030682010-07-23 19:45:36600 // This was called from DownloadFinished; continue to call
601 // ContinueDownloadFinished.
602 if (item->need_final_rename()) {
603 item->set_need_final_rename(false);
604 ContinueDownloadFinished(item);
[email protected]6aa4a1c02010-01-15 18:49:58605 }
[email protected]8f783752009-04-01 23:33:45606}
607
[email protected]9ccbb372008-10-10 18:50:32608void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
[email protected]aa033af2010-07-27 18:16:39609 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
610
[email protected]9ccbb372008-10-10 18:50:32611 // If this was a dangerous download, it has now been approved and must be
612 // removed from dangerous_finished_ so it does not get deleted on shutdown.
[email protected]aa033af2010-07-27 18:16:39613 dangerous_finished_.erase(download->id());
[email protected]9ccbb372008-10-10 18:50:32614
[email protected]0aad67b2009-07-15 20:34:28615 // Handle chrome extensions explicitly and skip the shell execute.
[email protected]a60c8ae2009-12-25 06:50:57616 if (download->is_extension_install()) {
[email protected]7ba53e12010-08-05 17:14:00617 download_util::OpenChromeExtension(profile_, this, *download);
[email protected]0aad67b2009-07-15 20:34:28618 download->set_auto_opened(true);
619 } else if (download->open_when_complete() ||
[email protected]6aa4a1c02010-01-15 18:49:58620 ShouldOpenFileBasedOnExtension(download->full_path()) ||
621 download->is_temporary()) {
622 // If the download is temporary, like in drag-and-drop, do not open it but
623 // we still need to set it auto-opened so that it can be removed from the
624 // download shelf.
625 if (!download->is_temporary())
626 OpenDownloadInShell(download, NULL);
[email protected]0aad67b2009-07-15 20:34:28627 download->set_auto_opened(true);
628 }
[email protected]9ccbb372008-10-10 18:50:32629
[email protected]0aad67b2009-07-15 20:34:28630 // Notify our observers that we are complete (the call to Finished() set the
631 // state to complete but did not notify).
632 download->UpdateObservers();
[email protected]6aa4a1c02010-01-15 18:49:58633
634 // The download file is meant to be completed if both the filename is
635 // finalized and the file data is downloaded. The ordering of these two
636 // actions is indeterministic. Thus, if the filename is not finalized yet,
637 // delay the notification.
638 if (download->name_finalized())
639 download->NotifyObserversDownloadFileCompleted();
[email protected]0aad67b2009-07-15 20:34:28640}
[email protected]eccb9d12009-10-28 05:40:09641
[email protected]9ccbb372008-10-10 18:50:32642// Called on the file thread. Renames the downloaded file to its original name.
643void DownloadManager::ProceedWithFinishedDangerousDownload(
644 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41645 const FilePath& path,
646 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32647 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41648 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16649 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32650 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24651 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16652 // Make our name unique at this point, as if a dangerous file is downloading
653 // and a 2nd download is started for a file with the same name, they would
654 // have the same path. This is because we uniquify the name on download
655 // start, and at that time the first file does not exists yet, so the second
656 // file gets the same name.
[email protected]5a2388a2010-03-26 16:13:39657 uniquifier = download_util::GetUniquePathNumber(new_path);
[email protected]7a256ea2008-10-17 17:34:16658 if (uniquifier > 0)
[email protected]5a2388a2010-03-26 16:13:39659 download_util::AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32660 success = file_util::Move(path, new_path);
661 } else {
662 NOTREACHED();
663 }
[email protected]6cade212008-12-03 00:32:22664
[email protected]d83d03aa2009-11-02 21:44:37665 ChromeThread::PostTask(
666 ChromeThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32667 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16668 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32669}
670
671// Call from the file thread when the finished dangerous download was renamed.
672void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
673 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41674 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16675 int new_path_uniquifier) {
[email protected]9ccbb372008-10-10 18:50:32676 DownloadMap::iterator it = downloads_.find(download_handle);
677 if (it == downloads_.end()) {
678 NOTREACHED();
679 return;
680 }
681
682 DownloadItem* download = it->second;
683 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16684 if (success) {
685 // We need to update the path uniquifier so that the UI shows the right
686 // name when calling GetFileName().
687 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32688 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16689 }
[email protected]9ccbb372008-10-10 18:50:32690
691 // Continue the download finished sequence.
692 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29693}
694
initial.commit09911bf2008-07-26 23:55:29695void DownloadManager::DownloadCancelled(int32 download_id) {
696 DownloadMap::iterator it = in_progress_.find(download_id);
697 if (it == in_progress_.end())
698 return;
699 DownloadItem* download = it->second;
700
initial.commit09911bf2008-07-26 23:55:29701 // Clean up will happen when the history system create callback runs if we
702 // don't have a valid db_handle yet.
[email protected]82f37b02010-07-29 22:04:57703 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
initial.commit09911bf2008-07-26 23:55:29704 in_progress_.erase(it);
[email protected]82f37b02010-07-29 22:04:57705 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29706 }
707
[email protected]d7d1c5c2009-08-05 23:52:50708 DownloadCancelledInternal(download_id,
709 download->render_process_id(),
710 download->request_id());
[email protected]6a7fb042010-02-01 16:30:47711 UpdateAppIcon();
[email protected]d7d1c5c2009-08-05 23:52:50712}
713
714void DownloadManager::DownloadCancelledInternal(int download_id,
715 int render_process_id,
716 int request_id) {
[email protected]d85cf072009-10-27 03:59:31717 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
718 ChromeThread::PostTask(
719 ChromeThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26720 NewRunnableFunction(&download_util::CancelDownloadRequest,
[email protected]d85cf072009-10-27 03:59:31721 g_browser_process->resource_dispatcher_host(),
722 render_process_id,
723 request_id));
[email protected]d7d1c5c2009-08-05 23:52:50724
initial.commit09911bf2008-07-26 23:55:29725 // Tell the file manager to cancel the download.
[email protected]d7d1c5c2009-08-05 23:52:50726 file_manager_->RemoveDownload(download_id, this); // On the UI thread
[email protected]d83d03aa2009-11-02 21:44:37727 ChromeThread::PostTask(
728 ChromeThread::FILE, FROM_HERE,
729 NewRunnableMethod(
730 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29731}
732
[email protected]7ba53e12010-08-05 17:14:00733// DownloadManager is owned by RDH, no need for reference counting.
734DISABLE_RUNNABLE_METHOD_REFCOUNT(ResourceDispatcherHost);
735
initial.commit09911bf2008-07-26 23:55:29736void DownloadManager::PauseDownload(int32 download_id, bool pause) {
737 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:31738 if (it == in_progress_.end())
739 return;
initial.commit09911bf2008-07-26 23:55:29740
[email protected]d85cf072009-10-27 03:59:31741 DownloadItem* download = it->second;
742 if (pause == download->is_paused())
743 return;
initial.commit09911bf2008-07-26 23:55:29744
[email protected]d85cf072009-10-27 03:59:31745 // Inform the ResourceDispatcherHost of the new pause state.
746 ChromeThread::PostTask(
747 ChromeThread::IO, FROM_HERE,
[email protected]7ba53e12010-08-05 17:14:00748 NewRunnableMethod(g_browser_process->resource_dispatcher_host(),
749 &ResourceDispatcherHost::PauseRequest,
750 download->render_process_id(),
751 download->request_id(),
752 pause));
[email protected]9ccbb372008-10-10 18:50:32753}
754
[email protected]6a7fb042010-02-01 16:30:47755void DownloadManager::UpdateAppIcon() {
756 int64 total_bytes = 0;
757 int64 received_bytes = 0;
758 int download_count = 0;
759 bool progress_known = true;
760
761 for (DownloadMap::iterator i = in_progress_.begin();
762 i != in_progress_.end();
763 ++i) {
764 ++download_count;
765 const DownloadItem* item = i->second;
766 if (item->total_bytes() > 0) {
767 total_bytes += item->total_bytes();
768 received_bytes += item->received_bytes();
769 } else {
770 // This download didn't specify a Content-Length, so the combined progress
771 // bar neeeds to be indeterminate.
772 progress_known = false;
773 }
774 }
775
776 float progress = 0;
777 if (progress_known && download_count)
[email protected]7ba53e12010-08-05 17:14:00778 progress = static_cast<float>(received_bytes) / total_bytes;
[email protected]6a7fb042010-02-01 16:30:47779
780 download_util::UpdateAppIconDownloadProgress(download_count,
781 progress_known,
782 progress);
783}
784
[email protected]9ccbb372008-10-10 18:50:32785void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41786 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32787 download->Rename(new_path);
[email protected]82f37b02010-07-29 22:04:57788 download_history_->UpdateDownloadPath(download, new_path);
[email protected]9ccbb372008-10-10 18:50:32789}
790
initial.commit09911bf2008-07-26 23:55:29791void DownloadManager::RemoveDownload(int64 download_handle) {
792 DownloadMap::iterator it = downloads_.find(download_handle);
793 if (it == downloads_.end())
794 return;
795
796 // Make history update.
797 DownloadItem* download = it->second;
[email protected]82f37b02010-07-29 22:04:57798 download_history_->RemoveEntry(download);
initial.commit09911bf2008-07-26 23:55:29799
800 // Remove from our tables and delete.
801 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32802 it = dangerous_finished_.find(download->id());
803 if (it != dangerous_finished_.end())
804 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:29805
806 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:28807 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:36808
809 delete download;
initial.commit09911bf2008-07-26 23:55:29810}
811
[email protected]e93d2822009-01-30 05:59:59812int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
813 const base::Time remove_end) {
[email protected]82f37b02010-07-29 22:04:57814 download_history_->RemoveEntriesBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29815
initial.commit09911bf2008-07-26 23:55:29816 DownloadMap::iterator it = downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:28817 std::vector<DownloadItem*> pending_deletes;
initial.commit09911bf2008-07-26 23:55:29818 while (it != downloads_.end()) {
819 DownloadItem* download = it->second;
820 DownloadItem::DownloadState state = download->state();
821 if (download->start_time() >= remove_begin &&
822 (remove_end.is_null() || download->start_time() < remove_end) &&
823 (state == DownloadItem::COMPLETE ||
824 state == DownloadItem::CANCELLED)) {
825 // Remove from the map and move to the next in the list.
[email protected]b7f05882009-02-22 01:21:56826 downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:58827
828 // Also remove it from any completed dangerous downloads.
829 DownloadMap::iterator dit = dangerous_finished_.find(download->id());
830 if (dit != dangerous_finished_.end())
831 dangerous_finished_.erase(dit);
832
[email protected]78b8fcc92009-03-31 17:36:28833 pending_deletes.push_back(download);
[email protected]b0ab1d42010-02-24 19:29:28834 // Observer interface.
initial.commit09911bf2008-07-26 23:55:29835
initial.commit09911bf2008-07-26 23:55:29836 continue;
837 }
838
839 ++it;
840 }
841
842 // Tell observers to refresh their views.
[email protected]78b8fcc92009-03-31 17:36:28843 int num_deleted = static_cast<int>(pending_deletes.size());
initial.commit09911bf2008-07-26 23:55:29844 if (num_deleted > 0)
[email protected]b0ab1d42010-02-24 19:29:28845 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:29846
[email protected]78b8fcc92009-03-31 17:36:28847 // Delete the download items after updating the observers.
848 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
849 pending_deletes.clear();
850
initial.commit09911bf2008-07-26 23:55:29851 return num_deleted;
852}
853
[email protected]e93d2822009-01-30 05:59:59854int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
855 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29856}
857
[email protected]d41355e6f2009-04-07 21:21:12858int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:46859 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
860 // This is an incognito downloader. Clear All should clear main download
861 // manager as well.
862 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
863 }
[email protected]d41355e6f2009-04-07 21:21:12864 // The null times make the date range unbounded.
865 return RemoveDownloadsBetween(base::Time(), base::Time());
866}
867
initial.commit09911bf2008-07-26 23:55:29868// Initiate a download of a specific URL. We send the request to the
869// ResourceDispatcherHost, and let it send us responses like a regular
870// download.
871void DownloadManager::DownloadUrl(const GURL& url,
872 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50873 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34874 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26875 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
876 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58877}
878
879void DownloadManager::DownloadUrlToFile(const GURL& url,
880 const GURL& referrer,
881 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32882 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58883 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34884 DCHECK(tab_contents);
[email protected]ae8945192010-07-20 16:56:26885 ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,
886 NewRunnableFunction(&download_util::DownloadUrl,
887 url,
888 referrer,
889 referrer_charset,
890 save_info,
891 g_browser_process->resource_dispatcher_host(),
892 tab_contents->GetRenderProcessHost()->id(),
893 tab_contents->render_view_host()->routing_id(),
894 request_context_getter_));
initial.commit09911bf2008-07-26 23:55:29895}
896
initial.commit09911bf2008-07-26 23:55:29897void DownloadManager::AddObserver(Observer* observer) {
898 observers_.AddObserver(observer);
899 observer->ModelChanged();
900}
901
902void DownloadManager::RemoveObserver(Observer* observer) {
903 observers_.RemoveObserver(observer);
904}
905
906// Post Windows Shell operations to the Download thread, to avoid blocking the
907// user interface.
908void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
909 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:37910 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:58911#if defined(OS_MACOSX)
912 // Mac needs to run this operation on the UI thread.
913 platform_util::ShowItemInFolder(download->full_path());
914#else
[email protected]d83d03aa2009-11-02 21:44:37915 ChromeThread::PostTask(
916 ChromeThread::FILE, FROM_HERE,
917 NewRunnableMethod(
918 file_manager_, &DownloadFileManager::OnShowDownloadInShell,
919 FilePath(download->full_path())));
[email protected]8b6ff012009-08-18 22:29:58920#endif
initial.commit09911bf2008-07-26 23:55:29921}
922
[email protected]8f783752009-04-01 23:33:45923void DownloadManager::OpenDownload(const DownloadItem* download,
924 gfx::NativeView parent_window) {
[email protected]0e34d7892009-06-05 19:17:40925 // Open Chrome extensions with ExtensionsService. For everything else do shell
[email protected]8f783752009-04-01 23:33:45926 // execute.
[email protected]a60c8ae2009-12-25 06:50:57927 if (download->is_extension_install()) {
[email protected]7ba53e12010-08-05 17:14:00928 download_util::OpenChromeExtension(profile_, this, *download);
[email protected]8f783752009-04-01 23:33:45929 } else {
930 OpenDownloadInShell(download, parent_window);
931 }
932}
933
initial.commit09911bf2008-07-26 23:55:29934void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
[email protected]e93d2822009-01-30 05:59:59935 gfx::NativeView parent_window) {
initial.commit09911bf2008-07-26 23:55:29936 DCHECK(file_manager_);
[email protected]d83d03aa2009-11-02 21:44:37937 DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
[email protected]8b6ff012009-08-18 22:29:58938#if defined(OS_MACOSX)
939 // Mac OS X requires opening downloads on the UI thread.
940 platform_util::OpenItem(download->full_path());
941#else
[email protected]d83d03aa2009-11-02 21:44:37942 ChromeThread::PostTask(
943 ChromeThread::FILE, FROM_HERE,
944 NewRunnableMethod(
945 file_manager_, &DownloadFileManager::OnOpenDownloadInShell,
946 download->full_path(), download->url(), parent_window));
[email protected]8b6ff012009-08-18 22:29:58947#endif
initial.commit09911bf2008-07-26 23:55:29948}
949
[email protected]eccb9d12009-10-28 05:40:09950void DownloadManager::OpenFilesBasedOnExtension(
951 const FilePath& path, bool open) {
952 FilePath::StringType extension = path.Extension();
953 if (extension.empty())
954 return;
955 DCHECK(extension[0] == FilePath::kExtensionSeparator);
956 extension.erase(0, 1);
[email protected]7ba53e12010-08-05 17:14:00957 if (open && !download_util::IsExecutableExtension(extension))
initial.commit09911bf2008-07-26 23:55:29958 auto_open_.insert(extension);
959 else
960 auto_open_.erase(extension);
961 SaveAutoOpens();
962}
963
[email protected]eccb9d12009-10-28 05:40:09964bool DownloadManager::ShouldOpenFileBasedOnExtension(
965 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:09966 FilePath::StringType extension = path.Extension();
967 if (extension.empty())
968 return false;
[email protected]7ba53e12010-08-05 17:14:00969 if (download_util::IsExecutableExtension(extension))
[email protected]eccb9d12009-10-28 05:40:09970 return false;
[email protected]92e11c82010-01-13 06:39:56971 if (Extension::IsExtension(path))
972 return false;
[email protected]eccb9d12009-10-28 05:40:09973 DCHECK(extension[0] == FilePath::kExtensionSeparator);
974 extension.erase(0, 1);
[email protected]92e11c82010-01-13 06:39:56975 if (auto_open_.find(extension) != auto_open_.end())
[email protected]8c756ac2009-01-30 23:36:41976 return true;
initial.commit09911bf2008-07-26 23:55:29977 return false;
978}
979
[email protected]eccb9d12009-10-28 05:40:09980bool DownloadManager::IsExecutableFile(const FilePath& path) const {
[email protected]7ba53e12010-08-05 17:14:00981 return download_util::IsExecutableExtension(path.Extension());
initial.commit09911bf2008-07-26 23:55:29982}
983
984void DownloadManager::ResetAutoOpenFiles() {
985 auto_open_.clear();
986 SaveAutoOpens();
987}
988
989bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
990 return !auto_open_.empty();
991}
992
993void DownloadManager::SaveAutoOpens() {
994 PrefService* prefs = profile_->GetPrefs();
995 if (prefs) {
[email protected]ddd231e2010-06-29 20:35:19996 std::string extensions;
[email protected]eccb9d12009-10-28 05:40:09997 for (AutoOpenSet::iterator it = auto_open_.begin();
initial.commit09911bf2008-07-26 23:55:29998 it != auto_open_.end(); ++it) {
[email protected]ddd231e2010-06-29 20:35:19999#if defined(OS_POSIX)
1000 std::string this_extension = *it;
1001#elif defined(OS_WIN)
1002 std::string this_extension = base::SysWideToUTF8(*it);
1003#endif
1004 extensions += this_extension + ":";
initial.commit09911bf2008-07-26 23:55:291005 }
1006 if (!extensions.empty())
1007 extensions.erase(extensions.size() - 1);
[email protected]b7f05882009-02-22 01:21:561008
[email protected]ddd231e2010-06-29 20:35:191009 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions);
initial.commit09911bf2008-07-26 23:55:291010 }
1011}
1012
[email protected]561abe62009-04-06 18:08:341013void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361014 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:291015 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]e6875c12010-07-18 11:14:131016 if (info->prompt_user_for_save_location)
[email protected]7ae7c2cb2009-01-06 23:31:411017 last_download_path_ = path.DirName();
initial.commit09911bf2008-07-26 23:55:291018 ContinueStartDownload(info, path);
1019}
1020
1021void DownloadManager::FileSelectionCanceled(void* params) {
1022 // The user didn't pick a place to save the file, so need to cancel the
1023 // download that's already in progress to the temporary location.
1024 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:501025 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:451026 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:501027 info->request_id);
initial.commit09911bf2008-07-26 23:55:291028}
1029
[email protected]9ccbb372008-10-10 18:50:321030void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1031 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1032 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1033 download->UpdateObservers();
1034
1035 // If the download is not complete, nothing to do. The required
1036 // post-processing will be performed when it does complete.
1037 if (download->state() != DownloadItem::COMPLETE)
1038 return;
1039
[email protected]d83d03aa2009-11-02 21:44:371040 ChromeThread::PostTask(
1041 ChromeThread::FILE, FROM_HERE,
1042 NewRunnableMethod(
1043 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
1044 download->db_handle(), download->full_path(),
1045 download->original_name()));
[email protected]9ccbb372008-10-10 18:50:321046}
1047
initial.commit09911bf2008-07-26 23:55:291048// Operations posted to us from the history service ----------------------------
1049
1050// The history service has retrieved all download entries. 'entries' contains
1051// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1052void DownloadManager::OnQueryDownloadEntriesComplete(
1053 std::vector<DownloadCreateInfo>* entries) {
1054 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:391055 DownloadItem* download = new DownloadItem(this, entries->at(i));
1056 DCHECK(!ContainsKey(downloads_, download->db_handle()));
initial.commit09911bf2008-07-26 23:55:291057 downloads_[download->db_handle()] = download;
initial.commit09911bf2008-07-26 23:55:291058 }
[email protected]b0ab1d42010-02-24 19:29:281059 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291060}
1061
initial.commit09911bf2008-07-26 23:55:291062// Once the new DownloadItem's creation info has been committed to the history
1063// service, we associate the DownloadItem with the db handle, update our
1064// 'downloads_' map and inform observers.
1065void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1066 int64 db_handle) {
1067 DownloadMap::iterator it = in_progress_.find(info.download_id);
1068 DCHECK(it != in_progress_.end());
1069
1070 DownloadItem* download = it->second;
[email protected]d2a8fb72010-01-21 05:31:421071
1072 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1073 // call this function with an invalid |db_handle|. For instance, this can
1074 // happen when the history database is offline. We cannot have multiple
1075 // DownloadItems with the same invalid db_handle, so we need to assign a
1076 // unique |db_handle| here.
[email protected]82f37b02010-07-29 22:04:571077 if (db_handle == DownloadHistory::kUninitializedHandle)
1078 db_handle = download_history_->GetNextFakeDbHandle();
[email protected]d2a8fb72010-01-21 05:31:421079
[email protected]82f37b02010-07-29 22:04:571080 DCHECK(download->db_handle() == DownloadHistory::kUninitializedHandle);
initial.commit09911bf2008-07-26 23:55:291081 download->set_db_handle(db_handle);
1082
1083 // Insert into our full map.
1084 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1085 downloads_[download->db_handle()] = download;
1086
[email protected]5e595482009-05-06 20:16:531087 // Show in the appropropriate browser UI.
1088 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291089
1090 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281091 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291092
1093 // If this download has been completed before we've received the db handle,
1094 // post one final message to the history service so that it can be properly
1095 // in sync with the DownloadItem's completion status, and also inform any
1096 // observers so that they get more than just the start notification.
1097 if (download->state() != DownloadItem::IN_PROGRESS) {
1098 in_progress_.erase(it);
[email protected]82f37b02010-07-29 22:04:571099 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:291100 download->UpdateObservers();
1101 }
[email protected]6a7fb042010-02-01 16:30:471102
1103 UpdateAppIcon();
initial.commit09911bf2008-07-26 23:55:291104}
1105
[email protected]5e595482009-05-06 20:16:531106void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1107 DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341108 // The 'contents' may no longer exist if the user closed the tab before we
1109 // get this start completion event. If it does, tell the origin TabContents
1110 // to display its download shelf.
[email protected]76543b92009-08-31 17:27:451111 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1112 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531113
1114 // If the contents no longer exists, we start the download in the last active
1115 // browser. This is not ideal but better than fully hiding the download from
1116 // the user.
1117 if (!contents) {
1118 Browser* last_active = BrowserList::GetLastActive();
1119 if (last_active)
1120 contents = last_active->GetSelectedTabContents();
1121 }
1122
1123 if (contents)
1124 contents->OnStartDownload(download);
1125}
1126
[email protected]6cade212008-12-03 00:32:221127// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121128void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411129 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381130}
[email protected]b0ab1d42010-02-24 19:29:281131
1132void DownloadManager::NotifyModelChanged() {
1133 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1134}
1135
[email protected]2e030682010-07-23 19:45:361136DownloadItem* DownloadManager::GetDownloadItem(int id) {
1137 for (DownloadMap::iterator it = downloads_.begin();
1138 it != downloads_.end(); ++it) {
1139 DownloadItem* item = it->second;
1140 if (item->id() == id)
1141 return item;
1142 }
1143 return NULL;
1144}
1145
[email protected]b0ab1d42010-02-24 19:29:281146// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1147
1148DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1149 DownloadManager* observing_download_manager)
1150 : observing_download_manager_(observing_download_manager),
1151 observed_download_manager_(NULL) {
1152 if (observing_download_manager->profile_->GetOriginalProfile() ==
1153 observing_download_manager->profile_) {
1154 return;
1155 }
1156
1157 observed_download_manager_ = observing_download_manager_->
1158 profile_->GetOriginalProfile()->GetDownloadManager();
1159 observed_download_manager_->AddObserver(this);
1160}
1161
1162DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1163 if (observed_download_manager_)
1164 observed_download_manager_->RemoveObserver(this);
1165}
1166
1167void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1168 observing_download_manager_->NotifyModelChanged();
1169}
1170
[email protected]b0ab1d42010-02-24 19:29:281171void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1172 observed_download_manager_ = NULL;
1173}