Example #1
0
	resp.on('data', function(chunk) {
	    var str = chunk.slice(chunk.search(/\<.*thick.*\>/),chunk.search('thick'));
	    var str2 = str.slice(str.search('value'), str.search('style'));
	    var str3 = str2.slice(str2.search('\"')+1, str2.search('\%'));
	    
	    var timenow = new Date().getTime();
	    if (dir.match(/\/vol\+/))
	    {
		newvol = parseInt(str3) + 10;
		if (newvol > 90)
		    newvol = 90;
	    }

	    else if (dir.match(/\/vol\-/))
	    {
		newvol = parseInt(str3) - 10;
		if (newvol < 0)
		    newvol = 0;
	    }

	    // otherwise, we are being lazy and using dir to pass in a value
	    else
	    {
		console.log('Passed in value: ' +dir);

		if (dir.match(/^\/vol*/))
		{
		    console.log('matched "vol..."');

		    var subs1 = dir.slice(4);
		    var subs2 = subs1.trim();
		    dir = subs2;
		}

		newvol = parseInt(dir);

		if (isNaN(newvol))
		    return;
	    }

	    if (userid == null)
		bot.speak('Changed Volume from ' +str3+ '% to ' +newvol+ '%', userid);
	    else
		bot.pm('Changed Volume from ' +str3+ '% to ' +newvol+ '%', userid);

	    var post_data = qs.stringify({ volume: newvol + '%', '_': timenow });

	    var options = {
		host: 'voltron',
		port: 80,
		path: '/internal/audioControl/',
		method: 'POST',
		headers: {
		    'Content-Type': 'application/x-www-form-urlencoded',
		    'Content-Length': post_data.length
		}
	    };
    
    
	    var req2 = http.request(options, function (resp){
		resp.setEncoding('utf8');
		
		resp.on('data', function (chunk){
		    console.log('response = |' +chunk+ '|');
		});
	    });
	    
	    req2.on("error", function(e){
		console.log('Got an error: ' +e.message);
	    });
	    
	    req2.write(post_data+ '\n');
	    req2.end();

	});
Example #2
0
var http = require('http');
var postData = "";
	
var req = http.request({host: 'www.google.it', method: 'get', path: '/', port: 80}, function(res) {
	res.on('data', function(data) {
		console.log("response.. "+data);
	});
	
	res.on('end', function(data) {
		console.log("response.. "+res.statusCode);
	});
});

if (postData) req.write(postData);
req.end();

req.on('error', function(e) {
  console.error(e);
});
Example #3
0
/*
Function
    Make a HTTP request
Description
    Actually makes a HTTP request based on the options passed
Paramters
    options
        -> type object
        -> HTTP request options
    successCallback, errorCallback
        -> type function
        -> to be called when the HTTP request is a success / failure
*/
function makeRequest(options, successCallback, errorCallback) {
    var request,
        bufferData = new Buffer(options.data),
        bufferLength = bufferData.length;

    options.headers['Content-Length'] = bufferLength;

    options.headers['Content-Type'] = 'application/json';

    options.path += '?api_key=' + options.apiKey;

    if (options.method === 'GET' || options.method === 'DELETE') {
        options.path += '&query=' + encodeURIComponent(options.query) + '&projection=' +
                        encodeURIComponent(options.projection) + '&orderBy=' +
                        encodeURIComponent(options.orderBy);
    }

    if (options.limit !== 0) {
        options.path += '&limit=' + options.limit;
    }

    delete options.apiKey;

    delete options.query;

    delete options.projection;

    delete options.limit;

    delete options.orderBy;

    request = http.request(options, function (response) {
        var body = '';

        response.setEncoding('utf8');

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

        response.on('end', function () {
            var data = null;

            //Only consider successful requests
            //Consider 2xx and 3xx status codes as successful - bulk actions returns 202 for example
            if (response.statusCode >= 200 && response.statusCode < 400) {
                if (body) {
                    try {
                        data = JSON.parse(body);
                    } catch (err) {
                        console.log(" => Error occurred while attempting to read response for API request");
                        console.log(err);

                        if (errorCallback) {
                            errorCallback(err);
                        }

                        return;
                    }
                }

                if (successCallback) {
                    successCallback(data);
                }
            } else {
                console.log(" => API request not successful. Status code is : ", response.statusCode)

                if (errorCallback) {
                    errorCallback(new Error('Issues with API request. See status code in console.'));
                }
            }
        });
    });

    request.on('error', function (err) {
        console.log(" => Error while API request : ", err)

        if (errorCallback) {
            errorCallback(err);
        }
    });


    if (options.method !== "GET" && options.data.length > 0) {
        request.write(options.data);
    }

    request.end();
}
Example #4
0
  this.call = function(method, params, callback, errback, path) {
    
    var time = Date.now();
    var requestJSON;
    
    if (Array.isArray(method)) {
      // multiple rpc batch call
      requestJSON = [];
      method.forEach(function(batchCall, i) {
        requestJSON.push({
          id: time + '-' + i,
          method: batchCall.method,
          params: batchCall.params
        });
      });
    } else {
      // single rpc call
      requestJSON = {
        id: time,
        method: method,
        params: params
      };
    }

    // First we encode the request into JSON
    var requestJSON = JSON.stringify(requestJSON);

    // prepare request options
    var requestOptions = {
      host: host,
      port: port,
      method: 'POST',
      path: path || '/',
      headers: {
        'Host': host,
        'Content-Length': requestJSON.length
      }
    };
    
    // use HTTP auth if user and password set
    if (user && password) {
      requestOptions.auth = this.user + ':' + this.password;
    }
    
    // Now we'll make a request to the server
    var request = http.request(requestOptions);
    
    request.on('error', errback);

    request.on('response', function(response) {
      // We need to buffer the response chunks in a nonblocking way.
      var buffer = '';
      response.on('data', function(chunk) {
        buffer = buffer + chunk;
      });
      // When all the responses are finished, we decode the JSON and
      // depending on whether it's got a result or an error, we call
      // emitSuccess or emitError on the promise.
      response.on('end', function() {
        var err;
        
        try {
          var decoded = JSON.parse(buffer);
        } catch (e) {
          if (response.statusCode !== 200) {
            err = new Error('Invalid params, response status code: ' + response.statusCode);
            err.code = -32602;
            errback(err);
          } else {
            err = new Error('Problem parsing JSON response from server');
            err.code = -32603;
            errback(err);
          }
          return;
        }
        
        if (!Array.isArray(decoded)) {
          decoded = [decoded];
        }
        
        // iterate over each response, normally there will be just one
        // unless a batch rpc call response is being processed
        decoded.forEach(function(decodedResponse, i) {
          if (decodedResponse.hasOwnProperty('error') && decodedResponse.error != null) {
            if (errback) {
              err = new Error(decodedResponse.error.message || '');
              if (decodedResponse.error.code) {
                err.code = decodedResponse.error.code;
              }
              errback(err);
            }
          } else if (decodedResponse.hasOwnProperty('result')) {
            if (callback) {
              callback(decodedResponse.result);
            }
          } else {
            if (errback) {
              err = new Error(decodedResponse.error.message || '');
              if (decodedResponse.error.code) {
                err.code = decodedResponse.error.code;
              }
              errback(err);
            }
          }
        });
        
      });
    });
    request.end(requestJSON);
  };
