<commit_before>'use strict';

const Script = require('smooch-bot').Script;
const AndreasSefzig = "[AndreasSefzig] ";
const EmpfangsBot =   "[EmpfangsBot] ";
const BeratungsBot =  "[BeratungsBot] ";
const KreationsBot =  "[KreationsBot] ";
const TechnikBot =    "[TechnikBot] ";

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say(AndreasSefzig+'Nicht so schnell bitte...'),
        receive: () => 'processing'
    },

 // -------------------------
 // Start
 // -------------------------

 // 3 Welcome Whispers
 // https://app.smooch.io/apps/571777938ea8c63e0057cc1f/whispers

 // Übergabe an Register
    start: {
        receive: () => 'register'
    },

 // -------------------------
 // Register
 // -------------------------

    register: {
        receive: (bot, message) => {

            var befehl = message.text.trim().toUpperCase();
            var dann = "register";

         // -----------------
         // System
         // -----------------

            if  (~befehl.indexOf("--BEFEHLE"))        { bot.say(EmpfangsBot+'--empfang '
                                                              +'\n○ --kreation '
                                                              +'\n○ --beratung '
                                                              +'\n○ --technik '
                                                              +'\n○ --sefzig '); }

         // -----------------
         // Tests
         // -----------------

            if  (~befehl.indexOf("--JAVASCRIPT"))     { bot.say(EmpfangsBot+'[Javascript:test_alert]'); }
            if  (~befehl.indexOf("--VIDEO"))          { bot.say(EmpfangsBot+'[Youtube:u07XONlDwX8]'); }

         // -----------------
         // Vorlage
         // -----------------

            if  (~befehl.indexOf("--VORLAGE"))        { bot.say(EmpfangsBot+'Text: Vorlage.'); }

         // Register Antwort
            return bot.setProp('register', 'gesprochen')
            .then(() => dann);
        }
    },

 // -------------------------
 // Onboarding
 // -------------------------

    name: {

        receive: (bot, message) => {

            var antwort = message.text.trim().toUpperCase();
            var name_falsch = "";
            var dann = "";

            if (antwort == "--JA")   {

               bot.say(EmpfangsBot+'Ich kenne Sie nun als');
               name_falsch == "nein";
               dann = "register";

            }
            if (antwort == "--NEIN") {

               name_falsch == "ja";
               dann = "vorname";

            }
            if (antwort == "--BOT") {

               name_falsch == "";
               dann = "register";

            }

            return bot.setProp('name_falsch', name_falsch)
            .then(() => dann);
        }
    },

    vorname: {

        prompt: (bot) => bot.say(EmpfangsBot+'Wie heissen Sie mit Vornamen?'),

        receive: (bot, message) => {

            var vorname = message.text;

            return bot.setProp('vorname', vorname)
            .then(() => bot.say(EmpfangsBot+`${vorname}, prima.`))
            .then(() => 'nachname');

        }
    },

    nachname: {

        prompt: (bot) => bot.say(EmpfangsBot+'Und wie heissen Sie mit Nachnamen?'),

        receive: (bot, message) => {

            var nachname = message.text;
            bot.setProp('nachname', nachname)

            return bot.getProp('vorname')
            .then((vorname) => bot.say(EmpfangsBot+`Sie heissen ${vorname} ${nachname}, ist das richtig?`))
            .then((vorname) => bot.say(EmpfangsBot+`Bitte bestätigen Sie, indem Sie --ja oder --nein schreiben!`))
            .then(() => 'name');

        }
    },

 // -------------------------
 // Empfangs-Bot
 // -------------------------

    empfang: {

        receive: (bot, message) => {

         // Befehl normalisieren
            var befehl = message.text.trim().toUpperCase();

         // Nächster Schritt default
            var dann = "empfang";

         // Befehle
            if  (~befehl.indexOf("--BEFEHLE"))        { bot.say(EmpfangsBot +'--Empfang '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt'); }

            if ((~befehl.indexOf("--ZURÜCK")) ||
                (~befehl.indexOf("--ABBRECHEN")))     { bot.say(EmpfangsBot +'Bis später!');
                                                        dann = "register"; }

         // Inhalte
            if ((~befehl.indexOf("--BEFEHL")) ||
                (~befehl.indexOf("--BEFEHL")))        { bot.say(EmpfangsBot +'Text Befehl.');
                                                        bot.say(EmpfangsBot +'Text Befehl.'); }
            if  (~befehl.indexOf("--BEFEHL"))         { bot.say(EmpfangsBot +'Text Befehl.'); }
            if  (~befehl.indexOf("--BEFEHL"))         { bot.say(EmpfangsBot +'Text Befehl.'); }
            if  (~befehl.indexOf("--BEFEHL"))         { bot.say(EmpfangsBot +'Text Befehl.'); }
            if  (~befehl.indexOf("--BEFEHL"))         { bot.say(EmpfangsBot +'Text Befehl.'); }

         // Konversation fortführen
            return bot.setProp('empfang', 'gesprochen')
                .then(() => dann);

        }

    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<commit_msg>EmpfangsBot<commit_after>'use strict';

const Script = require('smooch-bot').Script;
const AndreasSefzig = "[AndreasSefzig] ";
const EmpfangsBot =   "[EmpfangsBot] ";
const BeratungsBot =  "[BeratungsBot] ";
const KreationsBot =  "[KreationsBot] ";
const TechnikBot =    "[TechnikBot] ";

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say(AndreasSefzig+'Nicht so schnell bitte...'),
        receive: () => 'processing'
    },

 // -------------------------
 // Start
 // -------------------------

 // 3 Welcome Whispers
 // https://app.smooch.io/apps/571777938ea8c63e0057cc1f/whispers

 // Übergabe an Register
    start: {
        receive: () => 'register'
    },

 // -------------------------
 // Register
 // -------------------------

    register: {
        receive: (bot, message) => {

            var befehl = message.text.trim().toUpperCase();
            var dann = "register";

         // -----------------
         // System
         // -----------------

            if  (~befehl.indexOf("--BEFEHLE"))        { bot.say(EmpfangsBot+'--empfang '
                                                              +'\n○ --kreation '
                                                              +'\n○ --beratung '
                                                              +'\n○ --technik '
                                                              +'\n○ --sefzig '); }

         // -----------------
         // Bots
         // -----------------

            if (~befehl.indexOf("--EMPFANG"))         { bot.say(LinkBot  +'Empfang 1');
                                                        bot.say(LinkBot  +'Empfang 2');
                                                        bot.say(LinkBot  +'Empfang 3');
                                                        dann = "empfang"; }

         // -----------------
         // Vorlage
         // -----------------

            if  (~befehl.indexOf("--VORLAGE"))        { bot.say(EmpfangsBot+'Text: Vorlage.'); }

         // Register Antwort
            return bot.setProp('register', 'gesprochen')
            .then(() => dann);
        }
    },

 // -------------------------
 // Empfangs-Bot
 // -------------------------

    empfang: {

        receive: (bot, message) => {

         // Befehl normalisieren
            var befehl = message.text.trim().toUpperCase();

         // Nächster Schritt default
            var dann = "empfang";

         // Befehle
            if  (~befehl.indexOf("--BEFEHLE"))        { bot.say(EmpfangsBot +'--Empfang '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt '
                                                              +'\n○ --Folgt'); }

            if ((~befehl.indexOf("--AUS")) ||
                (~befehl.indexOf("--ZURÜCK")) ||
                (~befehl.indexOf("--ABBRECHEN")))     { bot.say(EmpfangsBot +'Bis später!');
                                                        dann = "register"; }

         // Inhalte
            if ((~befehl.indexOf("--BEFEHL")) ||
                (~befehl.indexOf("--BEFEHL")))        { bot.say(EmpfangsBot +'Text Befehl.');
                                                        bot.say(EmpfangsBot +'Text Befehl.'); }
            if  (~befehl.indexOf("--BEFEHL"))         { bot.say(EmpfangsBot +'Text Befehl.'); }
            if  (~befehl.indexOf("--BEFEHL"))         { bot.say(EmpfangsBot +'Text Befehl.'); }
            if  (~befehl.indexOf("--BEFEHL"))         { bot.say(EmpfangsBot +'Text Befehl.'); }
            if  (~befehl.indexOf("--BEFEHL"))         { bot.say(EmpfangsBot +'Text Befehl.'); }

         // Konversation fortführen
            return bot.setProp('empfang', 'gesprochen')
                .then(() => dann);

        }

    },

 // -------------------------
 // Onboarding
 // -------------------------

    name: {

        receive: (bot, message) => {

            var antwort = message.text.trim().toUpperCase();
            var name_falsch = "";
            var dann = "";

            if (antwort == "--JA")   {

               bot.say(EmpfangsBot+'Ich kenne Sie nun als');
               name_falsch == "nein";
               dann = "register";

            }
            if (antwort == "--NEIN") {

               name_falsch == "ja";
               dann = "vorname";

            }
            if (antwort == "--BOT") {

               name_falsch == "";
               dann = "register";

            }

            return bot.setProp('name_falsch', name_falsch)
            .then(() => dann);
        }
    },

    vorname: {

        prompt: (bot) => bot.say(EmpfangsBot+'Wie heissen Sie mit Vornamen?'),

        receive: (bot, message) => {

            var vorname = message.text;

            return bot.setProp('vorname', vorname)
            .then(() => bot.say(EmpfangsBot+`${vorname}, prima.`))
            .then(() => 'nachname');

        }
    },

    nachname: {

        prompt: (bot) => bot.say(EmpfangsBot+'Und wie heissen Sie mit Nachnamen?'),

        receive: (bot, message) => {

            var nachname = message.text;
            bot.setProp('nachname', nachname)

            return bot.getProp('vorname')
            .then((vorname) => bot.say(EmpfangsBot+`Sie heissen ${vorname} ${nachname}, ist das richtig?`))
            .then((vorname) => bot.say(EmpfangsBot+`Bitte bestätigen Sie, indem Sie --ja oder --nein schreiben!`))
            .then(() => 'name');

        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then(() => 'finish');
        }
    }
});
<|endoftext|>


