blob: 890c9bc65c03aa361b3f18f770e408cec6abf0ff [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]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]bb1a4212011-08-22 22:38:2525#include "content/browser/download/download_persistent_store_info.h"
[email protected]da4a5582011-10-17 19:08:0626#include "content/browser/download/download_stats.h"
[email protected]71bf3f5e2011-08-15 21:05:2227#include "content/browser/download/download_status_updater.h"
[email protected]be76b7e2011-10-13 12:57:5728#include "content/browser/download/interrupt_reasons.h"
[email protected]7324d1d2011-03-01 05:02:1629#include "content/browser/renderer_host/render_process_host.h"
30#include "content/browser/renderer_host/render_view_host.h"
31#include "content/browser/renderer_host/resource_dispatcher_host.h"
32#include "content/browser/tab_contents/tab_contents.h"
[email protected]87f3c082011-10-19 18:07:4433#include "content/public/browser/content_browser_client.h"
[email protected]1bd0ef12011-10-20 05:24:1734#include "content/public/browser/download_manager_delegate.h"
[email protected]ad50def52011-10-19 23:17:0735#include "content/public/browser/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]1bd0ef12011-10-20 05:24:1762DownloadManager::DownloadManager(content::DownloadManagerDelegate* delegate,
[email protected]da1a27b2011-07-29 23:16:3363 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]594e66fe2011-10-25 22:49:41328void DownloadManager::CreateDownloadItem(
329 DownloadCreateInfo* info, const DownloadRequestHandle& request_handle) {
[email protected]c2e76012010-12-23 21:10:29330 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
331
332 DownloadItem* download = new DownloadItem(this, *info,
[email protected]594e66fe2011-10-25 22:49:41333 request_handle,
[email protected]6d0c9fb2011-08-22 19:26:03334 browser_context_->IsOffTheRecord());
[email protected]4cd82f72011-05-23 19:15:01335 int32 download_id = info->download_id;
336 DCHECK(!ContainsKey(in_progress_, download_id));
[email protected]d8472d92011-08-26 20:15:20337
338 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]821960a2011-08-23 20:40:03339 CHECK(!ContainsKey(active_downloads_, download_id));
[email protected]c2e76012010-12-23 21:10:29340 downloads_.insert(download);
[email protected]4cd82f72011-05-23 19:15:01341 active_downloads_[download_id] = download;
[email protected]c2e76012010-12-23 21:10:29342}
343
[email protected]4cd82f72011-05-23 19:15:01344void DownloadManager::ContinueDownloadWithPath(DownloadItem* download,
345 const FilePath& chosen_file) {
[email protected]ca4b5fa32010-10-09 12:42:18346 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]4cd82f72011-05-23 19:15:01347 DCHECK(download);
[email protected]aa033af2010-07-27 18:16:39348
[email protected]4cd82f72011-05-23 19:15:01349 int32 download_id = download->id();
initial.commit09911bf2008-07-26 23:55:29350
[email protected]70850c72011-01-11 17:31:27351 // NOTE(ahendrickson) Eventually |active_downloads_| will replace
352 // |in_progress_|, but we don't want to change the semantics yet.
[email protected]4cd82f72011-05-23 19:15:01353 DCHECK(!ContainsKey(in_progress_, download_id));
[email protected]70850c72011-01-11 17:31:27354 DCHECK(ContainsKey(downloads_, download));
[email protected]4cd82f72011-05-23 19:15:01355 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]70850c72011-01-11 17:31:27356
[email protected]4cd82f72011-05-23 19:15:01357 // Make sure the initial file name is set only once.
358 DCHECK(download->full_path().empty());
359 download->OnPathDetermined(chosen_file);
[email protected]4cd82f72011-05-23 19:15:01360
361 VLOG(20) << __FUNCTION__ << "()"
362 << " download = " << download->DebugString(true);
363
364 in_progress_[download_id] = download;
[email protected]5f8589fe2011-08-17 20:58:39365 UpdateDownloadProgress(); // Reflect entry into in_progress_.
initial.commit09911bf2008-07-26 23:55:29366
[email protected]adb2f3d12011-01-23 16:24:54367 // Rename to intermediate name.
[email protected]f5920322011-03-24 20:34:16368 FilePath download_path;
[email protected]ec865262011-08-23 20:01:48369 if (!delegate_->OverrideIntermediatePath(download, &download_path))
[email protected]4cd82f72011-05-23 19:15:01370 download_path = download->full_path();
[email protected]594cd7d2010-07-21 03:23:56371
[email protected]f5920322011-03-24 20:34:16372 BrowserThread::PostTask(
373 BrowserThread::FILE, FROM_HERE,
374 NewRunnableMethod(
375 file_manager_, &DownloadFileManager::RenameInProgressDownloadFile,
[email protected]eda58402011-09-21 19:32:02376 download->global_id(), download_path));
[email protected]f5920322011-03-24 20:34:16377
378 download->Rename(download_path);
379
[email protected]2588ea9d2011-08-22 20:59:53380 delegate_->AddItemToPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29381}
382
initial.commit09911bf2008-07-26 23:55:29383void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
[email protected]70850c72011-01-11 17:31:27384 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
385 DownloadMap::iterator it = active_downloads_.find(download_id);
386 if (it != active_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29387 DownloadItem* download = it->second;
[email protected]bf68a00b2011-04-07 17:28:26388 if (download->IsInProgress()) {
[email protected]70850c72011-01-11 17:31:27389 download->Update(size);
[email protected]5f8589fe2011-08-17 20:58:39390 UpdateDownloadProgress(); // Reflect size updates.
[email protected]2588ea9d2011-08-22 20:59:53391 delegate_->UpdateItemInPersistentStore(download);
[email protected]70850c72011-01-11 17:31:27392 }
initial.commit09911bf2008-07-26 23:55:29393 }
394}
395
[email protected]bf68a00b2011-04-07 17:28:26396void DownloadManager::OnResponseCompleted(int32 download_id,
397 int64 size,
[email protected]bf68a00b2011-04-07 17:28:26398 const std::string& hash) {
[email protected]33c6d3f12011-09-04 00:00:54399 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]da6e3922010-11-24 21:45:50400 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
401 << " size = " << size;
[email protected]9d7ef802011-02-25 19:03:35402 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:32403
[email protected]c4f02c42011-01-24 21:55:06404 // If it's not in active_downloads_, that means it was cancelled; just
405 // ignore the notification.
406 if (active_downloads_.count(download_id) == 0)
407 return;
408
[email protected]adb2f3d12011-01-23 16:24:54409 DownloadItem* download = active_downloads_[download_id];
[email protected]a850ba42010-09-10 22:00:30410 download->OnAllDataSaved(size);
[email protected]9ccbb372008-10-10 18:50:32411
[email protected]b09f1282011-09-14 00:37:45412 delegate_->OnResponseCompleted(download, hash);
413
[email protected]adb2f3d12011-01-23 16:24:54414 MaybeCompleteDownload(download);
415}
[email protected]9ccbb372008-10-10 18:50:32416
[email protected]7d413112011-06-16 18:50:17417void DownloadManager::AssertQueueStateConsistent(DownloadItem* download) {
[email protected]5cd11b6e2011-06-10 20:30:59418 // TODO(rdsmith): Change to DCHECK after http://crbug.com/85408 resolved.
[email protected]7d413112011-06-16 18:50:17419 if (download->state() == DownloadItem::REMOVING) {
420 CHECK(!ContainsKey(downloads_, download));
421 CHECK(!ContainsKey(active_downloads_, download->id()));
422 CHECK(!ContainsKey(in_progress_, download->id()));
423 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
424 return;
425 }
426
427 // Should be in downloads_ if we're not REMOVING.
428 CHECK(ContainsKey(downloads_, download));
429
430 // Check history_downloads_ consistency.
[email protected]2588ea9d2011-08-22 20:59:53431 if (download->db_handle() != DownloadItem::kUninitializedHandle) {
[email protected]7d413112011-06-16 18:50:17432 CHECK(ContainsKey(history_downloads_, download->db_handle()));
433 } else {
434 // TODO(rdsmith): Somewhat painful; make sure to disable in
435 // release builds after resolution of http://crbug.com/85408.
436 for (DownloadMap::iterator it = history_downloads_.begin();
437 it != history_downloads_.end(); ++it) {
438 CHECK(it->second != download);
439 }
440 }
441
[email protected]61b75a52011-08-29 16:34:34442 int64 state = download->state();
443 base::debug::Alias(&state);
[email protected]f9a2997f2011-09-23 16:54:07444 if (ContainsKey(active_downloads_, download->id())) {
445 if (download->db_handle() != DownloadItem::kUninitializedHandle)
446 CHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
447 if (DownloadItem::IN_PROGRESS != download->state())
448 CHECK_EQ(DownloadItem::kUninitializedHandle, download->db_handle());
449 }
[email protected]821960a2011-08-23 20:40:03450 if (DownloadItem::IN_PROGRESS == download->state())
451 CHECK(ContainsKey(active_downloads_, download->id()));
[email protected]5cd11b6e2011-06-10 20:30:59452}
453
[email protected]adb2f3d12011-01-23 16:24:54454bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
455 // If we don't have all the data, the download is not ready for
456 // completion.
457 if (!download->all_data_saved())
458 return false;
[email protected]6a7fb042010-02-01 16:30:47459
[email protected]9d7ef802011-02-25 19:03:35460 // If the download is dangerous, but not yet validated, it's not ready for
461 // completion.
462 if (download->safety_state() == DownloadItem::DANGEROUS)
463 return false;
464
[email protected]adb2f3d12011-01-23 16:24:54465 // If the download isn't active (e.g. has been cancelled) it's not
466 // ready for completion.
467 if (active_downloads_.count(download->id()) == 0)
468 return false;
469
470 // If the download hasn't been inserted into the history system
471 // (which occurs strictly after file name determination, intermediate
472 // file rename, and UI display) then it's not ready for completion.
[email protected]2588ea9d2011-08-22 20:59:53473 if (download->db_handle() == DownloadItem::kUninitializedHandle)
[email protected]7054b592011-06-22 14:46:42474 return false;
475
476 return true;
[email protected]adb2f3d12011-01-23 16:24:54477}
478
479void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
480 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
481 VLOG(20) << __FUNCTION__ << "()" << " download = "
482 << download->DebugString(false);
483
484 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32485 return;
[email protected]9ccbb372008-10-10 18:50:32486
[email protected]adb2f3d12011-01-23 16:24:54487 // TODO(rdsmith): DCHECK that we only pass through this point
488 // once per download. The natural way to do this is by a state
489 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56490
[email protected]adb2f3d12011-01-23 16:24:54491 // Confirm we're in the proper set of states to be here;
[email protected]9d7ef802011-02-25 19:03:35492 // in in_progress_, have all data, have a history handle, (validated or safe).
493 DCHECK_NE(DownloadItem::DANGEROUS, download->safety_state());
[email protected]adb2f3d12011-01-23 16:24:54494 DCHECK_EQ(1u, in_progress_.count(download->id()));
495 DCHECK(download->all_data_saved());
[email protected]2588ea9d2011-08-22 20:59:53496 DCHECK(download->db_handle() != DownloadItem::kUninitializedHandle);
[email protected]adb2f3d12011-01-23 16:24:54497 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
498
499 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
500 << download->DebugString(false);
501
502 // Remove the id from in_progress
503 in_progress_.erase(download->id());
[email protected]5f8589fe2011-08-17 20:58:39504 UpdateDownloadProgress(); // Reflect removal from in_progress_.
[email protected]adb2f3d12011-01-23 16:24:54505
[email protected]2588ea9d2011-08-22 20:59:53506 delegate_->UpdateItemInPersistentStore(download);
[email protected]adb2f3d12011-01-23 16:24:54507
[email protected]f5920322011-03-24 20:34:16508 // Finish the download.
[email protected]48837962011-04-19 17:03:29509 download->OnDownloadCompleting(file_manager_);
[email protected]9ccbb372008-10-10 18:50:32510}
511
[email protected]cc3c7c092011-05-09 18:40:21512void DownloadManager::DownloadCompleted(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27513 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21514 DownloadItem* download = GetDownloadItem(download_id);
515 DCHECK(download);
[email protected]2588ea9d2011-08-22 20:59:53516 delegate_->UpdateItemInPersistentStore(download);
[email protected]70850c72011-01-11 17:31:27517 active_downloads_.erase(download_id);
[email protected]821960a2011-08-23 20:40:03518 AssertQueueStateConsistent(download);
[email protected]70850c72011-01-11 17:31:27519}
520
[email protected]f5920322011-03-24 20:34:16521void DownloadManager::OnDownloadRenamedToFinalName(int download_id,
522 const FilePath& full_path,
523 int uniquifier) {
[email protected]da6e3922010-11-24 21:45:50524 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
[email protected]f5920322011-03-24 20:34:16525 << " full_path = \"" << full_path.value() << "\""
526 << " uniquifier = " << uniquifier;
[email protected]ca4b5fa32010-10-09 12:42:18527 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]f5920322011-03-24 20:34:16528
[email protected]2e030682010-07-23 19:45:36529 DownloadItem* item = GetDownloadItem(download_id);
530 if (!item)
531 return;
[email protected]6cade212008-12-03 00:32:22532
[email protected]8fa1eeb52011-04-13 14:18:02533 if (item->safety_state() == DownloadItem::SAFE) {
534 DCHECK_EQ(0, uniquifier) << "We should not uniquify SAFE downloads twice";
535 }
536
[email protected]eda58402011-09-21 19:32:02537 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(
538 file_manager_,
539 &DownloadFileManager::CompleteDownload,
540 item->global_id()));
[email protected]9ccbb372008-10-10 18:50:32541
[email protected]f5920322011-03-24 20:34:16542 if (uniquifier)
543 item->set_path_uniquifier(uniquifier);
[email protected]9ccbb372008-10-10 18:50:32544
[email protected]f5920322011-03-24 20:34:16545 item->OnDownloadRenamedToFinalName(full_path);
[email protected]2588ea9d2011-08-22 20:59:53546 delegate_->UpdatePathForItemInPersistentStore(item, full_path);
initial.commit09911bf2008-07-26 23:55:29547}
548
[email protected]93af2272011-09-21 18:29:17549void DownloadManager::CancelDownload(int32 download_id) {
550 DownloadItem* download = GetActiveDownload(download_id);
551 // A cancel at the right time could remove the download from the
552 // |active_downloads_| map before we get here.
553 if (!download)
554 return;
555
556 download->Cancel(true);
557}
558
559void DownloadManager::DownloadCancelledInternal(DownloadItem* download) {
[email protected]d8472d92011-08-26 20:15:20560 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d8472d92011-08-26 20:15:20561
562 VLOG(20) << __FUNCTION__ << "()"
[email protected]da6e3922010-11-24 21:45:50563 << " download = " << download->DebugString(true);
564
[email protected]93af2272011-09-21 18:29:17565 RemoveFromActiveList(download);
[email protected]47a881b2011-08-29 22:59:21566 // This function is called from the DownloadItem, so DI state
567 // should already have been updated.
568 AssertQueueStateConsistent(download);
initial.commit09911bf2008-07-26 23:55:29569
[email protected]d8472d92011-08-26 20:15:20570 download->OffThreadCancel(file_manager_);
initial.commit09911bf2008-07-26 23:55:29571}
572
[email protected]be76b7e2011-10-13 12:57:57573void DownloadManager::OnDownloadInterrupted(int32 download_id,
574 int64 size,
575 InterruptReason reason) {
[email protected]47a881b2011-08-29 22:59:21576 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
577
578 DownloadItem* download = GetActiveDownload(download_id);
579 if (!download)
580 return;
581
[email protected]be76b7e2011-10-13 12:57:57582 VLOG(20) << __FUNCTION__ << "()"
583 << " reason " << InterruptReasonDebugString(reason)
[email protected]47a881b2011-08-29 22:59:21584 << " at offset " << download->received_bytes()
585 << " size = " << size
586 << " download = " << download->DebugString(true);
587
[email protected]93af2272011-09-21 18:29:17588 RemoveFromActiveList(download);
[email protected]be76b7e2011-10-13 12:57:57589 download->Interrupted(size, reason);
[email protected]93af2272011-09-21 18:29:17590 download->OffThreadCancel(file_manager_);
[email protected]47a881b2011-08-29 22:59:21591}
592
593DownloadItem* DownloadManager::GetActiveDownload(int32 download_id) {
[email protected]bf68a00b2011-04-07 17:28:26594 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
595 DownloadMap::iterator it = active_downloads_.find(download_id);
[email protected]bf68a00b2011-04-07 17:28:26596 if (it == active_downloads_.end())
[email protected]47a881b2011-08-29 22:59:21597 return NULL;
[email protected]bf68a00b2011-04-07 17:28:26598
599 DownloadItem* download = it->second;
600
[email protected]47a881b2011-08-29 22:59:21601 DCHECK(download);
602 DCHECK_EQ(download_id, download->id());
[email protected]4cd82f72011-05-23 19:15:01603
[email protected]47a881b2011-08-29 22:59:21604 return download;
605}
[email protected]54610672011-07-18 18:24:43606
[email protected]93af2272011-09-21 18:29:17607void DownloadManager::RemoveFromActiveList(DownloadItem* download) {
608 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
609 DCHECK(download);
610
611 // Clean up will happen when the history system create callback runs if we
612 // don't have a valid db_handle yet.
613 if (download->db_handle() != DownloadItem::kUninitializedHandle) {
614 in_progress_.erase(download->id());
615 active_downloads_.erase(download->id());
616 UpdateDownloadProgress(); // Reflect removal from in_progress_.
617 delegate_->UpdateItemInPersistentStore(download);
618 }
619}
620
[email protected]9bb54ee2011-10-12 17:43:35621void DownloadManager::SetDownloadManagerDelegate(
[email protected]1bd0ef12011-10-20 05:24:17622 content::DownloadManagerDelegate* delegate) {
[email protected]9bb54ee2011-10-12 17:43:35623 delegate_ = delegate;
624}
625
[email protected]5f8589fe2011-08-17 20:58:39626void DownloadManager::UpdateDownloadProgress() {
627 delegate_->DownloadProgressUpdated();
[email protected]6a7fb042010-02-01 16:30:47628}
629
[email protected]6d0146c2011-08-04 19:13:04630int DownloadManager::RemoveDownloadItems(
631 const DownloadVector& pending_deletes) {
632 if (pending_deletes.empty())
633 return 0;
634
635 // Delete from internal maps.
636 for (DownloadVector::const_iterator it = pending_deletes.begin();
637 it != pending_deletes.end();
638 ++it) {
639 DownloadItem* download = *it;
640 DCHECK(download);
641 history_downloads_.erase(download->db_handle());
642 save_page_downloads_.erase(download->id());
643 downloads_.erase(download);
644 }
645
646 // Tell observers to refresh their views.
647 NotifyModelChanged();
648
649 // Delete the download items themselves.
650 const int num_deleted = static_cast<int>(pending_deletes.size());
651 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
652 return num_deleted;
653}
654
[email protected]93af2272011-09-21 18:29:17655void DownloadManager::RemoveDownload(int64 download_handle) {
656 DownloadMap::iterator it = history_downloads_.find(download_handle);
657 if (it == history_downloads_.end())
658 return;
659
660 // Make history update.
661 DownloadItem* download = it->second;
662 delegate_->RemoveItemFromPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29663
664 // Remove from our tables and delete.
[email protected]6d0146c2011-08-04 19:13:04665 int downloads_count = RemoveDownloadItems(DownloadVector(1, download));
[email protected]f04182f32010-12-10 19:12:07666 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29667}
668
[email protected]e93d2822009-01-30 05:59:59669int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
670 const base::Time remove_end) {
[email protected]2588ea9d2011-08-22 20:59:53671 delegate_->RemoveItemsFromPersistentStoreBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29672
[email protected]a312a442010-12-15 23:40:33673 // All downloads visible to the user will be in the history,
674 // so scan that map.
[email protected]6d0146c2011-08-04 19:13:04675 DownloadVector pending_deletes;
676 for (DownloadMap::const_iterator it = history_downloads_.begin();
677 it != history_downloads_.end();
678 ++it) {
initial.commit09911bf2008-07-26 23:55:29679 DownloadItem* download = it->second;
initial.commit09911bf2008-07-26 23:55:29680 if (download->start_time() >= remove_begin &&
681 (remove_end.is_null() || download->start_time() < remove_end) &&
[email protected]6d0146c2011-08-04 19:13:04682 (download->IsComplete() || download->IsCancelled())) {
[email protected]7d413112011-06-16 18:50:17683 AssertQueueStateConsistent(download);
[email protected]78b8fcc92009-03-31 17:36:28684 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29685 }
initial.commit09911bf2008-07-26 23:55:29686 }
[email protected]6d0146c2011-08-04 19:13:04687 return RemoveDownloadItems(pending_deletes);
initial.commit09911bf2008-07-26 23:55:29688}
689
[email protected]e93d2822009-01-30 05:59:59690int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
691 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29692}
693
[email protected]d41355e6f2009-04-07 21:21:12694int DownloadManager::RemoveAllDownloads() {
[email protected]da4a5582011-10-17 19:08:06695 download_stats::RecordClearAllSize(history_downloads_.size());
[email protected]d41355e6f2009-04-07 21:21:12696 // The null times make the date range unbounded.
697 return RemoveDownloadsBetween(base::Time(), base::Time());
698}
699
initial.commit09911bf2008-07-26 23:55:29700// Initiate a download of a specific URL. We send the request to the
701// ResourceDispatcherHost, and let it send us responses like a regular
702// download.
703void DownloadManager::DownloadUrl(const GURL& url,
704 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50705 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34706 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26707 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
708 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58709}
710
711void DownloadManager::DownloadUrlToFile(const GURL& url,
712 const GURL& referrer,
713 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32714 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58715 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34716 DCHECK(tab_contents);
[email protected]c79a0c02011-08-22 22:37:37717 ResourceDispatcherHost* resource_dispatcher_host =
718 content::GetContentClient()->browser()->GetResourceDispatcherHost();
[email protected]ed24fad2011-05-10 22:44:01719 // We send a pointer to content::ResourceContext, instead of the usual
720 // reference, so that a copy of the object isn't made.
[email protected]ca4b5fa32010-10-09 12:42:18721 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]a0ce3282011-08-19 20:49:52722 NewRunnableFunction(&BeginDownload,
[email protected]ae8945192010-07-20 16:56:26723 url,
724 referrer,
[email protected]ae8945192010-07-20 16:56:26725 save_info,
[email protected]c79a0c02011-08-22 22:37:37726 resource_dispatcher_host,
[email protected]ae8945192010-07-20 16:56:26727 tab_contents->GetRenderProcessHost()->id(),
728 tab_contents->render_view_host()->routing_id(),
[email protected]cafe4ad2011-07-28 18:34:56729 &tab_contents->browser_context()->
730 GetResourceContext()));
initial.commit09911bf2008-07-26 23:55:29731}
732
initial.commit09911bf2008-07-26 23:55:29733void DownloadManager::AddObserver(Observer* observer) {
734 observers_.AddObserver(observer);
735 observer->ModelChanged();
736}
737
738void DownloadManager::RemoveObserver(Observer* observer) {
739 observers_.RemoveObserver(observer);
740}
741
[email protected]45f432e942011-10-25 18:17:22742bool DownloadManager::IsDownloadProgressKnown() const {
743 for (DownloadMap::const_iterator i = in_progress_.begin();
[email protected]073ed7b2010-09-27 09:20:02744 i != in_progress_.end(); ++i) {
745 if (i->second->total_bytes() <= 0)
746 return false;
747 }
748
749 return true;
750}
751
[email protected]45f432e942011-10-25 18:17:22752int64 DownloadManager::GetInProgressDownloadCount() const {
[email protected]073ed7b2010-09-27 09:20:02753 return in_progress_.size();
754}
755
[email protected]45f432e942011-10-25 18:17:22756int64 DownloadManager::GetReceivedDownloadBytes() const {
[email protected]073ed7b2010-09-27 09:20:02757 DCHECK(IsDownloadProgressKnown());
758 int64 received_bytes = 0;
[email protected]45f432e942011-10-25 18:17:22759 for (DownloadMap::const_iterator i = in_progress_.begin();
[email protected]073ed7b2010-09-27 09:20:02760 i != in_progress_.end(); ++i) {
761 received_bytes += i->second->received_bytes();
762 }
763 return received_bytes;
764}
765
[email protected]45f432e942011-10-25 18:17:22766int64 DownloadManager::GetTotalDownloadBytes() const {
[email protected]073ed7b2010-09-27 09:20:02767 DCHECK(IsDownloadProgressKnown());
768 int64 total_bytes = 0;
[email protected]45f432e942011-10-25 18:17:22769 for (DownloadMap::const_iterator i = in_progress_.begin();
[email protected]073ed7b2010-09-27 09:20:02770 i != in_progress_.end(); ++i) {
771 total_bytes += i->second->total_bytes();
772 }
773 return total_bytes;
774}
775
[email protected]99cb7f82011-07-28 17:27:26776void DownloadManager::FileSelected(const FilePath& path, void* params) {
[email protected]4cd82f72011-05-23 19:15:01777 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
778
779 int32* id_ptr = reinterpret_cast<int32*>(params);
780 DCHECK(id_ptr != NULL);
781 int32 download_id = *id_ptr;
782 delete id_ptr;
783
784 DownloadItem* download = GetActiveDownloadItem(download_id);
785 if (!download)
786 return;
787 VLOG(20) << __FUNCTION__ << "()" << " path = \"" << path.value() << "\""
788 << " download = " << download->DebugString(true);
789
[email protected]da1a27b2011-07-29 23:16:33790 if (download->prompt_user_for_save_location())
[email protected]7ae7c2cb2009-01-06 23:31:41791 last_download_path_ = path.DirName();
[email protected]287b86b2011-02-26 00:11:35792
[email protected]4cd82f72011-05-23 19:15:01793 // Make sure the initial file name is set only once.
794 ContinueDownloadWithPath(download, path);
initial.commit09911bf2008-07-26 23:55:29795}
796
797void DownloadManager::FileSelectionCanceled(void* params) {
798 // The user didn't pick a place to save the file, so need to cancel the
799 // download that's already in progress to the temporary location.
[email protected]4cd82f72011-05-23 19:15:01800 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
801 int32* id_ptr = reinterpret_cast<int32*>(params);
802 DCHECK(id_ptr != NULL);
803 int32 download_id = *id_ptr;
804 delete id_ptr;
805
806 DownloadItem* download = GetActiveDownloadItem(download_id);
807 if (!download)
808 return;
809
810 VLOG(20) << __FUNCTION__ << "()"
811 << " download = " << download->DebugString(true);
812
[email protected]93af2272011-09-21 18:29:17813 // TODO(ahendrickson) -- This currently has no effect, as the download is
814 // not put on the active list until the file selection is complete. Need
815 // to put it on the active list earlier in the process.
816 RemoveFromActiveList(download);
817
818 download->OffThreadCancel(file_manager_);
[email protected]4cd82f72011-05-23 19:15:01819}
820
initial.commit09911bf2008-07-26 23:55:29821// Operations posted to us from the history service ----------------------------
822
823// The history service has retrieved all download entries. 'entries' contains
[email protected]bb1a4212011-08-22 22:38:25824// 'DownloadPersistentStoreInfo's in sorted order (by ascending start_time).
[email protected]2588ea9d2011-08-22 20:59:53825void DownloadManager::OnPersistentStoreQueryComplete(
[email protected]bb1a4212011-08-22 22:38:25826 std::vector<DownloadPersistentStoreInfo>* entries) {
[email protected]d8472d92011-08-26 20:15:20827 // TODO(rdsmith): Remove this and related logic when
[email protected]639ddad2011-10-05 02:53:47828 // http://crbug.com/85408 is fixed.
[email protected]d8472d92011-08-26 20:15:20829 largest_db_handle_in_history_ = 0;
830
initial.commit09911bf2008-07-26 23:55:29831 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:39832 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]d8472d92011-08-26 20:15:20833 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]821960a2011-08-23 20:40:03834 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
[email protected]f04182f32010-12-10 19:12:07835 downloads_.insert(download);
836 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:50837 VLOG(20) << __FUNCTION__ << "()" << i << ">"
838 << " download = " << download->DebugString(true);
[email protected]d8472d92011-08-26 20:15:20839
840 if (download->db_handle() > largest_db_handle_in_history_)
841 largest_db_handle_in_history_ = download->db_handle();
initial.commit09911bf2008-07-26 23:55:29842 }
[email protected]b0ab1d42010-02-24 19:29:28843 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:48844 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:29845}
846
[email protected]f9a45b02011-06-30 23:49:19847void DownloadManager::AddDownloadItemToHistory(DownloadItem* download,
848 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:27849 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d2a8fb72010-01-21 05:31:42850
[email protected]639ddad2011-10-05 02:53:47851 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/85408
[email protected]1e9fe7ff2011-06-24 17:37:33852 // is fixed.
[email protected]2588ea9d2011-08-22 20:59:53853 CHECK_NE(DownloadItem::kUninitializedHandle, db_handle);
[email protected]1e9fe7ff2011-06-24 17:37:33854
[email protected]da4a5582011-10-17 19:08:06855 download_stats::RecordHistorySize(history_downloads_.size());
856
[email protected]2588ea9d2011-08-22 20:59:53857 DCHECK(download->db_handle() == DownloadItem::kUninitializedHandle);
[email protected]5bcd73eb2011-03-23 21:14:02858 download->set_db_handle(db_handle);
859
[email protected]639ddad2011-10-05 02:53:47860 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/85408
[email protected]d8472d92011-08-26 20:15:20861 // is fixed.
[email protected]821960a2011-08-23 20:40:03862 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
[email protected]5bcd73eb2011-03-23 21:14:02863 history_downloads_[download->db_handle()] = download;
[email protected]6d0146c2011-08-04 19:13:04864
865 // Show in the appropriate browser UI.
866 // This includes buttons to save or cancel, for a dangerous download.
867 ShowDownloadInBrowser(download);
868
869 // Inform interested objects about the new download.
870 NotifyModelChanged();
[email protected]f9a45b02011-06-30 23:49:19871}
872
[email protected]2588ea9d2011-08-22 20:59:53873
874void DownloadManager::OnItemAddedToPersistentStore(int32 download_id,
875 int64 db_handle) {
876 if (save_page_downloads_.count(download_id)) {
877 OnSavePageItemAddedToPersistentStore(download_id, db_handle);
878 } else if (active_downloads_.count(download_id)) {
879 OnDownloadItemAddedToPersistentStore(download_id, db_handle);
880 }
881 // It's valid that we don't find a matching item, i.e. on shutdown.
882}
883
[email protected]f9a45b02011-06-30 23:49:19884// Once the new DownloadItem's creation info has been committed to the history
885// service, we associate the DownloadItem with the db handle, update our
886// 'history_downloads_' map and inform observers.
[email protected]2588ea9d2011-08-22 20:59:53887void DownloadManager::OnDownloadItemAddedToPersistentStore(int32 download_id,
888 int64 db_handle) {
[email protected]f9a45b02011-06-30 23:49:19889 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]19420cc2011-07-18 17:43:45890 DownloadItem* download = GetActiveDownloadItem(download_id);
[email protected]93af2272011-09-21 18:29:17891 if (!download)
[email protected]19420cc2011-07-18 17:43:45892 return;
[email protected]54610672011-07-18 18:24:43893
894 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
895 << " download_id = " << download_id
896 << " download = " << download->DebugString(true);
[email protected]f9a45b02011-06-30 23:49:19897
[email protected]d8472d92011-08-26 20:15:20898 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]d8472d92011-08-26 20:15:20899 int64 largest_handle = largest_db_handle_in_history_;
900 base::debug::Alias(&largest_handle);
[email protected]e5107ce2011-09-19 20:36:13901 int32 matching_item_download_id
902 = (ContainsKey(history_downloads_, db_handle) ?
903 history_downloads_[db_handle]->id() : 0);
904 base::debug::Alias(&matching_item_download_id);
905
[email protected]61b75a52011-08-29 16:34:34906 CHECK(!ContainsKey(history_downloads_, db_handle));
[email protected]d8472d92011-08-26 20:15:20907
[email protected]f9a45b02011-06-30 23:49:19908 AddDownloadItemToHistory(download, db_handle);
initial.commit09911bf2008-07-26 23:55:29909
[email protected]93af2272011-09-21 18:29:17910 // If the download is still in progress, try to complete it.
911 //
912 // Otherwise, download has been cancelled or interrupted before we've
913 // received the DB handle. We post one final message to the history
914 // service so that it can be properly in sync with the DownloadItem's
915 // completion status, and also inform any observers so that they get
916 // more than just the start notification.
917 if (download->IsInProgress()) {
918 MaybeCompleteDownload(download);
919 } else {
[email protected]639ddad2011-10-05 02:53:47920 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/85408
[email protected]93af2272011-09-21 18:29:17921 // is fixed.
922 CHECK(download->IsCancelled())
923 << " download = " << download->DebugString(true);
924 in_progress_.erase(download_id);
925 active_downloads_.erase(download_id);
926 delegate_->UpdateItemInPersistentStore(download);
927 download->UpdateObservers();
928 }
initial.commit09911bf2008-07-26 23:55:29929}
930
[email protected]4cd82f72011-05-23 19:15:01931void DownloadManager::ShowDownloadInBrowser(DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:34932 // The 'contents' may no longer exist if the user closed the tab before we
[email protected]99cb7f82011-07-28 17:27:26933 // get this start completion event.
[email protected]db6831a2011-06-09 21:08:28934 DownloadRequestHandle request_handle = download->request_handle();
[email protected]686493142011-07-15 21:47:22935 TabContents* content = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:26936
937 // If the contents no longer exists, we ask the embedder to suggest another
938 // tab.
[email protected]da1a27b2011-07-29 23:16:33939 if (!content)
[email protected]aa9881c2011-08-15 18:01:12940 content = delegate_->GetAlternativeTabContentsToNotifyForDownload();
[email protected]5e595482009-05-06 20:16:53941
[email protected]99cb7f82011-07-28 17:27:26942 if (content)
943 content->OnStartDownload(download);
[email protected]5e595482009-05-06 20:16:53944}
945
[email protected]6cade212008-12-03 00:32:22946// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:12947void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:41948 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:38949}
[email protected]b0ab1d42010-02-24 19:29:28950
951void DownloadManager::NotifyModelChanged() {
952 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
953}
954
[email protected]4cd82f72011-05-23 19:15:01955DownloadItem* DownloadManager::GetDownloadItem(int download_id) {
956 // The |history_downloads_| map is indexed by the download's db_handle,
957 // not its id, so we have to iterate.
[email protected]f04182f32010-12-10 19:12:07958 for (DownloadMap::iterator it = history_downloads_.begin();
959 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:36960 DownloadItem* item = it->second;
[email protected]4cd82f72011-05-23 19:15:01961 if (item->id() == download_id)
[email protected]2e030682010-07-23 19:45:36962 return item;
963 }
964 return NULL;
965}
966
[email protected]4cd82f72011-05-23 19:15:01967DownloadItem* DownloadManager::GetActiveDownloadItem(int download_id) {
[email protected]93af2272011-09-21 18:29:17968 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]4cd82f72011-05-23 19:15:01969 DownloadItem* download = active_downloads_[download_id];
970 DCHECK(download != NULL);
971 return download;
972}
973
[email protected]57fd1252010-12-23 17:24:09974// Confirm that everything in all maps is also in |downloads_|, and that
975// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:07976void DownloadManager::AssertContainersConsistent() const {
977#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:09978 // Turn everything into sets.
[email protected]6d0146c2011-08-04 19:13:04979 const DownloadMap* input_maps[] = {&active_downloads_,
980 &history_downloads_,
981 &save_page_downloads_};
982 DownloadSet active_set, history_set, save_page_set;
983 DownloadSet* all_sets[] = {&active_set, &history_set, &save_page_set};
984 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(all_sets));
[email protected]57fd1252010-12-23 17:24:09985 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
986 for (DownloadMap::const_iterator it = input_maps[i]->begin();
[email protected]6d0146c2011-08-04 19:13:04987 it != input_maps[i]->end(); ++it) {
988 all_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:07989 }
990 }
[email protected]57fd1252010-12-23 17:24:09991
992 // Check if each set is fully present in downloads, and create a union.
[email protected]57fd1252010-12-23 17:24:09993 DownloadSet downloads_union;
994 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
995 DownloadSet remainder;
996 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
997 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
998 downloads_.begin(), downloads_.end(),
999 insert_it);
1000 DCHECK(remainder.empty());
1001 std::insert_iterator<DownloadSet>
1002 insert_union(downloads_union, downloads_union.end());
1003 std::set_union(downloads_union.begin(), downloads_union.end(),
1004 all_sets[i]->begin(), all_sets[i]->end(),
1005 insert_union);
1006 }
1007
1008 // Is everything in downloads_ present in one of the other sets?
1009 DownloadSet remainder;
1010 std::insert_iterator<DownloadSet>
1011 insert_remainder(remainder, remainder.begin());
1012 std::set_difference(downloads_.begin(), downloads_.end(),
1013 downloads_union.begin(), downloads_union.end(),
1014 insert_remainder);
1015 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071016#endif
1017}
1018
[email protected]6d0146c2011-08-04 19:13:041019void DownloadManager::SavePageDownloadStarted(DownloadItem* download) {
1020 DCHECK(!ContainsKey(save_page_downloads_, download->id()));
1021 downloads_.insert(download);
1022 save_page_downloads_[download->id()] = download;
1023
1024 // Add this entry to the history service.
1025 // Additionally, the UI is notified in the callback.
[email protected]2588ea9d2011-08-22 20:59:531026 delegate_->AddItemToPersistentStore(download);
[email protected]6d0146c2011-08-04 19:13:041027}
1028
1029// SavePackage will call SavePageDownloadFinished upon completion/cancellation.
[email protected]2588ea9d2011-08-22 20:59:531030// The history callback will call OnSavePageItemAddedToPersistentStore.
[email protected]6d0146c2011-08-04 19:13:041031// If the download finishes before the history callback,
[email protected]2588ea9d2011-08-22 20:59:531032// OnSavePageItemAddedToPersistentStore calls SavePageDownloadFinished, ensuring
1033// that the history event is update regardless of the order in which these two
1034// events complete.
[email protected]6d0146c2011-08-04 19:13:041035// If something removes the download item from the download manager (Remove,
1036// Shutdown) the result will be that the SavePage system will not be able to
1037// properly update the download item (which no longer exists) or the download
1038// history, but the action will complete properly anyway. This may lead to the
1039// history entry being wrong on a reload of chrome (specifically in the case of
1040// Initiation -> History Callback -> Removal -> Completion), but there's no way
1041// to solve that without canceling on Remove (which would then update the DB).
1042
[email protected]2588ea9d2011-08-22 20:59:531043void DownloadManager::OnSavePageItemAddedToPersistentStore(int32 download_id,
1044 int64 db_handle) {
[email protected]6d0146c2011-08-04 19:13:041045 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1046
1047 DownloadMap::const_iterator it = save_page_downloads_.find(download_id);
1048 // This can happen if the download manager is shutting down and all maps
1049 // have been cleared.
1050 if (it == save_page_downloads_.end())
1051 return;
1052
1053 DownloadItem* download = it->second;
1054 if (!download) {
1055 NOTREACHED();
1056 return;
1057 }
1058
[email protected]d8472d92011-08-26 20:15:201059 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]d8472d92011-08-26 20:15:201060 int64 largest_handle = largest_db_handle_in_history_;
1061 base::debug::Alias(&largest_handle);
[email protected]61b75a52011-08-29 16:34:341062 CHECK(!ContainsKey(history_downloads_, db_handle));
[email protected]d8472d92011-08-26 20:15:201063
[email protected]6d0146c2011-08-04 19:13:041064 AddDownloadItemToHistory(download, db_handle);
1065
1066 // Finalize this download if it finished before the history callback.
1067 if (!download->IsInProgress())
1068 SavePageDownloadFinished(download);
1069}
1070
1071void DownloadManager::SavePageDownloadFinished(DownloadItem* download) {
[email protected]2588ea9d2011-08-22 20:59:531072 if (download->db_handle() != DownloadItem::kUninitializedHandle) {
1073 delegate_->UpdateItemInPersistentStore(download);
[email protected]6d0146c2011-08-04 19:13:041074 DCHECK(ContainsKey(save_page_downloads_, download->id()));
1075 save_page_downloads_.erase(download->id());
1076
1077 if (download->IsComplete())
[email protected]ad50def52011-10-19 23:17:071078 content::NotificationService::current()->Notify(
[email protected]6d0146c2011-08-04 19:13:041079 content::NOTIFICATION_SAVE_PACKAGE_SUCCESSFULLY_FINISHED,
[email protected]6c2381d2011-10-19 02:52:531080 content::Source<DownloadManager>(this),
1081 content::Details<DownloadItem>(download));
[email protected]6d0146c2011-08-04 19:13:041082 }
1083}
[email protected]da4a5582011-10-17 19:08:061084
1085void DownloadManager::MarkDownloadOpened(DownloadItem* download) {
1086 delegate_->UpdateItemInPersistentStore(download);
1087 int num_unopened = 0;
1088 for (DownloadMap::iterator it = history_downloads_.begin();
1089 it != history_downloads_.end(); ++it) {
1090 if (it->second->IsComplete() && !it->second->opened())
1091 ++num_unopened;
1092 }
1093 download_stats::RecordOpensOutstanding(num_unopened);
1094}