Example #1
0
  socket.on('proxy', function(settings, callback){
    var header
        , host = settings.host ? settings.host : socket.handshake.headers.host.replace(/\:\d+$/, '')
        , cookie = socket.handshake.headers.cookie
        , path = typeof settings.path === 'string' ? settings.path : '/'
        , type = typeof settings.type === 'string' ? settings.type.toUpperCase() : 'GET'
        , data = settings.data ? settings.data : ''
        , contentType = settings.contentType ? settings.contentType : 'application/x-www-form-urlencoded';

    if(typeof data !== 'string') {
      data = typeof data === 'object' ? serialize(data) : '';
    }

    // Build headers
    headers = {
      'host': host 
      , 'Content-Length': data.length
      , 'Content-Type': contentType
      , 'Cookie': cookie
    };

    // Create proxy request
    var request = http.createClient(80, host).request(type, path, headers);

    // On the response
    request.on('response', function (response) {
      if(response.statusCode == 200) {
        response.setEncoding('utf8');
        response.on('data', function (chunk) {
          var result = JSON.parse(chunk)
              , command = {}
              , message = {};
              
          if(typeof result.command === 'object') {
            command = result.command;
          }
          
          if(result.message !== undefined && result.message !== null) {
            message = result.message;
          } 
          
          // Send callback response
          if(typeof callback === 'function') {
            callback(message);
          }

          /** Execute commands **/
          // Broadcast message
          if(command.broadcast && command.broadcast.send === true) {
            var callback = 'broadcastCallback';
                
            if(typeof command.broadcast.callback === 'string') {
              callback = command.broadcast.callback;
            }
            
            if(command.broadcast.message !== undefined && command.broadcast.message !== null) {
              message = command.broadcast.message;
            }
            
            socket.json.broadcast.send(
              JSON.stringify({
                callback: callback,
                message: message
              })
            );
          }
        });
      }
    });

    request.write(data);
    request.end();
  });
var http = require('http');
var linux_usb = http.createClient(80, 'www.linux-usb.org');
var request = linux_usb.request('GET', '/usb.ids', {'host': 'www.linux-usb.org'});
request.end();

function splitEntry(line) {
	var trimed = line.trim();
	var r = new Array();
	r.push(trimed.substr(0, 4));
	r.push(trimed.substr(5));
	return r;
}

var lastManufacturer = undefined;
var result = "";
var closeManufacturer = false;

