<commit_before>var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url");

var Firebase = require("firebase")
var WebSocketServer = require('websocket').server;
var reqobj = require("request")

var fb = new Firebase("improvplusplus.firebaseIO.com");

var server = my_http.createServer(function(request,response){

}).listen(3000,'0.0.0.0');

wsServer = new WebSocketServer({
    httpServer: server
});

var history = [];
var clients = [];

wsServer.on('request', function(request) {
    var connection = request.accept(null, request.origin);
    var index = clients.push(connection) - 1;
    var username = false;
    var result = false;

    connection.on('message', function(message) {
        if(message.type === 'utf8') {
            var obj = message.utf8Data;
            var json_msg = JSON.parse(obj);
            username = json_msg.username;

	    var num_msgs = 0;

	    //get number of messages
	    fb.child("num_msgs").on("value", function(snapshot) {
		num_msgs = snapshot.val();
	    },
	    function (errorObject) {
		fb.child("num_msgs").set(0);
	    });

	    var fb_messages = fb.child("messages");
	    fb_messages.child(num_msgs).set({
		obj
	    });
	    console.log(json_msg);
	    num_msgs++;
	    fb.child("num_msgs").set(num_msgs);
	    console.log(num_msgs);

            for(var i = 0; i < clients.length; i++) {
                clients[i].sendUTF(obj);
            }
        }
    });

    connection.on('close', function(reasonCode, description) {
        for(var i = 0; i < clients.length; i++) {
            clients[i].sendUTF(JSON.stringify({username: username, message: 'User disconnected.'}));
        }
    });
});
<commit_msg>fixed num_msgs scope to keep persistent count instead of resetting<commit_after>var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url");

var Firebase = require("firebase")
var WebSocketServer = require('websocket').server;
var reqobj = require("request")

var fb = new Firebase("improvplusplus.firebaseIO.com");

var server = my_http.createServer(function(request,response){

}).listen(3000,'0.0.0.0');

wsServer = new WebSocketServer({
    httpServer: server
});

var history = [];
var clients = [];
var num_msgs = 0;

wsServer.on('request', function(request) {
    var connection = request.accept(null, request.origin);
    var index = clients.push(connection) - 1;
    var username = false;
    var result = false;

    connection.on('message', function(message) {
        if(message.type === 'utf8') {
            var obj = message.utf8Data;
            var json_msg = JSON.parse(obj);
            username = json_msg.username;

	    //get number of messages
	    fb.child("num_msgs").on("value", function(snapshot) {
		num_msgs = snapshot.val();
	    },
	    function (errorObject) {
		fb.child("num_msgs").set(0);
	    });

	    var fb_messages = fb.child("messages");
	    fb_messages.child(num_msgs).set({
		obj
	    });

	    //log console because my dumbass computer doesn't do CSS
	    console.log(json_msg);

	    //record number of messages locally and on database
	    num_msgs++;
	    fb.child("num_msgs").set(num_msgs);
	    console.log(num_msgs);

            for(var i = 0; i < clients.length; i++) {
                clients[i].sendUTF(obj);
            }
        }
    });

    connection.on('close', function(reasonCode, description) {
        for(var i = 0; i < clients.length; i++) {
            clients[i].sendUTF(JSON.stringify({username: username, message: 'User disconnected.'}));
        }
    });
});
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const persist = require('./persist')
const jira = require('./jira')
var jiraConfig = {}

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

persist.getCreds()
  .then(jiravals => {
    jiraConfig = jiravals
  // console.log('jiravals = ' + jiravals.jirau + ' ' + jiravals.jirap)
  })
  .catch(function (err) {
    console.error('Promise Rejected: ' + err)
  })

// *********************************************
  // Setup different handlers for messages
  // *********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// Respond to a JIRA issue (e.g. PX-1234)
