blob: 094fbdf47b0c6d1ea992525fc560f587af36ea0f [file] [log] [blame]
[email protected]0afff032012-01-06 20:55:001// Copyright (c) 2012 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]5656f8a2011-11-17 16:12:585#include "content/browser/download/download_manager_impl.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"
[email protected]c6944272012-01-06 22:12:2811#include "base/debug/alias.h"
initial.commit09911bf2008-07-26 23:55:2912#include "base/file_util.h"
[email protected]503d03872011-05-06 08:36:2613#include "base/i18n/case_conversion.h"
initial.commit09911bf2008-07-26 23:55:2914#include "base/logging.h"
[email protected]f1675202012-07-09 15:18:0015#include "base/message_loop.h"
[email protected]7286e3fc2011-07-19 22:13:2416#include "base/stl_util.h"
[email protected]eda58402011-09-21 19:32:0217#include "base/stringprintf.h"
[email protected]d59d40c2012-08-08 18:18:3718#include "base/supports_user_data.h"
[email protected]eda58402011-09-21 19:32:0219#include "base/synchronization/lock.h"
20#include "base/sys_string_conversions.h"
[email protected]d2a8fb72010-01-21 05:31:4221#include "build/build_config.h"
[email protected]2bddd2072012-06-18 16:16:5122#include "content/browser/download/byte_stream.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"
[email protected]c09a8fd2011-11-21 19:54:5025#include "content/browser/download/download_item_impl.h"
[email protected]da4a5582011-10-17 19:08:0626#include "content/browser/download/download_stats.h"
[email protected]b3c41c0b2012-03-06 15:48:3227#include "content/browser/renderer_host/render_view_host_impl.h"
[email protected]ea114722012-03-12 01:11:2528#include "content/browser/renderer_host/resource_dispatcher_host_impl.h"
[email protected]93ddb3c2012-04-11 21:44:2929#include "content/browser/web_contents/web_contents_impl.h"
[email protected]ccb797302011-12-15 16:55:1130#include "content/public/browser/browser_context.h"
[email protected]c38831a12011-10-28 12:44:4931#include "content/public/browser/browser_thread.h"
[email protected]87f3c082011-10-19 18:07:4432#include "content/public/browser/content_browser_client.h"
[email protected]bf3b08a2012-03-08 01:52:3433#include "content/public/browser/download_interrupt_reasons.h"
[email protected]1bd0ef12011-10-20 05:24:1734#include "content/public/browser/download_manager_delegate.h"
[email protected]8da82ea2012-03-11 22:16:5235#include "content/public/browser/download_persistent_store_info.h"
[email protected]c5a5c0842012-05-04 20:05:1436#include "content/public/browser/download_url_parameters.h"
[email protected]ad50def52011-10-19 23:17:0737#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1638#include "content/public/browser/notification_types.h"
[email protected]f3b1a082011-11-18 00:34:3039#include "content/public/browser/render_process_host.h"
[email protected]94e2bbe2012-06-22 15:26:1340#include "content/public/browser/resource_context.h"
[email protected]0bfbf882011-12-22 18:19:2741#include "content/public/browser/web_contents_delegate.h"
[email protected]c5a5c0842012-05-04 20:05:1442#include "net/base/load_flags.h"
[email protected]27678b2a2012-02-04 22:09:1443#include "net/base/upload_data.h"
[email protected]f859eba2012-05-30 17:22:4944#include "webkit/glue/webkit_glue.h"
initial.commit09911bf2008-07-26 23:55:2945
[email protected]631bb742011-11-02 11:29:3946using content::BrowserThread;
[email protected]98e814062012-01-27 00:35:4247using content::DownloadId;
[email protected]e582fdd2011-12-20 16:48:1748using content::DownloadItem;
[email protected]8da82ea2012-03-11 22:16:5249using content::DownloadPersistentStoreInfo;
[email protected]ea114722012-03-12 01:11:2550using content::ResourceDispatcherHostImpl;
[email protected]2a6bc3e2011-12-28 23:51:3351using content::WebContents;
[email protected]631bb742011-11-02 11:29:3952
[email protected]a0ce3282011-08-19 20:49:5253namespace {
54
[email protected]99229b22012-07-11 17:38:5055// This is just used to remember which DownloadItems come from SavePage.
[email protected]d59d40c2012-08-08 18:18:3756class SavePageData : public base::SupportsUserData::Data {
[email protected]99229b22012-07-11 17:38:5057 public:
58 // A spoonful of syntactic sugar.
59 static bool Get(DownloadItem* item) {
[email protected]d59d40c2012-08-08 18:18:3760 return item->GetUserData(kKey) != NULL;
[email protected]99229b22012-07-11 17:38:5061 }
62
[email protected]d59d40c2012-08-08 18:18:3763 explicit SavePageData(DownloadItem* item) {
64 item->SetUserData(kKey, this);
[email protected]99229b22012-07-11 17:38:5065 }
66
[email protected]d59d40c2012-08-08 18:18:3767 virtual ~SavePageData() {}
[email protected]99229b22012-07-11 17:38:5068
69 private:
70 static const char kKey[];
71
[email protected]d59d40c2012-08-08 18:18:3772 DISALLOW_COPY_AND_ASSIGN(SavePageData);
[email protected]99229b22012-07-11 17:38:5073};
74
[email protected]d59d40c2012-08-08 18:18:3775const char SavePageData::kKey[] = "DownloadItem SavePageData";
[email protected]99229b22012-07-11 17:38:5076
[email protected]c5a5c0842012-05-04 20:05:1477void BeginDownload(content::DownloadUrlParameters* params) {
78 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
79 // ResourceDispatcherHost{Base} is-not-a URLRequest::Delegate, and
80 // DownloadUrlParameters can-not include resource_dispatcher_host_impl.h, so
81 // we must down cast. RDHI is the only subclass of RDH as of 2012 May 4.
[email protected]c5a5c0842012-05-04 20:05:1482 scoped_ptr<net::URLRequest> request(new net::URLRequest(
[email protected]94e2bbe2012-06-22 15:26:1383 params->url(),
84 NULL,
85 params->resource_context()->GetRequestContext()));
[email protected]f859eba2012-05-30 17:22:4986 request->set_referrer(params->referrer().url.spec());
87 webkit_glue::ConfigureURLRequestForReferrerPolicy(
88 request.get(), params->referrer().policy);
[email protected]c5a5c0842012-05-04 20:05:1489 request->set_load_flags(request->load_flags() | params->load_flags());
90 request->set_method(params->method());
91 if (!params->post_body().empty())
92 request->AppendBytesToUpload(params->post_body().data(),
93 params->post_body().size());
94 if (params->post_id() >= 0) {
[email protected]27678b2a2012-02-04 22:09:1495 // The POST in this case does not have an actual body, and only works
96 // when retrieving data from cache. This is done because we don't want
97 // to do a re-POST without user consent, and currently don't have a good
98 // plan on how to display the UI for that.
[email protected]c5a5c0842012-05-04 20:05:1499 DCHECK(params->prefer_cache());
100 DCHECK(params->method() == "POST");
[email protected]27678b2a2012-02-04 22:09:14101 scoped_refptr<net::UploadData> upload_data = new net::UploadData();
[email protected]c5a5c0842012-05-04 20:05:14102 upload_data->set_identifier(params->post_id());
[email protected]27678b2a2012-02-04 22:09:14103 request->set_upload(upload_data);
104 }
[email protected]c5a5c0842012-05-04 20:05:14105 for (content::DownloadUrlParameters::RequestHeadersType::const_iterator iter
106 = params->request_headers_begin();
107 iter != params->request_headers_end();
108 ++iter) {
109 request->SetExtraRequestHeaderByName(
110 iter->first, iter->second, false/*overwrite*/);
111 }
[email protected]56f0b082012-06-14 07:12:32112 params->resource_dispatcher_host()->BeginDownload(
[email protected]ea114722012-03-12 01:11:25113 request.Pass(),
[email protected]a53e2f92012-05-15 15:27:06114 params->content_initiated(),
[email protected]c5a5c0842012-05-04 20:05:14115 params->resource_context(),
116 params->render_process_host_id(),
117 params->render_view_host_routing_id(),
118 params->prefer_cache(),
119 params->save_info(),
120 params->callback());
[email protected]a0ce3282011-08-19 20:49:52121}
122
[email protected]33d22102012-01-25 17:46:53123class MapValueIteratorAdapter {
124 public:
125 explicit MapValueIteratorAdapter(
126 base::hash_map<int64, DownloadItem*>::const_iterator iter)
127 : iter_(iter) {
128 }
129 ~MapValueIteratorAdapter() {}
130
131 DownloadItem* operator*() { return iter_->second; }
132
133 MapValueIteratorAdapter& operator++() {
134 ++iter_;
135 return *this;
136 }
137
138 bool operator!=(const MapValueIteratorAdapter& that) const {
139 return iter_ != that.iter_;
140 }
141
142 private:
143 base::hash_map<int64, DownloadItem*>::const_iterator iter_;
144 // Allow copy and assign.
145};
146
[email protected]5948e1a2012-03-10 00:19:18147void EnsureNoPendingDownloadsOnFile(scoped_refptr<DownloadFileManager> dfm,
148 bool* result) {
149 if (dfm->NumberOfActiveDownloads())
150 *result = false;
151 BrowserThread::PostTask(
152 BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure());
153}
154
[email protected]0a5c9112012-03-12 17:49:02155void EnsureNoPendingDownloadJobsOnIO(bool* result) {
[email protected]5948e1a2012-03-10 00:19:18156 scoped_refptr<DownloadFileManager> download_file_manager =
[email protected]ea114722012-03-12 01:11:25157 ResourceDispatcherHostImpl::Get()->download_file_manager();
[email protected]5948e1a2012-03-10 00:19:18158 BrowserThread::PostTask(
159 BrowserThread::FILE, FROM_HERE,
160 base::Bind(&EnsureNoPendingDownloadsOnFile,
161 download_file_manager, result));
162}
163
[email protected]d25fda12012-06-12 17:05:03164class DownloadItemFactoryImpl : public content::DownloadItemFactory {
165 public:
166 DownloadItemFactoryImpl() {}
167 virtual ~DownloadItemFactoryImpl() {}
168
[email protected]db1d8f72012-07-13 19:23:16169 virtual DownloadItemImpl* CreatePersistedItem(
170 DownloadItemImplDelegate* delegate,
[email protected]d25fda12012-06-12 17:05:03171 content::DownloadId download_id,
172 const content::DownloadPersistentStoreInfo& info,
173 const net::BoundNetLog& bound_net_log) OVERRIDE {
174 return new DownloadItemImpl(delegate, download_id, info, bound_net_log);
175 }
176
[email protected]db1d8f72012-07-13 19:23:16177 virtual DownloadItemImpl* CreateActiveItem(
178 DownloadItemImplDelegate* delegate,
[email protected]d25fda12012-06-12 17:05:03179 const DownloadCreateInfo& info,
[email protected]94d841cf2012-06-12 20:58:20180 scoped_ptr<DownloadRequestHandleInterface> request_handle,
[email protected]d25fda12012-06-12 17:05:03181 bool is_otr,
182 const net::BoundNetLog& bound_net_log) OVERRIDE {
[email protected]94d841cf2012-06-12 20:58:20183 return new DownloadItemImpl(delegate, info, request_handle.Pass(),
184 is_otr, bound_net_log);
[email protected]d25fda12012-06-12 17:05:03185 }
186
[email protected]db1d8f72012-07-13 19:23:16187 virtual DownloadItemImpl* CreateSavePageItem(
188 DownloadItemImplDelegate* delegate,
[email protected]d25fda12012-06-12 17:05:03189 const FilePath& path,
190 const GURL& url,
191 bool is_otr,
192 content::DownloadId download_id,
193 const std::string& mime_type,
194 const net::BoundNetLog& bound_net_log) OVERRIDE {
195 return new DownloadItemImpl(delegate, path, url, is_otr, download_id,
196 mime_type, bound_net_log);
197 }
198};
199
[email protected]a0ce3282011-08-19 20:49:52200} // namespace
201
[email protected]99907362012-01-11 05:41:40202namespace content {
203
[email protected]5948e1a2012-03-10 00:19:18204bool DownloadManager::EnsureNoPendingDownloadsForTesting() {
205 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
206 bool result = true;
207 BrowserThread::PostTask(
208 BrowserThread::IO, FROM_HERE,
[email protected]0a5c9112012-03-12 17:49:02209 base::Bind(&EnsureNoPendingDownloadJobsOnIO, &result));
[email protected]5948e1a2012-03-10 00:19:18210 MessageLoop::current()->Run();
211 return result;
212}
213
[email protected]99907362012-01-11 05:41:40214} // namespace content
215
[email protected]d25fda12012-06-12 17:05:03216DownloadManagerImpl::DownloadManagerImpl(
217 DownloadFileManager* file_manager,
218 scoped_ptr<content::DownloadItemFactory> factory,
219 net::NetLog* net_log)
220 : factory_(factory.Pass()),
[email protected]09ea72c7422012-07-02 20:35:40221 history_size_(0),
[email protected]d25fda12012-06-12 17:05:03222 shutdown_needed_(false),
[email protected]b441a8492012-06-06 14:55:57223 browser_context_(NULL),
[email protected]d25fda12012-06-12 17:05:03224 file_manager_(file_manager),
[email protected]33c20cd92012-06-14 22:02:50225 delegate_(NULL),
[email protected]b441a8492012-06-06 14:55:57226 net_log_(net_log) {
[email protected]d25fda12012-06-12 17:05:03227 DCHECK(file_manager);
228 if (!factory_.get())
229 factory_.reset(new DownloadItemFactoryImpl());
initial.commit09911bf2008-07-26 23:55:29230}
231
[email protected]5656f8a2011-11-17 16:12:58232DownloadManagerImpl::~DownloadManagerImpl() {
[email protected]326a6a92010-09-10 20:21:13233 DCHECK(!shutdown_needed_);
initial.commit09911bf2008-07-26 23:55:29234}
235
[email protected]5656f8a2011-11-17 16:12:58236DownloadId DownloadManagerImpl::GetNextId() {
[email protected]491aaa62012-06-07 03:50:18237 DownloadId id;
238 if (delegate_)
239 id = delegate_->GetNextId();
240 if (!id.IsValid()) {
241 static int next_id;
242 id = DownloadId(browser_context_, ++next_id);
243 }
244
245 return id;
[email protected]2909e342011-10-29 00:46:53246}
247
[email protected]47665442012-07-27 02:31:22248DownloadFileManager* DownloadManagerImpl::GetDownloadFileManager() {
249 return file_manager_;
250}
251
[email protected]db1d8f72012-07-13 19:23:16252bool DownloadManagerImpl::ShouldOpenDownload(DownloadItemImpl* item) {
[email protected]491aaa62012-06-07 03:50:18253 if (!delegate_)
254 return true;
255
[email protected]fc03de22011-12-06 23:28:12256 return delegate_->ShouldOpenDownload(item);
257}
258
259bool DownloadManagerImpl::ShouldOpenFileBasedOnExtension(const FilePath& path) {
[email protected]491aaa62012-06-07 03:50:18260 if (!delegate_)
261 return false;
262
[email protected]fc03de22011-12-06 23:28:12263 return delegate_->ShouldOpenFileBasedOnExtension(path);
264}
265
[email protected]b441a8492012-06-06 14:55:57266void DownloadManagerImpl::SetDelegate(
267 content::DownloadManagerDelegate* delegate) {
268 delegate_ = delegate;
269}
270
[email protected]b488b5a52012-06-06 17:01:28271content::DownloadManagerDelegate* DownloadManagerImpl::GetDelegate() const {
272 return delegate_;
273}
274
[email protected]5656f8a2011-11-17 16:12:58275void DownloadManagerImpl::Shutdown() {
[email protected]da6e3922010-11-24 21:45:50276 VLOG(20) << __FUNCTION__ << "()"
277 << " shutdown_needed_ = " << shutdown_needed_;
[email protected]326a6a92010-09-10 20:21:13278 if (!shutdown_needed_)
279 return;
280 shutdown_needed_ = false;
initial.commit09911bf2008-07-26 23:55:29281
[email protected]75e51b52012-02-04 16:57:54282 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown(this));
[email protected]fb4f8d902011-09-16 06:07:08283 // TODO(benjhayden): Consider clearing observers_.
[email protected]326a6a92010-09-10 20:21:13284
[email protected]d25fda12012-06-12 17:05:03285 DCHECK(file_manager_);
286 BrowserThread::PostTask(
287 BrowserThread::FILE, FROM_HERE,
288 base::Bind(&DownloadFileManager::OnDownloadManagerShutdown,
289 file_manager_, make_scoped_refptr(this)));
initial.commit09911bf2008-07-26 23:55:29290
[email protected]f04182f32010-12-10 19:12:07291 AssertContainersConsistent();
292
293 // Go through all downloads in downloads_. Dangerous ones we need to
294 // remove on disk, and in progress ones we need to cancel.
[email protected]ba7895d2012-06-22 19:02:52295 for (DownloadMap::iterator it = downloads_.begin(); it != downloads_.end();) {
[email protected]db1d8f72012-07-13 19:23:16296 DownloadItemImpl* download = it->second;
[email protected]f04182f32010-12-10 19:12:07297
298 // Save iterator from potential erases in this set done by called code.
299 // Iterators after an erasure point are still valid for lists and
300 // associative containers such as sets.
301 it++;
302
[email protected]c09a8fd2011-11-21 19:54:50303 if (download->GetSafetyState() == DownloadItem::DANGEROUS &&
[email protected]48837962011-04-19 17:03:29304 download->IsPartialDownload()) {
[email protected]f04182f32010-12-10 19:12:07305 // The user hasn't accepted it, so we need to remove it
306 // from the disk. This may or may not result in it being
307 // removed from the DownloadManager queues and deleted
[email protected]fc03de22011-12-06 23:28:12308 // (specifically, DownloadManager::DownloadRemoved only
[email protected]f04182f32010-12-10 19:12:07309 // removes and deletes it if it's known to the history service)
310 // so the only thing we know after calling this function is that
311 // the download was deleted if-and-only-if it was removed
312 // from all queues.
[email protected]303077002011-04-19 23:21:01313 download->Delete(DownloadItem::DELETE_DUE_TO_BROWSER_SHUTDOWN);
[email protected]bf68a00b2011-04-07 17:28:26314 } else if (download->IsPartialDownload()) {
[email protected]93af2272011-09-21 18:29:17315 download->Cancel(false);
[email protected]491aaa62012-06-07 03:50:18316 if (delegate_)
317 delegate_->UpdateItemInPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29318 }
319 }
320
[email protected]f04182f32010-12-10 19:12:07321 // At this point, all dangerous downloads have had their files removed
322 // and all in progress downloads have been cancelled. We can now delete
323 // anything left.
[email protected]9ccbb372008-10-10 18:50:32324
[email protected]70850c72011-01-11 17:31:27325 active_downloads_.clear();
[email protected]7e834f02012-08-09 20:38:56326 STLDeleteValues(&downloads_);
327 downloads_.clear();
initial.commit09911bf2008-07-26 23:55:29328
[email protected]41f558fb2012-01-09 22:59:58329 // We'll have nothing more to report to the observers after this point.
330 observers_.Clear();
331
initial.commit09911bf2008-07-26 23:55:29332 file_manager_ = NULL;
[email protected]b441a8492012-06-06 14:55:57333 if (delegate_)
334 delegate_->Shutdown();
[email protected]47665442012-07-27 02:31:22335 delegate_ = NULL;
initial.commit09911bf2008-07-26 23:55:29336}
337
[email protected]5656f8a2011-11-17 16:12:58338void DownloadManagerImpl::GetTemporaryDownloads(
[email protected]6d0146c2011-08-04 19:13:04339 const FilePath& dir_path, DownloadVector* result) {
[email protected]82f37b02010-07-29 22:04:57340 DCHECK(result);
[email protected]6aa4a1c02010-01-15 18:49:58341
[email protected]09ea72c7422012-07-02 20:35:40342 for (DownloadMap::iterator it = downloads_.begin();
343 it != downloads_.end(); ++it) {
[email protected]db1d8f72012-07-13 19:23:16344 DownloadItemImpl* item = it->second;
[email protected]09ea72c7422012-07-02 20:35:40345 // TODO(benjhayden): Don't check IsPersisted().
346 if (item->IsTemporary() &&
347 item->IsPersisted() &&
[email protected]3d833de2012-05-30 23:32:06348 (dir_path.empty() ||
[email protected]09ea72c7422012-07-02 20:35:40349 item->GetTargetFilePath().DirName() == dir_path))
350 result->push_back(item);
[email protected]6aa4a1c02010-01-15 18:49:58351 }
[email protected]6aa4a1c02010-01-15 18:49:58352}
353
[email protected]5656f8a2011-11-17 16:12:58354void DownloadManagerImpl::GetAllDownloads(
[email protected]6d0146c2011-08-04 19:13:04355 const FilePath& dir_path, DownloadVector* result) {
[email protected]82f37b02010-07-29 22:04:57356 DCHECK(result);
[email protected]8ddbd66a2010-05-21 16:38:34357
[email protected]09ea72c7422012-07-02 20:35:40358 for (DownloadMap::iterator it = downloads_.begin();
359 it != downloads_.end(); ++it) {
[email protected]db1d8f72012-07-13 19:23:16360 DownloadItemImpl* item = it->second;
[email protected]09ea72c7422012-07-02 20:35:40361 // TODO(benjhayden): Don't check IsPersisted().
362 if (!item->IsTemporary() &&
363 item->IsPersisted() &&
[email protected]3d833de2012-05-30 23:32:06364 (dir_path.empty() ||
[email protected]09ea72c7422012-07-02 20:35:40365 item->GetTargetFilePath().DirName() == dir_path))
366 result->push_back(item);
[email protected]8ddbd66a2010-05-21 16:38:34367 }
[email protected]8ddbd66a2010-05-21 16:38:34368}
369
[email protected]5656f8a2011-11-17 16:12:58370void DownloadManagerImpl::SearchDownloads(const string16& query,
371 DownloadVector* result) {
[email protected]503d03872011-05-06 08:36:26372 string16 query_lower(base::i18n::ToLower(query));
[email protected]d3b12902010-08-16 23:39:42373
[email protected]09ea72c7422012-07-02 20:35:40374 for (DownloadMap::iterator it = downloads_.begin();
375 it != downloads_.end(); ++it) {
[email protected]db1d8f72012-07-13 19:23:16376 DownloadItemImpl* download_item = it->second;
[email protected]d3b12902010-08-16 23:39:42377 // Display Incognito downloads only in Incognito window, and vice versa.
378 // The Incognito Downloads page will get the list of non-Incognito downloads
379 // from its parent profile.
[email protected]09ea72c7422012-07-02 20:35:40380 // TODO(benjhayden): Don't check IsPersisted().
381 if (!download_item->IsTemporary() &&
382 download_item->IsPersisted() &&
383 (browser_context_->IsOffTheRecord() == download_item->IsOtr()) &&
384 download_item->MatchesQuery(query_lower)) {
[email protected]d3b12902010-08-16 23:39:42385 result->push_back(download_item);
[email protected]09ea72c7422012-07-02 20:35:40386 }
[email protected]d3b12902010-08-16 23:39:42387 }
[email protected]d3b12902010-08-16 23:39:42388}
389
[email protected]5656f8a2011-11-17 16:12:58390bool DownloadManagerImpl::Init(content::BrowserContext* browser_context) {
[email protected]6d0c9fb2011-08-22 19:26:03391 DCHECK(browser_context);
initial.commit09911bf2008-07-26 23:55:29392 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
393 shutdown_needed_ = true;
394
[email protected]6d0c9fb2011-08-22 19:26:03395 browser_context_ = browser_context;
[email protected]024f2f02010-04-30 22:51:46396
initial.commit09911bf2008-07-26 23:55:29397 return true;
398}
399
[email protected]aa9881c2011-08-15 18:01:12400// We have received a message from DownloadFileManager about a new download.
[email protected]2bddd2072012-06-18 16:16:51401content::DownloadId DownloadManagerImpl::StartDownload(
402 scoped_ptr<DownloadCreateInfo> info,
403 scoped_ptr<content::ByteStreamReader> stream) {
[email protected]ca4b5fa32010-10-09 12:42:18404 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]287b86b2011-02-26 00:11:35405
[email protected]2bddd2072012-06-18 16:16:51406 // |bound_net_log| will be used for logging both the download item's and
407 // the download file's events.
408 net::BoundNetLog bound_net_log = CreateDownloadItem(info.get());
409
410 // If info->download_id was unknown on entry to this function, it was
411 // assigned in CreateDownloadItem.
412 DownloadId download_id = info->download_id;
413
414 DownloadFileManager::CreateDownloadFileCallback callback(
415 base::Bind(&DownloadManagerImpl::OnDownloadFileCreated,
416 this, download_id.local()));
417
418 BrowserThread::PostTask(
419 BrowserThread::FILE, FROM_HERE,
420 base::Bind(&DownloadFileManager::CreateDownloadFile,
421 file_manager_, base::Passed(info.Pass()),
422 base::Passed(stream.Pass()),
423 make_scoped_refptr(this),
424 GenerateFileHash(), bound_net_log,
425 callback));
426
427 return download_id;
428}
429
430void DownloadManagerImpl::OnDownloadFileCreated(
431 int32 download_id, content::DownloadInterruptReason reason) {
432 if (reason != content::DOWNLOAD_INTERRUPT_REASON_NONE) {
[email protected]b36cad502012-07-13 23:19:14433 OnDownloadInterrupted(download_id, reason);
[email protected]2bddd2072012-06-18 16:16:51434 // TODO(rdsmith): It makes no sense to continue along the
435 // regular download path after we've gotten an error. But it's
436 // the way the code has historically worked, and this allows us
437 // to get the download persisted and observers of the download manager
438 // notified, so tests work. When we execute all side effects of cancel
439 // (including queue removal) immedately rather than waiting for
440 // persistence we should replace this comment with a "return;".
441 }
442
[email protected]47665442012-07-27 02:31:22443 DownloadMap::iterator download_iter = active_downloads_.find(download_id);
444 if (download_iter == active_downloads_.end())
445 return;
446
447 DownloadItemImpl* download = download_iter->second;
448 content::DownloadTargetCallback callback =
449 base::Bind(&DownloadManagerImpl::OnDownloadTargetDetermined,
450 this, download_id);
451 if (!delegate_ || !delegate_->DetermineDownloadTarget(download, callback)) {
452 FilePath target_path = download->GetForcedFilePath();
453 // TODO(asanka): Determine a useful path if |target_path| is empty.
454 callback.Run(target_path,
455 DownloadItem::TARGET_DISPOSITION_OVERWRITE,
456 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
457 target_path);
458 }
459}
460
461void DownloadManagerImpl::OnDownloadTargetDetermined(
462 int32 download_id,
463 const FilePath& target_path,
464 DownloadItem::TargetDisposition disposition,
465 content::DownloadDangerType danger_type,
466 const FilePath& intermediate_path) {
467 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
468 DownloadMap::iterator download_iter = active_downloads_.find(download_id);
469 if (download_iter != active_downloads_.end()) {
470 // Once DownloadItem::OnDownloadTargetDetermined() is called, we expect a
471 // DownloadRenamedToIntermediateName() callback. This is necessary for the
472 // download to proceed.
473 download_iter->second->OnDownloadTargetDetermined(
474 target_path, disposition, danger_type, intermediate_path);
475 }
[email protected]287b86b2011-02-26 00:11:35476}
477
[email protected]5656f8a2011-11-17 16:12:58478void DownloadManagerImpl::CheckForHistoryFilesRemoval() {
[email protected]9fc114672011-06-15 08:17:48479 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]09ea72c7422012-07-02 20:35:40480 for (DownloadMap::iterator it = downloads_.begin();
481 it != downloads_.end(); ++it) {
[email protected]db1d8f72012-07-13 19:23:16482 DownloadItemImpl* item = it->second;
[email protected]09ea72c7422012-07-02 20:35:40483 if (item->IsPersisted())
484 CheckForFileRemoval(item);
[email protected]9fc114672011-06-15 08:17:48485 }
486}
487
[email protected]db1d8f72012-07-13 19:23:16488void DownloadManagerImpl::CheckForFileRemoval(DownloadItemImpl* download_item) {
[email protected]9fc114672011-06-15 08:17:48489 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
490 if (download_item->IsComplete() &&
[email protected]c09a8fd2011-11-21 19:54:50491 !download_item->GetFileExternallyRemoved()) {
[email protected]9fc114672011-06-15 08:17:48492 BrowserThread::PostTask(
493 BrowserThread::FILE, FROM_HERE,
[email protected]5656f8a2011-11-17 16:12:58494 base::Bind(&DownloadManagerImpl::CheckForFileRemovalOnFileThread,
[email protected]09ea72c7422012-07-02 20:35:40495 this, download_item->GetId(),
[email protected]fabf36d22011-10-28 21:50:17496 download_item->GetTargetFilePath()));
[email protected]9fc114672011-06-15 08:17:48497 }
498}
499
[email protected]5656f8a2011-11-17 16:12:58500void DownloadManagerImpl::CheckForFileRemovalOnFileThread(
[email protected]09ea72c7422012-07-02 20:35:40501 int32 download_id, const FilePath& path) {
[email protected]9fc114672011-06-15 08:17:48502 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
503 if (!file_util::PathExists(path)) {
504 BrowserThread::PostTask(
505 BrowserThread::UI, FROM_HERE,
[email protected]5656f8a2011-11-17 16:12:58506 base::Bind(&DownloadManagerImpl::OnFileRemovalDetected,
507 this,
[email protected]09ea72c7422012-07-02 20:35:40508 download_id));
[email protected]9fc114672011-06-15 08:17:48509 }
510}
511
[email protected]09ea72c7422012-07-02 20:35:40512void DownloadManagerImpl::OnFileRemovalDetected(int32 download_id) {
[email protected]9fc114672011-06-15 08:17:48513 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]db1d8f72012-07-13 19:23:16514 if (ContainsKey(downloads_, download_id))
515 downloads_[download_id]->OnDownloadedFileRemoved();
[email protected]9fc114672011-06-15 08:17:48516}
517
[email protected]37757c62011-12-20 20:07:12518content::BrowserContext* DownloadManagerImpl::GetBrowserContext() const {
[email protected]5656f8a2011-11-17 16:12:58519 return browser_context_;
520}
521
[email protected]ef17c9a2012-02-09 05:08:09522net::BoundNetLog DownloadManagerImpl::CreateDownloadItem(
[email protected]2bddd2072012-06-18 16:16:51523 DownloadCreateInfo* info) {
[email protected]c2e76012010-12-23 21:10:29524 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
525
[email protected]ef17c9a2012-02-09 05:08:09526 net::BoundNetLog bound_net_log =
527 net::BoundNetLog::Make(net_log_, net::NetLog::SOURCE_DOWNLOAD);
[email protected]d25fda12012-06-12 17:05:03528 if (!info->download_id.IsValid())
529 info->download_id = GetNextId();
[email protected]db1d8f72012-07-13 19:23:16530 DownloadItemImpl* download = factory_->CreateActiveItem(
[email protected]2bddd2072012-06-18 16:16:51531 this, *info,
532 scoped_ptr<DownloadRequestHandleInterface>(
533 new DownloadRequestHandle(info->request_handle)).Pass(),
[email protected]ef17c9a2012-02-09 05:08:09534 browser_context_->IsOffTheRecord(), bound_net_log);
[email protected]d8472d92011-08-26 20:15:20535
[email protected]ba7895d2012-06-22 19:02:52536 DCHECK(!ContainsKey(downloads_, download->GetId()));
537 downloads_[download->GetId()] = download;
538 DCHECK(!ContainsKey(active_downloads_, download->GetId()));
539 active_downloads_[download->GetId()] = download;
[email protected]6a1a59a12012-07-26 17:26:40540 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadCreated(this, download));
[email protected]ef17c9a2012-02-09 05:08:09541
542 return bound_net_log;
[email protected]c2e76012010-12-23 21:10:29543}
544
[email protected]db1d8f72012-07-13 19:23:16545DownloadItemImpl* DownloadManagerImpl::CreateSavePackageDownloadItem(
[email protected]fc03de22011-12-06 23:28:12546 const FilePath& main_file_path,
547 const GURL& page_url,
548 bool is_otr,
[email protected]6474b112012-05-04 19:35:27549 const std::string& mime_type,
[email protected]fc03de22011-12-06 23:28:12550 DownloadItem::Observer* observer) {
[email protected]ef17c9a2012-02-09 05:08:09551 net::BoundNetLog bound_net_log =
552 net::BoundNetLog::Make(net_log_, net::NetLog::SOURCE_DOWNLOAD);
[email protected]db1d8f72012-07-13 19:23:16553 DownloadItemImpl* download = factory_->CreateSavePageItem(
[email protected]6474b112012-05-04 19:35:27554 this,
555 main_file_path,
556 page_url,
557 is_otr,
558 GetNextId(),
559 mime_type,
560 bound_net_log);
[email protected]fc03de22011-12-06 23:28:12561
562 download->AddObserver(observer);
563
[email protected]ba7895d2012-06-22 19:02:52564 DCHECK(!ContainsKey(downloads_, download->GetId()));
565 downloads_[download->GetId()] = download;
[email protected]d59d40c2012-08-08 18:18:37566 DCHECK(!SavePageData::Get(download));
567 new SavePageData(download);
568 DCHECK(SavePageData::Get(download));
[email protected]fc03de22011-12-06 23:28:12569
[email protected]6a1a59a12012-07-26 17:26:40570 // TODO(benjhayden): Fire OnDownloadCreated for SavePackage downloads when
571 // we're comfortable with the user interacting with them.
572 // FOR_EACH_OBSERVER(Observer, observers_, OnDownloadCreated(this, download));
573
[email protected]fc03de22011-12-06 23:28:12574 // Will notify the observer in the callback.
[email protected]491aaa62012-06-07 03:50:18575 if (delegate_)
576 delegate_->AddItemToPersistentStore(download);
[email protected]fc03de22011-12-06 23:28:12577
578 return download;
579}
580
[email protected]443853c62011-12-22 19:22:41581void DownloadManagerImpl::UpdateDownload(int32 download_id,
582 int64 bytes_so_far,
583 int64 bytes_per_sec,
[email protected]0afff032012-01-06 20:55:00584 const std::string& hash_state) {
[email protected]70850c72011-01-11 17:31:27585 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
586 DownloadMap::iterator it = active_downloads_.find(download_id);
587 if (it != active_downloads_.end()) {
[email protected]db1d8f72012-07-13 19:23:16588 DownloadItemImpl* download = it->second;
[email protected]bf68a00b2011-04-07 17:28:26589 if (download->IsInProgress()) {
[email protected]443853c62011-12-22 19:22:41590 download->UpdateProgress(bytes_so_far, bytes_per_sec, hash_state);
[email protected]491aaa62012-06-07 03:50:18591 if (delegate_)
592 delegate_->UpdateItemInPersistentStore(download);
[email protected]70850c72011-01-11 17:31:27593 }
initial.commit09911bf2008-07-26 23:55:29594 }
595}
596
[email protected]5656f8a2011-11-17 16:12:58597void DownloadManagerImpl::OnResponseCompleted(int32 download_id,
598 int64 size,
599 const std::string& hash) {
[email protected]33c6d3f12011-09-04 00:00:54600 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]da6e3922010-11-24 21:45:50601 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
602 << " size = " << size;
[email protected]9d7ef802011-02-25 19:03:35603 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]9ccbb372008-10-10 18:50:32604
[email protected]c4f02c42011-01-24 21:55:06605 // If it's not in active_downloads_, that means it was cancelled; just
606 // ignore the notification.
607 if (active_downloads_.count(download_id) == 0)
608 return;
609
[email protected]db1d8f72012-07-13 19:23:16610 DownloadItemImpl* download = active_downloads_[download_id];
[email protected]ac4af82f2011-11-10 19:09:37611 download->OnAllDataSaved(size, hash);
[email protected]da4cd4262012-05-18 20:42:35612 MaybeCompleteDownload(download);
[email protected]adb2f3d12011-01-23 16:24:54613}
[email protected]9ccbb372008-10-10 18:50:32614
[email protected]db1d8f72012-07-13 19:23:16615void DownloadManagerImpl::AssertStateConsistent(
616 DownloadItemImpl* download) const {
[email protected]ba7895d2012-06-22 19:02:52617 CHECK(ContainsKey(downloads_, download->GetId()));
[email protected]7d413112011-06-16 18:50:17618
[email protected]c09a8fd2011-11-21 19:54:50619 int64 state = download->GetState();
[email protected]61b75a52011-08-29 16:34:34620 base::debug::Alias(&state);
[email protected]c09a8fd2011-11-21 19:54:50621 if (ContainsKey(active_downloads_, download->GetId())) {
[email protected]5009b7a2012-02-21 18:47:03622 if (download->IsPersisted())
[email protected]c09a8fd2011-11-21 19:54:50623 CHECK_EQ(DownloadItem::IN_PROGRESS, download->GetState());
624 if (DownloadItem::IN_PROGRESS != download->GetState())
625 CHECK_EQ(DownloadItem::kUninitializedHandle, download->GetDbHandle());
[email protected]f9a2997f2011-09-23 16:54:07626 }
[email protected]c09a8fd2011-11-21 19:54:50627 if (DownloadItem::IN_PROGRESS == download->GetState())
628 CHECK(ContainsKey(active_downloads_, download->GetId()));
[email protected]5cd11b6e2011-06-10 20:30:59629}
630
[email protected]db1d8f72012-07-13 19:23:16631bool DownloadManagerImpl::IsDownloadReadyForCompletion(
632 DownloadItemImpl* download) {
[email protected]adb2f3d12011-01-23 16:24:54633 // If we don't have all the data, the download is not ready for
634 // completion.
[email protected]c09a8fd2011-11-21 19:54:50635 if (!download->AllDataSaved())
[email protected]adb2f3d12011-01-23 16:24:54636 return false;
[email protected]6a7fb042010-02-01 16:30:47637
[email protected]9d7ef802011-02-25 19:03:35638 // If the download is dangerous, but not yet validated, it's not ready for
639 // completion.
[email protected]c09a8fd2011-11-21 19:54:50640 if (download->GetSafetyState() == DownloadItem::DANGEROUS)
[email protected]9d7ef802011-02-25 19:03:35641 return false;
642
[email protected]adb2f3d12011-01-23 16:24:54643 // If the download isn't active (e.g. has been cancelled) it's not
644 // ready for completion.
[email protected]c09a8fd2011-11-21 19:54:50645 if (active_downloads_.count(download->GetId()) == 0)
[email protected]adb2f3d12011-01-23 16:24:54646 return false;
647
648 // If the download hasn't been inserted into the history system
649 // (which occurs strictly after file name determination, intermediate
650 // file rename, and UI display) then it's not ready for completion.
[email protected]5009b7a2012-02-21 18:47:03651 if (!download->IsPersisted())
[email protected]7054b592011-06-22 14:46:42652 return false;
653
654 return true;
[email protected]adb2f3d12011-01-23 16:24:54655}
656
[email protected]6474b112012-05-04 19:35:27657// When SavePackage downloads MHTML to GData (see
658// SavePackageFilePickerChromeOS), GData calls MaybeCompleteDownload() like it
659// does for non-SavePackage downloads, but SavePackage downloads never satisfy
660// IsDownloadReadyForCompletion(). GDataDownloadObserver manually calls
661// DownloadItem::UpdateObservers() when the upload completes so that SavePackage
662// notices that the upload has completed and runs its normal Finish() pathway.
663// MaybeCompleteDownload() is never the mechanism by which SavePackage completes
664// downloads. SavePackage always uses its own Finish() to mark downloads
665// complete.
666
[email protected]db1d8f72012-07-13 19:23:16667void DownloadManagerImpl::MaybeCompleteDownload(
668 DownloadItemImpl* download) {
[email protected]adb2f3d12011-01-23 16:24:54669 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
670 VLOG(20) << __FUNCTION__ << "()" << " download = "
671 << download->DebugString(false);
672
673 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32674 return;
[email protected]9ccbb372008-10-10 18:50:32675
[email protected]adb2f3d12011-01-23 16:24:54676 // TODO(rdsmith): DCHECK that we only pass through this point
677 // once per download. The natural way to do this is by a state
678 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56679
[email protected]adb2f3d12011-01-23 16:24:54680 // Confirm we're in the proper set of states to be here;
[email protected]550520f2012-05-14 20:58:48681 // have all data, have a history handle, (validated or safe).
682 DCHECK(download->IsInProgress());
[email protected]c09a8fd2011-11-21 19:54:50683 DCHECK_NE(DownloadItem::DANGEROUS, download->GetSafetyState());
[email protected]c09a8fd2011-11-21 19:54:50684 DCHECK(download->AllDataSaved());
[email protected]5009b7a2012-02-21 18:47:03685 DCHECK(download->IsPersisted());
[email protected]adb2f3d12011-01-23 16:24:54686
[email protected]da4cd4262012-05-18 20:42:35687 // Give the delegate a chance to override. It's ok to keep re-setting the
688 // delegate's |complete_callback| cb as long as there isn't another call-point
689 // trying to set it to a different cb. TODO(benjhayden): Change the callback
690 // to point directly to the item instead of |this| when DownloadItem supports
691 // weak-ptrs.
[email protected]491aaa62012-06-07 03:50:18692 if (delegate_ && !delegate_->ShouldCompleteDownload(download, base::Bind(
[email protected]da4cd4262012-05-18 20:42:35693 &DownloadManagerImpl::MaybeCompleteDownloadById,
694 this, download->GetId())))
[email protected]c2918652011-11-01 18:50:23695 return;
696
[email protected]adb2f3d12011-01-23 16:24:54697 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
698 << download->DebugString(false);
699
[email protected]491aaa62012-06-07 03:50:18700 if (delegate_)
701 delegate_->UpdateItemInPersistentStore(download);
[email protected]47665442012-07-27 02:31:22702 download->OnDownloadCompleting();
[email protected]9ccbb372008-10-10 18:50:32703}
704
[email protected]da4cd4262012-05-18 20:42:35705void DownloadManagerImpl::MaybeCompleteDownloadById(int download_id) {
[email protected]db1d8f72012-07-13 19:23:16706 if (ContainsKey(active_downloads_, download_id))
707 MaybeCompleteDownload(active_downloads_[download_id]);
[email protected]da4cd4262012-05-18 20:42:35708}
709
[email protected]db1d8f72012-07-13 19:23:16710void DownloadManagerImpl::DownloadCompleted(DownloadItemImpl* download) {
[email protected]70850c72011-01-11 17:31:27711 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21712 DCHECK(download);
[email protected]491aaa62012-06-07 03:50:18713 if (delegate_)
714 delegate_->UpdateItemInPersistentStore(download);
[email protected]fc03de22011-12-06 23:28:12715 active_downloads_.erase(download->GetId());
716 AssertStateConsistent(download);
[email protected]70850c72011-01-11 17:31:27717}
718
[email protected]5656f8a2011-11-17 16:12:58719void DownloadManagerImpl::CancelDownload(int32 download_id) {
[email protected]93af2272011-09-21 18:29:17720 // A cancel at the right time could remove the download from the
721 // |active_downloads_| map before we get here.
[email protected]db1d8f72012-07-13 19:23:16722 if (ContainsKey(active_downloads_, download_id))
723 active_downloads_[download_id]->Cancel(true);
[email protected]93af2272011-09-21 18:29:17724}
725
[email protected]db1d8f72012-07-13 19:23:16726void DownloadManagerImpl::DownloadStopped(DownloadItemImpl* download) {
[email protected]d8472d92011-08-26 20:15:20727 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d8472d92011-08-26 20:15:20728
729 VLOG(20) << __FUNCTION__ << "()"
[email protected]da6e3922010-11-24 21:45:50730 << " download = " << download->DebugString(true);
731
[email protected]93af2272011-09-21 18:29:17732 RemoveFromActiveList(download);
[email protected]47a881b2011-08-29 22:59:21733 // This function is called from the DownloadItem, so DI state
734 // should already have been updated.
[email protected]fc03de22011-12-06 23:28:12735 AssertStateConsistent(download);
initial.commit09911bf2008-07-26 23:55:29736
[email protected]d25fda12012-06-12 17:05:03737 DCHECK(file_manager_);
[email protected]47665442012-07-27 02:31:22738 download->OffThreadCancel();
initial.commit09911bf2008-07-26 23:55:29739}
740
[email protected]bf3b08a2012-03-08 01:52:34741void DownloadManagerImpl::OnDownloadInterrupted(
742 int32 download_id,
[email protected]bf3b08a2012-03-08 01:52:34743 content::DownloadInterruptReason reason) {
[email protected]47a881b2011-08-29 22:59:21744 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
745
[email protected]db1d8f72012-07-13 19:23:16746 if (!ContainsKey(active_downloads_, download_id))
[email protected]47a881b2011-08-29 22:59:21747 return;
[email protected]b36cad502012-07-13 23:19:14748 active_downloads_[download_id]->Interrupt(reason);
[email protected]47a881b2011-08-29 22:59:21749}
750
[email protected]db1d8f72012-07-13 19:23:16751void DownloadManagerImpl::RemoveFromActiveList(DownloadItemImpl* download) {
[email protected]93af2272011-09-21 18:29:17752 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
753 DCHECK(download);
754
755 // Clean up will happen when the history system create callback runs if we
756 // don't have a valid db_handle yet.
[email protected]5009b7a2012-02-21 18:47:03757 if (download->IsPersisted()) {
[email protected]c09a8fd2011-11-21 19:54:50758 active_downloads_.erase(download->GetId());
[email protected]491aaa62012-06-07 03:50:18759 if (delegate_)
760 delegate_->UpdateItemInPersistentStore(download);
[email protected]93af2272011-09-21 18:29:17761 }
762}
763
[email protected]fd3a82832012-01-19 20:35:12764bool DownloadManagerImpl::GenerateFileHash() {
[email protected]491aaa62012-06-07 03:50:18765 return delegate_ && delegate_->GenerateFileHash();
[email protected]fd3a82832012-01-19 20:35:12766}
767
[email protected]5656f8a2011-11-17 16:12:58768int DownloadManagerImpl::RemoveDownloadItems(
[email protected]db1d8f72012-07-13 19:23:16769 const DownloadItemImplVector& pending_deletes) {
[email protected]6d0146c2011-08-04 19:13:04770 if (pending_deletes.empty())
771 return 0;
772
773 // Delete from internal maps.
[email protected]db1d8f72012-07-13 19:23:16774 for (DownloadItemImplVector::const_iterator it = pending_deletes.begin();
[email protected]7e834f02012-08-09 20:38:56775 it != pending_deletes.end();
776 ++it) {
[email protected]db1d8f72012-07-13 19:23:16777 DownloadItemImpl* download = *it;
[email protected]6d0146c2011-08-04 19:13:04778 DCHECK(download);
[email protected]7e834f02012-08-09 20:38:56779 int32 download_id = download->GetId();
780 delete download;
781 downloads_.erase(download_id);
[email protected]6d0146c2011-08-04 19:13:04782 }
[email protected]6d0146c2011-08-04 19:13:04783 NotifyModelChanged();
[email protected]7e834f02012-08-09 20:38:56784 return static_cast<int>(pending_deletes.size());
[email protected]6d0146c2011-08-04 19:13:04785}
786
[email protected]db1d8f72012-07-13 19:23:16787void DownloadManagerImpl::DownloadRemoved(DownloadItemImpl* download) {
[email protected]09ea72c7422012-07-02 20:35:40788 if (!download ||
789 downloads_.find(download->GetId()) == downloads_.end())
790 return;
791
792 // TODO(benjhayden,rdsmith): Remove this.
793 if (!download->IsPersisted())
[email protected]93af2272011-09-21 18:29:17794 return;
795
796 // Make history update.
[email protected]491aaa62012-06-07 03:50:18797 if (delegate_)
798 delegate_->RemoveItemFromPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29799
800 // Remove from our tables and delete.
[email protected]db1d8f72012-07-13 19:23:16801 int downloads_count =
802 RemoveDownloadItems(DownloadItemImplVector(1, download));
[email protected]f04182f32010-12-10 19:12:07803 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29804}
805
[email protected]fd3a82832012-01-19 20:35:12806int DownloadManagerImpl::RemoveDownloadsBetween(base::Time remove_begin,
807 base::Time remove_end) {
[email protected]491aaa62012-06-07 03:50:18808 if (delegate_)
809 delegate_->RemoveItemsFromPersistentStoreBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29810
[email protected]db1d8f72012-07-13 19:23:16811 DownloadItemImplVector pending_deletes;
[email protected]09ea72c7422012-07-02 20:35:40812 for (DownloadMap::const_iterator it = downloads_.begin();
813 it != downloads_.end();
[email protected]6d0146c2011-08-04 19:13:04814 ++it) {
[email protected]db1d8f72012-07-13 19:23:16815 DownloadItemImpl* download = it->second;
[email protected]09ea72c7422012-07-02 20:35:40816 if (download->IsPersisted() &&
817 download->GetStartTime() >= remove_begin &&
[email protected]c09a8fd2011-11-21 19:54:50818 (remove_end.is_null() || download->GetStartTime() < remove_end) &&
[email protected]6d0146c2011-08-04 19:13:04819 (download->IsComplete() || download->IsCancelled())) {
[email protected]fc03de22011-12-06 23:28:12820 AssertStateConsistent(download);
[email protected]7e834f02012-08-09 20:38:56821 download->NotifyRemoved();
[email protected]78b8fcc92009-03-31 17:36:28822 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29823 }
initial.commit09911bf2008-07-26 23:55:29824 }
[email protected]6d0146c2011-08-04 19:13:04825 return RemoveDownloadItems(pending_deletes);
initial.commit09911bf2008-07-26 23:55:29826}
827
[email protected]fd3a82832012-01-19 20:35:12828int DownloadManagerImpl::RemoveDownloads(base::Time remove_begin) {
[email protected]e93d2822009-01-30 05:59:59829 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29830}
831
[email protected]5656f8a2011-11-17 16:12:58832int DownloadManagerImpl::RemoveAllDownloads() {
[email protected]d41355e6f2009-04-07 21:21:12833 // The null times make the date range unbounded.
[email protected]09ea72c7422012-07-02 20:35:40834 int num_deleted = RemoveDownloadsBetween(base::Time(), base::Time());
835 download_stats::RecordClearAllSize(num_deleted);
836 return num_deleted;
[email protected]d41355e6f2009-04-07 21:21:12837}
838
[email protected]0d4e30c2012-01-28 00:47:53839void DownloadManagerImpl::DownloadUrl(
[email protected]c5a5c0842012-05-04 20:05:14840 scoped_ptr<content::DownloadUrlParameters> params) {
841 if (params->post_id() >= 0) {
842 // Check this here so that the traceback is more useful.
843 DCHECK(params->prefer_cache());
844 DCHECK(params->method() == "POST");
845 }
846 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
847 &BeginDownload, base::Owned(params.release())));
initial.commit09911bf2008-07-26 23:55:29848}
849
[email protected]5656f8a2011-11-17 16:12:58850void DownloadManagerImpl::AddObserver(Observer* observer) {
initial.commit09911bf2008-07-26 23:55:29851 observers_.AddObserver(observer);
[email protected]a1e41e72012-02-22 17:41:25852 // TODO: It is the responsibility of the observers to query the
853 // DownloadManager. Remove the following call from here and update all
854 // observers.
[email protected]75e51b52012-02-04 16:57:54855 observer->ModelChanged(this);
initial.commit09911bf2008-07-26 23:55:29856}
857
[email protected]5656f8a2011-11-17 16:12:58858void DownloadManagerImpl::RemoveObserver(Observer* observer) {
initial.commit09911bf2008-07-26 23:55:29859 observers_.RemoveObserver(observer);
860}
861
initial.commit09911bf2008-07-26 23:55:29862// Operations posted to us from the history service ----------------------------
863
864// The history service has retrieved all download entries. 'entries' contains
[email protected]bb1a4212011-08-22 22:38:25865// 'DownloadPersistentStoreInfo's in sorted order (by ascending start_time).
[email protected]5656f8a2011-11-17 16:12:58866void DownloadManagerImpl::OnPersistentStoreQueryComplete(
[email protected]bb1a4212011-08-22 22:38:25867 std::vector<DownloadPersistentStoreInfo>* entries) {
[email protected]09ea72c7422012-07-02 20:35:40868 history_size_ = entries->size();
initial.commit09911bf2008-07-26 23:55:29869 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]deb40832012-02-23 15:41:37870 int64 db_handle = entries->at(i).db_handle;
871 base::debug::Alias(&db_handle);
[email protected]deb40832012-02-23 15:41:37872
[email protected]ef17c9a2012-02-09 05:08:09873 net::BoundNetLog bound_net_log =
874 net::BoundNetLog::Make(net_log_, net::NetLog::SOURCE_DOWNLOAD);
[email protected]db1d8f72012-07-13 19:23:16875 DownloadItemImpl* download = factory_->CreatePersistedItem(
[email protected]ef17c9a2012-02-09 05:08:09876 this, GetNextId(), entries->at(i), bound_net_log);
[email protected]ba7895d2012-06-22 19:02:52877 DCHECK(!ContainsKey(downloads_, download->GetId()));
878 downloads_[download->GetId()] = download;
[email protected]6a1a59a12012-07-26 17:26:40879 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadCreated(this, download));
[email protected]da6e3922010-11-24 21:45:50880 VLOG(20) << __FUNCTION__ << "()" << i << ">"
881 << " download = " << download->DebugString(true);
initial.commit09911bf2008-07-26 23:55:29882 }
[email protected]b0ab1d42010-02-24 19:29:28883 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:48884 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:29885}
886
[email protected]db1d8f72012-07-13 19:23:16887void DownloadManagerImpl::AddDownloadItemToHistory(DownloadItemImpl* download,
[email protected]5656f8a2011-11-17 16:12:58888 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:27889 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]0634626a2012-05-03 19:04:26890 DCHECK_NE(DownloadItem::kUninitializedHandle, db_handle);
[email protected]5009b7a2012-02-21 18:47:03891 DCHECK(!download->IsPersisted());
[email protected]c09a8fd2011-11-21 19:54:50892 download->SetDbHandle(db_handle);
[email protected]5009b7a2012-02-21 18:47:03893 download->SetIsPersisted();
[email protected]5bcd73eb2011-03-23 21:14:02894
[email protected]09ea72c7422012-07-02 20:35:40895 download_stats::RecordHistorySize(history_size_);
896 // Not counting |download|.
897 ++history_size_;
[email protected]6d0146c2011-08-04 19:13:04898
899 // Show in the appropriate browser UI.
900 // This includes buttons to save or cancel, for a dangerous download.
901 ShowDownloadInBrowser(download);
902
903 // Inform interested objects about the new download.
904 NotifyModelChanged();
[email protected]f9a45b02011-06-30 23:49:19905}
906
[email protected]2588ea9d2011-08-22 20:59:53907
[email protected]5656f8a2011-11-17 16:12:58908void DownloadManagerImpl::OnItemAddedToPersistentStore(int32 download_id,
909 int64 db_handle) {
[email protected]2588ea9d2011-08-22 20:59:53910 // It's valid that we don't find a matching item, i.e. on shutdown.
[email protected]db1d8f72012-07-13 19:23:16911 if (!ContainsKey(downloads_, download_id))
[email protected]99229b22012-07-11 17:38:50912 return;
[email protected]db1d8f72012-07-13 19:23:16913
914 DownloadItemImpl* item = downloads_[download_id];
[email protected]99229b22012-07-11 17:38:50915 AddDownloadItemToHistory(item, db_handle);
[email protected]d59d40c2012-08-08 18:18:37916 if (SavePageData::Get(item)) {
[email protected]99229b22012-07-11 17:38:50917 OnSavePageItemAddedToPersistentStore(item);
918 } else {
919 OnDownloadItemAddedToPersistentStore(item);
920 }
[email protected]2588ea9d2011-08-22 20:59:53921}
922
[email protected]09ea72c7422012-07-02 20:35:40923// Once the new DownloadItem has been committed to the persistent store,
924// associate it with its db_handle (TODO(benjhayden) merge db_handle with id),
925// show it in the browser (TODO(benjhayden) the ui should observe us instead),
926// and notify observers (TODO(benjhayden) observers should be able to see the
927// item when it's created so they can observe it directly. Are there any
928// clients that actually need to know when the item is added to the history?).
[email protected]5656f8a2011-11-17 16:12:58929void DownloadManagerImpl::OnDownloadItemAddedToPersistentStore(
[email protected]db1d8f72012-07-13 19:23:16930 DownloadItemImpl* item) {
[email protected]f9a45b02011-06-30 23:49:19931 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]99229b22012-07-11 17:38:50932 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << item->GetDbHandle()
933 << " download_id = " << item->GetId()
934 << " download = " << item->DebugString(true);
initial.commit09911bf2008-07-26 23:55:29935
[email protected]93af2272011-09-21 18:29:17936 // If the download is still in progress, try to complete it.
937 //
938 // Otherwise, download has been cancelled or interrupted before we've
939 // received the DB handle. We post one final message to the history
940 // service so that it can be properly in sync with the DownloadItem's
941 // completion status, and also inform any observers so that they get
942 // more than just the start notification.
[email protected]99229b22012-07-11 17:38:50943 if (item->IsInProgress()) {
944 MaybeCompleteDownload(item);
[email protected]93af2272011-09-21 18:29:17945 } else {
[email protected]99229b22012-07-11 17:38:50946 DCHECK(item->IsCancelled());
947 active_downloads_.erase(item->GetId());
[email protected]491aaa62012-06-07 03:50:18948 if (delegate_)
[email protected]99229b22012-07-11 17:38:50949 delegate_->UpdateItemInPersistentStore(item);
950 item->UpdateObservers();
[email protected]93af2272011-09-21 18:29:17951 }
initial.commit09911bf2008-07-26 23:55:29952}
953
[email protected]db1d8f72012-07-13 19:23:16954void DownloadManagerImpl::ShowDownloadInBrowser(DownloadItemImpl* download) {
[email protected]a29e4f22012-04-12 21:22:03955 // The 'contents' may no longer exist if the user closed the contents before
956 // we get this start completion event.
[email protected]a62d42902012-01-24 17:24:38957 WebContents* content = download->GetWebContents();
[email protected]99cb7f82011-07-28 17:27:26958
959 // If the contents no longer exists, we ask the embedder to suggest another
[email protected]a29e4f22012-04-12 21:22:03960 // contents.
[email protected]491aaa62012-06-07 03:50:18961 if (!content && delegate_)
[email protected]ef9572e2012-01-04 22:14:12962 content = delegate_->GetAlternativeWebContentsToNotifyForDownload();
[email protected]5e595482009-05-06 20:16:53963
[email protected]0bfbf882011-12-22 18:19:27964 if (content && content->GetDelegate())
965 content->GetDelegate()->OnStartDownload(content, download);
[email protected]5e595482009-05-06 20:16:53966}
967
[email protected]5656f8a2011-11-17 16:12:58968int DownloadManagerImpl::InProgressCount() const {
[email protected]550520f2012-05-14 20:58:48969 // Don't use active_downloads_.count() because Cancel() leaves items in
970 // active_downloads_ if they haven't made it into the persistent store yet.
[email protected]007e7412012-03-13 20:10:56971 // Need to actually look at each item's state.
972 int count = 0;
[email protected]550520f2012-05-14 20:58:48973 for (DownloadMap::const_iterator it = active_downloads_.begin();
974 it != active_downloads_.end(); ++it) {
[email protected]db1d8f72012-07-13 19:23:16975 DownloadItemImpl* item = it->second;
[email protected]007e7412012-03-13 20:10:56976 if (item->IsInProgress())
977 ++count;
978 }
979 return count;
[email protected]5656f8a2011-11-17 16:12:58980}
981
[email protected]5656f8a2011-11-17 16:12:58982void DownloadManagerImpl::NotifyModelChanged() {
[email protected]75e51b52012-02-04 16:57:54983 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged(this));
[email protected]b0ab1d42010-02-24 19:29:28984}
985
[email protected]5656f8a2011-11-17 16:12:58986DownloadItem* DownloadManagerImpl::GetDownloadItem(int download_id) {
[email protected]09ea72c7422012-07-02 20:35:40987 DownloadItem* download = GetDownload(download_id);
988 return (download && download->IsPersisted()) ? download : NULL;
[email protected]2e030682010-07-23 19:45:36989}
990
[email protected]ba7895d2012-06-22 19:02:52991DownloadItem* DownloadManagerImpl::GetDownload(int download_id) {
992 return ContainsKey(downloads_, download_id) ? downloads_[download_id] : NULL;
993}
994
[email protected]5656f8a2011-11-17 16:12:58995DownloadItem* DownloadManagerImpl::GetActiveDownloadItem(int download_id) {
[email protected]5d3e83642011-12-16 01:14:36996 if (ContainsKey(active_downloads_, download_id))
997 return active_downloads_[download_id];
998 return NULL;
[email protected]4cd82f72011-05-23 19:15:01999}
1000
[email protected]57fd1252010-12-23 17:24:091001// Confirm that everything in all maps is also in |downloads_|, and that
1002// everything in |downloads_| is also in some other map.
[email protected]5656f8a2011-11-17 16:12:581003void DownloadManagerImpl::AssertContainersConsistent() const {
[email protected]f04182f32010-12-10 19:12:071004#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:091005 // Turn everything into sets.
[email protected]99229b22012-07-11 17:38:501006 const DownloadMap* input_maps[] = {&active_downloads_};
1007 DownloadSet active_set;
1008 DownloadSet* all_sets[] = {&active_set};
[email protected]6d0146c2011-08-04 19:13:041009 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(all_sets));
[email protected]57fd1252010-12-23 17:24:091010 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
1011 for (DownloadMap::const_iterator it = input_maps[i]->begin();
[email protected]6d0146c2011-08-04 19:13:041012 it != input_maps[i]->end(); ++it) {
1013 all_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:071014 }
1015 }
[email protected]57fd1252010-12-23 17:24:091016
[email protected]ba7895d2012-06-22 19:02:521017 DownloadSet all_downloads;
1018 for (DownloadMap::const_iterator it = downloads_.begin();
1019 it != downloads_.end(); ++it) {
1020 all_downloads.insert(it->second);
1021 }
1022
[email protected]57fd1252010-12-23 17:24:091023 // Check if each set is fully present in downloads, and create a union.
[email protected]57fd1252010-12-23 17:24:091024 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
1025 DownloadSet remainder;
1026 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
1027 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
[email protected]ba7895d2012-06-22 19:02:521028 all_downloads.begin(), all_downloads.end(),
[email protected]57fd1252010-12-23 17:24:091029 insert_it);
1030 DCHECK(remainder.empty());
[email protected]57fd1252010-12-23 17:24:091031 }
[email protected]f04182f32010-12-10 19:12:071032#endif
1033}
1034
[email protected]6d0146c2011-08-04 19:13:041035// SavePackage will call SavePageDownloadFinished upon completion/cancellation.
[email protected]2588ea9d2011-08-22 20:59:531036// The history callback will call OnSavePageItemAddedToPersistentStore.
[email protected]6d0146c2011-08-04 19:13:041037// If the download finishes before the history callback,
[email protected]2588ea9d2011-08-22 20:59:531038// OnSavePageItemAddedToPersistentStore calls SavePageDownloadFinished, ensuring
1039// that the history event is update regardless of the order in which these two
1040// events complete.
[email protected]6d0146c2011-08-04 19:13:041041// If something removes the download item from the download manager (Remove,
1042// Shutdown) the result will be that the SavePage system will not be able to
1043// properly update the download item (which no longer exists) or the download
1044// history, but the action will complete properly anyway. This may lead to the
1045// history entry being wrong on a reload of chrome (specifically in the case of
1046// Initiation -> History Callback -> Removal -> Completion), but there's no way
1047// to solve that without canceling on Remove (which would then update the DB).
1048
[email protected]5656f8a2011-11-17 16:12:581049void DownloadManagerImpl::OnSavePageItemAddedToPersistentStore(
[email protected]db1d8f72012-07-13 19:23:161050 DownloadItemImpl* item) {
[email protected]6d0146c2011-08-04 19:13:041051 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1052
[email protected]6d0146c2011-08-04 19:13:041053 // Finalize this download if it finished before the history callback.
[email protected]99229b22012-07-11 17:38:501054 if (!item->IsInProgress())
1055 SavePageDownloadFinished(item);
[email protected]6d0146c2011-08-04 19:13:041056}
1057
[email protected]db1d8f72012-07-13 19:23:161058void DownloadManagerImpl::SavePageDownloadFinished(
1059 content::DownloadItem* download) {
[email protected]5009b7a2012-02-21 18:47:031060 if (download->IsPersisted()) {
[email protected]491aaa62012-06-07 03:50:181061 if (delegate_)
1062 delegate_->UpdateItemInPersistentStore(download);
[email protected]6d0146c2011-08-04 19:13:041063 if (download->IsComplete())
[email protected]ad50def52011-10-19 23:17:071064 content::NotificationService::current()->Notify(
[email protected]6d0146c2011-08-04 19:13:041065 content::NOTIFICATION_SAVE_PACKAGE_SUCCESSFULLY_FINISHED,
[email protected]6c2381d2011-10-19 02:52:531066 content::Source<DownloadManager>(this),
1067 content::Details<DownloadItem>(download));
[email protected]6d0146c2011-08-04 19:13:041068 }
1069}
[email protected]da4a5582011-10-17 19:08:061070
[email protected]db1d8f72012-07-13 19:23:161071void DownloadManagerImpl::DownloadOpened(DownloadItemImpl* download) {
[email protected]491aaa62012-06-07 03:50:181072 if (delegate_)
1073 delegate_->UpdateItemInPersistentStore(download);
[email protected]da4a5582011-10-17 19:08:061074 int num_unopened = 0;
[email protected]09ea72c7422012-07-02 20:35:401075 for (DownloadMap::iterator it = downloads_.begin();
1076 it != downloads_.end(); ++it) {
[email protected]db1d8f72012-07-13 19:23:161077 DownloadItemImpl* item = it->second;
[email protected]09ea72c7422012-07-02 20:35:401078 if (item->IsComplete() &&
1079 !item->GetOpened())
[email protected]da4a5582011-10-17 19:08:061080 ++num_unopened;
1081 }
1082 download_stats::RecordOpensOutstanding(num_unopened);
1083}
[email protected]5656f8a2011-11-17 16:12:581084
[email protected]3d833de2012-05-30 23:32:061085void DownloadManagerImpl::DownloadRenamedToIntermediateName(
[email protected]db1d8f72012-07-13 19:23:161086 DownloadItemImpl* download) {
[email protected]3d833de2012-05-30 23:32:061087 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]47665442012-07-27 02:31:221088 // download->GetFullPath() is only expected to be meaningful after this
1089 // callback is received. Therefore we can now add the download to a persistent
1090 // store. If the rename failed, we receive an OnDownloadInterrupted() call
1091 // before we receive the DownloadRenamedToIntermediateName() call.
1092 if (delegate_) {
[email protected]491aaa62012-06-07 03:50:181093 delegate_->AddItemToPersistentStore(download);
[email protected]47665442012-07-27 02:31:221094 } else {
1095 OnItemAddedToPersistentStore(download->GetId(),
1096 DownloadItem::kUninitializedHandle);
1097 }
[email protected]3d833de2012-05-30 23:32:061098}
1099
1100void DownloadManagerImpl::DownloadRenamedToFinalName(
[email protected]db1d8f72012-07-13 19:23:161101 DownloadItemImpl* download) {
[email protected]3d833de2012-05-30 23:32:061102 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1103 // If the rename failed, we receive an OnDownloadInterrupted() call before we
1104 // receive the DownloadRenamedToFinalName() call.
[email protected]491aaa62012-06-07 03:50:181105 if (delegate_) {
1106 delegate_->UpdatePathForItemInPersistentStore(
1107 download, download->GetFullPath());
1108 }
[email protected]3d833de2012-05-30 23:32:061109}