blob: e50371bc38b1f8007babfb89c3d76528caaeec1d [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]cd448092010-12-06 23:49:1320#include "chrome/browser/download/download_extensions.h"
[email protected]6c69796d2010-07-16 21:41:1621#include "chrome/browser/download/download_file_manager.h"
[email protected]82f37b02010-07-29 22:04:5722#include "chrome/browser/download/download_history.h"
[email protected]6c69796d2010-07-16 21:41:1623#include "chrome/browser/download/download_item.h"
[email protected]e5dc4222010-08-30 22:16:3224#include "chrome/browser/download/download_prefs.h"
[email protected]287b86b2011-02-26 00:11:3525#include "chrome/browser/download/download_safe_browsing_client.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]d2a8fb72010-01-21 05:31:4233#include "chrome/browser/tab_contents/tab_util.h"
[email protected]7b5dc002010-11-16 23:08:1034#include "chrome/browser/ui/browser.h"
initial.commit09911bf2008-07-26 23:55:2935#include "chrome/common/chrome_paths.h"
[email protected]91e1bd82009-09-03 22:04:4036#include "chrome/common/notification_type.h"
[email protected]7324d1d2011-03-01 05:02:1637#include "content/browser/browser_thread.h"
38#include "content/browser/renderer_host/render_process_host.h"
39#include "content/browser/renderer_host/render_view_host.h"
40#include "content/browser/renderer_host/resource_dispatcher_host.h"
41#include "content/browser/tab_contents/tab_contents.h"
[email protected]46072d42008-07-28 14:49:3542#include "googleurl/src/gurl.h"
[email protected]34ac8f32009-02-22 23:03:2743#include "grit/generated_resources.h"
[email protected]21ca982c2010-01-26 22:49:5544#include "grit/theme_resources.h"
initial.commit09911bf2008-07-26 23:55:2945#include "net/base/mime_util.h"
46#include "net/base/net_util.h"
[email protected]c051a1b2011-01-21 23:30:1747#include "ui/base/l10n/l10n_util.h"
[email protected]42ce29d2011-01-20 23:19:4648#include "ui/base/resource/resource_bundle.h"
initial.commit09911bf2008-07-26 23:55:2949
[email protected]073ed7b2010-09-27 09:20:0250DownloadManager::DownloadManager(DownloadStatusUpdater* status_updater)
initial.commit09911bf2008-07-26 23:55:2951 : shutdown_needed_(false),
52 profile_(NULL),
[email protected]073ed7b2010-09-27 09:20:0253 file_manager_(NULL),
[email protected]a3d2bc42010-10-06 14:08:4954 status_updater_(status_updater->AsWeakPtr()) {
[email protected]073ed7b2010-09-27 09:20:0255 if (status_updater_)
56 status_updater_->AddDelegate(this);
initial.commit09911bf2008-07-26 23:55:2957}
58
59DownloadManager::~DownloadManager() {
[email protected]326a6a92010-09-10 20:21:1360 DCHECK(!shutdown_needed_);
[email protected]073ed7b2010-09-27 09:20:0261 if (status_updater_)
62 status_updater_->RemoveDelegate(this);
initial.commit09911bf2008-07-26 23:55:2963}
64
65void DownloadManager::Shutdown() {
[email protected]da6e3922010-11-24 21:45:5066 VLOG(20) << __FUNCTION__ << "()"
67 << " shutdown_needed_ = " << shutdown_needed_;
[email protected]326a6a92010-09-10 20:21:1368 if (!shutdown_needed_)
69 return;
70 shutdown_needed_ = false;
initial.commit09911bf2008-07-26 23:55:2971
[email protected]326a6a92010-09-10 20:21:1372 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
73
74 if (file_manager_) {
[email protected]ca4b5fa32010-10-09 12:42:1875 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
[email protected]326a6a92010-09-10 20:21:1376 NewRunnableMethod(file_manager_,
77 &DownloadFileManager::OnDownloadManagerShutdown,
[email protected]dc7cdcb92010-12-14 06:40:5478 make_scoped_refptr(this)));
[email protected]326a6a92010-09-10 20:21:1379 }
initial.commit09911bf2008-07-26 23:55:2980
[email protected]f04182f32010-12-10 19:12:0781 AssertContainersConsistent();
82
83 // Go through all downloads in downloads_. Dangerous ones we need to
84 // remove on disk, and in progress ones we need to cancel.
[email protected]57fd1252010-12-23 17:24:0985 for (DownloadSet::iterator it = downloads_.begin(); it != downloads_.end();) {
[email protected]f04182f32010-12-10 19:12:0786 DownloadItem* download = *it;
87
88 // Save iterator from potential erases in this set done by called code.
89 // Iterators after an erasure point are still valid for lists and
90 // associative containers such as sets.
91 it++;
92
93 if (download->safety_state() == DownloadItem::DANGEROUS &&
94 (download->state() == DownloadItem::IN_PROGRESS ||
95 download->state() == DownloadItem::COMPLETE)) {
96 // The user hasn't accepted it, so we need to remove it
97 // from the disk. This may or may not result in it being
98 // removed from the DownloadManager queues and deleted
99 // (specifically, DownloadManager::RemoveDownload only
100 // removes and deletes it if it's known to the history service)
101 // so the only thing we know after calling this function is that
102 // the download was deleted if-and-only-if it was removed
103 // from all queues.
104 download->Remove(true);
105 } else if (download->state() == DownloadItem::IN_PROGRESS) {
106 download->Cancel(false);
107 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29108 }
109 }
110
[email protected]f04182f32010-12-10 19:12:07111 // At this point, all dangerous downloads have had their files removed
112 // and all in progress downloads have been cancelled. We can now delete
113 // anything left.
114 STLDeleteElements(&downloads_);
[email protected]9ccbb372008-10-10 18:50:32115
[email protected]f04182f32010-12-10 19:12:07116 // And clear all non-owning containers.
initial.commit09911bf2008-07-26 23:55:29117 in_progress_.clear();
[email protected]70850c72011-01-11 17:31:27118 active_downloads_.clear();
[email protected]57fd1252010-12-23 17:24:09119#if !defined(NDEBUG)
120 save_page_as_downloads_.clear();
121#endif
initial.commit09911bf2008-07-26 23:55:29122
123 file_manager_ = NULL;
124
initial.commit09911bf2008-07-26 23:55:29125 // Make sure the save as dialog doesn't notify us back if we're gone before
126 // it returns.
127 if (select_file_dialog_.get())
128 select_file_dialog_->ListenerDestroyed();
129
[email protected]82f37b02010-07-29 22:04:57130 download_history_.reset();
[email protected]68a49e52011-01-28 10:39:51131 download_prefs_.reset();
[email protected]82f37b02010-07-29 22:04:57132
[email protected]2c93f6f2010-11-08 20:41:17133 request_context_getter_ = NULL;
134
initial.commit09911bf2008-07-26 23:55:29135 shutdown_needed_ = false;
136}
137
[email protected]82f37b02010-07-29 22:04:57138void DownloadManager::GetTemporaryDownloads(
139 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
140 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58141
[email protected]f04182f32010-12-10 19:12:07142 for (DownloadMap::iterator it = history_downloads_.begin();
143 it != history_downloads_.end(); ++it) {
[email protected]6aa4a1c02010-01-15 18:49:58144 if (it->second->is_temporary() &&
145 it->second->full_path().DirName() == dir_path)
[email protected]82f37b02010-07-29 22:04:57146 result->push_back(it->second);
[email protected]6aa4a1c02010-01-15 18:49:58147 }
[email protected]6aa4a1c02010-01-15 18:49:58148}
149
[email protected]82f37b02010-07-29 22:04:57150void DownloadManager::GetAllDownloads(
151 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
152 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34153
[email protected]f04182f32010-12-10 19:12:07154 for (DownloadMap::iterator it = history_downloads_.begin();
155 it != history_downloads_.end(); ++it) {
[email protected]8ddbd66a2010-05-21 16:38:34156 if (!it->second->is_temporary() &&
157 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57158 result->push_back(it->second);
[email protected]8ddbd66a2010-05-21 16:38:34159 }
[email protected]8ddbd66a2010-05-21 16:38:34160}
161
[email protected]82f37b02010-07-29 22:04:57162void DownloadManager::GetCurrentDownloads(
163 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
164 DCHECK(result);
[email protected]c4a530b2010-03-08 17:33:03165
[email protected]f04182f32010-12-10 19:12:07166 for (DownloadMap::iterator it = history_downloads_.begin();
167 it != history_downloads_.end(); ++it) {
[email protected]c4a530b2010-03-08 17:33:03168 if (!it->second->is_temporary() &&
169 (it->second->state() == DownloadItem::IN_PROGRESS ||
170 it->second->safety_state() == DownloadItem::DANGEROUS) &&
171 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57172 result->push_back(it->second);
[email protected]c4a530b2010-03-08 17:33:03173 }
[email protected]f7e9fd62010-09-28 15:45:06174
175 // If we have a parent profile, let it add its downloads to the results.
176 Profile* original_profile = profile_->GetOriginalProfile();
177 if (original_profile != profile_)
178 original_profile->GetDownloadManager()->GetCurrentDownloads(dir_path,
179 result);
[email protected]c4a530b2010-03-08 17:33:03180}
181
[email protected]d3b12902010-08-16 23:39:42182void DownloadManager::SearchDownloads(const string16& query,
183 std::vector<DownloadItem*>* result) {
184 DCHECK(result);
185
186 string16 query_lower(l10n_util::ToLower(query));
187
[email protected]f04182f32010-12-10 19:12:07188 for (DownloadMap::iterator it = history_downloads_.begin();
189 it != history_downloads_.end(); ++it) {
[email protected]d3b12902010-08-16 23:39:42190 DownloadItem* download_item = it->second;
191
192 if (download_item->is_temporary() || download_item->is_extension_install())
193 continue;
194
195 // Display Incognito downloads only in Incognito window, and vice versa.
196 // The Incognito Downloads page will get the list of non-Incognito downloads
197 // from its parent profile.
198 if (profile_->IsOffTheRecord() != download_item->is_otr())
199 continue;
200
201 if (download_item->MatchesQuery(query_lower))
202 result->push_back(download_item);
203 }
204
205 // If we have a parent profile, let it add its downloads to the results.
206 Profile* original_profile = profile_->GetOriginalProfile();
207 if (original_profile != profile_)
208 original_profile->GetDownloadManager()->SearchDownloads(query, result);
209}
210
initial.commit09911bf2008-07-26 23:55:29211// Query the history service for information about all persisted downloads.
212bool DownloadManager::Init(Profile* profile) {
213 DCHECK(profile);
214 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
215 shutdown_needed_ = true;
216
217 profile_ = profile;
[email protected]be180c802009-10-23 06:33:31218 request_context_getter_ = profile_->GetRequestContext();
[email protected]d3b12902010-08-16 23:39:42219 download_history_.reset(new DownloadHistory(profile));
[email protected]82f37b02010-07-29 22:04:57220 download_history_->Load(
221 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
[email protected]024f2f02010-04-30 22:51:46222
[email protected]e5dc4222010-08-30 22:16:32223 download_prefs_.reset(new DownloadPrefs(profile_->GetPrefs()));
224
[email protected]2941c2392010-07-15 22:54:30225 // In test mode, there may be no ResourceDispatcherHost. In this case it's
226 // safe to avoid setting |file_manager_| because we only call a small set of
227 // functions, none of which need it.
initial.commit09911bf2008-07-26 23:55:29228 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]2941c2392010-07-15 22:54:30229 if (rdh) {
230 file_manager_ = rdh->download_file_manager();
231 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29232 }
233
[email protected]b0ab1d42010-02-24 19:29:28234 other_download_manager_observer_.reset(
235 new OtherDownloadManagerObserver(this));
236
initial.commit09911bf2008-07-26 23:55:29237 return true;
238}
239
initial.commit09911bf2008-07-26 23:55:29240// We have received a message from DownloadFileManager about a new download. We
241// create a download item and store it in our download map, and inform the
242// history system of a new download. Since this method can be called while the
243// history service thread is still reading the persistent state, we do not
[email protected]f04182f32010-12-10 19:12:07244// insert the new DownloadItem into 'history_downloads_' or inform our
[email protected]adb2f3d12011-01-23 16:24:54245// observers at this point. OnCreateDownloadEntryComplete() handles that
[email protected]f04182f32010-12-10 19:12:07246// finalization of the the download creation as a callback from the
247// history thread.
initial.commit09911bf2008-07-26 23:55:29248void DownloadManager::StartDownload(DownloadCreateInfo* info) {
[email protected]ca4b5fa32010-10-09 12:42:18249 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]287b86b2011-02-26 00:11:35250
251 // Create a client to verify download URL with safebrowsing.
252 // It deletes itself after the callback.
253 scoped_refptr<DownloadSBClient> sb_client = new DownloadSBClient(info);
254 sb_client->CheckDownloadUrl(
255 NewCallback(this, &DownloadManager::CheckDownloadUrlDone));
256}
257
258void DownloadManager::CheckDownloadUrlDone(DownloadCreateInfo* info,
259 bool is_dangerous_url) {
260 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29261 DCHECK(info);
262
[email protected]287b86b2011-02-26 00:11:35263 info->is_dangerous_url = is_dangerous_url;
264
[email protected]a60c8ae2009-12-25 06:50:57265 // Check whether this download is for an extension install or not.
[email protected]e6875c12010-07-18 11:14:13266 // Allow extensions to be explicitly saved.
267 if (!info->prompt_user_for_save_location) {
[email protected]a60c8ae2009-12-25 06:50:57268 if (UserScript::HasUserScriptFileExtension(info->url) ||
269 info->mime_type == Extension::kMimeType)
270 info->is_extension_install = true;
271 }
272
[email protected]8af9d032010-02-10 00:00:32273 if (info->save_info.file_path.empty()) {
[email protected]2941c2392010-07-15 22:54:30274 FilePath generated_name;
[email protected]7ba53e12010-08-05 17:14:00275 download_util::GenerateFileNameFromInfo(info, &generated_name);
[email protected]2941c2392010-07-15 22:54:30276
277 // Freeze the user's preference for showing a Save As dialog. We're going
278 // to bounce around a bunch of threads and we don't want to worry about race
279 // conditions where the user changes this pref out from under us.
[email protected]0e9b6072011-02-17 12:42:05280 if (download_prefs_->PromptForDownload()) {
[email protected]2941c2392010-07-15 22:54:30281 // But ignore the user's preference for the following scenarios:
282 // 1) Extension installation. Note that we only care here about the case
283 // where an extension is installed, not when one is downloaded with
284 // "save as...".
285 // 2) Filetypes marked "always open." If the user just wants this file
286 // opened, don't bother asking where to keep it.
287 if (!info->is_extension_install &&
288 !ShouldOpenFileBasedOnExtension(generated_name))
[email protected]e6875c12010-07-18 11:14:13289 info->prompt_user_for_save_location = true;
[email protected]2941c2392010-07-15 22:54:30290 }
[email protected]14e0a102011-02-22 14:04:01291 if (download_prefs_->IsDownloadPathManaged()) {
292 info->prompt_user_for_save_location = false;
293 }
[email protected]2941c2392010-07-15 22:54:30294
[email protected]8af9d032010-02-10 00:00:32295 // Determine the proper path for a download, by either one of the following:
296 // 1) using the default download directory.
297 // 2) prompting the user.
[email protected]ccea03c2010-12-17 03:31:50298 if (info->prompt_user_for_save_location && !last_download_path_.empty()) {
[email protected]8af9d032010-02-10 00:00:32299 info->suggested_path = last_download_path_;
[email protected]80dc3612010-07-27 19:35:08300 } else {
[email protected]e5dc4222010-08-30 22:16:32301 info->suggested_path = download_prefs_->download_path();
[email protected]80dc3612010-07-27 19:35:08302 }
[email protected]8af9d032010-02-10 00:00:32303 info->suggested_path = info->suggested_path.Append(generated_name);
304 } else {
305 info->suggested_path = info->save_info.file_path;
306 }
initial.commit09911bf2008-07-26 23:55:29307
[email protected]e6875c12010-07-18 11:14:13308 if (!info->prompt_user_for_save_location &&
309 info->save_info.file_path.empty()) {
[email protected]287b86b2011-02-26 00:11:35310 info->is_dangerous_file = download_util::IsDangerous(
[email protected]b580f25e2011-01-29 05:06:17311 info, profile(), ShouldOpenFileBasedOnExtension(info->suggested_path));
[email protected]e9ebf3fc2008-10-17 22:06:58312 }
313
initial.commit09911bf2008-07-26 23:55:29314 // We need to move over to the download thread because we don't want to stat
315 // the suggested path on the UI thread.
[email protected]5a3b97e2010-10-05 09:49:11316 // We can only access preferences on the UI thread, so check the download path
317 // now and pass the value to the FILE thread.
[email protected]ca4b5fa32010-10-09 12:42:18318 BrowserThread::PostTask(
319 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37320 NewRunnableMethod(
[email protected]5a3b97e2010-10-05 09:49:11321 this,
322 &DownloadManager::CheckIfSuggestedPathExists,
323 info,
324 download_prefs()->download_path()));
initial.commit09911bf2008-07-26 23:55:29325}
326
[email protected]5a3b97e2010-10-05 09:49:11327void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info,
328 const FilePath& default_path) {
[email protected]ca4b5fa32010-10-09 12:42:18329 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
initial.commit09911bf2008-07-26 23:55:29330 DCHECK(info);
331
[email protected]5a3b97e2010-10-05 09:49:11332 // Make sure the default download directory exists.
333 // TODO(phajdan.jr): only create the directory when we're sure the user
334 // is going to save there and not to another directory of his choice.
335 file_util::CreateDirectory(default_path);
336
initial.commit09911bf2008-07-26 23:55:29337 // Check writability of the suggested path. If we can't write to it, default
338 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]7ae7c2cb2009-01-06 23:31:41339 FilePath dir = info->suggested_path.DirName();
340 FilePath filename = info->suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32341 if (!file_util::PathIsWritable(dir)) {
[email protected]da6e3922010-11-24 21:45:50342 VLOG(1) << "Unable to write to directory \"" << dir.value() << "\"";
[email protected]e6875c12010-07-18 11:14:13343 info->prompt_user_for_save_location = true;
initial.commit09911bf2008-07-26 23:55:29344 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
[email protected]7ae7c2cb2009-01-06 23:31:41345 info->suggested_path = info->suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29346 }
347
[email protected]6cade212008-12-03 00:32:22348 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]287b86b2011-02-26 00:11:35349 if (info->IsDangerous()) {
[email protected]7ae7c2cb2009-01-06 23:31:41350 info->original_name = FilePath(info->suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32351 // Create a temporary file to hold the file until the user approves its
352 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41353 FilePath::StringType file_name;
354 FilePath path;
[email protected]463e1b432011-01-21 22:05:51355#if defined(OS_WIN)
356 string16 unconfirmed_prefix =
357 l10n_util::GetStringUTF16(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
358#else
359 std::string unconfirmed_prefix =
360 l10n_util::GetStringUTF8(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
361#endif
362
[email protected]9ccbb372008-10-10 18:50:32363 while (path.empty()) {
[email protected]2594c2b2010-11-08 23:04:26364 base::SStringPrintf(
365 &file_name,
[email protected]463e1b432011-01-21 22:05:51366 unconfirmed_prefix.append(
367 FILE_PATH_LITERAL(" %d.crdownload")).c_str(),
[email protected]2594c2b2010-11-08 23:04:26368 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41369 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07370 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41371 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32372 }
373 info->suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16374 } else {
[email protected]594cd7d2010-07-21 03:23:56375 // Do not add the path uniquifier if we are saving to a specific path as in
376 // the drag-out case.
377 if (info->save_info.file_path.empty()) {
378 info->path_uniquifier = download_util::GetUniquePathNumberWithCrDownload(
379 info->suggested_path);
380 }
[email protected]7a256ea2008-10-17 17:34:16381 // We know the final path, build it if necessary.
382 if (info->path_uniquifier > 0) {
[email protected]5a2388a2010-03-26 16:13:39383 download_util::AppendNumberToPath(&(info->suggested_path),
384 info->path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16385 // Setting path_uniquifier to 0 to make sure we don't try to unique it
386 // later on.
387 info->path_uniquifier = 0;
[email protected]7d3851d82008-12-12 03:26:07388 } else if (info->path_uniquifier == -1) {
389 // We failed to find a unique path. We have to prompt the user.
[email protected]da6e3922010-11-24 21:45:50390 VLOG(1) << "Unable to find a unique path for suggested path \""
[email protected]287b86b2011-02-26 00:11:35391 << info->suggested_path.value() << "\"";
[email protected]e6875c12010-07-18 11:14:13392 info->prompt_user_for_save_location = true;
[email protected]7a256ea2008-10-17 17:34:16393 }
[email protected]9ccbb372008-10-10 18:50:32394 }
395
[email protected]594cd7d2010-07-21 03:23:56396 // Create an empty file at the suggested path so that we don't allocate the
397 // same "non-existant" path to multiple downloads.
398 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]e6875c12010-07-18 11:14:13399 if (!info->prompt_user_for_save_location &&
400 info->save_info.file_path.empty()) {
[email protected]287b86b2011-02-26 00:11:35401 if (info->IsDangerous())
[email protected]594cd7d2010-07-21 03:23:56402 file_util::WriteFile(info->suggested_path, "", 0);
403 else
404 file_util::WriteFile(download_util::GetCrDownloadPath(
405 info->suggested_path), "", 0);
[email protected]7d3851d82008-12-12 03:26:07406 }
407
[email protected]ca4b5fa32010-10-09 12:42:18408 BrowserThread::PostTask(
409 BrowserThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29410 NewRunnableMethod(this,
411 &DownloadManager::OnPathExistenceAvailable,
412 info));
413}
414
415void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
[email protected]da6e3922010-11-24 21:45:50416 VLOG(20) << __FUNCTION__ << "()" << " info = " << info->DebugString();
[email protected]ca4b5fa32010-10-09 12:42:18417 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29418 DCHECK(info);
419
[email protected]e6875c12010-07-18 11:14:13420 if (info->prompt_user_for_save_location) {
initial.commit09911bf2008-07-26 23:55:29421 // We must ask the user for the place to put the download.
422 if (!select_file_dialog_.get())
423 select_file_dialog_ = SelectFileDialog::Create(this);
424
[email protected]76543b92009-08-31 17:27:45425 TabContents* contents = tab_util::GetTabContentsByID(info->child_id,
426 info->render_view_id);
[email protected]b949f1112009-04-12 20:03:08427 SelectFileDialog::FileTypeInfo file_type_info;
428 file_type_info.extensions.resize(1);
429 file_type_info.extensions[0].push_back(info->suggested_path.Extension());
[email protected]15bc8052009-04-17 19:57:24430 if (!file_type_info.extensions[0][0].empty())
431 file_type_info.extensions[0][0].erase(0, 1); // drop the .
[email protected]b949f1112009-04-12 20:03:08432 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23433 gfx::NativeWindow owning_window =
434 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
initial.commit09911bf2008-07-26 23:55:29435 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34436 string16(),
437 info->suggested_path,
[email protected]b949f1112009-04-12 20:03:08438 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]0f44d3e2009-03-12 23:36:30439 owning_window, info);
[email protected]ac167ce2010-11-24 17:59:48440 FOR_EACH_OBSERVER(Observer, observers_, SelectFileDialogDisplayed());
initial.commit09911bf2008-07-26 23:55:29441 } else {
442 // No prompting for download, just continue with the suggested name.
[email protected]287b86b2011-02-26 00:11:35443 info->path = info->suggested_path;
444 AttachDownloadItem(info);
initial.commit09911bf2008-07-26 23:55:29445 }
446}
447
[email protected]c2e76012010-12-23 21:10:29448void DownloadManager::CreateDownloadItem(DownloadCreateInfo* info) {
449 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
450
451 DownloadItem* download = new DownloadItem(this, *info,
452 profile_->IsOffTheRecord());
453 DCHECK(!ContainsKey(in_progress_, info->download_id));
[email protected]70850c72011-01-11 17:31:27454 DCHECK(!ContainsKey(active_downloads_, info->download_id));
[email protected]c2e76012010-12-23 21:10:29455 downloads_.insert(download);
[email protected]70850c72011-01-11 17:31:27456 active_downloads_[info->download_id] = download;
[email protected]c2e76012010-12-23 21:10:29457}
458
[email protected]287b86b2011-02-26 00:11:35459void DownloadManager::AttachDownloadItem(DownloadCreateInfo* info) {
[email protected]adb2f3d12011-01-23 16:24:54460 VLOG(20) << __FUNCTION__ << "()" << " info = " << info->DebugString();
461
[email protected]ca4b5fa32010-10-09 12:42:18462 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]aa033af2010-07-27 18:16:39463
[email protected]287b86b2011-02-26 00:11:35464 // Life of |info| ends here. No more references to it after this method.
initial.commit09911bf2008-07-26 23:55:29465 scoped_ptr<DownloadCreateInfo> infop(info);
initial.commit09911bf2008-07-26 23:55:29466
[email protected]70850c72011-01-11 17:31:27467 // NOTE(ahendrickson) Eventually |active_downloads_| will replace
468 // |in_progress_|, but we don't want to change the semantics yet.
[email protected]aa033af2010-07-27 18:16:39469 DCHECK(!ContainsKey(in_progress_, info->download_id));
[email protected]70850c72011-01-11 17:31:27470 DCHECK(ContainsKey(active_downloads_, info->download_id));
471 DownloadItem* download = active_downloads_[info->download_id];
[email protected]c2e76012010-12-23 21:10:29472 DCHECK(download != NULL);
[email protected]70850c72011-01-11 17:31:27473 DCHECK(ContainsKey(downloads_, download));
474
[email protected]c2e76012010-12-23 21:10:29475 download->SetFileCheckResults(info->path,
[email protected]287b86b2011-02-26 00:11:35476 info->is_dangerous_file,
477 info->is_dangerous_url,
[email protected]c2e76012010-12-23 21:10:29478 info->path_uniquifier,
479 info->prompt_user_for_save_location,
480 info->is_extension_install,
481 info->original_name);
[email protected]aa033af2010-07-27 18:16:39482 in_progress_[info->download_id] = download;
[email protected]adb2f3d12011-01-23 16:24:54483 UpdateAppIcon(); // Reflect entry into in_progress_.
initial.commit09911bf2008-07-26 23:55:29484
[email protected]adb2f3d12011-01-23 16:24:54485 // Rename to intermediate name.
[email protected]287b86b2011-02-26 00:11:35486 if (info->IsDangerous()) {
[email protected]adb2f3d12011-01-23 16:24:54487 // The download is not safe. We can now rename the file to its
488 // tentative name using OnFinalDownloadName (the actual final
489 // name after user confirmation will be set in
490 // ProceedWithFinishedDangerousDownload).
[email protected]ca4b5fa32010-10-09 12:42:18491 BrowserThread::PostTask(
492 BrowserThread::FILE, FROM_HERE,
[email protected]594cd7d2010-07-21 03:23:56493 NewRunnableMethod(
[email protected]0d7e79fa2010-10-08 23:35:47494 file_manager_, &DownloadFileManager::OnFinalDownloadName,
[email protected]287b86b2011-02-26 00:11:35495 download->id(), info->path, make_scoped_refptr(this)));
[email protected]594cd7d2010-07-21 03:23:56496 } else {
[email protected]adb2f3d12011-01-23 16:24:54497 // The download is a safe download. We need to
498 // rename it to its intermediate '.crdownload' path. The final
499 // name after user confirmation will be set from
500 // DownloadItem::OnSafeDownloadFinished.
[email protected]287b86b2011-02-26 00:11:35501 FilePath download_path = download_util::GetCrDownloadPath(info->path);
[email protected]ca4b5fa32010-10-09 12:42:18502 BrowserThread::PostTask(
503 BrowserThread::FILE, FROM_HERE,
[email protected]594cd7d2010-07-21 03:23:56504 NewRunnableMethod(
[email protected]0d7e79fa2010-10-08 23:35:47505 file_manager_, &DownloadFileManager::OnIntermediateDownloadName,
[email protected]dc7cdcb92010-12-14 06:40:54506 download->id(), download_path, make_scoped_refptr(this)));
[email protected]44b94b82010-11-08 20:49:18507 download->Rename(download_path);
[email protected]594cd7d2010-07-21 03:23:56508 }
509
[email protected]82f37b02010-07-29 22:04:57510 download_history_->AddEntry(*info, download,
511 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
initial.commit09911bf2008-07-26 23:55:29512}
513
initial.commit09911bf2008-07-26 23:55:29514void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
[email protected]70850c72011-01-11 17:31:27515 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
516 DownloadMap::iterator it = active_downloads_.find(download_id);
517 if (it != active_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29518 DownloadItem* download = it->second;
[email protected]70850c72011-01-11 17:31:27519 if (download->state() == DownloadItem::IN_PROGRESS) {
520 download->Update(size);
[email protected]adb2f3d12011-01-23 16:24:54521 UpdateAppIcon(); // Reflect size updates.
[email protected]70850c72011-01-11 17:31:27522 download_history_->UpdateEntry(download);
523 }
initial.commit09911bf2008-07-26 23:55:29524 }
525}
526
[email protected]a850ba42010-09-10 22:00:30527void DownloadManager::OnAllDataSaved(int32 download_id, int64 size) {
[email protected]da6e3922010-11-24 21:45:50528 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
529 << " size = " << size;
[email protected]9d7ef802011-02-25 19:03:35530 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:32531
[email protected]c4f02c42011-01-24 21:55:06532 // If it's not in active_downloads_, that means it was cancelled; just
533 // ignore the notification.
534 if (active_downloads_.count(download_id) == 0)
535 return;
536
[email protected]adb2f3d12011-01-23 16:24:54537 DownloadItem* download = active_downloads_[download_id];
[email protected]a850ba42010-09-10 22:00:30538 download->OnAllDataSaved(size);
[email protected]9ccbb372008-10-10 18:50:32539
[email protected]adb2f3d12011-01-23 16:24:54540 MaybeCompleteDownload(download);
541}
[email protected]9ccbb372008-10-10 18:50:32542
[email protected]adb2f3d12011-01-23 16:24:54543bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
544 // If we don't have all the data, the download is not ready for
545 // completion.
546 if (!download->all_data_saved())
547 return false;
[email protected]6a7fb042010-02-01 16:30:47548
[email protected]9d7ef802011-02-25 19:03:35549 // If the download is dangerous, but not yet validated, it's not ready for
550 // completion.
551 if (download->safety_state() == DownloadItem::DANGEROUS)
552 return false;
553
[email protected]adb2f3d12011-01-23 16:24:54554 // If the download isn't active (e.g. has been cancelled) it's not
555 // ready for completion.
556 if (active_downloads_.count(download->id()) == 0)
557 return false;
558
559 // If the download hasn't been inserted into the history system
560 // (which occurs strictly after file name determination, intermediate
561 // file rename, and UI display) then it's not ready for completion.
562 return (download->db_handle() != DownloadHistory::kUninitializedHandle);
563}
564
565void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
566 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
567 VLOG(20) << __FUNCTION__ << "()" << " download = "
568 << download->DebugString(false);
569
570 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32571 return;
[email protected]9ccbb372008-10-10 18:50:32572
[email protected]adb2f3d12011-01-23 16:24:54573 // TODO(rdsmith): DCHECK that we only pass through this point
574 // once per download. The natural way to do this is by a state
575 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56576
[email protected]adb2f3d12011-01-23 16:24:54577 // Confirm we're in the proper set of states to be here;
[email protected]9d7ef802011-02-25 19:03:35578 // in in_progress_, have all data, have a history handle, (validated or safe).
579 DCHECK_NE(DownloadItem::DANGEROUS, download->safety_state());
[email protected]adb2f3d12011-01-23 16:24:54580 DCHECK_EQ(1u, in_progress_.count(download->id()));
581 DCHECK(download->all_data_saved());
582 DCHECK(download->db_handle() != DownloadHistory::kUninitializedHandle);
583 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
584
585 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
586 << download->DebugString(false);
587
588 // Remove the id from in_progress
589 in_progress_.erase(download->id());
590 UpdateAppIcon(); // Reflect removal from in_progress_.
591
592 // Final update of download item and history.
593 download->MarkAsComplete();
594 download_history_->UpdateEntry(download);
595
596 switch (download->safety_state()) {
597 case DownloadItem::DANGEROUS:
598 // If this a dangerous download not yet validated by the user, don't do
599 // anything. When the user notifies us, it will trigger a call to
600 // ProceedWithFinishedDangerousDownload.
[email protected]9d7ef802011-02-25 19:03:35601 NOTREACHED();
[email protected]adb2f3d12011-01-23 16:24:54602 return;
603 case DownloadItem::DANGEROUS_BUT_VALIDATED:
604 // The dangerous download has been validated by the user. We first
605 // need to rename the downloaded file from its temporary name to
606 // its final name. We will continue the download processing in the
607 // callback.
608 BrowserThread::PostTask(
609 BrowserThread::FILE, FROM_HERE,
610 NewRunnableMethod(
611 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
612 download->db_handle(),
613 download->full_path(), download->target_name()));
614 return;
615 case DownloadItem::SAFE:
616 // The download is safe; just finish it.
617 download->OnSafeDownloadFinished(file_manager_);
618 return;
619 }
[email protected]9ccbb372008-10-10 18:50:32620}
621
[email protected]70850c72011-01-11 17:31:27622void DownloadManager::RemoveFromActiveList(int32 download_id) {
623 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
624 active_downloads_.erase(download_id);
625}
626
[email protected]8f783752009-04-01 23:33:45627void DownloadManager::DownloadRenamedToFinalName(int download_id,
628 const FilePath& full_path) {
[email protected]da6e3922010-11-24 21:45:50629 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
630 << " full_path = \"" << full_path.value() << "\"";
[email protected]ca4b5fa32010-10-09 12:42:18631 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]2e030682010-07-23 19:45:36632 DownloadItem* item = GetDownloadItem(download_id);
633 if (!item)
634 return;
[email protected]9246de32010-11-10 22:58:47635 item->OnDownloadRenamedToFinalName(full_path);
[email protected]8f783752009-04-01 23:33:45636}
637
[email protected]9ccbb372008-10-10 18:50:32638// Called on the file thread. Renames the downloaded file to its original name.
639void DownloadManager::ProceedWithFinishedDangerousDownload(
640 int64 download_handle,
[email protected]7ae7c2cb2009-01-06 23:31:41641 const FilePath& path,
642 const FilePath& original_name) {
[email protected]9ccbb372008-10-10 18:50:32643 bool success = false;
[email protected]7ae7c2cb2009-01-06 23:31:41644 FilePath new_path;
[email protected]7a256ea2008-10-17 17:34:16645 int uniquifier = 0;
[email protected]9ccbb372008-10-10 18:50:32646 if (file_util::PathExists(path)) {
[email protected]889ed35c2009-01-21 00:07:24647 new_path = path.DirName().Append(original_name);
[email protected]7a256ea2008-10-17 17:34:16648 // Make our name unique at this point, as if a dangerous file is downloading
649 // and a 2nd download is started for a file with the same name, they would
650 // have the same path. This is because we uniquify the name on download
651 // start, and at that time the first file does not exists yet, so the second
652 // file gets the same name.
[email protected]5a2388a2010-03-26 16:13:39653 uniquifier = download_util::GetUniquePathNumber(new_path);
[email protected]7a256ea2008-10-17 17:34:16654 if (uniquifier > 0)
[email protected]5a2388a2010-03-26 16:13:39655 download_util::AppendNumberToPath(&new_path, uniquifier);
[email protected]9ccbb372008-10-10 18:50:32656 success = file_util::Move(path, new_path);
657 } else {
658 NOTREACHED();
659 }
[email protected]6cade212008-12-03 00:32:22660
[email protected]ca4b5fa32010-10-09 12:42:18661 BrowserThread::PostTask(
662 BrowserThread::UI, FROM_HERE,
[email protected]9ccbb372008-10-10 18:50:32663 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
[email protected]7a256ea2008-10-17 17:34:16664 download_handle, success, new_path, uniquifier));
[email protected]9ccbb372008-10-10 18:50:32665}
666
667// Call from the file thread when the finished dangerous download was renamed.
668void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
669 bool success,
[email protected]7ae7c2cb2009-01-06 23:31:41670 const FilePath& new_path,
[email protected]7a256ea2008-10-17 17:34:16671 int new_path_uniquifier) {
[email protected]da6e3922010-11-24 21:45:50672 VLOG(20) << __FUNCTION__ << "()" << " download_handle = " << download_handle
673 << " success = " << success
674 << " new_path = \"" << new_path.value() << "\""
675 << " new_path_uniquifier = " << new_path_uniquifier;
[email protected]f04182f32010-12-10 19:12:07676 DownloadMap::iterator it = history_downloads_.find(download_handle);
677 if (it == history_downloads_.end()) {
[email protected]9ccbb372008-10-10 18:50:32678 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
[email protected]44b94b82010-11-08 20:49:18686 // name when calling GetFileNameToReportUser().
[email protected]7a256ea2008-10-17 17:34:16687 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.
[email protected]f04182f32010-12-10 19:12:07692 download->Finished();
initial.commit09911bf2008-07-26 23:55:29693}
694
initial.commit09911bf2008-07-26 23:55:29695void DownloadManager::DownloadCancelled(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27696 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29697 DownloadMap::iterator it = in_progress_.find(download_id);
698 if (it == in_progress_.end())
699 return;
700 DownloadItem* download = it->second;
701
[email protected]da6e3922010-11-24 21:45:50702 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
703 << " download = " << download->DebugString(true);
704
initial.commit09911bf2008-07-26 23:55:29705 // Clean up will happen when the history system create callback runs if we
706 // don't have a valid db_handle yet.
[email protected]82f37b02010-07-29 22:04:57707 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
initial.commit09911bf2008-07-26 23:55:29708 in_progress_.erase(it);
[email protected]70850c72011-01-11 17:31:27709 active_downloads_.erase(download_id);
[email protected]adb2f3d12011-01-23 16:24:54710 UpdateAppIcon(); // Reflect removal from in_progress_.
[email protected]82f37b02010-07-29 22:04:57711 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29712 }
713
[email protected]d7d1c5c2009-08-05 23:52:50714 DownloadCancelledInternal(download_id,
715 download->render_process_id(),
716 download->request_id());
717}
718
719void DownloadManager::DownloadCancelledInternal(int download_id,
720 int render_process_id,
721 int request_id) {
[email protected]d85cf072009-10-27 03:59:31722 // Cancel the network request. RDH is guaranteed to outlive the IO thread.
[email protected]ca4b5fa32010-10-09 12:42:18723 BrowserThread::PostTask(
724 BrowserThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26725 NewRunnableFunction(&download_util::CancelDownloadRequest,
[email protected]d85cf072009-10-27 03:59:31726 g_browser_process->resource_dispatcher_host(),
727 render_process_id,
728 request_id));
[email protected]d7d1c5c2009-08-05 23:52:50729
[email protected]ca4b5fa32010-10-09 12:42:18730 BrowserThread::PostTask(
731 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37732 NewRunnableMethod(
733 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29734}
735
736void 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]ca4b5fa32010-10-09 12:42:18745 BrowserThread::PostTask(
746 BrowserThread::IO, FROM_HERE,
[email protected]e2abdeb22010-09-03 19:56:15747 NewRunnableMethod(this,
748 &DownloadManager::PauseDownloadRequest,
749 g_browser_process->resource_dispatcher_host(),
[email protected]7ba53e12010-08-05 17:14:00750 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() {
[email protected]073ed7b2010-09-27 09:20:02756 if (status_updater_)
757 status_updater_->Update();
[email protected]6a7fb042010-02-01 16:30:47758}
759
[email protected]9ccbb372008-10-10 18:50:32760void DownloadManager::RenameDownload(DownloadItem* download,
[email protected]7ae7c2cb2009-01-06 23:31:41761 const FilePath& new_path) {
[email protected]9ccbb372008-10-10 18:50:32762 download->Rename(new_path);
[email protected]82f37b02010-07-29 22:04:57763 download_history_->UpdateDownloadPath(download, new_path);
[email protected]9ccbb372008-10-10 18:50:32764}
765
[email protected]e2abdeb22010-09-03 19:56:15766void DownloadManager::PauseDownloadRequest(ResourceDispatcherHost* rdh,
767 int render_process_id,
768 int request_id,
769 bool pause) {
[email protected]ca4b5fa32010-10-09 12:42:18770 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
[email protected]e2abdeb22010-09-03 19:56:15771 rdh->PauseRequest(render_process_id, request_id, pause);
772}
773
initial.commit09911bf2008-07-26 23:55:29774void DownloadManager::RemoveDownload(int64 download_handle) {
[email protected]f04182f32010-12-10 19:12:07775 DownloadMap::iterator it = history_downloads_.find(download_handle);
776 if (it == history_downloads_.end())
initial.commit09911bf2008-07-26 23:55:29777 return;
778
779 // Make history update.
780 DownloadItem* download = it->second;
[email protected]82f37b02010-07-29 22:04:57781 download_history_->RemoveEntry(download);
initial.commit09911bf2008-07-26 23:55:29782
783 // Remove from our tables and delete.
[email protected]f04182f32010-12-10 19:12:07784 history_downloads_.erase(it);
785 int downloads_count = downloads_.erase(download);
786 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29787
788 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:28789 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:36790
791 delete download;
initial.commit09911bf2008-07-26 23:55:29792}
793
[email protected]e93d2822009-01-30 05:59:59794int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
795 const base::Time remove_end) {
[email protected]82f37b02010-07-29 22:04:57796 download_history_->RemoveEntriesBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29797
[email protected]a312a442010-12-15 23:40:33798 // All downloads visible to the user will be in the history,
799 // so scan that map.
[email protected]f04182f32010-12-10 19:12:07800 DownloadMap::iterator it = history_downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:28801 std::vector<DownloadItem*> pending_deletes;
[email protected]f04182f32010-12-10 19:12:07802 while (it != history_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29803 DownloadItem* download = it->second;
804 DownloadItem::DownloadState state = download->state();
805 if (download->start_time() >= remove_begin &&
806 (remove_end.is_null() || download->start_time() < remove_end) &&
807 (state == DownloadItem::COMPLETE ||
808 state == DownloadItem::CANCELLED)) {
809 // Remove from the map and move to the next in the list.
[email protected]f04182f32010-12-10 19:12:07810 history_downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:58811
812 // Also remove it from any completed dangerous downloads.
[email protected]78b8fcc92009-03-31 17:36:28813 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29814
initial.commit09911bf2008-07-26 23:55:29815 continue;
816 }
817
818 ++it;
819 }
820
[email protected]a312a442010-12-15 23:40:33821 // If we aren't deleting anything, we're done.
[email protected]57fd1252010-12-23 17:24:09822 if (pending_deletes.empty())
823 return 0;
initial.commit09911bf2008-07-26 23:55:29824
[email protected]a312a442010-12-15 23:40:33825 // Remove the chosen downloads from the main owning container.
826 for (std::vector<DownloadItem*>::iterator it = pending_deletes.begin();
827 it != pending_deletes.end(); it++) {
828 downloads_.erase(*it);
829 }
830
831 // Tell observers to refresh their views.
832 NotifyModelChanged();
833
834 // Delete the download items themselves.
[email protected]57fd1252010-12-23 17:24:09835 int num_deleted = static_cast<int>(pending_deletes.size());
836
[email protected]78b8fcc92009-03-31 17:36:28837 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
838 pending_deletes.clear();
839
initial.commit09911bf2008-07-26 23:55:29840 return num_deleted;
841}
842
[email protected]e93d2822009-01-30 05:59:59843int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
844 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29845}
846
[email protected]d41355e6f2009-04-07 21:21:12847int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:46848 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
849 // This is an incognito downloader. Clear All should clear main download
850 // manager as well.
851 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
852 }
[email protected]d41355e6f2009-04-07 21:21:12853 // The null times make the date range unbounded.
854 return RemoveDownloadsBetween(base::Time(), base::Time());
855}
856
[email protected]ec4826a2010-09-21 09:15:59857void DownloadManager::SavePageAsDownloadStarted(DownloadItem* download_item) {
[email protected]57fd1252010-12-23 17:24:09858#if !defined(NDEBUG)
859 save_page_as_downloads_.insert(download_item);
860#endif
[email protected]f04182f32010-12-10 19:12:07861 downloads_.insert(download_item);
[email protected]ec4826a2010-09-21 09:15:59862}
863
initial.commit09911bf2008-07-26 23:55:29864// Initiate a download of a specific URL. We send the request to the
865// ResourceDispatcherHost, and let it send us responses like a regular
866// download.
867void DownloadManager::DownloadUrl(const GURL& url,
868 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50869 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34870 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26871 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
872 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58873}
874
875void DownloadManager::DownloadUrlToFile(const GURL& url,
876 const GURL& referrer,
877 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32878 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58879 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34880 DCHECK(tab_contents);
[email protected]ca4b5fa32010-10-09 12:42:18881 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26882 NewRunnableFunction(&download_util::DownloadUrl,
883 url,
884 referrer,
885 referrer_charset,
886 save_info,
887 g_browser_process->resource_dispatcher_host(),
888 tab_contents->GetRenderProcessHost()->id(),
889 tab_contents->render_view_host()->routing_id(),
890 request_context_getter_));
initial.commit09911bf2008-07-26 23:55:29891}
892
initial.commit09911bf2008-07-26 23:55:29893void DownloadManager::AddObserver(Observer* observer) {
894 observers_.AddObserver(observer);
895 observer->ModelChanged();
896}
897
898void DownloadManager::RemoveObserver(Observer* observer) {
899 observers_.RemoveObserver(observer);
900}
901
[email protected]eccb9d12009-10-28 05:40:09902bool DownloadManager::ShouldOpenFileBasedOnExtension(
903 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:09904 FilePath::StringType extension = path.Extension();
905 if (extension.empty())
906 return false;
[email protected]92e11c82010-01-13 06:39:56907 if (Extension::IsExtension(path))
908 return false;
[email protected]eccb9d12009-10-28 05:40:09909 DCHECK(extension[0] == FilePath::kExtensionSeparator);
910 extension.erase(0, 1);
[email protected]e5dc4222010-08-30 22:16:32911 return download_prefs_->IsAutoOpenEnabledForExtension(extension);
initial.commit09911bf2008-07-26 23:55:29912}
913
[email protected]073ed7b2010-09-27 09:20:02914bool DownloadManager::IsDownloadProgressKnown() {
915 for (DownloadMap::iterator i = in_progress_.begin();
916 i != in_progress_.end(); ++i) {
917 if (i->second->total_bytes() <= 0)
918 return false;
919 }
920
921 return true;
922}
923
924int64 DownloadManager::GetInProgressDownloadCount() {
925 return in_progress_.size();
926}
927
928int64 DownloadManager::GetReceivedDownloadBytes() {
929 DCHECK(IsDownloadProgressKnown());
930 int64 received_bytes = 0;
931 for (DownloadMap::iterator i = in_progress_.begin();
932 i != in_progress_.end(); ++i) {
933 received_bytes += i->second->received_bytes();
934 }
935 return received_bytes;
936}
937
938int64 DownloadManager::GetTotalDownloadBytes() {
939 DCHECK(IsDownloadProgressKnown());
940 int64 total_bytes = 0;
941 for (DownloadMap::iterator i = in_progress_.begin();
942 i != in_progress_.end(); ++i) {
943 total_bytes += i->second->total_bytes();
944 }
945 return total_bytes;
946}
947
[email protected]561abe62009-04-06 18:08:34948void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:36949 int index, void* params) {
initial.commit09911bf2008-07-26 23:55:29950 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]e6875c12010-07-18 11:14:13951 if (info->prompt_user_for_save_location)
[email protected]7ae7c2cb2009-01-06 23:31:41952 last_download_path_ = path.DirName();
[email protected]287b86b2011-02-26 00:11:35953
954 info->path = path;
955 AttachDownloadItem(info);
initial.commit09911bf2008-07-26 23:55:29956}
957
958void DownloadManager::FileSelectionCanceled(void* params) {
959 // The user didn't pick a place to save the file, so need to cancel the
960 // download that's already in progress to the temporary location.
961 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
[email protected]d7d1c5c2009-08-05 23:52:50962 DownloadCancelledInternal(info->download_id,
[email protected]76543b92009-08-31 17:27:45963 info->child_id,
[email protected]d7d1c5c2009-08-05 23:52:50964 info->request_id);
initial.commit09911bf2008-07-26 23:55:29965}
966
[email protected]9ccbb372008-10-10 18:50:32967void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
[email protected]9d7ef802011-02-25 19:03:35968 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:32969 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
970 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
971 download->UpdateObservers();
972
[email protected]9d7ef802011-02-25 19:03:35973 MaybeCompleteDownload(download);
[email protected]9ccbb372008-10-10 18:50:32974}
975
initial.commit09911bf2008-07-26 23:55:29976// Operations posted to us from the history service ----------------------------
977
978// The history service has retrieved all download entries. 'entries' contains
979// 'DownloadCreateInfo's in sorted order (by ascending start_time).
980void DownloadManager::OnQueryDownloadEntriesComplete(
981 std::vector<DownloadCreateInfo>* entries) {
982 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:39983 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]f04182f32010-12-10 19:12:07984 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
985 downloads_.insert(download);
986 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:50987 VLOG(20) << __FUNCTION__ << "()" << i << ">"
988 << " download = " << download->DebugString(true);
initial.commit09911bf2008-07-26 23:55:29989 }
[email protected]b0ab1d42010-02-24 19:29:28990 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:29991}
992
initial.commit09911bf2008-07-26 23:55:29993// Once the new DownloadItem's creation info has been committed to the history
994// service, we associate the DownloadItem with the db handle, update our
[email protected]f04182f32010-12-10 19:12:07995// 'history_downloads_' map and inform observers.
[email protected]9f5cb562010-11-08 22:06:59996void DownloadManager::OnCreateDownloadEntryComplete(
[email protected]76d8b622010-11-11 19:50:05997 DownloadCreateInfo info,
[email protected]9f5cb562010-11-08 22:06:59998 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:27999 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:291000 DownloadMap::iterator it = in_progress_.find(info.download_id);
1001 DCHECK(it != in_progress_.end());
1002
1003 DownloadItem* download = it->second;
[email protected]da6e3922010-11-24 21:45:501004 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
1005 << " download_id = " << info.download_id
1006 << " download = " << download->DebugString(true);
[email protected]d2a8fb72010-01-21 05:31:421007
1008 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1009 // call this function with an invalid |db_handle|. For instance, this can
1010 // happen when the history database is offline. We cannot have multiple
1011 // DownloadItems with the same invalid db_handle, so we need to assign a
1012 // unique |db_handle| here.
[email protected]82f37b02010-07-29 22:04:571013 if (db_handle == DownloadHistory::kUninitializedHandle)
1014 db_handle = download_history_->GetNextFakeDbHandle();
[email protected]d2a8fb72010-01-21 05:31:421015
[email protected]82f37b02010-07-29 22:04:571016 DCHECK(download->db_handle() == DownloadHistory::kUninitializedHandle);
initial.commit09911bf2008-07-26 23:55:291017 download->set_db_handle(db_handle);
1018
1019 // Insert into our full map.
[email protected]70850c72011-01-11 17:31:271020 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
[email protected]f04182f32010-12-10 19:12:071021 history_downloads_[download->db_handle()] = download;
initial.commit09911bf2008-07-26 23:55:291022
[email protected]70850c72011-01-11 17:31:271023 // Show in the appropriate browser UI.
[email protected]9d7ef802011-02-25 19:03:351024 // This includes buttons to save or cancel, for a dangerous download.
[email protected]5e595482009-05-06 20:16:531025 ShowDownloadInBrowser(info, download);
initial.commit09911bf2008-07-26 23:55:291026
1027 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281028 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291029
[email protected]adb2f3d12011-01-23 16:24:541030 // If this download has been cancelled before we've received the DB handle,
initial.commit09911bf2008-07-26 23:55:291031 // post one final message to the history service so that it can be properly
1032 // in sync with the DownloadItem's completion status, and also inform any
1033 // observers so that they get more than just the start notification.
[email protected]adb2f3d12011-01-23 16:24:541034 //
1035 // Otherwise, try to complete the download
initial.commit09911bf2008-07-26 23:55:291036 if (download->state() != DownloadItem::IN_PROGRESS) {
[email protected]adb2f3d12011-01-23 16:24:541037 DCHECK_EQ(DownloadItem::CANCELLED, download->state());
initial.commit09911bf2008-07-26 23:55:291038 in_progress_.erase(it);
[email protected]70850c72011-01-11 17:31:271039 active_downloads_.erase(info.download_id);
[email protected]82f37b02010-07-29 22:04:571040 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:291041 download->UpdateObservers();
[email protected]adb2f3d12011-01-23 16:24:541042 } else {
1043 MaybeCompleteDownload(download);
initial.commit09911bf2008-07-26 23:55:291044 }
1045}
1046
[email protected]5e595482009-05-06 20:16:531047void DownloadManager::ShowDownloadInBrowser(const DownloadCreateInfo& info,
1048 DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341049 // The 'contents' may no longer exist if the user closed the tab before we
1050 // get this start completion event. If it does, tell the origin TabContents
1051 // to display its download shelf.
[email protected]76543b92009-08-31 17:27:451052 TabContents* contents = tab_util::GetTabContentsByID(info.child_id,
1053 info.render_view_id);
[email protected]5e595482009-05-06 20:16:531054
1055 // If the contents no longer exists, we start the download in the last active
1056 // browser. This is not ideal but better than fully hiding the download from
1057 // the user.
1058 if (!contents) {
1059 Browser* last_active = BrowserList::GetLastActive();
1060 if (last_active)
1061 contents = last_active->GetSelectedTabContents();
1062 }
1063
1064 if (contents)
1065 contents->OnStartDownload(download);
1066}
1067
[email protected]6cade212008-12-03 00:32:221068// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121069void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411070 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381071}
[email protected]b0ab1d42010-02-24 19:29:281072
1073void DownloadManager::NotifyModelChanged() {
1074 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1075}
1076
[email protected]2e030682010-07-23 19:45:361077DownloadItem* DownloadManager::GetDownloadItem(int id) {
[email protected]f04182f32010-12-10 19:12:071078 for (DownloadMap::iterator it = history_downloads_.begin();
1079 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:361080 DownloadItem* item = it->second;
1081 if (item->id() == id)
1082 return item;
1083 }
1084 return NULL;
1085}
1086
[email protected]57fd1252010-12-23 17:24:091087// Confirm that everything in all maps is also in |downloads_|, and that
1088// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:071089void DownloadManager::AssertContainersConsistent() const {
1090#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:091091 // Turn everything into sets.
[email protected]adb2f3d12011-01-23 16:24:541092 DownloadSet active_set, history_set;
[email protected]70850c72011-01-11 17:31:271093 const DownloadMap* input_maps[] = {&active_downloads_, &history_downloads_};
[email protected]adb2f3d12011-01-23 16:24:541094 DownloadSet* local_sets[] = {&active_set, &history_set};
[email protected]57fd1252010-12-23 17:24:091095 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(local_sets));
1096 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
1097 for (DownloadMap::const_iterator it = input_maps[i]->begin();
1098 it != input_maps[i]->end(); it++) {
1099 local_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:071100 }
1101 }
[email protected]57fd1252010-12-23 17:24:091102
1103 // Check if each set is fully present in downloads, and create a union.
[email protected]adb2f3d12011-01-23 16:24:541104 const DownloadSet* all_sets[] = {&active_set, &history_set,
[email protected]57fd1252010-12-23 17:24:091105 &save_page_as_downloads_};
1106 DownloadSet downloads_union;
1107 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
1108 DownloadSet remainder;
1109 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
1110 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
1111 downloads_.begin(), downloads_.end(),
1112 insert_it);
1113 DCHECK(remainder.empty());
1114 std::insert_iterator<DownloadSet>
1115 insert_union(downloads_union, downloads_union.end());
1116 std::set_union(downloads_union.begin(), downloads_union.end(),
1117 all_sets[i]->begin(), all_sets[i]->end(),
1118 insert_union);
1119 }
1120
1121 // Is everything in downloads_ present in one of the other sets?
1122 DownloadSet remainder;
1123 std::insert_iterator<DownloadSet>
1124 insert_remainder(remainder, remainder.begin());
1125 std::set_difference(downloads_.begin(), downloads_.end(),
1126 downloads_union.begin(), downloads_union.end(),
1127 insert_remainder);
1128 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071129#endif
1130}
1131
[email protected]b0ab1d42010-02-24 19:29:281132// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1133
1134DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1135 DownloadManager* observing_download_manager)
1136 : observing_download_manager_(observing_download_manager),
1137 observed_download_manager_(NULL) {
1138 if (observing_download_manager->profile_->GetOriginalProfile() ==
1139 observing_download_manager->profile_) {
1140 return;
1141 }
1142
1143 observed_download_manager_ = observing_download_manager_->
1144 profile_->GetOriginalProfile()->GetDownloadManager();
1145 observed_download_manager_->AddObserver(this);
1146}
1147
1148DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1149 if (observed_download_manager_)
1150 observed_download_manager_->RemoveObserver(this);
1151}
1152
1153void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1154 observing_download_manager_->NotifyModelChanged();
1155}
1156
[email protected]b0ab1d42010-02-24 19:29:281157void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1158 observed_download_manager_ = NULL;
1159}