home *** CD-ROM | disk | FTP | other *** search
- /***** BEGIN LICENSE BLOCK *****
-
- FlashGot - a Firefox extension for external download managers integration
- Copyright (C) 2004-2005 Giorgio Maone - g.maone@informaction.com
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
- ***** END LICENSE BLOCK *****/
-
- function FlashGotDM(name) {
- if(arguments.length>0) {
- this._init(name);
- }
- }
-
- FlashGotDM.dms=[];
- FlashGotDM.dmtests={};
- FlashGotDM.executables={};
- FlashGotDM.cleanup=function() {
- var name;
- for(name in FlashGotDM.executables) {
- var f=FlashGotDM.executables[name];
- if(f instanceof Components.interfaces.nsIFile) {
- try { f.remove(true); } catch(ex) {}
- }
- }
- }
-
- FlashGotDM.prototype = {
- _init: function(name) {
- this.name=name;
- const dms=FlashGotDM.dms;
- dms[name]=dms[dms.length]=this;
- }
- ,
- _service: null,
- _cookieManager: null,
- _exeFile: false,
- _supported: null
- ,
- exeName: "FlashGot.exe",
- askPath: [false,false,false],
- cookieSupport: true
- ,
- get codeName() {
- return this.name.replace(/\W/g,"_");
- }
- ,
- get service() {
- return this._service?this._service:this._service=
- Components.classes[SERVICE_CTRID].getService(Components.interfaces.nsISupports).wrappedJSObject;
- }
- ,
- get cookieManager() {
- return this._cookieManager?this._cookieManager:this._cookieManager=
- Components.classes["@mozilla.org/cookiemanager;1"
- ].getService(Components.interfaces.nsICookieManager);
- }
- ,
- get exeFile() {
- if(typeof(this._exeFile)=="object") return this._exeFile;
- const exeName=this.exeName;
- if(!exeName) return this._exeFile=null;
- if(typeof(FlashGotDM.executables[exeName])=="object") {
- return this._exeFile=FlashGotDM.executables[exeName];
- }
- try {
- const exeFile=Components.classes["@mozilla.org/file/local;1"].createInstance(
- Components.interfaces.nsILocalFile);
- exeFile.initWithPath(this.service.globals.profDir.path);
- exeFile.append(exeName);
- if(exeFile.exists()) {
- try { exeFile.remove(true); } catch(ex) { this.log(ex.message); }
- }
- this._exeFile=this.checkExePlatform(exeFile);
- if(this._exeFile!=null && this.createExecutable()) {
- this.log(this._exeFile.path+" created");
- }
- } catch(ex) {
- this._exeFile=null;
- this.log("Can't init "+exeName+":\n"+ex.message);
- }
- return FlashGotDM.executables[exeName]=this._exeFile;
- }
- ,
- checkExePlatform: function(exeFile) {
- return /(\/.*\.exe)|(\\.*\.sh)$/i.test(exeFile.path)?null:exeFile;
- }
- ,
- get supported() {
- if(typeof(this._supported)=="boolean") return this._supported;
- if(!this.exeName) return true;
- if(!this.exeFile) return false;
-
- var dmtest;
- if(typeof(FlashGotDM.dmtests[this.exeName])!="string") {
- const dmtestFile=this.service.tmpDir.clone();
- dmtestFile.append(this.exeName+".test");
- try {
- this.launchSupportTest(dmtestFile);
- this.log(dmtest=this.service.readFile(dmtestFile));
- } catch(ex) {
- this.log(ex.message);
- dmtest="";
- }
- FlashGotDM.dmtests[this.exeName]=dmtest;
- } else dmtest=FlashGotDM.dmtests[this.exeName];
- return this._supported=dmtest.indexOf(this.name+"|OK")>-1;
- }
- ,
- launchSupportTest: function (testFile) {
- this.runNative(["-o",testFile.path],true);
- }
- ,
- log: function(msg) {
- this.service.log(msg);
- }
- ,
- updateProgress: function(links,idx,len) {
- links.progress.value=50 + 49 * idx / len;
- }
- ,
- isValidLink: function(url) {
- return true;
- }
- ,
- createJobHeader: function(links, opType) {
- return links.length+";"+this.name+";"+
- (this.service.getPref(this.codeName+".quiet."+opType,false)
- ?this.service.OP_QET:opType)
- +";"+links.folder+";\n"
- }
- ,
- createJobBody: function(links) {
- var job="";
- var l,url;
- const len=links.length;
- this.checkCookieSupport();
- var postData=links.postData;
- if(!postData) postData="";
- for(var j=0; j<len; j++) {
- job+="\n"+(url=(l=links[j]).href)+"\n"
- +l._description+"\n"
- +this.getCookie(l,links)+"\n"
- +postData;
- this.updateProgress(links,j,len);
- }
- return job;
- }
- ,
- createJob: function(links,opType) {
- var job=this.createJobHeader(links,opType)
- + this.getReferrer(links)
- + this.createJobBody(links)+"\n";
- if(job.substring(job.length-1)!="\n") {
- job+="\n";
- }
- if(typeof(links.document)=="object") {
- job+= links.document.referrer+ "\n" +links.document.cookie;
- } else {
- job+="\n";
- }
- return job;
- }
- ,
- _bgJob: true,
- get bgJob() {
- return this._bgJob && this.service.bgProcessing;
- }
- ,
- download: function(links, opType) {
- try {
- links.folder=(links.length>0)?this.selectFolder(links,opType):"";
- const dm=this;
- var asyncError=null;
- function performJob() {
- try {
- dm.performJob(dm.createJob(links,opType));
- } catch(ex) {
- asyncError=ex;
- }
- links.progress.value=100;
- }
- if(links.length>1 && this.bgJob) {
- this.log("Async download job");
- this.service.runAsync(
- performJob,
- function() { if(asyncError) dm.log(asyncError.message); }
- );
- } else {
- this.log("Synchronous download job");
- performJob();
- }
- } catch(ex) {
- this.log(ex.message);
- links.progress.value=100;
- }
- }
- ,
- getReferrer: function(links) {
- return this.service.getPref("autoReferrer",true)?
- (links.referrer?links.referrer
- :typeof(links.document)=="object"?links.document.URL
- :links[0]?links[0].href:"about:blank"
- ):this.service.getPref("fakeReferrer","");
- }
- ,
- checkCookieSupport: function() {
- this.getCookie=this.cookieSupport && !this.service.getPref("omitCookies")
- ?this._getCookie
- :function() { return ""; }
- ;
- }
- ,
- getCookie: function() { return ""; }
- ,
- _getCookie: function(link,links) {
- if(!this.cookieSupport) return (this.getCookie=function() { return ""; })();
-
- var host,cookies;
- if(cookies=links.cookies) {
- host=link.host;
- if(host) {
- var c=cookies[host];
- return c?c:"";
- }
- return "";
- }
-
- var j,objCookie;
- const hostCookies={};
-
-
- var rxHost=/http[s]{0,1}:\/\/([^\/]+\.[^\/]+)/i;
- var l,parts;
- for(j=links.length; j-->0;) {
- l=links[j];
- parts=l.href.match(rxHost);
- if(parts) {
- hostCookies[l.host=parts[1]]="";
- } else {
- l.host=null;
- }
- }
-
- var cookieHost,cookieTable,tmpCookie;
- const domainCookies={};
-
- for(var iter = this.cookieManager.enumerator; iter.hasMoreElements();) {
- if((objCookie=iter.getNext()) instanceof Components.interfaces.nsICookie) {
- cookieHost=objCookie.host;
- if(cookieHost.charAt(0)==".") {
- cookieHost=cookieHost.substring(1);
- cookieTable=domainCookies;
- if(typeof(tmpCookie=domainCookies[cookieHost])!="string") {
- tmpCookie="";
- }
- } else {
- if(typeof(tmpCookie=hostCookies[cookieHost])!="string") continue;
- cookieTable=hostCookies;
- }
- cookieTable[cookieHost]=tmpCookie.concat(objCookie.name+"="+objCookie.value+"; ");
- }
- }
-
-
- for(cookieHost in hostCookies) {
- var dotPos;
- for(host=cookieHost; (dotPos=host.indexOf('.'))>=0; ) {
- if(tmpCookie=domainCookies[host]) {
- hostCookies[cookieHost]+=tmpCookie;
- }
- host=host.substring(dotPos+1);
- }
- }
-
- links.cookies=hostCookies;
- return this.getCookie(link,links);
- }
- ,
- createJobFile: function(job) {
- const jobFile=this.service.tmpDir.clone();
- jobFile.append("flashgot.fgt");
- jobFile.createUnique(0,0700);
- this.service.writeFile(jobFile,job);
- return jobFile;
- }
- ,
- _waitForNative: true,
- get waitForNative() {
- return this._waitForNative && ! this.service.isUIThread;
- }
- ,
- performJob: function(job) {
- const jobFile=this.createJobFile(job);
- this.runNative([jobFile.path],this.waitForNative);
- }
- ,
- createExecutable: function() {
- const exeFile=this.exeFile;
- if(!exeFile) return false;
-
- const cc=Components.classes;
- const ci=Components.interfaces;
- const ios=cc['@mozilla.org/network/io-service;1'].getService(ci.nsIIOService);
- const bis=cc['@mozilla.org/binaryinputstream;1'].createInstance(ci.nsIBinaryInputStream);
-
- var channel;
- bis.setInputStream((
- channel=
- ios.newChannel("chrome://flashgot/content/"+this.exeName,null,null)
- ).open())
- ;
- const bytesCount=channel.contentLength;
-
- const os=cc["@mozilla.org/network/file-output-stream;1"].createInstance(
- ci.nsIFileOutputStream);
-
- try {
-
- os.init(exeFile,0x02 | 0x08, 0700, 0);
- const bos=cc['@mozilla.org/binaryoutputstream;1'].createInstance(ci.nsIBinaryOutputStream);
- bos.setOutputStream(os);
- bos.writeByteArray(bis.readByteArray(bytesCount),bytesCount);
- bos.close();
-
- } catch(ioErr) { // locked?
- try {
- if(exeFile.exists()) { // security check: it must be the right exe!
- const testBis=cc['@mozilla.org/binaryinputstream;1'].createInstance(
- ci.nsIBinaryInputStream);
- testBis.setInputStream(
- (channel=ios.newChannelFromURI(ios.newFileURI(exeFile))).open());
- const error=new Error("Old, corrupt or unlegitemately modified "
- +exeFile.path
- +".\nThe file is locked: please delete it manually\n");
- +ioErr.message;
- if(channel.contentLength!=bytesCount) throw error;
-
- const legitimateData=bis.readByteArray(bytesCount);
- const testData=testBis.readByteArray(bytesCount);
- for(var j=bytesCount; j-->0;) {
- if(legitimateData[j]!=testData[j]) throw new error;
- }
- } else throw ioErr;
- } catch(unrecoverableErr) {
- this.log("Error creating native executable\n"+exeFile.path+"\n"+unrecoverableErr.message);
- }
- } finally {
- os.close();
- bis.close();
- }
-
- return true;
- }
- ,
- runNative: function(args,blocking,exeFile) {
- try {
- if(typeof(exeFile)=="object"
- || (exeFile=this.exeFile).exists()
- || this.createExecutable()) {
- const proc=Components.classes['@mozilla.org/process/util;1'].createInstance(
- Components.interfaces.nsIProcess);
- proc.init(exeFile);
- this.log("Running "+exeFile.path+" ("+(blocking?"blocking":"async")+")");
- proc.run(blocking,args,args.length,{});
- if(blocking && proc.exitValue!=0) {
- this.log("Warning: native invocation of\n"
- +exeFile.path
- +"\nwith arguments <"
- +args.join(" ")
- +">\nreturned "+proc.exitValue);
- }
- return proc.exitValue;
- } else {
- this.log("Bad executable "+exeFile);
- }
- } catch(err) {
- this.log("Error running native executable:\n"+exeFile.path+" "+args.join(" ")+"\n"+err.message);
- }
- return 0xffffffff;
- }
- ,
- getWindow: function() {
- return this.service.getWindow();
- }
- ,
- selectFolder: function(links,opType) {
- const cc=Components.classes;
- const ci=Components.interfaces;
- const downloadDirPref="browser.download.dir";
- const autoPref_FF="browser.download.useDownloadDir";
- const autoPref_Moz="browser.download.autoDownload";
-
- var initialDir=null;
- var downloadDir=null;
- links.quickDownload=false;
- const pref = cc["@mozilla.org/preferences-service;1"].getService(ci.nsIPrefBranch);
-
- try {
- initialDir = pref.getComplexValue("browser.download.dir", ci.nsILocalFile);
- } catch(ex) {}
-
- try {
- if(links.quickDownload=pref.getBoolPref(autoPref_FF)) {
- downloadDir=pref.getComplexValue("browser.download.defaultFolder",ci.nsILocalFile);
- }
- } catch(noFFEx) {
- try {
- links.quickDownload=pref.getBoolPref(autoPref_Moz);
- downloadDir=initialDir;
- } catch(noMozEx) {
- links.quickDownload=false;
- }
- }
-
- if(!this.askPath[opType]) return "";
-
- if(downloadDir && downloadDir.exists() && downloadDir.isDirectory() &&
- links.quickDownload) {
- return downloadDir.path;
- }
-
- var title;
- try {
- var bundle = cc["@mozilla.org/intl/stringbundle;1"].getService(ci.nsIStringBundleService);
- bundle = bundle.createBundle("chrome://mozapps/locale/downloads/unknownContentType.properties");
- title = bundle.GetStringFromName("myDownloads");
- } catch(ex) {
- title="Download directory";
- }
- title='FlashGot ('+this.name+') - '+title;
-
-
- const fp = cc["@mozilla.org/filepicker;1"].createInstance(ci.nsIFilePicker);
- const win=this.getWindow();
- fp.init(win, title, ci.nsIFilePicker.modeGetFolder);
- try {
- if (initialDir && initialDir.exists() && initialDir.isDirectory()) {
- fp.displayDirectory = initialDir;
- }
- } catch (ex) { this.log(ex); }
-
- fp.appendFilters(ci.nsIFilePicker.filterAll);
-
- if (fp.show()==ci.nsIFilePicker.returnOK) {
- var localFile = fp.file.QueryInterface(ci.nsILocalFile);
- pref.setComplexValue(downloadDirPref, ci.nsILocalFile, localFile);
- var path=new String(localFile.path);
- path._fgSelected=true;
- return path;
- }
-
- throw new Error("Download cancelled by user");
- }
-
- }
-
- function FlashGotDMX(name,cmd, argsTemplate) {
- if(arguments.length!=0) {
- this._init(name);
- const cmds=FlashGotDMX.prototype.unixCmds;
- cmds[cmds.length]={longName: name, shortName: cmd};
- this.unixCmd=cmd;
- if(argsTemplate) this.argsTemplate=argsTemplate;
- }
- }
- FlashGotDMX.prototype=new FlashGotDM();
- FlashGotDMX.constructor=FlashGotDMX;
- FlashGotDMX.prototype.exeName="flashgot.sh";
- FlashGotDMX.prototype.cookieSupport=false;
- FlashGotDMX.prototype.askPath=[true,true,true];
- FlashGotDMX.prototype.unixCmds=[];
- FlashGotDMX.prototype.unixShell=null;
- FlashGotDMX.prototype.argsTemplate="[URL]";
- FlashGotDMX.prototype.launchSupportTest=function(testFile) {
- const cmds=this.unixCmds;
- var script="(\n";
- var cmd;
- for(var j=cmds.length; j-->0;) {
- cmd=cmds[j];
- script+=" [ -x \"`which '"+cmd.shortName+"'`\" ] && echo '"
- +cmd.longName+"|OK' || echo '"+cmd.longName+"|KO'\n";
- }
- script+=") > '"+ testFile.path + "'\n";
- this.performJob(script,true);
- };
- FlashGotDMX.prototype.createCmdLine=function(URL,REFERER,COOKIE,FOLDER,POST) {
- return this.unixCmd+ " " +
- this.argsTemplate.replace(/\[(.*?)\b(URL|REFERER|COOKIE|FOLDER|POST)\b(.*?)\]/g,
- function(all,before,parm,after) {
- v=eval("typeof("+parm+")=='string'?"+parm+":null");
- return v
- ?before+v+after
- :"";
- }
- ) +" &\n";
- };
- FlashGotDMX.prototype.createJob=function(links,opType) {
- function shellEsc(s) {
- return s?s.replace(/([\\\*\?\[\]\$&<>\|\(\)\{\};"'`])/g,"\\$1").replace(/\s/g,"\\ "):"";
- }
- // basic implementation
- const len=links.length;
- const folder=shellEsc(links.folder);
- const referrer=shellEsc(this.getReferrer(links));
- const postData=shellEsc(links.postData);
- var job="";
- var l,url;
- this.checkCookieSupport();
- for(var j=0; j<len; j++) {
- l=links[j];
- url=l.href;
- job+=this.createCmdLine(
- shellEsc(url),
- referrer,
- shellEsc(this.getCookie(l,links)),
- folder,
- postData);
- this.updateProgress(links,j,len);
- }
- return job;
- };
- FlashGotDMX.prototype.performJob=function(job,blocking) {
- const jobFile=this.createJobFile("#!"+this.unixShell.path+"\n"+job);
- jobFile.permissions=0700;
- this.runNative([],
- this.waitForNative || (typeof(blocking)!="undefined" && blocking),
- jobFile);
- };
- FlashGotDMX.prototype.checkExePlatform=function(exeFile) {
- const f=Components.classes["@mozilla.org/file/local;1"].createInstance(
- Components.interfaces.nsILocalFile);
- try {
- f.initWithPath("/bin/sh");
- if(f.exists()) {
- FlashGotDMX.prototype.unixShell=f;
- return exeFile;
- }
- this.log(f.path+" not found");
- } catch(ex) {
- this.log(ex.message);
- }
- return null;
- };
- FlashGotDMX.prototype.createExecutable=function() {
- return false;
- };
-
- function FlashGotDMMac(name, creatorId, macAppName) {
- if(arguments.length!=0) {
- this._initMac(name,creatorId,macAppName);
- }
- }
- FlashGotDMMac.prototype=new FlashGotDM();
- FlashGotDMMac.constructor=FlashGotDMMac;
- FlashGotDMMac.prototype.exeName="flashgot-mac.sh";
- FlashGotDMMac.prototype.cookieSupport=false;
- FlashGotDMMac.prototype.OSASCRIPT="/usr/bin/osascript";
- FlashGotDMMac.prototype.macCreators=[];
- FlashGotDMMac.prototype._initMac=function(name, creatorId, macAppName) {
- this._init(name);
- if(creatorId) {
- const creators=FlashGotDMMac.prototype.macCreators;
- creators[creators.length]={name: name, id: creatorId};
- }
- this.macAppName = macAppName?macAppName:name;
- };
- FlashGotDMMac.prototype.createScriptLauncher=function(scriptPath) {
- return "#!/bin/sh\n"
- +this.OSASCRIPT+" '"+scriptPath+"'";
- };
- FlashGotDMMac.prototype.checkExePlatform=function(exeFile) {
- const f=Components.classes["@mozilla.org/file/local;1"].createInstance(
- Components.interfaces.nsILocalFile);
- try {
- f.initWithPath(this.OSASCRIPT);
- if(f.exists()) return exeFile;
- this.log(f.path+" not found");
- } catch(ex) {
- this.log(ex.message);
- }
- return null;
- };
- FlashGotDMMac.prototype.createExecutable=function() {
- const exeFile=this.exeFile;
- if(exeFile) {
- try {
- const script=this.service.tmpDir.clone();
- script.append("flashgot-test.scpt");
- FlashGotDMMac.prototype.testAppleScript=script;
- script.createUnique(0,0700);
- if(exeFile.exists()) exeFile.remove(true);
- exeFile.create(0,0700);
- this.service.writeFile(exeFile,this.createScriptLauncher(script.path));
- exeFile.permissions=0700;
- return true;
- } catch(ex) {
- this.log(ex.message);
- }
- }
- return false;
- };
- FlashGotDMMac.prototype.launchSupportTest=function(testFile) {
- const creators=FlashGotDMMac.prototype.macCreators;
- const RESP=" do shell script \"echo >>'"+testFile.path+"' '\" & theName & \"|";
- function response(msg) {
- return RESP+msg+"'\"\n";
- }
- var s="on test(theName, theCreator)\n"
- +" tell app \"Finder\"\n"
- +" set theResponse to \"KO\"\n"
- +" try\n"
- +" get name of application file id theCreator\n"
- +" if result contains theName then\n"
- +" set theResponse to \"OK\"\n"
- +" end if\n"
- +" on error\n"
- +" end try\n"
- +" do shell script \"echo >>'"+testFile.path+"' '\" & theName & \"|\" & theResponse & \"'\"\n"
- +" end tell\n"
- +"end test\n"
- +"\n";
- for(var j=creators.length; j-->0;) {
- s+='get test("'+creators[j].name+'","'+creators[j].id+'")\n';
- }
- this.service.writeFile(this.testAppleScript,s);
- this.runNative([],true,this.exeFile);
- };
- FlashGotDMMac.prototype.performJob=function(job) {
- const script=this.createJobFile(job);
- const launcher=this.createJobFile(this.createScriptLauncher(script.path));
- launcher.permissions=0700;
- this.runNative([],this.waitForNative,launcher);
- };
- FlashGotDMMac.prototype.createJob=function(links,opType) {
- const referrer=this.getReferrer(links);
- var job = "tell application \""+ this.macAppName+ "\"\n";
- for(var j=0,len=links.length; j<len; j++) {
- job+="GetURL \""+links[j].href+"\" from \""+ referrer +"\"\n";
- this.updateProgress(links,j,len);
- }
- job+="end tell\n";
- return job;
- };
-
- // END DMS classes
-
- // DMS initialization
-
- FlashGotDM.initDMS=function() {
- var dm;
-
- dm=new FlashGotDM("Download Accelerator Plus");
- dm.exclusive=true;
-
- new FlashGotDM("Download Master");
-
- new FlashGotDM("FlashGet");
-
- dm=new FlashGotDM("Free Download Manager");
- dm._waitForNative=false;
-
- new FlashGotDM("FreshDownload");
-
- dm=new FlashGotDM("GetRight");
- dm.super_download=FlashGotDM.prototype.download;
- dm.super_createJob=FlashGotDM.prototype.createJob;
- dm.download=function(links, opType) {
- const service=this.service;
- if(opType==service.OP_ONE && !service.getPref("GetRight.quick")) {
- opType=service.OP_SEL;
- }
- this.super_download(links,opType);
- };
- dm.createJob=function(links, opType) {
- const service=this.service;
- var folder=links.folder;
- if(!(folder && folder._fgSelected)) folder=false;
-
- var referrer=this.getReferrer(links);
-
- switch(opType) {
- case service.OP_ONE:
- var job=this.super_createJob(links,opType);
- if(this.service.getPref("GetRight.old")) job+="\nold";
- return job;
- case service.OP_SEL:
- case service.OP_ALL:
- var urlList="";
- var referrerLine=(referrer && referrer.length>0)?"\r\nReferer: "+referrer+"\r\n":"\r\n";
- var l,decodedURL,fileSpec,cookie;
- for(var j=0, len=links.length; j<len; j++) {
- l=links[j];
-
- if(folder) {
- var decodedURL=l.href;
- try { decodedURL=decodeURI(decodedURL) } catch(ex) {};
- var urlParts=decodedURL.match(/\/\/.+[=\/]([^\/]+\.[\w\d]+)/);
- if(!urlParts) urlParts=l.href.match(/.*\/(.+)/);
- if(urlParts && (fileSpec=urlParts[1])
- // && (links.length==1 || !/\.(php|[\w]?htm[l]?|asp|jsp|do|xml|rdf|\d+)$/i.test(fileSpec))
- ) {
- fileSpec="File: "+folder+"\\"+fileSpec+"\r\n";
- } else continue;
- } else fileSpec="";
- urlList+="URL: "+l.href
- +"\r\nDesc: "+l._description
- +referrerLine+fileSpec;
- if(cookie=this.getCookie(l,links)) {
- urlList+="Cookie: " + cookie + "\r\n";
- }
- this.updateProgress(links,j,len);
- }
- var file=service.tmpDir.clone();
- file.append("flashgot.grx");
- file.createUnique(0,0600);
- service.writeFile(file,urlList);
- referrer=file.path;
- break;
- }
- var cmdOpts="/Q";
- if(service.getPref("GetRight.autostart",false)) { // CHECK ME!!!
- cmdOpts+="\n /AUTO";
- }
- return this.createJobHeader({ length: 0, folder: "" },opType) +
- referrer + "\n" + cmdOpts;
- };
- dm.askPath=[false,true,true];
-
- new FlashGotDM("HiDownload");
- new FlashGotDM("InstantGet");
- new FlashGotDM("Internet Download Accelerator");
-
- var lg2002=new FlashGotDM("LeechGet 2002");
- var lg2004=new FlashGotDM("LeechGet");
- lg2004._bgJob=lg2002._bgJob=false;
- lg2004.super_createJob=lg2002.super_createJob=FlashGotDM.prototype.createJob;
- lg2004.createJob=lg2002.createJob=function(links, opType) {
- const service=this.service;
- var referrer;
- switch(opType) {
- case service.OP_ONE:
- return this.super_createJob(links, links.quickDownload?service.OP_ONE:service.OP_SEL);
- case service.OP_SEL:
- var htmlDoc="<html><head><title>FlashGot selection</title></head><body>";
- var l;
- for(var j=0, len=links.length; j<len; j++) {
- l=links[j];
- var des=l._description;
- var tag=l.tagName?l.tagName.toLowerCase():"";
- htmlDoc=htmlDoc.concat(tag=="img"
- ?"<img src=\""+l.href+"\" alt=\""+des
- +"\" width=\""+l.width+"\" height=\""+l.height+
- "\" />\n"
- :"<a href=\""+l.href+"\">"+des+"</a>\n");
- this.updateProgress(links,j,len);
- }
- referrer=service.httpServer.addDoc(
- htmlDoc.concat("</body></html>")
- );
- break;
- default:
- referrer=links.document.URL;
- if(referrer.match(/^\s*file:/i)) { // fix for local URLs
- // we serve local URLs through built-in HTTP server...
- return this.createJob(links,service.OP_SEL);
- }
- }
- return this.createJobHeader({ length: 0, folder: "" },opType)+referrer+"\n";
- };
-
- new FlashGotDM("Net Transport");
- new FlashGotDM("NetAnts");
- new FlashGotDM("Mass Downloader");
-
- new FlashGotDM("ReGet");
-
- const httpFtpRx=/^(http:|ftp:)/;
- const httpFtpValidator=function(url) {
- return this.validLinkRx.test(url);
- };
- dm=new FlashGotDM("Star Downloader");
- dm.cookieSupport=false;
- dm.isValidLink=httpFtpValidator;
- dm._waitForNative=false;
-
- dm=new FlashGotDM("TrueDownloader");
- dm.isValidLink=httpFtpValidator;
- dm._waitForNative=false;
-
- new FlashGotDM("Thunder");
- new FlashGotDM("WellGet");
-
- dm=new FlashGotDMX("Aria","aria", "[-r REFERER] [-d FOLDER] -g [URL]");
- dm.createJob=function(links,opType) {
- return FlashGotDMX.prototype.createJob.call(this,links,opType) + "\nsleep 4\n" + this.unixCmd+" -s &\n";
- };
- dm._waitForNative=false;
-
- dm=new FlashGotDMX("Downloader 4 X (nt)","nt");
- dm.createJob=function(links,opType) {
- return this.unixCmd+"&\nsleep 1\n" +
- (links.folder && links.folder._fgSelected
- ? this.unixCmd+" -d '"+links.folder+"'\n"
- :"") +
- FlashGotDMX.prototype.createJob.call(this,links,opType);
- };
- (new FlashGotDMX("Downloader 4 X","d4x")).createJob=dm.createJob;
-
- dm=new FlashGotDMX("KDE KGet","kget");
- dm.askPath=[false,false,false];
- dm.createJob=function(links,opType) {
- return FlashGotDMX.prototype.createJob.call(this,links,opType);
- };
-
- // Needs a lot of work, not ready for prime time
-
- dm=new FlashGotDMX("cURL","curl", '-L -O [--referer REFERER] [-b COOKIE] [-d POST] [URL]');
- dm.createJob=function(links,opType) {
- var job="[ -x \"`which 'xterm'`\" ] && CURL_CMD='xterm -e curl' || CURL_CMD='curl'\n";
- if (links.folder) job+="cd '"+links.folder+"'\n";
- this.unixCmd="$CURL_CMD";
- return job + FlashGotDMX.prototype.createJob.call(this,links,opType);
- };
-
-
- function FlashGotDMSD(version) {
- this._initMac("Speed Download "+version,"Spee");
- this.version=version;
- };
- FlashGotDMSD.prototype=new FlashGotDMMac();
- FlashGotDMSD.prototype.createJob=function(links,opType) {
- const v=this.version;
-
- var job = "tell app \""+ this.macAppName+ "\" to AddURL {";
- var urlList=[];
- var cookieList=[];
- var l;
- for(var j=0,len=links.length; j<len; j++) {
- l=links[j];
- urlList[urlList.length]='"'+l.href+'"';
- if(v>2) {
- cookieList[cookieList.length]='"'+this.getCookie(l,links)+'"';
- }
- this.updateProgress(links,j,len);
- }
- job+=urlList.join(',')+"}";
- if(v>2) {
- if(links.postData && links.postData.length) {
- job+=' with form data "'+links.postData+'"';
- }
- const referer=this.getReferrer(links);
- if(referer && referer.length) {
- job+=' from "'+referer+'"';
- }
- if(cookieList.length) {
- job+=' with cookies {' + cookieList.join(',') + '}';
- }
- }
- return job;
- };
-
- new FlashGotDMSD(2);
- new FlashGotDMSD(3).cookieSupport=true;
-
- new FlashGotDMMac("iGetter","iGET");
-
- FlashGotDM.dms.sort(function(a,b) { a=a.name.toLowerCase(); b=b.name.toLowerCase(); return a>b?1:a<b?-1:0; });
-
-
- };
- FlashGotDM.initDMS();
-
- const SHUTDOWN="profile-before-change";
- const STARTUP="profile-after-change";
-
- function FlashGotService() {
-
- const osvr=Components.classes['@mozilla.org/observer-service;1'].getService(
- Components.interfaces.nsIObserverService);
-
- osvr.addObserver(this,SHUTDOWN,false);
- osvr.addObserver(this,"xpcom-shutdown",false);
- osvr.addObserver(this,STARTUP,false);
-
- Components.classes["@mozilla.org/uriloader;1"].getService(
- Components.interfaces.nsIURILoader).registerContentListener(this);
-
- }
-
- FlashGotService.prototype = {
- OP_ONE: 0,
- OP_SEL: 1,
- OP_ALL: 2,
- OP_QET: 3
- ,
- get wrappedJSObject() {
- return this;
- }
- ,
- unregister: function() {
- try {
- const osvr=Components.classes['@mozilla.org/observer-service;1'].getService(
- Components.interfaces.nsIObserverService);
- osvr.removeObserver(this,SHUTDOWN);
- osvr.removeObserver(this,"xpcom-shutdown");
- osvr.removeObserver(this,STARTUP);
- Components.classes["@mozilla.org/uriloader;1"].getService(
- Components.interfaces.nsIURILoader).unRegisterContentListener(this);
- } catch(ex) {
- this.log("Error unregistering service as observer: "+ex);
- }
- }
- ,
- QueryInterface: function(iid) {
- xpcom_checkInterfaces(iid,SERVICE_IIDS,Components.results.NS_ERROR_NO_INTERFACE);
- return this;
- }
- ,
- /* nsIObserver */
- observe: function(subject, topic, data) {
- if(subject==this.prefs) {
- this.syncPrefs(data);
- } else {
- switch(topic) {
- case "xpcom-shutdown":
- this.unregister();
- break;
- case SHUTDOWN:
- this.cleanup();
- break;
- case STARTUP:
- // apparently the following caused problems reported in 0.5.9.5
- // this.initGlobals();
- break;
- }
- }
- }
- ,
- syncPrefs: function(name) {
- this.logEnabled=this.getPref("logEnabled",true);
- if(name) {
- switch(name) {
- case "hide-icons":
- var w;
- for(var wins=this.windowMediator.getEnumerator(null); wins.hasMoreElements();) {
- w=wins.getNext();
- if(typeof(w.flashGot)=="object" && w.flashGot.toggleMainMenuIcon) {
- w.flashGot.toggleMainMenuIcon();
- }
- }
- }
- }
- }
- ,
- _shouldIntercept: function(contentType) {
- if(this.bypassAutostart || !this.DMS.found) {
- return false;
- }
- if(this.forceAutostart) return true;
- if(!this.getPref("autoStart",true)) return false;
-
- if(this.getPref("interceptAll",false)) {
- if(!/\bxpinstall\b/.test(contentType)) {
- return true;
- }
- }
-
- if(contentType=="application/x-unknown-content-type") return false;
- var ms=Components.classes['@mozilla.org/uriloader/external-helper-app-service;1'
- ].getService(Components.interfaces.nsIMIMEService);
- const exts=this.extensions;
- for(var j=exts.length; j-->0;) {
- if(contentType==ms.getTypeFromExtension(exts[j])) return true;
- }
-
- }
- ,
- _willHandle: function(url, contentType) {
- if(!/^(http|https|ftp|sftp|rtsp|mms):/i.test(url) ) {
- if((/^\s*javascript/i).test(url)) this.log("JavaScript url intercepted: "+url);
- return false;
- }
- return true;
- }
- ,
- /* nsIURIContentListener */
- canHandleContent: function(contentType, isContentPreferred, desiredContentType) {
- return this._shouldIntercept(contentType);
- }
- ,
- doContent: function(contentType, isContentPreferred, channel, contentHandler) {
- const ci=Components.interfaces;
- channel.QueryInterface(ci.nsIChannel);
- const uri=channel.URI;
-
- if(!this._willHandle(uri.spec,contentType)) {
- throw new Error("FlashGot not interested in "+contentType+" from "+uri.spec);
- }
-
- this.log("Intercepting download...");
-
- const pathParts=uri.path.split(/\//);
- var links=[ {
- href: channel.URI.spec,
- title: pathParts[pathParts.length-1]
- } ];
-
- if(channel instanceof ci.nsIHttpChannel) {
- links.referrer=channel.referrer.spec;
- if(channel instanceof ci.nsIUploadChannel
- && channel.uploadStream instanceof Components.interfaces.nsISeekableStream) {
- this.log("Extracting post data...");
- try {
- channel.uploadStream.seek(0,0);
- const sis=Components.classes[
- '@mozilla.org/scriptableinputstream;1'].createInstance(
- ci.nsIScriptableInputStream);
- sis.init(channel.uploadStream);
- var postData=sis.read(sis.available()).replace(/\s$/,'').split(/[\r\n]/);
- links.postData=postData[postData.length-1];
- sis.close();
- } catch(ex) {
- this.log(ex.message);
- }
- }
- }
-
- if(this.download(links)) {
- this.log("...interception done!");
- } else {
- throw new Error("Can't download from this URL: "+uri.spec);
- }
-
- channel.cancel(Components.results.NS_BINDING_ABORTED);
-
- this.log("Original request cancelled.");
- contentHandler.value=null;
- return true;
- }
- ,
- isPreferred: function(contentType, desiredContentType) {
- return this._shouldIntercept(contentType);
- }
- ,
- onStartURIOpen: function(uri) {
- return false;
- }
- ,
- mailer: false // is Thunderbird?
- ,
- get defaultDM() {
- return this.getPref("defaultDM",null);
- }
- ,
- set defaultDM(name) {
- this.setPref("defaultDM", name);
- return name;
- }
- ,
- get tmpDir() {
- return this.globals.tmpDir;
- }
- ,
- get profDir() {
- return this.globals.profDir;
- }
- ,
- get DMS() {
- return this.globals.DMS;
- }
- ,
- get extensions() {
- var s=this.getPref("extensions","");
- return s?s.split(','):[];
- }
- ,
- set extensions(v) {
- var arr=null;
- var s = typeof(v)=="string"
- ? v : typeof(v)=="object" && typeof(v.join)=="function"
- ? (arr=v).join(',') : "";
- this.setPref("extensions", s);
- return arr?arr:[];
- }
- ,
- addExtension: function(ext) {
- if(ext) {
- var extensions=this.extensions;
- if(!this.extensionExists(ext,extensions)) {
- extensions[extensions.length]=ext;
- extensions.sort();
- this.extensions=extensions;
- return true;
- }
- }
- return false;
- }
- ,
- removeExtension: function(ext) {
- var extensions=this.extensions;
- var j=this.indexOfExtension(ext,extensions);
- if(j>-1) {
- extensions.splice(j,1);
- this.extensions=extensions;
- return true;
- }
- return false;
- }
- ,
- extensionExists: function(ext,extensions) {
- return this.indexOfExtension(ext,extensions)>-1;
- }
- ,
- indexOfExtension: function(ext,extensions) {
- var ext=ext.toLowerCase();
- if(typeof(extensions)!="object") extensions=this.extensions;
- for(var j=extensions.length; j-->0;) {
- if(extensions[j].toLowerCase()==ext) return j;
- }
- return -1;
- }
- ,
-
- get httpServer() {
- return (!this._httpServer) || this._httpServer.isDown
- ?this._httpServer=new FlashGotHttpServer(this)
- :this._httpServer;
- }
-
- ,
- download: function(links, opType, dmName) {
- if(links.length==0) return false;
- if(!opType) opType=links.length>1?this.OP_SEL:this.OP_ONE;
- if(!dmName) dmName=this.defaultDM;
- const dm=this.globals.DMS[dmName];
- if(!dm) {
- this.log("FlashGot error: no download manager selected!");
- return false;
- }
- const encodedURLs=this.getPref(dm.codeName+".encode",this.getPref("encode",true));
-
- if(!links.postData) links.postData="";
- links.progress = { value: 0 };
-
- function parseDesc(link) {
- return link._description?link._description.replace(/\s+/g," ")
- :link._description = (typeof(link.title)=="string" && link.title.length>0
- ?link.title.replace(/\s+/g," "):link.innerHTML
- ?link.innerHTML.replace(/\s+/g," ").replace(/<.*?>/g,"")
- :"");
- }
-
- function prepareArray() {
- var l,j,len;
- for(j=0,len=links.length; j<len; j++) {
- l=links[j];
- links[j]={
- href: l.href,
- _description: parseDesc(l),
- _position: j
- };
- }
- }
-
- function processLinks() {
- const pg=links.progress;
- var len=links.length;
- if(len>1) {
- pg.value=12;
- // sort by href asc,_description.length desc
- dm.log("Sorting links");
- links.sort(function(a,b) {
- var aurl,burl,ades,bdes;
- return (aurl=a.href)>(burl=b.href)?1:aurl<burl?-1
- :(ades=a._description.length)>(bdes=b._description.length)?-1:ades<bdes?1
- :0;
- });
- }
- pg.value=24;
- //kill duplicates and sanitize
- dm.log("Killing duplicates and sanitizing");
- const escapeCheckNo=/(%[0-9a-f]{2,4})/i;
- const escapeCheckYes=/[\s]+/;
- var j,len,l,href,urlParts;
- var currentURL=null;
- var pos1,pos2;
- for(j=0,len=links.length; j<len; j++) {
- l=links[j];
- href=l.href;
- if( href==currentURL || (len>1 && !dm.isValidLink(href)) ) {
- links.splice(j--,1);
- --len;
- } else {
- currentURL=href;
- try {
- if(encodedURLs) {
- if(escapeCheckYes.test(href) || !escapeCheckNo.test(href)) {
- href=encodeURI(href);
- }
- // workaround for malformed hash urls... I have still to think about it :-)
- while((pos1=href.indexOf('#'))>-1
- && ((pos2=href.indexOf('?'))<0
- || pos2>pos1 || pos1!=href.lastIndexOf('#'))) {
- href=href.substring(0,pos1)+'%23'+href.substring(pos1+1);
- }
- l.href=href;
- } else {
- l.href=decodeURI(href);
- }
- } catch(e) {
- dm.log("Problem "
- +encodedURLs?"escaping":"unescaping"
- +" URL "+href+": "+e.message);
- }
- }
- pg.value=25+25*j/len;
- }
- if(len>1) {
- dm.log("Sorting again "+links.length+" links");
- links.sort(function(a,b) {
- a=a._position; b=b._position;
- return a>b?1:a<b?-1:0;
- });
- dm.log("Preprocessing done");
- }
- }
-
-
-
- function trueDownload() {
- links.progress.value=50;
- dm.log("Starting download");
- dm.download(links,opType);
- }
-
- prepareArray();
-
- this.log("Processing "+links.length+" links");
- if(links.length>1 && this.bgProcessing) {
- this.log("(background processing)");
- this.runAsync(
- processLinks,
- trueDownload);
- } else {
- this.log("(blocking processing)");
- processLinks();
- trueDownload();
- }
- return true;
- }
- ,
- get bgProcessing() {
- return this.getPref("bgProcessing",true);
- }
- ,
- runAsync: function(asyncJob,postJob) {
- const cc=Components.classes;
- const ci=Components.interfaces;
- var postRunnable=null;
-
- if(postJob) {
- postRunnable = cc["@mozilla.org/xpcomproxy;1"].getService(ci.nsIProxyObjectManager
- ).getProxyForObject(
- cc["@mozilla.org/event-queue-service;1"].getService(ci.nsIEventQueueService
- ).getSpecialEventQueue(ci.nsIEventQueueService.UI_THREAD_EVENT_QUEUE),
- ci.nsIRunnable,
- {
- QueryInterface: function(iid) {
- if(iid.equals(ci.nsISupport) || iid.equals(ci.nsIRunnable)) {
- return this;
- }
- throw Components.results.NS_ERROR_NO_INTERFACE;
- },
- run: function() { postJob(); }
- }
- , 5); // 5 == PROXY_ALWAYS | PROXY_SYNC
- }
-
- const asyncRunnable={
- run: function() {
- try {
- asyncJob();
- } catch(ex) {
- }
- if(postRunnable) postRunnable.run();
- }
- };
-
- const thread=cc['@mozilla.org/thread;1'].createInstance(ci.nsIThread);
- this.uiThread=thread.currentThread;
- thread.init(asyncRunnable, 0,
- ci.nsIThread.PRIORITY_NORMAL, ci.nsIThread.SCOPE_GLOBAL, ci.nsIThread.STATE_JOINABLE);
- }
- ,
- get prefService() {
- return Components.classes["@mozilla.org/preferences-service;1"].getService(
- Components.interfaces.nsIPrefService);
- }
- ,
- getPref: function(name,def) {
- const IPC=Components.interfaces.nsIPrefBranch;
- const prefs=this.prefs;
- try {
- switch(prefs.getPrefType(name)) {
- case IPC.PREF_STRING:
- return prefs.getCharPref(name);
- case IPC.PREF_INT:
- return prefs.getIntPref(name);
- case IPC.PREF_BOOL:
- return prefs.getBoolPref(name);
- }
- } catch(e) {}
- return def;
- }
- ,
- setPref: function(name,value) {
- const prefs=this.prefs;
- switch(typeof(value)) {
- case "string":
- prefs.setCharPref(name,value);
- break;
- case "boolean":
- prefs.setBoolPref(name,value);
- break;
- case "number":
- prefs.setIntPref(name,value);
- break;
- default:
- throw new Error("Unsupported type "+typeof(value)+" for preference "+name);
- }
- }
- ,
- uiThread: null
- ,
- get isUIThread() {
- // returns true if current thread is equal to uiThread
- // if uiThread is not initialized, it gets initialized with current thread
- // and returned
- const uiThread=this.uiThread;
- const currentThread=this.currentThread;
- return uiThread?uiThread==currentThread:this.uiThread=currentThread;
- }
- ,
- get currentThread() {
- return Components.classes['@mozilla.org/thread;1'
- ].createInstance(Components.interfaces.nsIThread).currentThread;
- }
- ,
- _logFile: null,
- get logFile() {
- if(this._logFile==null) {
- this._logFile=this.profDir.clone();
- this._logFile.append("flashgot.log");
- }
- return this._logFile;
- }
- ,
- logStream: null,
- logEnabled: false,
- log: function(msg) {
- if(this.logEnabled) {
- try {
- if(!this.logStream) {
- const logFile=this.logFile;
- const logStream=Components.classes["@mozilla.org/network/file-output-stream;1"
- ].createInstance(Components.interfaces.nsIFileOutputStream );
- logStream.init(logFile, 0x02 | 0x08 | 0x10, 0600, 0 );
- this.logStream=logStream;
- const header="*** Log start at "+new Date().toGMTString()+"\n";
- this.logStream.write(header,header.length);
- }
-
- if(msg!=null) {
- msg+="\n";
- this.logStream.write(msg,msg.length);
- }
- this.logStream.flush();
- } catch(ex) {
- if(this.isUIThread) dump(ex.message+"\noccurred logging this message:\n"+msg);
- }
- }
- }
- ,
- dumpStack: function(msg) {
- dump( (msg?msg:"")+"\n"+new Error().stack+"\n");
- }
- ,
- clearLog: function() {
- try {
- if(this.logStream) {
- try {
- this.logStream.close();
- } catch(eexx) {
- dump(eexx.message);
- }
- }
- if(this.logFile) this.logFile.remove(true);
- this.logStream=null;
- this.log(null);
- } catch(ex) { dump(ex.message); }
- }
- ,
- get windowMediator() {
- return Components.classes["@mozilla.org/appshell/window-mediator;1"
- ].getService(Components.interfaces.nsIWindowMediator);
- }
- ,
- getWindow: function() {
- return this.windowMediator.getMostRecentWindow(null);
- }
- ,
- checkLocale: function() {
- if(typeof(this._checkedLocale)=="undefined") {
- try {
- this._checkedLocale=(new IA_LocaleChecker("flashgot")).check();
- } catch(ex) {
- this.log("Locale check failed: "+ex);
- this._checkedLocale=null;
- }
- }
- return this._checkedLocale;
- }
- ,
- _globals: null,
- get globals() {
- if(!this._initialized) {
- const currentThread=this.currentThread;
- if(currentThread==this._initThread) return this._globals;
- this.initGlobals();
- for(var t=0; !this._initialized; t++) {
- currentThread.sleep(100);
- if(t>60) {
- this._initialized=true;
- throw new Error("FlashGot initialization timeout");
- }
- }
- }
- return this._globals;
- }
- ,
- PREFS_BRANCH: "flashgot."
- ,
- _prefs: null,
- get prefs() {
- var prefs=this._prefs;
- if(!prefs) {
- this._prefs=prefs=this.prefService.getBranch(this.PREFS_BRANCH
- ).QueryInterface(Components.interfaces.nsIPrefBranchInternal);
- }
- return prefs;
- }
- ,
- _initialized: false,
- _initializing: false,
- _initThread: null,
- _initException: null,
- initGlobals: function() {
- // this.dumpStack("FG.initGlobals()");
- if(this._globals || this._initializing || this._initialized) return;
- this._initializing=true;
- const service=this;
- this.runAsync(function() { service._asyncInit(); });
- }
- ,
- _asyncInit: function() {
- function prepareTmp(t) {
- t.append("flashgot");
- t.createUnique(1,0700);
- return t;
- }
- try {
-
- this._initThread=this.currentThread;
-
- const startTime=new Date().getTime();
- const prefs=this.prefs;
- const cc=Components.classes;
- const ci=Components.interfaces;
-
- const fileLocator=cc["@mozilla.org/file/directory_service;1"].getService(
- ci.nsIProperties);
- const profDir=fileLocator.get("ProfD",ci.nsIFile);
- var tmpDir;
- try {
- tmpDir=prepareTmp(prefs.getComplexValue("tmpDir", ci.nsILocalFile));
- } catch(ex) {
- tmpDir=prepareTmp(fileLocator.get("TmpD",ci.nsIFile));
- }
-
- this._globals={
- tmpDir: tmpDir,
- profDir: profDir,
- prefs: prefs
- };
-
- prefs.addObserver("", this, false);
- this.syncPrefs();
-
- this.log("Per-session init started");
-
- this._setupLegacyPrefs();
-
- this._globals.DMS=this.checkDownloadManagers();
- this.log("Per-session init done in "+(new Date().getTime()-startTime)+"ms");
- } catch(initEx) {
- this._initException=initEx;
- }
- this._initializing=false;
- this._initialized=true;
- }
- ,
- dispose: function() {
- this.prefs.removeObserver("",this);
- this._prefs=null;
- this._initializing=this._initialized=false;
- this._initThread=this._initException=null;
- this._globals=null;
- }
- ,
- checkDownloadManagers: function() {
-
- const dms=FlashGotDM.dms;
- dms.found=false;
-
-
- var defaultDM=this.defaultDM;
- if(!dms[defaultDM]) defaultDM=null;
- var firstSupported=null;
- var dm;
- for(var j=dms.length; j-- >0;) {
- dm=dms[j];
- if(dm.supported ) {
- dms.found=true;
- firstSupported=dm.name;
- } else {
- this.log("Warning: download manager "+dm.name+" not found");
- if(defaultDM==dm.name) {
- defaultDM=null;
- this.log(dm.name+" was default download manager: resetting.");
- }
- if(dm.exclusive) {
- dms.splice(j,1);
- }
- }
- }
-
- if( (!defaultDM) && firstSupported!=null) {
- this.defaultDM=firstSupported;
- this.log("Default download manager set to "+this.defaultDM);
- } else if(!dms.found) {
- this.log("Serious warning! no supported download manager found...");
- } else {
- if(dms[defaultDM].exclusive) {
- for(j=dms.length; j-->0;) {
- if(dms[j].name!=defaultDM) {
- dms.splice(j,1);
- }
- }
- }
- }
-
- return dms;
- }
- ,
- _cleaningup: false
- ,
- cleanup: function() {
- if(this._cleaningup) return;
- try {
- this._cleaningup=true;
- this.log("Starting cleanup");
- if(this._httpServer) {
- this._httpServer.shutdown();
- }
-
- try {
- FlashGotDM.cleanup();
- } catch(eexx) {
- dump(eexx.message);
- }
-
- if(this._globals && this._globals.tmpDir.exists()) {
- this._globals.tmpDir.remove(true);
- }
-
- this.log("Cleanup done");
- if(this._logFile) try {
- if(this.logStream) this.logStream.close();
- var maxLogSize=Math.max(Math.min(this.getPref('maxLogSize',100000),1000000),50000);
- const logFile=this.logFile;
- const logSize=logFile.fileSize;
- if(logSize>maxLogSize) { // log rotation
- dump("Cutting log (size: "+logSize+", max: "+maxLogSize+")");
- const cc=Components.classes;
- const ci=Components.interfaces;
-
- const logBak=logFile.clone();
- logBak.leafName=logBak.leafName+".bak";
- if(logBak.exists()) logBak.remove(true);
- logFile.copyTo(logBak.parent,logBak.leafName);
- const is=cc['@mozilla.org/network/file-input-stream;1'].createInstance(
- ci.nsIFileInputStream);
- is.init(logBak,0x01, 0400, null);
- is.QueryInterface(ci.nsISeekableStream);
- is.seek(ci.nsISeekableStream.NS_SEEK_END,-maxLogSize);
- const sis=cc['@mozilla.org/scriptableinputstream;1'].createInstance(
- ci.nsIScriptableInputStream);
- sis.init(is);
- var buffer;
- var content="\n";
- var logStart=-1;
- while(buffer=sis.read(5000)) {
- content+=buffer;
- if((logStart=content.indexOf("\n*** Log start at "))>-1) {
- content=content.substring(logStart);
- break;
- }
- content=buffer;
- }
- if(logStart>-1) {
- const os=cc["@mozilla.org/network/file-output-stream;1"].createInstance(
- ci.nsIFileOutputStream);
- os.init(logFile,0x02 | 0x08 | 0x20, 0700, 0);
- os.write(content,content.length);
- while(buffer=sis.read(20000)) {
- os.write(buffer,buffer.length);
- }
- os.close();
- }
- sis.close();
- }
- } catch(eexx) {
- dump("Error cleaning up log: "+eexx.message);
- }
- this.logStream=null;
- } catch(ex) {
- this.log(ex.message);
- }
- this._cleaningup=false;
- this.dispose();
- }
- ,
- readFile: function(file) {
- const cc=Components.classes;
- const ci=Components.interfaces;
-
- const is = cc["@mozilla.org/network/file-input-stream;1"].createInstance(
- ci.nsIFileInputStream );
- is.init(file ,0x01, 0400, null);
- const sis = cc["@mozilla.org/scriptableinputstream;1"].createInstance(
- ci.nsIScriptableInputStream );
- sis.init(is);
- const res=sis.read(sis.available());
- is.close();
- return res;
- }
- ,
- writeFile: function(file, content) {
- const cc=Components.classes;
- const ci=Components.interfaces;
- const unicodeConverter = cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(
- ci.nsIScriptableUnicodeConverter);
- unicodeConverter.charset = "UTF-8";
- content=unicodeConverter.ConvertFromUnicode(content);
- const os=cc["@mozilla.org/network/file-output-stream;1"].createInstance(
- ci.nsIFileOutputStream);
- os.init(file,0x02,0700,0);
- os.write(content,content.length);
- os.close();
- }
- ,
- _setupLegacyPrefs: function() {
- try {
- const file=this._globals.profDir.clone();
- const defFile=file.clone();
- file.append("pref");
- file.append("flashgot.js");
- defFile.append("prefs.js");
- if(file.exists() && defFile.exists()) {
- this.prefService.readUserPrefs(file);
- this.prefService.readUserPrefs(defFile);
- this.prefService.savePrefFile(null);
- file.remove(true);
- }
- } catch(e) {
- this.log(e.message);
- }
- }
- ,
- showDMSReference: function() {
- this.getWindow().open("http://www.flashgot.net/dms","_blank");
- }
- ,
- _dirtyJobsDone: false,
- doDirtyJobs: function() {
- if(this._dirtyJobsDone) {
- return;
- }
- const cc=Components.classes;
- const ci=Components.interfaces;
- const locator = cc["@mozilla.org/file/directory_service;1"].getService(ci.nsIProperties);
- const chromeDirs=[locator.get("AChrom", ci.nsIFile).path,
- locator.get("UChrm", ci.nsIFile).path];
- const rdf = cc["@mozilla.org/rdf/rdf-service;1"].getService(ci.nsIRDFService);
- const rdfUtil = cc["@mozilla.org/rdf/container-utils;1"].getService(ci.nsIRDFContainerUtils);
- const overlays=new Object();
- overlays['browser']
- =overlays['navigator']
- =["chrome://flashgot/localeCheckOverlay.xul","chrome://flashgot/content/localeCheckOverlay.xul"];
-
- var url, ds, overlayName, overlay, literal, res, src;
- for(var j = 0; j < chromeDirs.length; j++) { // Application & Profile Dirs
- // Loop files
- var overlayDir=chromeDirs[j].replace(/\\/g,'/')+'/overlayinfo/';
- for(overlayName in overlays){
- try{
- url="file:///"+ overlayDir +overlayName+ '/content/overlays.rdf';
- ds = rdf.GetDataSourceBlocking(url).QueryInterface(ci.nsIRDFRemoteDataSource);
- // Loop overlay elements for this file
- var overlay=overlays[overlayName];
- for(var i = 0; i < overlay.length; i++){
- var literal=rdf.GetLiteral(overlay[i]);
- // Find Element
- var archs = ds.ArcLabelsIn(literal);
- while(archs.hasMoreElements()){
- var res = archs.getNext().QueryInterface(ci.nsIRDFResource);
- var sources = ds.GetSources(res, literal, true);
-
- // Get parent element for element
- while(sources.hasMoreElements()){
- src = sources.getNext().QueryInterface(ci.nsIRDFResource);
-
- try {
- ds.Unassert(src, res, literal);
- this.log("Removed "+ literal.Value +" from "+url);
- } catch(ex) {
- this.log("Failed to remove "+ listeral.Value +" from "+url);
- this.log(ex.message);
- }
- }
- }
- }
-
- ds.Flush();
- this.log("Cleaned "+url);
- } catch(ex) {
- this.log("Failed to clean "+url);
- this.log(ex.message);
- }
- }
- }
-
- try {
- const xulFile=locator.get("ProfD", ci.nsIFile).clone();
- xulFile.append("XUL.mfl");
- xulFile.remove(true);
- this.log(xulFile.path+" deleted");
- } catch(ex) {
- this.log("Failed to delete XUL.mfl: "+ex.message);
- }
- this._dirtyJobsDone=true;
- }
- }
-
- /* Data Swap HTTP server */
-
- FlashGotHttpServer=function(fgService) {
- this.fgService=fgService;
- this.isDown=true;
- this.serverSocket=Components.classes['@mozilla.org/network/server-socket;1'
- ].createInstance(Components.interfaces.nsIServerSocket);
- this.serverSocket.init(-1,true,-1);
- this.isDown=false;
- this.serverSocket.asyncListen(this);
- this.tmpDir=this.fgService.globals.tmpDir.clone();
- this.tmpDir.append("httpserv");
- this.logEnabled=fgService.getPref("LeechGet.httpLog",false);
- this.log("Listening");
- }
-
- FlashGotHttpServer.prototype={
- documents: []
- ,
- log: function(msg){
- if(this.logEnabled && this.fgService.logEnabled) {
- try {
- if(!this.logStream) {
- const logFile=this.tmpDir.clone();
- logFile.append("server.log");
- logFile.createUnique(0,0600);
- const logStream=Components.classes["@mozilla.org/network/file-output-stream;1"
- ].createInstance(Components.interfaces.nsIFileOutputStream );
- logStream.init(logFile, 0x02 | 0x10, 0600, 0 );
- this.logStream=logStream;
- }
- msg="HttpServer:"+this.serverSocket.port+" - "+msg+"\n";
- this.logStream.write(msg,msg.length);
- this.logStream.flush();
- } catch(ex) {}
- }
- }
- ,
- onSocketAccepted: function(ss,transport) {
- this.log("Accepted request from "
- +transport.host+":"+transport.port);
- try {
- new FlashGotHttpHandler(this,transport);
- } catch(ex) {
- this.log(ex.message);
- }
- }
- ,
- onStopListening: function(ss,status) {
- this.isDown=true;
- if(this.logStream) {
- this.log("Stopped, status "+status);
- }
- }
- ,
- randomName: function(len) {
- if(!len) len=8;
- var name="";
- for(var j=len; j-->0;) {
- name+=String.fromCharCode(65+(Math.round(Math.random()*25)));
- }
- return name;
- }
- ,
- addDoc: function(docSource,docType) {
- if(typeof(docType)=="undefined") docType="html";
- var file=this.tmpDir.clone();
- file.append(this.randomName()+"."+docType);
- file.createUnique(0,0600);
- this.fgService.writeFile(file,docSource);
- const name=file.leafName;
- this.documents.push(name);
- return "http://localhost:"+this.serverSocket.port+"/"+name;
- }
- ,
- getDoc: function(name) {
- const docs=this.documents;
- for(var j=docs.length; j-->0;) {
- if(docs[j]==name) break;
- }
- if(j<0) return null;
- var file=this.tmpDir.clone();
- file.append(name);
- return file.exists()?this.fgService.readFile(file):null;
- }
- ,
- shutdown: function() {
- try {
- this.log("Shutting down");
- if(this.logStream) {
- this.logStream.close();
- this.logStream=null;
- }
- this.serverSocket.close();
- } catch(ex) {}
- }
- }
-
- function FlashGotHttpHandler(server,transport) {
- this.server=server;
- this.inputBuffer="";
- this.transport=transport;
- this.asyncStream=transport.openInputStream(0,0,0).QueryInterface(
- Components.interfaces.nsIAsyncInputStream);
- this.log("Waiting for request data...");
-
- const nsIThread=Components.interfaces.nsIThread;
- var thread=Components.classes['@mozilla.org/thread;1'].createInstance(nsIThread);
- thread.init(this, 0, nsIThread.PRIORITY_NORMAL, nsIThread.SCOPE_GLOBAL,nsIThread.STATE_JOINABLE);
- this.log("Thread started");
- }
-
- FlashGotHttpHandler.prototype = {
- log: function(msg) {
- this.server.log(this.transport.host+":"+this.transport.port+" - "+msg);
- }
- ,
- run: function() {
- this.log("I'm in thread");
- this.asyncStream.asyncWait(this,0,0,null);
- this.log("Asyncwait issued");
- }
- ,
- onInputStreamReady: function(asyncStream) {
- const bytesCount=asyncStream.available();
- this.log("Input stream ready, available bytes: "+bytesCount);
- if(bytesCount) {
- const inStream=Components.classes['@mozilla.org/scriptableinputstream;1'].createInstance(
- Components.interfaces.nsIScriptableInputStream);
- inStream.init(asyncStream);
- var chunk=inStream.read(inStream.available());
- this.log("Received data chunk "+chunk);
- var buffer=this.inputBuffer.concat(chunk);
- var eor=chunk.length==0?buffer.length:buffer.search("\r?\n\r?\n");
- this.log("EOR: "+eor);
- if(eor>-1) {
- var request=buffer.substring(0,eor);
- this.inputBuffer="";
- this.handleRequest(request);
- this.close();
- } else {
- this.inputBuffer=buffer;
- this.run();
- }
- } else {
- this.close();
- }
- }
- ,
- close: function() {
- this.asyncStream.close();
- }
- ,
- buildResponse: function(body,status,contentType) {
- if(!contentType) contentType="text/html";
- if(!status) {
- status="200 OK";
- } else {
- body="<h1>"+status+"</h1><pre>"
- +body
- +"</pre><h5>FlashGot Http Server v. 0.1</h5>"
- }
- return "HTTP/1.1 "+status+"\r\nContent-type: "+contentType+"\r\n\r\n"+body;
- }
- ,
- handleRequest: function(request) {
- var response;
- var match;
- this.log("Handling request\n"+request);
- try {
- if(!(match=request.match(/^GET \/([^\s]*)/))) {
- response=this.buildResponse(request,"400 Bad Request");
- } else {
- var doc=this.server.getDoc(match[1]);
-
- if(doc==null) {
- response=this.buildResponse(request,"404 Not Found");
- } else {
- response=this.buildResponse(doc);
- }
- }
- } catch(ex) {
- response=this.buildResponse(ex.message+"\n"+request,"500 Server error");
- }
- var out=this.transport.openOutputStream(1,0,0);
- out.write(response,response.length);
- out.close();
- this.log("Sent response\n"+response);
- }
- }
-
-
- /* Locale check */
- IA_LocaleChecker=function(module) {
- this.module=module;
- }
-
- IA_LocaleChecker.prototype = {
-
- check: function() {
- const module=this.module;
- const cc=Components.classes;
- const ci=Components.interfaces;
-
- const localeURL="chrome://"+module+"/locale";
-
- try {
- const window=cc['@mozilla.org/appshell/appShellService;1'
- ].getService(ci.nsIAppShellService
- ).hiddenDOMWindow
- } catch(ex) {}
-
- function log(msg) {
- dump("LocaleChecker: "+msg+"\n");
- }
-
- function checkLocale(locale) {
- function isLocaleSelected() {
- try {
- return chreg.getSelectedLocale(module)==locale;
- } catch(ex) {
- log(ex.message);
- return false;
- }
- }
-
- try {
- if(!isLocaleSelected()) {
- log("trying to select locale "+locale);
- chreg.selectLocaleForPackage(locale,module,true);
- if(isLocaleSelected()) {
-
- for(var j=2; j-->0;) {
- chreg.checkForNewChrome();
- chreg.reloadChrome();
- log("chrome reloaded! "+j);
- }
-
- } else {
- log("Can't select locale "+locale+" for "+module);
- locale=null;
- }
- }
- } catch(ex) {
- log("Error checking/setting locale "+locale+" for "+module+"\n"+ex.message);
- locale=null;
- }
- return locale;
- }
-
- var chreg=cc["@mozilla.org/chrome/chrome-registry;1"].getService(ci.nsIChromeRegistry);
- try {
- if(ci.nsIXULChromeRegistry) chreg.QueryInterface(ci.nsIXULChromeRegistry);
- return; // it is Firefox, we can leave safely now!
- } catch(ex) { log(ex.message); }
- try {
- if(ci.nsIChromeRegistrySea) chreg.QueryInterface(ci.nsIChromeRegistrySea);
- } catch(ex) { log(ex.message); }
-
- var browserLocale=null;
- try {
- browserLocale=chreg.getSelectedLocale("browser",true);
- } catch(ex1) {
- log("It seems no locale is selected for browser... trying with navigator");
- try {
- browserLocale=chreg.getSelectedLocale("navigator",true);
- } catch(ex2) {
- log("It seems no locale is selected for navigator...");
- }
- }
- var ret=null;
- if(browserLocale==null
- || !(ret=checkLocale(browserLocale))) {
- ret=checkLocale("en-US");
- }
- return ret;
- }
- }
-
-
- // XPCOM Scaffolding code
-
- // component defined in this file
-
- const SERVICE_NAME="FlashGot Service";
- const SERVICE_CID =
- Components.ID("{2a55fc5c-7b31-4ee1-ab15-5ee2eb428cbe}");
- const SERVICE_CTRID =
- "@maone.net/flashgot-service;1";
-
- const SERVICE_CONSTRUCTOR=FlashGotService;
-
-
- // interfaces implemented by this component
- const SERVICE_IIDS =
- [
- Components.interfaces.nsIObserver,
- Components.interfaces.nsISupports,
- Components.interfaces.nsISupportsWeakReference,
- Components.interfaces.nsIURIContentListener
- ];
-
- // Factory object
- const SERVICE_FACTORY = {
- _instance: null,
- createInstance: function (outer, iid) {
- if (outer != null)
- throw Components.results.NS_ERROR_NO_AGGREGATION;
-
- xpcom_checkInterfaces(iid,SERVICE_IIDS,Components.results.NS_ERROR_INVALID_ARG);
- // kept this for flexibility sake, but we're really adopting an
- // early instantiation and late init singleton pattern
- return this._instance==null?this._instance=new SERVICE_CONSTRUCTOR():this._instance;
- }
- };
-
- function xpcom_checkInterfaces(iid,iids,ex) {
- for(var j=iids.length; j-- >0;) {
- if(iid.equals(iids[j])) return true;
- }
- throw ex;
- }
-
- // Module
-
- var Module = new Object();
- Module.firstTime=true;
- Module.registerSelf = function (compMgr, fileSpec, location, type) {
- if(this.firstTime) {
-
- debug("*** Registering "+SERVICE_CTRID+".\n");
-
- compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar
- ).registerFactoryLocation(SERVICE_CID,
- SERVICE_NAME,
- SERVICE_CTRID,
- fileSpec,
- location,
- type);
-
- Components.classes['@mozilla.org/categorymanager;1'].getService(
- Components.interfaces.nsICategoryManager
- ).addCategoryEntry("app-startup",
- SERVICE_NAME, "service," + SERVICE_CTRID, true, true, null);
-
- this.firstTime=false;
- }
- }
- Module.unregisterSelf = function(compMgr, fileSpec, location) {
- compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar
- ).unregisterFactoryLocation(SERVICE_CID, fileSpec);
- Components.classes['@mozilla.org/categorymanager;1'].getService(
- Components.interfaces.nsICategoryManager
- ).deleteCategoryEntry("app-startup",SERVICE_NAME, true);
- }
-
- Module.getClassObject = function (compMgr, cid, iid) {
- if(cid.equals(SERVICE_CID))
- return SERVICE_FACTORY;
-
- if (!iid.equals(Components.interfaces.nsIFactory))
- throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
-
- throw Components.results.NS_ERROR_NO_INTERFACE;
-
- }
-
- Module.canUnload = function(compMgr) {
- return true;
- }
-
- // entrypoint
- function NSGetModule(compMgr, fileSpec) {
- return Module;
- }
-
-
-
-