blob: 0ba403a8faa227d9373de462a92bdd5b076480f6 [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]88008002011-05-24 23:14:15502void DownloadManager::OnPathExistenceAvailable(int32 download_id,
503 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()) {
527 extension.erase(extension.begin()); // drop the .
528 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));
635 if (os_error == 0) {
636 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]5cd11b6e2011-06-10 20:30:59689void DownloadManager::AssertNotInQueues(DownloadItem* download) {
690 // TODO(rdsmith): Change to DCHECK after http://crbug.com/85408 resolved.
691 CHECK(!ContainsKey(downloads_, download));
692 CHECK(!ContainsKey(active_downloads_, download->id()));
693 CHECK(!ContainsKey(in_progress_, download->id()));
694 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
695}
696
[email protected]adb2f3d12011-01-23 16:24:54697bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
698 // If we don't have all the data, the download is not ready for
699 // completion.
700 if (!download->all_data_saved())
701 return false;
[email protected]6a7fb042010-02-01 16:30:47702
[email protected]9d7ef802011-02-25 19:03:35703 // If the download is dangerous, but not yet validated, it's not ready for
704 // completion.
705 if (download->safety_state() == DownloadItem::DANGEROUS)
706 return false;
707
[email protected]adb2f3d12011-01-23 16:24:54708 // If the download isn't active (e.g. has been cancelled) it's not
709 // ready for completion.
710 if (active_downloads_.count(download->id()) == 0)
711 return false;
712
713 // If the download hasn't been inserted into the history system
714 // (which occurs strictly after file name determination, intermediate
715 // file rename, and UI display) then it's not ready for completion.
716 return (download->db_handle() != DownloadHistory::kUninitializedHandle);
717}
718
719void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
720 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
721 VLOG(20) << __FUNCTION__ << "()" << " download = "
722 << download->DebugString(false);
723
724 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32725 return;
[email protected]9ccbb372008-10-10 18:50:32726
[email protected]adb2f3d12011-01-23 16:24:54727 // TODO(rdsmith): DCHECK that we only pass through this point
728 // once per download. The natural way to do this is by a state
729 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56730
[email protected]adb2f3d12011-01-23 16:24:54731 // Confirm we're in the proper set of states to be here;
[email protected]9d7ef802011-02-25 19:03:35732 // in in_progress_, have all data, have a history handle, (validated or safe).
733 DCHECK_NE(DownloadItem::DANGEROUS, download->safety_state());
[email protected]adb2f3d12011-01-23 16:24:54734 DCHECK_EQ(1u, in_progress_.count(download->id()));
735 DCHECK(download->all_data_saved());
736 DCHECK(download->db_handle() != DownloadHistory::kUninitializedHandle);
737 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
738
739 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
740 << download->DebugString(false);
741
742 // Remove the id from in_progress
743 in_progress_.erase(download->id());
744 UpdateAppIcon(); // Reflect removal from in_progress_.
745
[email protected]adb2f3d12011-01-23 16:24:54746 download_history_->UpdateEntry(download);
747
[email protected]f5920322011-03-24 20:34:16748 // Finish the download.
[email protected]48837962011-04-19 17:03:29749 download->OnDownloadCompleting(file_manager_);
[email protected]9ccbb372008-10-10 18:50:32750}
751
[email protected]cc3c7c092011-05-09 18:40:21752void DownloadManager::DownloadCompleted(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27753 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21754 DownloadItem* download = GetDownloadItem(download_id);
755 DCHECK(download);
756 download_history_->UpdateEntry(download);
[email protected]70850c72011-01-11 17:31:27757 active_downloads_.erase(download_id);
758}
759
[email protected]f5920322011-03-24 20:34:16760void DownloadManager::OnDownloadRenamedToFinalName(int download_id,
761 const FilePath& full_path,
762 int uniquifier) {
[email protected]da6e3922010-11-24 21:45:50763 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
[email protected]f5920322011-03-24 20:34:16764 << " full_path = \"" << full_path.value() << "\""
765 << " uniquifier = " << uniquifier;
[email protected]ca4b5fa32010-10-09 12:42:18766 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]f5920322011-03-24 20:34:16767
[email protected]2e030682010-07-23 19:45:36768 DownloadItem* item = GetDownloadItem(download_id);
769 if (!item)
770 return;
[email protected]6cade212008-12-03 00:32:22771
[email protected]8fa1eeb52011-04-13 14:18:02772 if (item->safety_state() == DownloadItem::SAFE) {
773 DCHECK_EQ(0, uniquifier) << "We should not uniquify SAFE downloads twice";
774 }
775
[email protected]ca4b5fa32010-10-09 12:42:18776 BrowserThread::PostTask(
[email protected]f5920322011-03-24 20:34:16777 BrowserThread::FILE, FROM_HERE,
778 NewRunnableMethod(
779 file_manager_, &DownloadFileManager::CompleteDownload, download_id));
[email protected]9ccbb372008-10-10 18:50:32780
[email protected]f5920322011-03-24 20:34:16781 if (uniquifier)
782 item->set_path_uniquifier(uniquifier);
[email protected]9ccbb372008-10-10 18:50:32783
[email protected]f5920322011-03-24 20:34:16784 item->OnDownloadRenamedToFinalName(full_path);
785 download_history_->UpdateDownloadPath(item, full_path);
initial.commit09911bf2008-07-26 23:55:29786}
787
initial.commit09911bf2008-07-26 23:55:29788void DownloadManager::DownloadCancelled(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27789 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29790 DownloadMap::iterator it = in_progress_.find(download_id);
791 if (it == in_progress_.end())
792 return;
793 DownloadItem* download = it->second;
794
[email protected]da6e3922010-11-24 21:45:50795 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
796 << " download = " << download->DebugString(true);
797
initial.commit09911bf2008-07-26 23:55:29798 // Clean up will happen when the history system create callback runs if we
799 // don't have a valid db_handle yet.
[email protected]82f37b02010-07-29 22:04:57800 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
initial.commit09911bf2008-07-26 23:55:29801 in_progress_.erase(it);
[email protected]70850c72011-01-11 17:31:27802 active_downloads_.erase(download_id);
[email protected]adb2f3d12011-01-23 16:24:54803 UpdateAppIcon(); // Reflect removal from in_progress_.
[email protected]82f37b02010-07-29 22:04:57804 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29805 }
806
[email protected]db6831a2011-06-09 21:08:28807 DownloadCancelledInternal(download_id, download->request_handle());
[email protected]d7d1c5c2009-08-05 23:52:50808}
809
[email protected]bc932ef2011-05-11 12:14:13810void DownloadManager::DownloadCancelledInternal(
[email protected]db6831a2011-06-09 21:08:28811 int download_id, DownloadRequestHandle request_handle) {
[email protected]f5920322011-03-24 20:34:16812 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]db6831a2011-06-09 21:08:28813 request_handle.CancelRequest();
[email protected]d7d1c5c2009-08-05 23:52:50814
[email protected]ca4b5fa32010-10-09 12:42:18815 BrowserThread::PostTask(
816 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37817 NewRunnableMethod(
818 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29819}
820
[email protected]bf68a00b2011-04-07 17:28:26821void DownloadManager::OnDownloadError(int32 download_id,
822 int64 size,
823 int os_error) {
824 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
825 DownloadMap::iterator it = active_downloads_.find(download_id);
826 // A cancel at the right time could remove the download from the
827 // |active_downloads_| map before we get here.
828 if (it == active_downloads_.end())
829 return;
830
831 DownloadItem* download = it->second;
832
[email protected]4cd82f72011-05-23 19:15:01833 VLOG(20) << __FUNCTION__ << "()" << " Error " << os_error
834 << " at offset " << download->received_bytes()
835 << " for download = " << download->DebugString(true);
836
837 download->Interrupted(size, os_error);
[email protected]bf68a00b2011-04-07 17:28:26838
839 // TODO(ahendrickson) - Remove this when we add resuming of interrupted
840 // downloads, as we will keep the download item around in that case.
841 //
842 // Clean up will happen when the history system create callback runs if we
843 // don't have a valid db_handle yet.
844 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
845 in_progress_.erase(download_id);
846 active_downloads_.erase(download_id);
847 UpdateAppIcon(); // Reflect removal from in_progress_.
848 download_history_->UpdateEntry(download);
849 }
850
[email protected]bf68a00b2011-04-07 17:28:26851 BrowserThread::PostTask(
852 BrowserThread::FILE, FROM_HERE,
853 NewRunnableMethod(
854 file_manager_, &DownloadFileManager::CancelDownload, download_id));
855}
856
[email protected]6a7fb042010-02-01 16:30:47857void DownloadManager::UpdateAppIcon() {
[email protected]073ed7b2010-09-27 09:20:02858 if (status_updater_)
859 status_updater_->Update();
[email protected]6a7fb042010-02-01 16:30:47860}
861
initial.commit09911bf2008-07-26 23:55:29862void DownloadManager::RemoveDownload(int64 download_handle) {
[email protected]f04182f32010-12-10 19:12:07863 DownloadMap::iterator it = history_downloads_.find(download_handle);
864 if (it == history_downloads_.end())
initial.commit09911bf2008-07-26 23:55:29865 return;
866
867 // Make history update.
868 DownloadItem* download = it->second;
[email protected]82f37b02010-07-29 22:04:57869 download_history_->RemoveEntry(download);
initial.commit09911bf2008-07-26 23:55:29870
871 // Remove from our tables and delete.
[email protected]f04182f32010-12-10 19:12:07872 history_downloads_.erase(it);
873 int downloads_count = downloads_.erase(download);
874 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29875
876 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:28877 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:36878
879 delete download;
initial.commit09911bf2008-07-26 23:55:29880}
881
[email protected]e93d2822009-01-30 05:59:59882int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
883 const base::Time remove_end) {
[email protected]82f37b02010-07-29 22:04:57884 download_history_->RemoveEntriesBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29885
[email protected]a312a442010-12-15 23:40:33886 // All downloads visible to the user will be in the history,
887 // so scan that map.
[email protected]f04182f32010-12-10 19:12:07888 DownloadMap::iterator it = history_downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:28889 std::vector<DownloadItem*> pending_deletes;
[email protected]f04182f32010-12-10 19:12:07890 while (it != history_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29891 DownloadItem* download = it->second;
initial.commit09911bf2008-07-26 23:55:29892 if (download->start_time() >= remove_begin &&
893 (remove_end.is_null() || download->start_time() < remove_end) &&
[email protected]bf68a00b2011-04-07 17:28:26894 (download->IsComplete() ||
895 download->IsCancelled() ||
896 download->IsInterrupted())) {
initial.commit09911bf2008-07-26 23:55:29897 // Remove from the map and move to the next in the list.
[email protected]f04182f32010-12-10 19:12:07898 history_downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:58899
900 // Also remove it from any completed dangerous downloads.
[email protected]78b8fcc92009-03-31 17:36:28901 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29902
initial.commit09911bf2008-07-26 23:55:29903 continue;
904 }
905
906 ++it;
907 }
908
[email protected]a312a442010-12-15 23:40:33909 // If we aren't deleting anything, we're done.
[email protected]57fd1252010-12-23 17:24:09910 if (pending_deletes.empty())
911 return 0;
initial.commit09911bf2008-07-26 23:55:29912
[email protected]a312a442010-12-15 23:40:33913 // Remove the chosen downloads from the main owning container.
914 for (std::vector<DownloadItem*>::iterator it = pending_deletes.begin();
915 it != pending_deletes.end(); it++) {
916 downloads_.erase(*it);
917 }
918
919 // Tell observers to refresh their views.
920 NotifyModelChanged();
921
922 // Delete the download items themselves.
[email protected]57fd1252010-12-23 17:24:09923 int num_deleted = static_cast<int>(pending_deletes.size());
924
[email protected]78b8fcc92009-03-31 17:36:28925 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
926 pending_deletes.clear();
927
initial.commit09911bf2008-07-26 23:55:29928 return num_deleted;
929}
930
[email protected]e93d2822009-01-30 05:59:59931int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
932 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29933}
934
[email protected]d41355e6f2009-04-07 21:21:12935int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:46936 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
937 // This is an incognito downloader. Clear All should clear main download
938 // manager as well.
939 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
940 }
[email protected]d41355e6f2009-04-07 21:21:12941 // The null times make the date range unbounded.
942 return RemoveDownloadsBetween(base::Time(), base::Time());
943}
944
[email protected]ec4826a2010-09-21 09:15:59945void DownloadManager::SavePageAsDownloadStarted(DownloadItem* download_item) {
[email protected]57fd1252010-12-23 17:24:09946#if !defined(NDEBUG)
947 save_page_as_downloads_.insert(download_item);
948#endif
[email protected]f04182f32010-12-10 19:12:07949 downloads_.insert(download_item);
[email protected]ec4826a2010-09-21 09:15:59950}
951
initial.commit09911bf2008-07-26 23:55:29952// Initiate a download of a specific URL. We send the request to the
953// ResourceDispatcherHost, and let it send us responses like a regular
954// download.
955void DownloadManager::DownloadUrl(const GURL& url,
956 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50957 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34958 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26959 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
960 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58961}
962
963void DownloadManager::DownloadUrlToFile(const GURL& url,
964 const GURL& referrer,
965 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32966 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58967 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34968 DCHECK(tab_contents);
[email protected]ed24fad2011-05-10 22:44:01969 // We send a pointer to content::ResourceContext, instead of the usual
970 // reference, so that a copy of the object isn't made.
[email protected]ca4b5fa32010-10-09 12:42:18971 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26972 NewRunnableFunction(&download_util::DownloadUrl,
973 url,
974 referrer,
975 referrer_charset,
976 save_info,
977 g_browser_process->resource_dispatcher_host(),
978 tab_contents->GetRenderProcessHost()->id(),
979 tab_contents->render_view_host()->routing_id(),
[email protected]ed24fad2011-05-10 22:44:01980 &tab_contents->profile()->GetResourceContext()));
initial.commit09911bf2008-07-26 23:55:29981}
982
initial.commit09911bf2008-07-26 23:55:29983void DownloadManager::AddObserver(Observer* observer) {
984 observers_.AddObserver(observer);
985 observer->ModelChanged();
986}
987
988void DownloadManager::RemoveObserver(Observer* observer) {
989 observers_.RemoveObserver(observer);
990}
991
[email protected]eccb9d12009-10-28 05:40:09992bool DownloadManager::ShouldOpenFileBasedOnExtension(
993 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:09994 FilePath::StringType extension = path.Extension();
995 if (extension.empty())
996 return false;
[email protected]92e11c82010-01-13 06:39:56997 if (Extension::IsExtension(path))
998 return false;
[email protected]eccb9d12009-10-28 05:40:09999 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1000 extension.erase(0, 1);
[email protected]e5dc4222010-08-30 22:16:321001 return download_prefs_->IsAutoOpenEnabledForExtension(extension);
initial.commit09911bf2008-07-26 23:55:291002}
1003
[email protected]073ed7b2010-09-27 09:20:021004bool DownloadManager::IsDownloadProgressKnown() {
1005 for (DownloadMap::iterator i = in_progress_.begin();
1006 i != in_progress_.end(); ++i) {
1007 if (i->second->total_bytes() <= 0)
1008 return false;
1009 }
1010
1011 return true;
1012}
1013
1014int64 DownloadManager::GetInProgressDownloadCount() {
1015 return in_progress_.size();
1016}
1017
1018int64 DownloadManager::GetReceivedDownloadBytes() {
1019 DCHECK(IsDownloadProgressKnown());
1020 int64 received_bytes = 0;
1021 for (DownloadMap::iterator i = in_progress_.begin();
1022 i != in_progress_.end(); ++i) {
1023 received_bytes += i->second->received_bytes();
1024 }
1025 return received_bytes;
1026}
1027
1028int64 DownloadManager::GetTotalDownloadBytes() {
1029 DCHECK(IsDownloadProgressKnown());
1030 int64 total_bytes = 0;
1031 for (DownloadMap::iterator i = in_progress_.begin();
1032 i != in_progress_.end(); ++i) {
1033 total_bytes += i->second->total_bytes();
1034 }
1035 return total_bytes;
1036}
1037
[email protected]561abe62009-04-06 18:08:341038void DownloadManager::FileSelected(const FilePath& path,
[email protected]23b357b2009-03-30 20:02:361039 int index, void* params) {
[email protected]4cd82f72011-05-23 19:15:011040 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1041
1042 int32* id_ptr = reinterpret_cast<int32*>(params);
1043 DCHECK(id_ptr != NULL);
1044 int32 download_id = *id_ptr;
1045 delete id_ptr;
1046
1047 DownloadItem* download = GetActiveDownloadItem(download_id);
1048 if (!download)
1049 return;
1050 VLOG(20) << __FUNCTION__ << "()" << " path = \"" << path.value() << "\""
1051 << " download = " << download->DebugString(true);
1052
1053 if (download->save_as())
[email protected]7ae7c2cb2009-01-06 23:31:411054 last_download_path_ = path.DirName();
[email protected]287b86b2011-02-26 00:11:351055
[email protected]4cd82f72011-05-23 19:15:011056 // Make sure the initial file name is set only once.
1057 ContinueDownloadWithPath(download, path);
initial.commit09911bf2008-07-26 23:55:291058}
1059
1060void DownloadManager::FileSelectionCanceled(void* params) {
1061 // The user didn't pick a place to save the file, so need to cancel the
1062 // download that's already in progress to the temporary location.
[email protected]4cd82f72011-05-23 19:15:011063 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1064 int32* id_ptr = reinterpret_cast<int32*>(params);
1065 DCHECK(id_ptr != NULL);
1066 int32 download_id = *id_ptr;
1067 delete id_ptr;
1068
1069 DownloadItem* download = GetActiveDownloadItem(download_id);
1070 if (!download)
1071 return;
1072
1073 VLOG(20) << __FUNCTION__ << "()"
1074 << " download = " << download->DebugString(true);
1075
[email protected]db6831a2011-06-09 21:08:281076 DownloadCancelledInternal(download_id, download->request_handle());
[email protected]4cd82f72011-05-23 19:15:011077}
1078
1079// TODO(phajdan.jr): This is apparently not being exercised in tests.
1080bool DownloadManager::IsDangerous(const DownloadItem& download,
[email protected]88008002011-05-24 23:14:151081 const DownloadStateInfo& state,
1082 bool visited_referrer_before) {
[email protected]4cd82f72011-05-23 19:15:011083 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1084
1085 bool auto_open = ShouldOpenFileBasedOnExtension(state.suggested_path);
1086 download_util::DownloadDangerLevel danger_level =
1087 download_util::GetFileDangerLevel(state.suggested_path.BaseName());
1088
1089 if (danger_level == download_util::Dangerous)
1090 return !(auto_open && state.has_user_gesture);
1091
1092 if (danger_level == download_util::AllowOnUserGesture &&
[email protected]88008002011-05-24 23:14:151093 (!state.has_user_gesture || !visited_referrer_before))
[email protected]4cd82f72011-05-23 19:15:011094 return true;
1095
1096 if (state.is_extension_install) {
1097 // Extensions that are not from the gallery are considered dangerous.
1098 ExtensionService* service = profile()->GetExtensionService();
1099 if (!service || !service->IsDownloadFromGallery(download.GetURL(),
1100 download.referrer_url()))
1101 return true;
1102 }
1103 return false;
initial.commit09911bf2008-07-26 23:55:291104}
1105
[email protected]9ccbb372008-10-10 18:50:321106void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
[email protected]9d7ef802011-02-25 19:03:351107 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:321108 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1109 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1110 download->UpdateObservers();
1111
[email protected]9d7ef802011-02-25 19:03:351112 MaybeCompleteDownload(download);
[email protected]9ccbb372008-10-10 18:50:321113}
1114
initial.commit09911bf2008-07-26 23:55:291115// Operations posted to us from the history service ----------------------------
1116
1117// The history service has retrieved all download entries. 'entries' contains
[email protected]4cd82f72011-05-23 19:15:011118// 'DownloadHistoryInfo's in sorted order (by ascending start_time).
initial.commit09911bf2008-07-26 23:55:291119void DownloadManager::OnQueryDownloadEntriesComplete(
[email protected]4cd82f72011-05-23 19:15:011120 std::vector<DownloadHistoryInfo>* entries) {
initial.commit09911bf2008-07-26 23:55:291121 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:391122 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]f04182f32010-12-10 19:12:071123 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
1124 downloads_.insert(download);
1125 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:501126 VLOG(20) << __FUNCTION__ << "()" << i << ">"
1127 << " download = " << download->DebugString(true);
initial.commit09911bf2008-07-26 23:55:291128 }
[email protected]b0ab1d42010-02-24 19:29:281129 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:481130 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:291131}
1132
initial.commit09911bf2008-07-26 23:55:291133// Once the new DownloadItem's creation info has been committed to the history
1134// service, we associate the DownloadItem with the db handle, update our
[email protected]f04182f32010-12-10 19:12:071135// 'history_downloads_' map and inform observers.
[email protected]4cd82f72011-05-23 19:15:011136void DownloadManager::OnCreateDownloadEntryComplete(int32 download_id,
1137 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:271138 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]4cd82f72011-05-23 19:15:011139 DownloadItem* download = GetActiveDownloadItem(download_id);
1140 if (!download)
1141 return;
initial.commit09911bf2008-07-26 23:55:291142
[email protected]da6e3922010-11-24 21:45:501143 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
[email protected]4cd82f72011-05-23 19:15:011144 << " download_id = " << download_id
[email protected]da6e3922010-11-24 21:45:501145 << " download = " << download->DebugString(true);
[email protected]d2a8fb72010-01-21 05:31:421146
[email protected]5bcd73eb2011-03-23 21:14:021147 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1148 // call this function with an invalid |db_handle|. For instance, this can
1149 // happen when the history database is offline. We cannot have multiple
1150 // DownloadItems with the same invalid db_handle, so we need to assign a
1151 // unique |db_handle| here.
1152 if (db_handle == DownloadHistory::kUninitializedHandle)
1153 db_handle = download_history_->GetNextFakeDbHandle();
1154
1155 DCHECK(download->db_handle() == DownloadHistory::kUninitializedHandle);
1156 download->set_db_handle(db_handle);
1157
[email protected]5bcd73eb2011-03-23 21:14:021158 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
1159 history_downloads_[download->db_handle()] = download;
initial.commit09911bf2008-07-26 23:55:291160
[email protected]70850c72011-01-11 17:31:271161 // Show in the appropriate browser UI.
[email protected]9d7ef802011-02-25 19:03:351162 // This includes buttons to save or cancel, for a dangerous download.
[email protected]4cd82f72011-05-23 19:15:011163 ShowDownloadInBrowser(download);
initial.commit09911bf2008-07-26 23:55:291164
1165 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281166 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291167
[email protected]bf68a00b2011-04-07 17:28:261168 // If the download is still in progress, try to complete it.
[email protected]adb2f3d12011-01-23 16:24:541169 //
[email protected]bf68a00b2011-04-07 17:28:261170 // Otherwise, download has been cancelled or interrupted before we've
1171 // received the DB handle. We post one final message to the history
1172 // service so that it can be properly in sync with the DownloadItem's
1173 // completion status, and also inform any observers so that they get
1174 // more than just the start notification.
1175 if (download->IsInProgress()) {
1176 MaybeCompleteDownload(download);
1177 } else {
1178 DCHECK(download->IsCancelled())
1179 << " download = " << download->DebugString(true);
[email protected]4cd82f72011-05-23 19:15:011180 in_progress_.erase(download_id);
1181 active_downloads_.erase(download_id);
[email protected]82f37b02010-07-29 22:04:571182 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:291183 download->UpdateObservers();
1184 }
1185}
1186
[email protected]4cd82f72011-05-23 19:15:011187void DownloadManager::ShowDownloadInBrowser(DownloadItem* download) {
[email protected]bc932ef2011-05-11 12:14:131188
[email protected]8ddbd66a2010-05-21 16:38:341189 // The 'contents' may no longer exist if the user closed the tab before we
1190 // get this start completion event. If it does, tell the origin TabContents
1191 // to display its download shelf.
[email protected]db6831a2011-06-09 21:08:281192 DownloadRequestHandle request_handle = download->request_handle();
1193 TabContents* contents = request_handle.GetTabContents();
[email protected]ddb85052011-05-18 14:40:271194 TabContentsWrapper* wrapper = NULL;
1195 if (contents)
1196 wrapper = TabContentsWrapper::GetCurrentWrapperForContents(contents);
[email protected]5e595482009-05-06 20:16:531197
1198 // If the contents no longer exists, we start the download in the last active
1199 // browser. This is not ideal but better than fully hiding the download from
1200 // the user.
[email protected]ddb85052011-05-18 14:40:271201 if (!wrapper) {
[email protected]5e595482009-05-06 20:16:531202 Browser* last_active = BrowserList::GetLastActive();
1203 if (last_active)
[email protected]ddb85052011-05-18 14:40:271204 wrapper = last_active->GetSelectedTabContentsWrapper();
[email protected]5e595482009-05-06 20:16:531205 }
1206
[email protected]ddb85052011-05-18 14:40:271207 if (!wrapper)
[email protected]bc932ef2011-05-11 12:14:131208 return;
1209
[email protected]ddb85052011-05-18 14:40:271210 wrapper->download_tab_helper()->OnStartDownload(download);
[email protected]5e595482009-05-06 20:16:531211}
1212
[email protected]6cade212008-12-03 00:32:221213// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121214void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411215 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381216}
[email protected]b0ab1d42010-02-24 19:29:281217
1218void DownloadManager::NotifyModelChanged() {
1219 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1220}
1221
[email protected]4cd82f72011-05-23 19:15:011222DownloadItem* DownloadManager::GetDownloadItem(int download_id) {
1223 // The |history_downloads_| map is indexed by the download's db_handle,
1224 // not its id, so we have to iterate.
[email protected]f04182f32010-12-10 19:12:071225 for (DownloadMap::iterator it = history_downloads_.begin();
1226 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:361227 DownloadItem* item = it->second;
[email protected]4cd82f72011-05-23 19:15:011228 if (item->id() == download_id)
[email protected]2e030682010-07-23 19:45:361229 return item;
1230 }
1231 return NULL;
1232}
1233
[email protected]4cd82f72011-05-23 19:15:011234DownloadItem* DownloadManager::GetActiveDownloadItem(int download_id) {
1235 DCHECK(ContainsKey(active_downloads_, download_id));
1236 DownloadItem* download = active_downloads_[download_id];
1237 DCHECK(download != NULL);
1238 return download;
1239}
1240
[email protected]57fd1252010-12-23 17:24:091241// Confirm that everything in all maps is also in |downloads_|, and that
1242// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:071243void DownloadManager::AssertContainersConsistent() const {
1244#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:091245 // Turn everything into sets.
[email protected]adb2f3d12011-01-23 16:24:541246 DownloadSet active_set, history_set;
[email protected]70850c72011-01-11 17:31:271247 const DownloadMap* input_maps[] = {&active_downloads_, &history_downloads_};
[email protected]adb2f3d12011-01-23 16:24:541248 DownloadSet* local_sets[] = {&active_set, &history_set};
[email protected]57fd1252010-12-23 17:24:091249 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(local_sets));
1250 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
1251 for (DownloadMap::const_iterator it = input_maps[i]->begin();
1252 it != input_maps[i]->end(); it++) {
1253 local_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:071254 }
1255 }
[email protected]57fd1252010-12-23 17:24:091256
1257 // Check if each set is fully present in downloads, and create a union.
[email protected]adb2f3d12011-01-23 16:24:541258 const DownloadSet* all_sets[] = {&active_set, &history_set,
[email protected]57fd1252010-12-23 17:24:091259 &save_page_as_downloads_};
1260 DownloadSet downloads_union;
1261 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
1262 DownloadSet remainder;
1263 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
1264 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
1265 downloads_.begin(), downloads_.end(),
1266 insert_it);
1267 DCHECK(remainder.empty());
1268 std::insert_iterator<DownloadSet>
1269 insert_union(downloads_union, downloads_union.end());
1270 std::set_union(downloads_union.begin(), downloads_union.end(),
1271 all_sets[i]->begin(), all_sets[i]->end(),
1272 insert_union);
1273 }
1274
1275 // Is everything in downloads_ present in one of the other sets?
1276 DownloadSet remainder;
1277 std::insert_iterator<DownloadSet>
1278 insert_remainder(remainder, remainder.begin());
1279 std::set_difference(downloads_.begin(), downloads_.end(),
1280 downloads_union.begin(), downloads_union.end(),
1281 insert_remainder);
1282 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071283#endif
1284}
1285
[email protected]b0ab1d42010-02-24 19:29:281286// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1287
1288DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1289 DownloadManager* observing_download_manager)
1290 : observing_download_manager_(observing_download_manager),
1291 observed_download_manager_(NULL) {
1292 if (observing_download_manager->profile_->GetOriginalProfile() ==
1293 observing_download_manager->profile_) {
1294 return;
1295 }
1296
1297 observed_download_manager_ = observing_download_manager_->
1298 profile_->GetOriginalProfile()->GetDownloadManager();
1299 observed_download_manager_->AddObserver(this);
1300}
1301
1302DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1303 if (observed_download_manager_)
1304 observed_download_manager_->RemoveObserver(this);
1305}
1306
1307void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1308 observing_download_manager_->NotifyModelChanged();
1309}
1310
[email protected]b0ab1d42010-02-24 19:29:281311void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1312 observed_download_manager_ = NULL;
1313}