request.on('response', function(response) {
	response.on('data', function(chunk) {
		var lines = chunk.toString().split("\n");

		for (var i = 0; i < lines.length; i++) {
			if ((lines[i].trim().length == 0) || (lines[i].trim().charAt(0) == "#")) {
				continue;
			}

			entry = splitEntry(lines[i]);
			
			if (lines[i].charAt(0) != "\t") {
				
				if (lastManufacturer != undefined) {
Example #3
0
 _getClient: function(port, host, https) {
   return this.options.client || http.createClient(port, host, https);
 },
 * 
 * You will need to have a Tropo scripting aplication set up
 *  to use this. See sample code below:
 *  
 *  message(msg, { to:number, network:"SMS" });
 *  
 *  Save this file in your Tropo account as message.js
 * 
 */
var http = require('http');
var sys = require('sys');

// Enter your tropo outbound messaging token below.
var token = 'your-tropo-token';
var msg = encodeURI('This is a test SMS message from Node.js.');
var number = '5551234567';

var tropoSessionAPI = 'api.tropo.com';
var path = '/1.0/sessions?action=create&token=' + token + '&msg=' + msg + '&number=' + number;

var tropo = http.createClient(80, tropoSessionAPI);
var request = tropo.request('GET', path, {'host': tropoSessionAPI});

request.end();

request.on('response', function (response) {
  response.setEncoding('utf8');
  response.addListener('data', function (chunk) {
  sys.log('Sent message. Tropo response code:' + response.statusCode + '. Body: ' + chunk);
  });
});         
Example #5
0
 this.updateHost = function (host) {
     this.host   = host;
     this.socket = http.createClient(this.port, this.host, this.options.useSSL);
 };
Example #6
0
API.prototype.get = function (what, callback) {
  var self = this;
  if (!what) {
    return callback(self.customError('error', 400));
  }

  what = handleToken(this, what);

  var path = this.options.api_path + what;

  var server = http.createClient(this.options.api_port, this.options.api_url, this.options.api_secure);

  var r = {'host':this.options.api_url};

  if(typeof this.options.channel !== 'undefined') {
    r["X-Channel"] = this.options.channel.id;
  }
  if(typeof this.options.page !== 'undefined') {
    r["X-Page"] = this.options.page.id;
  }

  if(this.options.debug) {
    try {
      throw new Error('qsapi::API');
    } catch (err) {
      var arr = err.stack.split('\n');
      arr = arr.splice(2);
      var toSend = [];
      for (var i=0;i<arr.length;i++) {
        if(arr[i].match(new RegExp(/\(\//))) {
          toSend.push(arr[i]);
        }

      }
      r["X-Debug"] = JSON.stringify(toSend);
    }
  }

  var request = server.request('GET', path, r);

  request.end();

  request.on('response', function (response) {
    var data = [];

    response.setEncoding('utf8');

    if (response.headers.location && response.headers.location.indexOf('?code=') > -1) {
      data.push(response.headers.location.split('?')[1]);
    }

    response.on('data', function (chunk) {
      data.push(chunk);
    });

    response.on('end', function () {
      return callback(data.join(''));
    });

  });

  request.on('error', function (e) {
    return callback(self.customError(e, 500));
  });

};
var http = require('http');

// This test is to make sure that when the HTTP server
// responds to a HEAD request, it does not send any body.
// In this case it was sending '0\r\n\r\n'

var server = http.createServer(function(req, res) {
  res.writeHead(200); // broken: defaults to TE chunked
  res.end();
});
server.listen(PORT);

responseComplete = false;

var req = http.createClient(PORT).request('HEAD', '/')
error('req');
req.end();
req.addListener('response', function (res) {
  error('response');
  res.addListener('end', function() {
    error('response end');
    server.close();
    responseComplete = true;
  });
});

process.addListener('exit', function () {
  assert.ok(responseComplete);
});
    fs.readFile(filename, "binary", function(err, file) {
      if(err) {
	res.writeHead(500, {"Content-Type": "text/plain"});
	res.write(err + "\n");
	res.end();
	return;
      }

      res.writeHead(200);
      res.write(file, "binary");
      res.end();
    });
  });
}

var twitter_client = http.createClient(80, "api.twitter.com"),
    tweet_emitter = new events.EventEmitter();

function get_tweets() {
  var req = twitter_client.request('GET', '/1/statuses/public_timeline.json', {'host': 'api.twitter.com'});

  req.addListener('response', function(res) {
    var body = "";
    res.addListener('data', function(data) {
      body += data;
    });

    res.addListener('end', function() {
      var tweets = JSON.parse(body);
      if(tweets.length > 0) {
	tweet_emitter.emit('tweets', tweets);
Example #9
0
exports.request = function(originalRequest){
	// make a shallow copy of original request object
	var request = {};
	for(var key in originalRequest){
		if(originalRequest.hasOwnProperty(key)){
			request[key] = originalRequest[key];
		}
	}
	
	if(request.url){
		var parsed = parse(request.url);
		if (parsed.pathname) {
			parsed.pathInfo = parsed.pathname;
		} else {
			parsed.pathInfo = "/";
		}
		request.queryString = parsed.query || "";
		for(var i in parsed){
			request[i] = parsed[i];
		}
	}
	var deferred = defer();
	if(exports.proxyServer){
		request.pathname = request.url;
		var proxySettings = parse(exports.proxyServer);
		request.port = proxySettings.port; 
		request.protocol = proxySettings.protocol;
		request.hostname = proxySettings.hostname;
	}
	
	var secure = request.protocol.indexOf("s") > -1;
	var client = http.createClient(request.port || (secure ? 443 : 80), request.hostname, secure);

	var requestPath = request.pathname || request.pathInfo || "";
	if (request.queryString) {
	  requestPath += "?"+request.queryString;
	}

	var req = client.request(request.method || "GET", requestPath, request.headers || {host: request.host});
	var timedOut;
	req.end();
	req.on("response", function (response){
		if(timedOut){
			return;
		}
		response.status = response.statusCode;
		var sendData = function(block){
			buffer.push(block);
		};
		var buffer = [];
		var bodyDeferred = defer();
		var body = response.body = LazyArray({
			some: function(callback){
				buffer.forEach(callback);
				sendData = callback;
				return bodyDeferred.promise;
			}
		});
		response.setEncoding(request.encoding || "utf8");

		response.on("data", function (chunk) {
			sendData(chunk);
		});
		response.on("end", function(){
			bodyDeferred.resolve();
		});
		response.on("error", function(error){
			bodyDeferred.reject(error);
		});
		deferred.resolve(response);
		clearTimeout(timeout);
	});
	var timeout = setTimeout(function(){
		timedOut = true;
		deferred.reject(new Error("Timeout"));
	}, 20000);
	req.on("error", function(error){
		deferred.reject(error);
	});
	req.on("timeout", function(error){
		deferred.reject(error);
	});
	req.on("close", function(error){
		deferred.reject(error);
	});
	if(request.body){
		return when(request.body.forEach(function(block){
			req.write(block);
		}), function(){
			req.end();
			return deferred.promise;
		});
	}
	req.end();
	return deferred.promise;
};
Example #10
0
// lib
var http = require('http');

// http object for connectingt to us.playstation.com
var psn_http = http.createClient(80, 'us.playstation.com');

// clean up a given username, PSN (according to Wikipedia) only accepts alphanumberic, underscores and hyphens
function cleanupUsername(u){
    return u.replace(/[^a-zA-Z0-9_\-\|]/g, "");
}
function checkUsername(u){
    u = cleanupUsername(u);
    if ( (u.length < 2) || (u.length>21) ){
        return false;
    }
    return u;
}
exports.checkUsername = checkUsername;

// standard fetch function
function fetch(path, cb){
    var request = psn_http.request('GET', path, {
        'host': 'us.playstation.com',
        'Referer': 'http://us.playstation.com/playstation/psn/profile/friends',
        'User-Agent': 'PS3Application libhttp/4.1.1-000 (CellOS)',
        'Accept': '*/*'});
    request.on('response', function(response) {
        response.setEncoding('utf8');
        var body = "";
        response.on('data', function(chunk) {
            body += chunk;
Example #11
0
Browser.prototype.request = function(method, path, options, fn, saveHistory){
  var self = this
    , server = this.server
    , host = this.host || '127.0.0.1'
    , headers = options.headers || {};

  // Ensure that server is ready to take connections
  if (server && !server.fd){
    (server.__deferred = server.__deferred || [])
      .push(arguments);
    if (!server.__started) {
      server.listen(server.__port = ++startingPort, host, function(){
        process.nextTick(function(){
          server.__deferred.forEach(function(args){
            self.request.apply(self, args);
          });
        });
      });
      server.__started = true;
    }
    return;
  }

  // Save history
  if (false !== saveHistory) this.history.push(path);

  // Cookies
  var cookies = this.cookieJar.cookieString({ url: path });
  if (cookies) headers.Cookie = cookies;

  // Request body
  if (options.body) {
    if (typeof options.body === 'object') {
      options.body = qs.stringify(options.body);
    }
    headers['Content-Length'] = options.body.length;
    headers['Content-Type']   = headers['Content-Type'] || 'application/x-www-form-urlencoded';
  }

  // Request
  headers.Host = host;

  // HTTP client
  if (!this.client) {
    // portno & host supplied
    if (this.port && this.host) {
      this.client = http.createClient(this.port, this.host);
    } else {
      this.client = http.createClient(server.__port);
    }
  }

  var req = this.client.request(method, path, headers);
  req.on('response', function(res){
    var status = res.statusCode
      , buf = '';

    // Cookies
    if (res.headers['set-cookie']) {
      res.headers['set-cookie'].forEach(function(cookie) {
        self.cookieJar.add(new Cookie(cookie));
      });
    }

    // Success
    if (status >= 200 && status < 300) {
      var contentType = res.headers['content-type'];
 
      if (!contentType) return fn(res);

      // JSON support
      if (~contentType.indexOf('json')) {
        res.body = '';
        res.on('data', function(chunk){ res.body += chunk; });
        res.on('end', function(){
          try {
            res.body = JSON.parse(res.body);
            fn(res, res.body);
          } catch (err) {
            self.emit('error', err);
          }
        });
        return;
      }

      // Ensure html
      if (!~contentType.indexOf('text/html')) {
        return fn(res);
      }

      // Buffer html
      res.setEncoding('utf8');
      res.on('data', function(chunk){ buf += chunk; });
      res.on('end', function(){
        self.parse(buf);
        fn(res, function(selector){
          return self.context.find(selector);
        });
      });

    // Redirect
    } else if (status >= 300 && status < 400) {
      var location = res.headers.location
        , path = url.parse(location).pathname;
      self.emit('redirect', location);
      if (self.followRedirects) {
        self.request('GET', path, options, fn);
      } else {
        return fn(res);
      }
    // Error
    } else {
      fn(res);
    }
  });

  req.end(options.body);

  return this;
};
 function test(expectedPort, expectedHost, port, host) {
   var client = http.createClient(port, host)
   expect(client.port).equal(expectedPort)
   expect(client.host).equal(expectedHost)
 }
 before(function () {
   // capture the deprecation warning here
   http.createClient()
 })
Example #14
0
function getMillisecs () {
	return((new Date()).getTime());
}

function timeExecutions (loops, func) {
	var start = getMillisecs();

	while (loops--)
		func();

	return(getMillisecs() - start);
}

var html = "";
http.createClient(testPort, testHost)
	.request("GET", testPath, { host: testHost })
	.addListener("response", function (response) {
		if (response.statusCode == "200") {
			response.setEncoding("utf8");
			response.addListener("data", function (chunk) {
				html += chunk;
			}).addListener("end", function() {
				var timeNodeHtmlParser = !testNHP ? 0 : timeExecutions(testIterations, function () {
					var handler = new htmlparser.DefaultHandler(function(err, dom) {
						if (err)
							sys.debug("Error: " + err);
					});
					var parser = new htmlparser.Parser(handler, { includeLocation: true });
					parser.parseComplete(html);
				})
Example #15
0
		// Throws an error; pretty sure it's encoding issues.
		//console.log(JSON.parse(rsp.responseData.translatedText.replace(/&#39;/g, "'")))
    }
  };

}
else{

  var sys = require('sys')
    , http = require('http');

  var languages = require('./languages').getLangs();
  var translates = exports;

  // http client for accessing google api
  var googleTranslate = http.createClient(80, 'ajax.googleapis.com');

  // translate the text
  exports.text = function (lang, text, callback) {
    // this is not a good curry recipe. needs moar spice
    if(typeof lang !== 'object'){
      callback = text;
      text = lang;
    }
    var req = googleTranslate.request('GET', getEnglishTranslatePath(lang, text),
      {'host': 'ajax.googleapis.com', 'encoding':'utf-8'});
      
      req.addListener('response', function (response) {
      
      	var responseBody = "";
      
Example #16
0
function request (options, callback) {
  if (!options.uri) {
    throw new Error("options.uri is a required argument")
  } else {
    if (typeof options.uri == "string") {
      options.uri = url.parse(options.uri);
    }
  }

  options._redirectsFollowed = options._redirectsFollowed ? options._redirectsFollowed : 0;
  options.maxRedirects = options.maxRedirects ? options.maxRedirects : 10;

  options.followRedirect = (options.followRedirect !== undefined) ? options.followRedirect : true;
  options.method = options.method ? options.method : 'GET';

  options.headers = options.headers ? options.headers :  {};
  if (!options.headers.host) {
    options.headers.host = options.uri.hostname;
    if (options.uri.port) {
      if ( !(options.uri.port === 80 && options.uri.protocol === 'http:') && 
           !(options.uri.port === 443 && options.uri.protocol === 'https:') )
      options.headers.host += (':'+options.uri.port)
    }
    var setHost = true;
  } else {
    var setHost = false;
  }
  if (options.gzip && compress) {
      options.headers['accept-encoding'] = 'gzip;q=1.0';
  }

  if (!options.uri.pathname) {options.uri.pathname = '/'}
  if (!options.uri.port) {
    if (options.uri.protocol == 'http:') {options.uri.port = 80}
    else if (options.uri.protocol == 'https:') {options.uri.port = 443}
  }

  if (options.uri.protocol == 'https:') {
    var secure = true; 
  } else {
    var secure = false;
  }

  if (options.bodyStream) {
    sys.error('options.bodyStream is deprecated. use options.reponseBodyStream instead.');
    options.responseBodyStream = options.bodyStream;
  }

  options.client = options.client ? options.client : http.createClient(options.uri.port, options.uri.hostname, secure);

  var clientErrorHandler = function (error) {
    if (setHost) delete options.headers.host;
    if (callback) callback(error);
  }
  options.client.addListener('error', clientErrorHandler);

  if (options.uri.auth && !options.headers.authorization) {
    options.headers.authorization = "Basic " + toBase64(options.uri.auth);
  }
  options.fullpath = options.uri.href.replace(options.uri.protocol + '//' + options.uri.host, '');
  if (options.fullpath.length === 0) options.fullpath = '/' 
  if (options.body) {
    // encode the response body from a hash
    if(options.body && (options.body.toString() == '[object Object]')){
		if(options.HTMLEncode){
			var body = [];
			for(var n in options.body){
				body.push(escapeFormData(n) + '=' + escapeFormData(options.body[n]));
			}
			options.body = body.join('&');
		}else{
			options.body = require('querystring').stringify(options.body);
		}
      options.headers['content-type'] || (options.headers['content-type'] = 'application/x-www-form-urlencoded');
    }

    options.headers['content-length'] = options.body.length;
  }
  options.request = options.client.request(options.method, options.fullpath, options.headers);

  options.request.addListener("response", function (response) {
    var buffer, responseStream;

    // If we get a gzip encoding, pump the response in a stream decoder,
    // and connect the rest of event listeners to the decoder
    if (response.headers['content-encoding'] && response.headers['content-encoding'] == 'gzip') {
        if (!compress) {
            clientErrorHandler(new Error("Cannot decode gzip response, please install `node-compress`"));
            return;
        }
        responseStream = new compress.GunzipStream();
        sys.pump(response, responseStream);
    }
    else {
        responseStream = response;
    }

    if (options.responseBodyStream) {
      buffer = options.responseBodyStream;
      sys.pump(responseStream, options.responseBodyStream);
    }
    else {
      buffer = '';
      responseStream.addListener("data", function (chunk) { buffer += chunk; } )
    }

    var closeTimeout;
    // If the server closes the connection before sending all the request,
    // we're sitting ducks
    options.client.addListener("close", function () {
            // Let's give some time to the response to catch up,
            // then fire manually the end event
            closeTimeout = setTimeout(function () { responseStream.emit("end"); }, options.closeTimeout || 10000);
        });

    responseStream.addListener("end", function () {
      options.client.removeListener("error", clientErrorHandler);
      /* Some errors can happen after the `end` event has been received,
       * for example, with an invalid Content-Length. Attaching a no-op
       * handler avoid having node crashing in those cases */
      options.client.addListener("error", postResponseErrorHandler);
      // Remove the timeout if necessary, and also detach the "end" listener
      // in the edge case when the response took more than the timeout to
      // reach the end state after closing the underlying socket
      if (closeTimeout) { clearTimeout(closeTimeout); }
      responseStream.removeListener("end", arguments.callee);

      if (response.statusCode > 299 && response.statusCode < 400 && options.followRedirect && response.headers.location && (options._redirectsFollowed < options.maxRedirects) ) {
        options._redirectsFollowed += 1
        options.uri = response.headers.location;
        delete options.client; 
        if (options.headers) {
          delete options.headers.host;
        }
        request(options, callback);
        return;
      } else {options._redirectsFollowed = 0}

      if (setHost) delete options.headers.host;
      if (callback) callback(null, response, buffer);
    })
  })

  if (options.body) {
    options.request.write(options.body, 'binary');
    options.request.end();
  } else if (options.requestBodyStream) {
    sys.pump(options.requestBodyStream, options.request);
  } else {
    options.request.end();
  }
}
Example #17
0
var Parser = require('../jsonparse');
var Http = require('http');
require('./colors');
var p = new Parser();
var cred = require('./credentials');
var client = Http.createClient(80, "stream.twitter.com");
var request = client.request("GET", "/1/statuses/sample.json", {
  "Host": "stream.twitter.com",
  "Authorization": (new Buffer(cred.username + ":" + cred.password)).toString("base64")
});
request.on('response', function (response) {
  console.log(response.statusCode);
  console.dir(response.headers);
  response.on('data', function (chunk) {
    p.write(chunk);
  });
  response.on('end', function () {
    console.log("END");
  });
});
request.end();
var text = "", name = "";
p.onValue = function (value) {
  if (this.stack.length === 1 && this.key === 'text') { text = value; }
  if (this.stack.length === 2 && this.key === 'name' && this.stack[1].key === 'user') { name = value; }
  if (this.stack.length === 0) {
    console.log(text.blue + " - " + name.yellow);
    text = name = "";
  }
};
Example #18
0
exports.request = function(request){
	if(request.url){
		var parsed = parse(request.url);
		for(var i in parsed){
			request[i] = parsed[i];
		}
	}
	var deferred = defer();
	if(exports.proxyServer){
		request.pathname = request.url;
		var proxySettings = parse(exports.proxyServer);
		request.port = proxySettings.port; 
		request.host = proxySettings.hostname;
	}
	
	var client = http.createClient(request.port || 80, request.host);

	var req = client.request(request.method || "GET", request.pathname || request.pathInfo, request.headers || {host: request.hostname});
	var timedOut;
	req.addListener("response", function (response){
		if(timedOut){
			return;
		}
		response.status = response.statusCode;
		var sendData = function(block){
			buffer.push(block);
		};
		var buffer = [];
		var bodyDeferred = defer();
		var body = response.body = LazyArray({
			some: function(callback){
				buffer.forEach(callback);
				sendData = callback;
				return bodyDeferred.promise;
			}
		});
		if(request.encoding){
			response.setEncoding(request.encoding);
		}

		response.addListener("data", function (chunk) {
			sendData(chunk);
		});
		response.addListener("end", function(){
			bodyDeferred.resolve();
		});
		response.addListener("error", function(error){
			bodyDeferred.reject(error);
		});
		deferred.resolve(response);
		clearTimeout(timeout);
	});
	var timeout = setTimeout(function(){
		timedOut = true;
		deferred.reject(new Error("Timeout"));
	}, 20000);
	req.addListener("error", function(error){
		deferred.reject(error);
	});
	req.addListener("timeout", function(error){
		deferred.reject(error);
	});
	req.addListener("close", function(error){
		deferred.reject(error);
	});
	if(request.body){
		return when(request.body.forEach(function(block){
			req.write(block);
		}), function(){
			req.end();
			return deferred.promise;
		});
	}
	req.end();
	return deferred.promise;
};
Example #19
0
	connect = require('connect'),
  _ = require('underscore')
    ,client = redis.createClient(),
    sub = redis.createClient(),
    pub = redis.createClient(),
    crypto = require('crypto')
    , http = require('http')
    , url = require('url')
	, querystring = require('querystring')
    , fs = require('fs')
    , sys = require(process.binding('natives').util ? 'util' : 'sys')
    , server
	, newfeed = require('./models/newfeed')
	, newuser = require('./models/user')
	, RedisStore = require('connect-redis')(express), multi
	, local = http.createClient(8002, '74.207.246.247')
	, fb = require('facebook-js'),
  async = require('async'),
  request = require('request');
function epoch(){return Math.round(new Date().getTime()/1000.0)};

client.on("error", function (err) {
    console.log("Error " + err);
});

// Configuration

app.configure(function(){
  app.use(express.logger({ format: '\x1b[1m:method\x1b[0m \x1b[33m:url\x1b[0m :response-time ms' }));
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
Example #20
0
      sys.puts("expected to be bad");
    }
    mp.addListener("error", function (er) {
      sys.puts("!! error occurred");
      res.writeHeader(400, {});
      res.write("bad");
      res.close();
    });
    mp.addListener("complete", function () {
      res.writeHeader(200, {});
      res.write("ok");
      res.close();
    });
  }),
  message,
  client = http.createClient(PORT);
server.listen(PORT);

// could dry these two up a bit.
function testGoodMessages () {
  var httpMessages = fixture.messages.slice(0);
  sys.puts("testing "+httpMessages.length+" good messages");
  (function testHTTP () {
    message = httpMessages.pop();
    if (!message) {
      testBadMessages();
      return;
    }
    sys.puts("test message "+httpMessages.length);
    var req = client.request("POST", "/", message.headers);
    req.write(message.body, "binary");
Example #21
0
function addBehaviors(bot, properties) {
    
    var persistence = new Persistence(properties);
    
    var userEval = 1;
    var yahooClient = http.createClient(80, 'answers.yahooapis.com');

    
    // Rate to mix in yahoo answers with stored responses
    // 0.75 = 75% Yahoo answers, 25% stored responses
    var mix = 0.5;
    
    bot.addMessageListener("logger", function(nick, message) {
        // Check to see if this is from a nick we shouldn't log
        if (properties.logger.ignoreNicks.filter(function (x) { return nick.indexOf(x) > -1; }).length > 0) {
            return true;
        }
        if (! (/^!/).test(message)) {
            persistence.saveMessage(nick, message);
        }
        return true;
    });

    var yahooAnswer = function(message) {
        var url = '/AnswersService/V1/questionSearch?appid=' + properties.yahooId + 
            "&query=" + querystring.escape(message) + "&type=resolved&output=json";
        sys.log("Calling " + url);
        var request = yahooClient.request('GET', url, { host: 'answers.yahoo.com' });
        request.end();
        var data = '';
        request.on('response', function(response) {
            response.setEncoding('utf8');
            response.on('data', function(chunk) {
                data += chunk;
            });
            response.on('end', function() {
                try {
                    var yahooResponse = JSON.parse(data);
                    if (yahooResponse.all.count > 0) {
                        var bestAnswer = yahooResponse.all.questions[0].ChosenAnswer;
                        bestAnswer = bestAnswer.substring(0, 400);
                        bot.say(bestAnswer);
                    } else {
                        persistence.getRandom(bot);
                    }
                } catch (err) {
                    sys.log(err);
                    persistence.getRandom(bot);
                }
            });
        });
    };

    bot.addMessageListener("listen for name", function (nick, message) {
        var re = new RegExp(properties.bot.nick);
        if (re.test(message)) {
            if (Math.random() < mix && properties.yahooId) {
                sys.log("mix = " + mix + ", serving from yahoo answers");
                yahooAnswer(message.replace(re, ''));
            } else {
                sys.log("mix = " + mix + ", serving from mysql");
                persistence.getRandom(bot);
            }
            return false;
        } else {
            return true;
        }
    });

    bot.addCommandListener("!do [nick]", /!do ([0-9A-Za-z_\-]*)/, "random quote", function(doNick) {
        persistence.getQuote(doNick, bot);
    });
    
    bot.addCommandListener("!msg [#]", /!msg ([0-9]*)/, "message recall", function(id) {
        persistence.getMessage(id, bot);
    });

    bot.addCommandListener("!about [regex pattern]", /!about (.*)/, "random message with phrase", function(pattern) {
        persistence.matchMessage(pattern, bot);
    });

    bot.addCommandListener("!uds", /!uds/, "random message about uds", function() {
        persistence.matchMessage('uds', bot);
    });

    bot.addCommandListener("!aevans", /!aevans/, "so, message from aevans", function() {
        persistence.matchMessageForNick('aevans', '^so(\\s|,)', bot);
    });

    bot.addCommandListener("!leaders [start index]", /!leaders\s*(\d*)/, "top users by message count", function(index) {
        persistence.leaders(index, bot);
    });

    bot.addCommandListener("!playback start end", /!playback (\d+ \d+)/, "playback a series of messages", function(range) {
        var match = range.match(/(\d+) (\d+)/);
        if (match) {
            var start = match[1];
            var end = match[2];
            if (end - start >= 10) {
                bot.say("playback limited to 10 messages");
            } else if (start >= end) {
                bot.say("start must be less than end");
            } else {
                for (var i = start; i <= end; i++) {
                    persistence.getMessage(i, bot);
                }
            }
        }
    });

    bot.addCommandListener("!stats nick", /!stats (.*)/, "stats about a user", function(nick) {
        persistence.userStats(nick, bot);
    });

    bot.addCommandListener("!alarm <time> -m <message>", /!alarm (.* -m .*)/, "set an alarm, valid time examples: 5s, 5m, 5h, 10:00, 14:30, 2:30pm", function(timeString, nick) {
        var matchInterval = timeString.match(/(\d+)([h|m|s]) -m (.*)/);
        var matchTime = timeString.match(/(\d{1,2}):(\d{2})(am|pm){0,1} -m (.*)/);
        if (matchInterval) {
            var timeNumber = matchInterval[1];
            var timeUnit = matchInterval[2];
            var sleepTime = timeNumber;
            if (timeUnit === 'h') {
                sleepTime = sleepTime * 60 * 60 * 1000;
            } else if (timeUnit === 'm') {
                sleepTime = sleepTime  * 60 * 1000;
            } else if (timeUnit === 's') {
                sleepTime = sleepTime * 1000;
            }
            if (sleepTime < 2147483647) {
                bot.say("Alarm will go off in " + msToString(sleepTime));
                setTimeout(function() {
                    bot.say(nick + ': ' + matchInterval[3]);
                }, sleepTime);
            } else {
                bot.say("Delay exceeds maximum timeout, see: http://stackoverflow.com/questions/3468607/why-does-settimeout-break-for-large-millisecond-delay-values");
            }
        } else if (matchTime) {
            var hour = parseInt(matchTime[1]);
            var minute = matchTime[2];
            if (matchTime[3] === 'pm' && hour != 12) {
                hour = hour + 12;
            } else if (matchTime[3] === 'am' && hour === 12) {
                hour = 0;
            }
            var now = new Date();
            var sleepTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minute, 0, 0) - now;
            if (sleepTime < 0) {
                sleepTime += 86400000;
            }
            bot.say("Alarm will go off in " + msToString(sleepTime));
            setTimeout(function() {
                bot.say(nick + ': ' + matchTime[4]);
            }, sleepTime);
        } else {
            bot.say("Unknown time format!");
        }
    });

    bot.addCommandListener("!uname", /!uname/, "information about host", function() {
        child_process.exec('uname -a', function(error, stdout, stderr) {
            bot.say(stdout);
        });
    });

    bot.addCommandListener("!version", /!version/, "report node version", function() {
        bot.say("Node version = " + process.version);
    });
    
    bot.addCommandListener("!help <cmd>", /!help(.*)/, "command help", function(cmd) {
        if (cmd) {
            bot.helpCommand(cmd);
        } else {
            bot.listCommands();
        }
    });
    
    bot.addCommandListener("!quote [symbol]", /!quote (.*)/, "get a stock quote", function(symbol) {
        var url = '/MODApis/Api/v2/Quote?symbol=' + symbol;
        var options = {
            host: 'dev.markitondemand.com',
            port: 80,
            path: url
        };
        var req = http.get(options, function(response) {
            var data = "";
            response.setEncoding("utf8");
            response.on("data", function(chunk) {
                data += chunk;
            });
            response.on("end", function() {
                xml2jsParser(data, function(err, result) {
                    console.log(result);
                    if (! result.Error && result.StockQuote.Status[0].indexOf('Failure') == -1) {
                        var mktCap = parseInt(result.StockQuote.MarketCap[0]);
                        var mktCapString = "";
                        if (mktCap > 1000000000) {
                            mktCapString = "$" + ((mktCap/1000000000).toFixed(2)) + "B";
                        } else if (mktCap > 1000000) {
                            mktCapString = "$" + ((mktCap/1000000).toFixed(2)) + "M";
                        }
                        var changePrefix = (result.StockQuote.Change[0] > 0) ? '+' : '';
                        bot.say(result.StockQuote.Name[0] + ' ... ' + 
                            '$' + result.StockQuote.LastPrice[0] + ' ' + 
                            changePrefix + result.StockQuote.Change[0] + ' ' + 
                            changePrefix + parseFloat(result.StockQuote.ChangePercent[0]).toFixed(2) + '% ' + 
                            mktCapString);
                    } else {
                        bot.say("Unable to get a quote for " + symbol);
                    }
                });
            });
        });
    });
    
    bot.addMessageListener("toggle", function(nick, message) {
        var check = message.match(/!toggle (.*)/);
        if (check) {
            var name = check[1];
            var result = bot.toggleMessageListener(name);
            if (result) {
                bot.say("Message listener " + name + " is active");
            } else {
                bot.say("Message listener " + name + " is inactive");
            }
            return false;
        }
        return true;
    });

    bot.addMessageListener("eval", function(nick, message) {
        var check = message.match(/!add (.*)/);
        if (check) {
            var msg = check[1];
            var mlName = "user eval " + userEval++;
            bot.addMessageListener(mlName, function(nick, message) {
                var sandbox = { output: null, nick: nick, message: message };
                Script.runInNewContext(msg, sandbox);
                if (sandbox.output) {
                    bot.say(sandbox.output);
                    return false;
                }
                return true;
            });
            bot.say("Added message listener: " + mlName);
            return false;
        }
        return true;
    });
        
    bot.addCommandListener("!define [phrase]", /!define (.*)/, "urban definition of a word or phrase", function(msg) {
        var data = "";
        var request = require('request');
        request("http://api.urbandictionary.com/v0/define?term=" + querystring.escape(msg), function (error, response, body) {
          if (!error && response.statusCode == 200) {
            var urbanresult = JSON.parse(body);
            bot.say(urbanresult.list[0].definition);
          }
        })
    });

    bot.addCommandListener("!example [phrase]", /!example (.*)/, "Use of urban definition of a word or phrase in a sentence", function(msg) {
        var data = "";
        var request = require('request');
        request("http://api.urbandictionary.com/v0/define?term=" + querystring.escape(msg), function (error, response, body) {
          if (!error && response.statusCode == 200) {
            var urbanresult = JSON.parse(body);
            bot.say(urbanresult.list[0].example);
          }
        })
    });

    bot.addCommandListener("!showerthought", /!showerthought/, "Return a reddit shower thought", function(msg) {
        var data = "";
        var request = require('request');
        request("http://www.reddit.com/r/showerthoughts/.json", function (error, response, body) {
          if (!error && response.statusCode == 200) {
            //console.log(body) // Print the results
            var showerthought = JSON.parse(body);
            // There are many returned in the json.  Get a count
            var showercount=showerthought.data.children.length
            var randomthought=Math.floor((Math.random() * showercount) + 1);
            console.log("Found " + showercount + " shower thoughts.  Randomly returning number " + randomthought);
            bot.say(showerthought.data.children[randomthought].data.title);
          }
        })
    });

    bot.addCommandListener("!firstworldproblems", /!firstworldproblems/, "Return a reddit first world problem", function(msg) {
        var data = "";
        var request = require('request');
        request("http://www.reddit.com/r/firstworldproblems/.json", function (error, response, body) {
          if (!error && response.statusCode == 200) {
            //console.log(body) // Print the results
            var firstworldproblem = JSON.parse(body);
            // There are many returned in the json.  Get a count
            var problemcount=firstworldproblem.data.children.length
            var randomproblem=Math.floor((Math.random() * problemcount) + 1);
            console.log("Found " + problemcount + " shower thoughts.  Randomly returning number " + randomproblem);
            bot.say(firstworldproblem.data.children[randomproblem].data.title);
          }
        })
    });

}
Example #22
0
    (function() {
        // Parse constructor arguments 
        if (!url) {
            throw new Error('Url and must be specified.');
        }

        // Secrets used for handshaking
        var key1 = createSecretKey();
        var key2 = createSecretKey();
        var challenge = createChallenge();

        debug(
            'key1=\'' + str2hex(key1) + '\'; ' +
            'key2=\'' + str2hex(key2) + '\'; ' +
            'challenge=\'' + str2hex(challenge) + '\''
        );

        var httpHeaders = {
            'Connection' : 'Upgrade',
            'Upgrade' : 'WebSocket',
            'Sec-WebSocket-Key1' : key1,
            'Sec-WebSocket-Key2' : key2
        };
        if (opts.origin) {
            httpHeaders['Origin'] = opts.origin;
        }
        if (proto) {
            httpHeaders['Sec-WebSocket-Protocol'] = proto;
        }

        var httpPath = '/';

        // Create the HTTP client that we'll use for handshaking. We'll cannabalize
        // its socket via the 'upgrade' event and leave it to rot.
        //
        // N.B. The ws+unix:// scheme makes use of the implementation detail
        //      that http.Client passes its constructor arguments through,
        //      un-inspected to net.Stream.connect(). The latter accepts a
        //      string as its first argument to connect to a UNIX socket.
        var httpClient = undefined;
        switch (getUrlScheme(url)) {
        case 'ws':
            var u = urllib.parse(url);
            httpClient = http.createClient(u.port || 80, u.hostname);
            httpPath = (u.pathname || '/') + (u.search || '');
            httpHeaders.Host = u.hostname + (u.port ? (":" + u.port) : "");
            break;

        case 'ws+unix':
            var sockPath = url.substring('ws+unix://'.length, url.length);
            httpClient = http.createClient(sockPath);
            httpHeaders.Host = 'localhost';
            break;

        default:
            throw new Error('Invalid URL scheme \'' + urlScheme + '\' specified.');
        }

        httpClient.on('upgrade', (function() {
            var data = undefined;

            return function(req, s, head) {
                stream = s;

                stream.on('data', function(d) {
                    if (d.length <= 0) {
                        return;
                    }

                    if (!data) {
                        data = d;
                    } else {
                        var data2 = new buffer.Buffer(data.length + d.length);

                        data.copy(data2, 0, 0, data.length);
                        d.copy(data2, data.length, 0, d.length);

                        data = data2;
                    }

                    if (data.length >= 16) {
                        var expected = computeSecretKeySignature(key1, key2, challenge);
                        var actual = data.slice(0, 16).toString('binary');

                        // Handshaking fails; we're donezo
                        if (actual != expected) {
                            debug(
                                'expected=\'' + str2hex(expected) + '\'; ' +
                                'actual=\'' + str2hex(actual) + '\''
                            );

                            process.nextTick(function() {
                                // N.B. Emit 'wserror' here, as 'error' is a reserved word in the
                                //      EventEmitter world, and gets thrown.
                                self.emit(
                                    'wserror',
                                    new Error('Invalid handshake from server:' +
                                        'expected \'' + str2hex(expected) + '\', ' +
                                        'actual \'' + str2hex(actual) + '\''
                                    )
                                );

                                if (self.onerror) {
                                    self.onerror();
                                }

                                finishClose();
                            });
                        }

                        // Un-register our data handler and add the one to be used
                        // for the normal, non-handshaking case. If we have extra
                        // data left over, manually fire off the handler on
                        // whatever remains.
                        //
                        // XXX: This is lame. We should only remove the listeners
                        //      that we added.
                        httpClient.removeAllListeners('upgrade');
                        stream.removeAllListeners('data');
                        stream.on('data', dataListener);

                        readyState = OPEN;

                        process.nextTick(function() {
                            self.emit('open');

                            if (self.onopen) {
                                self.onopen();
                            }
                        });

                        // Consume any leftover data
                        if (data.length > 16) {
                            stream.emit('data', data.slice(16, data.length));
                        }
                    }
                });
                stream.on('fd', fdListener);
                stream.on('error', errorListener);
                stream.on('close', function() {
                    errorListener(new Error('Stream closed unexpectedly.'));
                });

                stream.emit('data', head);
            };
        })());
        httpClient.on('error', function(e) {
            httpClient.end();
            errorListener(e);
        });

        var httpReq = httpClient.request(httpPath, httpHeaders);

        httpReq.write(challenge, 'binary');
        httpReq.end();
    })();
Example #23
0
	this.perform = function(rurl, method, cb, data, exheaders, tlscb) {
		this.clientheaders = exheaders;
		var curl = url.parse(rurl);
		var key = curl.protocol + "//" + curl.hostname;

		if(!clients[key]) {
			var client = null;
			switch(curl.protocol) {
				case "https:":
					client = http.createClient(curl.port||443, curl.hostname);
					//client.setSecure();
//"x509_PEM");
				break;
				default:
					client = http.createClient(curl.port||80, curl.hostname);
					break;
			}
			clients[key] = {
				"http": client,
				"headers": {}
			};
		}

		clients[key].headers = {
			"User-Agent": "Node-Http",
			"Accept" : "*/*",
			"Connection" : "close",
			"Host" : curl.hostname
		};
		if(method == "POST" || method == "PUT") {
			clients[key].headers["Content-Length"] = data.length;
			clients[key].headers["Content-Type"] = "application/json";
		}	

		for (attr in exheaders) { clients[key].headers[attr] = exheaders[attr]; }		
		if(!compress && clients[key].headers["Accept-Encoding"]) {
			clients[key].headers["Accept-Encoding"] = "none";
		}
		var mycookies = [];

		cookies.filter(function(value, index, arr) {
			if(curl.pathname) {
				return(curl.hostname.substring(curl.hostname.length - value.domain.length) == value.domain && curl.pathname.indexOf(value.path) >= 0);
			}
			else {
				return(curl.hostname.substring(curl.hostname.length - value.domain.length) == value.domain);
			}
		}).forEach( function(cookie) {
			mycookies.push(cookie.value);
		});
		if( mycookies.length > 0 ) {
			clients[key].headers["Cookie"] = mycookies.join(";");
		}

		var target = "";
		if(curl.pathname) target += curl.pathname;
		if(curl.search) target += curl.search;
		if(curl.hash) target += curl.hash;
		if(target=="") target = "/";

		var req = clients[key].http.request(method, target, clients[key].headers);
		req.addListener("response", function(res) {
			var mybody = [];
			if(tlscb) {
				if(!tlscb({
						"status" : res.connection.verifyPeer(), 
						"certificate" : res.connection.getPeerCertificate("DNstring")
					}
				)) {
					cb(-2, null, null);		
					return;
				}
			}
			res.setEncoding("utf8");
			if(res.headers["content-encoding"] == "gzip") {
				res.setEncoding("binary");
			}
			res.addListener("data", function(chunk) {
				mybody.push(chunk);
			});
			res.addListener("end", function() {
				var body = mybody.join("");
				if( compress !== null && res.headers["content-encoding"] == "gzip") {
					gunzip.init();
					body = gunzip.inflate(body, "binary");
					gunzip.end();
				}
				var resp = {
					"response": {
						"status" : res.statusCode,
						"headers" : res.headers,
						"body-length" : body.length,
						"body" : body
					},
					"request": {
						"url" : rurl,
						"headers" : clients[key].headers
					}
				}
				cb(resp);	
			});
			res.addListener("error", function() {
				cb(-1, res.headers, mybody.join(""));		
			});
			if(res.headers["set-cookie"]) {
				res.headers["set-cookie"].forEach( function( cookie ) {
					props = cookie.split(";");
					var newcookie = {
						"value": "",
						"domain": "",
						"path": "/",
						"expires": ""
					};

					newcookie.value = props.shift();
					props.forEach( function( prop ) {
						var parts = prop.split("="),
						name = parts[0].trim();
						switch(name.toLowerCase()) {
							case "domain":
								newcookie.domain = parts[1].trim();
								break;
							case "path":
								newcookie.path = parts[1].trim();
								break;
							case "expires":
								newcookie.expires = parts[1].trim();
								break;
						}
					});
					if(newcookie.domain == "") newcookie.domain = curl.hostname;
					var match = cookies.filter(function(value, index, arr) {
						if(value.domain == newcookie.domain && value.path == newcookie.path && value.value.split("=")[0] == newcookie.value.split("=")[0]) {
							arr[index] = newcookie;
							return true;
						}
						else {
							return false;
						}
					});
					if(match.length == 0) cookies.push(newcookie);
				});
			}
		});
		if(method == "POST" || method == "PUT") {
			req.write(data);
		}
		req.end();
	}
Example #24
0
var http = require('http');
var testCase = require('nodeunit').testCase;

var base = require('../test/base.js');
var dao = require('../dao.js');


var hostname = process.env.HOSTNAME || 'localhost';
var port = process.env.PORT || 3000;

// copied (and then modified) from httputil method 
// https://github.com/caolan/nodeunit/blob/master/lib/utils.js
var client = http.createClient(port, hostname);
client.fetch = function (method, path, headers, respReady) {
  var request = this.request(method, path, headers);
  request.end();
  request.on('response', function (response) {
    response.setEncoding('utf8');
    response.on('data', function (chunk) {
        if (response.body) {
            response.body += chunk;
        } else {
            response.body = chunk;
        }
    });
    response.on('end', function () {
        if (response.headers['content-type'].indexOf('application/json') != -1) {
            response.bodyAsObject = JSON.parse(response.body);
        }
        respReady(response);
    });
Example #25
0
 topic: function () {
     app.listen(8000);            
     client = http.createClient(8000, 'localhost');
     return null;
 },
Example #26
0
    var _updateAllNodes = function(callback) {

        var _allNodes = {};
        var _processedSeeds = 0;
        var _numberOfSeeds = seeds.length;

        for (var i = 0; i < _numberOfSeeds; i++) {

            var s = seeds[i].split(":");
            if (s && s.length == 2) {

                var c = http.createClient(s[1],s[0]);

                c.addListener('error', function (err) {
                    sys.log("Error using seed host: "+s[0]+":"+s[1]);
                    console.log(err);
                    _processedSeeds++;
                    if (_processedSeeds === _numberOfSeeds) {
                        if (callback && typeof callback === "function") callback();
                    }
                });

                var request = c.request("GET", "/_nodes");
                request.on('response', function(response) {

                    var o = "";

                    response.on('data', function(chunk) { o += chunk; });

                    response.on('end', function() {
                        var clusterNodes = JSON.parse(o);
                        if (!clusterName) {clusterName = clusterNodes.cluster_name};
                        // If cluster name does not match then skip node response.
                        if (clusterName === clusterNodes.cluster_name) {
                            for (nid in clusterNodes.nodes) {
                                if (clusterNodes.nodes[nid].http_address || clusterNodes.nodes[nid].httpAddress) {
                                    var nodeInfo = extractNodeInfo(clusterNodes.nodes[nid]);
                                    // safety check: if http address parsing fails then empty object is returned
                                    if (nodeInfo && nodeInfo.nodeName) {
                                        _allNodes[nid] = nodeInfo;
                                    }
                                }
                            }
                        }
                        _processedSeeds++;
                        if (_processedSeeds === _numberOfSeeds) {
                            allNodes = mergeNodes(allNodes, _allNodes);
                            allNodesCount = 0;
                            for (n in allNodes) { if (allNodes.hasOwnProperty(n)) allNodesCount++; }
//                            console.log("updated all nodes: " + new Date());
//                            console.log(allNodes);
                            if (callback && typeof callback === "function") callback();
                        }
                    });
                });

                request.end();

            } else {
                _processedSeeds++;
            }
        }
    }
Example #27
0
function client(s){
  return http.createClient(s._port, 'localhost');
};
Example #28
0
    case 'start':
        verb = 'Starting'.green;
        past = 'started';
        break;
    case 'stop':
        verb = 'Stopping'.red.bold;
        past = 'stopped';
        break;
    default:
        action = 'restart';
        verb = 'Restarting'.yellow;
        past = 'restarted';
        break;
}

var couch_http = http.createClient(config.opt.couch_port, config.opt.couch_host);
if (config.opt.couch_prefix.length > 0) {
  var cprefix = config.opt.couch_prefix + '_';
} else {
  var cprefix = '';
}

// var request = couch_http.request(
//   'GET',
//   '/' + cprefix + 'apps' + '/_design/nodeapps/_view/all',
//   {
//     'host': config.opt.couch_host,
//     'Authorization': "Basic " + base64_encode(new Buffer(config.opt.couch_user + ":" + (config.opt.couch_pass || "")))
//   }
// );
Example #29
0
exports.request = function(originalRequest){
	// make a shallow copy of original request object
	var request = {};
	for(var key in originalRequest){
		if(originalRequest.hasOwnProperty(key)){
			request[key] = originalRequest[key];
		}
	}
	
	if(request.url){
		var parsed = parse(request.url);
		if (parsed.pathname) {
			parsed.pathInfo = parsed.pathname;
		} else {
			parsed.pathInfo = "/";
		}
		request.queryString = parsed.query || "";
		for(var i in parsed){
			request[i] = parsed[i];
		}
	}
	var deferred = defer();
	if(exports.proxyServer){
		request.pathname = request.url;
		var proxySettings = parse(exports.proxyServer);
		request.port = proxySettings.port; 
		request.protocol = proxySettings.protocol;
		request.hostname = proxySettings.hostname;
	}
	
	var secure = request.protocol.indexOf("s") > -1;
	var client = http.createClient(request.port || (secure ? 443 : 80), request.hostname, secure);
	var timedOut, bodyDeferred;
	client.on("error", function(error){
		if(bodyDeferred){
			bodyDeferred.reject(error);
		}else{
			deferred.reject(error);
		}
		clearTimeout(timeout);
	});
	// Limits the time of sending the request + receiving the response header to 20 seconds.
	// No timeout is used on the client stream, but we do destroy the stream if a timeout is reached.
	var timeout = setTimeout(function(){
		timedOut = true;
		client.destroy();
		deferred.reject(new Error("Timeout"));
	}, 20000);

	var requestPath = request.pathname || request.pathInfo || "";
	if (request.queryString) {
	  requestPath += "?"+request.queryString;
	}

	var req = client.request(request.method || "GET", requestPath, request.headers || 
		{host: request.host || request.hostname + (request.port ? ":" + request.port : "")});
	req.on("response", function (response){
		if(timedOut){
			return;
		}
		response.status = response.statusCode;
		var sendData = function(block){
			buffer.push(block);
		};
		var buffer = [];
		bodyDeferred = defer();
		var body = response.body = LazyArray({
			some: function(callback){
				buffer.forEach(callback);
				sendData = callback;
				return bodyDeferred.promise;
			}
		});
		response.setEncoding(request.encoding || "utf8");

		response.on("data", function (chunk) {
			sendData(chunk);
		});
		response.on("end", function(){
			bodyDeferred.resolve();
			// Since we have no connection pooling, let's not pretend to use Keep-Alive
			client.end();
		});
		deferred.resolve(response);
		clearTimeout(timeout);
	});
	if(request.body){
		return when(request.body.forEach(function(block){
			req.write(block);
		}), function(){
			req.end();
			return deferred.promise;
		});
	}else{
		req.end();
		return deferred.promise;
	}
};
Example #30
0
CouchDB.prototype.client = function (method, path, data, callback) {
    path = (this.instance.pathname || '') + '/' + path;

    var headers = {
        'Host': this.instance.hostname,
        'Accept': 'application/json'
    };
    if (method === 'POST' || method === 'PUT') {
        if (typeof data !== 'string') {
            try {
                data = JSON.stringify(data);
            }
            catch (e) {
                return callback(e);
            }
        }
        headers['Content-Type'] = 'application/json';
    }
    else if (data) {
        path = url.parse(path).pathname + '?' + querystring.stringify(data);
    }

    if (this.instance.auth) {
        var enc = new Buffer(this.instance.auth).toString('base64');
        headers.Authorization = "Basic " + enc;
    }

    var client = http.createClient(this.instance.port, this.instance.hostname);
    client.on('error', callback);
    var request = client.request(method, path, headers);

    request.on('response', function (response) {
        logger.debug('response:', {
            headers: response.headers,
            url: response.url,
            method: response.method,
            statusCode: response.statusCode
        });
        var buffer = [];
        response.on('data', function (chunk) {
            buffer.push(chunk.toString());
        });
        response.on('end', function () {
            var data = buffer.length ? JSON.parse(buffer.join('')): null;
            logger.debug('data:', data);
            if (response.statusCode >= 300) {
                if (data && data.error) {
                    //var err = new Error(data.reason || data.error);
                    var err = new Error(data.reason || data.error);
                    err.error = data.error;
                    err.reason = data.reason;
                    err.response = response;
                    callback(err, data, response);
                }
                else {
                    var err2 = exports.statusCodeError(response.statusCode);
                    err2.response = response;
                    callback(err2, data, response);
                }
            }
            else {
                process.nextTick(function () {
                    callback(null, data, response);
                });
            }
        });
    });

    if (data && (method === 'POST' || method === 'PUT')) {
        request.write(data, 'utf8');
    }
    request.end();

    logger.debug('request:', request.output[0]);
};