slapp.message(/px-(\d+)/i, ['mention', 'direct_message', 'ambient'], (msg) => {
  var text = (msg.body.event && msg.body.event.text) || ''
  var pattern = /px-(\d+)/ig
  var match = text.match(pattern)

  // there may be multiple issues in the text
  for (var i = 0; i < match.length; i++) {
    const issueKey = match[i].toUpperCase()
    jira.getIssue(jiraConfig.jiraurl, jiraConfig.jirau, jiraConfig.jirap, issueKey).then(jiraIssue => {
      var avatarUrl = null
      if (jiraIssue.fields.assignee != null) {
        avatarUrl = jiraIssue.fields.assignee.avatarUrls['24x24']
      }
      var color = 'good'
      switch (jiraIssue.fields.issuetype.name) {
        case 'Bug':
        case 'Bug-task':
          switch (jiraIssue.fields.priority.name) {
            case 'Open':
              color = 'good'
              break
            case 'High':
              color = 'danger'
              break
            case 'Medium':
              color = 'warning'
              break
          }
          break
        case 'Story':
          color = '#63BA3C'
          break
        case 'Task':
        case 'Sub-task':
          color = '#4BADE8'
          break
        case 'Epic':
          color = '#904EE2'
          break
      }
      msg.say({
        text: '',
        // text: 'Proximus JIRA issue ' + issueKey,
        attachments: [{
          text: '',
          title: issueKey + ': ' + jiraIssue.fields.summary,
          thumb_url: avatarUrl,
          title_link: 'https://inmotionnow.atlassian.net/browse/' + issueKey,
          mrkdwn_in: ['fields'],
          'fields': [
            {
              'title': 'Priority',
              'value': '`' + jiraIssue.fields.priority.name + '`',
              'short': true
            },
            {
              'title': 'Assignee',
              'value': jiraIssue.fields.assignee === null ? 'Unassigned' : jiraIssue.fields.assignee.displayName,
              'short': true
            },
            {
              'title': 'Status',
              'value': '`' + jiraIssue.fields.status.name + '`',
              'short': true
            },
            {
              'title': 'Type',
              'value': jiraIssue.fields.issuetype.name,
              'short': true
            }

          ],
          color: color
        }]
      })
    }).catch((err) => {
      console.log(err)
      msg.say({
        text: "Sorry, couldn't find " + issueKey + ' :cry:'
      })
    })
  }
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
  // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>icon size<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const persist = require('./persist')
const jira = require('./jira')
var jiraConfig = {}

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

persist.getCreds()
  .then(jiravals => {
    jiraConfig = jiravals
  // console.log('jiravals = ' + jiravals.jirau + ' ' + jiravals.jirap)
  })
  .catch(function (err) {
    console.error('Promise Rejected: ' + err)
  })

// *********************************************
  // Setup different handlers for messages
  // *********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// Respond to a JIRA issue (e.g. PX-1234)
slapp.message(/px-(\d+)/i, ['mention', 'direct_message', 'ambient'], (msg) => {
  var text = (msg.body.event && msg.body.event.text) || ''
  var pattern = /px-(\d+)/ig
  var match = text.match(pattern)

  // there may be multiple issues in the text
  for (var i = 0; i < match.length; i++) {
    const issueKey = match[i].toUpperCase()
    jira.getIssue(jiraConfig.jiraurl, jiraConfig.jirau, jiraConfig.jirap, issueKey).then(jiraIssue => {
      var avatarUrl = null
      if (jiraIssue.fields.assignee != null) {
        avatarUrl = jiraIssue.fields.assignee.avatarUrls['32x32']
      }
      var color = 'good'
      switch (jiraIssue.fields.issuetype.name) {
        case 'Bug':
        case 'Bug-task':
          switch (jiraIssue.fields.priority.name) {
            case 'Open':
              color = 'good'
              break
            case 'High':
              color = 'danger'
              break
            case 'Medium':
              color = 'warning'
              break
          }
          break
        case 'Story':
          color = '#63BA3C'
          break
        case 'Task':
        case 'Sub-task':
          color = '#4BADE8'
          break
        case 'Epic':
          color = '#904EE2'
          break
      }
      msg.say({
        text: '',
        // text: 'Proximus JIRA issue ' + issueKey,
        attachments: [{
          text: '',
          title: issueKey + ': ' + jiraIssue.fields.summary,
          thumb_url: avatarUrl,
          title_link: 'https://inmotionnow.atlassian.net/browse/' + issueKey,
          mrkdwn_in: ['fields'],
          'fields': [
            {
              'title': 'Priority',
              'value': '`' + jiraIssue.fields.priority.name + '`',
              'short': true
            },
            {
              'title': 'Assignee',
              'value': jiraIssue.fields.assignee === null ? 'Unassigned' : jiraIssue.fields.assignee.displayName,
              'short': true
            },
            {
              'title': 'Status',
              'value': '`' + jiraIssue.fields.status.name + '`',
              'short': true
            },
            {
              'title': 'Type',
              'value': jiraIssue.fields.issuetype.name,
              'short': true
            }

          ],
          color: color
        }]
      })
    }).catch((err) => {
      console.log(err)
      msg.say({
        text: "Sorry, couldn't find " + issueKey + ' :cry:'
      })
    })
  }
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
  // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>#!/usr/bin/env node

var _ = require('underscore')._;
var async = require('async');
var commander = require('commander');
var express = require('express')
var fs = require('fs');
var https = require('https');
var log = require('winston');
var path = require('path');
var spawn = require('child_process').spawn;
var uuid = require('node-uuid');
var mkdirp = require('mkdirp');

// Set up configuration

commander
.option('-p, --port <port>', 'set the listen port (9443)', 9443)
.option('-s, --store <store>', 'set the store directory (~/mole-store)', path.join(process.env['HOME'], 'mole-store'))
.option('-d, --debug', 'show debug output', false)
.parse(process.argv);

// Set up the storage directory and move there

mkdirp.sync(path.join(commander.store, 'crt'));
mkdirp.sync(path.join(commander.store, 'data'));
mkdirp.sync(path.join(commander.store, 'server'));
process.chdir(commander.store);

// Set up logging

log.setLevels(log.config.syslog.levels);
log.remove(log.transports.Console);
log.add(log.transports.Console, {level: commander.debug ? 'debug' : 'info', timestamp: true});

// Set up users

var userStore = require('./lib/users');
var userFile = path.join(commander.sore, 'users.json');
log.debug('Using users file', userFile);
var users = new userStore(userFile);

var caCertFile = path.join(commander.store, 'ca-cert.pem');
var serverCertFile = path.join(commander.store, 'crt', 'server-cert.pem');
var serverKeyFile = path.join(commander.store, 'crt', 'server-key.pem');

log.debug('Checking for existing certificates');
if (!path.existsSync(caCertFile)) {
    spawn(path.join(__dirname, 'gen-ca.exp')).on('exit', function (code) {
        spawn(path.join(__dirname, 'gen-user.exp'), [ 'server' ]).on('exit', function (code) {
            log.info('Created CA & server certificates');
            startApp();
        });
    });
} else {
    startApp();
}

function startApp() {
    log.debug('Create HTTP server');
    var app = express.createServer({
        ca: [ fs.readFileSync(caCertFile) ],
        key: fs.readFileSync(serverKeyFile),
        cert: fs.readFileSync(serverCertFile),
        requestCert: true,
    });

    app.get(/\/register\/([0-9a-f-]+)$/, register);
    app.post('/newtoken', newtoken);
    app.post(/\/users\/([a-z0-9_-]+)$/, newuser);
    app.del(/\/users\/([a-z0-9_-]+)$/, deluser);
    app.get('/store', listfiles);
    app.put(/\/store\/([0-9a-z_.-]+)$/, putfile);
    app.get(/\/store\/([0-9a-z_.-]+)$/, getfile);
    app.listen(commander.port);
    log.info('Server listening on port ' + commander.port);
}

function createUserCert(name, callback) {
    var openssl = spawn(path.join(__dirname, 'gen-user.exp'), [ name ]);
    var fingerprint;

    function recv(data) {
        var s = data.toString('utf-8').trim();
        if (s.match(/^[0-9A-F:]+$/)) {
            fingerprint = s;
        } else {
            log.warning(data);
        }
    }

    openssl.stdout.on('data', recv);
    openssl.stderr.on('data', recv);

    openssl.on('exit', function (code) {
        callback(fingerprint);
    });
}

function authenticate(req) {
    if (!req.client.authorized) {
        log.debug('Client not authorized');
        return null;
    }

    var cert = req.connection.getPeerCertificate();
    var username = cert.subject.CN;

    var user = users.get(username);
    if (!user) {
        log.warning('Certificate claimed username "' + username + '" which does not exist');
        return null;
    }

    if (user.fingerprint !== cert.fingerprint) {
        log.warning('Certificate presented for "' + username + '" does not match stored fingerprint');
        return null;
    }

    log.info('Certificate authentication for ' + username + ' succeeded');
    return user;
}

function createUser(name, admin, callback) {
    var user = { created: Date.now(), token: uuid.v4() };

    createUserCert(name, function (fingerprint) {
        user.fingerprint = fingerprint;
        user.admin = !!admin;
        users.set(name, user);
        callback(user);
    });
}

function register(req, res){
    var token = req.params[0];
    var found = false;

    log.debug('GET /register/' + token);
    _.each(users.all(), function (user) {
        if (!found) {
            var name = user.name;
            var ud = user.data;
            if (ud.token === token) {
                found = true;
                var cert = fs.readFileSync('crt/' + name + '-cert.pem', 'utf-8');
                var key = fs.readFileSync('crt/' + name + '-key.pem', 'utf-8');
                var ca = fs.readFileSync(path.join(__dirname, 'ca-cert.pem'), 'utf-8');
                delete ud.token;
                ud.registered = Date.now();
                users.save();

                res.json({ cert: cert, key: key, ca: ca });
            }
        }
    });

    if (!found) {
        res.send(404);
        res.end();
    }
}

function newtoken(req, res){
    log.debug('POST /newtoken');
    var user = authenticate(req);
    if (user) {
        user.token = uuid.v4();
        users.save();
        res.json({ token: user.token });
    } else {
        res.send(403);
        res.end();
    };
}

// Create a new user (or reset certificate and token for an existing one).

function newuser(req, res){
    var username = req.params[0];
    log.debug('POST /users/' + username);
    var user = authenticate(req, users);
    if (users.all().length === 0 || user && user.admin) {
        var newUserAdmin = users.all().length == 0;
        createUser(username, newUserAdmin, function (u) {
            res.send(JSON.stringify(u));
        });
    } else {
        res.send(403);
        res.end();
    }
}

// Delete a user

function deluser(req, res){
    var username = req.params[0];
    log.debug('DELETE /users/' + username);
    var user = authenticate(req, users);
    if (user && user.admin) {
        if (users.get(username)) {
            users.del(username);
            users.save();
        } else {
            res.send(404);
        }
    } else {
        res.send(403);
    }
    res.end();
}

// List the files in storage.

function listfiles(req, res) {
    log.debug('GET /store');
    function stat(fname, callback) {
        fs.stat(path.join('data', fname), function (err, res) {
            if (err) {
                callback(err);
            } else {
                callback(null, { name: fname, mtime: res.mtime.getTime() });
            }
        });
    }

    var user = authenticate(req);
    if (user) {
        fs.readdir(path.join(commander.store, 'data'), function (err, files) {
            async.map(files, stat, function (err, files) {
                res.json(files);
            });
        });
    } else {
        res.send(403);
        res.end();
    }
}

// Add a file to storage.

function putfile(req, res) {
    var file = req.params[0];
    log.debug('PUT /store/' + file);
    var user = authenticate(req);
    if (user) {
        var buffer = '';
        req.setEncoding('utf-8');
        req.on('data', function (chunk) {
            buffer += chunk;
        });
        req.on('end', function () {
            fs.writeFile(path.join('data', file), buffer, function () {
                res.json({ status: 'ok', length: buffer.length });
            });
        });
    } else {
        res.send(403);
        res.end();
    }
}

// Get a file from storage.

function getfile(req, res) {
    var file = req.params[0];
    log.debug('GET /store/' + file);
    var user = authenticate(req);
    if (user) {
        res.sendfile(path.join('data', file));
    } else {
        res.send(403);
        res.end();
    }
}

<commit_msg>Trim logging a little.<commit_after>#!/usr/bin/env node

var _ = require('underscore')._;
var async = require('async');
var commander = require('commander');
var express = require('express')
var fs = require('fs');
var https = require('https');
var log = require('winston');
var path = require('path');
var spawn = require('child_process').spawn;
var uuid = require('node-uuid');
var mkdirp = require('mkdirp');

// Set up configuration

commander
.option('-p, --port <port>', 'set the listen port (9443)', 9443)
.option('-s, --store <store>', 'set the store directory (~/mole-store)', path.join(process.env['HOME'], 'mole-store'))
.option('-d, --debug', 'show debug output', false)
.parse(process.argv);

// Set up the storage directory and move there

mkdirp.sync(path.join(commander.store, 'crt'));
mkdirp.sync(path.join(commander.store, 'data'));
mkdirp.sync(path.join(commander.store, 'server'));
process.chdir(commander.store);

// Set up logging

log.setLevels(log.config.syslog.levels);
log.remove(log.transports.Console);
log.add(log.transports.Console, {level: commander.debug ? 'debug' : 'info', timestamp: true});

// Set up users

var userStore = require('./lib/users');
var userFile = path.join(commander.sore, 'users.json');
log.debug('Using users file', userFile);
var users = new userStore(userFile);

var caCertFile = path.join(commander.store, 'ca-cert.pem');
var serverCertFile = path.join(commander.store, 'crt', 'server-cert.pem');
var serverKeyFile = path.join(commander.store, 'crt', 'server-key.pem');

log.debug('Checking for existing certificates');
if (!path.existsSync(caCertFile)) {
    spawn(path.join(__dirname, 'gen-ca.exp')).on('exit', function (code) {
        spawn(path.join(__dirname, 'gen-user.exp'), [ 'server' ]).on('exit', function (code) {
            log.info('Created CA & server certificates');
            startApp();
        });
    });
} else {
    startApp();
}

function startApp() {
    log.debug('Create HTTP server');
    var app = express.createServer({
        ca: [ fs.readFileSync(caCertFile) ],
        key: fs.readFileSync(serverKeyFile),
        cert: fs.readFileSync(serverCertFile),
        requestCert: true,
    });

    app.get(/\/register\/([0-9a-f-]+)$/, register);
    app.post('/newtoken', newtoken);
    app.post(/\/users\/([a-z0-9_-]+)$/, newuser);
    app.del(/\/users\/([a-z0-9_-]+)$/, deluser);
    app.get('/store', listfiles);
    app.put(/\/store\/([0-9a-z_.-]+)$/, putfile);
    app.get(/\/store\/([0-9a-z_.-]+)$/, getfile);
    app.listen(commander.port);
    log.info('Server listening on port ' + commander.port);
}

function createUserCert(name, callback) {
    var openssl = spawn(path.join(__dirname, 'gen-user.exp'), [ name ]);
    var fingerprint;

    function recv(data) {
        var s = data.toString('utf-8').trim();
        if (s.match(/^[0-9A-F:]+$/)) {
            fingerprint = s;
        } else if (s.length > 0) {
            log.warning(s);
        }
    }

    openssl.stdout.on('data', recv);
    openssl.stderr.on('data', recv);

    openssl.on('exit', function (code) {
        callback(fingerprint);
    });
}

function authenticate(req) {
    if (!req.client.authorized) {
        log.debug('Client not authorized');
        return null;
    }

    var cert = req.connection.getPeerCertificate();
    var username = cert.subject.CN;

    var user = users.get(username);
    if (!user) {
        log.warning('Certificate claimed username "' + username + '" which does not exist');
        return null;
    }

    if (user.fingerprint !== cert.fingerprint) {
        log.warning('Certificate presented for "' + username + '" does not match stored fingerprint');
        return null;
    }

    log.debug('Certificate authentication for ' + username + ' succeeded');
    return user;
}

function createUser(name, admin, callback) {
    var user = { created: Date.now(), token: uuid.v4() };

    createUserCert(name, function (fingerprint) {
        user.fingerprint = fingerprint;
        user.admin = !!admin;
        users.set(name, user);
        callback(user);
    });
}

function register(req, res){
    var token = req.params[0];
    var found = false;

    log.debug('GET /register/' + token);
    _.each(users.all(), function (user) {
        if (!found) {
            var name = user.name;
            var ud = user.data;
            if (ud.token === token) {
                found = true;
                var cert = fs.readFileSync('crt/' + name + '-cert.pem', 'utf-8');
                var key = fs.readFileSync('crt/' + name + '-key.pem', 'utf-8');
                var ca = fs.readFileSync(path.join(__dirname, 'ca-cert.pem'), 'utf-8');
                delete ud.token;
                ud.registered = Date.now();
                users.save();

                res.json({ cert: cert, key: key, ca: ca });
            }
        }
    });

    if (!found) {
        res.send(404);
        res.end();
    }
}

function newtoken(req, res){
    log.debug('POST /newtoken');
    var user = authenticate(req);
    if (user) {
        user.token = uuid.v4();
        users.save();
        res.json({ token: user.token });
    } else {
        res.send(403);
        res.end();
    };
}

// Create a new user (or reset certificate and token for an existing one).

function newuser(req, res){
    var username = req.params[0];
    log.debug('POST /users/' + username);
    var user = authenticate(req, users);
    if (users.all().length === 0 || user && user.admin) {
        var newUserAdmin = users.all().length == 0;
        createUser(username, newUserAdmin, function (u) {
            res.send(JSON.stringify(u));
        });
    } else {
        res.send(403);
        res.end();
    }
}

// Delete a user

function deluser(req, res){
    var username = req.params[0];
    log.debug('DELETE /users/' + username);
    var user = authenticate(req, users);
    if (user && user.admin) {
        if (users.get(username)) {
            users.del(username);
            users.save();
        } else {
            res.send(404);
        }
    } else {
        res.send(403);
    }
    res.end();
}

// List the files in storage.

function listfiles(req, res) {
    log.debug('GET /store');
    function stat(fname, callback) {
        fs.stat(path.join('data', fname), function (err, res) {
            if (err) {
                callback(err);
            } else {
                callback(null, { name: fname, mtime: res.mtime.getTime() });
            }
        });
    }

    var user = authenticate(req);
    if (user) {
        fs.readdir(path.join(commander.store, 'data'), function (err, files) {
            async.map(files, stat, function (err, files) {
                res.json(files);
            });
        });
    } else {
        res.send(403);
        res.end();
    }
}

// Add a file to storage.

function putfile(req, res) {
    var file = req.params[0];
    log.debug('PUT /store/' + file);
    var user = authenticate(req);
    if (user) {
        var buffer = '';
        req.setEncoding('utf-8');
        req.on('data', function (chunk) {
            buffer += chunk;
        });
        req.on('end', function () {
            fs.writeFile(path.join('data', file), buffer, function () {
                res.json({ status: 'ok', length: buffer.length });
            });
        });
    } else {
        res.send(403);
        res.end();
    }
}

// Get a file from storage.

function getfile(req, res) {
    var file = req.params[0];
    log.debug('GET /store/' + file);
    var user = authenticate(req);
    if (user) {
        res.sendfile(path.join('data', file));
    } else {
        res.send(403);
        res.end();
    }
}

<|endoftext|>


<commit_before>var sys = require("sys"),
	http = require("http"),
	url = require("url"),
	path = require("path"),
	fs = require("fs");

exec = require( 'child_process' ).exec;

var dcsGetDir = "/var/tmp/dcs-get";
var port = 8080;

var serv = http.createServer(function( req, res ){
	var reqURL = url.parse( req.url );
	var request = /^\/?([^\/]*)\/?([^\/]*)/.exec(reqURL.pathname);
	console.log(request[1] + ", " + request[2]);
	switch(request[1])
	{
		case '':
			home(req, res);
			break;
		case 'static':
			res.writeHead(200);
			serveStatic(req, res, request[2]);
			res.end();
			break;
		case 'download':
			download(req, res, request[2]);
			break;
		default:
			pageNotFound( req, res );
			break;
	}
	return;
});

serv.listen(port);
console.log("Server running at http://localhost:"+port+"/");

exec("dcs-get list", function(err, stdout, stderr){
	if ( err ) {
		console.log( "Unable to list packages" );
	}
	else
	{
		packageList = stdout.split("\n");

		for ( var i in packageList ) {
			var temp = /(.*)\ -(.*)-/.exec( packageList[i] );
			if ( temp ) {
				var data = {};
				data.name = temp[1];
				data.info = temp[2];
				packageList[i] = data;
			}
		}
	}
});

exec( "dcs-get list", function( err, stdout, stderr ) {
	if ( err ) {
		console.log( "Unable to list packages" );
	}
	packageList = stdout.split("\n");

	for ( var i in packageList ) {
		var temp = /(.*)\ -(.*)-/.exec(packageList[i].trim());
		if (temp) {
			var data = {};
			data.name = temp[1];
			data.info = temp[2];
			packageList[i] = data;
		}
	}
});

function home(req, res){
	res.writeHead( 500, {"Content-Type": "text/HTML"});
	res.write('<title>UWCS Gaming</title>');
	res.write('<link href="static/main.css" rel="stylesheet" type="text/css" />');
	res.write('<link href="static/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />');
	res.write("Welcome to gaming-get Homepage
You have installed:
");
	try
	{
		var files = fs.readdirSync( dcsGetDir );
		var ignore = new Array( "bin", "cleanup", "downloads", "downloaded", "lib");
		for ( var i in files ) {
			if ( ignore.indexOf( files[i] ) == -1 ) {
				res.write( files[i]+"
" );
			}
		}
		res.write("
Available packages:
");
		for ( var i in packageList ) {
			res.write('
');
			res.write('Install' );
			res.write('' + packageList[i].name + '');
			res.write('' + packageList[i].info + '');
			res.write('
');
		}
		res.write('Some tester text blah');
	}
	catch(err)
	{
		if(err.code == 'ENOENT')
		{
			console.log(err);
			res.write("Error: dcs-get not installed\n");
		}
	}

	res.end();
	return;

}

function download( request, response, packageName ) {
	if ( packageName != null ) {

		exec( "dcs-get install "+packageName, function ( err, stdout, stderr ) {
		if ( err ) {
			response.write( "Unable to install\n" );
			console.log( err );
			response.end();
			return;
		}
		response.writeHead( 500, {"Content-Type": "text/HTML"});
		response.write( stdout );
		response.end();
		return;
	});

	}

	else {
		response.writeHead( 500, {"Content-Type": "text/HTML"});
                response.write( "Invalid Request." );
                response.end();
	}
}

function pageNotFound ( req, res ) {
	console.log("404 trying to get: "+req.url);
	res.writeHead(500, {'Content-Type': 'text/HTML'});
	res.write("404'd!!!");
	res.end();
	return;
}

function serveStatic(req, res, filePath) {
	try
	{
		res.write(fs.readFileSync("./static/"+filePath));
	}
	catch(err)
	{
		if(err.code == 'EBADF')
		{
			pageNotFound(req, res);
			console.log(err);
		}
		else
		{
			console.log(err);
			res.write("ERROR: " + err.code);
		}
	}
	return;
}
<commit_msg>Newlines.<commit_after>var sys = require("sys"),
	http = require("http"),
	url = require("url"),
	path = require("path"),
	fs = require("fs");

exec = require( 'child_process' ).exec;

var dcsGetDir = "/var/tmp/dcs-get";
var port = 8080;

var serv = http.createServer(function( req, res ){
	var reqURL = url.parse( req.url );
	var request = /^\/?([^\/]*)\/?([^\/]*)/.exec(reqURL.pathname);
	console.log(request[1] + ", " + request[2]);
	switch(request[1])
	{
		case '':
			home(req, res);
			break;
		case 'static':
			res.writeHead(200);
			serveStatic(req, res, request[2]);
			res.end();
			break;
		case 'download':
			download(req, res, request[2]);
			break;
		default:
			pageNotFound( req, res );
			break;
	}
	return;
});

serv.listen(port);
console.log("Server running at http://localhost:"+port+"/");

exec("dcs-get list", function(err, stdout, stderr){
	if ( err ) {
		console.log( "Unable to list packages" );
	}
	else
	{
		packageList = stdout.split("\n");

		for ( var i in packageList ) {
			var temp = /(.*)\ -(.*)-/.exec( packageList[i] );
			if ( temp ) {
				var data = {};
				data.name = temp[1];
				data.info = temp[2];
				packageList[i] = data;
			}
		}
	}
});

exec( "dcs-get list", function( err, stdout, stderr ) {
	if ( err ) {
		console.log( "Unable to list packages" );
	}
	packageList = stdout.split("\n");

	for ( var i in packageList ) {
		var temp = /(.*)\ -(.*)-/.exec(packageList[i].trim());
		if (temp) {
			var data = {};
			data.name = temp[1];
			data.info = temp[2];
			packageList[i] = data;
		}
	}
});

function home(req, res){
	res.writeHead( 500, {"Content-Type": "text/HTML"});
	res.write('<title>UWCS Gaming</title>');
	res.write('<link href="static/main.css" rel="stylesheet" type="text/css" />');
	res.write('<link href="static/favicon.ico" rel="shortcut icon" type="image/vnd.microsoft.icon" />');
	res.write("Welcome to gaming-get Homepage
You have installed:
");
	try
	{
		var files = fs.readdirSync( dcsGetDir );
		var ignore = new Array( "bin", "cleanup", "downloads", "downloaded", "lib");
		for ( var i in files ) {
			if ( ignore.indexOf( files[i] ) == -1 ) {
				res.write( files[i]+"
" );
			}
		}
		res.write("
Available packages:
\n");
		for ( var i in packageList ) {
			res.write('
\n');
			res.write('Install\n' );
			res.write('' + packageList[i].name + '\n');
			res.write('' + packageList[i].info + '\n');
			res.write('
\n');
		}
		res.write('Some tester text blah');
	}
	catch(err)
	{
		if(err.code == 'ENOENT')
		{
			console.log(err);
			res.write("Error: dcs-get not installed\n");
		}
	}

	res.end();
	return;

}

function download( request, response, packageName ) {
	if ( packageName != null ) {

		exec( "dcs-get install "+packageName, function ( err, stdout, stderr ) {
		if ( err ) {
			response.write( "Unable to install\n" );
			console.log( err );
			response.end();
			return;
		}
		response.writeHead( 500, {"Content-Type": "text/HTML"});
		response.write( stdout );
		response.end();
		return;
	});

	}

	else {
		response.writeHead( 500, {"Content-Type": "text/HTML"});
                response.write( "Invalid Request." );
                response.end();
	}
}

function pageNotFound ( req, res ) {
	console.log("404 trying to get: "+req.url);
	res.writeHead(500, {'Content-Type': 'text/HTML'});
	res.write("404'd!!!");
	res.end();
	return;
}

function serveStatic(req, res, filePath) {
	try
	{
		res.write(fs.readFileSync("./static/"+filePath));
	}
	catch(err)
	{
		if(err.code == 'EBADF')
		{
			pageNotFound(req, res);
			console.log(err);
		}
		else
		{
			console.log(err);
			res.write("ERROR: " + err.code);
		}
	}
	return;
}
<|endoftext|>


<commit_before>//-------------
// version 1.1
// maj 11/2016
// by e-Coucou
//-------------
// 08/2017 try to add webhook !!
//
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var mongodb = require("mongodb");
var ObjectID = mongodb.ObjectID;

var CONTACTS_COLLECTION = "contacts";

var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());

// Create a database variable outside of the database connection callback to reuse the connection pool in your app.
var db;

// Connect to the database before starting the application server.
mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err, database) {
  if (err) {
    console.log(err);
    process.exit(1);
  }

  // Save database object from the callback for reuse.
  db = database;
  console.log("Database connection ready");

  // Initialize the app.
  var server = app.listen(process.env.PORT || 8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
  });
});

// CONTACTS API ROUTES BELOW

// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
  console.log("ERROR: " + reason);
  res.status(code || 500).json({"error": message});
}

/*  "/contacts"
 *    GET: finds all contacts
 *    POST: creates a new contact
 */

app.get("/contacts", function(req, res) {
  db.collection(CONTACTS_COLLECTION).find({}).toArray(function(err, docs) {
    if (err) {
      handleError(res, err.message, "Failed to get contacts.");
    } else {
      res.status(200).json(docs);
    }
  });
});

app.post("/contacts", function(req, res) {
  var newContact = req.body;
  var d = new Date();
    newContact.date = d.toLocaleDateString();
    newContact.heure = d.toLocaleTimeString();

//toLocaleString().substring(0,9);

//  if (!(req.body.firstName || req.body.lastName)) {
//    handleError(res, "Invalid user input", "Must provide a first or last name.", 400);
//  }

  db.collection(CONTACTS_COLLECTION).insertOne(newContact, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to create new contact.");
    } else {
      res.status(201).json(doc.ops[0]);
    }
  });
});

//----------------------
// add scale value
//
// scale : name
// high / low
app.post("/api/v1/scale", function(req, res) {
    var newScale = req.body;

    db.collection(CONTACTS_COLLECTION).insertOne(newScale, function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to create new scale value.");
        } else {
        res.status(201).json(doc.ops[0]);
        }
    });
});

//------
// WebHook ?!
var obj = {
  "id": "id",
  "timestamp": "2017-02-09T15:38:26.548Z",
  "lang": "fr",
  "result": {
    "source": "agent",
    "resolvedQuery": "Population Test",
    "action": "complete",
    "actionIncomplete": false,
    "parameters": {},
    "contexts": [],
    "metadata": {
      "intentId": "9f41ef7c-82fa-42a7-9a30-49a93e2c14d0",
      "webhookUsed": "true",
      "webhookForSlotFillingUsed": "false",
      "intentName": "Population"
    },
    "fulfillment": {
      "speech": "Ca roule pour moi",
      "messages": [
        {
          "type": 0,
          "speech": "Ca roule pour moi"
        }
      ]
    },
    "score": 1
  },
  "status": {
    "code": 200,
    "errorType": "success"
  },
  "sessionId": "4b6a6779-b8ea-4094-b2ed-a302ba201815"
}
app.post("/api/v1/webhook", function(req,res) {
	console.log(req.body.result.fulfillment.speech);
//	req.body.result.fulfillment.speech = "Je connais la réponse";
//	req.body.result.
	obj.id = req.body.id;
	obj.result.metadata.intentId = req.body.result.metadata.itentId;
	obj.sessionId = req.body.sessionId;
	console.log(req.body);
	console.log(obj);
	console.log(Date.now())
	res.status(200).json(req.body);
//	res.render('index', { title: 'WebHook Info' });
});

/*  "/contacts/:id"
 *    GET: find contact by id
 *    PUT: update contact by id
 *    DELETE: deletes contact by id
 */

app.get("/contacts/:id", function(req, res) {
  db.collection(CONTACTS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to get contact");
    } else {
      res.status(200).json(doc);
    }
  });
});

app.get("/api/v1/test/:name", function(req, res) {
    console.log("Param: " + req.params.name);
    db.collection(CONTACTS_COLLECTION).find({ name: req.params.name }).toArray( function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to list name");
        } else {
            res.status(200).json(doc);
        }
    });
});
//-----------------------------------------------
// API V1 -> SEARCH
//
app.get("/api/v1/search", function(req, res) {
    if (req.query.source == "*" || ( typeof req.query.source == 'undefined')) { source = { $regex: /\w|/, $options:"i"} } else { source = req.query.source }
    if (req.query.name == "*" || (typeof req.query.name == 'undefined')) { name = { $regex: /\w|/, $options:"i"} } else { name = req.query.name }
    if (typeof req.query.before == 'undefined') { before = ObjectID(Math.floor((new Date('2100/12/31'))/1000).toString(16) + "0000000000000000") } else { before = ObjectID(Math.floor((new Date(req.query.before))/1000 - 7200).toString(16) + "0000000000000000") }
    if (typeof req.query.after == 'undefined') { after = ObjectID(Math.floor((new Date('2016/01/01'))/1000).toString(16) + "0000000000000000") } else { after = ObjectID(Math.floor((new Date(req.query.after))/1000 - 7200).toString(16) + "0000000000000000") }
    if (typeof req.query.filtre == 'undefined') { filtre = {} } else { if (req.query.filtre == "name") { filtre = {name: 1, value:  1, _id: 0} } else {filtre = { value: 1 , _id: 0 } } }

	selection = { name: name, source: source , _id: {$lt: before, $gt: after}} ;

	console.log("before = "+before+"  after : "+after);

    db.collection(CONTACTS_COLLECTION).find( selection , filtre ).toArray( function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find contact");
        } else {
            res.status(200).json(doc);
        }
    });
});
// /api/v1/scale
app.get("/api/v1/list/scale", function(req, res) {

    if (req.query.scale == "*" || ( typeof req.query.scale == 'undefined')) { scale = { $regex: /\w|/, $options:"i"} } else { scale = req.query.scale }

        selection = { scale : scale } ;

        db.collection(CONTACTS_COLLECTION).find( selection ).toArray( function(err, doc) {
            if (err) {
                handleError(res, err.message, "Failed to find scale");
            } else {
                res.status(200).json(doc);
            }
        });
    });
