Bug 382825 - Add a retryDownload method to the download manager backend. r=cbiesinger

git-svn-id: svn://10.0.0.236/trunk@227505 18797224-902f-48f8-a5cc-f745e15eee43
This commit is contained in:
sdwilsh%shawnwilsher.com 2007-06-05 00:03:36 +00:00
parent e02872210c
commit 76f9eb283a
9 changed files with 342 additions and 116 deletions

View File

@ -51,7 +51,7 @@ interface nsIDownloadProgressListener;
interface nsISimpleEnumerator;
interface mozIStorageConnection;
[scriptable, uuid(1c015a52-c4e3-4c1c-9071-2c2eaeed8bfc)]
[scriptable, uuid(bbf6561b-d7d7-48fa-967c-9cc46cc372b4)]
interface nsIDownloadManager : nsISupports {
// Download States
const short DOWNLOAD_NOTSTARTED = -1;
@ -150,6 +150,17 @@ interface nsIDownloadManager : nsISupports {
*/
void resumeDownload(in unsigned long aID);
/**
* Retries a failed download.
*
* @param aID The unique ID of the download.
* @throws NS_ERROR_NOT_AVAILALE if the download id is not known.
* @throws NS_ERROR_FAILURE if the download is not in the following states:
* nsIDownloadManager::DOWNLOAD_CANCELED
* nsIDownloadManager::DOWNLOAD_FAILED
*/
void retryDownload(in unsigned long aID);
/**
* Opens the Download Manager front end, selecting the specified download.
*

View File

@ -428,6 +428,105 @@ nsDownloadManager::GetRetentionBehavior()
return val;
}
nsresult
nsDownloadManager::GetDownloadFromDB(PRUint32 aID, nsDownload **retVal)
{
NS_ASSERTION(!FindDownload(aID),
"If it is a current download, you should not call this method!");
// First, let's query the database and see if it even exists
nsCOMPtr<mozIStorageStatement> stmt;
nsresult rv = mDBConn->CreateStatement(NS_LITERAL_CSTRING(
"SELECT id, state, startTime, source, target, name "
"FROM moz_downloads "
"WHERE id = ?1"), getter_AddRefs(stmt));
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt64Parameter(0, aID);
NS_ENSURE_SUCCESS(rv, rv);
PRBool hasResults = PR_FALSE;
rv = stmt->ExecuteStep(&hasResults);
if (NS_FAILED(rv) || !hasResults)
return NS_ERROR_NOT_AVAILABLE;
// We have a download, so lets create it
nsRefPtr<nsDownload> dl = new nsDownload();
if (!dl)
return NS_ERROR_OUT_OF_MEMORY;
// Setting all properties of the download now
dl->mCancelable = nsnull;
dl->mID = stmt->AsInt64(0);
dl->mDownloadState = stmt->AsInt32(1);
dl->mStartTime = stmt->AsInt64(2);
nsCString source;
stmt->GetUTF8String(3, source);
rv = NS_NewURI(getter_AddRefs(dl->mSource), source);
NS_ENSURE_SUCCESS(rv, rv);
nsCString target;
stmt->GetUTF8String(4, target);
rv = NS_NewURI(getter_AddRefs(dl->mTarget), target);
NS_ENSURE_SUCCESS(rv, rv);
stmt->GetString(5, dl->mDisplayName);
nsCOMPtr<nsILocalFile> file;
rv = dl->GetTargetFile(getter_AddRefs(file));
NS_ENSURE_SUCCESS(rv, rv);
PRBool fileExists;
if (NS_SUCCEEDED(file->Exists(&fileExists)) && fileExists) {
if (dl->mDownloadState == nsIDownloadManager::DOWNLOAD_FINISHED) {
dl->mPercentComplete = 100;
PRInt64 size;
rv = file->GetFileSize(&size);
NS_ENSURE_SUCCESS(rv, rv);
dl->mMaxBytes = dl->mCurrBytes = size;
} else {
dl->mPercentComplete = -1;
dl->mMaxBytes = LL_MAXUINT;
}
} else {
dl->mPercentComplete = 0;
dl->mMaxBytes = LL_MAXUINT;
dl->mCurrBytes = 0;
}
// Addrefing and returning
NS_ADDREF(*retVal = dl);
return NS_OK;
}
nsresult
nsDownloadManager::AddToCurrentDownloads(nsDownload *aDl)
{
// If this is an install operation, ensure we have a progress listener for the
// install and track this download separately.
if (aDl->mDownloadType == nsIXPInstallManagerUI::DOWNLOAD_TYPE_INSTALL) {
if (!mXPIProgress) {
mXPIProgress = new nsXPIProgressListener(this);
if (!mXPIProgress)
return NS_ERROR_OUT_OF_MEMORY;
}
nsIXPIProgressDialog *dialog = mXPIProgress.get();
nsXPIProgressListener *listener = NS_STATIC_CAST(nsXPIProgressListener*,
dialog);
listener->AddDownload(aDl);
}
mCurrentDownloads.AppendObject(aDl);
return NS_OK;
}
///////////////////////////////////////////////////////////////////////////////
//// nsIDownloadManager
NS_IMETHODIMP
nsDownloadManager::GetActiveDownloadCount(PRInt32 *aResult)
{
@ -442,9 +541,6 @@ nsDownloadManager::GetActiveDownloads(nsISimpleEnumerator **aResult)
return NS_NewArrayEnumerator(aResult, mCurrentDownloads);
}
///////////////////////////////////////////////////////////////////////////////
// nsIDownloadManager
NS_IMETHODIMP
nsDownloadManager::AddDownload(DownloadType aDownloadType,
nsIURI* aSource,
@ -502,21 +598,8 @@ nsDownloadManager::AddDownload(DownloadType aDownloadType,
NS_ENSURE_TRUE(id, NS_ERROR_FAILURE);
dl->mID = id;
// If this is an install operation, ensure we have a progress listener for the
// install and track this download separately.
if (aDownloadType == nsIXPInstallManagerUI::DOWNLOAD_TYPE_INSTALL) {
if (!mXPIProgress) {
mXPIProgress = new nsXPIProgressListener(this);
if (!mXPIProgress)
return NS_ERROR_OUT_OF_MEMORY;
}
nsIXPIProgressDialog* dialog = mXPIProgress.get();
nsXPIProgressListener* listener = NS_STATIC_CAST(nsXPIProgressListener*, dialog);
listener->AddDownload(*aDownload);
}
mCurrentDownloads.AppendObject(dl);
rv = AddToCurrentDownloads(dl);
NS_ENSURE_SUCCESS(rv, rv);
NS_ADDREF(*aDownload = dl);
@ -601,6 +684,44 @@ nsDownloadManager::CancelDownload(PRUint32 aID)
return NS_OK;
}
NS_IMETHODIMP
nsDownloadManager::RetryDownload(PRUint32 aID)
{
nsRefPtr<nsDownload> dl;
nsresult rv = GetDownloadFromDB(aID, getter_AddRefs(dl));
NS_ENSURE_SUCCESS(rv, rv);
// if our download is not canceled or failed, we should fail
if (dl->mDownloadState != nsIDownloadManager::DOWNLOAD_FAILED &&
dl->mDownloadState != nsIDownloadManager::DOWNLOAD_CANCELED)
return NS_ERROR_FAILURE;
// we are redownloading this, so we need to link the download manager to the
// download else we'll try to dereference null pointers - eww
dl->mDownloadManager = this;
dl->SetStartTime(PR_Now());
rv = dl->SetState(nsIDownloadManager::DOWNLOAD_NOTSTARTED);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIWebBrowserPersist> wbp =
do_CreateInstance("@mozilla.org/embedding/browser/nsWebBrowserPersist;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
// Creates a cycle that will be broken in nsDownload::OnStateChange
dl->mCancelable = wbp;
wbp->SetProgressListener(dl);
rv = wbp->SetPersistFlags(nsIWebBrowserPersist::PERSIST_FLAGS_REPLACE_EXISTING_FILES |
nsIWebBrowserPersist::PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION);
NS_ENSURE_SUCCESS(rv, rv);
rv = AddToCurrentDownloads(dl);
NS_ENSURE_SUCCESS(rv, rv);
return wbp->SaveURI(dl->mSource, nsnull, nsnull, nsnull, nsnull, dl->mTarget);
}
NS_IMETHODIMP
nsDownloadManager::RemoveDownload(PRUint32 aID)
{
@ -1187,7 +1308,7 @@ nsDownload::nsDownload() : mDownloadState(nsIDownloadManager::DOWNLOAD_NOTSTARTE
mID(0),
mPercentComplete(0),
mCurrBytes(LL_ZERO),
mMaxBytes(LL_ZERO),
mMaxBytes(LL_MAXUINT),
mStartTime(LL_ZERO),
mLastUpdate(PR_Now() - (PRUint32)gUpdateInterval),
mPaused(PR_FALSE),
@ -1641,6 +1762,7 @@ nsresult
nsDownload::UpdateDB()
{
NS_ASSERTION(mID, "Download ID is stored as zero. This is bad!");
NS_ASSERTION(mDownloadManager, "Egads! We have no download manager!");
nsCOMPtr<mozIStorageStatement> stmt;
nsresult rv = mDownloadManager->mDBConn->CreateStatement(NS_LITERAL_CSTRING(

View File

@ -96,6 +96,8 @@ protected:
nsresult InitDB(PRBool *aDoImport);
nsresult CreateTable();
nsresult ImportDownloadHistory();
nsresult GetDownloadFromDB(PRUint32 aID, nsDownload **retVal);
nsresult AddToCurrentDownloads(nsDownload *aDl);
/**
* Adds a download with the specified information to the DB.

View File

@ -66,6 +66,7 @@ if (!profileDir) {
file.append("downloads.rdf");
return file;
}
print("*** Throwing trying to get " + prop);
throw Cr.NS_ERROR_FAILURE;
},
QueryInterface: function(iid) {
@ -86,3 +87,80 @@ function importDownloadsFile(aFName)
file.copyTo(newFile, "downloads.rdf");
}
function cleanup()
{
// removing rdf
var rdfFile = dirSvc.get("DLoads", Ci.nsIFile);
if (rdfFile.exists()) rdfFile.remove(true);
// removing database
var dbFile = dirSvc.get("ProfD", Ci.nsIFile);
dbFile.append("downloads.sqlite");
if (dbFile.exists())
try { dbFile.remove(true); } catch(e) { /* stupid windows box */ }
// removing downloaded file
var destFile = dirSvc.get("ProfD", Ci.nsIFile);
destFile.append("download.result");
if (destFile.exists()) destFile.remove(true);
}
var gDownloadCount = 0;
function addDownload()
{
const nsIWBP = Ci.nsIWebBrowserPersist;
var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
.createInstance(Ci.nsIWebBrowserPersist);
persist.persistFlags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES |
nsIWBP.PERSIST_FLAGS_BYPASS_CACHE |
nsIWBP.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
var destFile = dirSvc.get("ProfD", Ci.nsIFile);
destFile.append("download.result");
var srcFile = dirSvc.get("ProfD", Ci.nsIFile);
srcFile.append("LICENSE");
var dl = dm.addDownload(nsIDownloadManager.DOWNLOAD_TYPE_DOWNLOAD,
createURI("http://localhost:4444/LICENSE"),
createURI(destFile), null, null, null,
Math.round(Date.now() * 1000), null, persist);
// This will throw if it isn't found, and that would mean test failure, so no
// try catch block
var test = dm.getDownload(dl.id);
// it is part of the active downloads now, even if it hasn't started.
gDownloadCount++;
persist.progressListener = dl.QueryInterface(Ci.nsIWebProgressListener);
persist.saveURI(dl.source, null, null, null, null, dl.targetFile);
return dl;
}
function getDownloadListener()
{
return {
onDownloadStateChange: function(aState, aDownload)
{
if (aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_FINISHED)
gDownloadCount--;
if (aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_CANCELED ||
aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_FAILED) {
gDownloadCount--;
}
if (gDownloadCount == 0)
httpserv.stop();
},
onStateChange: function(a, b, c, d, e) { },
onProgressChange: function(a, b, c, d, e, f, g) { },
onStatusChange: function(a, b, c, d, e) { },
onLocationChange: function(a, b, c, d) { },
onSecurityChange: function(a, b, c, d) { }
};
}
cleanup();