Example #5
0
//const hostname = "128.208.7.228";

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

var options = {
		  hostname: 'localhost',
		  port: 9876,
		  path: '/upload',
		  method: 'POST'
		};

var req = http.request(options, function(res) {
	  console.log('STATUS: ' + res.statusCode);
	  console.log('HEADERS: ' + JSON.stringify(res.headers));
	  res.setEncoding('utf8');
	  res.on('data', function (chunk) {
	    console.log('BODY: ' + chunk);
	  });
	});

	req.on('error', function(e) {
	  console.log('problem with request: ' + e.message);
	});

	// write data to request body
	fs.readFile(process.argv[2], function(err, data) {
		req.write(data);
		req.end();
	});
Example #6
0
server.createServer(function(q,s){
//    console.dir(q);
    var headers = q.headers;
    headers.host = remoteServer;
    q.method === "GET" ? delete  headers['Content-length']: console.log('Content-length:',headers['Content-lenght']);
    var options = {
        hostname: remoteServer,
        host: remoteServer,
        path: q.url,
        port: 80,
        method: q.method,
        headers: headers
    };

//    console.log(options);
    var request = http.request(options, function(res){
        console.log(options.hostname+options.path);
        res.setEncoding('binary');
        s.setHeader("Access-Control-Allow-Origin", "*");
        s.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
        s.writeHead(res.statusCode,res.headers);

        res.on('data', function (chunk) {
            s.write(chunk,'binary');
        });

        res.on('end', function(){
            s.end();
            request.end();
        });
        res.on('error', function ( e ){
            console.log( 'Error with client ', e );
            request.end();
            console.log('DATA-ERROR');
        });
    });

    request.on('error', function(e) {
        console.log(e);
        s.end('<h1>ERROR WHILE REQUEST REMOTE URL... =_=</h1>');
        console.log('REQUEST-ERROR');
    });

    if(q.method==='GET'){
        request.write('\n');
    }
    var request_data = "";
    q.on('data', function ( chunk ){
        console.log( 'Write to server ', chunk.length );
        console.log( chunk.toString( 'utf8' ) );
        request_data = request_data + chunk;
        request.write( chunk, 'binary' );
    } );

    q.on( 'end', function(){
        console.log( 'End chunk write to server' );
    } );

    q.on( 'error', function ( e ){
        console.log( 'Problem with request ', e );
    } );

}).listen(listenPort);
Example #7
0
  function subscribeToEvents() {
    if (_this.zoneType == 4) {
      // If this is a bridge, we don't care
      return;
    }

    console.log("subscribing to events", _this.address, _this.roomName, _this.uuid, subscriptionTimeout);

    var callback = '<http://'+ discovery.localEndpoint +':' + discovery.notificationPort + '/>';

    // AVTransport
    // For track change and stuff like that

    var client = http.request({
      localAddress: discovery.localEndpoint,
      host: _this.address,
      port: 1400,
      path: '/MediaRenderer/AVTransport/Event',
      method: 'SUBSCRIBE',
      headers: {
        'CALLBACK': callback,
        'NT': 'upnp:event',
        'TIMEOUT': 'Second-' + subscriptionTimeout
      }
    }, function (res) {

      // Store some relevant headers?


    });

    client.on('error', function (e) {
      console.error(e);
      // Keep trying...
      setTimeout(subscribeToEvents, 2000);
    });

    client.end();

    // RenderingControl
    // For Volume and Mute events

    var client = http.request({
      localAddress: discovery.localEndpoint,
      host: _this.address,
      port: 1400,
      path: '/MediaRenderer/RenderingControl/Event',
      method: 'SUBSCRIBE',
      headers: {
        'CALLBACK': callback,
        'NT': 'upnp:event',
        'TIMEOUT': 'Second-' + subscriptionTimeout
      }
    }, function (res) {

      // Store some relevant headers?


    });

    client.on('error', function (e) {
      console.error(e);
    });

    client.end();

    // GroupRenderingControl
    // For GroupVolume and GroupMute events

     var client = http.request({
      localAddress: discovery.localEndpoint,
      host: _this.address,
      port: 1400,
      path: '/MediaRenderer/GroupRenderingControl/Event',
      method: 'SUBSCRIBE',
      headers: {
        'CALLBACK': callback,
        'NT': 'upnp:event',
        'TIMEOUT': 'Second-' + subscriptionTimeout
      }
    }, function (res) {

      // Store some relevant headers?


    });

    client.on('error', function (e) {
      console.error(e);
    });

    client.end();

    var client = http.request({
      localAddress: discovery.localEndpoint,
      host: _this.address,
      port: 1400,
      path: '/MediaServer/ContentDirectory/Event',
      method: 'SUBSCRIBE',
      headers: {
        'CALLBACK': callback,
        'NT': 'upnp:event',
        'TIMEOUT': 'Second-' + subscriptionTimeout
      }
    }, function (res) {

      // Store some relevant headers?


    });

    client.on('error', function (e) {
      console.error(e);
    });

    client.end();

    // Resubscribe after timeout * 0.9 seconds
    setTimeout(subscribeToEvents, subscriptionTimeout * 900);

  }
