blob: c61912a27dab764060b2dd4e824dca69c84f7245 [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"
[email protected]503d03872011-05-06 08:36:269#include "base/i18n/case_conversion.h"
initial.commit09911bf2008-07-26 23:55:2910#include "base/logging.h"
[email protected]fed38252011-07-08 17:26:5011#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1412#include "base/rand_util.h"
[email protected]92926d92010-09-02 18:35:0613#include "base/stl_util-inl.h"
[email protected]2594c2b2010-11-08 23:04:2614#include "base/stringprintf.h"
[email protected]1b5044d2009-02-24 00:04:1415#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2916#include "base/task.h"
[email protected]ce7f62e32010-08-10 23:43:5917#include "base/utf_string_conversions.h"
[email protected]d2a8fb72010-01-21 05:31:4218#include "build/build_config.h"
initial.commit09911bf2008-07-26 23:55:2919#include "chrome/browser/browser_process.h"
[email protected]4cd82f72011-05-23 19:15:0120#include "chrome/browser/download/download_create_info.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]db6831a2011-06-09 21:08:2826#include "chrome/browser/download/download_request_handle.h"
[email protected]287b86b2011-02-26 00:11:3527#include "chrome/browser/download/download_safe_browsing_client.h"
[email protected]073ed7b2010-09-27 09:20:0228#include "chrome/browser/download/download_status_updater.h"
[email protected]e9ef0a62009-08-11 22:50:1329#include "chrome/browser/download/download_util.h"
[email protected]eaa7dd182010-12-14 11:09:0030#include "chrome/browser/extensions/extension_service.h"
[email protected]4cd82f72011-05-23 19:15:0131#include "chrome/browser/history/download_history_info.h"
[email protected]14a000d2010-04-29 21:44:2432#include "chrome/browser/platform_util.h"
[email protected]8ecad5e2010-12-02 21:18:3333#include "chrome/browser/profiles/profile.h"
[email protected]d2a8fb72010-01-21 05:31:4234#include "chrome/browser/tab_contents/tab_util.h"
[email protected]7b5dc002010-11-16 23:08:1035#include "chrome/browser/ui/browser.h"
[email protected]71b73f02011-04-06 15:57:2936#include "chrome/browser/ui/browser_list.h"
[email protected]ddb85052011-05-18 14:40:2737#include "chrome/browser/ui/download/download_tab_helper.h"
38#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
initial.commit09911bf2008-07-26 23:55:2939#include "chrome/common/chrome_paths.h"
[email protected]7324d1d2011-03-01 05:02:1640#include "content/browser/browser_thread.h"
41#include "content/browser/renderer_host/render_process_host.h"
42#include "content/browser/renderer_host/render_view_host.h"
43#include "content/browser/renderer_host/resource_dispatcher_host.h"
44#include "content/browser/tab_contents/tab_contents.h"
[email protected]432115822011-07-10 15:52:2745#include "content/common/content_notification_types.h"
[email protected]46072d42008-07-28 14:49:3546#include "googleurl/src/gurl.h"
[email protected]34ac8f32009-02-22 23:03:2747#include "grit/generated_resources.h"
[email protected]21ca982c2010-01-26 22:49:5548#include "grit/theme_resources.h"
initial.commit09911bf2008-07-26 23:55:2949#include "net/base/mime_util.h"
50#include "net/base/net_util.h"
[email protected]c051a1b2011-01-21 23:30:1751#include "ui/base/l10n/l10n_util.h"
[email protected]42ce29d2011-01-20 23:19:4652#include "ui/base/resource/resource_bundle.h"
initial.commit09911bf2008-07-26 23:55:2953
[email protected]073ed7b2010-09-27 09:20:0254DownloadManager::DownloadManager(DownloadStatusUpdater* status_updater)
initial.commit09911bf2008-07-26 23:55:2955 : shutdown_needed_(false),
56 profile_(NULL),
[email protected]073ed7b2010-09-27 09:20:0257 file_manager_(NULL),
[email protected]a3d2bc42010-10-06 14:08:4958 status_updater_(status_updater->AsWeakPtr()) {
[email protected]073ed7b2010-09-27 09:20:0259 if (status_updater_)
60 status_updater_->AddDelegate(this);
initial.commit09911bf2008-07-26 23:55:2961}
62
63DownloadManager::~DownloadManager() {
[email protected]326a6a92010-09-10 20:21:1364 DCHECK(!shutdown_needed_);
[email protected]073ed7b2010-09-27 09:20:0265 if (status_updater_)
66 status_updater_->RemoveDelegate(this);
initial.commit09911bf2008-07-26 23:55:2967}
68
69void DownloadManager::Shutdown() {
[email protected]da6e3922010-11-24 21:45:5070 VLOG(20) << __FUNCTION__ << "()"
71 << " shutdown_needed_ = " << shutdown_needed_;
[email protected]326a6a92010-09-10 20:21:1372 if (!shutdown_needed_)
73 return;
74 shutdown_needed_ = false;
initial.commit09911bf2008-07-26 23:55:2975
[email protected]326a6a92010-09-10 20:21:1376 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
77
78 if (file_manager_) {
[email protected]ca4b5fa32010-10-09 12:42:1879 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
[email protected]326a6a92010-09-10 20:21:1380 NewRunnableMethod(file_manager_,
81 &DownloadFileManager::OnDownloadManagerShutdown,
[email protected]dc7cdcb92010-12-14 06:40:5482 make_scoped_refptr(this)));
[email protected]326a6a92010-09-10 20:21:1383 }
initial.commit09911bf2008-07-26 23:55:2984
[email protected]f04182f32010-12-10 19:12:0785 AssertContainersConsistent();
86
87 // Go through all downloads in downloads_. Dangerous ones we need to
88 // remove on disk, and in progress ones we need to cancel.
[email protected]57fd1252010-12-23 17:24:0989 for (DownloadSet::iterator it = downloads_.begin(); it != downloads_.end();) {
[email protected]f04182f32010-12-10 19:12:0790 DownloadItem* download = *it;
91
92 // Save iterator from potential erases in this set done by called code.
93 // Iterators after an erasure point are still valid for lists and
94 // associative containers such as sets.
95 it++;
96
97 if (download->safety_state() == DownloadItem::DANGEROUS &&
[email protected]48837962011-04-19 17:03:2998 download->IsPartialDownload()) {
[email protected]f04182f32010-12-10 19:12:0799 // The user hasn't accepted it, so we need to remove it
100 // from the disk. This may or may not result in it being
101 // removed from the DownloadManager queues and deleted
102 // (specifically, DownloadManager::RemoveDownload only
103 // removes and deletes it if it's known to the history service)
104 // so the only thing we know after calling this function is that
105 // the download was deleted if-and-only-if it was removed
106 // from all queues.
[email protected]303077002011-04-19 23:21:01107 download->Delete(DownloadItem::DELETE_DUE_TO_BROWSER_SHUTDOWN);
[email protected]bf68a00b2011-04-07 17:28:26108 } else if (download->IsPartialDownload()) {
[email protected]f04182f32010-12-10 19:12:07109 download->Cancel(false);
110 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29111 }
112 }
113
[email protected]f04182f32010-12-10 19:12:07114 // At this point, all dangerous downloads have had their files removed
115 // and all in progress downloads have been cancelled. We can now delete
116 // anything left.
[email protected]9ccbb372008-10-10 18:50:32117
[email protected]5cd11b6e2011-06-10 20:30:59118 // Copy downloads_ to separate container so as not to set off checks
119 // in DownloadItem destruction.
120 DownloadSet downloads_to_delete;
121 downloads_to_delete.swap(downloads_);
122
initial.commit09911bf2008-07-26 23:55:29123 in_progress_.clear();
[email protected]70850c72011-01-11 17:31:27124 active_downloads_.clear();
[email protected]5cd11b6e2011-06-10 20:30:59125 history_downloads_.clear();
[email protected]57fd1252010-12-23 17:24:09126#if !defined(NDEBUG)
127 save_page_as_downloads_.clear();
128#endif
[email protected]5cd11b6e2011-06-10 20:30:59129 STLDeleteElements(&downloads_to_delete);
initial.commit09911bf2008-07-26 23:55:29130
131 file_manager_ = NULL;
132
initial.commit09911bf2008-07-26 23:55:29133 // Make sure the save as dialog doesn't notify us back if we're gone before
134 // it returns.
135 if (select_file_dialog_.get())
136 select_file_dialog_->ListenerDestroyed();
137
[email protected]82f37b02010-07-29 22:04:57138 download_history_.reset();
[email protected]68a49e52011-01-28 10:39:51139 download_prefs_.reset();
[email protected]82f37b02010-07-29 22:04:57140
initial.commit09911bf2008-07-26 23:55:29141 shutdown_needed_ = false;
142}
143
[email protected]82f37b02010-07-29 22:04:57144void DownloadManager::GetTemporaryDownloads(
145 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
146 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58147
[email protected]f04182f32010-12-10 19:12:07148 for (DownloadMap::iterator it = history_downloads_.begin();
149 it != history_downloads_.end(); ++it) {
[email protected]6aa4a1c02010-01-15 18:49:58150 if (it->second->is_temporary() &&
151 it->second->full_path().DirName() == dir_path)
[email protected]82f37b02010-07-29 22:04:57152 result->push_back(it->second);
[email protected]6aa4a1c02010-01-15 18:49:58153 }
[email protected]6aa4a1c02010-01-15 18:49:58154}
155
[email protected]82f37b02010-07-29 22:04:57156void DownloadManager::GetAllDownloads(
157 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
158 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34159
[email protected]f04182f32010-12-10 19:12:07160 for (DownloadMap::iterator it = history_downloads_.begin();
161 it != history_downloads_.end(); ++it) {
[email protected]8ddbd66a2010-05-21 16:38:34162 if (!it->second->is_temporary() &&
163 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57164 result->push_back(it->second);
[email protected]8ddbd66a2010-05-21 16:38:34165 }
[email protected]8ddbd66a2010-05-21 16:38:34166}
167
[email protected]82f37b02010-07-29 22:04:57168void DownloadManager::GetCurrentDownloads(
169 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
170 DCHECK(result);
[email protected]c4a530b2010-03-08 17:33:03171
[email protected]f04182f32010-12-10 19:12:07172 for (DownloadMap::iterator it = history_downloads_.begin();
173 it != history_downloads_.end(); ++it) {
[email protected]bf68a00b2011-04-07 17:28:26174 DownloadItem* item =it->second;
175 // Skip temporary items.
176 if (item->is_temporary())
177 continue;
178 // Skip items that have all their data, and are OK to save.
179 if (!item->IsPartialDownload() &&
180 (item->safety_state() != DownloadItem::DANGEROUS))
181 continue;
182 // Skip items that don't match |dir_path|.
183 // If |dir_path| is empty, all remaining items match.
184 if (!dir_path.empty() && (it->second->full_path().DirName() != dir_path))
185 continue;
186
187 result->push_back(item);
[email protected]c4a530b2010-03-08 17:33:03188 }
[email protected]f7e9fd62010-09-28 15:45:06189
190 // If we have a parent profile, let it add its downloads to the results.
191 Profile* original_profile = profile_->GetOriginalProfile();
192 if (original_profile != profile_)
193 original_profile->GetDownloadManager()->GetCurrentDownloads(dir_path,
194 result);
[email protected]c4a530b2010-03-08 17:33:03195}
196
[email protected]d3b12902010-08-16 23:39:42197void DownloadManager::SearchDownloads(const string16& query,
198 std::vector<DownloadItem*>* result) {
199 DCHECK(result);
200
[email protected]503d03872011-05-06 08:36:26201 string16 query_lower(base::i18n::ToLower(query));
[email protected]d3b12902010-08-16 23:39:42202
[email protected]f04182f32010-12-10 19:12:07203 for (DownloadMap::iterator it = history_downloads_.begin();
204 it != history_downloads_.end(); ++it) {
[email protected]d3b12902010-08-16 23:39:42205 DownloadItem* download_item = it->second;
206
207 if (download_item->is_temporary() || download_item->is_extension_install())
208 continue;
209
210 // Display Incognito downloads only in Incognito window, and vice versa.
211 // The Incognito Downloads page will get the list of non-Incognito downloads
212 // from its parent profile.
213 if (profile_->IsOffTheRecord() != download_item->is_otr())
214 continue;
215
216 if (download_item->MatchesQuery(query_lower))
217 result->push_back(download_item);
218 }
219
220 // If we have a parent profile, let it add its downloads to the results.
221 Profile* original_profile = profile_->GetOriginalProfile();
222 if (original_profile != profile_)
223 original_profile->GetDownloadManager()->SearchDownloads(query, result);
224}
225
initial.commit09911bf2008-07-26 23:55:29226// Query the history service for information about all persisted downloads.
227bool DownloadManager::Init(Profile* profile) {
228 DCHECK(profile);
229 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
230 shutdown_needed_ = true;
231
232 profile_ = profile;
[email protected]d3b12902010-08-16 23:39:42233 download_history_.reset(new DownloadHistory(profile));
[email protected]82f37b02010-07-29 22:04:57234 download_history_->Load(
235 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
[email protected]024f2f02010-04-30 22:51:46236
[email protected]e5dc4222010-08-30 22:16:32237 download_prefs_.reset(new DownloadPrefs(profile_->GetPrefs()));
238
[email protected]2941c2392010-07-15 22:54:30239 // In test mode, there may be no ResourceDispatcherHost. In this case it's
240 // safe to avoid setting |file_manager_| because we only call a small set of
241 // functions, none of which need it.
initial.commit09911bf2008-07-26 23:55:29242 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]2941c2392010-07-15 22:54:30243 if (rdh) {
244 file_manager_ = rdh->download_file_manager();
245 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29246 }
247
[email protected]b0ab1d42010-02-24 19:29:28248 other_download_manager_observer_.reset(
249 new OtherDownloadManagerObserver(this));
250
initial.commit09911bf2008-07-26 23:55:29251 return true;
252}
253
initial.commit09911bf2008-07-26 23:55:29254// We have received a message from DownloadFileManager about a new download. We
255// create a download item and store it in our download map, and inform the
256// history system of a new download. Since this method can be called while the
257// history service thread is still reading the persistent state, we do not
[email protected]f04182f32010-12-10 19:12:07258// insert the new DownloadItem into 'history_downloads_' or inform our
[email protected]adb2f3d12011-01-23 16:24:54259// observers at this point. OnCreateDownloadEntryComplete() handles that
[email protected]f04182f32010-12-10 19:12:07260// finalization of the the download creation as a callback from the
261// history thread.
[email protected]4cd82f72011-05-23 19:15:01262void DownloadManager::StartDownload(int32 download_id) {
[email protected]ca4b5fa32010-10-09 12:42:18263 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]287b86b2011-02-26 00:11:35264
[email protected]4cd82f72011-05-23 19:15:01265 DownloadItem* download = GetActiveDownloadItem(download_id);
266 if (!download)
267 return;
268
[email protected]4b58e7d2011-07-11 10:22:56269#if defined(ENABLE_SAFE_BROWSING)
[email protected]287b86b2011-02-26 00:11:35270 // Create a client to verify download URL with safebrowsing.
271 // It deletes itself after the callback.
[email protected]26711732011-03-09 00:21:22272 scoped_refptr<DownloadSBClient> sb_client = new DownloadSBClient(
[email protected]4cd82f72011-05-23 19:15:01273 download_id, download->url_chain(), download->referrer_url());
[email protected]287b86b2011-02-26 00:11:35274 sb_client->CheckDownloadUrl(
[email protected]4cd82f72011-05-23 19:15:01275 NewCallback(this, &DownloadManager::CheckDownloadUrlDone));
[email protected]4b58e7d2011-07-11 10:22:56276#else
277 CheckDownloadUrlDone(download_id, false);
278#endif
[email protected]287b86b2011-02-26 00:11:35279}
280
[email protected]9fc114672011-06-15 08:17:48281void DownloadManager::CheckForHistoryFilesRemoval() {
282 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
283 for (DownloadMap::iterator it = history_downloads_.begin();
284 it != history_downloads_.end(); ++it) {
285 CheckForFileRemoval(it->second);
286 }
287}
288
289void DownloadManager::CheckForFileRemoval(DownloadItem* download_item) {
290 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
291 if (download_item->IsComplete() &&
292 !download_item->file_externally_removed()) {
293 BrowserThread::PostTask(
294 BrowserThread::FILE, FROM_HERE,
295 NewRunnableMethod(this,
296 &DownloadManager::CheckForFileRemovalOnFileThread,
297 download_item->db_handle(),
298 download_item->GetTargetFilePath()));
299 }
300}
301
302void DownloadManager::CheckForFileRemovalOnFileThread(
303 int64 db_handle, const FilePath& path) {
304 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
305 if (!file_util::PathExists(path)) {
306 BrowserThread::PostTask(
307 BrowserThread::UI, FROM_HERE,
308 NewRunnableMethod(this,
309 &DownloadManager::OnFileRemovalDetected,
310 db_handle));
311 }
312}
313
314void DownloadManager::OnFileRemovalDetected(int64 db_handle) {
315 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
316 DownloadMap::iterator it = history_downloads_.find(db_handle);
317 if (it != history_downloads_.end()) {
318 DownloadItem* download_item = it->second;
319 download_item->OnDownloadedFileRemoved();
320 }
321}
322
[email protected]4cd82f72011-05-23 19:15:01323void DownloadManager::CheckDownloadUrlDone(int32 download_id,
[email protected]287b86b2011-02-26 00:11:35324 bool is_dangerous_url) {
325 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29326
[email protected]4cd82f72011-05-23 19:15:01327 DownloadItem* download = GetActiveDownloadItem(download_id);
328 if (!download)
329 return;
330
331 if (is_dangerous_url)
332 download->MarkUrlDangerous();
333
[email protected]88008002011-05-24 23:14:15334 download_history_->CheckVisitedReferrerBefore(download_id,
335 download->referrer_url(),
336 NewCallback(this, &DownloadManager::CheckVisitedReferrerBeforeDone));
337}
338
339void DownloadManager::CheckVisitedReferrerBeforeDone(
340 int32 download_id,
341 bool visited_referrer_before) {
342 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
343
344 DownloadItem* download = GetActiveDownloadItem(download_id);
345 if (!download)
346 return;
[email protected]287b86b2011-02-26 00:11:35347
[email protected]a60c8ae2009-12-25 06:50:57348 // Check whether this download is for an extension install or not.
[email protected]e6875c12010-07-18 11:14:13349 // Allow extensions to be explicitly saved.
[email protected]88008002011-05-24 23:14:15350 DownloadStateInfo state = download->state_info();
[email protected]4cd82f72011-05-23 19:15:01351 if (!state.prompt_user_for_save_location) {
352 if (UserScript::IsURLUserScript(download->GetURL(),
353 download->mime_type()) ||
354 (download->mime_type() == Extension::kMimeType)) {
355 state.is_extension_install = true;
[email protected]bac4f4b2011-03-05 02:01:40356 }
[email protected]a60c8ae2009-12-25 06:50:57357 }
358
[email protected]4cd82f72011-05-23 19:15:01359 if (state.force_file_name.empty()) {
[email protected]2941c2392010-07-15 22:54:30360 FilePath generated_name;
[email protected]4cd82f72011-05-23 19:15:01361 download_util::GenerateFileNameFromRequest(download->GetURL(),
362 download->content_disposition(),
363 download->referrer_charset(),
364 download->mime_type(),
365 &generated_name);
[email protected]2941c2392010-07-15 22:54:30366
367 // Freeze the user's preference for showing a Save As dialog. We're going
368 // to bounce around a bunch of threads and we don't want to worry about race
369 // conditions where the user changes this pref out from under us.
[email protected]0e9b6072011-02-17 12:42:05370 if (download_prefs_->PromptForDownload()) {
[email protected]2941c2392010-07-15 22:54:30371 // But ignore the user's preference for the following scenarios:
372 // 1) Extension installation. Note that we only care here about the case
373 // where an extension is installed, not when one is downloaded with
374 // "save as...".
375 // 2) Filetypes marked "always open." If the user just wants this file
376 // opened, don't bother asking where to keep it.
[email protected]4cd82f72011-05-23 19:15:01377 if (!state.is_extension_install &&
[email protected]2941c2392010-07-15 22:54:30378 !ShouldOpenFileBasedOnExtension(generated_name))
[email protected]4cd82f72011-05-23 19:15:01379 state.prompt_user_for_save_location = true;
[email protected]2941c2392010-07-15 22:54:30380 }
[email protected]14e0a102011-02-22 14:04:01381 if (download_prefs_->IsDownloadPathManaged()) {
[email protected]4cd82f72011-05-23 19:15:01382 state.prompt_user_for_save_location = false;
[email protected]14e0a102011-02-22 14:04:01383 }
[email protected]2941c2392010-07-15 22:54:30384
[email protected]8af9d032010-02-10 00:00:32385 // Determine the proper path for a download, by either one of the following:
386 // 1) using the default download directory.
387 // 2) prompting the user.
[email protected]4cd82f72011-05-23 19:15:01388 if (state.prompt_user_for_save_location && !last_download_path_.empty()) {
389 state.suggested_path = last_download_path_;
[email protected]80dc3612010-07-27 19:35:08390 } else {
[email protected]4cd82f72011-05-23 19:15:01391 state.suggested_path = download_prefs_->download_path();
[email protected]80dc3612010-07-27 19:35:08392 }
[email protected]4cd82f72011-05-23 19:15:01393 state.suggested_path = state.suggested_path.Append(generated_name);
[email protected]8af9d032010-02-10 00:00:32394 } else {
[email protected]4cd82f72011-05-23 19:15:01395 state.suggested_path = state.force_file_name;
[email protected]8af9d032010-02-10 00:00:32396 }
initial.commit09911bf2008-07-26 23:55:29397
[email protected]88008002011-05-24 23:14:15398 if (!state.prompt_user_for_save_location && state.force_file_name.empty()) {
399 state.is_dangerous_file =
400 IsDangerous(*download, state, visited_referrer_before);
401 }
[email protected]e9ebf3fc2008-10-17 22:06:58402
initial.commit09911bf2008-07-26 23:55:29403 // We need to move over to the download thread because we don't want to stat
404 // the suggested path on the UI thread.
[email protected]5a3b97e2010-10-05 09:49:11405 // We can only access preferences on the UI thread, so check the download path
406 // now and pass the value to the FILE thread.
[email protected]ca4b5fa32010-10-09 12:42:18407 BrowserThread::PostTask(
408 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37409 NewRunnableMethod(
[email protected]5a3b97e2010-10-05 09:49:11410 this,
411 &DownloadManager::CheckIfSuggestedPathExists,
[email protected]88008002011-05-24 23:14:15412 download->id(),
[email protected]4cd82f72011-05-23 19:15:01413 state,
[email protected]5a3b97e2010-10-05 09:49:11414 download_prefs()->download_path()));
initial.commit09911bf2008-07-26 23:55:29415}
416
[email protected]fed38252011-07-08 17:26:50417void DownloadManager::CheckIfSuggestedPathExists(int32 download_id,
418 DownloadStateInfo state,
419 const FilePath& default_path) {
[email protected]ca4b5fa32010-10-09 12:42:18420 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
initial.commit09911bf2008-07-26 23:55:29421
[email protected]fed38252011-07-08 17:26:50422 // Make sure the default download directory exists.
423 // TODO(phajdan.jr): only create the directory when we're sure the user
424 // is going to save there and not to another directory of his choice.
425 file_util::CreateDirectory(default_path);
426
427 // Check writability of the suggested path. If we can't write to it, default
428 // to the user's "My Documents" directory. We'll prompt them in this case.
429 FilePath dir = state.suggested_path.DirName();
430 FilePath filename = state.suggested_path.BaseName();
431 if (!file_util::PathIsWritable(dir)) {
432 VLOG(1) << "Unable to write to directory \"" << dir.value() << "\"";
[email protected]4cd82f72011-05-23 19:15:01433 state.prompt_user_for_save_location = true;
[email protected]fed38252011-07-08 17:26:50434 PathService::Get(chrome::DIR_USER_DOCUMENTS, &state.suggested_path);
435 state.suggested_path = state.suggested_path.Append(filename);
436 }
initial.commit09911bf2008-07-26 23:55:29437
[email protected]6cade212008-12-03 00:32:22438 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]4cd82f72011-05-23 19:15:01439 if (state.IsDangerous()) {
[email protected]fed38252011-07-08 17:26:50440 state.target_name = FilePath(state.suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32441 // Create a temporary file to hold the file until the user approves its
442 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41443 FilePath::StringType file_name;
444 FilePath path;
[email protected]463e1b432011-01-21 22:05:51445#if defined(OS_WIN)
446 string16 unconfirmed_prefix =
447 l10n_util::GetStringUTF16(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
448#else
449 std::string unconfirmed_prefix =
450 l10n_util::GetStringUTF8(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
451#endif
452
[email protected]9ccbb372008-10-10 18:50:32453 while (path.empty()) {
[email protected]2594c2b2010-11-08 23:04:26454 base::SStringPrintf(
455 &file_name,
[email protected]463e1b432011-01-21 22:05:51456 unconfirmed_prefix.append(
457 FILE_PATH_LITERAL(" %d.crdownload")).c_str(),
[email protected]2594c2b2010-11-08 23:04:26458 base::RandInt(0, 100000));
[email protected]fed38252011-07-08 17:26:50459 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07460 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41461 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32462 }
[email protected]4cd82f72011-05-23 19:15:01463 state.suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16464 } else {
[email protected]594cd7d2010-07-21 03:23:56465 // Do not add the path uniquifier if we are saving to a specific path as in
466 // the drag-out case.
[email protected]4cd82f72011-05-23 19:15:01467 if (state.force_file_name.empty()) {
468 state.path_uniquifier = download_util::GetUniquePathNumberWithCrDownload(
469 state.suggested_path);
[email protected]594cd7d2010-07-21 03:23:56470 }
[email protected]7a256ea2008-10-17 17:34:16471 // We know the final path, build it if necessary.
[email protected]4cd82f72011-05-23 19:15:01472 if (state.path_uniquifier > 0) {
473 download_util::AppendNumberToPath(&(state.suggested_path),
474 state.path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16475 // Setting path_uniquifier to 0 to make sure we don't try to unique it
476 // later on.
[email protected]4cd82f72011-05-23 19:15:01477 state.path_uniquifier = 0;
478 } else if (state.path_uniquifier == -1) {
[email protected]7d3851d82008-12-12 03:26:07479 // We failed to find a unique path. We have to prompt the user.
[email protected]da6e3922010-11-24 21:45:50480 VLOG(1) << "Unable to find a unique path for suggested path \""
[email protected]4cd82f72011-05-23 19:15:01481 << state.suggested_path.value() << "\"";
482 state.prompt_user_for_save_location = true;
[email protected]7a256ea2008-10-17 17:34:16483 }
[email protected]9ccbb372008-10-10 18:50:32484 }
485
[email protected]594cd7d2010-07-21 03:23:56486 // Create an empty file at the suggested path so that we don't allocate the
487 // same "non-existant" path to multiple downloads.
488 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]4cd82f72011-05-23 19:15:01489 if (!state.prompt_user_for_save_location &&
490 state.force_file_name.empty()) {
491 if (state.IsDangerous())
492 file_util::WriteFile(state.suggested_path, "", 0);
[email protected]594cd7d2010-07-21 03:23:56493 else
494 file_util::WriteFile(download_util::GetCrDownloadPath(
[email protected]4cd82f72011-05-23 19:15:01495 state.suggested_path), "", 0);
[email protected]7d3851d82008-12-12 03:26:07496 }
497
[email protected]ca4b5fa32010-10-09 12:42:18498 BrowserThread::PostTask(
499 BrowserThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29500 NewRunnableMethod(this,
501 &DownloadManager::OnPathExistenceAvailable,
[email protected]4cd82f72011-05-23 19:15:01502 download_id,
503 state));
initial.commit09911bf2008-07-26 23:55:29504}
505
[email protected]22001462011-06-22 17:42:51506void DownloadManager::OnPathExistenceAvailable(
507 int32 download_id, const DownloadStateInfo& new_state) {
[email protected]ca4b5fa32010-10-09 12:42:18508 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29509
[email protected]4cd82f72011-05-23 19:15:01510 DownloadItem* download = GetActiveDownloadItem(download_id);
511 if (!download)
512 return;
513
514 VLOG(20) << __FUNCTION__ << "()"
515 << " download = " << download->DebugString(true);
516
517 download->SetFileCheckResults(new_state);
518
519 FilePath suggested_path = download->suggested_path();
520
521 if (download->save_as()) {
initial.commit09911bf2008-07-26 23:55:29522 // We must ask the user for the place to put the download.
523 if (!select_file_dialog_.get())
524 select_file_dialog_ = SelectFileDialog::Create(this);
525
[email protected]db6831a2011-06-09 21:08:28526 DownloadRequestHandle request_handle = download->request_handle();
527 TabContents* contents = request_handle.GetTabContents();
[email protected]b949f1112009-04-12 20:03:08528 SelectFileDialog::FileTypeInfo file_type_info;
[email protected]4cd82f72011-05-23 19:15:01529 FilePath::StringType extension = suggested_path.Extension();
[email protected]07038782011-04-29 17:08:07530 if (!extension.empty()) {
[email protected]f9a45b02011-06-30 23:49:19531 extension.erase(extension.begin()); // drop the .
[email protected]07038782011-04-29 17:08:07532 file_type_info.extensions.resize(1);
533 file_type_info.extensions[0].push_back(extension);
534 }
[email protected]b949f1112009-04-12 20:03:08535 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23536 gfx::NativeWindow owning_window =
537 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
[email protected]4cd82f72011-05-23 19:15:01538 // |id_ptr| will be deleted in either FileSelected() or
539 // FileSelectionCancelled().
540 int32* id_ptr = new int32;
541 *id_ptr = download_id;
initial.commit09911bf2008-07-26 23:55:29542 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34543 string16(),
[email protected]4cd82f72011-05-23 19:15:01544 suggested_path,
[email protected]b949f1112009-04-12 20:03:08545 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]4cd82f72011-05-23 19:15:01546 contents, owning_window,
547 reinterpret_cast<void*>(id_ptr));
[email protected]f5920322011-03-24 20:34:16548 FOR_EACH_OBSERVER(Observer, observers_,
[email protected]fed38252011-07-08 17:26:50549 SelectFileDialogDisplayed(download_id));
initial.commit09911bf2008-07-26 23:55:29550 } else {
551 // No prompting for download, just continue with the suggested name.
[email protected]4cd82f72011-05-23 19:15:01552 ContinueDownloadWithPath(download, suggested_path);
initial.commit09911bf2008-07-26 23:55:29553 }
554}
555
[email protected]c2e76012010-12-23 21:10:29556void DownloadManager::CreateDownloadItem(DownloadCreateInfo* info) {
557 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
558
559 DownloadItem* download = new DownloadItem(this, *info,
560 profile_->IsOffTheRecord());
[email protected]4cd82f72011-05-23 19:15:01561 int32 download_id = info->download_id;
562 DCHECK(!ContainsKey(in_progress_, download_id));
563 DCHECK(!ContainsKey(active_downloads_, download_id));
[email protected]c2e76012010-12-23 21:10:29564 downloads_.insert(download);
[email protected]4cd82f72011-05-23 19:15:01565 active_downloads_[download_id] = download;
[email protected]c2e76012010-12-23 21:10:29566}
567
[email protected]4cd82f72011-05-23 19:15:01568void DownloadManager::ContinueDownloadWithPath(DownloadItem* download,
569 const FilePath& chosen_file) {
[email protected]ca4b5fa32010-10-09 12:42:18570 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]4cd82f72011-05-23 19:15:01571 DCHECK(download);
[email protected]aa033af2010-07-27 18:16:39572
[email protected]4cd82f72011-05-23 19:15:01573 int32 download_id = download->id();
initial.commit09911bf2008-07-26 23:55:29574
[email protected]70850c72011-01-11 17:31:27575 // NOTE(ahendrickson) Eventually |active_downloads_| will replace
576 // |in_progress_|, but we don't want to change the semantics yet.
[email protected]4cd82f72011-05-23 19:15:01577 DCHECK(!ContainsKey(in_progress_, download_id));
[email protected]70850c72011-01-11 17:31:27578 DCHECK(ContainsKey(downloads_, download));
[email protected]4cd82f72011-05-23 19:15:01579 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]70850c72011-01-11 17:31:27580
[email protected]4cd82f72011-05-23 19:15:01581 // Make sure the initial file name is set only once.
582 DCHECK(download->full_path().empty());
583 download->OnPathDetermined(chosen_file);
584 download->UpdateTarget();
585
586 VLOG(20) << __FUNCTION__ << "()"
587 << " download = " << download->DebugString(true);
588
589 in_progress_[download_id] = download;
[email protected]adb2f3d12011-01-23 16:24:54590 UpdateAppIcon(); // Reflect entry into in_progress_.
initial.commit09911bf2008-07-26 23:55:29591
[email protected]adb2f3d12011-01-23 16:24:54592 // Rename to intermediate name.
[email protected]f5920322011-03-24 20:34:16593 FilePath download_path;
[email protected]4cd82f72011-05-23 19:15:01594 if (download->IsDangerous()) {
[email protected]adb2f3d12011-01-23 16:24:54595 // The download is not safe. We can now rename the file to its
[email protected]f5920322011-03-24 20:34:16596 // tentative name using RenameInProgressDownloadFile.
597 // NOTE: The |Rename| below will be a no-op for dangerous files, as we're
598 // renaming it to the same name.
[email protected]4cd82f72011-05-23 19:15:01599 download_path = download->full_path();
[email protected]594cd7d2010-07-21 03:23:56600 } else {
[email protected]adb2f3d12011-01-23 16:24:54601 // The download is a safe download. We need to
602 // rename it to its intermediate '.crdownload' path. The final
603 // name after user confirmation will be set from
[email protected]48837962011-04-19 17:03:29604 // DownloadItem::OnDownloadCompleting.
[email protected]4cd82f72011-05-23 19:15:01605 download_path =
606 download_util::GetCrDownloadPath(download->full_path());
[email protected]594cd7d2010-07-21 03:23:56607 }
608
[email protected]f5920322011-03-24 20:34:16609 BrowserThread::PostTask(
610 BrowserThread::FILE, FROM_HERE,
611 NewRunnableMethod(
612 file_manager_, &DownloadFileManager::RenameInProgressDownloadFile,
613 download->id(), download_path));
614
615 download->Rename(download_path);
616
[email protected]4cd82f72011-05-23 19:15:01617 download_history_->AddEntry(download,
[email protected]82f37b02010-07-29 22:04:57618 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
initial.commit09911bf2008-07-26 23:55:29619}
620
initial.commit09911bf2008-07-26 23:55:29621void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
[email protected]70850c72011-01-11 17:31:27622 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
623 DownloadMap::iterator it = active_downloads_.find(download_id);
624 if (it != active_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29625 DownloadItem* download = it->second;
[email protected]bf68a00b2011-04-07 17:28:26626 if (download->IsInProgress()) {
[email protected]70850c72011-01-11 17:31:27627 download->Update(size);
[email protected]adb2f3d12011-01-23 16:24:54628 UpdateAppIcon(); // Reflect size updates.
[email protected]70850c72011-01-11 17:31:27629 download_history_->UpdateEntry(download);
630 }
initial.commit09911bf2008-07-26 23:55:29631 }
632}
633
[email protected]bf68a00b2011-04-07 17:28:26634void DownloadManager::OnResponseCompleted(int32 download_id,
635 int64 size,
636 int os_error,
637 const std::string& hash) {
638 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]7c8e55ba2011-07-01 18:59:23639 // ERR_CONNECTION_CLOSED is allowed since a number of servers in the wild
640 // advertise a larger Content-Length than the amount of bytes in the message
641 // body, and then close the connection. Other browsers - IE8, Firefox 4.0.1,
642 // and Safari 5.0.4 - treat the download as complete in this case, so we
643 // follow their lead.
[email protected]cf3ea772011-07-07 22:14:11644 // EXPERIMENT(ahendrickson) -- Treat ERR_CONNECTION_CLOSED as an error to
645 // gather statistics. To be reverted in a few days.
646 if (os_error == 0) {
[email protected]bf68a00b2011-04-07 17:28:26647 OnAllDataSaved(download_id, size, hash);
648 } else {
649 OnDownloadError(download_id, size, os_error);
650 }
651}
652
[email protected]26711732011-03-09 00:21:22653void DownloadManager::OnAllDataSaved(int32 download_id,
654 int64 size,
655 const std::string& hash) {
[email protected]da6e3922010-11-24 21:45:50656 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
657 << " size = " << size;
[email protected]9d7ef802011-02-25 19:03:35658 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:32659
[email protected]c4f02c42011-01-24 21:55:06660 // If it's not in active_downloads_, that means it was cancelled; just
661 // ignore the notification.
662 if (active_downloads_.count(download_id) == 0)
663 return;
664
[email protected]adb2f3d12011-01-23 16:24:54665 DownloadItem* download = active_downloads_[download_id];
[email protected]a850ba42010-09-10 22:00:30666 download->OnAllDataSaved(size);
[email protected]9ccbb372008-10-10 18:50:32667
[email protected]26711732011-03-09 00:21:22668 // When hash is not available, it means either it is not calculated
669 // or there is error while it is calculated. We will skip the download hash
670 // check in that case.
671 if (!hash.empty()) {
[email protected]4b58e7d2011-07-11 10:22:56672#if defined(ENABLE_SAFE_BROWSING)
[email protected]26711732011-03-09 00:21:22673 scoped_refptr<DownloadSBClient> sb_client =
674 new DownloadSBClient(download_id,
[email protected]8799e542011-04-20 03:47:34675 download->url_chain(),
[email protected]26711732011-03-09 00:21:22676 download->referrer_url());
677 sb_client->CheckDownloadHash(
678 hash, NewCallback(this, &DownloadManager::CheckDownloadHashDone));
[email protected]4b58e7d2011-07-11 10:22:56679#else
680 CheckDownloadHashDone(download_id, false);
681#endif
[email protected]26711732011-03-09 00:21:22682 }
[email protected]adb2f3d12011-01-23 16:24:54683 MaybeCompleteDownload(download);
684}
[email protected]9ccbb372008-10-10 18:50:32685
[email protected]26711732011-03-09 00:21:22686// TODO(lzheng): This function currently works as a callback place holder.
687// Once we decide the hash check is reliable, we could move the
688// MaybeCompleteDownload in OnAllDataSaved to this function.
689void DownloadManager::CheckDownloadHashDone(int32 download_id,
690 bool is_dangerous_hash) {
691 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
692 DVLOG(1) << "CheckDownloadHashDone, download_id: " << download_id
693 << " is dangerous_hash: " << is_dangerous_hash;
694
695 // If it's not in active_downloads_, that means it was cancelled or
696 // the download already finished.
697 if (active_downloads_.count(download_id) == 0)
698 return;
699
700 DVLOG(1) << "CheckDownloadHashDone, url: "
[email protected]4cd82f72011-05-23 19:15:01701 << active_downloads_[download_id]->GetURL().spec();
[email protected]26711732011-03-09 00:21:22702}
703
[email protected]7d413112011-06-16 18:50:17704void DownloadManager::AssertQueueStateConsistent(DownloadItem* download) {
[email protected]5cd11b6e2011-06-10 20:30:59705 // TODO(rdsmith): Change to DCHECK after http://crbug.com/85408 resolved.
[email protected]7d413112011-06-16 18:50:17706 if (download->state() == DownloadItem::REMOVING) {
707 CHECK(!ContainsKey(downloads_, download));
708 CHECK(!ContainsKey(active_downloads_, download->id()));
709 CHECK(!ContainsKey(in_progress_, download->id()));
710 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
711 return;
712 }
713
714 // Should be in downloads_ if we're not REMOVING.
715 CHECK(ContainsKey(downloads_, download));
716
717 // Check history_downloads_ consistency.
718 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
719 CHECK(ContainsKey(history_downloads_, download->db_handle()));
720 } else {
721 // TODO(rdsmith): Somewhat painful; make sure to disable in
722 // release builds after resolution of http://crbug.com/85408.
723 for (DownloadMap::iterator it = history_downloads_.begin();
724 it != history_downloads_.end(); ++it) {
725 CHECK(it->second != download);
726 }
727 }
728
729 CHECK(ContainsKey(active_downloads_, download->id()) ==
730 (download->state() == DownloadItem::IN_PROGRESS));
731 CHECK(ContainsKey(in_progress_, download->id()) ==
732 (download->state() == DownloadItem::IN_PROGRESS));
[email protected]5cd11b6e2011-06-10 20:30:59733}
734
[email protected]adb2f3d12011-01-23 16:24:54735bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
736 // If we don't have all the data, the download is not ready for
737 // completion.
738 if (!download->all_data_saved())
739 return false;
[email protected]6a7fb042010-02-01 16:30:47740
[email protected]9d7ef802011-02-25 19:03:35741 // If the download is dangerous, but not yet validated, it's not ready for
742 // completion.
743 if (download->safety_state() == DownloadItem::DANGEROUS)
744 return false;
745
[email protected]adb2f3d12011-01-23 16:24:54746 // If the download isn't active (e.g. has been cancelled) it's not
747 // ready for completion.
748 if (active_downloads_.count(download->id()) == 0)
749 return false;
750
751 // If the download hasn't been inserted into the history system
752 // (which occurs strictly after file name determination, intermediate
753 // file rename, and UI display) then it's not ready for completion.
[email protected]7054b592011-06-22 14:46:42754 if (download->db_handle() == DownloadHistory::kUninitializedHandle)
755 return false;
756
757 return true;
[email protected]adb2f3d12011-01-23 16:24:54758}
759
760void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
761 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
762 VLOG(20) << __FUNCTION__ << "()" << " download = "
763 << download->DebugString(false);
764
765 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32766 return;
[email protected]9ccbb372008-10-10 18:50:32767
[email protected]adb2f3d12011-01-23 16:24:54768 // TODO(rdsmith): DCHECK that we only pass through this point
769 // once per download. The natural way to do this is by a state
770 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56771
[email protected]adb2f3d12011-01-23 16:24:54772 // Confirm we're in the proper set of states to be here;
[email protected]9d7ef802011-02-25 19:03:35773 // in in_progress_, have all data, have a history handle, (validated or safe).
774 DCHECK_NE(DownloadItem::DANGEROUS, download->safety_state());
[email protected]adb2f3d12011-01-23 16:24:54775 DCHECK_EQ(1u, in_progress_.count(download->id()));
776 DCHECK(download->all_data_saved());
777 DCHECK(download->db_handle() != DownloadHistory::kUninitializedHandle);
778 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
779
780 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
781 << download->DebugString(false);
782
783 // Remove the id from in_progress
784 in_progress_.erase(download->id());
785 UpdateAppIcon(); // Reflect removal from in_progress_.
786
[email protected]adb2f3d12011-01-23 16:24:54787 download_history_->UpdateEntry(download);
788
[email protected]f5920322011-03-24 20:34:16789 // Finish the download.
[email protected]48837962011-04-19 17:03:29790 download->OnDownloadCompleting(file_manager_);
[email protected]9ccbb372008-10-10 18:50:32791}
792
[email protected]cc3c7c092011-05-09 18:40:21793void DownloadManager::DownloadCompleted(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27794 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21795 DownloadItem* download = GetDownloadItem(download_id);
796 DCHECK(download);
797 download_history_->UpdateEntry(download);
[email protected]70850c72011-01-11 17:31:27798 active_downloads_.erase(download_id);
799}
800
[email protected]f5920322011-03-24 20:34:16801void DownloadManager::OnDownloadRenamedToFinalName(int download_id,
802 const FilePath& full_path,
803 int uniquifier) {
[email protected]da6e3922010-11-24 21:45:50804 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
[email protected]f5920322011-03-24 20:34:16805 << " full_path = \"" << full_path.value() << "\""
806 << " uniquifier = " << uniquifier;
[email protected]ca4b5fa32010-10-09 12:42:18807 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]f5920322011-03-24 20:34:16808
[email protected]2e030682010-07-23 19:45:36809 DownloadItem* item = GetDownloadItem(download_id);
810 if (!item)
811 return;
[email protected]6cade212008-12-03 00:32:22812
[email protected]8fa1eeb52011-04-13 14:18:02813 if (item->safety_state() == DownloadItem::SAFE) {
814 DCHECK_EQ(0, uniquifier) << "We should not uniquify SAFE downloads twice";
815 }
816
[email protected]ca4b5fa32010-10-09 12:42:18817 BrowserThread::PostTask(
[email protected]f5920322011-03-24 20:34:16818 BrowserThread::FILE, FROM_HERE,
819 NewRunnableMethod(
820 file_manager_, &DownloadFileManager::CompleteDownload, download_id));
[email protected]9ccbb372008-10-10 18:50:32821
[email protected]f5920322011-03-24 20:34:16822 if (uniquifier)
823 item->set_path_uniquifier(uniquifier);
[email protected]9ccbb372008-10-10 18:50:32824
[email protected]f5920322011-03-24 20:34:16825 item->OnDownloadRenamedToFinalName(full_path);
826 download_history_->UpdateDownloadPath(item, full_path);
initial.commit09911bf2008-07-26 23:55:29827}
828
initial.commit09911bf2008-07-26 23:55:29829void DownloadManager::DownloadCancelled(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27830 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29831 DownloadMap::iterator it = in_progress_.find(download_id);
832 if (it == in_progress_.end())
833 return;
834 DownloadItem* download = it->second;
835
[email protected]da6e3922010-11-24 21:45:50836 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
837 << " download = " << download->DebugString(true);
838
initial.commit09911bf2008-07-26 23:55:29839 // Clean up will happen when the history system create callback runs if we
840 // don't have a valid db_handle yet.
[email protected]82f37b02010-07-29 22:04:57841 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
initial.commit09911bf2008-07-26 23:55:29842 in_progress_.erase(it);
[email protected]70850c72011-01-11 17:31:27843 active_downloads_.erase(download_id);
[email protected]adb2f3d12011-01-23 16:24:54844 UpdateAppIcon(); // Reflect removal from in_progress_.
[email protected]82f37b02010-07-29 22:04:57845 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29846 }
847
[email protected]db6831a2011-06-09 21:08:28848 DownloadCancelledInternal(download_id, download->request_handle());
[email protected]d7d1c5c2009-08-05 23:52:50849}
850
[email protected]bc932ef2011-05-11 12:14:13851void DownloadManager::DownloadCancelledInternal(
[email protected]f0a151f2011-07-08 22:26:15852 int download_id, const DownloadRequestHandle& request_handle) {
[email protected]f5920322011-03-24 20:34:16853 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]db6831a2011-06-09 21:08:28854 request_handle.CancelRequest();
[email protected]d7d1c5c2009-08-05 23:52:50855
[email protected]ca4b5fa32010-10-09 12:42:18856 BrowserThread::PostTask(
857 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37858 NewRunnableMethod(
859 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29860}
861
[email protected]bf68a00b2011-04-07 17:28:26862void DownloadManager::OnDownloadError(int32 download_id,
863 int64 size,
864 int os_error) {
865 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
866 DownloadMap::iterator it = active_downloads_.find(download_id);
867 // A cancel at the right time could remove the download from the
868 // |active_downloads_| map before we get here.
869 if (it == active_downloads_.end())
870 return;
871
872 DownloadItem* download = it->second;
873
[email protected]4cd82f72011-05-23 19:15:01874 VLOG(20) << __FUNCTION__ << "()" << " Error " << os_error
875 << " at offset " << download->received_bytes()
876 << " for download = " << download->DebugString(true);
877
878 download->Interrupted(size, os_error);
[email protected]bf68a00b2011-04-07 17:28:26879
880 // TODO(ahendrickson) - Remove this when we add resuming of interrupted
881 // downloads, as we will keep the download item around in that case.
882 //
883 // Clean up will happen when the history system create callback runs if we
884 // don't have a valid db_handle yet.
885 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
886 in_progress_.erase(download_id);
887 active_downloads_.erase(download_id);
888 UpdateAppIcon(); // Reflect removal from in_progress_.
889 download_history_->UpdateEntry(download);
890 }
891
[email protected]bf68a00b2011-04-07 17:28:26892 BrowserThread::PostTask(
893 BrowserThread::FILE, FROM_HERE,
894 NewRunnableMethod(
895 file_manager_, &DownloadFileManager::CancelDownload, download_id));
896}
897
[email protected]6a7fb042010-02-01 16:30:47898void DownloadManager::UpdateAppIcon() {
[email protected]073ed7b2010-09-27 09:20:02899 if (status_updater_)
900 status_updater_->Update();
[email protected]6a7fb042010-02-01 16:30:47901}
902
initial.commit09911bf2008-07-26 23:55:29903void DownloadManager::RemoveDownload(int64 download_handle) {
[email protected]f04182f32010-12-10 19:12:07904 DownloadMap::iterator it = history_downloads_.find(download_handle);
905 if (it == history_downloads_.end())
initial.commit09911bf2008-07-26 23:55:29906 return;
907
908 // Make history update.
909 DownloadItem* download = it->second;
[email protected]82f37b02010-07-29 22:04:57910 download_history_->RemoveEntry(download);
initial.commit09911bf2008-07-26 23:55:29911
912 // Remove from our tables and delete.
[email protected]f04182f32010-12-10 19:12:07913 history_downloads_.erase(it);
914 int downloads_count = downloads_.erase(download);
915 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29916
917 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:28918 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:36919
920 delete download;
initial.commit09911bf2008-07-26 23:55:29921}
922
[email protected]e93d2822009-01-30 05:59:59923int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
924 const base::Time remove_end) {
[email protected]82f37b02010-07-29 22:04:57925 download_history_->RemoveEntriesBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29926
[email protected]a312a442010-12-15 23:40:33927 // All downloads visible to the user will be in the history,
928 // so scan that map.
[email protected]f04182f32010-12-10 19:12:07929 DownloadMap::iterator it = history_downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:28930 std::vector<DownloadItem*> pending_deletes;
[email protected]f04182f32010-12-10 19:12:07931 while (it != history_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29932 DownloadItem* download = it->second;
initial.commit09911bf2008-07-26 23:55:29933 if (download->start_time() >= remove_begin &&
934 (remove_end.is_null() || download->start_time() < remove_end) &&
[email protected]bf68a00b2011-04-07 17:28:26935 (download->IsComplete() ||
936 download->IsCancelled() ||
937 download->IsInterrupted())) {
[email protected]7d413112011-06-16 18:50:17938 AssertQueueStateConsistent(download);
939
initial.commit09911bf2008-07-26 23:55:29940 // Remove from the map and move to the next in the list.
[email protected]f04182f32010-12-10 19:12:07941 history_downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:58942
943 // Also remove it from any completed dangerous downloads.
[email protected]78b8fcc92009-03-31 17:36:28944 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29945
initial.commit09911bf2008-07-26 23:55:29946 continue;
947 }
948
949 ++it;
950 }
951
[email protected]a312a442010-12-15 23:40:33952 // If we aren't deleting anything, we're done.
[email protected]57fd1252010-12-23 17:24:09953 if (pending_deletes.empty())
954 return 0;
initial.commit09911bf2008-07-26 23:55:29955
[email protected]a312a442010-12-15 23:40:33956 // Remove the chosen downloads from the main owning container.
957 for (std::vector<DownloadItem*>::iterator it = pending_deletes.begin();
958 it != pending_deletes.end(); it++) {
959 downloads_.erase(*it);
960 }
961
962 // Tell observers to refresh their views.
963 NotifyModelChanged();
964
965 // Delete the download items themselves.
[email protected]57fd1252010-12-23 17:24:09966 int num_deleted = static_cast<int>(pending_deletes.size());
967
[email protected]78b8fcc92009-03-31 17:36:28968 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
969 pending_deletes.clear();
970
initial.commit09911bf2008-07-26 23:55:29971 return num_deleted;
972}
973
[email protected]e93d2822009-01-30 05:59:59974int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
975 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29976}
977
[email protected]d41355e6f2009-04-07 21:21:12978int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:46979 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
980 // This is an incognito downloader. Clear All should clear main download
981 // manager as well.
982 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
983 }
[email protected]d41355e6f2009-04-07 21:21:12984 // The null times make the date range unbounded.
985 return RemoveDownloadsBetween(base::Time(), base::Time());
986}
987
[email protected]f9a45b02011-06-30 23:49:19988void DownloadManager::SavePageAsDownloadStarted(DownloadItem* download) {
[email protected]57fd1252010-12-23 17:24:09989#if !defined(NDEBUG)
[email protected]f9a45b02011-06-30 23:49:19990 save_page_as_downloads_.insert(download);
[email protected]57fd1252010-12-23 17:24:09991#endif
[email protected]f9a45b02011-06-30 23:49:19992 downloads_.insert(download);
993 // Add to history and notify observers.
994 AddDownloadItemToHistory(download, DownloadHistory::kUninitializedHandle);
995 NotifyModelChanged();
[email protected]ec4826a2010-09-21 09:15:59996}
997
initial.commit09911bf2008-07-26 23:55:29998// Initiate a download of a specific URL. We send the request to the
999// ResourceDispatcherHost, and let it send us responses like a regular
1000// download.
1001void DownloadManager::DownloadUrl(const GURL& url,
1002 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:501003 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:341004 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:261005 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
1006 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:581007}
1008
1009void DownloadManager::DownloadUrlToFile(const GURL& url,
1010 const GURL& referrer,
1011 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:321012 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:581013 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:341014 DCHECK(tab_contents);
[email protected]ed24fad2011-05-10 22:44:011015 // We send a pointer to content::ResourceContext, instead of the usual
1016 // reference, so that a copy of the object isn't made.
[email protected]ca4b5fa32010-10-09 12:42:181017 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:261018 NewRunnableFunction(&download_util::DownloadUrl,
1019 url,
1020 referrer,
1021 referrer_charset,
1022 save_info,
1023 g_browser_process->resource_dispatcher_host(),
1024 tab_contents->GetRenderProcessHost()->id(),
1025 tab_contents->render_view_host()->routing_id(),
[email protected]ed24fad2011-05-10 22:44:011026 &tab_contents->profile()->GetResourceContext()));
initial.commit09911bf2008-07-26 23:55:291027}
1028
initial.commit09911bf2008-07-26 23:55:291029void DownloadManager::AddObserver(Observer* observer) {
1030 observers_.AddObserver(observer);
1031 observer->ModelChanged();
1032}
1033
1034void DownloadManager::RemoveObserver(Observer* observer) {
1035 observers_.RemoveObserver(observer);
1036}
1037
[email protected]eccb9d12009-10-28 05:40:091038bool DownloadManager::ShouldOpenFileBasedOnExtension(
1039 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:091040 FilePath::StringType extension = path.Extension();
1041 if (extension.empty())
1042 return false;
[email protected]92e11c82010-01-13 06:39:561043 if (Extension::IsExtension(path))
1044 return false;
[email protected]eccb9d12009-10-28 05:40:091045 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1046 extension.erase(0, 1);
[email protected]e5dc4222010-08-30 22:16:321047 return download_prefs_->IsAutoOpenEnabledForExtension(extension);
initial.commit09911bf2008-07-26 23:55:291048}
1049
[email protected]073ed7b2010-09-27 09:20:021050bool DownloadManager::IsDownloadProgressKnown() {
1051 for (DownloadMap::iterator i = in_progress_.begin();
1052 i != in_progress_.end(); ++i) {
1053 if (i->second->total_bytes() <= 0)
1054 return false;
1055 }
1056
1057 return true;
1058}
1059
1060int64 DownloadManager::GetInProgressDownloadCount() {
1061 return in_progress_.size();
1062}
1063
1064int64 DownloadManager::GetReceivedDownloadBytes() {
1065 DCHECK(IsDownloadProgressKnown());
1066 int64 received_bytes = 0;
1067 for (DownloadMap::iterator i = in_progress_.begin();
1068 i != in_progress_.end(); ++i) {
1069 received_bytes += i->second->received_bytes();
1070 }
1071 return received_bytes;
1072}
1073
1074int64 DownloadManager::GetTotalDownloadBytes() {
1075 DCHECK(IsDownloadProgressKnown());
1076 int64 total_bytes = 0;
1077 for (DownloadMap::iterator i = in_progress_.begin();
1078 i != in_progress_.end(); ++i) {
1079 total_bytes += i->second->total_bytes();
1080 }
1081 return total_bytes;
1082}
1083
[email protected]561abe62009-04-06 18:08:341084void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361085 int index, void* params) {
[email protected]4cd82f72011-05-23 19:15:011086 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1087
1088 int32* id_ptr = reinterpret_cast<int32*>(params);
1089 DCHECK(id_ptr != NULL);
1090 int32 download_id = *id_ptr;
1091 delete id_ptr;
1092
1093 DownloadItem* download = GetActiveDownloadItem(download_id);
1094 if (!download)
1095 return;
1096 VLOG(20) << __FUNCTION__ << "()" << " path = \"" << path.value() << "\""
1097 << " download = " << download->DebugString(true);
1098
1099 if (download->save_as())
[email protected]7ae7c2cb2009-01-06 23:31:411100 last_download_path_ = path.DirName();
[email protected]287b86b2011-02-26 00:11:351101
[email protected]4cd82f72011-05-23 19:15:011102 // Make sure the initial file name is set only once.
1103 ContinueDownloadWithPath(download, path);
initial.commit09911bf2008-07-26 23:55:291104}
1105
1106void DownloadManager::FileSelectionCanceled(void* params) {
1107 // The user didn't pick a place to save the file, so need to cancel the
1108 // download that's already in progress to the temporary location.
[email protected]4cd82f72011-05-23 19:15:011109 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1110 int32* id_ptr = reinterpret_cast<int32*>(params);
1111 DCHECK(id_ptr != NULL);
1112 int32 download_id = *id_ptr;
1113 delete id_ptr;
1114
1115 DownloadItem* download = GetActiveDownloadItem(download_id);
1116 if (!download)
1117 return;
1118
1119 VLOG(20) << __FUNCTION__ << "()"
1120 << " download = " << download->DebugString(true);
1121
[email protected]db6831a2011-06-09 21:08:281122 DownloadCancelledInternal(download_id, download->request_handle());
[email protected]4cd82f72011-05-23 19:15:011123}
1124
1125// TODO(phajdan.jr): This is apparently not being exercised in tests.
1126bool DownloadManager::IsDangerous(const DownloadItem& download,
[email protected]88008002011-05-24 23:14:151127 const DownloadStateInfo& state,
1128 bool visited_referrer_before) {
[email protected]4cd82f72011-05-23 19:15:011129 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1130
1131 bool auto_open = ShouldOpenFileBasedOnExtension(state.suggested_path);
1132 download_util::DownloadDangerLevel danger_level =
1133 download_util::GetFileDangerLevel(state.suggested_path.BaseName());
1134
1135 if (danger_level == download_util::Dangerous)
1136 return !(auto_open && state.has_user_gesture);
1137
1138 if (danger_level == download_util::AllowOnUserGesture &&
[email protected]88008002011-05-24 23:14:151139 (!state.has_user_gesture || !visited_referrer_before))
[email protected]4cd82f72011-05-23 19:15:011140 return true;
1141
1142 if (state.is_extension_install) {
1143 // Extensions that are not from the gallery are considered dangerous.
1144 ExtensionService* service = profile()->GetExtensionService();
1145 if (!service || !service->IsDownloadFromGallery(download.GetURL(),
1146 download.referrer_url()))
1147 return true;
1148 }
1149 return false;
initial.commit09911bf2008-07-26 23:55:291150}
1151
[email protected]9ccbb372008-10-10 18:50:321152void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
[email protected]9d7ef802011-02-25 19:03:351153 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:321154 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1155 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1156 download->UpdateObservers();
1157
[email protected]9d7ef802011-02-25 19:03:351158 MaybeCompleteDownload(download);
[email protected]9ccbb372008-10-10 18:50:321159}
1160
initial.commit09911bf2008-07-26 23:55:291161// Operations posted to us from the history service ----------------------------
1162
1163// The history service has retrieved all download entries. 'entries' contains
[email protected]4cd82f72011-05-23 19:15:011164// 'DownloadHistoryInfo's in sorted order (by ascending start_time).
initial.commit09911bf2008-07-26 23:55:291165void DownloadManager::OnQueryDownloadEntriesComplete(
[email protected]4cd82f72011-05-23 19:15:011166 std::vector<DownloadHistoryInfo>* entries) {
initial.commit09911bf2008-07-26 23:55:291167 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:391168 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]f04182f32010-12-10 19:12:071169 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
1170 downloads_.insert(download);
1171 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:501172 VLOG(20) << __FUNCTION__ << "()" << i << ">"
1173 << " download = " << download->DebugString(true);
initial.commit09911bf2008-07-26 23:55:291174 }
[email protected]b0ab1d42010-02-24 19:29:281175 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:481176 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:291177}
1178
[email protected]f9a45b02011-06-30 23:49:191179void DownloadManager::AddDownloadItemToHistory(DownloadItem* download,
1180 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:271181 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d2a8fb72010-01-21 05:31:421182
[email protected]5bcd73eb2011-03-23 21:14:021183 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1184 // call this function with an invalid |db_handle|. For instance, this can
1185 // happen when the history database is offline. We cannot have multiple
1186 // DownloadItems with the same invalid db_handle, so we need to assign a
1187 // unique |db_handle| here.
1188 if (db_handle == DownloadHistory::kUninitializedHandle)
1189 db_handle = download_history_->GetNextFakeDbHandle();
1190
[email protected]1e9fe7ff2011-06-24 17:37:331191 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/84508
1192 // is fixed.
1193 CHECK_NE(DownloadHistory::kUninitializedHandle, db_handle);
1194
[email protected]5bcd73eb2011-03-23 21:14:021195 DCHECK(download->db_handle() == DownloadHistory::kUninitializedHandle);
1196 download->set_db_handle(db_handle);
1197
[email protected]5bcd73eb2011-03-23 21:14:021198 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
1199 history_downloads_[download->db_handle()] = download;
[email protected]f9a45b02011-06-30 23:49:191200}
1201
1202// Once the new DownloadItem's creation info has been committed to the history
1203// service, we associate the DownloadItem with the db handle, update our
1204// 'history_downloads_' map and inform observers.
1205void DownloadManager::OnCreateDownloadEntryComplete(int32 download_id,
1206 int64 db_handle) {
1207 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1208 DownloadItem* download = GetActiveDownloadItem(download_id);
1209 if (!download)
1210 return;
1211
1212 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
1213 << " download_id = " << download_id
1214 << " download = " << download->DebugString(true);
1215
1216 AddDownloadItemToHistory(download, db_handle);
initial.commit09911bf2008-07-26 23:55:291217
[email protected]70850c72011-01-11 17:31:271218 // Show in the appropriate browser UI.
[email protected]9d7ef802011-02-25 19:03:351219 // This includes buttons to save or cancel, for a dangerous download.
[email protected]4cd82f72011-05-23 19:15:011220 ShowDownloadInBrowser(download);
initial.commit09911bf2008-07-26 23:55:291221
1222 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281223 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291224
[email protected]bf68a00b2011-04-07 17:28:261225 // If the download is still in progress, try to complete it.
[email protected]adb2f3d12011-01-23 16:24:541226 //
[email protected]bf68a00b2011-04-07 17:28:261227 // Otherwise, download has been cancelled or interrupted before we've
1228 // received the DB handle. We post one final message to the history
1229 // service so that it can be properly in sync with the DownloadItem's
1230 // completion status, and also inform any observers so that they get
1231 // more than just the start notification.
1232 if (download->IsInProgress()) {
1233 MaybeCompleteDownload(download);
1234 } else {
1235 DCHECK(download->IsCancelled())
1236 << " download = " << download->DebugString(true);
[email protected]4cd82f72011-05-23 19:15:011237 in_progress_.erase(download_id);
1238 active_downloads_.erase(download_id);
[email protected]82f37b02010-07-29 22:04:571239 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:291240 download->UpdateObservers();
1241 }
1242}
1243
[email protected]4cd82f72011-05-23 19:15:011244void DownloadManager::ShowDownloadInBrowser(DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341245 // The 'contents' may no longer exist if the user closed the tab before we
1246 // get this start completion event. If it does, tell the origin TabContents
1247 // to display its download shelf.
[email protected]db6831a2011-06-09 21:08:281248 DownloadRequestHandle request_handle = download->request_handle();
1249 TabContents* contents = request_handle.GetTabContents();
[email protected]ddb85052011-05-18 14:40:271250 TabContentsWrapper* wrapper = NULL;
1251 if (contents)
1252 wrapper = TabContentsWrapper::GetCurrentWrapperForContents(contents);
[email protected]5e595482009-05-06 20:16:531253
1254 // If the contents no longer exists, we start the download in the last active
1255 // browser. This is not ideal but better than fully hiding the download from
1256 // the user.
[email protected]ddb85052011-05-18 14:40:271257 if (!wrapper) {
[email protected]4c9c5942011-06-20 18:28:021258 Browser* last_active = BrowserList::GetLastActiveWithProfile(profile_);
[email protected]5e595482009-05-06 20:16:531259 if (last_active)
[email protected]ddb85052011-05-18 14:40:271260 wrapper = last_active->GetSelectedTabContentsWrapper();
[email protected]5e595482009-05-06 20:16:531261 }
1262
[email protected]ddb85052011-05-18 14:40:271263 if (!wrapper)
[email protected]bc932ef2011-05-11 12:14:131264 return;
1265
[email protected]ddb85052011-05-18 14:40:271266 wrapper->download_tab_helper()->OnStartDownload(download);
[email protected]5e595482009-05-06 20:16:531267}
1268
[email protected]6cade212008-12-03 00:32:221269// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121270void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411271 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381272}
[email protected]b0ab1d42010-02-24 19:29:281273
1274void DownloadManager::NotifyModelChanged() {
1275 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1276}
1277
[email protected]4cd82f72011-05-23 19:15:011278DownloadItem* DownloadManager::GetDownloadItem(int download_id) {
1279 // The |history_downloads_| map is indexed by the download's db_handle,
1280 // not its id, so we have to iterate.
[email protected]f04182f32010-12-10 19:12:071281 for (DownloadMap::iterator it = history_downloads_.begin();
1282 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:361283 DownloadItem* item = it->second;
[email protected]4cd82f72011-05-23 19:15:011284 if (item->id() == download_id)
[email protected]2e030682010-07-23 19:45:361285 return item;
1286 }
1287 return NULL;
1288}
1289
[email protected]4cd82f72011-05-23 19:15:011290DownloadItem* DownloadManager::GetActiveDownloadItem(int download_id) {
1291 DCHECK(ContainsKey(active_downloads_, download_id));
1292 DownloadItem* download = active_downloads_[download_id];
1293 DCHECK(download != NULL);
1294 return download;
1295}
1296
[email protected]57fd1252010-12-23 17:24:091297// Confirm that everything in all maps is also in |downloads_|, and that
1298// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:071299void DownloadManager::AssertContainersConsistent() const {
1300#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:091301 // Turn everything into sets.
[email protected]adb2f3d12011-01-23 16:24:541302 DownloadSet active_set, history_set;
[email protected]70850c72011-01-11 17:31:271303 const DownloadMap* input_maps[] = {&active_downloads_, &history_downloads_};
[email protected]adb2f3d12011-01-23 16:24:541304 DownloadSet* local_sets[] = {&active_set, &history_set};
[email protected]57fd1252010-12-23 17:24:091305 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(local_sets));
1306 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
1307 for (DownloadMap::const_iterator it = input_maps[i]->begin();
1308 it != input_maps[i]->end(); it++) {
1309 local_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:071310 }
1311 }
[email protected]57fd1252010-12-23 17:24:091312
1313 // Check if each set is fully present in downloads, and create a union.
[email protected]adb2f3d12011-01-23 16:24:541314 const DownloadSet* all_sets[] = {&active_set, &history_set,
[email protected]57fd1252010-12-23 17:24:091315 &save_page_as_downloads_};
1316 DownloadSet downloads_union;
1317 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
1318 DownloadSet remainder;
1319 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
1320 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
1321 downloads_.begin(), downloads_.end(),
1322 insert_it);
1323 DCHECK(remainder.empty());
1324 std::insert_iterator<DownloadSet>
1325 insert_union(downloads_union, downloads_union.end());
1326 std::set_union(downloads_union.begin(), downloads_union.end(),
1327 all_sets[i]->begin(), all_sets[i]->end(),
1328 insert_union);
1329 }
1330
1331 // Is everything in downloads_ present in one of the other sets?
1332 DownloadSet remainder;
1333 std::insert_iterator<DownloadSet>
1334 insert_remainder(remainder, remainder.begin());
1335 std::set_difference(downloads_.begin(), downloads_.end(),
1336 downloads_union.begin(), downloads_union.end(),
1337 insert_remainder);
1338 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071339#endif
1340}
1341
[email protected]b0ab1d42010-02-24 19:29:281342// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1343
1344DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1345 DownloadManager* observing_download_manager)
1346 : observing_download_manager_(observing_download_manager),
1347 observed_download_manager_(NULL) {
1348 if (observing_download_manager->profile_->GetOriginalProfile() ==
1349 observing_download_manager->profile_) {
1350 return;
1351 }
1352
1353 observed_download_manager_ = observing_download_manager_->
1354 profile_->GetOriginalProfile()->GetDownloadManager();
1355 observed_download_manager_->AddObserver(this);
1356}
1357
1358DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1359 if (observed_download_manager_)
1360 observed_download_manager_->RemoveObserver(this);
1361}
1362
1363void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1364 observing_download_manager_->NotifyModelChanged();
1365}
1366
[email protected]b0ab1d42010-02-24 19:29:281367void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1368 observed_download_manager_ = NULL;
1369}