//----------------------------
// API for IOS
//
app.get("/api/v1/name", function(req, res) {
        db.collection(CONTACTS_COLLECTION).distinct( "name" , function(err, doc) {
            if (err) {
                handleError(res, err.message, "Failed to find name");
            } else {
                res.status(200).json(doc);
            }
    });
});

app.get("/api/v1/source", function(req, res) {
    db.collection(CONTACTS_COLLECTION).distinct( "source" , function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find source");
        } else {
            res.status(200).json(doc);
        }
    });
});

app.get("/api/v1/date", function(req, res) {
    db.collection(CONTACTS_COLLECTION).distinct( "date" , function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find date");
        } else {
            res.status(200).json(doc);
        }
    });
});

app.get("/api/v1/heure", function(req, res) {
    db.collection(CONTACTS_COLLECTION).distinct( "heure" , function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find heure");
        } else {
            res.status(200).json(doc);
        }
    });
});
app.get("/api/v1/scale", function(req, res) {
    db.collection(CONTACTS_COLLECTION).distinct( "scale" , function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find scale value");
        } else {
        res.status(200).json(doc);
        }
    });
});

//--------xxxxx
app.put("/contacts/:id", function(req, res) {
  var updateDoc = req.body;
  delete updateDoc._id;

  db.collection(CONTACTS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to update contact");
    } else {
      res.status(204).end();
    }
  });
});
//------------------------------------------------
// API delete
//
app.delete("/api/v1/id/:id", function(req, res) {
  db.collection(CONTACTS_COLLECTION).deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) {
    if (err) {
      handleError(res, err.message, "Failed to delete contact");
    } else {
      res.status(204).end();
    }
  });
});