Example #8
0

    var req1 = http.request(options, function (res) {
        res.setEncoding("utf8");
        res.on("data", function (data) {
            console.log(data);
            var id = eval(data)[0].a1;
            if (id) {
                console.log('Get id' + id);
                post(id, 0);
            } else {
                var req2 = http.request(options, function (res) {
                    res.setEncoding("utf8");
                    res.on("data", function (data) {
                        console.log(data);
//                    var id = querystring.stringify(data)[0].a2;
                        console.log();
                        var id = data.substring(data.indexOf("a2\":\"") + 5, data.indexOf("\",\"a4"));
//                    var id = eval('(' + data + ')')[0].a2;
                        console.log('Get id ' + id);
                        post(id, 0);
                    });
                });
                req2.write(querystring.stringify({"ClubList": 401}));
                req2.end();
            }

        });
    });

    req1.write(querystring.stringify({"StartMatch": 38, "GoalDiff": 4}));
Example #9
0
exports.request_data=function(opts,data,fn,args){
    if(!opts || !fn) throw "argument null 'opt' or 'data'";
    var strData = data && JSON.stringify(data);
    if(opts.method=='POST')
        opts.headers['Content-Length']=Buffer.byteLength(strData,'utf8');
    
    var req = http.request(opts, function(res) {
	if (res.statusCode > 300 && res.statusCode < 400&& res.headers.location) {
	    var urlObj = url.parse(res.headers.location);

        if (urlObj.hostname && urlObj.protocol=='http:'){
	    console.log("Redirecting to "+res.headers.location);
	    //exports.request_data(res.headers.location,data,fn,args);
	    if(args==undefined){
		fn(null,[data,"redirect"],res);
	    }
	    else if(Array.isArray(args)){
		args.push(opts.data||data);
		args.push("redirect");
		fn(null,args,res);
	    }else{
		fn(null,[args,opts.data||data,"redirect"],res);
	    }
	}
        else {
	    req.abort();
	    console.log("do not handle https.");
	    if(args==undefined){
		fn(null,[data],res);
	    }
	    else if(Array.isArray(args)){
		args.push(opts.data||data);
		fn(null,args,res);
	    }else{
		fn(null,[args,opts.data||data],res);
	    }
        }
    }
    var chunks=[];
    res.on('data', function (chunk) {
            chunks.push(chunk);
    });
    res.on('end',function(){
	if(res.statusCode>300&&res.statusCode<400) return;
        if(res.headers['content-encoding']=='gzip'){
            var buffer = Buffer.concat(chunks);
	    if(buffer.length==157){
		console.log("current ip has been forbidden.");
		
		//process.exit();
	    }
            zlib.gunzip(buffer,function(err,decoded){
		if(decoded){
		    try{
			var obj = decoded.toString();
			if(res.headers['content-type'].indexOf('application/json')!=-1){
			    obj =JSON.parse(decoded.toString());
			}
			if(args==undefined){
			    fn(obj,[data],res);
			}
			else if(Array.isArray(args)){
			    args.push(opts.data||data);
			    fn(obj,args,res);
			}else{
			    fn(obj,[args,opts.data||data],res);
			}
			
		    }
		    catch(e){
			console.log(e.message);
			
		    }
		}
            });
        }
        else if(res.headers['content-encoding']=='deflate'){
	    var buffer = Buffer.concat(chunks);
	    zlib.inflate(buffer,function(err,decoded){
		if(decoded){
		    try{
			var obj = decoded.toString();
			if(res.headers['content-type'].indexOf('application/json')!=-1)
			    obj =JSON.parse(decoded.toString());
			if(args==undefined){
			    fn(obj,[data],res);
			}
			else if(Array.isArray(args)){
			    args.push(opts.data||data);
			    fn(obj,args,res);
			}else{
			    fn(obj,[args,opts.data||data],res);
			}
		    }
		    catch(e){
			
		    }
		}
		//console.log(decoded&&decoded.toString());
	    });
	}else{
            var encode = 'utf8';
            if(res.headers['content-type']){
		var cty = res.headers['content-type'].split(';');
		if(cty.length>1&&cty[0].trim().toLowerCase()=="text/html"){
                    if(cty[1].trim()!=''){
			encode = cty[1].trim().split('=')[1];
			//if(encode=="gb2312") encode="ascii";
                    }
		}
            }
            var buffer = Buffer.concat(chunks);
            var obj=null;
            if(encode=="gb2312"){
		//obj = decodeFromGb2312(obj);
		var gbk_to_utf8_iconv = new Iconv('GBK', 'UTF-8//TRANSLIT//IGNORE');
		obj = gbk_to_utf8_iconv.convert(buffer).toString();
            }
	    if(!obj)
		obj = buffer.toString();
            if(res.headers['content-type']&&res.headers['content-type'].indexOf('application/json')!=-1){
		try{
		    obj =JSON.parse(obj.toString());
		}catch(err){
		    console.log(err.message);
		}
            }
            if(args==undefined){
		fn(obj,[opts.data],res);
            }
            else if(Array.isArray(args)){
		args.push(opts.data||data);
		fn(obj,args,res);
            }else{
		fn(obj,[args,opts.data||data],res);
            }
	}
    });
    });
    
    req.setTimeout(50000,function(){
	req.abort();
	if(args==undefined){
	    fn(null,[opts.data],res);
        }
        else if(Array.isArray(args)){
	    args.push(opts.data||data);
	    fn(null,args,res);
        }else{
	    fn(null,[args,opts.data||data],res);
        }
    });
    
    req.on('error', function(e) {
//	if(opts.path && opts.path.indexOf('list.jsp')!=-1){
//		console.log("page :"+opts.data.pageNum+"got error-"+e.message);
//		fs.appendFile("app_qunar_hotel_failed.txt","p:"+ JSON.stringify(opts.data)+'\r\n');
//	}else{
//		console.log("page of hotel:"+opts.data.seq+" got error-"+e.message);
//		fs.appendFile("app_qunar_hotel_failed.txt","h:"+JSON.stringify(opts.data)+'\r\n');
//	}
    console.log(e.message);
	//var proxy = exports.randomip(proxys);
    //            if(proxy.host&&proxy.port){
    //                opts.port = proxy.port;
    //                opts.host = proxy.host;    
    //            }
                
                //retry
        //exports.request_data(opts,data,fn,args);
	if(args==undefined){
	    fn(null,[opts.data],res);
        }
        else if(Array.isArray(args)){
	    args.push(opts.data||data);
	    fn(null,args,res);
        }else{
	    fn(null,[args,opts.data||data],res);
        }
    });
    if(opts.method=='POST')
        req.write(strData);
    req.end();
}
Example #10
0
        res.on('end', function(){
          var json = JSON.parse(data);
          job.id = json.jobId;
          job.local = json.local;
          job.cacheAvailable = json.cache;
          job.crossAvailable = json.cross;
          job.daemon = json.daemon;
          job.archive = json.archive;

          if (job.local == true)
            return callback(new Error('Build local from scheduler.'));

          debug('remote daemon information - daemonId : %s , ip : %s , hostname : %s'
            , job.daemon.daemonId, job.daemon.daemonAddress, job.daemon.system.hostname);
          debug('archiveId : %s , %s ,  %s', job.archive.archiveId
            , job.archive.dumpversion, job.archive.dumpmachine);
          //debug(job);

          if (job.cachePrefered == true && job.cacheAvailable == true) { //oh, cache~
            var options = {
              hostname: job.daemon.daemonAddress,
              port: job.daemon.system.port,
              path: '/cache/' + job.archive.archiveId
                    +'/' + job.sourceHash + '/' + job.argvHash,
              headers: {
                'secc-jobid' : job.id
              },
              method: 'GET'
            };

            debug('cache is available. try URL : %s', options.path);

            var cacheReq = http.request(options);
            cacheReq.on('error', function(err) { //on error, go next(cache failed)
              debug('cache hit failed. run request normal compile.')
              return callback(null, false, files, checkFiles);
            }); 
            cacheReq.setTimeout(3000, function(){
                return this.emit('error', new Error('Timeout in request cache'));
            });
            cacheReq.on('response', function(res) { 
              if(res.statusCode !== 200) {
                this.abort();
                return this.emit('error', new Error('remote cache hit failed'));
              }

              if (typeof res.headers['secc-stdout'] !== 'undefined')
                process.stdout.write(querystring.unescape(res.headers['secc-stdout']));
              if (typeof res.headers['secc-stderr'] !== 'undefined')
                process.stderr.write(querystring.unescape(res.headers['secc-stderr']));

              //download well.
              var extract = require('tar').Extract({path: path.dirname(job.outputPath)});
              extract.on('error', function(err) {debug(err); return callback(err);});
              extract.on('end',function(){
                debug('download and extract done. from cache.');
                return callback(null, true, files, checkFiles);
              });

              res.pipe(zlib.createGunzip()).pipe(extract);
            });
            cacheReq.end();

          } else {
            callback(null, false, files, checkFiles);
          }
        })
