blob: 0bf6266c77ce294e89f1d92f1a21fb7be9ccfa51 [file] [log] [blame]
[email protected]f4f50ef2011-01-21 19:01:191// Copyright (c) 2011 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
[email protected]cdaa8652008-09-13 02:48:595#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]2041cf342010-02-19 03:15:597#include "base/callback.h"
initial.commit09911bf2008-07-26 23:55:298#include "base/file_util.h"
[email protected]503d03872011-05-06 08:36:269#include "base/i18n/case_conversion.h"
initial.commit09911bf2008-07-26 23:55:2910#include "base/logging.h"
[email protected]fed38252011-07-08 17:26:5011#include "base/path_service.h"
[email protected]1b5044d2009-02-24 00:04:1412#include "base/rand_util.h"
[email protected]7286e3fc2011-07-19 22:13:2413#include "base/stl_util.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]8ecad5e2010-12-02 21:18:3332#include "chrome/browser/profiles/profile.h"
[email protected]d2a8fb72010-01-21 05:31:4233#include "chrome/browser/tab_contents/tab_util.h"
initial.commit09911bf2008-07-26 23:55:2934#include "chrome/common/chrome_paths.h"
[email protected]8c40da62011-07-13 22:58:4635#include "chrome/common/pref_names.h"
[email protected]7324d1d2011-03-01 05:02:1636#include "content/browser/browser_thread.h"
[email protected]99cb7f82011-07-28 17:27:2637#include "content/browser/content_browser_client.h"
[email protected]7324d1d2011-03-01 05:02:1638#include "content/browser/renderer_host/render_process_host.h"
39#include "content/browser/renderer_host/render_view_host.h"
40#include "content/browser/renderer_host/resource_dispatcher_host.h"
41#include "content/browser/tab_contents/tab_contents.h"
[email protected]432115822011-07-10 15:52:2742#include "content/common/content_notification_types.h"
[email protected]46072d42008-07-28 14:49:3543#include "googleurl/src/gurl.h"
[email protected]34ac8f32009-02-22 23:03:2744#include "grit/generated_resources.h"
[email protected]21ca982c2010-01-26 22:49:5545#include "grit/theme_resources.h"
initial.commit09911bf2008-07-26 23:55:2946#include "net/base/mime_util.h"
47#include "net/base/net_util.h"
[email protected]c051a1b2011-01-21 23:30:1748#include "ui/base/l10n/l10n_util.h"
[email protected]42ce29d2011-01-20 23:19:4649#include "ui/base/resource/resource_bundle.h"
initial.commit09911bf2008-07-26 23:55:2950
[email protected]073ed7b2010-09-27 09:20:0251DownloadManager::DownloadManager(DownloadStatusUpdater* status_updater)
initial.commit09911bf2008-07-26 23:55:2952 : shutdown_needed_(false),
53 profile_(NULL),
[email protected]073ed7b2010-09-27 09:20:0254 file_manager_(NULL),
[email protected]a3d2bc42010-10-06 14:08:4955 status_updater_(status_updater->AsWeakPtr()) {
[email protected]073ed7b2010-09-27 09:20:0256 if (status_updater_)
57 status_updater_->AddDelegate(this);
initial.commit09911bf2008-07-26 23:55:2958}
59
60DownloadManager::~DownloadManager() {
[email protected]326a6a92010-09-10 20:21:1361 DCHECK(!shutdown_needed_);
[email protected]073ed7b2010-09-27 09:20:0262 if (status_updater_)
63 status_updater_->RemoveDelegate(this);
initial.commit09911bf2008-07-26 23:55:2964}
65
66void DownloadManager::Shutdown() {
[email protected]da6e3922010-11-24 21:45:5067 VLOG(20) << __FUNCTION__ << "()"
68 << " shutdown_needed_ = " << shutdown_needed_;
[email protected]326a6a92010-09-10 20:21:1369 if (!shutdown_needed_)
70 return;
71 shutdown_needed_ = false;
initial.commit09911bf2008-07-26 23:55:2972
[email protected]326a6a92010-09-10 20:21:1373 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
74
75 if (file_manager_) {
[email protected]ca4b5fa32010-10-09 12:42:1876 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
[email protected]326a6a92010-09-10 20:21:1377 NewRunnableMethod(file_manager_,
78 &DownloadFileManager::OnDownloadManagerShutdown,
[email protected]dc7cdcb92010-12-14 06:40:5479 make_scoped_refptr(this)));
[email protected]326a6a92010-09-10 20:21:1380 }
initial.commit09911bf2008-07-26 23:55:2981
[email protected]f04182f32010-12-10 19:12:0782 AssertContainersConsistent();
83
84 // Go through all downloads in downloads_. Dangerous ones we need to
85 // remove on disk, and in progress ones we need to cancel.
[email protected]57fd1252010-12-23 17:24:0986 for (DownloadSet::iterator it = downloads_.begin(); it != downloads_.end();) {
[email protected]f04182f32010-12-10 19:12:0787 DownloadItem* download = *it;
88
89 // Save iterator from potential erases in this set done by called code.
90 // Iterators after an erasure point are still valid for lists and
91 // associative containers such as sets.
92 it++;
93
94 if (download->safety_state() == DownloadItem::DANGEROUS &&
[email protected]48837962011-04-19 17:03:2995 download->IsPartialDownload()) {
[email protected]f04182f32010-12-10 19:12:0796 // The user hasn't accepted it, so we need to remove it
97 // from the disk. This may or may not result in it being
98 // removed from the DownloadManager queues and deleted
99 // (specifically, DownloadManager::RemoveDownload only
100 // removes and deletes it if it's known to the history service)
101 // so the only thing we know after calling this function is that
102 // the download was deleted if-and-only-if it was removed
103 // from all queues.
[email protected]303077002011-04-19 23:21:01104 download->Delete(DownloadItem::DELETE_DUE_TO_BROWSER_SHUTDOWN);
[email protected]bf68a00b2011-04-07 17:28:26105 } else if (download->IsPartialDownload()) {
[email protected]54610672011-07-18 18:24:43106 download->Cancel(false);
107 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29108 }
109 }
110
[email protected]f04182f32010-12-10 19:12:07111 // At this point, all dangerous downloads have had their files removed
112 // and all in progress downloads have been cancelled. We can now delete
113 // anything left.
[email protected]9ccbb372008-10-10 18:50:32114
[email protected]5cd11b6e2011-06-10 20:30:59115 // Copy downloads_ to separate container so as not to set off checks
116 // in DownloadItem destruction.
117 DownloadSet downloads_to_delete;
118 downloads_to_delete.swap(downloads_);
119
initial.commit09911bf2008-07-26 23:55:29120 in_progress_.clear();
[email protected]70850c72011-01-11 17:31:27121 active_downloads_.clear();
[email protected]5cd11b6e2011-06-10 20:30:59122 history_downloads_.clear();
[email protected]57fd1252010-12-23 17:24:09123#if !defined(NDEBUG)
124 save_page_as_downloads_.clear();
125#endif
[email protected]5cd11b6e2011-06-10 20:30:59126 STLDeleteElements(&downloads_to_delete);
initial.commit09911bf2008-07-26 23:55:29127
128 file_manager_ = NULL;
129
[email protected]82f37b02010-07-29 22:04:57130 download_history_.reset();
[email protected]68a49e52011-01-28 10:39:51131 download_prefs_.reset();
[email protected]82f37b02010-07-29 22:04:57132
initial.commit09911bf2008-07-26 23:55:29133 shutdown_needed_ = false;
134}
135
[email protected]82f37b02010-07-29 22:04:57136void DownloadManager::GetTemporaryDownloads(
137 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
138 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58139
[email protected]f04182f32010-12-10 19:12:07140 for (DownloadMap::iterator it = history_downloads_.begin();
141 it != history_downloads_.end(); ++it) {
[email protected]6aa4a1c02010-01-15 18:49:58142 if (it->second->is_temporary() &&
143 it->second->full_path().DirName() == dir_path)
[email protected]82f37b02010-07-29 22:04:57144 result->push_back(it->second);
[email protected]6aa4a1c02010-01-15 18:49:58145 }
[email protected]6aa4a1c02010-01-15 18:49:58146}
147
[email protected]82f37b02010-07-29 22:04:57148void DownloadManager::GetAllDownloads(
149 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
150 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34151
[email protected]f04182f32010-12-10 19:12:07152 for (DownloadMap::iterator it = history_downloads_.begin();
153 it != history_downloads_.end(); ++it) {
[email protected]8ddbd66a2010-05-21 16:38:34154 if (!it->second->is_temporary() &&
155 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57156 result->push_back(it->second);
[email protected]8ddbd66a2010-05-21 16:38:34157 }
[email protected]8ddbd66a2010-05-21 16:38:34158}
159
[email protected]82f37b02010-07-29 22:04:57160void DownloadManager::GetCurrentDownloads(
161 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
162 DCHECK(result);
[email protected]c4a530b2010-03-08 17:33:03163
[email protected]f04182f32010-12-10 19:12:07164 for (DownloadMap::iterator it = history_downloads_.begin();
165 it != history_downloads_.end(); ++it) {
[email protected]bf68a00b2011-04-07 17:28:26166 DownloadItem* item =it->second;
167 // Skip temporary items.
168 if (item->is_temporary())
169 continue;
170 // Skip items that have all their data, and are OK to save.
171 if (!item->IsPartialDownload() &&
172 (item->safety_state() != DownloadItem::DANGEROUS))
173 continue;
174 // Skip items that don't match |dir_path|.
175 // If |dir_path| is empty, all remaining items match.
176 if (!dir_path.empty() && (it->second->full_path().DirName() != dir_path))
177 continue;
178
179 result->push_back(item);
[email protected]c4a530b2010-03-08 17:33:03180 }
[email protected]f7e9fd62010-09-28 15:45:06181
182 // If we have a parent profile, let it add its downloads to the results.
183 Profile* original_profile = profile_->GetOriginalProfile();
184 if (original_profile != profile_)
185 original_profile->GetDownloadManager()->GetCurrentDownloads(dir_path,
186 result);
[email protected]c4a530b2010-03-08 17:33:03187}
188
[email protected]d3b12902010-08-16 23:39:42189void DownloadManager::SearchDownloads(const string16& query,
190 std::vector<DownloadItem*>* result) {
191 DCHECK(result);
192
[email protected]503d03872011-05-06 08:36:26193 string16 query_lower(base::i18n::ToLower(query));
[email protected]d3b12902010-08-16 23:39:42194
[email protected]f04182f32010-12-10 19:12:07195 for (DownloadMap::iterator it = history_downloads_.begin();
196 it != history_downloads_.end(); ++it) {
[email protected]d3b12902010-08-16 23:39:42197 DownloadItem* download_item = it->second;
198
199 if (download_item->is_temporary() || download_item->is_extension_install())
200 continue;
201
202 // Display Incognito downloads only in Incognito window, and vice versa.
203 // The Incognito Downloads page will get the list of non-Incognito downloads
204 // from its parent profile.
205 if (profile_->IsOffTheRecord() != download_item->is_otr())
206 continue;
207
208 if (download_item->MatchesQuery(query_lower))
209 result->push_back(download_item);
210 }
211
212 // If we have a parent profile, let it add its downloads to the results.
213 Profile* original_profile = profile_->GetOriginalProfile();
214 if (original_profile != profile_)
215 original_profile->GetDownloadManager()->SearchDownloads(query, result);
216}
217
initial.commit09911bf2008-07-26 23:55:29218// Query the history service for information about all persisted downloads.
219bool DownloadManager::Init(Profile* profile) {
220 DCHECK(profile);
221 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
222 shutdown_needed_ = true;
223
224 profile_ = profile;
[email protected]d3b12902010-08-16 23:39:42225 download_history_.reset(new DownloadHistory(profile));
[email protected]82f37b02010-07-29 22:04:57226 download_history_->Load(
227 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
[email protected]024f2f02010-04-30 22:51:46228
[email protected]e5dc4222010-08-30 22:16:32229 download_prefs_.reset(new DownloadPrefs(profile_->GetPrefs()));
230
[email protected]2941c2392010-07-15 22:54:30231 // In test mode, there may be no ResourceDispatcherHost. In this case it's
232 // safe to avoid setting |file_manager_| because we only call a small set of
233 // functions, none of which need it.
initial.commit09911bf2008-07-26 23:55:29234 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]2941c2392010-07-15 22:54:30235 if (rdh) {
236 file_manager_ = rdh->download_file_manager();
237 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29238 }
239
[email protected]b0ab1d42010-02-24 19:29:28240 other_download_manager_observer_.reset(
241 new OtherDownloadManagerObserver(this));
242
initial.commit09911bf2008-07-26 23:55:29243 return true;
244}
245
initial.commit09911bf2008-07-26 23:55:29246// We have received a message from DownloadFileManager about a new download. We
247// create a download item and store it in our download map, and inform the
248// history system of a new download. Since this method can be called while the
249// history service thread is still reading the persistent state, we do not
[email protected]f04182f32010-12-10 19:12:07250// insert the new DownloadItem into 'history_downloads_' or inform our
[email protected]adb2f3d12011-01-23 16:24:54251// observers at this point. OnCreateDownloadEntryComplete() handles that
[email protected]f04182f32010-12-10 19:12:07252// finalization of the the download creation as a callback from the
253// history thread.
[email protected]4cd82f72011-05-23 19:15:01254void DownloadManager::StartDownload(int32 download_id) {
[email protected]ca4b5fa32010-10-09 12:42:18255 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]287b86b2011-02-26 00:11:35256
[email protected]4cd82f72011-05-23 19:15:01257 DownloadItem* download = GetActiveDownloadItem(download_id);
258 if (!download)
259 return;
260
[email protected]4b58e7d2011-07-11 10:22:56261#if defined(ENABLE_SAFE_BROWSING)
[email protected]287b86b2011-02-26 00:11:35262 // Create a client to verify download URL with safebrowsing.
263 // It deletes itself after the callback.
[email protected]26711732011-03-09 00:21:22264 scoped_refptr<DownloadSBClient> sb_client = new DownloadSBClient(
[email protected]8c40da62011-07-13 22:58:46265 download_id, download->url_chain(), download->referrer_url(),
266 profile_->GetPrefs()->GetBoolean(prefs::kSafeBrowsingEnabled));
[email protected]287b86b2011-02-26 00:11:35267 sb_client->CheckDownloadUrl(
[email protected]4cd82f72011-05-23 19:15:01268 NewCallback(this, &DownloadManager::CheckDownloadUrlDone));
[email protected]4b58e7d2011-07-11 10:22:56269#else
270 CheckDownloadUrlDone(download_id, false);
271#endif
[email protected]287b86b2011-02-26 00:11:35272}
273
[email protected]9fc114672011-06-15 08:17:48274void DownloadManager::CheckForHistoryFilesRemoval() {
275 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
276 for (DownloadMap::iterator it = history_downloads_.begin();
277 it != history_downloads_.end(); ++it) {
278 CheckForFileRemoval(it->second);
279 }
280}
281
282void DownloadManager::CheckForFileRemoval(DownloadItem* download_item) {
283 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
284 if (download_item->IsComplete() &&
285 !download_item->file_externally_removed()) {
286 BrowserThread::PostTask(
287 BrowserThread::FILE, FROM_HERE,
288 NewRunnableMethod(this,
289 &DownloadManager::CheckForFileRemovalOnFileThread,
290 download_item->db_handle(),
291 download_item->GetTargetFilePath()));
292 }
293}
294
295void DownloadManager::CheckForFileRemovalOnFileThread(
296 int64 db_handle, const FilePath& path) {
297 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
298 if (!file_util::PathExists(path)) {
299 BrowserThread::PostTask(
300 BrowserThread::UI, FROM_HERE,
301 NewRunnableMethod(this,
302 &DownloadManager::OnFileRemovalDetected,
303 db_handle));
304 }
305}
306
307void DownloadManager::OnFileRemovalDetected(int64 db_handle) {
308 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
309 DownloadMap::iterator it = history_downloads_.find(db_handle);
310 if (it != history_downloads_.end()) {
311 DownloadItem* download_item = it->second;
312 download_item->OnDownloadedFileRemoved();
313 }
314}
315
[email protected]4cd82f72011-05-23 19:15:01316void DownloadManager::CheckDownloadUrlDone(int32 download_id,
[email protected]287b86b2011-02-26 00:11:35317 bool is_dangerous_url) {
318 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29319
[email protected]4cd82f72011-05-23 19:15:01320 DownloadItem* download = GetActiveDownloadItem(download_id);
321 if (!download)
322 return;
323
324 if (is_dangerous_url)
325 download->MarkUrlDangerous();
326
[email protected]88008002011-05-24 23:14:15327 download_history_->CheckVisitedReferrerBefore(download_id,
328 download->referrer_url(),
329 NewCallback(this, &DownloadManager::CheckVisitedReferrerBeforeDone));
330}
331
332void DownloadManager::CheckVisitedReferrerBeforeDone(
333 int32 download_id,
334 bool visited_referrer_before) {
335 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
336
337 DownloadItem* download = GetActiveDownloadItem(download_id);
338 if (!download)
339 return;
[email protected]287b86b2011-02-26 00:11:35340
[email protected]a60c8ae2009-12-25 06:50:57341 // Check whether this download is for an extension install or not.
[email protected]e6875c12010-07-18 11:14:13342 // Allow extensions to be explicitly saved.
[email protected]88008002011-05-24 23:14:15343 DownloadStateInfo state = download->state_info();
[email protected]4cd82f72011-05-23 19:15:01344 if (!state.prompt_user_for_save_location) {
345 if (UserScript::IsURLUserScript(download->GetURL(),
346 download->mime_type()) ||
347 (download->mime_type() == Extension::kMimeType)) {
348 state.is_extension_install = true;
[email protected]bac4f4b2011-03-05 02:01:40349 }
[email protected]a60c8ae2009-12-25 06:50:57350 }
351
[email protected]4cd82f72011-05-23 19:15:01352 if (state.force_file_name.empty()) {
[email protected]2941c2392010-07-15 22:54:30353 FilePath generated_name;
[email protected]0622875ab2011-07-27 12:10:34354 download_util::GenerateFileNameFromRequest(*download,
[email protected]4cd82f72011-05-23 19:15:01355 &generated_name);
[email protected]2941c2392010-07-15 22:54:30356
357 // Freeze the user's preference for showing a Save As dialog. We're going
358 // to bounce around a bunch of threads and we don't want to worry about race
359 // conditions where the user changes this pref out from under us.
[email protected]0e9b6072011-02-17 12:42:05360 if (download_prefs_->PromptForDownload()) {
[email protected]2941c2392010-07-15 22:54:30361 // But ignore the user's preference for the following scenarios:
362 // 1) Extension installation. Note that we only care here about the case
363 // where an extension is installed, not when one is downloaded with
364 // "save as...".
365 // 2) Filetypes marked "always open." If the user just wants this file
366 // opened, don't bother asking where to keep it.
[email protected]4cd82f72011-05-23 19:15:01367 if (!state.is_extension_install &&
[email protected]2941c2392010-07-15 22:54:30368 !ShouldOpenFileBasedOnExtension(generated_name))
[email protected]4cd82f72011-05-23 19:15:01369 state.prompt_user_for_save_location = true;
[email protected]2941c2392010-07-15 22:54:30370 }
[email protected]14e0a102011-02-22 14:04:01371 if (download_prefs_->IsDownloadPathManaged()) {
[email protected]4cd82f72011-05-23 19:15:01372 state.prompt_user_for_save_location = false;
[email protected]14e0a102011-02-22 14:04:01373 }
[email protected]2941c2392010-07-15 22:54:30374
[email protected]8af9d032010-02-10 00:00:32375 // Determine the proper path for a download, by either one of the following:
376 // 1) using the default download directory.
377 // 2) prompting the user.
[email protected]4cd82f72011-05-23 19:15:01378 if (state.prompt_user_for_save_location && !last_download_path_.empty()) {
379 state.suggested_path = last_download_path_;
[email protected]80dc3612010-07-27 19:35:08380 } else {
[email protected]4cd82f72011-05-23 19:15:01381 state.suggested_path = download_prefs_->download_path();
[email protected]80dc3612010-07-27 19:35:08382 }
[email protected]4cd82f72011-05-23 19:15:01383 state.suggested_path = state.suggested_path.Append(generated_name);
[email protected]8af9d032010-02-10 00:00:32384 } else {
[email protected]4cd82f72011-05-23 19:15:01385 state.suggested_path = state.force_file_name;
[email protected]8af9d032010-02-10 00:00:32386 }
initial.commit09911bf2008-07-26 23:55:29387
[email protected]88008002011-05-24 23:14:15388 if (!state.prompt_user_for_save_location && state.force_file_name.empty()) {
389 state.is_dangerous_file =
390 IsDangerous(*download, state, visited_referrer_before);
391 }
[email protected]e9ebf3fc2008-10-17 22:06:58392
initial.commit09911bf2008-07-26 23:55:29393 // We need to move over to the download thread because we don't want to stat
394 // the suggested path on the UI thread.
[email protected]5a3b97e2010-10-05 09:49:11395 // We can only access preferences on the UI thread, so check the download path
396 // now and pass the value to the FILE thread.
[email protected]ca4b5fa32010-10-09 12:42:18397 BrowserThread::PostTask(
398 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37399 NewRunnableMethod(
[email protected]5a3b97e2010-10-05 09:49:11400 this,
401 &DownloadManager::CheckIfSuggestedPathExists,
[email protected]88008002011-05-24 23:14:15402 download->id(),
[email protected]4cd82f72011-05-23 19:15:01403 state,
[email protected]5a3b97e2010-10-05 09:49:11404 download_prefs()->download_path()));
initial.commit09911bf2008-07-26 23:55:29405}
406
[email protected]fed38252011-07-08 17:26:50407void DownloadManager::CheckIfSuggestedPathExists(int32 download_id,
408 DownloadStateInfo state,
409 const FilePath& default_path) {
[email protected]ca4b5fa32010-10-09 12:42:18410 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
initial.commit09911bf2008-07-26 23:55:29411
[email protected]fed38252011-07-08 17:26:50412 // Make sure the default download directory exists.
413 // TODO(phajdan.jr): only create the directory when we're sure the user
414 // is going to save there and not to another directory of his choice.
415 file_util::CreateDirectory(default_path);
416
417 // Check writability of the suggested path. If we can't write to it, default
418 // to the user's "My Documents" directory. We'll prompt them in this case.
419 FilePath dir = state.suggested_path.DirName();
420 FilePath filename = state.suggested_path.BaseName();
421 if (!file_util::PathIsWritable(dir)) {
422 VLOG(1) << "Unable to write to directory \"" << dir.value() << "\"";
[email protected]4cd82f72011-05-23 19:15:01423 state.prompt_user_for_save_location = true;
[email protected]fed38252011-07-08 17:26:50424 PathService::Get(chrome::DIR_USER_DOCUMENTS, &state.suggested_path);
425 state.suggested_path = state.suggested_path.Append(filename);
426 }
initial.commit09911bf2008-07-26 23:55:29427
[email protected]6cade212008-12-03 00:32:22428 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]4cd82f72011-05-23 19:15:01429 if (state.IsDangerous()) {
[email protected]fed38252011-07-08 17:26:50430 state.target_name = FilePath(state.suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32431 // Create a temporary file to hold the file until the user approves its
432 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41433 FilePath::StringType file_name;
434 FilePath path;
[email protected]463e1b432011-01-21 22:05:51435#if defined(OS_WIN)
436 string16 unconfirmed_prefix =
437 l10n_util::GetStringUTF16(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
438#else
439 std::string unconfirmed_prefix =
440 l10n_util::GetStringUTF8(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
441#endif
442
[email protected]9ccbb372008-10-10 18:50:32443 while (path.empty()) {
[email protected]2594c2b2010-11-08 23:04:26444 base::SStringPrintf(
445 &file_name,
[email protected]463e1b432011-01-21 22:05:51446 unconfirmed_prefix.append(
447 FILE_PATH_LITERAL(" %d.crdownload")).c_str(),
[email protected]2594c2b2010-11-08 23:04:26448 base::RandInt(0, 100000));
[email protected]fed38252011-07-08 17:26:50449 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07450 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41451 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32452 }
[email protected]4cd82f72011-05-23 19:15:01453 state.suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16454 } else {
[email protected]594cd7d2010-07-21 03:23:56455 // Do not add the path uniquifier if we are saving to a specific path as in
456 // the drag-out case.
[email protected]4cd82f72011-05-23 19:15:01457 if (state.force_file_name.empty()) {
458 state.path_uniquifier = download_util::GetUniquePathNumberWithCrDownload(
459 state.suggested_path);
[email protected]594cd7d2010-07-21 03:23:56460 }
[email protected]7a256ea2008-10-17 17:34:16461 // We know the final path, build it if necessary.
[email protected]4cd82f72011-05-23 19:15:01462 if (state.path_uniquifier > 0) {
463 download_util::AppendNumberToPath(&(state.suggested_path),
464 state.path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16465 // Setting path_uniquifier to 0 to make sure we don't try to unique it
466 // later on.
[email protected]4cd82f72011-05-23 19:15:01467 state.path_uniquifier = 0;
468 } else if (state.path_uniquifier == -1) {
[email protected]7d3851d82008-12-12 03:26:07469 // We failed to find a unique path. We have to prompt the user.
[email protected]da6e3922010-11-24 21:45:50470 VLOG(1) << "Unable to find a unique path for suggested path \""
[email protected]4cd82f72011-05-23 19:15:01471 << state.suggested_path.value() << "\"";
472 state.prompt_user_for_save_location = true;
[email protected]7a256ea2008-10-17 17:34:16473 }
[email protected]9ccbb372008-10-10 18:50:32474 }
475
[email protected]594cd7d2010-07-21 03:23:56476 // Create an empty file at the suggested path so that we don't allocate the
477 // same "non-existant" path to multiple downloads.
478 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]4cd82f72011-05-23 19:15:01479 if (!state.prompt_user_for_save_location &&
480 state.force_file_name.empty()) {
481 if (state.IsDangerous())
482 file_util::WriteFile(state.suggested_path, "", 0);
[email protected]594cd7d2010-07-21 03:23:56483 else
484 file_util::WriteFile(download_util::GetCrDownloadPath(
[email protected]4cd82f72011-05-23 19:15:01485 state.suggested_path), "", 0);
[email protected]7d3851d82008-12-12 03:26:07486 }
487
[email protected]ca4b5fa32010-10-09 12:42:18488 BrowserThread::PostTask(
489 BrowserThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29490 NewRunnableMethod(this,
491 &DownloadManager::OnPathExistenceAvailable,
[email protected]4cd82f72011-05-23 19:15:01492 download_id,
493 state));
initial.commit09911bf2008-07-26 23:55:29494}
495
[email protected]22001462011-06-22 17:42:51496void DownloadManager::OnPathExistenceAvailable(
497 int32 download_id, const DownloadStateInfo& new_state) {
[email protected]ca4b5fa32010-10-09 12:42:18498 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29499
[email protected]4cd82f72011-05-23 19:15:01500 DownloadItem* download = GetActiveDownloadItem(download_id);
501 if (!download)
502 return;
503
504 VLOG(20) << __FUNCTION__ << "()"
505 << " download = " << download->DebugString(true);
506
507 download->SetFileCheckResults(new_state);
508
509 FilePath suggested_path = download->suggested_path();
510
511 if (download->save_as()) {
initial.commit09911bf2008-07-26 23:55:29512 // We must ask the user for the place to put the download.
[email protected]db6831a2011-06-09 21:08:28513 DownloadRequestHandle request_handle = download->request_handle();
514 TabContents* contents = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:26515
[email protected]4cd82f72011-05-23 19:15:01516 // |id_ptr| will be deleted in either FileSelected() or
517 // FileSelectionCancelled().
518 int32* id_ptr = new int32;
519 *id_ptr = download_id;
[email protected]99cb7f82011-07-28 17:27:26520
521 content::GetContentClient()->browser()->ChooseDownloadPath(
522 this, contents, suggested_path, reinterpret_cast<void*>(id_ptr));
523
[email protected]f5920322011-03-24 20:34:16524 FOR_EACH_OBSERVER(Observer, observers_,
[email protected]fed38252011-07-08 17:26:50525 SelectFileDialogDisplayed(download_id));
initial.commit09911bf2008-07-26 23:55:29526 } else {
527 // No prompting for download, just continue with the suggested name.
[email protected]4cd82f72011-05-23 19:15:01528 ContinueDownloadWithPath(download, suggested_path);
initial.commit09911bf2008-07-26 23:55:29529 }
530}
531
[email protected]c2e76012010-12-23 21:10:29532void DownloadManager::CreateDownloadItem(DownloadCreateInfo* info) {
533 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
534
535 DownloadItem* download = new DownloadItem(this, *info,
536 profile_->IsOffTheRecord());
[email protected]4cd82f72011-05-23 19:15:01537 int32 download_id = info->download_id;
538 DCHECK(!ContainsKey(in_progress_, download_id));
539 DCHECK(!ContainsKey(active_downloads_, download_id));
[email protected]c2e76012010-12-23 21:10:29540 downloads_.insert(download);
[email protected]4cd82f72011-05-23 19:15:01541 active_downloads_[download_id] = download;
[email protected]c2e76012010-12-23 21:10:29542}
543
[email protected]4cd82f72011-05-23 19:15:01544void DownloadManager::ContinueDownloadWithPath(DownloadItem* download,
545 const FilePath& chosen_file) {
[email protected]ca4b5fa32010-10-09 12:42:18546 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]4cd82f72011-05-23 19:15:01547 DCHECK(download);
[email protected]aa033af2010-07-27 18:16:39548
[email protected]4cd82f72011-05-23 19:15:01549 int32 download_id = download->id();
initial.commit09911bf2008-07-26 23:55:29550
[email protected]70850c72011-01-11 17:31:27551 // NOTE(ahendrickson) Eventually |active_downloads_| will replace
552 // |in_progress_|, but we don't want to change the semantics yet.
[email protected]4cd82f72011-05-23 19:15:01553 DCHECK(!ContainsKey(in_progress_, download_id));
[email protected]70850c72011-01-11 17:31:27554 DCHECK(ContainsKey(downloads_, download));
[email protected]4cd82f72011-05-23 19:15:01555 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]70850c72011-01-11 17:31:27556
[email protected]4cd82f72011-05-23 19:15:01557 // Make sure the initial file name is set only once.
558 DCHECK(download->full_path().empty());
559 download->OnPathDetermined(chosen_file);
[email protected]4cd82f72011-05-23 19:15:01560
561 VLOG(20) << __FUNCTION__ << "()"
562 << " download = " << download->DebugString(true);
563
564 in_progress_[download_id] = download;
[email protected]adb2f3d12011-01-23 16:24:54565 UpdateAppIcon(); // Reflect entry into in_progress_.
initial.commit09911bf2008-07-26 23:55:29566
[email protected]adb2f3d12011-01-23 16:24:54567 // Rename to intermediate name.
[email protected]f5920322011-03-24 20:34:16568 FilePath download_path;
[email protected]4cd82f72011-05-23 19:15:01569 if (download->IsDangerous()) {
[email protected]adb2f3d12011-01-23 16:24:54570 // The download is not safe. We can now rename the file to its
[email protected]f5920322011-03-24 20:34:16571 // tentative name using RenameInProgressDownloadFile.
572 // NOTE: The |Rename| below will be a no-op for dangerous files, as we're
573 // renaming it to the same name.
[email protected]4cd82f72011-05-23 19:15:01574 download_path = download->full_path();
[email protected]594cd7d2010-07-21 03:23:56575 } else {
[email protected]adb2f3d12011-01-23 16:24:54576 // The download is a safe download. We need to
577 // rename it to its intermediate '.crdownload' path. The final
578 // name after user confirmation will be set from
[email protected]48837962011-04-19 17:03:29579 // DownloadItem::OnDownloadCompleting.
[email protected]4cd82f72011-05-23 19:15:01580 download_path =
581 download_util::GetCrDownloadPath(download->full_path());
[email protected]594cd7d2010-07-21 03:23:56582 }
583
[email protected]f5920322011-03-24 20:34:16584 BrowserThread::PostTask(
585 BrowserThread::FILE, FROM_HERE,
586 NewRunnableMethod(
587 file_manager_, &DownloadFileManager::RenameInProgressDownloadFile,
588 download->id(), download_path));
589
590 download->Rename(download_path);
591
[email protected]4cd82f72011-05-23 19:15:01592 download_history_->AddEntry(download,
[email protected]82f37b02010-07-29 22:04:57593 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
initial.commit09911bf2008-07-26 23:55:29594}
595
initial.commit09911bf2008-07-26 23:55:29596void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
[email protected]70850c72011-01-11 17:31:27597 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
598 DownloadMap::iterator it = active_downloads_.find(download_id);
599 if (it != active_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29600 DownloadItem* download = it->second;
[email protected]bf68a00b2011-04-07 17:28:26601 if (download->IsInProgress()) {
[email protected]70850c72011-01-11 17:31:27602 download->Update(size);
[email protected]adb2f3d12011-01-23 16:24:54603 UpdateAppIcon(); // Reflect size updates.
[email protected]70850c72011-01-11 17:31:27604 download_history_->UpdateEntry(download);
605 }
initial.commit09911bf2008-07-26 23:55:29606 }
607}
608
[email protected]bf68a00b2011-04-07 17:28:26609void DownloadManager::OnResponseCompleted(int32 download_id,
610 int64 size,
611 int os_error,
612 const std::string& hash) {
613 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]7c8e55ba2011-07-01 18:59:23614 // ERR_CONNECTION_CLOSED is allowed since a number of servers in the wild
615 // advertise a larger Content-Length than the amount of bytes in the message
616 // body, and then close the connection. Other browsers - IE8, Firefox 4.0.1,
617 // and Safari 5.0.4 - treat the download as complete in this case, so we
618 // follow their lead.
[email protected]1822a422011-07-15 15:49:19619 if (os_error == 0 || os_error == net::ERR_CONNECTION_CLOSED) {
[email protected]bf68a00b2011-04-07 17:28:26620 OnAllDataSaved(download_id, size, hash);
621 } else {
622 OnDownloadError(download_id, size, os_error);
623 }
624}
625
[email protected]26711732011-03-09 00:21:22626void DownloadManager::OnAllDataSaved(int32 download_id,
627 int64 size,
628 const std::string& hash) {
[email protected]da6e3922010-11-24 21:45:50629 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
630 << " size = " << size;
[email protected]9d7ef802011-02-25 19:03:35631 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:32632
[email protected]c4f02c42011-01-24 21:55:06633 // If it's not in active_downloads_, that means it was cancelled; just
634 // ignore the notification.
635 if (active_downloads_.count(download_id) == 0)
636 return;
637
[email protected]adb2f3d12011-01-23 16:24:54638 DownloadItem* download = active_downloads_[download_id];
[email protected]a850ba42010-09-10 22:00:30639 download->OnAllDataSaved(size);
[email protected]9ccbb372008-10-10 18:50:32640
[email protected]26711732011-03-09 00:21:22641 // When hash is not available, it means either it is not calculated
642 // or there is error while it is calculated. We will skip the download hash
643 // check in that case.
644 if (!hash.empty()) {
[email protected]4b58e7d2011-07-11 10:22:56645#if defined(ENABLE_SAFE_BROWSING)
[email protected]26711732011-03-09 00:21:22646 scoped_refptr<DownloadSBClient> sb_client =
647 new DownloadSBClient(download_id,
[email protected]8799e542011-04-20 03:47:34648 download->url_chain(),
[email protected]8c40da62011-07-13 22:58:46649 download->referrer_url(),
650 profile_->GetPrefs()->GetBoolean(
651 prefs::kSafeBrowsingEnabled));
[email protected]26711732011-03-09 00:21:22652 sb_client->CheckDownloadHash(
653 hash, NewCallback(this, &DownloadManager::CheckDownloadHashDone));
[email protected]4b58e7d2011-07-11 10:22:56654#else
655 CheckDownloadHashDone(download_id, false);
656#endif
[email protected]26711732011-03-09 00:21:22657 }
[email protected]adb2f3d12011-01-23 16:24:54658 MaybeCompleteDownload(download);
659}
[email protected]9ccbb372008-10-10 18:50:32660
[email protected]26711732011-03-09 00:21:22661// TODO(lzheng): This function currently works as a callback place holder.
662// Once we decide the hash check is reliable, we could move the
663// MaybeCompleteDownload in OnAllDataSaved to this function.
664void DownloadManager::CheckDownloadHashDone(int32 download_id,
665 bool is_dangerous_hash) {
666 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
667 DVLOG(1) << "CheckDownloadHashDone, download_id: " << download_id
668 << " is dangerous_hash: " << is_dangerous_hash;
669
670 // If it's not in active_downloads_, that means it was cancelled or
671 // the download already finished.
672 if (active_downloads_.count(download_id) == 0)
673 return;
674
675 DVLOG(1) << "CheckDownloadHashDone, url: "
[email protected]4cd82f72011-05-23 19:15:01676 << active_downloads_[download_id]->GetURL().spec();
[email protected]26711732011-03-09 00:21:22677}
678
[email protected]7d413112011-06-16 18:50:17679void DownloadManager::AssertQueueStateConsistent(DownloadItem* download) {
[email protected]5cd11b6e2011-06-10 20:30:59680 // TODO(rdsmith): Change to DCHECK after http://crbug.com/85408 resolved.
[email protected]7d413112011-06-16 18:50:17681 if (download->state() == DownloadItem::REMOVING) {
682 CHECK(!ContainsKey(downloads_, download));
683 CHECK(!ContainsKey(active_downloads_, download->id()));
684 CHECK(!ContainsKey(in_progress_, download->id()));
685 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
686 return;
687 }
688
689 // Should be in downloads_ if we're not REMOVING.
690 CHECK(ContainsKey(downloads_, download));
691
692 // Check history_downloads_ consistency.
693 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
694 CHECK(ContainsKey(history_downloads_, download->db_handle()));
695 } else {
696 // TODO(rdsmith): Somewhat painful; make sure to disable in
697 // release builds after resolution of http://crbug.com/85408.
698 for (DownloadMap::iterator it = history_downloads_.begin();
699 it != history_downloads_.end(); ++it) {
700 CHECK(it->second != download);
701 }
702 }
703
704 CHECK(ContainsKey(active_downloads_, download->id()) ==
705 (download->state() == DownloadItem::IN_PROGRESS));
[email protected]54610672011-07-18 18:24:43706 CHECK(ContainsKey(in_progress_, download->id()) ==
707 (download->state() == DownloadItem::IN_PROGRESS));
[email protected]5cd11b6e2011-06-10 20:30:59708}
709
[email protected]adb2f3d12011-01-23 16:24:54710bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
711 // If we don't have all the data, the download is not ready for
712 // completion.
713 if (!download->all_data_saved())
714 return false;
[email protected]6a7fb042010-02-01 16:30:47715
[email protected]9d7ef802011-02-25 19:03:35716 // If the download is dangerous, but not yet validated, it's not ready for
717 // completion.
718 if (download->safety_state() == DownloadItem::DANGEROUS)
719 return false;
720
[email protected]adb2f3d12011-01-23 16:24:54721 // If the download isn't active (e.g. has been cancelled) it's not
722 // ready for completion.
723 if (active_downloads_.count(download->id()) == 0)
724 return false;
725
726 // If the download hasn't been inserted into the history system
727 // (which occurs strictly after file name determination, intermediate
728 // file rename, and UI display) then it's not ready for completion.
[email protected]7054b592011-06-22 14:46:42729 if (download->db_handle() == DownloadHistory::kUninitializedHandle)
730 return false;
731
732 return true;
[email protected]adb2f3d12011-01-23 16:24:54733}
734
735void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
736 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
737 VLOG(20) << __FUNCTION__ << "()" << " download = "
738 << download->DebugString(false);
739
740 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32741 return;
[email protected]9ccbb372008-10-10 18:50:32742
[email protected]adb2f3d12011-01-23 16:24:54743 // TODO(rdsmith): DCHECK that we only pass through this point
744 // once per download. The natural way to do this is by a state
745 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56746
[email protected]adb2f3d12011-01-23 16:24:54747 // Confirm we're in the proper set of states to be here;
[email protected]9d7ef802011-02-25 19:03:35748 // in in_progress_, have all data, have a history handle, (validated or safe).
749 DCHECK_NE(DownloadItem::DANGEROUS, download->safety_state());
[email protected]adb2f3d12011-01-23 16:24:54750 DCHECK_EQ(1u, in_progress_.count(download->id()));
751 DCHECK(download->all_data_saved());
752 DCHECK(download->db_handle() != DownloadHistory::kUninitializedHandle);
753 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
754
755 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
756 << download->DebugString(false);
757
758 // Remove the id from in_progress
759 in_progress_.erase(download->id());
760 UpdateAppIcon(); // Reflect removal from in_progress_.
761
[email protected]adb2f3d12011-01-23 16:24:54762 download_history_->UpdateEntry(download);
763
[email protected]f5920322011-03-24 20:34:16764 // Finish the download.
[email protected]48837962011-04-19 17:03:29765 download->OnDownloadCompleting(file_manager_);
[email protected]9ccbb372008-10-10 18:50:32766}
767
[email protected]cc3c7c092011-05-09 18:40:21768void DownloadManager::DownloadCompleted(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27769 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21770 DownloadItem* download = GetDownloadItem(download_id);
771 DCHECK(download);
772 download_history_->UpdateEntry(download);
[email protected]70850c72011-01-11 17:31:27773 active_downloads_.erase(download_id);
774}
775
[email protected]f5920322011-03-24 20:34:16776void DownloadManager::OnDownloadRenamedToFinalName(int download_id,
777 const FilePath& full_path,
778 int uniquifier) {
[email protected]da6e3922010-11-24 21:45:50779 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
[email protected]f5920322011-03-24 20:34:16780 << " full_path = \"" << full_path.value() << "\""
781 << " uniquifier = " << uniquifier;
[email protected]ca4b5fa32010-10-09 12:42:18782 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]f5920322011-03-24 20:34:16783
[email protected]2e030682010-07-23 19:45:36784 DownloadItem* item = GetDownloadItem(download_id);
785 if (!item)
786 return;
[email protected]6cade212008-12-03 00:32:22787
[email protected]8fa1eeb52011-04-13 14:18:02788 if (item->safety_state() == DownloadItem::SAFE) {
789 DCHECK_EQ(0, uniquifier) << "We should not uniquify SAFE downloads twice";
790 }
791
[email protected]ca4b5fa32010-10-09 12:42:18792 BrowserThread::PostTask(
[email protected]f5920322011-03-24 20:34:16793 BrowserThread::FILE, FROM_HERE,
794 NewRunnableMethod(
795 file_manager_, &DownloadFileManager::CompleteDownload, download_id));
[email protected]9ccbb372008-10-10 18:50:32796
[email protected]f5920322011-03-24 20:34:16797 if (uniquifier)
798 item->set_path_uniquifier(uniquifier);
[email protected]9ccbb372008-10-10 18:50:32799
[email protected]f5920322011-03-24 20:34:16800 item->OnDownloadRenamedToFinalName(full_path);
801 download_history_->UpdateDownloadPath(item, full_path);
initial.commit09911bf2008-07-26 23:55:29802}
803
[email protected]54610672011-07-18 18:24:43804void DownloadManager::DownloadCancelled(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27805 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]54610672011-07-18 18:24:43806 DownloadMap::iterator it = in_progress_.find(download_id);
807 if (it == in_progress_.end())
initial.commit09911bf2008-07-26 23:55:29808 return;
809 DownloadItem* download = it->second;
810
[email protected]da6e3922010-11-24 21:45:50811 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
812 << " download = " << download->DebugString(true);
813
[email protected]54610672011-07-18 18:24:43814 // Clean up will happen when the history system create callback runs if we
815 // don't have a valid db_handle yet.
816 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
817 in_progress_.erase(it);
818 active_downloads_.erase(download_id);
819 UpdateAppIcon(); // Reflect removal from in_progress_.
820 download_history_->UpdateEntry(download);
821 }
initial.commit09911bf2008-07-26 23:55:29822
[email protected]54610672011-07-18 18:24:43823 DownloadCancelledInternal(download_id, download->request_handle());
824}
[email protected]d7d1c5c2009-08-05 23:52:50825
[email protected]54610672011-07-18 18:24:43826void DownloadManager::DownloadCancelledInternal(
827 int download_id, const DownloadRequestHandle& request_handle) {
828 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
829 request_handle.CancelRequest();
[email protected]d7d1c5c2009-08-05 23:52:50830
[email protected]ca4b5fa32010-10-09 12:42:18831 BrowserThread::PostTask(
832 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37833 NewRunnableMethod(
834 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29835}
836
[email protected]bf68a00b2011-04-07 17:28:26837void DownloadManager::OnDownloadError(int32 download_id,
838 int64 size,
839 int os_error) {
840 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
841 DownloadMap::iterator it = active_downloads_.find(download_id);
842 // A cancel at the right time could remove the download from the
843 // |active_downloads_| map before we get here.
844 if (it == active_downloads_.end())
845 return;
846
847 DownloadItem* download = it->second;
848
[email protected]4cd82f72011-05-23 19:15:01849 VLOG(20) << __FUNCTION__ << "()" << " Error " << os_error
850 << " at offset " << download->received_bytes()
851 << " for download = " << download->DebugString(true);
852
[email protected]54610672011-07-18 18:24:43853 download->Interrupted(size, os_error);
854
855 // TODO(ahendrickson) - Remove this when we add resuming of interrupted
856 // downloads, as we will keep the download item around in that case.
857 //
858 // Clean up will happen when the history system create callback runs if we
859 // don't have a valid db_handle yet.
860 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
861 in_progress_.erase(download_id);
862 active_downloads_.erase(download_id);
863 UpdateAppIcon(); // Reflect removal from in_progress_.
864 download_history_->UpdateEntry(download);
865 }
866
867 BrowserThread::PostTask(
868 BrowserThread::FILE, FROM_HERE,
869 NewRunnableMethod(
870 file_manager_, &DownloadFileManager::CancelDownload, download_id));
[email protected]bf68a00b2011-04-07 17:28:26871}
872
[email protected]6a7fb042010-02-01 16:30:47873void DownloadManager::UpdateAppIcon() {
[email protected]073ed7b2010-09-27 09:20:02874 if (status_updater_)
875 status_updater_->Update();
[email protected]6a7fb042010-02-01 16:30:47876}
877
[email protected]54610672011-07-18 18:24:43878void DownloadManager::RemoveDownload(int64 download_handle) {
879 DownloadMap::iterator it = history_downloads_.find(download_handle);
880 if (it == history_downloads_.end())
881 return;
882
883 // Make history update.
884 DownloadItem* download = it->second;
885 download_history_->RemoveEntry(download);
initial.commit09911bf2008-07-26 23:55:29886
887 // Remove from our tables and delete.
[email protected]54610672011-07-18 18:24:43888 history_downloads_.erase(it);
[email protected]f04182f32010-12-10 19:12:07889 int downloads_count = downloads_.erase(download);
890 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29891
892 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:28893 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:36894
895 delete download;
initial.commit09911bf2008-07-26 23:55:29896}
897
[email protected]e93d2822009-01-30 05:59:59898int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
899 const base::Time remove_end) {
[email protected]82f37b02010-07-29 22:04:57900 download_history_->RemoveEntriesBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29901
[email protected]a312a442010-12-15 23:40:33902 // All downloads visible to the user will be in the history,
903 // so scan that map.
[email protected]f04182f32010-12-10 19:12:07904 DownloadMap::iterator it = history_downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:28905 std::vector<DownloadItem*> pending_deletes;
[email protected]f04182f32010-12-10 19:12:07906 while (it != history_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29907 DownloadItem* download = it->second;
initial.commit09911bf2008-07-26 23:55:29908 if (download->start_time() >= remove_begin &&
909 (remove_end.is_null() || download->start_time() < remove_end) &&
[email protected]bf68a00b2011-04-07 17:28:26910 (download->IsComplete() ||
911 download->IsCancelled() ||
912 download->IsInterrupted())) {
[email protected]7d413112011-06-16 18:50:17913 AssertQueueStateConsistent(download);
914
initial.commit09911bf2008-07-26 23:55:29915 // Remove from the map and move to the next in the list.
[email protected]f04182f32010-12-10 19:12:07916 history_downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:58917
918 // Also remove it from any completed dangerous downloads.
[email protected]78b8fcc92009-03-31 17:36:28919 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29920
initial.commit09911bf2008-07-26 23:55:29921 continue;
922 }
923
924 ++it;
925 }
926
[email protected]a312a442010-12-15 23:40:33927 // If we aren't deleting anything, we're done.
[email protected]57fd1252010-12-23 17:24:09928 if (pending_deletes.empty())
929 return 0;
initial.commit09911bf2008-07-26 23:55:29930
[email protected]a312a442010-12-15 23:40:33931 // Remove the chosen downloads from the main owning container.
932 for (std::vector<DownloadItem*>::iterator it = pending_deletes.begin();
933 it != pending_deletes.end(); it++) {
934 downloads_.erase(*it);
935 }
936
937 // Tell observers to refresh their views.
938 NotifyModelChanged();
939
940 // Delete the download items themselves.
[email protected]57fd1252010-12-23 17:24:09941 int num_deleted = static_cast<int>(pending_deletes.size());
942
[email protected]78b8fcc92009-03-31 17:36:28943 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
944 pending_deletes.clear();
945
initial.commit09911bf2008-07-26 23:55:29946 return num_deleted;
947}
948
[email protected]e93d2822009-01-30 05:59:59949int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
950 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29951}
952
[email protected]d41355e6f2009-04-07 21:21:12953int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:46954 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
955 // This is an incognito downloader. Clear All should clear main download
956 // manager as well.
957 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
958 }
[email protected]d41355e6f2009-04-07 21:21:12959 // The null times make the date range unbounded.
960 return RemoveDownloadsBetween(base::Time(), base::Time());
961}
962
[email protected]f9a45b02011-06-30 23:49:19963void DownloadManager::SavePageAsDownloadStarted(DownloadItem* download) {
[email protected]57fd1252010-12-23 17:24:09964#if !defined(NDEBUG)
[email protected]f9a45b02011-06-30 23:49:19965 save_page_as_downloads_.insert(download);
[email protected]57fd1252010-12-23 17:24:09966#endif
[email protected]f9a45b02011-06-30 23:49:19967 downloads_.insert(download);
968 // Add to history and notify observers.
969 AddDownloadItemToHistory(download, DownloadHistory::kUninitializedHandle);
970 NotifyModelChanged();
[email protected]ec4826a2010-09-21 09:15:59971}
972
initial.commit09911bf2008-07-26 23:55:29973// Initiate a download of a specific URL. We send the request to the
974// ResourceDispatcherHost, and let it send us responses like a regular
975// download.
976void DownloadManager::DownloadUrl(const GURL& url,
977 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50978 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34979 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26980 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
981 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58982}
983
984void DownloadManager::DownloadUrlToFile(const GURL& url,
985 const GURL& referrer,
986 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32987 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58988 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34989 DCHECK(tab_contents);
[email protected]ed24fad2011-05-10 22:44:01990 // We send a pointer to content::ResourceContext, instead of the usual
991 // reference, so that a copy of the object isn't made.
[email protected]ca4b5fa32010-10-09 12:42:18992 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26993 NewRunnableFunction(&download_util::DownloadUrl,
994 url,
995 referrer,
996 referrer_charset,
997 save_info,
998 g_browser_process->resource_dispatcher_host(),
999 tab_contents->GetRenderProcessHost()->id(),
1000 tab_contents->render_view_host()->routing_id(),
[email protected]ed24fad2011-05-10 22:44:011001 &tab_contents->profile()->GetResourceContext()));
initial.commit09911bf2008-07-26 23:55:291002}
1003
initial.commit09911bf2008-07-26 23:55:291004void DownloadManager::AddObserver(Observer* observer) {
1005 observers_.AddObserver(observer);
1006 observer->ModelChanged();
1007}
1008
1009void DownloadManager::RemoveObserver(Observer* observer) {
1010 observers_.RemoveObserver(observer);
1011}
1012
[email protected]eccb9d12009-10-28 05:40:091013bool DownloadManager::ShouldOpenFileBasedOnExtension(
1014 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:091015 FilePath::StringType extension = path.Extension();
1016 if (extension.empty())
1017 return false;
[email protected]92e11c82010-01-13 06:39:561018 if (Extension::IsExtension(path))
1019 return false;
[email protected]eccb9d12009-10-28 05:40:091020 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1021 extension.erase(0, 1);
[email protected]e5dc4222010-08-30 22:16:321022 return download_prefs_->IsAutoOpenEnabledForExtension(extension);
initial.commit09911bf2008-07-26 23:55:291023}
1024
[email protected]073ed7b2010-09-27 09:20:021025bool DownloadManager::IsDownloadProgressKnown() {
1026 for (DownloadMap::iterator i = in_progress_.begin();
1027 i != in_progress_.end(); ++i) {
1028 if (i->second->total_bytes() <= 0)
1029 return false;
1030 }
1031
1032 return true;
1033}
1034
1035int64 DownloadManager::GetInProgressDownloadCount() {
1036 return in_progress_.size();
1037}
1038
1039int64 DownloadManager::GetReceivedDownloadBytes() {
1040 DCHECK(IsDownloadProgressKnown());
1041 int64 received_bytes = 0;
1042 for (DownloadMap::iterator i = in_progress_.begin();
1043 i != in_progress_.end(); ++i) {
1044 received_bytes += i->second->received_bytes();
1045 }
1046 return received_bytes;
1047}
1048
1049int64 DownloadManager::GetTotalDownloadBytes() {
1050 DCHECK(IsDownloadProgressKnown());
1051 int64 total_bytes = 0;
1052 for (DownloadMap::iterator i = in_progress_.begin();
1053 i != in_progress_.end(); ++i) {
1054 total_bytes += i->second->total_bytes();
1055 }
1056 return total_bytes;
1057}
1058
[email protected]99cb7f82011-07-28 17:27:261059void DownloadManager::FileSelected(const FilePath& path, void* params) {
[email protected]4cd82f72011-05-23 19:15:011060 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1061
1062 int32* id_ptr = reinterpret_cast<int32*>(params);
1063 DCHECK(id_ptr != NULL);
1064 int32 download_id = *id_ptr;
1065 delete id_ptr;
1066
1067 DownloadItem* download = GetActiveDownloadItem(download_id);
1068 if (!download)
1069 return;
1070 VLOG(20) << __FUNCTION__ << "()" << " path = \"" << path.value() << "\""
1071 << " download = " << download->DebugString(true);
1072
1073 if (download->save_as())
[email protected]7ae7c2cb2009-01-06 23:31:411074 last_download_path_ = path.DirName();
[email protected]287b86b2011-02-26 00:11:351075
[email protected]4cd82f72011-05-23 19:15:011076 // Make sure the initial file name is set only once.
1077 ContinueDownloadWithPath(download, path);
initial.commit09911bf2008-07-26 23:55:291078}
1079
1080void DownloadManager::FileSelectionCanceled(void* params) {
1081 // The user didn't pick a place to save the file, so need to cancel the
1082 // download that's already in progress to the temporary location.
[email protected]4cd82f72011-05-23 19:15:011083 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1084 int32* id_ptr = reinterpret_cast<int32*>(params);
1085 DCHECK(id_ptr != NULL);
1086 int32 download_id = *id_ptr;
1087 delete id_ptr;
1088
1089 DownloadItem* download = GetActiveDownloadItem(download_id);
1090 if (!download)
1091 return;
1092
1093 VLOG(20) << __FUNCTION__ << "()"
1094 << " download = " << download->DebugString(true);
1095
[email protected]54610672011-07-18 18:24:431096 DownloadCancelledInternal(download_id, download->request_handle());
[email protected]4cd82f72011-05-23 19:15:011097}
1098
1099// TODO(phajdan.jr): This is apparently not being exercised in tests.
1100bool DownloadManager::IsDangerous(const DownloadItem& download,
[email protected]88008002011-05-24 23:14:151101 const DownloadStateInfo& state,
1102 bool visited_referrer_before) {
[email protected]4cd82f72011-05-23 19:15:011103 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1104
1105 bool auto_open = ShouldOpenFileBasedOnExtension(state.suggested_path);
1106 download_util::DownloadDangerLevel danger_level =
1107 download_util::GetFileDangerLevel(state.suggested_path.BaseName());
1108
1109 if (danger_level == download_util::Dangerous)
1110 return !(auto_open && state.has_user_gesture);
1111
1112 if (danger_level == download_util::AllowOnUserGesture &&
[email protected]88008002011-05-24 23:14:151113 (!state.has_user_gesture || !visited_referrer_before))
[email protected]4cd82f72011-05-23 19:15:011114 return true;
1115
1116 if (state.is_extension_install) {
1117 // Extensions that are not from the gallery are considered dangerous.
1118 ExtensionService* service = profile()->GetExtensionService();
1119 if (!service || !service->IsDownloadFromGallery(download.GetURL(),
1120 download.referrer_url()))
1121 return true;
1122 }
1123 return false;
initial.commit09911bf2008-07-26 23:55:291124}
1125
1126// Operations posted to us from the history service ----------------------------
1127
1128// The history service has retrieved all download entries. 'entries' contains
[email protected]4cd82f72011-05-23 19:15:011129// 'DownloadHistoryInfo's in sorted order (by ascending start_time).
initial.commit09911bf2008-07-26 23:55:291130void DownloadManager::OnQueryDownloadEntriesComplete(
[email protected]4cd82f72011-05-23 19:15:011131 std::vector<DownloadHistoryInfo>* entries) {
initial.commit09911bf2008-07-26 23:55:291132 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:391133 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]f04182f32010-12-10 19:12:071134 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
1135 downloads_.insert(download);
1136 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:501137 VLOG(20) << __FUNCTION__ << "()" << i << ">"
1138 << " download = " << download->DebugString(true);
initial.commit09911bf2008-07-26 23:55:291139 }
[email protected]b0ab1d42010-02-24 19:29:281140 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:481141 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:291142}
1143
[email protected]f9a45b02011-06-30 23:49:191144void DownloadManager::AddDownloadItemToHistory(DownloadItem* download,
1145 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:271146 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d2a8fb72010-01-21 05:31:421147
[email protected]5bcd73eb2011-03-23 21:14:021148 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1149 // call this function with an invalid |db_handle|. For instance, this can
1150 // happen when the history database is offline. We cannot have multiple
1151 // DownloadItems with the same invalid db_handle, so we need to assign a
1152 // unique |db_handle| here.
1153 if (db_handle == DownloadHistory::kUninitializedHandle)
1154 db_handle = download_history_->GetNextFakeDbHandle();
1155
[email protected]1e9fe7ff2011-06-24 17:37:331156 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/84508
1157 // is fixed.
[email protected]54610672011-07-18 18:24:431158 CHECK_NE(DownloadHistory::kUninitializedHandle, db_handle);
[email protected]1e9fe7ff2011-06-24 17:37:331159
[email protected]5bcd73eb2011-03-23 21:14:021160 DCHECK(download->db_handle() == DownloadHistory::kUninitializedHandle);
1161 download->set_db_handle(db_handle);
1162
[email protected]5bcd73eb2011-03-23 21:14:021163 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
1164 history_downloads_[download->db_handle()] = download;
[email protected]f9a45b02011-06-30 23:49:191165}
1166
1167// Once the new DownloadItem's creation info has been committed to the history
1168// service, we associate the DownloadItem with the db handle, update our
1169// 'history_downloads_' map and inform observers.
1170void DownloadManager::OnCreateDownloadEntryComplete(int32 download_id,
1171 int64 db_handle) {
1172 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]19420cc2011-07-18 17:43:451173 DownloadItem* download = GetActiveDownloadItem(download_id);
[email protected]54610672011-07-18 18:24:431174 if (!download)
[email protected]19420cc2011-07-18 17:43:451175 return;
[email protected]54610672011-07-18 18:24:431176
1177 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
1178 << " download_id = " << download_id
1179 << " download = " << download->DebugString(true);
[email protected]f9a45b02011-06-30 23:49:191180
1181 AddDownloadItemToHistory(download, db_handle);
initial.commit09911bf2008-07-26 23:55:291182
[email protected]70850c72011-01-11 17:31:271183 // Show in the appropriate browser UI.
[email protected]9d7ef802011-02-25 19:03:351184 // This includes buttons to save or cancel, for a dangerous download.
[email protected]4cd82f72011-05-23 19:15:011185 ShowDownloadInBrowser(download);
initial.commit09911bf2008-07-26 23:55:291186
1187 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281188 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291189
[email protected]54610672011-07-18 18:24:431190 // If the download is still in progress, try to complete it.
1191 //
1192 // Otherwise, download has been cancelled or interrupted before we've
1193 // received the DB handle. We post one final message to the history
1194 // service so that it can be properly in sync with the DownloadItem's
1195 // completion status, and also inform any observers so that they get
1196 // more than just the start notification.
1197 if (download->IsInProgress()) {
1198 MaybeCompleteDownload(download);
1199 } else {
1200 DCHECK(download->IsCancelled())
1201 << " download = " << download->DebugString(true);
1202 in_progress_.erase(download_id);
1203 active_downloads_.erase(download_id);
1204 download_history_->UpdateEntry(download);
1205 download->UpdateObservers();
1206 }
initial.commit09911bf2008-07-26 23:55:291207}
1208
[email protected]4cd82f72011-05-23 19:15:011209void DownloadManager::ShowDownloadInBrowser(DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341210 // The 'contents' may no longer exist if the user closed the tab before we
[email protected]99cb7f82011-07-28 17:27:261211 // get this start completion event.
[email protected]db6831a2011-06-09 21:08:281212 DownloadRequestHandle request_handle = download->request_handle();
[email protected]686493142011-07-15 21:47:221213 TabContents* content = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:261214
1215 // If the contents no longer exists, we ask the embedder to suggest another
1216 // tab.
[email protected]686493142011-07-15 21:47:221217 if (!content) {
[email protected]99cb7f82011-07-28 17:27:261218 content = content::GetContentClient()->browser()->
1219 GetAlternativeTabContentsToNotifyForDownload(this);
[email protected]5e595482009-05-06 20:16:531220 }
1221
[email protected]99cb7f82011-07-28 17:27:261222 if (content)
1223 content->OnStartDownload(download);
[email protected]5e595482009-05-06 20:16:531224}
1225
[email protected]6cade212008-12-03 00:32:221226// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121227void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411228 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381229}
[email protected]b0ab1d42010-02-24 19:29:281230
1231void DownloadManager::NotifyModelChanged() {
1232 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1233}
1234
[email protected]4cd82f72011-05-23 19:15:011235DownloadItem* DownloadManager::GetDownloadItem(int download_id) {
1236 // The |history_downloads_| map is indexed by the download's db_handle,
1237 // not its id, so we have to iterate.
[email protected]f04182f32010-12-10 19:12:071238 for (DownloadMap::iterator it = history_downloads_.begin();
1239 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:361240 DownloadItem* item = it->second;
[email protected]4cd82f72011-05-23 19:15:011241 if (item->id() == download_id)
[email protected]2e030682010-07-23 19:45:361242 return item;
1243 }
1244 return NULL;
1245}
1246
[email protected]4cd82f72011-05-23 19:15:011247DownloadItem* DownloadManager::GetActiveDownloadItem(int download_id) {
1248 DCHECK(ContainsKey(active_downloads_, download_id));
1249 DownloadItem* download = active_downloads_[download_id];
1250 DCHECK(download != NULL);
1251 return download;
1252}
1253
[email protected]57fd1252010-12-23 17:24:091254// Confirm that everything in all maps is also in |downloads_|, and that
1255// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:071256void DownloadManager::AssertContainersConsistent() const {
1257#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:091258 // Turn everything into sets.
[email protected]adb2f3d12011-01-23 16:24:541259 DownloadSet active_set, history_set;
[email protected]70850c72011-01-11 17:31:271260 const DownloadMap* input_maps[] = {&active_downloads_, &history_downloads_};
[email protected]adb2f3d12011-01-23 16:24:541261 DownloadSet* local_sets[] = {&active_set, &history_set};
[email protected]57fd1252010-12-23 17:24:091262 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(local_sets));
1263 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
1264 for (DownloadMap::const_iterator it = input_maps[i]->begin();
1265 it != input_maps[i]->end(); it++) {
1266 local_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:071267 }
1268 }
[email protected]57fd1252010-12-23 17:24:091269
1270 // Check if each set is fully present in downloads, and create a union.
[email protected]adb2f3d12011-01-23 16:24:541271 const DownloadSet* all_sets[] = {&active_set, &history_set,
[email protected]57fd1252010-12-23 17:24:091272 &save_page_as_downloads_};
1273 DownloadSet downloads_union;
1274 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
1275 DownloadSet remainder;
1276 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
1277 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
1278 downloads_.begin(), downloads_.end(),
1279 insert_it);
1280 DCHECK(remainder.empty());
1281 std::insert_iterator<DownloadSet>
1282 insert_union(downloads_union, downloads_union.end());
1283 std::set_union(downloads_union.begin(), downloads_union.end(),
1284 all_sets[i]->begin(), all_sets[i]->end(),
1285 insert_union);
1286 }
1287
1288 // Is everything in downloads_ present in one of the other sets?
1289 DownloadSet remainder;
1290 std::insert_iterator<DownloadSet>
1291 insert_remainder(remainder, remainder.begin());
1292 std::set_difference(downloads_.begin(), downloads_.end(),
1293 downloads_union.begin(), downloads_union.end(),
1294 insert_remainder);
1295 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071296#endif
1297}
1298
[email protected]b0ab1d42010-02-24 19:29:281299// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1300
1301DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1302 DownloadManager* observing_download_manager)
1303 : observing_download_manager_(observing_download_manager),
1304 observed_download_manager_(NULL) {
1305 if (observing_download_manager->profile_->GetOriginalProfile() ==
1306 observing_download_manager->profile_) {
1307 return;
1308 }
1309
1310 observed_download_manager_ = observing_download_manager_->
1311 profile_->GetOriginalProfile()->GetDownloadManager();
1312 observed_download_manager_->AddObserver(this);
1313}
1314
1315DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1316 if (observed_download_manager_)
1317 observed_download_manager_->RemoveObserver(this);
1318}
1319
1320void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1321 observing_download_manager_->NotifyModelChanged();
1322}
1323
[email protected]b0ab1d42010-02-24 19:29:281324void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1325 observed_download_manager_ = NULL;
1326}