View File

@ -0,0 +1,95 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Download Manager Test Code.
*
* The Initial Developer of the Original Code is
* Mozilla Corporation.
* Portions created by the Initial Developer are Copyright (C) 2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Shawn Wilsher <me@shawnwilsher.com> (Original Author)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// This tests the retryDownload function of nsIDownloadManager. This function
// was added in Bug 382825.
const nsIDownloadManager = Ci.nsIDownloadManager;
const dm = Cc["@mozilla.org/download-manager;1"].getService(nsIDownloadManager);
function test_retry_canceled()
{
var dl = addDownload();
// since we are going to be retrying a failed download, we need to inflate
// this so it doesn't stop our server
gDownloadCount++;
dm.cancelDownload(dl.id);
do_check_eq(nsIDownloadManager.DOWNLOAD_CANCELED, dl.state);
// Our download object will no longer be updated.
dm.retryDownload(dl.id);
}
function test_retry_bad()
{
try {
dm.retryDownload(0);
do_throw("Hey! We expect to get an exception with this!");
} catch(e) {
do_check_eq(Components.lastResult, Cr.NS_ERROR_NOT_AVAILABLE);
}
}
var tests = [test_retry_canceled, test_retry_bad];
var httpserv = null;
function run_test()
{
httpserv = new nsHttpServer();
httpserv.registerDirectory("/", dirSvc.get("ProfD", Ci.nsILocalFile));
httpserv.start(4444);
dm.addListener(getDownloadListener());
for (var i = 0; i < tests.length; i++)
tests[i]();
cleanup();
var thread = Cc["@mozilla.org/thread-manager;1"]
.getService().currentThread;
while (!httpserv.isStopped())
thread.processNextEvent(true);
// get rid of any pending requests
while (thread.hasPendingEvents())
thread.processNextEvent(true);
}

