blob: 3519e121ae040ec20c6b52ad00d7a1782b9108ef [file] [log] [blame]
license.botbf09a502008-08-24 00:55:551// Copyright (c) 2006-2008 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.
initial.commit09911bf2008-07-26 23:55:294
5#include <time.h>
6
[email protected]cdaa8652008-09-13 02:48:597#include "chrome/browser/download/download_manager.h"
initial.commit09911bf2008-07-26 23:55:298
9#include "base/file_util.h"
10#include "base/logging.h"
11#include "base/message_loop.h"
12#include "base/path_service.h"
13#include "base/registry.h"
14#include "base/string_util.h"
15#include "base/task.h"
16#include "base/thread.h"
17#include "base/timer.h"
[email protected]9ccbb372008-10-10 18:50:3218#include "base/rand_util.h"
initial.commit09911bf2008-07-26 23:55:2919#include "base/win_util.h"
20#include "chrome/browser/browser_list.h"
21#include "chrome/browser/browser_process.h"
[email protected]cdaa8652008-09-13 02:48:5922#include "chrome/browser/download/download_file.h"
23#include "chrome/browser/download/download_util.h"
initial.commit09911bf2008-07-26 23:55:2924#include "chrome/browser/profile.h"
25#include "chrome/browser/render_process_host.h"
26#include "chrome/browser/render_view_host.h"
27#include "chrome/browser/resource_dispatcher_host.h"
28#include "chrome/browser/tab_util.h"
29#include "chrome/browser/web_contents.h"
30#include "chrome/common/chrome_paths.h"
31#include "chrome/common/l10n_util.h"
32#include "chrome/common/notification_service.h"
33#include "chrome/common/pref_names.h"
34#include "chrome/common/pref_service.h"
35#include "chrome/common/stl_util-inl.h"
36#include "chrome/common/win_util.h"
[email protected]46072d42008-07-28 14:49:3537#include "googleurl/src/gurl.h"
initial.commit09911bf2008-07-26 23:55:2938#include "net/base/mime_util.h"
39#include "net/base/net_util.h"
40#include "net/url_request/url_request_context.h"
41
42#include "generated_resources.h"
43
44// Periodically update our observers.
45class DownloadItemUpdateTask : public Task {
46 public:
47 explicit DownloadItemUpdateTask(DownloadItem* item) : item_(item) {}
48 void Run() { if (item_) item_->UpdateObservers(); }
49
50 private:
51 DownloadItem* item_;
52};
53
54// Update frequency (milliseconds).
55static const int kUpdateTimeMs = 1000;
56
57// Our download table ID starts at 1, so we use 0 to represent a download that
58// has started, but has not yet had its data persisted in the table. We use fake
59// database handles in incognito mode starting at -1 and progressly getting more
60// negative.
61static const int kUninitializedHandle = 0;
62
63// Attempts to modify |path| to be a non-existing path.
64// Returns true if |path| points to a non-existing path upon return.
65static bool UniquifyPath(std::wstring* path) {
66 DCHECK(path);
67 const int kMaxAttempts = 100;
68
69 if (!file_util::PathExists(*path))
70 return true;
71
72 std::wstring new_path;
73 for (int count = 1; count <= kMaxAttempts; ++count) {
74 new_path.assign(*path);
75 file_util::InsertBeforeExtension(&new_path, StringPrintf(L" (%d)", count));
76
77 if (!file_util::PathExists(new_path)) {
78 path->swap(new_path);
79 return true;
80 }
81 }
82
83 return false;
84}
85
[email protected]f052118e2008-09-05 02:25:3286static bool DownloadPathIsDangerous(const std::wstring& download_path) {
87 std::wstring desktop_dir;
88 if (!PathService::Get(chrome::DIR_USER_DESKTOP, &desktop_dir)) {
89 NOTREACHED();
90 return false;
91 }
92 return (download_path == desktop_dir);
93}
94
initial.commit09911bf2008-07-26 23:55:2995// DownloadItem implementation -------------------------------------------------
96
97// Constructor for reading from the history service.
98DownloadItem::DownloadItem(const DownloadCreateInfo& info)
99 : id_(-1),
100 full_path_(info.path),
[email protected]9ccbb372008-10-10 18:50:32101 original_name_(info.original_name),
initial.commit09911bf2008-07-26 23:55:29102 url_(info.url),
103 total_bytes_(info.total_bytes),
104 received_bytes_(info.received_bytes),
105 start_tick_(0),
106 state_(static_cast<DownloadState>(info.state)),
107 start_time_(info.start_time),
108 db_handle_(info.db_handle),
initial.commit09911bf2008-07-26 23:55:29109 manager_(NULL),
[email protected]9ccbb372008-10-10 18:50:32110 safety_state_(SAFE),
initial.commit09911bf2008-07-26 23:55:29111 is_paused_(false),
112 open_when_complete_(false),
113 render_process_id_(-1),
114 request_id_(-1) {
115 if (state_ == IN_PROGRESS)
116 state_ = CANCELLED;
117 Init(false /* don't start progress timer */);
118}
119
120// Constructor for DownloadItem created via user action in the main thread.
121DownloadItem::DownloadItem(int32 download_id,
122 const std::wstring& path,
123 const std::wstring& url,
[email protected]9ccbb372008-10-10 18:50:32124 const std::wstring& original_name,
initial.commit09911bf2008-07-26 23:55:29125 const Time start_time,
126 int64 download_size,
127 int render_process_id,
[email protected]9ccbb372008-10-10 18:50:32128 int request_id,
129 bool is_dangerous)
initial.commit09911bf2008-07-26 23:55:29130 : id_(download_id),
131 full_path_(path),
132 url_(url),
[email protected]9ccbb372008-10-10 18:50:32133 original_name_(original_name),
initial.commit09911bf2008-07-26 23:55:29134 total_bytes_(download_size),
135 received_bytes_(0),
136 start_tick_(GetTickCount()),
137 state_(IN_PROGRESS),
138 start_time_(start_time),
139 db_handle_(kUninitializedHandle),
initial.commit09911bf2008-07-26 23:55:29140 manager_(NULL),
[email protected]9ccbb372008-10-10 18:50:32141 safety_state_(is_dangerous ? DANGEROUS : SAFE),
initial.commit09911bf2008-07-26 23:55:29142 is_paused_(false),
143 open_when_complete_(false),
144 render_process_id_(render_process_id),
145 request_id_(request_id) {
146 Init(true /* start progress timer */);
147}
148
149void DownloadItem::Init(bool start_timer) {
150 file_name_ = file_util::GetFilenameFromPath(full_path_);
151 if (start_timer)
152 StartProgressTimer();
153}
154
155DownloadItem::~DownloadItem() {
initial.commit09911bf2008-07-26 23:55:29156 state_ = REMOVING;
157 UpdateObservers();
158}
159
160void DownloadItem::AddObserver(Observer* observer) {
161 observers_.AddObserver(observer);
162}
163
164void DownloadItem::RemoveObserver(Observer* observer) {
165 observers_.RemoveObserver(observer);
166}
167
168void DownloadItem::UpdateObservers() {
169 FOR_EACH_OBSERVER(Observer, observers_, OnDownloadUpdated(this));
170}
171
172// If we've received more data than we were expecting (bad server info?), revert
173// to 'unknown size mode'.
174void DownloadItem::UpdateSize(int64 bytes_so_far) {
175 received_bytes_ = bytes_so_far;
176 if (received_bytes_ > total_bytes_)
177 total_bytes_ = 0;
178}
179
180// Updates from the download thread may have been posted while this download
181// was being cancelled in the UI thread, so we'll accept them unless we're
182// complete.
183void DownloadItem::Update(int64 bytes_so_far) {
184 if (state_ == COMPLETE) {
185 NOTREACHED();
186 return;
187 }
188 UpdateSize(bytes_so_far);
189 UpdateObservers();
190}
191
192// Triggered by a user action
193void DownloadItem::Cancel(bool update_history) {
194 if (state_ != IN_PROGRESS) {
195 // Small downloads might be complete before this method has a chance to run.
196 return;
197 }
198 state_ = CANCELLED;
199 UpdateObservers();
200 StopProgressTimer();
201 if (update_history)
202 manager_->DownloadCancelled(id_);
203}
204
205void DownloadItem::Finished(int64 size) {
206 state_ = COMPLETE;
207 UpdateSize(size);
initial.commit09911bf2008-07-26 23:55:29208 StopProgressTimer();
209}
210
[email protected]9ccbb372008-10-10 18:50:32211void DownloadItem::Remove(bool delete_on_disk) {
initial.commit09911bf2008-07-26 23:55:29212 Cancel(true);
213 state_ = REMOVING;
[email protected]9ccbb372008-10-10 18:50:32214 if (delete_on_disk)
215 manager_->DeleteDownload(full_path_);
initial.commit09911bf2008-07-26 23:55:29216 manager_->RemoveDownload(db_handle_);
[email protected]9ccbb372008-10-10 18:50:32217 // We are now deleted.
initial.commit09911bf2008-07-26 23:55:29218}
219
220void DownloadItem::StartProgressTimer() {
[email protected]2d316662008-09-03 18:18:14221 update_timer_.Start(TimeDelta::FromMilliseconds(kUpdateTimeMs), this,
222 &DownloadItem::UpdateObservers);
initial.commit09911bf2008-07-26 23:55:29223}
224
225void DownloadItem::StopProgressTimer() {
[email protected]2d316662008-09-03 18:18:14226 update_timer_.Stop();
initial.commit09911bf2008-07-26 23:55:29227}
228
229bool DownloadItem::TimeRemaining(TimeDelta* remaining) const {
230 if (total_bytes_ <= 0)
231 return false; // We never received the content_length for this download.
232
233 int64 speed = CurrentSpeed();
234 if (speed == 0)
235 return false;
236
237 *remaining =
238 TimeDelta::FromSeconds((total_bytes_ - received_bytes_) / speed);
239 return true;
240}
241
242int64 DownloadItem::CurrentSpeed() const {
243 uintptr_t diff = GetTickCount() - start_tick_;
244 return diff == 0 ? 0 : received_bytes_ * 1000 / diff;
245}
246
247int DownloadItem::PercentComplete() const {
248 int percent = -1;
249 if (total_bytes_ > 0)
250 percent = static_cast<int>(received_bytes_ * 100.0 / total_bytes_);
251 return percent;
252}
253
254void DownloadItem::Rename(const std::wstring& full_path) {
255 DCHECK(!full_path.empty());
256 full_path_ = full_path;
257 file_name_ = file_util::GetFilenameFromPath(full_path_);
258}
259
260void DownloadItem::TogglePause() {
261 DCHECK(state_ == IN_PROGRESS);
262 manager_->PauseDownload(id_, !is_paused_);
263 is_paused_ = !is_paused_;
264 UpdateObservers();
265}
266
[email protected]9ccbb372008-10-10 18:50:32267std::wstring DownloadItem::GetFileName() const {
268 if (safety_state_ == DownloadItem::SAFE)
269 return file_name_;
270 return original_name_;
271}
272
initial.commit09911bf2008-07-26 23:55:29273// DownloadManager implementation ----------------------------------------------
274
275// static
276void DownloadManager::RegisterUserPrefs(PrefService* prefs) {
277 prefs->RegisterBooleanPref(prefs::kPromptForDownload, false);
278 prefs->RegisterStringPref(prefs::kDownloadExtensionsToOpen, L"");
[email protected]f052118e2008-09-05 02:25:32279 prefs->RegisterBooleanPref(prefs::kDownloadDirUpgraded, false);
280
281 // The default download path is userprofile\download.
282 std::wstring default_download_path;
283 if (!PathService::Get(chrome::DIR_USER_DOCUMENTS, &default_download_path)) {
284 NOTREACHED();
285 }
286 file_util::AppendToPath(&default_download_path,
287 l10n_util::GetString(IDS_DOWNLOAD_DIRECTORY));
288 prefs->RegisterStringPref(prefs::kDownloadDefaultDirectory,
289 default_download_path);
290
291 // If the download path is dangerous we forcefully reset it. But if we do
292 // so we set a flag to make sure we only do it once, to avoid fighting
293 // the user if he really wants it on an unsafe place such as the desktop.
294
295 if (!prefs->GetBoolean(prefs::kDownloadDirUpgraded)) {
296 std::wstring current_download_dir =
297 prefs->GetString(prefs::kDownloadDefaultDirectory);
298 if (DownloadPathIsDangerous(current_download_dir)) {
299 prefs->SetString(prefs::kDownloadDefaultDirectory,
300 default_download_path);
301 }
302 prefs->SetBoolean(prefs::kDownloadDirUpgraded, true);
303 }
initial.commit09911bf2008-07-26 23:55:29304}
305
306DownloadManager::DownloadManager()
307 : shutdown_needed_(false),
308 profile_(NULL),
309 file_manager_(NULL),
310 ui_loop_(MessageLoop::current()),
311 file_loop_(NULL) {
312}
313
314DownloadManager::~DownloadManager() {
315 if (shutdown_needed_)
316 Shutdown();
317}
318
319void DownloadManager::Shutdown() {
320 DCHECK(shutdown_needed_) << "Shutdown called when not needed.";
321
322 // Stop receiving download updates
323 file_manager_->RemoveDownloadManager(this);
324
325 // Stop making history service requests
326 cancelable_consumer_.CancelAllRequests();
327
328 // 'in_progress_' may contain DownloadItems that have not finished the start
329 // complete (from the history service) and thus aren't in downloads_.
330 DownloadMap::iterator it = in_progress_.begin();
[email protected]9ccbb372008-10-10 18:50:32331 std::set<DownloadItem*> to_remove;
initial.commit09911bf2008-07-26 23:55:29332 for (; it != in_progress_.end(); ++it) {
333 DownloadItem* download = it->second;
[email protected]9ccbb372008-10-10 18:50:32334 if (download->safety_state() == DownloadItem::DANGEROUS) {
335 // Forget about any download that the user did not approve.
336 // Note that we cannot call download->Remove() this would invalidate our
337 // iterator.
338 to_remove.insert(download);
339 continue;
initial.commit09911bf2008-07-26 23:55:29340 }
[email protected]9ccbb372008-10-10 18:50:32341 DCHECK_EQ(DownloadItem::IN_PROGRESS, download->state());
342 download->Cancel(false);
343 UpdateHistoryForDownload(download);
initial.commit09911bf2008-07-26 23:55:29344 if (download->db_handle() == kUninitializedHandle) {
345 // An invalid handle means that 'download' does not yet exist in
346 // 'downloads_', so we have to delete it here.
347 delete download;
348 }
349 }
350
[email protected]9ccbb372008-10-10 18:50:32351 // 'dangerous_finished_' contains all complete downloads that have not been
352 // approved. They should be removed.
353 it = dangerous_finished_.begin();
354 for (; it != dangerous_finished_.end(); ++it)
355 to_remove.insert(it->second);
356
357 // Remove the dangerous download that are not approved.
358 for (std::set<DownloadItem*>::const_iterator rm_it = to_remove.begin();
359 rm_it != to_remove.end(); ++rm_it) {
360 DownloadItem* download = *rm_it;
[email protected]e10e17c72008-10-15 17:48:32361 int64 handle = download->db_handle();
[email protected]9ccbb372008-10-10 18:50:32362 download->Remove(true);
[email protected]e10e17c72008-10-15 17:48:32363 // Same as above, delete the download if it is not in 'downloads_' (as the
364 // Remove() call above won't have deleted it).
365 if (handle == kUninitializedHandle)
[email protected]9ccbb372008-10-10 18:50:32366 delete download;
367 }
368 to_remove.clear();
369
initial.commit09911bf2008-07-26 23:55:29370 in_progress_.clear();
[email protected]9ccbb372008-10-10 18:50:32371 dangerous_finished_.clear();
initial.commit09911bf2008-07-26 23:55:29372 STLDeleteValues(&downloads_);
373
374 file_manager_ = NULL;
375
376 // Save our file extensions to auto open.
377 SaveAutoOpens();
378
379 // Make sure the save as dialog doesn't notify us back if we're gone before
380 // it returns.
381 if (select_file_dialog_.get())
382 select_file_dialog_->ListenerDestroyed();
383
384 shutdown_needed_ = false;
385}
386
387// Issue a history query for downloads matching 'search_text'. If 'search_text'
388// is empty, return all downloads that we know about.
389void DownloadManager::GetDownloads(Observer* observer,
390 const std::wstring& search_text) {
391 DCHECK(observer);
392
393 // Return a empty list if we've not yet received the set of downloads from the
394 // history system (we'll update all observers once we get that list in
395 // OnQueryDownloadEntriesComplete), or if there are no downloads at all.
396 std::vector<DownloadItem*> download_copy;
397 if (downloads_.empty()) {
398 observer->SetDownloads(download_copy);
399 return;
400 }
401
402 // We already know all the downloads and there is no filter, so just return a
403 // copy to the observer.
404 if (search_text.empty()) {
405 download_copy.reserve(downloads_.size());
406 for (DownloadMap::iterator it = downloads_.begin();
407 it != downloads_.end(); ++it) {
408 download_copy.push_back(it->second);
409 }
410
411 // We retain ownership of the DownloadItems.
412 observer->SetDownloads(download_copy);
413 return;
414 }
415
416 // Issue a request to the history service for a list of downloads matching
417 // our search text.
418 HistoryService* hs =
419 profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
420 if (hs) {
421 HistoryService::Handle h =
422 hs->SearchDownloads(search_text,
423 &cancelable_consumer_,
424 NewCallback(this,
425 &DownloadManager::OnSearchComplete));
426 cancelable_consumer_.SetClientData(hs, h, observer);
427 }
428}
429
430// Query the history service for information about all persisted downloads.
431bool DownloadManager::Init(Profile* profile) {
432 DCHECK(profile);
433 DCHECK(!shutdown_needed_) << "DownloadManager already initialized.";
434 shutdown_needed_ = true;
435
436 profile_ = profile;
437 request_context_ = profile_->GetRequestContext();
438
439 // 'incognito mode' will have access to past downloads, but we won't store
440 // information about new downloads while in that mode.
441 QueryHistoryForDownloads();
442
443 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
444 if (!rdh) {
445 NOTREACHED();
446 return false;
447 }
448
449 file_manager_ = rdh->download_file_manager();
450 if (!file_manager_) {
451 NOTREACHED();
452 return false;
453 }
454
455 file_loop_ = g_browser_process->file_thread()->message_loop();
456 if (!file_loop_) {
457 NOTREACHED();
458 return false;
459 }
460
461 // Get our user preference state.
462 PrefService* prefs = profile_->GetPrefs();
463 DCHECK(prefs);
464 prompt_for_download_.Init(prefs::kPromptForDownload, prefs, NULL);
465
initial.commit09911bf2008-07-26 23:55:29466 download_path_.Init(prefs::kDownloadDefaultDirectory, prefs, NULL);
467
[email protected]bb69e9b32008-08-14 23:08:14468 // Ensure that the download directory specified in the preferences exists.
469 file_loop_->PostTask(FROM_HERE, NewRunnableMethod(
470 file_manager_, &DownloadFileManager::CreateDirectory, *download_path_));
471
initial.commit09911bf2008-07-26 23:55:29472 // We store any file extension that should be opened automatically at
473 // download completion in this pref.
474 download_util::InitializeExeTypes(&exe_types_);
475
476 std::wstring extensions_to_open =
477 prefs->GetString(prefs::kDownloadExtensionsToOpen);
478 std::vector<std::wstring> extensions;
479 SplitString(extensions_to_open, L':', &extensions);
480 for (size_t i = 0; i < extensions.size(); ++i) {
481 if (!extensions[i].empty() && !IsExecutable(extensions[i]))
482 auto_open_.insert(extensions[i]);
483 }
484
485 return true;
486}
487
488void DownloadManager::QueryHistoryForDownloads() {
489 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
490 if (hs) {
491 hs->QueryDownloads(
492 &cancelable_consumer_,
493 NewCallback(this, &DownloadManager::OnQueryDownloadEntriesComplete));
494 }
495}
496
497// We have received a message from DownloadFileManager about a new download. We
498// create a download item and store it in our download map, and inform the
499// history system of a new download. Since this method can be called while the
500// history service thread is still reading the persistent state, we do not
501// insert the new DownloadItem into 'downloads_' or inform our observers at this
502// point. OnCreateDatabaseEntryComplete() handles that finalization of the the
503// download creation as a callback from the history thread.
504void DownloadManager::StartDownload(DownloadCreateInfo* info) {
505 DCHECK(MessageLoop::current() == ui_loop_);
506 DCHECK(info);
507
508 // Determine the proper path for a download, by choosing either the default
509 // download directory, or prompting the user.
510 std::wstring generated_name;
511 GenerateFilename(info, &generated_name);
512 if (*prompt_for_download_ && !last_download_path_.empty())
513 info->suggested_path = last_download_path_;
514 else
515 info->suggested_path = *download_path_;
516 file_util::AppendToPath(&info->suggested_path, generated_name);
517
518 // We need to move over to the download thread because we don't want to stat
519 // the suggested path on the UI thread.
520 file_loop_->PostTask(FROM_HERE,
521 NewRunnableMethod(this,
522 &DownloadManager::CheckIfSuggestedPathExists,
523 info));
524}
525
526void DownloadManager::CheckIfSuggestedPathExists(DownloadCreateInfo* info) {
527 DCHECK(info);
528
529 // Check writability of the suggested path. If we can't write to it, default
530 // to the user's "My Documents" directory. We'll prompt them in this case.
[email protected]9ccbb372008-10-10 18:50:32531 std::wstring dir = file_util::GetDirectoryFromPath(info->suggested_path);
532 const std::wstring filename =
533 file_util::GetFilenameFromPath(info->suggested_path);
534 if (!file_util::PathIsWritable(dir)) {
initial.commit09911bf2008-07-26 23:55:29535 info->save_as = true;
initial.commit09911bf2008-07-26 23:55:29536 PathService::Get(chrome::DIR_USER_DOCUMENTS, &info->suggested_path);
537 file_util::AppendToPath(&info->suggested_path, filename);
538 }
539
540 info->suggested_path_exists = !UniquifyPath(&info->suggested_path);
541
[email protected]9ccbb372008-10-10 18:50:32542 // If the download is deemmed dangerous, we'll use a temporary name for it.
543 if (!info->save_as && IsDangerous(filename)) {
544 info->original_name = file_util::GetFilenameFromPath(info->suggested_path);
545 // Create a temporary file to hold the file until the user approves its
546 // download.
547 std::wstring file_name;
548 std::wstring path;
549 while (path.empty()) {
550 SStringPrintf(&file_name, L"dangerous_download_%d.download",
551 base::RandInt(0, 100000));
552 path = dir;
553 file_util::AppendToPath(&path, file_name);
554 if (file_util::PathExists(path))
555 path.clear();
556 }
557 info->suggested_path = path;
558 info->is_dangerous = true;
559 }
560
initial.commit09911bf2008-07-26 23:55:29561 // Now we return to the UI thread.
562 ui_loop_->PostTask(FROM_HERE,
563 NewRunnableMethod(this,
564 &DownloadManager::OnPathExistenceAvailable,
565 info));
566}
567
568void DownloadManager::OnPathExistenceAvailable(DownloadCreateInfo* info) {
569 DCHECK(MessageLoop::current() == ui_loop_);
570 DCHECK(info);
571
572 if (*prompt_for_download_ || info->save_as || info->suggested_path_exists) {
573 // We must ask the user for the place to put the download.
574 if (!select_file_dialog_.get())
575 select_file_dialog_ = SelectFileDialog::Create(this);
576
577 TabContents* contents = tab_util::GetTabContentsByID(
578 info->render_process_id, info->render_view_id);
579 HWND owning_hwnd =
580 contents ? GetAncestor(contents->GetContainerHWND(), GA_ROOT) : NULL;
581 select_file_dialog_->SelectFile(SelectFileDialog::SELECT_SAVEAS_FILE,
582 std::wstring(), info->suggested_path,
583 owning_hwnd, info);
584 } else {
585 // No prompting for download, just continue with the suggested name.
586 ContinueStartDownload(info, info->suggested_path);
587 }
588}
589
590void DownloadManager::ContinueStartDownload(DownloadCreateInfo* info,
591 const std::wstring& target_path) {
592 scoped_ptr<DownloadCreateInfo> infop(info);
593 info->path = target_path;
594
595 DownloadItem* download = NULL;
596 DownloadMap::iterator it = in_progress_.find(info->download_id);
597 if (it == in_progress_.end()) {
598 download = new DownloadItem(info->download_id,
599 info->path,
600 info->url,
[email protected]9ccbb372008-10-10 18:50:32601 info->original_name,
initial.commit09911bf2008-07-26 23:55:29602 info->start_time,
603 info->total_bytes,
604 info->render_process_id,
[email protected]9ccbb372008-10-10 18:50:32605 info->request_id,
606 info->is_dangerous);
initial.commit09911bf2008-07-26 23:55:29607 download->set_manager(this);
608 in_progress_[info->download_id] = download;
609 } else {
610 NOTREACHED(); // Should not exist!
611 return;
612 }
613
614 // If the download already completed by the time we reached this point, then
615 // notify observers that it did.
616 PendingFinishedMap::iterator pending_it =
617 pending_finished_downloads_.find(info->download_id);
618 if (pending_it != pending_finished_downloads_.end())
619 DownloadFinished(pending_it->first, pending_it->second);
620
621 download->Rename(target_path);
622
623 file_loop_->PostTask(FROM_HERE,
624 NewRunnableMethod(file_manager_,
625 &DownloadFileManager::OnFinalDownloadName,
626 download->id(),
627 target_path));
628
629 if (profile_->IsOffTheRecord()) {
630 // Fake a db handle for incognito mode, since nothing is actually stored in
631 // the database in this mode. We have to make sure that these handles don't
632 // collide with normal db handles, so we use a negative value. Eventually,
633 // they could overlap, but you'd have to do enough downloading that your ISP
634 // would likely stab you in the neck first. YMMV.
635 static int64 fake_db_handle = kUninitializedHandle - 1;
636 OnCreateDownloadEntryComplete(*info, fake_db_handle--);
637 } else {
638 // Update the history system with the new download.
639 // FIXME(acw|paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
640 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
641 if (hs) {
642 hs->CreateDownload(
643 *info, &cancelable_consumer_,
644 NewCallback(this, &DownloadManager::OnCreateDownloadEntryComplete));
645 }
646 }
647}
648
649// Convenience function for updating the history service for a download.
650void DownloadManager::UpdateHistoryForDownload(DownloadItem* download) {
651 DCHECK(download);
652
653 // Don't store info in the database if the download was initiated while in
654 // incognito mode or if it hasn't been initialized in our database table.
655 if (download->db_handle() <= kUninitializedHandle)
656 return;
657
658 // FIXME(acw|paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
659 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
660 if (hs) {
661 hs->UpdateDownload(download->received_bytes(),
662 download->state(),
663 download->db_handle());
664 }
665}
666
667void DownloadManager::RemoveDownloadFromHistory(DownloadItem* download) {
668 DCHECK(download);
669 // FIXME(acw|paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
670 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
671 if (download->db_handle() > kUninitializedHandle && hs)
672 hs->RemoveDownload(download->db_handle());
673}
674
675void DownloadManager::RemoveDownloadsFromHistoryBetween(const Time remove_begin,
676 const Time remove_end) {
677 // FIXME(acw|paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
678 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
679 if (hs)
680 hs->RemoveDownloadsBetween(remove_begin, remove_end);
681}
682
683void DownloadManager::UpdateDownload(int32 download_id, int64 size) {
684 DownloadMap::iterator it = in_progress_.find(download_id);
685 if (it != in_progress_.end()) {
686 DownloadItem* download = it->second;
687 download->Update(size);
688 UpdateHistoryForDownload(download);
689 }
690}
691
692void DownloadManager::DownloadFinished(int32 download_id, int64 size) {
693 DownloadMap::iterator it = in_progress_.find(download_id);
[email protected]9ccbb372008-10-10 18:50:32694 if (it == in_progress_.end()) {
initial.commit09911bf2008-07-26 23:55:29695 // The download is done, but the user hasn't selected a final location for
696 // it yet (the Save As dialog box is probably still showing), so just keep
697 // track of the fact that this download id is complete, when the
698 // DownloadItem is constructed later we'll notify its completion then.
699 PendingFinishedMap::iterator erase_it =
700 pending_finished_downloads_.find(download_id);
701 DCHECK(erase_it == pending_finished_downloads_.end());
702 pending_finished_downloads_[download_id] = size;
[email protected]9ccbb372008-10-10 18:50:32703 return;
initial.commit09911bf2008-07-26 23:55:29704 }
[email protected]9ccbb372008-10-10 18:50:32705
706 // Remove the id from the list of pending ids.
707 PendingFinishedMap::iterator erase_it =
708 pending_finished_downloads_.find(download_id);
709 if (erase_it != pending_finished_downloads_.end())
710 pending_finished_downloads_.erase(erase_it);
711
712 DownloadItem* download = it->second;
713 download->Finished(size);
714
715 // Clean up will happen when the history system create callback runs if we
716 // don't have a valid db_handle yet.
717 if (download->db_handle() != kUninitializedHandle) {
718 in_progress_.erase(it);
719 NotifyAboutDownloadStop();
720 UpdateHistoryForDownload(download);
721 }
722
723 // If this a dangerous download not yet validated by the user, don't do
724 // anything. When the user notifies us, it will trigger a call to
725 // ProceedWithFinishedDangerousDownload.
726 if (download->safety_state() == DownloadItem::DANGEROUS) {
727 dangerous_finished_[download_id] = download;
728 return;
729 }
730
731 if (download->safety_state() == DownloadItem::DANGEROUS_BUT_VALIDATED) {
732 // We first need to rename the donwloaded file from its temporary name to
733 // its final name before we can continue.
734 file_loop_->PostTask(FROM_HERE,
735 NewRunnableMethod(
736 this, &DownloadManager::ProceedWithFinishedDangerousDownload,
737 download->db_handle(),
738 download->full_path(), download->original_name()));
739 return;
740 }
741 ContinueDownloadFinished(download);
742}
743
744void DownloadManager::ContinueDownloadFinished(DownloadItem* download) {
745 // If this was a dangerous download, it has now been approved and must be
746 // removed from dangerous_finished_ so it does not get deleted on shutdown.
747 DownloadMap::iterator it = dangerous_finished_.find(download->id());
748 if (it != dangerous_finished_.end())
749 dangerous_finished_.erase(it);
750
751 // Notify our observers that we are complete (the call to Finished() set the
752 // state to complete but did not notify).
753 download->UpdateObservers();
754
755 // Open the download if the user or user prefs indicate it should be.
756 const std::wstring extension =
757 file_util::GetFileExtensionFromPath(download->full_path());
758 if (download->open_when_complete() || ShouldOpenFileExtension(extension))
759 OpenDownloadInShell(download, NULL);
760}
761
762// Called on the file thread. Renames the downloaded file to its original name.
763void DownloadManager::ProceedWithFinishedDangerousDownload(
764 int64 download_handle,
765 const std::wstring& path,
766 const std::wstring& original_name) {
767 bool success = false;
768 std::wstring new_path = path;
769 if (file_util::PathExists(path)) {
770 new_path = file_util::GetDirectoryFromPath(new_path);
771 file_util::AppendToPath(&new_path, original_name);
772 success = file_util::Move(path, new_path);
773 } else {
774 NOTREACHED();
775 }
776
777 ui_loop_->PostTask(FROM_HERE,
778 NewRunnableMethod(this, &DownloadManager::DangerousDownloadRenamed,
779 download_handle, success, new_path));
780}
781
782// Call from the file thread when the finished dangerous download was renamed.
783void DownloadManager::DangerousDownloadRenamed(int64 download_handle,
784 bool success,
785 const std::wstring& new_path) {
786 DownloadMap::iterator it = downloads_.find(download_handle);
787 if (it == downloads_.end()) {
788 NOTREACHED();
789 return;
790 }
791
792 DownloadItem* download = it->second;
793 // If we failed to rename the file, we'll just keep the name as is.
794 if (success)
795 RenameDownload(download, new_path);
796
797 // Continue the download finished sequence.
798 ContinueDownloadFinished(download);
initial.commit09911bf2008-07-26 23:55:29799}
800
801// static
802// We have to tell the ResourceDispatcherHost to cancel the download from this
803// thread, since we can't forward tasks from the file thread to the io thread
804// reliably (crash on shutdown race condition).
805void DownloadManager::CancelDownloadRequest(int render_process_id,
806 int request_id) {
807 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
[email protected]ab820df2008-08-26 05:55:10808 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29809 if (!io_thread || !rdh)
810 return;
811 io_thread->message_loop()->PostTask(FROM_HERE,
812 NewRunnableFunction(&DownloadManager::OnCancelDownloadRequest,
813 rdh,
814 render_process_id,
815 request_id));
816}
817
818// static
819void DownloadManager::OnCancelDownloadRequest(ResourceDispatcherHost* rdh,
820 int render_process_id,
821 int request_id) {
822 rdh->CancelRequest(render_process_id, request_id, false);
823}
824
825void DownloadManager::DownloadCancelled(int32 download_id) {
826 DownloadMap::iterator it = in_progress_.find(download_id);
827 if (it == in_progress_.end())
828 return;
829 DownloadItem* download = it->second;
830
831 CancelDownloadRequest(download->render_process_id(), download->request_id());
832
833 // Clean up will happen when the history system create callback runs if we
834 // don't have a valid db_handle yet.
835 if (download->db_handle() != kUninitializedHandle) {
836 in_progress_.erase(it);
837 NotifyAboutDownloadStop();
838 UpdateHistoryForDownload(download);
839 }
840
841 // Tell the file manager to cancel the download.
842 file_manager_->RemoveDownload(download->id(), this); // On the UI thread
843 file_loop_->PostTask(FROM_HERE,
844 NewRunnableMethod(file_manager_,
845 &DownloadFileManager::CancelDownload,
846 download->id()));
847}
848
849void DownloadManager::PauseDownload(int32 download_id, bool pause) {
850 DownloadMap::iterator it = in_progress_.find(download_id);
851 if (it != in_progress_.end()) {
852 DownloadItem* download = it->second;
853 if (pause == download->is_paused())
854 return;
855
856 // Inform the ResourceDispatcherHost of the new pause state.
[email protected]ab820df2008-08-26 05:55:10857 base::Thread* io_thread = g_browser_process->io_thread();
initial.commit09911bf2008-07-26 23:55:29858 ResourceDispatcherHost* rdh = g_browser_process->resource_dispatcher_host();
859 if (!io_thread || !rdh)
860 return;
861
862 io_thread->message_loop()->PostTask(FROM_HERE,
863 NewRunnableFunction(&DownloadManager::OnPauseDownloadRequest,
864 rdh,
865 download->render_process_id(),
866 download->request_id(),
867 pause));
868 }
869}
870
871// static
872void DownloadManager::OnPauseDownloadRequest(ResourceDispatcherHost* rdh,
873 int render_process_id,
874 int request_id,
875 bool pause) {
876 rdh->PauseRequest(render_process_id, request_id, pause);
877}
878
[email protected]9ccbb372008-10-10 18:50:32879bool DownloadManager::IsDangerous(const std::wstring& file_name) {
880 // TODO(jcampan): Improve me.
881 return IsExecutable(file_util::GetFileExtensionFromPath(file_name));
882}
883
884void DownloadManager::RenameDownload(DownloadItem* download,
885 const std::wstring& new_path) {
886 download->Rename(new_path);
887
888 // Update the history.
889
890 // No update necessary if the download was initiated while in incognito mode.
891 if (download->db_handle() <= kUninitializedHandle)
892 return;
893
894 // FIXME(acw|paulg) see bug 958058. EXPLICIT_ACCESS below is wrong.
895 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
896 if (hs)
897 hs->UpdateDownloadPath(new_path, download->db_handle());
898}
899
initial.commit09911bf2008-07-26 23:55:29900void DownloadManager::RemoveDownload(int64 download_handle) {
901 DownloadMap::iterator it = downloads_.find(download_handle);
902 if (it == downloads_.end())
903 return;
904
905 // Make history update.
906 DownloadItem* download = it->second;
907 RemoveDownloadFromHistory(download);
908
909 // Remove from our tables and delete.
910 downloads_.erase(it);
[email protected]9ccbb372008-10-10 18:50:32911 it = dangerous_finished_.find(download->id());
912 if (it != dangerous_finished_.end())
913 dangerous_finished_.erase(it);
initial.commit09911bf2008-07-26 23:55:29914 delete download;
915
916 // Tell observers to refresh their views.
917 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
918}
919
920int DownloadManager::RemoveDownloadsBetween(const Time remove_begin,
921 const Time remove_end) {
922 RemoveDownloadsFromHistoryBetween(remove_begin, remove_end);
923
924 int num_deleted = 0;
925 DownloadMap::iterator it = downloads_.begin();
926 while (it != downloads_.end()) {
927 DownloadItem* download = it->second;
928 DownloadItem::DownloadState state = download->state();
929 if (download->start_time() >= remove_begin &&
930 (remove_end.is_null() || download->start_time() < remove_end) &&
931 (state == DownloadItem::COMPLETE ||
932 state == DownloadItem::CANCELLED)) {
933 // Remove from the map and move to the next in the list.
934 it = downloads_.erase(it);
935 delete download;
936
937 ++num_deleted;
938 continue;
939 }
940
941 ++it;
942 }
943
944 // Tell observers to refresh their views.
945 if (num_deleted > 0)
946 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
947
948 return num_deleted;
949}
950
951int DownloadManager::RemoveDownloads(const Time remove_begin) {
952 return RemoveDownloadsBetween(remove_begin, Time());
953}
954
955// Initiate a download of a specific URL. We send the request to the
956// ResourceDispatcherHost, and let it send us responses like a regular
957// download.
958void DownloadManager::DownloadUrl(const GURL& url,
959 const GURL& referrer,
960 WebContents* web_contents) {
961 DCHECK(web_contents);
962 file_manager_->DownloadUrl(url,
963 referrer,
964 web_contents->process()->host_id(),
965 web_contents->render_view_host()->routing_id(),
966 request_context_.get());
967}
968
969void DownloadManager::NotifyAboutDownloadStart() {
970 NotificationService::current()->
971 Notify(NOTIFY_DOWNLOAD_START, NotificationService::AllSources(),
972 NotificationService::NoDetails());
973}
974
975void DownloadManager::NotifyAboutDownloadStop() {
976 NotificationService::current()->
977 Notify(NOTIFY_DOWNLOAD_STOP, NotificationService::AllSources(),
978 NotificationService::NoDetails());
979}
980
981void DownloadManager::GenerateExtension(const std::wstring& file_name,
982 const std::string& mime_type,
983 std::wstring* generated_extension) {
984 // We're worried about three things here:
985 //
986 // 1) Security. Many sites let users upload content, such as buddy icons, to
987 // their web sites. We want to mitigate the case where an attacker
988 // supplies a malicious executable with an executable file extension but an
989 // honest site serves the content with a benign content type, such as
990 // image/jpeg.
991 //
992 // 2) Usability. If the site fails to provide a file extension, we want to
993 // guess a reasonable file extension based on the content type.
994 //
995 // 3) Shell integration. Some file extensions automatically integrate with
996 // the shell. We block these extensions to prevent a malicious web site
997 // from integrating with the user's shell.
998
999 static const wchar_t default_extension[] = L"download";
1000
1001 // See if our file name already contains an extension.
1002 std::wstring extension(file_util::GetFileExtensionFromPath(file_name));
1003
1004 // Rename shell-integrated extensions.
1005 if (win_util::IsShellIntegratedExtension(extension))
1006 extension.assign(default_extension);
1007
1008 std::string mime_type_from_extension;
[email protected]a9bb6f692008-07-30 16:40:101009 net::GetMimeTypeFromFile(file_name, &mime_type_from_extension);
initial.commit09911bf2008-07-26 23:55:291010 if (mime_type == mime_type_from_extension) {
1011 // The hinted extension matches the mime type. It looks like a winner.
1012 generated_extension->swap(extension);
1013 return;
1014 }
1015
1016 if (IsExecutable(extension) && !IsExecutableMimeType(mime_type)) {
1017 // We want to be careful about executable extensions. The worry here is
1018 // that a trusted web site could be tricked into dropping an executable file
1019 // on the user's filesystem.
[email protected]a9bb6f692008-07-30 16:40:101020 if (!net::GetPreferredExtensionForMimeType(mime_type, &extension)) {
initial.commit09911bf2008-07-26 23:55:291021 // We couldn't find a good extension for this content type. Use a dummy
1022 // extension instead.
1023 extension.assign(default_extension);
1024 }
1025 }
1026
1027 if (extension.empty()) {
[email protected]a9bb6f692008-07-30 16:40:101028 net::GetPreferredExtensionForMimeType(mime_type, &extension);
initial.commit09911bf2008-07-26 23:55:291029 } else {
1030 // Append entension generated from the mime type if:
1031 // 1. New extension is not ".txt"
1032 // 2. New extension is not the same as the already existing extension.
1033 // 3. New extension is not executable. This action mitigates the case when
1034 // an execuatable is hidden in a benign file extension;
1035 // E.g. my-cat.jpg becomes my-cat.jpg.js if content type is
1036 // application/x-javascript.
1037 std::wstring append_extension;
[email protected]a9bb6f692008-07-30 16:40:101038 if (net::GetPreferredExtensionForMimeType(mime_type, &append_extension)) {
initial.commit09911bf2008-07-26 23:55:291039 if (append_extension != L".txt" && append_extension != extension &&
1040 !IsExecutable(append_extension))
1041 extension += append_extension;
1042 }
1043 }
1044
1045 generated_extension->swap(extension);
1046}
1047
1048void DownloadManager::GenerateFilename(DownloadCreateInfo* info,
1049 std::wstring* generated_name) {
1050 std::wstring file_name =
[email protected]8ac1a752008-07-31 19:40:371051 net::GetSuggestedFilename(GURL(info->url),
1052 info->content_disposition,
1053 L"download");
initial.commit09911bf2008-07-26 23:55:291054 DCHECK(!file_name.empty());
1055
1056 // Make sure we get the right file extension.
1057 std::wstring extension;
1058 GenerateExtension(file_name, info->mime_type, &extension);
1059 file_util::ReplaceExtension(&file_name, extension);
1060
1061 // Prepend "_" to the file name if it's a reserved name
1062 if (win_util::IsReservedName(file_name))
1063 file_name = std::wstring(L"_") + file_name;
1064
1065 generated_name->assign(file_name);
1066}
1067
1068void DownloadManager::AddObserver(Observer* observer) {
1069 observers_.AddObserver(observer);
1070 observer->ModelChanged();
1071}
1072
1073void DownloadManager::RemoveObserver(Observer* observer) {
1074 observers_.RemoveObserver(observer);
1075}
1076
1077// Post Windows Shell operations to the Download thread, to avoid blocking the
1078// user interface.
1079void DownloadManager::ShowDownloadInShell(const DownloadItem* download) {
1080 DCHECK(file_manager_);
1081 file_loop_->PostTask(FROM_HERE,
1082 NewRunnableMethod(file_manager_,
1083 &DownloadFileManager::OnShowDownloadInShell,
1084 download->full_path()));
1085}
1086
1087void DownloadManager::OpenDownloadInShell(const DownloadItem* download,
1088 HWND parent_window) {
1089 DCHECK(file_manager_);
1090 file_loop_->PostTask(FROM_HERE,
1091 NewRunnableMethod(file_manager_,
1092 &DownloadFileManager::OnOpenDownloadInShell,
1093 download->full_path(), download->url(), parent_window));
1094}
1095
1096void DownloadManager::OpenFilesOfExtension(const std::wstring& extension,
1097 bool open) {
1098 if (open && !IsExecutable(extension))
1099 auto_open_.insert(extension);
1100 else
1101 auto_open_.erase(extension);
1102 SaveAutoOpens();
1103}
1104
1105bool DownloadManager::ShouldOpenFileExtension(const std::wstring& extension) {
1106 if (!IsExecutable(extension) &&
1107 auto_open_.find(extension) != auto_open_.end())
1108 return true;
1109 return false;
1110}
1111
1112// static
1113bool DownloadManager::IsExecutableMimeType(const std::string& mime_type) {
1114 // JavaScript is just as powerful as EXE.
[email protected]a9bb6f692008-07-30 16:40:101115 if (net::MatchesMimeType("text/javascript", mime_type))
initial.commit09911bf2008-07-26 23:55:291116 return true;
[email protected]a9bb6f692008-07-30 16:40:101117 if (net::MatchesMimeType("text/javascript;version=*", mime_type))
initial.commit09911bf2008-07-26 23:55:291118 return true;
1119
1120 // We don't consider other non-application types to be executable.
[email protected]a9bb6f692008-07-30 16:40:101121 if (!net::MatchesMimeType("application/*", mime_type))
initial.commit09911bf2008-07-26 23:55:291122 return false;
1123
1124 // These application types are not executable.
[email protected]a9bb6f692008-07-30 16:40:101125 if (net::MatchesMimeType("application/*+xml", mime_type))
initial.commit09911bf2008-07-26 23:55:291126 return false;
[email protected]a9bb6f692008-07-30 16:40:101127 if (net::MatchesMimeType("application/xml", mime_type))
initial.commit09911bf2008-07-26 23:55:291128 return false;
1129
1130 return true;
1131}
1132
1133bool DownloadManager::IsExecutable(const std::wstring& extension) {
1134 return exe_types_.find(extension) != exe_types_.end();
1135}
1136
1137void DownloadManager::ResetAutoOpenFiles() {
1138 auto_open_.clear();
1139 SaveAutoOpens();
1140}
1141
1142bool DownloadManager::HasAutoOpenFileTypesRegistered() const {
1143 return !auto_open_.empty();
1144}
1145
1146void DownloadManager::SaveAutoOpens() {
1147 PrefService* prefs = profile_->GetPrefs();
1148 if (prefs) {
1149 std::wstring extensions;
1150 for (std::set<std::wstring>::iterator it = auto_open_.begin();
1151 it != auto_open_.end(); ++it) {
1152 extensions += *it + L":";
1153 }
1154 if (!extensions.empty())
1155 extensions.erase(extensions.size() - 1);
1156 prefs->SetString(prefs::kDownloadExtensionsToOpen, extensions);
1157 }
1158}
1159
1160void DownloadManager::FileSelected(const std::wstring& path, void* params) {
1161 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1162 if (*prompt_for_download_)
1163 last_download_path_ = file_util::GetDirectoryFromPath(path);
1164 ContinueStartDownload(info, path);
1165}
1166
1167void DownloadManager::FileSelectionCanceled(void* params) {
1168 // The user didn't pick a place to save the file, so need to cancel the
1169 // download that's already in progress to the temporary location.
1170 DownloadCreateInfo* info = reinterpret_cast<DownloadCreateInfo*>(params);
1171 file_loop_->PostTask(FROM_HERE,
1172 NewRunnableMethod(file_manager_, &DownloadFileManager::CancelDownload,
1173 info->download_id));
1174}
1175
[email protected]9ccbb372008-10-10 18:50:321176void DownloadManager::DeleteDownload(const std::wstring& path) {
1177 file_loop_->PostTask(FROM_HERE, NewRunnableMethod(
1178 file_manager_, &DownloadFileManager::DeleteFile, path));
1179}
1180
1181
1182void DownloadManager::DangerousDownloadValidated(DownloadItem* download) {
1183 DCHECK_EQ(DownloadItem::DANGEROUS, download->safety_state());
1184 download->set_safety_state(DownloadItem::DANGEROUS_BUT_VALIDATED);
1185 download->UpdateObservers();
1186
1187 // If the download is not complete, nothing to do. The required
1188 // post-processing will be performed when it does complete.
1189 if (download->state() != DownloadItem::COMPLETE)
1190 return;
1191
1192 file_loop_->PostTask(FROM_HERE,
1193 NewRunnableMethod(this,
1194 &DownloadManager::ProceedWithFinishedDangerousDownload,
1195 download->db_handle(), download->full_path(),
1196 download->original_name()));
1197}
1198
initial.commit09911bf2008-07-26 23:55:291199// Operations posted to us from the history service ----------------------------
1200
1201// The history service has retrieved all download entries. 'entries' contains
1202// 'DownloadCreateInfo's in sorted order (by ascending start_time).
1203void DownloadManager::OnQueryDownloadEntriesComplete(
1204 std::vector<DownloadCreateInfo>* entries) {
1205 for (size_t i = 0; i < entries->size(); ++i) {
1206 DownloadItem* download = new DownloadItem(entries->at(i));
1207 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1208 downloads_[download->db_handle()] = download;
1209 download->set_manager(this);
1210 }
1211 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1212}
1213
1214
1215// Once the new DownloadItem's creation info has been committed to the history
1216// service, we associate the DownloadItem with the db handle, update our
1217// 'downloads_' map and inform observers.
1218void DownloadManager::OnCreateDownloadEntryComplete(DownloadCreateInfo info,
1219 int64 db_handle) {
1220 DownloadMap::iterator it = in_progress_.find(info.download_id);
1221 DCHECK(it != in_progress_.end());
1222
1223 DownloadItem* download = it->second;
1224 DCHECK(download->db_handle() == kUninitializedHandle);
1225 download->set_db_handle(db_handle);
1226
1227 // Insert into our full map.
1228 DCHECK(downloads_.find(download->db_handle()) == downloads_.end());
1229 downloads_[download->db_handle()] = download;
1230
1231 // The 'contents' may no longer exist if the user closed the tab before we get
1232 // this start completion event. If it does, tell the origin WebContents to
1233 // display its download shelf.
1234 TabContents* contents =
1235 tab_util::GetTabContentsByID(info.render_process_id, info.render_view_id);
1236
1237 // If the contents no longer exists or is no longer active, we start the
1238 // download in the last active browser. This is not ideal but better than
1239 // fully hiding the download from the user. Note: non active means that the
1240 // user navigated away from the tab contents. This has nothing to do with
1241 // tab selection.
1242 if (!contents || !contents->is_active()) {
1243 Browser* last_active = BrowserList::GetLastActive();
1244 if (last_active)
1245 contents = last_active->GetSelectedTabContents();
1246 }
1247
1248 if (contents)
1249 contents->OnStartDownload(download);
1250
1251 // Inform interested objects about the new download.
1252 FOR_EACH_OBSERVER(Observer, observers_, ModelChanged());
1253 NotifyAboutDownloadStart();
1254
1255 // If this download has been completed before we've received the db handle,
1256 // post one final message to the history service so that it can be properly
1257 // in sync with the DownloadItem's completion status, and also inform any
1258 // observers so that they get more than just the start notification.
1259 if (download->state() != DownloadItem::IN_PROGRESS) {
1260 in_progress_.erase(it);
1261 NotifyAboutDownloadStop();
1262 UpdateHistoryForDownload(download);
1263 download->UpdateObservers();
1264 }
1265}
1266
1267// Called when the history service has retrieved the list of downloads that
1268// match the search text.
1269void DownloadManager::OnSearchComplete(HistoryService::Handle handle,
1270 std::vector<int64>* results) {
1271 HistoryService* hs = profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
1272 Observer* requestor = cancelable_consumer_.GetClientData(hs, handle);
1273 if (!requestor)
1274 return;
1275
1276 std::vector<DownloadItem*> searched_downloads;
1277 for (std::vector<int64>::iterator it = results->begin();
1278 it != results->end(); ++it) {
1279 DownloadMap::iterator dit = downloads_.find(*it);
1280 if (dit != downloads_.end())
1281 searched_downloads.push_back(dit->second);
1282 }
1283
1284 requestor->SetDownloads(searched_downloads);
1285}
license.botbf09a502008-08-24 00:55:551286