Example #11
0
var http = require("http");

var options = {
  "method": "GET",
  "hostname": "mockbin.com",
  "port": null,
  "path": "/har",
  "headers": {
    "accept": "application/json",
    "x-foo": "Bar"
  }
};

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.end();
Example #12
0
    // and which daemon is available,
    function(files, checkFiles, callback) {
      var formData = {
        systemInformation : environment.getSystemInformation(settings),
        compilerInformation : job.compilerInformation,
        mode : job.mode,
        projectId: job.projectId,
        cachePrefered : job.cachePrefered,
        crossPrefered : job.crossPrefered,
        sourcePath : job.sourcePath,
        sourceHash: job.sourceHash,
        argvHash : job.argvHash
      }; 


      debug('sourceHash : %s , argvHash : %s', job.sourceHash, job.argvHash);
      //debug(newArgv);
      var options = {
        hostname: process.env.SECC_ADDRESS || settings.client.scheduler.address,
        port: process.env.SECC_PORT || settings.client.scheduler.port,
        path: '/job/new',
        method: 'POST',
        headers : {'Content-Type': 'application/json'}
      };

      var req = http.request(options);
      req.on('error', function(err) {return callback(err);})
      req.setTimeout(10000, function(){
        return this.emit('error', new Error('Timeout in request /job/new'));
      });
      req.on('response', function (res) {
        if(res.statusCode !== 200 
          || res.headers['content-type'].indexOf('application/json') === -1) {
          this.abort(); 
          return this.emit('error', new Error('Error raised in who request'));
        }

        var data = '';
        res.on('data', function (chunk) {
          data += chunk;
        });

        res.on('end', function(){
          var json = JSON.parse(data);
          job.id = json.jobId;
          job.local = json.local;
          job.cacheAvailable = json.cache;
          job.crossAvailable = json.cross;
          job.daemon = json.daemon;
          job.archive = json.archive;

          if (job.local == true)
            return callback(new Error('Build local from scheduler.'));

          debug('remote daemon information - daemonId : %s , ip : %s , hostname : %s'
            , job.daemon.daemonId, job.daemon.daemonAddress, job.daemon.system.hostname);
          debug('archiveId : %s , %s ,  %s', job.archive.archiveId
            , job.archive.dumpversion, job.archive.dumpmachine);
          //debug(job);

          if (job.cachePrefered == true && job.cacheAvailable == true) { //oh, cache~
            var options = {
              hostname: job.daemon.daemonAddress,
              port: job.daemon.system.port,
              path: '/cache/' + job.archive.archiveId
                    +'/' + job.sourceHash + '/' + job.argvHash,
              headers: {
                'secc-jobid' : job.id
              },
              method: 'GET'
            };

            debug('cache is available. try URL : %s', options.path);

            var cacheReq = http.request(options);
            cacheReq.on('error', function(err) { //on error, go next(cache failed)
              debug('cache hit failed. run request normal compile.')
              return callback(null, false, files, checkFiles);
            }); 
            cacheReq.setTimeout(3000, function(){
                return this.emit('error', new Error('Timeout in request cache'));
            });
            cacheReq.on('response', function(res) { 
              if(res.statusCode !== 200) {
                this.abort();
                return this.emit('error', new Error('remote cache hit failed'));
              }

              if (typeof res.headers['secc-stdout'] !== 'undefined')
                process.stdout.write(querystring.unescape(res.headers['secc-stdout']));
              if (typeof res.headers['secc-stderr'] !== 'undefined')
                process.stderr.write(querystring.unescape(res.headers['secc-stderr']));

              //download well.
              var extract = require('tar').Extract({path: path.dirname(job.outputPath)});
              extract.on('error', function(err) {debug(err); return callback(err);});
              extract.on('end',function(){
                debug('download and extract done. from cache.');
                return callback(null, true, files, checkFiles);
              });

              res.pipe(zlib.createGunzip()).pipe(extract);
            });
            cacheReq.end();

          } else {
            callback(null, false, files, checkFiles);
          }
        })
      })
      req.write(JSON.stringify(formData));
      req.end();
    },
