blob: 66afe0449ddceb7a1e823efda809b7d7b7214596 [file] [log] [blame]
[email protected]f4f50ef2011-01-21 19:01:191// Copyright (c) 2011 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]2041cf342010-02-19 03:15:597#include "base/callback.h"
initial.commit09911bf2008-07-26 23:55:298#include "base/file_util.h"
9#include "base/logging.h"
initial.commit09911bf2008-07-26 23:55:2910#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1411#include "base/rand_util.h"
[email protected]92926d92010-09-02 18:35:0612#include "base/stl_util-inl.h"
[email protected]2594c2b2010-11-08 23:04:2613#include "base/stringprintf.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"
initial.commit09911bf2008-07-26 23:55:2918#include "chrome/browser/browser_list.h"
19#include "chrome/browser/browser_process.h"
[email protected]facac1532010-10-11 22:59:5020#include "chrome/browser/browser_thread.h"
[email protected]cd448092010-12-06 23:49:1321#include "chrome/browser/download/download_extensions.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]e5dc4222010-08-30 22:16:3225#include "chrome/browser/download/download_prefs.h"
[email protected]073ed7b2010-09-27 09:20:0226#include "chrome/browser/download/download_status_updater.h"
[email protected]e9ef0a62009-08-11 22:50:1327#include "chrome/browser/download/download_util.h"
[email protected]eaa7dd182010-12-14 11:09:0028#include "chrome/browser/extensions/extension_service.h"
[email protected]a0835ac2010-09-13 19:40:0829#include "chrome/browser/history/download_create_info.h"
[email protected]be180c802009-10-23 06:33:3130#include "chrome/browser/net/chrome_url_request_context.h"
[email protected]14a000d2010-04-29 21:44:2431#include "chrome/browser/platform_util.h"
[email protected]8ecad5e2010-12-02 21:18:3332#include "chrome/browser/profiles/profile.h"
[email protected]8c8657d62009-01-16 18:31:2633#include "chrome/browser/renderer_host/render_process_host.h"
[email protected]6524b5f92009-01-22 17:48:2534#include "chrome/browser/renderer_host/render_view_host.h"
[email protected]8e2b6472010-12-15 22:19:4835#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
[email protected]57c6a652009-05-04 07:58:3436#include "chrome/browser/tab_contents/tab_contents.h"
[email protected]d2a8fb72010-01-21 05:31:4237#include "chrome/browser/tab_contents/tab_util.h"
[email protected]7b5dc002010-11-16 23:08:1038#include "chrome/browser/ui/browser.h"
initial.commit09911bf2008-07-26 23:55:2939#include "chrome/common/chrome_paths.h"
[email protected]91e1bd82009-09-03 22:04:4040#include "chrome/common/notification_type.h"
[email protected]46072d42008-07-28 14:49:3541#include "googleurl/src/gurl.h"
[email protected]34ac8f32009-02-22 23:03:2742#include "grit/generated_resources.h"
[email protected]21ca982c2010-01-26 22:49:5543#include "grit/theme_resources.h"
initial.commit09911bf2008-07-26 23:55:2944#include "net/base/mime_util.h"
45#include "net/base/net_util.h"
[email protected]c051a1b2011-01-21 23:30:1746#include "ui/base/l10n/l10n_util.h"
[email protected]42ce29d2011-01-20 23:19:4647#include "ui/base/resource/resource_bundle.h"
initial.commit09911bf2008-07-26 23:55:2948
[email protected]073ed7b2010-09-27 09:20:0249DownloadManager::DownloadManager(DownloadStatusUpdater* status_updater)
initial.commit09911bf2008-07-26 23:55:2950 : shutdown_needed_(false),
51 profile_(NULL),
[email protected]073ed7b2010-09-27 09:20:0252 file_manager_(NULL),
[email protected]a3d2bc42010-10-06 14:08:4953 status_updater_(status_updater->AsWeakPtr()) {
[email protected]073ed7b2010-09-27 09:20:0254 if (status_updater_)
55 status_updater_->AddDelegate(this);
initial.commit09911bf2008-07-26 23:55:2956}
57
58DownloadManager::~DownloadManager() {
[email protected]326a6a92010-09-10 20:21:1359 DCHECK(!shutdown_needed_);
[email protected]073ed7b2010-09-27 09:20:0260 if (status_updater_)
61 status_updater_->RemoveDelegate(this);
initial.commit09911bf2008-07-26 23:55:2962}
63
64void DownloadManager::Shutdown() {
[email protected]da6e3922010-11-24 21:45:5065 VLOG(20) << __FUNCTION__ << "()"
66 << " shutdown_needed_ = " << shutdown_needed_;
[email protected]326a6a92010-09-10 20:21:1367 if (!shutdown_needed_)
68 return;
69 shutdown_needed_ = false;
initial.commit09911bf2008-07-26 23:55:2970
[email protected]326a6a92010-09-10 20:21:1371 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
72
73 if (file_manager_) {
[email protected]ca4b5fa32010-10-09 12:42:1874 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
[email protected]326a6a92010-09-10 20:21:1375 NewRunnableMethod(file_manager_,
76 &DownloadFileManager::OnDownloadManagerShutdown,
[email protected]dc7cdcb92010-12-14 06:40:5477 make_scoped_refptr(this)));
[email protected]326a6a92010-09-10 20:21:1378 }
initial.commit09911bf2008-07-26 23:55:2979
[email protected]f04182f32010-12-10 19:12:0780 AssertContainersConsistent();
81
82 // Go through all downloads in downloads_. Dangerous ones we need to
83 // remove on disk, and in progress ones we need to cancel.
[email protected]57fd1252010-12-23 17:24:0984 for (DownloadSet::iterator it = downloads_.begin(); it != downloads_.end();) {
[email protected]f04182f32010-12-10 19:12:0785 DownloadItem* download = *it;
86
87 // Save iterator from potential erases in this set done by called code.
88 // Iterators after an erasure point are still valid for lists and
89 // associative containers such as sets.
90 it++;
91
92 if (download->safety_state() == DownloadItem::DANGEROUS &&
93 (download->state() == DownloadItem::IN_PROGRESS ||
94 download->state() == DownloadItem::COMPLETE)) {
95 // The user hasn't accepted it, so we need to remove it
96 // from the disk. This may or may not result in it being
97 // removed from the DownloadManager queues and deleted
98 // (specifically, DownloadManager::RemoveDownload only
99 // removes and deletes it if it's known to the history service)
100 // so the only thing we know after calling this function is that
101 // the download was deleted if-and-only-if it was removed
102 // from all queues.
103 download->Remove(true);
104 } else if (download->state() == DownloadItem::IN_PROGRESS) {
105 download->Cancel(false);
106 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29107 }
108 }
109
[email protected]f04182f32010-12-10 19:12:07110 // At this point, all dangerous downloads have had their files removed
111 // and all in progress downloads have been cancelled. We can now delete
112 // anything left.
113 STLDeleteElements(&downloads_);
[email protected]9ccbb372008-10-10 18:50:32114
[email protected]f04182f32010-12-10 19:12:07115 // And clear all non-owning containers.
initial.commit09911bf2008-07-26 23:55:29116 in_progress_.clear();
[email protected]70850c72011-01-11 17:31:27117 active_downloads_.clear();
[email protected]57fd1252010-12-23 17:24:09118#if !defined(NDEBUG)
119 save_page_as_downloads_.clear();
120#endif
initial.commit09911bf2008-07-26 23:55:29121
122 file_manager_ = NULL;
123
initial.commit09911bf2008-07-26 23:55:29124 // Make sure the save as dialog doesn't notify us back if we're gone before
125 // it returns.
126 if (select_file_dialog_.get())
127 select_file_dialog_->ListenerDestroyed();
128
[email protected]82f37b02010-07-29 22:04:57129 download_history_.reset();
[email protected]68a49e52011-01-28 10:39:51130 download_prefs_.reset();
[email protected]82f37b02010-07-29 22:04:57131
[email protected]2c93f6f2010-11-08 20:41:17132 request_context_getter_ = NULL;
133
initial.commit09911bf2008-07-26 23:55:29134 shutdown_needed_ = false;
135}
136
[email protected]82f37b02010-07-29 22:04:57137void DownloadManager::GetTemporaryDownloads(
138 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
139 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58140
[email protected]f04182f32010-12-10 19:12:07141 for (DownloadMap::iterator it = history_downloads_.begin();
142 it != history_downloads_.end(); ++it) {
[email protected]6aa4a1c02010-01-15 18:49:58143 if (it->second->is_temporary() &&
144 it->second->full_path().DirName() == dir_path)
[email protected]82f37b02010-07-29 22:04:57145 result->push_back(it->second);
[email protected]6aa4a1c02010-01-15 18:49:58146 }
[email protected]6aa4a1c02010-01-15 18:49:58147}
148
[email protected]82f37b02010-07-29 22:04:57149void DownloadManager::GetAllDownloads(
150 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
151 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34152
[email protected]f04182f32010-12-10 19:12:07153 for (DownloadMap::iterator it = history_downloads_.begin();
154 it != history_downloads_.end(); ++it) {
[email protected]8ddbd66a2010-05-21 16:38:34155 if (!it->second->is_temporary() &&
156 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57157 result->push_back(it->second);
[email protected]8ddbd66a2010-05-21 16:38:34158 }
[email protected]8ddbd66a2010-05-21 16:38:34159}
160
[email protected]82f37b02010-07-29 22:04:57161void DownloadManager::GetCurrentDownloads(
162 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
163 DCHECK(result);
[email protected]c4a530b2010-03-08 17:33:03164
[email protected]f04182f32010-12-10 19:12:07165 for (DownloadMap::iterator it = history_downloads_.begin();
166 it != history_downloads_.end(); ++it) {
[email protected]c4a530b2010-03-08 17:33:03167 if (!it->second->is_temporary() &&
168 (it->second->state() == DownloadItem::IN_PROGRESS ||
169 it->second->safety_state() == DownloadItem::DANGEROUS) &&
170 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57171 result->push_back(it->second);
[email protected]c4a530b2010-03-08 17:33:03172 }
[email protected]f7e9fd62010-09-28 15:45:06173
174 // If we have a parent profile, let it add its downloads to the results.
175 Profile* original_profile = profile_->GetOriginalProfile();
176 if (original_profile != profile_)
177 original_profile->GetDownloadManager()->GetCurrentDownloads(dir_path,
178 result);
[email protected]c4a530b2010-03-08 17:33:03179}
180
[email protected]d3b12902010-08-16 23:39:42181void DownloadManager::SearchDownloads(const string16& query,
182 std::vector<DownloadItem*>* result) {
183 DCHECK(result);
184
185 string16 query_lower(l10n_util::ToLower(query));
186
[email protected]f04182f32010-12-10 19:12:07187 for (DownloadMap::iterator it = history_downloads_.begin();
188 it != history_downloads_.end(); ++it) {
[email protected]d3b12902010-08-16 23:39:42189 DownloadItem* download_item = it->second;
190
191 if (download_item->is_temporary() || download_item->is_extension_install())
192 continue;
193
194 // Display Incognito downloads only in Incognito window, and vice versa.
195 // The Incognito Downloads page will get the list of non-Incognito downloads
196 // from its parent profile.
197 if (profile_->IsOffTheRecord() != download_item->is_otr())
198 continue;
199
200 if (download_item->MatchesQuery(query_lower))
201 result->push_back(download_item);
202 }
203
204 // If we have a parent profile, let it add its downloads to the results.
205 Profile* original_profile = profile_->GetOriginalProfile();
206 if (original_profile != profile_)
207 original_profile->GetDownloadManager()->SearchDownloads(query, result);
208}
209
initial.commit09911bf2008-07-26 23:55:29210// Query the history service for information about all persisted downloads.
211bool DownloadManager::Init(Profile* profile) {
212 DCHECK(profile);
213 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
214 shutdown_needed_ = true;
215
216 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31217 request_context_getter_ = profile_->GetRequestContext();
[email protected]d3b12902010-08-16 23:39:42218 download_history_.reset(new DownloadHistory(profile));
[email protected]82f37b02010-07-29 22:04:57219 download_history_->Load(
220 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
[email protected]024f2f02010-04-30 22:51:46221
[email protected]e5dc4222010-08-30 22:16:32222 download_prefs_.reset(new DownloadPrefs(profile_->GetPrefs()));
223
[email protected]2941c2392010-07-15 22:54:30224 // In test mode, there may be no ResourceDispatcherHost. In this case it's
225 // safe to avoid setting |file_manager_| because we only call a small set of
226 // functions, none of which need it.
initial.commit09911bf2008-07-26 23:55:29227 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]2941c2392010-07-15 22:54:30228 if (rdh) {
229 file_manager_ = rdh->download_file_manager();
230 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29231 }
232
[email protected]b0ab1d42010-02-24 19:29:28233 other_download_manager_observer_.reset(
234 new OtherDownloadManagerObserver(this));
235
initial.commit09911bf2008-07-26 23:55:29236 return true;
237}
238
initial.commit09911bf2008-07-26 23:55:29239// We have received a message from DownloadFileManager about a new download. We
240// create a download item and store it in our download map, and inform the
241// history system of a new download. Since this method can be called while the
242// history service thread is still reading the persistent state, we do not
[email protected]f04182f32010-12-10 19:12:07243// insert the new DownloadItem into 'history_downloads_' or inform our
[email protected]adb2f3d12011-01-23 16:24:54244// observers at this point. OnCreateDownloadEntryComplete() handles that
[email protected]f04182f32010-12-10 19:12:07245// finalization of the the download creation as a callback from the
246// history thread.
initial.commit09911bf2008-07-26 23:55:29247void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]ca4b5fa32010-10-09 12:42:18248 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29249 DCHECK(info);
250
[email protected]a60c8ae2009-12-25 06:50:57251 // Check whether this download is for an extension install or not.
[email protected]e6875c12010-07-18 11:14:13252 // Allow extensions to be explicitly saved.
253 if (!info->prompt_user_for_save_location) {
[email protected]a60c8ae2009-12-25 06:50:57254 if (UserScript::HasUserScriptFileExtension(info->url) ||
255 info->mime_type == Extension::kMimeType)
256 info->is_extension_install = true;
257 }
258
[email protected]8af9d032010-02-10 00:00:32259 if (info->save_info.file_path.empty()) {
[email protected]2941c2392010-07-15 22:54:30260 FilePath generated_name;
[email protected]7ba53e12010-08-05 17:14:00261 download_util::GenerateFileNameFromInfo(info, &generated_name);
[email protected]2941c2392010-07-15 22:54:30262
263 // Freeze the user's preference for showing a Save As dialog. We're going
264 // to bounce around a bunch of threads and we don't want to worry about race
265 // conditions where the user changes this pref out from under us.
[email protected]e5dc4222010-08-30 22:16:32266 if (download_prefs_->prompt_for_download()) {
[email protected]2941c2392010-07-15 22:54:30267 // But ignore the user's preference for the following scenarios:
268 // 1) Extension installation. Note that we only care here about the case
269 // where an extension is installed, not when one is downloaded with
270 // "save as...".
271 // 2) Filetypes marked "always open." If the user just wants this file
272 // opened, don't bother asking where to keep it.
273 if (!info->is_extension_install &&
274 !ShouldOpenFileBasedOnExtension(generated_name))
[email protected]e6875c12010-07-18 11:14:13275 info->prompt_user_for_save_location = true;
[email protected]2941c2392010-07-15 22:54:30276 }
277
[email protected]8af9d032010-02-10 00:00:32278 // Determine the proper path for a download, by either one of the following:
279 // 1) using the default download directory.
280 // 2) prompting the user.
[email protected]ccea03c2010-12-17 03:31:50281 if (info->prompt_user_for_save_location && !last_download_path_.empty()) {
[email protected]8af9d032010-02-10 00:00:32282 info->suggested_path = last_download_path_;
[email protected]80dc3612010-07-27 19:35:08283 } else {
[email protected]e5dc4222010-08-30 22:16:32284 info->suggested_path = download_prefs_->download_path();
[email protected]80dc3612010-07-27 19:35:08285 }
[email protected]8af9d032010-02-10 00:00:32286 info->suggested_path = info->suggested_path.Append(generated_name);
287 } else {
288 info->suggested_path = info->save_info.file_path;
289 }
initial.commit09911bf2008-07-26 23:55:29290
[email protected]e6875c12010-07-18 11:14:13291 if (!info->prompt_user_for_save_location &&
292 info->save_info.file_path.empty()) {
[email protected]b580f25e2011-01-29 05:06:17293 info->is_dangerous = download_util::IsDangerous(
294 info, profile(), ShouldOpenFileBasedOnExtension(info->suggested_path));
[email protected]e9ebf3fc2008-10-17 22:06:58295 }
296
initial.commit09911bf2008-07-26 23:55:29297 // We need to move over to the download thread because we don't want to stat
298 // the suggested path on the UI thread.
[email protected]5a3b97e2010-10-05 09:49:11299 // We can only access preferences on the UI thread, so check the download path
300 // now and pass the value to the FILE thread.
[email protected]ca4b5fa32010-10-09 12:42:18301 BrowserThread::PostTask(
302 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37303 NewRunnableMethod(
[email protected]5a3b97e2010-10-05 09:49:11304 this,
305 &DownloadManager::CheckIfSuggestedPathExists,
306 info,
307 download_prefs()->download_path()));
initial.commit09911bf2008-07-26 23:55:29308}
309
[email protected]5a3b97e2010-10-05 09:49:11310void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info,
311 const FilePath& default_path) {
[email protected]ca4b5fa32010-10-09 12:42:18312 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
initial.commit09911bf2008-07-26 23:55:29313 DCHECK(info);
314
[email protected]5a3b97e2010-10-05 09:49:11315 // Make sure the default download directory exists.
316 // TODO(phajdan.jr): only create the directory when we're sure the user
317 // is going to save there and not to another directory of his choice.
318 file_util::CreateDirectory(default_path);
319
initial.commit09911bf2008-07-26 23:55:29320 // Check writability of the suggested path. If we can't write to it, default
321 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41322 FilePath dir = info->suggested_path.DirName();
323 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32324 if (!file_util::PathIsWritable(dir)) {
[email protected]da6e3922010-11-24 21:45:50325 VLOG(1) << "Unable to write to directory \"" << dir.value() << "\"";
[email protected]e6875c12010-07-18 11:14:13326 info->prompt_user_for_save_location = true;
initial.commit09911bf2008-07-26 23:55:29327 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41328 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29329 }
330
[email protected]6cade212008-12-03 00:32:22331 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]e9ebf3fc2008-10-17 22:06:58332 if (info->is_dangerous) {
[email protected]7ae7c2cb2009-01-06 23:31:41333 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32334 // Create a temporary file to hold the file until the user approves its
335 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41336 FilePath::StringType file_name;
337 FilePath path;
[email protected]463e1b432011-01-21 22:05:51338#if defined(OS_WIN)
339 string16 unconfirmed_prefix =
340 l10n_util::GetStringUTF16(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
341#else
342 std::string unconfirmed_prefix =
343 l10n_util::GetStringUTF8(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
344#endif
345
[email protected]9ccbb372008-10-10 18:50:32346 while (path.empty()) {
[email protected]2594c2b2010-11-08 23:04:26347 base::SStringPrintf(
348 &file_name,
[email protected]463e1b432011-01-21 22:05:51349 unconfirmed_prefix.append(
350 FILE_PATH_LITERAL(" %d.crdownload")).c_str(),
[email protected]2594c2b2010-11-08 23:04:26351 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41352 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07353 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41354 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32355 }
356 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16357 } else {
[email protected]594cd7d2010-07-21 03:23:56358 // Do not add the path uniquifier if we are saving to a specific path as in
359 // the drag-out case.
360 if (info->save_info.file_path.empty()) {
361 info->path_uniquifier = download_util::GetUniquePathNumberWithCrDownload(
362 info->suggested_path);
363 }
[email protected]7a256ea2008-10-17 17:34:16364 // We know the final path, build it if necessary.
365 if (info->path_uniquifier > 0) {
[email protected]5a2388a2010-03-26 16:13:39366 download_util::AppendNumberToPath(&(info->suggested_path),
367 info->path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16368 // Setting path_uniquifier to 0 to make sure we don't try to unique it
369 // later on.
370 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07371 } else if (info->path_uniquifier == -1) {
372 // We failed to find a unique path. We have to prompt the user.
[email protected]da6e3922010-11-24 21:45:50373 VLOG(1) << "Unable to find a unique path for suggested path \""
374 << info->suggested_path.value() << "\"";
[email protected]e6875c12010-07-18 11:14:13375 info->prompt_user_for_save_location = true;
[email protected]7a256ea2008-10-17 17:34:16376 }
[email protected]9ccbb372008-10-10 18:50:32377 }
378
[email protected]594cd7d2010-07-21 03:23:56379 // Create an empty file at the suggested path so that we don't allocate the
380 // same "non-existant" path to multiple downloads.
381 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]e6875c12010-07-18 11:14:13382 if (!info->prompt_user_for_save_location &&
383 info->save_info.file_path.empty()) {
[email protected]594cd7d2010-07-21 03:23:56384 if (info->is_dangerous)
385 file_util::WriteFile(info->suggested_path, "", 0);
386 else
387 file_util::WriteFile(download_util::GetCrDownloadPath(
388 info->suggested_path), "", 0);
[email protected]7d3851d82008-12-12 03:26:07389 }
390
[email protected]ca4b5fa32010-10-09 12:42:18391 BrowserThread::PostTask(
392 BrowserThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29393 NewRunnableMethod(this,
394 &DownloadManager::OnPathExistenceAvailable,
395 info));
396}
397
398void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]da6e3922010-11-24 21:45:50399 VLOG(20) << __FUNCTION__ << "()" << " info = " << info->DebugString();
[email protected]ca4b5fa32010-10-09 12:42:18400 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29401 DCHECK(info);
402
[email protected]e6875c12010-07-18 11:14:13403 if (info->prompt_user_for_save_location) {
initial.commit09911bf2008-07-26 23:55:29404 // We must ask the user for the place to put the download.
405 if (!select_file_dialog_.get())
406 select_file_dialog_ = SelectFileDialog::Create(this);
407
[email protected]76543b92009-08-31 17:27:45408 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
409 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08410 SelectFileDialog::FileTypeInfo file_type_info;
411 file_type_info.extensions.resize(1);
412 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24413 if (!file_type_info.extensions[0][0].empty())
414 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08415 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23416 gfx::NativeWindow owning_window =
417 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29418 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34419 string16(),
420 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08421 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30422 owning_window, info);
[email protected]ac167ce2010-11-24 17:59:48423 FOR_EACH_OBSERVER(Observer, observers_, SelectFileDialogDisplayed());
initial.commit09911bf2008-07-26 23:55:29424 } else {
425 // No prompting for download, just continue with the suggested name.
[email protected]c2e76012010-12-23 21:10:29426 AttachDownloadItem(info, info->suggested_path);
initial.commit09911bf2008-07-26 23:55:29427 }
428}
429
[email protected]c2e76012010-12-23 21:10:29430void DownloadManager::CreateDownloadItem(DownloadCreateInfo* info) {
431 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
432
433 DownloadItem* download = new DownloadItem(this, *info,
434 profile_->IsOffTheRecord());
435 DCHECK(!ContainsKey(in_progress_, info->download_id));
[email protected]70850c72011-01-11 17:31:27436 DCHECK(!ContainsKey(active_downloads_, info->download_id));
[email protected]c2e76012010-12-23 21:10:29437 downloads_.insert(download);
[email protected]70850c72011-01-11 17:31:27438 active_downloads_[info->download_id] = download;
[email protected]c2e76012010-12-23 21:10:29439}
440
441void DownloadManager::AttachDownloadItem(DownloadCreateInfo* info,
[email protected]a850ba42010-09-10 22:00:30442 const FilePath& target_path) {
[email protected]adb2f3d12011-01-23 16:24:54443 VLOG(20) << __FUNCTION__ << "()" << " info = " << info->DebugString();
444
[email protected]ca4b5fa32010-10-09 12:42:18445 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]aa033af2010-07-27 18:16:39446
initial.commit09911bf2008-07-26 23:55:29447 scoped_ptr<DownloadCreateInfo> infop(info);
448 info->path = target_path;
449
[email protected]70850c72011-01-11 17:31:27450 // NOTE(ahendrickson) Eventually |active_downloads_| will replace
451 // |in_progress_|, but we don't want to change the semantics yet.
[email protected]aa033af2010-07-27 18:16:39452 DCHECK(!ContainsKey(in_progress_, info->download_id));
[email protected]70850c72011-01-11 17:31:27453 DCHECK(ContainsKey(active_downloads_, info->download_id));
454 DownloadItem* download = active_downloads_[info->download_id];
[email protected]c2e76012010-12-23 21:10:29455 DCHECK(download != NULL);
[email protected]70850c72011-01-11 17:31:27456 DCHECK(ContainsKey(downloads_, download));
457
[email protected]c2e76012010-12-23 21:10:29458 download->SetFileCheckResults(info->path,
459 info->is_dangerous,
460 info->path_uniquifier,
461 info->prompt_user_for_save_location,
462 info->is_extension_install,
463 info->original_name);
[email protected]aa033af2010-07-27 18:16:39464 in_progress_[info->download_id] = download;
[email protected]adb2f3d12011-01-23 16:24:54465 UpdateAppIcon(); // Reflect entry into in_progress_.
initial.commit09911bf2008-07-26 23:55:29466
[email protected]adb2f3d12011-01-23 16:24:54467 // Rename to intermediate name.
468 if (info->is_dangerous) {
469 // The download is not safe. We can now rename the file to its
470 // tentative name using OnFinalDownloadName (the actual final
471 // name after user confirmation will be set in
472 // ProceedWithFinishedDangerousDownload).
[email protected]ca4b5fa32010-10-09 12:42:18473 BrowserThread::PostTask(
474 BrowserThread::FILE, FROM_HERE,
[email protected]594cd7d2010-07-21 03:23:56475 NewRunnableMethod(
[email protected]0d7e79fa2010-10-08 23:35:47476 file_manager_, &DownloadFileManager::OnFinalDownloadName,
[email protected]adb2f3d12011-01-23 16:24:54477 download->id(), target_path, false,
[email protected]dc7cdcb92010-12-14 06:40:54478 make_scoped_refptr(this)));
[email protected]594cd7d2010-07-21 03:23:56479 } else {
[email protected]adb2f3d12011-01-23 16:24:54480 // The download is a safe download. We need to
481 // rename it to its intermediate '.crdownload' path. The final
482 // name after user confirmation will be set from
483 // DownloadItem::OnSafeDownloadFinished.
[email protected]594cd7d2010-07-21 03:23:56484 FilePath download_path = download_util::GetCrDownloadPath(target_path);
[email protected]ca4b5fa32010-10-09 12:42:18485 BrowserThread::PostTask(
486 BrowserThread::FILE, FROM_HERE,
[email protected]594cd7d2010-07-21 03:23:56487 NewRunnableMethod(
[email protected]0d7e79fa2010-10-08 23:35:47488 file_manager_, &DownloadFileManager::OnIntermediateDownloadName,
[email protected]dc7cdcb92010-12-14 06:40:54489 download->id(), download_path, make_scoped_refptr(this)));
[email protected]44b94b82010-11-08 20:49:18490 download->Rename(download_path);
[email protected]594cd7d2010-07-21 03:23:56491 }
492
[email protected]82f37b02010-07-29 22:04:57493 download_history_->AddEntry(*info, download,
494 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
initial.commit09911bf2008-07-26 23:55:29495}
496
initial.commit09911bf2008-07-26 23:55:29497void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
[email protected]70850c72011-01-11 17:31:27498 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
499 DownloadMap::iterator it = active_downloads_.find(download_id);
500 if (it != active_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29501 DownloadItem* download = it->second;
[email protected]70850c72011-01-11 17:31:27502 if (download->state() == DownloadItem::IN_PROGRESS) {
503 download->Update(size);
[email protected]adb2f3d12011-01-23 16:24:54504 UpdateAppIcon(); // Reflect size updates.
[email protected]70850c72011-01-11 17:31:27505 download_history_->UpdateEntry(download);
506 }
initial.commit09911bf2008-07-26 23:55:29507 }
508}
509
[email protected]a850ba42010-09-10 22:00:30510void DownloadManager::OnAllDataSaved(int32 download_id, int64 size) {
[email protected]da6e3922010-11-24 21:45:50511 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
512 << " size = " << size;
[email protected]9ccbb372008-10-10 18:50:32513
[email protected]c4f02c42011-01-24 21:55:06514 // If it's not in active_downloads_, that means it was cancelled; just
515 // ignore the notification.
516 if (active_downloads_.count(download_id) == 0)
517 return;
518
[email protected]adb2f3d12011-01-23 16:24:54519 DownloadItem* download = active_downloads_[download_id];
[email protected]a850ba42010-09-10 22:00:30520 download->OnAllDataSaved(size);
[email protected]9ccbb372008-10-10 18:50:32521
[email protected]adb2f3d12011-01-23 16:24:54522 MaybeCompleteDownload(download);
523}
[email protected]9ccbb372008-10-10 18:50:32524
[email protected]adb2f3d12011-01-23 16:24:54525bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
526 // If we don't have all the data, the download is not ready for
527 // completion.
528 if (!download->all_data_saved())
529 return false;
[email protected]6a7fb042010-02-01 16:30:47530
[email protected]adb2f3d12011-01-23 16:24:54531 // If the download isn't active (e.g. has been cancelled) it's not
532 // ready for completion.
533 if (active_downloads_.count(download->id()) == 0)
534 return false;
535
536 // If the download hasn't been inserted into the history system
537 // (which occurs strictly after file name determination, intermediate
538 // file rename, and UI display) then it's not ready for completion.
539 return (download->db_handle() != DownloadHistory::kUninitializedHandle);
540}
541
542void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
543 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
544 VLOG(20) << __FUNCTION__ << "()" << " download = "
545 << download->DebugString(false);
546
547 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32548 return;
[email protected]9ccbb372008-10-10 18:50:32549
[email protected]adb2f3d12011-01-23 16:24:54550 // TODO(rdsmith): DCHECK that we only pass through this point
551 // once per download. The natural way to do this is by a state
552 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56553
[email protected]adb2f3d12011-01-23 16:24:54554 // Confirm we're in the proper set of states to be here;
555 // in in_progress_, have all data, have a history handle.
556 DCHECK_EQ(1u, in_progress_.count(download->id()));
557 DCHECK(download->all_data_saved());
558 DCHECK(download->db_handle() != DownloadHistory::kUninitializedHandle);
559 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
560
561 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
562 << download->DebugString(false);
563
564 // Remove the id from in_progress
565 in_progress_.erase(download->id());
566 UpdateAppIcon(); // Reflect removal from in_progress_.
567
568 // Final update of download item and history.
569 download->MarkAsComplete();
570 download_history_->UpdateEntry(download);
571
572 switch (download->safety_state()) {
573 case DownloadItem::DANGEROUS:
574 // If this a dangerous download not yet validated by the user, don't do
575 // anything. When the user notifies us, it will trigger a call to
576 // ProceedWithFinishedDangerousDownload.
577 return;
578 case DownloadItem::DANGEROUS_BUT_VALIDATED:
579 // The dangerous download has been validated by the user. We first
580 // need to rename the downloaded file from its temporary name to
581 // its final name. We will continue the download processing in the
582 // callback.
583 BrowserThread::PostTask(
584 BrowserThread::FILE, FROM_HERE,
585 NewRunnableMethod(
586 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
587 download->db_handle(),
588 download->full_path(), download->target_name()));
589 return;
590 case DownloadItem::SAFE:
591 // The download is safe; just finish it.
592 download->OnSafeDownloadFinished(file_manager_);
593 return;
594 }
[email protected]9ccbb372008-10-10 18:50:32595}
596
[email protected]70850c72011-01-11 17:31:27597void DownloadManager::RemoveFromActiveList(int32 download_id) {
598 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
599 active_downloads_.erase(download_id);
600}
601
[email protected]8f783752009-04-01 23:33:45602void DownloadManager::DownloadRenamedToFinalName(int download_id,
603 const FilePath& full_path) {
[email protected]da6e3922010-11-24 21:45:50604 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
605 << " full_path = \"" << full_path.value() << "\"";
[email protected]ca4b5fa32010-10-09 12:42:18606 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]2e030682010-07-23 19:45:36607 DownloadItem* item = GetDownloadItem(download_id);
608 if (!item)
609 return;
[email protected]9246de32010-11-10 22:58:47610 item->OnDownloadRenamedToFinalName(full_path);
[email protected]8f783752009-04-01 23:33:45611}
612
[email protected]9ccbb372008-10-10 18:50:32613// Called on the file thread. Renames the downloaded file to its original name.
614void DownloadManager::ProceedWithFinishedDangerousDownload(
615 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41616 const FilePath& path,
617 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32618 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41619 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16620 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32621 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24622 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16623 // Make our name unique at this point, as if a dangerous file is downloading
624 // and a 2nd download is started for a file with the same name, they would
625 // have the same path. This is because we uniquify the name on download
626 // start, and at that time the first file does not exists yet, so the second
627 // file gets the same name.
[email protected]5a2388a2010-03-26 16:13:39628 uniquifier = download_util::GetUniquePathNumber(new_path);
[email protected]7a256ea2008-10-17 17:34:16629 if (uniquifier > 0)
[email protected]5a2388a2010-03-26 16:13:39630 download_util::AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32631 success = file_util::Move(path, new_path);
632 } else {
633 NOTREACHED();
634 }
[email protected]6cade212008-12-03 00:32:22635
[email protected]ca4b5fa32010-10-09 12:42:18636 BrowserThread::PostTask(
637 BrowserThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32638 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16639 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32640}
641
642// Call from the file thread when the finished dangerous download was renamed.
643void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
644 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41645 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16646 int new_path_uniquifier) {
[email protected]da6e3922010-11-24 21:45:50647 VLOG(20) << __FUNCTION__ << "()" << " download_handle = " << download_handle
648 << " success = " << success
649 << " new_path = \"" << new_path.value() << "\""
650 << " new_path_uniquifier = " << new_path_uniquifier;
[email protected]f04182f32010-12-10 19:12:07651 DownloadMap::iterator it = history_downloads_.find(download_handle);
652 if (it == history_downloads_.end()) {
[email protected]9ccbb372008-10-10 18:50:32653 NOTREACHED();
654 return;
655 }
656
657 DownloadItem* download = it->second;
658 // If we failed to rename the file, we'll just keep the name as is.
[email protected]7a256ea2008-10-17 17:34:16659 if (success) {
660 // We need to update the path uniquifier so that the UI shows the right
[email protected]44b94b82010-11-08 20:49:18661 // name when calling GetFileNameToReportUser().
[email protected]7a256ea2008-10-17 17:34:16662 download->set_path_uniquifier(new_path_uniquifier);
[email protected]9ccbb372008-10-10 18:50:32663 RenameDownload(download, new_path);
[email protected]7a256ea2008-10-17 17:34:16664 }
[email protected]9ccbb372008-10-10 18:50:32665
666 // Continue the download finished sequence.
[email protected]f04182f32010-12-10 19:12:07667 download->Finished();
initial.commit09911bf2008-07-26 23:55:29668}
669
initial.commit09911bf2008-07-26 23:55:29670void DownloadManager::DownloadCancelled(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27671 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29672 DownloadMap::iterator it = in_progress_.find(download_id);
673 if (it == in_progress_.end())
674 return;
675 DownloadItem* download = it->second;
676
[email protected]da6e3922010-11-24 21:45:50677 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
678 << " download = " << download->DebugString(true);
679
initial.commit09911bf2008-07-26 23:55:29680 // Clean up will happen when the history system create callback runs if we
681 // don't have a valid db_handle yet.
[email protected]82f37b02010-07-29 22:04:57682 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
initial.commit09911bf2008-07-26 23:55:29683 in_progress_.erase(it);
[email protected]70850c72011-01-11 17:31:27684 active_downloads_.erase(download_id);
[email protected]adb2f3d12011-01-23 16:24:54685 UpdateAppIcon(); // Reflect removal from in_progress_.
[email protected]82f37b02010-07-29 22:04:57686 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29687 }
688
[email protected]d7d1c5c2009-08-05 23:52:50689 DownloadCancelledInternal(download_id,
690 download->render_process_id(),
691 download->request_id());
692}
693
694void DownloadManager::DownloadCancelledInternal(int download_id,
695 int render_process_id,
696 int request_id) {
[email protected]d85cf072009-10-27 03:59:31697 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
[email protected]ca4b5fa32010-10-09 12:42:18698 BrowserThread::PostTask(
699 BrowserThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26700 NewRunnableFunction(&download_util::CancelDownloadRequest,
[email protected]d85cf072009-10-27 03:59:31701 g_browser_process->resource_dispatcher_host(),
702 render_process_id,
703 request_id));
[email protected]d7d1c5c2009-08-05 23:52:50704
[email protected]ca4b5fa32010-10-09 12:42:18705 BrowserThread::PostTask(
706 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37707 NewRunnableMethod(
708 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29709}
710
711void DownloadManager::PauseDownload(int32 download_id, bool pause) {
712 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]d85cf072009-10-27 03:59:31713 if (it == in_progress_.end())
714 return;
initial.commit09911bf2008-07-26 23:55:29715
[email protected]d85cf072009-10-27 03:59:31716 DownloadItem* download = it->second;
717 if (pause == download->is_paused())
718 return;
initial.commit09911bf2008-07-26 23:55:29719
[email protected]ca4b5fa32010-10-09 12:42:18720 BrowserThread::PostTask(
721 BrowserThread::IO, FROM_HERE,
[email protected]e2abdeb22010-09-03 19:56:15722 NewRunnableMethod(this,
723 &DownloadManager::PauseDownloadRequest,
724 g_browser_process->resource_dispatcher_host(),
[email protected]7ba53e12010-08-05 17:14:00725 download->render_process_id(),
726 download->request_id(),
727 pause));
[email protected]9ccbb372008-10-10 18:50:32728}
729
[email protected]6a7fb042010-02-01 16:30:47730void DownloadManager::UpdateAppIcon() {
[email protected]073ed7b2010-09-27 09:20:02731 if (status_updater_)
732 status_updater_->Update();
[email protected]6a7fb042010-02-01 16:30:47733}
734
[email protected]9ccbb372008-10-10 18:50:32735void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41736 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32737 download->Rename(new_path);
[email protected]82f37b02010-07-29 22:04:57738 download_history_->UpdateDownloadPath(download, new_path);
[email protected]9ccbb372008-10-10 18:50:32739}
740
[email protected]e2abdeb22010-09-03 19:56:15741void DownloadManager::PauseDownloadRequest(ResourceDispatcherHost* rdh,
742 int render_process_id,
743 int request_id,
744 bool pause) {
[email protected]ca4b5fa32010-10-09 12:42:18745 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
[email protected]e2abdeb22010-09-03 19:56:15746 rdh->PauseRequest(render_process_id, request_id, pause);
747}
748
initial.commit09911bf2008-07-26 23:55:29749void DownloadManager::RemoveDownload(int64 download_handle) {
[email protected]f04182f32010-12-10 19:12:07750 DownloadMap::iterator it = history_downloads_.find(download_handle);
751 if (it == history_downloads_.end())
initial.commit09911bf2008-07-26 23:55:29752 return;
753
754 // Make history update.
755 DownloadItem* download = it->second;
[email protected]82f37b02010-07-29 22:04:57756 download_history_->RemoveEntry(download);
initial.commit09911bf2008-07-26 23:55:29757
758 // Remove from our tables and delete.
[email protected]f04182f32010-12-10 19:12:07759 history_downloads_.erase(it);
760 int downloads_count = downloads_.erase(download);
761 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29762
763 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:28764 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:36765
766 delete download;
initial.commit09911bf2008-07-26 23:55:29767}
768
[email protected]e93d2822009-01-30 05:59:59769int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
770 const base::Time remove_end) {
[email protected]82f37b02010-07-29 22:04:57771 download_history_->RemoveEntriesBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29772
[email protected]a312a442010-12-15 23:40:33773 // All downloads visible to the user will be in the history,
774 // so scan that map.
[email protected]f04182f32010-12-10 19:12:07775 DownloadMap::iterator it = history_downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:28776 std::vector<DownloadItem*> pending_deletes;
[email protected]f04182f32010-12-10 19:12:07777 while (it != history_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29778 DownloadItem* download = it->second;
779 DownloadItem::DownloadState state = download->state();
780 if (download->start_time() >= remove_begin &&
781 (remove_end.is_null() || download->start_time() < remove_end) &&
782 (state == DownloadItem::COMPLETE ||
783 state == DownloadItem::CANCELLED)) {
784 // Remove from the map and move to the next in the list.
[email protected]f04182f32010-12-10 19:12:07785 history_downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:58786
787 // Also remove it from any completed dangerous downloads.
[email protected]78b8fcc92009-03-31 17:36:28788 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29789
initial.commit09911bf2008-07-26 23:55:29790 continue;
791 }
792
793 ++it;
794 }
795
[email protected]a312a442010-12-15 23:40:33796 // If we aren't deleting anything, we're done.
[email protected]57fd1252010-12-23 17:24:09797 if (pending_deletes.empty())
798 return 0;
initial.commit09911bf2008-07-26 23:55:29799
[email protected]a312a442010-12-15 23:40:33800 // Remove the chosen downloads from the main owning container.
801 for (std::vector<DownloadItem*>::iterator it = pending_deletes.begin();
802 it != pending_deletes.end(); it++) {
803 downloads_.erase(*it);
804 }
805
806 // Tell observers to refresh their views.
807 NotifyModelChanged();
808
809 // Delete the download items themselves.
[email protected]57fd1252010-12-23 17:24:09810 int num_deleted = static_cast<int>(pending_deletes.size());
811
[email protected]78b8fcc92009-03-31 17:36:28812 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
813 pending_deletes.clear();
814
initial.commit09911bf2008-07-26 23:55:29815 return num_deleted;
816}
817
[email protected]e93d2822009-01-30 05:59:59818int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
819 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29820}
821
[email protected]d41355e6f2009-04-07 21:21:12822int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:46823 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
824 // This is an incognito downloader. Clear All should clear main download
825 // manager as well.
826 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
827 }
[email protected]d41355e6f2009-04-07 21:21:12828 // The null times make the date range unbounded.
829 return RemoveDownloadsBetween(base::Time(), base::Time());
830}
831
[email protected]ec4826a2010-09-21 09:15:59832void DownloadManager::SavePageAsDownloadStarted(DownloadItem* download_item) {
[email protected]57fd1252010-12-23 17:24:09833#if !defined(NDEBUG)
834 save_page_as_downloads_.insert(download_item);
835#endif
[email protected]f04182f32010-12-10 19:12:07836 downloads_.insert(download_item);
[email protected]ec4826a2010-09-21 09:15:59837}
838
initial.commit09911bf2008-07-26 23:55:29839// Initiate a download of a specific URL. We send the request to the
840// ResourceDispatcherHost, and let it send us responses like a regular
841// download.
842void DownloadManager::DownloadUrl(const GURL& url,
843 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50844 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34845 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26846 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
847 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58848}
849
850void DownloadManager::DownloadUrlToFile(const GURL& url,
851 const GURL& referrer,
852 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32853 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58854 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34855 DCHECK(tab_contents);
[email protected]ca4b5fa32010-10-09 12:42:18856 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26857 NewRunnableFunction(&download_util::DownloadUrl,
858 url,
859 referrer,
860 referrer_charset,
861 save_info,
862 g_browser_process->resource_dispatcher_host(),
863 tab_contents->GetRenderProcessHost()->id(),
864 tab_contents->render_view_host()->routing_id(),
865 request_context_getter_));
initial.commit09911bf2008-07-26 23:55:29866}
867
initial.commit09911bf2008-07-26 23:55:29868void DownloadManager::AddObserver(Observer* observer) {
869 observers_.AddObserver(observer);
870 observer->ModelChanged();
871}
872
873void DownloadManager::RemoveObserver(Observer* observer) {
874 observers_.RemoveObserver(observer);
875}
876
[email protected]eccb9d12009-10-28 05:40:09877bool DownloadManager::ShouldOpenFileBasedOnExtension(
878 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:09879 FilePath::StringType extension = path.Extension();
880 if (extension.empty())
881 return false;
[email protected]92e11c82010-01-13 06:39:56882 if (Extension::IsExtension(path))
883 return false;
[email protected]eccb9d12009-10-28 05:40:09884 DCHECK(extension[0] == FilePath::kExtensionSeparator);
885 extension.erase(0, 1);
[email protected]e5dc4222010-08-30 22:16:32886 return download_prefs_->IsAutoOpenEnabledForExtension(extension);
initial.commit09911bf2008-07-26 23:55:29887}
888
[email protected]073ed7b2010-09-27 09:20:02889bool DownloadManager::IsDownloadProgressKnown() {
890 for (DownloadMap::iterator i = in_progress_.begin();
891 i != in_progress_.end(); ++i) {
892 if (i->second->total_bytes() <= 0)
893 return false;
894 }
895
896 return true;
897}
898
899int64 DownloadManager::GetInProgressDownloadCount() {
900 return in_progress_.size();
901}
902
903int64 DownloadManager::GetReceivedDownloadBytes() {
904 DCHECK(IsDownloadProgressKnown());
905 int64 received_bytes = 0;
906 for (DownloadMap::iterator i = in_progress_.begin();
907 i != in_progress_.end(); ++i) {
908 received_bytes += i->second->received_bytes();
909 }
910 return received_bytes;
911}
912
913int64 DownloadManager::GetTotalDownloadBytes() {
914 DCHECK(IsDownloadProgressKnown());
915 int64 total_bytes = 0;
916 for (DownloadMap::iterator i = in_progress_.begin();
917 i != in_progress_.end(); ++i) {
918 total_bytes += i->second->total_bytes();
919 }
920 return total_bytes;
921}
922
[email protected]561abe62009-04-06 18:08:34923void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:36924 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:29925 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]e6875c12010-07-18 11:14:13926 if (info->prompt_user_for_save_location)
[email protected]7ae7c2cb2009-01-06 23:31:41927 last_download_path_ = path.DirName();
[email protected]c2e76012010-12-23 21:10:29928 AttachDownloadItem(info, path);
initial.commit09911bf2008-07-26 23:55:29929}
930
931void DownloadManager::FileSelectionCanceled(void* params) {
932 // The user didn't pick a place to save the file, so need to cancel the
933 // download that's already in progress to the temporary location.
934 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:50935 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:45936 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:50937 info->request_id);
initial.commit09911bf2008-07-26 23:55:29938}
939
[email protected]9ccbb372008-10-10 18:50:32940void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
941 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
942 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
943 download->UpdateObservers();
944
945 // If the download is not complete, nothing to do. The required
946 // post-processing will be performed when it does complete.
947 if (download->state() != DownloadItem::COMPLETE)
948 return;
949
[email protected]ca4b5fa32010-10-09 12:42:18950 BrowserThread::PostTask(
951 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37952 NewRunnableMethod(
953 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
954 download->db_handle(), download->full_path(),
[email protected]44b94b82010-11-08 20:49:18955 download->target_name()));
[email protected]9ccbb372008-10-10 18:50:32956}
957
initial.commit09911bf2008-07-26 23:55:29958// Operations posted to us from the history service ----------------------------
959
960// The history service has retrieved all download entries. 'entries' contains
961// 'DownloadCreateInfo's in sorted order (by ascending start_time).
962void DownloadManager::OnQueryDownloadEntriesComplete(
963 std::vector<DownloadCreateInfo>* entries) {
964 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:39965 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]f04182f32010-12-10 19:12:07966 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
967 downloads_.insert(download);
968 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:50969 VLOG(20) << __FUNCTION__ << "()" << i << ">"
970 << " download = " << download->DebugString(true);
initial.commit09911bf2008-07-26 23:55:29971 }
[email protected]b0ab1d42010-02-24 19:29:28972 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:29973}
974
initial.commit09911bf2008-07-26 23:55:29975// Once the new DownloadItem's creation info has been committed to the history
976// service, we associate the DownloadItem with the db handle, update our
[email protected]f04182f32010-12-10 19:12:07977// 'history_downloads_' map and inform observers.
[email protected]9f5cb562010-11-08 22:06:59978void DownloadManager::OnCreateDownloadEntryComplete(
[email protected]76d8b622010-11-11 19:50:05979 DownloadCreateInfo info,
[email protected]9f5cb562010-11-08 22:06:59980 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:27981 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29982 DownloadMap::iterator it = in_progress_.find(info.download_id);
983 DCHECK(it != in_progress_.end());
984
985 DownloadItem* download = it->second;
[email protected]da6e3922010-11-24 21:45:50986 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
987 << " download_id = " << info.download_id
988 << " download = " << download->DebugString(true);
[email protected]d2a8fb72010-01-21 05:31:42989
990 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
991 // call this function with an invalid |db_handle|. For instance, this can
992 // happen when the history database is offline. We cannot have multiple
993 // DownloadItems with the same invalid db_handle, so we need to assign a
994 // unique |db_handle| here.
[email protected]82f37b02010-07-29 22:04:57995 if (db_handle == DownloadHistory::kUninitializedHandle)
996 db_handle = download_history_->GetNextFakeDbHandle();
[email protected]d2a8fb72010-01-21 05:31:42997
[email protected]82f37b02010-07-29 22:04:57998 DCHECK(download->db_handle() == DownloadHistory::kUninitializedHandle);
initial.commit09911bf2008-07-26 23:55:29999 download->set_db_handle(db_handle);
1000
1001 // Insert into our full map.
[email protected]70850c72011-01-11 17:31:271002 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
[email protected]f04182f32010-12-10 19:12:071003 history_downloads_[download->db_handle()] = download;
initial.commit09911bf2008-07-26 23:55:291004
[email protected]70850c72011-01-11 17:31:271005 // Show in the appropriate browser UI.
[email protected]5e595482009-05-06 20:16:531006 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291007
1008 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281009 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291010
[email protected]adb2f3d12011-01-23 16:24:541011 // If this download has been cancelled before we've received the DB handle,
initial.commit09911bf2008-07-26 23:55:291012 // post one final message to the history service so that it can be properly
1013 // in sync with the DownloadItem's completion status, and also inform any
1014 // observers so that they get more than just the start notification.
[email protected]adb2f3d12011-01-23 16:24:541015 //
1016 // Otherwise, try to complete the download
initial.commit09911bf2008-07-26 23:55:291017 if (download->state() != DownloadItem::IN_PROGRESS) {
[email protected]adb2f3d12011-01-23 16:24:541018 DCHECK_EQ(DownloadItem::CANCELLED, download->state());
initial.commit09911bf2008-07-26 23:55:291019 in_progress_.erase(it);
[email protected]70850c72011-01-11 17:31:271020 active_downloads_.erase(info.download_id);
[email protected]82f37b02010-07-29 22:04:571021 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:291022 download->UpdateObservers();
[email protected]adb2f3d12011-01-23 16:24:541023 } else {
1024 MaybeCompleteDownload(download);
initial.commit09911bf2008-07-26 23:55:291025 }
1026}
1027
[email protected]5e595482009-05-06 20:16:531028void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1029 DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341030 // The 'contents' may no longer exist if the user closed the tab before we
1031 // get this start completion event. If it does, tell the origin TabContents
1032 // to display its download shelf.
[email protected]76543b92009-08-31 17:27:451033 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1034 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531035
1036 // If the contents no longer exists, we start the download in the last active
1037 // browser. This is not ideal but better than fully hiding the download from
1038 // the user.
1039 if (!contents) {
1040 Browser* last_active = BrowserList::GetLastActive();
1041 if (last_active)
1042 contents = last_active->GetSelectedTabContents();
1043 }
1044
1045 if (contents)
1046 contents->OnStartDownload(download);
1047}
1048
[email protected]6cade212008-12-03 00:32:221049// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121050void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411051 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381052}
[email protected]b0ab1d42010-02-24 19:29:281053
1054void DownloadManager::NotifyModelChanged() {
1055 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1056}
1057
[email protected]2e030682010-07-23 19:45:361058DownloadItem* DownloadManager::GetDownloadItem(int id) {
[email protected]f04182f32010-12-10 19:12:071059 for (DownloadMap::iterator it = history_downloads_.begin();
1060 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:361061 DownloadItem* item = it->second;
1062 if (item->id() == id)
1063 return item;
1064 }
1065 return NULL;
1066}
1067
[email protected]57fd1252010-12-23 17:24:091068// Confirm that everything in all maps is also in |downloads_|, and that
1069// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:071070void DownloadManager::AssertContainersConsistent() const {
1071#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:091072 // Turn everything into sets.
[email protected]adb2f3d12011-01-23 16:24:541073 DownloadSet active_set, history_set;
[email protected]70850c72011-01-11 17:31:271074 const DownloadMap* input_maps[] = {&active_downloads_, &history_downloads_};
[email protected]adb2f3d12011-01-23 16:24:541075 DownloadSet* local_sets[] = {&active_set, &history_set};
[email protected]57fd1252010-12-23 17:24:091076 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(local_sets));
1077 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
1078 for (DownloadMap::const_iterator it = input_maps[i]->begin();
1079 it != input_maps[i]->end(); it++) {
1080 local_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:071081 }
1082 }
[email protected]57fd1252010-12-23 17:24:091083
1084 // Check if each set is fully present in downloads, and create a union.
[email protected]adb2f3d12011-01-23 16:24:541085 const DownloadSet* all_sets[] = {&active_set, &history_set,
[email protected]57fd1252010-12-23 17:24:091086 &save_page_as_downloads_};
1087 DownloadSet downloads_union;
1088 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
1089 DownloadSet remainder;
1090 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
1091 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
1092 downloads_.begin(), downloads_.end(),
1093 insert_it);
1094 DCHECK(remainder.empty());
1095 std::insert_iterator<DownloadSet>
1096 insert_union(downloads_union, downloads_union.end());
1097 std::set_union(downloads_union.begin(), downloads_union.end(),
1098 all_sets[i]->begin(), all_sets[i]->end(),
1099 insert_union);
1100 }
1101
1102 // Is everything in downloads_ present in one of the other sets?
1103 DownloadSet remainder;
1104 std::insert_iterator<DownloadSet>
1105 insert_remainder(remainder, remainder.begin());
1106 std::set_difference(downloads_.begin(), downloads_.end(),
1107 downloads_union.begin(), downloads_union.end(),
1108 insert_remainder);
1109 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071110#endif
1111}
1112
[email protected]b0ab1d42010-02-24 19:29:281113// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1114
1115DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1116 DownloadManager* observing_download_manager)
1117 : observing_download_manager_(observing_download_manager),
1118 observed_download_manager_(NULL) {
1119 if (observing_download_manager->profile_->GetOriginalProfile() ==
1120 observing_download_manager->profile_) {
1121 return;
1122 }
1123
1124 observed_download_manager_ = observing_download_manager_->
1125 profile_->GetOriginalProfile()->GetDownloadManager();
1126 observed_download_manager_->AddObserver(this);
1127}
1128
1129DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1130 if (observed_download_manager_)
1131 observed_download_manager_->RemoveObserver(this);
1132}
1133
1134void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1135 observing_download_manager_->NotifyModelChanged();
1136}
1137
[email protected]b0ab1d42010-02-24 19:29:281138void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1139 observed_download_manager_ = NULL;
1140}