app.delete("/api/v1/name/:name", function(req, res) {
    db.collection(CONTACTS_COLLECTION).deleteMany({ name: req.params.name}, function(err, result) {
        if (err) {
            handleError(res, err.message, "Failed to delete contact");
        } else {
            res.status(204).end();
        }
    });
});

app.delete("/api/v1/source/:source", function(req, res) {
    db.collection(CONTACTS_COLLECTION).deleteMany({ source: req.params.source }, function(err, result) {
        if (err) {
            handleError(res, err.message, "Failed to delete contact");
        } else {
            res.status(204).end();
        }
    });
});
// delete with value and name
app.delete("/api/v1/valeur", function(req, res) {

  console.log("before = "+req.query.max+"  after : "+req.query.min);
  selection = { name: req.query.name, value: req.query.max } ;
//  selection = { name: req.query.name, value: {$lt: req.query.min, $gt: req.query.max}} ;

    db.collection(CONTACTS_COLLECTION).deleteMany( selection , function(err, result) {
        if (err) {
            handleError(res, err.message, "Failed to delete contact");
        } else {
            res.status(204).end();
        }
    });
});
<commit_msg>wh maj obj<commit_after>//-------------
// version 1.1
// maj 11/2016
// by e-Coucou
//-------------
// 08/2017 try to add webhook !!
//
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var mongodb = require("mongodb");
var ObjectID = mongodb.ObjectID;