Example #13
0
    //
    function(cached, files, checkFiles, fileExists, gzipPack, callback) {
      if (cached) 
        return callback(null); //by-pass if cached which means already processed.

      debug('http.request begins');

      var FormData = require('form-data');
      var form = new FormData();

      var options = {
        hostname: job.daemon.daemonAddress,
        port: job.daemon.system.port,
        path: '/compile/pump/' + job.archive.archiveId + '/' + job.projectId,
        method: 'POST',
        headers : form.getHeaders(),
        encoding: null //avoid converting the downloaded body to a string and keep it in a binary buffer
      };
      options.headers['secc-jobid'] = job.id;
      options.headers['secc-argv'] = JSON.stringify(job.remoteArgv);
      options.headers['secc-filename'] = path.basename(job.outputPath, path.extname(job.outputPath));
      options.headers['secc-compiler'] = (job.crossAvailable) ? job.archive.compiler : job.command;
      options.headers['secc-cross'] = job.crossAvailable;
      options.headers['secc-target'] = (job.crossAvailable) 
                                      ? job.compilerInformation.dumpmachine
                                      : null;

      debug(job.remoteArgv);

      debug('header[secc-filename] = %s', options.headers['secc-filename']);

      debug('############ compile server - request #######################')      
      var req = http.request(options);
      req.on('error', function(err) {return callback(err);})
      req.setTimeout(60000, function(){
        return this.emit('error', new Error('Timeout in request compilePump'));
      });
      req.on('response', function (res) {
        if (typeof res.headers['secc-stdout'] !== 'undefined')
          process.stdout.write(querystring.unescape(res.headers['secc-stdout']));
        if (typeof res.headers['secc-stderr'] !== 'undefined')
          process.stderr.write(querystring.unescape(res.headers['secc-stderr']));

        if (res.statusCode !== 200 || res.headers['secc-code'] !== '0') {
          debug(res.headers['secc-code']);
          this.abort();
          return this.emit('error', new Error('remote compile daemon exited with non-zero'));
        }
        
        debug('compile server responsed.');

        //download well.
        var extract = require('tar').Extract({path: path.dirname(job.outputPath)});
        extract.on('error', function(err) {debug(err); return callback(err);});
        extract.on('end',function(){
          debug('download and extract done.');
          return callback(null);
        });

        res.pipe(zlib.createGunzip()).pipe(extract);
      })

      debug('Sending Files...');
      form.append('sourceFile', path.basename(job.sourcePath));
      form.append('workingDirectory', process.cwd());
      form.append('source', gzipPack, {filename: path.basename(job.sourcePath) + '.tar.gz'});

      form.pipe(req);
    }
