blob: c6e5ea6bcb91c7127d14e5a9f6bacc5ac3c3802b [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]71bf3f5e2011-08-15 21:05:225#include "content/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:296
[email protected]e7557f172011-08-19 23:42:017#include <iterator>
8
[email protected]2041cf342010-02-19 03:15:599#include "base/callback.h"
initial.commit09911bf2008-07-26 23:55:2910#include "base/file_util.h"
[email protected]503d03872011-05-06 08:36:2611#include "base/i18n/case_conversion.h"
initial.commit09911bf2008-07-26 23:55:2912#include "base/logging.h"
[email protected]7286e3fc2011-07-19 22:13:2413#include "base/stl_util.h"
initial.commit09911bf2008-07-26 23:55:2914#include "base/task.h"
[email protected]d2a8fb72010-01-21 05:31:4215#include "build/build_config.h"
[email protected]82f37b02010-07-29 22:04:5716#include "chrome/browser/download/download_history.h"
[email protected]e9ef0a62009-08-11 22:50:1317#include "chrome/browser/download/download_util.h"
[email protected]4cd82f72011-05-23 19:15:0118#include "chrome/browser/history/download_history_info.h"
[email protected]8ecad5e2010-12-02 21:18:3319#include "chrome/browser/profiles/profile.h"
[email protected]7324d1d2011-03-01 05:02:1620#include "content/browser/browser_thread.h"
[email protected]a0ce3282011-08-19 20:49:5221#include "content/browser/content_browser_client.h"
[email protected]71bf3f5e2011-08-15 21:05:2222#include "content/browser/download/download_create_info.h"
23#include "content/browser/download/download_file_manager.h"
24#include "content/browser/download/download_item.h"
[email protected]d6b7fd1e2011-08-16 22:42:0025#include "content/browser/download/download_manager_delegate.h"
[email protected]71bf3f5e2011-08-15 21:05:2226#include "content/browser/download/download_status_updater.h"
[email protected]7324d1d2011-03-01 05:02:1627#include "content/browser/renderer_host/render_process_host.h"
28#include "content/browser/renderer_host/render_view_host.h"
29#include "content/browser/renderer_host/resource_dispatcher_host.h"
30#include "content/browser/tab_contents/tab_contents.h"
[email protected]432115822011-07-10 15:52:2731#include "content/common/content_notification_types.h"
[email protected]6d0146c2011-08-04 19:13:0432#include "content/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:2933
[email protected]a0ce3282011-08-19 20:49:5234namespace {
35
36void BeginDownload(
37 const GURL& url,
38 const GURL& referrer,
39 const DownloadSaveInfo& save_info,
40 int render_process_host_id,
41 int render_view_id,
42 const content::ResourceContext* context) {
43 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
44
45 content::GetContentClient()->browser()->GetResourceDispatcherHost()->
46 BeginDownload(url,
47 referrer,
48 save_info,
49 true, // Show "Save as" UI.
50 render_process_host_id,
51 render_view_id,
52 *context);
53}
54
55} // namespace
56
[email protected]da1a27b2011-07-29 23:16:3357DownloadManager::DownloadManager(DownloadManagerDelegate* delegate,
58 DownloadStatusUpdater* status_updater)
initial.commit09911bf2008-07-26 23:55:2959 : shutdown_needed_(false),
60 profile_(NULL),
[email protected]073ed7b2010-09-27 09:20:0261 file_manager_(NULL),
[email protected]da1a27b2011-07-29 23:16:3362 status_updater_(status_updater->AsWeakPtr()),
[email protected]6d0146c2011-08-04 19:13:0463 next_save_page_id_(0),
[email protected]da1a27b2011-07-29 23:16:3364 delegate_(delegate) {
[email protected]073ed7b2010-09-27 09:20:0265 if (status_updater_)
66 status_updater_->AddDelegate(this);
initial.commit09911bf2008-07-26 23:55:2967}
68
69DownloadManager::~DownloadManager() {
[email protected]326a6a92010-09-10 20:21:1370 DCHECK(!shutdown_needed_);
[email protected]073ed7b2010-09-27 09:20:0271 if (status_updater_)
72 status_updater_->RemoveDelegate(this);
initial.commit09911bf2008-07-26 23:55:2973}
74
75void DownloadManager::Shutdown() {
[email protected]da6e3922010-11-24 21:45:5076 VLOG(20) << __FUNCTION__ << "()"
77 << " shutdown_needed_ = " << shutdown_needed_;
[email protected]326a6a92010-09-10 20:21:1378 if (!shutdown_needed_)
79 return;
80 shutdown_needed_ = false;
initial.commit09911bf2008-07-26 23:55:2981
[email protected]326a6a92010-09-10 20:21:1382 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
83
84 if (file_manager_) {
[email protected]ca4b5fa32010-10-09 12:42:1885 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
[email protected]326a6a92010-09-10 20:21:1386 NewRunnableMethod(file_manager_,
87 &DownloadFileManager::OnDownloadManagerShutdown,
[email protected]dc7cdcb92010-12-14 06:40:5488 make_scoped_refptr(this)));
[email protected]326a6a92010-09-10 20:21:1389 }
initial.commit09911bf2008-07-26 23:55:2990
[email protected]f04182f32010-12-10 19:12:0791 AssertContainersConsistent();
92
93 // Go through all downloads in downloads_. Dangerous ones we need to
94 // remove on disk, and in progress ones we need to cancel.
[email protected]57fd1252010-12-23 17:24:0995 for (DownloadSet::iterator it = downloads_.begin(); it != downloads_.end();) {
[email protected]f04182f32010-12-10 19:12:0796 DownloadItem* download = *it;
97
98 // Save iterator from potential erases in this set done by called code.
99 // Iterators after an erasure point are still valid for lists and
100 // associative containers such as sets.
101 it++;
102
103 if (download->safety_state() == DownloadItem::DANGEROUS &&
[email protected]48837962011-04-19 17:03:29104 download->IsPartialDownload()) {
[email protected]f04182f32010-12-10 19:12:07105 // The user hasn't accepted it, so we need to remove it
106 // from the disk. This may or may not result in it being
107 // removed from the DownloadManager queues and deleted
108 // (specifically, DownloadManager::RemoveDownload only
109 // removes and deletes it if it's known to the history service)
110 // so the only thing we know after calling this function is that
111 // the download was deleted if-and-only-if it was removed
112 // from all queues.
[email protected]303077002011-04-19 23:21:01113 download->Delete(DownloadItem::DELETE_DUE_TO_BROWSER_SHUTDOWN);
[email protected]bf68a00b2011-04-07 17:28:26114 } else if (download->IsPartialDownload()) {
[email protected]54610672011-07-18 18:24:43115 download->Cancel(false);
116 download_history_->UpdateEntry(download);
initial.commit09911bf2008-07-26 23:55:29117 }
118 }
119
[email protected]f04182f32010-12-10 19:12:07120 // At this point, all dangerous downloads have had their files removed
121 // and all in progress downloads have been cancelled. We can now delete
122 // anything left.
[email protected]9ccbb372008-10-10 18:50:32123
[email protected]5cd11b6e2011-06-10 20:30:59124 // Copy downloads_ to separate container so as not to set off checks
125 // in DownloadItem destruction.
126 DownloadSet downloads_to_delete;
127 downloads_to_delete.swap(downloads_);
128
initial.commit09911bf2008-07-26 23:55:29129 in_progress_.clear();
[email protected]70850c72011-01-11 17:31:27130 active_downloads_.clear();
[email protected]5cd11b6e2011-06-10 20:30:59131 history_downloads_.clear();
[email protected]5cd11b6e2011-06-10 20:30:59132 STLDeleteElements(&downloads_to_delete);
initial.commit09911bf2008-07-26 23:55:29133
[email protected]6d0146c2011-08-04 19:13:04134 DCHECK(save_page_downloads_.empty());
135
initial.commit09911bf2008-07-26 23:55:29136 file_manager_ = NULL;
137
[email protected]82f37b02010-07-29 22:04:57138 download_history_.reset();
[email protected]82f37b02010-07-29 22:04:57139
initial.commit09911bf2008-07-26 23:55:29140 shutdown_needed_ = false;
141}
142
[email protected]82f37b02010-07-29 22:04:57143void DownloadManager::GetTemporaryDownloads(
[email protected]6d0146c2011-08-04 19:13:04144 const FilePath& dir_path, DownloadVector* result) {
[email protected]82f37b02010-07-29 22:04:57145 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58146
[email protected]f04182f32010-12-10 19:12:07147 for (DownloadMap::iterator it = history_downloads_.begin();
148 it != history_downloads_.end(); ++it) {
[email protected]6aa4a1c02010-01-15 18:49:58149 if (it->second->is_temporary() &&
150 it->second->full_path().DirName() == dir_path)
[email protected]82f37b02010-07-29 22:04:57151 result->push_back(it->second);
[email protected]6aa4a1c02010-01-15 18:49:58152 }
[email protected]6aa4a1c02010-01-15 18:49:58153}
154
[email protected]82f37b02010-07-29 22:04:57155void DownloadManager::GetAllDownloads(
[email protected]6d0146c2011-08-04 19:13:04156 const FilePath& dir_path, DownloadVector* result) {
[email protected]82f37b02010-07-29 22:04:57157 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34158
[email protected]f04182f32010-12-10 19:12:07159 for (DownloadMap::iterator it = history_downloads_.begin();
160 it != history_downloads_.end(); ++it) {
[email protected]8ddbd66a2010-05-21 16:38:34161 if (!it->second->is_temporary() &&
162 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57163 result->push_back(it->second);
[email protected]8ddbd66a2010-05-21 16:38:34164 }
[email protected]8ddbd66a2010-05-21 16:38:34165}
166
[email protected]82f37b02010-07-29 22:04:57167void DownloadManager::GetCurrentDownloads(
[email protected]6d0146c2011-08-04 19:13:04168 const FilePath& dir_path, DownloadVector* result) {
[email protected]82f37b02010-07-29 22:04:57169 DCHECK(result);
[email protected]c4a530b2010-03-08 17:33:03170
[email protected]f04182f32010-12-10 19:12:07171 for (DownloadMap::iterator it = history_downloads_.begin();
172 it != history_downloads_.end(); ++it) {
[email protected]bf68a00b2011-04-07 17:28:26173 DownloadItem* item =it->second;
174 // Skip temporary items.
175 if (item->is_temporary())
176 continue;
177 // Skip items that have all their data, and are OK to save.
178 if (!item->IsPartialDownload() &&
179 (item->safety_state() != DownloadItem::DANGEROUS))
180 continue;
181 // Skip items that don't match |dir_path|.
182 // If |dir_path| is empty, all remaining items match.
183 if (!dir_path.empty() && (it->second->full_path().DirName() != dir_path))
184 continue;
185
186 result->push_back(item);
[email protected]c4a530b2010-03-08 17:33:03187 }
[email protected]f7e9fd62010-09-28 15:45:06188
189 // If we have a parent profile, let it add its downloads to the results.
190 Profile* original_profile = profile_->GetOriginalProfile();
191 if (original_profile != profile_)
192 original_profile->GetDownloadManager()->GetCurrentDownloads(dir_path,
193 result);
[email protected]c4a530b2010-03-08 17:33:03194}
195
[email protected]d3b12902010-08-16 23:39:42196void DownloadManager::SearchDownloads(const string16& query,
[email protected]6d0146c2011-08-04 19:13:04197 DownloadVector* result) {
[email protected]d3b12902010-08-16 23:39:42198 DCHECK(result);
199
[email protected]503d03872011-05-06 08:36:26200 string16 query_lower(base::i18n::ToLower(query));
[email protected]d3b12902010-08-16 23:39:42201
[email protected]f04182f32010-12-10 19:12:07202 for (DownloadMap::iterator it = history_downloads_.begin();
203 it != history_downloads_.end(); ++it) {
[email protected]d3b12902010-08-16 23:39:42204 DownloadItem* download_item = it->second;
205
206 if (download_item->is_temporary() || download_item->is_extension_install())
207 continue;
208
209 // Display Incognito downloads only in Incognito window, and vice versa.
210 // The Incognito Downloads page will get the list of non-Incognito downloads
211 // from its parent profile.
212 if (profile_->IsOffTheRecord() != download_item->is_otr())
213 continue;
214
215 if (download_item->MatchesQuery(query_lower))
216 result->push_back(download_item);
217 }
218
219 // If we have a parent profile, let it add its downloads to the results.
220 Profile* original_profile = profile_->GetOriginalProfile();
221 if (original_profile != profile_)
222 original_profile->GetDownloadManager()->SearchDownloads(query, result);
223}
224
initial.commit09911bf2008-07-26 23:55:29225// Query the history service for information about all persisted downloads.
226bool DownloadManager::Init(Profile* profile) {
227 DCHECK(profile);
228 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
229 shutdown_needed_ = true;
230
231 profile_ = profile;
[email protected]d3b12902010-08-16 23:39:42232 download_history_.reset(new DownloadHistory(profile));
[email protected]82f37b02010-07-29 22:04:57233 download_history_->Load(
234 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
[email protected]024f2f02010-04-30 22:51:46235
[email protected]2941c2392010-07-15 22:54:30236 // In test mode, there may be no ResourceDispatcherHost. In this case it's
237 // safe to avoid setting |file_manager_| because we only call a small set of
238 // functions, none of which need it.
[email protected]a0ce3282011-08-19 20:49:52239 ResourceDispatcherHost* rdh =
240 content::GetContentClient()->browser()->GetResourceDispatcherHost();
[email protected]2941c2392010-07-15 22:54:30241 if (rdh) {
242 file_manager_ = rdh->download_file_manager();
243 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29244 }
245
[email protected]b0ab1d42010-02-24 19:29:28246 other_download_manager_observer_.reset(
247 new OtherDownloadManagerObserver(this));
248
initial.commit09911bf2008-07-26 23:55:29249 return true;
250}
251
[email protected]aa9881c2011-08-15 18:01:12252// We have received a message from DownloadFileManager about a new download.
[email protected]4cd82f72011-05-23 19:15:01253void DownloadManager::StartDownload(int32 download_id) {
[email protected]ca4b5fa32010-10-09 12:42:18254 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]287b86b2011-02-26 00:11:35255
[email protected]aa9881c2011-08-15 18:01:12256 if (delegate_->ShouldStartDownload(download_id))
257 RestartDownload(download_id);
[email protected]287b86b2011-02-26 00:11:35258}
259
[email protected]9fc114672011-06-15 08:17:48260void DownloadManager::CheckForHistoryFilesRemoval() {
261 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
262 for (DownloadMap::iterator it = history_downloads_.begin();
263 it != history_downloads_.end(); ++it) {
264 CheckForFileRemoval(it->second);
265 }
266}
267
268void DownloadManager::CheckForFileRemoval(DownloadItem* download_item) {
269 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
270 if (download_item->IsComplete() &&
271 !download_item->file_externally_removed()) {
272 BrowserThread::PostTask(
273 BrowserThread::FILE, FROM_HERE,
274 NewRunnableMethod(this,
275 &DownloadManager::CheckForFileRemovalOnFileThread,
276 download_item->db_handle(),
277 download_item->GetTargetFilePath()));
278 }
279}
280
281void DownloadManager::CheckForFileRemovalOnFileThread(
282 int64 db_handle, const FilePath& path) {
283 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
284 if (!file_util::PathExists(path)) {
285 BrowserThread::PostTask(
286 BrowserThread::UI, FROM_HERE,
287 NewRunnableMethod(this,
288 &DownloadManager::OnFileRemovalDetected,
289 db_handle));
290 }
291}
292
293void DownloadManager::OnFileRemovalDetected(int64 db_handle) {
294 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
295 DownloadMap::iterator it = history_downloads_.find(db_handle);
296 if (it != history_downloads_.end()) {
297 DownloadItem* download_item = it->second;
298 download_item->OnDownloadedFileRemoved();
299 }
300}
301
[email protected]aa9881c2011-08-15 18:01:12302void DownloadManager::RestartDownload(
303 int32 download_id) {
[email protected]ca4b5fa32010-10-09 12:42:18304 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29305
[email protected]4cd82f72011-05-23 19:15:01306 DownloadItem* download = GetActiveDownloadItem(download_id);
307 if (!download)
308 return;
309
310 VLOG(20) << __FUNCTION__ << "()"
311 << " download = " << download->DebugString(true);
312
[email protected]4cd82f72011-05-23 19:15:01313 FilePath suggested_path = download->suggested_path();
314
[email protected]da1a27b2011-07-29 23:16:33315 if (download->prompt_user_for_save_location()) {
initial.commit09911bf2008-07-26 23:55:29316 // We must ask the user for the place to put the download.
[email protected]db6831a2011-06-09 21:08:28317 DownloadRequestHandle request_handle = download->request_handle();
318 TabContents* contents = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:26319
[email protected]4cd82f72011-05-23 19:15:01320 // |id_ptr| will be deleted in either FileSelected() or
321 // FileSelectionCancelled().
322 int32* id_ptr = new int32;
323 *id_ptr = download_id;
[email protected]99cb7f82011-07-28 17:27:26324
[email protected]da1a27b2011-07-29 23:16:33325 delegate_->ChooseDownloadPath(
[email protected]aa9881c2011-08-15 18:01:12326 contents, suggested_path, reinterpret_cast<void*>(id_ptr));
[email protected]99cb7f82011-07-28 17:27:26327
[email protected]f5920322011-03-24 20:34:16328 FOR_EACH_OBSERVER(Observer, observers_,
[email protected]fed38252011-07-08 17:26:50329 SelectFileDialogDisplayed(download_id));
initial.commit09911bf2008-07-26 23:55:29330 } else {
331 // No prompting for download, just continue with the suggested name.
[email protected]4cd82f72011-05-23 19:15:01332 ContinueDownloadWithPath(download, suggested_path);
initial.commit09911bf2008-07-26 23:55:29333 }
334}
335
[email protected]c2e76012010-12-23 21:10:29336void DownloadManager::CreateDownloadItem(DownloadCreateInfo* info) {
337 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
338
339 DownloadItem* download = new DownloadItem(this, *info,
340 profile_->IsOffTheRecord());
[email protected]4cd82f72011-05-23 19:15:01341 int32 download_id = info->download_id;
342 DCHECK(!ContainsKey(in_progress_, download_id));
343 DCHECK(!ContainsKey(active_downloads_, download_id));
[email protected]c2e76012010-12-23 21:10:29344 downloads_.insert(download);
[email protected]4cd82f72011-05-23 19:15:01345 active_downloads_[download_id] = download;
[email protected]c2e76012010-12-23 21:10:29346}
347
[email protected]4cd82f72011-05-23 19:15:01348void DownloadManager::ContinueDownloadWithPath(DownloadItem* download,
349 const FilePath& chosen_file) {
[email protected]ca4b5fa32010-10-09 12:42:18350 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]4cd82f72011-05-23 19:15:01351 DCHECK(download);
[email protected]aa033af2010-07-27 18:16:39352
[email protected]4cd82f72011-05-23 19:15:01353 int32 download_id = download->id();
initial.commit09911bf2008-07-26 23:55:29354
[email protected]70850c72011-01-11 17:31:27355 // NOTE(ahendrickson) Eventually |active_downloads_| will replace
356 // |in_progress_|, but we don't want to change the semantics yet.
[email protected]4cd82f72011-05-23 19:15:01357 DCHECK(!ContainsKey(in_progress_, download_id));
[email protected]70850c72011-01-11 17:31:27358 DCHECK(ContainsKey(downloads_, download));
[email protected]4cd82f72011-05-23 19:15:01359 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]70850c72011-01-11 17:31:27360
[email protected]4cd82f72011-05-23 19:15:01361 // Make sure the initial file name is set only once.
362 DCHECK(download->full_path().empty());
363 download->OnPathDetermined(chosen_file);
[email protected]4cd82f72011-05-23 19:15:01364
365 VLOG(20) << __FUNCTION__ << "()"
366 << " download = " << download->DebugString(true);
367
368 in_progress_[download_id] = download;
[email protected]5f8589fe2011-08-17 20:58:39369 UpdateDownloadProgress(); // Reflect entry into in_progress_.
initial.commit09911bf2008-07-26 23:55:29370
[email protected]adb2f3d12011-01-23 16:24:54371 // Rename to intermediate name.
[email protected]f5920322011-03-24 20:34:16372 FilePath download_path;
[email protected]4cd82f72011-05-23 19:15:01373 if (download->IsDangerous()) {
[email protected]adb2f3d12011-01-23 16:24:54374 // The download is not safe. We can now rename the file to its
[email protected]f5920322011-03-24 20:34:16375 // tentative name using RenameInProgressDownloadFile.
376 // NOTE: The |Rename| below will be a no-op for dangerous files, as we're
377 // renaming it to the same name.
[email protected]4cd82f72011-05-23 19:15:01378 download_path = download->full_path();
[email protected]594cd7d2010-07-21 03:23:56379 } else {
[email protected]adb2f3d12011-01-23 16:24:54380 // The download is a safe download. We need to
381 // rename it to its intermediate '.crdownload' path. The final
382 // name after user confirmation will be set from
[email protected]48837962011-04-19 17:03:29383 // DownloadItem::OnDownloadCompleting.
[email protected]4cd82f72011-05-23 19:15:01384 download_path =
385 download_util::GetCrDownloadPath(download->full_path());
[email protected]594cd7d2010-07-21 03:23:56386 }
387
[email protected]f5920322011-03-24 20:34:16388 BrowserThread::PostTask(
389 BrowserThread::FILE, FROM_HERE,
390 NewRunnableMethod(
391 file_manager_, &DownloadFileManager::RenameInProgressDownloadFile,
392 download->id(), download_path));
393
394 download->Rename(download_path);
395
[email protected]4cd82f72011-05-23 19:15:01396 download_history_->AddEntry(download,
[email protected]82f37b02010-07-29 22:04:57397 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
initial.commit09911bf2008-07-26 23:55:29398}
399
initial.commit09911bf2008-07-26 23:55:29400void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
[email protected]70850c72011-01-11 17:31:27401 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
402 DownloadMap::iterator it = active_downloads_.find(download_id);
403 if (it != active_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29404 DownloadItem* download = it->second;
[email protected]bf68a00b2011-04-07 17:28:26405 if (download->IsInProgress()) {
[email protected]70850c72011-01-11 17:31:27406 download->Update(size);
[email protected]5f8589fe2011-08-17 20:58:39407 UpdateDownloadProgress(); // Reflect size updates.
[email protected]70850c72011-01-11 17:31:27408 download_history_->UpdateEntry(download);
409 }
initial.commit09911bf2008-07-26 23:55:29410 }
411}
412
[email protected]bf68a00b2011-04-07 17:28:26413void DownloadManager::OnResponseCompleted(int32 download_id,
414 int64 size,
415 int os_error,
416 const std::string& hash) {
417 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]7c8e55ba2011-07-01 18:59:23418 // ERR_CONNECTION_CLOSED is allowed since a number of servers in the wild
419 // advertise a larger Content-Length than the amount of bytes in the message
420 // body, and then close the connection. Other browsers - IE8, Firefox 4.0.1,
421 // and Safari 5.0.4 - treat the download as complete in this case, so we
422 // follow their lead.
[email protected]1822a422011-07-15 15:49:19423 if (os_error == 0 || os_error == net::ERR_CONNECTION_CLOSED) {
[email protected]bf68a00b2011-04-07 17:28:26424 OnAllDataSaved(download_id, size, hash);
425 } else {
426 OnDownloadError(download_id, size, os_error);
427 }
428}
429
[email protected]26711732011-03-09 00:21:22430void DownloadManager::OnAllDataSaved(int32 download_id,
431 int64 size,
432 const std::string& hash) {
[email protected]da6e3922010-11-24 21:45:50433 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
434 << " size = " << size;
[email protected]9d7ef802011-02-25 19:03:35435 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:32436
[email protected]c4f02c42011-01-24 21:55:06437 // If it's not in active_downloads_, that means it was cancelled; just
438 // ignore the notification.
439 if (active_downloads_.count(download_id) == 0)
440 return;
441
[email protected]adb2f3d12011-01-23 16:24:54442 DownloadItem* download = active_downloads_[download_id];
[email protected]a850ba42010-09-10 22:00:30443 download->OnAllDataSaved(size);
[email protected]9ccbb372008-10-10 18:50:32444
[email protected]adb2f3d12011-01-23 16:24:54445 MaybeCompleteDownload(download);
446}
[email protected]9ccbb372008-10-10 18:50:32447
[email protected]7d413112011-06-16 18:50:17448void DownloadManager::AssertQueueStateConsistent(DownloadItem* download) {
[email protected]5cd11b6e2011-06-10 20:30:59449 // TODO(rdsmith): Change to DCHECK after http://crbug.com/85408 resolved.
[email protected]7d413112011-06-16 18:50:17450 if (download->state() == DownloadItem::REMOVING) {
451 CHECK(!ContainsKey(downloads_, download));
452 CHECK(!ContainsKey(active_downloads_, download->id()));
453 CHECK(!ContainsKey(in_progress_, download->id()));
454 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
455 return;
456 }
457
458 // Should be in downloads_ if we're not REMOVING.
459 CHECK(ContainsKey(downloads_, download));
460
461 // Check history_downloads_ consistency.
462 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
463 CHECK(ContainsKey(history_downloads_, download->db_handle()));
464 } else {
465 // TODO(rdsmith): Somewhat painful; make sure to disable in
466 // release builds after resolution of http://crbug.com/85408.
467 for (DownloadMap::iterator it = history_downloads_.begin();
468 it != history_downloads_.end(); ++it) {
469 CHECK(it->second != download);
470 }
471 }
472
473 CHECK(ContainsKey(active_downloads_, download->id()) ==
474 (download->state() == DownloadItem::IN_PROGRESS));
[email protected]54610672011-07-18 18:24:43475 CHECK(ContainsKey(in_progress_, download->id()) ==
476 (download->state() == DownloadItem::IN_PROGRESS));
[email protected]5cd11b6e2011-06-10 20:30:59477}
478
[email protected]adb2f3d12011-01-23 16:24:54479bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
480 // If we don't have all the data, the download is not ready for
481 // completion.
482 if (!download->all_data_saved())
483 return false;
[email protected]6a7fb042010-02-01 16:30:47484
[email protected]9d7ef802011-02-25 19:03:35485 // If the download is dangerous, but not yet validated, it's not ready for
486 // completion.
487 if (download->safety_state() == DownloadItem::DANGEROUS)
488 return false;
489
[email protected]adb2f3d12011-01-23 16:24:54490 // If the download isn't active (e.g. has been cancelled) it's not
491 // ready for completion.
492 if (active_downloads_.count(download->id()) == 0)
493 return false;
494
495 // If the download hasn't been inserted into the history system
496 // (which occurs strictly after file name determination, intermediate
497 // file rename, and UI display) then it's not ready for completion.
[email protected]7054b592011-06-22 14:46:42498 if (download->db_handle() == DownloadHistory::kUninitializedHandle)
499 return false;
500
501 return true;
[email protected]adb2f3d12011-01-23 16:24:54502}
503
504void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
505 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
506 VLOG(20) << __FUNCTION__ << "()" << " download = "
507 << download->DebugString(false);
508
509 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32510 return;
[email protected]9ccbb372008-10-10 18:50:32511
[email protected]adb2f3d12011-01-23 16:24:54512 // TODO(rdsmith): DCHECK that we only pass through this point
513 // once per download. The natural way to do this is by a state
514 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56515
[email protected]adb2f3d12011-01-23 16:24:54516 // Confirm we're in the proper set of states to be here;
[email protected]9d7ef802011-02-25 19:03:35517 // in in_progress_, have all data, have a history handle, (validated or safe).
518 DCHECK_NE(DownloadItem::DANGEROUS, download->safety_state());
[email protected]adb2f3d12011-01-23 16:24:54519 DCHECK_EQ(1u, in_progress_.count(download->id()));
520 DCHECK(download->all_data_saved());
521 DCHECK(download->db_handle() != DownloadHistory::kUninitializedHandle);
522 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
523
524 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
525 << download->DebugString(false);
526
527 // Remove the id from in_progress
528 in_progress_.erase(download->id());
[email protected]5f8589fe2011-08-17 20:58:39529 UpdateDownloadProgress(); // Reflect removal from in_progress_.
[email protected]adb2f3d12011-01-23 16:24:54530
[email protected]adb2f3d12011-01-23 16:24:54531 download_history_->UpdateEntry(download);
532
[email protected]f5920322011-03-24 20:34:16533 // Finish the download.
[email protected]48837962011-04-19 17:03:29534 download->OnDownloadCompleting(file_manager_);
[email protected]9ccbb372008-10-10 18:50:32535}
536
[email protected]cc3c7c092011-05-09 18:40:21537void DownloadManager::DownloadCompleted(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27538 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21539 DownloadItem* download = GetDownloadItem(download_id);
540 DCHECK(download);
541 download_history_->UpdateEntry(download);
[email protected]70850c72011-01-11 17:31:27542 active_downloads_.erase(download_id);
543}
544
[email protected]f5920322011-03-24 20:34:16545void DownloadManager::OnDownloadRenamedToFinalName(int download_id,
546 const FilePath& full_path,
547 int uniquifier) {
[email protected]da6e3922010-11-24 21:45:50548 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
[email protected]f5920322011-03-24 20:34:16549 << " full_path = \"" << full_path.value() << "\""
550 << " uniquifier = " << uniquifier;
[email protected]ca4b5fa32010-10-09 12:42:18551 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]f5920322011-03-24 20:34:16552
[email protected]2e030682010-07-23 19:45:36553 DownloadItem* item = GetDownloadItem(download_id);
554 if (!item)
555 return;
[email protected]6cade212008-12-03 00:32:22556
[email protected]8fa1eeb52011-04-13 14:18:02557 if (item->safety_state() == DownloadItem::SAFE) {
558 DCHECK_EQ(0, uniquifier) << "We should not uniquify SAFE downloads twice";
559 }
560
[email protected]ca4b5fa32010-10-09 12:42:18561 BrowserThread::PostTask(
[email protected]f5920322011-03-24 20:34:16562 BrowserThread::FILE, FROM_HERE,
563 NewRunnableMethod(
564 file_manager_, &DownloadFileManager::CompleteDownload, download_id));
[email protected]9ccbb372008-10-10 18:50:32565
[email protected]f5920322011-03-24 20:34:16566 if (uniquifier)
567 item->set_path_uniquifier(uniquifier);
[email protected]9ccbb372008-10-10 18:50:32568
[email protected]f5920322011-03-24 20:34:16569 item->OnDownloadRenamedToFinalName(full_path);
570 download_history_->UpdateDownloadPath(item, full_path);
initial.commit09911bf2008-07-26 23:55:29571}
572
[email protected]54610672011-07-18 18:24:43573void DownloadManager::DownloadCancelled(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27574 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]54610672011-07-18 18:24:43575 DownloadMap::iterator it = in_progress_.find(download_id);
576 if (it == in_progress_.end())
initial.commit09911bf2008-07-26 23:55:29577 return;
578 DownloadItem* download = it->second;
579
[email protected]da6e3922010-11-24 21:45:50580 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
581 << " download = " << download->DebugString(true);
582
[email protected]54610672011-07-18 18:24:43583 // Clean up will happen when the history system create callback runs if we
584 // don't have a valid db_handle yet.
585 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
586 in_progress_.erase(it);
587 active_downloads_.erase(download_id);
[email protected]5f8589fe2011-08-17 20:58:39588 UpdateDownloadProgress(); // Reflect removal from in_progress_.
[email protected]54610672011-07-18 18:24:43589 download_history_->UpdateEntry(download);
590 }
initial.commit09911bf2008-07-26 23:55:29591
[email protected]54610672011-07-18 18:24:43592 DownloadCancelledInternal(download_id, download->request_handle());
593}
[email protected]d7d1c5c2009-08-05 23:52:50594
[email protected]54610672011-07-18 18:24:43595void DownloadManager::DownloadCancelledInternal(
596 int download_id, const DownloadRequestHandle& request_handle) {
597 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
598 request_handle.CancelRequest();
[email protected]d7d1c5c2009-08-05 23:52:50599
[email protected]ca4b5fa32010-10-09 12:42:18600 BrowserThread::PostTask(
601 BrowserThread::FILE, FROM_HERE,
[email protected]d83d03aa2009-11-02 21:44:37602 NewRunnableMethod(
603 file_manager_, &DownloadFileManager::CancelDownload, download_id));
initial.commit09911bf2008-07-26 23:55:29604}
605
[email protected]bf68a00b2011-04-07 17:28:26606void DownloadManager::OnDownloadError(int32 download_id,
607 int64 size,
608 int os_error) {
609 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
610 DownloadMap::iterator it = active_downloads_.find(download_id);
611 // A cancel at the right time could remove the download from the
612 // |active_downloads_| map before we get here.
613 if (it == active_downloads_.end())
614 return;
615
616 DownloadItem* download = it->second;
617
[email protected]4cd82f72011-05-23 19:15:01618 VLOG(20) << __FUNCTION__ << "()" << " Error " << os_error
619 << " at offset " << download->received_bytes()
620 << " for download = " << download->DebugString(true);
621
[email protected]54610672011-07-18 18:24:43622 download->Interrupted(size, os_error);
623
624 // TODO(ahendrickson) - Remove this when we add resuming of interrupted
625 // downloads, as we will keep the download item around in that case.
626 //
627 // Clean up will happen when the history system create callback runs if we
628 // don't have a valid db_handle yet.
629 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
630 in_progress_.erase(download_id);
631 active_downloads_.erase(download_id);
[email protected]5f8589fe2011-08-17 20:58:39632 UpdateDownloadProgress(); // Reflect removal from in_progress_.
[email protected]54610672011-07-18 18:24:43633 download_history_->UpdateEntry(download);
634 }
635
636 BrowserThread::PostTask(
637 BrowserThread::FILE, FROM_HERE,
638 NewRunnableMethod(
639 file_manager_, &DownloadFileManager::CancelDownload, download_id));
[email protected]bf68a00b2011-04-07 17:28:26640}
641
[email protected]5f8589fe2011-08-17 20:58:39642void DownloadManager::UpdateDownloadProgress() {
643 delegate_->DownloadProgressUpdated();
[email protected]6a7fb042010-02-01 16:30:47644}
645
[email protected]6d0146c2011-08-04 19:13:04646int DownloadManager::RemoveDownloadItems(
647 const DownloadVector& pending_deletes) {
648 if (pending_deletes.empty())
649 return 0;
650
651 // Delete from internal maps.
652 for (DownloadVector::const_iterator it = pending_deletes.begin();
653 it != pending_deletes.end();
654 ++it) {
655 DownloadItem* download = *it;
656 DCHECK(download);
657 history_downloads_.erase(download->db_handle());
658 save_page_downloads_.erase(download->id());
659 downloads_.erase(download);
660 }
661
662 // Tell observers to refresh their views.
663 NotifyModelChanged();
664
665 // Delete the download items themselves.
666 const int num_deleted = static_cast<int>(pending_deletes.size());
667 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
668 return num_deleted;
669}
670
[email protected]54610672011-07-18 18:24:43671void DownloadManager::RemoveDownload(int64 download_handle) {
672 DownloadMap::iterator it = history_downloads_.find(download_handle);
673 if (it == history_downloads_.end())
674 return;
675
676 // Make history update.
677 DownloadItem* download = it->second;
678 download_history_->RemoveEntry(download);
initial.commit09911bf2008-07-26 23:55:29679
680 // Remove from our tables and delete.
[email protected]6d0146c2011-08-04 19:13:04681 int downloads_count = RemoveDownloadItems(DownloadVector(1, download));
[email protected]f04182f32010-12-10 19:12:07682 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29683}
684
[email protected]e93d2822009-01-30 05:59:59685int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
686 const base::Time remove_end) {
[email protected]82f37b02010-07-29 22:04:57687 download_history_->RemoveEntriesBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29688
[email protected]a312a442010-12-15 23:40:33689 // All downloads visible to the user will be in the history,
690 // so scan that map.
[email protected]6d0146c2011-08-04 19:13:04691 DownloadVector pending_deletes;
692 for (DownloadMap::const_iterator it = history_downloads_.begin();
693 it != history_downloads_.end();
694 ++it) {
initial.commit09911bf2008-07-26 23:55:29695 DownloadItem* download = it->second;
initial.commit09911bf2008-07-26 23:55:29696 if (download->start_time() >= remove_begin &&
697 (remove_end.is_null() || download->start_time() < remove_end) &&
[email protected]6d0146c2011-08-04 19:13:04698 (download->IsComplete() || download->IsCancelled())) {
[email protected]7d413112011-06-16 18:50:17699 AssertQueueStateConsistent(download);
[email protected]78b8fcc92009-03-31 17:36:28700 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29701 }
initial.commit09911bf2008-07-26 23:55:29702 }
[email protected]6d0146c2011-08-04 19:13:04703 return RemoveDownloadItems(pending_deletes);
initial.commit09911bf2008-07-26 23:55:29704}
705
[email protected]e93d2822009-01-30 05:59:59706int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
707 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29708}
709
[email protected]d41355e6f2009-04-07 21:21:12710int DownloadManager::RemoveAllDownloads() {
[email protected]024f2f02010-04-30 22:51:46711 if (this != profile_->GetOriginalProfile()->GetDownloadManager()) {
712 // This is an incognito downloader. Clear All should clear main download
713 // manager as well.
714 profile_->GetOriginalProfile()->GetDownloadManager()->RemoveAllDownloads();
715 }
[email protected]d41355e6f2009-04-07 21:21:12716 // The null times make the date range unbounded.
717 return RemoveDownloadsBetween(base::Time(), base::Time());
718}
719
initial.commit09911bf2008-07-26 23:55:29720// Initiate a download of a specific URL. We send the request to the
721// ResourceDispatcherHost, and let it send us responses like a regular
722// download.
723void DownloadManager::DownloadUrl(const GURL& url,
724 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50725 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34726 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26727 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
728 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58729}
730
731void DownloadManager::DownloadUrlToFile(const GURL& url,
732 const GURL& referrer,
733 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32734 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58735 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34736 DCHECK(tab_contents);
[email protected]ed24fad2011-05-10 22:44:01737 // We send a pointer to content::ResourceContext, instead of the usual
738 // reference, so that a copy of the object isn't made.
[email protected]ca4b5fa32010-10-09 12:42:18739 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]a0ce3282011-08-19 20:49:52740 NewRunnableFunction(&BeginDownload,
[email protected]ae8945192010-07-20 16:56:26741 url,
742 referrer,
[email protected]ae8945192010-07-20 16:56:26743 save_info,
[email protected]ae8945192010-07-20 16:56:26744 tab_contents->GetRenderProcessHost()->id(),
745 tab_contents->render_view_host()->routing_id(),
[email protected]cafe4ad2011-07-28 18:34:56746 &tab_contents->browser_context()->
747 GetResourceContext()));
initial.commit09911bf2008-07-26 23:55:29748}
749
initial.commit09911bf2008-07-26 23:55:29750void DownloadManager::AddObserver(Observer* observer) {
751 observers_.AddObserver(observer);
752 observer->ModelChanged();
753}
754
755void DownloadManager::RemoveObserver(Observer* observer) {
756 observers_.RemoveObserver(observer);
757}
758
[email protected]073ed7b2010-09-27 09:20:02759bool DownloadManager::IsDownloadProgressKnown() {
760 for (DownloadMap::iterator i = in_progress_.begin();
761 i != in_progress_.end(); ++i) {
762 if (i->second->total_bytes() <= 0)
763 return false;
764 }
765
766 return true;
767}
768
769int64 DownloadManager::GetInProgressDownloadCount() {
770 return in_progress_.size();
771}
772
773int64 DownloadManager::GetReceivedDownloadBytes() {
774 DCHECK(IsDownloadProgressKnown());
775 int64 received_bytes = 0;
776 for (DownloadMap::iterator i = in_progress_.begin();
777 i != in_progress_.end(); ++i) {
778 received_bytes += i->second->received_bytes();
779 }
780 return received_bytes;
781}
782
783int64 DownloadManager::GetTotalDownloadBytes() {
784 DCHECK(IsDownloadProgressKnown());
785 int64 total_bytes = 0;
786 for (DownloadMap::iterator i = in_progress_.begin();
787 i != in_progress_.end(); ++i) {
788 total_bytes += i->second->total_bytes();
789 }
790 return total_bytes;
791}
792
[email protected]99cb7f82011-07-28 17:27:26793void DownloadManager::FileSelected(const FilePath& path, void* params) {
[email protected]4cd82f72011-05-23 19:15:01794 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
795
796 int32* id_ptr = reinterpret_cast<int32*>(params);
797 DCHECK(id_ptr != NULL);
798 int32 download_id = *id_ptr;
799 delete id_ptr;
800
801 DownloadItem* download = GetActiveDownloadItem(download_id);
802 if (!download)
803 return;
804 VLOG(20) << __FUNCTION__ << "()" << " path = \"" << path.value() << "\""
805 << " download = " << download->DebugString(true);
806
[email protected]da1a27b2011-07-29 23:16:33807 if (download->prompt_user_for_save_location())
[email protected]7ae7c2cb2009-01-06 23:31:41808 last_download_path_ = path.DirName();
[email protected]287b86b2011-02-26 00:11:35809
[email protected]4cd82f72011-05-23 19:15:01810 // Make sure the initial file name is set only once.
811 ContinueDownloadWithPath(download, path);
initial.commit09911bf2008-07-26 23:55:29812}
813
814void DownloadManager::FileSelectionCanceled(void* params) {
815 // The user didn't pick a place to save the file, so need to cancel the
816 // download that's already in progress to the temporary location.
[email protected]4cd82f72011-05-23 19:15:01817 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
818 int32* id_ptr = reinterpret_cast<int32*>(params);
819 DCHECK(id_ptr != NULL);
820 int32 download_id = *id_ptr;
821 delete id_ptr;
822
823 DownloadItem* download = GetActiveDownloadItem(download_id);
824 if (!download)
825 return;
826
827 VLOG(20) << __FUNCTION__ << "()"
828 << " download = " << download->DebugString(true);
829
[email protected]54610672011-07-18 18:24:43830 DownloadCancelledInternal(download_id, download->request_handle());
[email protected]4cd82f72011-05-23 19:15:01831}
832
initial.commit09911bf2008-07-26 23:55:29833// Operations posted to us from the history service ----------------------------
834
835// The history service has retrieved all download entries. 'entries' contains
[email protected]4cd82f72011-05-23 19:15:01836// 'DownloadHistoryInfo's in sorted order (by ascending start_time).
initial.commit09911bf2008-07-26 23:55:29837void DownloadManager::OnQueryDownloadEntriesComplete(
[email protected]4cd82f72011-05-23 19:15:01838 std::vector<DownloadHistoryInfo>* entries) {
initial.commit09911bf2008-07-26 23:55:29839 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:39840 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]f04182f32010-12-10 19:12:07841 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
842 downloads_.insert(download);
843 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:50844 VLOG(20) << __FUNCTION__ << "()" << i << ">"
845 << " download = " << download->DebugString(true);
initial.commit09911bf2008-07-26 23:55:29846 }
[email protected]b0ab1d42010-02-24 19:29:28847 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:48848 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:29849}
850
[email protected]f9a45b02011-06-30 23:49:19851void DownloadManager::AddDownloadItemToHistory(DownloadItem* download,
852 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:27853 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d2a8fb72010-01-21 05:31:42854
[email protected]5bcd73eb2011-03-23 21:14:02855 // It's not immediately obvious, but HistoryBackend::CreateDownload() can
856 // call this function with an invalid |db_handle|. For instance, this can
857 // happen when the history database is offline. We cannot have multiple
858 // DownloadItems with the same invalid db_handle, so we need to assign a
859 // unique |db_handle| here.
860 if (db_handle == DownloadHistory::kUninitializedHandle)
861 db_handle = download_history_->GetNextFakeDbHandle();
862
[email protected]1e9fe7ff2011-06-24 17:37:33863 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/84508
864 // is fixed.
[email protected]54610672011-07-18 18:24:43865 CHECK_NE(DownloadHistory::kUninitializedHandle, db_handle);
[email protected]1e9fe7ff2011-06-24 17:37:33866
[email protected]5bcd73eb2011-03-23 21:14:02867 DCHECK(download->db_handle() == DownloadHistory::kUninitializedHandle);
868 download->set_db_handle(db_handle);
869
[email protected]5bcd73eb2011-03-23 21:14:02870 DCHECK(!ContainsKey(history_downloads_, download->db_handle()));
871 history_downloads_[download->db_handle()] = download;
[email protected]6d0146c2011-08-04 19:13:04872
873 // Show in the appropriate browser UI.
874 // This includes buttons to save or cancel, for a dangerous download.
875 ShowDownloadInBrowser(download);
876
877 // Inform interested objects about the new download.
878 NotifyModelChanged();
[email protected]f9a45b02011-06-30 23:49:19879}
880
881// Once the new DownloadItem's creation info has been committed to the history
882// service, we associate the DownloadItem with the db handle, update our
883// 'history_downloads_' map and inform observers.
884void DownloadManager::OnCreateDownloadEntryComplete(int32 download_id,
885 int64 db_handle) {
886 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]19420cc2011-07-18 17:43:45887 DownloadItem* download = GetActiveDownloadItem(download_id);
[email protected]54610672011-07-18 18:24:43888 if (!download)
[email protected]19420cc2011-07-18 17:43:45889 return;
[email protected]54610672011-07-18 18:24:43890
891 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
892 << " download_id = " << download_id
893 << " download = " << download->DebugString(true);
[email protected]f9a45b02011-06-30 23:49:19894
895 AddDownloadItemToHistory(download, db_handle);
initial.commit09911bf2008-07-26 23:55:29896
[email protected]54610672011-07-18 18:24:43897 // If the download is still in progress, try to complete it.
898 //
899 // Otherwise, download has been cancelled or interrupted before we've
900 // received the DB handle. We post one final message to the history
901 // service so that it can be properly in sync with the DownloadItem's
902 // completion status, and also inform any observers so that they get
903 // more than just the start notification.
904 if (download->IsInProgress()) {
905 MaybeCompleteDownload(download);
906 } else {
907 DCHECK(download->IsCancelled())
908 << " download = " << download->DebugString(true);
909 in_progress_.erase(download_id);
910 active_downloads_.erase(download_id);
911 download_history_->UpdateEntry(download);
912 download->UpdateObservers();
913 }
initial.commit09911bf2008-07-26 23:55:29914}
915
[email protected]4cd82f72011-05-23 19:15:01916void DownloadManager::ShowDownloadInBrowser(DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:34917 // The 'contents' may no longer exist if the user closed the tab before we
[email protected]99cb7f82011-07-28 17:27:26918 // get this start completion event.
[email protected]db6831a2011-06-09 21:08:28919 DownloadRequestHandle request_handle = download->request_handle();
[email protected]686493142011-07-15 21:47:22920 TabContents* content = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:26921
922 // If the contents no longer exists, we ask the embedder to suggest another
923 // tab.
[email protected]da1a27b2011-07-29 23:16:33924 if (!content)
[email protected]aa9881c2011-08-15 18:01:12925 content = delegate_->GetAlternativeTabContentsToNotifyForDownload();
[email protected]5e595482009-05-06 20:16:53926
[email protected]99cb7f82011-07-28 17:27:26927 if (content)
928 content->OnStartDownload(download);
[email protected]5e595482009-05-06 20:16:53929}
930
[email protected]6cade212008-12-03 00:32:22931// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:12932void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:41933 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:38934}
[email protected]b0ab1d42010-02-24 19:29:28935
936void DownloadManager::NotifyModelChanged() {
937 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
938}
939
[email protected]4cd82f72011-05-23 19:15:01940DownloadItem* DownloadManager::GetDownloadItem(int download_id) {
941 // The |history_downloads_| map is indexed by the download's db_handle,
942 // not its id, so we have to iterate.
[email protected]f04182f32010-12-10 19:12:07943 for (DownloadMap::iterator it = history_downloads_.begin();
944 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:36945 DownloadItem* item = it->second;
[email protected]4cd82f72011-05-23 19:15:01946 if (item->id() == download_id)
[email protected]2e030682010-07-23 19:45:36947 return item;
948 }
949 return NULL;
950}
951
[email protected]4cd82f72011-05-23 19:15:01952DownloadItem* DownloadManager::GetActiveDownloadItem(int download_id) {
953 DCHECK(ContainsKey(active_downloads_, download_id));
954 DownloadItem* download = active_downloads_[download_id];
955 DCHECK(download != NULL);
956 return download;
957}
958
[email protected]57fd1252010-12-23 17:24:09959// Confirm that everything in all maps is also in |downloads_|, and that
960// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:07961void DownloadManager::AssertContainersConsistent() const {
962#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:09963 // Turn everything into sets.
[email protected]6d0146c2011-08-04 19:13:04964 const DownloadMap* input_maps[] = {&active_downloads_,
965 &history_downloads_,
966 &save_page_downloads_};
967 DownloadSet active_set, history_set, save_page_set;
968 DownloadSet* all_sets[] = {&active_set, &history_set, &save_page_set};
969 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(all_sets));
[email protected]57fd1252010-12-23 17:24:09970 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
971 for (DownloadMap::const_iterator it = input_maps[i]->begin();
[email protected]6d0146c2011-08-04 19:13:04972 it != input_maps[i]->end(); ++it) {
973 all_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:07974 }
975 }
[email protected]57fd1252010-12-23 17:24:09976
977 // Check if each set is fully present in downloads, and create a union.
[email protected]57fd1252010-12-23 17:24:09978 DownloadSet downloads_union;
979 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
980 DownloadSet remainder;
981 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
982 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
983 downloads_.begin(), downloads_.end(),
984 insert_it);
985 DCHECK(remainder.empty());
986 std::insert_iterator<DownloadSet>
987 insert_union(downloads_union, downloads_union.end());
988 std::set_union(downloads_union.begin(), downloads_union.end(),
989 all_sets[i]->begin(), all_sets[i]->end(),
990 insert_union);
991 }
992
993 // Is everything in downloads_ present in one of the other sets?
994 DownloadSet remainder;
995 std::insert_iterator<DownloadSet>
996 insert_remainder(remainder, remainder.begin());
997 std::set_difference(downloads_.begin(), downloads_.end(),
998 downloads_union.begin(), downloads_union.end(),
999 insert_remainder);
1000 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071001#endif
1002}
1003
[email protected]b0ab1d42010-02-24 19:29:281004// DownloadManager::OtherDownloadManagerObserver implementation ----------------
1005
1006DownloadManager::OtherDownloadManagerObserver::OtherDownloadManagerObserver(
1007 DownloadManager* observing_download_manager)
1008 : observing_download_manager_(observing_download_manager),
1009 observed_download_manager_(NULL) {
1010 if (observing_download_manager->profile_->GetOriginalProfile() ==
1011 observing_download_manager->profile_) {
1012 return;
1013 }
1014
1015 observed_download_manager_ = observing_download_manager_->
1016 profile_->GetOriginalProfile()->GetDownloadManager();
1017 observed_download_manager_->AddObserver(this);
1018}
1019
1020DownloadManager::OtherDownloadManagerObserver::~OtherDownloadManagerObserver() {
1021 if (observed_download_manager_)
1022 observed_download_manager_->RemoveObserver(this);
1023}
1024
1025void DownloadManager::OtherDownloadManagerObserver::ModelChanged() {
1026 observing_download_manager_->NotifyModelChanged();
1027}
1028
[email protected]b0ab1d42010-02-24 19:29:281029void DownloadManager::OtherDownloadManagerObserver::ManagerGoingDown() {
1030 observed_download_manager_ = NULL;
1031}
[email protected]6d0146c2011-08-04 19:13:041032
1033void DownloadManager::SavePageDownloadStarted(DownloadItem* download) {
1034 DCHECK(!ContainsKey(save_page_downloads_, download->id()));
1035 downloads_.insert(download);
1036 save_page_downloads_[download->id()] = download;
1037
1038 // Add this entry to the history service.
1039 // Additionally, the UI is notified in the callback.
1040 download_history_->AddEntry(download,
1041 NewCallback(this, &DownloadManager::OnSavePageDownloadEntryAdded));
1042}
1043
1044// SavePackage will call SavePageDownloadFinished upon completion/cancellation.
1045// The history callback will call OnSavePageDownloadEntryAdded.
1046// If the download finishes before the history callback,
1047// OnSavePageDownloadEntryAdded calls SavePageDownloadFinished, ensuring that
1048// the history event is update regardless of the order in which these two events
1049// complete.
1050// If something removes the download item from the download manager (Remove,
1051// Shutdown) the result will be that the SavePage system will not be able to
1052// properly update the download item (which no longer exists) or the download
1053// history, but the action will complete properly anyway. This may lead to the
1054// history entry being wrong on a reload of chrome (specifically in the case of
1055// Initiation -> History Callback -> Removal -> Completion), but there's no way
1056// to solve that without canceling on Remove (which would then update the DB).
1057
1058void DownloadManager::OnSavePageDownloadEntryAdded(int32 download_id,
1059 int64 db_handle) {
1060 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1061
1062 DownloadMap::const_iterator it = save_page_downloads_.find(download_id);
1063 // This can happen if the download manager is shutting down and all maps
1064 // have been cleared.
1065 if (it == save_page_downloads_.end())
1066 return;
1067
1068 DownloadItem* download = it->second;
1069 if (!download) {
1070 NOTREACHED();
1071 return;
1072 }
1073
1074 AddDownloadItemToHistory(download, db_handle);
1075
1076 // Finalize this download if it finished before the history callback.
1077 if (!download->IsInProgress())
1078 SavePageDownloadFinished(download);
1079}
1080
1081void DownloadManager::SavePageDownloadFinished(DownloadItem* download) {
1082 if (download->db_handle() != DownloadHistory::kUninitializedHandle) {
1083 download_history_->UpdateEntry(download);
1084 DCHECK(ContainsKey(save_page_downloads_, download->id()));
1085 save_page_downloads_.erase(download->id());
1086
1087 if (download->IsComplete())
1088 NotificationService::current()->Notify(
1089 content::NOTIFICATION_SAVE_PACKAGE_SUCCESSFULLY_FINISHED,
1090 Source<DownloadManager>(this),
1091 Details<DownloadItem>(download));
1092 }
1093}
1094
1095int32 DownloadManager::GetNextSavePageId() {
1096 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1097 return next_save_page_id_++;
1098}
1099