<commit_before>// pending connect exposing static.mime (not available in npm yet)
var mime = require('connect/node_modules/mime');
mime.define({ 'text/cache-manifest': ['appcache'] });

var connect = require('connect'),
    parse = require('url').parse,
    querystring = require('querystring').parse,
    sessions = { run: {}, log: {} },
    eventid = 0,
    uuid = require('node-uuid');

function remoteServer(app) {
  app.get('/remote/:id?', function (req, res, next) {
    var url = parse(req.url),
        query = querystring(url.query);

    // save a new session id - maybe give it a token back?
    // serve up some JavaScript
    var id = req.params.id || uuid();
    res.writeHead(200, {'Content-Type': 'text/javascript'});
    res.end((query.callback || 'callback') + '("' + id + '");');
  });

  app.get('/remote/:id/log', function (req, res) {
    var id = req.params.id;
    res.writeHead(200, {'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache'});
    res.write('eventId:0\n\n');

    sessions.log[id] = res;
    sessions.log[id].xhr = req.headers['x-requested-with'] == 'XMLHttpRequest';
  });

  app.post('/remote/:id/log', function (req, res) {
    // post made to send log to jsconsole
    var id = req.params.id;
    // passed over to Server Sent Events on jsconsole.com
    if (sessions.log[id]) {
      sessions.log[id].write('data: ' + req.body.data + '\neventId:' + (++eventid) + '\n\n');

      if (sessions.log[id].xhr) {
        sessions.log[id].end(); // lets older browsers finish their xhr request
      }
    }

    res.writeHead(200, { 'Content-Type' : 'text/plain' });
    res.end();
  });

  app.get('/remote/:id/run', function (req, res) {
    var id = req.params.id;
    res.writeHead(200, {'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache'});
    res.write('eventId:0\n\n');
    sessions.run[id] = res;
    sessions.run[id].xhr = req.headers['x-requested-with'] == 'XMLHttpRequest';
  });

  app.post('/remote/:id/run', function (req, res) {
    var id = req.params.id;

    if (sessions.run[id]) {
      sessions.run[id].write('data: ' + req.body.data + '\neventId:' + (++eventid) + '\n\n');

      if (sessions.run[id].xhr) {
        sessions.run[id].end(); // lets older browsers finish their xhr request
      }
    }
    res.writeHead(200, { 'Content-Type' : 'text/plain' });
    res.end();
  });
}

// connect.static.mime.define('text/cache-manifest', ['appcache']);

var server = connect.createServer(
  connect.bodyParser(),
  connect.logger(),
  connect.static(__dirname),
  connect.router(remoteServer)
);

console.log('Listening on ' + (process.ARGV[2] || 80));
server.listen(parseInt(process.ARGV[2]) || 80);
<commit_msg>0.6.0 support<commit_after>// pending connect exposing static.mime (not available in npm yet)
var mime = require('connect/node_modules/mime');
mime.define({ 'text/cache-manifest': ['appcache'] });

var connect = require('connect'),
    parse = require('url').parse,
    querystring = require('querystring').parse,
    sessions = { run: {}, log: {} },
    eventid = 0,
    uuid = require('node-uuid');

function remoteServer(app) {
  app.get('/remote/:id?', function (req, res, next) {
    var url = parse(req.url),
        query = querystring(url.query);

    // save a new session id - maybe give it a token back?
    // serve up some JavaScript
    var id = req.params.id || uuid();
    res.writeHead(200, {'Content-Type': 'text/javascript'});
    res.end((query.callback || 'callback') + '("' + id + '");');
  });

  app.get('/remote/:id/log', function (req, res) {
    var id = req.params.id;
    res.writeHead(200, {'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache'});
    res.write('eventId:0\n\n');

    sessions.log[id] = res;
    sessions.log[id].xhr = req.headers['x-requested-with'] == 'XMLHttpRequest';
  });

  app.post('/remote/:id/log', function (req, res) {
    // post made to send log to jsconsole
    var id = req.params.id;
    // passed over to Server Sent Events on jsconsole.com
    if (sessions.log[id]) {
      sessions.log[id].write('data: ' + req.body.data + '\neventId:' + (++eventid) + '\n\n');

      if (sessions.log[id].xhr) {
        sessions.log[id].end(); // lets older browsers finish their xhr request
      }
    }

    res.writeHead(200, { 'Content-Type' : 'text/plain' });
    res.end();
  });

  app.get('/remote/:id/run', function (req, res) {
    var id = req.params.id;
    res.writeHead(200, {'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache'});
    res.write('eventId:0\n\n');
    sessions.run[id] = res;
    sessions.run[id].xhr = req.headers['x-requested-with'] == 'XMLHttpRequest';
  });

  app.post('/remote/:id/run', function (req, res) {
    var id = req.params.id;

    if (sessions.run[id]) {
      sessions.run[id].write('data: ' + req.body.data + '\neventId:' + (++eventid) + '\n\n');

      if (sessions.run[id].xhr) {
        sessions.run[id].end(); // lets older browsers finish their xhr request
      }
    }
    res.writeHead(200, { 'Content-Type' : 'text/plain' });
    res.end();
  });
}

// connect.static.mime.define('text/cache-manifest', ['appcache']);

var server = connect.createServer(
  connect.bodyParser(),
  connect.logger(),
  connect.static(__dirname),
  connect.router(remoteServer)
);

console.log('Listening on ' + (process.argv[2] || 80));
server.listen(parseInt(process.argv[2]) || 80);
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var newUser = require("./db");
var nlp = require("./nlp");
var pushConv = require("./push");

