home *** CD-ROM | disk | FTP | other *** search
- /***** 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 "FlashGot".
- -
- - The Initial Developer of the Original Code is Giorgio Maone.
- - Portions created by the Initial Developer are Copyright (C) 2004
- - the Initial Developer. All Rights Reserved.
- -
- - Contributor(s): Giorgio Maone <g.maone @ informaction.com>
- -
- - 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 LGPL or the GPL. 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 *****/
-
-
-
-
- function FlashGotDM(name) {
- if(arguments.length>0) {
- this._init(name);
- }
- }
-
- FlashGotDM.dms=[];
- FlashGotDM.dmtests={};
- FlashGotDM.executables={};
-
- 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]
- ,
- get service() {
- return this._service?this._service:this._service=
- Components.classes["@informaction.org/flashgot-service;1"
- ].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];
- }
- const exeFile=Components.classes["@mozilla.org/file/local;1"].createInstance(
- Components.interfaces.nsILocalFile);
- exeFile.initWithPath(this.service.globals.profDir.path);
- exeFile.append(exeName);
- try { exeFile.remove(true); } catch(ex) {}
- this._exeFile=this.checkExePlatform(exeFile);
- if(this._exeFile!=null) {
- try {
- this.createExecutable();
- this.log(this._exeFile.path+" created");
- } catch(ex) {
- this._exeFile=null;
- }
- }
- 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=new RegExp("^"+this.name+"\\|OK$","m").test(dmtest);
- }
- ,
- launchSupportTest: function (testFile) {
- this.runNative(["-o",testFile.path],true);
- }
- ,
- log: function(msg) {
- this.service.log(msg);
- }
- ,
- createJobHeader: function(links, opType) {
- return links.length+";"+this.name+";"+opType+";"+links.folder+";\n"
- }
- ,
- createJobBody: function(links) {
- var job="";
- var l,url;
- var cookies={};
- for(var j=0, len=links.length; j<len; j++) {
- job+="\n"+(url=(l=links[j]).href)+"\n"
- +l._description+"\n"
- +this.getCookie(url,cookies)+"\n"
- +this.getPostData(l);
- }
- return job;
- }
- ,
- createJob: function(links,opType) {
- return this.createJobHeader(links,opType)
- + this.getReferrer(links)
- + this.createJobBody(links);
- }
- ,
- download: function(links, opType) {
- links.folder=(links.length>0)?this.selectFolder(opType):"";
- try {
- this.performJob(this.createJob(links,opType));
- } catch(ex) {
- this.log(ex);
- }
- }
- ,
- getReferrer: function(links) {
- return links.referrer?links.referrer
- :links.document?links.document.location.href
- :links[0]?links[0].href:"about:blank";
- }
- ,
- getCookie: function(url,cookies) {
-
- const parts=url.match(/http[s]{0,1}:\/\/([^\/]+)/i);
- if(!parts) return "";
- const host=parts[1];
- var cookie=cookies[host];
- if(cookie) return cookie;
-
- cookie="";
- var iter = this.cookieManager.enumerator;
- var objCookie;
- var cookieHost;
- while (iter.hasMoreElements()){
- objCookie = iter.getNext();
- try {
- if(objCookie instanceof Components.interfaces.nsICookie // implicit QueryInterface()
- && ( host==(cookieHost=objCookie.host) // exact match
- || ( cookieHost.charAt(0)=='.' && cookieHost==host.substring(host.indexOf('.'))
- && cookie.indexOf("; "+objCookie.name+"=")==-1 // we don't override subdomain cookies
- ) // domain match
- )) {
- cookie+="; "+objCookie.name+"="+objCookie.value; // value should be already escaped...
- }
- } catch(ex) {}
- }
- return cookies[host]=cookie?cookie.substring(2):"";
- }
- ,
- getPostData: function(l) {
- return "";
- }
- ,
- createJobFile: function(job) {
- const jobFile=this.service.tmpDir.clone();
- jobFile.append("flashgot.fgt");
- jobFile.createUnique(0,0700);
- this.service.writeFile(jobFile,job);
- return jobFile;
- }
- ,
- performJob: function(job) {
- const jobFile=this.createJobFile(job);
- this.runNative([jobFile.path],false);
- }
- ,
- 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) {
- if(typeof(exeFile)!="object") exeFile=this.exeFile;
- try {
- if(exeFile && exeFile.exists() || this.createExecutable()) {
- const proc=Components.classes['@mozilla.org/process/util;1'].createInstance(
- Components.interfaces.nsIProcess);
- proc.init(exeFile);
- 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;
- }
- } catch(err) {
- this.log("Error running native executable:\n"+exeFile.path+" "+args.join(" ")+"\n"+err.message);
- }
- return 0xffffffff;
- }
- ,
- getWindow: function() {
- return Components.classes["@mozilla.org/appshell/window-mediator;1"
- ].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow(null)
- }
- ,
- selectFolder: function(opType) {
- const cc=Components.classes;
- const ci=Components.interfaces;
- const downloadDirPref="browser.download.dir";
- const useDownloadDirPref="browser.download.useDownloadDir";
- if(!this.askPath[opType]) return "";
-
- var initialDir;
- const pref = cc["@mozilla.org/preferences-service;1"].getService(ci.nsIPrefBranch);
- try {
- var initialDir = pref.getComplexValue("browser.download.dir", ci.nsILocalFile);
- if(initialDir && pref.getBoolPref(useDownloadDirPref)) {
- return initialDir.path;
- }
- } catch(ex) {}
-
- 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) {
- 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);
- return localFile.path;
- }
-
- throw new Error("Download cancelled by user");
- }
-
- }
-
- function FlashGotDMX(name) {
- if(arguments.length!=0) {
- this._init(name);
- }
- }
- FlashGotDMX.prototype=new FlashGotDM();
- FlashGotDMX.constructor=FlashGotDMX;
- FlashGotDMX._super=FlashGotDM.prototype;
- FlashGotDMX.prototype.exeName="flashgot.sh";
- FlashGotDMX.prototype.askPath=[true,true,true];
-
- function FlashGotDMMac(name, creatorId, macAppName) {
- if(arguments.length!=0) {
- this._init(name);
- }
- const creators=FlashGotDMMac.prototype.macCreators;
- creators[creators.length]={name: name, id: creatorId};
- this.macAppName = macAppName?macAppName:name;
- }
- FlashGotDMMac.prototype=new FlashGotDM();
- FlashGotDMMac.constructor=FlashGotDMMac;
- FlashGotDMMac._super=FlashGotDM.prototype;
- FlashGotDMMac.prototype.exeName="flashgot-mac.sh";
- FlashGotDMMac.prototype.OSASCRIPT="/usr/bin/osascript";
- FlashGotDMMac.prototype.macCreators=[];
- FlashGotDMMac.prototype.createScriptLauncher=function(scriptPath) {
- return "#!/bin/sh\n"
- +"/usr/bin/osascript '"+scriptPath+"'";
- }
- FlashGotDMMac.prototype.checkExePlatform=function(exeFile) {
- var 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) || exeFile.exists() ) return false;
- 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;
- } 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 application \"Finder\"\n"
- +" try\n"
- +" if exists application file id theCreator then\n"
- + response("OK")
- +" end if\n"
- +" on error\n"
- + response("KO")
- +" end try\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([],false,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";
- }
- job+="end tell\n";
- return job;
- }
-
-
- FlashGotDM.initDMS=function() {
- var dm;
-
- new FlashGotDM("Download Master");
-
- new FlashGotDM("FlashGet");
-
- new FlashGotDM("Free Download Manager");
-
- dm=new FlashGotDM("GetRight");
- dm.super_createJob=FlashGotDM.prototype.createJob;
- dm.createJob=function(links, opType) {
- const service=this.service;
- const folder=links.folder;
- var referrer;
- switch(opType) {
- case service.OP_ONE:
- return this.super_createJob(links, opType);
- case service.OP_SEL:
- case service.OP_ALL:
- var urlList="";
- var l;
- for(var j=0, len=links.length; j<len; j++) {
- l=links[j];
- urlList+="URL: "+l.href+"\r\nDesc:"+l._description+"\r\n";
- if(folder) {
- var urlParts=l.href.match(/\/([^\/]+?)(\?|\/?$)/);
- if(urlParts) {
- urlList+="File: "+folder+"\\"+decodeURI(urlParts[1])+"\r\n";
- }
- }
- }
- var file=service.tmpDir.clone();
- file.append("flashgot.grx");
- file.createUnique(0,0600);
- service.writeFile(file,urlList);
- referrer=file.path;
- break;
- default:
- referrer=this.getReferrer(links);
- }
- return this.createJobHeader({ length: 0, folder: "" },opType)+referrer+"\n";
- }
- dm.askPath=[false,true,true];
-
- new FlashGotDM("Internet Download Accelerator");
-
- var lg2002=new FlashGotDM("LeechGet 2002");
- lg2002.super_createJob=FlashGotDM.prototype.createJob;
- lg2002.createJob=function(links, opType) {
- const service=this.service;
- var referrer;
- switch(opType) {
- case service.OP_ONE:
- return this.super_createJob(links, opType);
- 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.toUpperCase():"";
- 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");
- }
- referrer=service.httpServer.addDoc(
- htmlDoc.concat("</body></html>")
- );
- break;
- default:
- referrer=this.getReferrer(links);
- }
- return this.createJobHeader({ length: 0, folder: "" },opType)+referrer+"\n";
- }
-
- var lg2004=new FlashGotDM("LeechGet 2004");
- lg2004.super_createJob=lg2002.super_createJob;
- lg2004.createJob=lg2002.createJob;
-
- new FlashGotDM("Net Transport");
-
- new FlashGotDM("ReGet Deluxe");
- new FlashGotDM("ReGet Junior");
- new FlashGotDM("ReGet Pro");
-
- new FlashGotDMX("Aria");
- new FlashGotDMX("Downloader 4 X");
-
- dm=new FlashGotDMMac("Speed Download 2","Spee");
- dm.createJob=function(links,opType) {
- var job = "tell application \""+ this.macAppName+ "\"\n";
- job+="AddURL {";
- for(var j=0,len=links.length; j<len; j++) {
- if(j>0) job+=',';
- job+='"'+links[j].href+'"';
- }
- job+="}\nend tell\n";
- return job;
- }
-
- new FlashGotDMMac("iGetter","iGET");
-
- FlashGotDM.dms.sort(function(a,b) { a=a.name.toUpperCase(); b=b.name.toUpperCase(); return a==b?0:a<b?-1:1; });
-
-
- };
- FlashGotDM.initDMS();
-
-
- const SHUTDOWN="profile-before-change";
- const STARTUP="profile-after-change";
-
- /* interfaces implemented by this component */
- const FLASHGOT_SERVICE_IIDS =
- [
- // Components.interfaces.IFlashGotService,
- Components.interfaces.nsIObserver,
- Components.interfaces.nsISupports,
- ];
-
- /* components defined in this file */
-
- const FLASHGOT_SERVICE_CID =
- Components.ID("{2a55fc5c-7b31-4ee1-ab15-5ee2eb428cbe}");
- const FLASHGOT_SERVICE_CTRID =
- "@informaction.org/flashgot-service;1";
-
- /* components used by this file */
- const CATMAN_CTRID = "@mozilla.org/categorymanager;1";
-
-
- function flashgot_checkInterfaces(iid,ex) {
- for(var j=FLASHGOT_SERVICE_IIDS.length; j-- >0;) {
- if(iid.equals(FLASHGOT_SERVICE_IIDS[j])) return true;
- }
- throw ex;
- }
-
- /* factory for FlashGotService */
- var FlashGotServiceFactory = new Object();
-
- FlashGotServiceFactory.createInstance = function (outer, iid) {
- if (outer != null)
- throw Components.results.NS_ERROR_NO_AGGREGATION;
-
- flashgot_checkInterfaces(iid,Components.results.NS_ERROR_INVALID_ARG);
-
- return new FlashGotService();
- }
-
- function FlashGotService() {
- this.wrappedJSObject=this;
- this._globals=null;
-
- 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);
- }
-
- FlashGotService.prototype = {
- OP_ONE: 0,
- OP_SEL: 1,
- OP_ALL: 2
- ,
- 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);
- } catch(ex) {
- this.log("Error unregistering service as observer: "+ex);
- }
- }
- ,
- QueryInterface: function(iid) {
- flashgot_checkInterfaces(iid,Components.results.NS_ERROR_NO_INTERFACE);
- return this;
- }
- ,
- /* nsIObserver */
- observe: function(subject, topic, data) {
- this.log(topic,data);
- switch(topic) {
- case "xpcom-shutdown":
- this.unregister();
- case SHUTDOWN:
- this.cleanup();
- break;
- case STARTUP:
- this.initGlobals();
- break;
- }
- }
- ,
- get defaultDM() {
- return this.getPref("defaultDM");
- }
- ,
- 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 httpServer() {
- return (!this._httpServer) || this._httpServer.isDown
- ?this._httpServer=new FlashGotHttpServer(this)
- :this._httpServer;
- }
-
- ,
- download: function(links, opType, dmName) {
- if(links.length==0) return;
- if(!opType) opType=links.length>1?this.OP_SEL:this.OP_ONE;
- if(!dmName) dmName=this.defaultDM;
- var dm=this.globals.DMS[dmName];
- if(!dm) {
- this.log("FlashGot error: no download manager selected!");
- return;
- }
- // urlescaped purification patch, thank to Matt Mees for suggestion
- function parseDesc(link) {
- return link._description?link._description
- :link._description = (typeof(link.title)=="string" && link.title.length>0
- ?link.title:link.innerHTML).replace(
- /<.*?>/g,"").replace(/\s+/g," ");
- }
-
- function killDuplicates(links, start) {
- var l=links[start];
- var href=l.href;
- var descLen=parseDesc(l).length;
- var l2;
- for(var k=start; k-->0;) {
- l2=links[k];
- if(href==l2.href) {
- if(descLen<=parseDesc(l2).length) {
- links.splice(j,1);
- return null;
- } else {
- links.splice(k,1);
- j--;
- }
- }
- }
- return l;
- }
-
- var l;
- for(var j=links.length; j-- >0; ) {
- if(!(l=killDuplicates(links,j))) continue;
-
- urlParts=l.href.split("?");
- try {
- urlParts[0]=decodeURI(urlParts[0]);
- l.href=urlParts.join("?");
- } catch(e) {
- this.log("Error decoding URI "+l.href+"\n"+e.message);
- }
- }
-
-
- dm.download(links,opType);
- }
- ,
- 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.globals.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.globals.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);
- }
- }
-
- ,
- log: function(msg) {
- try {
- if(!this.rootWindow) {
- this.rootWindow=Components.classes['@mozilla.org/appshell/appShellService;1'
- ].getService(Components.interfaces.nsIAppShellService).hiddenDOMWindow;
- }
- this.rootWindow.dump("<FLASHGOT>\n"+msg+"\n</FLASHGOT>\n");
- } catch(ex) {}
- }
- ,
- checkLink: function(link) {
- return link && link.href && /^[a-z]+:\/\/.*/i.test(link.href) && ! /^(javascript|mailto|news|file):/i.test(link.href);
- }
- ,
- checkAnchor: function(elem) {
- return elem instanceof Components.interfaces.nsIDOMHTMLAnchorElement
- && elem.href;
- }
- ,
- findLinkAsc: function(node) {
- while(node) {
- if(this.checkAnchor(node))
- return this.checkLink(node)?node:null;
- node = node.parentNode;
- }
- return 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;
- }
- ,
- get globals() {
- return this._globals?this._globals:this._globals=this.initGlobals();
- }
- ,
- initCount: 0,
- initOKCount: 0,
- initGlobals: function() {
- this.initCount++;
- this.rootWindow=null;
-
- const cc=Components.classes;
- const ci=Components.interfaces;
-
- this.prefService.getBranch("browser.dom.window.dump.").setBoolPref("enabled",true);
-
- this.log("Per-session init started");
- this.log("Checked locale: "+this.checkLocale());
-
- const fileLocator=cc["@mozilla.org/file/directory_service;1"].getService(
- ci.nsIProperties);
- const tmpDir=fileLocator.get("TmpD",ci.nsIFile);
- const profDir=fileLocator.get("ProfD",ci.nsIFile);
-
- tmpDir.append("flashgot");
- tmpDir.createUnique(1,0700);
-
- this._globals={
- tmpDir: tmpDir,
- profDir: profDir,
- prefs: this.prefService.getBranch("flashgot.")
- };
-
- this.setupLegacyPrefs();
-
- this._globals.DMS=this.checkDownloadManagers(),
-
- this.log("Per-session init done");
-
- this.initOKCount++;
- return this._globals;
- }
- ,
- 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( (!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...");
- }
-
- return dms;
- }
- ,
- cleanup: function() {
- try {
- if(this._httpServer) {
- this._httpServer.shutdown();
- }
- if(this._globals && this._globals.tmpDir.exists()) {
- this._globals.tmpDir.remove(true);
- }
- } catch(ex) {
- this.log(ex);
- }
- }
- ,
- readFile: function(file) {
- const cc=Components.classes;
- const ci=Components.interfaces;
-
- var is = cc["@mozilla.org/network/file-input-stream;1"].createInstance(
- ci.nsIFileInputStream );
- is.init(file ,0x01, 0400, null);
- var sis = cc["@mozilla.org/scriptableinputstream;1"].createInstance(
- ci.nsIScriptableInputStream );
- sis.init( is );
- var 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 {
- var file=this.globals.profDir.clone();
- file.append("pref");
- file.append("flashgot.js");
- if(file.exists()) {
- this.prefService.readUserPrefs(file);
- }
- } catch(e) {
- this.log(e.message);
- }
- }
- ,
- _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"];
-
- 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);
- }
- }
- }
- this._dirtyJobsDone=true;
- }
- }
-
- var Module = new Object();
- Module.firstTime=true;
- Module.registerSelf = function (compMgr, fileSpec, location, type) {
- if(this.firstTime) {
-
- debug("*** Registering FlashGot service.\n");
-
- compMgr =
- compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
-
- compMgr.registerFactoryLocation(FLASHGOT_SERVICE_CID,
- "FlashGot Service",
- FLASHGOT_SERVICE_CTRID,
- fileSpec,
- location,
- type);
- /*
- Components.classes[FLASHGOT_SERVICE_CTRID].getService(
- Components.interfaces.nsISupports);
- */ //CHECK ME
- this.firstTime=false;
- }
-
-
- }
- Module.unregisterSelf =
- function(compMgr, fileSpec, location)
- {
-
- compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
-
- compMgr.unregisterFactoryLocation(FLASHGOT_SERVICE_CID, fileSpec);
-
- }
-
- Module.getClassObject = function (compMgr, cid, iid) {
- if (cid.equals(FLASHGOT_SERVICE_CID))
- return FlashGotServiceFactory;
-
- 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;
- }
-
- /* 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.log("Listening");
- }
-
- FlashGotHttpServer.prototype={
- documents: []
- ,
- log: function(msg){
- try {
- if(!this.logStream) {
- logFile=this.tmpDir.clone();
- logFile.append("server.log");
- logFile.createUnique(0,0600);
- this.logStream=Components.classes["@mozilla.org/network/file-output-stream;1"
- ].createInstance(Components.interfaces.nsIFileOutputStream );
- this.logStream.init(logFile, 0x02 | 0x10, 0600, 0 );
- }
- 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) {
- if(window) window.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.nsIXULChromeRegistry);
-
- 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;
- }
- }
-
-