blob: 0be279e5fe41ee82e2b045fafe5998503ee55176 [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"
initial.commit09911bf2008-07-26 23:55:2911#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]f20d7332011-03-08 21:11:5345#include "content/common/notification_type.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]287b86b2011-02-26 00:11:35269 // Create a client to verify download URL with safebrowsing.
270 // It deletes itself after the callback.
[email protected]26711732011-03-09 00:21:22271 scoped_refptr<DownloadSBClient> sb_client = new DownloadSBClient(
[email protected]4cd82f72011-05-23 19:15:01272 download_id, download->url_chain(), download->referrer_url());
[email protected]287b86b2011-02-26 00:11:35273 sb_client->CheckDownloadUrl(
[email protected]4cd82f72011-05-23 19:15:01274 NewCallback(this, &DownloadManager::CheckDownloadUrlDone));
[email protected]287b86b2011-02-26 00:11:35275}
276
[email protected]9fc114672011-06-15 08:17:48277void DownloadManager::CheckForHistoryFilesRemoval() {
278 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
279 for (DownloadMap::iterator it = history_downloads_.begin();
280 it != history_downloads_.end(); ++it) {
281 CheckForFileRemoval(it->second);
282 }
283}
284
285void DownloadManager::CheckForFileRemoval(DownloadItem* download_item) {
286 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
287 if (download_item->IsComplete() &&
288 !download_item->file_externally_removed()) {
289 BrowserThread::PostTask(
290 BrowserThread::FILE, FROM_HERE,
291 NewRunnableMethod(this,
292 &DownloadManager::CheckForFileRemovalOnFileThread,
293 download_item->db_handle(),
294 download_item->GetTargetFilePath()));
295 }
296}
297
298void DownloadManager::CheckForFileRemovalOnFileThread(
299 int64 db_handle, const FilePath& path) {
300 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
301 if (!file_util::PathExists(path)) {
302 BrowserThread::PostTask(
303 BrowserThread::UI, FROM_HERE,
304 NewRunnableMethod(this,
305 &DownloadManager::OnFileRemovalDetected,
306 db_handle));
307 }
308}
309
310void DownloadManager::OnFileRemovalDetected(int64 db_handle) {
311 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
312 DownloadMap::iterator it = history_downloads_.find(db_handle);
313 if (it != history_downloads_.end()) {
314 DownloadItem* download_item = it->second;
315 download_item->OnDownloadedFileRemoved();
316 }
317}
318
[email protected]4cd82f72011-05-23 19:15:01319void DownloadManager::CheckDownloadUrlDone(int32 download_id,
[email protected]287b86b2011-02-26 00:11:35320 bool is_dangerous_url) {
321 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29322
[email protected]4cd82f72011-05-23 19:15:01323 DownloadItem* download = GetActiveDownloadItem(download_id);
324 if (!download)
325 return;
326
327 if (is_dangerous_url)
328 download->MarkUrlDangerous();
329
[email protected]88008002011-05-24 23:14:15330 download_history_->CheckVisitedReferrerBefore(download_id,
331 download->referrer_url(),
332 NewCallback(this, &DownloadManager::CheckVisitedReferrerBeforeDone));
333}
334
335void DownloadManager::CheckVisitedReferrerBeforeDone(
336 int32 download_id,
337 bool visited_referrer_before) {
338 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
339
340 DownloadItem* download = GetActiveDownloadItem(download_id);
341 if (!download)
342 return;
[email protected]287b86b2011-02-26 00:11:35343
[email protected]a60c8ae2009-12-25 06:50:57344 // Check whether this download is for an extension install or not.
[email protected]e6875c12010-07-18 11:14:13345 // Allow extensions to be explicitly saved.
[email protected]88008002011-05-24 23:14:15346 DownloadStateInfo state = download->state_info();
[email protected]4cd82f72011-05-23 19:15:01347 if (!state.prompt_user_for_save_location) {
348 if (UserScript::IsURLUserScript(download->GetURL(),
349 download->mime_type()) ||
350 (download->mime_type() == Extension::kMimeType)) {
351 state.is_extension_install = true;
[email protected]bac4f4b2011-03-05 02:01:40352 }
[email protected]a60c8ae2009-12-25 06:50:57353 }
354
[email protected]4cd82f72011-05-23 19:15:01355 if (state.force_file_name.empty()) {
[email protected]2941c2392010-07-15 22:54:30356 FilePath generated_name;
[email protected]4cd82f72011-05-23 19:15:01357 download_util::GenerateFileNameFromRequest(download->GetURL(),
358 download->content_disposition(),
359 download->referrer_charset(),
360 download->mime_type(),
361 &generated_name);
[email protected]2941c2392010-07-15 22:54:30362
363 // Freeze the user's preference for showing a Save As dialog. We're going
364 // to bounce around a bunch of threads and we don't want to worry about race
365 // conditions where the user changes this pref out from under us.
[email protected]0e9b6072011-02-17 12:42:05366 if (download_prefs_->PromptForDownload()) {
[email protected]2941c2392010-07-15 22:54:30367 // But ignore the user's preference for the following scenarios:
368 // 1) Extension installation. Note that we only care here about the case
369 // where an extension is installed, not when one is downloaded with
370 // "save as...".
371 // 2) Filetypes marked "always open." If the user just wants this file
372 // opened, don't bother asking where to keep it.
[email protected]4cd82f72011-05-23 19:15:01373 if (!state.is_extension_install &&
[email protected]2941c2392010-07-15 22:54:30374 !ShouldOpenFileBasedOnExtension(generated_name))
[email protected]4cd82f72011-05-23 19:15:01375 state.prompt_user_for_save_location = true;
[email protected]2941c2392010-07-15 22:54:30376 }
[email protected]14e0a102011-02-22 14:04:01377 if (download_prefs_->IsDownloadPathManaged()) {
[email protected]4cd82f72011-05-23 19:15:01378 state.prompt_user_for_save_location = false;
[email protected]14e0a102011-02-22 14:04:01379 }
[email protected]2941c2392010-07-15 22:54:30380
[email protected]8af9d032010-02-10 00:00:32381 // Determine the proper path for a download, by either one of the following:
382 // 1) using the default download directory.
383 // 2) prompting the user.
[email protected]4cd82f72011-05-23 19:15:01384 if (state.prompt_user_for_save_location && !last_download_path_.empty()) {
385 state.suggested_path = last_download_path_;
[email protected]80dc3612010-07-27 19:35:08386 } else {
[email protected]4cd82f72011-05-23 19:15:01387 state.suggested_path = download_prefs_->download_path();
[email protected]80dc3612010-07-27 19:35:08388 }
[email protected]4cd82f72011-05-23 19:15:01389 state.suggested_path = state.suggested_path.Append(generated_name);
[email protected]8af9d032010-02-10 00:00:32390 } else {
[email protected]4cd82f72011-05-23 19:15:01391 state.suggested_path = state.force_file_name;
[email protected]8af9d032010-02-10 00:00:32392 }
initial.commit09911bf2008-07-26 23:55:29393
[email protected]88008002011-05-24 23:14:15394 if (!state.prompt_user_for_save_location && state.force_file_name.empty()) {
395 state.is_dangerous_file =
396 IsDangerous(*download, state, visited_referrer_before);
397 }
[email protected]e9ebf3fc2008-10-17 22:06:58398
initial.commit09911bf2008-07-26 23:55:29399 // We need to move over to the download thread because we don't want to stat
400 // the suggested path on the UI thread.
[email protected]5a3b97e2010-10-05 09:49:11401 // We can only access preferences on the UI thread, so check the download path
402 // now and pass the value to the FILE thread.
[email protected]ca4b5fa32010-10-09 12:42:18403 BrowserThread::PostTask(
404 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37405 NewRunnableMethod(
[email protected]5a3b97e2010-10-05 09:49:11406 this,
407 &DownloadManager::CheckIfSuggestedPathExists,
[email protected]88008002011-05-24 23:14:15408 download->id(),
[email protected]4cd82f72011-05-23 19:15:01409 state,
[email protected]5a3b97e2010-10-05 09:49:11410 download_prefs()->download_path()));
initial.commit09911bf2008-07-26 23:55:29411}
412
[email protected]4cd82f72011-05-23 19:15:01413void DownloadManager::CheckIfSuggestedPathExists(int32 download_id,
414 DownloadStateInfo state,
[email protected]5a3b97e2010-10-05 09:49:11415 const FilePath& default_path) {
[email protected]ca4b5fa32010-10-09 12:42:18416 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
initial.commit09911bf2008-07-26 23:55:29417
[email protected]5a3b97e2010-10-05 09:49:11418 // Make sure the default download directory exists.
419 // TODO(phajdan.jr): only create the directory when we're sure the user
420 // is going to save there and not to another directory of his choice.
421 file_util::CreateDirectory(default_path);
422
initial.commit09911bf2008-07-26 23:55:29423 // Check writability of the suggested path. If we can't write to it, default
424 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]4cd82f72011-05-23 19:15:01425 FilePath dir = state.suggested_path.DirName();
426 FilePath filename = state.suggested_path.BaseName();
[email protected]9ccbb372008-10-10 18:50:32427 if (!file_util::PathIsWritable(dir)) {
[email protected]da6e3922010-11-24 21:45:50428 VLOG(1) << "Unable to write to directory \"" << dir.value() << "\"";
[email protected]4cd82f72011-05-23 19:15:01429 state.prompt_user_for_save_location = true;
430 PathService::Get(chrome::DIR_USER_DOCUMENTS, &state.suggested_path);
431 state.suggested_path = state.suggested_path.Append(filename);
initial.commit09911bf2008-07-26 23:55:29432 }
433
[email protected]6cade212008-12-03 00:32:22434 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]4cd82f72011-05-23 19:15:01435 if (state.IsDangerous()) {
436 state.target_name = FilePath(state.suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32437 // Create a temporary file to hold the file until the user approves its
438 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41439 FilePath::StringType file_name;
440 FilePath path;
[email protected]463e1b432011-01-21 22:05:51441#if defined(OS_WIN)
442 string16 unconfirmed_prefix =
443 l10n_util::GetStringUTF16(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
444#else
445 std::string unconfirmed_prefix =
446 l10n_util::GetStringUTF8(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
447#endif
448
[email protected]9ccbb372008-10-10 18:50:32449 while (path.empty()) {
[email protected]2594c2b2010-11-08 23:04:26450 base::SStringPrintf(
451 &file_name,
[email protected]463e1b432011-01-21 22:05:51452 unconfirmed_prefix.append(
453 FILE_PATH_LITERAL(" %d.crdownload")).c_str(),
[email protected]2594c2b2010-11-08 23:04:26454 base::RandInt(0, 100000));
[email protected]7ae7c2cb2009-01-06 23:31:41455 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07456 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41457 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32458 }
[email protected]4cd82f72011-05-23 19:15:01459 state.suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16460 } else {
[email protected]594cd7d2010-07-21 03:23:56461 // Do not add the path uniquifier if we are saving to a specific path as in
462 // the drag-out case.
[email protected]4cd82f72011-05-23 19:15:01463 if (state.force_file_name.empty()) {
464 state.path_uniquifier = download_util::GetUniquePathNumberWithCrDownload(
465 state.suggested_path);
[email protected]594cd7d2010-07-21 03:23:56466 }
[email protected]7a256ea2008-10-17 17:34:16467 // We know the final path, build it if necessary.
[email protected]4cd82f72011-05-23 19:15:01468 if (state.path_uniquifier > 0) {
469 download_util::AppendNumberToPath(&(state.suggested_path),
470 state.path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16471 // Setting path_uniquifier to 0 to make sure we don't try to unique it
472 // later on.
[email protected]4cd82f72011-05-23 19:15:01473 state.path_uniquifier = 0;
474 } else if (state.path_uniquifier == -1) {
[email protected]7d3851d82008-12-12 03:26:07475 // We failed to find a unique path. We have to prompt the user.
[email protected]da6e3922010-11-24 21:45:50476 VLOG(1) << "Unable to find a unique path for suggested path \""
[email protected]4cd82f72011-05-23 19:15:01477 << state.suggested_path.value() << "\"";
478 state.prompt_user_for_save_location = true;
[email protected]7a256ea2008-10-17 17:34:16479 }
[email protected]9ccbb372008-10-10 18:50:32480 }
481
[email protected]594cd7d2010-07-21 03:23:56482 // Create an empty file at the suggested path so that we don't allocate the
483 // same "non-existant" path to multiple downloads.
484 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]4cd82f72011-05-23 19:15:01485 if (!state.prompt_user_for_save_location &&
486 state.force_file_name.empty()) {
487 if (state.IsDangerous())
488 file_util::WriteFile(state.suggested_path, "", 0);
[email protected]594cd7d2010-07-21 03:23:56489 else
490 file_util::WriteFile(download_util::GetCrDownloadPath(
[email protected]4cd82f72011-05-23 19:15:01491 state.suggested_path), "", 0);
[email protected]7d3851d82008-12-12 03:26:07492 }
493
[email protected]ca4b5fa32010-10-09 12:42:18494 BrowserThread::PostTask(
495 BrowserThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29496 NewRunnableMethod(this,
497 &DownloadManager::OnPathExistenceAvailable,
[email protected]4cd82f72011-05-23 19:15:01498 download_id,
499 state));
initial.commit09911bf2008-07-26 23:55:29500}
501
[email protected]22001462011-06-22 17:42:51502void DownloadManager::OnPathExistenceAvailable(
503 int32 download_id, const DownloadStateInfo& new_state) {
[email protected]ca4b5fa32010-10-09 12:42:18504 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29505
[email protected]4cd82f72011-05-23 19:15:01506 DownloadItem* download = GetActiveDownloadItem(download_id);
507 if (!download)
508 return;
509
510 VLOG(20) << __FUNCTION__ << "()"
511 << " download = " << download->DebugString(true);
512
513 download->SetFileCheckResults(new_state);
514
515 FilePath suggested_path = download->suggested_path();
516
517 if (download->save_as()) {
initial.commit09911bf2008-07-26 23:55:29518 // We must ask the user for the place to put the download.
519 if (!select_file_dialog_.get())
520 select_file_dialog_ = SelectFileDialog::Create(this);
521
[email protected]db6831a2011-06-09 21:08:28522 DownloadRequestHandle request_handle = download->request_handle();
523 TabContents* contents = request_handle.GetTabContents();
[email protected]b949f1112009-04-12 20:03:08524 SelectFileDialog::FileTypeInfo file_type_info;
[email protected]4cd82f72011-05-23 19:15:01525 FilePath::StringType extension = suggested_path.Extension();
[email protected]07038782011-04-29 17:08:07526 if (!extension.empty()) {
[email protected]f9a45b02011-06-30 23:49:19527 extension.erase(extension.begin()); // drop the .
[email protected]07038782011-04-29 17:08:07528 file_type_info.extensions.resize(1);
529 file_type_info.extensions[0].push_back(extension);
530 }
[email protected]b949f1112009-04-12 20:03:08531 file_type_info.include_all_files = true;
[email protected]076700e62009-04-01 18:41:23532 gfx::NativeWindow owning_window =
533 contents ? platform_util::GetTopLevel(contents->GetNativeView()) : NULL;
[email protected]4cd82f72011-05-23 19:15:01534 // |id_ptr| will be deleted in either FileSelected() or
535 // FileSelectionCancelled().
536 int32* id_ptr = new int32;
537 *id_ptr = download_id;
initial.commit09911bf2008-07-26 23:55:29538 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
[email protected]561abe62009-04-06 18:08:34539 string16(),
[email protected]4cd82f72011-05-23 19:15:01540 suggested_path,
[email protected]b949f1112009-04-12 20:03:08541 &file_type_info, 0, FILE_PATH_LITERAL(""),
[email protected]4cd82f72011-05-23 19:15:01542 contents, owning_window,
543 reinterpret_cast<void*>(id_ptr));
[email protected]f5920322011-03-24 20:34:16544 FOR_EACH_OBSERVER(Observer, observers_,
[email protected]4cd82f72011-05-23 19:15:01545 SelectFileDialogDisplayed(download_id));
initial.commit09911bf2008-07-26 23:55:29546 } else {
547 // No prompting for download, just continue with the suggested name.
[email protected]4cd82f72011-05-23 19:15:01548 ContinueDownloadWithPath(download, suggested_path);
initial.commit09911bf2008-07-26 23:55:29549 }
550}
551
[email protected]c2e76012010-12-23 21:10:29552void DownloadManager::CreateDownloadItem(DownloadCreateInfo* info) {
553 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
554
555 DownloadItem* download = new DownloadItem(this, *info,
556 profile_->IsOffTheRecord());
[email protected]4cd82f72011-05-23 19:15:01557 int32 download_id = info->download_id;
558 DCHECK(!ContainsKey(in_progress_, download_id));
559 DCHECK(!ContainsKey(active_downloads_, download_id));
[email protected]c2e76012010-12-23 21:10:29560 downloads_.insert(download);
[email protected]4cd82f72011-05-23 19:15:01561 active_downloads_[download_id] = download;
[email protected]c2e76012010-12-23 21:10:29562}
563
[email protected]4cd82f72011-05-23 19:15:01564void DownloadManager::ContinueDownloadWithPath(DownloadItem* download,
565 const FilePath& chosen_file) {
[email protected]ca4b5fa32010-10-09 12:42:18566 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]4cd82f72011-05-23 19:15:01567 DCHECK(download);
[email protected]aa033af2010-07-27 18:16:39568
[email protected]4cd82f72011-05-23 19:15:01569 int32 download_id = download->id();
initial.commit09911bf2008-07-26 23:55:29570
[email protected]70850c72011-01-11 17:31:27571 // NOTE(ahendrickson) Eventually |active_downloads_| will replace
572 // |in_progress_|, but we don't want to change the semantics yet.
[email protected]4cd82f72011-05-23 19:15:01573 DCHECK(!ContainsKey(in_progress_, download_id));
[email protected]70850c72011-01-11 17:31:27574 DCHECK(ContainsKey(downloads_, download));
[email protected]4cd82f72011-05-23 19:15:01575 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]70850c72011-01-11 17:31:27576
[email protected]4cd82f72011-05-23 19:15:01577 // Make sure the initial file name is set only once.
578 DCHECK(download->full_path().empty());
579 download->OnPathDetermined(chosen_file);
580 download->UpdateTarget();
581
582 VLOG(20) << __FUNCTION__ << "()"
583 << " download = " << download->DebugString(true);
584
585 in_progress_[download_id] = download;
[email protected]adb2f3d12011-01-23 16:24:54586 UpdateAppIcon(); // Reflect entry into in_progress_.
initial.commit09911bf2008-07-26 23:55:29587
[email protected]adb2f3d12011-01-23 16:24:54588 // Rename to intermediate name.
[email protected]f5920322011-03-24 20:34:16589 FilePath download_path;
[email protected]4cd82f72011-05-23 19:15:01590 if (download->IsDangerous()) {
[email protected]adb2f3d12011-01-23 16:24:54591 // The download is not safe. We can now rename the file to its
[email protected]f5920322011-03-24 20:34:16592 // tentative name using RenameInProgressDownloadFile.
593 // NOTE: The |Rename| below will be a no-op for dangerous files, as we're
594 // renaming it to the same name.
[email protected]4cd82f72011-05-23 19:15:01595 download_path = download->full_path();
[email protected]594cd7d2010-07-21 03:23:56596 } else {
[email protected]adb2f3d12011-01-23 16:24:54597 // The download is a safe download. We need to
598 // rename it to its intermediate '.crdownload' path. The final
599 // name after user confirmation will be set from
[email protected]48837962011-04-19 17:03:29600 // DownloadItem::OnDownloadCompleting.
[email protected]4cd82f72011-05-23 19:15:01601 download_path =
602 download_util::GetCrDownloadPath(download->full_path());
[email protected]594cd7d2010-07-21 03:23:56603 }
604
[email protected]f5920322011-03-24 20:34:16605 BrowserThread::PostTask(
606 BrowserThread::FILE, FROM_HERE,
607 NewRunnableMethod(
608 file_manager_, &DownloadFileManager::RenameInProgressDownloadFile,
609 download->id(), download_path));
610
611 download->Rename(download_path);
612
[email protected]4cd82f72011-05-23 19:15:01613 download_history_->AddEntry(download,
[email protected]82f37b02010-07-29 22:04:57614 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
initial.commit09911bf2008-07-26 23:55:29615}
616
initial.commit09911bf2008-07-26 23:55:29617void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
[email protected]70850c72011-01-11 17:31:27618 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
619 DownloadMap::iterator it = active_downloads_.find(download_id);
620 if (it != active_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29621 DownloadItem* download = it->second;
[email protected]bf68a00b2011-04-07 17:28:26622 if (download->IsInProgress()) {
[email protected]70850c72011-01-11 17:31:27623 download->Update(size);
[email protected]adb2f3d12011-01-23 16:24:54624 UpdateAppIcon(); // Reflect size updates.
[email protected]70850c72011-01-11 17:31:27625 download_history_->UpdateEntry(download);
626 }
initial.commit09911bf2008-07-26 23:55:29627 }
628}
629
[email protected]bf68a00b2011-04-07 17:28:26630void DownloadManager::OnResponseCompleted(int32 download_id,
631 int64 size,
632 int os_error,
633 const std::string& hash) {
634 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]ac54efc2011-06-30 15:28:02635 if (os_error == 0) {
[email protected]bf68a00b2011-04-07 17:28:26636 OnAllDataSaved(download_id, size, hash);
637 } else {
638 OnDownloadError(download_id, size, os_error);
639 }
640}
641
[email protected]26711732011-03-09 00:21:22642void DownloadManager::OnAllDataSaved(int32 download_id,
643 int64 size,
644 const std::string& hash) {
[email protected]da6e3922010-11-24 21:45:50645 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
646 << " size = " << size;
[email protected]9d7ef802011-02-25 19:03:35647 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:32648
[email protected]c4f02c42011-01-24 21:55:06649 // If it's not in active_downloads_, that means it was cancelled; just
650 // ignore the notification.
651 if (active_downloads_.count(download_id) == 0)
652 return;
653
[email protected]adb2f3d12011-01-23 16:24:54654 DownloadItem* download = active_downloads_[download_id];
[email protected]a850ba42010-09-10 22:00:30655 download->OnAllDataSaved(size);
[email protected]9ccbb372008-10-10 18:50:32656
[email protected]26711732011-03-09 00:21:22657 // When hash is not available, it means either it is not calculated
658 // or there is error while it is calculated. We will skip the download hash
659 // check in that case.
660 if (!hash.empty()) {
661 scoped_refptr<DownloadSBClient> sb_client =
662 new DownloadSBClient(download_id,
[email protected]8799e542011-04-20 03:47:34663 download->url_chain(),
[email protected]26711732011-03-09 00:21:22664 download->referrer_url());
665 sb_client->CheckDownloadHash(
666 hash, NewCallback(this, &DownloadManager::CheckDownloadHashDone));
667 }
[email protected]adb2f3d12011-01-23 16:24:54668 MaybeCompleteDownload(download);
669}
[email protected]9ccbb372008-10-10 18:50:32670
[email protected]26711732011-03-09 00:21:22671// TODO(lzheng): This function currently works as a callback place holder.
672// Once we decide the hash check is reliable, we could move the
673// MaybeCompleteDownload in OnAllDataSaved to this function.
674void DownloadManager::CheckDownloadHashDone(int32 download_id,
675 bool is_dangerous_hash) {
676 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
677 DVLOG(1) << "CheckDownloadHashDone, download_id: " << download_id
678 << " is dangerous_hash: " << is_dangerous_hash;
679
680 // If it's not in active_downloads_, that means it was cancelled or
681 // the download already finished.
682 if (active_downloads_.count(download_id) == 0)
683 return;
684
685 DVLOG(1) << "CheckDownloadHashDone, url: "
[email protected]4cd82f72011-05-23 19:15:01686 << active_downloads_[download_id]->GetURL().spec();
[email protected]26711732011-03-09 00:21:22687}
688
[email protected]7d413112011-06-16 18:50:17689void DownloadManager::AssertQueueStateConsistent(DownloadItem* download) {
[email protected]5cd11b6e2011-06-10 20:30:59690 // TODO(rdsmith): Change to DCHECK after http://crbug.com/85408 resolved.
[email protected]7d413112011-06-16 18:50:17691 if (download->state() == DownloadItem::REMOVING) {
692 CHECK(!ContainsKey(downloads_, download));
693 CHECK(!ContainsKey(active_downloads_, download->id()));
694 CHECK(!ContainsKey(in_progress_, download->id()));
695 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
696 return;
697 }
698
699 // Should be in downloads_ if we're not REMOVING.
700 CHECK(ContainsKey(downloads_, download));
701
702 // Check history_downloads_ consistency.
703 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
704 CHECK(ContainsKey(history_downloads_, download->db_handle()));
705 } else {
706 // TODO(rdsmith): Somewhat painful; make sure to disable in
707 // release builds after resolution of http://crbug.com/85408.
708 for (DownloadMap::iterator it = history_downloads_.begin();
709 it != history_downloads_.end(); ++it) {
710 CHECK(it->second != download);
711 }
712 }
713
714 CHECK(ContainsKey(active_downloads_, download->id()) ==
715 (download->state() == DownloadItem::IN_PROGRESS));
716 CHECK(ContainsKey(in_progress_, download->id()) ==
717 (download->state() == DownloadItem::IN_PROGRESS));
[email protected]5cd11b6e2011-06-10 20:30:59718}
719
[email protected]adb2f3d12011-01-23 16:24:54720bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
721 // If we don't have all the data, the download is not ready for
722 // completion.
723 if (!download->all_data_saved())
724 return false;
[email protected]6a7fb042010-02-01 16:30:47725
[email protected]9d7ef802011-02-25 19:03:35726 // If the download is dangerous, but not yet validated, it's not ready for
727 // completion.
728 if (download->safety_state() == DownloadItem::DANGEROUS)
729 return false;
730
[email protected]adb2f3d12011-01-23 16:24:54731 // If the download isn't active (e.g. has been cancelled) it's not
732 // ready for completion.
733 if (active_downloads_.count(download->id()) == 0)
734 return false;
735
736 // If the download hasn't been inserted into the history system
737 // (which occurs strictly after file name determination, intermediate
738 // file rename, and UI display) then it's not ready for completion.
[email protected]7054b592011-06-22 14:46:42739 if (download->db_handle() == DownloadHistory::kUninitializedHandle)
740 return false;
741
742 return true;
[email protected]adb2f3d12011-01-23 16:24:54743}
744
745void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
746 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
747 VLOG(20) << __FUNCTION__ << "()" << " download = "
748 << download->DebugString(false);
749
750 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32751 return;
[email protected]9ccbb372008-10-10 18:50:32752
[email protected]adb2f3d12011-01-23 16:24:54753 // TODO(rdsmith): DCHECK that we only pass through this point
754 // once per download. The natural way to do this is by a state
755 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56756
[email protected]adb2f3d12011-01-23 16:24:54757 // Confirm we're in the proper set of states to be here;
[email protected]9d7ef802011-02-25 19:03:35758 // in in_progress_, have all data, have a history handle, (validated or safe).
759 DCHECK_NE(DownloadItem::DANGEROUS, download->safety_state());
[email protected]adb2f3d12011-01-23 16:24:54760 DCHECK_EQ(1u, in_progress_.count(download->id()));
761 DCHECK(download->all_data_saved());
762 DCHECK(download->db_handle() != DownloadHistory::kUninitializedHandle);
763 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
764
765 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
766 << download->DebugString(false);
767
768 // Remove the id from in_progress
769 in_progress_.erase(download->id());
770 UpdateAppIcon(); // Reflect removal from in_progress_.
771
[email protected]adb2f3d12011-01-23 16:24:54772 download_history_->UpdateEntry(download);
773
[email protected]f5920322011-03-24 20:34:16774 // Finish the download.
[email protected]48837962011-04-19 17:03:29775 download->OnDownloadCompleting(file_manager_);
[email protected]9ccbb372008-10-10 18:50:32776}
777
[email protected]cc3c7c092011-05-09 18:40:21778void DownloadManager::DownloadCompleted(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27779 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21780 DownloadItem* download = GetDownloadItem(download_id);
781 DCHECK(download);
782 download_history_->UpdateEntry(download);
[email protected]70850c72011-01-11 17:31:27783 active_downloads_.erase(download_id);
784}
785
[email protected]f5920322011-03-24 20:34:16786void DownloadManager::OnDownloadRenamedToFinalName(int download_id,
787 const FilePath& full_path,
788 int uniquifier) {
[email protected]da6e3922010-11-24 21:45:50789 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
[email protected]f5920322011-03-24 20:34:16790 << " full_path = \"" << full_path.value() << "\""
791 << " uniquifier = " << uniquifier;
[email protected]ca4b5fa32010-10-09 12:42:18792 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]f5920322011-03-24 20:34:16793
[email protected]2e030682010-07-23 19:45:36794 DownloadItem* item = GetDownloadItem(download_id);
795 if (!item)
796 return;
[email protected]6cade212008-12-03 00:32:22797
[email protected]8fa1eeb52011-04-13 14:18:02798 if (item->safety_state() == DownloadItem::SAFE) {
799 DCHECK_EQ(0, uniquifier) << "We should not uniquify SAFE downloads twice";
800 }
801
[email protected]ca4b5fa32010-10-09 12:42:18802 BrowserThread::PostTask(
[email protected]f5920322011-03-24 20:34:16803 BrowserThread::FILE, FROM_HERE,
804 NewRunnableMethod(
805 file_manager_, &DownloadFileManager::CompleteDownload, download_id));
[email protected]9ccbb372008-10-10 18:50:32806
[email protected]f5920322011-03-24 20:34:16807 if (uniquifier)
808 item->set_path_uniquifier(uniquifier);
[email protected]9ccbb372008-10-10 18:50:32809
[email protected]f5920322011-03-24 20:34:16810 item->OnDownloadRenamedToFinalName(full_path);
811 download_history_->UpdateDownloadPath(item, full_path);
initial.commit09911bf2008-07-26 23:55:29812}
813
initial.commit09911bf2008-07-26 23:55:29814void DownloadManager::DownloadCancelled(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27815 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29816 DownloadMap::iterator it = in_progress_.find(download_id);
817 if (it == in_progress_.end())
818 return;
819 DownloadItem* download = it->second;
820
[email protected]da6e3922010-11-24 21:45:50821 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
822 << " download = " << download->DebugString(true);
823
initial.commit09911bf2008-07-26 23:55:29824 // Clean up will happen when the history system create callback runs if we
825 // don't have a valid db_handle yet.
[email protected]82f37b02010-07-29 22:04:57826 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
initial.commit09911bf2008-07-26 23:55:29827 in_progress_.erase(it);
[email protected]70850c72011-01-11 17:31:27828 active_downloads_.erase(download_id);
[email protected]adb2f3d12011-01-23 16:24:54829 UpdateAppIcon(); // Reflect removal from in_progress_.
[email protected]82f37b02010-07-29 22:04:57830 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29831 }
832
[email protected]db6831a2011-06-09 21:08:28833 DownloadCancelledInternal(download_id, download->request_handle());
[email protected]d7d1c5c2009-08-05 23:52:50834}
835
[email protected]bc932ef2011-05-11 12:14:13836void DownloadManager::DownloadCancelledInternal(
[email protected]db6831a2011-06-09 21:08:28837 int download_id, DownloadRequestHandle request_handle) {
[email protected]f5920322011-03-24 20:34:16838 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]db6831a2011-06-09 21:08:28839 request_handle.CancelRequest();
[email protected]d7d1c5c2009-08-05 23:52:50840
[email protected]ca4b5fa32010-10-09 12:42:18841 BrowserThread::PostTask(
842 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37843 NewRunnableMethod(
844 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29845}
846
[email protected]bf68a00b2011-04-07 17:28:26847void DownloadManager::OnDownloadError(int32 download_id,
848 int64 size,
849 int os_error) {
850 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
851 DownloadMap::iterator it = active_downloads_.find(download_id);
852 // A cancel at the right time could remove the download from the
853 // |active_downloads_| map before we get here.
854 if (it == active_downloads_.end())
855 return;
856
857 DownloadItem* download = it->second;
858
[email protected]4cd82f72011-05-23 19:15:01859 VLOG(20) << __FUNCTION__ << "()" << " Error " << os_error
860 << " at offset " << download->received_bytes()
861 << " for download = " << download->DebugString(true);
862
863 download->Interrupted(size, os_error);
[email protected]bf68a00b2011-04-07 17:28:26864
865 // TODO(ahendrickson) - Remove this when we add resuming of interrupted
866 // downloads, as we will keep the download item around in that case.
867 //
868 // Clean up will happen when the history system create callback runs if we
869 // don't have a valid db_handle yet.
870 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
871 in_progress_.erase(download_id);
872 active_downloads_.erase(download_id);
873 UpdateAppIcon(); // Reflect removal from in_progress_.
874 download_history_->UpdateEntry(download);
875 }
876
[email protected]bf68a00b2011-04-07 17:28:26877 BrowserThread::PostTask(
878 BrowserThread::FILE, FROM_HERE,
879 NewRunnableMethod(
880 file_manager_, &DownloadFileManager::CancelDownload, download_id));
881}
882
[email protected]6a7fb042010-02-01 16:30:47883void DownloadManager::UpdateAppIcon() {
[email protected]073ed7b2010-09-27 09:20:02884 if (status_updater_)
885 status_updater_->Update();
[email protected]6a7fb042010-02-01 16:30:47886}
887
initial.commit09911bf2008-07-26 23:55:29888void DownloadManager::RemoveDownload(int64 download_handle) {
[email protected]f04182f32010-12-10 19:12:07889 DownloadMap::iterator it = history_downloads_.find(download_handle);
890 if (it == history_downloads_.end())
initial.commit09911bf2008-07-26 23:55:29891 return;
892
893 // Make history update.
894 DownloadItem* download = it->second;
[email protected]82f37b02010-07-29 22:04:57895 download_history_->RemoveEntry(download);
initial.commit09911bf2008-07-26 23:55:29896
897 // Remove from our tables and delete.
[email protected]f04182f32010-12-10 19:12:07898 history_downloads_.erase(it);
899 int downloads_count = downloads_.erase(download);
900 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29901
902 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:28903 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:36904
905 delete download;
initial.commit09911bf2008-07-26 23:55:29906}
907
[email protected]e93d2822009-01-30 05:59:59908int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
909 const base::Time remove_end) {
[email protected]82f37b02010-07-29 22:04:57910 download_history_->RemoveEntriesBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29911
[email protected]a312a442010-12-15 23:40:33912 // All downloads visible to the user will be in the history,
913 // so scan that map.
[email protected]f04182f32010-12-10 19:12:07914 DownloadMap::iterator it = history_downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:28915 std::vector<DownloadItem*> pending_deletes;
[email protected]f04182f32010-12-10 19:12:07916 while (it != history_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29917 DownloadItem* download = it->second;
initial.commit09911bf2008-07-26 23:55:29918 if (download->start_time() >= remove_begin &&
919 (remove_end.is_null() || download->start_time() < remove_end) &&
[email protected]bf68a00b2011-04-07 17:28:26920 (download->IsComplete() ||
921 download->IsCancelled() ||
922 download->IsInterrupted())) {
[email protected]7d413112011-06-16 18:50:17923 AssertQueueStateConsistent(download);
924
initial.commit09911bf2008-07-26 23:55:29925 // Remove from the map and move to the next in the list.
[email protected]f04182f32010-12-10 19:12:07926 history_downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:58927
928 // Also remove it from any completed dangerous downloads.
[email protected]78b8fcc92009-03-31 17:36:28929 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29930
initial.commit09911bf2008-07-26 23:55:29931 continue;
932 }
933
934 ++it;
935 }
936
[email protected]a312a442010-12-15 23:40:33937 // If we aren't deleting anything, we're done.
[email protected]57fd1252010-12-23 17:24:09938 if (pending_deletes.empty())
939 return 0;
initial.commit09911bf2008-07-26 23:55:29940
[email protected]a312a442010-12-15 23:40:33941 // Remove the chosen downloads from the main owning container.
942 for (std::vector<DownloadItem*>::iterator it = pending_deletes.begin();
943 it != pending_deletes.end(); it++) {
944 downloads_.erase(*it);
945 }
946
947 // Tell observers to refresh their views.
948 NotifyModelChanged();
949
950 // Delete the download items themselves.
[email protected]57fd1252010-12-23 17:24:09951 int num_deleted = static_cast<int>(pending_deletes.size());
952
[email protected]78b8fcc92009-03-31 17:36:28953 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
954 pending_deletes.clear();
955
initial.commit09911bf2008-07-26 23:55:29956 return num_deleted;
957}
958
[email protected]e93d2822009-01-30 05:59:59959int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
960 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29961}
962
[email protected]d41355e6f2009-04-07 21:21:12963int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:46964 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
965 // This is an incognito downloader. Clear All should clear main download
966 // manager as well.
967 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
968 }
[email protected]d41355e6f2009-04-07 21:21:12969 // The null times make the date range unbounded.
970 return RemoveDownloadsBetween(base::Time(), base::Time());
971}
972
[email protected]f9a45b02011-06-30 23:49:19973void DownloadManager::SavePageAsDownloadStarted(DownloadItem* download) {
[email protected]57fd1252010-12-23 17:24:09974#if !defined(NDEBUG)
[email protected]f9a45b02011-06-30 23:49:19975 save_page_as_downloads_.insert(download);
[email protected]57fd1252010-12-23 17:24:09976#endif
[email protected]f9a45b02011-06-30 23:49:19977 downloads_.insert(download);
978 // Add to history and notify observers.
979 AddDownloadItemToHistory(download, DownloadHistory::kUninitializedHandle);
980 NotifyModelChanged();
[email protected]ec4826a2010-09-21 09:15:59981}
982
initial.commit09911bf2008-07-26 23:55:29983// Initiate a download of a specific URL. We send the request to the
984// ResourceDispatcherHost, and let it send us responses like a regular
985// download.
986void DownloadManager::DownloadUrl(const GURL& url,
987 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50988 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34989 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26990 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
991 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58992}
993
994void DownloadManager::DownloadUrlToFile(const GURL& url,
995 const GURL& referrer,
996 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32997 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58998 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34999 DCHECK(tab_contents);
[email protected]ed24fad2011-05-10 22:44:011000 // We send a pointer to content::ResourceContext, instead of the usual
1001 // reference, so that a copy of the object isn't made.
[email protected]ca4b5fa32010-10-09 12:42:181002 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:261003 NewRunnableFunction(&download_util::DownloadUrl,
1004 url,
1005 referrer,
1006 referrer_charset,
1007 save_info,
1008 g_browser_process->resource_dispatcher_host(),
1009 tab_contents->GetRenderProcessHost()->id(),
1010 tab_contents->render_view_host()->routing_id(),
[email protected]ed24fad2011-05-10 22:44:011011 &tab_contents->profile()->GetResourceContext()));
initial.commit09911bf2008-07-26 23:55:291012}
1013
initial.commit09911bf2008-07-26 23:55:291014void DownloadManager::AddObserver(Observer* observer) {
1015 observers_.AddObserver(observer);
1016 observer->ModelChanged();
1017}
1018
1019void DownloadManager::RemoveObserver(Observer* observer) {
1020 observers_.RemoveObserver(observer);
1021}
1022
[email protected]eccb9d12009-10-28 05:40:091023bool DownloadManager::ShouldOpenFileBasedOnExtension(
1024 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:091025 FilePath::StringType extension = path.Extension();
1026 if (extension.empty())
1027 return false;
[email protected]92e11c82010-01-13 06:39:561028 if (Extension::IsExtension(path))
1029 return false;
[email protected]eccb9d12009-10-28 05:40:091030 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1031 extension.erase(0, 1);
[email protected]e5dc4222010-08-30 22:16:321032 return download_prefs_->IsAutoOpenEnabledForExtension(extension);
initial.commit09911bf2008-07-26 23:55:291033}
1034
[email protected]073ed7b2010-09-27 09:20:021035bool DownloadManager::IsDownloadProgressKnown() {
1036 for (DownloadMap::iterator i = in_progress_.begin();
1037 i != in_progress_.end(); ++i) {
1038 if (i->second->total_bytes() <= 0)
1039 return false;
1040 }
1041
1042 return true;
1043}
1044
1045int64 DownloadManager::GetInProgressDownloadCount() {
1046 return in_progress_.size();
1047}
1048
1049int64 DownloadManager::GetReceivedDownloadBytes() {
1050 DCHECK(IsDownloadProgressKnown());
1051 int64 received_bytes = 0;
1052 for (DownloadMap::iterator i = in_progress_.begin();
1053 i != in_progress_.end(); ++i) {
1054 received_bytes += i->second->received_bytes();
1055 }
1056 return received_bytes;
1057}
1058
1059int64 DownloadManager::GetTotalDownloadBytes() {
1060 DCHECK(IsDownloadProgressKnown());
1061 int64 total_bytes = 0;
1062 for (DownloadMap::iterator i = in_progress_.begin();
1063 i != in_progress_.end(); ++i) {
1064 total_bytes += i->second->total_bytes();
1065 }
1066 return total_bytes;
1067}
1068
[email protected]561abe62009-04-06 18:08:341069void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361070 int index, void* params) {
[email protected]4cd82f72011-05-23 19:15:011071 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1072
1073 int32* id_ptr = reinterpret_cast<int32*>(params);
1074 DCHECK(id_ptr != NULL);
1075 int32 download_id = *id_ptr;
1076 delete id_ptr;
1077
1078 DownloadItem* download = GetActiveDownloadItem(download_id);
1079 if (!download)
1080 return;
1081 VLOG(20) << __FUNCTION__ << "()" << " path = \"" << path.value() << "\""
1082 << " download = " << download->DebugString(true);
1083
1084 if (download->save_as())
[email protected]7ae7c2cb2009-01-06 23:31:411085 last_download_path_ = path.DirName();
[email protected]287b86b2011-02-26 00:11:351086
[email protected]4cd82f72011-05-23 19:15:011087 // Make sure the initial file name is set only once.
1088 ContinueDownloadWithPath(download, path);
initial.commit09911bf2008-07-26 23:55:291089}
1090
1091void DownloadManager::FileSelectionCanceled(void* params) {
1092 // The user didn't pick a place to save the file, so need to cancel the
1093 // download that's already in progress to the temporary location.
[email protected]4cd82f72011-05-23 19:15:011094 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1095 int32* id_ptr = reinterpret_cast<int32*>(params);
1096 DCHECK(id_ptr != NULL);
1097 int32 download_id = *id_ptr;
1098 delete id_ptr;
1099
1100 DownloadItem* download = GetActiveDownloadItem(download_id);
1101 if (!download)
1102 return;
1103
1104 VLOG(20) << __FUNCTION__ << "()"
1105 << " download = " << download->DebugString(true);
1106
[email protected]db6831a2011-06-09 21:08:281107 DownloadCancelledInternal(download_id, download->request_handle());
[email protected]4cd82f72011-05-23 19:15:011108}
1109
1110// TODO(phajdan.jr): This is apparently not being exercised in tests.
1111bool DownloadManager::IsDangerous(const DownloadItem& download,
[email protected]88008002011-05-24 23:14:151112 const DownloadStateInfo& state,
1113 bool visited_referrer_before) {
[email protected]4cd82f72011-05-23 19:15:011114 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1115
1116 bool auto_open = ShouldOpenFileBasedOnExtension(state.suggested_path);
1117 download_util::DownloadDangerLevel danger_level =
1118 download_util::GetFileDangerLevel(state.suggested_path.BaseName());
1119
1120 if (danger_level == download_util::Dangerous)
1121 return !(auto_open && state.has_user_gesture);
1122
1123 if (danger_level == download_util::AllowOnUserGesture &&
[email protected]88008002011-05-24 23:14:151124 (!state.has_user_gesture || !visited_referrer_before))
[email protected]4cd82f72011-05-23 19:15:011125 return true;
1126
1127 if (state.is_extension_install) {
1128 // Extensions that are not from the gallery are considered dangerous.
1129 ExtensionService* service = profile()->GetExtensionService();
1130 if (!service || !service->IsDownloadFromGallery(download.GetURL(),
1131 download.referrer_url()))
1132 return true;
1133 }
1134 return false;
initial.commit09911bf2008-07-26 23:55:291135}
1136
[email protected]9ccbb372008-10-10 18:50:321137void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
[email protected]9d7ef802011-02-25 19:03:351138 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:321139 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1140 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1141 download->UpdateObservers();
1142
[email protected]9d7ef802011-02-25 19:03:351143 MaybeCompleteDownload(download);
[email protected]9ccbb372008-10-10 18:50:321144}
1145
initial.commit09911bf2008-07-26 23:55:291146// Operations posted to us from the history service ----------------------------
1147
1148// The history service has retrieved all download entries. 'entries' contains
[email protected]4cd82f72011-05-23 19:15:011149// 'DownloadHistoryInfo's in sorted order (by ascending start_time).
initial.commit09911bf2008-07-26 23:55:291150void DownloadManager::OnQueryDownloadEntriesComplete(
[email protected]4cd82f72011-05-23 19:15:011151 std::vector<DownloadHistoryInfo>* entries) {
initial.commit09911bf2008-07-26 23:55:291152 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:391153 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]f04182f32010-12-10 19:12:071154 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
1155 downloads_.insert(download);
1156 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:501157 VLOG(20) << __FUNCTION__ << "()" << i << ">"
1158 << " download = " << download->DebugString(true);
initial.commit09911bf2008-07-26 23:55:291159 }
[email protected]b0ab1d42010-02-24 19:29:281160 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:481161 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:291162}
1163
[email protected]f9a45b02011-06-30 23:49:191164void DownloadManager::AddDownloadItemToHistory(DownloadItem* download,
1165 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:271166 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d2a8fb72010-01-21 05:31:421167
[email protected]5bcd73eb2011-03-23 21:14:021168 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1169 // call this function with an invalid |db_handle|. For instance, this can
1170 // happen when the history database is offline. We cannot have multiple
1171 // DownloadItems with the same invalid db_handle, so we need to assign a
1172 // unique |db_handle| here.
1173 if (db_handle == DownloadHistory::kUninitializedHandle)
1174 db_handle = download_history_->GetNextFakeDbHandle();
1175
[email protected]1e9fe7ff2011-06-24 17:37:331176 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/84508
1177 // is fixed.
1178 CHECK_NE(DownloadHistory::kUninitializedHandle, db_handle);
1179
[email protected]5bcd73eb2011-03-23 21:14:021180 DCHECK(download->db_handle() == DownloadHistory::kUninitializedHandle);
1181 download->set_db_handle(db_handle);
1182
[email protected]5bcd73eb2011-03-23 21:14:021183 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
1184 history_downloads_[download->db_handle()] = download;
[email protected]f9a45b02011-06-30 23:49:191185}
1186
1187// Once the new DownloadItem's creation info has been committed to the history
1188// service, we associate the DownloadItem with the db handle, update our
1189// 'history_downloads_' map and inform observers.
1190void DownloadManager::OnCreateDownloadEntryComplete(int32 download_id,
1191 int64 db_handle) {
1192 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1193 DownloadItem* download = GetActiveDownloadItem(download_id);
1194 if (!download)
1195 return;
1196
1197 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
1198 << " download_id = " << download_id
1199 << " download = " << download->DebugString(true);
1200
1201 AddDownloadItemToHistory(download, db_handle);
initial.commit09911bf2008-07-26 23:55:291202
[email protected]70850c72011-01-11 17:31:271203 // Show in the appropriate browser UI.
[email protected]9d7ef802011-02-25 19:03:351204 // This includes buttons to save or cancel, for a dangerous download.
[email protected]4cd82f72011-05-23 19:15:011205 ShowDownloadInBrowser(download);
initial.commit09911bf2008-07-26 23:55:291206
1207 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281208 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291209
[email protected]bf68a00b2011-04-07 17:28:261210 // If the download is still in progress, try to complete it.
[email protected]adb2f3d12011-01-23 16:24:541211 //
[email protected]bf68a00b2011-04-07 17:28:261212 // Otherwise, download has been cancelled or interrupted before we've
1213 // received the DB handle. We post one final message to the history
1214 // service so that it can be properly in sync with the DownloadItem's
1215 // completion status, and also inform any observers so that they get
1216 // more than just the start notification.
1217 if (download->IsInProgress()) {
1218 MaybeCompleteDownload(download);
1219 } else {
1220 DCHECK(download->IsCancelled())
1221 << " download = " << download->DebugString(true);
[email protected]4cd82f72011-05-23 19:15:011222 in_progress_.erase(download_id);
1223 active_downloads_.erase(download_id);
[email protected]82f37b02010-07-29 22:04:571224 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:291225 download->UpdateObservers();
1226 }
1227}
1228
[email protected]4cd82f72011-05-23 19:15:011229void DownloadManager::ShowDownloadInBrowser(DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341230 // The 'contents' may no longer exist if the user closed the tab before we
1231 // get this start completion event. If it does, tell the origin TabContents
1232 // to display its download shelf.
[email protected]db6831a2011-06-09 21:08:281233 DownloadRequestHandle request_handle = download->request_handle();
1234 TabContents* contents = request_handle.GetTabContents();
[email protected]ddb85052011-05-18 14:40:271235 TabContentsWrapper* wrapper = NULL;
1236 if (contents)
1237 wrapper = TabContentsWrapper::GetCurrentWrapperForContents(contents);
[email protected]5e595482009-05-06 20:16:531238
1239 // If the contents no longer exists, we start the download in the last active
1240 // browser. This is not ideal but better than fully hiding the download from
1241 // the user.
[email protected]ddb85052011-05-18 14:40:271242 if (!wrapper) {
[email protected]4c9c5942011-06-20 18:28:021243 Browser* last_active = BrowserList::GetLastActiveWithProfile(profile_);
[email protected]5e595482009-05-06 20:16:531244 if (last_active)
[email protected]ddb85052011-05-18 14:40:271245 wrapper = last_active->GetSelectedTabContentsWrapper();
[email protected]5e595482009-05-06 20:16:531246 }
1247
[email protected]ddb85052011-05-18 14:40:271248 if (!wrapper)
[email protected]bc932ef2011-05-11 12:14:131249 return;
1250
[email protected]ddb85052011-05-18 14:40:271251 wrapper->download_tab_helper()->OnStartDownload(download);
[email protected]5e595482009-05-06 20:16:531252}
1253
[email protected]6cade212008-12-03 00:32:221254// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121255void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411256 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381257}
[email protected]b0ab1d42010-02-24 19:29:281258
1259void DownloadManager::NotifyModelChanged() {
1260 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1261}
1262
[email protected]4cd82f72011-05-23 19:15:011263DownloadItem* DownloadManager::GetDownloadItem(int download_id) {
1264 // The |history_downloads_| map is indexed by the download's db_handle,
1265 // not its id, so we have to iterate.
[email protected]f04182f32010-12-10 19:12:071266 for (DownloadMap::iterator it = history_downloads_.begin();
1267 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:361268 DownloadItem* item = it->second;
[email protected]4cd82f72011-05-23 19:15:011269 if (item->id() == download_id)
[email protected]2e030682010-07-23 19:45:361270 return item;
1271 }
1272 return NULL;
1273}
1274
[email protected]4cd82f72011-05-23 19:15:011275DownloadItem* DownloadManager::GetActiveDownloadItem(int download_id) {
1276 DCHECK(ContainsKey(active_downloads_, download_id));
1277 DownloadItem* download = active_downloads_[download_id];
1278 DCHECK(download != NULL);
1279 return download;
1280}
1281
[email protected]57fd1252010-12-23 17:24:091282// Confirm that everything in all maps is also in |downloads_|, and that
1283// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:071284void DownloadManager::AssertContainersConsistent() const {
1285#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:091286 // Turn everything into sets.
[email protected]adb2f3d12011-01-23 16:24:541287 DownloadSet active_set, history_set;
[email protected]70850c72011-01-11 17:31:271288 const DownloadMap* input_maps[] = {&active_downloads_, &history_downloads_};
[email protected]adb2f3d12011-01-23 16:24:541289 DownloadSet* local_sets[] = {&active_set, &history_set};
[email protected]57fd1252010-12-23 17:24:091290 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(local_sets));
1291 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
1292 for (DownloadMap::const_iterator it = input_maps[i]->begin();
1293 it != input_maps[i]->end(); it++) {
1294 local_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:071295 }
1296 }
[email protected]57fd1252010-12-23 17:24:091297
1298 // Check if each set is fully present in downloads, and create a union.
[email protected]adb2f3d12011-01-23 16:24:541299 const DownloadSet* all_sets[] = {&active_set, &history_set,
[email protected]57fd1252010-12-23 17:24:091300 &save_page_as_downloads_};
1301 DownloadSet downloads_union;
1302 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
1303 DownloadSet remainder;
1304 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
1305 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
1306 downloads_.begin(), downloads_.end(),
1307 insert_it);
1308 DCHECK(remainder.empty());
1309 std::insert_iterator<DownloadSet>
1310 insert_union(downloads_union, downloads_union.end());
1311 std::set_union(downloads_union.begin(), downloads_union.end(),
1312 all_sets[i]->begin(), all_sets[i]->end(),
1313 insert_union);
1314 }
1315
1316 // Is everything in downloads_ present in one of the other sets?
1317 DownloadSet remainder;
1318 std::insert_iterator<DownloadSet>
1319 insert_remainder(remainder, remainder.begin());
1320 std::set_difference(downloads_.begin(), downloads_.end(),
1321 downloads_union.begin(), downloads_union.end(),
1322 insert_remainder);
1323 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071324#endif
1325}
1326
[email protected]b0ab1d42010-02-24 19:29:281327// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1328
1329DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1330 DownloadManager* observing_download_manager)
1331 : observing_download_manager_(observing_download_manager),
1332 observed_download_manager_(NULL) {
1333 if (observing_download_manager->profile_->GetOriginalProfile() ==
1334 observing_download_manager->profile_) {
1335 return;
1336 }
1337
1338 observed_download_manager_ = observing_download_manager_->
1339 profile_->GetOriginalProfile()->GetDownloadManager();
1340 observed_download_manager_->AddObserver(this);
1341}
1342
1343DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1344 if (observed_download_manager_)
1345 observed_download_manager_->RemoveObserver(this);
1346}
1347
1348void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1349 observing_download_manager_->NotifyModelChanged();
1350}
1351
[email protected]b0ab1d42010-02-24 19:29:281352void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1353 observed_download_manager_ = NULL;
1354}