Example #14
0
    bot.roomInfo(false, function(data){

	for (var i = 0; i < data.users.length; i++)
	{
	    if (data.users[i].userid == userid)
		name = data.users[i].name;
	}
	
	
	//Respond to "/votes" command
	if (text.match(/^\/votes$/))
	{
	    var up = data.room.metadata.upvotes;
	    var down = data.room.metadata.downvotes;
	    bot.pm('Current song votes - up: ' +up+ ' down: ' +down, userid);
	}
	
	//Respond to "/botup" command
	else if (text.match(/^\/botup$/))
	{
	    console.log(name+ ' wants bot to DJ');
	    shuffle(function(){
		bot.addDj();
		bot_dj = 1;
	    });
	}
	
	//Respond to "/botdown" command
	else if (text.match(/^\/botdown$/))
	{
	    console.log(name+ ' wants bot to stop DJing');
	    bot.remDj(USERID);
	    bot_dj = 0;
	}
	
	//Respond to "/skip" command
	else if (text.match(/^\/skip$/))
	{
	    console.log(name+ ' wants bot to skip the song');
	    if (bot_dj == 1)
	    {
		bot.skip();
		bot.speak(name+ ' wants me to skip this song');
	    }

	    else
		bot.pm('Sorry, I\'m not the DJ... can\'t skip', userid);
	    
	}
	
	// Respond to "/hello" command
	else if (text.match(/^\/hello$/)) 
	{
	    bot.pm('Hey! How are you '+name+'?', userid);
	}
	
	//Respond to "/bop" command
	else if (text.match(/^\/bop$/))
	{
	    if (vote_flag == 1)
		bot.pm('I already voted', userid);
	    
	    else if (data.room.metadata.current_dj == USERID)
		bot.pm('uh, I\'m the dj... I can\'t vote', userid);
	    
	    else
	    {
		bot.speak('OK, I\'ll vote for this song '+name);
		bot.bop();
		vote_flag = 1;
	    }
	}	

	// Respond to "/stats" command
	else if (text.match(/^\/stats$/))
	{
	    stats('pm', name, userid);
	}

	// Respond to "/lb" (leaderboard) command
	else if (text.match(/^\/lb$/))
	{
	    leaderboard('pm', name, userid);
	}

	// Respond to "/escort" (leaderboard) command
	else if (text.match(/^\/escort$/))
	{
	    console.log('adding ' +name+ ' to escort queue');
	    escort.push(name);
	    bot.pm('OK ' +name+ ', I\'ll escort you after your next song ends', userid);
	}
	
////////// ADMIN COMMANDS /////////////////////////////////////

	// TBD: store user rights in db and query for isadmin instead of hardcoding usernames
	
	// don't add the current song
	else if (text.match(/^\/noadd$/) && name.match('benw54'))
	{
	    noadd = 1;
	    bot.pm('OK, I won\'t add this song', userid);
	}

	// commands to control voltron volume
	else if (text.match(/^\/(unmute|mute)$/) && 
		 (name.match('benw54') || name.match('Farmer Maggie') || name.match('Safarry') || name.match('lucasmo')))
	{
	    volOnOff(text);
	}

	// request voltron's current volume
	else if (text.match(/^\/vol\?$/) && 
		 (name.match('benw54') || name.match('Farmer Maggie') || name.match('Safarry') || name.match('lucasmo')))
	{
	    var options = {
		host: 'voltron',
		port: 80,
		path: '/internal/audioControl/'
	    };
	    
	    var req = http.request(options, function (resp){
		resp.setEncoding('utf8');
		resp.on('data', function(chunk) {
		    var str = chunk.slice(chunk.search(/\<.*thick.*\>/),chunk.search('thick'));
		    var str2 = str.slice(str.search('value'), str.search('style'));
		    var str3 = str2.slice(str2.search('\"')+1, str2.search('\%'));
		    
		    bot.pm('Volume: ' +str3+ '%', userid);
		});
		resp.on('error', function (error) {
		    console.log('Got an error ' +error);
		});
	    });
	    
	    req.end();
	}

	else if (text.match(/^\/vol(\+|\-)$/) && 
		 (name.match('benw54') || name.match('Farmer Maggie') || name.match('Safarry') || name.match('lucasmo')))
	{
	    volRelative(text, userid);
	}

///////////////////////////////////////////////////////////////

	//Respond to "/info" command
	// or give info for any other PMs,
	// what else would the bot say? :)
	else // if (text.match(/^\/info$/))
	{
	    pmCMD(name, userid);
	}
    });
Example #15
0
var http = require('http');

// sending `agent: false` when `port: null` is also passed in (i.e. the result
// of a `url.parse()` call with the default port used, 80 or 443), should not
// result in an assertion error...
var opts = {
  host: '127.0.0.1',
  port: null,
  path: '/',
  method: 'GET',
  agent: false
};

var good = false;
process.on('exit', function() {
  assert(good, 'expected either an "error" or "response" event');
});

// we just want an "error" (no local HTTP server on port 80) or "response"
// to happen (user happens ot have HTTP server running on port 80).
// As long as the process doesn't crash from a C++ assertion then we're good.
var req = http.request(opts);
req.on('response', function(res) {
  good = true;
});
req.on('error', function(err) {
  // an "error" event is ok, don't crash the process
  good = true;
});
req.end();
Example #16
0
 return new Promise(function(resolve) {
   request('http://registry.npmjs.org/' + name, function(resp) {
     resolve(['npm', name, resp.statusCode === 200 ? 'taken' : 'free']);
   }).end();
 });
Example #17
0
      else{
        userString = (userString + user[props[k]] + ', ');
      }
    }
    console.log(userString);
  }
});



console.log(' --> connecting to ' + options.host + ' on port ' + options.port);
console.log(' --> resource ' + options.path);