const scriptRules = require('./script.json');

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello!  I\'m A16, the Agile2016 EventBot Concierge.  To find out what I can help you with type MENU for options or KEY for Keywords.')
                .then(() => 'speak');
        }
    },

    speak: {
        receive: (bot, message) => {
            console.log("===bot user ");
            console.log("===receive step 1",message);
            let upperText = message.text.trim().toUpperCase();

            var botUser = bot.userId;
            var authUsers = ['a30fa820d0a0f0216fa26070'];

            //Undone - currently only creates new user
            //needs to create conversation record and update it throughout the prcoess
            console.log("===before db",bot);
            newUser(bot)
              .then (console.log("===after db", bot.userId))

              //undone - test for userid and or message
              //look at stacking messages in DB and looking them up
              //end conversation and do not send a response to the user that kicked things off
              //
              if (authUsers.indexOf(bot.userId) !== -1) {
                console.log("===before push",bot);
                //pushConv(bot);
              }

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "-SUPPORT":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    case "-ACE":
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            console.log("===receive step 2",upperText);

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                var promises = [];
                var source;
                var fulfillmentSpeech;
                var simplified;
                promises.push(nlp(message.text, bot.userId));

                Q.all(promises).then(function(responses) {
                    // response is the JSON from API.ai
                    responses.forEach(function(response) {
                        //console.log("===in Q.all");
                        console.log("===received result from API.ai",response);
                        source = response.result.source;
                        if (source && source !== 'agent')
                        {
                            fulfillmentSpeech = response.result.fulfillment.speech;
                            simplified = response.result.parameters.simplified;
                        }
                        console.log("source: ", source);
                        console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                        console.log("simplified: ", simplified);

                        respondMessage(source, fulfillmentSpeech, simplified);
                    });
                }, function(error) {
                    console.log("===Q all error ", error);
                });
                //return next();

            }

            function respondMessage(source, fulfillmentSpeech, simplified)
            {
                console.log("source: ", source);
                console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                console.log("simplified: ", simplified);
                console.log("===receive step 3",upperText);

              if (source != 'agent')
                {
                    console.log("===source is ", source);
                    if (fulfillmentSpeech)
                    {
                        console.log("fulfillmentSpeech is: ", fulfillmentSpeech);
                        return bot.say(fulfillmentSpeech).then(() => 'speak');
                    }
                    else if (simplified)
                    {
                        console.log("simplified is: ", simplified);
                        upperText = simplified.toUpperCase();
                    }
                }
                if (!_.has(scriptRules, upperText)) {
                    console.log("===no rule", upperText);
                    return bot.say(`I'm sorry that is not something I know.  Type MENU or KEY for a list of things I can help you with.`).then(() => 'speak');
                }

                console.log("===receive step 3",upperText);

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                bot.userId = botUser;

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log("=== p line",line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });
                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<commit_msg>test msg<commit_after>'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
var pg = require('pg');
var Q = require("q");
var request = require("request");
var newUser = require("./db");
var nlp = require("./nlp");
var pushConv = require("./push");

const scriptRules = require('./script.json');

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

module.exports = new Script({
    processing: {
        //prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello!  I\'m A16, the Agile2016 EventBot Concierge.  To find out what I can help you with type MENU for options or KEY for Keywords.')
                .then(() => 'speak');
        }
    },

    speak: {
        receive: (bot, message) => {
            console.log("===bot user ");
            console.log("===receive step 1",message);
            let upperText = message.text.trim().toUpperCase();

            var botUser = bot.userId;
            var authUsers = ['a30fa820d0a0f0216fa26070'];

            //Undone - currently only creates new user
            //needs to create conversation record and update it throughout the prcoess
            console.log("===before db",bot);
            newUser(bot)
              .then (console.log("===after db", bot.userId))

              //undone - test for userid and or message
              //look at stacking messages in DB and looking them up
              //end conversation and do not send a response to the user that kicked things off
              //
              if (authUsers.indexOf(bot.userId) !== -1) {
                if (message.substr(0,5) == '/msg ') {
                  console.log("===before push",bot);
                //pushConv(bot);
                }
              }

            function updateSilent() {
                switch (upperText) {
                    case "CONNECT ME":
                        return bot.setProp("silent", true);
                    case "-SUPPORT":
                        return bot.setProp("silent", true);
                    case "DISCONNECT":
                        return bot.setProp("silent", false);
                    case "-ACE":
                        return bot.setProp("silent", false);
                    default:
                        return Promise.resolve();
                }
            }

            console.log("===receive step 2",upperText);

            function getSilent() {
                return bot.getProp("silent");
            }

            function processMessage(isSilent) {
                if (isSilent) {
                    return Promise.resolve("speak");
                }

                var promises = [];
                var source;
                var fulfillmentSpeech;
                var simplified;
                promises.push(nlp(message.text, bot.userId));

                Q.all(promises).then(function(responses) {
                    // response is the JSON from API.ai
                    responses.forEach(function(response) {
                        //console.log("===in Q.all");
                        console.log("===received result from API.ai",response);
                        source = response.result.source;
                        if (source && source !== 'agent')
                        {
                            fulfillmentSpeech = response.result.fulfillment.speech;
                            simplified = response.result.parameters.simplified;
                        }
                        console.log("source: ", source);
                        console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                        console.log("simplified: ", simplified);

                        respondMessage(source, fulfillmentSpeech, simplified);
                    });
                }, function(error) {
                    console.log("===Q all error ", error);
                });
                //return next();

            }

            function respondMessage(source, fulfillmentSpeech, simplified)
            {
                console.log("source: ", source);
                console.log("fulfillmentSpeech: ", fulfillmentSpeech);
                console.log("simplified: ", simplified);
                console.log("===receive step 3",upperText);

              if (source != 'agent')
                {
                    console.log("===source is ", source);
                    if (fulfillmentSpeech)
                    {
                        console.log("fulfillmentSpeech is: ", fulfillmentSpeech);
                        return bot.say(fulfillmentSpeech).then(() => 'speak');
                    }
                    else if (simplified)
                    {
                        console.log("simplified is: ", simplified);
                        upperText = simplified.toUpperCase();
                    }
                }
                if (!_.has(scriptRules, upperText)) {
                    console.log("===no rule", upperText);
                    return bot.say(`I'm sorry that is not something I know.  Type MENU or KEY for a list of things I can help you with.`).then(() => 'speak');
                }

                console.log("===receive step 3",upperText);

                var response = scriptRules[upperText];
                var lines = response.split('\n');

                bot.userId = botUser;

                var p = Promise.resolve();
                _.each(lines, function(line) {
                    line = line.trim();
                    p = p.then(function() {
                        console.log("=== p line",line);
                        return wait(50).then(function() {
                            return bot.say(line);
                        });
                    });
                });
                return p.then(() => 'speak');
            }

            return updateSilent()
                .then(getSilent)
                .then(processMessage);
        }
    }
});
<|endoftext|>


<commit_before>'use strict';

const restify = require('restify');

// Routes
const action = require('./routes/action');

let server = restify.createServer();
server.use(restify.bodyParser());
server.post('/action/:action_name', action.post);

server.listen(8080, function() {
  console.log('%s listening at %s', server.name, server.url);
});
<commit_msg>Must bind  for heroku<commit_after>'use strict';

const restify = require('restify');

// Routes
const action = require('./routes/action');

let server = restify.createServer();
server.use(restify.bodyParser());
server.post('/action/:action_name', action.post);

server.listen((process.env.PORT || 8080), function() {
  console.log('%s listening at %s', server.name, server.url);
});
<|endoftext|>


<commit_before>(function($){
  $.fn.vals = function(){
    if(this.attr('data-list')){
      var vals = [];
      $('[name='+ this.attr('id')+']').each(function(i){ vals[i] = $(this).val() });
      return vals.join();
    } else
      return $.fn.val.apply(this, arguments);
    }
})(window.jQuery || window.Zepto);

var msg = 0;
var ws;
var utf8 = {};

function addStatus(text){
    var date = new Date();
    document.getElementById('n2ostatus').innerHTML =
    document.getElementById('n2ostatus').innerHTML + "E> " + text + "
";
}

utf8.toByteArray = function(str) {
    var byteArray = [];
    for (var i = 0; i < str.length; i++)
        if (str.charCodeAt(i) <= 0x7F)
            byteArray.push(str.charCodeAt(i));
        else {
            var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');
            for (var j = 0; j < h.length; j++)
                byteArray.push(parseInt(h[j], 16));
        }
    return byteArray;
};

function WebSocketsInit(){
    if ("MozWebSocket" in window) { WebSocket = MozWebSocket; }
    if ("WebSocket" in window) {
        ws = new WebSocket("ws://"+window.location.hostname+
                            ":8000"+//window.location.port+
                   "/ws"+window.location.pathname+
                                window.location.search);
        initialized = false;
        ws.onopen = function() { if (!initialized) { ws.send(['N2O',TransitionProcess]); initialized = true; } };
        ws.onmessage = function (evt) {
            msg = evt.data;
            var actions = msg;//Bert.decodebuf(msg);;
//            addStatus("Received: '" + actions + "'");
            eval(actions);
        };
        ws.onclose = function() { addStatus("websocket was closed"); };
    } else {
        addStatus("sorry, your browser does not support websockets.");
    }
}

WebSocketsInit();
<commit_msg>fix samples<commit_after>(function($){
  $.fn.vals = function(){
    if(this.attr('data-list')){
      var vals = [];
      $('[name='+ this.attr('id')+']').each(function(i){ vals[i] = $(this).val() });
      return vals.join();
    } else
      return $.fn.val.apply(this, arguments);
    }
})(window.jQuery || window.Zepto);

var msg = 0;
var ws;
var utf8 = {};

function addStatus(text){
    var date = new Date();
    document.getElementById('n2ostatus').innerHTML =
    document.getElementById('n2ostatus').innerHTML + "E> " + text + "
";
}

utf8.toByteArray = function(str) {
    var byteArray = [];
    for (var i = 0; i < str.length; i++)
        if (str.charCodeAt(i) <= 0x7F)
            byteArray.push(str.charCodeAt(i));
        else {
            var h = encodeURIComponent(str.charAt(i)).substr(1).split('%');
            for (var j = 0; j < h.length; j++)
                byteArray.push(parseInt(h[j], 16));
        }
    return byteArray;
};

function WebSocketsInit(){
    if ("MozWebSocket" in window) { WebSocket = MozWebSocket; }
    if ("WebSocket" in window) {
        ws = new WebSocket("ws://"+window.location.hostname+
                            ":8000"+//window.location.port+
                   "/ws"+window.location.pathname+
                                window.location.search);
        initialized = false;
        ws.onopen = function() { if (!initialized) { ws.send(['N2O',TransitionProcess]); initialized = true; } };
        ws.onmessage = function (evt) {
            msg = evt.data;
            var actions = msg;//Bert.decodebuf(msg);;
            addStatus("Received: '" + actions + "'");
            eval(actions);
        };
        ws.onclose = function() { addStatus("websocket was closed"); };
    } else {
        addStatus("sorry, your browser does not support websockets.");
    }
}

WebSocketsInit();
<|endoftext|>


<commit_before>require('riot');

var Router = function(routes) {
  this._registeredObservers = [];
  this._routes = routes;

  riot.route.stop();
  riot.route.start();
  riot.route(this._router.bind(this));
  riot.route.exec();
  riot.router = this;
};

Router.prototype.registerObserver = function(el) {
  this._registeredObservers.push(el);
};

Router.prototype._matchTargetSegmentToRouteName = function(targetSegment, routeName) {
  if (targetSegment == routeName) {
    return true;
  } else if (routeName[0] == ':') {
    return 'symbol';
  } else {
    return false;
  }
};

