home *** CD-ROM | disk | FTP | other *** search
- var featureDiscovery = {
-
- // Set this to false to disable debug output
- FD_DEBUG : false,
-
- // Constants
- MAX_NUMBER_FEATURES : 256, // maximum number of feature discovery urls in .dat file
- FEATURE_DISCOVERY_FILE : "featureDiscovery.dat",
-
- // Prefs
- PREF_LASTUPDATEDATE : "browser.featurediscovery.lastupdatedate",
- PREF_UPDATE_URL : "browser.featurediscovery.updateurl",
- PREF_UPDATE_INTERVAL : "browser.featurediscovery.updateinterval",
-
- // Pref types
- PREF_TYPE_INVALID : 0, // Invalid
- PREF_TYPE_STRING : 32, // String
- PREF_TYPE_INT : 64, // Integer
- PREF_TYPE_BOOL : 128, // Boolean
-
- // File open flags (from prio.h)
- PR_RDONLY : 1,
- PR_WRONLY : 2,
- PR_TRUNCATE : 4,
-
- // Globals
- datFileDir : null,
- ioService : null,
- remoteupdatefile : null,
- featureList : null,
- prefService : null,
- uriservice : null,
-
- Init : function() {
- this.debug('Init()');
-
- // Get the working directory based on DefRt
- // Data file stored in /dist/bin/defaults/featurediscovery.dat (for the debug build)
-
- if (!this.datFileDir) {
- this.datFileDir = Components.classes["@mozilla.org/file/directory_service;1"]
- .getService(Components.interfaces.nsIProperties)
- .get("DefRt", Components.interfaces.nsILocalFile);
- }
- this.debug(' datFileDir: '+this.datFileDir.path);
-
- /*
- const IPS = Components.interfaces.nsIPromptService;
- var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
- .getService(IPS);
- ps.alert(window,"Feature Discovery", "The feature discovery path is " + this.datFileDir.path );
- */
-
- this.ReadFeatureDiscovery();
-
- // MERC - rfransen - begin update featurediscovery.dat process.
-
- // We need to work with the browser preferences, so let's get a reference
- // to the preference service.
- prefService = Components.classes["@mozilla.org/preferences-service;1"]
- .getService(Components.interfaces.nsIPrefBranch);
-
- // And we need to the uri service
- uriservice = Components.classes["@mozilla.org/network/standard-url;1"]
- .createInstance(Components.interfaces.nsIURI);
-
- if (prefService)
- {
- // We should first check to see if our prefs our at all valid...
- if ((prefService.getPrefType(this.PREF_LASTUPDATEDATE) == this.PREF_TYPE_INT ) &&
- (prefService.getPrefType(this.PREF_UPDATE_INTERVAL) == this.PREF_TYPE_INT ) &&
- (prefService.getPrefType(this.PREF_UPDATE_URL) == this.PREF_TYPE_STRING ))
- {
- // Ok, the first thing we should do is see if it is time go fetch an updated .dat file
- // Right, so how about we see the last we downloaded the File?
- var lastdownloadtime = prefService.getIntPref(this.PREF_LASTUPDATEDATE);
- this.debug("lastdownloadtime: " + lastdownloadtime);
- // Right, now we know when we last updated this file, so now what?
- // We should determine the update frequency
- var updatefrequency = prefService.getIntPref(this.PREF_UPDATE_INTERVAL);
- this.debug("updatefrequency: " + updatefrequency);
- // Ok, so have we passed the update interval?
- var updatedifferential = this.NowInSeconds() > (lastdownloadtime + updatefrequency);
- this.debug("updatedifferential: " + updatedifferential);
- // if uodatedifferential is true, let's party, otherwise, not time to download
- if (updatedifferential)
- {
- // It is time to get the new .dat file, let's get it!
- this.FetchNewDatFile();
- }
- else
- {
- this.debug("No new .dat file to grab. Aborting Fetch.");
- }
- }
- else
- {
- // Uh oh, some of our pref's are not valid, let's dump and bail
- try
- {
- this.debug("lastupdatedate : " + prefService.getPrefType(this.PREF_LASTUPDATEDATE) + "\n" +
- "updateinterval : " + prefService.getPrefType(this.PREF_UPDATE_INTERVAL) + "\n" +
- "update url : " + prefService.getPrefType(this.PREF_UPDATE_URL));
- }
- catch(e)
- {
- dump("Caught Exception trying to dump prefs : " + e);
- return;
- }
- }
- }
- else
- {
- // Not good if we are here. let's dump a msg and bail
- this.debug("Pref service unavailable. Aborting feature discovery update.");
- return;
- }
- },
-
- /*
- *****************************************************************
- * Function: FetchNewDatFile()
- * Arguments: None
- * Return: None
- * Description: Retrieves the latest featurediscovery.dat file
- * from the remote datastore using the nsIXPInstallManager
- * service.
- * Author: Ryan Fransen
- *****************************************************************
- */
- FetchNewDatFile : function() {
- this.debug("Starting 'FetchNewDatFile'");
- // Lets find out where the remote .dat file is.
- this.remoteupdatefile = new Array(1);
- this.remoteupdatefile[0] = prefService.getCharPref(this.PREF_UPDATE_URL)
- // Lets get the ball rolling with the update service
- var xpimgr = Components.classes["@mozilla.org/xpinstall/install-manager;1"]
- .createInstance(Components.interfaces.nsIXPInstallManager);
-
- if (xpimgr)
- {
- // Engage!
- xpimgr.initManagerFromChrome(this.remoteupdatefile, this.remoteupdatefile.length, this);
-
- // We should probably wait to load the .dat file until the update
- // service has finished loading it. So there must be some sort of callback for
- // this... Aha! There is. It is called "OnStateChange" via the
- // nsIXPIProgressDialog::INSTALL_DONE flag.
- // Hm... What if the download fails, or takes WAY too long, what then?
- // We would have no feature discovery file loaded at that point...
- // Well, we could just go ahead and load the local one at startup, and then
- // re-load the file again once we get the new one.
- }
- else
- {
- // Note the failure and abort
- this.debug("nsIXPInstallManager service unavailable.");
- return;
- }
- },
-
- /*
- *****************************************************************
- * Function: NowInSeconds()
- * Arguments: None
- * Return: The current workstation time in seconds (Unix Time/1000)
- * Description: Provides a way to get a time reference.
- * Author: Ryan Fransen
- *****************************************************************
- */
- NowInSeconds : function ()
- {
- return new Date().valueOf() / 1000;
- },
-
- /*
- *****************************************************************
- * Function: onStateChange()
- * Arguments: aIndex, aState, aValue
- * Return: None
- * Description: Callback from nsIXPInstallManager.
- * Handles the various states that the install manager goes through
- * that we may be interested in. Of course, we really only care
- * about one state - INSTALL_DONE
- * Author: Ryan Fransen
- *****************************************************************
- */
- onStateChange : function (aIndex, aState, aValue)
- {
- this.debug("OnStateChange");
- const nsIXPIProgressDialog = Components.interfaces.nsIXPIProgressDialog;
- switch (aState)
- {
- case nsIXPIProgressDialog.DOWNLOAD_START:
- case nsIXPIProgressDialog.DOWNLOAD_DONE:
- case nsIXPIProgressDialog.INSTALL_START:
- // Do nothing
- break;
- case nsIXPIProgressDialog.INSTALL_DONE:
- // Call our local oninstalldone handler
- this.OnInstallDone();
- break;
- }
- },
-
- /*
- *****************************************************************
- * Function: OnInstallDone()
- * Arguments: None
- * Return: None
- * Description: Performs any post .dat file install work
- * Author: Ryan Fransen
- *****************************************************************
- */
- OnInstallDone : function ()
- {
- // It is finally time to read in the feaurediscovery.dat file into memory and process it.
- try
- {
- this.ReadFeatureDiscovery();
- }
- catch(e)
- {
- // Ok, so we couldn't load the new featurediscovery.dat file, what should we do?
- // Note the failure and bail - don't update the lastupdatedate pref.
- this.debug("ReadFeatureDiscovery() failed!");
- return;
- }
-
- // Now that we have fetched the new .dat file, we should probably
- // capture the current time and save it in the lastupdatedate pref.
- try
- {
- prefService.setIntPref(this.PREF_LASTUPDATEDATE, this.NowInSeconds());
- }
- // We don't want to bail if this fails. We should note the failure.
- catch(e)
- {
- dump("Caught Exception trying to set pref 'browser.featurediscovery.lastupdatedate': " + e);
- }
-
- this.debug("Install complete");
- },
-
- // We don't really need this callback,
- // so let's just placate the install service
- // and play nicely with the other kids
- onProgress : function(aIndex, aValue, aMaxValue) {},
-
- // END - rfransen
-
-
- GetFeatureDiscoveryFile : function() {
- this.debug('GetFeatureDiscoveryFile(): '+this.FEATURE_DISCOVERY_FILE);
-
- if (!this.datFileDir) this.Init();
-
- // Create file descriptor
- if (this.datFileDir) {
- var file = this.datFileDir.clone();
- file.append(this.FEATURE_DISCOVERY_FILE);
- return file; // returns nsILocalFile
- }
- else
- return null;
- },
-
- EnsureFeatureDiscoveryFileExists : function() {
- this.debug('EnsureFeatureDiscoveryFileExists()');
- var file = this.GetFeatureDiscoveryFile();
- //this.debug('EnsureFeatureDiscoveryFileExists() - file is ' + file);
- if (!file.exists()) {
- this.debug(' creating file: '+this.FEATURE_DISCOVERY_FILE);
- file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0);
- }
- return file; // returns nsILocalFile
- },
-
- ReadFeatureDiscovery : function() {
- this.debug('ReadFeatureDiscovery()');
-
- var file = this.EnsureFeatureDiscoveryFileExists();
-
- if (file) {
- // Init the file input stream
- var fis = Components.classes["@mozilla.org/network/file-input-stream;1"]
- .createInstance(Components.interfaces.nsIFileInputStream);
- fis.init(file, this.PR_RDONLY, 0, 0);
-
- // Init a scriptable input stream
- var sis = Components.classes["@mozilla.org/scriptableinputstream;1"]
- .createInstance(Components.interfaces.nsIScriptableInputStream);
- sis.init(fis);
-
- // Read the file
- var fileContents = sis.read(sis.available());
-
- // Close file
- fis.close();
-
- // Return the lines as an array
- this.featureList = fileContents.split('\n');
-
- //return fileContents.split('\n');
- }
- //return null;
- },
-
- ProcessFeatureDiscovery : function(uri) {
- // Determine if this uri is found in the list of feature discovery urls.
-
- uriservice.spec = uri;
- var host = uriservice.host;
-
- this.debug('ProcessFeatureDiscovery()');
-
- var featureType = null; // return string value (e.g. searchbar)
-
- if (uriservice.scheme == "http" || uriservice == "https")
- {
- if (!this.featureList)
- this.ReadFeatureDiscovery();
-
- // Load in the feature discovery urls
- var entries = this.featureList; //this.ReadFeatureDiscovery();
-
-
- if (entries) {
- host=host.toLowerCase(); // match "ABC.com" and "abc.com"
-
- var blnFoundMatch = false; // did we find a match?
- var i; // loop index
-
- // loop for each feature discovery URL in the file until a match is found or
- // we have looped too many times
- this.debug('Searching through : ' + entries.length);
- for (i = 0; i < entries.length && !blnFoundMatch && i < this.MAX_NUMBER_FEATURES; i++) {
- // each line in featurediscovery.dat is x|y where x is the URL and y is the
- // feature discovery type (e.g. searchbar) - whitespace is trimmed out in code
- // parse out the line into the featureURL array
- featureURL = entries[i].split('|');
- if (featureURL) {
- // if featureURL[0] is found in host, the indexOf returns something other than -1
- // trim removes any trailing whitespace
- this.debug('Searching for [' + trim(featureURL[0].toLowerCase()) + '] in [' + host + ']');
- if (host.indexOf(trim(featureURL[0].toLowerCase())) != -1) {
- // trip the flag to end the loop
- this.debug('Found match [' + trim(featureURL[0].toLowerCase()) + '] in [' + host + ']');
- blnFoundMatch = true;
- featureType = featureURL;
- } // end if
- }
- } // end for
- if (i >= this.MAX_NUMBER_FEATURES)
- this.debug('Reached max number of features in featurediscovery.dat.');
-
- } else { // else no file was found so return null
- this.debug('Unable to read entries from array.');
- }
- }
- return featureType;
- },
-
- debug : function(msg) {
- if (this.FD_DEBUG)
- dump('^^^ featureDiscovery.js: '+msg+'\n');
- },
-
- trim : function(str) {
- if (!str) return "";
- str = str.replace(/^\s+/, "");
- return str.replace(/\s+$/, "");
- }
-
- };