API for modifying the Firefox download list

I want to write a small Firefox add-on that detects when files that were downloaded were deleted (deleted) locally and delete the corresponding entry in the firefox download list.

Can someone point me to the appropriate api to manipulate the download list? I can't seem to find him.

0
source share
1 answer

The corresponding PlacesUtils API, which abstracts the complexity of the Places database.

If your code works in the context of a chrome window, you get a free PlacesUtils text variable. Otherwise (download, add SDK, whatever) you need to import PlacesUtils.jsm .

 Cu.import("resource://gre/modules/PlacesUtils.jsm"); 

As for Places , the downloaded files are nothing more than a special kind of visited pages, respectively annotated. It is a matter of only one line of code to get an array of all downloaded files.

 var results = PlacesUtils.annotations.getAnnotationsWithName("downloads/destinationFileURI"); 

Since we requested the destinationFileURI annotation, each resultarray element contains the loading location in the annotationValue property as a file: URI specification string.

With this you can check if the file really exists

 function getFileFromURIspec(fileurispec){ // if Services is not available in your context Cu.import("resource://gre/modules/Services.jsm"); var filehandler = Services.io.getProtocolHandler("file").QueryInterface(Ci.nsIFileProtocolHandler); try{ return filehandler.getFileFromURLSpec(fileurispec); } catch(e){ return null; } } 

getFileFromURIspec will return an nsIFile or null instance if the specification is not valid, which should not happen in this case, but the health check never hurts. With this, you can call the exists() method, and if it returns false , then the corresponding page entry in Places will be suitable for deletion. We can determine which page is its uri, which is also convenient for each results element.

 PlacesUtils.bhistory.removePage(result.uri); 

Summarizing

 var results = PlacesUtils.annotations.getAnnotationsWithName("downloads/destinationFileURI"); results.forEach(function(result){ var file = getFileFromURIspec(result.annotationValue); if(!file){ // I don't know how you should treat this edge case // ask the user, just log, remove, some combination? } else if(!file.exists()){ PlacesUtils.bhistory.removePage(result.uri); } }); 
+3
source

All Articles