// Recursive function for matching paths to routes
Router.prototype._matchRoute = function(segments, depth, routes) {
  var targetSegment = segments[depth];
  var params = {};

  for (var routeName in routes) {
    if (routes.hasOwnProperty(routeName)) {
      // If the segment at the current level matches a route on that level,
      // try to resolve the route
      if(this._matchTargetSegmentToRouteName(targetSegment, routeName)) {
        // Extract params from path segments
        if (this._matchTargetSegmentToRouteName(targetSegment, routeName) == 'symbol') {
          params[routeName.substr(1)] = targetSegment;
        }

        // A function means that we can resolve the route
        if(typeof(routes[routeName]) == 'function') {
          return {params: params, routeFunction: routes[routeName], matched: true};
        // An array means that we resolve the route with the function if the
        // requested path ends here or we need to go deeper into subroutes
        } else if (routes[routeName] && routes[routeName].constructor === Array) {
          if (segments.length > depth + 1) {
            return this._matchRoute(segments, depth + 1, routes[routeName][1])
          } else {
            return {params: params, routeFunction: routes[routeName][0], matched: true};
          }
        // An object means that we need to go into subroutes
        } else if (segments.length > depth + 1) {
          return this._matchRoute(segments, depth + 1, routes[routeName]);
        // Only accept functions, arrays, and objects
        } else {
          return {params: params, routeFunction: undefined, matched: false};
        }
      }
    }
  }

  // If matching fails, fall back to catchall
  return {params: params, routeFunction: routes['*'] || undefined, matched: false};
};

Router.prototype._notifyRegisteredObservers = function(path, params) {
  this._registeredObservers.forEach(function(observer, i, observers) {
    observer.trigger(path, params);
  })
};

Router.prototype._router = function() {
  // Fancy code to avoid killing arguments optimization
  // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
  var pathSegments = new Array(arguments.length);
  for(var i = 0; i < pathSegments.length; ++i) {
    pathSegments[i] = arguments[i];
  }
  var routeInfo = this._matchRoute(pathSegments, 0, this._routes);
  var path = '/' + pathSegments.join('/');

  if (routeInfo && routeInfo.routeFunction) {
    var routeFunction = routeInfo.routeFunction;
    var params = routeInfo.params;

    routeFunction(path, params);
    if(routeInfo.matched) {
      this._notifyRegisteredObservers('routeMatch', path, params)
    } else {
      this._notifyRegisteredObservers('routeFallback', path, params)
    }
  } else {
    console.error('Failed to find route for path "' + path + '".');
    this._notifyRegisteredObservers('routeFailure', path, null)
  }
};

module.exports = Router;
<commit_msg>Simplified subroute index route processing<commit_after>require('riot');

var Router = function(routes) {
  this._registeredObservers = [];
  this._routes = routes;

  riot.route.stop();
  riot.route.start();
  riot.route(this._router.bind(this));
  riot.route.exec();
  riot.router = this;
};

Router.prototype.registerObserver = function(el) {
  this._registeredObservers.push(el);
};

Router.prototype._matchTargetSegmentToRouteName = function(targetSegment, routeName) {
  if (targetSegment == routeName) {
    return true;
  } else if (routeName[0] == ':') {
    return 'symbol';
  } else {
    return false;
  }
};

// Recursive function for matching paths to routes
Router.prototype._matchRoute = function(segments, depth, routes) {
  var targetSegment = segments[depth];
  var params = {};

  for (var routeName in routes) {
    if (routes.hasOwnProperty(routeName)) {
      // If the segment at the current level matches a route on that level,
      // try to resolve the route
      if(this._matchTargetSegmentToRouteName(targetSegment, routeName)) {
        // Extract params from path segments
        if (this._matchTargetSegmentToRouteName(targetSegment, routeName) == 'symbol') {
          params[routeName.substr(1)] = targetSegment;
        }

        // A function means that we can resolve the route
        if(typeof(routes[routeName]) == 'function') {
          return {params: params, routeFunction: routes[routeName], matched: true};
        // An object means that we need to go into subroutes
        } else if (segments.length > depth + 1) {
          return this._matchRoute(segments, depth + 1, routes[routeName]);
        // Only accept functions, arrays, and objects
        } else {
          return {params: params, routeFunction: undefined, matched: false};
        }
      }
    }
  }

  // If matching fails, fall back to catchall
  return {params: params, routeFunction: routes['*'] || undefined, matched: false};
};

Router.prototype._notifyRegisteredObservers = function(path, params) {
  this._registeredObservers.forEach(function(observer, i, observers) {
    observer.trigger(path, params);
  })
};

Router.prototype._router = function() {
  // Fancy code to avoid killing arguments optimization
  // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
  var pathSegments = new Array(arguments.length);
  for(var i = 0; i < pathSegments.length; ++i) {
    pathSegments[i] = arguments[i];
  }
  // Add trailing '' if it doesn't exist yet so that index routes in subroutes
  // get processed
  if (pathSegments.length > 1) {
    pathSegments.push('');
  }
  var routeInfo = this._matchRoute(pathSegments, 0, this._routes);
  var path = '/' + pathSegments.join('/');

  if (routeInfo && routeInfo.routeFunction) {
    var routeFunction = routeInfo.routeFunction;
    var params = routeInfo.params;

    routeFunction(path, params);
    if(routeInfo.matched) {
      this._notifyRegisteredObservers('routeMatch', path, params)
    } else {
      this._notifyRegisteredObservers('routeFallback', path, params)
    }
  } else {
    console.error('Failed to find route for path "' + path + '".');
    this._notifyRegisteredObservers('routeFailure', path, null)
  }
};

module.exports = Router;
<|endoftext|>


<commit_before>// App
var express = require('express');

// Sessions
var session = require('express-session');
// var cookieParser = require('cookie-parser');

// Handles auth signin and signout
var passport = require('passport');

// Flash to send messages to client
var flash = require('connect-flash');

// Body parser parses xhr request data to req.body for easy usage
var bodyParser = require('body-parser');

// Use Path to locate static assets and config files
var path = require('path');

// ENV
var env = process.env.NODE_ENV || 'dev';

// For Route Logging
var morgan = require('morgan');

// Set PORT based on environment Production or local
var PORT = process.env.PORT || 3000;

// SESSION OPTIONS under SESSION managment
var sessionOptions = {
  secret: 'surehopethecanadianslikethis',
  resave: false,
  saveUninitialized: false
};

// Initialize EXPRESS APP -- Was going to use basic http routing but Express is faster to setup --
var app = express();

// Import and run PASSPORT CONFIG
require('./server/config/passport')(passport);

// ## DEV ##

if(env === 'dev') {
  // Asset compiler and middleware for Express compatability
  var webpack = require('webpack');
  var webpackHotMiddleware = require('webpack-hot-middleware');
  var webpackDevMiddleware = require('webpack-dev-middleware');
  var webpackConfig = require('./webpack.dev.config');

  var compiler = webpack(webpackConfig);

  app.use(webpackHotMiddleware(compiler));

  app.use(webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    stats: { colors: true }
  }));

  // Log routing to console
  app.use(morgan('dev'));
} else {
  // ## PUBLIC STATIC folder client will read from in production ##

  // Set static directory to public which will be compiled by Webpack

  app.use(express.static(path.join(__dirname, 'public')));
}

// ## XHR managment ##

// Handle body parsing for xhr requests from app -- mostlikely Game data and such
app.use(bodyParser.json());

// If there were more config I need to pass to BODYPARSER I would move it to an easier to see variable
app.use(bodyParser.urlencoded({ extended: false }));

// ## VIEW ENGINE ##
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'server/views'));

// ## Session management ##

// Use cookie parser to parse cookise for express-session
// app.use(cookieParser());

// Set express-session secret with SESSION OPTIONS
app.use(session(sessionOptions));

// Initialize PASSPORT
app.use(passport.initialize());

// Take over session management from EXPRESS SESSION
app.use(passport.session());

// Flash for messages sent from server
app.use(flash())

// Here I run the exported function from the routing section of the server folder and pass it the EXPRESS ROUTER and the configured PASSPORT variable for authentication
require('./server/routes')(app, passport);

// ## SOCKETS ##

// SocketIo for WebSockets
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
// Set up initial number of rooms
var roomNum = 1;

io.on('connection', function(client) {
  console.log('Client -- %s -- connected to the server', client.id);
  if(io.nsps['/'].adapter.rooms['room-'+roomNum] && io.nsps['/'].adapter.rooms['room-'+roomNum].length === 2) {
    // Add room so this means 2 per room
    roomNum++;
  }

  var nsp = io.of('/room-'+roomNum);
  console.log('joining room no. '+roomNum)
  client.join('room-'+roomNum);

  io.sockets.in('room-'+roomNum).emit('connectToRoom', roomNum);

  client.on('disconnect', function() {
    io.sockets.in('room-'+roomNum).emit('playerDisconnect');
  })
})

// Start server listening on the PORT variable
server.listen(PORT);
<commit_msg>so many bugs baby<commit_after>// App
var express = require('express');

// Sessions
var session = require('express-session');
// var cookieParser = require('cookie-parser');

