blob: 3d18682768da0d0f15d7f00102b57d3640c55017 [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"
[email protected]96c3bdbaa2012-08-31 16:39:5424#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]eb795632012-09-01 00:19:3144#include "net/url_request/url_request_context.h"
[email protected]f859eba2012-05-30 17:22:4945#include "webkit/glue/webkit_glue.h"
initial.commit09911bf2008-07-26 23:55:2946
[email protected]631bb742011-11-02 11:29:3947using content::BrowserThread;
[email protected]98e814062012-01-27 00:35:4248using content::DownloadId;
[email protected]e582fdd2011-12-20 16:48:1749using content::DownloadItem;
[email protected]8da82ea2012-03-11 22:16:5250using content::DownloadPersistentStoreInfo;
[email protected]ea114722012-03-12 01:11:2551using content::ResourceDispatcherHostImpl;
[email protected]2a6bc3e2011-12-28 23:51:3352using content::WebContents;
[email protected]631bb742011-11-02 11:29:3953
[email protected]a0ce3282011-08-19 20:49:5254namespace {
55
[email protected]96c3bdbaa2012-08-31 16:39:5456// This is just used to remember which DownloadItems come from SavePage.
57class SavePageData : public base::SupportsUserData::Data {
58 public:
59 // A spoonful of syntactic sugar.
60 static bool Get(DownloadItem* item) {
61 return item->GetUserData(kKey) != NULL;
62 }
63
64 explicit SavePageData(DownloadItem* item) {
65 item->SetUserData(kKey, this);
66 }
67
68 virtual ~SavePageData() {}
69
70 private:
71 static const char kKey[];
72
73 DISALLOW_COPY_AND_ASSIGN(SavePageData);
74};
75
76const char SavePageData::kKey[] = "DownloadItem SavePageData";
77
[email protected]c873c862012-10-17 15:32:1278void BeginDownload(scoped_ptr<content::DownloadUrlParameters> params) {
[email protected]c5a5c0842012-05-04 20:05:1479 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
80 // ResourceDispatcherHost{Base} is-not-a URLRequest::Delegate, and
81 // DownloadUrlParameters can-not include resource_dispatcher_host_impl.h, so
82 // we must down cast. RDHI is the only subclass of RDH as of 2012 May 4.
[email protected]eb795632012-09-01 00:19:3183 scoped_ptr<net::URLRequest> request(
84 params->resource_context()->GetRequestContext()->CreateRequest(
85 params->url(), NULL));
[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(),
[email protected]c873c862012-10-17 15:32:12119 params->GetSaveInfo(),
[email protected]c5a5c0842012-05-04 20:05:14120 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]96c3bdbaa2012-08-31 16:39:54147void EnsureNoPendingDownloadsOnFile(scoped_refptr<DownloadFileManager> dfm,
148 bool* result) {
149 if (dfm->NumberOfActiveDownloads())
150 *result = false;
[email protected]5948e1a2012-03-10 00:19:18151 BrowserThread::PostTask(
152 BrowserThread::UI, FROM_HERE, MessageLoop::QuitClosure());
153}
154
[email protected]96c3bdbaa2012-08-31 16:39:54155void EnsureNoPendingDownloadJobsOnIO(bool* result) {
156 scoped_refptr<DownloadFileManager> download_file_manager =
157 ResourceDispatcherHostImpl::Get()->download_file_manager();
158 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 const net::BoundNetLog& bound_net_log) OVERRIDE {
[email protected]94d841cf2012-06-12 20:58:20182 return new DownloadItemImpl(delegate, info, request_handle.Pass(),
[email protected]66521d02012-08-14 17:51:54183 bound_net_log);
[email protected]d25fda12012-06-12 17:05:03184 }
185
[email protected]db1d8f72012-07-13 19:23:16186 virtual DownloadItemImpl* CreateSavePageItem(
187 DownloadItemImplDelegate* delegate,
[email protected]d25fda12012-06-12 17:05:03188 const FilePath& path,
189 const GURL& url,
[email protected]d25fda12012-06-12 17:05:03190 content::DownloadId download_id,
191 const std::string& mime_type,
192 const net::BoundNetLog& bound_net_log) OVERRIDE {
[email protected]66521d02012-08-14 17:51:54193 return new DownloadItemImpl(delegate, path, url, download_id,
[email protected]d25fda12012-06-12 17:05:03194 mime_type, bound_net_log);
195 }
196};
197
[email protected]a0ce3282011-08-19 20:49:52198} // namespace
199
[email protected]d25fda12012-06-12 17:05:03200DownloadManagerImpl::DownloadManagerImpl(
[email protected]96c3bdbaa2012-08-31 16:39:54201 DownloadFileManager* file_manager,
202 scoped_ptr<content::DownloadItemFactory> factory,
[email protected]d25fda12012-06-12 17:05:03203 net::NetLog* net_log)
[email protected]96c3bdbaa2012-08-31 16:39:54204 : factory_(factory.Pass()),
[email protected]09ea72c7422012-07-02 20:35:40205 history_size_(0),
[email protected]d25fda12012-06-12 17:05:03206 shutdown_needed_(false),
[email protected]b441a8492012-06-06 14:55:57207 browser_context_(NULL),
[email protected]96c3bdbaa2012-08-31 16:39:54208 file_manager_(file_manager),
[email protected]33c20cd92012-06-14 22:02:50209 delegate_(NULL),
[email protected]b441a8492012-06-06 14:55:57210 net_log_(net_log) {
[email protected]96c3bdbaa2012-08-31 16:39:54211 DCHECK(file_manager);
212 if (!factory_.get())
213 factory_.reset(new DownloadItemFactoryImpl());
initial.commit09911bf2008-07-26 23:55:29214}
215
[email protected]5656f8a2011-11-17 16:12:58216DownloadManagerImpl::~DownloadManagerImpl() {
[email protected]326a6a92010-09-10 20:21:13217 DCHECK(!shutdown_needed_);
initial.commit09911bf2008-07-26 23:55:29218}
219
[email protected]5656f8a2011-11-17 16:12:58220DownloadId DownloadManagerImpl::GetNextId() {
[email protected]491aaa62012-06-07 03:50:18221 DownloadId id;
222 if (delegate_)
223 id = delegate_->GetNextId();
224 if (!id.IsValid()) {
225 static int next_id;
226 id = DownloadId(browser_context_, ++next_id);
227 }
228
229 return id;
[email protected]2909e342011-10-29 00:46:53230}
231
[email protected]96c3bdbaa2012-08-31 16:39:54232DownloadFileManager* DownloadManagerImpl::GetDownloadFileManager() {
233 return file_manager_;
[email protected]47665442012-07-27 02:31:22234}
235
[email protected]db1d8f72012-07-13 19:23:16236bool DownloadManagerImpl::ShouldOpenDownload(DownloadItemImpl* item) {
[email protected]491aaa62012-06-07 03:50:18237 if (!delegate_)
238 return true;
239
[email protected]fc03de22011-12-06 23:28:12240 return delegate_->ShouldOpenDownload(item);
241}
242
243bool DownloadManagerImpl::ShouldOpenFileBasedOnExtension(const FilePath& path) {
[email protected]491aaa62012-06-07 03:50:18244 if (!delegate_)
245 return false;
246
[email protected]fc03de22011-12-06 23:28:12247 return delegate_->ShouldOpenFileBasedOnExtension(path);
248}
249
[email protected]b441a8492012-06-06 14:55:57250void DownloadManagerImpl::SetDelegate(
251 content::DownloadManagerDelegate* delegate) {
252 delegate_ = delegate;
253}
254
[email protected]b488b5a52012-06-06 17:01:28255content::DownloadManagerDelegate* DownloadManagerImpl::GetDelegate() const {
256 return delegate_;
257}
258
[email protected]5656f8a2011-11-17 16:12:58259void DownloadManagerImpl::Shutdown() {
[email protected]da6e3922010-11-24 21:45:50260 VLOG(20) << __FUNCTION__ << "()"
261 << " shutdown_needed_ = " << shutdown_needed_;
[email protected]326a6a92010-09-10 20:21:13262 if (!shutdown_needed_)
263 return;
264 shutdown_needed_ = false;
initial.commit09911bf2008-07-26 23:55:29265
[email protected]75e51b52012-02-04 16:57:54266 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown(this));
[email protected]fb4f8d902011-09-16 06:07:08267 // TODO(benjhayden): Consider clearing observers_.
[email protected]326a6a92010-09-10 20:21:13268
[email protected]f04182f32010-12-10 19:12:07269 AssertContainersConsistent();
270
271 // Go through all downloads in downloads_. Dangerous ones we need to
272 // remove on disk, and in progress ones we need to cancel.
[email protected]ba7895d2012-06-22 19:02:52273 for (DownloadMap::iterator it = downloads_.begin(); it != downloads_.end();) {
[email protected]db1d8f72012-07-13 19:23:16274 DownloadItemImpl* download = it->second;
[email protected]f04182f32010-12-10 19:12:07275
276 // Save iterator from potential erases in this set done by called code.
277 // Iterators after an erasure point are still valid for lists and
278 // associative containers such as sets.
279 it++;
280
[email protected]c09a8fd2011-11-21 19:54:50281 if (download->GetSafetyState() == DownloadItem::DANGEROUS &&
[email protected]48837962011-04-19 17:03:29282 download->IsPartialDownload()) {
[email protected]f04182f32010-12-10 19:12:07283 // The user hasn't accepted it, so we need to remove it
284 // from the disk. This may or may not result in it being
285 // removed from the DownloadManager queues and deleted
[email protected]fc03de22011-12-06 23:28:12286 // (specifically, DownloadManager::DownloadRemoved only
[email protected]f04182f32010-12-10 19:12:07287 // removes and deletes it if it's known to the history service)
288 // so the only thing we know after calling this function is that
289 // the download was deleted if-and-only-if it was removed
290 // from all queues.
[email protected]303077002011-04-19 23:21:01291 download->Delete(DownloadItem::DELETE_DUE_TO_BROWSER_SHUTDOWN);
[email protected]bf68a00b2011-04-07 17:28:26292 } else if (download->IsPartialDownload()) {
[email protected]93af2272011-09-21 18:29:17293 download->Cancel(false);
[email protected]491aaa62012-06-07 03:50:18294 if (delegate_)
295 delegate_->UpdateItemInPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29296 }
297 }
298
[email protected]f04182f32010-12-10 19:12:07299 // At this point, all dangerous downloads have had their files removed
300 // and all in progress downloads have been cancelled. We can now delete
301 // anything left.
[email protected]9ccbb372008-10-10 18:50:32302
[email protected]bd466f302012-10-08 17:11:19303 // We delete the downloads before clearing the active_downloads_ map
304 // so that downloads in the COMPLETING_INTERNAL state (which will have
305 // ignored the Cancel() above) will still show up in active_downloads_
306 // in order to satisfy the invariants enforced in AssertStateConsistent().
[email protected]7745ff02012-10-01 00:09:24307 STLDeleteValues(&downloads_);
[email protected]bd466f302012-10-08 17:11:19308 active_downloads_.clear();
[email protected]7e834f02012-08-09 20:38:56309 downloads_.clear();
initial.commit09911bf2008-07-26 23:55:29310
[email protected]bd466f302012-10-08 17:11:19311 DCHECK(file_manager_);
312 BrowserThread::PostTask(
313 BrowserThread::FILE, FROM_HERE,
314 base::Bind(&DownloadFileManager::OnDownloadManagerShutdown,
315 file_manager_, make_scoped_refptr(this)));
316
[email protected]41f558fb2012-01-09 22:59:58317 // We'll have nothing more to report to the observers after this point.
318 observers_.Clear();
319
[email protected]96c3bdbaa2012-08-31 16:39:54320 file_manager_ = NULL;
[email protected]b441a8492012-06-06 14:55:57321 if (delegate_)
322 delegate_->Shutdown();
[email protected]47665442012-07-27 02:31:22323 delegate_ = NULL;
initial.commit09911bf2008-07-26 23:55:29324}
325
[email protected]5656f8a2011-11-17 16:12:58326bool DownloadManagerImpl::Init(content::BrowserContext* browser_context) {
[email protected]6d0c9fb2011-08-22 19:26:03327 DCHECK(browser_context);
initial.commit09911bf2008-07-26 23:55:29328 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
329 shutdown_needed_ = true;
330
[email protected]6d0c9fb2011-08-22 19:26:03331 browser_context_ = browser_context;
[email protected]024f2f02010-04-30 22:51:46332
initial.commit09911bf2008-07-26 23:55:29333 return true;
334}
335
[email protected]96c3bdbaa2012-08-31 16:39:54336// We have received a message from DownloadFileManager about a new download.
[email protected]3d43eef2012-10-09 23:17:56337DownloadItem* DownloadManagerImpl::StartDownload(
[email protected]2bddd2072012-06-18 16:16:51338 scoped_ptr<DownloadCreateInfo> info,
339 scoped_ptr<content::ByteStreamReader> stream) {
[email protected]ca4b5fa32010-10-09 12:42:18340 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]287b86b2011-02-26 00:11:35341
[email protected]96c3bdbaa2012-08-31 16:39:54342 // |bound_net_log| will be used for logging both the download item's and
343 // the download file's events.
344 net::BoundNetLog bound_net_log = CreateDownloadItem(info.get());
[email protected]2bddd2072012-06-18 16:16:51345
[email protected]96c3bdbaa2012-08-31 16:39:54346 // If info->download_id was unknown on entry to this function, it was
347 // assigned in CreateDownloadItem.
348 DownloadId download_id = info->download_id;
[email protected]2bddd2072012-06-18 16:16:51349
[email protected]96bfed052012-09-15 22:21:01350 if (delegate_) {
351 FilePath website_save_directory; // Unused
352 bool skip_dir_check = false; // Unused
353 delegate_->GetSaveDir(GetBrowserContext(), &website_save_directory,
354 &info->default_download_directory, &skip_dir_check);
355 }
356
[email protected]96c3bdbaa2012-08-31 16:39:54357 DownloadFileManager::CreateDownloadFileCallback callback(
358 base::Bind(&DownloadManagerImpl::OnDownloadFileCreated,
359 this, download_id.local()));
360
361 BrowserThread::PostTask(
362 BrowserThread::FILE, FROM_HERE,
363 base::Bind(&DownloadFileManager::CreateDownloadFile,
364 file_manager_, base::Passed(info.Pass()),
[email protected]f51935a2012-09-10 19:00:11365 base::Passed(stream.Pass()), make_scoped_refptr(this),
366 (delegate_ && delegate_->GenerateFileHash()), bound_net_log,
[email protected]96c3bdbaa2012-08-31 16:39:54367 callback));
368
[email protected]3d43eef2012-10-09 23:17:56369 return GetDownload(download_id.local());
[email protected]96c3bdbaa2012-08-31 16:39:54370}
371
372void DownloadManagerImpl::OnDownloadFileCreated(
373 int32 download_id, content::DownloadInterruptReason reason) {
374 if (reason != content::DOWNLOAD_INTERRUPT_REASON_NONE) {
375 OnDownloadInterrupted(download_id, reason);
376 // TODO(rdsmith): It makes no sense to continue along the
377 // regular download path after we've gotten an error. But it's
378 // the way the code has historically worked, and this allows us
379 // to get the download persisted and observers of the download manager
380 // notified, so tests work. When we execute all side effects of cancel
381 // (including queue removal) immedately rather than waiting for
382 // persistence we should replace this comment with a "return;".
383 }
384
385 DownloadMap::iterator download_iter = active_downloads_.find(download_id);
386 if (download_iter == active_downloads_.end())
387 return;
388
389 DownloadItemImpl* download = download_iter->second;
390 content::DownloadTargetCallback callback =
391 base::Bind(&DownloadManagerImpl::OnDownloadTargetDetermined,
392 this, download_id);
393 if (!delegate_ || !delegate_->DetermineDownloadTarget(download, callback)) {
394 FilePath target_path = download->GetForcedFilePath();
395 // TODO(asanka): Determine a useful path if |target_path| is empty.
396 callback.Run(target_path,
397 DownloadItem::TARGET_DISPOSITION_OVERWRITE,
398 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
399 target_path);
400 }
[email protected]47665442012-07-27 02:31:22401}
402
403void DownloadManagerImpl::OnDownloadTargetDetermined(
404 int32 download_id,
405 const FilePath& target_path,
406 DownloadItem::TargetDisposition disposition,
407 content::DownloadDangerType danger_type,
408 const FilePath& intermediate_path) {
409 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
410 DownloadMap::iterator download_iter = active_downloads_.find(download_id);
411 if (download_iter != active_downloads_.end()) {
412 // Once DownloadItem::OnDownloadTargetDetermined() is called, we expect a
413 // DownloadRenamedToIntermediateName() callback. This is necessary for the
414 // download to proceed.
415 download_iter->second->OnDownloadTargetDetermined(
416 target_path, disposition, danger_type, intermediate_path);
417 }
[email protected]287b86b2011-02-26 00:11:35418}
419
[email protected]5656f8a2011-11-17 16:12:58420void DownloadManagerImpl::CheckForHistoryFilesRemoval() {
[email protected]9fc114672011-06-15 08:17:48421 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]09ea72c7422012-07-02 20:35:40422 for (DownloadMap::iterator it = downloads_.begin();
423 it != downloads_.end(); ++it) {
[email protected]db1d8f72012-07-13 19:23:16424 DownloadItemImpl* item = it->second;
[email protected]09ea72c7422012-07-02 20:35:40425 if (item->IsPersisted())
426 CheckForFileRemoval(item);
[email protected]9fc114672011-06-15 08:17:48427 }
428}
429
[email protected]db1d8f72012-07-13 19:23:16430void DownloadManagerImpl::CheckForFileRemoval(DownloadItemImpl* download_item) {
[email protected]9fc114672011-06-15 08:17:48431 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
432 if (download_item->IsComplete() &&
[email protected]c09a8fd2011-11-21 19:54:50433 !download_item->GetFileExternallyRemoved()) {
[email protected]9fc114672011-06-15 08:17:48434 BrowserThread::PostTask(
435 BrowserThread::FILE, FROM_HERE,
[email protected]5656f8a2011-11-17 16:12:58436 base::Bind(&DownloadManagerImpl::CheckForFileRemovalOnFileThread,
[email protected]09ea72c7422012-07-02 20:35:40437 this, download_item->GetId(),
[email protected]fabf36d22011-10-28 21:50:17438 download_item->GetTargetFilePath()));
[email protected]9fc114672011-06-15 08:17:48439 }
440}
441
[email protected]5656f8a2011-11-17 16:12:58442void DownloadManagerImpl::CheckForFileRemovalOnFileThread(
[email protected]09ea72c7422012-07-02 20:35:40443 int32 download_id, const FilePath& path) {
[email protected]9fc114672011-06-15 08:17:48444 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
445 if (!file_util::PathExists(path)) {
446 BrowserThread::PostTask(
447 BrowserThread::UI, FROM_HERE,
[email protected]5656f8a2011-11-17 16:12:58448 base::Bind(&DownloadManagerImpl::OnFileRemovalDetected,
449 this,
[email protected]09ea72c7422012-07-02 20:35:40450 download_id));
[email protected]9fc114672011-06-15 08:17:48451 }
452}
453
[email protected]09ea72c7422012-07-02 20:35:40454void DownloadManagerImpl::OnFileRemovalDetected(int32 download_id) {
[email protected]9fc114672011-06-15 08:17:48455 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]db1d8f72012-07-13 19:23:16456 if (ContainsKey(downloads_, download_id))
457 downloads_[download_id]->OnDownloadedFileRemoved();
[email protected]9fc114672011-06-15 08:17:48458}
459
[email protected]37757c62011-12-20 20:07:12460content::BrowserContext* DownloadManagerImpl::GetBrowserContext() const {
[email protected]5656f8a2011-11-17 16:12:58461 return browser_context_;
462}
463
[email protected]96c3bdbaa2012-08-31 16:39:54464net::BoundNetLog DownloadManagerImpl::CreateDownloadItem(
465 DownloadCreateInfo* info) {
[email protected]c2e76012010-12-23 21:10:29466 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
467
[email protected]96c3bdbaa2012-08-31 16:39:54468 net::BoundNetLog bound_net_log =
469 net::BoundNetLog::Make(net_log_, net::NetLog::SOURCE_DOWNLOAD);
[email protected]d25fda12012-06-12 17:05:03470 if (!info->download_id.IsValid())
471 info->download_id = GetNextId();
[email protected]96c3bdbaa2012-08-31 16:39:54472 DownloadItemImpl* download = factory_->CreateActiveItem(
[email protected]2bddd2072012-06-18 16:16:51473 this, *info,
474 scoped_ptr<DownloadRequestHandleInterface>(
475 new DownloadRequestHandle(info->request_handle)).Pass(),
[email protected]66521d02012-08-14 17:51:54476 bound_net_log);
[email protected]d8472d92011-08-26 20:15:20477
[email protected]ba7895d2012-06-22 19:02:52478 DCHECK(!ContainsKey(downloads_, download->GetId()));
479 downloads_[download->GetId()] = download;
480 DCHECK(!ContainsKey(active_downloads_, download->GetId()));
481 active_downloads_[download->GetId()] = download;
[email protected]6a1a59a12012-07-26 17:26:40482 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadCreated(this, download));
[email protected]ef17c9a2012-02-09 05:08:09483
[email protected]96c3bdbaa2012-08-31 16:39:54484 return bound_net_log;
[email protected]c2e76012010-12-23 21:10:29485}
486
[email protected]db1d8f72012-07-13 19:23:16487DownloadItemImpl* DownloadManagerImpl::CreateSavePackageDownloadItem(
[email protected]fc03de22011-12-06 23:28:12488 const FilePath& main_file_path,
489 const GURL& page_url,
[email protected]6474b112012-05-04 19:35:27490 const std::string& mime_type,
[email protected]fc03de22011-12-06 23:28:12491 DownloadItem::Observer* observer) {
[email protected]ef17c9a2012-02-09 05:08:09492 net::BoundNetLog bound_net_log =
493 net::BoundNetLog::Make(net_log_, net::NetLog::SOURCE_DOWNLOAD);
[email protected]96c3bdbaa2012-08-31 16:39:54494 DownloadItemImpl* download = factory_->CreateSavePageItem(
[email protected]6474b112012-05-04 19:35:27495 this,
496 main_file_path,
497 page_url,
[email protected]6474b112012-05-04 19:35:27498 GetNextId(),
499 mime_type,
500 bound_net_log);
[email protected]fc03de22011-12-06 23:28:12501
502 download->AddObserver(observer);
503
[email protected]ba7895d2012-06-22 19:02:52504 DCHECK(!ContainsKey(downloads_, download->GetId()));
505 downloads_[download->GetId()] = download;
[email protected]96c3bdbaa2012-08-31 16:39:54506 DCHECK(!SavePageData::Get(download));
507 new SavePageData(download);
508 DCHECK(SavePageData::Get(download));
[email protected]fc03de22011-12-06 23:28:12509
[email protected]8a5ccda2012-08-22 23:55:41510 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadCreated(this, download));
[email protected]6a1a59a12012-07-26 17:26:40511
[email protected]fc03de22011-12-06 23:28:12512 // Will notify the observer in the callback.
[email protected]491aaa62012-06-07 03:50:18513 if (delegate_)
514 delegate_->AddItemToPersistentStore(download);
[email protected]fc03de22011-12-06 23:28:12515
516 return download;
517}
518
[email protected]96c3bdbaa2012-08-31 16:39:54519void DownloadManagerImpl::UpdateDownload(int32 download_id,
520 int64 bytes_so_far,
521 int64 bytes_per_sec,
522 const std::string& hash_state) {
523 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
524 DownloadMap::iterator it = active_downloads_.find(download_id);
525 if (it != active_downloads_.end()) {
526 DownloadItemImpl* download = it->second;
527 if (download->IsInProgress()) {
528 download->UpdateProgress(bytes_so_far, bytes_per_sec, hash_state);
529 if (delegate_)
530 delegate_->UpdateItemInPersistentStore(download);
531 }
532 }
533}
534
535void DownloadManagerImpl::OnResponseCompleted(int32 download_id,
536 int64 size,
537 const std::string& hash) {
538 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
539 VLOG(20) << __FUNCTION__ << "()" << " download_id = " << download_id
540 << " size = " << size;
541 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
542
543 // If it's not in active_downloads_, that means it was cancelled; just
544 // ignore the notification.
545 if (active_downloads_.count(download_id) == 0)
546 return;
547
548 DownloadItemImpl* download = active_downloads_[download_id];
549 download->OnAllDataSaved(size, hash);
550 MaybeCompleteDownload(download);
551}
552
[email protected]db1d8f72012-07-13 19:23:16553void DownloadManagerImpl::AssertStateConsistent(
554 DownloadItemImpl* download) const {
[email protected]ba7895d2012-06-22 19:02:52555 CHECK(ContainsKey(downloads_, download->GetId()));
[email protected]7d413112011-06-16 18:50:17556
[email protected]c09a8fd2011-11-21 19:54:50557 int64 state = download->GetState();
[email protected]61b75a52011-08-29 16:34:34558 base::debug::Alias(&state);
[email protected]c09a8fd2011-11-21 19:54:50559 if (ContainsKey(active_downloads_, download->GetId())) {
[email protected]5009b7a2012-02-21 18:47:03560 if (download->IsPersisted())
[email protected]c09a8fd2011-11-21 19:54:50561 CHECK_EQ(DownloadItem::IN_PROGRESS, download->GetState());
562 if (DownloadItem::IN_PROGRESS != download->GetState())
563 CHECK_EQ(DownloadItem::kUninitializedHandle, download->GetDbHandle());
[email protected]f9a2997f2011-09-23 16:54:07564 }
[email protected]c09a8fd2011-11-21 19:54:50565 if (DownloadItem::IN_PROGRESS == download->GetState())
566 CHECK(ContainsKey(active_downloads_, download->GetId()));
[email protected]5cd11b6e2011-06-10 20:30:59567}
568
[email protected]db1d8f72012-07-13 19:23:16569bool DownloadManagerImpl::IsDownloadReadyForCompletion(
570 DownloadItemImpl* download) {
[email protected]adb2f3d12011-01-23 16:24:54571 // If we don't have all the data, the download is not ready for
572 // completion.
[email protected]c09a8fd2011-11-21 19:54:50573 if (!download->AllDataSaved())
[email protected]adb2f3d12011-01-23 16:24:54574 return false;
[email protected]6a7fb042010-02-01 16:30:47575
[email protected]9d7ef802011-02-25 19:03:35576 // If the download is dangerous, but not yet validated, it's not ready for
577 // completion.
[email protected]c09a8fd2011-11-21 19:54:50578 if (download->GetSafetyState() == DownloadItem::DANGEROUS)
[email protected]9d7ef802011-02-25 19:03:35579 return false;
580
[email protected]adb2f3d12011-01-23 16:24:54581 // If the download isn't active (e.g. has been cancelled) it's not
582 // ready for completion.
[email protected]c09a8fd2011-11-21 19:54:50583 if (active_downloads_.count(download->GetId()) == 0)
[email protected]adb2f3d12011-01-23 16:24:54584 return false;
585
586 // If the download hasn't been inserted into the history system
587 // (which occurs strictly after file name determination, intermediate
588 // file rename, and UI display) then it's not ready for completion.
[email protected]5009b7a2012-02-21 18:47:03589 if (!download->IsPersisted())
[email protected]7054b592011-06-22 14:46:42590 return false;
591
592 return true;
[email protected]adb2f3d12011-01-23 16:24:54593}
594
[email protected]6474b112012-05-04 19:35:27595// When SavePackage downloads MHTML to GData (see
596// SavePackageFilePickerChromeOS), GData calls MaybeCompleteDownload() like it
597// does for non-SavePackage downloads, but SavePackage downloads never satisfy
598// IsDownloadReadyForCompletion(). GDataDownloadObserver manually calls
599// DownloadItem::UpdateObservers() when the upload completes so that SavePackage
600// notices that the upload has completed and runs its normal Finish() pathway.
601// MaybeCompleteDownload() is never the mechanism by which SavePackage completes
602// downloads. SavePackage always uses its own Finish() to mark downloads
603// complete.
604
[email protected]db1d8f72012-07-13 19:23:16605void DownloadManagerImpl::MaybeCompleteDownload(
606 DownloadItemImpl* download) {
[email protected]adb2f3d12011-01-23 16:24:54607 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
608 VLOG(20) << __FUNCTION__ << "()" << " download = "
609 << download->DebugString(false);
610
611 if (!IsDownloadReadyForCompletion(download))
[email protected]9ccbb372008-10-10 18:50:32612 return;
[email protected]9ccbb372008-10-10 18:50:32613
[email protected]adb2f3d12011-01-23 16:24:54614 // TODO(rdsmith): DCHECK that we only pass through this point
615 // once per download. The natural way to do this is by a state
616 // transition on the DownloadItem.
[email protected]594cd7d2010-07-21 03:23:56617
[email protected]adb2f3d12011-01-23 16:24:54618 // Confirm we're in the proper set of states to be here;
[email protected]550520f2012-05-14 20:58:48619 // have all data, have a history handle, (validated or safe).
620 DCHECK(download->IsInProgress());
[email protected]c09a8fd2011-11-21 19:54:50621 DCHECK_NE(DownloadItem::DANGEROUS, download->GetSafetyState());
[email protected]c09a8fd2011-11-21 19:54:50622 DCHECK(download->AllDataSaved());
[email protected]5009b7a2012-02-21 18:47:03623 DCHECK(download->IsPersisted());
[email protected]adb2f3d12011-01-23 16:24:54624
[email protected]da4cd4262012-05-18 20:42:35625 // Give the delegate a chance to override. It's ok to keep re-setting the
626 // delegate's |complete_callback| cb as long as there isn't another call-point
627 // trying to set it to a different cb. TODO(benjhayden): Change the callback
628 // to point directly to the item instead of |this| when DownloadItem supports
629 // weak-ptrs.
[email protected]491aaa62012-06-07 03:50:18630 if (delegate_ && !delegate_->ShouldCompleteDownload(download, base::Bind(
[email protected]da4cd4262012-05-18 20:42:35631 &DownloadManagerImpl::MaybeCompleteDownloadById,
632 this, download->GetId())))
[email protected]c2918652011-11-01 18:50:23633 return;
634
[email protected]adb2f3d12011-01-23 16:24:54635 VLOG(20) << __FUNCTION__ << "()" << " executing: download = "
636 << download->DebugString(false);
637
[email protected]491aaa62012-06-07 03:50:18638 if (delegate_)
639 delegate_->UpdateItemInPersistentStore(download);
[email protected]47665442012-07-27 02:31:22640 download->OnDownloadCompleting();
[email protected]9ccbb372008-10-10 18:50:32641}
642
[email protected]da4cd4262012-05-18 20:42:35643void DownloadManagerImpl::MaybeCompleteDownloadById(int download_id) {
[email protected]db1d8f72012-07-13 19:23:16644 if (ContainsKey(active_downloads_, download_id))
645 MaybeCompleteDownload(active_downloads_[download_id]);
[email protected]da4cd4262012-05-18 20:42:35646}
647
[email protected]db1d8f72012-07-13 19:23:16648void DownloadManagerImpl::DownloadCompleted(DownloadItemImpl* download) {
[email protected]70850c72011-01-11 17:31:27649 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]cc3c7c092011-05-09 18:40:21650 DCHECK(download);
[email protected]491aaa62012-06-07 03:50:18651 if (delegate_)
652 delegate_->UpdateItemInPersistentStore(download);
[email protected]fc03de22011-12-06 23:28:12653 active_downloads_.erase(download->GetId());
654 AssertStateConsistent(download);
[email protected]70850c72011-01-11 17:31:27655}
656
[email protected]5656f8a2011-11-17 16:12:58657void DownloadManagerImpl::CancelDownload(int32 download_id) {
[email protected]93af2272011-09-21 18:29:17658 // A cancel at the right time could remove the download from the
659 // |active_downloads_| map before we get here.
[email protected]db1d8f72012-07-13 19:23:16660 if (ContainsKey(active_downloads_, download_id))
661 active_downloads_[download_id]->Cancel(true);
[email protected]93af2272011-09-21 18:29:17662}
663
[email protected]db1d8f72012-07-13 19:23:16664void DownloadManagerImpl::DownloadStopped(DownloadItemImpl* download) {
[email protected]d8472d92011-08-26 20:15:20665 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]d8472d92011-08-26 20:15:20666
667 VLOG(20) << __FUNCTION__ << "()"
[email protected]da6e3922010-11-24 21:45:50668 << " download = " << download->DebugString(true);
669
[email protected]93af2272011-09-21 18:29:17670 RemoveFromActiveList(download);
[email protected]47a881b2011-08-29 22:59:21671 // This function is called from the DownloadItem, so DI state
672 // should already have been updated.
[email protected]fc03de22011-12-06 23:28:12673 AssertStateConsistent(download);
[email protected]96c3bdbaa2012-08-31 16:39:54674
675 DCHECK(file_manager_);
676 download->OffThreadCancel();
677}
678
679void DownloadManagerImpl::OnDownloadInterrupted(
680 int32 download_id,
681 content::DownloadInterruptReason reason) {
682 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
683
684 if (!ContainsKey(active_downloads_, download_id))
685 return;
686 active_downloads_[download_id]->Interrupt(reason);
[email protected]47a881b2011-08-29 22:59:21687}
688
[email protected]db1d8f72012-07-13 19:23:16689void DownloadManagerImpl::RemoveFromActiveList(DownloadItemImpl* download) {
[email protected]93af2272011-09-21 18:29:17690 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
691 DCHECK(download);
692
693 // Clean up will happen when the history system create callback runs if we
694 // don't have a valid db_handle yet.
[email protected]5009b7a2012-02-21 18:47:03695 if (download->IsPersisted()) {
[email protected]c09a8fd2011-11-21 19:54:50696 active_downloads_.erase(download->GetId());
[email protected]491aaa62012-06-07 03:50:18697 if (delegate_)
698 delegate_->UpdateItemInPersistentStore(download);
[email protected]93af2272011-09-21 18:29:17699 }
700}
701
[email protected]5656f8a2011-11-17 16:12:58702int DownloadManagerImpl::RemoveDownloadItems(
[email protected]db1d8f72012-07-13 19:23:16703 const DownloadItemImplVector& pending_deletes) {
[email protected]6d0146c2011-08-04 19:13:04704 if (pending_deletes.empty())
705 return 0;
706
707 // Delete from internal maps.
[email protected]db1d8f72012-07-13 19:23:16708 for (DownloadItemImplVector::const_iterator it = pending_deletes.begin();
[email protected]7e834f02012-08-09 20:38:56709 it != pending_deletes.end();
710 ++it) {
[email protected]db1d8f72012-07-13 19:23:16711 DownloadItemImpl* download = *it;
[email protected]6d0146c2011-08-04 19:13:04712 DCHECK(download);
[email protected]7e834f02012-08-09 20:38:56713 int32 download_id = download->GetId();
714 delete download;
715 downloads_.erase(download_id);
[email protected]6d0146c2011-08-04 19:13:04716 }
[email protected]6d0146c2011-08-04 19:13:04717 NotifyModelChanged();
[email protected]7e834f02012-08-09 20:38:56718 return static_cast<int>(pending_deletes.size());
[email protected]6d0146c2011-08-04 19:13:04719}
720
[email protected]db1d8f72012-07-13 19:23:16721void DownloadManagerImpl::DownloadRemoved(DownloadItemImpl* download) {
[email protected]09ea72c7422012-07-02 20:35:40722 if (!download ||
723 downloads_.find(download->GetId()) == downloads_.end())
724 return;
725
726 // TODO(benjhayden,rdsmith): Remove this.
727 if (!download->IsPersisted())
[email protected]93af2272011-09-21 18:29:17728 return;
729
730 // Make history update.
[email protected]491aaa62012-06-07 03:50:18731 if (delegate_)
732 delegate_->RemoveItemFromPersistentStore(download);
initial.commit09911bf2008-07-26 23:55:29733
734 // Remove from our tables and delete.
[email protected]db1d8f72012-07-13 19:23:16735 int downloads_count =
736 RemoveDownloadItems(DownloadItemImplVector(1, download));
[email protected]f04182f32010-12-10 19:12:07737 DCHECK_EQ(1, downloads_count);
initial.commit09911bf2008-07-26 23:55:29738}
739
[email protected]fd3a82832012-01-19 20:35:12740int DownloadManagerImpl::RemoveDownloadsBetween(base::Time remove_begin,
741 base::Time remove_end) {
[email protected]491aaa62012-06-07 03:50:18742 if (delegate_)
743 delegate_->RemoveItemsFromPersistentStoreBetween(remove_begin, remove_end);
initial.commit09911bf2008-07-26 23:55:29744
[email protected]db1d8f72012-07-13 19:23:16745 DownloadItemImplVector pending_deletes;
[email protected]09ea72c7422012-07-02 20:35:40746 for (DownloadMap::const_iterator it = downloads_.begin();
747 it != downloads_.end();
[email protected]6d0146c2011-08-04 19:13:04748 ++it) {
[email protected]db1d8f72012-07-13 19:23:16749 DownloadItemImpl* download = it->second;
[email protected]09ea72c7422012-07-02 20:35:40750 if (download->IsPersisted() &&
751 download->GetStartTime() >= remove_begin &&
[email protected]c09a8fd2011-11-21 19:54:50752 (remove_end.is_null() || download->GetStartTime() < remove_end) &&
[email protected]6d0146c2011-08-04 19:13:04753 (download->IsComplete() || download->IsCancelled())) {
[email protected]fc03de22011-12-06 23:28:12754 AssertStateConsistent(download);
[email protected]7e834f02012-08-09 20:38:56755 download->NotifyRemoved();
[email protected]78b8fcc92009-03-31 17:36:28756 pending_deletes.push_back(download);
initial.commit09911bf2008-07-26 23:55:29757 }
initial.commit09911bf2008-07-26 23:55:29758 }
[email protected]6d0146c2011-08-04 19:13:04759 return RemoveDownloadItems(pending_deletes);
initial.commit09911bf2008-07-26 23:55:29760}
761
[email protected]fd3a82832012-01-19 20:35:12762int DownloadManagerImpl::RemoveDownloads(base::Time remove_begin) {
[email protected]e93d2822009-01-30 05:59:59763 return RemoveDownloadsBetween(remove_begin, base::Time());
initial.commit09911bf2008-07-26 23:55:29764}
765
[email protected]5656f8a2011-11-17 16:12:58766int DownloadManagerImpl::RemoveAllDownloads() {
[email protected]d41355e6f2009-04-07 21:21:12767 // The null times make the date range unbounded.
[email protected]09ea72c7422012-07-02 20:35:40768 int num_deleted = RemoveDownloadsBetween(base::Time(), base::Time());
769 download_stats::RecordClearAllSize(num_deleted);
770 return num_deleted;
[email protected]d41355e6f2009-04-07 21:21:12771}
772
[email protected]0d4e30c2012-01-28 00:47:53773void DownloadManagerImpl::DownloadUrl(
[email protected]c5a5c0842012-05-04 20:05:14774 scoped_ptr<content::DownloadUrlParameters> params) {
775 if (params->post_id() >= 0) {
776 // Check this here so that the traceback is more useful.
777 DCHECK(params->prefer_cache());
778 DCHECK(params->method() == "POST");
779 }
780 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
[email protected]c873c862012-10-17 15:32:12781 &BeginDownload, base::Passed(params.Pass())));
initial.commit09911bf2008-07-26 23:55:29782}
783
[email protected]5656f8a2011-11-17 16:12:58784void DownloadManagerImpl::AddObserver(Observer* observer) {
initial.commit09911bf2008-07-26 23:55:29785 observers_.AddObserver(observer);
[email protected]a1e41e72012-02-22 17:41:25786 // TODO: It is the responsibility of the observers to query the
787 // DownloadManager. Remove the following call from here and update all
788 // observers.
[email protected]75e51b52012-02-04 16:57:54789 observer->ModelChanged(this);
initial.commit09911bf2008-07-26 23:55:29790}
791
[email protected]5656f8a2011-11-17 16:12:58792void DownloadManagerImpl::RemoveObserver(Observer* observer) {
initial.commit09911bf2008-07-26 23:55:29793 observers_.RemoveObserver(observer);
794}
795
initial.commit09911bf2008-07-26 23:55:29796// Operations posted to us from the history service ----------------------------
797
798// The history service has retrieved all download entries. 'entries' contains
[email protected]bb1a4212011-08-22 22:38:25799// 'DownloadPersistentStoreInfo's in sorted order (by ascending start_time).
[email protected]5656f8a2011-11-17 16:12:58800void DownloadManagerImpl::OnPersistentStoreQueryComplete(
[email protected]bb1a4212011-08-22 22:38:25801 std::vector<DownloadPersistentStoreInfo>* entries) {
[email protected]09ea72c7422012-07-02 20:35:40802 history_size_ = entries->size();
initial.commit09911bf2008-07-26 23:55:29803 for (size_t i = 0; i < entries->size(); ++i) {
[email protected]deb40832012-02-23 15:41:37804 int64 db_handle = entries->at(i).db_handle;
805 base::debug::Alias(&db_handle);
[email protected]deb40832012-02-23 15:41:37806
[email protected]ef17c9a2012-02-09 05:08:09807 net::BoundNetLog bound_net_log =
808 net::BoundNetLog::Make(net_log_, net::NetLog::SOURCE_DOWNLOAD);
[email protected]96c3bdbaa2012-08-31 16:39:54809 DownloadItemImpl* download = factory_->CreatePersistedItem(
[email protected]ef17c9a2012-02-09 05:08:09810 this, GetNextId(), entries->at(i), bound_net_log);
[email protected]ba7895d2012-06-22 19:02:52811 DCHECK(!ContainsKey(downloads_, download->GetId()));
812 downloads_[download->GetId()] = download;
[email protected]6a1a59a12012-07-26 17:26:40813 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadCreated(this, download));
[email protected]da6e3922010-11-24 21:45:50814 VLOG(20) << __FUNCTION__ << "()" << i << ">"
815 << " download = " << download->DebugString(true);
initial.commit09911bf2008-07-26 23:55:29816 }
[email protected]b0ab1d42010-02-24 19:29:28817 NotifyModelChanged();
[email protected]9fc114672011-06-15 08:17:48818 CheckForHistoryFilesRemoval();
initial.commit09911bf2008-07-26 23:55:29819}
820
[email protected]db1d8f72012-07-13 19:23:16821void DownloadManagerImpl::AddDownloadItemToHistory(DownloadItemImpl* download,
[email protected]5656f8a2011-11-17 16:12:58822 int64 db_handle) {
[email protected]70850c72011-01-11 17:31:27823 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]0634626a2012-05-03 19:04:26824 DCHECK_NE(DownloadItem::kUninitializedHandle, db_handle);
[email protected]5009b7a2012-02-21 18:47:03825 DCHECK(!download->IsPersisted());
[email protected]c09a8fd2011-11-21 19:54:50826 download->SetDbHandle(db_handle);
[email protected]5009b7a2012-02-21 18:47:03827 download->SetIsPersisted();
[email protected]5bcd73eb2011-03-23 21:14:02828
[email protected]09ea72c7422012-07-02 20:35:40829 download_stats::RecordHistorySize(history_size_);
830 // Not counting |download|.
831 ++history_size_;
[email protected]6d0146c2011-08-04 19:13:04832
833 // Show in the appropriate browser UI.
834 // This includes buttons to save or cancel, for a dangerous download.
835 ShowDownloadInBrowser(download);
836
837 // Inform interested objects about the new download.
838 NotifyModelChanged();
[email protected]f9a45b02011-06-30 23:49:19839}
840
[email protected]96c3bdbaa2012-08-31 16:39:54841
[email protected]5656f8a2011-11-17 16:12:58842void DownloadManagerImpl::OnItemAddedToPersistentStore(int32 download_id,
843 int64 db_handle) {
[email protected]2588ea9d2011-08-22 20:59:53844 // It's valid that we don't find a matching item, i.e. on shutdown.
[email protected]db1d8f72012-07-13 19:23:16845 if (!ContainsKey(downloads_, download_id))
[email protected]99229b22012-07-11 17:38:50846 return;
[email protected]db1d8f72012-07-13 19:23:16847
848 DownloadItemImpl* item = downloads_[download_id];
[email protected]99229b22012-07-11 17:38:50849 AddDownloadItemToHistory(item, db_handle);
[email protected]96c3bdbaa2012-08-31 16:39:54850 if (SavePageData::Get(item)) {
[email protected]99229b22012-07-11 17:38:50851 OnSavePageItemAddedToPersistentStore(item);
852 } else {
853 OnDownloadItemAddedToPersistentStore(item);
854 }
[email protected]2588ea9d2011-08-22 20:59:53855}
856
[email protected]09ea72c7422012-07-02 20:35:40857// Once the new DownloadItem has been committed to the persistent store,
858// associate it with its db_handle (TODO(benjhayden) merge db_handle with id),
859// show it in the browser (TODO(benjhayden) the ui should observe us instead),
860// and notify observers (TODO(benjhayden) observers should be able to see the
861// item when it's created so they can observe it directly. Are there any
862// clients that actually need to know when the item is added to the history?).
[email protected]5656f8a2011-11-17 16:12:58863void DownloadManagerImpl::OnDownloadItemAddedToPersistentStore(
[email protected]db1d8f72012-07-13 19:23:16864 DownloadItemImpl* item) {
[email protected]f9a45b02011-06-30 23:49:19865 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]99229b22012-07-11 17:38:50866 VLOG(20) << __FUNCTION__ << "()" << " db_handle = " << item->GetDbHandle()
867 << " download_id = " << item->GetId()
868 << " download = " << item->DebugString(true);
initial.commit09911bf2008-07-26 23:55:29869
[email protected]93af2272011-09-21 18:29:17870 // If the download is still in progress, try to complete it.
871 //
872 // Otherwise, download has been cancelled or interrupted before we've
873 // received the DB handle. We post one final message to the history
874 // service so that it can be properly in sync with the DownloadItem's
875 // completion status, and also inform any observers so that they get
876 // more than just the start notification.
[email protected]99229b22012-07-11 17:38:50877 if (item->IsInProgress()) {
878 MaybeCompleteDownload(item);
[email protected]93af2272011-09-21 18:29:17879 } else {
[email protected]99229b22012-07-11 17:38:50880 DCHECK(item->IsCancelled());
881 active_downloads_.erase(item->GetId());
[email protected]491aaa62012-06-07 03:50:18882 if (delegate_)
[email protected]99229b22012-07-11 17:38:50883 delegate_->UpdateItemInPersistentStore(item);
884 item->UpdateObservers();
[email protected]93af2272011-09-21 18:29:17885 }
initial.commit09911bf2008-07-26 23:55:29886}
887
[email protected]db1d8f72012-07-13 19:23:16888void DownloadManagerImpl::ShowDownloadInBrowser(DownloadItemImpl* download) {
[email protected]a29e4f22012-04-12 21:22:03889 // The 'contents' may no longer exist if the user closed the contents before
890 // we get this start completion event.
[email protected]a62d42902012-01-24 17:24:38891 WebContents* content = download->GetWebContents();
[email protected]99cb7f82011-07-28 17:27:26892
893 // If the contents no longer exists, we ask the embedder to suggest another
[email protected]a29e4f22012-04-12 21:22:03894 // contents.
[email protected]491aaa62012-06-07 03:50:18895 if (!content && delegate_)
[email protected]ef9572e2012-01-04 22:14:12896 content = delegate_->GetAlternativeWebContentsToNotifyForDownload();
[email protected]5e595482009-05-06 20:16:53897
[email protected]0bfbf882011-12-22 18:19:27898 if (content && content->GetDelegate())
899 content->GetDelegate()->OnStartDownload(content, download);
[email protected]5e595482009-05-06 20:16:53900}
901
[email protected]5656f8a2011-11-17 16:12:58902int DownloadManagerImpl::InProgressCount() const {
[email protected]550520f2012-05-14 20:58:48903 // Don't use active_downloads_.count() because Cancel() leaves items in
904 // active_downloads_ if they haven't made it into the persistent store yet.
[email protected]007e7412012-03-13 20:10:56905 // Need to actually look at each item's state.
906 int count = 0;
[email protected]550520f2012-05-14 20:58:48907 for (DownloadMap::const_iterator it = active_downloads_.begin();
908 it != active_downloads_.end(); ++it) {
[email protected]db1d8f72012-07-13 19:23:16909 DownloadItemImpl* item = it->second;
[email protected]007e7412012-03-13 20:10:56910 if (item->IsInProgress())
911 ++count;
912 }
913 return count;
[email protected]5656f8a2011-11-17 16:12:58914}
915
[email protected]5656f8a2011-11-17 16:12:58916void DownloadManagerImpl::NotifyModelChanged() {
[email protected]75e51b52012-02-04 16:57:54917 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged(this));
[email protected]b0ab1d42010-02-24 19:29:28918}
919
[email protected]ba7895d2012-06-22 19:02:52920DownloadItem* DownloadManagerImpl::GetDownload(int download_id) {
921 return ContainsKey(downloads_, download_id) ? downloads_[download_id] : NULL;
922}
923
[email protected]9f1f4092012-09-10 21:18:04924void DownloadManagerImpl::GetAllDownloads(DownloadVector* downloads) {
925 for (DownloadMap::iterator it = downloads_.begin();
926 it != downloads_.end(); ++it) {
927 downloads->push_back(it->second);
928 }
929}
930
[email protected]57fd1252010-12-23 17:24:09931// Confirm that everything in all maps is also in |downloads_|, and that
932// everything in |downloads_| is also in some other map.
[email protected]5656f8a2011-11-17 16:12:58933void DownloadManagerImpl::AssertContainersConsistent() const {
[email protected]f04182f32010-12-10 19:12:07934#if !defined(NDEBUG)
[email protected]57fd1252010-12-23 17:24:09935 // Turn everything into sets.
[email protected]99229b22012-07-11 17:38:50936 const DownloadMap* input_maps[] = {&active_downloads_};
937 DownloadSet active_set;
938 DownloadSet* all_sets[] = {&active_set};
[email protected]6d0146c2011-08-04 19:13:04939 DCHECK_EQ(ARRAYSIZE_UNSAFE(input_maps), ARRAYSIZE_UNSAFE(all_sets));
[email protected]57fd1252010-12-23 17:24:09940 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input_maps); i++) {
941 for (DownloadMap::const_iterator it = input_maps[i]->begin();
[email protected]6d0146c2011-08-04 19:13:04942 it != input_maps[i]->end(); ++it) {
943 all_sets[i]->insert(&*it->second);
[email protected]f04182f32010-12-10 19:12:07944 }
945 }
[email protected]57fd1252010-12-23 17:24:09946
[email protected]ba7895d2012-06-22 19:02:52947 DownloadSet all_downloads;
948 for (DownloadMap::const_iterator it = downloads_.begin();
949 it != downloads_.end(); ++it) {
950 all_downloads.insert(it->second);
951 }
952
[email protected]57fd1252010-12-23 17:24:09953 // Check if each set is fully present in downloads, and create a union.
[email protected]57fd1252010-12-23 17:24:09954 for (int i = 0; i < static_cast<int>(ARRAYSIZE_UNSAFE(all_sets)); i++) {
955 DownloadSet remainder;
956 std::insert_iterator<DownloadSet> insert_it(remainder, remainder.begin());
957 std::set_difference(all_sets[i]->begin(), all_sets[i]->end(),
[email protected]ba7895d2012-06-22 19:02:52958 all_downloads.begin(), all_downloads.end(),
[email protected]57fd1252010-12-23 17:24:09959 insert_it);
960 DCHECK(remainder.empty());
[email protected]57fd1252010-12-23 17:24:09961 }
[email protected]f04182f32010-12-10 19:12:07962#endif
963}
964
[email protected]6d0146c2011-08-04 19:13:04965// SavePackage will call SavePageDownloadFinished upon completion/cancellation.
[email protected]2588ea9d2011-08-22 20:59:53966// The history callback will call OnSavePageItemAddedToPersistentStore.
[email protected]6d0146c2011-08-04 19:13:04967// If the download finishes before the history callback,
[email protected]2588ea9d2011-08-22 20:59:53968// OnSavePageItemAddedToPersistentStore calls SavePageDownloadFinished, ensuring
969// that the history event is update regardless of the order in which these two
970// events complete.
[email protected]6d0146c2011-08-04 19:13:04971// If something removes the download item from the download manager (Remove,
972// Shutdown) the result will be that the SavePage system will not be able to
973// properly update the download item (which no longer exists) or the download
974// history, but the action will complete properly anyway. This may lead to the
975// history entry being wrong on a reload of chrome (specifically in the case of
976// Initiation -> History Callback -> Removal -> Completion), but there's no way
977// to solve that without canceling on Remove (which would then update the DB).
978
[email protected]5656f8a2011-11-17 16:12:58979void DownloadManagerImpl::OnSavePageItemAddedToPersistentStore(
[email protected]db1d8f72012-07-13 19:23:16980 DownloadItemImpl* item) {
[email protected]6d0146c2011-08-04 19:13:04981 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
982
[email protected]6d0146c2011-08-04 19:13:04983 // Finalize this download if it finished before the history callback.
[email protected]99229b22012-07-11 17:38:50984 if (!item->IsInProgress())
985 SavePageDownloadFinished(item);
[email protected]6d0146c2011-08-04 19:13:04986}
987
[email protected]db1d8f72012-07-13 19:23:16988void DownloadManagerImpl::SavePageDownloadFinished(
989 content::DownloadItem* download) {
[email protected]5009b7a2012-02-21 18:47:03990 if (download->IsPersisted()) {
[email protected]491aaa62012-06-07 03:50:18991 if (delegate_)
992 delegate_->UpdateItemInPersistentStore(download);
[email protected]6d0146c2011-08-04 19:13:04993 }
994}
[email protected]da4a5582011-10-17 19:08:06995
[email protected]db1d8f72012-07-13 19:23:16996void DownloadManagerImpl::DownloadOpened(DownloadItemImpl* download) {
[email protected]491aaa62012-06-07 03:50:18997 if (delegate_)
998 delegate_->UpdateItemInPersistentStore(download);
[email protected]da4a5582011-10-17 19:08:06999 int num_unopened = 0;
[email protected]09ea72c7422012-07-02 20:35:401000 for (DownloadMap::iterator it = downloads_.begin();
1001 it != downloads_.end(); ++it) {
[email protected]db1d8f72012-07-13 19:23:161002 DownloadItemImpl* item = it->second;
[email protected]09ea72c7422012-07-02 20:35:401003 if (item->IsComplete() &&
1004 !item->GetOpened())
[email protected]da4a5582011-10-17 19:08:061005 ++num_unopened;
1006 }
1007 download_stats::RecordOpensOutstanding(num_unopened);
1008}
[email protected]5656f8a2011-11-17 16:12:581009
[email protected]3d833de2012-05-30 23:32:061010void DownloadManagerImpl::DownloadRenamedToIntermediateName(
[email protected]db1d8f72012-07-13 19:23:161011 DownloadItemImpl* download) {
[email protected]3d833de2012-05-30 23:32:061012 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]47665442012-07-27 02:31:221013 // download->GetFullPath() is only expected to be meaningful after this
1014 // callback is received. Therefore we can now add the download to a persistent
[email protected]96c3bdbaa2012-08-31 16:39:541015 // store. If the rename failed, we receive an OnDownloadInterrupted() call
[email protected]47665442012-07-27 02:31:221016 // before we receive the DownloadRenamedToIntermediateName() call.
1017 if (delegate_) {
[email protected]491aaa62012-06-07 03:50:181018 delegate_->AddItemToPersistentStore(download);
[email protected]47665442012-07-27 02:31:221019 } else {
1020 OnItemAddedToPersistentStore(download->GetId(),
1021 DownloadItem::kUninitializedHandle);
1022 }
[email protected]3d833de2012-05-30 23:32:061023}
1024
1025void DownloadManagerImpl::DownloadRenamedToFinalName(
[email protected]db1d8f72012-07-13 19:23:161026 DownloadItemImpl* download) {
[email protected]3d833de2012-05-30 23:32:061027 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
[email protected]96c3bdbaa2012-08-31 16:39:541028 // If the rename failed, we receive an OnDownloadInterrupted() call before we
1029 // receive the DownloadRenamedToFinalName() call.
[email protected]491aaa62012-06-07 03:50:181030 if (delegate_) {
1031 delegate_->UpdatePathForItemInPersistentStore(
1032 download, download->GetFullPath());
1033 }
[email protected]3d833de2012-05-30 23:32:061034}