var CONTACTS_COLLECTION = "contacts";

var app = express();
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.json());

// Create a database variable outside of the database connection callback to reuse the connection pool in your app.
var db;

// Connect to the database before starting the application server.
mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err, database) {
  if (err) {
    console.log(err);
    process.exit(1);
  }

  // Save database object from the callback for reuse.
  db = database;
  console.log("Database connection ready");

  // Initialize the app.
  var server = app.listen(process.env.PORT || 8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
  });
});

// CONTACTS API ROUTES BELOW

// Generic error handler used by all endpoints.
function handleError(res, reason, message, code) {
  console.log("ERROR: " + reason);
  res.status(code || 500).json({"error": message});
}

/*  "/contacts"
 *    GET: finds all contacts
 *    POST: creates a new contact
 */

app.get("/contacts", function(req, res) {
  db.collection(CONTACTS_COLLECTION).find({}).toArray(function(err, docs) {
    if (err) {
      handleError(res, err.message, "Failed to get contacts.");
    } else {
      res.status(200).json(docs);
    }
  });
});

app.post("/contacts", function(req, res) {
  var newContact = req.body;
  var d = new Date();
    newContact.date = d.toLocaleDateString();
    newContact.heure = d.toLocaleTimeString();

//toLocaleString().substring(0,9);

//  if (!(req.body.firstName || req.body.lastName)) {
//    handleError(res, "Invalid user input", "Must provide a first or last name.", 400);
//  }

  db.collection(CONTACTS_COLLECTION).insertOne(newContact, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to create new contact.");
    } else {
      res.status(201).json(doc.ops[0]);
    }
  });
});

//----------------------
// add scale value
//
// scale : name
// high / low
app.post("/api/v1/scale", function(req, res) {
    var newScale = req.body;

    db.collection(CONTACTS_COLLECTION).insertOne(newScale, function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to create new scale value.");
        } else {
        res.status(201).json(doc.ops[0]);
        }
    });
});

//------
// WebHook ?!
var obj = {
  "id": "id",
  "timestamp": "2017-02-09T15:38:26.548Z",
  "lang": "fr",
  "result": {
    "source": "agent",
    "resolvedQuery": "Population Test",
    "action": "complete",
    "actionIncomplete": false,
    "parameters": {},
    "contexts": [],
    "metadata": {
      "intentId": "9f41ef7c-82fa-42a7-9a30-49a93e2c14d0",
      "webhookUsed": "true",
      "webhookForSlotFillingUsed": "false",
      "intentName": "Population"
    },
    "fulfillment": {
      "speech": "Ca roule pour moi",
      "messages": [
        {
          "type": 0,
          "speech": "Ca roule pour moi"
        }
      ]
    },
    "score": 1
  },
  "status": {
    "code": 200,
    "errorType": "success"
  },
  "sessionId": "4b6a6779-b8ea-4094-b2ed-a302ba201815"
}
app.post("/api/v1/webhook", function(req,res) {
	console.log(req.body.result.fulfillment.speech);
//	req.body.result.fulfillment.speech = "Je connais la réponse";
//	req.body.result.
	obj.id = req.body.id;
	obj.result.metadata.intentId = req.body.result.metadata.itentId;
	obj.sessionId = req.body.sessionId;
	console.log(req.body);
	console.log(obj);
	console.log(Date.now())
	res.status(200).json(obj);
//	res.render('index', { title: 'WebHook Info' });
});

/*  "/contacts/:id"
 *    GET: find contact by id
 *    PUT: update contact by id
 *    DELETE: deletes contact by id
 */

app.get("/contacts/:id", function(req, res) {
  db.collection(CONTACTS_COLLECTION).findOne({ _id: new ObjectID(req.params.id) }, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to get contact");
    } else {
      res.status(200).json(doc);
    }
  });
});

app.get("/api/v1/test/:name", function(req, res) {
    console.log("Param: " + req.params.name);
    db.collection(CONTACTS_COLLECTION).find({ name: req.params.name }).toArray( function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to list name");
        } else {
            res.status(200).json(doc);
        }
    });
});
//-----------------------------------------------
// API V1 -> SEARCH
//
app.get("/api/v1/search", function(req, res) {
    if (req.query.source == "*" || ( typeof req.query.source == 'undefined')) { source = { $regex: /\w|/, $options:"i"} } else { source = req.query.source }
    if (req.query.name == "*" || (typeof req.query.name == 'undefined')) { name = { $regex: /\w|/, $options:"i"} } else { name = req.query.name }
    if (typeof req.query.before == 'undefined') { before = ObjectID(Math.floor((new Date('2100/12/31'))/1000).toString(16) + "0000000000000000") } else { before = ObjectID(Math.floor((new Date(req.query.before))/1000 - 7200).toString(16) + "0000000000000000") }
    if (typeof req.query.after == 'undefined') { after = ObjectID(Math.floor((new Date('2016/01/01'))/1000).toString(16) + "0000000000000000") } else { after = ObjectID(Math.floor((new Date(req.query.after))/1000 - 7200).toString(16) + "0000000000000000") }
    if (typeof req.query.filtre == 'undefined') { filtre = {} } else { if (req.query.filtre == "name") { filtre = {name: 1, value:  1, _id: 0} } else {filtre = { value: 1 , _id: 0 } } }

	selection = { name: name, source: source , _id: {$lt: before, $gt: after}} ;

	console.log("before = "+before+"  after : "+after);

    db.collection(CONTACTS_COLLECTION).find( selection , filtre ).toArray( function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find contact");
        } else {
            res.status(200).json(doc);
        }
    });
});
// /api/v1/scale
app.get("/api/v1/list/scale", function(req, res) {

    if (req.query.scale == "*" || ( typeof req.query.scale == 'undefined')) { scale = { $regex: /\w|/, $options:"i"} } else { scale = req.query.scale }

        selection = { scale : scale } ;

        db.collection(CONTACTS_COLLECTION).find( selection ).toArray( function(err, doc) {
            if (err) {
                handleError(res, err.message, "Failed to find scale");
            } else {
                res.status(200).json(doc);
            }
        });
    });
//----------------------------
// API for IOS
//
app.get("/api/v1/name", function(req, res) {
        db.collection(CONTACTS_COLLECTION).distinct( "name" , function(err, doc) {
            if (err) {
                handleError(res, err.message, "Failed to find name");
            } else {
                res.status(200).json(doc);
            }
    });
});

app.get("/api/v1/source", function(req, res) {
    db.collection(CONTACTS_COLLECTION).distinct( "source" , function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find source");
        } else {
            res.status(200).json(doc);
        }
    });
});

app.get("/api/v1/date", function(req, res) {
    db.collection(CONTACTS_COLLECTION).distinct( "date" , function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find date");
        } else {
            res.status(200).json(doc);
        }
    });
});

app.get("/api/v1/heure", function(req, res) {
    db.collection(CONTACTS_COLLECTION).distinct( "heure" , function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find heure");
        } else {
            res.status(200).json(doc);
        }
    });
});
app.get("/api/v1/scale", function(req, res) {
    db.collection(CONTACTS_COLLECTION).distinct( "scale" , function(err, doc) {
        if (err) {
            handleError(res, err.message, "Failed to find scale value");
        } else {
        res.status(200).json(doc);
        }
    });
});

//--------xxxxx
app.put("/contacts/:id", function(req, res) {
  var updateDoc = req.body;
  delete updateDoc._id;

  db.collection(CONTACTS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
    if (err) {
      handleError(res, err.message, "Failed to update contact");
    } else {
      res.status(204).end();
    }
  });
});
//------------------------------------------------
// API delete
//
app.delete("/api/v1/id/:id", function(req, res) {
  db.collection(CONTACTS_COLLECTION).deleteOne({_id: new ObjectID(req.params.id)}, function(err, result) {
    if (err) {
      handleError(res, err.message, "Failed to delete contact");
    } else {
      res.status(204).end();
    }
  });
});

app.delete("/api/v1/name/:name", function(req, res) {
    db.collection(CONTACTS_COLLECTION).deleteMany({ name: req.params.name}, function(err, result) {
        if (err) {
            handleError(res, err.message, "Failed to delete contact");
        } else {
            res.status(204).end();
        }
    });
});

app.delete("/api/v1/source/:source", function(req, res) {
    db.collection(CONTACTS_COLLECTION).deleteMany({ source: req.params.source }, function(err, result) {
        if (err) {
            handleError(res, err.message, "Failed to delete contact");
        } else {
            res.status(204).end();
        }
    });
});
// delete with value and name
app.delete("/api/v1/valeur", function(req, res) {

  console.log("before = "+req.query.max+"  after : "+req.query.min);
  selection = { name: req.query.name, value: req.query.max } ;
//  selection = { name: req.query.name, value: {$lt: req.query.min, $gt: req.query.max}} ;

    db.collection(CONTACTS_COLLECTION).deleteMany( selection , function(err, result) {
        if (err) {
            handleError(res, err.message, "Failed to delete contact");
        } else {
            res.status(204).end();
        }
    });
});
<|endoftext|>


