blob: 7c4c5b74c033fb76c163a9ba91aa69e8b6ff0b7e [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]eda58402011-09-21 19:32:029#include "base/bind.h"
[email protected]2041cf342010-02-19 03:15:5910#include "base/callback.h"
initial.commit09911bf2008-07-26 23:55:2911#include "base/file_util.h"
[email protected]503d03872011-05-06 08:36:2612#include "base/i18n/case_conversion.h"
initial.commit09911bf2008-07-26 23:55:2913#include "base/logging.h"
[email protected]7286e3fc2011-07-19 22:13:2414#include "base/stl_util.h"
[email protected]eda58402011-09-21 19:32:0215#include "base/stringprintf.h"
16#include "base/synchronization/lock.h"
17#include "base/sys_string_conversions.h"
initial.commit09911bf2008-07-26 23:55:2918#include "base/task.h"
[email protected]d2a8fb72010-01-21 05:31:4219#include "build/build_config.h"
[email protected]6d0c9fb2011-08-22 19:26:0320#include "content/browser/browser_context.h"
[email protected]7324d1d2011-03-01 05:02:1621#include "content/browser/browser_thread.h"
[email protected]a0ce3282011-08-19 20:49:5222#include "content/browser/content_browser_client.h"
[email protected]71bf3f5e2011-08-15 21:05:2223#include "content/browser/download/download_create_info.h"
24#include "content/browser/download/download_file_manager.h"
25#include "content/browser/download/download_item.h"
[email protected]d6b7fd1e2011-08-16 22:42:0026#include "content/browser/download/download_manager_delegate.h"
[email protected]bb1a4212011-08-22 22:38:2527#include "content/browser/download/download_persistent_store_info.h"
[email protected]da4a5582011-10-17 19:08:0628#include "content/browser/download/download_stats.h"
[email protected]71bf3f5e2011-08-15 21:05:2229#include "content/browser/download/download_status_updater.h"
[email protected]be76b7e2011-10-13 12:57:5730#include "content/browser/download/interrupt_reasons.h"
[email protected]7324d1d2011-03-01 05:02:1631#include "content/browser/renderer_host/render_process_host.h"
32#include "content/browser/renderer_host/render_view_host.h"
33#include "content/browser/renderer_host/resource_dispatcher_host.h"
34#include "content/browser/tab_contents/tab_contents.h"
[email protected]6d0146c2011-08-04 19:13:0435#include "content/common/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1636#include "content/public/browser/notification_types.h"
initial.commit09911bf2008-07-26 23:55:2937
[email protected]a0ce3282011-08-19 20:49:5238namespace {
39
40void BeginDownload(
41 const GURL& url,
42 const GURL& referrer,
43 const DownloadSaveInfo& save_info,
[email protected]c79a0c02011-08-22 22:37:3744 ResourceDispatcherHost* resource_dispatcher_host,
45 int render_process_id,
[email protected]a0ce3282011-08-19 20:49:5246 int render_view_id,
47 const content::ResourceContext* context) {
[email protected]8e3ae68c2011-09-16 22:15:4748 net::URLRequest* request = new net::URLRequest(url, resource_dispatcher_host);
49 request->set_referrer(referrer.spec());
[email protected]c79a0c02011-08-22 22:37:3750 resource_dispatcher_host->BeginDownload(
[email protected]8e3ae68c2011-09-16 22:15:4751 request,
52 save_info,
53 true,
54 DownloadResourceHandler::OnStartedCallback(),
55 render_process_id,
56 render_view_id,
[email protected]c79a0c02011-08-22 22:37:3757 *context);
[email protected]a0ce3282011-08-19 20:49:5258}
59
60} // namespace
61
[email protected]da1a27b2011-07-29 23:16:3362DownloadManager::DownloadManager(DownloadManagerDelegate* delegate,
63 DownloadStatusUpdater* status_updater)
initial.commit09911bf2008-07-26 23:55:2964 : shutdown_needed_(false),
[email protected]6d0c9fb2011-08-22 19:26:0365 browser_context_(NULL),
[email protected]eda58402011-09-21 19:32:0266 next_id_(0),
[email protected]073ed7b2010-09-27 09:20:0267 file_manager_(NULL),
[email protected]eda58402011-09-21 19:32:0268 status_updater_((status_updater != NULL)
69 ? status_updater->AsWeakPtr()
70 : base::WeakPtr<DownloadStatusUpdater>()),
[email protected]d8472d92011-08-26 20:15:2071 delegate_(delegate),
72 largest_db_handle_in_history_(DownloadItem::kUninitializedHandle) {
[email protected]eda58402011-09-21 19:32:0273 // NOTE(benjhayden): status_updater may be NULL when using
74 // TestingBrowserProcess.
75 if (status_updater_.get() != NULL)
[email protected]073ed7b2010-09-27 09:20:0276 status_updater_->AddDelegate(this);
initial.commit09911bf2008-07-26 23:55:2977}
78
79DownloadManager::~DownloadManager() {
[email protected]326a6a92010-09-10 20:21:1380 DCHECK(!shutdown_needed_);
[email protected]eda58402011-09-21 19:32:0281 if (status_updater_.get() != NULL)
[email protected]073ed7b2010-09-27 09:20:0282 status_updater_->RemoveDelegate(this);
initial.commit09911bf2008-07-26 23:55:2983}
84
85void DownloadManager::Shutdown() {
[email protected]da6e3922010-11-24 21:45:5086 VLOG(20) << __FUNCTION__ << "()"
87 << " shutdown_needed_ = " << shutdown_needed_;
[email protected]326a6a92010-09-10 20:21:1388 if (!shutdown_needed_)
89 return;
90 shutdown_needed_ = false;
initial.commit09911bf2008-07-26 23:55:2991
[email protected]326a6a92010-09-10 20:21:1392 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
[email protected]fb4f8d902011-09-16 06:07:0893 // TODO(benjhayden): Consider clearing observers_.
[email protected]326a6a92010-09-10 20:21:1394
95 if (file_manager_) {
[email protected]ca4b5fa32010-10-09 12:42:1896 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
[email protected]326a6a92010-09-10 20:21:1397 NewRunnableMethod(file_manager_,
98 &DownloadFileManager::OnDownloadManagerShutdown,
[email protected]dc7cdcb92010-12-14 06:40:5499 make_scoped_refptr(this)));
[email protected]326a6a92010-09-10 20:21:13100 }
initial.commit09911bf2008-07-26 23:55:29101
[email protected]f04182f32010-12-10 19:12:07102 AssertContainersConsistent();
103
104 // Go through all downloads in downloads_. Dangerous ones we need to
105 // remove on disk, and in progress ones we need to cancel.
[email protected]57fd1252010-12-23 17:24:09106 for (DownloadSet::iterator it = downloads_.begin(); it != downloads_.end();) {
[email protected]f04182f32010-12-10 19:12:07107 DownloadItem* download = *it;
108
109 // Save iterator from potential erases in this set done by called code.
110 // Iterators after an erasure point are still valid for lists and
111 // associative containers such as sets.
112 it++;
113
114 if (download->safety_state() == DownloadItem::DANGEROUS &&
[email protected]48837962011-04-19 17:03:29115 download->IsPartialDownload()) {
[email protected]f04182f32010-12-10 19:12:07116 // The user hasn't accepted it, so we need to remove it
117 // from the disk. This may or may not result in it being
118 // removed from the DownloadManager queues and deleted
119 // (specifically, DownloadManager::RemoveDownload only
120 // removes and deletes it if it's known to the history service)
121 // so the only thing we know after calling this function is that
122 // the download was deleted if-and-only-if it was removed
123 // from all queues.
[email protected]303077002011-04-19 23:21:01124 download->Delete(DownloadItem::DELETE_DUE_TO_BROWSER_SHUTDOWN);
[email protected]bf68a00b2011-04-07 17:28:26125 } else if (download->IsPartialDownload()) {
[email protected]93af2272011-09-21 18:29:17126 download->Cancel(false);
127 delegate_->UpdateItemInPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29128 }
129 }
130
[email protected]f04182f32010-12-10 19:12:07131 // At this point, all dangerous downloads have had their files removed
132 // and all in progress downloads have been cancelled. We can now delete
133 // anything left.
[email protected]9ccbb372008-10-10 18:50:32134
[email protected]5cd11b6e2011-06-10 20:30:59135 // Copy downloads_ to separate container so as not to set off checks
136 // in DownloadItem destruction.
137 DownloadSet downloads_to_delete;
138 downloads_to_delete.swap(downloads_);
139
initial.commit09911bf2008-07-26 23:55:29140 in_progress_.clear();
[email protected]70850c72011-01-11 17:31:27141 active_downloads_.clear();
[email protected]5cd11b6e2011-06-10 20:30:59142 history_downloads_.clear();
[email protected]5cd11b6e2011-06-10 20:30:59143 STLDeleteElements(&downloads_to_delete);
initial.commit09911bf2008-07-26 23:55:29144
[email protected]6d0146c2011-08-04 19:13:04145 DCHECK(save_page_downloads_.empty());
146
initial.commit09911bf2008-07-26 23:55:29147 file_manager_ = NULL;
[email protected]2588ea9d2011-08-22 20:59:53148 delegate_->Shutdown();
[email protected]82f37b02010-07-29 22:04:57149
initial.commit09911bf2008-07-26 23:55:29150 shutdown_needed_ = false;
151}
152
[email protected]82f37b02010-07-29 22:04:57153void DownloadManager::GetTemporaryDownloads(
[email protected]6d0146c2011-08-04 19:13:04154 const FilePath& dir_path, DownloadVector* result) {
[email protected]82f37b02010-07-29 22:04:57155 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58156
[email protected]f04182f32010-12-10 19:12:07157 for (DownloadMap::iterator it = history_downloads_.begin();
158 it != history_downloads_.end(); ++it) {
[email protected]6aa4a1c02010-01-15 18:49:58159 if (it->second->is_temporary() &&
160 it->second->full_path().DirName() == dir_path)
[email protected]82f37b02010-07-29 22:04:57161 result->push_back(it->second);
[email protected]6aa4a1c02010-01-15 18:49:58162 }
[email protected]6aa4a1c02010-01-15 18:49:58163}
164
[email protected]82f37b02010-07-29 22:04:57165void DownloadManager::GetAllDownloads(
[email protected]6d0146c2011-08-04 19:13:04166 const FilePath& dir_path, DownloadVector* result) {
[email protected]82f37b02010-07-29 22:04:57167 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34168
[email protected]f04182f32010-12-10 19:12:07169 for (DownloadMap::iterator it = history_downloads_.begin();
170 it != history_downloads_.end(); ++it) {
[email protected]8ddbd66a2010-05-21 16:38:34171 if (!it->second->is_temporary() &&
172 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57173 result->push_back(it->second);
[email protected]8ddbd66a2010-05-21 16:38:34174 }
[email protected]8ddbd66a2010-05-21 16:38:34175}
176
[email protected]d3b12902010-08-16 23:39:42177void DownloadManager::SearchDownloads(const string16& query,
[email protected]6d0146c2011-08-04 19:13:04178 DownloadVector* result) {
[email protected]503d03872011-05-06 08:36:26179 string16 query_lower(base::i18n::ToLower(query));
[email protected]d3b12902010-08-16 23:39:42180
[email protected]f04182f32010-12-10 19:12:07181 for (DownloadMap::iterator it = history_downloads_.begin();
182 it != history_downloads_.end(); ++it) {
[email protected]d3b12902010-08-16 23:39:42183 DownloadItem* download_item = it->second;
184
[email protected]8a282712011-08-23 19:28:00185 if (download_item->is_temporary())
[email protected]d3b12902010-08-16 23:39:42186 continue;
187
188 // Display Incognito downloads only in Incognito window, and vice versa.
189 // The Incognito Downloads page will get the list of non-Incognito downloads
190 // from its parent profile.
[email protected]6d0c9fb2011-08-22 19:26:03191 if (browser_context_->IsOffTheRecord() != download_item->is_otr())
[email protected]d3b12902010-08-16 23:39:42192 continue;
193
194 if (download_item->MatchesQuery(query_lower))
195 result->push_back(download_item);
196 }
[email protected]d3b12902010-08-16 23:39:42197}
198
[email protected]eda58402011-09-21 19:32:02199void DownloadManager::OnPersistentStoreGetNextId(int next_id) {
200 DVLOG(1) << __FUNCTION__ << " " << next_id;
201 base::AutoLock lock(next_id_lock_);
202 // TODO(benjhayden) Delay Profile initialization until here, and set next_id_
203 // = next_id. The '+=' works for now because these ids are not yet persisted
204 // to the database. GetNextId() can allocate zero or more ids starting from 0,
205 // then this callback can increment next_id_, and the items with lower ids
206 // won't clash with any other items even though there may be items loaded from
207 // the history because items from the history don't have valid ids.
208 next_id_ += next_id;
209}
210
211DownloadId DownloadManager::GetNextId() {
212 // May be called on any thread via the GetNextIdThunk.
213 // TODO(benjhayden) If otr, forward to parent DM.
214 base::AutoLock lock(next_id_lock_);
215 return DownloadId(this, next_id_++);
216}
217
218DownloadManager::GetNextIdThunkType DownloadManager::GetNextIdThunk() {
219 // TODO(benjhayden) If otr, forward to parent DM.
220 return base::Bind(&DownloadManager::GetNextId, this);
221}
222
initial.commit09911bf2008-07-26 23:55:29223// Query the history service for information about all persisted downloads.
[email protected]6d0c9fb2011-08-22 19:26:03224bool DownloadManager::Init(content::BrowserContext* browser_context) {
225 DCHECK(browser_context);
initial.commit09911bf2008-07-26 23:55:29226 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
227 shutdown_needed_ = true;
228
[email protected]6d0c9fb2011-08-22 19:26:03229 browser_context_ = browser_context;
[email protected]024f2f02010-04-30 22:51:46230
[email protected]2941c2392010-07-15 22:54:30231 // In test mode, there may be no ResourceDispatcherHost. In this case it's
232 // safe to avoid setting |file_manager_| because we only call a small set of
233 // functions, none of which need it.
[email protected]a0ce3282011-08-19 20:49:52234 ResourceDispatcherHost* rdh =
235 content::GetContentClient()->browser()->GetResourceDispatcherHost();
[email protected]2941c2392010-07-15 22:54:30236 if (rdh) {
237 file_manager_ = rdh->download_file_manager();
238 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29239 }
240
initial.commit09911bf2008-07-26 23:55:29241 return true;
242}
243
[email protected]aa9881c2011-08-15 18:01:12244// We have received a message from DownloadFileManager about a new download.
[email protected]4cd82f72011-05-23 19:15:01245void DownloadManager::StartDownload(int32 download_id) {
[email protected]ca4b5fa32010-10-09 12:42:18246 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]287b86b2011-02-26 00:11:35247
[email protected]aa9881c2011-08-15 18:01:12248 if (delegate_->ShouldStartDownload(download_id))
249 RestartDownload(download_id);
[email protected]287b86b2011-02-26 00:11:35250}
251
[email protected]9fc114672011-06-15 08:17:48252void DownloadManager::CheckForHistoryFilesRemoval() {
253 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
254 for (DownloadMap::iterator it = history_downloads_.begin();
255 it != history_downloads_.end(); ++it) {
256 CheckForFileRemoval(it->second);
257 }
258}
259
260void DownloadManager::CheckForFileRemoval(DownloadItem* download_item) {
261 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
262 if (download_item->IsComplete() &&
263 !download_item->file_externally_removed()) {
264 BrowserThread::PostTask(
265 BrowserThread::FILE, FROM_HERE,
266 NewRunnableMethod(this,
267 &DownloadManager::CheckForFileRemovalOnFileThread,
268 download_item->db_handle(),
269 download_item->GetTargetFilePath()));
270 }
271}
272
273void DownloadManager::CheckForFileRemovalOnFileThread(
274 int64 db_handle, const FilePath& path) {
275 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
276 if (!file_util::PathExists(path)) {
277 BrowserThread::PostTask(
278 BrowserThread::UI, FROM_HERE,
279 NewRunnableMethod(this,
280 &DownloadManager::OnFileRemovalDetected,
281 db_handle));
282 }
283}
284
285void DownloadManager::OnFileRemovalDetected(int64 db_handle) {
286 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
287 DownloadMap::iterator it = history_downloads_.find(db_handle);
288 if (it != history_downloads_.end()) {
289 DownloadItem* download_item = it->second;
290 download_item->OnDownloadedFileRemoved();
291 }
292}
293
[email protected]aa9881c2011-08-15 18:01:12294void DownloadManager::RestartDownload(
295 int32 download_id) {
[email protected]ca4b5fa32010-10-09 12:42:18296 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29297
[email protected]4cd82f72011-05-23 19:15:01298 DownloadItem* download = GetActiveDownloadItem(download_id);
299 if (!download)
300 return;
301
302 VLOG(20) << __FUNCTION__ << "()"
303 << " download = " << download->DebugString(true);
304
[email protected]4cd82f72011-05-23 19:15:01305 FilePath suggested_path = download->suggested_path();
306
[email protected]da1a27b2011-07-29 23:16:33307 if (download->prompt_user_for_save_location()) {
initial.commit09911bf2008-07-26 23:55:29308 // We must ask the user for the place to put the download.
[email protected]db6831a2011-06-09 21:08:28309 DownloadRequestHandle request_handle = download->request_handle();
310 TabContents* contents = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:26311
[email protected]4cd82f72011-05-23 19:15:01312 // |id_ptr| will be deleted in either FileSelected() or
[email protected]93af2272011-09-21 18:29:17313 // FileSelectionCancelled().
[email protected]4cd82f72011-05-23 19:15:01314 int32* id_ptr = new int32;
315 *id_ptr = download_id;
[email protected]99cb7f82011-07-28 17:27:26316
[email protected]da1a27b2011-07-29 23:16:33317 delegate_->ChooseDownloadPath(
[email protected]aa9881c2011-08-15 18:01:12318 contents, suggested_path, reinterpret_cast<void*>(id_ptr));
[email protected]99cb7f82011-07-28 17:27:26319
[email protected]f5920322011-03-24 20:34:16320 FOR_EACH_OBSERVER(Observer, observers_,
[email protected]fed38252011-07-08 17:26:50321 SelectFileDialogDisplayed(download_id));
initial.commit09911bf2008-07-26 23:55:29322 } else {
323 // No prompting for download, just continue with the suggested name.
[email protected]4cd82f72011-05-23 19:15:01324 ContinueDownloadWithPath(download, suggested_path);
initial.commit09911bf2008-07-26 23:55:29325 }
326}
327
[email protected]c2e76012010-12-23 21:10:29328void DownloadManager::CreateDownloadItem(DownloadCreateInfo* info) {
329 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
330
331 DownloadItem* download = new DownloadItem(this, *info,
[email protected]6d0c9fb2011-08-22 19:26:03332 browser_context_->IsOffTheRecord());
[email protected]4cd82f72011-05-23 19:15:01333 int32 download_id = info->download_id;
334 DCHECK(!ContainsKey(in_progress_, download_id));
[email protected]d8472d92011-08-26 20:15:20335
336 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]821960a2011-08-23 20:40:03337 CHECK(!ContainsKey(active_downloads_, download_id));
[email protected]c2e76012010-12-23 21:10:29338 downloads_.insert(download);
[email protected]4cd82f72011-05-23 19:15:01339 active_downloads_[download_id] = download;
[email protected]c2e76012010-12-23 21:10:29340}
341
[email protected]4cd82f72011-05-23 19:15:01342void DownloadManager::ContinueDownloadWithPath(DownloadItem* download,
343 const FilePath& chosen_file) {
[email protected]ca4b5fa32010-10-09 12:42:18344 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]4cd82f72011-05-23 19:15:01345 DCHECK(download);
[email protected]aa033af2010-07-27 18:16:39346
[email protected]4cd82f72011-05-23 19:15:01347 int32 download_id = download->id();
initial.commit09911bf2008-07-26 23:55:29348
[email protected]70850c72011-01-11 17:31:27349 // NOTE(ahendrickson) Eventually |active_downloads_| will replace
350 // |in_progress_|, but we don't want to change the semantics yet.
[email protected]4cd82f72011-05-23 19:15:01351 DCHECK(!ContainsKey(in_progress_, download_id));
[email protected]70850c72011-01-11 17:31:27352 DCHECK(ContainsKey(downloads_, download));
[email protected]4cd82f72011-05-23 19:15:01353 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]70850c72011-01-11 17:31:27354
[email protected]4cd82f72011-05-23 19:15:01355 // Make sure the initial file name is set only once.
356 DCHECK(download->full_path().empty());
357 download->OnPathDetermined(chosen_file);
[email protected]4cd82f72011-05-23 19:15:01358
359 VLOG(20) << __FUNCTION__ << "()"
360 << " download = " << download->DebugString(true);
361
362 in_progress_[download_id] = download;
[email protected]5f8589fe2011-08-17 20:58:39363 UpdateDownloadProgress(); // Reflect entry into in_progress_.
initial.commit09911bf2008-07-26 23:55:29364
[email protected]adb2f3d12011-01-23 16:24:54365 // Rename to intermediate name.
[email protected]f5920322011-03-24 20:34:16366 FilePath download_path;
[email protected]ec865262011-08-23 20:01:48367 if (!delegate_->OverrideIntermediatePath(download, &download_path))
[email protected]4cd82f72011-05-23 19:15:01368 download_path = download->full_path();
[email protected]594cd7d2010-07-21 03:23:56369
[email protected]f5920322011-03-24 20:34:16370 BrowserThread::PostTask(
371 BrowserThread::FILE, FROM_HERE,
372 NewRunnableMethod(
373 file_manager_, &DownloadFileManager::RenameInProgressDownloadFile,
[email protected]eda58402011-09-21 19:32:02374 download->global_id(), download_path));
[email protected]f5920322011-03-24 20:34:16375
376 download->Rename(download_path);
377
[email protected]2588ea9d2011-08-22 20:59:53378 delegate_->AddItemToPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29379}
380
initial.commit09911bf2008-07-26 23:55:29381void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
[email protected]70850c72011-01-11 17:31:27382 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
383 DownloadMap::iterator it = active_downloads_.find(download_id);
384 if (it != active_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29385 DownloadItem* download = it->second;
[email protected]bf68a00b2011-04-07 17:28:26386 if (download->IsInProgress()) {
[email protected]70850c72011-01-11 17:31:27387 download->Update(size);
[email protected]5f8589fe2011-08-17 20:58:39388 UpdateDownloadProgress(); // Reflect size updates.
[email protected]2588ea9d2011-08-22 20:59:53389 delegate_->UpdateItemInPersistentStore(download);
[email protected]70850c72011-01-11 17:31:27390 }
initial.commit09911bf2008-07-26 23:55:29391 }
392}
393
[email protected]bf68a00b2011-04-07 17:28:26394void DownloadManager::OnResponseCompleted(int32 download_id,
395 int64 size,
[email protected]bf68a00b2011-04-07 17:28:26396 const std::string& hash) {
[email protected]33c6d3f12011-09-04 00:00:54397 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]da6e3922010-11-24 21:45:50398 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
399 << " size = " << size;
[email protected]9d7ef802011-02-25 19:03:35400 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:32401
[email protected]c4f02c42011-01-24 21:55:06402 // If it's not in active_downloads_, that means it was cancelled; just
403 // ignore the notification.
404 if (active_downloads_.count(download_id) == 0)
405 return;
406
[email protected]adb2f3d12011-01-23 16:24:54407 DownloadItem* download = active_downloads_[download_id];
[email protected]a850ba42010-09-10 22:00:30408 download->OnAllDataSaved(size);
[email protected]9ccbb372008-10-10 18:50:32409
[email protected]b09f1282011-09-14 00:37:45410 delegate_->OnResponseCompleted(download, hash);
411
[email protected]adb2f3d12011-01-23 16:24:54412 MaybeCompleteDownload(download);
413}
[email protected]9ccbb372008-10-10 18:50:32414
[email protected]7d413112011-06-16 18:50:17415void DownloadManager::AssertQueueStateConsistent(DownloadItem* download) {
[email protected]5cd11b6e2011-06-10 20:30:59416 // TODO(rdsmith): Change to DCHECK after http://crbug.com/85408 resolved.
[email protected]7d413112011-06-16 18:50:17417 if (download->state() == DownloadItem::REMOVING) {
418 CHECK(!ContainsKey(downloads_, download));
419 CHECK(!ContainsKey(active_downloads_, download->id()));
420 CHECK(!ContainsKey(in_progress_, download->id()));
421 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
422 return;
423 }
424
425 // Should be in downloads_ if we're not REMOVING.
426 CHECK(ContainsKey(downloads_, download));
427
428 // Check history_downloads_ consistency.
[email protected]2588ea9d2011-08-22 20:59:53429 if (download->db_handle() != DownloadItem::kUninitializedHandle) {
[email protected]7d413112011-06-16 18:50:17430 CHECK(ContainsKey(history_downloads_, download->db_handle()));
431 } else {
432 // TODO(rdsmith): Somewhat painful; make sure to disable in
433 // release builds after resolution of http://crbug.com/85408.
434 for (DownloadMap::iterator it = history_downloads_.begin();
435 it != history_downloads_.end(); ++it) {
436 CHECK(it->second != download);
437 }
438 }
439
[email protected]61b75a52011-08-29 16:34:34440 int64 state = download->state();
441 base::debug::Alias(&state);
[email protected]f9a2997f2011-09-23 16:54:07442 if (ContainsKey(active_downloads_, download->id())) {
443 if (download->db_handle() != DownloadItem::kUninitializedHandle)
444 CHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
445 if (DownloadItem::IN_PROGRESS != download->state())
446 CHECK_EQ(DownloadItem::kUninitializedHandle, download->db_handle());
447 }
[email protected]821960a2011-08-23 20:40:03448 if (DownloadItem::IN_PROGRESS == download->state())
449 CHECK(ContainsKey(active_downloads_, download->id()));
[email protected]5cd11b6e2011-06-10 20:30:59450}
451
[email protected]adb2f3d12011-01-23 16:24:54452bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
453 // If we don't have all the data, the download is not ready for
454 // completion.
455 if (!download->all_data_saved())
456 return false;
[email protected]6a7fb042010-02-01 16:30:47457
[email protected]9d7ef802011-02-25 19:03:35458 // If the download is dangerous, but not yet validated, it's not ready for
459 // completion.
460 if (download->safety_state() == DownloadItem::DANGEROUS)
461 return false;
462
[email protected]adb2f3d12011-01-23 16:24:54463 // If the download isn't active (e.g. has been cancelled) it's not
464 // ready for completion.
465 if (active_downloads_.count(download->id()) == 0)
466 return false;
467
468 // If the download hasn't been inserted into the history system
469 // (which occurs strictly after file name determination, intermediate
470 // file rename, and UI display) then it's not ready for completion.
[email protected]2588ea9d2011-08-22 20:59:53471 if (download->db_handle() == DownloadItem::kUninitializedHandle)
[email protected]7054b592011-06-22 14:46:42472 return false;
473
474 return true;
[email protected]adb2f3d12011-01-23 16:24:54475}
476
477void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
478 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
479 VLOG(20) << __FUNCTION__ << "()" << " download = "
480 << download->DebugString(false);
481
482 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32483 return;
[email protected]9ccbb372008-10-10 18:50:32484
[email protected]adb2f3d12011-01-23 16:24:54485 // TODO(rdsmith): DCHECK that we only pass through this point
486 // once per download. The natural way to do this is by a state
487 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56488
[email protected]adb2f3d12011-01-23 16:24:54489 // Confirm we're in the proper set of states to be here;
[email protected]9d7ef802011-02-25 19:03:35490 // in in_progress_, have all data, have a history handle, (validated or safe).
491 DCHECK_NE(DownloadItem::DANGEROUS, download->safety_state());
[email protected]adb2f3d12011-01-23 16:24:54492 DCHECK_EQ(1u, in_progress_.count(download->id()));
493 DCHECK(download->all_data_saved());
[email protected]2588ea9d2011-08-22 20:59:53494 DCHECK(download->db_handle() != DownloadItem::kUninitializedHandle);
[email protected]adb2f3d12011-01-23 16:24:54495 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
496
497 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
498 << download->DebugString(false);
499
500 // Remove the id from in_progress
501 in_progress_.erase(download->id());
[email protected]5f8589fe2011-08-17 20:58:39502 UpdateDownloadProgress(); // Reflect removal from in_progress_.
[email protected]adb2f3d12011-01-23 16:24:54503
[email protected]2588ea9d2011-08-22 20:59:53504 delegate_->UpdateItemInPersistentStore(download);
[email protected]adb2f3d12011-01-23 16:24:54505
[email protected]f5920322011-03-24 20:34:16506 // Finish the download.
[email protected]48837962011-04-19 17:03:29507 download->OnDownloadCompleting(file_manager_);
[email protected]9ccbb372008-10-10 18:50:32508}
509
[email protected]cc3c7c092011-05-09 18:40:21510void DownloadManager::DownloadCompleted(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27511 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21512 DownloadItem* download = GetDownloadItem(download_id);
513 DCHECK(download);
[email protected]2588ea9d2011-08-22 20:59:53514 delegate_->UpdateItemInPersistentStore(download);
[email protected]70850c72011-01-11 17:31:27515 active_downloads_.erase(download_id);
[email protected]821960a2011-08-23 20:40:03516 AssertQueueStateConsistent(download);
[email protected]70850c72011-01-11 17:31:27517}
518
[email protected]f5920322011-03-24 20:34:16519void DownloadManager::OnDownloadRenamedToFinalName(int download_id,
520 const FilePath& full_path,
521 int uniquifier) {
[email protected]da6e3922010-11-24 21:45:50522 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
[email protected]f5920322011-03-24 20:34:16523 << " full_path = \"" << full_path.value() << "\""
524 << " uniquifier = " << uniquifier;
[email protected]ca4b5fa32010-10-09 12:42:18525 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]f5920322011-03-24 20:34:16526
[email protected]2e030682010-07-23 19:45:36527 DownloadItem* item = GetDownloadItem(download_id);
528 if (!item)
529 return;
[email protected]6cade212008-12-03 00:32:22530
[email protected]8fa1eeb52011-04-13 14:18:02531 if (item->safety_state() == DownloadItem::SAFE) {
532 DCHECK_EQ(0, uniquifier) << "We should not uniquify SAFE downloads twice";
533 }
534
[email protected]eda58402011-09-21 19:32:02535 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(
536 file_manager_,
537 &DownloadFileManager::CompleteDownload,
538 item->global_id()));
[email protected]9ccbb372008-10-10 18:50:32539
[email protected]f5920322011-03-24 20:34:16540 if (uniquifier)
541 item->set_path_uniquifier(uniquifier);
[email protected]9ccbb372008-10-10 18:50:32542
[email protected]f5920322011-03-24 20:34:16543 item->OnDownloadRenamedToFinalName(full_path);
[email protected]2588ea9d2011-08-22 20:59:53544 delegate_->UpdatePathForItemInPersistentStore(item, full_path);
initial.commit09911bf2008-07-26 23:55:29545}
546
[email protected]93af2272011-09-21 18:29:17547void DownloadManager::CancelDownload(int32 download_id) {
548 DownloadItem* download = GetActiveDownload(download_id);
549 // A cancel at the right time could remove the download from the
550 // |active_downloads_| map before we get here.
551 if (!download)
552 return;
553
554 download->Cancel(true);
555}
556
557void DownloadManager::DownloadCancelledInternal(DownloadItem* download) {
[email protected]d8472d92011-08-26 20:15:20558 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d8472d92011-08-26 20:15:20559
560 VLOG(20) << __FUNCTION__ << "()"
[email protected]da6e3922010-11-24 21:45:50561 << " download = " << download->DebugString(true);
562
[email protected]93af2272011-09-21 18:29:17563 RemoveFromActiveList(download);
[email protected]47a881b2011-08-29 22:59:21564 // This function is called from the DownloadItem, so DI state
565 // should already have been updated.
566 AssertQueueStateConsistent(download);
initial.commit09911bf2008-07-26 23:55:29567
[email protected]d8472d92011-08-26 20:15:20568 download->OffThreadCancel(file_manager_);
initial.commit09911bf2008-07-26 23:55:29569}
570
[email protected]be76b7e2011-10-13 12:57:57571void DownloadManager::OnDownloadInterrupted(int32 download_id,
572 int64 size,
573 InterruptReason reason) {
[email protected]47a881b2011-08-29 22:59:21574 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
575
576 DownloadItem* download = GetActiveDownload(download_id);
577 if (!download)
578 return;
579
[email protected]be76b7e2011-10-13 12:57:57580 VLOG(20) << __FUNCTION__ << "()"
581 << " reason " << InterruptReasonDebugString(reason)
[email protected]47a881b2011-08-29 22:59:21582 << " at offset " << download->received_bytes()
583 << " size = " << size
584 << " download = " << download->DebugString(true);
585
[email protected]93af2272011-09-21 18:29:17586 RemoveFromActiveList(download);
[email protected]be76b7e2011-10-13 12:57:57587 download->Interrupted(size, reason);
[email protected]93af2272011-09-21 18:29:17588 download->OffThreadCancel(file_manager_);
[email protected]47a881b2011-08-29 22:59:21589}
590
591DownloadItem* DownloadManager::GetActiveDownload(int32 download_id) {
[email protected]bf68a00b2011-04-07 17:28:26592 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
593 DownloadMap::iterator it = active_downloads_.find(download_id);
[email protected]bf68a00b2011-04-07 17:28:26594 if (it == active_downloads_.end())
[email protected]47a881b2011-08-29 22:59:21595 return NULL;
[email protected]bf68a00b2011-04-07 17:28:26596
597 DownloadItem* download = it->second;
598
[email protected]47a881b2011-08-29 22:59:21599 DCHECK(download);
600 DCHECK_EQ(download_id, download->id());
[email protected]4cd82f72011-05-23 19:15:01601
[email protected]47a881b2011-08-29 22:59:21602 return download;
603}
[email protected]54610672011-07-18 18:24:43604
[email protected]93af2272011-09-21 18:29:17605void DownloadManager::RemoveFromActiveList(DownloadItem* download) {
606 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
607 DCHECK(download);
608
609 // Clean up will happen when the history system create callback runs if we
610 // don't have a valid db_handle yet.
611 if (download->db_handle() != DownloadItem::kUninitializedHandle) {
612 in_progress_.erase(download->id());
613 active_downloads_.erase(download->id());
614 UpdateDownloadProgress(); // Reflect removal from in_progress_.
615 delegate_->UpdateItemInPersistentStore(download);
616 }
617}
618
[email protected]9bb54ee2011-10-12 17:43:35619void DownloadManager::SetDownloadManagerDelegate(
620 DownloadManagerDelegate* delegate) {
621 delegate_ = delegate;
622}
623
[email protected]5f8589fe2011-08-17 20:58:39624void DownloadManager::UpdateDownloadProgress() {
625 delegate_->DownloadProgressUpdated();
[email protected]6a7fb042010-02-01 16:30:47626}
627
[email protected]6d0146c2011-08-04 19:13:04628int DownloadManager::RemoveDownloadItems(
629 const DownloadVector& pending_deletes) {
630 if (pending_deletes.empty())
631 return 0;
632
633 // Delete from internal maps.
634 for (DownloadVector::const_iterator it = pending_deletes.begin();
635 it != pending_deletes.end();
636 ++it) {
637 DownloadItem* download = *it;
638 DCHECK(download);
639 history_downloads_.erase(download->db_handle());
640 save_page_downloads_.erase(download->id());
641 downloads_.erase(download);
642 }
643
644 // Tell observers to refresh their views.
645 NotifyModelChanged();
646
647 // Delete the download items themselves.
648 const int num_deleted = static_cast<int>(pending_deletes.size());
649 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
650 return num_deleted;
651}
652
[email protected]93af2272011-09-21 18:29:17653void DownloadManager::RemoveDownload(int64 download_handle) {
654 DownloadMap::iterator it = history_downloads_.find(download_handle);
655 if (it == history_downloads_.end())
656 return;
657
658 // Make history update.
659 DownloadItem* download = it->second;
660 delegate_->RemoveItemFromPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29661
662 // Remove from our tables and delete.
[email protected]6d0146c2011-08-04 19:13:04663 int downloads_count = RemoveDownloadItems(DownloadVector(1, download));
[email protected]f04182f32010-12-10 19:12:07664 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29665}
666
[email protected]e93d2822009-01-30 05:59:59667int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
668 const base::Time remove_end) {
[email protected]2588ea9d2011-08-22 20:59:53669 delegate_->RemoveItemsFromPersistentStoreBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29670
[email protected]a312a442010-12-15 23:40:33671 // All downloads visible to the user will be in the history,
672 // so scan that map.
[email protected]6d0146c2011-08-04 19:13:04673 DownloadVector pending_deletes;
674 for (DownloadMap::const_iterator it = history_downloads_.begin();
675 it != history_downloads_.end();
676 ++it) {
initial.commit09911bf2008-07-26 23:55:29677 DownloadItem* download = it->second;
initial.commit09911bf2008-07-26 23:55:29678 if (download->start_time() >= remove_begin &&
679 (remove_end.is_null() || download->start_time() < remove_end) &&
[email protected]6d0146c2011-08-04 19:13:04680 (download->IsComplete() || download->IsCancelled())) {
[email protected]7d413112011-06-16 18:50:17681 AssertQueueStateConsistent(download);
[email protected]78b8fcc92009-03-31 17:36:28682 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29683 }
initial.commit09911bf2008-07-26 23:55:29684 }
[email protected]6d0146c2011-08-04 19:13:04685 return RemoveDownloadItems(pending_deletes);
initial.commit09911bf2008-07-26 23:55:29686}
687
[email protected]e93d2822009-01-30 05:59:59688int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
689 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29690}
691
[email protected]d41355e6f2009-04-07 21:21:12692int DownloadManager::RemoveAllDownloads() {
[email protected]da4a5582011-10-17 19:08:06693 download_stats::RecordClearAllSize(history_downloads_.size());
[email protected]d41355e6f2009-04-07 21:21:12694 // The null times make the date range unbounded.
695 return RemoveDownloadsBetween(base::Time(), base::Time());
696}
697
initial.commit09911bf2008-07-26 23:55:29698// Initiate a download of a specific URL. We send the request to the
699// ResourceDispatcherHost, and let it send us responses like a regular
700// download.
701void DownloadManager::DownloadUrl(const GURL& url,
702 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50703 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34704 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26705 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
706 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58707}
708
709void DownloadManager::DownloadUrlToFile(const GURL& url,
710 const GURL& referrer,
711 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32712 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58713 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34714 DCHECK(tab_contents);
[email protected]c79a0c02011-08-22 22:37:37715 ResourceDispatcherHost* resource_dispatcher_host =
716 content::GetContentClient()->browser()->GetResourceDispatcherHost();
[email protected]ed24fad2011-05-10 22:44:01717 // We send a pointer to content::ResourceContext, instead of the usual
718 // reference, so that a copy of the object isn't made.
[email protected]ca4b5fa32010-10-09 12:42:18719 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]a0ce3282011-08-19 20:49:52720 NewRunnableFunction(&BeginDownload,
[email protected]ae8945192010-07-20 16:56:26721 url,
722 referrer,
[email protected]ae8945192010-07-20 16:56:26723 save_info,
[email protected]c79a0c02011-08-22 22:37:37724 resource_dispatcher_host,
[email protected]ae8945192010-07-20 16:56:26725 tab_contents->GetRenderProcessHost()->id(),
726 tab_contents->render_view_host()->routing_id(),
[email protected]cafe4ad2011-07-28 18:34:56727 &tab_contents->browser_context()->
728 GetResourceContext()));
initial.commit09911bf2008-07-26 23:55:29729}
730
initial.commit09911bf2008-07-26 23:55:29731void DownloadManager::AddObserver(Observer* observer) {
732 observers_.AddObserver(observer);
733 observer->ModelChanged();
734}
735
736void DownloadManager::RemoveObserver(Observer* observer) {
737 observers_.RemoveObserver(observer);
738}
739
[email protected]073ed7b2010-09-27 09:20:02740bool DownloadManager::IsDownloadProgressKnown() {
741 for (DownloadMap::iterator i = in_progress_.begin();
742 i != in_progress_.end(); ++i) {
743 if (i->second->total_bytes() <= 0)
744 return false;
745 }
746
747 return true;
748}
749
750int64 DownloadManager::GetInProgressDownloadCount() {
751 return in_progress_.size();
752}
753
754int64 DownloadManager::GetReceivedDownloadBytes() {
755 DCHECK(IsDownloadProgressKnown());
756 int64 received_bytes = 0;
757 for (DownloadMap::iterator i = in_progress_.begin();
758 i != in_progress_.end(); ++i) {
759 received_bytes += i->second->received_bytes();
760 }
761 return received_bytes;
762}
763
764int64 DownloadManager::GetTotalDownloadBytes() {
765 DCHECK(IsDownloadProgressKnown());
766 int64 total_bytes = 0;
767 for (DownloadMap::iterator i = in_progress_.begin();
768 i != in_progress_.end(); ++i) {
769 total_bytes += i->second->total_bytes();
770 }
771 return total_bytes;
772}
773
[email protected]99cb7f82011-07-28 17:27:26774void DownloadManager::FileSelected(const FilePath& path, void* params) {
[email protected]4cd82f72011-05-23 19:15:01775 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
776
777 int32* id_ptr = reinterpret_cast<int32*>(params);
778 DCHECK(id_ptr != NULL);
779 int32 download_id = *id_ptr;
780 delete id_ptr;
781
782 DownloadItem* download = GetActiveDownloadItem(download_id);
783 if (!download)
784 return;
785 VLOG(20) << __FUNCTION__ << "()" << " path = \"" << path.value() << "\""
786 << " download = " << download->DebugString(true);
787
[email protected]da1a27b2011-07-29 23:16:33788 if (download->prompt_user_for_save_location())
[email protected]7ae7c2cb2009-01-06 23:31:41789 last_download_path_ = path.DirName();
[email protected]287b86b2011-02-26 00:11:35790
[email protected]4cd82f72011-05-23 19:15:01791 // Make sure the initial file name is set only once.
792 ContinueDownloadWithPath(download, path);
initial.commit09911bf2008-07-26 23:55:29793}
794
795void DownloadManager::FileSelectionCanceled(void* params) {
796 // The user didn't pick a place to save the file, so need to cancel the
797 // download that's already in progress to the temporary location.
[email protected]4cd82f72011-05-23 19:15:01798 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
799 int32* id_ptr = reinterpret_cast<int32*>(params);
800 DCHECK(id_ptr != NULL);
801 int32 download_id = *id_ptr;
802 delete id_ptr;
803
804 DownloadItem* download = GetActiveDownloadItem(download_id);
805 if (!download)
806 return;
807
808 VLOG(20) << __FUNCTION__ << "()"
809 << " download = " << download->DebugString(true);
810
[email protected]93af2272011-09-21 18:29:17811 // TODO(ahendrickson) -- This currently has no effect, as the download is
812 // not put on the active list until the file selection is complete. Need
813 // to put it on the active list earlier in the process.
814 RemoveFromActiveList(download);
815
816 download->OffThreadCancel(file_manager_);
[email protected]4cd82f72011-05-23 19:15:01817}
818
initial.commit09911bf2008-07-26 23:55:29819// Operations posted to us from the history service ----------------------------
820
821// The history service has retrieved all download entries. 'entries' contains
[email protected]bb1a4212011-08-22 22:38:25822// 'DownloadPersistentStoreInfo's in sorted order (by ascending start_time).
[email protected]2588ea9d2011-08-22 20:59:53823void DownloadManager::OnPersistentStoreQueryComplete(
[email protected]bb1a4212011-08-22 22:38:25824 std::vector<DownloadPersistentStoreInfo>* entries) {
[email protected]d8472d92011-08-26 20:15:20825 // TODO(rdsmith): Remove this and related logic when
[email protected]639ddad2011-10-05 02:53:47826 // http://crbug.com/85408 is fixed.
[email protected]d8472d92011-08-26 20:15:20827 largest_db_handle_in_history_ = 0;
828
initial.commit09911bf2008-07-26 23:55:29829 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:39830 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]d8472d92011-08-26 20:15:20831 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]821960a2011-08-23 20:40:03832 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
[email protected]f04182f32010-12-10 19:12:07833 downloads_.insert(download);
834 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:50835 VLOG(20) << __FUNCTION__ << "()" << i << ">"
836 << " download = " << download->DebugString(true);
[email protected]d8472d92011-08-26 20:15:20837
838 if (download->db_handle() > largest_db_handle_in_history_)
839 largest_db_handle_in_history_ = download->db_handle();
initial.commit09911bf2008-07-26 23:55:29840 }
[email protected]b0ab1d42010-02-24 19:29:28841 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:48842 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:29843}
844
[email protected]f9a45b02011-06-30 23:49:19845void DownloadManager::AddDownloadItemToHistory(DownloadItem* download,
846 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:27847 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d2a8fb72010-01-21 05:31:42848
[email protected]639ddad2011-10-05 02:53:47849 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/85408
[email protected]1e9fe7ff2011-06-24 17:37:33850 // is fixed.
[email protected]2588ea9d2011-08-22 20:59:53851 CHECK_NE(DownloadItem::kUninitializedHandle, db_handle);
[email protected]1e9fe7ff2011-06-24 17:37:33852
[email protected]da4a5582011-10-17 19:08:06853 download_stats::RecordHistorySize(history_downloads_.size());
854
[email protected]2588ea9d2011-08-22 20:59:53855 DCHECK(download->db_handle() == DownloadItem::kUninitializedHandle);
[email protected]5bcd73eb2011-03-23 21:14:02856 download->set_db_handle(db_handle);
857
[email protected]639ddad2011-10-05 02:53:47858 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/85408
[email protected]d8472d92011-08-26 20:15:20859 // is fixed.
[email protected]821960a2011-08-23 20:40:03860 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
[email protected]5bcd73eb2011-03-23 21:14:02861 history_downloads_[download->db_handle()] = download;
[email protected]6d0146c2011-08-04 19:13:04862
863 // Show in the appropriate browser UI.
864 // This includes buttons to save or cancel, for a dangerous download.
865 ShowDownloadInBrowser(download);
866
867 // Inform interested objects about the new download.
868 NotifyModelChanged();
[email protected]f9a45b02011-06-30 23:49:19869}
870
[email protected]2588ea9d2011-08-22 20:59:53871
872void DownloadManager::OnItemAddedToPersistentStore(int32 download_id,
873 int64 db_handle) {
874 if (save_page_downloads_.count(download_id)) {
875 OnSavePageItemAddedToPersistentStore(download_id, db_handle);
876 } else if (active_downloads_.count(download_id)) {
877 OnDownloadItemAddedToPersistentStore(download_id, db_handle);
878 }
879 // It's valid that we don't find a matching item, i.e. on shutdown.
880}
881
[email protected]f9a45b02011-06-30 23:49:19882// Once the new DownloadItem's creation info has been committed to the history
883// service, we associate the DownloadItem with the db handle, update our
884// 'history_downloads_' map and inform observers.
[email protected]2588ea9d2011-08-22 20:59:53885void DownloadManager::OnDownloadItemAddedToPersistentStore(int32 download_id,
886 int64 db_handle) {
[email protected]f9a45b02011-06-30 23:49:19887 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]19420cc2011-07-18 17:43:45888 DownloadItem* download = GetActiveDownloadItem(download_id);
[email protected]93af2272011-09-21 18:29:17889 if (!download)
[email protected]19420cc2011-07-18 17:43:45890 return;
[email protected]54610672011-07-18 18:24:43891
892 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
893 << " download_id = " << download_id
894 << " download = " << download->DebugString(true);
[email protected]f9a45b02011-06-30 23:49:19895
[email protected]d8472d92011-08-26 20:15:20896 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]d8472d92011-08-26 20:15:20897 int64 largest_handle = largest_db_handle_in_history_;
898 base::debug::Alias(&largest_handle);
[email protected]e5107ce2011-09-19 20:36:13899 int32 matching_item_download_id
900 = (ContainsKey(history_downloads_, db_handle) ?
901 history_downloads_[db_handle]->id() : 0);
902 base::debug::Alias(&matching_item_download_id);
903
[email protected]61b75a52011-08-29 16:34:34904 CHECK(!ContainsKey(history_downloads_, db_handle));
[email protected]d8472d92011-08-26 20:15:20905
[email protected]f9a45b02011-06-30 23:49:19906 AddDownloadItemToHistory(download, db_handle);
initial.commit09911bf2008-07-26 23:55:29907
[email protected]93af2272011-09-21 18:29:17908 // If the download is still in progress, try to complete it.
909 //
910 // Otherwise, download has been cancelled or interrupted before we've
911 // received the DB handle. We post one final message to the history
912 // service so that it can be properly in sync with the DownloadItem's
913 // completion status, and also inform any observers so that they get
914 // more than just the start notification.
915 if (download->IsInProgress()) {
916 MaybeCompleteDownload(download);
917 } else {
[email protected]639ddad2011-10-05 02:53:47918 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/85408
[email protected]93af2272011-09-21 18:29:17919 // is fixed.
920 CHECK(download->IsCancelled())
921 << " download = " << download->DebugString(true);
922 in_progress_.erase(download_id);
923 active_downloads_.erase(download_id);
924 delegate_->UpdateItemInPersistentStore(download);
925 download->UpdateObservers();
926 }
initial.commit09911bf2008-07-26 23:55:29927}
928
[email protected]4cd82f72011-05-23 19:15:01929void DownloadManager::ShowDownloadInBrowser(DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:34930 // The 'contents' may no longer exist if the user closed the tab before we
[email protected]99cb7f82011-07-28 17:27:26931 // get this start completion event.
[email protected]db6831a2011-06-09 21:08:28932 DownloadRequestHandle request_handle = download->request_handle();
[email protected]686493142011-07-15 21:47:22933 TabContents* content = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:26934
935 // If the contents no longer exists, we ask the embedder to suggest another
936 // tab.
[email protected]da1a27b2011-07-29 23:16:33937 if (!content)
[email protected]aa9881c2011-08-15 18:01:12938 content = delegate_->GetAlternativeTabContentsToNotifyForDownload();
[email protected]5e595482009-05-06 20:16:53939
[email protected]99cb7f82011-07-28 17:27:26940 if (content)
941 content->OnStartDownload(download);
[email protected]5e595482009-05-06 20:16:53942}
943
[email protected]6cade212008-12-03 00:32:22944// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:12945void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:41946 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:38947}
[email protected]b0ab1d42010-02-24 19:29:28948
949void DownloadManager::NotifyModelChanged() {
950 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
951}
952
[email protected]4cd82f72011-05-23 19:15:01953DownloadItem* DownloadManager::GetDownloadItem(int download_id) {
954 // The |history_downloads_| map is indexed by the download's db_handle,
955 // not its id, so we have to iterate.
[email protected]f04182f32010-12-10 19:12:07956 for (DownloadMap::iterator it = history_downloads_.begin();
957 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:36958 DownloadItem* item = it->second;
[email protected]4cd82f72011-05-23 19:15:01959 if (item->id() == download_id)
[email protected]2e030682010-07-23 19:45:36960 return item;
961 }
962 return NULL;
963}
964
[email protected]4cd82f72011-05-23 19:15:01965DownloadItem* DownloadManager::GetActiveDownloadItem(int download_id) {
[email protected]93af2272011-09-21 18:29:17966 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]4cd82f72011-05-23 19:15:01967 DownloadItem* download = active_downloads_[download_id];
968 DCHECK(download != NULL);
969 return download;
970}
971
[email protected]57fd1252010-12-23 17:24:09972// Confirm that everything in all maps is also in |downloads_|, and that
973// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:07974void DownloadManager::AssertContainersConsistent() const {
975#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:09976 // Turn everything into sets.
[email protected]6d0146c2011-08-04 19:13:04977 const DownloadMap* input_maps[] = {&active_downloads_,
978 &history_downloads_,
979 &save_page_downloads_};
980 DownloadSet active_set, history_set, save_page_set;
981 DownloadSet* all_sets[] = {&active_set, &history_set, &save_page_set};
982 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(all_sets));
[email protected]57fd1252010-12-23 17:24:09983 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
984 for (DownloadMap::const_iterator it = input_maps[i]->begin();
[email protected]6d0146c2011-08-04 19:13:04985 it != input_maps[i]->end(); ++it) {
986 all_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:07987 }
988 }
[email protected]57fd1252010-12-23 17:24:09989
990 // Check if each set is fully present in downloads, and create a union.
[email protected]57fd1252010-12-23 17:24:09991 DownloadSet downloads_union;
992 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
993 DownloadSet remainder;
994 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
995 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
996 downloads_.begin(), downloads_.end(),
997 insert_it);
998 DCHECK(remainder.empty());
999 std::insert_iterator<DownloadSet>
1000 insert_union(downloads_union, downloads_union.end());
1001 std::set_union(downloads_union.begin(), downloads_union.end(),
1002 all_sets[i]->begin(), all_sets[i]->end(),
1003 insert_union);
1004 }
1005
1006 // Is everything in downloads_ present in one of the other sets?
1007 DownloadSet remainder;
1008 std::insert_iterator<DownloadSet>
1009 insert_remainder(remainder, remainder.begin());
1010 std::set_difference(downloads_.begin(), downloads_.end(),
1011 downloads_union.begin(), downloads_union.end(),
1012 insert_remainder);
1013 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071014#endif
1015}
1016
[email protected]6d0146c2011-08-04 19:13:041017void DownloadManager::SavePageDownloadStarted(DownloadItem* download) {
1018 DCHECK(!ContainsKey(save_page_downloads_, download->id()));
1019 downloads_.insert(download);
1020 save_page_downloads_[download->id()] = download;
1021
1022 // Add this entry to the history service.
1023 // Additionally, the UI is notified in the callback.
[email protected]2588ea9d2011-08-22 20:59:531024 delegate_->AddItemToPersistentStore(download);
[email protected]6d0146c2011-08-04 19:13:041025}
1026
1027// SavePackage will call SavePageDownloadFinished upon completion/cancellation.
[email protected]2588ea9d2011-08-22 20:59:531028// The history callback will call OnSavePageItemAddedToPersistentStore.
[email protected]6d0146c2011-08-04 19:13:041029// If the download finishes before the history callback,
[email protected]2588ea9d2011-08-22 20:59:531030// OnSavePageItemAddedToPersistentStore calls SavePageDownloadFinished, ensuring
1031// that the history event is update regardless of the order in which these two
1032// events complete.
[email protected]6d0146c2011-08-04 19:13:041033// If something removes the download item from the download manager (Remove,
1034// Shutdown) the result will be that the SavePage system will not be able to
1035// properly update the download item (which no longer exists) or the download
1036// history, but the action will complete properly anyway. This may lead to the
1037// history entry being wrong on a reload of chrome (specifically in the case of
1038// Initiation -> History Callback -> Removal -> Completion), but there's no way
1039// to solve that without canceling on Remove (which would then update the DB).
1040
[email protected]2588ea9d2011-08-22 20:59:531041void DownloadManager::OnSavePageItemAddedToPersistentStore(int32 download_id,
1042 int64 db_handle) {
[email protected]6d0146c2011-08-04 19:13:041043 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1044
1045 DownloadMap::const_iterator it = save_page_downloads_.find(download_id);
1046 // This can happen if the download manager is shutting down and all maps
1047 // have been cleared.
1048 if (it == save_page_downloads_.end())
1049 return;
1050
1051 DownloadItem* download = it->second;
1052 if (!download) {
1053 NOTREACHED();
1054 return;
1055 }
1056
[email protected]d8472d92011-08-26 20:15:201057 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]d8472d92011-08-26 20:15:201058 int64 largest_handle = largest_db_handle_in_history_;
1059 base::debug::Alias(&largest_handle);
[email protected]61b75a52011-08-29 16:34:341060 CHECK(!ContainsKey(history_downloads_, db_handle));
[email protected]d8472d92011-08-26 20:15:201061
[email protected]6d0146c2011-08-04 19:13:041062 AddDownloadItemToHistory(download, db_handle);
1063
1064 // Finalize this download if it finished before the history callback.
1065 if (!download->IsInProgress())
1066 SavePageDownloadFinished(download);
1067}
1068
1069void DownloadManager::SavePageDownloadFinished(DownloadItem* download) {
[email protected]2588ea9d2011-08-22 20:59:531070 if (download->db_handle() != DownloadItem::kUninitializedHandle) {
1071 delegate_->UpdateItemInPersistentStore(download);
[email protected]6d0146c2011-08-04 19:13:041072 DCHECK(ContainsKey(save_page_downloads_, download->id()));
1073 save_page_downloads_.erase(download->id());
1074
1075 if (download->IsComplete())
1076 NotificationService::current()->Notify(
1077 content::NOTIFICATION_SAVE_PACKAGE_SUCCESSFULLY_FINISHED,
[email protected]6c2381d2011-10-19 02:52:531078 content::Source<DownloadManager>(this),
1079 content::Details<DownloadItem>(download));
[email protected]6d0146c2011-08-04 19:13:041080 }
1081}
[email protected]da4a5582011-10-17 19:08:061082
1083void DownloadManager::MarkDownloadOpened(DownloadItem* download) {
1084 delegate_->UpdateItemInPersistentStore(download);
1085 int num_unopened = 0;
1086 for (DownloadMap::iterator it = history_downloads_.begin();
1087 it != history_downloads_.end(); ++it) {
1088 if (it->second->IsComplete() && !it->second->opened())
1089 ++num_unopened;
1090 }
1091 download_stats::RecordOpensOutstanding(num_unopened);
1092}