blob: cb62310f9020260ca3d677cc4069385919a372ec [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]da1a27b2011-07-29 23:16:3325#include "chrome/browser/download/download_manager_delegate.h"
[email protected]e5dc4222010-08-30 22:16:3226#include "chrome/browser/download/download_prefs.h"
[email protected]db6831a2011-06-09 21:08:2827#include "chrome/browser/download/download_request_handle.h"
[email protected]287b86b2011-02-26 00:11:3528#include "chrome/browser/download/download_safe_browsing_client.h"
[email protected]073ed7b2010-09-27 09:20:0229#include "chrome/browser/download/download_status_updater.h"
[email protected]e9ef0a62009-08-11 22:50:1330#include "chrome/browser/download/download_util.h"
[email protected]eaa7dd182010-12-14 11:09:0031#include "chrome/browser/extensions/extension_service.h"
[email protected]4cd82f72011-05-23 19:15:0132#include "chrome/browser/history/download_history_info.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"
initial.commit09911bf2008-07-26 23:55:2935#include "chrome/common/chrome_paths.h"
[email protected]8c40da62011-07-13 22:58:4636#include "chrome/common/pref_names.h"
[email protected]7324d1d2011-03-01 05:02:1637#include "content/browser/browser_thread.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]da1a27b2011-07-29 23:16:3351DownloadManager::DownloadManager(DownloadManagerDelegate* delegate,
52 DownloadStatusUpdater* status_updater)
initial.commit09911bf2008-07-26 23:55:2953 : shutdown_needed_(false),
54 profile_(NULL),
[email protected]073ed7b2010-09-27 09:20:0255 file_manager_(NULL),
[email protected]da1a27b2011-07-29 23:16:3356 status_updater_(status_updater->AsWeakPtr()),
57 delegate_(delegate) {
[email protected]073ed7b2010-09-27 09:20:0258 if (status_updater_)
59 status_updater_->AddDelegate(this);
initial.commit09911bf2008-07-26 23:55:2960}
61
62DownloadManager::~DownloadManager() {
[email protected]326a6a92010-09-10 20:21:1363 DCHECK(!shutdown_needed_);
[email protected]073ed7b2010-09-27 09:20:0264 if (status_updater_)
65 status_updater_->RemoveDelegate(this);
initial.commit09911bf2008-07-26 23:55:2966}
67
68void DownloadManager::Shutdown() {
[email protected]da6e3922010-11-24 21:45:5069 VLOG(20) << __FUNCTION__ << "()"
70 << " shutdown_needed_ = " << shutdown_needed_;
[email protected]326a6a92010-09-10 20:21:1371 if (!shutdown_needed_)
72 return;
73 shutdown_needed_ = false;
initial.commit09911bf2008-07-26 23:55:2974
[email protected]326a6a92010-09-10 20:21:1375 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
76
77 if (file_manager_) {
[email protected]ca4b5fa32010-10-09 12:42:1878 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
[email protected]326a6a92010-09-10 20:21:1379 NewRunnableMethod(file_manager_,
80 &DownloadFileManager::OnDownloadManagerShutdown,
[email protected]dc7cdcb92010-12-14 06:40:5481 make_scoped_refptr(this)));
[email protected]326a6a92010-09-10 20:21:1382 }
initial.commit09911bf2008-07-26 23:55:2983
[email protected]f04182f32010-12-10 19:12:0784 AssertContainersConsistent();
85
86 // Go through all downloads in downloads_. Dangerous ones we need to
87 // remove on disk, and in progress ones we need to cancel.
[email protected]57fd1252010-12-23 17:24:0988 for (DownloadSet::iterator it = downloads_.begin(); it != downloads_.end();) {
[email protected]f04182f32010-12-10 19:12:0789 DownloadItem* download = *it;
90
91 // Save iterator from potential erases in this set done by called code.
92 // Iterators after an erasure point are still valid for lists and
93 // associative containers such as sets.
94 it++;
95
96 if (download->safety_state() == DownloadItem::DANGEROUS &&
[email protected]48837962011-04-19 17:03:2997 download->IsPartialDownload()) {
[email protected]f04182f32010-12-10 19:12:0798 // The user hasn't accepted it, so we need to remove it
99 // from the disk. This may or may not result in it being
100 // removed from the DownloadManager queues and deleted
101 // (specifically, DownloadManager::RemoveDownload only
102 // removes and deletes it if it's known to the history service)
103 // so the only thing we know after calling this function is that
104 // the download was deleted if-and-only-if it was removed
105 // from all queues.
[email protected]303077002011-04-19 23:21:01106 download->Delete(DownloadItem::DELETE_DUE_TO_BROWSER_SHUTDOWN);
[email protected]bf68a00b2011-04-07 17:28:26107 } else if (download->IsPartialDownload()) {
[email protected]54610672011-07-18 18:24:43108 download->Cancel(false);
109 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29110 }
111 }
112
[email protected]f04182f32010-12-10 19:12:07113 // At this point, all dangerous downloads have had their files removed
114 // and all in progress downloads have been cancelled. We can now delete
115 // anything left.
[email protected]9ccbb372008-10-10 18:50:32116
[email protected]5cd11b6e2011-06-10 20:30:59117 // Copy downloads_ to separate container so as not to set off checks
118 // in DownloadItem destruction.
119 DownloadSet downloads_to_delete;
120 downloads_to_delete.swap(downloads_);
121
initial.commit09911bf2008-07-26 23:55:29122 in_progress_.clear();
[email protected]70850c72011-01-11 17:31:27123 active_downloads_.clear();
[email protected]5cd11b6e2011-06-10 20:30:59124 history_downloads_.clear();
[email protected]57fd1252010-12-23 17:24:09125#if !defined(NDEBUG)
126 save_page_as_downloads_.clear();
127#endif
[email protected]5cd11b6e2011-06-10 20:30:59128 STLDeleteElements(&downloads_to_delete);
initial.commit09911bf2008-07-26 23:55:29129
130 file_manager_ = NULL;
131
[email protected]82f37b02010-07-29 22:04:57132 download_history_.reset();
[email protected]68a49e52011-01-28 10:39:51133 download_prefs_.reset();
[email protected]82f37b02010-07-29 22:04:57134
initial.commit09911bf2008-07-26 23:55:29135 shutdown_needed_ = false;
136}
137
[email protected]82f37b02010-07-29 22:04:57138void DownloadManager::GetTemporaryDownloads(
139 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
140 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58141
[email protected]f04182f32010-12-10 19:12:07142 for (DownloadMap::iterator it = history_downloads_.begin();
143 it != history_downloads_.end(); ++it) {
[email protected]6aa4a1c02010-01-15 18:49:58144 if (it->second->is_temporary() &&
145 it->second->full_path().DirName() == dir_path)
[email protected]82f37b02010-07-29 22:04:57146 result->push_back(it->second);
[email protected]6aa4a1c02010-01-15 18:49:58147 }
[email protected]6aa4a1c02010-01-15 18:49:58148}
149
[email protected]82f37b02010-07-29 22:04:57150void DownloadManager::GetAllDownloads(
151 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
152 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34153
[email protected]f04182f32010-12-10 19:12:07154 for (DownloadMap::iterator it = history_downloads_.begin();
155 it != history_downloads_.end(); ++it) {
[email protected]8ddbd66a2010-05-21 16:38:34156 if (!it->second->is_temporary() &&
157 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57158 result->push_back(it->second);
[email protected]8ddbd66a2010-05-21 16:38:34159 }
[email protected]8ddbd66a2010-05-21 16:38:34160}
161
[email protected]82f37b02010-07-29 22:04:57162void DownloadManager::GetCurrentDownloads(
163 const FilePath& dir_path, std::vector<DownloadItem*>* result) {
164 DCHECK(result);
[email protected]c4a530b2010-03-08 17:33:03165
[email protected]f04182f32010-12-10 19:12:07166 for (DownloadMap::iterator it = history_downloads_.begin();
167 it != history_downloads_.end(); ++it) {
[email protected]bf68a00b2011-04-07 17:28:26168 DownloadItem* item =it->second;
169 // Skip temporary items.
170 if (item->is_temporary())
171 continue;
172 // Skip items that have all their data, and are OK to save.
173 if (!item->IsPartialDownload() &&
174 (item->safety_state() != DownloadItem::DANGEROUS))
175 continue;
176 // Skip items that don't match |dir_path|.
177 // If |dir_path| is empty, all remaining items match.
178 if (!dir_path.empty() && (it->second->full_path().DirName() != dir_path))
179 continue;
180
181 result->push_back(item);
[email protected]c4a530b2010-03-08 17:33:03182 }
[email protected]f7e9fd62010-09-28 15:45:06183
184 // If we have a parent profile, let it add its downloads to the results.
185 Profile* original_profile = profile_->GetOriginalProfile();
186 if (original_profile != profile_)
187 original_profile->GetDownloadManager()->GetCurrentDownloads(dir_path,
188 result);
[email protected]c4a530b2010-03-08 17:33:03189}
190
[email protected]d3b12902010-08-16 23:39:42191void DownloadManager::SearchDownloads(const string16& query,
192 std::vector<DownloadItem*>* result) {
193 DCHECK(result);
194
[email protected]503d03872011-05-06 08:36:26195 string16 query_lower(base::i18n::ToLower(query));
[email protected]d3b12902010-08-16 23:39:42196
[email protected]f04182f32010-12-10 19:12:07197 for (DownloadMap::iterator it = history_downloads_.begin();
198 it != history_downloads_.end(); ++it) {
[email protected]d3b12902010-08-16 23:39:42199 DownloadItem* download_item = it->second;
200
201 if (download_item->is_temporary() || download_item->is_extension_install())
202 continue;
203
204 // Display Incognito downloads only in Incognito window, and vice versa.
205 // The Incognito Downloads page will get the list of non-Incognito downloads
206 // from its parent profile.
207 if (profile_->IsOffTheRecord() != download_item->is_otr())
208 continue;
209
210 if (download_item->MatchesQuery(query_lower))
211 result->push_back(download_item);
212 }
213
214 // If we have a parent profile, let it add its downloads to the results.
215 Profile* original_profile = profile_->GetOriginalProfile();
216 if (original_profile != profile_)
217 original_profile->GetDownloadManager()->SearchDownloads(query, result);
218}
219
initial.commit09911bf2008-07-26 23:55:29220// Query the history service for information about all persisted downloads.
221bool DownloadManager::Init(Profile* profile) {
222 DCHECK(profile);
223 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
224 shutdown_needed_ = true;
225
226 profile_ = profile;
[email protected]d3b12902010-08-16 23:39:42227 download_history_.reset(new DownloadHistory(profile));
[email protected]82f37b02010-07-29 22:04:57228 download_history_->Load(
229 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
[email protected]024f2f02010-04-30 22:51:46230
[email protected]e5dc4222010-08-30 22:16:32231 download_prefs_.reset(new DownloadPrefs(profile_->GetPrefs()));
232
[email protected]2941c2392010-07-15 22:54:30233 // In test mode, there may be no ResourceDispatcherHost. In this case it's
234 // safe to avoid setting |file_manager_| because we only call a small set of
235 // functions, none of which need it.
initial.commit09911bf2008-07-26 23:55:29236 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]2941c2392010-07-15 22:54:30237 if (rdh) {
238 file_manager_ = rdh->download_file_manager();
239 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29240 }
241
[email protected]b0ab1d42010-02-24 19:29:28242 other_download_manager_observer_.reset(
243 new OtherDownloadManagerObserver(this));
244
initial.commit09911bf2008-07-26 23:55:29245 return true;
246}
247
initial.commit09911bf2008-07-26 23:55:29248// We have received a message from DownloadFileManager about a new download. We
249// create a download item and store it in our download map, and inform the
250// history system of a new download. Since this method can be called while the
251// history service thread is still reading the persistent state, we do not
[email protected]f04182f32010-12-10 19:12:07252// insert the new DownloadItem into 'history_downloads_' or inform our
[email protected]adb2f3d12011-01-23 16:24:54253// observers at this point. OnCreateDownloadEntryComplete() handles that
[email protected]f04182f32010-12-10 19:12:07254// finalization of the the download creation as a callback from the
255// history thread.
[email protected]4cd82f72011-05-23 19:15:01256void DownloadManager::StartDownload(int32 download_id) {
[email protected]ca4b5fa32010-10-09 12:42:18257 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]287b86b2011-02-26 00:11:35258
[email protected]4cd82f72011-05-23 19:15:01259 DownloadItem* download = GetActiveDownloadItem(download_id);
260 if (!download)
261 return;
262
[email protected]4b58e7d2011-07-11 10:22:56263#if defined(ENABLE_SAFE_BROWSING)
[email protected]287b86b2011-02-26 00:11:35264 // Create a client to verify download URL with safebrowsing.
265 // It deletes itself after the callback.
[email protected]26711732011-03-09 00:21:22266 scoped_refptr<DownloadSBClient> sb_client = new DownloadSBClient(
[email protected]8c40da62011-07-13 22:58:46267 download_id, download->url_chain(), download->referrer_url(),
268 profile_->GetPrefs()->GetBoolean(prefs::kSafeBrowsingEnabled));
[email protected]287b86b2011-02-26 00:11:35269 sb_client->CheckDownloadUrl(
[email protected]4cd82f72011-05-23 19:15:01270 NewCallback(this, &DownloadManager::CheckDownloadUrlDone));
[email protected]4b58e7d2011-07-11 10:22:56271#else
272 CheckDownloadUrlDone(download_id, false);
273#endif
[email protected]287b86b2011-02-26 00:11:35274}
275
[email protected]9fc114672011-06-15 08:17:48276void DownloadManager::CheckForHistoryFilesRemoval() {
277 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
278 for (DownloadMap::iterator it = history_downloads_.begin();
279 it != history_downloads_.end(); ++it) {
280 CheckForFileRemoval(it->second);
281 }
282}
283
284void DownloadManager::CheckForFileRemoval(DownloadItem* download_item) {
285 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
286 if (download_item->IsComplete() &&
287 !download_item->file_externally_removed()) {
288 BrowserThread::PostTask(
289 BrowserThread::FILE, FROM_HERE,
290 NewRunnableMethod(this,
291 &DownloadManager::CheckForFileRemovalOnFileThread,
292 download_item->db_handle(),
293 download_item->GetTargetFilePath()));
294 }
295}
296
297void DownloadManager::CheckForFileRemovalOnFileThread(
298 int64 db_handle, const FilePath& path) {
299 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
300 if (!file_util::PathExists(path)) {
301 BrowserThread::PostTask(
302 BrowserThread::UI, FROM_HERE,
303 NewRunnableMethod(this,
304 &DownloadManager::OnFileRemovalDetected,
305 db_handle));
306 }
307}
308
309void DownloadManager::OnFileRemovalDetected(int64 db_handle) {
310 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
311 DownloadMap::iterator it = history_downloads_.find(db_handle);
312 if (it != history_downloads_.end()) {
313 DownloadItem* download_item = it->second;
314 download_item->OnDownloadedFileRemoved();
315 }
316}
317
[email protected]4cd82f72011-05-23 19:15:01318void DownloadManager::CheckDownloadUrlDone(int32 download_id,
[email protected]287b86b2011-02-26 00:11:35319 bool is_dangerous_url) {
320 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29321
[email protected]4cd82f72011-05-23 19:15:01322 DownloadItem* download = GetActiveDownloadItem(download_id);
323 if (!download)
324 return;
325
326 if (is_dangerous_url)
327 download->MarkUrlDangerous();
328
[email protected]88008002011-05-24 23:14:15329 download_history_->CheckVisitedReferrerBefore(download_id,
330 download->referrer_url(),
331 NewCallback(this, &DownloadManager::CheckVisitedReferrerBeforeDone));
332}
333
334void DownloadManager::CheckVisitedReferrerBeforeDone(
335 int32 download_id,
336 bool visited_referrer_before) {
337 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
338
339 DownloadItem* download = GetActiveDownloadItem(download_id);
340 if (!download)
341 return;
[email protected]287b86b2011-02-26 00:11:35342
[email protected]a60c8ae2009-12-25 06:50:57343 // Check whether this download is for an extension install or not.
[email protected]e6875c12010-07-18 11:14:13344 // Allow extensions to be explicitly saved.
[email protected]88008002011-05-24 23:14:15345 DownloadStateInfo state = download->state_info();
[email protected]4cd82f72011-05-23 19:15:01346 if (!state.prompt_user_for_save_location) {
347 if (UserScript::IsURLUserScript(download->GetURL(),
348 download->mime_type()) ||
349 (download->mime_type() == Extension::kMimeType)) {
350 state.is_extension_install = true;
[email protected]bac4f4b2011-03-05 02:01:40351 }
[email protected]a60c8ae2009-12-25 06:50:57352 }
353
[email protected]4cd82f72011-05-23 19:15:01354 if (state.force_file_name.empty()) {
[email protected]2941c2392010-07-15 22:54:30355 FilePath generated_name;
[email protected]0622875ab2011-07-27 12:10:34356 download_util::GenerateFileNameFromRequest(*download,
[email protected]4cd82f72011-05-23 19:15:01357 &generated_name);
[email protected]2941c2392010-07-15 22:54:30358
359 // Freeze the user's preference for showing a Save As dialog. We're going
360 // to bounce around a bunch of threads and we don't want to worry about race
361 // conditions where the user changes this pref out from under us.
[email protected]0e9b6072011-02-17 12:42:05362 if (download_prefs_->PromptForDownload()) {
[email protected]2941c2392010-07-15 22:54:30363 // But ignore the user's preference for the following scenarios:
364 // 1) Extension installation. Note that we only care here about the case
365 // where an extension is installed, not when one is downloaded with
366 // "save as...".
367 // 2) Filetypes marked "always open." If the user just wants this file
368 // opened, don't bother asking where to keep it.
[email protected]4cd82f72011-05-23 19:15:01369 if (!state.is_extension_install &&
[email protected]2941c2392010-07-15 22:54:30370 !ShouldOpenFileBasedOnExtension(generated_name))
[email protected]4cd82f72011-05-23 19:15:01371 state.prompt_user_for_save_location = true;
[email protected]2941c2392010-07-15 22:54:30372 }
[email protected]14e0a102011-02-22 14:04:01373 if (download_prefs_->IsDownloadPathManaged()) {
[email protected]4cd82f72011-05-23 19:15:01374 state.prompt_user_for_save_location = false;
[email protected]14e0a102011-02-22 14:04:01375 }
[email protected]2941c2392010-07-15 22:54:30376
[email protected]8af9d032010-02-10 00:00:32377 // Determine the proper path for a download, by either one of the following:
378 // 1) using the default download directory.
379 // 2) prompting the user.
[email protected]4cd82f72011-05-23 19:15:01380 if (state.prompt_user_for_save_location && !last_download_path_.empty()) {
381 state.suggested_path = last_download_path_;
[email protected]80dc3612010-07-27 19:35:08382 } else {
[email protected]4cd82f72011-05-23 19:15:01383 state.suggested_path = download_prefs_->download_path();
[email protected]80dc3612010-07-27 19:35:08384 }
[email protected]4cd82f72011-05-23 19:15:01385 state.suggested_path = state.suggested_path.Append(generated_name);
[email protected]8af9d032010-02-10 00:00:32386 } else {
[email protected]4cd82f72011-05-23 19:15:01387 state.suggested_path = state.force_file_name;
[email protected]8af9d032010-02-10 00:00:32388 }
initial.commit09911bf2008-07-26 23:55:29389
[email protected]88008002011-05-24 23:14:15390 if (!state.prompt_user_for_save_location && state.force_file_name.empty()) {
391 state.is_dangerous_file =
[email protected]da1a27b2011-07-29 23:16:33392 IsDangerousFile(*download, state, visited_referrer_before);
[email protected]88008002011-05-24 23:14:15393 }
[email protected]e9ebf3fc2008-10-17 22:06:58394
initial.commit09911bf2008-07-26 23:55:29395 // We need to move over to the download thread because we don't want to stat
396 // the suggested path on the UI thread.
[email protected]5a3b97e2010-10-05 09:49:11397 // We can only access preferences on the UI thread, so check the download path
398 // now and pass the value to the FILE thread.
[email protected]ca4b5fa32010-10-09 12:42:18399 BrowserThread::PostTask(
400 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37401 NewRunnableMethod(
[email protected]5a3b97e2010-10-05 09:49:11402 this,
403 &DownloadManager::CheckIfSuggestedPathExists,
[email protected]88008002011-05-24 23:14:15404 download->id(),
[email protected]4cd82f72011-05-23 19:15:01405 state,
[email protected]5a3b97e2010-10-05 09:49:11406 download_prefs()->download_path()));
initial.commit09911bf2008-07-26 23:55:29407}
408
[email protected]fed38252011-07-08 17:26:50409void DownloadManager::CheckIfSuggestedPathExists(int32 download_id,
410 DownloadStateInfo state,
411 const FilePath& default_path) {
[email protected]ca4b5fa32010-10-09 12:42:18412 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
initial.commit09911bf2008-07-26 23:55:29413
[email protected]fed38252011-07-08 17:26:50414 // Make sure the default download directory exists.
415 // TODO(phajdan.jr): only create the directory when we're sure the user
416 // is going to save there and not to another directory of his choice.
417 file_util::CreateDirectory(default_path);
418
419 // Check writability of the suggested path. If we can't write to it, default
420 // to the user's "My Documents" directory. We'll prompt them in this case.
421 FilePath dir = state.suggested_path.DirName();
422 FilePath filename = state.suggested_path.BaseName();
423 if (!file_util::PathIsWritable(dir)) {
424 VLOG(1) << "Unable to write to directory \"" << dir.value() << "\"";
[email protected]4cd82f72011-05-23 19:15:01425 state.prompt_user_for_save_location = true;
[email protected]fed38252011-07-08 17:26:50426 PathService::Get(chrome::DIR_USER_DOCUMENTS, &state.suggested_path);
427 state.suggested_path = state.suggested_path.Append(filename);
428 }
initial.commit09911bf2008-07-26 23:55:29429
[email protected]6cade212008-12-03 00:32:22430 // If the download is deemed dangerous, we'll use a temporary name for it.
[email protected]4cd82f72011-05-23 19:15:01431 if (state.IsDangerous()) {
[email protected]fed38252011-07-08 17:26:50432 state.target_name = FilePath(state.suggested_path).BaseName();
[email protected]9ccbb372008-10-10 18:50:32433 // Create a temporary file to hold the file until the user approves its
434 // download.
[email protected]7ae7c2cb2009-01-06 23:31:41435 FilePath::StringType file_name;
436 FilePath path;
[email protected]463e1b432011-01-21 22:05:51437#if defined(OS_WIN)
438 string16 unconfirmed_prefix =
439 l10n_util::GetStringUTF16(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
440#else
441 std::string unconfirmed_prefix =
442 l10n_util::GetStringUTF8(IDS_DOWNLOAD_UNCONFIRMED_PREFIX);
443#endif
444
[email protected]9ccbb372008-10-10 18:50:32445 while (path.empty()) {
[email protected]2594c2b2010-11-08 23:04:26446 base::SStringPrintf(
447 &file_name,
[email protected]463e1b432011-01-21 22:05:51448 unconfirmed_prefix.append(
449 FILE_PATH_LITERAL(" %d.crdownload")).c_str(),
[email protected]2594c2b2010-11-08 23:04:26450 base::RandInt(0, 100000));
[email protected]fed38252011-07-08 17:26:50451 path = dir.Append(file_name);
[email protected]7d3851d82008-12-12 03:26:07452 if (file_util::PathExists(path))
[email protected]7ae7c2cb2009-01-06 23:31:41453 path = FilePath();
[email protected]9ccbb372008-10-10 18:50:32454 }
[email protected]4cd82f72011-05-23 19:15:01455 state.suggested_path = path;
[email protected]7a256ea2008-10-17 17:34:16456 } else {
[email protected]594cd7d2010-07-21 03:23:56457 // Do not add the path uniquifier if we are saving to a specific path as in
458 // the drag-out case.
[email protected]4cd82f72011-05-23 19:15:01459 if (state.force_file_name.empty()) {
460 state.path_uniquifier = download_util::GetUniquePathNumberWithCrDownload(
461 state.suggested_path);
[email protected]594cd7d2010-07-21 03:23:56462 }
[email protected]7a256ea2008-10-17 17:34:16463 // We know the final path, build it if necessary.
[email protected]4cd82f72011-05-23 19:15:01464 if (state.path_uniquifier > 0) {
465 download_util::AppendNumberToPath(&(state.suggested_path),
466 state.path_uniquifier);
[email protected]7a256ea2008-10-17 17:34:16467 // Setting path_uniquifier to 0 to make sure we don't try to unique it
468 // later on.
[email protected]4cd82f72011-05-23 19:15:01469 state.path_uniquifier = 0;
470 } else if (state.path_uniquifier == -1) {
[email protected]7d3851d82008-12-12 03:26:07471 // We failed to find a unique path. We have to prompt the user.
[email protected]da6e3922010-11-24 21:45:50472 VLOG(1) << "Unable to find a unique path for suggested path \""
[email protected]4cd82f72011-05-23 19:15:01473 << state.suggested_path.value() << "\"";
474 state.prompt_user_for_save_location = true;
[email protected]7a256ea2008-10-17 17:34:16475 }
[email protected]9ccbb372008-10-10 18:50:32476 }
477
[email protected]594cd7d2010-07-21 03:23:56478 // Create an empty file at the suggested path so that we don't allocate the
479 // same "non-existant" path to multiple downloads.
480 // See: http://code.google.com/p/chromium/issues/detail?id=3662
[email protected]4cd82f72011-05-23 19:15:01481 if (!state.prompt_user_for_save_location &&
482 state.force_file_name.empty()) {
483 if (state.IsDangerous())
484 file_util::WriteFile(state.suggested_path, "", 0);
[email protected]594cd7d2010-07-21 03:23:56485 else
486 file_util::WriteFile(download_util::GetCrDownloadPath(
[email protected]4cd82f72011-05-23 19:15:01487 state.suggested_path), "", 0);
[email protected]7d3851d82008-12-12 03:26:07488 }
489
[email protected]ca4b5fa32010-10-09 12:42:18490 BrowserThread::PostTask(
491 BrowserThread::UI, FROM_HERE,
initial.commit09911bf2008-07-26 23:55:29492 NewRunnableMethod(this,
493 &DownloadManager::OnPathExistenceAvailable,
[email protected]4cd82f72011-05-23 19:15:01494 download_id,
495 state));
initial.commit09911bf2008-07-26 23:55:29496}
497
[email protected]22001462011-06-22 17:42:51498void DownloadManager::OnPathExistenceAvailable(
499 int32 download_id, const DownloadStateInfo& new_state) {
[email protected]ca4b5fa32010-10-09 12:42:18500 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29501
[email protected]4cd82f72011-05-23 19:15:01502 DownloadItem* download = GetActiveDownloadItem(download_id);
503 if (!download)
504 return;
505
506 VLOG(20) << __FUNCTION__ << "()"
507 << " download = " << download->DebugString(true);
508
509 download->SetFileCheckResults(new_state);
510
511 FilePath suggested_path = download->suggested_path();
512
[email protected]da1a27b2011-07-29 23:16:33513 if (download->prompt_user_for_save_location()) {
initial.commit09911bf2008-07-26 23:55:29514 // We must ask the user for the place to put the download.
[email protected]db6831a2011-06-09 21:08:28515 DownloadRequestHandle request_handle = download->request_handle();
516 TabContents* contents = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:26517
[email protected]4cd82f72011-05-23 19:15:01518 // |id_ptr| will be deleted in either FileSelected() or
519 // FileSelectionCancelled().
520 int32* id_ptr = new int32;
521 *id_ptr = download_id;
[email protected]99cb7f82011-07-28 17:27:26522
[email protected]da1a27b2011-07-29 23:16:33523 delegate_->ChooseDownloadPath(
[email protected]99cb7f82011-07-28 17:27:26524 this, contents, suggested_path, reinterpret_cast<void*>(id_ptr));
525
[email protected]f5920322011-03-24 20:34:16526 FOR_EACH_OBSERVER(Observer, observers_,
[email protected]fed38252011-07-08 17:26:50527 SelectFileDialogDisplayed(download_id));
initial.commit09911bf2008-07-26 23:55:29528 } else {
529 // No prompting for download, just continue with the suggested name.
[email protected]4cd82f72011-05-23 19:15:01530 ContinueDownloadWithPath(download, suggested_path);
initial.commit09911bf2008-07-26 23:55:29531 }
532}
533
[email protected]c2e76012010-12-23 21:10:29534void DownloadManager::CreateDownloadItem(DownloadCreateInfo* info) {
535 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
536
537 DownloadItem* download = new DownloadItem(this, *info,
538 profile_->IsOffTheRecord());
[email protected]4cd82f72011-05-23 19:15:01539 int32 download_id = info->download_id;
540 DCHECK(!ContainsKey(in_progress_, download_id));
541 DCHECK(!ContainsKey(active_downloads_, download_id));
[email protected]c2e76012010-12-23 21:10:29542 downloads_.insert(download);
[email protected]4cd82f72011-05-23 19:15:01543 active_downloads_[download_id] = download;
[email protected]c2e76012010-12-23 21:10:29544}
545
[email protected]4cd82f72011-05-23 19:15:01546void DownloadManager::ContinueDownloadWithPath(DownloadItem* download,
547 const FilePath& chosen_file) {
[email protected]ca4b5fa32010-10-09 12:42:18548 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]4cd82f72011-05-23 19:15:01549 DCHECK(download);
[email protected]aa033af2010-07-27 18:16:39550
[email protected]4cd82f72011-05-23 19:15:01551 int32 download_id = download->id();
initial.commit09911bf2008-07-26 23:55:29552
[email protected]70850c72011-01-11 17:31:27553 // NOTE(ahendrickson) Eventually |active_downloads_| will replace
554 // |in_progress_|, but we don't want to change the semantics yet.
[email protected]4cd82f72011-05-23 19:15:01555 DCHECK(!ContainsKey(in_progress_, download_id));
[email protected]70850c72011-01-11 17:31:27556 DCHECK(ContainsKey(downloads_, download));
[email protected]4cd82f72011-05-23 19:15:01557 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]70850c72011-01-11 17:31:27558
[email protected]4cd82f72011-05-23 19:15:01559 // Make sure the initial file name is set only once.
560 DCHECK(download->full_path().empty());
561 download->OnPathDetermined(chosen_file);
[email protected]4cd82f72011-05-23 19:15:01562
563 VLOG(20) << __FUNCTION__ << "()"
564 << " download = " << download->DebugString(true);
565
566 in_progress_[download_id] = download;
[email protected]adb2f3d12011-01-23 16:24:54567 UpdateAppIcon(); // Reflect entry into in_progress_.
initial.commit09911bf2008-07-26 23:55:29568
[email protected]adb2f3d12011-01-23 16:24:54569 // Rename to intermediate name.
[email protected]f5920322011-03-24 20:34:16570 FilePath download_path;
[email protected]4cd82f72011-05-23 19:15:01571 if (download->IsDangerous()) {
[email protected]adb2f3d12011-01-23 16:24:54572 // The download is not safe. We can now rename the file to its
[email protected]f5920322011-03-24 20:34:16573 // tentative name using RenameInProgressDownloadFile.
574 // NOTE: The |Rename| below will be a no-op for dangerous files, as we're
575 // renaming it to the same name.
[email protected]4cd82f72011-05-23 19:15:01576 download_path = download->full_path();
[email protected]594cd7d2010-07-21 03:23:56577 } else {
[email protected]adb2f3d12011-01-23 16:24:54578 // The download is a safe download. We need to
579 // rename it to its intermediate '.crdownload' path. The final
580 // name after user confirmation will be set from
[email protected]48837962011-04-19 17:03:29581 // DownloadItem::OnDownloadCompleting.
[email protected]4cd82f72011-05-23 19:15:01582 download_path =
583 download_util::GetCrDownloadPath(download->full_path());
[email protected]594cd7d2010-07-21 03:23:56584 }
585
[email protected]f5920322011-03-24 20:34:16586 BrowserThread::PostTask(
587 BrowserThread::FILE, FROM_HERE,
588 NewRunnableMethod(
589 file_manager_, &DownloadFileManager::RenameInProgressDownloadFile,
590 download->id(), download_path));
591
592 download->Rename(download_path);
593
[email protected]4cd82f72011-05-23 19:15:01594 download_history_->AddEntry(download,
[email protected]82f37b02010-07-29 22:04:57595 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
initial.commit09911bf2008-07-26 23:55:29596}
597
initial.commit09911bf2008-07-26 23:55:29598void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
[email protected]70850c72011-01-11 17:31:27599 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
600 DownloadMap::iterator it = active_downloads_.find(download_id);
601 if (it != active_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29602 DownloadItem* download = it->second;
[email protected]bf68a00b2011-04-07 17:28:26603 if (download->IsInProgress()) {
[email protected]70850c72011-01-11 17:31:27604 download->Update(size);
[email protected]adb2f3d12011-01-23 16:24:54605 UpdateAppIcon(); // Reflect size updates.
[email protected]70850c72011-01-11 17:31:27606 download_history_->UpdateEntry(download);
607 }
initial.commit09911bf2008-07-26 23:55:29608 }
609}
610
[email protected]bf68a00b2011-04-07 17:28:26611void DownloadManager::OnResponseCompleted(int32 download_id,
612 int64 size,
613 int os_error,
614 const std::string& hash) {
615 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]7c8e55ba2011-07-01 18:59:23616 // ERR_CONNECTION_CLOSED is allowed since a number of servers in the wild
617 // advertise a larger Content-Length than the amount of bytes in the message
618 // body, and then close the connection. Other browsers - IE8, Firefox 4.0.1,
619 // and Safari 5.0.4 - treat the download as complete in this case, so we
620 // follow their lead.
[email protected]1822a422011-07-15 15:49:19621 if (os_error == 0 || os_error == net::ERR_CONNECTION_CLOSED) {
[email protected]bf68a00b2011-04-07 17:28:26622 OnAllDataSaved(download_id, size, hash);
623 } else {
624 OnDownloadError(download_id, size, os_error);
625 }
626}
627
[email protected]26711732011-03-09 00:21:22628void DownloadManager::OnAllDataSaved(int32 download_id,
629 int64 size,
630 const std::string& hash) {
[email protected]da6e3922010-11-24 21:45:50631 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
632 << " size = " << size;
[email protected]9d7ef802011-02-25 19:03:35633 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:32634
[email protected]c4f02c42011-01-24 21:55:06635 // If it's not in active_downloads_, that means it was cancelled; just
636 // ignore the notification.
637 if (active_downloads_.count(download_id) == 0)
638 return;
639
[email protected]adb2f3d12011-01-23 16:24:54640 DownloadItem* download = active_downloads_[download_id];
[email protected]a850ba42010-09-10 22:00:30641 download->OnAllDataSaved(size);
[email protected]9ccbb372008-10-10 18:50:32642
[email protected]26711732011-03-09 00:21:22643 // When hash is not available, it means either it is not calculated
644 // or there is error while it is calculated. We will skip the download hash
645 // check in that case.
646 if (!hash.empty()) {
[email protected]4b58e7d2011-07-11 10:22:56647#if defined(ENABLE_SAFE_BROWSING)
[email protected]26711732011-03-09 00:21:22648 scoped_refptr<DownloadSBClient> sb_client =
649 new DownloadSBClient(download_id,
[email protected]8799e542011-04-20 03:47:34650 download->url_chain(),
[email protected]8c40da62011-07-13 22:58:46651 download->referrer_url(),
652 profile_->GetPrefs()->GetBoolean(
653 prefs::kSafeBrowsingEnabled));
[email protected]26711732011-03-09 00:21:22654 sb_client->CheckDownloadHash(
655 hash, NewCallback(this, &DownloadManager::CheckDownloadHashDone));
[email protected]4b58e7d2011-07-11 10:22:56656#else
657 CheckDownloadHashDone(download_id, false);
658#endif
[email protected]26711732011-03-09 00:21:22659 }
[email protected]adb2f3d12011-01-23 16:24:54660 MaybeCompleteDownload(download);
661}
[email protected]9ccbb372008-10-10 18:50:32662
[email protected]26711732011-03-09 00:21:22663// TODO(lzheng): This function currently works as a callback place holder.
664// Once we decide the hash check is reliable, we could move the
665// MaybeCompleteDownload in OnAllDataSaved to this function.
666void DownloadManager::CheckDownloadHashDone(int32 download_id,
667 bool is_dangerous_hash) {
668 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
669 DVLOG(1) << "CheckDownloadHashDone, download_id: " << download_id
670 << " is dangerous_hash: " << is_dangerous_hash;
671
672 // If it's not in active_downloads_, that means it was cancelled or
673 // the download already finished.
674 if (active_downloads_.count(download_id) == 0)
675 return;
676
677 DVLOG(1) << "CheckDownloadHashDone, url: "
[email protected]4cd82f72011-05-23 19:15:01678 << active_downloads_[download_id]->GetURL().spec();
[email protected]26711732011-03-09 00:21:22679}
680
[email protected]7d413112011-06-16 18:50:17681void DownloadManager::AssertQueueStateConsistent(DownloadItem* download) {
[email protected]5cd11b6e2011-06-10 20:30:59682 // TODO(rdsmith): Change to DCHECK after http://crbug.com/85408 resolved.
[email protected]7d413112011-06-16 18:50:17683 if (download->state() == DownloadItem::REMOVING) {
684 CHECK(!ContainsKey(downloads_, download));
685 CHECK(!ContainsKey(active_downloads_, download->id()));
686 CHECK(!ContainsKey(in_progress_, download->id()));
687 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
688 return;
689 }
690
691 // Should be in downloads_ if we're not REMOVING.
692 CHECK(ContainsKey(downloads_, download));
693
694 // Check history_downloads_ consistency.
695 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
696 CHECK(ContainsKey(history_downloads_, download->db_handle()));
697 } else {
698 // TODO(rdsmith): Somewhat painful; make sure to disable in
699 // release builds after resolution of http://crbug.com/85408.
700 for (DownloadMap::iterator it = history_downloads_.begin();
701 it != history_downloads_.end(); ++it) {
702 CHECK(it->second != download);
703 }
704 }
705
706 CHECK(ContainsKey(active_downloads_, download->id()) ==
707 (download->state() == DownloadItem::IN_PROGRESS));
[email protected]54610672011-07-18 18:24:43708 CHECK(ContainsKey(in_progress_, download->id()) ==
709 (download->state() == DownloadItem::IN_PROGRESS));
[email protected]5cd11b6e2011-06-10 20:30:59710}
711
[email protected]adb2f3d12011-01-23 16:24:54712bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
713 // If we don't have all the data, the download is not ready for
714 // completion.
715 if (!download->all_data_saved())
716 return false;
[email protected]6a7fb042010-02-01 16:30:47717
[email protected]9d7ef802011-02-25 19:03:35718 // If the download is dangerous, but not yet validated, it's not ready for
719 // completion.
720 if (download->safety_state() == DownloadItem::DANGEROUS)
721 return false;
722
[email protected]adb2f3d12011-01-23 16:24:54723 // If the download isn't active (e.g. has been cancelled) it's not
724 // ready for completion.
725 if (active_downloads_.count(download->id()) == 0)
726 return false;
727
728 // If the download hasn't been inserted into the history system
729 // (which occurs strictly after file name determination, intermediate
730 // file rename, and UI display) then it's not ready for completion.
[email protected]7054b592011-06-22 14:46:42731 if (download->db_handle() == DownloadHistory::kUninitializedHandle)
732 return false;
733
734 return true;
[email protected]adb2f3d12011-01-23 16:24:54735}
736
737void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
738 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
739 VLOG(20) << __FUNCTION__ << "()" << " download = "
740 << download->DebugString(false);
741
742 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32743 return;
[email protected]9ccbb372008-10-10 18:50:32744
[email protected]adb2f3d12011-01-23 16:24:54745 // TODO(rdsmith): DCHECK that we only pass through this point
746 // once per download. The natural way to do this is by a state
747 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56748
[email protected]adb2f3d12011-01-23 16:24:54749 // Confirm we're in the proper set of states to be here;
[email protected]9d7ef802011-02-25 19:03:35750 // in in_progress_, have all data, have a history handle, (validated or safe).
751 DCHECK_NE(DownloadItem::DANGEROUS, download->safety_state());
[email protected]adb2f3d12011-01-23 16:24:54752 DCHECK_EQ(1u, in_progress_.count(download->id()));
753 DCHECK(download->all_data_saved());
754 DCHECK(download->db_handle() != DownloadHistory::kUninitializedHandle);
755 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
756
757 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
758 << download->DebugString(false);
759
760 // Remove the id from in_progress
761 in_progress_.erase(download->id());
762 UpdateAppIcon(); // Reflect removal from in_progress_.
763
[email protected]adb2f3d12011-01-23 16:24:54764 download_history_->UpdateEntry(download);
765
[email protected]f5920322011-03-24 20:34:16766 // Finish the download.
[email protected]48837962011-04-19 17:03:29767 download->OnDownloadCompleting(file_manager_);
[email protected]9ccbb372008-10-10 18:50:32768}
769
[email protected]cc3c7c092011-05-09 18:40:21770void DownloadManager::DownloadCompleted(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27771 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21772 DownloadItem* download = GetDownloadItem(download_id);
773 DCHECK(download);
774 download_history_->UpdateEntry(download);
[email protected]70850c72011-01-11 17:31:27775 active_downloads_.erase(download_id);
776}
777
[email protected]f5920322011-03-24 20:34:16778void DownloadManager::OnDownloadRenamedToFinalName(int download_id,
779 const FilePath& full_path,
780 int uniquifier) {
[email protected]da6e3922010-11-24 21:45:50781 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
[email protected]f5920322011-03-24 20:34:16782 << " full_path = \"" << full_path.value() << "\""
783 << " uniquifier = " << uniquifier;
[email protected]ca4b5fa32010-10-09 12:42:18784 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]f5920322011-03-24 20:34:16785
[email protected]2e030682010-07-23 19:45:36786 DownloadItem* item = GetDownloadItem(download_id);
787 if (!item)
788 return;
[email protected]6cade212008-12-03 00:32:22789
[email protected]8fa1eeb52011-04-13 14:18:02790 if (item->safety_state() == DownloadItem::SAFE) {
791 DCHECK_EQ(0, uniquifier) << "We should not uniquify SAFE downloads twice";
792 }
793
[email protected]ca4b5fa32010-10-09 12:42:18794 BrowserThread::PostTask(
[email protected]f5920322011-03-24 20:34:16795 BrowserThread::FILE, FROM_HERE,
796 NewRunnableMethod(
797 file_manager_, &DownloadFileManager::CompleteDownload, download_id));
[email protected]9ccbb372008-10-10 18:50:32798
[email protected]f5920322011-03-24 20:34:16799 if (uniquifier)
800 item->set_path_uniquifier(uniquifier);
[email protected]9ccbb372008-10-10 18:50:32801
[email protected]f5920322011-03-24 20:34:16802 item->OnDownloadRenamedToFinalName(full_path);
803 download_history_->UpdateDownloadPath(item, full_path);
initial.commit09911bf2008-07-26 23:55:29804}
805
[email protected]54610672011-07-18 18:24:43806void DownloadManager::DownloadCancelled(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27807 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]54610672011-07-18 18:24:43808 DownloadMap::iterator it = in_progress_.find(download_id);
809 if (it == in_progress_.end())
initial.commit09911bf2008-07-26 23:55:29810 return;
811 DownloadItem* download = it->second;
812
[email protected]da6e3922010-11-24 21:45:50813 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
814 << " download = " << download->DebugString(true);
815
[email protected]54610672011-07-18 18:24:43816 // Clean up will happen when the history system create callback runs if we
817 // don't have a valid db_handle yet.
818 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
819 in_progress_.erase(it);
820 active_downloads_.erase(download_id);
821 UpdateAppIcon(); // Reflect removal from in_progress_.
822 download_history_->UpdateEntry(download);
823 }
initial.commit09911bf2008-07-26 23:55:29824
[email protected]54610672011-07-18 18:24:43825 DownloadCancelledInternal(download_id, download->request_handle());
826}
[email protected]d7d1c5c2009-08-05 23:52:50827
[email protected]54610672011-07-18 18:24:43828void DownloadManager::DownloadCancelledInternal(
829 int download_id, const DownloadRequestHandle& request_handle) {
830 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
831 request_handle.CancelRequest();
[email protected]d7d1c5c2009-08-05 23:52:50832
[email protected]ca4b5fa32010-10-09 12:42:18833 BrowserThread::PostTask(
834 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37835 NewRunnableMethod(
836 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29837}
838
[email protected]bf68a00b2011-04-07 17:28:26839void DownloadManager::OnDownloadError(int32 download_id,
840 int64 size,
841 int os_error) {
842 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
843 DownloadMap::iterator it = active_downloads_.find(download_id);
844 // A cancel at the right time could remove the download from the
845 // |active_downloads_| map before we get here.
846 if (it == active_downloads_.end())
847 return;
848
849 DownloadItem* download = it->second;
850
[email protected]4cd82f72011-05-23 19:15:01851 VLOG(20) << __FUNCTION__ << "()" << " Error " << os_error
852 << " at offset " << download->received_bytes()
853 << " for download = " << download->DebugString(true);
854
[email protected]54610672011-07-18 18:24:43855 download->Interrupted(size, os_error);
856
857 // TODO(ahendrickson) - Remove this when we add resuming of interrupted
858 // downloads, as we will keep the download item around in that case.
859 //
860 // Clean up will happen when the history system create callback runs if we
861 // don't have a valid db_handle yet.
862 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
863 in_progress_.erase(download_id);
864 active_downloads_.erase(download_id);
865 UpdateAppIcon(); // Reflect removal from in_progress_.
866 download_history_->UpdateEntry(download);
867 }
868
869 BrowserThread::PostTask(
870 BrowserThread::FILE, FROM_HERE,
871 NewRunnableMethod(
872 file_manager_, &DownloadFileManager::CancelDownload, download_id));
[email protected]bf68a00b2011-04-07 17:28:26873}
874
[email protected]6a7fb042010-02-01 16:30:47875void DownloadManager::UpdateAppIcon() {
[email protected]073ed7b2010-09-27 09:20:02876 if (status_updater_)
877 status_updater_->Update();
[email protected]6a7fb042010-02-01 16:30:47878}
879
[email protected]54610672011-07-18 18:24:43880void DownloadManager::RemoveDownload(int64 download_handle) {
881 DownloadMap::iterator it = history_downloads_.find(download_handle);
882 if (it == history_downloads_.end())
883 return;
884
885 // Make history update.
886 DownloadItem* download = it->second;
887 download_history_->RemoveEntry(download);
initial.commit09911bf2008-07-26 23:55:29888
889 // Remove from our tables and delete.
[email protected]54610672011-07-18 18:24:43890 history_downloads_.erase(it);
[email protected]f04182f32010-12-10 19:12:07891 int downloads_count = downloads_.erase(download);
892 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29893
894 // Tell observers to refresh their views.
[email protected]b0ab1d42010-02-24 19:29:28895 NotifyModelChanged();
[email protected]6f712872008-11-07 00:35:36896
897 delete download;
initial.commit09911bf2008-07-26 23:55:29898}
899
[email protected]e93d2822009-01-30 05:59:59900int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
901 const base::Time remove_end) {
[email protected]82f37b02010-07-29 22:04:57902 download_history_->RemoveEntriesBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29903
[email protected]a312a442010-12-15 23:40:33904 // All downloads visible to the user will be in the history,
905 // so scan that map.
[email protected]f04182f32010-12-10 19:12:07906 DownloadMap::iterator it = history_downloads_.begin();
[email protected]78b8fcc92009-03-31 17:36:28907 std::vector<DownloadItem*> pending_deletes;
[email protected]f04182f32010-12-10 19:12:07908 while (it != history_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29909 DownloadItem* download = it->second;
initial.commit09911bf2008-07-26 23:55:29910 if (download->start_time() >= remove_begin &&
911 (remove_end.is_null() || download->start_time() < remove_end) &&
[email protected]bf68a00b2011-04-07 17:28:26912 (download->IsComplete() ||
913 download->IsCancelled() ||
914 download->IsInterrupted())) {
[email protected]7d413112011-06-16 18:50:17915 AssertQueueStateConsistent(download);
916
initial.commit09911bf2008-07-26 23:55:29917 // Remove from the map and move to the next in the list.
[email protected]f04182f32010-12-10 19:12:07918 history_downloads_.erase(it++);
[email protected]a6604d92008-10-30 00:58:58919
920 // Also remove it from any completed dangerous downloads.
[email protected]78b8fcc92009-03-31 17:36:28921 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29922
initial.commit09911bf2008-07-26 23:55:29923 continue;
924 }
925
926 ++it;
927 }
928
[email protected]a312a442010-12-15 23:40:33929 // If we aren't deleting anything, we're done.
[email protected]57fd1252010-12-23 17:24:09930 if (pending_deletes.empty())
931 return 0;
initial.commit09911bf2008-07-26 23:55:29932
[email protected]a312a442010-12-15 23:40:33933 // Remove the chosen downloads from the main owning container.
934 for (std::vector<DownloadItem*>::iterator it = pending_deletes.begin();
935 it != pending_deletes.end(); it++) {
936 downloads_.erase(*it);
937 }
938
939 // Tell observers to refresh their views.
940 NotifyModelChanged();
941
942 // Delete the download items themselves.
[email protected]57fd1252010-12-23 17:24:09943 int num_deleted = static_cast<int>(pending_deletes.size());
944
[email protected]78b8fcc92009-03-31 17:36:28945 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
946 pending_deletes.clear();
947
initial.commit09911bf2008-07-26 23:55:29948 return num_deleted;
949}
950
[email protected]e93d2822009-01-30 05:59:59951int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
952 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29953}
954
[email protected]d41355e6f2009-04-07 21:21:12955int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:46956 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
957 // This is an incognito downloader. Clear All should clear main download
958 // manager as well.
959 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
960 }
[email protected]d41355e6f2009-04-07 21:21:12961 // The null times make the date range unbounded.
962 return RemoveDownloadsBetween(base::Time(), base::Time());
963}
964
[email protected]f9a45b02011-06-30 23:49:19965void DownloadManager::SavePageAsDownloadStarted(DownloadItem* download) {
[email protected]57fd1252010-12-23 17:24:09966#if !defined(NDEBUG)
[email protected]f9a45b02011-06-30 23:49:19967 save_page_as_downloads_.insert(download);
[email protected]57fd1252010-12-23 17:24:09968#endif
[email protected]f9a45b02011-06-30 23:49:19969 downloads_.insert(download);
970 // Add to history and notify observers.
971 AddDownloadItemToHistory(download, DownloadHistory::kUninitializedHandle);
972 NotifyModelChanged();
[email protected]ec4826a2010-09-21 09:15:59973}
974
initial.commit09911bf2008-07-26 23:55:29975// Initiate a download of a specific URL. We send the request to the
976// ResourceDispatcherHost, and let it send us responses like a regular
977// download.
978void DownloadManager::DownloadUrl(const GURL& url,
979 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50980 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34981 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26982 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
983 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58984}
985
986void DownloadManager::DownloadUrlToFile(const GURL& url,
987 const GURL& referrer,
988 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32989 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58990 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34991 DCHECK(tab_contents);
[email protected]ed24fad2011-05-10 22:44:01992 // We send a pointer to content::ResourceContext, instead of the usual
993 // reference, so that a copy of the object isn't made.
[email protected]ca4b5fa32010-10-09 12:42:18994 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]ae8945192010-07-20 16:56:26995 NewRunnableFunction(&download_util::DownloadUrl,
996 url,
997 referrer,
998 referrer_charset,
999 save_info,
1000 g_browser_process->resource_dispatcher_host(),
1001 tab_contents->GetRenderProcessHost()->id(),
1002 tab_contents->render_view_host()->routing_id(),
[email protected]cafe4ad2011-07-28 18:34:561003 &tab_contents->browser_context()->
1004 GetResourceContext()));
initial.commit09911bf2008-07-26 23:55:291005}
1006
initial.commit09911bf2008-07-26 23:55:291007void DownloadManager::AddObserver(Observer* observer) {
1008 observers_.AddObserver(observer);
1009 observer->ModelChanged();
1010}
1011
1012void DownloadManager::RemoveObserver(Observer* observer) {
1013 observers_.RemoveObserver(observer);
1014}
1015
[email protected]eccb9d12009-10-28 05:40:091016bool DownloadManager::ShouldOpenFileBasedOnExtension(
1017 const FilePath& path) const {
[email protected]eccb9d12009-10-28 05:40:091018 FilePath::StringType extension = path.Extension();
1019 if (extension.empty())
1020 return false;
[email protected]92e11c82010-01-13 06:39:561021 if (Extension::IsExtension(path))
1022 return false;
[email protected]eccb9d12009-10-28 05:40:091023 DCHECK(extension[0] == FilePath::kExtensionSeparator);
1024 extension.erase(0, 1);
[email protected]e5dc4222010-08-30 22:16:321025 return download_prefs_->IsAutoOpenEnabledForExtension(extension);
initial.commit09911bf2008-07-26 23:55:291026}
1027
[email protected]073ed7b2010-09-27 09:20:021028bool DownloadManager::IsDownloadProgressKnown() {
1029 for (DownloadMap::iterator i = in_progress_.begin();
1030 i != in_progress_.end(); ++i) {
1031 if (i->second->total_bytes() <= 0)
1032 return false;
1033 }
1034
1035 return true;
1036}
1037
1038int64 DownloadManager::GetInProgressDownloadCount() {
1039 return in_progress_.size();
1040}
1041
1042int64 DownloadManager::GetReceivedDownloadBytes() {
1043 DCHECK(IsDownloadProgressKnown());
1044 int64 received_bytes = 0;
1045 for (DownloadMap::iterator i = in_progress_.begin();
1046 i != in_progress_.end(); ++i) {
1047 received_bytes += i->second->received_bytes();
1048 }
1049 return received_bytes;
1050}
1051
1052int64 DownloadManager::GetTotalDownloadBytes() {
1053 DCHECK(IsDownloadProgressKnown());
1054 int64 total_bytes = 0;
1055 for (DownloadMap::iterator i = in_progress_.begin();
1056 i != in_progress_.end(); ++i) {
1057 total_bytes += i->second->total_bytes();
1058 }
1059 return total_bytes;
1060}
1061
[email protected]99cb7f82011-07-28 17:27:261062void DownloadManager::FileSelected(const FilePath& path, void* params) {
[email protected]4cd82f72011-05-23 19:15:011063 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1064
1065 int32* id_ptr = reinterpret_cast<int32*>(params);
1066 DCHECK(id_ptr != NULL);
1067 int32 download_id = *id_ptr;
1068 delete id_ptr;
1069
1070 DownloadItem* download = GetActiveDownloadItem(download_id);
1071 if (!download)
1072 return;
1073 VLOG(20) << __FUNCTION__ << "()" << " path = \"" << path.value() << "\""
1074 << " download = " << download->DebugString(true);
1075
[email protected]da1a27b2011-07-29 23:16:331076 if (download->prompt_user_for_save_location())
[email protected]7ae7c2cb2009-01-06 23:31:411077 last_download_path_ = path.DirName();
[email protected]287b86b2011-02-26 00:11:351078
[email protected]4cd82f72011-05-23 19:15:011079 // Make sure the initial file name is set only once.
1080 ContinueDownloadWithPath(download, path);
initial.commit09911bf2008-07-26 23:55:291081}
1082
1083void DownloadManager::FileSelectionCanceled(void* params) {
1084 // The user didn't pick a place to save the file, so need to cancel the
1085 // download that's already in progress to the temporary location.
[email protected]4cd82f72011-05-23 19:15:011086 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1087 int32* id_ptr = reinterpret_cast<int32*>(params);
1088 DCHECK(id_ptr != NULL);
1089 int32 download_id = *id_ptr;
1090 delete id_ptr;
1091
1092 DownloadItem* download = GetActiveDownloadItem(download_id);
1093 if (!download)
1094 return;
1095
1096 VLOG(20) << __FUNCTION__ << "()"
1097 << " download = " << download->DebugString(true);
1098
[email protected]54610672011-07-18 18:24:431099 DownloadCancelledInternal(download_id, download->request_handle());
[email protected]4cd82f72011-05-23 19:15:011100}
1101
1102// TODO(phajdan.jr): This is apparently not being exercised in tests.
[email protected]da1a27b2011-07-29 23:16:331103bool DownloadManager::IsDangerousFile(const DownloadItem& download,
1104 const DownloadStateInfo& state,
1105 bool visited_referrer_before) {
[email protected]4cd82f72011-05-23 19:15:011106 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1107
1108 bool auto_open = ShouldOpenFileBasedOnExtension(state.suggested_path);
1109 download_util::DownloadDangerLevel danger_level =
1110 download_util::GetFileDangerLevel(state.suggested_path.BaseName());
1111
1112 if (danger_level == download_util::Dangerous)
1113 return !(auto_open && state.has_user_gesture);
1114
1115 if (danger_level == download_util::AllowOnUserGesture &&
[email protected]88008002011-05-24 23:14:151116 (!state.has_user_gesture || !visited_referrer_before))
[email protected]4cd82f72011-05-23 19:15:011117 return true;
1118
1119 if (state.is_extension_install) {
1120 // Extensions that are not from the gallery are considered dangerous.
1121 ExtensionService* service = profile()->GetExtensionService();
1122 if (!service || !service->IsDownloadFromGallery(download.GetURL(),
1123 download.referrer_url()))
1124 return true;
1125 }
1126 return false;
initial.commit09911bf2008-07-26 23:55:291127}
1128
1129// Operations posted to us from the history service ----------------------------
1130
1131// The history service has retrieved all download entries. 'entries' contains
[email protected]4cd82f72011-05-23 19:15:011132// 'DownloadHistoryInfo's in sorted order (by ascending start_time).
initial.commit09911bf2008-07-26 23:55:291133void DownloadManager::OnQueryDownloadEntriesComplete(
[email protected]4cd82f72011-05-23 19:15:011134 std::vector<DownloadHistoryInfo>* entries) {
initial.commit09911bf2008-07-26 23:55:291135 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:391136 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]f04182f32010-12-10 19:12:071137 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
1138 downloads_.insert(download);
1139 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:501140 VLOG(20) << __FUNCTION__ << "()" << i << ">"
1141 << " download = " << download->DebugString(true);
initial.commit09911bf2008-07-26 23:55:291142 }
[email protected]b0ab1d42010-02-24 19:29:281143 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:481144 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:291145}
1146
[email protected]f9a45b02011-06-30 23:49:191147void DownloadManager::AddDownloadItemToHistory(DownloadItem* download,
1148 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:271149 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d2a8fb72010-01-21 05:31:421150
[email protected]5bcd73eb2011-03-23 21:14:021151 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
1152 // call this function with an invalid |db_handle|. For instance, this can
1153 // happen when the history database is offline. We cannot have multiple
1154 // DownloadItems with the same invalid db_handle, so we need to assign a
1155 // unique |db_handle| here.
1156 if (db_handle == DownloadHistory::kUninitializedHandle)
1157 db_handle = download_history_->GetNextFakeDbHandle();
1158
[email protected]1e9fe7ff2011-06-24 17:37:331159 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/84508
1160 // is fixed.
[email protected]54610672011-07-18 18:24:431161 CHECK_NE(DownloadHistory::kUninitializedHandle, db_handle);
[email protected]1e9fe7ff2011-06-24 17:37:331162
[email protected]5bcd73eb2011-03-23 21:14:021163 DCHECK(download->db_handle() == DownloadHistory::kUninitializedHandle);
1164 download->set_db_handle(db_handle);
1165
[email protected]5bcd73eb2011-03-23 21:14:021166 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
1167 history_downloads_[download->db_handle()] = download;
[email protected]f9a45b02011-06-30 23:49:191168}
1169
1170// Once the new DownloadItem's creation info has been committed to the history
1171// service, we associate the DownloadItem with the db handle, update our
1172// 'history_downloads_' map and inform observers.
1173void DownloadManager::OnCreateDownloadEntryComplete(int32 download_id,
1174 int64 db_handle) {
1175 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]19420cc2011-07-18 17:43:451176 DownloadItem* download = GetActiveDownloadItem(download_id);
[email protected]54610672011-07-18 18:24:431177 if (!download)
[email protected]19420cc2011-07-18 17:43:451178 return;
[email protected]54610672011-07-18 18:24:431179
1180 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
1181 << " download_id = " << download_id
1182 << " download = " << download->DebugString(true);
[email protected]f9a45b02011-06-30 23:49:191183
1184 AddDownloadItemToHistory(download, db_handle);
initial.commit09911bf2008-07-26 23:55:291185
[email protected]70850c72011-01-11 17:31:271186 // Show in the appropriate browser UI.
[email protected]9d7ef802011-02-25 19:03:351187 // This includes buttons to save or cancel, for a dangerous download.
[email protected]4cd82f72011-05-23 19:15:011188 ShowDownloadInBrowser(download);
initial.commit09911bf2008-07-26 23:55:291189
1190 // Inform interested objects about the new download.
[email protected]b0ab1d42010-02-24 19:29:281191 NotifyModelChanged();
initial.commit09911bf2008-07-26 23:55:291192
[email protected]54610672011-07-18 18:24:431193 // If the download is still in progress, try to complete it.
1194 //
1195 // Otherwise, download has been cancelled or interrupted before we've
1196 // received the DB handle. We post one final message to the history
1197 // service so that it can be properly in sync with the DownloadItem's
1198 // completion status, and also inform any observers so that they get
1199 // more than just the start notification.
1200 if (download->IsInProgress()) {
1201 MaybeCompleteDownload(download);
1202 } else {
1203 DCHECK(download->IsCancelled())
1204 << " download = " << download->DebugString(true);
1205 in_progress_.erase(download_id);
1206 active_downloads_.erase(download_id);
1207 download_history_->UpdateEntry(download);
1208 download->UpdateObservers();
1209 }
initial.commit09911bf2008-07-26 23:55:291210}
1211
[email protected]4cd82f72011-05-23 19:15:011212void DownloadManager::ShowDownloadInBrowser(DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:341213 // The 'contents' may no longer exist if the user closed the tab before we
[email protected]99cb7f82011-07-28 17:27:261214 // get this start completion event.
[email protected]db6831a2011-06-09 21:08:281215 DownloadRequestHandle request_handle = download->request_handle();
[email protected]686493142011-07-15 21:47:221216 TabContents* content = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:261217
1218 // If the contents no longer exists, we ask the embedder to suggest another
1219 // tab.
[email protected]da1a27b2011-07-29 23:16:331220 if (!content)
1221 content = delegate_->GetAlternativeTabContentsToNotifyForDownload(this);
[email protected]5e595482009-05-06 20:16:531222
[email protected]99cb7f82011-07-28 17:27:261223 if (content)
1224 content->OnStartDownload(download);
[email protected]5e595482009-05-06 20:16:531225}
1226
[email protected]6cade212008-12-03 00:32:221227// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:121228void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:411229 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:381230}
[email protected]b0ab1d42010-02-24 19:29:281231
1232void DownloadManager::NotifyModelChanged() {
1233 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1234}
1235
[email protected]4cd82f72011-05-23 19:15:011236DownloadItem* DownloadManager::GetDownloadItem(int download_id) {
1237 // The |history_downloads_| map is indexed by the download's db_handle,
1238 // not its id, so we have to iterate.
[email protected]f04182f32010-12-10 19:12:071239 for (DownloadMap::iterator it = history_downloads_.begin();
1240 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:361241 DownloadItem* item = it->second;
[email protected]4cd82f72011-05-23 19:15:011242 if (item->id() == download_id)
[email protected]2e030682010-07-23 19:45:361243 return item;
1244 }
1245 return NULL;
1246}
1247
[email protected]4cd82f72011-05-23 19:15:011248DownloadItem* DownloadManager::GetActiveDownloadItem(int download_id) {
1249 DCHECK(ContainsKey(active_downloads_, download_id));
1250 DownloadItem* download = active_downloads_[download_id];
1251 DCHECK(download != NULL);
1252 return download;
1253}
1254
[email protected]57fd1252010-12-23 17:24:091255// Confirm that everything in all maps is also in |downloads_|, and that
1256// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:071257void DownloadManager::AssertContainersConsistent() const {
1258#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:091259 // Turn everything into sets.
[email protected]adb2f3d12011-01-23 16:24:541260 DownloadSet active_set, history_set;
[email protected]70850c72011-01-11 17:31:271261 const DownloadMap* input_maps[] = {&active_downloads_, &history_downloads_};
[email protected]adb2f3d12011-01-23 16:24:541262 DownloadSet* local_sets[] = {&active_set, &history_set};
[email protected]57fd1252010-12-23 17:24:091263 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(local_sets));
1264 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
1265 for (DownloadMap::const_iterator it = input_maps[i]->begin();
1266 it != input_maps[i]->end(); it++) {
1267 local_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:071268 }
1269 }
[email protected]57fd1252010-12-23 17:24:091270
1271 // Check if each set is fully present in downloads, and create a union.
[email protected]adb2f3d12011-01-23 16:24:541272 const DownloadSet* all_sets[] = {&active_set, &history_set,
[email protected]57fd1252010-12-23 17:24:091273 &save_page_as_downloads_};
1274 DownloadSet downloads_union;
1275 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
1276 DownloadSet remainder;
1277 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
1278 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
1279 downloads_.begin(), downloads_.end(),
1280 insert_it);
1281 DCHECK(remainder.empty());
1282 std::insert_iterator<DownloadSet>
1283 insert_union(downloads_union, downloads_union.end());
1284 std::set_union(downloads_union.begin(), downloads_union.end(),
1285 all_sets[i]->begin(), all_sets[i]->end(),
1286 insert_union);
1287 }
1288
1289 // Is everything in downloads_ present in one of the other sets?
1290 DownloadSet remainder;
1291 std::insert_iterator<DownloadSet>
1292 insert_remainder(remainder, remainder.begin());
1293 std::set_difference(downloads_.begin(), downloads_.end(),
1294 downloads_union.begin(), downloads_union.end(),
1295 insert_remainder);
1296 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071297#endif
1298}
1299
[email protected]b0ab1d42010-02-24 19:29:281300// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1301
1302DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1303 DownloadManager* observing_download_manager)
1304 : observing_download_manager_(observing_download_manager),
1305 observed_download_manager_(NULL) {
1306 if (observing_download_manager->profile_->GetOriginalProfile() ==
1307 observing_download_manager->profile_) {
1308 return;
1309 }
1310
1311 observed_download_manager_ = observing_download_manager_->
1312 profile_->GetOriginalProfile()->GetDownloadManager();
1313 observed_download_manager_->AddObserver(this);
1314}
1315
1316DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1317 if (observed_download_manager_)
1318 observed_download_manager_->RemoveObserver(this);
1319}
1320
1321void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1322 observing_download_manager_->NotifyModelChanged();
1323}
1324
[email protected]b0ab1d42010-02-24 19:29:281325void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1326 observed_download_manager_ = NULL;
1327}