// Handles auth signin and signout
var passport = require('passport');

// Flash to send messages to client
var flash = require('connect-flash');

// Body parser parses xhr request data to req.body for easy usage
var bodyParser = require('body-parser');

// Use Path to locate static assets and config files
var path = require('path');

// ENV
var env = process.env.NODE_ENV || 'dev';

// Set PORT based on environment Production or local
var PORT = process.env.PORT || 3000;

// SESSION OPTIONS under SESSION managment
var sessionOptions = {
  secret: 'surehopethecanadianslikethis',
  resave: false,
  saveUninitialized: false
};

// Initialize EXPRESS APP -- Was going to use basic http routing but Express is faster to setup --
var app = express();

// Import and run PASSPORT CONFIG
require('./server/config/passport')(passport);

// ## DEV ##

if(env === 'dev') {
  // Asset compiler and middleware for Express compatability
  // For Route Logging
  var morgan = require('morgan');
  var webpack = require('webpack');
  var webpackHotMiddleware = require('webpack-hot-middleware');
  var webpackDevMiddleware = require('webpack-dev-middleware');
  var webpackConfig = require('./webpack.dev.config');

  var compiler = webpack(webpackConfig);

  app.use(webpackHotMiddleware(compiler));

  app.use(webpackDevMiddleware(compiler, {
    publicPath: webpackConfig.output.publicPath,
    stats: { colors: true }
  }));

  // Log routing to console
  app.use(morgan('dev'));
} else {
  // ## PUBLIC STATIC folder client will read from in production ##

  // Set static directory to public which will be compiled by Webpack

  app.use(express.static(path.join(__dirname, 'public')));
}

// ## XHR managment ##

// Handle body parsing for xhr requests from app -- mostlikely Game data and such
app.use(bodyParser.json());

// If there were more config I need to pass to BODYPARSER I would move it to an easier to see variable
app.use(bodyParser.urlencoded({ extended: false }));

// ## VIEW ENGINE ##
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'server/views'));

// ## Session management ##

// Use cookie parser to parse cookise for express-session
// app.use(cookieParser());

// Set express-session secret with SESSION OPTIONS
app.use(session(sessionOptions));

// Initialize PASSPORT
app.use(passport.initialize());

// Take over session management from EXPRESS SESSION
app.use(passport.session());

// Flash for messages sent from server
app.use(flash())

// Here I run the exported function from the routing section of the server folder and pass it the EXPRESS ROUTER and the configured PASSPORT variable for authentication
require('./server/routes')(app, passport);

// ## SOCKETS ##

// SocketIo for WebSockets
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
// Set up initial number of rooms
var roomNum = 1;

io.on('connection', function(client) {
  console.log('Client -- %s -- connected to the server', client.id);
  if(io.nsps['/'].adapter.rooms['room-'+roomNum] && io.nsps['/'].adapter.rooms['room-'+roomNum].length === 2) {
    // Add room so this means 2 per room
    roomNum++;
  }

  var nsp = io.of('/room-'+roomNum);
  console.log('joining room no. '+roomNum)
  client.join('room-'+roomNum);

  io.sockets.in('room-'+roomNum).emit('connectToRoom', roomNum);

  client.on('disconnect', function() {
    io.sockets.in('room-'+roomNum).emit('playerDisconnect');
  })
})

// Start server listening on the PORT variable
server.listen(PORT);
<|endoftext|>


<commit_before>'use strict';

var config=require('../../configs');
var railways=require('../../services/railwayapi/apiParser');

exports.handlePNRStatusRequest=function(intent, session, response) {
    //intent.slots.Train.value;

    railways.getJsonPNRstatus(intent.slots.pnrNumber.value, function (events){

    	// Create speech output
	    var speechOutput =  events;
	    speechOutput['speech']=speechOutput['speech'];
	    //"The correct train name recieved: " + intent.slots.Train.value;

	    if(speechOutput['heading']!=null)
		{
			response.tellWithCard(speechOutput['speech'], speechOutput['heading'] , speechOutput['status']);
		}
		else
		{
		    response.tell(speechOutput['speech']);
		}
    });

};

<commit_msg>testing for api exhaustion<commit_after>'use strict';

var config=require('../../configs');
var railways=require('../../services/railwayapi/apiParser');

exports.handlePNRStatusRequest=function(intent, session, response) {
    //intent.slots.Train.value;

    railways.getJsonPNRstatus(intent.slots.pnrNumber.value, function (events){

    	// Create speech output
	    var speechOutput =  events;
	    speechOutput['speech']=speechOutput['speech'];
	    //"The correct train name recieved: " + intent.slots.Train.value;
	    if (speechOutput['status']==null)
               {
                  railways.getJsonPNRstatus(intent.slots.pnrNumber.value, function (events){

                  // Create speech output
                  var speechOutput =  events;
                  speechOutput['speech']=speechOutput['speech'];
                  //"The correct train name recieved: " + intent.slots.Train.value;

	          if(speechOutput['heading']!=null)
	         	{
			response.tellWithCard(speechOutput['speech'], speechOutput['heading'] , speechOutput['status']);
		        }
		   else
		     {
		      response.tell(speechOutput['speech']);
		     }
                 });
            }
         else if(speechOutput['heading']!=null)
                {
                        response.tellWithCard(speechOutput['speech'], speechOutput['heading'] , speechOutput['status']);
                }
                else
                {
                    response.tell(speechOutput['speech']);
                }
    });

};

<|endoftext|>


<commit_before>/*
//1 get user profile
//2 get rit of beebop error
//3 click more buttons
//4 write json for hypo
*/

'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >= 8 && myDate.getHours() <=12 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(
                              function updateUser() {
                                givenName: 'New',
                                surname: 'Name'
                              })
        .then(() => 'selecteerHypotheek');
    }
},

speak: {
          receive: (bot, message) => {

              const upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  /*  CREATE EXTRA JSON FILE FOR HYPO AND INCLUDE IT */
                  if (!_.has(scriptRules, upperText)) {
                      return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)').then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters Hypotheek':
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'woningType')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja, dat wil ik wel':
            return bot.say(`👍 Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, dat hoeft niet':
              receive: () => 'bye'
              break;
          default:
            receive => 'processing'
            break;
      }
    }
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const email=message.text;
          return bot.setProp('email', email)
              .then(()  => bot.say(`Ok - ✉  dan hou ik je via ${email} op de hoogte.`))
              .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekStarter: {
    receive: () => 'askName'
},

hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

woningType: {
  receive: (bot, message) => {
    switch(message.text) {
        case '🏬 Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case '🏠 Huis':
          return bot.say(`Leuk`)
          .then(() => 'vervolgVragen')
          break;
    case '📭 Vakantiewoning':
          return bot.say(`Gezellig`)
          .then(() => 'vervolgVragen')
          break;
      default:
        receive => 'processing'
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say(`Hoe heet je eigelijk? 😋`),
          receive: (bot, message) => {
              const Name = message.text;
              return bot.setProp('Name', Name)
                  .then(() => bot.say(`Hoi ${Name}. 📋 Ik heb nog wat vragen voor je om verder te kunnen.`))
                  .then(() => 'processing')
            }
},

lastCheck: {
    prompt: (bot) => bot.say(' Is er nog iets waar ik  je bij kan helpen?  🔶  %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ik zoek meer informatie':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

meerInfo: {
  prompt: (bot) => bot.say('bestand'),
   receive: () => 'processing'
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => 'pri'
// },

finish: {
receive: () => 'finish'
}
});
<commit_msg>av<commit_after>/*
//1 get user profile
//2 get rit of beebop error
//3 click more buttons
//4 write json for hypo
*/

'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 8 )
{
  groet = "Goeiemorgen 🌝.  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else
if ( myDate.getHours() >= 8 && myDate.getHours() <=12 )
{
  groet = "Goeiemorgen 🌝 ";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag 🌞";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17&& myDate.getHours() <= 20 )
{
groet = "Goedenavond 🌙";
}
else
if (myDate.getHours() > 20  || myDate.getHours() <= 24 )
{
  groet = "Goedenavond 🌙  Bedankt voor je bezoek maar op dit moment is Independer echter gesloten. 🕘 Uiteraard kun je met onze IndyBot verder praten maar er is helaas niemand die jouw vraag specifiek kan beantwoorden. Je kan je vraag ook doormailen 📩 naar info@independer. Dan komt het altijd goed.";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom. ";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
prompt: (bot) => bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}... Wat voor soort hypotheek zoek je? `)
        .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
        .then(() => bot.say(`%[Starters Hypotheek](postback:hypotheektype_starter)`))
        .then(() => bot.say (`%[Nieuwe hypotheek](postback:hypotheektype_nieuw) `))
        .then(() => bot.say (`%[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`))
        .then(
                              => function updateUser() {
                                givenName: 'New',
                                surname: 'Name'
                              })
        .then(() => 'selecteerHypotheek');
    }
},