<commit_before>var express = require("express"),
    app = express(),
    bodyParser = require('body-parser')
    errorHandler = require('errorhandler'),
    methodOverride = require('method-override'),
    port = parseInt(process.env.PORT, 10) || 4567;

app.get("/", function (req, res) {
  res.redirect("/app/index.html");
});

app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static(__dirname + '/lazysheetmusic'));
app.use(errorHandler({
  dumpExceptions: true,
  showStack: true
}));

console.log("Simple static server listening at http://localhost:" + port);
app.listen(port);
<commit_msg>redirection<commit_after>var express = require("express"),
    app = express(),
    bodyParser = require('body-parser')
    errorHandler = require('errorhandler'),
    methodOverride = require('method-override'),
    port = parseInt(process.env.PORT, 10) || 4567;

app.get("/", function (req, res) {
  //res.redirect("/index.html");
});

app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static(__dirname + '/lazysheetmusic'));
app.use(errorHandler({
  dumpExceptions: true,
  showStack: true
}));

console.log("Simple static server listening at http://localhost:" + port);
app.listen(port);
<|endoftext|>


<commit_before>import {Transform} from 'vega-dataflow';
import {inherits} from 'vega-util';

/**
 * Computes extents (min/max) for a data field.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The field over which to compute extends.
 */
export default function Extent(params) {
  Transform.call(this, [+Infinity, -Infinity], params);
}

Extent.Definition = {
  "type": "Extent",
  "metadata": {},
  "params": [
    { "name": "field", "type": "field", "required": true }
  ]
};

var prototype = inherits(Extent, Transform);

prototype.transform = function(_, pulse) {
  var extent = this.value,
      field = _.field,
      min = extent[0],
      max = extent[1],
      flag = pulse.ADD,
      mod;

  mod = pulse.changed()
     || pulse.modified(field.fields)
     || _.modified('field');

  if (mod) {
    flag = pulse.SOURCE;
    min = +Infinity;
    max = -Infinity;
  }

  pulse.visit(flag, function(t) {
    var v = field(t);
    if (v < min) min = v;
    if (v > max) max = v;
  });

  this.value = [min, max];
};
<commit_msg>Add null check to Extent.<commit_after>import {Transform} from 'vega-dataflow';
import {inherits} from 'vega-util';

/**
 * Computes extents (min/max) for a data field.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {function(object): *} params.field - The field over which to compute extends.
 */
export default function Extent(params) {
  Transform.call(this, [+Infinity, -Infinity], params);
}

Extent.Definition = {
  "type": "Extent",
  "metadata": {},
  "params": [
    { "name": "field", "type": "field", "required": true }
  ]
};

var prototype = inherits(Extent, Transform);

prototype.transform = function(_, pulse) {
  var extent = this.value,
      field = _.field,
      min = extent[0],
      max = extent[1],
      flag = pulse.ADD,
      mod;

  mod = pulse.changed()
     || pulse.modified(field.fields)
     || _.modified('field');

  if (mod) {
    flag = pulse.SOURCE;
    min = +Infinity;
    max = -Infinity;
  }

  pulse.visit(flag, function(t) {
    var v = field(t);
    if (v != null) {
      if (v < min) min = v;
      if (v > max) max = v;
    }
  });

  this.value = [min, max];
};
<|endoftext|>


<commit_before>import formats from './formats';
import {transforms} from 'vega-dataflow';
import {load} from 'vega-loader';
import {
  error, extend, isArray, isObject, isString, pad, truncate, truthy
} from 'vega-util';
import {parse, context} from 'vega-runtime';
import {scaleGradient} from 'vega-scenegraph';
import {rgb, lab, hcl, hsl} from 'd3-color';

function scale(name, ctx) {
  var s = isString(name) ? ctx.scales[name]
    : isObject(name) && name.signal ? ctx.signals[name.signal]
    : undefined;
  return s && s.value;
}

function functions() {
  var fn = formats();
  fn.pad = pad;
  fn.truncate = truncate;

  fn.rgb = rgb;
  fn.lab = lab;
  fn.hcl = hcl;
  fn.hsl = hsl;
  fn.gradient = scaleGradient;

  fn.pinchDistance = function() {
    return 'Math.sqrt('
      + 'pow(event.touches[0].clientX - event.touches[1].clientX, 2) + '
      + 'pow(event.touches[0].clientY - event.touches[1].clientY, 2)'
      + ')';
  };

  fn.pinchAngle = function() {
    return 'Math.atan2('
      + 'event.touches[1].clientY - event.touches[0].clientY,'
      + 'event.touches[1].clientX - event.touches[0].clientX'
      + ')';
  };

  fn.open = function(uri, name) {
    if (typeof window !== 'undefined' && window && window.open) {
      var opt = this.context.dataflow.loadOptions(),
          url = load.sanitize(uri, extend({type:'open', name:name}, opt));
      if (url) {
        window.open(url, name);
      } else {
        error('Invalid URL: ' + opt.url);
      }
    } else {
      error('Open function can only be invoked in a browser.');
    }
  };

  fn.span = function(array) {
    return array[array.length-1] - array[0];
  };

  fn.range = function(name) {
    var s = scale(name, this.context);
    return s && s.range ? s.range() : [0, 0];
  };

  fn.bandwidth = function(name) {
    var s = scale(name, this.context);
    return s && s.bandwidth ? s.bandwidth() : 0;
  };

  fn.scale = function(name, value) {
    var s = scale(name, this.context);
    return s ? s(value) : undefined;
  };

  fn.scaleInvert = function(name, range) {
    var s = scale(name, this.context);
    return !s ? undefined
      : isArray(range) ? (s.invertRange || s.invert)(range)
      : (s.invert || s.invertExtent)(range);
  };

  fn.scaleCopy = function(name) {
    var s = scale(name, this.context);
    return s ? s.copy() : undefined;
  };

  fn.indata = function(name, field, value) {
    var index = this.context.data[name]['index:' + field],
        entry = index ? index.value[value] : undefined;
    return entry ? entry.count : entry;
  };

  fn.inrange = function(value, range) {
    var r0 = range[0], r1 = range[range.length-1], t;
    if (r0 > r1) t = r0, r0 = r1, r1 = t;
    return r0 <= value && value <= r1;
  };

  fn.encode = function(item, name, retval) {
    if (item) {
      var df = this.context.dataflow,
          target = item.mark.source;
      df.pulse(target, df.changeset().encode(item, name));
    }
    return retval !== undefined ? retval : item;
  };

  fn.modify = function(name, insert, remove, toggle, modify, values) {
    var df = this.context.dataflow,
        data = this.context.data[name],
        input = data.input,
        changes = data.changes,
        stamp = df.stamp(),
        predicate, key;

    if (!(input.value.length || insert || toggle)) {
      // nothing to do!
      return 0;
    }

    if (!changes || changes.stamp < stamp) {
      data.changes = (changes = df.changeset());
      changes.stamp = stamp;
      df.runAfter(function() { df.pulse(input, changes).run(); });
    }

    if (remove) {
      changes.remove(remove === true ? truthy : remove);
    }

    if (insert) {
      changes.insert(insert);
    }

    if (toggle) {
      predicate = function(_) {
        for (key in toggle) {
          if (_[key] !== toggle[key]) return false;
        }
        return true;
      };

      if (input.value.filter(predicate).length) {
        changes.remove(predicate);
      } else {
        changes.insert(toggle);
      }
    }

    if (modify) {
      for (key in values) {
        changes.modify(modify, key, values[key]);
      }
    }

    return 1;
  };

  return fn;
}

export default function(view, spec) {
  return parse(spec, context(view, transforms, functions()));
}
<commit_msg>Allow dynamic context lookup for scale expression functions.<commit_after>import formats from './formats';
import {transforms} from 'vega-dataflow';
import {load} from 'vega-loader';
import {
  error, extend, isArray, isObject, isString, pad, truncate, truthy
} from 'vega-util';
import {parse, context} from 'vega-runtime';
import {scaleGradient} from 'vega-scenegraph';
import {rgb, lab, hcl, hsl} from 'd3-color';

function scale(name, ctx) {
  var s = isString(name) ? ctx.scales[name]
    : isObject(name) && name.signal ? ctx.signals[name.signal]
    : undefined;
  return s && s.value;
}