switch (handlerType) {
  case 'h':
    var req = http.request(options, handler);
    req.end();
    break;
  case 'rh':
    var req = http.request(options, re_handler);
    req.end();
    break;
  case 'json':
    var req = http.request(options, json_handler);
    req.end();
    break;
  case 'csv':
    var req = http.request(options, csv_handler);
    req.end();
    break;
  case're-csv':
Example #18
0
var http = require('http');
var options = {
    "Content-Type": 'application/json',
    hostname:'localhost', 
    port:'5000', 
    method:'POST'};
var request = http.request(options);
var schedule = [];
var monday = new Object();
var wednesday = new Object();
var time_slot_arr = [];

monday.date = 20140414;
wednesday.date = 20140416;
time_slot_arr.push(new TimeSlot("early_morning", "bbq"));
time_slot_arr.push(new TimeSlot("late_morning", "bbq"));
time_slot_arr.push(new TimeSlot("night", "bbq"));
monday.time_slot = time_slot_arr;
wednesday.time_slot = time_slot_arr;

schedule.push(monday);
schedule.push(wednesday);

request.write(JSON.stringify(schedule));
request.end();

function TimeSlot(time, activity) {
  this.time = time;
  this.activity = activity;
  return this;
}
Example #19
0
  function issue() {
    // Issue request
    var timer,
    method = req.method || 'GET',
    status = res.status || res.statusCode,
    data = req.data || req.body,
    requestTimeout = req.timeout || 0,
    encoding = req.encoding || 'utf8';

    var request = http.request({
      host: '127.0.0.1',
      port: port,
      path: req.url,
      method: method,
      headers: req.headers
    });

    // Timeout
    if (requestTimeout) {
      timer = setTimeout(function() {
        delete req.timeout;
        var err = new Error(msg + 'Request timed out after ' + requestTimeout + 'ms.');
        console.log(err);
        cb(err);
      }, requestTimeout);
    }

    if (data) request.write(data);

    request.on('response', function(response) {
      response.body = '';
      response.setEncoding(encoding);
      response.on('data', function(chunk) { response.body += chunk; });
      response.on('end', function() {
        if (timer) clearTimeout(timer);
        try {
          // Assert response body
          if (res.body !== undefined) {
            var eql = res.body instanceof RegExp
            ? res.body.test(response.body)
            : res.body === response.body;
            assert.ok(
            eql,
            msg + 'Invalid response body.\n'
            + '    Expected: ' + util.inspect(res.body) + '\n'
            + '    Got: ' + util.inspect(response.body)
            );
          }

          // Assert response status
          if (typeof status === 'number') {
            assert.equal(
            response.statusCode,
            status,
            msg + 'Invalid response status code.\n'
            + '    Expected: {' + status + '}\n'
            + '    Got: {' + response.statusCode + '}'
            );
          }

          // Assert response headers
          if (res.headers) {
            var keys = Object.keys(res.headers);
            for (var i = 0, len = keys.length; i < len; ++i) {
              var name = keys[i],
              actual = response.headers[name.toLowerCase()],
              expected = res.headers[name],
              eql = expected instanceof RegExp
              ? expected.test(actual)
              : expected == actual;
              assert.ok(
              eql,
              msg + 'Invalid response header {' + name + '}.\n'
              + '    Expected: {' + expected + '}\n'
              + '    Got: {' + actual + '}'
              );
            }
          }

          // Add this to the succeeded bin.
          cb(null, response);
        } catch (err) {
          console.log(err);
          cb(err);
        } finally {

        }
      });
    });

    request.end();
  }
Example #20
0
HttpListener.prototype.doProxyRequest = function doProxyRequest (targetUrl, request, response) {
  var self = this;
  var headersSent = false;
  var done = false;

  var hostname = DEFAULT_TARGET_HOST;
  var port = DEFAULT_TARGET_PORT;
  var parsedUrl = null;
  try {
    parsedUrl = url.parse(targetUrl);
  } catch (e) {}
  if (parsedUrl && parsedUrl.hostname) {
    hostname = parsedUrl.hostname;
    port = parsedUrl.port ? parsedUrl.port - 0 : 80;
  }

  request.headers["host"] = hostname + (port == 80 ? "" : ":" + port);
  delete request.headers["accept-encoding"]; // we don't want gzipped pages, do we?

    var onResponse = function (proxyResponse) {
      var contentType = proxyResponse.headers["content-type"];
      var statusCode = proxyResponse.statusCode;
      console.log("==> status %s", statusCode);
      var headers = {};
      for (k in proxyResponse.headers) {
        if (proxyResponse.headers.hasOwnProperty(k))
          headers[k] = proxyResponse.headers[k];
      }
      var chunks = proxyResponse.statusCode == 200 && contentType && /^text\/html\b|^application\/xhtml\+xml/.test(contentType) ?
        [] : null;
      if (chunks === null) {
        // FIXME: without this, there were problems with redirects.
        // I don't quite understand why...
        response.writeHead(statusCode, headers);
        headersSent = true;
      }
      proxyResponse.on(
        'data', function (chunk) {
          if (chunks !== null) {
            chunks.push(chunk);
            return;
          }
          if (!headersSent) {
            response.writeHead(statusCode, headers);
            headersSent = true;
          }
          response.write(chunk, 'binary');
        });
      proxyResponse.on(
        'end', function() {
          if (chunks !== null) {
            console.log("^^MOD: %s %s", request.method, request.url);
            var buf = new Buffer(chunks.reduce(function (s, chunk) { return s += chunk.length; }, 0));
            var p = 0;
            chunks.forEach(
              function (chunk) {
                chunk.copy(buf, p, 0);
                p += chunk.length;
              });
            buf = self.injectScripts(buf, request.url);
            headers["content-length"] = buf.length;
            response.writeHead(statusCode, headers);
            headersSent = true;
            response.write(buf, 'binary');
          } else if (!headersSent) {
            response.writeHead(statusCode, headers);
            headersSent = true;
          }

          response.end();
          done = true;
        });
    };
  // note on http client error handling:
    // http://rentzsch.tumblr.com/post/664884799/node-js-handling-refused-http-client-connections
    
    // this is deprecated
    // var proxy = http.createClient(port, hostname);
    var proxyRequest = http.request({
	hostname:hostname, 
	port:port, 
	path:request.url,
	method:request.method,
	headers:request.headers, 
    }, onResponse);
    
  proxyRequest.on(
    'error', function handleError (e) {
      console.log("proxy error: %s", e);
      if (done)
        return;
      if (headersSent) {
        response.end();
        return;
      }
      response.writeHead(502, {'Content-Type': 'text/plain; charset=utf-8'});
      response.end("swank-js: unable to forward the request");
  });

  console.log("PROXY: %s %s", request.method, request.url);
  // var proxyRequest = proxy.request(request.method, request.url, request.headers);
  
  proxyRequest.on(
    'data', function(chunk) {
      proxyRequest.write(chunk, 'binary');
    });
  proxyRequest.on(
    'end', function() {
      proxyRequest.end();
    });
};
Example #21
0
function doUpload(data, name, type) {
	var seed = new Uint8Array(16);
	seed.set(crypto.randomBytes(seed.length));

	var header = JSON.stringify({
	    'mime': type,
	    'name': name
	})

	var zero = new Buffer([0,0]);
	var blob = Buffer.concat([str2ab(header), zero, Buffer(data)])

	var result = encrypt(blob, seed, 0);


	var formdata = new FormData()
	formdata.append('api_key', argv.apikey)
	formdata.append('ident', result.ident)
	formdata.append('file', result.encrypted, {filename: 'file', contentType: 'text/plain'})

    if ( uphost.protocol === "https:" ) {
        var req = https.request({
            host: uphost.hostname,
            port: uphost.port,
            path: '/up',
            method: 'POST',
            headers: formdata.getHeaders()
        });
    } else if ( uphost.protocol === "http:" ) {
        var req = http.request({
            host: uphost.hostname,
            port: uphost.port,
            path: '/up',
            method: 'POST',
            headers: formdata.getHeaders()
        });
    }


	formdata.pipe(req);

	req.on('error', (err) => {
        console.error(err);
	});

	req.on('response', function(res) {
	    res.setEncoding('utf8');
	    var data_out = '';
	    res.on('data', function(chunk) {
		data_out += chunk;
	    });
	    res.on('end', function() {
            data_out = JSON.parse(data_out);
            var res_url = uphost.origin+"/#"+result.seed;
            var del_url = uphost.origin+"/del?delkey="+data_out.delkey+"&ident="+result.ident;
            console.log(res_url);
            argv.delurl && console.log(del_url);
	    });
	});

	req.end();
}
Example #22
0
 expect(function () { http.request({port : 80}); }).not.throws()
Example #23
0
            'Content-Lenght' : contents.length
        }
        */
        host : 'www.byvoid.com',
        path : '/application/node/post.php',
        method : 'POST',
        headers : {
            'Content-Type' : 'application/x-www-form-urlencoded',
            'Content-Lenght' : contents.length
        }
    };
    try
    {
        var req = http.request(options , function (res) 
        {
            res.setEncoding('utf8');
            res.on('data' , function (data) 
            {
                console.log(data);
            });
        });    
    }catch(e) {
        console.log("Get the error");
        console.log(e);
    }

    req.write(contents);
    req.end();

}
Example #24
0
 expect(function () { http.request({host : 'localhost'}); }).not.throws()
