blob: 8f6d03b1a6f580fd58db50cd149c7840ca012efb [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]821960a2011-08-23 20:40:03440 if (ContainsKey(active_downloads_, download->id()))
441 CHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
442 if (DownloadItem::IN_PROGRESS == download->state())
443 CHECK(ContainsKey(active_downloads_, download->id()));
[email protected]5cd11b6e2011-06-10 20:30:59444}
445
[email protected]adb2f3d12011-01-23 16:24:54446bool DownloadManager::IsDownloadReadyForCompletion(DownloadItem* download) {
447 // If we don't have all the data, the download is not ready for
448 // completion.
449 if (!download->all_data_saved())
450 return false;
[email protected]6a7fb042010-02-01 16:30:47451
[email protected]9d7ef802011-02-25 19:03:35452 // If the download is dangerous, but not yet validated, it's not ready for
453 // completion.
454 if (download->safety_state() == DownloadItem::DANGEROUS)
455 return false;
456
[email protected]adb2f3d12011-01-23 16:24:54457 // If the download isn't active (e.g. has been cancelled) it's not
458 // ready for completion.
459 if (active_downloads_.count(download->id()) == 0)
460 return false;
461
462 // If the download hasn't been inserted into the history system
463 // (which occurs strictly after file name determination, intermediate
464 // file rename, and UI display) then it's not ready for completion.
[email protected]2588ea9d2011-08-22 20:59:53465 if (download->db_handle() == DownloadItem::kUninitializedHandle)
[email protected]7054b592011-06-22 14:46:42466 return false;
467
468 return true;
[email protected]adb2f3d12011-01-23 16:24:54469}
470
471void DownloadManager::MaybeCompleteDownload(DownloadItem* download) {
472 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
473 VLOG(20) << __FUNCTION__ << "()" << " download = "
474 << download->DebugString(false);
475
476 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32477 return;
[email protected]9ccbb372008-10-10 18:50:32478
[email protected]adb2f3d12011-01-23 16:24:54479 // TODO(rdsmith): DCHECK that we only pass through this point
480 // once per download. The natural way to do this is by a state
481 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56482
[email protected]adb2f3d12011-01-23 16:24:54483 // Confirm we're in the proper set of states to be here;
[email protected]9d7ef802011-02-25 19:03:35484 // in in_progress_, have all data, have a history handle, (validated or safe).
485 DCHECK_NE(DownloadItem::DANGEROUS, download->safety_state());
[email protected]adb2f3d12011-01-23 16:24:54486 DCHECK_EQ(1u, in_progress_.count(download->id()));
487 DCHECK(download->all_data_saved());
[email protected]2588ea9d2011-08-22 20:59:53488 DCHECK(download->db_handle() != DownloadItem::kUninitializedHandle);
[email protected]adb2f3d12011-01-23 16:24:54489 DCHECK_EQ(1u, history_downloads_.count(download->db_handle()));
490
491 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
492 << download->DebugString(false);
493
494 // Remove the id from in_progress
495 in_progress_.erase(download->id());
[email protected]5f8589fe2011-08-17 20:58:39496 UpdateDownloadProgress(); // Reflect removal from in_progress_.
[email protected]adb2f3d12011-01-23 16:24:54497
[email protected]2588ea9d2011-08-22 20:59:53498 delegate_->UpdateItemInPersistentStore(download);
[email protected]adb2f3d12011-01-23 16:24:54499
[email protected]f5920322011-03-24 20:34:16500 // Finish the download.
[email protected]48837962011-04-19 17:03:29501 download->OnDownloadCompleting(file_manager_);
[email protected]9ccbb372008-10-10 18:50:32502}
503
[email protected]cc3c7c092011-05-09 18:40:21504void DownloadManager::DownloadCompleted(int32 download_id) {
[email protected]70850c72011-01-11 17:31:27505 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21506 DownloadItem* download = GetDownloadItem(download_id);
507 DCHECK(download);
[email protected]2588ea9d2011-08-22 20:59:53508 delegate_->UpdateItemInPersistentStore(download);
[email protected]70850c72011-01-11 17:31:27509 active_downloads_.erase(download_id);
[email protected]821960a2011-08-23 20:40:03510 AssertQueueStateConsistent(download);
[email protected]70850c72011-01-11 17:31:27511}
512
[email protected]f5920322011-03-24 20:34:16513void DownloadManager::OnDownloadRenamedToFinalName(int download_id,
514 const FilePath& full_path,
515 int uniquifier) {
[email protected]da6e3922010-11-24 21:45:50516 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
[email protected]f5920322011-03-24 20:34:16517 << " full_path = \"" << full_path.value() << "\""
518 << " uniquifier = " << uniquifier;
[email protected]ca4b5fa32010-10-09 12:42:18519 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]f5920322011-03-24 20:34:16520
[email protected]2e030682010-07-23 19:45:36521 DownloadItem* item = GetDownloadItem(download_id);
522 if (!item)
523 return;
[email protected]6cade212008-12-03 00:32:22524
[email protected]8fa1eeb52011-04-13 14:18:02525 if (item->safety_state() == DownloadItem::SAFE) {
526 DCHECK_EQ(0, uniquifier) << "We should not uniquify SAFE downloads twice";
527 }
528
[email protected]eda58402011-09-21 19:32:02529 BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(
530 file_manager_,
531 &DownloadFileManager::CompleteDownload,
532 item->global_id()));
[email protected]9ccbb372008-10-10 18:50:32533
[email protected]f5920322011-03-24 20:34:16534 if (uniquifier)
535 item->set_path_uniquifier(uniquifier);
[email protected]9ccbb372008-10-10 18:50:32536
[email protected]f5920322011-03-24 20:34:16537 item->OnDownloadRenamedToFinalName(full_path);
[email protected]2588ea9d2011-08-22 20:59:53538 delegate_->UpdatePathForItemInPersistentStore(item, full_path);
initial.commit09911bf2008-07-26 23:55:29539}
540
[email protected]93af2272011-09-21 18:29:17541void DownloadManager::CancelDownload(int32 download_id) {
542 DownloadItem* download = GetActiveDownload(download_id);
543 // A cancel at the right time could remove the download from the
544 // |active_downloads_| map before we get here.
545 if (!download)
546 return;
547
548 download->Cancel(true);
549}
550
551void DownloadManager::DownloadCancelledInternal(DownloadItem* download) {
[email protected]d8472d92011-08-26 20:15:20552 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d8472d92011-08-26 20:15:20553
554 VLOG(20) << __FUNCTION__ << "()"
[email protected]da6e3922010-11-24 21:45:50555 << " download = " << download->DebugString(true);
556
[email protected]93af2272011-09-21 18:29:17557 RemoveFromActiveList(download);
[email protected]47a881b2011-08-29 22:59:21558 // This function is called from the DownloadItem, so DI state
559 // should already have been updated.
560 AssertQueueStateConsistent(download);
initial.commit09911bf2008-07-26 23:55:29561
[email protected]d8472d92011-08-26 20:15:20562 download->OffThreadCancel(file_manager_);
initial.commit09911bf2008-07-26 23:55:29563}
564
[email protected]bf68a00b2011-04-07 17:28:26565void DownloadManager::OnDownloadError(int32 download_id,
566 int64 size,
[email protected]33c6d3f12011-09-04 00:00:54567 net::Error error) {
[email protected]47a881b2011-08-29 22:59:21568 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
569
570 DownloadItem* download = GetActiveDownload(download_id);
571 if (!download)
572 return;
573
574 VLOG(20) << __FUNCTION__ << "()" << " Error " << error
575 << " at offset " << download->received_bytes()
576 << " size = " << size
577 << " download = " << download->DebugString(true);
578
[email protected]93af2272011-09-21 18:29:17579 RemoveFromActiveList(download);
580 download->Interrupted(size, error);
581 download->OffThreadCancel(file_manager_);
[email protected]47a881b2011-08-29 22:59:21582}
583
584DownloadItem* DownloadManager::GetActiveDownload(int32 download_id) {
[email protected]bf68a00b2011-04-07 17:28:26585 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
586 DownloadMap::iterator it = active_downloads_.find(download_id);
[email protected]bf68a00b2011-04-07 17:28:26587 if (it == active_downloads_.end())
[email protected]47a881b2011-08-29 22:59:21588 return NULL;
[email protected]bf68a00b2011-04-07 17:28:26589
590 DownloadItem* download = it->second;
591
[email protected]47a881b2011-08-29 22:59:21592 DCHECK(download);
593 DCHECK_EQ(download_id, download->id());
[email protected]4cd82f72011-05-23 19:15:01594
[email protected]47a881b2011-08-29 22:59:21595 return download;
596}
[email protected]54610672011-07-18 18:24:43597
[email protected]93af2272011-09-21 18:29:17598void DownloadManager::RemoveFromActiveList(DownloadItem* download) {
599 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
600 DCHECK(download);
601
602 // Clean up will happen when the history system create callback runs if we
603 // don't have a valid db_handle yet.
604 if (download->db_handle() != DownloadItem::kUninitializedHandle) {
605 in_progress_.erase(download->id());
606 active_downloads_.erase(download->id());
607 UpdateDownloadProgress(); // Reflect removal from in_progress_.
608 delegate_->UpdateItemInPersistentStore(download);
609 }
610}
611
[email protected]5f8589fe2011-08-17 20:58:39612void DownloadManager::UpdateDownloadProgress() {
613 delegate_->DownloadProgressUpdated();
[email protected]6a7fb042010-02-01 16:30:47614}
615
[email protected]6d0146c2011-08-04 19:13:04616int DownloadManager::RemoveDownloadItems(
617 const DownloadVector& pending_deletes) {
618 if (pending_deletes.empty())
619 return 0;
620
621 // Delete from internal maps.
622 for (DownloadVector::const_iterator it = pending_deletes.begin();
623 it != pending_deletes.end();
624 ++it) {
625 DownloadItem* download = *it;
626 DCHECK(download);
627 history_downloads_.erase(download->db_handle());
628 save_page_downloads_.erase(download->id());
629 downloads_.erase(download);
630 }
631
632 // Tell observers to refresh their views.
633 NotifyModelChanged();
634
635 // Delete the download items themselves.
636 const int num_deleted = static_cast<int>(pending_deletes.size());
637 STLDeleteContainerPointers(pending_deletes.begin(), pending_deletes.end());
638 return num_deleted;
639}
640
[email protected]93af2272011-09-21 18:29:17641void DownloadManager::RemoveDownload(int64 download_handle) {
642 DownloadMap::iterator it = history_downloads_.find(download_handle);
643 if (it == history_downloads_.end())
644 return;
645
646 // Make history update.
647 DownloadItem* download = it->second;
648 delegate_->RemoveItemFromPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29649
650 // Remove from our tables and delete.
[email protected]6d0146c2011-08-04 19:13:04651 int downloads_count = RemoveDownloadItems(DownloadVector(1, download));
[email protected]f04182f32010-12-10 19:12:07652 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29653}
654
[email protected]e93d2822009-01-30 05:59:59655int DownloadManager::RemoveDownloadsBetween(const base::Time remove_begin,
656 const base::Time remove_end) {
[email protected]2588ea9d2011-08-22 20:59:53657 delegate_->RemoveItemsFromPersistentStoreBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29658
[email protected]a312a442010-12-15 23:40:33659 // All downloads visible to the user will be in the history,
660 // so scan that map.
[email protected]6d0146c2011-08-04 19:13:04661 DownloadVector pending_deletes;
662 for (DownloadMap::const_iterator it = history_downloads_.begin();
663 it != history_downloads_.end();
664 ++it) {
initial.commit09911bf2008-07-26 23:55:29665 DownloadItem* download = it->second;
initial.commit09911bf2008-07-26 23:55:29666 if (download->start_time() >= remove_begin &&
667 (remove_end.is_null() || download->start_time() < remove_end) &&
[email protected]6d0146c2011-08-04 19:13:04668 (download->IsComplete() || download->IsCancelled())) {
[email protected]7d413112011-06-16 18:50:17669 AssertQueueStateConsistent(download);
[email protected]78b8fcc92009-03-31 17:36:28670 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29671 }
initial.commit09911bf2008-07-26 23:55:29672 }
[email protected]6d0146c2011-08-04 19:13:04673 return RemoveDownloadItems(pending_deletes);
initial.commit09911bf2008-07-26 23:55:29674}
675
[email protected]e93d2822009-01-30 05:59:59676int DownloadManager::RemoveDownloads(const base::Time remove_begin) {
677 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29678}
679
[email protected]d41355e6f2009-04-07 21:21:12680int DownloadManager::RemoveAllDownloads() {
681 // The null times make the date range unbounded.
682 return RemoveDownloadsBetween(base::Time(), base::Time());
683}
684
initial.commit09911bf2008-07-26 23:55:29685// Initiate a download of a specific URL. We send the request to the
686// ResourceDispatcherHost, and let it send us responses like a regular
687// download.
688void DownloadManager::DownloadUrl(const GURL& url,
689 const GURL& referrer,
[email protected]c9825a42009-05-01 22:51:50690 const std::string& referrer_charset,
[email protected]57c6a652009-05-04 07:58:34691 TabContents* tab_contents) {
[email protected]ae8945192010-07-20 16:56:26692 DownloadUrlToFile(url, referrer, referrer_charset, DownloadSaveInfo(),
693 tab_contents);
[email protected]6aa4a1c02010-01-15 18:49:58694}
695
696void DownloadManager::DownloadUrlToFile(const GURL& url,
697 const GURL& referrer,
698 const std::string& referrer_charset,
[email protected]8af9d032010-02-10 00:00:32699 const DownloadSaveInfo& save_info,
[email protected]6aa4a1c02010-01-15 18:49:58700 TabContents* tab_contents) {
[email protected]57c6a652009-05-04 07:58:34701 DCHECK(tab_contents);
[email protected]c79a0c02011-08-22 22:37:37702 ResourceDispatcherHost* resource_dispatcher_host =
703 content::GetContentClient()->browser()->GetResourceDispatcherHost();
[email protected]ed24fad2011-05-10 22:44:01704 // We send a pointer to content::ResourceContext, instead of the usual
705 // reference, so that a copy of the object isn't made.
[email protected]ca4b5fa32010-10-09 12:42:18706 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
[email protected]a0ce3282011-08-19 20:49:52707 NewRunnableFunction(&BeginDownload,
[email protected]ae8945192010-07-20 16:56:26708 url,
709 referrer,
[email protected]ae8945192010-07-20 16:56:26710 save_info,
[email protected]c79a0c02011-08-22 22:37:37711 resource_dispatcher_host,
[email protected]ae8945192010-07-20 16:56:26712 tab_contents->GetRenderProcessHost()->id(),
713 tab_contents->render_view_host()->routing_id(),
[email protected]cafe4ad2011-07-28 18:34:56714 &tab_contents->browser_context()->
715 GetResourceContext()));
initial.commit09911bf2008-07-26 23:55:29716}
717
initial.commit09911bf2008-07-26 23:55:29718void DownloadManager::AddObserver(Observer* observer) {
719 observers_.AddObserver(observer);
720 observer->ModelChanged();
721}
722
723void DownloadManager::RemoveObserver(Observer* observer) {
724 observers_.RemoveObserver(observer);
725}
726
[email protected]073ed7b2010-09-27 09:20:02727bool DownloadManager::IsDownloadProgressKnown() {
728 for (DownloadMap::iterator i = in_progress_.begin();
729 i != in_progress_.end(); ++i) {
730 if (i->second->total_bytes() <= 0)
731 return false;
732 }
733
734 return true;
735}
736
737int64 DownloadManager::GetInProgressDownloadCount() {
738 return in_progress_.size();
739}
740
741int64 DownloadManager::GetReceivedDownloadBytes() {
742 DCHECK(IsDownloadProgressKnown());
743 int64 received_bytes = 0;
744 for (DownloadMap::iterator i = in_progress_.begin();
745 i != in_progress_.end(); ++i) {
746 received_bytes += i->second->received_bytes();
747 }
748 return received_bytes;
749}
750
751int64 DownloadManager::GetTotalDownloadBytes() {
752 DCHECK(IsDownloadProgressKnown());
753 int64 total_bytes = 0;
754 for (DownloadMap::iterator i = in_progress_.begin();
755 i != in_progress_.end(); ++i) {
756 total_bytes += i->second->total_bytes();
757 }
758 return total_bytes;
759}
760
[email protected]99cb7f82011-07-28 17:27:26761void DownloadManager::FileSelected(const FilePath& path, void* params) {
[email protected]4cd82f72011-05-23 19:15:01762 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
763
764 int32* id_ptr = reinterpret_cast<int32*>(params);
765 DCHECK(id_ptr != NULL);
766 int32 download_id = *id_ptr;
767 delete id_ptr;
768
769 DownloadItem* download = GetActiveDownloadItem(download_id);
770 if (!download)
771 return;
772 VLOG(20) << __FUNCTION__ << "()" << " path = \"" << path.value() << "\""
773 << " download = " << download->DebugString(true);
774
[email protected]da1a27b2011-07-29 23:16:33775 if (download->prompt_user_for_save_location())
[email protected]7ae7c2cb2009-01-06 23:31:41776 last_download_path_ = path.DirName();
[email protected]287b86b2011-02-26 00:11:35777
[email protected]4cd82f72011-05-23 19:15:01778 // Make sure the initial file name is set only once.
779 ContinueDownloadWithPath(download, path);
initial.commit09911bf2008-07-26 23:55:29780}
781
782void DownloadManager::FileSelectionCanceled(void* params) {
783 // The user didn't pick a place to save the file, so need to cancel the
784 // download that's already in progress to the temporary location.
[email protected]4cd82f72011-05-23 19:15:01785 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
786 int32* id_ptr = reinterpret_cast<int32*>(params);
787 DCHECK(id_ptr != NULL);
788 int32 download_id = *id_ptr;
789 delete id_ptr;
790
791 DownloadItem* download = GetActiveDownloadItem(download_id);
792 if (!download)
793 return;
794
795 VLOG(20) << __FUNCTION__ << "()"
796 << " download = " << download->DebugString(true);
797
[email protected]93af2272011-09-21 18:29:17798 // TODO(ahendrickson) -- This currently has no effect, as the download is
799 // not put on the active list until the file selection is complete. Need
800 // to put it on the active list earlier in the process.
801 RemoveFromActiveList(download);
802
803 download->OffThreadCancel(file_manager_);
[email protected]4cd82f72011-05-23 19:15:01804}
805
initial.commit09911bf2008-07-26 23:55:29806// Operations posted to us from the history service ----------------------------
807
808// The history service has retrieved all download entries. 'entries' contains
[email protected]bb1a4212011-08-22 22:38:25809// 'DownloadPersistentStoreInfo's in sorted order (by ascending start_time).
[email protected]2588ea9d2011-08-22 20:59:53810void DownloadManager::OnPersistentStoreQueryComplete(
[email protected]bb1a4212011-08-22 22:38:25811 std::vector<DownloadPersistentStoreInfo>* entries) {
[email protected]d8472d92011-08-26 20:15:20812 // TODO(rdsmith): Remove this and related logic when
813 // http://crbug.com/84508 is fixed.
814 largest_db_handle_in_history_ = 0;
815
initial.commit09911bf2008-07-26 23:55:29816 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]aa033af2010-07-27 18:16:39817 DownloadItem* download = new DownloadItem(this, entries->at(i));
[email protected]d8472d92011-08-26 20:15:20818 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]821960a2011-08-23 20:40:03819 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
[email protected]f04182f32010-12-10 19:12:07820 downloads_.insert(download);
821 history_downloads_[download->db_handle()] = download;
[email protected]da6e3922010-11-24 21:45:50822 VLOG(20) << __FUNCTION__ << "()" << i << ">"
823 << " download = " << download->DebugString(true);
[email protected]d8472d92011-08-26 20:15:20824
825 if (download->db_handle() > largest_db_handle_in_history_)
826 largest_db_handle_in_history_ = download->db_handle();
initial.commit09911bf2008-07-26 23:55:29827 }
[email protected]b0ab1d42010-02-24 19:29:28828 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:48829 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:29830}
831
[email protected]f9a45b02011-06-30 23:49:19832void DownloadManager::AddDownloadItemToHistory(DownloadItem* download,
833 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:27834 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d2a8fb72010-01-21 05:31:42835
[email protected]1e9fe7ff2011-06-24 17:37:33836 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/84508
837 // is fixed.
[email protected]2588ea9d2011-08-22 20:59:53838 CHECK_NE(DownloadItem::kUninitializedHandle, db_handle);
[email protected]1e9fe7ff2011-06-24 17:37:33839
[email protected]2588ea9d2011-08-22 20:59:53840 DCHECK(download->db_handle() == DownloadItem::kUninitializedHandle);
[email protected]5bcd73eb2011-03-23 21:14:02841 download->set_db_handle(db_handle);
842
[email protected]d8472d92011-08-26 20:15:20843 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/84508
844 // is fixed.
[email protected]821960a2011-08-23 20:40:03845 CHECK(!ContainsKey(history_downloads_, download->db_handle()));
[email protected]5bcd73eb2011-03-23 21:14:02846 history_downloads_[download->db_handle()] = download;
[email protected]6d0146c2011-08-04 19:13:04847
848 // Show in the appropriate browser UI.
849 // This includes buttons to save or cancel, for a dangerous download.
850 ShowDownloadInBrowser(download);
851
852 // Inform interested objects about the new download.
853 NotifyModelChanged();
[email protected]f9a45b02011-06-30 23:49:19854}
855
[email protected]2588ea9d2011-08-22 20:59:53856
857void DownloadManager::OnItemAddedToPersistentStore(int32 download_id,
858 int64 db_handle) {
859 if (save_page_downloads_.count(download_id)) {
860 OnSavePageItemAddedToPersistentStore(download_id, db_handle);
861 } else if (active_downloads_.count(download_id)) {
862 OnDownloadItemAddedToPersistentStore(download_id, db_handle);
863 }
864 // It's valid that we don't find a matching item, i.e. on shutdown.
865}
866
[email protected]f9a45b02011-06-30 23:49:19867// Once the new DownloadItem's creation info has been committed to the history
868// service, we associate the DownloadItem with the db handle, update our
869// 'history_downloads_' map and inform observers.
[email protected]2588ea9d2011-08-22 20:59:53870void DownloadManager::OnDownloadItemAddedToPersistentStore(int32 download_id,
871 int64 db_handle) {
[email protected]f9a45b02011-06-30 23:49:19872 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]19420cc2011-07-18 17:43:45873 DownloadItem* download = GetActiveDownloadItem(download_id);
[email protected]93af2272011-09-21 18:29:17874 if (!download)
[email protected]19420cc2011-07-18 17:43:45875 return;
[email protected]54610672011-07-18 18:24:43876
877 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << db_handle
878 << " download_id = " << download_id
879 << " download = " << download->DebugString(true);
[email protected]f9a45b02011-06-30 23:49:19880
[email protected]d8472d92011-08-26 20:15:20881 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]d8472d92011-08-26 20:15:20882 int64 largest_handle = largest_db_handle_in_history_;
883 base::debug::Alias(&largest_handle);
[email protected]e5107ce2011-09-19 20:36:13884 int32 matching_item_download_id
885 = (ContainsKey(history_downloads_, db_handle) ?
886 history_downloads_[db_handle]->id() : 0);
887 base::debug::Alias(&matching_item_download_id);
888
[email protected]61b75a52011-08-29 16:34:34889 CHECK(!ContainsKey(history_downloads_, db_handle));
[email protected]d8472d92011-08-26 20:15:20890
[email protected]f9a45b02011-06-30 23:49:19891 AddDownloadItemToHistory(download, db_handle);
initial.commit09911bf2008-07-26 23:55:29892
[email protected]93af2272011-09-21 18:29:17893 // If the download is still in progress, try to complete it.
894 //
895 // Otherwise, download has been cancelled or interrupted before we've
896 // received the DB handle. We post one final message to the history
897 // service so that it can be properly in sync with the DownloadItem's
898 // completion status, and also inform any observers so that they get
899 // more than just the start notification.
900 if (download->IsInProgress()) {
901 MaybeCompleteDownload(download);
902 } else {
903 // TODO(rdsmith): Convert to DCHECK() when http://crbug.com/84508
904 // is fixed.
905 CHECK(download->IsCancelled())
906 << " download = " << download->DebugString(true);
907 in_progress_.erase(download_id);
908 active_downloads_.erase(download_id);
909 delegate_->UpdateItemInPersistentStore(download);
910 download->UpdateObservers();
911 }
initial.commit09911bf2008-07-26 23:55:29912}
913
[email protected]4cd82f72011-05-23 19:15:01914void DownloadManager::ShowDownloadInBrowser(DownloadItem* download) {
[email protected]8ddbd66a2010-05-21 16:38:34915 // The 'contents' may no longer exist if the user closed the tab before we
[email protected]99cb7f82011-07-28 17:27:26916 // get this start completion event.
[email protected]db6831a2011-06-09 21:08:28917 DownloadRequestHandle request_handle = download->request_handle();
[email protected]686493142011-07-15 21:47:22918 TabContents* content = request_handle.GetTabContents();
[email protected]99cb7f82011-07-28 17:27:26919
920 // If the contents no longer exists, we ask the embedder to suggest another
921 // tab.
[email protected]da1a27b2011-07-29 23:16:33922 if (!content)
[email protected]aa9881c2011-08-15 18:01:12923 content = delegate_->GetAlternativeTabContentsToNotifyForDownload();
[email protected]5e595482009-05-06 20:16:53924
[email protected]99cb7f82011-07-28 17:27:26925 if (content)
926 content->OnStartDownload(download);
[email protected]5e595482009-05-06 20:16:53927}
928
[email protected]6cade212008-12-03 00:32:22929// Clears the last download path, used to initialize "save as" dialogs.
[email protected]905a08d2008-11-19 07:24:12930void DownloadManager::ClearLastDownloadPath() {
[email protected]7ae7c2cb2009-01-06 23:31:41931 last_download_path_ = FilePath();
[email protected]eea46622009-07-15 20:49:38932}
[email protected]b0ab1d42010-02-24 19:29:28933
934void DownloadManager::NotifyModelChanged() {
935 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
936}
937
[email protected]4cd82f72011-05-23 19:15:01938DownloadItem* DownloadManager::GetDownloadItem(int download_id) {
939 // The |history_downloads_| map is indexed by the download's db_handle,
940 // not its id, so we have to iterate.
[email protected]f04182f32010-12-10 19:12:07941 for (DownloadMap::iterator it = history_downloads_.begin();
942 it != history_downloads_.end(); ++it) {
[email protected]2e030682010-07-23 19:45:36943 DownloadItem* item = it->second;
[email protected]4cd82f72011-05-23 19:15:01944 if (item->id() == download_id)
[email protected]2e030682010-07-23 19:45:36945 return item;
946 }
947 return NULL;
948}
949
[email protected]4cd82f72011-05-23 19:15:01950DownloadItem* DownloadManager::GetActiveDownloadItem(int download_id) {
[email protected]93af2272011-09-21 18:29:17951 DCHECK(ContainsKey(active_downloads_, download_id));
[email protected]4cd82f72011-05-23 19:15:01952 DownloadItem* download = active_downloads_[download_id];
953 DCHECK(download != NULL);
954 return download;
955}
956
[email protected]57fd1252010-12-23 17:24:09957// Confirm that everything in all maps is also in |downloads_|, and that
958// everything in |downloads_| is also in some other map.
[email protected]f04182f32010-12-10 19:12:07959void DownloadManager::AssertContainersConsistent() const {
960#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:09961 // Turn everything into sets.
[email protected]6d0146c2011-08-04 19:13:04962 const DownloadMap* input_maps[] = {&active_downloads_,
963 &history_downloads_,
964 &save_page_downloads_};
965 DownloadSet active_set, history_set, save_page_set;
966 DownloadSet* all_sets[] = {&active_set, &history_set, &save_page_set};
967 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(all_sets));
[email protected]57fd1252010-12-23 17:24:09968 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
969 for (DownloadMap::const_iterator it = input_maps[i]->begin();
[email protected]6d0146c2011-08-04 19:13:04970 it != input_maps[i]->end(); ++it) {
971 all_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:07972 }
973 }
[email protected]57fd1252010-12-23 17:24:09974
975 // Check if each set is fully present in downloads, and create a union.
[email protected]57fd1252010-12-23 17:24:09976 DownloadSet downloads_union;
977 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
978 DownloadSet remainder;
979 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
980 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
981 downloads_.begin(), downloads_.end(),
982 insert_it);
983 DCHECK(remainder.empty());
984 std::insert_iterator<DownloadSet>
985 insert_union(downloads_union, downloads_union.end());
986 std::set_union(downloads_union.begin(), downloads_union.end(),
987 all_sets[i]->begin(), all_sets[i]->end(),
988 insert_union);
989 }
990
991 // Is everything in downloads_ present in one of the other sets?
992 DownloadSet remainder;
993 std::insert_iterator<DownloadSet>
994 insert_remainder(remainder, remainder.begin());
995 std::set_difference(downloads_.begin(), downloads_.end(),
996 downloads_union.begin(), downloads_union.end(),
997 insert_remainder);
998 DCHECK(remainder.empty());
[email protected]f04182f32010-12-10 19:12:07999#endif
1000}
1001
[email protected]6d0146c2011-08-04 19:13:041002void DownloadManager::SavePageDownloadStarted(DownloadItem* download) {
1003 DCHECK(!ContainsKey(save_page_downloads_, download->id()));
1004 downloads_.insert(download);
1005 save_page_downloads_[download->id()] = download;
1006
1007 // Add this entry to the history service.
1008 // Additionally, the UI is notified in the callback.
[email protected]2588ea9d2011-08-22 20:59:531009 delegate_->AddItemToPersistentStore(download);
[email protected]6d0146c2011-08-04 19:13:041010}
1011
1012// SavePackage will call SavePageDownloadFinished upon completion/cancellation.
[email protected]2588ea9d2011-08-22 20:59:531013// The history callback will call OnSavePageItemAddedToPersistentStore.
[email protected]6d0146c2011-08-04 19:13:041014// If the download finishes before the history callback,
[email protected]2588ea9d2011-08-22 20:59:531015// OnSavePageItemAddedToPersistentStore calls SavePageDownloadFinished, ensuring
1016// that the history event is update regardless of the order in which these two
1017// events complete.
[email protected]6d0146c2011-08-04 19:13:041018// If something removes the download item from the download manager (Remove,
1019// Shutdown) the result will be that the SavePage system will not be able to
1020// properly update the download item (which no longer exists) or the download
1021// history, but the action will complete properly anyway. This may lead to the
1022// history entry being wrong on a reload of chrome (specifically in the case of
1023// Initiation -> History Callback -> Removal -> Completion), but there's no way
1024// to solve that without canceling on Remove (which would then update the DB).
1025
[email protected]2588ea9d2011-08-22 20:59:531026void DownloadManager::OnSavePageItemAddedToPersistentStore(int32 download_id,
1027 int64 db_handle) {
[email protected]6d0146c2011-08-04 19:13:041028 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1029
1030 DownloadMap::const_iterator it = save_page_downloads_.find(download_id);
1031 // This can happen if the download manager is shutting down and all maps
1032 // have been cleared.
1033 if (it == save_page_downloads_.end())
1034 return;
1035
1036 DownloadItem* download = it->second;
1037 if (!download) {
1038 NOTREACHED();
1039 return;
1040 }
1041
[email protected]d8472d92011-08-26 20:15:201042 // TODO(rdsmith): Remove after http://crbug.com/85408 resolved.
[email protected]d8472d92011-08-26 20:15:201043 int64 largest_handle = largest_db_handle_in_history_;
1044 base::debug::Alias(&largest_handle);
[email protected]61b75a52011-08-29 16:34:341045 CHECK(!ContainsKey(history_downloads_, db_handle));
[email protected]d8472d92011-08-26 20:15:201046
[email protected]6d0146c2011-08-04 19:13:041047 AddDownloadItemToHistory(download, db_handle);
1048
1049 // Finalize this download if it finished before the history callback.
1050 if (!download->IsInProgress())
1051 SavePageDownloadFinished(download);
1052}
1053
1054void DownloadManager::SavePageDownloadFinished(DownloadItem* download) {
[email protected]2588ea9d2011-08-22 20:59:531055 if (download->db_handle() != DownloadItem::kUninitializedHandle) {
1056 delegate_->UpdateItemInPersistentStore(download);
[email protected]6d0146c2011-08-04 19:13:041057 DCHECK(ContainsKey(save_page_downloads_, download->id()));
1058 save_page_downloads_.erase(download->id());
1059
1060 if (download->IsComplete())
1061 NotificationService::current()->Notify(
1062 content::NOTIFICATION_SAVE_PACKAGE_SUCCESSFULLY_FINISHED,
1063 Source<DownloadManager>(this),
1064 Details<DownloadItem>(download));
1065 }
1066}