speak: {
          receive: (bot, message) => {

              const upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  /*  CREATE EXTRA JSON FILE FOR HYPO AND INCLUDE IT */
                  if (!_.has(scriptRules, upperText)) {
                      return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)').then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
},

selecteerHypotheek: {
    receive: (bot, message) => {
      switch(message.text) {
      case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => 'askName')
          break;
      case 'Starters Hypotheek':
          return bot.say(`Wat voor type woning zoek je? `)
          .then(() => bot.say(`%[🏬 Appartement](postback:hypotheekkeuze_appartement) %[🏠 Huis](postback:hypotheekkeuze_huis) %[📭 Vakantiewoning](postback:hypotheekkeuze_vakantiewoning)`))
          .then(() => 'woningType')
              break;
        case 'Nieuwe hypotheek':
          return bot.say(`😞 Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[💼 Zoek Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/jelocatie.aspx)`))
            .then(() => 'finish')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`😟 Het spijt me maar op dit moment biedt Independer alleen  Starters een hypotheek.`)
          .then(()=> bot.say(`Als het allemaal wel zo ver is, wil je dan een update ontvangen? %[Ja, dat wil ik wel](postback:update_ja) %[Nee, dat hoeft niet](postback:update_nee)`))
            .then(() => 'updateOntvangen')
          break;
        default:
          return bot.say(`![](http://www.bieg.nl/beeld/speechbubble.gif)`)
            .then(() => 'processing')
          break;
      }
    }
},

updateOntvangen: {
    receive: (bot, message) => {
      switch(message.text) {
        case 'Ja, dat wil ik wel':
            return bot.say(`👍 Leuk, dan houd ik  je op de hoogte zodra er weer nieuws is.`)
            .then(() => 'update_ja');
          break;
          case 'Nee, dat hoeft niet':
              receive: () => 'bye'
              break;
          default:
            receive => 'processing'
            break;
      }
    }
},

update_ja: {
  prompt: (bot) => bot.say('Wat is je email adres?'),
      receive: (bot, message) => {
          const email=message.text;
          return bot.setProp('email', email)
              .then(()  => bot.say(`Ok - ✉  dan hou ik je via ${email} op de hoogte.`))
              .then(()  =>'lastCheck')
    }
},
update_nee: {
  receive: () => 'bye'
},

hypotheekStarter: {
    receive: () => 'askName'
},

hypotheektype_nieuw: {
    prompt: (bot) => bot.say('Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)'),
    receive: () => 'processing'
},

woningType: {
  receive: (bot, message) => {
    switch(message.text) {
        case '🏬 Appartement':
          return bot.say(`Nice!`)
          .then(() => 'vervolgVragen')
          break;
      case '🏠 Huis':
          return bot.say(`Leuk`)
          .then(() => 'vervolgVragen')
          break;
    case '📭 Vakantiewoning':
          return bot.say(`Gezellig`)
          .then(() => 'vervolgVragen')
          break;
      default:
        receive => 'processing'
        break;
        }
    }
},

vervolgVragen: {
  prompt: (bot) => bot.say(`Hoe heet je eigelijk? 😋`),
          receive: (bot, message) => {
              const Name = message.text;
              return bot.setProp('Name', Name)
                  .then(() => bot.say(`Hoi ${Name}. 📋 Ik heb nog wat vragen voor je om verder te kunnen.`))
                  .then(() => 'processing')
            }
},

lastCheck: {
    prompt: (bot) => bot.say(' Is er nog iets waar ik  je bij kan helpen?  🔶  %[Ik zoek meer informatie](postback:meerInfo) %[Nee hoor](postback:bye)'),
          receive: (bot, message) => {
            switch(message.text) {
              case 'Nee hoor':
                  receive: ()  => 'bye'
                  break;
             case 'Ik zoek meer informatie':
                  receive: () => 'speak'
                  break;
            case 'Nee':
                  receive: () => 'bye'
                  break;
            default:
              return bot.say('![](http://www.bieg.nl/beeld/speechbubble.gif)')
                .then(() => 'processing')
              break;
            }
        }
},

meerInfo: {
  prompt: (bot) => bot.say('bestand'),
   receive: () => 'processing'
},

bye: {
    prompt: (bot) => bot.say('Fijn je gesproken te hebben. Bedankt voor je tijd ⏲'),
    receive: ()  => 'finish'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => 'pri'
// },

finish: {
receive: () => 'finish'
}
});
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var router = express.Router();
var mustacheExpress = require('mustache-express');
var humanize = require('humanizer');
var icons = require('glyphicons');
var jwt = require('jsonwebtoken');
var querystring = require('querystring');
var http = require('http');

var secret = process.env.TOKENS_KSOTD || 'shhhhh';
var phrase = process.env.PHRASE_KSOTD || 'hakunamatata';

var apiCall = function(path, method, signed, data, success, err) {
    let host = process.env.API || 'api.keyboardshortcutoftheday.com';
    let port = process.env.API_PORT || '80';
    let headers = {'X-API-Key': signed};
    let dataString = JSON.stringify(data);
    if(method === 'GET' && data) {
        path += '?' + querystring.stringify(data);
    } else {
        headers = {
            'Content-Type': 'application/json',
            'Content-Length': dataString.length,
            'X-API-Key': signed
          };
    }
    let options = {
        host,
        port,
        path,
        method,
        headers
      };
      try {
            let req = http.request(options, function(res){

                res.setEncoding('utf-8');
                var responseString = '';

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

                res.on('end', function(){
                    if(responseString) {
                        let responseObject = JSON.parse(responseString);
                        if(responseObject.message) {
                            err(responseObject, req);
                            return;
                        }
                        success(responseObject);
                    } else {
                        err('No response', req);
                    }
                });
                res.on('error', err);
            });
            req.on('error', err);
            req.write(dataString);
            req.end();
        } catch (error) {
            err(error);
        }
}

var shortcut = {
    message: 'Not yet'
}

var emptyShortcut = shortcut;

var getShortcut = function(signed, res) {
    apiCall('/shortcuts/1', 'GET', signed, null, function (dataObject){
        shortcut = dataObject || emptyShortcut;
        res.render('index', { title: 'Keyboard shortcut of the day', dissa: icons.ticket, token: signed, 'shortcut' : JSON.stringify(shortcut), 'description': shortcut.description, stitle: shortcut.title, vendor: shortcut.vendor, product: shortcut.product, keys: shortcut.keycombo, documentation: shortcut.documentation });
    },
    function(error, req){
        res.render('error', { message: error.message, token: signed});
    }
    );
}

router.get('/', function (req, res) {
    var signed = jwt.sign({ phrase }, secret, { expiresIn: '1h'});
    getShortcut(signed, res);
})

var app = express();
app.use(express.static('public'));
app.engine('html', mustacheExpress());
app.set('views', 'views');
app.set('view engine', 'html');
app.use('/js', [express.static(__dirname + '/node_modules/jquery/dist/'),
                express.static(__dirname + '/node_modules/bootstrap/dist/js/'),
                express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/js/'),
                express.static(__dirname + '/node_modules/popper.js/dist/')]);
