Example #1
0
var miniLoger = function (messageText, responseTime, statusCode) {
    keen.addEvent("checkSite", { "website": messageText, "time": responseTime, "statusCode": statusCode }, function (err) {
        if (err) {
            console.log("Oh no, an error writing to keen.io!");
        }
    });
};
Example #2
0
 constructor() {
   if (!config.sendUsageStatistics) return;
   this.keen = keenio.configure({ projectId: _PROJECT_ID, writeKey: _WRITE_KEY });
   this.getDefaultDataKey = cache.registerFunc(() => {
     return sysinfo.getUserHash().then((hash) => {
         return { version: config.ungitDevVersion, userHash: hash };
       });
   });
 }
Example #3
0
  var enforceScopedKey = function(req, res, next) {
    var publicScopedKey = req.query.api_key;

    try {
      var scopedParams = Keen.decryptScopedKey(config.publicKey, publicScopedKey);

      self.logger.verbose("Successfully decrypted scopedParams: %s for request: %s", JSON.stringify(scopedParams), req.url);

      // If we succesfully recognized the scope key, let's do some checks and then
      // pass this on to Keen.io

      // Ensure that the analysisType that was specified in the scoped key
      // is the same one being used in the URL.
      if (scopedParams.analysisType && path.basename(req.path) !== scopedParams.analysisType) {
        self.logger.warn("Invalid type of analysis attempted. Rejecting request.");
        return res.send(403);
      }

      // Prepare a new scoped key for Keen.io - We keep all the params in there, maybe
      // some day soon Keen.io will support filtering on them too.
      var privateScopedKey = Keen.encryptScopedKey(config.masterKey, scopedParams);
      req.query.api_key = privateScopedKey;

      // Overwrite the query parameters with the one set in the scopedKey
      _.extend(req.query, scopedParams);

      // If overwriting filters, rewrite them a-la-mode Keen.io
      if (_.has(scopedParams, 'filters')) {
        req.query.filters = JSON.stringify(req.query.filters);
      }

      // Rewrite the URL with the new query parameters
      req.url = req.path + '?' + querystring.stringify(req.query);

      next();
    }
    catch (e) {
      self.logger.warn("Unable to decrypt scoped key. Rejecting request.");
      res.send(403);
    }
  };
Example #4
0
 constructor() {
   if (!config.sendUsageStatistics) return;
   this.keen = keenio.configure({ projectId: _PROJECT_ID, writeKey: _WRITE_KEY });
   this.getDefaultData = cache((callback) => {
     async.parallel({
       userHash: sysinfo.getUserHash.bind(sysinfo),
       version: sysinfo.getUngitVersion.bind(sysinfo)
     }, (err, data) => {
       callback(err, data);
     });
   });
 }
Example #5
0
app.addRoute("/", function (req, res) {

  var url_parts = url.parse(req.url, true);
  var query = url_parts.query;
  var projectId = query.projectId;
  var writeKey = query.writeKey;
  var temperature = query.temperature;
  var msg = "";

  if (!projectId || !writeKey) {
    msg = "projectId and writeKey are required.";
    console.log(msg);
    res.end(msg);
    return;
  }

  var client = Keen.configure({
      projectId: projectId,
      writeKey: writeKey
  });

  // res.writeHead(200, { "Content-Type": "text/html" });

  if (projectId && writeKey && temperature) {

    // send single event to Keen IO
    client.addEvent("temperature", {"temperature": temperature}, function(err, result) {
        if (err) {
            msg = "Oh no, an error!";
            console.log(msg);
            res.end(msg);
        } else {
            msg = "Hooray, it worked! Saved temp: " + temperature;
            console.log(msg);
            res.end(msg);
        }
    });

  } else {
    msg = "query parameter missing!";
    console.log(msg);
    res.end(msg);
  }


});
      fs.readFile(file, 'utf8', function (err, data) {
        if (err) {
          console.log('Error: ' + err);
          return;
        }
        config = JSON.parse(data);

        // Configure Keen.io instance. Only projectId and writeKey are required to send data.
        keen = keen.configure({
            projectId: config.keen_project_id,
            writeKey: config.keen_write_key,
            readKey: config.keen_read_key,
            masterKey: config.keen_master_key
        });

        if (devMode) {
          readLocalFile();
        } else {
          readRemoteFile();
        }
      });
        function (document) {

          var frameDuration = new Date().getTime() - frameStart;
          var dur = frameDuration < 60000 ? msToSec(frameDuration) + ' seconds' : msToMin(frameDuration) + ' minutes';
          console.log('Rendered frame ' + currentFrame + ' in ' + dur + '.');

          keen.addEvent(projectName,
              {
                'currentFrame': currentFrame,
                'frameDuration': frameDuration,
                'computerName': config.computerName || 'unknown'
              }, function(err, res) {
            if (err) {
                console.log("Oh no, an error!", err);
            } else {
                console.log("Hooray, it worked!", res);
            }
          });

          totalFramesRendered++;

          if (!devMode) {
            sendComplete(frameDuration);
          } else {
            currentFrame++;
            readLocalFile();
          }

          // check to send Tweet
          if (sendTweet && !(totalFramesRendered % framesBTWTweets)) {
            createTweetStatus(frameDuration, createTweet, function() {
              if (devMode) {
                readLocalFile();
              } else {
                readRemoteFile();
              }
            });
          }
        },
