blob: 881beb9ebe3505327247e9b7daa079f19392ef45 [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]71bf3f5e2011-08-15 21:05:2228#include "content/browser/download/download_status_updater.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]432115822011-07-10 15:52:2733#include "content/common/content_notification_types.h"
[email protected]6d0146c2011-08-04 19:13:0434#include "content/common/notification_service.h"
initial.commit09911bf2008-07-26 23:55:2935
[email protected]a0ce3282011-08-19 20:49:5236namespace {
37
38void BeginDownload(
39 const GURL& url,
40 const GURL& referrer,
41 const DownloadSaveInfo& save_info,
[email protected]c79a0c02011-08-22 22:37:3742 ResourceDispatcherHost* resource_dispatcher_host,
43 int render_process_id,
[email protected]a0ce3282011-08-19 20:49:5244 int render_view_id,
45 const content::ResourceContext* context) {
[email protected]8e3ae68c2011-09-16 22:15:4746 net::URLRequest* request = new net::URLRequest(url, resource_dispatcher_host);
47 request->set_referrer(referrer.spec());
[email protected]c79a0c02011-08-22 22:37:3748 resource_dispatcher_host->BeginDownload(
[email protected]8e3ae68c2011-09-16 22:15:4749 request,
50 save_info,
51 true,
52 DownloadResourceHandler::OnStartedCallback(),
53 render_process_id,
54 render_view_id,
[email protected]c79a0c02011-08-22 22:37:3755 *context);
[email protected]a0ce3282011-08-19 20:49:5256}
57
58} // namespace
59
[email protected]da1a27b2011-07-29 23:16:3360DownloadManager::DownloadManager(DownloadManagerDelegate* delegate,
61 DownloadStatusUpdater* status_updater)
initial.commit09911bf2008-07-26 23:55:2962 : shutdown_needed_(false),
[email protected]6d0c9fb2011-08-22 19:26:0363 browser_context_(NULL),
[email protected]eda58402011-09-21 19:32:0264 next_id_(0),
[email protected]073ed7b2010-09-27 09:20:0265 file_manager_(NULL),
[email protected]eda58402011-09-21 19:32:0266 status_updater_((status_updater != NULL)
67 ? status_updater->AsWeakPtr()
68 : base::WeakPtr<DownloadStatusUpdater>()),
[email protected]d8472d92011-08-26 20:15:2069 delegate_(delegate),
70 largest_db_handle_in_history_(DownloadItem::kUninitializedHandle) {
[email protected]eda58402011-09-21 19:32:0271 // NOTE(benjhayden): status_updater may be NULL when using
72 // TestingBrowserProcess.
73 if (status_updater_.get() != NULL)
[email protected]073ed7b2010-09-27 09:20:0274 status_updater_->AddDelegate(this);
initial.commit09911bf2008-07-26 23:55:2975}
76
77DownloadManager::~DownloadManager() {
[email protected]326a6a92010-09-10 20:21:1378 DCHECK(!shutdown_needed_);
[email protected]eda58402011-09-21 19:32:0279 if (status_updater_.get() != NULL)
[email protected]073ed7b2010-09-27 09:20:0280 status_updater_->RemoveDelegate(this);
initial.commit09911bf2008-07-26 23:55:2981}
82
83void DownloadManager::Shutdown() {
[email protected]da6e3922010-11-24 21:45:5084 VLOG(20) << __FUNCTION__ << "()"
85 << " shutdown_needed_ = " << shutdown_needed_;
[email protected]326a6a92010-09-10 20:21:1386 if (!shutdown_needed_)
87 return;
88 shutdown_needed_ = false;
initial.commit09911bf2008-07-26 23:55:2989
[email protected]326a6a92010-09-10 20:21:1390 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown());
[email protected]fb4f8d902011-09-16 06:07:0891 // TODO(benjhayden): Consider clearing observers_.
[email protected]326a6a92010-09-10 20:21:1392
93 if (file_manager_) {
[email protected]ca4b5fa32010-10-09 12:42:1894 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
[email protected]326a6a92010-09-10 20:21:1395 NewRunnableMethod(file_manager_,
96 &DownloadFileManager::OnDownloadManagerShutdown,
[email protected]dc7cdcb92010-12-14 06:40:5497 make_scoped_refptr(this)));
[email protected]326a6a92010-09-10 20:21:1398 }
initial.commit09911bf2008-07-26 23:55:2999
[email protected]f04182f32010-12-10 19:12:07100 AssertContainersConsistent();
101
102 // Go through all downloads in downloads_. Dangerous ones we need to
103 // remove on disk, and in progress ones we need to cancel.
[email protected]57fd1252010-12-23 17:24:09104 for (DownloadSet::iterator it = downloads_.begin(); it != downloads_.end();) {
[email protected]f04182f32010-12-10 19:12:07105 DownloadItem* download = *it;
106
107 // Save iterator from potential erases in this set done by called code.
108 // Iterators after an erasure point are still valid for lists and
109 // associative containers such as sets.
110 it++;
111
112 if (download->safety_state() == DownloadItem::DANGEROUS &&
[email protected]48837962011-04-19 17:03:29113 download->IsPartialDownload()) {
[email protected]f04182f32010-12-10 19:12:07114 // The user hasn't accepted it, so we need to remove it
115 // from the disk. This may or may not result in it being
116 // removed from the DownloadManager queues and deleted
117 // (specifically, DownloadManager::RemoveDownload only
118 // removes and deletes it if it's known to the history service)
119 // so the only thing we know after calling this function is that
120 // the download was deleted if-and-only-if it was removed
121 // from all queues.
[email protected]303077002011-04-19 23:21:01122 download->Delete(DownloadItem::DELETE_DUE_TO_BROWSER_SHUTDOWN);
[email protected]bf68a00b2011-04-07 17:28:26123 } else if (download->IsPartialDownload()) {
[email protected]93af2272011-09-21 18:29:17124 download->Cancel(false);
125 delegate_->UpdateItemInPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29126 }
127 }
128
[email protected]f04182f32010-12-10 19:12:07129 // At this point, all dangerous downloads have had their files removed
130 // and all in progress downloads have been cancelled. We can now delete
131 // anything left.
[email protected]9ccbb372008-10-10 18:50:32132
[email protected]5cd11b6e2011-06-10 20:30:59133 // Copy downloads_ to separate container so as not to set off checks
134 // in DownloadItem destruction.
135 DownloadSet downloads_to_delete;
136 downloads_to_delete.swap(downloads_);
137
initial.commit09911bf2008-07-26 23:55:29138 in_progress_.clear();
[email protected]70850c72011-01-11 17:31:27139 active_downloads_.clear();
[email protected]5cd11b6e2011-06-10 20:30:59140 history_downloads_.clear();
[email protected]5cd11b6e2011-06-10 20:30:59141 STLDeleteElements(&downloads_to_delete);
initial.commit09911bf2008-07-26 23:55:29142
[email protected]6d0146c2011-08-04 19:13:04143 DCHECK(save_page_downloads_.empty());
144
initial.commit09911bf2008-07-26 23:55:29145 file_manager_ = NULL;
[email protected]2588ea9d2011-08-22 20:59:53146 delegate_->Shutdown();
[email protected]82f37b02010-07-29 22:04:57147
initial.commit09911bf2008-07-26 23:55:29148 shutdown_needed_ = false;
149}
150
[email protected]82f37b02010-07-29 22:04:57151void DownloadManager::GetTemporaryDownloads(
[email protected]6d0146c2011-08-04 19:13:04152 const FilePath& dir_path, DownloadVector* result) {
[email protected]82f37b02010-07-29 22:04:57153 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58154
[email protected]f04182f32010-12-10 19:12:07155 for (DownloadMap::iterator it = history_downloads_.begin();
156 it != history_downloads_.end(); ++it) {
[email protected]6aa4a1c02010-01-15 18:49:58157 if (it->second->is_temporary() &&
158 it->second->full_path().DirName() == dir_path)
[email protected]82f37b02010-07-29 22:04:57159 result->push_back(it->second);
[email protected]6aa4a1c02010-01-15 18:49:58160 }
[email protected]6aa4a1c02010-01-15 18:49:58161}
162
[email protected]82f37b02010-07-29 22:04:57163void DownloadManager::GetAllDownloads(
[email protected]6d0146c2011-08-04 19:13:04164 const FilePath& dir_path, DownloadVector* result) {
[email protected]82f37b02010-07-29 22:04:57165 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34166
[email protected]f04182f32010-12-10 19:12:07167 for (DownloadMap::iterator it = history_downloads_.begin();
168 it != history_downloads_.end(); ++it) {
[email protected]8ddbd66a2010-05-21 16:38:34169 if (!it->second->is_temporary() &&
170 (dir_path.empty() || it->second->full_path().DirName() == dir_path))
[email protected]82f37b02010-07-29 22:04:57171 result->push_back(it->second);
[email protected]8ddbd66a2010-05-21 16:38:34172 }
[email protected]8ddbd66a2010-05-21 16:38:34173}
174
[email protected]d3b12902010-08-16 23:39:42175void DownloadManager::SearchDownloads(const string16& query,
[email protected]6d0146c2011-08-04 19:13:04176 DownloadVector* result) {
[email protected]503d03872011-05-06 08:36:26177 string16 query_lower(base::i18n::ToLower(query));
[email protected]d3b12902010-08-16 23:39:42178
[email protected]f04182f32010-12-10 19:12:07179 for (DownloadMap::iterator it = history_downloads_.begin();
180 it != history_downloads_.end(); ++it) {
[email protected]d3b12902010-08-16 23:39:42181 DownloadItem* download_item = it->second;
182
[email protected]8a282712011-08-23 19:28:00183 if (download_item->is_temporary())
[email protected]d3b12902010-08-16 23:39:42184 continue;
185
186 // Display Incognito downloads only in Incognito window, and vice versa.
187 // The Incognito Downloads page will get the list of non-Incognito downloads
188 // from its parent profile.
[email protected]6d0c9fb2011-08-22 19:26:03189 if (browser_context_->IsOffTheRecord() != download_item->is_otr())
[email protected]d3b12902010-08-16 23:39:42190 continue;
191
192 if (download_item->MatchesQuery(query_lower))
193 result->push_back(download_item);
194 }
[email protected]d3b12902010-08-16 23:39:42195}
196
[email protected]eda58402011-09-21 19:32:02197void DownloadManager::OnPersistentStoreGetNextId(int next_id) {
198 DVLOG(1) << __FUNCTION__ << " " << next_id;
199 base::AutoLock lock(next_id_lock_);
200 // TODO(benjhayden) Delay Profile initialization until here, and set next_id_
201 // = next_id. The '+=' works for now because these ids are not yet persisted
202 // to the database. GetNextId() can allocate zero or more ids starting from 0,
203 // then this callback can increment next_id_, and the items with lower ids
204 // won't clash with any other items even though there may be items loaded from
205 // the history because items from the history don't have valid ids.
206 next_id_ += next_id;
207}
208
209DownloadId DownloadManager::GetNextId() {
210 // May be called on any thread via the GetNextIdThunk.
211 // TODO(benjhayden) If otr, forward to parent DM.
212 base::AutoLock lock(next_id_lock_);
213 return DownloadId(this, next_id_++);
214}
215
216DownloadManager::GetNextIdThunkType DownloadManager::GetNextIdThunk() {
217 // TODO(benjhayden) If otr, forward to parent DM.
218 return base::Bind(&DownloadManager::GetNextId, this);
219}
220
initial.commit09911bf2008-07-26 23:55:29221// Query the history service for information about all persisted downloads.
[email protected]6d0c9fb2011-08-22 19:26:03222bool DownloadManager::Init(content::BrowserContext* browser_context) {
223 DCHECK(browser_context);
initial.commit09911bf2008-07-26 23:55:29224 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
225 shutdown_needed_ = true;
226
[email protected]6d0c9fb2011-08-22 19:26:03227 browser_context_ = browser_context;
[email protected]024f2f02010-04-30 22:51:46228
[email protected]2941c2392010-07-15 22:54:30229 // In test mode, there may be no ResourceDispatcherHost. In this case it's
230 // safe to avoid setting |file_manager_| because we only call a small set of
231 // functions, none of which need it.
[email protected]a0ce3282011-08-19 20:49:52232 ResourceDispatcherHost* rdh =
233 content::GetContentClient()->browser()->GetResourceDispatcherHost();
[email protected]2941c2392010-07-15 22:54:30234 if (rdh) {
235 file_manager_ = rdh->download_file_manager();
236 DCHECK(file_manager_);
initial.commit09911bf2008-07-26 23:55:29237 }
238
initial.commit09911bf2008-07-26 23:55:29239 return true;
240}
241
[email protected]aa9881c2011-08-15 18:01:12242// We have received a message from DownloadFileManager about a new download.
[email protected]4cd82f72011-05-23 19:15:01243void DownloadManager::StartDownload(int32 download_id) {
[email protected]ca4b5fa32010-10-09 12:42:18244 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]287b86b2011-02-26 00:11:35245
[email protected]aa9881c2011-08-15 18:01:12246 if (delegate_->ShouldStartDownload(download_id))
247 RestartDownload(download_id);
[email protected]287b86b2011-02-26 00:11:35248}
249
[email protected]9fc114672011-06-15 08:17:48250void DownloadManager::CheckForHistoryFilesRemoval() {
251 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
252 for (DownloadMap::iterator it = history_downloads_.begin();
253 it != history_downloads_.end(); ++it) {
254 CheckForFileRemoval(it->second);
255 }
256}
257
258void DownloadManager::CheckForFileRemoval(DownloadItem* download_item) {
259 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
260 if (download_item->IsComplete() &&
261 !download_item->file_externally_removed()) {
262 BrowserThread::PostTask(
263 BrowserThread::FILE, FROM_HERE,
264 NewRunnableMethod(this,
265 &DownloadManager::CheckForFileRemovalOnFileThread,
266 download_item->db_handle(),
267 download_item->GetTargetFilePath()));
268 }
269}
270
271void DownloadManager::CheckForFileRemovalOnFileThread(
272 int64 db_handle, const FilePath& path) {
273 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
274 if (!file_util::PathExists(path)) {
275 BrowserThread::PostTask(
276 BrowserThread::UI, FROM_HERE,
277 NewRunnableMethod(this,
278 &DownloadManager::OnFileRemovalDetected,
279 db_handle));
280 }
281}
282
283void DownloadManager::OnFileRemovalDetected(int64 db_handle) {
284 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
285 DownloadMap::iterator it = history_downloads_.find(db_handle);
286 if (it != history_downloads_.end()) {
287 DownloadItem* download_item = it->second;
288 download_item->OnDownloadedFileRemoved();
289 }
290}
291
[email protected]aa9881c2011-08-15 18:01:12292void DownloadManager::RestartDownload(
293 int32 download_id) {
[email protected]ca4b5fa32010-10-09 12:42:18294 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
initial.commit09911bf2008-07-26 23:55:29295
[email protected]4cd82f72011-05-23 19:15:01296 DownloadItem* download = GetActiveDownloadItem(download_id);
297 if (!download)
298 return;
299
300 VLOG(20) << __FUNCTION__ << "()"
301 << " download = " << download->DebugString(true);
302
[email protected]4cd82f72011-05-23 19:15:01303 FilePath suggested_path = download->suggested_path();
304
[email protected]da1a27b2011-07-29 23:16:33305 if (download->prompt_user_for_save_location()) {
initial.commit09911bf2008-07-26 23:55:29306 // We must ask the user for the place to put the download.
[email protected]db6831a2011-06-09 21:08:28307 DownloadRequestHandle request_handle = download->request_handle();
308 TabContents* contents = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:26309
[email protected]4cd82f72011-05-23 19:15:01310 // |id_ptr| will be deleted in either FileSelected() or
[email protected]93af2272011-09-21 18:29:17311 // FileSelectionCancelled().
[email protected]4cd82f72011-05-23 19:15:01312 int32* id_ptr = new int32;
313 *id_ptr = download_id;
[email protected]99cb7f82011-07-28 17:27:26314
[email protected]da1a27b2011-07-29 23:16:33315 delegate_->ChooseDownloadPath(
[email protected]aa9881c2011-08-15 18:01:12316 contents, suggested_path, reinterpret_cast<void*>(id_ptr));
[email protected]99cb7f82011-07-28 17:27:26317
[email protected]f5920322011-03-24 20:34:16318 FOR_EACH_OBSERVER(Observer, observers_,
[email protected]fed38252011-07-08 17:26:50319 SelectFileDialogDisplayed(download_id));
initial.commit09911bf2008-07-26 23:55:29320 } else {
321 // No prompting for download, just continue with the suggested name.
[email protected]4cd82f72011-05-23 19:15:01322 ContinueDownloadWithPath(download, suggested_path);
initial.commit09911bf2008-07-26 23:55:29323 }
324}
325
[email protected]c2e76012010-12-23 21:10:29326void DownloadManager::CreateDownloadItem(DownloadCreateInfo* info) {
327 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
328
329 DownloadItem* download = new DownloadItem(this, *info,
[email protected]6d0c9fb2011-08-22 19:26:03330 browser_context_->IsOffTheRecord());
[email protected]4cd82f72011-05-23 19:15:01331 int32 download_id = info->download_id;
332 DCHECK(!ContainsKey(in_progress_, download_id));
[email protected]d8472d92011-08-26 20:15:20333
334 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]821960a2011-08-23 20:40:03335 CHECK(!ContainsKey(active_downloads_, download_id));
[email protected]c2e76012010-12-23 21:10:29336 downloads_.insert(download);
[email protected]4cd82f72011-05-23 19:15:01337 active_downloads_[download_id] = download;
[email protected]c2e76012010-12-23 21:10:29338}
339
[email protected]4cd82f72011-05-23 19:15:01340void DownloadManager::ContinueDownloadWithPath(DownloadItem* download,
341 const FilePath& chosen_file) {
[email protected]ca4b5fa32010-10-09 12:42:18342 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]4cd82f72011-05-23 19:15:01343 DCHECK(download);
[email protected]aa033af2010-07-27 18:16:39344
[email protected]4cd82f72011-05-23 19:15:01345 int32 download_id = download->id();
initial.commit09911bf2008-07-26 23:55:29346
[email protected]70850c72011-01-11 17:31:27347 // NOTE(ahendrickson) Eventually |active_downloads_| will replace
348 // |in_progress_|, but we don't want to change the semantics yet.
[email protected]4cd82f72011-05-23 19:15:01349 DCHECK(!ContainsKey(in_progress_, download_id));
[email protected]70850c72011-01-11 17:31:27350 DCHECK(ContainsKey(downloads_, download));
[email protected]4cd82f72011-05-23 19:15:01351 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]70850c72011-01-11 17:31:27352
[email protected]4cd82f72011-05-23 19:15:01353 // Make sure the initial file name is set only once.
354 DCHECK(download->full_path().empty());
355 download->OnPathDetermined(chosen_file);
[email protected]4cd82f72011-05-23 19:15:01356
357 VLOG(20) << __FUNCTION__ << "()"
358 << " download = " << download->DebugString(true);
359
360 in_progress_[download_id] = download;
[email protected]5f8589fe2011-08-17 20:58:39361 UpdateDownloadProgress(); // Reflect entry into in_progress_.
initial.commit09911bf2008-07-26 23:55:29362
[email protected]adb2f3d12011-01-23 16:24:54363 // Rename to intermediate name.
[email protected]f5920322011-03-24 20:34:16364 FilePath download_path;
[email protected]ec865262011-08-23 20:01:48365 if (!delegate_->OverrideIntermediatePath(download, &download_path))
[email protected]4cd82f72011-05-23 19:15:01366 download_path = download->full_path();
[email protected]594cd7d2010-07-21 03:23:56367
[email protected]f5920322011-03-24 20:34:16368 BrowserThread::PostTask(
369 BrowserThread::FILE, FROM_HERE,
370 NewRunnableMethod(
371 file_manager_, &DownloadFileManager::RenameInProgressDownloadFile,
[email protected]eda58402011-09-21 19:32:02372 download->global_id(), download_path));
[email protected]f5920322011-03-24 20:34:16373
374 download->Rename(download_path);
375
[email protected]2588ea9d2011-08-22 20:59:53376 delegate_->AddItemToPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29377}
378
initial.commit09911bf2008-07-26 23:55:29379void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
[email protected]70850c72011-01-11 17:31:27380 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
381 DownloadMap::iterator it = active_downloads_.find(download_id);
382 if (it != active_downloads_.end()) {
initial.commit09911bf2008-07-26 23:55:29383 DownloadItem* download = it->second;
[email protected]bf68a00b2011-04-07 17:28:26384 if (download->IsInProgress()) {
[email protected]70850c72011-01-11 17:31:27385 download->Update(size);
[email protected]5f8589fe2011-08-17 20:58:39386 UpdateDownloadProgress(); // Reflect size updates.
[email protected]2588ea9d2011-08-22 20:59:53387 delegate_->UpdateItemInPersistentStore(download);
[email protected]70850c72011-01-11 17:31:27388 }
initial.commit09911bf2008-07-26 23:55:29389 }
390}
391
[email protected]bf68a00b2011-04-07 17:28:26392void DownloadManager::OnResponseCompleted(int32 download_id,
393 int64 size,
[email protected]bf68a00b2011-04-07 17:28:26394 const std::string& hash) {
[email protected]33c6d3f12011-09-04 00:00:54395 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]da6e3922010-11-24 21:45:50396 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
397 << " size = " << size;
[email protected]9d7ef802011-02-25 19:03:35398 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:32399
[email protected]c4f02c42011-01-24 21:55:06400 // If it's not in active_downloads_, that means it was cancelled; just
401 // ignore the notification.
402 if (active_downloads_.count(download_id) == 0)
403 return;
404
[email protected]adb2f3d12011-01-23 16:24:54405 DownloadItem* download = active_downloads_[download_id];
[email protected]a850ba42010-09-10 22:00:30406 download->OnAllDataSaved(size);
[email protected]9ccbb372008-10-10 18:50:32407
[email protected]b09f1282011-09-14 00:37:45408 delegate_->OnResponseCompleted(download, hash);
409
[email protected]adb2f3d12011-01-23 16:24:54410 MaybeCompleteDownload(download);
411}
[email protected]9ccbb372008-10-10 18:50:32412
[email protected]7d413112011-06-16 18:50:17413void DownloadManager::AssertQueueStateConsistent(DownloadItem* download) {
[email protected]5cd11b6e2011-06-10 20:30:59414 // TODO(rdsmith): Change to DCHECK after http://crbug.com/85408 resolved.
[email protected]7d413112011-06-16 18:50:17415 if (download->state() == DownloadItem::REMOVING) {
416 CHECK(!ContainsKey(downloads_, download));
417 CHECK(!ContainsKey(active_downloads_, download->id()));
418 CHECK(!ContainsKey(in_progress_, download->id()));
419 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
420 return;
421 }
422
423 // Should be in downloads_ if we're not REMOVING.
424 CHECK(ContainsKey(downloads_, download));
425
426 // Check history_downloads_ consistency.
[email protected]2588ea9d2011-08-22 20:59:53427 if (download->db_handle() != DownloadItem::kUninitializedHandle) {
[email protected]7d413112011-06-16 18:50:17428 CHECK(ContainsKey(history_downloads_, download->db_handle()));
429 } else {
430 // TODO(rdsmith): Somewhat painful; make sure to disable in
431 // release builds after resolution of http://crbug.com/85408.
432 for (DownloadMap::iterator it = history_downloads_.begin();
433 it != history_downloads_.end(); ++it) {
434 CHECK(it->second != download);
435 }
436 }
437
[email protected]61b75a52011-08-29 16:34:34438 int64 state = download->state();
439 base::debug::Alias(&state);
[email protected]f9a2997f2011-09-23 16:54:07440 if (ContainsKey(active_downloads_, download->id())) {
441 if (download->db_handle() != DownloadItem::kUninitializedHandle)
442 CHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
443 if (DownloadItem::IN_PROGRESS != download->state())
444 CHECK_EQ(DownloadItem::kUninitializedHandle, download->db_handle());
445 }
[email protected]821960a2011-08-23 20:40:03446 if (DownloadItem::IN_PROGRESS == download->state())
447 CHECK(ContainsKey(active_downloads_, download->id()));
[email protected]5cd11b6e2011-06-10 20:30:59448}
449
[email protected]adb2f3d12011-01-23 16:24:54450bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
451 // If we don't have all the data, the download is not ready for
452 // completion.
453 if (!download->all_data_saved())
454 return false;
[email protected]6a7fb042010-02-01 16:30:47455
[email protected]9d7ef802011-02-25 19:03:35456 // If the download is dangerous, but not yet validated, it's not ready for
457 // completion.
458 if (download->safety_state() == DownloadItem::DANGEROUS)
459 return false;
460
[email protected]adb2f3d12011-01-23 16:24:54461 // If the download isn't active (e.g. has been cancelled) it's not
462 // ready for completion.
463 if (active_downloads_.count(download->id()) == 0)
464 return false;
465
466 // If the download hasn't been inserted into the history system
467 // (which occurs strictly after file name determination, intermediate
468 // file rename, and UI display) then it's not ready for completion.
[email protected]2588ea9d2011-08-22 20:59:53469 if (download->db_handle() == DownloadItem::kUninitializedHandle)
[email protected]7054b592011-06-22 14:46:42470 return false;
471
472 return true;
[email protected]adb2f3d12011-01-23 16:24:54473}
474
475void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
476 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
477 VLOG(20) << __FUNCTION__ << "()" << " download = "
478 << download->DebugString(false);
479
480 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32481 return;
[email protected]9ccbb372008-10-10 18:50:32482
[email protected]adb2f3d12011-01-23 16:24:54483 // TODO(rdsmith): DCHECK that we only pass through this point
484 // once per download. The natural way to do this is by a state
485 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56486
[email protected]adb2f3d12011-01-23 16:24:54487 // Confirm we're in the proper set of states to be here;
[email protected]9d7ef802011-02-25 19:03:35488 // in in_progress_, have all data, have a history handle, (validated or safe).
489 DCHECK_NE(DownloadItem::DANGEROUS, download->safety_state());
[email protected]adb2f3d12011-01-23 16:24:54490 DCHECK_EQ(1u, in_progress_.count(download->id()));
491 DCHECK(download->all_data_saved());
[email protected]2588ea9d2011-08-22 20:59:53492 DCHECK(download->db_handle() != DownloadItem::kUninitializedHandle);
[email protected]adb2f3d12011-01-23 16:24:54493 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
494
495 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
496 << download->DebugString(false);
497
498 // Remove the id from in_progress
499 in_progress_.erase(download->id());
[email protected]5f8589fe2011-08-17 20:58:39500 UpdateDownloadProgress(); // Reflect removal from in_progress_.
[email protected]adb2f3d12011-01-23 16:24:54501
[email protected]2588ea9d2011-08-22 20:59:53502 delegate_->UpdateItemInPersistentStore(download);
[email protected]adb2f3d12011-01-23 16:24:54503
[email protected]f5920322011-03-24 20:34:16504 // Finish the download.
[email protected]48837962011-04-19 17:03:29505 download->OnDownloadCompleting(file_manager_);
[email protected]9ccbb372008-10-10 18:50:32506}
507
[email protected]cc3c7c092011-05-09 18:40:21508void DownloadManager::DownloadCompleted(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27509 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21510 DownloadItem* download = GetDownloadItem(download_id);
511 DCHECK(download);
[email protected]2588ea9d2011-08-22 20:59:53512 delegate_->UpdateItemInPersistentStore(download);
[email protected]70850c72011-01-11 17:31:27513 active_downloads_.erase(download_id);
[email protected]821960a2011-08-23 20:40:03514 AssertQueueStateConsistent(download);
[email protected]70850c72011-01-11 17:31:27515}
516
[email protected]f5920322011-03-24 20:34:16517void DownloadManager::OnDownloadRenamedToFinalName(int download_id,
518 const FilePath& full_path,
519 int uniquifier) {
[email protected]da6e3922010-11-24 21:45:50520 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
[email protected]f5920322011-03-24 20:34:16521 << " full_path = \"" << full_path.value() << "\""
522 << " uniquifier = " << uniquifier;
[email protected]ca4b5fa32010-10-09 12:42:18523 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]f5920322011-03-24 20:34:16524
[email protected]2e030682010-07-23 19:45:36525 DownloadItem* item = GetDownloadItem(download_id);
526 if (!item)
527 return;
[email protected]6cade212008-12-03 00:32:22528
[email protected]8fa1eeb52011-04-13 14:18:02529 if (item->safety_state() == DownloadItem::SAFE) {
530 DCHECK_EQ(0, uniquifier) << "We should not uniquify SAFE downloads twice";
531 }
532
[email protected]eda58402011-09-21 19:32:02533 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(
534 file_manager_,
535 &DownloadFileManager::CompleteDownload,
536 item->global_id()));
[email protected]9ccbb372008-10-10 18:50:32537
[email protected]f5920322011-03-24 20:34:16538 if (uniquifier)
539 item->set_path_uniquifier(uniquifier);
[email protected]9ccbb372008-10-10 18:50:32540
[email protected]f5920322011-03-24 20:34:16541 item->OnDownloadRenamedToFinalName(full_path);
[email protected]2588ea9d2011-08-22 20:59:53542 delegate_->UpdatePathForItemInPersistentStore(item, full_path);
initial.commit09911bf2008-07-26 23:55:29543}
544
[email protected]93af2272011-09-21 18:29:17545void DownloadManager::CancelDownload(int32 download_id) {
546 DownloadItem* download = GetActiveDownload(download_id);
547 // A cancel at the right time could remove the download from the
548 // |active_downloads_| map before we get here.
549 if (!download)
550 return;
551
552 download->Cancel(true);
553}
554
555void DownloadManager::DownloadCancelledInternal(DownloadItem* download) {
[email protected]d8472d92011-08-26 20:15:20556 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d8472d92011-08-26 20:15:20557
558 VLOG(20) << __FUNCTION__ << "()"
[email protected]da6e3922010-11-24 21:45:50559 << " download = " << download->DebugString(true);
560
[email protected]93af2272011-09-21 18:29:17561 RemoveFromActiveList(download);
[email protected]47a881b2011-08-29 22:59:21562 // This function is called from the DownloadItem, so DI state
563 // should already have been updated.
564 AssertQueueStateConsistent(download);
initial.commit09911bf2008-07-26 23:55:29565
[email protected]d8472d92011-08-26 20:15:20566 download->OffThreadCancel(file_manager_);
initial.commit09911bf2008-07-26 23:55:29567}
568
[email protected]bf68a00b2011-04-07 17:28:26569void DownloadManager::OnDownloadError(int32 download_id,
570 int64 size,
[email protected]33c6d3f12011-09-04 00:00:54571 net::Error error) {
[email protected]47a881b2011-08-29 22:59:21572 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
573
574 DownloadItem* download = GetActiveDownload(download_id);
575 if (!download)
576 return;
577
578 VLOG(20) << __FUNCTION__ << "()" << " Error " << error
579 << " at offset " << download->received_bytes()
580 << " size = " << size
581 << " download = " << download->DebugString(true);
582
[email protected]93af2272011-09-21 18:29:17583 RemoveFromActiveList(download);
584 download->Interrupted(size, error);
585 download->OffThreadCancel(file_manager_);
[email protected]47a881b2011-08-29 22:59:21586}
587
588DownloadItem* DownloadManager::GetActiveDownload(int32 download_id) {
[email protected]bf68a00b2011-04-07 17:28:26589 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
590 DownloadMap::iterator it = active_downloads_.find(download_id);
[email protected]bf68a00b2011-04-07 17:28:26591 if (it == active_downloads_.end())
[email protected]47a881b2011-08-29 22:59:21592 return NULL;
[email protected]bf68a00b2011-04-07 17:28:26593
594 DownloadItem* download = it->second;
595
[email protected]47a881b2011-08-29 22:59:21596 DCHECK(download);
597 DCHECK_EQ(download_id, download->id());
[email protected]4cd82f72011-05-23 19:15:01598
[email protected]47a881b2011-08-29 22:59:21599 return download;
600}
[email protected]54610672011-07-18 18:24:43601
[email protected]93af2272011-09-21 18:29:17602void DownloadManager::RemoveFromActiveList(DownloadItem* download) {
603 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
604 DCHECK(download);
605
606 // Clean up will happen when the history system create callback runs if we
607 // don't have a valid db_handle yet.
608 if (download->db_handle() != DownloadItem::kUninitializedHandle) {
609 in_progress_.erase(download->id());
610 active_downloads_.erase(download->id());
611 UpdateDownloadProgress(); // Reflect removal from in_progress_.
612 delegate_->UpdateItemInPersistentStore(download);
613 }
614}
615
[email protected]9bb54ee2011-10-12 17:43:35616void DownloadManager::SetDownloadManagerDelegate(
617 DownloadManagerDelegate* delegate) {
618 delegate_ = delegate;
619}
620
[email protected]5f8589fe2011-08-17 20:58:39621void DownloadManager::UpdateDownloadProgress() {
622 delegate_->DownloadProgressUpdated();
[email protected]6a7fb042010-02-01 16:30:47623}
624
[email protected]6d0146c2011-08-04 19:13:04625int DownloadManager::RemoveDownloadItems(
626 const DownloadVector& pending_deletes) {
627 if (pending_deletes.empty())
628 return 0;
629
630 // Delete from internal maps.
631 for (DownloadVector::const_iterator it = pending_deletes.begin();
632 it != pending_deletes.end();
633 ++it) {
634 DownloadItem* download = *it;
635 DCHECK(download);
636 history_downloads_.erase(download->db_handle());
637 save_page_downloads_.erase(download->id());
638 downloads_.erase(download);
639 }
640
641 // Tell observers to refresh their views.
642 NotifyModelChanged();
643
644 // Delete the download items themselves.
645 const int num_deleted = static_cast<int>(pending_deletes.size());
646 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
647 return num_deleted;
648}
649
[email protected]93af2272011-09-21 18:29:17650void DownloadManager::RemoveDownload(int64 download_handle) {
651 DownloadMap::iterator it = history_downloads_.find(download_handle);
652 if (it == history_downloads_.end())
653 return;
654
655 // Make history update.
656 DownloadItem* download = it->second;
657 delegate_->RemoveItemFromPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29658
659 // Remove from our tables and delete.
[email protected]6d0146c2011-08-04 19:13:04660 int downloads_count = RemoveDownloadItems(DownloadVector(1, download));
[email protected]f04182f32010-12-10 19:12:07661 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29662}
663
[email protected]e93d2822009-01-30 05:59:59664int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
665 const base::Time remove_end) {
[email protected]2588ea9d2011-08-22 20:59:53666 delegate_->RemoveItemsFromPersistentStoreBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29667
[email protected]a312a442010-12-15 23:40:33668 // All downloads visible to the user will be in the history,
669 // so scan that map.
[email protected]6d0146c2011-08-04 19:13:04670 DownloadVector pending_deletes;
671 for (DownloadMap::const_iterator it = history_downloads_.begin();
672 it != history_downloads_.end();
673 ++it) {
initial.commit09911bf2008-07-26 23:55:29674 DownloadItem* download = it->second;
initial.commit09911bf2008-07-26 23:55:29675 if (download->start_time() >= remove_begin &&
676 (remove_end.is_null() || download->start_time() < remove_end) &&
[email protected]6d0146c2011-08-04 19:13:04677 (download->IsComplete() || download->IsCancelled())) {
[email protected]7d413112011-06-16 18:50:17678 AssertQueueStateConsistent(download);
[email protected]78b8fcc92009-03-31 17:36:28679 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29680 }
initial.commit09911bf2008-07-26 23:55:29681 }
[email protected]6d0146c2011-08-04 19:13:04682 return RemoveDownloadItems(pending_deletes);
initial.commit09911bf2008-07-26 23:55:29683}
684
[email protected]e93d2822009-01-30 05:59:59685int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
686 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29687}
688
[email protected]d41355e6f2009-04-07 21:21:12689int DownloadManager::RemoveAllDownloads() {
690 // The null times make the date range unbounded.
691 return RemoveDownloadsBetween(base::Time(), base::Time());
692}
693
initial.commit09911bf2008-07-26 23:55:29694// Initiate a download of a specific URL. We send the request to the
695// ResourceDispatcherHost, and let it send us responses like a regular
696// download.
697void DownloadManager::DownloadUrl(const GURL& url,
698 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50699 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34700 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26701 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
702 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58703}
704
705void DownloadManager::DownloadUrlToFile(const GURL& url,
706 const GURL& referrer,
707 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32708 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58709 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34710 DCHECK(tab_contents);
[email protected]c79a0c02011-08-22 22:37:37711 ResourceDispatcherHost* resource_dispatcher_host =
712 content::GetContentClient()->browser()->GetResourceDispatcherHost();
[email protected]ed24fad2011-05-10 22:44:01713 // We send a pointer to content::ResourceContext, instead of the usual
714 // reference, so that a copy of the object isn't made.
[email protected]ca4b5fa32010-10-09 12:42:18715 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]a0ce3282011-08-19 20:49:52716 NewRunnableFunction(&BeginDownload,
[email protected]ae8945192010-07-20 16:56:26717 url,
718 referrer,
[email protected]ae8945192010-07-20 16:56:26719 save_info,
[email protected]c79a0c02011-08-22 22:37:37720 resource_dispatcher_host,
[email protected]ae8945192010-07-20 16:56:26721 tab_contents->GetRenderProcessHost()->id(),
722 tab_contents->render_view_host()->routing_id(),
[email protected]cafe4ad2011-07-28 18:34:56723 &tab_contents->browser_context()->
724 GetResourceContext()));
initial.commit09911bf2008-07-26 23:55:29725}
726
initial.commit09911bf2008-07-26 23:55:29727void DownloadManager::AddObserver(Observer* observer) {
728 observers_.AddObserver(observer);
729 observer->ModelChanged();
730}
731
732void DownloadManager::RemoveObserver(Observer* observer) {
733 observers_.RemoveObserver(observer);
734}
735
[email protected]073ed7b2010-09-27 09:20:02736bool DownloadManager::IsDownloadProgressKnown() {
737 for (DownloadMap::iterator i = in_progress_.begin();
738 i != in_progress_.end(); ++i) {
739 if (i->second->total_bytes() <= 0)
740 return false;
741 }
742
743 return true;
744}
745
746int64 DownloadManager::GetInProgressDownloadCount() {
747 return in_progress_.size();
748}
749
750int64 DownloadManager::GetReceivedDownloadBytes() {
751 DCHECK(IsDownloadProgressKnown());
752 int64 received_bytes = 0;
753 for (DownloadMap::iterator i = in_progress_.begin();
754 i != in_progress_.end(); ++i) {
755 received_bytes += i->second->received_bytes();
756 }
757 return received_bytes;
758}
759
760int64 DownloadManager::GetTotalDownloadBytes() {
761 DCHECK(IsDownloadProgressKnown());
762 int64 total_bytes = 0;
763 for (DownloadMap::iterator i = in_progress_.begin();
764 i != in_progress_.end(); ++i) {
765 total_bytes += i->second->total_bytes();
766 }
767 return total_bytes;
768}
769
[email protected]99cb7f82011-07-28 17:27:26770void DownloadManager::FileSelected(const FilePath& path, void* params) {
[email protected]4cd82f72011-05-23 19:15:01771 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
772
773 int32* id_ptr = reinterpret_cast<int32*>(params);
774 DCHECK(id_ptr != NULL);
775 int32 download_id = *id_ptr;
776 delete id_ptr;
777
778 DownloadItem* download = GetActiveDownloadItem(download_id);
779 if (!download)
780 return;
781 VLOG(20) << __FUNCTION__ << "()" << " path = \"" << path.value() << "\""
782 << " download = " << download->DebugString(true);
783
[email protected]da1a27b2011-07-29 23:16:33784 if (download->prompt_user_for_save_location())
[email protected]7ae7c2cb2009-01-06 23:31:41785 last_download_path_ = path.DirName();
[email protected]287b86b2011-02-26 00:11:35786
[email protected]4cd82f72011-05-23 19:15:01787 // Make sure the initial file name is set only once.
788 ContinueDownloadWithPath(download, path);
initial.commit09911bf2008-07-26 23:55:29789}
790
791void DownloadManager::FileSelectionCanceled(void* params) {
792 // The user didn't pick a place to save the file, so need to cancel the
793 // download that's already in progress to the temporary location.
[email protected]4cd82f72011-05-23 19:15:01794 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
795 int32* id_ptr = reinterpret_cast<int32*>(params);
796 DCHECK(id_ptr != NULL);
797 int32 download_id = *id_ptr;
798 delete id_ptr;
799
800 DownloadItem* download = GetActiveDownloadItem(download_id);
801 if (!download)
802 return;
803
804 VLOG(20) << __FUNCTION__ << "()"
805 << " download = " << download->DebugString(true);
806
[email protected]93af2272011-09-21 18:29:17807 // TODO(ahendrickson) -- This currently has no effect, as the download is
808 // not put on the active list until the file selection is complete. Need
809 // to put it on the active list earlier in the process.
810 RemoveFromActiveList(download);
811
812 download->OffThreadCancel(file_manager_);
[email protected]4cd82f72011-05-23 19:15:01813}
814
initial.commit09911bf2008-07-26 23:55:29815// Operations posted to us from the history service ----------------------------
816
817// The history service has retrieved all download entries. 'entries' contains
[email protected]bb1a4212011-08-22 22:38:25818// 'DownloadPersistentStoreInfo's in sorted order (by ascending start_time).
[email protected]2588ea9d2011-08-22 20:59:53819void DownloadManager::OnPersistentStoreQueryComplete(
[email protected]bb1a4212011-08-22 22:38:25820 std::vector<DownloadPersistentStoreInfo>* entries) {
[email protected]d8472d92011-08-26 20:15:20821 // TODO(rdsmith): Remove this and related logic when
[email protected]639ddad2011-10-05 02:53:47822 // http://crbug.com/85408 is fixed.
[email protected]d8472d92011-08-26 20:15:20823 largest_db_handle_in_history_ = 0;
824
initial.commit09911bf2008-07-26 23:55:29825 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:39826 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]d8472d92011-08-26 20:15:20827 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]821960a2011-08-23 20:40:03828 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
[email protected]f04182f32010-12-10 19:12:07829 downloads_.insert(download);
830 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:50831 VLOG(20) << __FUNCTION__ << "()" << i << ">"
832 << " download = " << download->DebugString(true);
[email protected]d8472d92011-08-26 20:15:20833
834 if (download->db_handle() > largest_db_handle_in_history_)
835 largest_db_handle_in_history_ = download->db_handle();
initial.commit09911bf2008-07-26 23:55:29836 }
[email protected]b0ab1d42010-02-24 19:29:28837 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:48838 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:29839}
840
[email protected]f9a45b02011-06-30 23:49:19841void DownloadManager::AddDownloadItemToHistory(DownloadItem* download,
842 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:27843 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d2a8fb72010-01-21 05:31:42844
[email protected]639ddad2011-10-05 02:53:47845 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/85408
[email protected]1e9fe7ff2011-06-24 17:37:33846 // is fixed.
[email protected]2588ea9d2011-08-22 20:59:53847 CHECK_NE(DownloadItem::kUninitializedHandle, db_handle);
[email protected]1e9fe7ff2011-06-24 17:37:33848
[email protected]2588ea9d2011-08-22 20:59:53849 DCHECK(download->db_handle() == DownloadItem::kUninitializedHandle);
[email protected]5bcd73eb2011-03-23 21:14:02850 download->set_db_handle(db_handle);
851
[email protected]639ddad2011-10-05 02:53:47852 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/85408
[email protected]d8472d92011-08-26 20:15:20853 // is fixed.
[email protected]821960a2011-08-23 20:40:03854 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
[email protected]5bcd73eb2011-03-23 21:14:02855 history_downloads_[download->db_handle()] = download;
[email protected]6d0146c2011-08-04 19:13:04856
857 // Show in the appropriate browser UI.
858 // This includes buttons to save or cancel, for a dangerous download.
859 ShowDownloadInBrowser(download);
860
861 // Inform interested objects about the new download.
862 NotifyModelChanged();
[email protected]f9a45b02011-06-30 23:49:19863}
864
[email protected]2588ea9d2011-08-22 20:59:53865
866void DownloadManager::OnItemAddedToPersistentStore(int32 download_id,
867 int64 db_handle) {
868 if (save_page_downloads_.count(download_id)) {
869 OnSavePageItemAddedToPersistentStore(download_id, db_handle);
870 } else if (active_downloads_.count(download_id)) {
871 OnDownloadItemAddedToPersistentStore(download_id, db_handle);
872 }
873 // It's valid that we don't find a matching item, i.e. on shutdown.
874}
875
[email protected]f9a45b02011-06-30 23:49:19876// Once the new DownloadItem's creation info has been committed to the history
877// service, we associate the DownloadItem with the db handle, update our
878// 'history_downloads_' map and inform observers.
[email protected]2588ea9d2011-08-22 20:59:53879void DownloadManager::OnDownloadItemAddedToPersistentStore(int32 download_id,
880 int64 db_handle) {
[email protected]f9a45b02011-06-30 23:49:19881 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]19420cc2011-07-18 17:43:45882 DownloadItem* download = GetActiveDownloadItem(download_id);
[email protected]93af2272011-09-21 18:29:17883 if (!download)
[email protected]19420cc2011-07-18 17:43:45884 return;
[email protected]54610672011-07-18 18:24:43885
886 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
887 << " download_id = " << download_id
888 << " download = " << download->DebugString(true);
[email protected]f9a45b02011-06-30 23:49:19889
[email protected]d8472d92011-08-26 20:15:20890 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]d8472d92011-08-26 20:15:20891 int64 largest_handle = largest_db_handle_in_history_;
892 base::debug::Alias(&largest_handle);
[email protected]e5107ce2011-09-19 20:36:13893 int32 matching_item_download_id
894 = (ContainsKey(history_downloads_, db_handle) ?
895 history_downloads_[db_handle]->id() : 0);
896 base::debug::Alias(&matching_item_download_id);
897
[email protected]61b75a52011-08-29 16:34:34898 CHECK(!ContainsKey(history_downloads_, db_handle));
[email protected]d8472d92011-08-26 20:15:20899
[email protected]f9a45b02011-06-30 23:49:19900 AddDownloadItemToHistory(download, db_handle);
initial.commit09911bf2008-07-26 23:55:29901
[email protected]93af2272011-09-21 18:29:17902 // If the download is still in progress, try to complete it.
903 //
904 // Otherwise, download has been cancelled or interrupted before we've
905 // received the DB handle. We post one final message to the history
906 // service so that it can be properly in sync with the DownloadItem's
907 // completion status, and also inform any observers so that they get
908 // more than just the start notification.
909 if (download->IsInProgress()) {
910 MaybeCompleteDownload(download);
911 } else {
[email protected]639ddad2011-10-05 02:53:47912 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/85408
[email protected]93af2272011-09-21 18:29:17913 // is fixed.
914 CHECK(download->IsCancelled())
915 << " download = " << download->DebugString(true);
916 in_progress_.erase(download_id);
917 active_downloads_.erase(download_id);
918 delegate_->UpdateItemInPersistentStore(download);
919 download->UpdateObservers();
920 }
initial.commit09911bf2008-07-26 23:55:29921}
922
[email protected]4cd82f72011-05-23 19:15:01923void DownloadManager::ShowDownloadInBrowser(DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:34924 // The 'contents' may no longer exist if the user closed the tab before we
[email protected]99cb7f82011-07-28 17:27:26925 // get this start completion event.
[email protected]db6831a2011-06-09 21:08:28926 DownloadRequestHandle request_handle = download->request_handle();
[email protected]686493142011-07-15 21:47:22927 TabContents* content = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:26928
929 // If the contents no longer exists, we ask the embedder to suggest another
930 // tab.
[email protected]da1a27b2011-07-29 23:16:33931 if (!content)
[email protected]aa9881c2011-08-15 18:01:12932 content = delegate_->GetAlternativeTabContentsToNotifyForDownload();
[email protected]5e595482009-05-06 20:16:53933
[email protected]99cb7f82011-07-28 17:27:26934 if (content)
935 content->OnStartDownload(download);
[email protected]5e595482009-05-06 20:16:53936}
937
[email protected]6cade212008-12-03 00:32:22938// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:12939void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:41940 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:38941}
[email protected]b0ab1d42010-02-24 19:29:28942
943void DownloadManager::NotifyModelChanged() {
944 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
945}
946
[email protected]4cd82f72011-05-23 19:15:01947DownloadItem* DownloadManager::GetDownloadItem(int download_id) {
948 // The |history_downloads_| map is indexed by the download's db_handle,
949 // not its id, so we have to iterate.
[email protected]f04182f32010-12-10 19:12:07950 for (DownloadMap::iterator it = history_downloads_.begin();
951 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:36952 DownloadItem* item = it->second;
[email protected]4cd82f72011-05-23 19:15:01953 if (item->id() == download_id)
[email protected]2e030682010-07-23 19:45:36954 return item;
955 }
956 return NULL;
957}
958
[email protected]4cd82f72011-05-23 19:15:01959DownloadItem* DownloadManager::GetActiveDownloadItem(int download_id) {
[email protected]93af2272011-09-21 18:29:17960 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]4cd82f72011-05-23 19:15:01961 DownloadItem* download = active_downloads_[download_id];
962 DCHECK(download != NULL);
963 return download;
964}
965
[email protected]57fd1252010-12-23 17:24:09966// Confirm that everything in all maps is also in |downloads_|, and that
967// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:07968void DownloadManager::AssertContainersConsistent() const {
969#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:09970 // Turn everything into sets.
[email protected]6d0146c2011-08-04 19:13:04971 const DownloadMap* input_maps[] = {&active_downloads_,
972 &history_downloads_,
973 &save_page_downloads_};
974 DownloadSet active_set, history_set, save_page_set;
975 DownloadSet* all_sets[] = {&active_set, &history_set, &save_page_set};
976 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(all_sets));
[email protected]57fd1252010-12-23 17:24:09977 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
978 for (DownloadMap::const_iterator it = input_maps[i]->begin();
[email protected]6d0146c2011-08-04 19:13:04979 it != input_maps[i]->end(); ++it) {
980 all_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:07981 }
982 }
[email protected]57fd1252010-12-23 17:24:09983
984 // Check if each set is fully present in downloads, and create a union.
[email protected]57fd1252010-12-23 17:24:09985 DownloadSet downloads_union;
986 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
987 DownloadSet remainder;
988 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
989 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
990 downloads_.begin(), downloads_.end(),
991 insert_it);
992 DCHECK(remainder.empty());
993 std::insert_iterator<DownloadSet>
994 insert_union(downloads_union, downloads_union.end());
995 std::set_union(downloads_union.begin(), downloads_union.end(),
996 all_sets[i]->begin(), all_sets[i]->end(),
997 insert_union);
998 }
999
1000 // Is everything in downloads_ present in one of the other sets?
1001 DownloadSet remainder;
1002 std::insert_iterator<DownloadSet>
1003 insert_remainder(remainder, remainder.begin());
1004 std::set_difference(downloads_.begin(), downloads_.end(),
1005 downloads_union.begin(), downloads_union.end(),
1006 insert_remainder);
1007 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:071008#endif
1009}
1010
[email protected]6d0146c2011-08-04 19:13:041011void DownloadManager::SavePageDownloadStarted(DownloadItem* download) {
1012 DCHECK(!ContainsKey(save_page_downloads_, download->id()));
1013 downloads_.insert(download);
1014 save_page_downloads_[download->id()] = download;
1015
1016 // Add this entry to the history service.
1017 // Additionally, the UI is notified in the callback.
[email protected]2588ea9d2011-08-22 20:59:531018 delegate_->AddItemToPersistentStore(download);
[email protected]6d0146c2011-08-04 19:13:041019}
1020
1021// SavePackage will call SavePageDownloadFinished upon completion/cancellation.
[email protected]2588ea9d2011-08-22 20:59:531022// The history callback will call OnSavePageItemAddedToPersistentStore.
[email protected]6d0146c2011-08-04 19:13:041023// If the download finishes before the history callback,
[email protected]2588ea9d2011-08-22 20:59:531024// OnSavePageItemAddedToPersistentStore calls SavePageDownloadFinished, ensuring
1025// that the history event is update regardless of the order in which these two
1026// events complete.
[email protected]6d0146c2011-08-04 19:13:041027// If something removes the download item from the download manager (Remove,
1028// Shutdown) the result will be that the SavePage system will not be able to
1029// properly update the download item (which no longer exists) or the download
1030// history, but the action will complete properly anyway. This may lead to the
1031// history entry being wrong on a reload of chrome (specifically in the case of
1032// Initiation -> History Callback -> Removal -> Completion), but there's no way
1033// to solve that without canceling on Remove (which would then update the DB).
1034
[email protected]2588ea9d2011-08-22 20:59:531035void DownloadManager::OnSavePageItemAddedToPersistentStore(int32 download_id,
1036 int64 db_handle) {
[email protected]6d0146c2011-08-04 19:13:041037 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1038
1039 DownloadMap::const_iterator it = save_page_downloads_.find(download_id);
1040 // This can happen if the download manager is shutting down and all maps
1041 // have been cleared.
1042 if (it == save_page_downloads_.end())
1043 return;
1044
1045 DownloadItem* download = it->second;
1046 if (!download) {
1047 NOTREACHED();
1048 return;
1049 }
1050
[email protected]d8472d92011-08-26 20:15:201051 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]d8472d92011-08-26 20:15:201052 int64 largest_handle = largest_db_handle_in_history_;
1053 base::debug::Alias(&largest_handle);
[email protected]61b75a52011-08-29 16:34:341054 CHECK(!ContainsKey(history_downloads_, db_handle));
[email protected]d8472d92011-08-26 20:15:201055
[email protected]6d0146c2011-08-04 19:13:041056 AddDownloadItemToHistory(download, db_handle);
1057
1058 // Finalize this download if it finished before the history callback.
1059 if (!download->IsInProgress())
1060 SavePageDownloadFinished(download);
1061}
1062
1063void DownloadManager::SavePageDownloadFinished(DownloadItem* download) {
[email protected]2588ea9d2011-08-22 20:59:531064 if (download->db_handle() != DownloadItem::kUninitializedHandle) {
1065 delegate_->UpdateItemInPersistentStore(download);
[email protected]6d0146c2011-08-04 19:13:041066 DCHECK(ContainsKey(save_page_downloads_, download->id()));
1067 save_page_downloads_.erase(download->id());
1068
1069 if (download->IsComplete())
1070 NotificationService::current()->Notify(
1071 content::NOTIFICATION_SAVE_PACKAGE_SUCCESSFULLY_FINISHED,
1072 Source<DownloadManager>(this),
1073 Details<DownloadItem>(download));
1074 }
1075}