1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/toolkit/components/downloads/nsDownloadManager.cpp Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,3748 @@ 1.4 +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 1.5 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.6 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.7 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.8 + 1.9 +#include "mozilla/DebugOnly.h" 1.10 + 1.11 +#include "mozIStorageService.h" 1.12 +#include "nsIAlertsService.h" 1.13 +#include "nsIArray.h" 1.14 +#include "nsIClassInfoImpl.h" 1.15 +#include "nsIDOMWindow.h" 1.16 +#include "nsIDownloadHistory.h" 1.17 +#include "nsIDownloadManagerUI.h" 1.18 +#include "nsIMIMEService.h" 1.19 +#include "nsIParentalControlsService.h" 1.20 +#include "nsIPrefService.h" 1.21 +#include "nsIPromptService.h" 1.22 +#include "nsIResumableChannel.h" 1.23 +#include "nsIWebBrowserPersist.h" 1.24 +#include "nsIWindowMediator.h" 1.25 +#include "nsILocalFileWin.h" 1.26 +#include "nsILoadContext.h" 1.27 +#include "nsIXULAppInfo.h" 1.28 + 1.29 +#include "nsAppDirectoryServiceDefs.h" 1.30 +#include "nsArrayEnumerator.h" 1.31 +#include "nsCExternalHandlerService.h" 1.32 +#include "nsDirectoryServiceDefs.h" 1.33 +#include "nsDownloadManager.h" 1.34 +#include "nsNetUtil.h" 1.35 +#include "nsThreadUtils.h" 1.36 + 1.37 +#include "mozStorageCID.h" 1.38 +#include "nsDocShellCID.h" 1.39 +#include "nsEmbedCID.h" 1.40 +#include "nsToolkitCompsCID.h" 1.41 + 1.42 +#include "SQLFunctions.h" 1.43 + 1.44 +#include "mozilla/Preferences.h" 1.45 + 1.46 +#ifdef XP_WIN 1.47 +#include <shlobj.h> 1.48 +#include "nsWindowsHelpers.h" 1.49 +#ifdef DOWNLOAD_SCANNER 1.50 +#include "nsDownloadScanner.h" 1.51 +#endif 1.52 +#endif 1.53 + 1.54 +#ifdef XP_MACOSX 1.55 +#include <CoreFoundation/CoreFoundation.h> 1.56 +#endif 1.57 + 1.58 +#ifdef MOZ_WIDGET_ANDROID 1.59 +#include "AndroidBridge.h" 1.60 +using namespace mozilla::widget::android; 1.61 +#endif 1.62 + 1.63 +#ifdef MOZ_WIDGET_GTK 1.64 +#include <gtk/gtk.h> 1.65 +#endif 1.66 + 1.67 +using namespace mozilla; 1.68 +using mozilla::downloads::GenerateGUID; 1.69 + 1.70 +#define DOWNLOAD_MANAGER_BUNDLE "chrome://mozapps/locale/downloads/downloads.properties" 1.71 +#define DOWNLOAD_MANAGER_ALERT_ICON "chrome://mozapps/skin/downloads/downloadIcon.png" 1.72 +#define PREF_BD_USEJSTRANSFER "browser.download.useJSTransfer" 1.73 +#define PREF_BDM_SHOWALERTONCOMPLETE "browser.download.manager.showAlertOnComplete" 1.74 +#define PREF_BDM_SHOWALERTINTERVAL "browser.download.manager.showAlertInterval" 1.75 +#define PREF_BDM_RETENTION "browser.download.manager.retention" 1.76 +#define PREF_BDM_QUITBEHAVIOR "browser.download.manager.quitBehavior" 1.77 +#define PREF_BDM_ADDTORECENTDOCS "browser.download.manager.addToRecentDocs" 1.78 +#define PREF_BDM_SCANWHENDONE "browser.download.manager.scanWhenDone" 1.79 +#define PREF_BDM_RESUMEONWAKEDELAY "browser.download.manager.resumeOnWakeDelay" 1.80 +#define PREF_BH_DELETETEMPFILEONEXIT "browser.helperApps.deleteTempFileOnExit" 1.81 + 1.82 +static const int64_t gUpdateInterval = 400 * PR_USEC_PER_MSEC; 1.83 + 1.84 +#define DM_SCHEMA_VERSION 9 1.85 +#define DM_DB_NAME NS_LITERAL_STRING("downloads.sqlite") 1.86 +#define DM_DB_CORRUPT_FILENAME NS_LITERAL_STRING("downloads.sqlite.corrupt") 1.87 + 1.88 +#define NS_SYSTEMINFO_CONTRACTID "@mozilla.org/system-info;1" 1.89 + 1.90 +//////////////////////////////////////////////////////////////////////////////// 1.91 +//// nsDownloadManager 1.92 + 1.93 +NS_IMPL_ISUPPORTS( 1.94 + nsDownloadManager 1.95 +, nsIDownloadManager 1.96 +, nsINavHistoryObserver 1.97 +, nsIObserver 1.98 +, nsISupportsWeakReference 1.99 +) 1.100 + 1.101 +nsDownloadManager *nsDownloadManager::gDownloadManagerService = nullptr; 1.102 + 1.103 +nsDownloadManager * 1.104 +nsDownloadManager::GetSingleton() 1.105 +{ 1.106 + if (gDownloadManagerService) { 1.107 + NS_ADDREF(gDownloadManagerService); 1.108 + return gDownloadManagerService; 1.109 + } 1.110 + 1.111 + gDownloadManagerService = new nsDownloadManager(); 1.112 + if (gDownloadManagerService) { 1.113 +#if defined(MOZ_WIDGET_GTK) 1.114 + g_type_init(); 1.115 +#endif 1.116 + NS_ADDREF(gDownloadManagerService); 1.117 + if (NS_FAILED(gDownloadManagerService->Init())) 1.118 + NS_RELEASE(gDownloadManagerService); 1.119 + } 1.120 + 1.121 + return gDownloadManagerService; 1.122 +} 1.123 + 1.124 +nsDownloadManager::~nsDownloadManager() 1.125 +{ 1.126 +#ifdef DOWNLOAD_SCANNER 1.127 + if (mScanner) { 1.128 + delete mScanner; 1.129 + mScanner = nullptr; 1.130 + } 1.131 +#endif 1.132 + gDownloadManagerService = nullptr; 1.133 +} 1.134 + 1.135 +nsresult 1.136 +nsDownloadManager::ResumeRetry(nsDownload *aDl) 1.137 +{ 1.138 + // Keep a reference in case we need to cancel the download 1.139 + nsRefPtr<nsDownload> dl = aDl; 1.140 + 1.141 + // Try to resume the active download 1.142 + nsresult rv = dl->Resume(); 1.143 + 1.144 + // If not, try to retry the download 1.145 + if (NS_FAILED(rv)) { 1.146 + // First cancel the download so it's no longer active 1.147 + rv = dl->Cancel(); 1.148 + 1.149 + // Then retry it 1.150 + if (NS_SUCCEEDED(rv)) 1.151 + rv = dl->Retry(); 1.152 + } 1.153 + 1.154 + return rv; 1.155 +} 1.156 + 1.157 +nsresult 1.158 +nsDownloadManager::PauseAllDownloads(bool aSetResume) 1.159 +{ 1.160 + nsresult rv = PauseAllDownloads(mCurrentDownloads, aSetResume); 1.161 + nsresult rv2 = PauseAllDownloads(mCurrentPrivateDownloads, aSetResume); 1.162 + NS_ENSURE_SUCCESS(rv, rv); 1.163 + NS_ENSURE_SUCCESS(rv2, rv2); 1.164 + return NS_OK; 1.165 +} 1.166 + 1.167 +nsresult 1.168 +nsDownloadManager::PauseAllDownloads(nsCOMArray<nsDownload>& aDownloads, bool aSetResume) 1.169 +{ 1.170 + nsresult retVal = NS_OK; 1.171 + for (int32_t i = aDownloads.Count() - 1; i >= 0; --i) { 1.172 + nsRefPtr<nsDownload> dl = aDownloads[i]; 1.173 + 1.174 + // Only pause things that need to be paused 1.175 + if (!dl->IsPaused()) { 1.176 + // Set auto-resume before pausing so that it gets into the DB 1.177 + dl->mAutoResume = aSetResume ? nsDownload::AUTO_RESUME : 1.178 + nsDownload::DONT_RESUME; 1.179 + 1.180 + // Try to pause the download but don't bail now if we fail 1.181 + nsresult rv = dl->Pause(); 1.182 + if (NS_FAILED(rv)) 1.183 + retVal = rv; 1.184 + } 1.185 + } 1.186 + 1.187 + return retVal; 1.188 +} 1.189 + 1.190 +nsresult 1.191 +nsDownloadManager::ResumeAllDownloads(bool aResumeAll) 1.192 +{ 1.193 + nsresult rv = ResumeAllDownloads(mCurrentDownloads, aResumeAll); 1.194 + nsresult rv2 = ResumeAllDownloads(mCurrentPrivateDownloads, aResumeAll); 1.195 + NS_ENSURE_SUCCESS(rv, rv); 1.196 + NS_ENSURE_SUCCESS(rv2, rv2); 1.197 + return NS_OK; 1.198 +} 1.199 + 1.200 +nsresult 1.201 +nsDownloadManager::ResumeAllDownloads(nsCOMArray<nsDownload>& aDownloads, bool aResumeAll) 1.202 +{ 1.203 + nsresult retVal = NS_OK; 1.204 + for (int32_t i = aDownloads.Count() - 1; i >= 0; --i) { 1.205 + nsRefPtr<nsDownload> dl = aDownloads[i]; 1.206 + 1.207 + // If aResumeAll is true, then resume everything; otherwise, check if the 1.208 + // download should auto-resume 1.209 + if (aResumeAll || dl->ShouldAutoResume()) { 1.210 + // Reset auto-resume before retrying so that it gets into the DB through 1.211 + // ResumeRetry's eventual call to SetState. We clear the value now so we 1.212 + // don't accidentally query completed downloads that were previously 1.213 + // auto-resumed (and try to resume them). 1.214 + dl->mAutoResume = nsDownload::DONT_RESUME; 1.215 + 1.216 + // Try to resume/retry the download but don't bail now if we fail 1.217 + nsresult rv = ResumeRetry(dl); 1.218 + if (NS_FAILED(rv)) 1.219 + retVal = rv; 1.220 + } 1.221 + } 1.222 + 1.223 + return retVal; 1.224 +} 1.225 + 1.226 +nsresult 1.227 +nsDownloadManager::RemoveAllDownloads() 1.228 +{ 1.229 + nsresult rv = RemoveAllDownloads(mCurrentDownloads); 1.230 + nsresult rv2 = RemoveAllDownloads(mCurrentPrivateDownloads); 1.231 + NS_ENSURE_SUCCESS(rv, rv); 1.232 + NS_ENSURE_SUCCESS(rv2, rv2); 1.233 + return NS_OK; 1.234 +} 1.235 + 1.236 +nsresult 1.237 +nsDownloadManager::RemoveAllDownloads(nsCOMArray<nsDownload>& aDownloads) 1.238 +{ 1.239 + nsresult rv = NS_OK; 1.240 + for (int32_t i = aDownloads.Count() - 1; i >= 0; --i) { 1.241 + nsRefPtr<nsDownload> dl = aDownloads[0]; 1.242 + 1.243 + nsresult result = NS_OK; 1.244 + if (!dl->mPrivate && dl->IsPaused() && GetQuitBehavior() != QUIT_AND_CANCEL) 1.245 + aDownloads.RemoveObject(dl); 1.246 + else 1.247 + result = dl->Cancel(); 1.248 + 1.249 + // Track the failure, but don't miss out on other downloads 1.250 + if (NS_FAILED(result)) 1.251 + rv = result; 1.252 + } 1.253 + 1.254 + return rv; 1.255 +} 1.256 + 1.257 +nsresult 1.258 +nsDownloadManager::RemoveDownloadsForURI(mozIStorageStatement* aStatement, nsIURI *aURI) 1.259 +{ 1.260 + mozStorageStatementScoper scope(aStatement); 1.261 + 1.262 + nsAutoCString source; 1.263 + nsresult rv = aURI->GetSpec(source); 1.264 + NS_ENSURE_SUCCESS(rv, rv); 1.265 + 1.266 + rv = aStatement->BindUTF8StringByName( 1.267 + NS_LITERAL_CSTRING("source"), source); 1.268 + NS_ENSURE_SUCCESS(rv, rv); 1.269 + 1.270 + bool hasMore = false; 1.271 + nsAutoTArray<nsCString, 4> downloads; 1.272 + // Get all the downloads that match the provided URI 1.273 + while (NS_SUCCEEDED(aStatement->ExecuteStep(&hasMore)) && 1.274 + hasMore) { 1.275 + nsAutoCString downloadGuid; 1.276 + rv = aStatement->GetUTF8String(0, downloadGuid); 1.277 + NS_ENSURE_SUCCESS(rv, rv); 1.278 + 1.279 + downloads.AppendElement(downloadGuid); 1.280 + } 1.281 + 1.282 + // Remove each download ignoring any failure so we reach other downloads 1.283 + for (int32_t i = downloads.Length(); --i >= 0; ) 1.284 + (void)RemoveDownload(downloads[i]); 1.285 + 1.286 + return NS_OK; 1.287 +} 1.288 + 1.289 +void // static 1.290 +nsDownloadManager::ResumeOnWakeCallback(nsITimer *aTimer, void *aClosure) 1.291 +{ 1.292 + // Resume the downloads that were set to autoResume 1.293 + nsDownloadManager *dlMgr = static_cast<nsDownloadManager *>(aClosure); 1.294 + (void)dlMgr->ResumeAllDownloads(false); 1.295 +} 1.296 + 1.297 +already_AddRefed<mozIStorageConnection> 1.298 +nsDownloadManager::GetFileDBConnection(nsIFile *dbFile) const 1.299 +{ 1.300 + NS_ASSERTION(dbFile, "GetFileDBConnection called with an invalid nsIFile"); 1.301 + 1.302 + nsCOMPtr<mozIStorageService> storage = 1.303 + do_GetService(MOZ_STORAGE_SERVICE_CONTRACTID); 1.304 + NS_ENSURE_TRUE(storage, nullptr); 1.305 + 1.306 + nsCOMPtr<mozIStorageConnection> conn; 1.307 + nsresult rv = storage->OpenDatabase(dbFile, getter_AddRefs(conn)); 1.308 + if (rv == NS_ERROR_FILE_CORRUPTED) { 1.309 + // delete and try again, since we don't care so much about losing a user's 1.310 + // download history 1.311 + rv = dbFile->Remove(false); 1.312 + NS_ENSURE_SUCCESS(rv, nullptr); 1.313 + rv = storage->OpenDatabase(dbFile, getter_AddRefs(conn)); 1.314 + } 1.315 + NS_ENSURE_SUCCESS(rv, nullptr); 1.316 + 1.317 + return conn.forget(); 1.318 +} 1.319 + 1.320 +already_AddRefed<mozIStorageConnection> 1.321 +nsDownloadManager::GetPrivateDBConnection() const 1.322 +{ 1.323 + nsCOMPtr<mozIStorageService> storage = 1.324 + do_GetService(MOZ_STORAGE_SERVICE_CONTRACTID); 1.325 + NS_ENSURE_TRUE(storage, nullptr); 1.326 + 1.327 + nsCOMPtr<mozIStorageConnection> conn; 1.328 + nsresult rv = storage->OpenSpecialDatabase("memory", getter_AddRefs(conn)); 1.329 + NS_ENSURE_SUCCESS(rv, nullptr); 1.330 + 1.331 + return conn.forget(); 1.332 +} 1.333 + 1.334 +void 1.335 +nsDownloadManager::CloseAllDBs() 1.336 +{ 1.337 + CloseDB(mDBConn, mUpdateDownloadStatement, mGetIdsForURIStatement); 1.338 + CloseDB(mPrivateDBConn, mUpdatePrivateDownloadStatement, mGetPrivateIdsForURIStatement); 1.339 +} 1.340 + 1.341 +void 1.342 +nsDownloadManager::CloseDB(mozIStorageConnection* aDBConn, 1.343 + mozIStorageStatement* aUpdateStmt, 1.344 + mozIStorageStatement* aGetIdsStmt) 1.345 +{ 1.346 + DebugOnly<nsresult> rv = aGetIdsStmt->Finalize(); 1.347 + MOZ_ASSERT(NS_SUCCEEDED(rv)); 1.348 + rv = aUpdateStmt->Finalize(); 1.349 + MOZ_ASSERT(NS_SUCCEEDED(rv)); 1.350 + rv = aDBConn->AsyncClose(nullptr); 1.351 + MOZ_ASSERT(NS_SUCCEEDED(rv)); 1.352 +} 1.353 + 1.354 +static nsresult 1.355 +InitSQLFunctions(mozIStorageConnection* aDBConn) 1.356 +{ 1.357 + nsresult rv = mozilla::downloads::GenerateGUIDFunction::create(aDBConn); 1.358 + NS_ENSURE_SUCCESS(rv, rv); 1.359 + return NS_OK; 1.360 +} 1.361 + 1.362 +nsresult 1.363 +nsDownloadManager::InitPrivateDB() 1.364 +{ 1.365 + bool ready = false; 1.366 + if (mPrivateDBConn && NS_SUCCEEDED(mPrivateDBConn->GetConnectionReady(&ready)) && ready) 1.367 + CloseDB(mPrivateDBConn, mUpdatePrivateDownloadStatement, mGetPrivateIdsForURIStatement); 1.368 + mPrivateDBConn = GetPrivateDBConnection(); 1.369 + if (!mPrivateDBConn) 1.370 + return NS_ERROR_NOT_AVAILABLE; 1.371 + 1.372 + nsresult rv = InitSQLFunctions(mPrivateDBConn); 1.373 + NS_ENSURE_SUCCESS(rv, rv); 1.374 + 1.375 + rv = CreateTable(mPrivateDBConn); 1.376 + NS_ENSURE_SUCCESS(rv, rv); 1.377 + 1.378 + rv = InitStatements(mPrivateDBConn, getter_AddRefs(mUpdatePrivateDownloadStatement), 1.379 + getter_AddRefs(mGetPrivateIdsForURIStatement)); 1.380 + NS_ENSURE_SUCCESS(rv, rv); 1.381 + return NS_OK; 1.382 +} 1.383 + 1.384 +nsresult 1.385 +nsDownloadManager::InitFileDB() 1.386 +{ 1.387 + nsresult rv; 1.388 + 1.389 + nsCOMPtr<nsIFile> dbFile; 1.390 + rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, 1.391 + getter_AddRefs(dbFile)); 1.392 + NS_ENSURE_SUCCESS(rv, rv); 1.393 + rv = dbFile->Append(DM_DB_NAME); 1.394 + NS_ENSURE_SUCCESS(rv, rv); 1.395 + 1.396 + bool ready = false; 1.397 + if (mDBConn && NS_SUCCEEDED(mDBConn->GetConnectionReady(&ready)) && ready) 1.398 + CloseDB(mDBConn, mUpdateDownloadStatement, mGetIdsForURIStatement); 1.399 + mDBConn = GetFileDBConnection(dbFile); 1.400 + NS_ENSURE_TRUE(mDBConn, NS_ERROR_NOT_AVAILABLE); 1.401 + 1.402 + rv = InitSQLFunctions(mDBConn); 1.403 + NS_ENSURE_SUCCESS(rv, rv); 1.404 + 1.405 + bool tableExists; 1.406 + rv = mDBConn->TableExists(NS_LITERAL_CSTRING("moz_downloads"), &tableExists); 1.407 + NS_ENSURE_SUCCESS(rv, rv); 1.408 + 1.409 + if (!tableExists) { 1.410 + rv = CreateTable(mDBConn); 1.411 + NS_ENSURE_SUCCESS(rv, rv); 1.412 + 1.413 + // We're done with the initialization now and can skip the remaining 1.414 + // upgrading logic. 1.415 + return NS_OK; 1.416 + } 1.417 + 1.418 + // Checking the database schema now 1.419 + int32_t schemaVersion; 1.420 + rv = mDBConn->GetSchemaVersion(&schemaVersion); 1.421 + NS_ENSURE_SUCCESS(rv, rv); 1.422 + 1.423 + // Changing the database? Be sure to do these two things! 1.424 + // 1) Increment DM_SCHEMA_VERSION 1.425 + // 2) Implement the proper downgrade/upgrade code for the current version 1.426 + 1.427 + switch (schemaVersion) { 1.428 + // Upgrading 1.429 + // Every time you increment the database schema, you need to implement 1.430 + // the upgrading code from the previous version to the new one. 1.431 + // Also, don't forget to make a unit test to test your upgrading code! 1.432 + case 1: // Drop a column (iconURL) from the database (bug 385875) 1.433 + { 1.434 + // Safely wrap this in a transaction so we don't hose the whole DB 1.435 + mozStorageTransaction safeTransaction(mDBConn, true); 1.436 + 1.437 + // Create a temporary table that will store the existing records 1.438 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.439 + "CREATE TEMPORARY TABLE moz_downloads_backup (" 1.440 + "id INTEGER PRIMARY KEY, " 1.441 + "name TEXT, " 1.442 + "source TEXT, " 1.443 + "target TEXT, " 1.444 + "startTime INTEGER, " 1.445 + "endTime INTEGER, " 1.446 + "state INTEGER" 1.447 + ")")); 1.448 + NS_ENSURE_SUCCESS(rv, rv); 1.449 + 1.450 + // Insert into a temporary table 1.451 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.452 + "INSERT INTO moz_downloads_backup " 1.453 + "SELECT id, name, source, target, startTime, endTime, state " 1.454 + "FROM moz_downloads")); 1.455 + NS_ENSURE_SUCCESS(rv, rv); 1.456 + 1.457 + // Drop the old table 1.458 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.459 + "DROP TABLE moz_downloads")); 1.460 + NS_ENSURE_SUCCESS(rv, rv); 1.461 + 1.462 + // Now recreate it with this schema version 1.463 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.464 + "CREATE TABLE moz_downloads (" 1.465 + "id INTEGER PRIMARY KEY, " 1.466 + "name TEXT, " 1.467 + "source TEXT, " 1.468 + "target TEXT, " 1.469 + "startTime INTEGER, " 1.470 + "endTime INTEGER, " 1.471 + "state INTEGER" 1.472 + ")")); 1.473 + NS_ENSURE_SUCCESS(rv, rv); 1.474 + 1.475 + // Insert the data back into it 1.476 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.477 + "INSERT INTO moz_downloads " 1.478 + "SELECT id, name, source, target, startTime, endTime, state " 1.479 + "FROM moz_downloads_backup")); 1.480 + NS_ENSURE_SUCCESS(rv, rv); 1.481 + 1.482 + // And drop our temporary table 1.483 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.484 + "DROP TABLE moz_downloads_backup")); 1.485 + NS_ENSURE_SUCCESS(rv, rv); 1.486 + 1.487 + // Finally, update the schemaVersion variable and the database schema 1.488 + schemaVersion = 2; 1.489 + rv = mDBConn->SetSchemaVersion(schemaVersion); 1.490 + NS_ENSURE_SUCCESS(rv, rv); 1.491 + } 1.492 + // Fallthrough to the next upgrade 1.493 + 1.494 + case 2: // Add referrer column to the database 1.495 + { 1.496 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.497 + "ALTER TABLE moz_downloads " 1.498 + "ADD COLUMN referrer TEXT")); 1.499 + NS_ENSURE_SUCCESS(rv, rv); 1.500 + 1.501 + // Finally, update the schemaVersion variable and the database schema 1.502 + schemaVersion = 3; 1.503 + rv = mDBConn->SetSchemaVersion(schemaVersion); 1.504 + NS_ENSURE_SUCCESS(rv, rv); 1.505 + } 1.506 + // Fallthrough to the next upgrade 1.507 + 1.508 + case 3: // This version adds a column to the database (entityID) 1.509 + { 1.510 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.511 + "ALTER TABLE moz_downloads " 1.512 + "ADD COLUMN entityID TEXT")); 1.513 + NS_ENSURE_SUCCESS(rv, rv); 1.514 + 1.515 + // Finally, update the schemaVersion variable and the database schema 1.516 + schemaVersion = 4; 1.517 + rv = mDBConn->SetSchemaVersion(schemaVersion); 1.518 + NS_ENSURE_SUCCESS(rv, rv); 1.519 + } 1.520 + // Fallthrough to the next upgrade 1.521 + 1.522 + case 4: // This version adds a column to the database (tempPath) 1.523 + { 1.524 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.525 + "ALTER TABLE moz_downloads " 1.526 + "ADD COLUMN tempPath TEXT")); 1.527 + NS_ENSURE_SUCCESS(rv, rv); 1.528 + 1.529 + // Finally, update the schemaVersion variable and the database schema 1.530 + schemaVersion = 5; 1.531 + rv = mDBConn->SetSchemaVersion(schemaVersion); 1.532 + NS_ENSURE_SUCCESS(rv, rv); 1.533 + } 1.534 + // Fallthrough to the next upgrade 1.535 + 1.536 + case 5: // This version adds two columns for tracking transfer progress 1.537 + { 1.538 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.539 + "ALTER TABLE moz_downloads " 1.540 + "ADD COLUMN currBytes INTEGER NOT NULL DEFAULT 0")); 1.541 + NS_ENSURE_SUCCESS(rv, rv); 1.542 + 1.543 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.544 + "ALTER TABLE moz_downloads " 1.545 + "ADD COLUMN maxBytes INTEGER NOT NULL DEFAULT -1")); 1.546 + NS_ENSURE_SUCCESS(rv, rv); 1.547 + 1.548 + // Finally, update the schemaVersion variable and the database schema 1.549 + schemaVersion = 6; 1.550 + rv = mDBConn->SetSchemaVersion(schemaVersion); 1.551 + NS_ENSURE_SUCCESS(rv, rv); 1.552 + } 1.553 + // Fallthrough to the next upgrade 1.554 + 1.555 + case 6: // This version adds three columns to DB (MIME type related info) 1.556 + { 1.557 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.558 + "ALTER TABLE moz_downloads " 1.559 + "ADD COLUMN mimeType TEXT")); 1.560 + NS_ENSURE_SUCCESS(rv, rv); 1.561 + 1.562 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.563 + "ALTER TABLE moz_downloads " 1.564 + "ADD COLUMN preferredApplication TEXT")); 1.565 + NS_ENSURE_SUCCESS(rv, rv); 1.566 + 1.567 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.568 + "ALTER TABLE moz_downloads " 1.569 + "ADD COLUMN preferredAction INTEGER NOT NULL DEFAULT 0")); 1.570 + NS_ENSURE_SUCCESS(rv, rv); 1.571 + 1.572 + // Finally, update the schemaVersion variable and the database schema 1.573 + schemaVersion = 7; 1.574 + rv = mDBConn->SetSchemaVersion(schemaVersion); 1.575 + NS_ENSURE_SUCCESS(rv, rv); 1.576 + } 1.577 + // Fallthrough to next upgrade 1.578 + 1.579 + case 7: // This version adds a column to remember to auto-resume downloads 1.580 + { 1.581 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.582 + "ALTER TABLE moz_downloads " 1.583 + "ADD COLUMN autoResume INTEGER NOT NULL DEFAULT 0")); 1.584 + NS_ENSURE_SUCCESS(rv, rv); 1.585 + 1.586 + // Finally, update the schemaVersion variable and the database schema 1.587 + schemaVersion = 8; 1.588 + rv = mDBConn->SetSchemaVersion(schemaVersion); 1.589 + NS_ENSURE_SUCCESS(rv, rv); 1.590 + } 1.591 + // Fallthrough to the next upgrade 1.592 + 1.593 + // Warning: schema versions >=8 must take into account that they can 1.594 + // be operating on schemas from unknown, future versions that have 1.595 + // been downgraded. Operations such as adding columns may fail, 1.596 + // since the column may already exist. 1.597 + 1.598 + case 8: // This version adds a column for GUIDs 1.599 + { 1.600 + bool exists; 1.601 + rv = mDBConn->IndexExists(NS_LITERAL_CSTRING("moz_downloads_guid_uniqueindex"), 1.602 + &exists); 1.603 + NS_ENSURE_SUCCESS(rv, rv); 1.604 + if (!exists) { 1.605 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.606 + "ALTER TABLE moz_downloads ADD COLUMN guid TEXT")); 1.607 + NS_ENSURE_SUCCESS(rv, rv); 1.608 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.609 + "CREATE UNIQUE INDEX moz_downloads_guid_uniqueindex ON moz_downloads (guid)")); 1.610 + NS_ENSURE_SUCCESS(rv, rv); 1.611 + } 1.612 + 1.613 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.614 + "UPDATE moz_downloads SET guid = GENERATE_GUID() WHERE guid ISNULL")); 1.615 + NS_ENSURE_SUCCESS(rv, rv); 1.616 + 1.617 + // Finally, update the database schema 1.618 + schemaVersion = 9; 1.619 + rv = mDBConn->SetSchemaVersion(schemaVersion); 1.620 + NS_ENSURE_SUCCESS(rv, rv); 1.621 + } 1.622 + // Fallthrough to the next upgrade 1.623 + 1.624 + // Extra sanity checking for developers 1.625 +#ifndef DEBUG 1.626 + case DM_SCHEMA_VERSION: 1.627 +#endif 1.628 + break; 1.629 + 1.630 + case 0: 1.631 + { 1.632 + NS_WARNING("Could not get download database's schema version!"); 1.633 + 1.634 + // The table may still be usable - someone may have just messed with the 1.635 + // schema version, so let's just treat this like a downgrade and verify 1.636 + // that the needed columns are there. If they aren't there, we'll drop 1.637 + // the table anyway. 1.638 + rv = mDBConn->SetSchemaVersion(DM_SCHEMA_VERSION); 1.639 + NS_ENSURE_SUCCESS(rv, rv); 1.640 + } 1.641 + // Fallthrough to downgrade check 1.642 + 1.643 + // Downgrading 1.644 + // If columns have been added to the table, we can still use the ones we 1.645 + // understand safely. If columns have been deleted or alterd, we just 1.646 + // drop the table and start from scratch. If you change how a column 1.647 + // should be interpreted, make sure you also change its name so this 1.648 + // check will catch it. 1.649 + default: 1.650 + { 1.651 + nsCOMPtr<mozIStorageStatement> stmt; 1.652 + rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.653 + "SELECT id, name, source, target, tempPath, startTime, endTime, state, " 1.654 + "referrer, entityID, currBytes, maxBytes, mimeType, " 1.655 + "preferredApplication, preferredAction, autoResume, guid " 1.656 + "FROM moz_downloads"), getter_AddRefs(stmt)); 1.657 + if (NS_SUCCEEDED(rv)) { 1.658 + // We have a database that contains all of the elements that make up 1.659 + // the latest known schema. Reset the version to force an upgrade 1.660 + // path if this downgraded database is used in a later version. 1.661 + mDBConn->SetSchemaVersion(DM_SCHEMA_VERSION); 1.662 + break; 1.663 + } 1.664 + 1.665 + // if the statement fails, that means all the columns were not there. 1.666 + // First we backup the database 1.667 + nsCOMPtr<mozIStorageService> storage = 1.668 + do_GetService(MOZ_STORAGE_SERVICE_CONTRACTID); 1.669 + NS_ENSURE_TRUE(storage, NS_ERROR_NOT_AVAILABLE); 1.670 + nsCOMPtr<nsIFile> backup; 1.671 + rv = storage->BackupDatabaseFile(dbFile, DM_DB_CORRUPT_FILENAME, nullptr, 1.672 + getter_AddRefs(backup)); 1.673 + NS_ENSURE_SUCCESS(rv, rv); 1.674 + 1.675 + // Then we dump it 1.676 + rv = mDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.677 + "DROP TABLE moz_downloads")); 1.678 + NS_ENSURE_SUCCESS(rv, rv); 1.679 + 1.680 + rv = CreateTable(mDBConn); 1.681 + NS_ENSURE_SUCCESS(rv, rv); 1.682 + } 1.683 + break; 1.684 + } 1.685 + 1.686 + return NS_OK; 1.687 +} 1.688 + 1.689 +nsresult 1.690 +nsDownloadManager::CreateTable(mozIStorageConnection* aDBConn) 1.691 +{ 1.692 + nsresult rv = aDBConn->SetSchemaVersion(DM_SCHEMA_VERSION); 1.693 + if (NS_FAILED(rv)) return rv; 1.694 + 1.695 + rv = aDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.696 + "CREATE TABLE moz_downloads (" 1.697 + "id INTEGER PRIMARY KEY, " 1.698 + "name TEXT, " 1.699 + "source TEXT, " 1.700 + "target TEXT, " 1.701 + "tempPath TEXT, " 1.702 + "startTime INTEGER, " 1.703 + "endTime INTEGER, " 1.704 + "state INTEGER, " 1.705 + "referrer TEXT, " 1.706 + "entityID TEXT, " 1.707 + "currBytes INTEGER NOT NULL DEFAULT 0, " 1.708 + "maxBytes INTEGER NOT NULL DEFAULT -1, " 1.709 + "mimeType TEXT, " 1.710 + "preferredApplication TEXT, " 1.711 + "preferredAction INTEGER NOT NULL DEFAULT 0, " 1.712 + "autoResume INTEGER NOT NULL DEFAULT 0, " 1.713 + "guid TEXT" 1.714 + ")")); 1.715 + if (NS_FAILED(rv)) return rv; 1.716 + 1.717 + rv = aDBConn->ExecuteSimpleSQL(NS_LITERAL_CSTRING( 1.718 + "CREATE UNIQUE INDEX moz_downloads_guid_uniqueindex " 1.719 + "ON moz_downloads(guid)")); 1.720 + return rv; 1.721 +} 1.722 + 1.723 +nsresult 1.724 +nsDownloadManager::RestoreDatabaseState() 1.725 +{ 1.726 + // Restore downloads that were in a scanning state. We can assume that they 1.727 + // have been dealt with by the virus scanner 1.728 + nsCOMPtr<mozIStorageStatement> stmt; 1.729 + nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.730 + "UPDATE moz_downloads " 1.731 + "SET state = :state " 1.732 + "WHERE state = :state_cond"), getter_AddRefs(stmt)); 1.733 + NS_ENSURE_SUCCESS(rv, rv); 1.734 + 1.735 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("state"), nsIDownloadManager::DOWNLOAD_FINISHED); 1.736 + NS_ENSURE_SUCCESS(rv, rv); 1.737 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("state_cond"), nsIDownloadManager::DOWNLOAD_SCANNING); 1.738 + NS_ENSURE_SUCCESS(rv, rv); 1.739 + 1.740 + rv = stmt->Execute(); 1.741 + NS_ENSURE_SUCCESS(rv, rv); 1.742 + 1.743 + // Convert supposedly-active downloads into downloads that should auto-resume 1.744 + rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.745 + "UPDATE moz_downloads " 1.746 + "SET autoResume = :autoResume " 1.747 + "WHERE state = :notStarted " 1.748 + "OR state = :queued " 1.749 + "OR state = :downloading"), getter_AddRefs(stmt)); 1.750 + NS_ENSURE_SUCCESS(rv, rv); 1.751 + 1.752 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("autoResume"), nsDownload::AUTO_RESUME); 1.753 + NS_ENSURE_SUCCESS(rv, rv); 1.754 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("notStarted"), nsIDownloadManager::DOWNLOAD_NOTSTARTED); 1.755 + NS_ENSURE_SUCCESS(rv, rv); 1.756 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("queued"), nsIDownloadManager::DOWNLOAD_QUEUED); 1.757 + NS_ENSURE_SUCCESS(rv, rv); 1.758 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("downloading"), nsIDownloadManager::DOWNLOAD_DOWNLOADING); 1.759 + NS_ENSURE_SUCCESS(rv, rv); 1.760 + 1.761 + rv = stmt->Execute(); 1.762 + NS_ENSURE_SUCCESS(rv, rv); 1.763 + 1.764 + // Switch any download that is supposed to automatically resume and is in a 1.765 + // finished state to *not* automatically resume. See Bug 409179 for details. 1.766 + rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.767 + "UPDATE moz_downloads " 1.768 + "SET autoResume = :autoResume " 1.769 + "WHERE state = :state " 1.770 + "AND autoResume = :autoResume_cond"), 1.771 + getter_AddRefs(stmt)); 1.772 + NS_ENSURE_SUCCESS(rv, rv); 1.773 + 1.774 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("autoResume"), nsDownload::DONT_RESUME); 1.775 + NS_ENSURE_SUCCESS(rv, rv); 1.776 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("state"), nsIDownloadManager::DOWNLOAD_FINISHED); 1.777 + NS_ENSURE_SUCCESS(rv, rv); 1.778 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("autoResume_cond"), nsDownload::AUTO_RESUME); 1.779 + NS_ENSURE_SUCCESS(rv, rv); 1.780 + 1.781 + rv = stmt->Execute(); 1.782 + NS_ENSURE_SUCCESS(rv, rv); 1.783 + 1.784 + return NS_OK; 1.785 +} 1.786 + 1.787 +nsresult 1.788 +nsDownloadManager::RestoreActiveDownloads() 1.789 +{ 1.790 + nsCOMPtr<mozIStorageStatement> stmt; 1.791 + nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.792 + "SELECT id " 1.793 + "FROM moz_downloads " 1.794 + "WHERE (state = :state AND LENGTH(entityID) > 0) " 1.795 + "OR autoResume != :autoResume"), getter_AddRefs(stmt)); 1.796 + NS_ENSURE_SUCCESS(rv, rv); 1.797 + 1.798 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("state"), nsIDownloadManager::DOWNLOAD_PAUSED); 1.799 + NS_ENSURE_SUCCESS(rv, rv); 1.800 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("autoResume"), nsDownload::DONT_RESUME); 1.801 + NS_ENSURE_SUCCESS(rv, rv); 1.802 + 1.803 + nsresult retVal = NS_OK; 1.804 + bool hasResults; 1.805 + while (NS_SUCCEEDED(stmt->ExecuteStep(&hasResults)) && hasResults) { 1.806 + nsRefPtr<nsDownload> dl; 1.807 + // Keep trying to add even if we fail one, but make sure to return failure. 1.808 + // Additionally, be careful to not call anything that tries to change the 1.809 + // database because we're iterating over a live statement. 1.810 + if (NS_FAILED(GetDownloadFromDB(stmt->AsInt32(0), getter_AddRefs(dl))) || 1.811 + NS_FAILED(AddToCurrentDownloads(dl))) 1.812 + retVal = NS_ERROR_FAILURE; 1.813 + } 1.814 + 1.815 + // Try to resume only the downloads that should auto-resume 1.816 + rv = ResumeAllDownloads(false); 1.817 + NS_ENSURE_SUCCESS(rv, rv); 1.818 + 1.819 + return retVal; 1.820 +} 1.821 + 1.822 +int64_t 1.823 +nsDownloadManager::AddDownloadToDB(const nsAString &aName, 1.824 + const nsACString &aSource, 1.825 + const nsACString &aTarget, 1.826 + const nsAString &aTempPath, 1.827 + int64_t aStartTime, 1.828 + int64_t aEndTime, 1.829 + const nsACString &aMimeType, 1.830 + const nsACString &aPreferredApp, 1.831 + nsHandlerInfoAction aPreferredAction, 1.832 + bool aPrivate, 1.833 + nsACString& aNewGUID) 1.834 +{ 1.835 + mozIStorageConnection* dbConn = aPrivate ? mPrivateDBConn : mDBConn; 1.836 + nsCOMPtr<mozIStorageStatement> stmt; 1.837 + nsresult rv = dbConn->CreateStatement(NS_LITERAL_CSTRING( 1.838 + "INSERT INTO moz_downloads " 1.839 + "(name, source, target, tempPath, startTime, endTime, state, " 1.840 + "mimeType, preferredApplication, preferredAction, guid) VALUES " 1.841 + "(:name, :source, :target, :tempPath, :startTime, :endTime, :state, " 1.842 + ":mimeType, :preferredApplication, :preferredAction, :guid)"), 1.843 + getter_AddRefs(stmt)); 1.844 + NS_ENSURE_SUCCESS(rv, 0); 1.845 + 1.846 + rv = stmt->BindStringByName(NS_LITERAL_CSTRING("name"), aName); 1.847 + NS_ENSURE_SUCCESS(rv, 0); 1.848 + 1.849 + rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("source"), aSource); 1.850 + NS_ENSURE_SUCCESS(rv, 0); 1.851 + 1.852 + rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("target"), aTarget); 1.853 + NS_ENSURE_SUCCESS(rv, 0); 1.854 + 1.855 + rv = stmt->BindStringByName(NS_LITERAL_CSTRING("tempPath"), aTempPath); 1.856 + NS_ENSURE_SUCCESS(rv, 0); 1.857 + 1.858 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("startTime"), aStartTime); 1.859 + NS_ENSURE_SUCCESS(rv, 0); 1.860 + 1.861 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("endTime"), aEndTime); 1.862 + NS_ENSURE_SUCCESS(rv, 0); 1.863 + 1.864 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("state"), nsIDownloadManager::DOWNLOAD_NOTSTARTED); 1.865 + NS_ENSURE_SUCCESS(rv, 0); 1.866 + 1.867 + rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("mimeType"), aMimeType); 1.868 + NS_ENSURE_SUCCESS(rv, 0); 1.869 + 1.870 + rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("preferredApplication"), aPreferredApp); 1.871 + NS_ENSURE_SUCCESS(rv, 0); 1.872 + 1.873 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("preferredAction"), aPreferredAction); 1.874 + NS_ENSURE_SUCCESS(rv, 0); 1.875 + 1.876 + nsAutoCString guid; 1.877 + rv = GenerateGUID(guid); 1.878 + NS_ENSURE_SUCCESS(rv, 0); 1.879 + rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), guid); 1.880 + NS_ENSURE_SUCCESS(rv, 0); 1.881 + 1.882 + bool hasMore; 1.883 + rv = stmt->ExecuteStep(&hasMore); // we want to keep our lock 1.884 + NS_ENSURE_SUCCESS(rv, 0); 1.885 + 1.886 + int64_t id = 0; 1.887 + rv = dbConn->GetLastInsertRowID(&id); 1.888 + NS_ENSURE_SUCCESS(rv, 0); 1.889 + 1.890 + aNewGUID = guid; 1.891 + 1.892 + // lock on DB from statement will be released once we return 1.893 + return id; 1.894 +} 1.895 + 1.896 +nsresult 1.897 +nsDownloadManager::InitDB() 1.898 +{ 1.899 + nsresult rv = InitPrivateDB(); 1.900 + NS_ENSURE_SUCCESS(rv, rv); 1.901 + 1.902 + rv = InitFileDB(); 1.903 + NS_ENSURE_SUCCESS(rv, rv); 1.904 + 1.905 + rv = InitStatements(mDBConn, getter_AddRefs(mUpdateDownloadStatement), 1.906 + getter_AddRefs(mGetIdsForURIStatement)); 1.907 + NS_ENSURE_SUCCESS(rv, rv); 1.908 + return NS_OK; 1.909 +} 1.910 + 1.911 +nsresult 1.912 +nsDownloadManager::InitStatements(mozIStorageConnection* aDBConn, 1.913 + mozIStorageStatement** aUpdateStatement, 1.914 + mozIStorageStatement** aGetIdsStatement) 1.915 +{ 1.916 + nsresult rv = aDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.917 + "UPDATE moz_downloads " 1.918 + "SET tempPath = :tempPath, startTime = :startTime, endTime = :endTime, " 1.919 + "state = :state, referrer = :referrer, entityID = :entityID, " 1.920 + "currBytes = :currBytes, maxBytes = :maxBytes, autoResume = :autoResume " 1.921 + "WHERE id = :id"), aUpdateStatement); 1.922 + NS_ENSURE_SUCCESS(rv, rv); 1.923 + 1.924 + rv = aDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.925 + "SELECT guid " 1.926 + "FROM moz_downloads " 1.927 + "WHERE source = :source"), aGetIdsStatement); 1.928 + NS_ENSURE_SUCCESS(rv, rv); 1.929 + 1.930 + return NS_OK; 1.931 +} 1.932 + 1.933 +nsresult 1.934 +nsDownloadManager::Init() 1.935 +{ 1.936 + nsresult rv; 1.937 + 1.938 + nsCOMPtr<nsIStringBundleService> bundleService = 1.939 + mozilla::services::GetStringBundleService(); 1.940 + if (!bundleService) 1.941 + return NS_ERROR_FAILURE; 1.942 + 1.943 + rv = bundleService->CreateBundle(DOWNLOAD_MANAGER_BUNDLE, 1.944 + getter_AddRefs(mBundle)); 1.945 + NS_ENSURE_SUCCESS(rv, rv); 1.946 + 1.947 +#if !defined(MOZ_JSDOWNLOADS) 1.948 + // When MOZ_JSDOWNLOADS is undefined, we still check the preference that can 1.949 + // be used to enable the JavaScript API during the migration process. 1.950 + mUseJSTransfer = Preferences::GetBool(PREF_BD_USEJSTRANSFER, false); 1.951 +#else 1.952 + 1.953 + nsAutoCString appID; 1.954 + nsCOMPtr<nsIXULAppInfo> info = do_GetService("@mozilla.org/xre/app-info;1"); 1.955 + if (info) { 1.956 + rv = info->GetID(appID); 1.957 + NS_ENSURE_SUCCESS(rv, rv); 1.958 + } 1.959 + 1.960 + // The webapp runtime doesn't use the new JS downloads API yet. 1.961 + // The conversion of the webapp runtime to use the JavaScript API for 1.962 + // downloads is tracked in bug 911636. 1.963 + if (appID.EqualsLiteral("webapprt@mozilla.org")) { 1.964 + mUseJSTransfer = false; 1.965 + } else { 1.966 +#if !defined(XP_WIN) 1.967 + mUseJSTransfer = true; 1.968 +#else 1.969 + // When MOZ_JSDOWNLOADS is defined on Windows, this component is disabled 1.970 + // unless we are running in Windows Metro. The conversion of Windows Metro 1.971 + // to use the JavaScript API for downloads is tracked in bug 906042. 1.972 + mUseJSTransfer = !IsRunningInWindowsMetro(); 1.973 +#endif 1.974 + } 1.975 + 1.976 +#endif 1.977 + 1.978 + if (mUseJSTransfer) 1.979 + return NS_OK; 1.980 + 1.981 + // Clean up any old downloads.rdf files from before Firefox 3 1.982 + { 1.983 + nsCOMPtr<nsIFile> oldDownloadsFile; 1.984 + bool fileExists; 1.985 + if (NS_SUCCEEDED(NS_GetSpecialDirectory(NS_APP_DOWNLOADS_50_FILE, 1.986 + getter_AddRefs(oldDownloadsFile))) && 1.987 + NS_SUCCEEDED(oldDownloadsFile->Exists(&fileExists)) && 1.988 + fileExists) { 1.989 + (void)oldDownloadsFile->Remove(false); 1.990 + } 1.991 + } 1.992 + 1.993 + mObserverService = mozilla::services::GetObserverService(); 1.994 + if (!mObserverService) 1.995 + return NS_ERROR_FAILURE; 1.996 + 1.997 + rv = InitDB(); 1.998 + NS_ENSURE_SUCCESS(rv, rv); 1.999 + 1.1000 +#ifdef DOWNLOAD_SCANNER 1.1001 + mScanner = new nsDownloadScanner(); 1.1002 + if (!mScanner) 1.1003 + return NS_ERROR_OUT_OF_MEMORY; 1.1004 + rv = mScanner->Init(); 1.1005 + if (NS_FAILED(rv)) { 1.1006 + delete mScanner; 1.1007 + mScanner = nullptr; 1.1008 + } 1.1009 +#endif 1.1010 + 1.1011 + // Do things *after* initializing various download manager properties such as 1.1012 + // restoring downloads to a consistent state 1.1013 + rv = RestoreDatabaseState(); 1.1014 + NS_ENSURE_SUCCESS(rv, rv); 1.1015 + 1.1016 + rv = RestoreActiveDownloads(); 1.1017 + NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Failed to restore all active downloads"); 1.1018 + 1.1019 + nsCOMPtr<nsINavHistoryService> history = 1.1020 + do_GetService(NS_NAVHISTORYSERVICE_CONTRACTID); 1.1021 + 1.1022 + (void)mObserverService->NotifyObservers( 1.1023 + static_cast<nsIDownloadManager *>(this), 1.1024 + "download-manager-initialized", 1.1025 + nullptr); 1.1026 + 1.1027 + // The following AddObserver calls must be the last lines in this function, 1.1028 + // because otherwise, this function may fail (and thus, this object would be not 1.1029 + // completely initialized), but the observerservice would still keep a reference 1.1030 + // to us and notify us about shutdown, which may cause crashes. 1.1031 + // failure to add an observer is not critical 1.1032 + (void)mObserverService->AddObserver(this, "quit-application", true); 1.1033 + (void)mObserverService->AddObserver(this, "quit-application-requested", true); 1.1034 + (void)mObserverService->AddObserver(this, "offline-requested", true); 1.1035 + (void)mObserverService->AddObserver(this, "sleep_notification", true); 1.1036 + (void)mObserverService->AddObserver(this, "wake_notification", true); 1.1037 + (void)mObserverService->AddObserver(this, "suspend_process_notification", true); 1.1038 + (void)mObserverService->AddObserver(this, "resume_process_notification", true); 1.1039 + (void)mObserverService->AddObserver(this, "profile-before-change", true); 1.1040 + (void)mObserverService->AddObserver(this, NS_IOSERVICE_GOING_OFFLINE_TOPIC, true); 1.1041 + (void)mObserverService->AddObserver(this, NS_IOSERVICE_OFFLINE_STATUS_TOPIC, true); 1.1042 + (void)mObserverService->AddObserver(this, "last-pb-context-exited", true); 1.1043 + (void)mObserverService->AddObserver(this, "last-pb-context-exiting", true); 1.1044 + 1.1045 + if (history) 1.1046 + (void)history->AddObserver(this, true); 1.1047 + 1.1048 + return NS_OK; 1.1049 +} 1.1050 + 1.1051 +int32_t 1.1052 +nsDownloadManager::GetRetentionBehavior() 1.1053 +{ 1.1054 + // We use 0 as the default, which is "remove when done" 1.1055 + nsresult rv; 1.1056 + nsCOMPtr<nsIPrefBranch> pref = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv); 1.1057 + NS_ENSURE_SUCCESS(rv, 0); 1.1058 + 1.1059 + int32_t val; 1.1060 + rv = pref->GetIntPref(PREF_BDM_RETENTION, &val); 1.1061 + NS_ENSURE_SUCCESS(rv, 0); 1.1062 + 1.1063 + // Allow the Downloads Panel to change the retention behavior. We do this to 1.1064 + // allow proper migration to the new feature when using the same profile on 1.1065 + // multiple versions of the product (bug 697678). Implementation note: in 1.1066 + // order to allow observers to change the retention value, we have to pass an 1.1067 + // object in the aSubject parameter, we cannot use aData for that. 1.1068 + nsCOMPtr<nsISupportsPRInt32> retentionBehavior = 1.1069 + do_CreateInstance(NS_SUPPORTS_PRINT32_CONTRACTID); 1.1070 + retentionBehavior->SetData(val); 1.1071 + (void)mObserverService->NotifyObservers(retentionBehavior, 1.1072 + "download-manager-change-retention", 1.1073 + nullptr); 1.1074 + retentionBehavior->GetData(&val); 1.1075 + 1.1076 + return val; 1.1077 +} 1.1078 + 1.1079 +enum nsDownloadManager::QuitBehavior 1.1080 +nsDownloadManager::GetQuitBehavior() 1.1081 +{ 1.1082 + // We use 0 as the default, which is "remember and resume the download" 1.1083 + nsresult rv; 1.1084 + nsCOMPtr<nsIPrefBranch> pref = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv); 1.1085 + NS_ENSURE_SUCCESS(rv, QUIT_AND_RESUME); 1.1086 + 1.1087 + int32_t val; 1.1088 + rv = pref->GetIntPref(PREF_BDM_QUITBEHAVIOR, &val); 1.1089 + NS_ENSURE_SUCCESS(rv, QUIT_AND_RESUME); 1.1090 + 1.1091 + switch (val) { 1.1092 + case 1: 1.1093 + return QUIT_AND_PAUSE; 1.1094 + case 2: 1.1095 + return QUIT_AND_CANCEL; 1.1096 + default: 1.1097 + return QUIT_AND_RESUME; 1.1098 + } 1.1099 +} 1.1100 + 1.1101 +// Using a globally-unique GUID, search all databases (both private and public). 1.1102 +// A return value of NS_ERROR_NOT_AVAILABLE means no download with the given GUID 1.1103 +// could be found, either private or public. 1.1104 + 1.1105 +nsresult 1.1106 +nsDownloadManager::GetDownloadFromDB(const nsACString& aGUID, nsDownload **retVal) 1.1107 +{ 1.1108 + MOZ_ASSERT(!FindDownload(aGUID), 1.1109 + "If it is a current download, you should not call this method!"); 1.1110 + 1.1111 + NS_NAMED_LITERAL_CSTRING(query, 1.1112 + "SELECT id, state, startTime, source, target, tempPath, name, referrer, " 1.1113 + "entityID, currBytes, maxBytes, mimeType, preferredAction, " 1.1114 + "preferredApplication, autoResume, guid " 1.1115 + "FROM moz_downloads " 1.1116 + "WHERE guid = :guid"); 1.1117 + // First, let's query the database and see if it even exists 1.1118 + nsCOMPtr<mozIStorageStatement> stmt; 1.1119 + nsresult rv = mDBConn->CreateStatement(query, getter_AddRefs(stmt)); 1.1120 + NS_ENSURE_SUCCESS(rv, rv); 1.1121 + 1.1122 + rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), aGUID); 1.1123 + NS_ENSURE_SUCCESS(rv, rv); 1.1124 + 1.1125 + rv = GetDownloadFromDB(mDBConn, stmt, retVal); 1.1126 + 1.1127 + // If the download cannot be found in the public database, try again 1.1128 + // in the private one. Otherwise, return whatever successful result 1.1129 + // or failure obtained from the public database. 1.1130 + if (rv == NS_ERROR_NOT_AVAILABLE) { 1.1131 + rv = mPrivateDBConn->CreateStatement(query, getter_AddRefs(stmt)); 1.1132 + NS_ENSURE_SUCCESS(rv, rv); 1.1133 + 1.1134 + rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), aGUID); 1.1135 + NS_ENSURE_SUCCESS(rv, rv); 1.1136 + 1.1137 + rv = GetDownloadFromDB(mPrivateDBConn, stmt, retVal); 1.1138 + 1.1139 + // Only if it still cannot be found do we report the failure. 1.1140 + if (rv == NS_ERROR_NOT_AVAILABLE) { 1.1141 + *retVal = nullptr; 1.1142 + } 1.1143 + } 1.1144 + return rv; 1.1145 +} 1.1146 + 1.1147 +nsresult 1.1148 +nsDownloadManager::GetDownloadFromDB(uint32_t aID, nsDownload **retVal) 1.1149 +{ 1.1150 + NS_WARNING("Using integer IDs without compat mode enabled"); 1.1151 + 1.1152 + MOZ_ASSERT(!FindDownload(aID), 1.1153 + "If it is a current download, you should not call this method!"); 1.1154 + 1.1155 + // First, let's query the database and see if it even exists 1.1156 + nsCOMPtr<mozIStorageStatement> stmt; 1.1157 + nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.1158 + "SELECT id, state, startTime, source, target, tempPath, name, referrer, " 1.1159 + "entityID, currBytes, maxBytes, mimeType, preferredAction, " 1.1160 + "preferredApplication, autoResume, guid " 1.1161 + "FROM moz_downloads " 1.1162 + "WHERE id = :id"), getter_AddRefs(stmt)); 1.1163 + NS_ENSURE_SUCCESS(rv, rv); 1.1164 + 1.1165 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("id"), aID); 1.1166 + NS_ENSURE_SUCCESS(rv, rv); 1.1167 + 1.1168 + return GetDownloadFromDB(mDBConn, stmt, retVal); 1.1169 +} 1.1170 + 1.1171 +nsresult 1.1172 +nsDownloadManager::GetDownloadFromDB(mozIStorageConnection* aDBConn, 1.1173 + mozIStorageStatement* stmt, 1.1174 + nsDownload **retVal) 1.1175 +{ 1.1176 + bool hasResults = false; 1.1177 + nsresult rv = stmt->ExecuteStep(&hasResults); 1.1178 + if (NS_FAILED(rv) || !hasResults) 1.1179 + return NS_ERROR_NOT_AVAILABLE; 1.1180 + 1.1181 + // We have a download, so lets create it 1.1182 + nsRefPtr<nsDownload> dl = new nsDownload(); 1.1183 + if (!dl) 1.1184 + return NS_ERROR_OUT_OF_MEMORY; 1.1185 + dl->mPrivate = aDBConn == mPrivateDBConn; 1.1186 + 1.1187 + dl->mDownloadManager = this; 1.1188 + 1.1189 + int32_t i = 0; 1.1190 + // Setting all properties of the download now 1.1191 + dl->mCancelable = nullptr; 1.1192 + dl->mID = stmt->AsInt64(i++); 1.1193 + dl->mDownloadState = stmt->AsInt32(i++); 1.1194 + dl->mStartTime = stmt->AsInt64(i++); 1.1195 + 1.1196 + nsCString source; 1.1197 + stmt->GetUTF8String(i++, source); 1.1198 + rv = NS_NewURI(getter_AddRefs(dl->mSource), source); 1.1199 + NS_ENSURE_SUCCESS(rv, rv); 1.1200 + 1.1201 + nsCString target; 1.1202 + stmt->GetUTF8String(i++, target); 1.1203 + rv = NS_NewURI(getter_AddRefs(dl->mTarget), target); 1.1204 + NS_ENSURE_SUCCESS(rv, rv); 1.1205 + 1.1206 + nsString tempPath; 1.1207 + stmt->GetString(i++, tempPath); 1.1208 + if (!tempPath.IsEmpty()) { 1.1209 + rv = NS_NewLocalFile(tempPath, true, getter_AddRefs(dl->mTempFile)); 1.1210 + NS_ENSURE_SUCCESS(rv, rv); 1.1211 + } 1.1212 + 1.1213 + stmt->GetString(i++, dl->mDisplayName); 1.1214 + 1.1215 + nsCString referrer; 1.1216 + rv = stmt->GetUTF8String(i++, referrer); 1.1217 + if (NS_SUCCEEDED(rv) && !referrer.IsEmpty()) { 1.1218 + rv = NS_NewURI(getter_AddRefs(dl->mReferrer), referrer); 1.1219 + NS_ENSURE_SUCCESS(rv, rv); 1.1220 + } 1.1221 + 1.1222 + rv = stmt->GetUTF8String(i++, dl->mEntityID); 1.1223 + NS_ENSURE_SUCCESS(rv, rv); 1.1224 + 1.1225 + int64_t currBytes = stmt->AsInt64(i++); 1.1226 + int64_t maxBytes = stmt->AsInt64(i++); 1.1227 + dl->SetProgressBytes(currBytes, maxBytes); 1.1228 + 1.1229 + // Build mMIMEInfo only if the mimeType in DB is not empty 1.1230 + nsAutoCString mimeType; 1.1231 + rv = stmt->GetUTF8String(i++, mimeType); 1.1232 + NS_ENSURE_SUCCESS(rv, rv); 1.1233 + 1.1234 + if (!mimeType.IsEmpty()) { 1.1235 + nsCOMPtr<nsIMIMEService> mimeService = 1.1236 + do_GetService(NS_MIMESERVICE_CONTRACTID, &rv); 1.1237 + NS_ENSURE_SUCCESS(rv, rv); 1.1238 + 1.1239 + rv = mimeService->GetFromTypeAndExtension(mimeType, EmptyCString(), 1.1240 + getter_AddRefs(dl->mMIMEInfo)); 1.1241 + NS_ENSURE_SUCCESS(rv, rv); 1.1242 + 1.1243 + nsHandlerInfoAction action = stmt->AsInt32(i++); 1.1244 + rv = dl->mMIMEInfo->SetPreferredAction(action); 1.1245 + NS_ENSURE_SUCCESS(rv, rv); 1.1246 + 1.1247 + nsAutoCString persistentDescriptor; 1.1248 + rv = stmt->GetUTF8String(i++, persistentDescriptor); 1.1249 + NS_ENSURE_SUCCESS(rv, rv); 1.1250 + 1.1251 + if (!persistentDescriptor.IsEmpty()) { 1.1252 + nsCOMPtr<nsILocalHandlerApp> handler = 1.1253 + do_CreateInstance(NS_LOCALHANDLERAPP_CONTRACTID, &rv); 1.1254 + NS_ENSURE_SUCCESS(rv, rv); 1.1255 + 1.1256 + nsCOMPtr<nsIFile> localExecutable; 1.1257 + rv = NS_NewNativeLocalFile(EmptyCString(), false, 1.1258 + getter_AddRefs(localExecutable)); 1.1259 + NS_ENSURE_SUCCESS(rv, rv); 1.1260 + 1.1261 + rv = localExecutable->SetPersistentDescriptor(persistentDescriptor); 1.1262 + NS_ENSURE_SUCCESS(rv, rv); 1.1263 + 1.1264 + rv = handler->SetExecutable(localExecutable); 1.1265 + NS_ENSURE_SUCCESS(rv, rv); 1.1266 + 1.1267 + rv = dl->mMIMEInfo->SetPreferredApplicationHandler(handler); 1.1268 + NS_ENSURE_SUCCESS(rv, rv); 1.1269 + } 1.1270 + } else { 1.1271 + // Compensate for the i++s skipped in the true block 1.1272 + i += 2; 1.1273 + } 1.1274 + 1.1275 + dl->mAutoResume = 1.1276 + static_cast<enum nsDownload::AutoResume>(stmt->AsInt32(i++)); 1.1277 + 1.1278 + rv = stmt->GetUTF8String(i++, dl->mGUID); 1.1279 + NS_ENSURE_SUCCESS(rv, rv); 1.1280 + 1.1281 + // Handle situations where we load a download from a database that has been 1.1282 + // used in an older version and not gone through the upgrade path (ie. it 1.1283 + // contains empty GUID entries). 1.1284 + if (dl->mGUID.IsEmpty()) { 1.1285 + rv = GenerateGUID(dl->mGUID); 1.1286 + NS_ENSURE_SUCCESS(rv, rv); 1.1287 + nsCOMPtr<mozIStorageStatement> stmt; 1.1288 + rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.1289 + "UPDATE moz_downloads SET guid = :guid " 1.1290 + "WHERE id = :id"), 1.1291 + getter_AddRefs(stmt)); 1.1292 + NS_ENSURE_SUCCESS(rv, rv); 1.1293 + rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), dl->mGUID); 1.1294 + NS_ENSURE_SUCCESS(rv, rv); 1.1295 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("id"), dl->mID); 1.1296 + NS_ENSURE_SUCCESS(rv, rv); 1.1297 + rv = stmt->Execute(); 1.1298 + NS_ENSURE_SUCCESS(rv, rv); 1.1299 + } 1.1300 + 1.1301 + // Addrefing and returning 1.1302 + NS_ADDREF(*retVal = dl); 1.1303 + return NS_OK; 1.1304 +} 1.1305 + 1.1306 +nsresult 1.1307 +nsDownloadManager::AddToCurrentDownloads(nsDownload *aDl) 1.1308 +{ 1.1309 + nsCOMArray<nsDownload>& currentDownloads = 1.1310 + aDl->mPrivate ? mCurrentPrivateDownloads : mCurrentDownloads; 1.1311 + if (!currentDownloads.AppendObject(aDl)) 1.1312 + return NS_ERROR_OUT_OF_MEMORY; 1.1313 + 1.1314 + aDl->mDownloadManager = this; 1.1315 + return NS_OK; 1.1316 +} 1.1317 + 1.1318 +void 1.1319 +nsDownloadManager::SendEvent(nsDownload *aDownload, const char *aTopic) 1.1320 +{ 1.1321 + (void)mObserverService->NotifyObservers(aDownload, aTopic, nullptr); 1.1322 +} 1.1323 + 1.1324 +//////////////////////////////////////////////////////////////////////////////// 1.1325 +//// nsIDownloadManager 1.1326 + 1.1327 +NS_IMETHODIMP 1.1328 +nsDownloadManager::GetActivePrivateDownloadCount(int32_t* aResult) 1.1329 +{ 1.1330 + NS_ENSURE_STATE(!mUseJSTransfer); 1.1331 + 1.1332 + *aResult = mCurrentPrivateDownloads.Count(); 1.1333 + return NS_OK; 1.1334 +} 1.1335 + 1.1336 +NS_IMETHODIMP 1.1337 +nsDownloadManager::GetActiveDownloadCount(int32_t *aResult) 1.1338 +{ 1.1339 + NS_ENSURE_STATE(!mUseJSTransfer); 1.1340 + 1.1341 + *aResult = mCurrentDownloads.Count(); 1.1342 + 1.1343 + return NS_OK; 1.1344 +} 1.1345 + 1.1346 +NS_IMETHODIMP 1.1347 +nsDownloadManager::GetActiveDownloads(nsISimpleEnumerator **aResult) 1.1348 +{ 1.1349 + NS_ENSURE_STATE(!mUseJSTransfer); 1.1350 + 1.1351 + return NS_NewArrayEnumerator(aResult, mCurrentDownloads); 1.1352 +} 1.1353 + 1.1354 +NS_IMETHODIMP 1.1355 +nsDownloadManager::GetActivePrivateDownloads(nsISimpleEnumerator **aResult) 1.1356 +{ 1.1357 + NS_ENSURE_STATE(!mUseJSTransfer); 1.1358 + 1.1359 + return NS_NewArrayEnumerator(aResult, mCurrentPrivateDownloads); 1.1360 +} 1.1361 + 1.1362 +/** 1.1363 + * For platforms where helper apps use the downloads directory (i.e. mobile), 1.1364 + * this should be kept in sync with nsExternalHelperAppService.cpp 1.1365 + */ 1.1366 +NS_IMETHODIMP 1.1367 +nsDownloadManager::GetDefaultDownloadsDirectory(nsIFile **aResult) 1.1368 +{ 1.1369 + nsCOMPtr<nsIFile> downloadDir; 1.1370 + 1.1371 + nsresult rv; 1.1372 + nsCOMPtr<nsIProperties> dirService = 1.1373 + do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv); 1.1374 + NS_ENSURE_SUCCESS(rv, rv); 1.1375 + 1.1376 + // OSX 10.4: 1.1377 + // Desktop 1.1378 + // OSX 10.5: 1.1379 + // User download directory 1.1380 + // Vista: 1.1381 + // Downloads 1.1382 + // XP/2K: 1.1383 + // My Documents/Downloads 1.1384 + // Linux: 1.1385 + // XDG user dir spec, with a fallback to Home/Downloads 1.1386 + 1.1387 + nsXPIDLString folderName; 1.1388 + mBundle->GetStringFromName(MOZ_UTF16("downloadsFolder"), 1.1389 + getter_Copies(folderName)); 1.1390 + 1.1391 +#if defined (XP_MACOSX) 1.1392 + rv = dirService->Get(NS_OSX_DEFAULT_DOWNLOAD_DIR, 1.1393 + NS_GET_IID(nsIFile), 1.1394 + getter_AddRefs(downloadDir)); 1.1395 + NS_ENSURE_SUCCESS(rv, rv); 1.1396 +#elif defined(XP_WIN) 1.1397 + rv = dirService->Get(NS_WIN_DEFAULT_DOWNLOAD_DIR, 1.1398 + NS_GET_IID(nsIFile), 1.1399 + getter_AddRefs(downloadDir)); 1.1400 + NS_ENSURE_SUCCESS(rv, rv); 1.1401 + 1.1402 + // Check the os version 1.1403 + nsCOMPtr<nsIPropertyBag2> infoService = 1.1404 + do_GetService(NS_SYSTEMINFO_CONTRACTID, &rv); 1.1405 + NS_ENSURE_SUCCESS(rv, rv); 1.1406 + 1.1407 + int32_t version; 1.1408 + NS_NAMED_LITERAL_STRING(osVersion, "version"); 1.1409 + rv = infoService->GetPropertyAsInt32(osVersion, &version); 1.1410 + NS_ENSURE_SUCCESS(rv, rv); 1.1411 + if (version < 6) { // XP/2K 1.1412 + // First get "My Documents" 1.1413 + rv = dirService->Get(NS_WIN_PERSONAL_DIR, 1.1414 + NS_GET_IID(nsIFile), 1.1415 + getter_AddRefs(downloadDir)); 1.1416 + NS_ENSURE_SUCCESS(rv, rv); 1.1417 + 1.1418 + rv = downloadDir->Append(folderName); 1.1419 + NS_ENSURE_SUCCESS(rv, rv); 1.1420 + 1.1421 + // This could be the first time we are creating the downloads folder in My 1.1422 + // Documents, so make sure it exists. 1.1423 + bool exists; 1.1424 + rv = downloadDir->Exists(&exists); 1.1425 + NS_ENSURE_SUCCESS(rv, rv); 1.1426 + if (!exists) { 1.1427 + rv = downloadDir->Create(nsIFile::DIRECTORY_TYPE, 0755); 1.1428 + NS_ENSURE_SUCCESS(rv, rv); 1.1429 + } 1.1430 + } 1.1431 +#elif defined(XP_UNIX) 1.1432 +#if defined(MOZ_WIDGET_ANDROID) 1.1433 + // Android doesn't have a $HOME directory, and by default we only have 1.1434 + // write access to /data/data/org.mozilla.{$APP} and /sdcard 1.1435 + char* downloadDirPath = getenv("DOWNLOADS_DIRECTORY"); 1.1436 + if (downloadDirPath) { 1.1437 + rv = NS_NewNativeLocalFile(nsDependentCString(downloadDirPath), 1.1438 + true, getter_AddRefs(downloadDir)); 1.1439 + NS_ENSURE_SUCCESS(rv, rv); 1.1440 + } 1.1441 + else { 1.1442 + rv = NS_ERROR_FAILURE; 1.1443 + } 1.1444 +#else 1.1445 + rv = dirService->Get(NS_UNIX_DEFAULT_DOWNLOAD_DIR, 1.1446 + NS_GET_IID(nsIFile), 1.1447 + getter_AddRefs(downloadDir)); 1.1448 + // fallback to Home/Downloads 1.1449 + if (NS_FAILED(rv)) { 1.1450 + rv = dirService->Get(NS_UNIX_HOME_DIR, 1.1451 + NS_GET_IID(nsIFile), 1.1452 + getter_AddRefs(downloadDir)); 1.1453 + NS_ENSURE_SUCCESS(rv, rv); 1.1454 + rv = downloadDir->Append(folderName); 1.1455 + NS_ENSURE_SUCCESS(rv, rv); 1.1456 + } 1.1457 +#endif 1.1458 +#else 1.1459 + rv = dirService->Get(NS_OS_HOME_DIR, 1.1460 + NS_GET_IID(nsIFile), 1.1461 + getter_AddRefs(downloadDir)); 1.1462 + NS_ENSURE_SUCCESS(rv, rv); 1.1463 + rv = downloadDir->Append(folderName); 1.1464 + NS_ENSURE_SUCCESS(rv, rv); 1.1465 +#endif 1.1466 + 1.1467 + downloadDir.forget(aResult); 1.1468 + 1.1469 + return NS_OK; 1.1470 +} 1.1471 + 1.1472 +#define NS_BRANCH_DOWNLOAD "browser.download." 1.1473 +#define NS_PREF_FOLDERLIST "folderList" 1.1474 +#define NS_PREF_DIR "dir" 1.1475 + 1.1476 +NS_IMETHODIMP 1.1477 +nsDownloadManager::GetUserDownloadsDirectory(nsIFile **aResult) 1.1478 +{ 1.1479 + nsresult rv; 1.1480 + nsCOMPtr<nsIProperties> dirService = 1.1481 + do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv); 1.1482 + NS_ENSURE_SUCCESS(rv, rv); 1.1483 + 1.1484 + nsCOMPtr<nsIPrefService> prefService = 1.1485 + do_GetService(NS_PREFSERVICE_CONTRACTID, &rv); 1.1486 + NS_ENSURE_SUCCESS(rv, rv); 1.1487 + 1.1488 + nsCOMPtr<nsIPrefBranch> prefBranch; 1.1489 + rv = prefService->GetBranch(NS_BRANCH_DOWNLOAD, 1.1490 + getter_AddRefs(prefBranch)); 1.1491 + NS_ENSURE_SUCCESS(rv, rv); 1.1492 + 1.1493 + int32_t val; 1.1494 + rv = prefBranch->GetIntPref(NS_PREF_FOLDERLIST, 1.1495 + &val); 1.1496 + NS_ENSURE_SUCCESS(rv, rv); 1.1497 + 1.1498 + switch(val) { 1.1499 + case 0: // Desktop 1.1500 + { 1.1501 + nsCOMPtr<nsIFile> downloadDir; 1.1502 + nsCOMPtr<nsIProperties> dirService = 1.1503 + do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv); 1.1504 + NS_ENSURE_SUCCESS(rv, rv); 1.1505 + rv = dirService->Get(NS_OS_DESKTOP_DIR, 1.1506 + NS_GET_IID(nsIFile), 1.1507 + getter_AddRefs(downloadDir)); 1.1508 + NS_ENSURE_SUCCESS(rv, rv); 1.1509 + downloadDir.forget(aResult); 1.1510 + return NS_OK; 1.1511 + } 1.1512 + break; 1.1513 + case 1: // Downloads 1.1514 + return GetDefaultDownloadsDirectory(aResult); 1.1515 + case 2: // Custom 1.1516 + { 1.1517 + nsCOMPtr<nsIFile> customDirectory; 1.1518 + prefBranch->GetComplexValue(NS_PREF_DIR, 1.1519 + NS_GET_IID(nsIFile), 1.1520 + getter_AddRefs(customDirectory)); 1.1521 + if (customDirectory) { 1.1522 + bool exists = false; 1.1523 + (void)customDirectory->Exists(&exists); 1.1524 + 1.1525 + if (!exists) { 1.1526 + rv = customDirectory->Create(nsIFile::DIRECTORY_TYPE, 0755); 1.1527 + if (NS_SUCCEEDED(rv)) { 1.1528 + customDirectory.forget(aResult); 1.1529 + return NS_OK; 1.1530 + } 1.1531 + 1.1532 + // Create failed, so it still doesn't exist. Fall out and get the 1.1533 + // default downloads directory. 1.1534 + } 1.1535 + 1.1536 + bool writable = false; 1.1537 + bool directory = false; 1.1538 + (void)customDirectory->IsWritable(&writable); 1.1539 + (void)customDirectory->IsDirectory(&directory); 1.1540 + 1.1541 + if (exists && writable && directory) { 1.1542 + customDirectory.forget(aResult); 1.1543 + return NS_OK; 1.1544 + } 1.1545 + } 1.1546 + rv = GetDefaultDownloadsDirectory(aResult); 1.1547 + if (NS_SUCCEEDED(rv)) { 1.1548 + (void)prefBranch->SetComplexValue(NS_PREF_DIR, 1.1549 + NS_GET_IID(nsIFile), 1.1550 + *aResult); 1.1551 + } 1.1552 + return rv; 1.1553 + } 1.1554 + break; 1.1555 + } 1.1556 + return NS_ERROR_INVALID_ARG; 1.1557 +} 1.1558 + 1.1559 +NS_IMETHODIMP 1.1560 +nsDownloadManager::AddDownload(DownloadType aDownloadType, 1.1561 + nsIURI *aSource, 1.1562 + nsIURI *aTarget, 1.1563 + const nsAString& aDisplayName, 1.1564 + nsIMIMEInfo *aMIMEInfo, 1.1565 + PRTime aStartTime, 1.1566 + nsIFile *aTempFile, 1.1567 + nsICancelable *aCancelable, 1.1568 + bool aIsPrivate, 1.1569 + nsIDownload **aDownload) 1.1570 +{ 1.1571 + NS_ENSURE_STATE(!mUseJSTransfer); 1.1572 + 1.1573 + NS_ENSURE_ARG_POINTER(aSource); 1.1574 + NS_ENSURE_ARG_POINTER(aTarget); 1.1575 + NS_ENSURE_ARG_POINTER(aDownload); 1.1576 + 1.1577 + nsresult rv; 1.1578 + 1.1579 + // target must be on the local filesystem 1.1580 + nsCOMPtr<nsIFileURL> targetFileURL = do_QueryInterface(aTarget, &rv); 1.1581 + NS_ENSURE_SUCCESS(rv, rv); 1.1582 + 1.1583 + nsCOMPtr<nsIFile> targetFile; 1.1584 + rv = targetFileURL->GetFile(getter_AddRefs(targetFile)); 1.1585 + NS_ENSURE_SUCCESS(rv, rv); 1.1586 + 1.1587 + nsRefPtr<nsDownload> dl = new nsDownload(); 1.1588 + if (!dl) 1.1589 + return NS_ERROR_OUT_OF_MEMORY; 1.1590 + 1.1591 + // give our new nsIDownload some info so it's ready to go off into the world 1.1592 + dl->mTarget = aTarget; 1.1593 + dl->mSource = aSource; 1.1594 + dl->mTempFile = aTempFile; 1.1595 + dl->mPrivate = aIsPrivate; 1.1596 + 1.1597 + dl->mDisplayName = aDisplayName; 1.1598 + if (dl->mDisplayName.IsEmpty()) 1.1599 + targetFile->GetLeafName(dl->mDisplayName); 1.1600 + 1.1601 + dl->mMIMEInfo = aMIMEInfo; 1.1602 + dl->SetStartTime(aStartTime == 0 ? PR_Now() : aStartTime); 1.1603 + 1.1604 + // Creates a cycle that will be broken when the download finishes 1.1605 + dl->mCancelable = aCancelable; 1.1606 + 1.1607 + // Adding to the DB 1.1608 + nsAutoCString source, target; 1.1609 + aSource->GetSpec(source); 1.1610 + aTarget->GetSpec(target); 1.1611 + 1.1612 + // Track the temp file for exthandler downloads 1.1613 + nsAutoString tempPath; 1.1614 + if (aTempFile) 1.1615 + aTempFile->GetPath(tempPath); 1.1616 + 1.1617 + // Break down MIMEInfo but don't panic if we can't get all the pieces - we 1.1618 + // can still download the file 1.1619 + nsAutoCString persistentDescriptor, mimeType; 1.1620 + nsHandlerInfoAction action = nsIMIMEInfo::saveToDisk; 1.1621 + if (aMIMEInfo) { 1.1622 + (void)aMIMEInfo->GetType(mimeType); 1.1623 + 1.1624 + nsCOMPtr<nsIHandlerApp> handlerApp; 1.1625 + (void)aMIMEInfo->GetPreferredApplicationHandler(getter_AddRefs(handlerApp)); 1.1626 + nsCOMPtr<nsILocalHandlerApp> locHandlerApp = do_QueryInterface(handlerApp); 1.1627 + 1.1628 + if (locHandlerApp) { 1.1629 + nsCOMPtr<nsIFile> executable; 1.1630 + (void)locHandlerApp->GetExecutable(getter_AddRefs(executable)); 1.1631 + (void)executable->GetPersistentDescriptor(persistentDescriptor); 1.1632 + } 1.1633 + 1.1634 + (void)aMIMEInfo->GetPreferredAction(&action); 1.1635 + } 1.1636 + 1.1637 + int64_t id = AddDownloadToDB(dl->mDisplayName, source, target, tempPath, 1.1638 + dl->mStartTime, dl->mLastUpdate, 1.1639 + mimeType, persistentDescriptor, action, 1.1640 + dl->mPrivate, dl->mGUID /* outparam */); 1.1641 + NS_ENSURE_TRUE(id, NS_ERROR_FAILURE); 1.1642 + dl->mID = id; 1.1643 + 1.1644 + rv = AddToCurrentDownloads(dl); 1.1645 + (void)dl->SetState(nsIDownloadManager::DOWNLOAD_QUEUED); 1.1646 + NS_ENSURE_SUCCESS(rv, rv); 1.1647 + 1.1648 +#ifdef DOWNLOAD_SCANNER 1.1649 + if (mScanner) { 1.1650 + bool scan = true; 1.1651 + nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID)); 1.1652 + if (prefs) { 1.1653 + (void)prefs->GetBoolPref(PREF_BDM_SCANWHENDONE, &scan); 1.1654 + } 1.1655 + // We currently apply local security policy to downloads when we scan 1.1656 + // via windows all-in-one download security api. The CheckPolicy call 1.1657 + // below is a pre-emptive part of that process. So tie applying security 1.1658 + // zone policy settings when downloads are intiated to the same pref 1.1659 + // that triggers applying security zone policy settings after a download 1.1660 + // completes. (bug 504804) 1.1661 + if (scan) { 1.1662 + AVCheckPolicyState res = mScanner->CheckPolicy(aSource, aTarget); 1.1663 + if (res == AVPOLICY_BLOCKED) { 1.1664 + // This download will get deleted during a call to IAE's Save, 1.1665 + // so go ahead and mark it as blocked and avoid the download. 1.1666 + (void)CancelDownload(id); 1.1667 + (void)dl->SetState(nsIDownloadManager::DOWNLOAD_BLOCKED_POLICY); 1.1668 + } 1.1669 + } 1.1670 + } 1.1671 +#endif 1.1672 + 1.1673 + // Check with parental controls to see if file downloads 1.1674 + // are allowed for this user. If not allowed, cancel the 1.1675 + // download and mark its state as being blocked. 1.1676 + nsCOMPtr<nsIParentalControlsService> pc = 1.1677 + do_CreateInstance(NS_PARENTALCONTROLSSERVICE_CONTRACTID); 1.1678 + if (pc) { 1.1679 + bool enabled = false; 1.1680 + (void)pc->GetBlockFileDownloadsEnabled(&enabled); 1.1681 + if (enabled) { 1.1682 + (void)CancelDownload(id); 1.1683 + (void)dl->SetState(nsIDownloadManager::DOWNLOAD_BLOCKED_PARENTAL); 1.1684 + } 1.1685 + 1.1686 + // Log the event if required by pc settings. 1.1687 + bool logEnabled = false; 1.1688 + (void)pc->GetLoggingEnabled(&logEnabled); 1.1689 + if (logEnabled) { 1.1690 + (void)pc->Log(nsIParentalControlsService::ePCLog_FileDownload, 1.1691 + enabled, 1.1692 + aSource, 1.1693 + nullptr); 1.1694 + } 1.1695 + } 1.1696 + 1.1697 + NS_ADDREF(*aDownload = dl); 1.1698 + 1.1699 + return NS_OK; 1.1700 +} 1.1701 + 1.1702 +NS_IMETHODIMP 1.1703 +nsDownloadManager::GetDownload(uint32_t aID, nsIDownload **aDownloadItem) 1.1704 +{ 1.1705 + NS_ENSURE_STATE(!mUseJSTransfer); 1.1706 + 1.1707 + NS_WARNING("Using integer IDs without compat mode enabled"); 1.1708 + 1.1709 + nsDownload *itm = FindDownload(aID); 1.1710 + 1.1711 + nsRefPtr<nsDownload> dl; 1.1712 + if (!itm) { 1.1713 + nsresult rv = GetDownloadFromDB(aID, getter_AddRefs(dl)); 1.1714 + NS_ENSURE_SUCCESS(rv, rv); 1.1715 + 1.1716 + itm = dl.get(); 1.1717 + } 1.1718 + 1.1719 + NS_ADDREF(*aDownloadItem = itm); 1.1720 + 1.1721 + return NS_OK; 1.1722 +} 1.1723 + 1.1724 +namespace { 1.1725 +class AsyncResult : public nsRunnable 1.1726 +{ 1.1727 +public: 1.1728 + AsyncResult(nsresult aStatus, nsIDownload* aResult, 1.1729 + nsIDownloadManagerResult* aCallback) 1.1730 + : mStatus(aStatus), mResult(aResult), mCallback(aCallback) 1.1731 + { 1.1732 + } 1.1733 + 1.1734 + NS_IMETHOD Run() 1.1735 + { 1.1736 + mCallback->HandleResult(mStatus, mResult); 1.1737 + return NS_OK; 1.1738 + } 1.1739 + 1.1740 +private: 1.1741 + nsresult mStatus; 1.1742 + nsCOMPtr<nsIDownload> mResult; 1.1743 + nsCOMPtr<nsIDownloadManagerResult> mCallback; 1.1744 +}; 1.1745 +} // anonymous namespace 1.1746 + 1.1747 +NS_IMETHODIMP 1.1748 +nsDownloadManager::GetDownloadByGUID(const nsACString& aGUID, 1.1749 + nsIDownloadManagerResult* aCallback) 1.1750 +{ 1.1751 + NS_ENSURE_STATE(!mUseJSTransfer); 1.1752 + 1.1753 + nsDownload *itm = FindDownload(aGUID); 1.1754 + 1.1755 + nsresult rv = NS_OK; 1.1756 + nsRefPtr<nsDownload> dl; 1.1757 + if (!itm) { 1.1758 + rv = GetDownloadFromDB(aGUID, getter_AddRefs(dl)); 1.1759 + itm = dl.get(); 1.1760 + } 1.1761 + 1.1762 + nsRefPtr<AsyncResult> runnable = new AsyncResult(rv, itm, aCallback); 1.1763 + NS_DispatchToMainThread(runnable); 1.1764 + return NS_OK; 1.1765 +} 1.1766 + 1.1767 +nsDownload * 1.1768 +nsDownloadManager::FindDownload(uint32_t aID) 1.1769 +{ 1.1770 + // we shouldn't ever have many downloads, so we can loop over them 1.1771 + for (int32_t i = mCurrentDownloads.Count() - 1; i >= 0; --i) { 1.1772 + nsDownload *dl = mCurrentDownloads[i]; 1.1773 + if (dl->mID == aID) 1.1774 + return dl; 1.1775 + } 1.1776 + 1.1777 + return nullptr; 1.1778 +} 1.1779 + 1.1780 +nsDownload * 1.1781 +nsDownloadManager::FindDownload(const nsACString& aGUID) 1.1782 +{ 1.1783 + // we shouldn't ever have many downloads, so we can loop over them 1.1784 + for (int32_t i = mCurrentDownloads.Count() - 1; i >= 0; --i) { 1.1785 + nsDownload *dl = mCurrentDownloads[i]; 1.1786 + if (dl->mGUID == aGUID) 1.1787 + return dl; 1.1788 + } 1.1789 + 1.1790 + for (int32_t i = mCurrentPrivateDownloads.Count() - 1; i >= 0; --i) { 1.1791 + nsDownload *dl = mCurrentPrivateDownloads[i]; 1.1792 + if (dl->mGUID == aGUID) 1.1793 + return dl; 1.1794 + } 1.1795 + 1.1796 + return nullptr; 1.1797 +} 1.1798 + 1.1799 +NS_IMETHODIMP 1.1800 +nsDownloadManager::CancelDownload(uint32_t aID) 1.1801 +{ 1.1802 + NS_ENSURE_STATE(!mUseJSTransfer); 1.1803 + 1.1804 + NS_WARNING("Using integer IDs without compat mode enabled"); 1.1805 + 1.1806 + // We AddRef here so we don't lose access to member variables when we remove 1.1807 + nsRefPtr<nsDownload> dl = FindDownload(aID); 1.1808 + 1.1809 + // if it's null, someone passed us a bad id. 1.1810 + if (!dl) 1.1811 + return NS_ERROR_FAILURE; 1.1812 + 1.1813 + return dl->Cancel(); 1.1814 +} 1.1815 + 1.1816 +nsresult 1.1817 +nsDownloadManager::RetryDownload(const nsACString& aGUID) 1.1818 +{ 1.1819 + nsRefPtr<nsDownload> dl; 1.1820 + nsresult rv = GetDownloadFromDB(aGUID, getter_AddRefs(dl)); 1.1821 + NS_ENSURE_SUCCESS(rv, rv); 1.1822 + 1.1823 + return RetryDownload(dl); 1.1824 +} 1.1825 + 1.1826 + 1.1827 +NS_IMETHODIMP 1.1828 +nsDownloadManager::RetryDownload(uint32_t aID) 1.1829 +{ 1.1830 + NS_ENSURE_STATE(!mUseJSTransfer); 1.1831 + 1.1832 + NS_WARNING("Using integer IDs without compat mode enabled"); 1.1833 + 1.1834 + nsRefPtr<nsDownload> dl; 1.1835 + nsresult rv = GetDownloadFromDB(aID, getter_AddRefs(dl)); 1.1836 + NS_ENSURE_SUCCESS(rv, rv); 1.1837 + 1.1838 + return RetryDownload(dl); 1.1839 +} 1.1840 + 1.1841 +nsresult 1.1842 +nsDownloadManager::RetryDownload(nsDownload* dl) 1.1843 +{ 1.1844 + // if our download is not canceled or failed, we should fail 1.1845 + if (dl->mDownloadState != nsIDownloadManager::DOWNLOAD_FAILED && 1.1846 + dl->mDownloadState != nsIDownloadManager::DOWNLOAD_BLOCKED_PARENTAL && 1.1847 + dl->mDownloadState != nsIDownloadManager::DOWNLOAD_BLOCKED_POLICY && 1.1848 + dl->mDownloadState != nsIDownloadManager::DOWNLOAD_DIRTY && 1.1849 + dl->mDownloadState != nsIDownloadManager::DOWNLOAD_CANCELED) 1.1850 + return NS_ERROR_FAILURE; 1.1851 + 1.1852 + // If the download has failed and is resumable then we first try resuming it 1.1853 + nsresult rv; 1.1854 + if (dl->mDownloadState == nsIDownloadManager::DOWNLOAD_FAILED && dl->IsResumable()) { 1.1855 + rv = dl->Resume(); 1.1856 + if (NS_SUCCEEDED(rv)) 1.1857 + return rv; 1.1858 + } 1.1859 + 1.1860 + // reset time and download progress 1.1861 + dl->SetStartTime(PR_Now()); 1.1862 + dl->SetProgressBytes(0, -1); 1.1863 + 1.1864 + nsCOMPtr<nsIWebBrowserPersist> wbp = 1.1865 + do_CreateInstance("@mozilla.org/embedding/browser/nsWebBrowserPersist;1", &rv); 1.1866 + NS_ENSURE_SUCCESS(rv, rv); 1.1867 + 1.1868 + rv = wbp->SetPersistFlags(nsIWebBrowserPersist::PERSIST_FLAGS_REPLACE_EXISTING_FILES | 1.1869 + nsIWebBrowserPersist::PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION); 1.1870 + NS_ENSURE_SUCCESS(rv, rv); 1.1871 + 1.1872 + rv = AddToCurrentDownloads(dl); 1.1873 + NS_ENSURE_SUCCESS(rv, rv); 1.1874 + 1.1875 + rv = dl->SetState(nsIDownloadManager::DOWNLOAD_QUEUED); 1.1876 + NS_ENSURE_SUCCESS(rv, rv); 1.1877 + 1.1878 + // Creates a cycle that will be broken when the download finishes 1.1879 + dl->mCancelable = wbp; 1.1880 + (void)wbp->SetProgressListener(dl); 1.1881 + 1.1882 + rv = wbp->SavePrivacyAwareURI(dl->mSource, nullptr, nullptr, nullptr, nullptr, 1.1883 + dl->mTarget, dl->mPrivate); 1.1884 + if (NS_FAILED(rv)) { 1.1885 + dl->mCancelable = nullptr; 1.1886 + (void)wbp->SetProgressListener(nullptr); 1.1887 + return rv; 1.1888 + } 1.1889 + 1.1890 + return NS_OK; 1.1891 +} 1.1892 + 1.1893 +static nsresult 1.1894 +RemoveDownloadByGUID(const nsACString& aGUID, mozIStorageConnection* aDBConn) 1.1895 +{ 1.1896 + nsCOMPtr<mozIStorageStatement> stmt; 1.1897 + nsresult rv = aDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.1898 + "DELETE FROM moz_downloads " 1.1899 + "WHERE guid = :guid"), getter_AddRefs(stmt)); 1.1900 + NS_ENSURE_SUCCESS(rv, rv); 1.1901 + 1.1902 + rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("guid"), aGUID); 1.1903 + NS_ENSURE_SUCCESS(rv, rv); 1.1904 + 1.1905 + rv = stmt->Execute(); 1.1906 + NS_ENSURE_SUCCESS(rv, rv); 1.1907 + 1.1908 + return NS_OK; 1.1909 +} 1.1910 + 1.1911 +nsresult 1.1912 +nsDownloadManager::RemoveDownload(const nsACString& aGUID) 1.1913 +{ 1.1914 + nsRefPtr<nsDownload> dl = FindDownload(aGUID); 1.1915 + MOZ_ASSERT(!dl, "Can't call RemoveDownload on a download in progress!"); 1.1916 + if (dl) 1.1917 + return NS_ERROR_FAILURE; 1.1918 + 1.1919 + nsresult rv = GetDownloadFromDB(aGUID, getter_AddRefs(dl)); 1.1920 + NS_ENSURE_SUCCESS(rv, rv); 1.1921 + 1.1922 + if (dl->mPrivate) { 1.1923 + RemoveDownloadByGUID(aGUID, mPrivateDBConn); 1.1924 + } else { 1.1925 + RemoveDownloadByGUID(aGUID, mDBConn); 1.1926 + } 1.1927 + 1.1928 + return NotifyDownloadRemoval(dl); 1.1929 +} 1.1930 + 1.1931 +NS_IMETHODIMP 1.1932 +nsDownloadManager::RemoveDownload(uint32_t aID) 1.1933 +{ 1.1934 + NS_ENSURE_STATE(!mUseJSTransfer); 1.1935 + 1.1936 + NS_WARNING("Using integer IDs without compat mode enabled"); 1.1937 + 1.1938 + nsRefPtr<nsDownload> dl = FindDownload(aID); 1.1939 + MOZ_ASSERT(!dl, "Can't call RemoveDownload on a download in progress!"); 1.1940 + if (dl) 1.1941 + return NS_ERROR_FAILURE; 1.1942 + 1.1943 + nsresult rv = GetDownloadFromDB(aID, getter_AddRefs(dl)); 1.1944 + NS_ENSURE_SUCCESS(rv, rv); 1.1945 + 1.1946 + nsCOMPtr<mozIStorageStatement> stmt; 1.1947 + rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.1948 + "DELETE FROM moz_downloads " 1.1949 + "WHERE id = :id"), getter_AddRefs(stmt)); 1.1950 + NS_ENSURE_SUCCESS(rv, rv); 1.1951 + 1.1952 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("id"), aID); // unsigned; 64-bit to prevent overflow 1.1953 + NS_ENSURE_SUCCESS(rv, rv); 1.1954 + 1.1955 + rv = stmt->Execute(); 1.1956 + NS_ENSURE_SUCCESS(rv, rv); 1.1957 + 1.1958 + // Notify the UI with the topic and download id 1.1959 + return NotifyDownloadRemoval(dl); 1.1960 +} 1.1961 + 1.1962 +nsresult 1.1963 +nsDownloadManager::NotifyDownloadRemoval(nsDownload* aRemoved) 1.1964 +{ 1.1965 + nsCOMPtr<nsISupportsPRUint32> id; 1.1966 + nsCOMPtr<nsISupportsCString> guid; 1.1967 + nsresult rv; 1.1968 + 1.1969 + // Only send an integer ID notification if the download is public. 1.1970 + bool sendDeprecatedNotification = !(aRemoved && aRemoved->mPrivate); 1.1971 + 1.1972 + if (sendDeprecatedNotification && aRemoved) { 1.1973 + id = do_CreateInstance(NS_SUPPORTS_PRUINT32_CONTRACTID, &rv); 1.1974 + NS_ENSURE_SUCCESS(rv, rv); 1.1975 + uint32_t dlID; 1.1976 + rv = aRemoved->GetId(&dlID); 1.1977 + NS_ENSURE_SUCCESS(rv, rv); 1.1978 + rv = id->SetData(dlID); 1.1979 + NS_ENSURE_SUCCESS(rv, rv); 1.1980 + } 1.1981 + 1.1982 + if (sendDeprecatedNotification) { 1.1983 + mObserverService->NotifyObservers(id, 1.1984 + "download-manager-remove-download", 1.1985 + nullptr); 1.1986 + } 1.1987 + 1.1988 + if (aRemoved) { 1.1989 + guid = do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID, &rv); 1.1990 + NS_ENSURE_SUCCESS(rv, rv); 1.1991 + nsAutoCString guidStr; 1.1992 + rv = aRemoved->GetGuid(guidStr); 1.1993 + NS_ENSURE_SUCCESS(rv, rv); 1.1994 + rv = guid->SetData(guidStr); 1.1995 + NS_ENSURE_SUCCESS(rv, rv); 1.1996 + } 1.1997 + 1.1998 + mObserverService->NotifyObservers(guid, 1.1999 + "download-manager-remove-download-guid", 1.2000 + nullptr); 1.2001 + return NS_OK; 1.2002 +} 1.2003 + 1.2004 +static nsresult 1.2005 +DoRemoveDownloadsByTimeframe(mozIStorageConnection* aDBConn, 1.2006 + int64_t aStartTime, 1.2007 + int64_t aEndTime) 1.2008 +{ 1.2009 + nsCOMPtr<mozIStorageStatement> stmt; 1.2010 + nsresult rv = aDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.2011 + "DELETE FROM moz_downloads " 1.2012 + "WHERE startTime >= :startTime " 1.2013 + "AND startTime <= :endTime " 1.2014 + "AND state NOT IN (:downloading, :paused, :queued)"), getter_AddRefs(stmt)); 1.2015 + NS_ENSURE_SUCCESS(rv, rv); 1.2016 + 1.2017 + // Bind the times 1.2018 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("startTime"), aStartTime); 1.2019 + NS_ENSURE_SUCCESS(rv, rv); 1.2020 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("endTime"), aEndTime); 1.2021 + NS_ENSURE_SUCCESS(rv, rv); 1.2022 + 1.2023 + // Bind the active states 1.2024 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("downloading"), nsIDownloadManager::DOWNLOAD_DOWNLOADING); 1.2025 + NS_ENSURE_SUCCESS(rv, rv); 1.2026 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("paused"), nsIDownloadManager::DOWNLOAD_PAUSED); 1.2027 + NS_ENSURE_SUCCESS(rv, rv); 1.2028 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("queued"), nsIDownloadManager::DOWNLOAD_QUEUED); 1.2029 + NS_ENSURE_SUCCESS(rv, rv); 1.2030 + 1.2031 + // Execute 1.2032 + rv = stmt->Execute(); 1.2033 + NS_ENSURE_SUCCESS(rv, rv); 1.2034 + 1.2035 + return NS_OK; 1.2036 +} 1.2037 + 1.2038 +NS_IMETHODIMP 1.2039 +nsDownloadManager::RemoveDownloadsByTimeframe(int64_t aStartTime, 1.2040 + int64_t aEndTime) 1.2041 +{ 1.2042 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2043 + 1.2044 + nsresult rv = DoRemoveDownloadsByTimeframe(mDBConn, aStartTime, aEndTime); 1.2045 + nsresult rv2 = DoRemoveDownloadsByTimeframe(mPrivateDBConn, aStartTime, aEndTime); 1.2046 + NS_ENSURE_SUCCESS(rv, rv); 1.2047 + NS_ENSURE_SUCCESS(rv2, rv2); 1.2048 + 1.2049 + // Notify the UI with the topic and null subject to indicate "remove multiple" 1.2050 + return NotifyDownloadRemoval(nullptr); 1.2051 +} 1.2052 + 1.2053 +NS_IMETHODIMP 1.2054 +nsDownloadManager::CleanUp() 1.2055 +{ 1.2056 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2057 + 1.2058 + return CleanUp(mDBConn); 1.2059 +} 1.2060 + 1.2061 +NS_IMETHODIMP 1.2062 +nsDownloadManager::CleanUpPrivate() 1.2063 +{ 1.2064 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2065 + 1.2066 + return CleanUp(mPrivateDBConn); 1.2067 +} 1.2068 + 1.2069 +nsresult 1.2070 +nsDownloadManager::CleanUp(mozIStorageConnection* aDBConn) 1.2071 +{ 1.2072 + DownloadState states[] = { nsIDownloadManager::DOWNLOAD_FINISHED, 1.2073 + nsIDownloadManager::DOWNLOAD_FAILED, 1.2074 + nsIDownloadManager::DOWNLOAD_CANCELED, 1.2075 + nsIDownloadManager::DOWNLOAD_BLOCKED_PARENTAL, 1.2076 + nsIDownloadManager::DOWNLOAD_BLOCKED_POLICY, 1.2077 + nsIDownloadManager::DOWNLOAD_DIRTY }; 1.2078 + 1.2079 + nsCOMPtr<mozIStorageStatement> stmt; 1.2080 + nsresult rv = aDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.2081 + "DELETE FROM moz_downloads " 1.2082 + "WHERE state = ? " 1.2083 + "OR state = ? " 1.2084 + "OR state = ? " 1.2085 + "OR state = ? " 1.2086 + "OR state = ? " 1.2087 + "OR state = ?"), getter_AddRefs(stmt)); 1.2088 + NS_ENSURE_SUCCESS(rv, rv); 1.2089 + for (uint32_t i = 0; i < ArrayLength(states); ++i) { 1.2090 + rv = stmt->BindInt32ByIndex(i, states[i]); 1.2091 + NS_ENSURE_SUCCESS(rv, rv); 1.2092 + } 1.2093 + 1.2094 + rv = stmt->Execute(); 1.2095 + NS_ENSURE_SUCCESS(rv, rv); 1.2096 + 1.2097 + // Notify the UI with the topic and null subject to indicate "remove multiple" 1.2098 + return NotifyDownloadRemoval(nullptr); 1.2099 +} 1.2100 + 1.2101 +static nsresult 1.2102 +DoGetCanCleanUp(mozIStorageConnection* aDBConn, bool *aResult) 1.2103 +{ 1.2104 + // This method should never return anything but NS_OK for the benefit of 1.2105 + // unwitting consumers. 1.2106 + 1.2107 + *aResult = false; 1.2108 + 1.2109 + DownloadState states[] = { nsIDownloadManager::DOWNLOAD_FINISHED, 1.2110 + nsIDownloadManager::DOWNLOAD_FAILED, 1.2111 + nsIDownloadManager::DOWNLOAD_CANCELED, 1.2112 + nsIDownloadManager::DOWNLOAD_BLOCKED_PARENTAL, 1.2113 + nsIDownloadManager::DOWNLOAD_BLOCKED_POLICY, 1.2114 + nsIDownloadManager::DOWNLOAD_DIRTY }; 1.2115 + 1.2116 + nsCOMPtr<mozIStorageStatement> stmt; 1.2117 + nsresult rv = aDBConn->CreateStatement(NS_LITERAL_CSTRING( 1.2118 + "SELECT COUNT(*) " 1.2119 + "FROM moz_downloads " 1.2120 + "WHERE state = ? " 1.2121 + "OR state = ? " 1.2122 + "OR state = ? " 1.2123 + "OR state = ? " 1.2124 + "OR state = ? " 1.2125 + "OR state = ?"), getter_AddRefs(stmt)); 1.2126 + NS_ENSURE_SUCCESS(rv, NS_OK); 1.2127 + for (uint32_t i = 0; i < ArrayLength(states); ++i) { 1.2128 + rv = stmt->BindInt32ByIndex(i, states[i]); 1.2129 + NS_ENSURE_SUCCESS(rv, NS_OK); 1.2130 + } 1.2131 + 1.2132 + bool moreResults; // We don't really care... 1.2133 + rv = stmt->ExecuteStep(&moreResults); 1.2134 + NS_ENSURE_SUCCESS(rv, NS_OK); 1.2135 + 1.2136 + int32_t count; 1.2137 + rv = stmt->GetInt32(0, &count); 1.2138 + NS_ENSURE_SUCCESS(rv, NS_OK); 1.2139 + 1.2140 + if (count > 0) 1.2141 + *aResult = true; 1.2142 + 1.2143 + return NS_OK; 1.2144 +} 1.2145 + 1.2146 +NS_IMETHODIMP 1.2147 +nsDownloadManager::GetCanCleanUp(bool *aResult) 1.2148 +{ 1.2149 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2150 + 1.2151 + return DoGetCanCleanUp(mDBConn, aResult); 1.2152 +} 1.2153 + 1.2154 +NS_IMETHODIMP 1.2155 +nsDownloadManager::GetCanCleanUpPrivate(bool *aResult) 1.2156 +{ 1.2157 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2158 + 1.2159 + return DoGetCanCleanUp(mPrivateDBConn, aResult); 1.2160 +} 1.2161 + 1.2162 +NS_IMETHODIMP 1.2163 +nsDownloadManager::PauseDownload(uint32_t aID) 1.2164 +{ 1.2165 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2166 + 1.2167 + NS_WARNING("Using integer IDs without compat mode enabled"); 1.2168 + 1.2169 + nsDownload *dl = FindDownload(aID); 1.2170 + if (!dl) 1.2171 + return NS_ERROR_FAILURE; 1.2172 + 1.2173 + return dl->Pause(); 1.2174 +} 1.2175 + 1.2176 +NS_IMETHODIMP 1.2177 +nsDownloadManager::ResumeDownload(uint32_t aID) 1.2178 +{ 1.2179 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2180 + 1.2181 + NS_WARNING("Using integer IDs without compat mode enabled"); 1.2182 + 1.2183 + nsDownload *dl = FindDownload(aID); 1.2184 + if (!dl) 1.2185 + return NS_ERROR_FAILURE; 1.2186 + 1.2187 + return dl->Resume(); 1.2188 +} 1.2189 + 1.2190 +NS_IMETHODIMP 1.2191 +nsDownloadManager::GetDBConnection(mozIStorageConnection **aDBConn) 1.2192 +{ 1.2193 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2194 + 1.2195 + NS_ADDREF(*aDBConn = mDBConn); 1.2196 + 1.2197 + return NS_OK; 1.2198 +} 1.2199 + 1.2200 +NS_IMETHODIMP 1.2201 +nsDownloadManager::GetPrivateDBConnection(mozIStorageConnection **aDBConn) 1.2202 +{ 1.2203 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2204 + 1.2205 + NS_ADDREF(*aDBConn = mPrivateDBConn); 1.2206 + 1.2207 + return NS_OK; 1.2208 + } 1.2209 + 1.2210 +NS_IMETHODIMP 1.2211 +nsDownloadManager::AddListener(nsIDownloadProgressListener *aListener) 1.2212 +{ 1.2213 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2214 + 1.2215 + mListeners.AppendObject(aListener); 1.2216 + return NS_OK; 1.2217 +} 1.2218 + 1.2219 +NS_IMETHODIMP 1.2220 +nsDownloadManager::AddPrivacyAwareListener(nsIDownloadProgressListener *aListener) 1.2221 +{ 1.2222 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2223 + 1.2224 + mPrivacyAwareListeners.AppendObject(aListener); 1.2225 + return NS_OK; 1.2226 +} 1.2227 + 1.2228 +NS_IMETHODIMP 1.2229 +nsDownloadManager::RemoveListener(nsIDownloadProgressListener *aListener) 1.2230 +{ 1.2231 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2232 + 1.2233 + mListeners.RemoveObject(aListener); 1.2234 + mPrivacyAwareListeners.RemoveObject(aListener); 1.2235 + return NS_OK; 1.2236 +} 1.2237 + 1.2238 +void 1.2239 +nsDownloadManager::NotifyListenersOnDownloadStateChange(int16_t aOldState, 1.2240 + nsDownload *aDownload) 1.2241 +{ 1.2242 + for (int32_t i = mPrivacyAwareListeners.Count() - 1; i >= 0; --i) { 1.2243 + mPrivacyAwareListeners[i]->OnDownloadStateChange(aOldState, aDownload); 1.2244 + } 1.2245 + 1.2246 + // Only privacy-aware listeners should receive notifications about private 1.2247 + // downloads, while non-privacy-aware listeners receive no sign they exist. 1.2248 + if (aDownload->mPrivate) { 1.2249 + return; 1.2250 + } 1.2251 + 1.2252 + for (int32_t i = mListeners.Count() - 1; i >= 0; --i) { 1.2253 + mListeners[i]->OnDownloadStateChange(aOldState, aDownload); 1.2254 + } 1.2255 +} 1.2256 + 1.2257 +void 1.2258 +nsDownloadManager::NotifyListenersOnProgressChange(nsIWebProgress *aProgress, 1.2259 + nsIRequest *aRequest, 1.2260 + int64_t aCurSelfProgress, 1.2261 + int64_t aMaxSelfProgress, 1.2262 + int64_t aCurTotalProgress, 1.2263 + int64_t aMaxTotalProgress, 1.2264 + nsDownload *aDownload) 1.2265 +{ 1.2266 + for (int32_t i = mPrivacyAwareListeners.Count() - 1; i >= 0; --i) { 1.2267 + mPrivacyAwareListeners[i]->OnProgressChange(aProgress, aRequest, aCurSelfProgress, 1.2268 + aMaxSelfProgress, aCurTotalProgress, 1.2269 + aMaxTotalProgress, aDownload); 1.2270 + } 1.2271 + 1.2272 + // Only privacy-aware listeners should receive notifications about private 1.2273 + // downloads, while non-privacy-aware listeners receive no sign they exist. 1.2274 + if (aDownload->mPrivate) { 1.2275 + return; 1.2276 + } 1.2277 + 1.2278 + for (int32_t i = mListeners.Count() - 1; i >= 0; --i) { 1.2279 + mListeners[i]->OnProgressChange(aProgress, aRequest, aCurSelfProgress, 1.2280 + aMaxSelfProgress, aCurTotalProgress, 1.2281 + aMaxTotalProgress, aDownload); 1.2282 + } 1.2283 +} 1.2284 + 1.2285 +void 1.2286 +nsDownloadManager::NotifyListenersOnStateChange(nsIWebProgress *aProgress, 1.2287 + nsIRequest *aRequest, 1.2288 + uint32_t aStateFlags, 1.2289 + nsresult aStatus, 1.2290 + nsDownload *aDownload) 1.2291 +{ 1.2292 + for (int32_t i = mPrivacyAwareListeners.Count() - 1; i >= 0; --i) { 1.2293 + mPrivacyAwareListeners[i]->OnStateChange(aProgress, aRequest, aStateFlags, aStatus, 1.2294 + aDownload); 1.2295 + } 1.2296 + 1.2297 + // Only privacy-aware listeners should receive notifications about private 1.2298 + // downloads, while non-privacy-aware listeners receive no sign they exist. 1.2299 + if (aDownload->mPrivate) { 1.2300 + return; 1.2301 + } 1.2302 + 1.2303 + for (int32_t i = mListeners.Count() - 1; i >= 0; --i) { 1.2304 + mListeners[i]->OnStateChange(aProgress, aRequest, aStateFlags, aStatus, 1.2305 + aDownload); 1.2306 + } 1.2307 +} 1.2308 + 1.2309 +//////////////////////////////////////////////////////////////////////////////// 1.2310 +//// nsINavHistoryObserver 1.2311 + 1.2312 +NS_IMETHODIMP 1.2313 +nsDownloadManager::OnBeginUpdateBatch() 1.2314 +{ 1.2315 + // This method in not normally invoked when mUseJSTransfer is enabled, however 1.2316 + // we provide an extra check in case it is called manually by add-ons. 1.2317 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2318 + 1.2319 + // We already have a transaction, so don't make another 1.2320 + if (mHistoryTransaction) 1.2321 + return NS_OK; 1.2322 + 1.2323 + // Start a transaction that commits when deleted 1.2324 + mHistoryTransaction = new mozStorageTransaction(mDBConn, true); 1.2325 + 1.2326 + return NS_OK; 1.2327 +} 1.2328 + 1.2329 +NS_IMETHODIMP 1.2330 +nsDownloadManager::OnEndUpdateBatch() 1.2331 +{ 1.2332 + // Get rid of the transaction and cause it to commit 1.2333 + mHistoryTransaction = nullptr; 1.2334 + 1.2335 + return NS_OK; 1.2336 +} 1.2337 + 1.2338 +NS_IMETHODIMP 1.2339 +nsDownloadManager::OnVisit(nsIURI *aURI, int64_t aVisitID, PRTime aTime, 1.2340 + int64_t aSessionID, int64_t aReferringID, 1.2341 + uint32_t aTransitionType, const nsACString& aGUID, 1.2342 + bool aHidden) 1.2343 +{ 1.2344 + return NS_OK; 1.2345 +} 1.2346 + 1.2347 +NS_IMETHODIMP 1.2348 +nsDownloadManager::OnTitleChanged(nsIURI *aURI, 1.2349 + const nsAString &aPageTitle, 1.2350 + const nsACString &aGUID) 1.2351 +{ 1.2352 + return NS_OK; 1.2353 +} 1.2354 + 1.2355 +NS_IMETHODIMP 1.2356 +nsDownloadManager::OnFrecencyChanged(nsIURI* aURI, 1.2357 + int32_t aNewFrecency, 1.2358 + const nsACString& aGUID, 1.2359 + bool aHidden, 1.2360 + PRTime aLastVisitDate) 1.2361 +{ 1.2362 + return NS_OK; 1.2363 +} 1.2364 + 1.2365 +NS_IMETHODIMP 1.2366 +nsDownloadManager::OnManyFrecenciesChanged() 1.2367 +{ 1.2368 + return NS_OK; 1.2369 +} 1.2370 + 1.2371 +NS_IMETHODIMP 1.2372 +nsDownloadManager::OnDeleteURI(nsIURI *aURI, 1.2373 + const nsACString& aGUID, 1.2374 + uint16_t aReason) 1.2375 +{ 1.2376 + // This method in not normally invoked when mUseJSTransfer is enabled, however 1.2377 + // we provide an extra check in case it is called manually by add-ons. 1.2378 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2379 + 1.2380 + nsresult rv = RemoveDownloadsForURI(mGetIdsForURIStatement, aURI); 1.2381 + nsresult rv2 = RemoveDownloadsForURI(mGetPrivateIdsForURIStatement, aURI); 1.2382 + NS_ENSURE_SUCCESS(rv, rv); 1.2383 + NS_ENSURE_SUCCESS(rv2, rv2); 1.2384 + return NS_OK; 1.2385 +} 1.2386 + 1.2387 +NS_IMETHODIMP 1.2388 +nsDownloadManager::OnClearHistory() 1.2389 +{ 1.2390 + return CleanUp(); 1.2391 +} 1.2392 + 1.2393 +NS_IMETHODIMP 1.2394 +nsDownloadManager::OnPageChanged(nsIURI *aURI, 1.2395 + uint32_t aChangedAttribute, 1.2396 + const nsAString& aNewValue, 1.2397 + const nsACString &aGUID) 1.2398 +{ 1.2399 + return NS_OK; 1.2400 +} 1.2401 + 1.2402 +NS_IMETHODIMP 1.2403 +nsDownloadManager::OnDeleteVisits(nsIURI *aURI, PRTime aVisitTime, 1.2404 + const nsACString& aGUID, 1.2405 + uint16_t aReason, uint32_t aTransitionType) 1.2406 +{ 1.2407 + // Don't bother removing downloads until the page is removed. 1.2408 + return NS_OK; 1.2409 +} 1.2410 + 1.2411 +//////////////////////////////////////////////////////////////////////////////// 1.2412 +//// nsIObserver 1.2413 + 1.2414 +NS_IMETHODIMP 1.2415 +nsDownloadManager::Observe(nsISupports *aSubject, 1.2416 + const char *aTopic, 1.2417 + const char16_t *aData) 1.2418 +{ 1.2419 + // This method in not normally invoked when mUseJSTransfer is enabled, however 1.2420 + // we provide an extra check in case it is called manually by add-ons. 1.2421 + NS_ENSURE_STATE(!mUseJSTransfer); 1.2422 + 1.2423 + // We need to count the active public downloads that could be lost 1.2424 + // by quitting, and add any active private ones as well, since per-window 1.2425 + // private browsing may be active. 1.2426 + int32_t currDownloadCount = mCurrentDownloads.Count(); 1.2427 + 1.2428 + // If we don't need to cancel all the downloads on quit, only count the ones 1.2429 + // that aren't resumable. 1.2430 + if (GetQuitBehavior() != QUIT_AND_CANCEL) { 1.2431 + for (int32_t i = currDownloadCount - 1; i >= 0; --i) { 1.2432 + if (mCurrentDownloads[i]->IsResumable()) { 1.2433 + currDownloadCount--; 1.2434 + } 1.2435 + } 1.2436 + 1.2437 + // We have a count of the public, non-resumable downloads. Now we need 1.2438 + // to add the total number of private downloads, since they are in danger 1.2439 + // of being lost. 1.2440 + currDownloadCount += mCurrentPrivateDownloads.Count(); 1.2441 + } 1.2442 + 1.2443 + nsresult rv; 1.2444 + if (strcmp(aTopic, "oncancel") == 0) { 1.2445 + nsCOMPtr<nsIDownload> dl = do_QueryInterface(aSubject, &rv); 1.2446 + NS_ENSURE_SUCCESS(rv, rv); 1.2447 + 1.2448 + dl->Cancel(); 1.2449 + } else if (strcmp(aTopic, "profile-before-change") == 0) { 1.2450 + CloseAllDBs(); 1.2451 + } else if (strcmp(aTopic, "quit-application") == 0) { 1.2452 + // Try to pause all downloads and, if appropriate, mark them as auto-resume 1.2453 + // unless user has specified that downloads should be canceled 1.2454 + enum QuitBehavior behavior = GetQuitBehavior(); 1.2455 + if (behavior != QUIT_AND_CANCEL) 1.2456 + (void)PauseAllDownloads(bool(behavior != QUIT_AND_PAUSE)); 1.2457 + 1.2458 + // Remove downloads to break cycles and cancel downloads 1.2459 + (void)RemoveAllDownloads(); 1.2460 + 1.2461 + // Now that active downloads have been canceled, remove all completed or 1.2462 + // aborted downloads if the user's retention policy specifies it. 1.2463 + if (GetRetentionBehavior() == 1) 1.2464 + CleanUp(); 1.2465 + } else if (strcmp(aTopic, "quit-application-requested") == 0 && 1.2466 + currDownloadCount) { 1.2467 + nsCOMPtr<nsISupportsPRBool> cancelDownloads = 1.2468 + do_QueryInterface(aSubject, &rv); 1.2469 + NS_ENSURE_SUCCESS(rv, rv); 1.2470 +#ifndef XP_MACOSX 1.2471 + ConfirmCancelDownloads(currDownloadCount, cancelDownloads, 1.2472 + MOZ_UTF16("quitCancelDownloadsAlertTitle"), 1.2473 + MOZ_UTF16("quitCancelDownloadsAlertMsgMultiple"), 1.2474 + MOZ_UTF16("quitCancelDownloadsAlertMsg"), 1.2475 + MOZ_UTF16("dontQuitButtonWin")); 1.2476 +#else 1.2477 + ConfirmCancelDownloads(currDownloadCount, cancelDownloads, 1.2478 + MOZ_UTF16("quitCancelDownloadsAlertTitle"), 1.2479 + MOZ_UTF16("quitCancelDownloadsAlertMsgMacMultiple"), 1.2480 + MOZ_UTF16("quitCancelDownloadsAlertMsgMac"), 1.2481 + MOZ_UTF16("dontQuitButtonMac")); 1.2482 +#endif 1.2483 + } else if (strcmp(aTopic, "offline-requested") == 0 && currDownloadCount) { 1.2484 + nsCOMPtr<nsISupportsPRBool> cancelDownloads = 1.2485 + do_QueryInterface(aSubject, &rv); 1.2486 + NS_ENSURE_SUCCESS(rv, rv); 1.2487 + ConfirmCancelDownloads(currDownloadCount, cancelDownloads, 1.2488 + MOZ_UTF16("offlineCancelDownloadsAlertTitle"), 1.2489 + MOZ_UTF16("offlineCancelDownloadsAlertMsgMultiple"), 1.2490 + MOZ_UTF16("offlineCancelDownloadsAlertMsg"), 1.2491 + MOZ_UTF16("dontGoOfflineButton")); 1.2492 + } 1.2493 + else if (strcmp(aTopic, NS_IOSERVICE_GOING_OFFLINE_TOPIC) == 0) { 1.2494 + // Pause all downloads, and mark them to auto-resume. 1.2495 + (void)PauseAllDownloads(true); 1.2496 + } 1.2497 + else if (strcmp(aTopic, NS_IOSERVICE_OFFLINE_STATUS_TOPIC) == 0 && 1.2498 + nsDependentString(aData).EqualsLiteral(NS_IOSERVICE_ONLINE)) { 1.2499 + // We can now resume all downloads that are supposed to auto-resume. 1.2500 + (void)ResumeAllDownloads(false); 1.2501 + } 1.2502 + else if (strcmp(aTopic, "alertclickcallback") == 0) { 1.2503 + nsCOMPtr<nsIDownloadManagerUI> dmui = 1.2504 + do_GetService("@mozilla.org/download-manager-ui;1", &rv); 1.2505 + NS_ENSURE_SUCCESS(rv, rv); 1.2506 + return dmui->Show(nullptr, nullptr, nsIDownloadManagerUI::REASON_USER_INTERACTED, 1.2507 + aData && NS_strcmp(aData, MOZ_UTF16("private")) == 0); 1.2508 + } else if (strcmp(aTopic, "sleep_notification") == 0 || 1.2509 + strcmp(aTopic, "suspend_process_notification") == 0) { 1.2510 + // Pause downloads if we're sleeping, and mark the downloads as auto-resume 1.2511 + (void)PauseAllDownloads(true); 1.2512 + } else if (strcmp(aTopic, "wake_notification") == 0 || 1.2513 + strcmp(aTopic, "resume_process_notification") == 0) { 1.2514 + int32_t resumeOnWakeDelay = 10000; 1.2515 + nsCOMPtr<nsIPrefBranch> pref = do_GetService(NS_PREFSERVICE_CONTRACTID); 1.2516 + if (pref) 1.2517 + (void)pref->GetIntPref(PREF_BDM_RESUMEONWAKEDELAY, &resumeOnWakeDelay); 1.2518 + 1.2519 + // Wait a little bit before trying to resume to avoid resuming when network 1.2520 + // connections haven't restarted yet 1.2521 + mResumeOnWakeTimer = do_CreateInstance("@mozilla.org/timer;1"); 1.2522 + if (resumeOnWakeDelay >= 0 && mResumeOnWakeTimer) { 1.2523 + (void)mResumeOnWakeTimer->InitWithFuncCallback(ResumeOnWakeCallback, 1.2524 + this, resumeOnWakeDelay, nsITimer::TYPE_ONE_SHOT); 1.2525 + } 1.2526 + } else if (strcmp(aTopic, "last-pb-context-exited") == 0) { 1.2527 + // Upon leaving private browsing mode, cancel all private downloads, 1.2528 + // remove all trace of them, and then blow away the private database 1.2529 + // and recreate a blank one. 1.2530 + RemoveAllDownloads(mCurrentPrivateDownloads); 1.2531 + InitPrivateDB(); 1.2532 + } else if (strcmp(aTopic, "last-pb-context-exiting") == 0) { 1.2533 + // If there are active private downloads, prompt the user to confirm leaving 1.2534 + // private browsing mode (thereby cancelling them). Otherwise, silently proceed. 1.2535 + if (!mCurrentPrivateDownloads.Count()) 1.2536 + return NS_OK; 1.2537 + 1.2538 + nsCOMPtr<nsISupportsPRBool> cancelDownloads = do_QueryInterface(aSubject, &rv); 1.2539 + NS_ENSURE_SUCCESS(rv, rv); 1.2540 + 1.2541 + ConfirmCancelDownloads(mCurrentPrivateDownloads.Count(), cancelDownloads, 1.2542 + MOZ_UTF16("leavePrivateBrowsingCancelDownloadsAlertTitle"), 1.2543 + MOZ_UTF16("leavePrivateBrowsingWindowsCancelDownloadsAlertMsgMultiple"), 1.2544 + MOZ_UTF16("leavePrivateBrowsingWindowsCancelDownloadsAlertMsg"), 1.2545 + MOZ_UTF16("dontLeavePrivateBrowsingButton")); 1.2546 + } 1.2547 + 1.2548 + return NS_OK; 1.2549 +} 1.2550 + 1.2551 +void 1.2552 +nsDownloadManager::ConfirmCancelDownloads(int32_t aCount, 1.2553 + nsISupportsPRBool *aCancelDownloads, 1.2554 + const char16_t *aTitle, 1.2555 + const char16_t *aCancelMessageMultiple, 1.2556 + const char16_t *aCancelMessageSingle, 1.2557 + const char16_t *aDontCancelButton) 1.2558 +{ 1.2559 + // If user has already dismissed quit request, then do nothing 1.2560 + bool quitRequestCancelled = false; 1.2561 + aCancelDownloads->GetData(&quitRequestCancelled); 1.2562 + if (quitRequestCancelled) 1.2563 + return; 1.2564 + 1.2565 + nsXPIDLString title, message, quitButton, dontQuitButton; 1.2566 + 1.2567 + mBundle->GetStringFromName(aTitle, getter_Copies(title)); 1.2568 + 1.2569 + nsAutoString countString; 1.2570 + countString.AppendInt(aCount); 1.2571 + const char16_t *strings[1] = { countString.get() }; 1.2572 + if (aCount > 1) { 1.2573 + mBundle->FormatStringFromName(aCancelMessageMultiple, strings, 1, 1.2574 + getter_Copies(message)); 1.2575 + mBundle->FormatStringFromName(MOZ_UTF16("cancelDownloadsOKTextMultiple"), 1.2576 + strings, 1, getter_Copies(quitButton)); 1.2577 + } else { 1.2578 + mBundle->GetStringFromName(aCancelMessageSingle, getter_Copies(message)); 1.2579 + mBundle->GetStringFromName(MOZ_UTF16("cancelDownloadsOKText"), 1.2580 + getter_Copies(quitButton)); 1.2581 + } 1.2582 + 1.2583 + mBundle->GetStringFromName(aDontCancelButton, getter_Copies(dontQuitButton)); 1.2584 + 1.2585 + // Get Download Manager window, to be parent of alert. 1.2586 + nsCOMPtr<nsIWindowMediator> wm = do_GetService(NS_WINDOWMEDIATOR_CONTRACTID); 1.2587 + nsCOMPtr<nsIDOMWindow> dmWindow; 1.2588 + if (wm) { 1.2589 + wm->GetMostRecentWindow(MOZ_UTF16("Download:Manager"), 1.2590 + getter_AddRefs(dmWindow)); 1.2591 + } 1.2592 + 1.2593 + // Show alert. 1.2594 + nsCOMPtr<nsIPromptService> prompter(do_GetService(NS_PROMPTSERVICE_CONTRACTID)); 1.2595 + if (prompter) { 1.2596 + int32_t flags = (nsIPromptService::BUTTON_TITLE_IS_STRING * nsIPromptService::BUTTON_POS_0) + (nsIPromptService::BUTTON_TITLE_IS_STRING * nsIPromptService::BUTTON_POS_1); 1.2597 + bool nothing = false; 1.2598 + int32_t button; 1.2599 + prompter->ConfirmEx(dmWindow, title, message, flags, quitButton.get(), dontQuitButton.get(), nullptr, nullptr, ¬hing, &button); 1.2600 + 1.2601 + aCancelDownloads->SetData(button == 1); 1.2602 + } 1.2603 +} 1.2604 + 1.2605 +//////////////////////////////////////////////////////////////////////////////// 1.2606 +//// nsDownload 1.2607 + 1.2608 +NS_IMPL_CLASSINFO(nsDownload, nullptr, 0, NS_DOWNLOAD_CID) 1.2609 +NS_IMPL_ISUPPORTS_CI( 1.2610 + nsDownload 1.2611 + , nsIDownload 1.2612 + , nsITransfer 1.2613 + , nsIWebProgressListener 1.2614 + , nsIWebProgressListener2 1.2615 +) 1.2616 + 1.2617 +nsDownload::nsDownload() : mDownloadState(nsIDownloadManager::DOWNLOAD_NOTSTARTED), 1.2618 + mID(0), 1.2619 + mPercentComplete(0), 1.2620 + mCurrBytes(0), 1.2621 + mMaxBytes(-1), 1.2622 + mStartTime(0), 1.2623 + mLastUpdate(PR_Now() - (uint32_t)gUpdateInterval), 1.2624 + mResumedAt(-1), 1.2625 + mSpeed(0), 1.2626 + mHasMultipleFiles(false), 1.2627 + mPrivate(false), 1.2628 + mAutoResume(DONT_RESUME) 1.2629 +{ 1.2630 +} 1.2631 + 1.2632 +nsDownload::~nsDownload() 1.2633 +{ 1.2634 +} 1.2635 + 1.2636 +NS_IMETHODIMP nsDownload::SetSha256Hash(const nsACString& aHash) { 1.2637 + MOZ_ASSERT(NS_IsMainThread(), "Must call SetSha256Hash on main thread"); 1.2638 + // This will be used later to query the application reputation service. 1.2639 + mHash = aHash; 1.2640 + return NS_OK; 1.2641 +} 1.2642 + 1.2643 +NS_IMETHODIMP nsDownload::SetSignatureInfo(nsIArray* aSignatureInfo) { 1.2644 + MOZ_ASSERT(NS_IsMainThread(), "Must call SetSignatureInfo on main thread"); 1.2645 + // This will be used later to query the application reputation service. 1.2646 + mSignatureInfo = aSignatureInfo; 1.2647 + return NS_OK; 1.2648 +} 1.2649 + 1.2650 +#ifdef MOZ_ENABLE_GIO 1.2651 +static void gio_set_metadata_done(GObject *source_obj, GAsyncResult *res, gpointer user_data) 1.2652 +{ 1.2653 + GError *err = nullptr; 1.2654 + g_file_set_attributes_finish(G_FILE(source_obj), res, nullptr, &err); 1.2655 + if (err) { 1.2656 +#ifdef DEBUG 1.2657 + NS_DebugBreak(NS_DEBUG_WARNING, "Set file metadata failed: ", err->message, __FILE__, __LINE__); 1.2658 +#endif 1.2659 + g_error_free(err); 1.2660 + } 1.2661 +} 1.2662 +#endif 1.2663 + 1.2664 +nsresult 1.2665 +nsDownload::SetState(DownloadState aState) 1.2666 +{ 1.2667 + NS_ASSERTION(mDownloadState != aState, 1.2668 + "Trying to set the download state to what it already is set to!"); 1.2669 + 1.2670 + int16_t oldState = mDownloadState; 1.2671 + mDownloadState = aState; 1.2672 + 1.2673 + // We don't want to lose access to our member variables 1.2674 + nsRefPtr<nsDownload> kungFuDeathGrip = this; 1.2675 + 1.2676 + // When the state changed listener is dispatched, queries to the database and 1.2677 + // the download manager api should reflect what the nsIDownload object would 1.2678 + // return. So, if a download is done (finished, canceled, etc.), it should 1.2679 + // first be removed from the current downloads. We will also have to update 1.2680 + // the database *before* notifying listeners. At this point, you can safely 1.2681 + // dispatch to the observers as well. 1.2682 + switch (aState) { 1.2683 + case nsIDownloadManager::DOWNLOAD_BLOCKED_PARENTAL: 1.2684 + case nsIDownloadManager::DOWNLOAD_BLOCKED_POLICY: 1.2685 + case nsIDownloadManager::DOWNLOAD_DIRTY: 1.2686 + case nsIDownloadManager::DOWNLOAD_CANCELED: 1.2687 + case nsIDownloadManager::DOWNLOAD_FAILED: 1.2688 +#ifdef ANDROID 1.2689 + // If we still have a temp file, remove it 1.2690 + bool tempExists; 1.2691 + if (mTempFile && NS_SUCCEEDED(mTempFile->Exists(&tempExists)) && tempExists) { 1.2692 + nsresult rv = mTempFile->Remove(false); 1.2693 + NS_ENSURE_SUCCESS(rv, rv); 1.2694 + } 1.2695 +#endif 1.2696 + 1.2697 + // Transfers are finished, so break the reference cycle 1.2698 + Finalize(); 1.2699 + break; 1.2700 +#ifdef DOWNLOAD_SCANNER 1.2701 + case nsIDownloadManager::DOWNLOAD_SCANNING: 1.2702 + { 1.2703 + nsresult rv = mDownloadManager->mScanner ? mDownloadManager->mScanner->ScanDownload(this) : NS_ERROR_NOT_INITIALIZED; 1.2704 + // If we failed, then fall through to 'download finished' 1.2705 + if (NS_SUCCEEDED(rv)) 1.2706 + break; 1.2707 + mDownloadState = aState = nsIDownloadManager::DOWNLOAD_FINISHED; 1.2708 + } 1.2709 +#endif 1.2710 + case nsIDownloadManager::DOWNLOAD_FINISHED: 1.2711 + { 1.2712 + nsresult rv = ExecuteDesiredAction(); 1.2713 + if (NS_FAILED(rv)) { 1.2714 + // We've failed to execute the desired action. As a result, we should 1.2715 + // fail the download so the user can try again. 1.2716 + (void)FailDownload(rv, nullptr); 1.2717 + return rv; 1.2718 + } 1.2719 + 1.2720 + // Now that we're done with handling the download, clean it up 1.2721 + Finalize(); 1.2722 + 1.2723 + nsCOMPtr<nsIPrefBranch> pref(do_GetService(NS_PREFSERVICE_CONTRACTID)); 1.2724 + 1.2725 + // Master pref to control this function. 1.2726 + bool showTaskbarAlert = true; 1.2727 + if (pref) 1.2728 + pref->GetBoolPref(PREF_BDM_SHOWALERTONCOMPLETE, &showTaskbarAlert); 1.2729 + 1.2730 + if (showTaskbarAlert) { 1.2731 + int32_t alertInterval = 2000; 1.2732 + if (pref) 1.2733 + pref->GetIntPref(PREF_BDM_SHOWALERTINTERVAL, &alertInterval); 1.2734 + 1.2735 + int64_t alertIntervalUSec = alertInterval * PR_USEC_PER_MSEC; 1.2736 + int64_t goat = PR_Now() - mStartTime; 1.2737 + showTaskbarAlert = goat > alertIntervalUSec; 1.2738 + 1.2739 + int32_t size = mPrivate ? 1.2740 + mDownloadManager->mCurrentPrivateDownloads.Count() : 1.2741 + mDownloadManager->mCurrentDownloads.Count(); 1.2742 + if (showTaskbarAlert && size == 0) { 1.2743 + nsCOMPtr<nsIAlertsService> alerts = 1.2744 + do_GetService("@mozilla.org/alerts-service;1"); 1.2745 + if (alerts) { 1.2746 + nsXPIDLString title, message; 1.2747 + 1.2748 + mDownloadManager->mBundle->GetStringFromName( 1.2749 + MOZ_UTF16("downloadsCompleteTitle"), 1.2750 + getter_Copies(title)); 1.2751 + mDownloadManager->mBundle->GetStringFromName( 1.2752 + MOZ_UTF16("downloadsCompleteMsg"), 1.2753 + getter_Copies(message)); 1.2754 + 1.2755 + bool removeWhenDone = 1.2756 + mDownloadManager->GetRetentionBehavior() == 0; 1.2757 + 1.2758 + // If downloads are automatically removed per the user's 1.2759 + // retention policy, there's no reason to make the text clickable 1.2760 + // because if it is, they'll click open the download manager and 1.2761 + // the items they downloaded will have been removed. 1.2762 + alerts->ShowAlertNotification( 1.2763 + NS_LITERAL_STRING(DOWNLOAD_MANAGER_ALERT_ICON), title, 1.2764 + message, !removeWhenDone, 1.2765 + mPrivate ? NS_LITERAL_STRING("private") : NS_LITERAL_STRING("non-private"), 1.2766 + mDownloadManager, EmptyString(), NS_LITERAL_STRING("auto"), 1.2767 + EmptyString(), nullptr); 1.2768 + } 1.2769 + } 1.2770 + } 1.2771 + 1.2772 +#if defined(XP_WIN) || defined(XP_MACOSX) || defined(MOZ_WIDGET_ANDROID) || defined(MOZ_WIDGET_GTK) 1.2773 + nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(mTarget); 1.2774 + nsCOMPtr<nsIFile> file; 1.2775 + nsAutoString path; 1.2776 + 1.2777 + if (fileURL && 1.2778 + NS_SUCCEEDED(fileURL->GetFile(getter_AddRefs(file))) && 1.2779 + file && 1.2780 + NS_SUCCEEDED(file->GetPath(path))) { 1.2781 + 1.2782 +#if defined(XP_WIN) || defined(MOZ_WIDGET_GTK) 1.2783 + // On Windows and Gtk, add the download to the system's "recent documents" 1.2784 + // list, with a pref to disable. 1.2785 + { 1.2786 + bool addToRecentDocs = true; 1.2787 + if (pref) 1.2788 + pref->GetBoolPref(PREF_BDM_ADDTORECENTDOCS, &addToRecentDocs); 1.2789 + 1.2790 + if (addToRecentDocs && !mPrivate) { 1.2791 +#ifdef XP_WIN 1.2792 + ::SHAddToRecentDocs(SHARD_PATHW, path.get()); 1.2793 +#elif defined(MOZ_WIDGET_GTK) 1.2794 + GtkRecentManager* manager = gtk_recent_manager_get_default(); 1.2795 + 1.2796 + gchar* uri = g_filename_to_uri(NS_ConvertUTF16toUTF8(path).get(), 1.2797 + nullptr, nullptr); 1.2798 + if (uri) { 1.2799 + gtk_recent_manager_add_item(manager, uri); 1.2800 + g_free(uri); 1.2801 + } 1.2802 +#endif 1.2803 + } 1.2804 +#ifdef MOZ_ENABLE_GIO 1.2805 + // Use GIO to store the source URI for later display in the file manager. 1.2806 + GFile* gio_file = g_file_new_for_path(NS_ConvertUTF16toUTF8(path).get()); 1.2807 + nsCString source_uri; 1.2808 + mSource->GetSpec(source_uri); 1.2809 + GFileInfo *file_info = g_file_info_new(); 1.2810 + g_file_info_set_attribute_string(file_info, "metadata::download-uri", source_uri.get()); 1.2811 + g_file_set_attributes_async(gio_file, 1.2812 + file_info, 1.2813 + G_FILE_QUERY_INFO_NONE, 1.2814 + G_PRIORITY_DEFAULT, 1.2815 + nullptr, gio_set_metadata_done, nullptr); 1.2816 + g_object_unref(file_info); 1.2817 + g_object_unref(gio_file); 1.2818 +#endif 1.2819 + } 1.2820 +#endif 1.2821 +#ifdef XP_MACOSX 1.2822 + // On OS X, make the downloads stack bounce. 1.2823 + CFStringRef observedObject = ::CFStringCreateWithCString(kCFAllocatorDefault, 1.2824 + NS_ConvertUTF16toUTF8(path).get(), 1.2825 + kCFStringEncodingUTF8); 1.2826 + CFNotificationCenterRef center = ::CFNotificationCenterGetDistributedCenter(); 1.2827 + ::CFNotificationCenterPostNotification(center, CFSTR("com.apple.DownloadFileFinished"), 1.2828 + observedObject, nullptr, TRUE); 1.2829 + ::CFRelease(observedObject); 1.2830 +#endif 1.2831 +#ifdef MOZ_WIDGET_ANDROID 1.2832 + nsCOMPtr<nsIMIMEInfo> mimeInfo; 1.2833 + nsAutoCString contentType; 1.2834 + GetMIMEInfo(getter_AddRefs(mimeInfo)); 1.2835 + 1.2836 + if (mimeInfo) 1.2837 + mimeInfo->GetMIMEType(contentType); 1.2838 + 1.2839 + mozilla::widget::android::GeckoAppShell::ScanMedia(path, NS_ConvertUTF8toUTF16(contentType)); 1.2840 +#endif 1.2841 + } 1.2842 + 1.2843 +#ifdef XP_WIN 1.2844 + // Adjust file attributes so that by default, new files are indexed 1.2845 + // by desktop search services. Skip off those that land in the temp 1.2846 + // folder. 1.2847 + nsCOMPtr<nsIFile> tempDir, fileDir; 1.2848 + rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(tempDir)); 1.2849 + NS_ENSURE_SUCCESS(rv, rv); 1.2850 + (void)file->GetParent(getter_AddRefs(fileDir)); 1.2851 + 1.2852 + bool isTemp = false; 1.2853 + if (fileDir) 1.2854 + (void)fileDir->Equals(tempDir, &isTemp); 1.2855 + 1.2856 + nsCOMPtr<nsILocalFileWin> localFileWin(do_QueryInterface(file)); 1.2857 + if (!isTemp && localFileWin) 1.2858 + (void)localFileWin->SetFileAttributesWin(nsILocalFileWin::WFA_SEARCH_INDEXED); 1.2859 +#endif 1.2860 + 1.2861 +#endif 1.2862 + // Now remove the download if the user's retention policy is "Remove when Done" 1.2863 + if (mDownloadManager->GetRetentionBehavior() == 0) 1.2864 + mDownloadManager->RemoveDownload(mGUID); 1.2865 + } 1.2866 + break; 1.2867 + default: 1.2868 + break; 1.2869 + } 1.2870 + 1.2871 + // Before notifying the listener, we must update the database so that calls 1.2872 + // to it work out properly. 1.2873 + nsresult rv = UpdateDB(); 1.2874 + NS_ENSURE_SUCCESS(rv, rv); 1.2875 + 1.2876 + mDownloadManager->NotifyListenersOnDownloadStateChange(oldState, this); 1.2877 + 1.2878 + switch (mDownloadState) { 1.2879 + case nsIDownloadManager::DOWNLOAD_DOWNLOADING: 1.2880 + // Only send the dl-start event to downloads that are actually starting. 1.2881 + if (oldState == nsIDownloadManager::DOWNLOAD_QUEUED) { 1.2882 + if (!mPrivate) 1.2883 + mDownloadManager->SendEvent(this, "dl-start"); 1.2884 + } 1.2885 + break; 1.2886 + case nsIDownloadManager::DOWNLOAD_FAILED: 1.2887 + if (!mPrivate) 1.2888 + mDownloadManager->SendEvent(this, "dl-failed"); 1.2889 + break; 1.2890 + case nsIDownloadManager::DOWNLOAD_SCANNING: 1.2891 + if (!mPrivate) 1.2892 + mDownloadManager->SendEvent(this, "dl-scanning"); 1.2893 + break; 1.2894 + case nsIDownloadManager::DOWNLOAD_FINISHED: 1.2895 + if (!mPrivate) 1.2896 + mDownloadManager->SendEvent(this, "dl-done"); 1.2897 + break; 1.2898 + case nsIDownloadManager::DOWNLOAD_BLOCKED_PARENTAL: 1.2899 + case nsIDownloadManager::DOWNLOAD_BLOCKED_POLICY: 1.2900 + if (!mPrivate) 1.2901 + mDownloadManager->SendEvent(this, "dl-blocked"); 1.2902 + break; 1.2903 + case nsIDownloadManager::DOWNLOAD_DIRTY: 1.2904 + if (!mPrivate) 1.2905 + mDownloadManager->SendEvent(this, "dl-dirty"); 1.2906 + break; 1.2907 + case nsIDownloadManager::DOWNLOAD_CANCELED: 1.2908 + if (!mPrivate) 1.2909 + mDownloadManager->SendEvent(this, "dl-cancel"); 1.2910 + break; 1.2911 + default: 1.2912 + break; 1.2913 + } 1.2914 + return NS_OK; 1.2915 +} 1.2916 + 1.2917 +//////////////////////////////////////////////////////////////////////////////// 1.2918 +//// nsIWebProgressListener2 1.2919 + 1.2920 +NS_IMETHODIMP 1.2921 +nsDownload::OnProgressChange64(nsIWebProgress *aWebProgress, 1.2922 + nsIRequest *aRequest, 1.2923 + int64_t aCurSelfProgress, 1.2924 + int64_t aMaxSelfProgress, 1.2925 + int64_t aCurTotalProgress, 1.2926 + int64_t aMaxTotalProgress) 1.2927 +{ 1.2928 + if (!mRequest) 1.2929 + mRequest = aRequest; // used for pause/resume 1.2930 + 1.2931 + if (mDownloadState == nsIDownloadManager::DOWNLOAD_QUEUED) { 1.2932 + // Obtain the referrer 1.2933 + nsresult rv; 1.2934 + nsCOMPtr<nsIChannel> channel(do_QueryInterface(aRequest)); 1.2935 + nsCOMPtr<nsIURI> referrer = mReferrer; 1.2936 + if (channel) 1.2937 + (void)NS_GetReferrerFromChannel(channel, getter_AddRefs(mReferrer)); 1.2938 + 1.2939 + // Restore the original referrer if the new one isn't useful 1.2940 + if (!mReferrer) 1.2941 + mReferrer = referrer; 1.2942 + 1.2943 + // If we have a MIME info, we know that exthandler has already added this to 1.2944 + // the history, but if we do not, we'll have to add it ourselves. 1.2945 + if (!mMIMEInfo && !mPrivate) { 1.2946 + nsCOMPtr<nsIDownloadHistory> dh = 1.2947 + do_GetService(NS_DOWNLOADHISTORY_CONTRACTID); 1.2948 + if (dh) 1.2949 + (void)dh->AddDownload(mSource, mReferrer, mStartTime, mTarget); 1.2950 + } 1.2951 + 1.2952 + // Fetch the entityID, but if we can't get it, don't panic (non-resumable) 1.2953 + nsCOMPtr<nsIResumableChannel> resumableChannel(do_QueryInterface(aRequest)); 1.2954 + if (resumableChannel) 1.2955 + (void)resumableChannel->GetEntityID(mEntityID); 1.2956 + 1.2957 + // Before we update the state and dispatch state notifications, we want to 1.2958 + // ensure that we have the correct state for this download with regards to 1.2959 + // its percent completion and size. 1.2960 + SetProgressBytes(0, aMaxTotalProgress); 1.2961 + 1.2962 + // Update the state and the database 1.2963 + rv = SetState(nsIDownloadManager::DOWNLOAD_DOWNLOADING); 1.2964 + NS_ENSURE_SUCCESS(rv, rv); 1.2965 + } 1.2966 + 1.2967 + // filter notifications since they come in so frequently 1.2968 + PRTime now = PR_Now(); 1.2969 + PRIntervalTime delta = now - mLastUpdate; 1.2970 + if (delta < gUpdateInterval) 1.2971 + return NS_OK; 1.2972 + 1.2973 + mLastUpdate = now; 1.2974 + 1.2975 + // Calculate the speed using the elapsed delta time and bytes downloaded 1.2976 + // during that time for more accuracy. 1.2977 + double elapsedSecs = double(delta) / PR_USEC_PER_SEC; 1.2978 + if (elapsedSecs > 0) { 1.2979 + double speed = double(aCurTotalProgress - mCurrBytes) / elapsedSecs; 1.2980 + if (mCurrBytes == 0) { 1.2981 + mSpeed = speed; 1.2982 + } else { 1.2983 + // Calculate 'smoothed average' of 10 readings. 1.2984 + mSpeed = mSpeed * 0.9 + speed * 0.1; 1.2985 + } 1.2986 + } 1.2987 + 1.2988 + SetProgressBytes(aCurTotalProgress, aMaxTotalProgress); 1.2989 + 1.2990 + // Report to the listener our real sizes 1.2991 + int64_t currBytes, maxBytes; 1.2992 + (void)GetAmountTransferred(&currBytes); 1.2993 + (void)GetSize(&maxBytes); 1.2994 + mDownloadManager->NotifyListenersOnProgressChange( 1.2995 + aWebProgress, aRequest, currBytes, maxBytes, currBytes, maxBytes, this); 1.2996 + 1.2997 + // If the maximums are different, then there must be more than one file 1.2998 + if (aMaxSelfProgress != aMaxTotalProgress) 1.2999 + mHasMultipleFiles = true; 1.3000 + 1.3001 + return NS_OK; 1.3002 +} 1.3003 + 1.3004 +NS_IMETHODIMP 1.3005 +nsDownload::OnRefreshAttempted(nsIWebProgress *aWebProgress, 1.3006 + nsIURI *aUri, 1.3007 + int32_t aDelay, 1.3008 + bool aSameUri, 1.3009 + bool *allowRefresh) 1.3010 +{ 1.3011 + *allowRefresh = true; 1.3012 + return NS_OK; 1.3013 +} 1.3014 + 1.3015 +//////////////////////////////////////////////////////////////////////////////// 1.3016 +//// nsIWebProgressListener 1.3017 + 1.3018 +NS_IMETHODIMP 1.3019 +nsDownload::OnProgressChange(nsIWebProgress *aWebProgress, 1.3020 + nsIRequest *aRequest, 1.3021 + int32_t aCurSelfProgress, 1.3022 + int32_t aMaxSelfProgress, 1.3023 + int32_t aCurTotalProgress, 1.3024 + int32_t aMaxTotalProgress) 1.3025 +{ 1.3026 + return OnProgressChange64(aWebProgress, aRequest, 1.3027 + aCurSelfProgress, aMaxSelfProgress, 1.3028 + aCurTotalProgress, aMaxTotalProgress); 1.3029 +} 1.3030 + 1.3031 +NS_IMETHODIMP 1.3032 +nsDownload::OnLocationChange(nsIWebProgress *aWebProgress, 1.3033 + nsIRequest *aRequest, nsIURI *aLocation, 1.3034 + uint32_t aFlags) 1.3035 +{ 1.3036 + return NS_OK; 1.3037 +} 1.3038 + 1.3039 +NS_IMETHODIMP 1.3040 +nsDownload::OnStatusChange(nsIWebProgress *aWebProgress, 1.3041 + nsIRequest *aRequest, nsresult aStatus, 1.3042 + const char16_t *aMessage) 1.3043 +{ 1.3044 + if (NS_FAILED(aStatus)) 1.3045 + return FailDownload(aStatus, aMessage); 1.3046 + return NS_OK; 1.3047 +} 1.3048 + 1.3049 +NS_IMETHODIMP 1.3050 +nsDownload::OnStateChange(nsIWebProgress *aWebProgress, 1.3051 + nsIRequest *aRequest, uint32_t aStateFlags, 1.3052 + nsresult aStatus) 1.3053 +{ 1.3054 + MOZ_ASSERT(NS_IsMainThread(), "Must call OnStateChange in main thread"); 1.3055 + 1.3056 + // We don't want to lose access to our member variables 1.3057 + nsRefPtr<nsDownload> kungFuDeathGrip = this; 1.3058 + 1.3059 + // Check if we're starting a request; the NETWORK flag is necessary to not 1.3060 + // pick up the START of *each* file but only for the whole request 1.3061 + if ((aStateFlags & STATE_START) && (aStateFlags & STATE_IS_NETWORK)) { 1.3062 + nsresult rv; 1.3063 + nsCOMPtr<nsIHttpChannel> channel = do_QueryInterface(aRequest, &rv); 1.3064 + if (NS_SUCCEEDED(rv)) { 1.3065 + uint32_t status; 1.3066 + rv = channel->GetResponseStatus(&status); 1.3067 + // HTTP 450 - Blocked by parental control proxies 1.3068 + if (NS_SUCCEEDED(rv) && status == 450) { 1.3069 + // Cancel using the provided object 1.3070 + (void)Cancel(); 1.3071 + 1.3072 + // Fail the download 1.3073 + (void)SetState(nsIDownloadManager::DOWNLOAD_BLOCKED_PARENTAL); 1.3074 + } 1.3075 + } 1.3076 + } else if ((aStateFlags & STATE_STOP) && (aStateFlags & STATE_IS_NETWORK) && 1.3077 + IsFinishable()) { 1.3078 + // We got both STOP and NETWORK so that means the whole request is done 1.3079 + // (and not just a single file if there are multiple files) 1.3080 + if (NS_SUCCEEDED(aStatus)) { 1.3081 + // We can't completely trust the bytes we've added up because we might be 1.3082 + // missing on some/all of the progress updates (especially from cache). 1.3083 + // Our best bet is the file itself, but if for some reason it's gone or 1.3084 + // if we have multiple files, the next best is what we've calculated. 1.3085 + int64_t fileSize; 1.3086 + nsCOMPtr<nsIFile> file; 1.3087 + // We need a nsIFile clone to deal with file size caching issues. :( 1.3088 + nsCOMPtr<nsIFile> clone; 1.3089 + if (!mHasMultipleFiles && 1.3090 + NS_SUCCEEDED(GetTargetFile(getter_AddRefs(file))) && 1.3091 + NS_SUCCEEDED(file->Clone(getter_AddRefs(clone))) && 1.3092 + NS_SUCCEEDED(clone->GetFileSize(&fileSize)) && fileSize > 0) { 1.3093 + mCurrBytes = mMaxBytes = fileSize; 1.3094 + 1.3095 + // If we resumed, keep the fact that we did and fix size calculations 1.3096 + if (WasResumed()) 1.3097 + mResumedAt = 0; 1.3098 + } else if (mMaxBytes == -1) { 1.3099 + mMaxBytes = mCurrBytes; 1.3100 + } else { 1.3101 + mCurrBytes = mMaxBytes; 1.3102 + } 1.3103 + 1.3104 + mPercentComplete = 100; 1.3105 + mLastUpdate = PR_Now(); 1.3106 + 1.3107 +#ifdef DOWNLOAD_SCANNER 1.3108 + bool scan = true; 1.3109 + nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID)); 1.3110 + if (prefs) 1.3111 + (void)prefs->GetBoolPref(PREF_BDM_SCANWHENDONE, &scan); 1.3112 + 1.3113 + if (scan) 1.3114 + (void)SetState(nsIDownloadManager::DOWNLOAD_SCANNING); 1.3115 + else 1.3116 + (void)SetState(nsIDownloadManager::DOWNLOAD_FINISHED); 1.3117 +#else 1.3118 + (void)SetState(nsIDownloadManager::DOWNLOAD_FINISHED); 1.3119 +#endif 1.3120 + } else { 1.3121 + // We failed for some unknown reason -- fail with a generic message 1.3122 + (void)FailDownload(aStatus, nullptr); 1.3123 + } 1.3124 + } 1.3125 + 1.3126 + mDownloadManager->NotifyListenersOnStateChange(aWebProgress, aRequest, 1.3127 + aStateFlags, aStatus, this); 1.3128 + return NS_OK; 1.3129 +} 1.3130 + 1.3131 +NS_IMETHODIMP 1.3132 +nsDownload::OnSecurityChange(nsIWebProgress *aWebProgress, 1.3133 + nsIRequest *aRequest, uint32_t aState) 1.3134 +{ 1.3135 + return NS_OK; 1.3136 +} 1.3137 + 1.3138 +//////////////////////////////////////////////////////////////////////////////// 1.3139 +//// nsIDownload 1.3140 + 1.3141 +NS_IMETHODIMP 1.3142 +nsDownload::Init(nsIURI *aSource, 1.3143 + nsIURI *aTarget, 1.3144 + const nsAString& aDisplayName, 1.3145 + nsIMIMEInfo *aMIMEInfo, 1.3146 + PRTime aStartTime, 1.3147 + nsIFile *aTempFile, 1.3148 + nsICancelable *aCancelable, 1.3149 + bool aIsPrivate) 1.3150 +{ 1.3151 + NS_WARNING("Huh...how did we get here?!"); 1.3152 + return NS_OK; 1.3153 +} 1.3154 + 1.3155 +NS_IMETHODIMP 1.3156 +nsDownload::GetState(int16_t *aState) 1.3157 +{ 1.3158 + *aState = mDownloadState; 1.3159 + return NS_OK; 1.3160 +} 1.3161 + 1.3162 +NS_IMETHODIMP 1.3163 +nsDownload::GetDisplayName(nsAString &aDisplayName) 1.3164 +{ 1.3165 + aDisplayName = mDisplayName; 1.3166 + return NS_OK; 1.3167 +} 1.3168 + 1.3169 +NS_IMETHODIMP 1.3170 +nsDownload::GetCancelable(nsICancelable **aCancelable) 1.3171 +{ 1.3172 + *aCancelable = mCancelable; 1.3173 + NS_IF_ADDREF(*aCancelable); 1.3174 + return NS_OK; 1.3175 +} 1.3176 + 1.3177 +NS_IMETHODIMP 1.3178 +nsDownload::GetTarget(nsIURI **aTarget) 1.3179 +{ 1.3180 + *aTarget = mTarget; 1.3181 + NS_IF_ADDREF(*aTarget); 1.3182 + return NS_OK; 1.3183 +} 1.3184 + 1.3185 +NS_IMETHODIMP 1.3186 +nsDownload::GetSource(nsIURI **aSource) 1.3187 +{ 1.3188 + *aSource = mSource; 1.3189 + NS_IF_ADDREF(*aSource); 1.3190 + return NS_OK; 1.3191 +} 1.3192 + 1.3193 +NS_IMETHODIMP 1.3194 +nsDownload::GetStartTime(int64_t *aStartTime) 1.3195 +{ 1.3196 + *aStartTime = mStartTime; 1.3197 + return NS_OK; 1.3198 +} 1.3199 + 1.3200 +NS_IMETHODIMP 1.3201 +nsDownload::GetPercentComplete(int32_t *aPercentComplete) 1.3202 +{ 1.3203 + *aPercentComplete = mPercentComplete; 1.3204 + return NS_OK; 1.3205 +} 1.3206 + 1.3207 +NS_IMETHODIMP 1.3208 +nsDownload::GetAmountTransferred(int64_t *aAmountTransferred) 1.3209 +{ 1.3210 + *aAmountTransferred = mCurrBytes + (WasResumed() ? mResumedAt : 0); 1.3211 + return NS_OK; 1.3212 +} 1.3213 + 1.3214 +NS_IMETHODIMP 1.3215 +nsDownload::GetSize(int64_t *aSize) 1.3216 +{ 1.3217 + *aSize = mMaxBytes + (WasResumed() && mMaxBytes != -1 ? mResumedAt : 0); 1.3218 + return NS_OK; 1.3219 +} 1.3220 + 1.3221 +NS_IMETHODIMP 1.3222 +nsDownload::GetMIMEInfo(nsIMIMEInfo **aMIMEInfo) 1.3223 +{ 1.3224 + *aMIMEInfo = mMIMEInfo; 1.3225 + NS_IF_ADDREF(*aMIMEInfo); 1.3226 + return NS_OK; 1.3227 +} 1.3228 + 1.3229 +NS_IMETHODIMP 1.3230 +nsDownload::GetTargetFile(nsIFile **aTargetFile) 1.3231 +{ 1.3232 + nsresult rv; 1.3233 + 1.3234 + nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(mTarget, &rv); 1.3235 + if (NS_FAILED(rv)) { 1.3236 + return rv; 1.3237 + } 1.3238 + 1.3239 + nsCOMPtr<nsIFile> file; 1.3240 + rv = fileURL->GetFile(getter_AddRefs(file)); 1.3241 + if (NS_FAILED(rv)) { 1.3242 + return rv; 1.3243 + } 1.3244 + 1.3245 + file.forget(aTargetFile); 1.3246 + return rv; 1.3247 +} 1.3248 + 1.3249 +NS_IMETHODIMP 1.3250 +nsDownload::GetSpeed(double *aSpeed) 1.3251 +{ 1.3252 + *aSpeed = mSpeed; 1.3253 + return NS_OK; 1.3254 +} 1.3255 + 1.3256 +NS_IMETHODIMP 1.3257 +nsDownload::GetId(uint32_t *aId) 1.3258 +{ 1.3259 + if (mPrivate) { 1.3260 + return NS_ERROR_NOT_AVAILABLE; 1.3261 + } 1.3262 + *aId = mID; 1.3263 + return NS_OK; 1.3264 +} 1.3265 + 1.3266 +NS_IMETHODIMP 1.3267 +nsDownload::GetGuid(nsACString &aGUID) 1.3268 +{ 1.3269 + aGUID = mGUID; 1.3270 + return NS_OK; 1.3271 +} 1.3272 + 1.3273 +NS_IMETHODIMP 1.3274 +nsDownload::GetReferrer(nsIURI **referrer) 1.3275 +{ 1.3276 + NS_IF_ADDREF(*referrer = mReferrer); 1.3277 + return NS_OK; 1.3278 +} 1.3279 + 1.3280 +NS_IMETHODIMP 1.3281 +nsDownload::GetResumable(bool *resumable) 1.3282 +{ 1.3283 + *resumable = IsResumable(); 1.3284 + return NS_OK; 1.3285 +} 1.3286 + 1.3287 +NS_IMETHODIMP 1.3288 +nsDownload::GetIsPrivate(bool *isPrivate) 1.3289 +{ 1.3290 + *isPrivate = mPrivate; 1.3291 + return NS_OK; 1.3292 +} 1.3293 + 1.3294 +//////////////////////////////////////////////////////////////////////////////// 1.3295 +//// nsDownload Helper Functions 1.3296 + 1.3297 +void 1.3298 +nsDownload::Finalize() 1.3299 +{ 1.3300 + // We're stopping, so break the cycle we created at download start 1.3301 + mCancelable = nullptr; 1.3302 + 1.3303 + // Reset values that aren't needed anymore, so the DB can be updated as well 1.3304 + mEntityID.Truncate(); 1.3305 + mTempFile = nullptr; 1.3306 + 1.3307 + // Remove ourself from the active downloads 1.3308 + nsCOMArray<nsDownload>& currentDownloads = mPrivate ? 1.3309 + mDownloadManager->mCurrentPrivateDownloads : 1.3310 + mDownloadManager->mCurrentDownloads; 1.3311 + (void)currentDownloads.RemoveObject(this); 1.3312 + 1.3313 + // Make sure we do not automatically resume 1.3314 + mAutoResume = DONT_RESUME; 1.3315 +} 1.3316 + 1.3317 +nsresult 1.3318 +nsDownload::ExecuteDesiredAction() 1.3319 +{ 1.3320 + // nsExternalHelperAppHandler is the only caller of AddDownload that sets a 1.3321 + // tempfile parameter. In this case, execute the desired action according to 1.3322 + // the saved mime info. 1.3323 + if (!mTempFile) { 1.3324 + return NS_OK; 1.3325 + } 1.3326 + 1.3327 + // We need to bail if for some reason the temp file got removed 1.3328 + bool fileExists; 1.3329 + if (NS_FAILED(mTempFile->Exists(&fileExists)) || !fileExists) 1.3330 + return NS_ERROR_FILE_NOT_FOUND; 1.3331 + 1.3332 + // Assume an unknown action is save to disk 1.3333 + nsHandlerInfoAction action = nsIMIMEInfo::saveToDisk; 1.3334 + if (mMIMEInfo) { 1.3335 + nsresult rv = mMIMEInfo->GetPreferredAction(&action); 1.3336 + NS_ENSURE_SUCCESS(rv, rv); 1.3337 + } 1.3338 + 1.3339 + nsresult retVal = NS_OK; 1.3340 + switch (action) { 1.3341 + case nsIMIMEInfo::saveToDisk: 1.3342 + // Move the file to the proper location 1.3343 + retVal = MoveTempToTarget(); 1.3344 + break; 1.3345 + case nsIMIMEInfo::useHelperApp: 1.3346 + case nsIMIMEInfo::useSystemDefault: 1.3347 + // For these cases we have to move the file to the target location and 1.3348 + // open with the appropriate application 1.3349 + retVal = OpenWithApplication(); 1.3350 + break; 1.3351 + default: 1.3352 + break; 1.3353 + } 1.3354 + 1.3355 + return retVal; 1.3356 +} 1.3357 + 1.3358 +nsresult 1.3359 +nsDownload::MoveTempToTarget() 1.3360 +{ 1.3361 + nsCOMPtr<nsIFile> target; 1.3362 + nsresult rv = GetTargetFile(getter_AddRefs(target)); 1.3363 + NS_ENSURE_SUCCESS(rv, rv); 1.3364 + 1.3365 + // MoveTo will fail if the file already exists, but we've already obtained 1.3366 + // confirmation from the user that this is OK, so remove it if it exists. 1.3367 + bool fileExists; 1.3368 + if (NS_SUCCEEDED(target->Exists(&fileExists)) && fileExists) { 1.3369 + rv = target->Remove(false); 1.3370 + NS_ENSURE_SUCCESS(rv, rv); 1.3371 + } 1.3372 + 1.3373 + // Extract the new leaf name from the file location 1.3374 + nsAutoString fileName; 1.3375 + rv = target->GetLeafName(fileName); 1.3376 + NS_ENSURE_SUCCESS(rv, rv); 1.3377 + nsCOMPtr<nsIFile> dir; 1.3378 + rv = target->GetParent(getter_AddRefs(dir)); 1.3379 + NS_ENSURE_SUCCESS(rv, rv); 1.3380 + rv = mTempFile->MoveTo(dir, fileName); 1.3381 + NS_ENSURE_SUCCESS(rv, rv); 1.3382 + 1.3383 + return NS_OK; 1.3384 +} 1.3385 + 1.3386 +nsresult 1.3387 +nsDownload::OpenWithApplication() 1.3388 +{ 1.3389 + // First move the temporary file to the target location 1.3390 + nsCOMPtr<nsIFile> target; 1.3391 + nsresult rv = GetTargetFile(getter_AddRefs(target)); 1.3392 + NS_ENSURE_SUCCESS(rv, rv); 1.3393 + 1.3394 + // Move the temporary file to the target location 1.3395 + rv = MoveTempToTarget(); 1.3396 + NS_ENSURE_SUCCESS(rv, rv); 1.3397 + 1.3398 + // We do not verify the return value here because, irrespective of success 1.3399 + // or failure of the method, the deletion of temp file has to take place, as 1.3400 + // per the corresponding preference. But we store this separately as this is 1.3401 + // what we ultimately return from this function. 1.3402 + nsresult retVal = mMIMEInfo->LaunchWithFile(target); 1.3403 + 1.3404 + bool deleteTempFileOnExit; 1.3405 + nsCOMPtr<nsIPrefBranch> prefs(do_GetService(NS_PREFSERVICE_CONTRACTID)); 1.3406 + if (!prefs || NS_FAILED(prefs->GetBoolPref(PREF_BH_DELETETEMPFILEONEXIT, 1.3407 + &deleteTempFileOnExit))) { 1.3408 + // No prefservice or no pref set; use default value 1.3409 +#if !defined(XP_MACOSX) 1.3410 + // Mac users have been very verbal about temp files being deleted on 1.3411 + // app exit - they don't like it - but we'll continue to do this on 1.3412 + // other platforms for now. 1.3413 + deleteTempFileOnExit = true; 1.3414 +#else 1.3415 + deleteTempFileOnExit = false; 1.3416 +#endif 1.3417 + } 1.3418 + 1.3419 + // Always schedule files to be deleted at the end of the private browsing 1.3420 + // mode, regardless of the value of the pref. 1.3421 + if (deleteTempFileOnExit || mPrivate) { 1.3422 + // Use the ExternalHelperAppService to push the temporary file to the list 1.3423 + // of files to be deleted on exit. 1.3424 + nsCOMPtr<nsPIExternalAppLauncher> appLauncher(do_GetService 1.3425 + (NS_EXTERNALHELPERAPPSERVICE_CONTRACTID)); 1.3426 + 1.3427 + // Even if we are unable to get this service we return the result 1.3428 + // of LaunchWithFile() which makes more sense. 1.3429 + if (appLauncher) { 1.3430 + if (mPrivate) { 1.3431 + (void)appLauncher->DeleteTemporaryPrivateFileWhenPossible(target); 1.3432 + } else { 1.3433 + (void)appLauncher->DeleteTemporaryFileOnExit(target); 1.3434 + } 1.3435 + } 1.3436 + } 1.3437 + 1.3438 + return retVal; 1.3439 +} 1.3440 + 1.3441 +void 1.3442 +nsDownload::SetStartTime(int64_t aStartTime) 1.3443 +{ 1.3444 + mStartTime = aStartTime; 1.3445 + mLastUpdate = aStartTime; 1.3446 +} 1.3447 + 1.3448 +void 1.3449 +nsDownload::SetProgressBytes(int64_t aCurrBytes, int64_t aMaxBytes) 1.3450 +{ 1.3451 + mCurrBytes = aCurrBytes; 1.3452 + mMaxBytes = aMaxBytes; 1.3453 + 1.3454 + // Get the real bytes that include resume position 1.3455 + int64_t currBytes, maxBytes; 1.3456 + (void)GetAmountTransferred(&currBytes); 1.3457 + (void)GetSize(&maxBytes); 1.3458 + 1.3459 + if (currBytes == maxBytes) 1.3460 + mPercentComplete = 100; 1.3461 + else if (maxBytes <= 0) 1.3462 + mPercentComplete = -1; 1.3463 + else 1.3464 + mPercentComplete = (int32_t)((double)currBytes / maxBytes * 100 + .5); 1.3465 +} 1.3466 + 1.3467 +NS_IMETHODIMP 1.3468 +nsDownload::Pause() 1.3469 +{ 1.3470 + if (!IsResumable()) 1.3471 + return NS_ERROR_UNEXPECTED; 1.3472 + 1.3473 + nsresult rv = CancelTransfer(); 1.3474 + NS_ENSURE_SUCCESS(rv, rv); 1.3475 + 1.3476 + return SetState(nsIDownloadManager::DOWNLOAD_PAUSED); 1.3477 +} 1.3478 + 1.3479 +nsresult 1.3480 +nsDownload::CancelTransfer() 1.3481 +{ 1.3482 + nsresult rv = NS_OK; 1.3483 + if (mCancelable) { 1.3484 + rv = mCancelable->Cancel(NS_BINDING_ABORTED); 1.3485 + // we're done with this, so break the cycle 1.3486 + mCancelable = nullptr; 1.3487 + } 1.3488 + 1.3489 + return rv; 1.3490 +} 1.3491 + 1.3492 +NS_IMETHODIMP 1.3493 +nsDownload::Cancel() 1.3494 +{ 1.3495 + // Don't cancel if download is already finished 1.3496 + if (IsFinished()) 1.3497 + return NS_OK; 1.3498 + 1.3499 + // Have the download cancel its connection 1.3500 + (void)CancelTransfer(); 1.3501 + 1.3502 + // Dump the temp file because we know we don't need the file anymore. The 1.3503 + // underlying transfer creating the file doesn't delete the file because it 1.3504 + // can't distinguish between a pause that cancels the transfer or a real 1.3505 + // cancel. 1.3506 + if (mTempFile) { 1.3507 + bool exists; 1.3508 + mTempFile->Exists(&exists); 1.3509 + if (exists) 1.3510 + mTempFile->Remove(false); 1.3511 + } 1.3512 + 1.3513 + nsCOMPtr<nsIFile> file; 1.3514 + if (NS_SUCCEEDED(GetTargetFile(getter_AddRefs(file)))) 1.3515 + { 1.3516 + bool exists; 1.3517 + file->Exists(&exists); 1.3518 + if (exists) 1.3519 + file->Remove(false); 1.3520 + } 1.3521 + 1.3522 + nsresult rv = SetState(nsIDownloadManager::DOWNLOAD_CANCELED); 1.3523 + NS_ENSURE_SUCCESS(rv, rv); 1.3524 + 1.3525 + return NS_OK; 1.3526 +} 1.3527 + 1.3528 +NS_IMETHODIMP 1.3529 +nsDownload::Resume() 1.3530 +{ 1.3531 + if (!IsPaused() || !IsResumable()) 1.3532 + return NS_ERROR_UNEXPECTED; 1.3533 + 1.3534 + nsresult rv; 1.3535 + nsCOMPtr<nsIWebBrowserPersist> wbp = 1.3536 + do_CreateInstance("@mozilla.org/embedding/browser/nsWebBrowserPersist;1", &rv); 1.3537 + NS_ENSURE_SUCCESS(rv, rv); 1.3538 + 1.3539 + rv = wbp->SetPersistFlags(nsIWebBrowserPersist::PERSIST_FLAGS_APPEND_TO_FILE | 1.3540 + nsIWebBrowserPersist::PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION); 1.3541 + NS_ENSURE_SUCCESS(rv, rv); 1.3542 + 1.3543 + // Create a new channel for the source URI 1.3544 + nsCOMPtr<nsIChannel> channel; 1.3545 + nsCOMPtr<nsIInterfaceRequestor> ir(do_QueryInterface(wbp)); 1.3546 + rv = NS_NewChannel(getter_AddRefs(channel), mSource, nullptr, nullptr, ir); 1.3547 + NS_ENSURE_SUCCESS(rv, rv); 1.3548 + 1.3549 + nsCOMPtr<nsIPrivateBrowsingChannel> pbChannel = do_QueryInterface(channel); 1.3550 + if (pbChannel) { 1.3551 + pbChannel->SetPrivate(mPrivate); 1.3552 + } 1.3553 + 1.3554 + // Make sure we can get a file, either the temporary or the real target, for 1.3555 + // both purposes of file size and a target to write to 1.3556 + nsCOMPtr<nsIFile> targetLocalFile(mTempFile); 1.3557 + if (!targetLocalFile) { 1.3558 + rv = GetTargetFile(getter_AddRefs(targetLocalFile)); 1.3559 + NS_ENSURE_SUCCESS(rv, rv); 1.3560 + } 1.3561 + 1.3562 + // Get the file size to be used as an offset, but if anything goes wrong 1.3563 + // along the way, we'll silently restart at 0. 1.3564 + int64_t fileSize; 1.3565 + // We need a nsIFile clone to deal with file size caching issues. :( 1.3566 + nsCOMPtr<nsIFile> clone; 1.3567 + if (NS_FAILED(targetLocalFile->Clone(getter_AddRefs(clone))) || 1.3568 + NS_FAILED(clone->GetFileSize(&fileSize))) 1.3569 + fileSize = 0; 1.3570 + 1.3571 + // Set the channel to resume at the right position along with the entityID 1.3572 + nsCOMPtr<nsIResumableChannel> resumableChannel(do_QueryInterface(channel)); 1.3573 + if (!resumableChannel) 1.3574 + return NS_ERROR_UNEXPECTED; 1.3575 + rv = resumableChannel->ResumeAt(fileSize, mEntityID); 1.3576 + NS_ENSURE_SUCCESS(rv, rv); 1.3577 + 1.3578 + // If we know the max size, we know what it should be when resuming 1.3579 + int64_t maxBytes; 1.3580 + GetSize(&maxBytes); 1.3581 + SetProgressBytes(0, maxBytes != -1 ? maxBytes - fileSize : -1); 1.3582 + // Track where we resumed because progress notifications restart at 0 1.3583 + mResumedAt = fileSize; 1.3584 + 1.3585 + // Set the referrer 1.3586 + if (mReferrer) { 1.3587 + nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(channel)); 1.3588 + if (httpChannel) { 1.3589 + rv = httpChannel->SetReferrer(mReferrer); 1.3590 + NS_ENSURE_SUCCESS(rv, rv); 1.3591 + } 1.3592 + } 1.3593 + 1.3594 + // Creates a cycle that will be broken when the download finishes 1.3595 + mCancelable = wbp; 1.3596 + (void)wbp->SetProgressListener(this); 1.3597 + 1.3598 + // Save the channel using nsIWBP 1.3599 + rv = wbp->SaveChannel(channel, targetLocalFile); 1.3600 + if (NS_FAILED(rv)) { 1.3601 + mCancelable = nullptr; 1.3602 + (void)wbp->SetProgressListener(nullptr); 1.3603 + return rv; 1.3604 + } 1.3605 + 1.3606 + return SetState(nsIDownloadManager::DOWNLOAD_DOWNLOADING); 1.3607 +} 1.3608 + 1.3609 +NS_IMETHODIMP 1.3610 +nsDownload::Remove() 1.3611 +{ 1.3612 + return mDownloadManager->RemoveDownload(mGUID); 1.3613 +} 1.3614 + 1.3615 +NS_IMETHODIMP 1.3616 +nsDownload::Retry() 1.3617 +{ 1.3618 + return mDownloadManager->RetryDownload(mGUID); 1.3619 +} 1.3620 + 1.3621 +bool 1.3622 +nsDownload::IsPaused() 1.3623 +{ 1.3624 + return mDownloadState == nsIDownloadManager::DOWNLOAD_PAUSED; 1.3625 +} 1.3626 + 1.3627 +bool 1.3628 +nsDownload::IsResumable() 1.3629 +{ 1.3630 + return !mEntityID.IsEmpty(); 1.3631 +} 1.3632 + 1.3633 +bool 1.3634 +nsDownload::WasResumed() 1.3635 +{ 1.3636 + return mResumedAt != -1; 1.3637 +} 1.3638 + 1.3639 +bool 1.3640 +nsDownload::ShouldAutoResume() 1.3641 +{ 1.3642 + return mAutoResume == AUTO_RESUME; 1.3643 +} 1.3644 + 1.3645 +bool 1.3646 +nsDownload::IsFinishable() 1.3647 +{ 1.3648 + return mDownloadState == nsIDownloadManager::DOWNLOAD_NOTSTARTED || 1.3649 + mDownloadState == nsIDownloadManager::DOWNLOAD_QUEUED || 1.3650 + mDownloadState == nsIDownloadManager::DOWNLOAD_DOWNLOADING; 1.3651 +} 1.3652 + 1.3653 +bool 1.3654 +nsDownload::IsFinished() 1.3655 +{ 1.3656 + return mDownloadState == nsIDownloadManager::DOWNLOAD_FINISHED; 1.3657 +} 1.3658 + 1.3659 +nsresult 1.3660 +nsDownload::UpdateDB() 1.3661 +{ 1.3662 + NS_ASSERTION(mID, "Download ID is stored as zero. This is bad!"); 1.3663 + NS_ASSERTION(mDownloadManager, "Egads! We have no download manager!"); 1.3664 + 1.3665 + mozIStorageStatement *stmt = mPrivate ? 1.3666 + mDownloadManager->mUpdatePrivateDownloadStatement : mDownloadManager->mUpdateDownloadStatement; 1.3667 + 1.3668 + nsAutoString tempPath; 1.3669 + if (mTempFile) 1.3670 + (void)mTempFile->GetPath(tempPath); 1.3671 + nsresult rv = stmt->BindStringByName(NS_LITERAL_CSTRING("tempPath"), tempPath); 1.3672 + 1.3673 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("startTime"), mStartTime); 1.3674 + NS_ENSURE_SUCCESS(rv, rv); 1.3675 + 1.3676 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("endTime"), mLastUpdate); 1.3677 + NS_ENSURE_SUCCESS(rv, rv); 1.3678 + 1.3679 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("state"), mDownloadState); 1.3680 + NS_ENSURE_SUCCESS(rv, rv); 1.3681 + 1.3682 + if (mReferrer) { 1.3683 + nsAutoCString referrer; 1.3684 + rv = mReferrer->GetSpec(referrer); 1.3685 + NS_ENSURE_SUCCESS(rv, rv); 1.3686 + rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("referrer"), referrer); 1.3687 + } else { 1.3688 + rv = stmt->BindNullByName(NS_LITERAL_CSTRING("referrer")); 1.3689 + } 1.3690 + NS_ENSURE_SUCCESS(rv, rv); 1.3691 + 1.3692 + rv = stmt->BindUTF8StringByName(NS_LITERAL_CSTRING("entityID"), mEntityID); 1.3693 + NS_ENSURE_SUCCESS(rv, rv); 1.3694 + 1.3695 + int64_t currBytes; 1.3696 + (void)GetAmountTransferred(&currBytes); 1.3697 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("currBytes"), currBytes); 1.3698 + NS_ENSURE_SUCCESS(rv, rv); 1.3699 + 1.3700 + int64_t maxBytes; 1.3701 + (void)GetSize(&maxBytes); 1.3702 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("maxBytes"), maxBytes); 1.3703 + NS_ENSURE_SUCCESS(rv, rv); 1.3704 + 1.3705 + rv = stmt->BindInt32ByName(NS_LITERAL_CSTRING("autoResume"), mAutoResume); 1.3706 + NS_ENSURE_SUCCESS(rv, rv); 1.3707 + 1.3708 + rv = stmt->BindInt64ByName(NS_LITERAL_CSTRING("id"), mID); 1.3709 + NS_ENSURE_SUCCESS(rv, rv); 1.3710 + 1.3711 + return stmt->Execute(); 1.3712 +} 1.3713 + 1.3714 +nsresult 1.3715 +nsDownload::FailDownload(nsresult aStatus, const char16_t *aMessage) 1.3716 +{ 1.3717 + // Grab the bundle before potentially losing our member variables 1.3718 + nsCOMPtr<nsIStringBundle> bundle = mDownloadManager->mBundle; 1.3719 + 1.3720 + (void)SetState(nsIDownloadManager::DOWNLOAD_FAILED); 1.3721 + 1.3722 + // Get title for alert. 1.3723 + nsXPIDLString title; 1.3724 + nsresult rv = bundle->GetStringFromName( 1.3725 + MOZ_UTF16("downloadErrorAlertTitle"), getter_Copies(title)); 1.3726 + NS_ENSURE_SUCCESS(rv, rv); 1.3727 + 1.3728 + // Get a generic message if we weren't supplied one 1.3729 + nsXPIDLString message; 1.3730 + message = aMessage; 1.3731 + if (message.IsEmpty()) { 1.3732 + rv = bundle->GetStringFromName( 1.3733 + MOZ_UTF16("downloadErrorGeneric"), getter_Copies(message)); 1.3734 + NS_ENSURE_SUCCESS(rv, rv); 1.3735 + } 1.3736 + 1.3737 + // Get Download Manager window to be parent of alert 1.3738 + nsCOMPtr<nsIWindowMediator> wm = 1.3739 + do_GetService(NS_WINDOWMEDIATOR_CONTRACTID, &rv); 1.3740 + NS_ENSURE_SUCCESS(rv, rv); 1.3741 + nsCOMPtr<nsIDOMWindow> dmWindow; 1.3742 + rv = wm->GetMostRecentWindow(MOZ_UTF16("Download:Manager"), 1.3743 + getter_AddRefs(dmWindow)); 1.3744 + NS_ENSURE_SUCCESS(rv, rv); 1.3745 + 1.3746 + // Show alert 1.3747 + nsCOMPtr<nsIPromptService> prompter = 1.3748 + do_GetService("@mozilla.org/embedcomp/prompt-service;1", &rv); 1.3749 + NS_ENSURE_SUCCESS(rv, rv); 1.3750 + return prompter->Alert(dmWindow, title, message); 1.3751 +}