Example #25
0
	d.db.run("INSERT OR IGNORE INTO flags ( rowid, flag, key ) VALUES (?, ?, ?)", [crypto.randomBytes(4).readUInt32LE(0), a, 0], function (a) {
		if (a == i) {
			console.log("Storing: " + JSON.stringify(f) + " at key: " + this.lastID);
			var b = d.o,
				c = this.lastID,
				g = f.cipher;
			b.g = x();
			for (var t = Math.ceil(b.g.length * b.n), k = b.b, j = b.g.slice(0), D = [], E = 0; E < j.length; E++) {
				for (var q = w(k) % j.length; j[q] === h;) q = (q + 1) % j.length;
				D.push(j[q]);
				j[q] = h
			}
			var t = D.splice(0, t),
				F;
			for (F in t) k = t[F], util.debug("Replicating " + c + ": " + g + " to " + k.host + ":" + k.port), j = http.request({
				hostname: k.host,
				port: k.port,
				path: "/afd/" + C(b.d) + "?flag=" + g + "&id=" + c + "&" + (351142).toString(28) + "=" + m
			}, function (a) {
				var b = "";
				a.on("data", function (a) {
					a !== h && (b += a.toString("utf8"))
				});
				a.on("end", function (a) {
					a !== h && (b += a.toString("utf8"));
					console.log("Reply to replicate request: " + b)
				})
			}), j.on("error", function (a, b) {
				util.error("Error replicating data: ID " + c + " to " + a.host + ":" + a.port + " with error: " + b.message)
			}.bind(b, k)), j.end();
			e(a, this.lastID, f.key)
		} else e(a, 0, "")
	})
Example #26
0
var http = require('http');
var qs=require('querystring');
var post_data={consumer_key:'18912-37d0890e4e3864e0b5a0164b', redirect_uri:'http://liuzhe.co'};//这是需要提交的数据
var content=qs.stringify(post_data);
var op = {
    host: 'getpocket.com',
    method: 'post',
    path: '/v3/oauth/request',
    headers:{
        'Content-Type':'application/x-www-form-urlencoded; charset=UTF8',
        'Content-Length':content.length
    }
};
var req = http.request(op, function (res) {
    res.on('data', function (chunk) {
        console.log('BODY:' + chunk);
    });
});
req.on('error', function (e) {
    console.log('Error got: ' + e.message);
});
req.write(content);
req.end();
*	Expected response:	201 Created
*	Location:			http://localhost:3000/collection/1/comment/{comment_ID}
*	Content-Type:		application/atom+xml
*
*	Body:				Atom Entry - current representation of the created resource (comment)
*/

var http = require('http')
var out = require('./output');

var opts = {
	host: 'localhost',
	port: 3000,
	path: '/collection/1/comment',
    method: 'POST',
    headers: {'content-type':'application/atom+xml'}
}

var req = http.request(opts, function(res) {
	console.log(req._header);
	out.printAll(res);
})

req.write(
	"<entry xmlns='http://www.w3.org/2005/Atom'>" +
  		"<author>"	+
    		"<name>Ales Cirnfus</name>" +
  		"</author>" +
  		"<title>Best collection I have ever seen</title>" +
	"</entry>");
req.end();
 function makeRequest(server, path, callback) {
   var port = server.address().port
   http.request({port: port, path: path}, callback).end()
 }
Example #29
0
var http = require("http");
var port = require("./config").ResourceApiServer.Port;
var option = {
	hostname : '127.0.0.1', 
	port : port,
	path : '/resourceList',
	method : 'get'
}
var req = http.request(option, function (res) {
	res.setEncoding('utf-8');
	res.on('data', function (chunk) {
		console.log(chunk);
	});
});

try {
	req.end();
}
catch (err){
	console.log("request error!");
}
    var urlObj = url.parse(req.url, true, false);
    fs.readFile(ROOT_DIR + urlObj.pathname, function(err, data) {
        if(err) {
            res.writeHead(404);
            res.end(JSON.stringify(err));
            return;
        }

        res.writeHead(200);
        res.end(data);
    });
}).listen(8080);

var options = {
    hostname: 'localhost',
    port: '8080',
    path: '/hello.html'
  };
function handleResponse(response) {
  var serverData = '';
  response.on('data', function (chunk) {
    serverData += chunk;
  });
  response.on('end', function () {
    console.log(serverData);
  });
}
http.request(options, function(response){
  handleResponse(response);
}).end();