Add ICU message format support
[chromium-blink-merge.git] / content / browser / download / download_manager_impl.cc
blob3f9a38444442e56ff182806f232c497a0cfd7b78
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/browser/download/download_manager_impl.h"
7 #include <iterator>
9 #include "base/bind.h"
10 #include "base/callback.h"
11 #include "base/debug/alias.h"
12 #include "base/i18n/case_conversion.h"
13 #include "base/logging.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/stl_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/sys_string_conversions.h"
18 #include "base/supports_user_data.h"
19 #include "base/synchronization/lock.h"
20 #include "build/build_config.h"
21 #include "content/browser/byte_stream.h"
22 #include "content/browser/download/download_create_info.h"
23 #include "content/browser/download/download_file_factory.h"
24 #include "content/browser/download/download_item_factory.h"
25 #include "content/browser/download/download_item_impl.h"
26 #include "content/browser/download/download_stats.h"
27 #include "content/browser/loader/resource_dispatcher_host_impl.h"
28 #include "content/browser/renderer_host/render_view_host_impl.h"
29 #include "content/browser/web_contents/web_contents_impl.h"
30 #include "content/public/browser/browser_context.h"
31 #include "content/public/browser/browser_thread.h"
32 #include "content/public/browser/content_browser_client.h"
33 #include "content/public/browser/download_interrupt_reasons.h"
34 #include "content/public/browser/download_manager_delegate.h"
35 #include "content/public/browser/download_url_parameters.h"
36 #include "content/public/browser/notification_service.h"
37 #include "content/public/browser/notification_types.h"
38 #include "content/public/browser/render_process_host.h"
39 #include "content/public/browser/resource_context.h"
40 #include "content/public/browser/web_contents_delegate.h"
41 #include "content/public/common/referrer.h"
42 #include "net/base/elements_upload_data_stream.h"
43 #include "net/base/load_flags.h"
44 #include "net/base/request_priority.h"
45 #include "net/base/upload_bytes_element_reader.h"
46 #include "net/url_request/url_request_context.h"
47 #include "url/origin.h"
49 namespace content {
50 namespace {
52 void BeginDownload(scoped_ptr<DownloadUrlParameters> params,
53 uint32 download_id) {
54 DCHECK_CURRENTLY_ON(BrowserThread::IO);
55 // ResourceDispatcherHost{Base} is-not-a URLRequest::Delegate, and
56 // DownloadUrlParameters can-not include resource_dispatcher_host_impl.h, so
57 // we must down cast. RDHI is the only subclass of RDH as of 2012 May 4.
58 scoped_ptr<net::URLRequest> request(
59 params->resource_context()->GetRequestContext()->CreateRequest(
60 params->url(), net::DEFAULT_PRIORITY, NULL));
61 request->set_method(params->method());
62 if (!params->post_body().empty()) {
63 const std::string& body = params->post_body();
64 scoped_ptr<net::UploadElementReader> reader(
65 net::UploadOwnedBytesElementReader::CreateWithString(body));
66 request->set_upload(
67 net::ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0));
69 if (params->post_id() >= 0) {
70 // The POST in this case does not have an actual body, and only works
71 // when retrieving data from cache. This is done because we don't want
72 // to do a re-POST without user consent, and currently don't have a good
73 // plan on how to display the UI for that.
74 DCHECK(params->prefer_cache());
75 DCHECK_EQ("POST", params->method());
76 ScopedVector<net::UploadElementReader> element_readers;
77 request->set_upload(make_scoped_ptr(
78 new net::ElementsUploadDataStream(element_readers.Pass(),
79 params->post_id())));
82 // If we're not at the beginning of the file, retrieve only the remaining
83 // portion.
84 bool has_last_modified = !params->last_modified().empty();
85 bool has_etag = !params->etag().empty();
87 // If we've asked for a range, we want to make sure that we only
88 // get that range if our current copy of the information is good.
89 // We shouldn't be asked to continue if we don't have a verifier.
90 DCHECK(params->offset() == 0 || has_etag || has_last_modified);
92 if (params->offset() > 0) {
93 request->SetExtraRequestHeaderByName(
94 "Range",
95 base::StringPrintf("bytes=%" PRId64 "-", params->offset()),
96 true);
98 if (has_last_modified) {
99 request->SetExtraRequestHeaderByName("If-Unmodified-Since",
100 params->last_modified(),
101 true);
103 if (has_etag) {
104 request->SetExtraRequestHeaderByName("If-Match", params->etag(), true);
108 for (DownloadUrlParameters::RequestHeadersType::const_iterator iter
109 = params->request_headers_begin();
110 iter != params->request_headers_end();
111 ++iter) {
112 request->SetExtraRequestHeaderByName(
113 iter->first, iter->second, false /*overwrite*/);
116 scoped_ptr<DownloadSaveInfo> save_info(new DownloadSaveInfo());
117 save_info->file_path = params->file_path();
118 save_info->suggested_name = params->suggested_name();
119 save_info->offset = params->offset();
120 save_info->hash_state = params->hash_state();
121 save_info->prompt_for_save_location = params->prompt();
122 save_info->file = params->GetFile();
124 ResourceDispatcherHost::Get()->BeginDownload(
125 request.Pass(),
126 params->referrer(),
127 params->content_initiated(),
128 params->resource_context(),
129 params->render_process_host_id(),
130 params->render_view_host_routing_id(),
131 params->prefer_cache(),
132 params->do_not_prompt_for_login(),
133 save_info.Pass(),
134 download_id,
135 params->callback());
138 class MapValueIteratorAdapter {
139 public:
140 explicit MapValueIteratorAdapter(
141 base::hash_map<int64, DownloadItem*>::const_iterator iter)
142 : iter_(iter) {
144 ~MapValueIteratorAdapter() {}
146 DownloadItem* operator*() { return iter_->second; }
148 MapValueIteratorAdapter& operator++() {
149 ++iter_;
150 return *this;
153 bool operator!=(const MapValueIteratorAdapter& that) const {
154 return iter_ != that.iter_;
157 private:
158 base::hash_map<int64, DownloadItem*>::const_iterator iter_;
159 // Allow copy and assign.
162 class DownloadItemFactoryImpl : public DownloadItemFactory {
163 public:
164 DownloadItemFactoryImpl() {}
165 ~DownloadItemFactoryImpl() override {}
167 DownloadItemImpl* CreatePersistedItem(
168 DownloadItemImplDelegate* delegate,
169 uint32 download_id,
170 const base::FilePath& current_path,
171 const base::FilePath& target_path,
172 const std::vector<GURL>& url_chain,
173 const GURL& referrer_url,
174 const std::string& mime_type,
175 const std::string& original_mime_type,
176 const base::Time& start_time,
177 const base::Time& end_time,
178 const std::string& etag,
179 const std::string& last_modified,
180 int64 received_bytes,
181 int64 total_bytes,
182 DownloadItem::DownloadState state,
183 DownloadDangerType danger_type,
184 DownloadInterruptReason interrupt_reason,
185 bool opened,
186 const net::BoundNetLog& bound_net_log) override {
187 return new DownloadItemImpl(
188 delegate,
189 download_id,
190 current_path,
191 target_path,
192 url_chain,
193 referrer_url,
194 mime_type,
195 original_mime_type,
196 start_time,
197 end_time,
198 etag,
199 last_modified,
200 received_bytes,
201 total_bytes,
202 state,
203 danger_type,
204 interrupt_reason,
205 opened,
206 bound_net_log);
209 DownloadItemImpl* CreateActiveItem(
210 DownloadItemImplDelegate* delegate,
211 uint32 download_id,
212 const DownloadCreateInfo& info,
213 const net::BoundNetLog& bound_net_log) override {
214 return new DownloadItemImpl(delegate, download_id, info, bound_net_log);
217 DownloadItemImpl* CreateSavePageItem(
218 DownloadItemImplDelegate* delegate,
219 uint32 download_id,
220 const base::FilePath& path,
221 const GURL& url,
222 const std::string& mime_type,
223 scoped_ptr<DownloadRequestHandleInterface> request_handle,
224 const net::BoundNetLog& bound_net_log) override {
225 return new DownloadItemImpl(delegate, download_id, path, url,
226 mime_type, request_handle.Pass(),
227 bound_net_log);
231 } // namespace
233 DownloadManagerImpl::DownloadManagerImpl(
234 net::NetLog* net_log,
235 BrowserContext* browser_context)
236 : item_factory_(new DownloadItemFactoryImpl()),
237 file_factory_(new DownloadFileFactory()),
238 history_size_(0),
239 shutdown_needed_(true),
240 browser_context_(browser_context),
241 delegate_(NULL),
242 net_log_(net_log),
243 weak_factory_(this) {
244 DCHECK(browser_context);
247 DownloadManagerImpl::~DownloadManagerImpl() {
248 DCHECK(!shutdown_needed_);
251 DownloadItemImpl* DownloadManagerImpl::CreateActiveItem(
252 uint32 id, const DownloadCreateInfo& info) {
253 DCHECK_CURRENTLY_ON(BrowserThread::UI);
254 DCHECK(!ContainsKey(downloads_, id));
255 net::BoundNetLog bound_net_log =
256 net::BoundNetLog::Make(net_log_, net::NetLog::SOURCE_DOWNLOAD);
257 DownloadItemImpl* download =
258 item_factory_->CreateActiveItem(this, id, info, bound_net_log);
259 downloads_[id] = download;
260 return download;
263 void DownloadManagerImpl::GetNextId(const DownloadIdCallback& callback) {
264 DCHECK_CURRENTLY_ON(BrowserThread::UI);
265 if (delegate_) {
266 delegate_->GetNextId(callback);
267 return;
269 static uint32 next_id = content::DownloadItem::kInvalidId + 1;
270 callback.Run(next_id++);
273 void DownloadManagerImpl::DetermineDownloadTarget(
274 DownloadItemImpl* item, const DownloadTargetCallback& callback) {
275 // Note that this next call relies on
276 // DownloadItemImplDelegate::DownloadTargetCallback and
277 // DownloadManagerDelegate::DownloadTargetCallback having the same
278 // type. If the types ever diverge, gasket code will need to
279 // be written here.
280 if (!delegate_ || !delegate_->DetermineDownloadTarget(item, callback)) {
281 base::FilePath target_path = item->GetForcedFilePath();
282 // TODO(asanka): Determine a useful path if |target_path| is empty.
283 callback.Run(target_path,
284 DownloadItem::TARGET_DISPOSITION_OVERWRITE,
285 DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
286 target_path);
290 bool DownloadManagerImpl::ShouldCompleteDownload(
291 DownloadItemImpl* item, const base::Closure& complete_callback) {
292 if (!delegate_ ||
293 delegate_->ShouldCompleteDownload(item, complete_callback)) {
294 return true;
296 // Otherwise, the delegate has accepted responsibility to run the
297 // callback when the download is ready for completion.
298 return false;
301 bool DownloadManagerImpl::ShouldOpenFileBasedOnExtension(
302 const base::FilePath& path) {
303 if (!delegate_)
304 return false;
306 return delegate_->ShouldOpenFileBasedOnExtension(path);
309 bool DownloadManagerImpl::ShouldOpenDownload(
310 DownloadItemImpl* item, const ShouldOpenDownloadCallback& callback) {
311 if (!delegate_)
312 return true;
314 // Relies on DownloadItemImplDelegate::ShouldOpenDownloadCallback and
315 // DownloadManagerDelegate::DownloadOpenDelayedCallback "just happening"
316 // to have the same type :-}.
317 return delegate_->ShouldOpenDownload(item, callback);
320 void DownloadManagerImpl::SetDelegate(DownloadManagerDelegate* delegate) {
321 delegate_ = delegate;
324 DownloadManagerDelegate* DownloadManagerImpl::GetDelegate() const {
325 return delegate_;
328 void DownloadManagerImpl::Shutdown() {
329 DVLOG(20) << __FUNCTION__ << "()"
330 << " shutdown_needed_ = " << shutdown_needed_;
331 if (!shutdown_needed_)
332 return;
333 shutdown_needed_ = false;
335 FOR_EACH_OBSERVER(Observer, observers_, ManagerGoingDown(this));
336 // TODO(benjhayden): Consider clearing observers_.
338 // If there are in-progress downloads, cancel them. This also goes for
339 // dangerous downloads which will remain in history if they aren't explicitly
340 // accepted or discarded. Canceling will remove the intermediate download
341 // file.
342 for (DownloadMap::iterator it = downloads_.begin(); it != downloads_.end();
343 ++it) {
344 DownloadItemImpl* download = it->second;
345 if (download->GetState() == DownloadItem::IN_PROGRESS)
346 download->Cancel(false);
348 STLDeleteValues(&downloads_);
350 // We'll have nothing more to report to the observers after this point.
351 observers_.Clear();
353 if (delegate_)
354 delegate_->Shutdown();
355 delegate_ = NULL;
358 void DownloadManagerImpl::StartDownload(
359 scoped_ptr<DownloadCreateInfo> info,
360 scoped_ptr<ByteStreamReader> stream,
361 const DownloadUrlParameters::OnStartedCallback& on_started) {
362 DCHECK_CURRENTLY_ON(BrowserThread::UI);
363 DCHECK(info);
364 uint32 download_id = info->download_id;
365 const bool new_download = (download_id == content::DownloadItem::kInvalidId);
366 base::Callback<void(uint32)> got_id(base::Bind(
367 &DownloadManagerImpl::StartDownloadWithId,
368 weak_factory_.GetWeakPtr(),
369 base::Passed(info.Pass()),
370 base::Passed(stream.Pass()),
371 on_started,
372 new_download));
373 if (new_download) {
374 GetNextId(got_id);
375 } else {
376 got_id.Run(download_id);
380 void DownloadManagerImpl::StartDownloadWithId(
381 scoped_ptr<DownloadCreateInfo> info,
382 scoped_ptr<ByteStreamReader> stream,
383 const DownloadUrlParameters::OnStartedCallback& on_started,
384 bool new_download,
385 uint32 id) {
386 DCHECK_CURRENTLY_ON(BrowserThread::UI);
387 DCHECK_NE(content::DownloadItem::kInvalidId, id);
388 DownloadItemImpl* download = NULL;
389 if (new_download) {
390 download = CreateActiveItem(id, *info);
391 } else {
392 DownloadMap::iterator item_iterator = downloads_.find(id);
393 // Trying to resume an interrupted download.
394 if (item_iterator == downloads_.end() ||
395 (item_iterator->second->GetState() == DownloadItem::CANCELLED)) {
396 // If the download is no longer known to the DownloadManager, then it was
397 // removed after it was resumed. Ignore. If the download is cancelled
398 // while resuming, then also ignore the request.
399 info->request_handle.CancelRequest();
400 if (!on_started.is_null())
401 on_started.Run(NULL, DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);
402 return;
404 download = item_iterator->second;
405 DCHECK_EQ(DownloadItem::INTERRUPTED, download->GetState());
406 download->MergeOriginInfoOnResume(*info);
409 base::FilePath default_download_directory;
410 if (delegate_) {
411 base::FilePath website_save_directory; // Unused
412 bool skip_dir_check = false; // Unused
413 delegate_->GetSaveDir(GetBrowserContext(), &website_save_directory,
414 &default_download_directory, &skip_dir_check);
417 // Create the download file and start the download.
418 scoped_ptr<DownloadFile> download_file(
419 file_factory_->CreateFile(
420 info->save_info.Pass(), default_download_directory,
421 info->url(), info->referrer_url,
422 delegate_ && delegate_->GenerateFileHash(),
423 stream.Pass(), download->GetBoundNetLog(),
424 download->DestinationObserverAsWeakPtr()));
426 // Attach the client ID identifying the app to the AV system.
427 if (download_file.get() && delegate_) {
428 download_file->SetClientGuid(
429 delegate_->ApplicationClientIdForFileScanning());
432 scoped_ptr<DownloadRequestHandleInterface> req_handle(
433 new DownloadRequestHandle(info->request_handle));
434 download->Start(download_file.Pass(), req_handle.Pass());
436 // For interrupted downloads, Start() will transition the state to
437 // IN_PROGRESS and consumers will be notified via OnDownloadUpdated().
438 // For new downloads, we notify here, rather than earlier, so that
439 // the download_file is bound to download and all the usual
440 // setters (e.g. Cancel) work.
441 if (new_download)
442 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadCreated(this, download));
444 if (!on_started.is_null())
445 on_started.Run(download, DOWNLOAD_INTERRUPT_REASON_NONE);
448 void DownloadManagerImpl::CheckForHistoryFilesRemoval() {
449 DCHECK_CURRENTLY_ON(BrowserThread::UI);
450 for (DownloadMap::iterator it = downloads_.begin();
451 it != downloads_.end(); ++it) {
452 DownloadItemImpl* item = it->second;
453 CheckForFileRemoval(item);
457 void DownloadManagerImpl::CheckForFileRemoval(DownloadItemImpl* download_item) {
458 DCHECK_CURRENTLY_ON(BrowserThread::UI);
459 if ((download_item->GetState() == DownloadItem::COMPLETE) &&
460 !download_item->GetFileExternallyRemoved() &&
461 delegate_) {
462 delegate_->CheckForFileExistence(
463 download_item,
464 base::Bind(&DownloadManagerImpl::OnFileExistenceChecked,
465 weak_factory_.GetWeakPtr(), download_item->GetId()));
469 void DownloadManagerImpl::OnFileExistenceChecked(uint32 download_id,
470 bool result) {
471 DCHECK_CURRENTLY_ON(BrowserThread::UI);
472 if (!result) { // File does not exist.
473 if (ContainsKey(downloads_, download_id))
474 downloads_[download_id]->OnDownloadedFileRemoved();
478 BrowserContext* DownloadManagerImpl::GetBrowserContext() const {
479 return browser_context_;
482 void DownloadManagerImpl::CreateSavePackageDownloadItem(
483 const base::FilePath& main_file_path,
484 const GURL& page_url,
485 const std::string& mime_type,
486 scoped_ptr<DownloadRequestHandleInterface> request_handle,
487 const DownloadItemImplCreated& item_created) {
488 DCHECK_CURRENTLY_ON(BrowserThread::UI);
489 GetNextId(base::Bind(
490 &DownloadManagerImpl::CreateSavePackageDownloadItemWithId,
491 weak_factory_.GetWeakPtr(),
492 main_file_path,
493 page_url,
494 mime_type,
495 base::Passed(request_handle.Pass()),
496 item_created));
499 void DownloadManagerImpl::CreateSavePackageDownloadItemWithId(
500 const base::FilePath& main_file_path,
501 const GURL& page_url,
502 const std::string& mime_type,
503 scoped_ptr<DownloadRequestHandleInterface> request_handle,
504 const DownloadItemImplCreated& item_created,
505 uint32 id) {
506 DCHECK_CURRENTLY_ON(BrowserThread::UI);
507 DCHECK_NE(content::DownloadItem::kInvalidId, id);
508 DCHECK(!ContainsKey(downloads_, id));
509 net::BoundNetLog bound_net_log =
510 net::BoundNetLog::Make(net_log_, net::NetLog::SOURCE_DOWNLOAD);
511 DownloadItemImpl* download_item = item_factory_->CreateSavePageItem(
512 this,
514 main_file_path,
515 page_url,
516 mime_type,
517 request_handle.Pass(),
518 bound_net_log);
519 downloads_[download_item->GetId()] = download_item;
520 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadCreated(
521 this, download_item));
522 if (!item_created.is_null())
523 item_created.Run(download_item);
526 void DownloadManagerImpl::OnSavePackageSuccessfullyFinished(
527 DownloadItem* download_item) {
528 FOR_EACH_OBSERVER(Observer, observers_,
529 OnSavePackageSuccessfullyFinished(this, download_item));
532 // Resume a download of a specific URL. We send the request to the
533 // ResourceDispatcherHost, and let it send us responses like a regular
534 // download.
535 void DownloadManagerImpl::ResumeInterruptedDownload(
536 scoped_ptr<content::DownloadUrlParameters> params,
537 uint32 id) {
538 RecordDownloadSource(INITIATED_BY_RESUMPTION);
539 BrowserThread::PostTask(
540 BrowserThread::IO,
541 FROM_HERE,
542 base::Bind(&BeginDownload, base::Passed(&params), id));
545 void DownloadManagerImpl::SetDownloadItemFactoryForTesting(
546 scoped_ptr<DownloadItemFactory> item_factory) {
547 item_factory_ = item_factory.Pass();
550 void DownloadManagerImpl::SetDownloadFileFactoryForTesting(
551 scoped_ptr<DownloadFileFactory> file_factory) {
552 file_factory_ = file_factory.Pass();
555 DownloadFileFactory* DownloadManagerImpl::GetDownloadFileFactoryForTesting() {
556 return file_factory_.get();
559 void DownloadManagerImpl::DownloadRemoved(DownloadItemImpl* download) {
560 if (!download)
561 return;
563 uint32 download_id = download->GetId();
564 if (downloads_.erase(download_id) == 0)
565 return;
566 delete download;
569 namespace {
571 bool RemoveDownloadBetween(base::Time remove_begin,
572 base::Time remove_end,
573 const DownloadItemImpl* download_item) {
574 return download_item->GetStartTime() >= remove_begin &&
575 (remove_end.is_null() || download_item->GetStartTime() < remove_end);
578 bool RemoveDownloadByOriginAndTime(const url::Origin& origin,
579 base::Time remove_begin,
580 base::Time remove_end,
581 const DownloadItemImpl* download_item) {
582 return origin.IsSameOriginWith(url::Origin(download_item->GetURL())) &&
583 RemoveDownloadBetween(remove_begin, remove_end, download_item);
586 } // namespace
588 int DownloadManagerImpl::RemoveDownloads(const DownloadRemover& remover) {
589 int count = 0;
590 DownloadMap::const_iterator it = downloads_.begin();
591 while (it != downloads_.end()) {
592 DownloadItemImpl* download = it->second;
594 // Increment done here to protect against invalidation below.
595 ++it;
597 if (download->GetState() != DownloadItem::IN_PROGRESS &&
598 remover.Run(download)) {
599 download->Remove();
600 count++;
603 return count;
606 int DownloadManagerImpl::RemoveDownloadsByOriginAndTime(
607 const url::Origin& origin,
608 base::Time remove_begin,
609 base::Time remove_end) {
610 return RemoveDownloads(base::Bind(&RemoveDownloadByOriginAndTime,
611 base::ConstRef(origin), remove_begin,
612 remove_end));
615 int DownloadManagerImpl::RemoveDownloadsBetween(base::Time remove_begin,
616 base::Time remove_end) {
617 return RemoveDownloads(
618 base::Bind(&RemoveDownloadBetween, remove_begin, remove_end));
621 int DownloadManagerImpl::RemoveDownloads(base::Time remove_begin) {
622 return RemoveDownloadsBetween(remove_begin, base::Time());
625 int DownloadManagerImpl::RemoveAllDownloads() {
626 // The null times make the date range unbounded.
627 int num_deleted = RemoveDownloadsBetween(base::Time(), base::Time());
628 RecordClearAllSize(num_deleted);
629 return num_deleted;
632 void DownloadManagerImpl::DownloadUrl(
633 scoped_ptr<DownloadUrlParameters> params) {
634 if (params->post_id() >= 0) {
635 // Check this here so that the traceback is more useful.
636 DCHECK(params->prefer_cache());
637 DCHECK_EQ("POST", params->method());
639 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
640 &BeginDownload, base::Passed(&params),
641 content::DownloadItem::kInvalidId));
644 void DownloadManagerImpl::AddObserver(Observer* observer) {
645 observers_.AddObserver(observer);
648 void DownloadManagerImpl::RemoveObserver(Observer* observer) {
649 observers_.RemoveObserver(observer);
652 DownloadItem* DownloadManagerImpl::CreateDownloadItem(
653 uint32 id,
654 const base::FilePath& current_path,
655 const base::FilePath& target_path,
656 const std::vector<GURL>& url_chain,
657 const GURL& referrer_url,
658 const std::string& mime_type,
659 const std::string& original_mime_type,
660 const base::Time& start_time,
661 const base::Time& end_time,
662 const std::string& etag,
663 const std::string& last_modified,
664 int64 received_bytes,
665 int64 total_bytes,
666 DownloadItem::DownloadState state,
667 DownloadDangerType danger_type,
668 DownloadInterruptReason interrupt_reason,
669 bool opened) {
670 if (ContainsKey(downloads_, id)) {
671 NOTREACHED();
672 return NULL;
674 DownloadItemImpl* item = item_factory_->CreatePersistedItem(
675 this,
677 current_path,
678 target_path,
679 url_chain,
680 referrer_url,
681 mime_type,
682 original_mime_type,
683 start_time,
684 end_time,
685 etag,
686 last_modified,
687 received_bytes,
688 total_bytes,
689 state,
690 danger_type,
691 interrupt_reason,
692 opened,
693 net::BoundNetLog::Make(net_log_, net::NetLog::SOURCE_DOWNLOAD));
694 downloads_[id] = item;
695 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadCreated(this, item));
696 DVLOG(20) << __FUNCTION__ << "() download = " << item->DebugString(true);
697 return item;
700 int DownloadManagerImpl::InProgressCount() const {
701 int count = 0;
702 for (DownloadMap::const_iterator it = downloads_.begin();
703 it != downloads_.end(); ++it) {
704 if (it->second->GetState() == DownloadItem::IN_PROGRESS)
705 ++count;
707 return count;
710 int DownloadManagerImpl::NonMaliciousInProgressCount() const {
711 int count = 0;
712 for (DownloadMap::const_iterator it = downloads_.begin();
713 it != downloads_.end(); ++it) {
714 if (it->second->GetState() == DownloadItem::IN_PROGRESS &&
715 it->second->GetDangerType() != DOWNLOAD_DANGER_TYPE_DANGEROUS_URL &&
716 it->second->GetDangerType() != DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT &&
717 it->second->GetDangerType() != DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST &&
718 it->second->GetDangerType() !=
719 DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED) {
720 ++count;
723 return count;
726 DownloadItem* DownloadManagerImpl::GetDownload(uint32 download_id) {
727 return ContainsKey(downloads_, download_id) ? downloads_[download_id] : NULL;
730 void DownloadManagerImpl::GetAllDownloads(DownloadVector* downloads) {
731 for (DownloadMap::iterator it = downloads_.begin();
732 it != downloads_.end(); ++it) {
733 downloads->push_back(it->second);
737 void DownloadManagerImpl::OpenDownload(DownloadItemImpl* download) {
738 int num_unopened = 0;
739 for (DownloadMap::iterator it = downloads_.begin();
740 it != downloads_.end(); ++it) {
741 DownloadItemImpl* item = it->second;
742 if ((item->GetState() == DownloadItem::COMPLETE) &&
743 !item->GetOpened())
744 ++num_unopened;
746 RecordOpensOutstanding(num_unopened);
748 if (delegate_)
749 delegate_->OpenDownload(download);
752 void DownloadManagerImpl::ShowDownloadInShell(DownloadItemImpl* download) {
753 if (delegate_)
754 delegate_->ShowDownloadInShell(download);
757 } // namespace content