File:  [mozdev] / chaff / src / content / chaff.js
Revision 1.3: download - view: text, annotated - select for diffs - revision graph
Sat Jun 28 22:18:03 2008 UTC (10 years, 8 months ago) by jduppel
Branches: MAIN
CVS tags: v_0_2, HEAD
Correcting typo and Javascript scoping

/* ***** BEGIN LICENSE BLOCK *****
 *   Version: GPL 3.0
 *
 * The contents of this file are subject to the GNU General Public License
 * 3.0 (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.gnu.org/licenses/gpl.html
 * 
 * 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 Chaff.
 *
 * The Initial Developer of the Original Code is
 * Jürgen Düppel.
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

function Chaff(id) {
  this.id=id;
}
Chaff.prototype = {
  searchTerms: ["google yahoo microsoft"],
  mMinInterval: 60000,
  mMaxInterval: 300000,
  mDebugLevel: 0,
  onLoad: function() {
    // initialization code
    this.initialized = true;
    this.strings = document.getElementById("chaff-strings");
    this.loadPreferences();
    this.loadSearchTerms();
    var delay=this.getDelay();
    var thisRef=this;
    this.log("scheduling in "+delay)
	window.setTimeout(function(){thisRef.runSearch()}, delay);
  },
//  onMenuItemCommand: function(e) {
//    var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
//                                  .getService(Components.interfaces.nsIPromptService);
//    promptService.alert(window, this.strings.getString("helloMessageTitle"),
//                                this.strings.getString("helloMessage"));
//  },
  loadSearchTerms: function(){
	  try {
      	var ioService = Components.classes["@mozilla.org/network/io-service;1"]
    	                                   .getService(Components.interfaces.nsIIOService);

		// create an nsIURI
      	var loc="http://www.google.com/trends/hottrends/atom/hourly";
		var uri = ioService.newURI(loc, null, null);
		
		// get a channel for that nsIURI
		var channel = ioService.newChannelFromURI(uri);
		
		if (channel){
			// get an listener
		    var thisRef=this;
			var listener = new ChaffListener(function(data){thisRef.searchTermsLoadComplete(data)}, channel);

			this.log("loading: "+loc);
//			channel.notificationCallbacks = listener;
			channel.asyncOpen(listener, null);
		}
	  } catch (ex){
	  }
  },
  searchTermsLoadComplete: function(data){
	  this.log(data);
	  var tempTerms=new Array();
	  var regexp = /<a href="[^"]*">([^<]*)<\/a>/ig;
	  var matches_array = data.match(regexp);
	  for (var current=0, len=matches_array.length; current<len; ++current ){
		  var regexpinner= /">([^<]*)<\//i;
		  var matchesInner=regexpinner.exec(matches_array[current]);
		  // just within parentheses
		  this.log(matchesInner[1]);
		  tempTerms.push(matchesInner[1]);
	  }
	  if (tempTerms.length>1){
		  this.searchTerms=tempTerms;
	  }
  },
  runSearch: function(){
	try {
	    var searchService = Components.classes["@mozilla.org/browser/search-service;1"].getService(Components.interfaces.nsIBrowserSearchService);
	    var engine = searchService.currentEngine;
	    if (!engine){
	    	engine=searchService.defaultEngine;
	    }
	    if (engine){
	    	var searchText=this.searchTerms[Math.floor(Math.random()*this.searchTerms.length)];
	    	if (this.searchTerms.length<2){
	    		this.loadSearchTerms();
	    	}
	        var submission = engine.getSubmission(searchText, null); // HTML response
	        if (submission){
	        	var ioService = Components.classes["@mozilla.org/network/io-service;1"]
	        	                                   .getService(Components.interfaces.nsIIOService);

				// create an nsIURI
				var uri = ioService.newURI(submission.uri.spec, null, null);
				
				// get a channel for that nsIURI
				var channel = ioService.newChannelFromURI(uri);
				
				if (channel){
					// get an listener
				    var thisRef=this;
					var listener = new ChaffListener(function(data){thisRef.searchComplete(data)}, channel);

					this.log("loading: "+submission.uri.spec);
//					channel.notificationCallbacks = listener;
					channel.asyncOpen(listener, null);
				}
	        }
	    }
	} catch (ex){
    	this.log("runSearch exception: "+ex);
	}
    
    var delay=this.getDelay();
    // schedule again
    var thisRef=this;
    this.log("scheduling in "+delay)
	window.setTimeout(function(){thisRef.runSearch()}, delay);
  },
  searchComplete: function(data){
	  this.log(data)
  },
  getDelay: function(){
	  var random = Math.random();
	  return this.mMinInterval+(this.mMaxInterval-this.mMinInterval)*random;
  },
  loadPreferences: function(){
	prefs = Components.classes['@mozilla.org/preferences-service;1'].
				getService(Components.interfaces.nsIPrefBranch);
	try {
		this.mMinInterval = prefs.getIntPref("extensions.chaff.mininterval_in_ms");
		this.mMaxInterval = prefs.getIntPref("extensions.chaff.maxinterval_in_ms");
		this.mDebugLevel = prefs.getIntPref("extensions.chaff.debuglevel");
	} catch (ex) {
    	this.log("loadPreferences exception: "+ex);
	}
  },
  /**
   * Outputs aText to the JavaScript console as well as to stdout.
   */
  log: function(aText) {
	if (this.mDebugLevel>0){
	    dump(CHAFF_LOG_PREFIX + aText + "\n");
	    var consoleService = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
	    consoleService.logStringMessage(CHAFF_LOG_PREFIX + aText);
	}
  },
};

function ChaffListener(callbackFunc, channel) {
  this.mCallbackFunc = callbackFunc;
  this.mChannel = channel;
}
ChaffListener.prototype = {
	mData: "",
    onStartRequest: function(request, context) {
		this.mData = "";
	},
    onStopRequest: function(request, context, status) {
	    if (Components.isSuccessCode(status)) {
	        // request was successful
	        this.mCallbackFunc(this.mData);
        } else {
	        // request failed
	        this.mCallbackFunc(null);
	    }
	    this.mChannel=null;
    },
    onDataAvailable: function(request, context, stream, offset, length) {
        var scriptableInputStream=Components.classes["@mozilla.org/scriptableinputstream;1"]
              .createInstance(Components.interfaces.nsIScriptableInputStream);
        scriptableInputStream.init(stream);
        this.mData += scriptableInputStream.read(length);
    },
    QueryInterface: function(iid) {
        if (iid.equals(Components.interfaces.nsISupports) ||
            iid.equals(Components.interfaces.nsIStreamListener) ||
            iid.equals(Components.interfaces.nsIRequestObserver))
            return this;
        else
            throw Components.results.NS_NOINTERFACE;
    },
};

window.addEventListener("load", function(e) { new Chaff().onLoad(e); }, false);

/**
 * Prefixed to all search debug output.
 */
const CHAFF_LOG_PREFIX = "*** Chaff: ";

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>