function functions() {
  var fn = formats();
  fn.pad = pad;
  fn.truncate = truncate;

  fn.rgb = rgb;
  fn.lab = lab;
  fn.hcl = hcl;
  fn.hsl = hsl;
  fn.gradient = scaleGradient;

  fn.clampRange = function(range, min, max) {
    var lo = range[0],
        hi = range[1],
        span;

    if (hi < lo) span = hi, hi = lo, lo = span;
    span = hi - lo;

    return [
      Math.min(Math.max(lo, min), max - span),
      Math.min(Math.max(hi, span), max)
    ];
  };

  fn.pinchDistance = function() {
    return 'Math.sqrt('
      + 'pow(event.touches[0].clientX - event.touches[1].clientX, 2) + '
      + 'pow(event.touches[0].clientY - event.touches[1].clientY, 2)'
      + ')';
  };

  fn.pinchAngle = function() {
    return 'Math.atan2('
      + 'event.touches[1].clientY - event.touches[0].clientY,'
      + 'event.touches[1].clientX - event.touches[0].clientX'
      + ')';
  };

  fn.open = function(uri, name) {
    if (typeof window !== 'undefined' && window && window.open) {
      var opt = this.context.dataflow.loadOptions(),
          url = load.sanitize(uri, extend({type:'open', name:name}, opt));
      if (url) {
        window.open(url, name);
      } else {
        error('Invalid URL: ' + opt.url);
      }
    } else {
      error('Open function can only be invoked in a browser.');
    }
  };

  fn.span = function(array) {
    return array[array.length-1] - array[0];
  };

  fn.range = function(name, group) {
    var s = scale(name, (group || this).context);
    return s && s.range ? s.range() : [0, 0];
  };

  fn.bandwidth = function(name, group) {
    var s = scale(name, (group || this).context);
    return s && s.bandwidth ? s.bandwidth() : 0;
  };

  fn.scaleCopy = function(name, group) {
    var s = scale(name, (group || this).context);
    return s ? s.copy() : undefined;
  };

  fn.scale = function(name, value, group) {
    var s = scale(name, (group || this).context);
    return s ? s(value) : undefined;
  };

  fn.scaleInvert = function(name, range, group) {
    var s = scale(name, (group || this).context);
    return !s ? undefined
      : isArray(range) ? (s.invertRange || s.invert)(range)
      : (s.invert || s.invertExtent)(range);
  };

  fn.indata = function(name, field, value) {
    var index = this.context.data[name]['index:' + field],
        entry = index ? index.value[value] : undefined;
    return entry ? entry.count : entry;
  };

  fn.inrange = function(value, range) {
    var r0 = range[0], r1 = range[range.length-1], t;
    if (r0 > r1) t = r0, r0 = r1, r1 = t;
    return r0 <= value && value <= r1;
  };

  fn.encode = function(item, name, retval) {
    if (item) {
      var df = this.context.dataflow,
          target = item.mark.source;
      df.pulse(target, df.changeset().encode(item, name));
    }
    return retval !== undefined ? retval : item;
  };

  fn.modify = function(name, insert, remove, toggle, modify, values) {
    var df = this.context.dataflow,
        data = this.context.data[name],
        input = data.input,
        changes = data.changes,
        stamp = df.stamp(),
        predicate, key;

    if (!(input.value.length || insert || toggle)) {
      // nothing to do!
      return 0;
    }

    if (!changes || changes.stamp < stamp) {
      data.changes = (changes = df.changeset());
      changes.stamp = stamp;
      df.runAfter(function() { df.pulse(input, changes).run(); });
    }

    if (remove) {
      changes.remove(remove === true ? truthy : remove);
    }

    if (insert) {
      changes.insert(insert);
    }

    if (toggle) {
      predicate = function(_) {
        for (key in toggle) {
          if (_[key] !== toggle[key]) return false;
        }
        return true;
      };

      if (input.value.filter(predicate).length) {
        changes.remove(predicate);
      } else {
        changes.insert(toggle);
      }
    }

    if (modify) {
      for (key in values) {
        changes.modify(modify, key, values[key]);
      }
    }

    return 1;
  };

  return fn;
}

export default function(view, spec) {
  return parse(spec, context(view, transforms, functions()));
}
<|endoftext|>


<commit_before>var
     bogart = require('bogart')
    ,fs     = require('fs')
    ,pug   = require('pug')
    ,path   = require('path')
    ,query  = require('./common').query
    ;

var render = function(view, opts) {
    opts = opts || {};

    opts.locals = opts.locals || {};

    var
    viewPath    = path.join('views/', view),
    layout      = opts.layout === undefined ? true : opts.layout;
    layout      = layout === true ? 'layout.pug' : layout;

    var renderedView = pug.compileFile(viewPath, opts)(opts.locals);

    if (layout) {
        opts.locals.body = renderedView;
        opts.layout = false;

        return render(layout, opts);
    }

    return renderedView;
};

var router = bogart.router();
router.get('/', function (req) {
    return query("SELECT hundred_block_location, description, COUNT(DISTINCT go_number) AS incident_count FROM crimes LEFT JOIN offense_descriptions ON crimes.offense_code = offense_descriptions.offense_code WHERE occurred_date > NOW() - INTERVAL '7 days 8 hours' AND NOT crimes.offense_code = 'X' GROUP BY hundred_block_location, crimes.offense_code, offense_descriptions.description ORDER By incident_count DESC, hundred_block_location").then(
        function (result) {
            return bogart.html(render('index.pug', {locals: result}));
        });
});
router.get('/drugs', function (req) {
    return query(
        "SELECT DISTINCT hundred_block_location, description, occurred_date, go_number FROM crimes LEFT JOIN offense_descriptions ON crimes.offense_code = offense_descriptions.offense_code WHERE occurred_date > NOW() - INTERVAL '2 months' AND crimes.offense_code LIKE '35__' ORDER BY occurred_date DESC").then(
            function (result) {
                return bogart.html(render('drugs.pug', {locals: result}));
            });
});
router.get('/liquor', function (req) {
    return query(
    "SELECT * FROM liquor_actions ORDER BY date DESC").then(
        function (result) {
            return bogart.html(render('liquor.pug', {locals: result}));
        });
});
router.get('/major', function (req) {
    return query(
        "SELECT DISTINCT hundred_block_location, description, occurred_date, go_number FROM crimes LEFT JOIN offense_descriptions ON crimes.offense_code = offense_descriptions.offense_code WHERE occurred_date > NOW() - INTERVAL '2 months' AND (crimes.offense_code LIKE '12__' OR crimes.offense_code LIKE '130_' OR crimes.offense_code LIKE '22__' OR crimes.offense_code LIKE '9__') ORDER BY occurred_date DESC").then(
            function (result) {
                return bogart.html(render('major.pug', {locals: result}));
            });
});
router.get('/main.css', function (req) {
    var css = fs.readFileSync('main.css', { encoding: 'utf8' });
    return {
        status: 200,
        headers: {
            'content-type': 'text/css',
            'content-length': css.length
        },
        body: css
    };
});

var app = bogart.app();
app.use(router);
app.start(process.env.PORT);
<commit_msg>Fix CSS route<commit_after>var
     bogart = require('bogart')
    ,fs     = require('fs')
    ,pug   = require('pug')
    ,path   = require('path')
    ,query  = require('./common').query
    ;

var render = function(view, opts) {
    opts = opts || {};

    opts.locals = opts.locals || {};

    var
    viewPath    = path.join('views/', view),
    layout      = opts.layout === undefined ? true : opts.layout;
    layout      = layout === true ? 'layout.pug' : layout;

    var renderedView = pug.compileFile(viewPath, opts)(opts.locals);

    if (layout) {
        opts.locals.body = renderedView;
        opts.layout = false;

        return render(layout, opts);
    }

    return renderedView;
};

var router = bogart.router();
router.get('/', function (req) {
    return query("SELECT hundred_block_location, description, COUNT(DISTINCT go_number) AS incident_count FROM crimes LEFT JOIN offense_descriptions ON crimes.offense_code = offense_descriptions.offense_code WHERE occurred_date > NOW() - INTERVAL '7 days 8 hours' AND NOT crimes.offense_code = 'X' GROUP BY hundred_block_location, crimes.offense_code, offense_descriptions.description ORDER By incident_count DESC, hundred_block_location").then(
        function (result) {
            return bogart.html(render('index.pug', {locals: result}));
        });
});
router.get('/drugs', function (req) {
    return query(
        "SELECT DISTINCT hundred_block_location, description, occurred_date, go_number FROM crimes LEFT JOIN offense_descriptions ON crimes.offense_code = offense_descriptions.offense_code WHERE occurred_date > NOW() - INTERVAL '2 months' AND crimes.offense_code LIKE '35__' ORDER BY occurred_date DESC").then(
            function (result) {
                return bogart.html(render('drugs.pug', {locals: result}));
            });
});
router.get('/liquor', function (req) {
    return query(
    "SELECT * FROM liquor_actions ORDER BY date DESC").then(
        function (result) {
            return bogart.html(render('liquor.pug', {locals: result}));
        });
});
router.get('/major', function (req) {
    return query(
        "SELECT DISTINCT hundred_block_location, description, occurred_date, go_number FROM crimes LEFT JOIN offense_descriptions ON crimes.offense_code = offense_descriptions.offense_code WHERE occurred_date > NOW() - INTERVAL '2 months' AND (crimes.offense_code LIKE '12__' OR crimes.offense_code LIKE '130_' OR crimes.offense_code LIKE '22__' OR crimes.offense_code LIKE '9__') ORDER BY occurred_date DESC").then(
            function (result) {
                return bogart.html(render('major.pug', {locals: result}));
            });
});
router.get('/main.css', function (req) {
    return bogart.promisify(fs.readFile)('main.css', 'utf-8').then(function (body) {
        return {
            status: 200,
            body: [body],
            headers: {'content-type': 'text/css', 'content-length': Buffer.byteLength(body, 'utf-8')}
        };
    });
});

var app = bogart.app();
app.use(router);
app.start(process.env.PORT);
<|endoftext|>


<commit_before>require('babel-register')({
  //only: ['./src/index.js', './src/Pipe.js'],
});
//require('babel-polyfill');
var WebMiddle = require('webmiddle');
<commit_msg>Cleanups<commit_after><|endoftext|>


<commit_before>"use strict";
var MONGODB_URL = process.env.MONGODB_URL || 'mongodb://mongo:27017/cloudlog';
var AMQP_URL = process.env.AMQP_URL || 'amqp://rabbitmq';
var HTTP_PORT = process.env.HTTP_PORT || 80;
var LOGIC_LOGFILE = process.env.LOGIC_LOGFILE || '/tmp/server-logic.log';
var OBSTORE_CONFIG = (process.env.OBSTORE_CONFIG && JSON.parse(process.env.OBSTORE_CONFIG)) || {
    provider: 'filesystem',
    root: '/var/lib/storage',
    container: 'cloudlog',
};

var express = require('express');
var morgan = require('morgan');

var Nodalion = require('nodalion');
var nodalionMongo = require('nodalion-mongo');
var nodalionHttp = require('nodalion-http');
var workQueue = require('nodalion-amqp');
require('nodalion-objstore').configure(OBSTORE_CONFIG);

var ns = Nodalion.namespace('/nodalion', ['defaultQueueDomain']);
var cl1 = Nodalion.namespace('/cl1', ['cl1']);
nodalionMongo.db(MONGODB_URL);