View File

@ -37,26 +37,6 @@
// This file tests the download manager backend
function cleanup()
{
// removing rdf
var rdfFile = dirSvc.get("DLoads", Ci.nsIFile);
if (rdfFile.exists()) rdfFile.remove(true);
// removing database
var dbFile = dirSvc.get("ProfD", Ci.nsIFile);
dbFile.append("downloads.sqlite");
if (dbFile.exists())
try { dbFile.remove(true); } catch(e) { /* stupid windows box */ }
// removing downloaded file
var destFile = dirSvc.get("ProfD", Ci.nsIFile);
destFile.append("download.result");
if (destFile.exists()) destFile.remove(true);
}
cleanup();
const nsIDownloadManager = Ci.nsIDownloadManager;
const dm = Cc["@mozilla.org/download-manager;1"].getService(nsIDownloadManager);
@ -117,40 +97,6 @@ function test_resumeDownload_empty_queue()
}
}
function addDownload()
{
print("*** DOWNLOAD MANAGER TEST - Adding a download");
const nsIWBP = Ci.nsIWebBrowserPersist;
var persist = Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
.createInstance(Ci.nsIWebBrowserPersist);
persist.persistFlags = nsIWBP.PERSIST_FLAGS_REPLACE_EXISTING_FILES |
nsIWBP.PERSIST_FLAGS_BYPASS_CACHE |
nsIWBP.PERSIST_FLAGS_AUTODETECT_APPLY_CONVERSION;
var destFile = dirSvc.get("ProfD", Ci.nsIFile);
destFile.append("download.result");
var srcFile = dirSvc.get("ProfD", Ci.nsIFile);
srcFile.append("LICENSE");
var dl = dm.addDownload(nsIDownloadManager.DOWNLOAD_TYPE_DOWNLOAD,
createURI("http://localhost:4444/LICENSE"),
createURI(destFile), null, null, null,
Math.round(Date.now() * 1000), null, persist);
// This will throw if it isn't found, and that would mean test failure, so no
// try catch block
var test = dm.getDownload(dl.id);
// it is part of the active downloads now, even if it hasn't started.
gDownloadCount++;
persist.progressListener = dl.QueryInterface(Ci.nsIWebProgressListener);
persist.saveURI(dl.source, null, null, null, null, dl.targetFile);
print("*** DOWNLOAD MANAGER TEST - Adding a download worked");
return dl;
}
function test_addDownload_normal()
{
print("*** DOWNLOAD MANAGER TEST - Testing normal download adding");
@ -172,33 +118,19 @@ var tests = [test_get_download_empty_queue, test_connection,
test_pauseDownload_empty_queue, test_resumeDownload_empty_queue,
test_addDownload_normal, test_addDownload_cancel];
var gDownloadCount = 0;
var httpserv = null;
function run_test()
{
print("*** DOWNLOAD MANAGER TEST - starting tests");
httpserv = new nsHttpServer();
httpserv.registerDirectory("/", dirSvc.get("ProfD", Ci.nsILocalFile));
httpserv.start(4444);
print("*** DOWNLOAD MANAGER TEST - server started");
print("Try creating listener...")
// our download listener
var listener = {
// this listener checks to ensure activeDownloadCount is correct.
onDownloadStateChange: function(aState, aDownload)
{
if (aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_FINISHED)
gDownloadCount--;
if (aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_CANCELED ||
aDownload.state == Ci.nsIDownloadManager.DOWNLOAD_FAILED) {
gDownloadCount--;
}
do_check_eq(gDownloadCount, dm.activeDownloadCount);
if (gDownloadCount == 0)
httpserv.stop();
},
onStateChange: function(a, b, c, d, e) { },
onProgressChange: function(a, b, c, d, e, f, g) { },
@ -207,8 +139,8 @@ function run_test()
onSecurityChange: function(a, b, c, d) { }
};
dm.addListener(listener);
dm.addListener(getDownloadListener());
print("Try creating observer...");
var observer = {
observe: function(aSubject, aTopic, aData) {
var dl = aSubject.QueryInterface(Ci.nsIDownload);
@ -253,8 +185,6 @@ function run_test()
os.addObserver(observer, "dl-cancel", false);
os.addObserver(observer, "dl-done", false);
print("Made it through adding observers.");
for (var i = 0; i < tests.length; i++)
tests[i]();

View File

@ -39,21 +39,6 @@
// Also tests cleanUp function of DM since we have a good number of entries to
// clean up after importing.
function cleanup()
{
// removing rdf
var rdfFile = dirSvc.get("DLoads", Ci.nsIFile);
if (rdfFile.exists()) rdfFile.remove(true);
// removing database
var dbFile = dirSvc.get("ProfD", Ci.nsIFile);
dbFile.append("downloads.sqlite");
if (dbFile.exists())
try { dbFile.remove(true); } catch(e) { /* stupid windows box */ }
}
cleanup();
importDownloadsFile("downloads.rdf");
const nsIDownloadManager = Ci.nsIDownloadManager;

View File

@ -430,16 +430,10 @@ function onDownloadAnimated(aEvent)
function onDownloadRetry(aEvent)
{
var download = aEvent.target;
if (download.localName == "download") {
var src = document.getElementById(download.id).getAttribute("uri");
var f = getLocalFileFromNativePathOrUrl(aEvent.target.getAttribute("file"));
saveURL(src, f, null, true, true);
}
if (download.localName == "download")
gDownloadManager.retryDownload(download.getAttribute("dlid"));
gDownloadViewController.onCommandUpdate();
// retry always places the item in the first spot
gDownloadsView.selectedIndex = 0;
}
// This is called by the progress listener. We don't actually use the event

View File

@ -45,6 +45,15 @@ interface nsICancelable;
interface nsIWebProgressListener;
interface nsIMIMEInfo;
/**
* Represents a download object.
*
* @note This object is no longer updated once it enters a completed state.
* Completed states are the following:
* nsIDownloadManager::DOWNLOAD_FINISHED
* nsIDownloadManager::DOWNLOAD_FAILED
* nsIDownloadManager::DOWNLOAD_CANCELED
*/
[scriptable, uuid(974db2c6-fbd2-4de1-8d24-f54ce4f3e8bc)]
interface nsIDownload : nsITransfer {
@ -66,7 +75,7 @@ interface nsIDownload : nsITransfer {
/**
* The size of file in bytes.
* Unknown size is represented by 0.
* Unknown size is represented by LL_MAXUINT.
*/
readonly attribute PRUint64 size;