app.use('/css', [express.static(__dirname + '/node_modules/bootstrap/dist/css/'),
                express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/css/')]);
app.use('/webfonts', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/webfonts/'));
app.use('/sprites', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/sprites/'));
app.use('/svg', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/svg/'));
app.use('/', router);

app.listen(process.env.PORT || 8080);<commit_msg>Api calls are broken<commit_after>'use strict';

var express = require('express');
var router = express.Router();
var mustacheExpress = require('mustache-express');
var humanize = require('humanizer');
var icons = require('glyphicons');
var jwt = require('jsonwebtoken');
var querystring = require('querystring');
var http = require('http');

var secret = process.env.TOKENS_KSOTD || 'shhhhh';
var phrase = process.env.PHRASE_KSOTD || 'hakunamatata';

var apiCall = function(path, method, signed, data, success, err) {
    let host = process.env.API || 'api.keyboardshortcutoftheday.com';
    let port = process.env.API_PORT || '80';
    let headers = {'X-API-Key': signed};
    let dataString = JSON.stringify(data);
    if(method === 'GET' && data) {
        path += '?' + querystring.stringify(data);
    } else {
        headers = {
            'Content-Type': 'application/json',
            'Content-Length': dataString.length,
            'X-API-Key': signed
          };
    }
    let options = {
        host,
        port,
        path,
        method,
        headers
      };
      try {
            // let req = http.request(options, function(res){

            //     res.setEncoding('utf-8');
            //     var responseString = '';

            //     res.on('data', function(data){
            //         responseString += data;
            //     });

            //     res.on('end', function(){
            //         if(responseString) {
            //             let responseObject = JSON.parse(responseString);
            //             if(responseObject.message) {
            //                 err(responseObject, req);
            //                 return;
            //             }
            //             success(responseObject);
            //         } else {
            //             err('No response', req);
            //         }
            //     });
            //     res.on('error', err);
            // });
            // req.on('error', err);
            // req.write(dataString);
            // req.end();
            err('Api calls are broken');
        } catch (error) {
            err(error);
        }
}

var shortcut = {
    message: 'Not yet'
}

var emptyShortcut = shortcut;

var getShortcut = function(signed, res) {
    apiCall('/shortcuts/1', 'GET', signed, null, function (dataObject){
        shortcut = dataObject || emptyShortcut;
        res.render('index', { title: 'Keyboard shortcut of the day', dissa: icons.ticket, token: signed, 'shortcut' : JSON.stringify(shortcut), 'description': shortcut.description, stitle: shortcut.title, vendor: shortcut.vendor, product: shortcut.product, keys: shortcut.keycombo, documentation: shortcut.documentation });
    },
    function(error, req){
        res.render('error', { message: error.message, token: signed});
    }
    );
}

router.get('/', function (req, res) {
    var signed = jwt.sign({ phrase }, secret, { expiresIn: '1h'});
    getShortcut(signed, res);
})

var app = express();
app.use(express.static('public'));
app.engine('html', mustacheExpress());
app.set('views', 'views');
app.set('view engine', 'html');
app.use('/js', [express.static(__dirname + '/node_modules/jquery/dist/'),
                express.static(__dirname + '/node_modules/bootstrap/dist/js/'),
                express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/js/'),
                express.static(__dirname + '/node_modules/popper.js/dist/')]);
app.use('/css', [express.static(__dirname + '/node_modules/bootstrap/dist/css/'),
                express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/css/')]);
app.use('/webfonts', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/webfonts/'));
app.use('/sprites', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/sprites/'));
app.use('/svg', express.static(__dirname + '/node_modules/@fortawesome/fontawesome-free/svg/'));
app.use('/', router);

app.listen(process.env.PORT || 8080);<|endoftext|>


<commit_before>window.onload = function() {
    style();
    $('.smile').click(function() {
        update();
    });
}

function style() {
    $colors = [
        'woodenairplanelamp',
        'hypertext',
        'nighty',
        'hidden',
        'blue'
        ];
    $index = Math.round(Math.random() * ($colors.length - 1) - 0);
    var style = $colors[$index];
    $('body').attr('class',style);
    wiggle();
}

function update() {
    if($index <= $colors.length - 2) {
        $index += 1;
    } else {
        $index = 0;
    }

    console.log($index);
    var style = $colors[$index];
    $('body').attr('class',style);
    wiggle();
}

function wiggle() {
    setInterval(function() {
        var width = window.innerWidth;
        var height = window.innerHeight;
        var texts = $('i').length;
        for(var i = 0; i < texts+1; i++) {
            var x = (Math.floor((Math.random() * 3) + 1)) * (Math.round(Math.random()) * 2 - 1);
            var y = (Math.floor((Math.random() * 3) + 1)) * (Math.round(Math.random()) * 2 - 1);
            var z = (Math.floor((Math.random() * 3) + 1)) * (Math.round(Math.random()) * 2 - 1);
            if($('i').eq(i).ismouseover() && $('i').has('a')) {
                $('i').eq(i).transition({x:x/9, y:y/9, rotate:z/9}, 10);
            }
            else {
                $('i').eq(i).transition({x:x, y:y, rotate:z}, 90);
            }
        }
    },100);
}

// ismouseover() by Subin Siby
// http://subinsb.com/how-to-check-if-the-mouse-is-over-an-element-in-jquery
$.mlp ={x:0,y:0};function documentHandler(){var $current =this=== document ? $(this): $(this).contents(); $current.mousemove(function(e){jQuery.mlp ={x:e.pageX,y:e.pageY}}); $current.find("iframe").load(documentHandler);}$(documentHandler); $.fn.ismouseover =function(overThis){var result =false;this.eq(0).each(function(){var $current = $(this).is("iframe")? $(this).contents().find("body"): $(this);var offset = $current.offset(); result
result = offset.left<=$.mlp.x && offset.left + $current.outerWidth()> $.mlp.x && offset.top<=$.mlp.y && offset.top + $current.outerHeight()> $.mlp.y;});return result;};<commit_msg>reorder styles<commit_after>window.onload = function() {
    style();
    $('.smile').click(function() {
        update();
    });
}

function style() {
    $colors = [
        'hidden',
        'woodenairplanelamp',
        'hypertext',
        'nighty',
        'blue'
        ];
    $index = Math.round(Math.random() * ($colors.length - 1) - 0);
    var style = $colors[$index];
    $('body').attr('class',style);
    wiggle();
}

function update() {
    if($index <= $colors.length - 2) {
        $index += 1;
    } else {
        $index = 0;
    }

    console.log($index);
    var style = $colors[$index];
    $('body').attr('class',style);
    wiggle();
}

function wiggle() {
    setInterval(function() {
        var width = window.innerWidth;
        var height = window.innerHeight;
        var texts = $('i').length;
        for(var i = 0; i < texts+1; i++) {
            var x = (Math.floor((Math.random() * 3) + 1)) * (Math.round(Math.random()) * 2 - 1);
            var y = (Math.floor((Math.random() * 3) + 1)) * (Math.round(Math.random()) * 2 - 1);
            var z = (Math.floor((Math.random() * 3) + 1)) * (Math.round(Math.random()) * 2 - 1);
            if($('i').eq(i).ismouseover() && $('i').has('a')) {
                $('i').eq(i).transition({x:x/9, y:y/9, rotate:z/9}, 10);
            }
            else {
                $('i').eq(i).transition({x:x, y:y, rotate:z}, 90);
            }
        }
    },100);
}

// ismouseover() by Subin Siby
// http://subinsb.com/how-to-check-if-the-mouse-is-over-an-element-in-jquery
$.mlp ={x:0,y:0};function documentHandler(){var $current =this=== document ? $(this): $(this).contents(); $current.mousemove(function(e){jQuery.mlp ={x:e.pageX,y:e.pageY}}); $current.find("iframe").load(documentHandler);}$(documentHandler); $.fn.ismouseover =function(overThis){var result =false;this.eq(0).each(function(){var $current = $(this).is("iframe")? $(this).contents().find("body"): $(this);var offset = $current.offset(); result
result = offset.left<=$.mlp.x && offset.left + $current.outerWidth()> $.mlp.x && offset.top<=$.mlp.y && offset.top + $current.outerHeight()> $.mlp.y;});return result;};<|endoftext|>


<commit_before>module.exports = function (callback) {
  var gm = require('gm');
  var fs = require('fs');
  var path = require('path');
  var sharp = require('sharp');
  var express = require('express')
  var config = require('./config')();
  var packageinfo = require('./package.json');

  var app = express();

  try {
    var images = require(config.image_store_path);
  } catch (e) {
    var images = [];
  }

  fs.mkdir(config.cache_folder_path, function(e) {});

  process.addListener('uncaughtException', function (err) {
    console.log('Uncaught exception: ');
    console.trace(err);
  })

  var countImage = function () {
    process.send("count");
  }

  var checkParameters = function (params, queryparams, square, callback) {
    if ((square && !params.size) || (square && isNaN(parseInt(params.size))) || (!square && !params.width) || (!square && !params.height) || (!square && isNaN(parseInt(params.width))) || (!square && isNaN(parseInt(params.height))) || (queryparams.gravity && sharp.gravity[queryparams.gravity] == null)) {
      return callback(true, 400, 'Invalid arguments');
    }
    if (params.size > config.max_width || params.size > config.max_height || params.width > config.max_height || params.height > config.max_width) {
      return callback(true, 413, 'Specified dimensions too large');
    }
    callback(false);
  }

  var displayError = function (res, code, message) {
    res.status(code);
    res.send({ error: message });
  }

  var findMatchingImage = function (id, callback) {
    var matchingImages = images.filter(function (image) { return image.id == id; });
    if (matchingImages.length == 0) {
      return false;
    }
    return matchingImages[0].filename;
  }

  var getGravity = function(gravity) {
    gravity = gravity ? gravity : 'center';
    gravity = gravity == 'centre' ? 'center' : gravity;
    return gravity;
  }

  var getDestination = function (width, height, gravity, blur, filePath, prefix) {
    return config.cache_folder_path + '/' + prefix + path.basename(filePath, path.extname(filePath)) + '-' + width + 'x' + height + '-' + gravity + (blur ? '-blur' : '') + '.jpg';
  }

  var getShortDestination = function (width, height, gravity, blur, filePath, prefix) {
    return config.cache_folder_path + '/' + prefix + width + '^' + height + '-' + gravity + (blur ? '-blurred' : '') + '.jpg';
  }

  var getAndCheckDestination = function (width, height, gravity, blur, filePath, prefix, shortName, callback) {
    var destination = shortName ? getShortDestination(width, height, gravity, blur, filePath, prefix) : getDestination(width, height, gravity, blur, filePath, prefix);
    fs.exists(destination, function (exists) {
      callback(exists, destination);
    })
  }

  var imageResize = function (width, height, gravity, filePath, destination, callback) {
    try {
      sharp(filePath).rotate().resize(width, height).crop(sharp.gravity[gravity]).progressive().toFile(destination, function (err) {
        callback(err, destination);
      });
    } catch (e) {
      callback(e, null);
    }
  }

  var getProcessedImage = function (width, height, gravity, gray, blur, filePath, shortName, callback) {
    gravity = getGravity(gravity);
    getAndCheckDestination(width, height, gravity, blur, filePath, gray ? 'gray-' : '', shortName, function (exists, destination) {
      if (exists) {
        return callback(null, destination);
      }
      imageResize(width, height, gravity, filePath, destination, function (err, destination) {
        if (err) {
          return callback(err);
        }
        if (gray) {
          var modifyImage = gm(destination).colorspace('GRAY');
          if (blur) {
            modifyImage.blur(0, 5);
          }
          modifyImage.write(destination, function (err) {
            if (err) {
              return callback(err);
            }
            callback(null, destination);
          })
        } else {
          if (blur) {
            gm(destination).blur(0, 5).write(destination, function (err) {
              if (err) {
                return callback(err);
              }
              callback(null, destination);
            })
          } else {
            callback(null, destination);
          }
        }
      })
    })
  }

  var getWidthAndHeight = function (params, square, callback) {
    var width = square ? params.size : params.width;
    var height = square ? params.size : params.height;
    callback(width, height);
  }

  var serveImage = function(req, res, square, gray) {
    checkParameters(req.params, req.query, square, function (err, code, message) {
      getWidthAndHeight(req.params, square, function (width, height) {
        if (err) {
          return displayError(res, code, message);
        }

        var filePath;
        var blur = false;
        if (req.query.image) {
          var matchingImage = findMatchingImage(req.query.image);
          if (matchingImage) {
            filePath = matchingImage;
          } else {
            return displayError(res, 400, 'Invalid image id');
          }
        } else {
          filePath = images[Math.floor(Math.random() * images.length)].filename;
        }
        getProcessedImage(width, height, req.query.gravity, gray, !(!req.query.blur && req.query.blur != ''), filePath, (!req.query.image && !req.query.random && req.query.random != ''), function (err, imagePath) {
          if (err) {
            console.log('filePath: ' + filePath);
            console.log('imagePath: ' + imagePath);
            console.log('error: ' + err);
            return displayError(res, 500, 'Something went wrong');
          }
          res.sendFile(imagePath);
          countImage();
        })
      })
    })
  }

  app.use(express.static(path.join(__dirname, 'public')));

  app.get('/info', function (req, res, next) {
    res.jsonp({ name: packageinfo.name, version: packageinfo.version, author: packageinfo.author });
  })

  app.get('/list', function (req, res, next) {
    var newImages = [];
    for (var i in images) {
      var item = images[i];
      var image = {
        format: item.format,
        width: item.width,
        height: item.height,
        filename: path.basename(item.filename),
        id: item.id
      }
      newImages.push(image);
    }
    res.jsonp(newImages);
  })

  app.get('/:size', function (req, res, next) {
    serveImage(req, res, true, false);
  })

  app.get('/g/:size', function (req, res, next) {
    serveImage(req, res, true, true);
  })

  app.get('/:width/:height', function (req, res, next) {
    serveImage(req, res, false, false);
  })

  app.get('/g/:width/:height', function (req, res, next) {
    serveImage(req, res, false, true);
  })

  app.get('*', function (req, res, next) {
    res.status(404);
    res.send({ error: 'Resource not found' });
  })

  callback(app);
}
<commit_msg>Show metadata in /list<commit_after>module.exports = function (callback) {
  var gm = require('gm');
  var fs = require('fs');
  var path = require('path');
  var sharp = require('sharp');
  var express = require('express')
  var config = require('./config')();
  var packageinfo = require('./package.json');

  var app = express();

  try {
    var images = require(config.image_store_path);
  } catch (e) {
    var images = [];
  }

  fs.mkdir(config.cache_folder_path, function(e) {});

  process.addListener('uncaughtException', function (err) {
    console.log('Uncaught exception: ');
    console.trace(err);
  })

  var countImage = function () {
    process.send("count");
  }

  var checkParameters = function (params, queryparams, square, callback) {
    if ((square && !params.size) || (square && isNaN(parseInt(params.size))) || (!square && !params.width) || (!square && !params.height) || (!square && isNaN(parseInt(params.width))) || (!square && isNaN(parseInt(params.height))) || (queryparams.gravity && sharp.gravity[queryparams.gravity] == null)) {
      return callback(true, 400, 'Invalid arguments');
    }
    if (params.size > config.max_width || params.size > config.max_height || params.width > config.max_height || params.height > config.max_width) {
      return callback(true, 413, 'Specified dimensions too large');
    }
    callback(false);
  }

  var displayError = function (res, code, message) {
    res.status(code);
    res.send({ error: message });
  }

  var findMatchingImage = function (id, callback) {
    var matchingImages = images.filter(function (image) { return image.id == id; });
    if (matchingImages.length == 0) {
      return false;
    }
    return matchingImages[0].filename;
  }

  var getGravity = function(gravity) {
    gravity = gravity ? gravity : 'center';
    gravity = gravity == 'centre' ? 'center' : gravity;
    return gravity;
  }

  var getDestination = function (width, height, gravity, blur, filePath, prefix) {
    return config.cache_folder_path + '/' + prefix + path.basename(filePath, path.extname(filePath)) + '-' + width + 'x' + height + '-' + gravity + (blur ? '-blur' : '') + '.jpg';
  }

  var getShortDestination = function (width, height, gravity, blur, filePath, prefix) {
    return config.cache_folder_path + '/' + prefix + width + '^' + height + '-' + gravity + (blur ? '-blurred' : '') + '.jpg';
  }

  var getAndCheckDestination = function (width, height, gravity, blur, filePath, prefix, shortName, callback) {
    var destination = shortName ? getShortDestination(width, height, gravity, blur, filePath, prefix) : getDestination(width, height, gravity, blur, filePath, prefix);
    fs.exists(destination, function (exists) {
      callback(exists, destination);
    })
  }

  var imageResize = function (width, height, gravity, filePath, destination, callback) {
    try {
      sharp(filePath).rotate().resize(width, height).crop(sharp.gravity[gravity]).progressive().toFile(destination, function (err) {
        callback(err, destination);
      });
    } catch (e) {
      callback(e, null);
    }
  }

  var getProcessedImage = function (width, height, gravity, gray, blur, filePath, shortName, callback) {
    gravity = getGravity(gravity);
    getAndCheckDestination(width, height, gravity, blur, filePath, gray ? 'gray-' : '', shortName, function (exists, destination) {
      if (exists) {
        return callback(null, destination);
      }
      imageResize(width, height, gravity, filePath, destination, function (err, destination) {
        if (err) {
          return callback(err);
        }
        if (gray) {
          var modifyImage = gm(destination).colorspace('GRAY');
          if (blur) {
            modifyImage.blur(0, 5);
          }
          modifyImage.write(destination, function (err) {
            if (err) {
              return callback(err);
            }
            callback(null, destination);
          })
        } else {
          if (blur) {
            gm(destination).blur(0, 5).write(destination, function (err) {
              if (err) {
                return callback(err);
              }
              callback(null, destination);
            })
          } else {
            callback(null, destination);
          }
        }
      })
    })
  }

  var getWidthAndHeight = function (params, square, callback) {
    var width = square ? params.size : params.width;
    var height = square ? params.size : params.height;
    callback(width, height);
  }

  var serveImage = function(req, res, square, gray) {
    checkParameters(req.params, req.query, square, function (err, code, message) {
      getWidthAndHeight(req.params, square, function (width, height) {
        if (err) {
          return displayError(res, code, message);
        }

        var filePath;
        var blur = false;
        if (req.query.image) {
          var matchingImage = findMatchingImage(req.query.image);
          if (matchingImage) {
            filePath = matchingImage;
          } else {
            return displayError(res, 400, 'Invalid image id');
          }
        } else {
          filePath = images[Math.floor(Math.random() * images.length)].filename;
        }
        getProcessedImage(width, height, req.query.gravity, gray, !(!req.query.blur && req.query.blur != ''), filePath, (!req.query.image && !req.query.random && req.query.random != ''), function (err, imagePath) {
          if (err) {
            console.log('filePath: ' + filePath);
            console.log('imagePath: ' + imagePath);
            console.log('error: ' + err);
            return displayError(res, 500, 'Something went wrong');
          }
          res.sendFile(imagePath);
          countImage();
        })
      })
    })
  }

  app.use(express.static(path.join(__dirname, 'public')));

  app.get('/info', function (req, res, next) {
    res.jsonp({ name: packageinfo.name, version: packageinfo.version, author: packageinfo.author });
  })

  app.get('/list', function (req, res, next) {
    var newImages = [];
    for (var i in images) {
      var item = images[i];
      var image = {
        format: item.format,
        width: item.width,
        height: item.height,
        filename: path.basename(item.filename),
        id: item.id,
        author: item.author,
        author_url: item.author_url,
        post_url: item.post_url
      }
      newImages.push(image);
    }
    res.jsonp(newImages);
  })

  app.get('/:size', function (req, res, next) {
    serveImage(req, res, true, false);
  })

  app.get('/g/:size', function (req, res, next) {
    serveImage(req, res, true, true);
  })

  app.get('/:width/:height', function (req, res, next) {
    serveImage(req, res, false, false);
  })

  app.get('/g/:width/:height', function (req, res, next) {
    serveImage(req, res, false, true);
  })

  app.get('*', function (req, res, next) {
    res.status(404);
    res.send({ error: 'Resource not found' });
  })

  callback(app);
}
<|endoftext|>