var nodalion = new Nodalion(__dirname + '/cedalion/cl1.cedimg', LOGIC_LOGFILE);

workQueue.connect(nodalion, AMQP_URL, ns.defaultQueueDomain());

var app = express();
app.use(morgan('combined'))
app.use(nodalionHttp.app(nodalion, cl1.cl1()));
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Unknown Error');
});
app.listen(HTTP_PORT);
console.log("Server listening on port " + HTTP_PORT);
<commit_msg>fixed the cl1.cedimg location<commit_after>"use strict";
var MONGODB_URL = process.env.MONGODB_URL || 'mongodb://mongo:27017/cloudlog';
var AMQP_URL = process.env.AMQP_URL || 'amqp://rabbitmq';
var HTTP_PORT = process.env.HTTP_PORT || 80;
var LOGIC_LOGFILE = process.env.LOGIC_LOGFILE || '/tmp/server-logic.log';
var OBSTORE_CONFIG = (process.env.OBSTORE_CONFIG && JSON.parse(process.env.OBSTORE_CONFIG)) || {
    provider: 'filesystem',
    root: '/var/lib/storage',
    container: 'cloudlog',
};

var express = require('express');
var morgan = require('morgan');

var Nodalion = require('nodalion');
var nodalionMongo = require('nodalion-mongo');
var nodalionHttp = require('nodalion-http');
var workQueue = require('nodalion-amqp');
require('nodalion-objstore').configure(OBSTORE_CONFIG);

var ns = Nodalion.namespace('/nodalion', ['defaultQueueDomain']);
var cl1 = Nodalion.namespace('/cl1', ['cl1']);
nodalionMongo.db(MONGODB_URL);

var nodalion = new Nodalion(__dirname + '/cedalion/cl1/cl1.cedimg', LOGIC_LOGFILE);

workQueue.connect(nodalion, AMQP_URL, ns.defaultQueueDomain());

var app = express();
app.use(morgan('combined'))
app.use(nodalionHttp.app(nodalion, cl1.cl1()));
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).send('Unknown Error');
});
app.listen(HTTP_PORT);
console.log("Server listening on port " + HTTP_PORT);
<|endoftext|>


<commit_before>const koa = require('koa');
const app = koa();
const bearsRouter = require(__dirname + '/routes/bears_routes');
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGOLAB_UR || 'mongodb://localhost/bears_app_dev');

app.use(bearsRouter.routes());
//route /api included in bears_routes.js file

var PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log('server up: ' + PORT));
//Run: mongod --dbpath=./db --smallfiles before server up
<commit_msg>fix the issue of typepo<commit_after>const koa = require('koa');
const app = module.exports = exports = koa();
const bearsRouter = require(__dirname + '/routes/bears_routes');
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGOLAB_URI || 'mongodb://localhost/bears_app_dev');

app.use(bearsRouter.routes());
//route /api included in bears_routes.js file

var PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log('server up: ' + PORT));
//Run: mongod --dbpath=./db --smallfiles before server up
<|endoftext|>


<commit_before>"use strict";

// Configuration
global.config = require("./config");

global.db = require("./databases/"+config.db_driver); // This is a bit of a hack and outdated way of doing things...

// Required node modules
var restify = require("restify");
var restifyOAuth2 = require("restify-oauth2");
var cluster = require('cluster');
var hooks = require("./hooks");

// Process variables

var server = restify.createServer({
	name: "Very Simple Application Analytics Server",
	version: "0.0.3",
	formatters: {
		"application/hal+json": function (req, res, body) {
			return res.formatters["application/json"](req, res, body);
		}
	}
});

var port = config.listen; // Default port to listen

if (process.argc >= 2) {
	port = parseInt(process.argv[2]); // Port can be also passed as an argument, this overrides config...
}

var RESOURCES = Object.freeze({
	INITIAL: "/",
	TOKEN: "/login",
	EVENT: "/event"
});

server.use(restify.authorizationParser());
server.use(restify.bodyParser({ mapParams: false }));
	restifyOAuth2.cc(server, { tokenEndpoint: RESOURCES.TOKEN, hooks: hooks });
server.get(RESOURCES.INITIAL, function (req, res) {
	var response = {
		_links: {
			self: { href: RESOURCES.INITIAL }
		}
	};

	if (req.clientId) {
		response._links["http://rel.example.com/event"] = { href: RESOURCES.EVENT };
	} else {
		response._links["oauth2-token"] = {
			href: RESOURCES.TOKEN,
			"grant-types": "client_credentials",
			"token-types": "bearer"
		};
	}

	res.contentType = "application/hal+json";
	res.send(response);
});

server.post(RESOURCES.EVENT, function (req, res) {
	if (!req.clientId) {
		return res.sendUnauthenticated();
	}
	var fields = [
		req.body.DeviceId,
		req.body.Description,
		req.body.ApiKey
	];
	var response = {
		"success": "event recorded successfully",
		_links: {
			self: { href: RESOURCES.EVENT },
			parent: { href: RESOURCES.INITIAL }
		}
	}
	db.createEvent(fields, function (err, result) {
		if (err) {
			response = {
				"error": "err",
				_links: {
					self: { href: RESOURCES.EVENT },
					parent: { href: RESOURCES.INITIAL }
				}
			}
		}
	});
	if (req.body.message_type === 'APPLICATION_EVENT_QUIT')
		hooks.invalidateClientToken(req.authorization.credentials);
	res.contentType = "application/hal+json";
	res.send(response);
});

// Adding error information...
process.on('uncaughtException', function (err) {
	console.log("UNCAUGHT EXCEPTION ");
	console.log("[Inside 'uncaughtException' event] " + err.stack || err.message);
});

// Clustering to utilize all CPU cores
if (cluster.isMaster) {

    // Fork workers
    for (var i = 0; i < config.workers; i++) {
        cluster.fork();
    }

    cluster.on('exit', function (worker, code, signal) {
    	console.log('worker ' + worker.process.pid + ' died');
    	cluster.fork();
    });
}
else {
    server.listen(port);
}<commit_msg>FIX: Kill worker on uncaughtException<commit_after>"use strict";

// Configuration
global.config = require("./config");

global.db = require("./databases/"+config.db_driver); // This is a bit of a hack and outdated way of doing things...

// Required node modules
var restify = require("restify");
var restifyOAuth2 = require("restify-oauth2");
var cluster = require('cluster');
var hooks = require("./hooks");

// Process variables

var server = restify.createServer({
	name: "Very Simple Application Analytics Server",
	version: "0.0.3",
	formatters: {
		"application/hal+json": function (req, res, body) {
			return res.formatters["application/json"](req, res, body);
		}
	}
});

var port = config.listen; // Default port to listen

if (process.argc >= 2) {
	port = parseInt(process.argv[2]); // Port can be also passed as an argument, this overrides config...
}

var RESOURCES = Object.freeze({
	INITIAL: "/",
	TOKEN: "/login",
	EVENT: "/event"
});

server.use(restify.authorizationParser());
server.use(restify.bodyParser({ mapParams: false }));
	restifyOAuth2.cc(server, { tokenEndpoint: RESOURCES.TOKEN, hooks: hooks });
server.get(RESOURCES.INITIAL, function (req, res) {
	var response = {
		_links: {
			self: { href: RESOURCES.INITIAL }
		}
	};

	if (req.clientId) {
		response._links["http://rel.example.com/event"] = { href: RESOURCES.EVENT };
	} else {
		response._links["oauth2-token"] = {
			href: RESOURCES.TOKEN,
			"grant-types": "client_credentials",
			"token-types": "bearer"
		};
	}

	res.contentType = "application/hal+json";
	res.send(response);
});

server.post(RESOURCES.EVENT, function (req, res) {
	if (!req.clientId) {
		return res.sendUnauthenticated();
	}
	var fields = [
		req.body.DeviceId,
		req.body.Description,
		req.body.ApiKey
	];
	var response = {
		"success": "event recorded successfully",
		_links: {
			self: { href: RESOURCES.EVENT },
			parent: { href: RESOURCES.INITIAL }
		}
	}
	db.createEvent(fields, function (err, result) {
		if (err) {
			response = {
				"error": "err",
				_links: {
					self: { href: RESOURCES.EVENT },
					parent: { href: RESOURCES.INITIAL }
				}
			}
		}
	});
	if (req.body.message_type === 'APPLICATION_EVENT_QUIT')
		hooks.invalidateClientToken(req.authorization.credentials);
	res.contentType = "application/hal+json";
	res.send(response);
});

// Adding error information output, and killing process when this happens.
process.on('uncaughtException', function (err) {
	console.log("UNCAUGHT EXCEPTION ");
	console.log("[Inside 'uncaughtException' event] " + err.stack || err.message);
	process.exit(1);
});

// Clustering to utilize all CPU cores
if (cluster.isMaster) {

    // Fork workers
    for (var i = 0; i < config.workers; i++) {
        cluster.fork();
    }

    cluster.on('exit', function (worker, code, signal) {
    	console.log('Worker ' + worker.process.pid + ' died');
    	console.log('Spawining new worker...');
    	cluster.fork();
    });
}
else {
    server.listen(port);
}<|endoftext|>


<commit_before>var socketIO = require('socket.io');
var app = require('./app');

app.set('port', process.env.PORT || 3000);

module.exports = function(callback) {
    var server = app.listen(app.get('port'), 'localhost', function(err) {
        callback(err, app.get('port'));
    });
    app.set('io', socketIO(server));
};
<commit_msg>Listen on 0.0.0.0 if production<commit_after>var socketIO = require('socket.io');
var app = require('./app');

app.set('port', process.env.PORT || 3000);

module.exports = function(callback) {
    var hostname = process.env.NODE_ENV === 'production' ? '0.0.0.0' : 'localhost';
    var server = app.listen(app.get('port'), hostname, function(err) {
        callback(err, app.get('port'));
    });
    app.set('io', socketIO(server));
};
<|endoftext|>