var fs = require('fs'),
    xml2js = require('xml2js'),
    keen = require('keen.io');

if(process.argv.length < 6) {
    console.log("Usage: node yeah-metrics.js YOUR_KEEN_IO_API_KEY YOUR_KEEN_IO_PROJECT_ID /path/to/jshint.xml /path/to/cobertura-coverage.xml");
    process.exit();
}

var api = keen.configure({
    projectId: process.argv[3],
    writeKey: process.argv[2]
});
var parser = new xml2js.Parser();

// Go!

fs.readFile(process.argv[4], function(err, data) {
    parser.parseString(data, function (err, result) {
        var errors = 0;
        for(var i=0;i<result.checkstyle.file.length;i++) {
           if(result.checkstyle.file[i].error[0]['$'].severity !== "error") continue;
           errors++;
        }

        api.addEvent("code_style", { score: errors, language: "javascript" }, function(err, res) {
            if(err) {
                console.error("Sending data failed:" , err, res);
            } else {
                console.info("Data sent to backend.");
            }
Example #9
0
'use strict';

var keen = require('keen.io');
var appConfig = require('./appConfig');
var keen = keen.configure(appConfig.keenConfig);

var miniLoger = function (messageText, responseTime, statusCode) {
    keen.addEvent("checkSite", { "website": messageText, "time": responseTime, "statusCode": statusCode }, function (err) {
        if (err) {
            console.log("Oh no, an error writing to keen.io!");
        }
    });
};

var checkSite = function (timeOut, siteAddress, callback) {

    var unirest = require('unirest');
    var dateStart = new Date();

    unirest.get(siteAddress)
        .timeout(timeOut)
        .headers({ 'Accept': 'text/html' })
        .end(function(response) {
            var dateEnd = new Date();

            if (isNaN(response.statusCode)) {
                response.statusCode = 0;
            }
            callback(response, siteAddress, dateEnd - dateStart);
        });
};
Example #10
0
var Keen = require('keen.io');
var tessel = require('tessel');
// attach the accelerometer to port A
var accel = require('accel-mma84').use(tessel.port['A']);
var count = 0;

console.log("setting up keen...");
// set up keen with your APIs here
var keen = Keen.configure({
    projectId: "###",
    writeKey: "###",
    readKey: "###"
});

var dataArray = [];
accel.on('ready', function () {
  console.log("Accelerometer is ready!");
  // as we get data push it into an array
  accel.on('data', function (xyz) {
    dataArray.push(xyz);
  });
});

// every second send up all the accelerometer data
setTimeout(function sendData(){
  keen.addEvent("accel", {data: dataArray}, function(err){
    if (err) throw err;

    console.log("Added event #"+count, "data: ", dataArray);
    count++;
    dataArray = [];
Example #11
0
var tessel = require('tessel');
var config = require('./config.json'); //with path

var climatelib = require('climate-si7020');
var climate = climatelib.use(tessel.port[config.sensor.port]);

var Keen = require('keen.io');
var keen = Keen.configure({
    projectId: config.keen.projectId,
    writeKey: config.keen.writeKey,
});

var previousTemp = 0;

climate.on('ready', function(){
  setInterval(function(){
    climate.readHumidity(function(err, humid){
      climate.readTemperature(config.sensor.unit, function(err, temp){
        if( Math.abs(previousTemp - temp ) > config.sensor.delta ) { // Only send to cloud if temp has changed more than delta.
          previousTemp = temp;
          sendToCloud(temp, humid);
        }
      });
    });
  }, config.sensor.interval);
});

climate.on('error', function(err) {
  console.log('error connecting module', err);
});
Example #12
0
var _ = require('lodash');
var Keen = require('keen.io');

var client;
var enabled = !!process.env.KEEN_PROJECT_ID;
var doLog = process.env.LOG_ANALYTICS === 'true';

if (enabled) {
  client = Keen.configure({
    projectId: process.env.KEEN_PROJECT_ID,
    writeKey: process.env.KEEN_WRITE_KEY
  });
}

var events = {
  install: function (ctx) {},
  uninstall: function (ctx) {},
  room_enter: function (ctx) {},
  room_exit: function (ctx) {},
  room_message: function (ctx) { return {match: ctx.match && ctx.match[0]}; },
  room_notification: function (ctx) {},
  room_topic_change: function (ctx) {}
};

exports.track = function (addon) {
  var tracker = {
    capture: function (event, data) {
      data = _.extend({
        addon: typeof addon.name === 'string' ? addon.name : 'default'
      }, data);
      if (doLog) {
Example #13
0
       {
		   host      : nconf.get('influxdb:host'),
		   port      : parseInt(nconf.get('influxdb:port')),
		   username  : nconf.get('influxdb:user'),
		   password  : nconf.get('influxdb:password'),
		   database  : nconf.get('influxdb:database'),
		   maxRetries: parseInt(nconf.get('influxdb:retries'))
       }
   );
   
var twilioClient = new twilio.RestClient(nconf.get('twilio:AccountSID'), nconf.get('twilio:AuthToken'));

var mandrillClient = new mandrill.Mandrill(nconf.get('mandrill:APIKey'));

var keenIOClient = keen_io.configure({
    projectId: nconf.get('keenio:project_id'),
    writeKey: nconf.get('keenio:write_key')
});
	
var previousTemp = -273.15;
var currentTemp =  -273.15;
var TEMP_DIFF_TO_TRIGGER_ARCHIVAL = parseFloat (nconf.get('app:tempdiff'));
var TEMP_TO_ACTIVATE_WARNING_BULB = parseFloat(nconf.get('app:temp_activate_bulb'));
var BULB_SENSOR_ID = nconf.get('app:temp_sensor_id');
var BULB_TOPIC = nconf.get('app:bulb_topic');
 
var NUM_OF_HIGH_TEMP_READINGS_TO_ACTIVATE_WARN = parseInt (nconf.get('app:number_of_readings_that_activate_warning')); //naming stuff is hard :)
var currentNumOfWarnReadings = 0;

var NUMBER_OF_BULB_CONTROL_MESSAGES= parseInt (nconf.get('app:number_of_bulb_control_messages'));

var NUM_OF_WARNING_SMS_MESSAGES = parseInt (nconf.get('app:number_of_warning_sms_messages'));
'use strict';
var util = require('util');
var BBPromise = require('bluebird');
var BaseStepLogEvent = require('broker/lib/event_types/step_log_event');
var Keen = require('keen.io');
var config = require('config');
var client = BBPromise.promisifyAll(Keen.configure(config.get('Hoist.keenio')));
var EventLogEvent = function (brokeredMessageOrProperties) {
  BaseStepLogEvent.call(this, brokeredMessageOrProperties);
};



util.inherits(EventLogEvent, BaseStepLogEvent);
console.log(BaseStepLogEvent.QueueName);

EventLogEvent.QueueName = BaseStepLogEvent.QueueName;



EventLogEvent.prototype.process = function (callback) {
  var self = this;
  return BBPromise.try(function () {
    return client.addEventAsync('hoist connect step',self.toJSON());
  }).bind(self)
  .then(function(){
    console.log('sent to keen');
    self.emit('done');
  }).nodeify(callback);
};
module.exports = EventLogEvent;
Example #15
0
var passport = require('passport');
var MeetupStrategy = require('passport-meetup').Strategy;
var http = require('http');
var path = require('path');

var MEETUP_KEY = process.env.MEETUP_KEY || console.log("no MEETUP_KEY!");
var MEETUP_SECRET = process.env.MEETUP_SECRET || console.log("no MEETUP_SECRET");

var logfmt = require("logfmt");
var keenReadKey = process.env.KEEN_READ_KEY
var keenWriteKey = process.env.KEEN_WRITE_KEY
var keenProjID = process.env.KEEN_PROJ_ID
var keenClass = require('keen.io');
var keen = keenClass.configure({
    projectId: keenProjID,
    writeKey: keenWriteKey,
    readKey: keenReadKey
});
keen.addEvent("startup");
var keenCountQuery = new keenClass.Query("count", {
  event_collection: "visit_ann_url",
  group_by: "url",
  timeframe: "this_7_days",
  timezone: "-14400"
});
var keenCount;
function keenCountFn() {
  keen.run(keenCountQuery, function(err, response) {
    if (err) return console.log(err);
    keenCount = {};
    var rrLen = response.result.length;
Example #16
0
var express = require('express');
var router = express.Router();
var Keen = require('keen.io');

var keen = Keen.configure({
    projectId: "<project_id>",
    writeKey: "<write_key>",
    readKey: "<read_key>",
    masterKey: "<master_key>"
});


/* GET home page. */
router.get('/', function(req, res) {
	// send back response
  res.render('index', { title: 'Express' });
});

router.get('/expenses', function(req, res) {

	var count = new Keen.Query("count", {
  event_collection: "expenses",
  group_by: "expense",
  timeframe: "this_7_days"
	});

	var total = count || 300;
  res.render('expenses', { total: total });
	// send back esponse for last 7 days using keen
});
Example #17
0
	initKeen: function(){
		keenClient = Keen.configure({
		    projectId: process.env.KEEN_PROJECT_ID,
		    writeKey: process.env.KEEN_WRITE_KEY
		});
	}
Example #18
0
var Keen = require('keen.io')
var tessel = require('tessel')
var gpsLib = require('gps-a2235h')
var keenConfig = require('./config/keenConfig')

// var portToUse = 'C'
//
// if (!tessel.port[portToUse]) {
//   portToUse = 'A'
// }

// var gps = gpsLib.use(tessel.port['A'])

// Configure instance. Only projectId and writeKey are required to send data.
var client = Keen.configure(keenConfig)

// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/

// BLUETOOTH

/*
This basic example scans for Bluetooth low energy
peripherals and prints out details when found
*/

// var noble = require('noble')
// var macs = []
// // USB modules don't have to be explicitly connected
//
// // Wait for the module to report that it is powered up first
'use strict';

var keenIO		= require('keen.io');
var flat		= require('flat');
var csv			= require('csv');
var csvUtils	= require('./lib/csv-utils');

var keen = keenIO.configure({
	projectId: process.env['KEEN_PROJECT_ID'],
	readKey: process.env['KEEN_READ_KEY']
});

// The latest 100 events we've logged
module.exports = function(req, res) {

	var latest = new keenIO.Query('extraction', {
		timeframe: req.query.timeframe || 'this_2_days',
		event_collection: req.query.event_collection || 'dwell',
		latest: req.query.limit || 1000
		});

	keen.run(latest, function(err, response) {

		if (err) {
			res.json(err);
			return;
		}

		var flattened = response.result.map(function(event) {
			return flat(event);
		});
Example #20
0
File: keen.js Project: applico/Pour
var Keen = require('keen.io');

var client = Keen.configure({
    projectId: "YOUR PROJECT ID",
    writeKey: "YOUR WRITE KEY",
    readKey: "YOUR READ KEY",
    masterKey: "YOUR MASTER KEY"
	});

module.exports = {
  "client" : client,
  "Keen": Keen
};