<commit_before>/*
    globals require console
*/
var Express = require('express');
var Http = require('http');
var Https = require('https');
var Fs = require('fs');
var WebSocketServer = require('ws').Server;
var NetfluxSrv = require('./node_modules/chainpad-server/NetfluxWebsocketSrv');
var Package = require('./package.json');
var Path = require("path");
var nThen = require("nthen");

var config;
try {
    config = require('./config');
} catch (e) {
    console.log("You can customize the configuration by copying config.example.js to config.js");
    config = require('./config.example');
}
var websocketPort = config.websocketPort || config.httpPort;
var useSecureWebsockets = config.useSecureWebsockets || false;

// This is stuff which will become available to replify
const debuggableStore = new WeakMap();
const debuggable = function (name, x) {
    if (name in debuggableStore) {
        try { throw new Error(); } catch (e) {
            console.error('cannot add ' + name + ' more than once [' + e.stack + ']');
        }
    } else {
        debuggableStore[name] = x;
    }
    return x;
};
debuggable('global', global);
debuggable('config', config);

// support multiple storage back ends
var Storage = require(config.storage||'./storage/file');

var app = debuggable('app', Express());

var httpsOpts;

var DEV_MODE = !!process.env.DEV
if (DEV_MODE) {
    console.log("DEV MODE ENABLED");
}

var FRESH_MODE = !!process.env.FRESH;
var FRESH_KEY = '';
if (FRESH_MODE) {
    console.log("FRESH MODE ENABLED");
    FRESH_KEY = +new Date();
}

const clone = (x) => (JSON.parse(JSON.stringify(x)));

var setHeaders = (function () {
    if (typeof(config.httpHeaders) !== 'object') { return function () {}; }

    const headers = clone(config.httpHeaders);
    if (config.contentSecurity) {
        headers['Content-Security-Policy'] = clone(config.contentSecurity);
        if (!/;$/.test(headers['Content-Security-Policy'])) { headers['Content-Security-Policy'] += ';' }
        if (headers['Content-Security-Policy'].indexOf('frame-ancestors') === -1) {
            // backward compat for those who do not merge the new version of the config
            // when updating. This prevents endless spinner if someone clicks donate.
            // It also fixes the cross-domain iframe.
            headers['Content-Security-Policy'] += "frame-ancestors *;";
        }
    }
    const padHeaders = clone(headers);
    if (config.padContentSecurity) {
        padHeaders['Content-Security-Policy'] = clone(config.padContentSecurity);
    }
    const ooHeaders = clone(headers);
    if (config.ooContentSecurity) {
        ooHeaders['Content-Security-Policy'] = clone(config.ooContentSecurity);
    }
    if (Object.keys(headers).length) {
        return function (req, res) {
            const h = [/^\/pad(2)?\/inner\.html.*/].some((regex) => {
                    return regex.test(req.url)
                }) ? padHeaders : ([
                    /^\/sheet\/inner\.html.*/,
                    /^\/common\/onlyoffice\/.*\/index\.html.*/
                ].some((regex) => {
                return regex.test(req.url)
            }) ? ooHeaders : headers);
            for (let header in h) { res.setHeader(header, h[header]); }
        };
    }
    return function () {};
}());

(function () {
if (!config.logFeedback) { return; }

const logFeedback = function (url) {
    url.replace(/\?(.*?)=/, function (all, fb) {
        console.log('[FEEDBACK] %s', fb);
    });
};

app.head(/^\/common\/feedback\.html/, function (req, res, next) {
    logFeedback(req.url);
    next();
});
}());

app.use(function (req, res, next) {
    setHeaders(req, res);
    if (/[\?\&]ver=[^\/]+$/.test(req.url)) { res.setHeader("Cache-Control", "max-age=31536000"); }
    next();
});

app.use(Express.static(__dirname + '/www'));

Fs.exists(__dirname + "/customize", function (e) {
    if (e) { return; }
    console.log("Cryptpad is customizable, see customize.dist/readme.md for details");
});

// FIXME I think this is a regression caused by a recent PR
// correct this hack without breaking the contributor's intended behaviour.

var mainPages = config.mainPages || ['index', 'privacy', 'terms', 'about', 'contact'];
var mainPagePattern = new RegExp('^\/(' + mainPages.join('|') + ').html$');
app.get(mainPagePattern, Express.static(__dirname + '/customize'));
app.get(mainPagePattern, Express.static(__dirname + '/customize.dist'));

app.use("/blob", Express.static(Path.join(__dirname, (config.blobPath || './blob')), {
    maxAge: DEV_MODE? "0d": "365d"
}));
app.use("/datastore", Express.static(Path.join(__dirname, (config.filePath || './datastore')), {
    maxAge: "0d"
}));
app.use("/block", Express.static(Path.join(__dirname, (config.blockPath || '/block')), {
    maxAge: "0d",
}));

app.use("/customize", Express.static(__dirname + '/customize'));
app.use("/customize", Express.static(__dirname + '/customize.dist'));
app.use("/customize.dist", Express.static(__dirname + '/customize.dist'));
app.use(/^\/[^\/]*$/, Express.static('customize'));
app.use(/^\/[^\/]*$/, Express.static('customize.dist'));

if (config.privKeyAndCertFiles) {
    var privKeyAndCerts = '';
    config.privKeyAndCertFiles.forEach(function (file) {
        privKeyAndCerts = privKeyAndCerts + Fs.readFileSync(file);
    });
    var array = privKeyAndCerts.split('\n-----BEGIN ');
    for (var i = 1; i < array.length; i++) { array[i] = '-----BEGIN ' + array[i]; }
    var privKey;
    for (var i = 0; i < array.length; i++) {
        if (array[i].indexOf('PRIVATE KEY-----\n') !== -1) {
            privKey = array[i];
            array.splice(i, 1);
            break;
        }
    }
    if (!privKey) { throw new Error("cannot find private key"); }
    httpsOpts = {
        cert: array.shift(),
        key: privKey,
        ca: array
    };
}

app.get('/api/config', function(req, res){
    var host = req.headers.host.replace(/\:[0-9]+/, '');
    res.setHeader('Content-Type', 'text/javascript');
    res.send('define(function(){\n' + [
        'var obj = ' + JSON.stringify({
            requireConf: {
                waitSeconds: 600,
                urlArgs: 'ver=' + Package.version + (FRESH_KEY? '-' + FRESH_KEY: '') + (DEV_MODE? '-' + (+new Date()): ''),
            },
            removeDonateButton: (config.removeDonateButton === true),
            allowSubscriptions: (config.allowSubscriptions === true),
            websocketPath: config.useExternalWebsocket ? undefined : config.websocketPath,
            websocketURL:'ws' + ((useSecureWebsockets) ? 's' : '') + '://' + host + ':' +
                websocketPort + '/cryptpad_websocket',
            httpUnsafeOrigin: config.httpUnsafeOrigin,
        }, null, '\t'),
        'obj.httpSafeOrigin = ' + (function () {
            if (config.httpSafeOrigin) { return '"' + config.httpSafeOrigin + '"'; }
            if (config.httpSafePort) {
                return "(function () { return window.location.origin.replace(/\:[0-9]+$/, ':" +
                    config.httpSafePort + "'); }())";
            }
            return 'window.location.origin';
        }()),
        'return obj',
        '});'
    ].join(';\n'));
});

var four04_path = Path.resolve(__dirname + '/customize.dist/404.html');
var custom_four04_path = Path.resolve(__dirname + '/customize/404.html');

var send404 = function (res, path) {
    if (!path && path !== four04_path) { path = four04_path; }
    Fs.exists(path, function (exists) {
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        if (exists) { return Fs.createReadStream(path).pipe(res); }
        send404(res);
    });
};

var FONT_NAME_MAP = {};
[ './www/common/onlyoffice/fonts/' ].forEach(function (path) {
    Fs.readdir(path, function (err, list) {
        if (err) { throw err; }
        list.forEach(function (fontName) {
            FONT_NAME_MAP[fontName.toLowerCase()] = path + fontName;
        });
    });
});

/* Code to automatically transform font to js */
/* Currently not active, but might be necessary */
app.use("/common/onlyoffice/fonts/odttf/:name", function (req, res) {
    var name = req.params.name.replace(/\.js$/, '').toLowerCase();
    var path = Path.join('./www/common/onlyoffice/fonts/odttf/', name);
    console.log(path);
    Fs.createReadStream(path).pipe(res).on('error', function (e) {
        console.error(e);
        res.status(404).send('No such font');
    });
});

/* All fonts file replaced by the list of fonts in ttf */
app.use("/common/onlyoffice/sdkjs/common/AllFonts.js",
    Express.static("./www/common/onlyoffice/AllFonts.js"));

/* Replace fonts thumbnail call */
app.use("/common/onlyoffice/sdkjs/common/Images/fonts_thumbnail@2x.png",
    Express.static("./www/common/onlyoffice/fonts_thumbnail@2x.png"));
app.use("/common/onlyoffice/sdkjs/common/Images/fonts_thumbnail.png",
    Express.static("./www/common/onlyoffice/fonts_thumbnail.png"));

app.use(function (req, res, next) {
    res.status(404);
    send404(res, custom_four04_path);
});

var httpServer = httpsOpts ? Https.createServer(httpsOpts, app) : Http.createServer(app);

httpServer.listen(config.httpPort,config.httpAddress,function(){
    var host = config.httpAddress;
    var hostName = !host.indexOf(':') ? '[' + host + ']' : host;

    var port = config.httpPort;
    var ps = port === 80? '': ':' + port;

    console.log('\n[%s] server available http://%s%s', new Date().toISOString(), hostName, ps);
});
if (config.httpSafePort) {
    Http.createServer(app).listen(config.httpSafePort, config.httpAddress);
}

var wsConfig = { server: httpServer };

var rpc;

var nt = nThen(function (w) {
    if (!config.enableTaskScheduling) { return; }
    var Tasks = require("./storage/tasks");
    console.log("loading task scheduler");
    Tasks.create(config, w(function (e, tasks) {
        config.tasks = tasks;
    }));
}).nThen(function (w) {
    config.rpc = typeof(config.rpc) === 'undefined'? './rpc.js' : config.rpc;
    if (typeof(config.rpc) !== 'string') { return; }
    // load pin store...
    var Rpc = require(config.rpc);
    Rpc.create(config, debuggable, w(function (e, _rpc) {
        if (e) {
            w.abort();
            throw e;
        }
        rpc = _rpc;
    }));
}).nThen(function () {
    if(config.useExternalWebsocket) { return; }
    if (websocketPort !== config.httpPort) {
        console.log("setting up a new websocket server");
        wsConfig = { port: websocketPort};
    }
    var wsSrv = new WebSocketServer(wsConfig);
    Storage.create(config, function (store) {
        NetfluxSrv.run(store, wsSrv, config, rpc);
    });
});

if (config.debugReplName) {
    require('replify')({ name: config.debugReplName, app: debuggableStore });
}
<commit_msg>remove some dead serverside code<commit_after>/*
    globals require console
*/
var Express = require('express');
var Http = require('http');
var Https = require('https');
var Fs = require('fs');
var WebSocketServer = require('ws').Server;
var NetfluxSrv = require('./node_modules/chainpad-server/NetfluxWebsocketSrv');
var Package = require('./package.json');
var Path = require("path");
var nThen = require("nthen");

var config;
try {
    config = require('./config');
} catch (e) {
    console.log("You can customize the configuration by copying config.example.js to config.js");
    config = require('./config.example');
}
var websocketPort = config.websocketPort || config.httpPort;
var useSecureWebsockets = config.useSecureWebsockets || false;

// This is stuff which will become available to replify
const debuggableStore = new WeakMap();
const debuggable = function (name, x) {
    if (name in debuggableStore) {
        try { throw new Error(); } catch (e) {
            console.error('cannot add ' + name + ' more than once [' + e.stack + ']');
        }
    } else {
        debuggableStore[name] = x;
    }
    return x;
};
debuggable('global', global);
debuggable('config', config);

// support multiple storage back ends
var Storage = require(config.storage||'./storage/file');

var app = debuggable('app', Express());

var httpsOpts;

var DEV_MODE = !!process.env.DEV
if (DEV_MODE) {
    console.log("DEV MODE ENABLED");
}

var FRESH_MODE = !!process.env.FRESH;
var FRESH_KEY = '';
if (FRESH_MODE) {
    console.log("FRESH MODE ENABLED");
    FRESH_KEY = +new Date();
}

const clone = (x) => (JSON.parse(JSON.stringify(x)));

var setHeaders = (function () {
    if (typeof(config.httpHeaders) !== 'object') { return function () {}; }

    const headers = clone(config.httpHeaders);
    if (config.contentSecurity) {
        headers['Content-Security-Policy'] = clone(config.contentSecurity);
        if (!/;$/.test(headers['Content-Security-Policy'])) { headers['Content-Security-Policy'] += ';' }
        if (headers['Content-Security-Policy'].indexOf('frame-ancestors') === -1) {
            // backward compat for those who do not merge the new version of the config
            // when updating. This prevents endless spinner if someone clicks donate.
            // It also fixes the cross-domain iframe.
            headers['Content-Security-Policy'] += "frame-ancestors *;";
        }
    }
    const padHeaders = clone(headers);
    if (config.padContentSecurity) {
        padHeaders['Content-Security-Policy'] = clone(config.padContentSecurity);
    }
    const ooHeaders = clone(headers);
    if (config.ooContentSecurity) {
        ooHeaders['Content-Security-Policy'] = clone(config.ooContentSecurity);
    }
    if (Object.keys(headers).length) {
        return function (req, res) {
            const h = [/^\/pad(2)?\/inner\.html.*/].some((regex) => {
                    return regex.test(req.url)
                }) ? padHeaders : ([
                    /^\/sheet\/inner\.html.*/,
                    /^\/common\/onlyoffice\/.*\/index\.html.*/
                ].some((regex) => {
                return regex.test(req.url)
            }) ? ooHeaders : headers);
            for (let header in h) { res.setHeader(header, h[header]); }
        };
    }
    return function () {};
}());

(function () {
if (!config.logFeedback) { return; }

const logFeedback = function (url) {
    url.replace(/\?(.*?)=/, function (all, fb) {
        console.log('[FEEDBACK] %s', fb);
    });
};

app.head(/^\/common\/feedback\.html/, function (req, res, next) {
    logFeedback(req.url);
    next();
});
}());

app.use(function (req, res, next) {
    setHeaders(req, res);
    if (/[\?\&]ver=[^\/]+$/.test(req.url)) { res.setHeader("Cache-Control", "max-age=31536000"); }
    next();
});

app.use(Express.static(__dirname + '/www'));

Fs.exists(__dirname + "/customize", function (e) {
    if (e) { return; }
    console.log("Cryptpad is customizable, see customize.dist/readme.md for details");
});

// FIXME I think this is a regression caused by a recent PR
// correct this hack without breaking the contributor's intended behaviour.

var mainPages = config.mainPages || ['index', 'privacy', 'terms', 'about', 'contact'];
var mainPagePattern = new RegExp('^\/(' + mainPages.join('|') + ').html$');
app.get(mainPagePattern, Express.static(__dirname + '/customize'));
app.get(mainPagePattern, Express.static(__dirname + '/customize.dist'));

app.use("/blob", Express.static(Path.join(__dirname, (config.blobPath || './blob')), {
    maxAge: DEV_MODE? "0d": "365d"
}));
app.use("/datastore", Express.static(Path.join(__dirname, (config.filePath || './datastore')), {
    maxAge: "0d"
}));
app.use("/block", Express.static(Path.join(__dirname, (config.blockPath || '/block')), {
    maxAge: "0d",
}));

app.use("/customize", Express.static(__dirname + '/customize'));
app.use("/customize", Express.static(__dirname + '/customize.dist'));
app.use("/customize.dist", Express.static(__dirname + '/customize.dist'));
app.use(/^\/[^\/]*$/, Express.static('customize'));
app.use(/^\/[^\/]*$/, Express.static('customize.dist'));

if (config.privKeyAndCertFiles) {
    var privKeyAndCerts = '';
    config.privKeyAndCertFiles.forEach(function (file) {
        privKeyAndCerts = privKeyAndCerts + Fs.readFileSync(file);
    });
    var array = privKeyAndCerts.split('\n-----BEGIN ');
    for (var i = 1; i < array.length; i++) { array[i] = '-----BEGIN ' + array[i]; }
    var privKey;
    for (var i = 0; i < array.length; i++) {
        if (array[i].indexOf('PRIVATE KEY-----\n') !== -1) {
            privKey = array[i];
            array.splice(i, 1);
            break;
        }
    }
    if (!privKey) { throw new Error("cannot find private key"); }
    httpsOpts = {
        cert: array.shift(),
        key: privKey,
        ca: array
    };
}

app.get('/api/config', function(req, res){
    var host = req.headers.host.replace(/\:[0-9]+/, '');
    res.setHeader('Content-Type', 'text/javascript');
    res.send('define(function(){\n' + [
        'var obj = ' + JSON.stringify({
            requireConf: {
                waitSeconds: 600,
                urlArgs: 'ver=' + Package.version + (FRESH_KEY? '-' + FRESH_KEY: '') + (DEV_MODE? '-' + (+new Date()): ''),
            },
            removeDonateButton: (config.removeDonateButton === true),
            allowSubscriptions: (config.allowSubscriptions === true),
            websocketPath: config.useExternalWebsocket ? undefined : config.websocketPath,
            websocketURL:'ws' + ((useSecureWebsockets) ? 's' : '') + '://' + host + ':' +
                websocketPort + '/cryptpad_websocket',
            httpUnsafeOrigin: config.httpUnsafeOrigin,
        }, null, '\t'),
        'obj.httpSafeOrigin = ' + (function () {
            if (config.httpSafeOrigin) { return '"' + config.httpSafeOrigin + '"'; }
            if (config.httpSafePort) {
                return "(function () { return window.location.origin.replace(/\:[0-9]+$/, ':" +
                    config.httpSafePort + "'); }())";
            }
            return 'window.location.origin';
        }()),
        'return obj',
        '});'
    ].join(';\n'));
});

var four04_path = Path.resolve(__dirname + '/customize.dist/404.html');
var custom_four04_path = Path.resolve(__dirname + '/customize/404.html');

var send404 = function (res, path) {
    if (!path && path !== four04_path) { path = four04_path; }
    Fs.exists(path, function (exists) {
        res.setHeader('Content-Type', 'text/html; charset=utf-8');
        if (exists) { return Fs.createReadStream(path).pipe(res); }
        send404(res);
    });
};

/* All fonts file replaced by the list of fonts in ttf */
app.use("/common/onlyoffice/sdkjs/common/AllFonts.js",
    Express.static("./www/common/onlyoffice/AllFonts.js"));

/* Replace fonts thumbnail call */
app.use("/common/onlyoffice/sdkjs/common/Images/fonts_thumbnail@2x.png",
    Express.static("./www/common/onlyoffice/fonts_thumbnail@2x.png"));
app.use("/common/onlyoffice/sdkjs/common/Images/fonts_thumbnail.png",
    Express.static("./www/common/onlyoffice/fonts_thumbnail.png"));

app.use(function (req, res, next) {
    res.status(404);
    send404(res, custom_four04_path);
});

var httpServer = httpsOpts ? Https.createServer(httpsOpts, app) : Http.createServer(app);

httpServer.listen(config.httpPort,config.httpAddress,function(){
    var host = config.httpAddress;
    var hostName = !host.indexOf(':') ? '[' + host + ']' : host;

    var port = config.httpPort;
    var ps = port === 80? '': ':' + port;

    console.log('\n[%s] server available http://%s%s', new Date().toISOString(), hostName, ps);
});
if (config.httpSafePort) {
    Http.createServer(app).listen(config.httpSafePort, config.httpAddress);
}

var wsConfig = { server: httpServer };

var rpc;

var nt = nThen(function (w) {
    if (!config.enableTaskScheduling) { return; }
    var Tasks = require("./storage/tasks");
    console.log("loading task scheduler");
    Tasks.create(config, w(function (e, tasks) {
        config.tasks = tasks;
    }));
}).nThen(function (w) {
    config.rpc = typeof(config.rpc) === 'undefined'? './rpc.js' : config.rpc;
    if (typeof(config.rpc) !== 'string') { return; }
    // load pin store...
    var Rpc = require(config.rpc);
    Rpc.create(config, debuggable, w(function (e, _rpc) {
        if (e) {
            w.abort();
            throw e;
        }
        rpc = _rpc;
    }));
}).nThen(function () {
    if(config.useExternalWebsocket) { return; }
    if (websocketPort !== config.httpPort) {
        console.log("setting up a new websocket server");
        wsConfig = { port: websocketPort};
    }
    var wsSrv = new WebSocketServer(wsConfig);
    Storage.create(config, function (store) {
        NetfluxSrv.run(store, wsSrv, config, rpc);
    });
});

if (config.debugReplName) {
    require('replify')({ name: config.debugReplName, app: debuggableStore });
}
<|endoftext|>


<commit_before>/*jshint node:true*/

//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------

// Postgresql database connectivity
var pg = require('pg');

// This application uses express as it's web server
// for more info, see: http://expressjs.com
var express = require('express');

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

// create a new express server
var app = express();

var server = require('http').createServer(app);

// use socket.io for real-time
var io = require('socket.io')(server);

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
server.listen(appEnv.port, appEnv.bind, function() {

	// print a message when the server starts listening
  console.log("server starting on " + appEnv.url);
});

// Postgres confg
var psql;

// are we operating in BlueMix
if (process.env.VCAP_SERVICES) {
    var env = JSON.parse(process.env.VCAP_SERVICES);
    psql = env['postgresql-9.1'][0].credentials;
    // The Postgresql service returns the database name in the "name"
    // property but the pg.js Node.js module expects it to be in the
    // "database" property.
    psql.database = psql.name;

// or Heroku
} else if (process.env.DATABASE_URL) {
  psql = process.env.DATABASE_URL;

} else {
    // Specify local Postgresql connection properties here.
    psql = {
        database: "iss",
        host: "localhost",
        port: 5432,
        user: "",
        password: "",
        ssl: false
    };
}

// On startup, create the table if it does not exist.
pg.connect(psql, function(err, client, done) {
  if (err) {
    return console.error('Error requesting client', err);
  }

  client.query('create table if not exists data(idx smallint, value double precision, ts timestamp without time zone)',
  function (err, result) {
    done();
    if (err) {
      return console.error('Error creating table data', err);
    }
  });

});

var ddlist = require('./data_dictionary').list;

var ls = require("lightstreamer-client");
var lsClient = new ls.LightstreamerClient("http://push.lightstreamer.com","ISSLIVE");
var telemetrySub = new ls.Subscription("MERGE", ddlist , ["Value"]);

function broadcastStatus () {

  var cs = lsClient.getStatus(), c = "DISCONNECTED";

  if (cs.indexOf("STALLED") > -1) {

    c = "STALLED";

  } else if (cs.indexOf("CONNECTED") > -1) {

    c = "CONNECTED";

  } else {

    c = "DISCONNECTED";
  }

  io.emit('STATUS', {connection: c, subscription: telemetrySub.isSubscribed()});

  console.log({connection: c, subscription: telemetrySub.isSubscribed()});
}

lsClient.addListener({
  onStatusChange: function (status) {

    broadcastStatus();
  }
});

lsClient.connect();

lsClient.subscribe(telemetrySub);

var ddhash = require('./data_dictionary').hash;

telemetrySub.addListener({

  onSubscription: function() {

    broadcastStatus();
  },

  onUnsubscription: function() {

    broadcastStatus();
  },

  onItemUpdate: function(update) {

    var u = {n: update.getItemName(), v: update.getValue("Value"), t: Date.now()/1000|0};

    pg.connect(psql, function(err, client, done) {
      if (err) {
        return console.error('Error requesting postgres client', err);
      }

      client.query('insert into data (idx, value, ts) values ($1, $2, to_timestamp($3))',
      [ddhash[u.n], u.v, u.t],

      function(err, result) {
        done();

        if (err) {
          return console.error('Error inserting data', err);
        }
      });
    });

    io.emit(u.n, [{u: u.v, t: u.t}]);
  }
});

function queryUnixtime(type, unixtime, client, cb) {
client.query(
  'SELECT * from data where idx = $1 and ts > to_timestamp($2) order by ts asc',
  //"select date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec' as ts, avg(value) as value from data where idx = $1 and ts > to_timestamp($2) group by date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec' order by date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec'",
  [ddhash[type], unixtime],
  function(err, res) {
    cb(err, res);
  });
}

function queryMostRecent(type, client, cb) {

client.query('select * from data where idx = $1 and ts = (select MAX(ts) from data where idx = $1)',
  [ddhash[type]],
  function(err, res) {
    cb(err, res);
  });
}

function emitRows(socket, type, rows) {
  socket.emit(type, rows.map(function(v) { return {u: v.value.toString(), t: v.ts.getTime()/1000|0}; }));
}

io.on('connection', function (socket) {
  console.log('connection');

  broadcastStatus();

  socket.on('STATUS', function () {

    broadcastStatus();
  });

  for(var i = 0, l = ddlist.length; i<l; i++) {

    var type = ddlist[i];

    (function (type) {

      socket.on(type, function (unixtime) {

        pg.connect(psql, function(err, client, done) {
          if (err) {
            return console.error('Error requesting client', err);
          }

          if(unixtime === -1) {

            queryMostRecent(type, client, function(err, res) {
              done();
              if (err) {
                return console.error('Error querying type: ' + type, err);
              }
              emitRows(socket, type, res.rows);
            });

          } else {

            queryUnixtime(type, unixtime, client, function(err, res) {

              if (err) {
                return console.error('Error querying type: ' + type, err);
              }
              if (res.rows.length === 0) {

                queryMostRecent(type, client, function(err, res) {
                  done();
                  if (err) {
                    return console.error('Error querying type: ' + type, err);
                  }
                  emitRows(socket, type, res.rows);
                });

              } else {
                done();
                emitRows(socket, type, res.rows);
              }

          });
         }
        });
      });
    })(type);

  }
});

<commit_msg>comment out table drop<commit_after>/*jshint node:true*/

//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------

// Postgresql database connectivity
var pg = require('pg');

// This application uses express as it's web server
// for more info, see: http://expressjs.com
var express = require('express');

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

// create a new express server
var app = express();

var server = require('http').createServer(app);

// use socket.io for real-time
var io = require('socket.io')(server);

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
server.listen(appEnv.port, appEnv.bind, function() {

	// print a message when the server starts listening
  console.log("server starting on " + appEnv.url);
});

// Postgres confg
var psql;

// are we operating in BlueMix
if (process.env.VCAP_SERVICES) {
    var env = JSON.parse(process.env.VCAP_SERVICES);
    psql = env['postgresql-9.1'][0].credentials;
    // The Postgresql service returns the database name in the "name"
    // property but the pg.js Node.js module expects it to be in the
    // "database" property.
    psql.database = psql.name;

// or Heroku
} else if (process.env.DATABASE_URL) {
  psql = process.env.DATABASE_URL;

} else {
    // Specify local Postgresql connection properties here.
    psql = {
        database: "iss",
        host: "localhost",
        port: 5432,
        user: "",
        password: "",
        ssl: false
    };
}

// On startup, create the table if it does not exist.
pg.connect(psql, function(err, client, done) {
  if (err) {
    return console.error('Error requesting client', err);
  }

  // client.query('drop table if exists data',
  // function (err, result) {
  //   if (err) {
  //     done();
  //     return console.error('Error dropping table data', err);
  //   }

    client.query('create table if not exists data(idx smallint, value double precision, ts timestamp without time zone)',
    function (err, result) {
      done();
      if (err) {
        return console.error('Error creating table data', err);
      }
    });

  // });

});

var ddlist = require('./data_dictionary').list;

var ls = require("lightstreamer-client");
var lsClient = new ls.LightstreamerClient("http://push.lightstreamer.com","ISSLIVE");
var telemetrySub = new ls.Subscription("MERGE", ddlist , ["Value"]);

function broadcastStatus () {

  var cs = lsClient.getStatus(), c = "DISCONNECTED";

  if (cs.indexOf("STALLED") > -1) {

    c = "STALLED";

  } else if (cs.indexOf("CONNECTED") > -1) {

    c = "CONNECTED";

  } else {

    c = "DISCONNECTED";
  }

  io.emit('STATUS', {connection: c, subscription: telemetrySub.isSubscribed()});

  console.log({connection: c, subscription: telemetrySub.isSubscribed()});
}

lsClient.addListener({
  onStatusChange: function (status) {

    broadcastStatus();
  }
});

lsClient.connect();

lsClient.subscribe(telemetrySub);

var ddhash = require('./data_dictionary').hash;

telemetrySub.addListener({

  onSubscription: function() {

    broadcastStatus();
  },

  onUnsubscription: function() {

    broadcastStatus();
  },

  onItemUpdate: function(update) {

    var u = {n: update.getItemName(), v: update.getValue("Value"), t: Date.now()/1000|0};

    pg.connect(psql, function(err, client, done) {
      if (err) {
        return console.error('Error requesting postgres client', err);
      }

      client.query('insert into data (idx, value, ts) values ($1, $2, to_timestamp($3))',
      [ddhash[u.n], u.v, u.t],

      function(err, result) {
        done();

        if (err) {
          return console.error('Error inserting data', err);
        }
      });
    });

    io.emit(u.n, [{u: u.v, t: u.t}]);
  }
});

function queryUnixtime(type, unixtime, client, cb) {
client.query(
  'SELECT * from data where idx = $1 and ts > to_timestamp($2) order by ts asc',
  //"select date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec' as ts, avg(value) as value from data where idx = $1 and ts > to_timestamp($2) group by date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec' order by date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec'",
  [ddhash[type], unixtime],
  function(err, res) {
    cb(err, res);
  });
}

function queryMostRecent(type, client, cb) {

client.query('select * from data where idx = $1 and ts = (select MAX(ts) from data where idx = $1)',
  [ddhash[type]],
  function(err, res) {
    cb(err, res);
  });
}

function emitRows(socket, type, rows) {
  socket.emit(type, rows.map(function(v) { return {u: v.value.toString(), t: v.ts.getTime()/1000|0}; }));
}

io.on('connection', function (socket) {
  console.log('connection');

  broadcastStatus();

  socket.on('STATUS', function () {

    broadcastStatus();
  });

  for(var i = 0, l = ddlist.length; i<l; i++) {

    var type = ddlist[i];

    (function (type) {

      socket.on(type, function (unixtime) {

        pg.connect(psql, function(err, client, done) {
          if (err) {
            return console.error('Error requesting client', err);
          }

          if(unixtime === -1) {

            queryMostRecent(type, client, function(err, res) {
              done();
              if (err) {
                return console.error('Error querying type: ' + type, err);
              }
              emitRows(socket, type, res.rows);
            });

          } else {

            queryUnixtime(type, unixtime, client, function(err, res) {

              if (err) {
                return console.error('Error querying type: ' + type, err);
              }
              if (res.rows.length === 0) {

                queryMostRecent(type, client, function(err, res) {
                  done();
                  if (err) {
                    return console.error('Error querying type: ' + type, err);
                  }
                  emitRows(socket, type, res.rows);
                });

              } else {
                done();
                emitRows(socket, type, res.rows);
              }

          });
         }
        });
      });
    })(type);

  }
});

<|endoftext|>


<commit_before>var express = require('express')
var app = express()
var p = require('path')
var util = require('util')
var hamljs = require('hamljs')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var session = require('express-session')
var flash = require('connect-flash')
var methodOverride = require('method-override')
var debug = require('debug')('explorer:server')

import {Users} from './lib/users.js'
import * as routes from './routes'

module.exports = function(config) {

  app.use(bodyParser.urlencoded({extended: false}))
  app.use(bodyParser.json())

  app.use(methodOverride(function(req, res) {
    if (req.body && typeof req.body === 'object' && '_method' in req.body) {
      // look in urlencoded POST bodies and delete it
      var method = req.body._method
      delete req.body._method
      return method
    }
  }))

  app.use(cookieParser())
  //sessions are only used for flash
  app.use(session({secret: config.session_secret, resave: false, saveUninitialized: false}))
  app.use(flash())
  app.use(express.static('bower_components'))
  app.use(express.static('client'))
  app.set('config', config)
  app.set('view engine','haml' )

  app.engine('.haml', function(str, options, fn) {
    options.locals = util._extend({}, options)
    //debug('template locals', options.locals)
    return hamljs.renderFile(str, 'utf-8', options, fn)
  })

  app.use(function(req, res, next) {
    res.renderBody = function(name, locals) {
      locals = util._extend(res.locals, locals ? locals : {})

      app.render(name, locals, function(err, body) {
        return res.render('index.haml', util._extend(locals, {body: body}))
      })
    }

    req.config = config
    req.users = users

    res.locals.app_root = config.app_root ? config.app_root : '/'

    res.locals.messages = {
      info: req.flash('info'),
      error: req.flash('error')
    }

    return next()
  })

  app.use(function(req, res, next) {

    let user = req.cookies.user

    if(!user && req.query.key) {
      req.user = users.getByKey(req.query.key)

      if(!req.user) {
        return res.status(401).send('Key is not valid')
      }
    }

    if(req.url != '/login' && (!user || !user.username)) {
      return res.redirect('/login')
    }

    if(user && user.username) {
      req.user = users.get(user.username)

      //has a bad cookie
      if(!req.user) {
        res.cookie('user', {}, util._extend({}, {httpOnly: false}, {expires: -1}))
        return res.redirect('/login')
      }
    }

    res.locals.user = req.user || {}

    debug('User %o', user)

    return next()
  })

  //Load routes
  routes.Tree(app)
  routes.User(app)
  routes.Settings(app)
  routes.Admin(app)

  //key?
  app.get('/rss', function(req, res) {

    if(!req.query.key)
      return res.send(401, 'Authentication failed')
    res.send('rss')
  })

  //where is this ES6 feature?
  var users = new Users({database: p.resolve(__dirname, config.database)})

  //load users from file to memory
  return users.load()
  .then(err => console.log('Db loaded'))
  .then(e => Promise.resolve(app))
}
<commit_msg>fix(user): Key access<commit_after>var express = require('express')
var app = express()
var p = require('path')
var util = require('util')
var hamljs = require('hamljs')
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var session = require('express-session')
var flash = require('connect-flash')
var methodOverride = require('method-override')
var debug = require('debug')('explorer:server')

import {Users} from './lib/users.js'
import * as routes from './routes'

module.exports = function(config) {

  app.use(bodyParser.urlencoded({extended: false}))
  app.use(bodyParser.json())

  app.use(methodOverride(function(req, res) {
    if (req.body && typeof req.body === 'object' && '_method' in req.body) {
      // look in urlencoded POST bodies and delete it
      var method = req.body._method
      delete req.body._method
      return method
    }
  }))

  app.use(cookieParser())
  //sessions are only used for flash
  app.use(session({secret: config.session_secret, resave: false, saveUninitialized: false}))
  app.use(flash())
  app.use(express.static('bower_components'))
  app.use(express.static('client'))
  app.set('config', config)
  app.set('view engine','haml' )

  app.engine('.haml', function(str, options, fn) {
    options.locals = util._extend({}, options)
    //debug('template locals', options.locals)
    return hamljs.renderFile(str, 'utf-8', options, fn)
  })

  app.use(function(req, res, next) {
    res.renderBody = function(name, locals) {
      locals = util._extend(res.locals, locals ? locals : {})

      app.render(name, locals, function(err, body) {
        return res.render('index.haml', util._extend(locals, {body: body}))
      })
    }

    req.config = config
    req.users = users

    res.locals.app_root = config.app_root ? config.app_root : '/'

    res.locals.messages = {
      info: req.flash('info'),
      error: req.flash('error')
    }

    return next()
  })

  app.use(function(req, res, next) {

    let user = req.cookies.user

    if((!user || !user.username) && req.query.key) {
      user = req.user = users.getByKey(req.query.key)

      if(!req.user) {
        return res.status(401).send('Key is not valid')
      }
    }

    if(req.url != '/login' && (!user || !user.username)) {
      return res.redirect('/login')
    }

    if(user && user.username && !req.user) {
      req.user = users.get(user.username)

      //has a bad cookie
      if(!req.user) {
        res.cookie('user', {}, util._extend({}, {httpOnly: false}, {expires: -1}))
        return res.redirect('/login')
      }
    }

    res.locals.user = req.user || {}

    debug('User %o', user)

    return next()
  })

  //Load routes
  routes.Tree(app)
  routes.User(app)
  routes.Settings(app)
  routes.Admin(app)

  //key?
  app.get('/rss', function(req, res) {

    if(!req.query.key)
      return res.send(401, 'Authentication failed')
    res.send('rss')
  })

  //where is this ES6 feature?
  var users = new Users({database: p.resolve(__dirname, config.database)})

  //load users from file to memory
  return users.load()
  .then(err => console.log('Db loaded'))
  .then(e => Promise.resolve(app))
}
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var http = require('http').Server(app);

app.use(express.static('static'));

var server = http.listen(80, function () {
    var address = server.address();
    console.log('Listening on %s:%s', address.address, address.port);
});<commit_msg>infer html extension to files<commit_after>var express = require('express');
var app = express();
var http = require('http').Server(app);

app.use(express.static('static', {extensions: ['html']}));

var server = http.listen(80, function () {
    var address = server.address();
    console.log('Listening on %s:%s', address.address, address.port);
});<|endoftext|>


<commit_before>#! /usr/bin/node
const http = require('http')
const port = 3009
var express = require('express');
var app = express();
var fs = require('fs');
var RateLimit = require('express-rate-limit');

var limiter = new RateLimit({
  windowMs: 60*60*24, // 24h
  max: 100, // limit each IP to 100 requests per windowMs
  delayMs: 0 // disable delaying - full speed until the max limit is reached
});

app.use(limiter);

const getRandomFromList = (type, list) => {
	const ran = Math.floor(Math.random()*list.length);
	return list[ran];
}

const sendResponse = (request, response, data) => {
  let result;
  response.setHeader('charset', 'utf8');

  if (request.query.format == 'json') {
    response.setHeader("Content-Type", "application/json; charset=utf-8")
    result = JSON.stringify(data);
  } else {
    response.setHeader("Content-Type", "text/plain; charset=utf-8")
    result = data.text
  }
  const buffer = new Buffer(result)
  response.setHeader('Content-Length', buffer.length)
  response.end(buffer.toString('utf-8'))
}

app.get('/v1', function(req, res) {
  const file = req.query.file
  if (file === undefined || !fs.existsSync('config/' + file + '.json')) {
    sendResponse(req, res, {"success": false, "text": "No config file '" + file + "' found"})
    return
  } else {
    process.env.NODE_ENV = file
  }

  var config = require('config');

  const list = config.get("values")
  console.log('New request')

  const action = getRandomFromList('action', config.get("actions"))

  let text = config.get("texts")[action]

  if (config.has("texts.prefix")) {
    text = config.get("texts.prefix") + text
  }

 //	const result = text.replace('{train}', train).replace('{gleis}', gleis).replace('{city}', city).replace('{action}', action);
 	 text = text.replace(/{(\w+)}/g, function (w, m) {
 		return getRandomFromList(m, list[m]);
 });
 // dirty way to handle nested placeholders
 text = text.replace(/{(\w+)}/g, function (w, m) {
   return getRandomFromList(m, list[m]);
});

 console.log("Result: " + text);

   sendResponse(req, res, {"text": text})
})

app.listen(3009);
<commit_msg>changed port to 8080<commit_after>#! /usr/bin/node
const http = require('http')
const port = 3009
var express = require('express');
var app = express();
var fs = require('fs');
var RateLimit = require('express-rate-limit');

var limiter = new RateLimit({
  windowMs: 60*60*24, // 24h
  max: 100, // limit each IP to 100 requests per windowMs
  delayMs: 0 // disable delaying - full speed until the max limit is reached
});

app.use(limiter);

const getRandomFromList = (type, list) => {
	const ran = Math.floor(Math.random()*list.length);
	return list[ran];
}

const sendResponse = (request, response, data) => {
  let result;
  response.setHeader('charset', 'utf8');

  if (request.query.format == 'json') {
    response.setHeader("Content-Type", "application/json; charset=utf-8")
    result = JSON.stringify(data);
  } else {
    response.setHeader("Content-Type", "text/plain; charset=utf-8")
    result = data.text
  }
  const buffer = new Buffer(result)
  response.setHeader('Content-Length', buffer.length)
  response.end(buffer.toString('utf-8'))
}

app.get('/v1', function(req, res) {
  const file = req.query.file
  if (file === undefined || !fs.existsSync('config/' + file + '.json')) {
    sendResponse(req, res, {"success": false, "text": "No config file '" + file + "' found"})
    return
  } else {
    process.env.NODE_ENV = file
  }

  var config = require('config');

  const list = config.get("values")
  console.log('New request')

  const action = getRandomFromList('action', config.get("actions"))

  let text = config.get("texts")[action]

  if (config.has("texts.prefix")) {
    text = config.get("texts.prefix") + text
  }

 //	const result = text.replace('{train}', train).replace('{gleis}', gleis).replace('{city}', city).replace('{action}', action);
 	 text = text.replace(/{(\w+)}/g, function (w, m) {
 		return getRandomFromList(m, list[m]);
 });
 // dirty way to handle nested placeholders
 text = text.replace(/{(\w+)}/g, function (w, m) {
   return getRandomFromList(m, list[m]);
});

 console.log("Result: " + text);

   sendResponse(req, res, {"text": text})
})

app.listen(8080);
<|endoftext|>


<commit_before>var every       = require('schedule').every;
var express     = require('express');
var request     = require('request');
var cheerio     = require('cheerio');
var config      = require('./config.js');
var _           = require('lodash');
var TelegramBot = require('node-telegram-bot-api');
var app         = express();

var targetUrl = 'https://www.biyroamer.com/category/adidas/ultra-boost';
var token = config.telegram.token;
var bot = new TelegramBot(token);
var lastSend;

every('5s').do(function() {
    var data = [];
    request(targetUrl, function(error, response, html){
        if(!error){
            var $ = cheerio.load(html);
            $('.post-title.entry-title').first().filter(function(index, value){
                data.push({"link": value.children[0].attribs.href, "word": value.children[0].children[0].data, "datetime": null});
            });
            $('.entry-date.updated').first().filter(function(index, value){
                data[index].datetime = value.attribs.datetime;
            });
            if (lastSend != new Date(data[0].datetime).getTime()){
                var chatID = [];
                bot.getUpdates().then(function(result){
                    for(i in result){
                        chatID = _.union(chatID, [result[i].message.chat.id]);
                    }
                    for( id in chatID){
                        bot.sendMessage(chatID[id], data[0].word + "\n" + data[0].link + "\n" + data[0].datetime).then(function(resp){

                        }).catch(function(error) {
                            if (error.response && error.response.statusCode === 403) {
                                 console.log('bot was blocked by the user');
                        }});
                    }
                });
                lastSend = new Date(data[0].datetime).getTime();
            }
        }
    });
});

app.listen('8081');
exports = module.exports = app;<commit_msg>add the Error Handling:statusCode = 403<commit_after>var every       = require('schedule').every;
var express     = require('express');
var request     = require('request');
var cheerio     = require('cheerio');
var config      = require('./config.js');
var _           = require('lodash');
var TelegramBot = require('node-telegram-bot-api');
var app         = express();

var targetUrl = 'https://www.biyroamer.com/category/adidas/ultra-boost';
var token = config.telegram.token;
var bot = new TelegramBot(token);
var lastSend;

every('5s').do(function() {
    var data = [];
    request(targetUrl, function(error, response, html){
        if(!error){
            var $ = cheerio.load(html);
            $('.post-title.entry-title').first().filter(function(index, value){
                data.push({"link": value.children[0].attribs.href, "word": value.children[0].children[0].data, "datetime": null});
            });
            $('.entry-date.updated').first().filter(function(index, value){
                data[index].datetime = value.attribs.datetime;
            });
            if (lastSend != new Date(data[0].datetime).getTime()){
                var chatID = [];
                bot.getUpdates().then(function(result){
                    for(i in result){
                        chatID = _.union(chatID, [result[i].message.chat.id]);
                    }
                    for( id in chatID){
                        bot.sendMessage(chatID[id], data[0].word + "\n" + data[0].link + "\n" + data[0].datetime).then(function(resp){
                        }).catch(function(error) {
                            if (error.response && error.response.statusCode === 403) console.log('bot was blocked by the user');
                        });
                    }
                });
                lastSend = new Date(data[0].datetime).getTime();
            }
        }
    });
});

app.listen('8081');
exports = module.exports = app;<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var config = require('./config');
var mongoose = require('mongoose');
var passport = require('passport');
var CronJob = require('cron').CronJob;
var jobManager = require('./lib/jobManager.js');

var app = express();

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.set('jwtSecret', process.env.JWT_SECRET || 'thisisnotreallyasecretmorelikeaterces');
app.use(passport.initialize());
app.set('view engine', 'jade');
var jwtauth = require('./lib/jwt_auth')(app.get('jwtSecret'));
mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost/concierge_dev');

require('./routes/index')(app);
require('./routes/call')(app);
require('./routes/register_user')(app);
require('./routes/register_concierge')(app, jwtauth);
require('./routes/job')(app, jwtauth);
require('./routes/confirm_user')(app, jwtauth);
require('./routes/resendConfirmation')(app, jwtauth);
require('./routes/change_password')(app, jwtauth);
require('./routes/change_phone')(app, jwtauth);
require('./routes/change_username')(app, jwtauth);
require('./routes/password_reset')(app);
require('./routes/user_jobs')(app, jwtauth);
require('./routes/concierge_jobs')(app, jwtauth);

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.listen(config.port);

console.log('Concierge magic starts here..on port: ' + config.port);

var jobCheckCron = new CronJob('0 * * * * *', function() {
  jobManager.checkJobs();
  console.log('Checking jobs to move to the Queue');
}, null, false, 'America/Los_Angeles');

var jobQueueCheckCron = new CronJob('0 * * * * *', function() {
  jobManager.checkQueue();
  console.log('Checking jobs to send to Twilio');
}, null, false, 'America/Los_Angeles');
jobCheckCron.start();
jobQueueCheckCron.start();
<commit_msg>removed user_jobs from server.js<commit_after>'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var config = require('./config');
var mongoose = require('mongoose');
var passport = require('passport');
var CronJob = require('cron').CronJob;
var jobManager = require('./lib/jobManager.js');

var app = express();

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.set('jwtSecret', process.env.JWT_SECRET || 'thisisnotreallyasecretmorelikeaterces');
app.use(passport.initialize());
app.set('view engine', 'jade');
var jwtauth = require('./lib/jwt_auth')(app.get('jwtSecret'));
mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost/concierge_dev');

require('./routes/index')(app);
require('./routes/call')(app);
require('./routes/register_user')(app);
require('./routes/register_concierge')(app, jwtauth);
require('./routes/job')(app, jwtauth);
require('./routes/confirm_user')(app, jwtauth);
require('./routes/resendConfirmation')(app, jwtauth);
require('./routes/change_password')(app, jwtauth);
require('./routes/change_phone')(app, jwtauth);
require('./routes/change_username')(app, jwtauth);
require('./routes/password_reset')(app);
require('./routes/concierge_jobs')(app, jwtauth);

app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.listen(config.port);

console.log('Concierge magic starts here..on port: ' + config.port);

var jobCheckCron = new CronJob('0 * * * * *', function() {
  jobManager.checkJobs();
  console.log('Checking jobs to move to the Queue');
}, null, false, 'America/Los_Angeles');

var jobQueueCheckCron = new CronJob('0 * * * * *', function() {
  jobManager.checkQueue();
  console.log('Checking jobs to send to Twilio');
}, null, false, 'America/Los_Angeles');
jobCheckCron.start();
jobQueueCheckCron.start();
<|endoftext|>


<commit_before>#!/bin/env node

var ipaddress = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var http = require('http');
var async= require('async');
var request = require('request');
var inspect = require('eyes').inspector({  maxLength:null, stream:null });

http.createServer(function (req, res) {
    var data={};
    data.incoming="";
    req.on('data', function(d){  data.incoming+=d; })
    req.on('end',function(){
        async.series([
            function(next){
                if (data.incoming=="") next(1);
                data.inc=QueryStringToJSON(data.incoming);
                res.writeHead(200, {'Content-Type': 'text/plain'});
                request.get('http://api.rottentomatoes.com/api/public/v1.0/movies.json?q='+data.inc.text+
                    '&page_limit=1&page=1&apikey=***REMOVED***',function(e,r){
                    e&&(data.error=!0,data.errmsg='Error searching movies!');
                    if(r){
                        data.search=JSON.parse(r.body);
                        if (data.search.total&&data.search.total>0) {
                            data.error=!1;
                        } else {
                            data.error=!0;
                            data.errmsg='No movies found!';
                        }
                    }
                    next();
                });
            },
            function(next){
                data.out={};
                if (!data.error)
                request.get('http://api.rottentomatoes.com/api/public/v1.0/movies/'+data.search.movies[0].id+
                    '.json?apikey=***REMOVED***',function(e,r){
                    e&&(data.error=!0,data.errmsg='Error retrieving movie details!');
                    if(r){
                        data.movie=JSON.parse(r.body);
                        data.out.channel='#'+data.inc.channel_name;
                        data.out.username=data.movie.title;
                        data.out.text=data.movie.year+'';
                        data.movie.genres&&(data.out.text+=',    ',data.movie.genres.forEach(function(g){data.out.text+=g+', '}));
                        data.movie.runtime&&(data.out.text+='   '+data.movie.runtime+' minutes');
                        data.out.text+='\n';
                        data.out.text+='Critics Score: '
                        data.movie.ratings||(data.movie.ratings={});
                        if (!data.movie.ratings.critics_score||data.movie.ratings.critics_score==-1)
                            data.out.text+='n/a';
                        else
                            data.out.text+=data.movie.ratings.critics_score+'%';
                        data.out.text+=',       Audience Score: '
                        if (!data.movie.ratings.audience_score||data.movie.ratings.audience_score==-1)
                            data.out.text+='n/a';
                        else
                            data.out.text+=data.movie.ratings.audience_score+'%';
                        data.out.text+='\n';
                        data.out.text+='Director(abr.): ';
                        data.movie.abridged_directors&&(data.movie.abridged_directors.forEach(function(d){data.out.text+=d.name+' '}));
                        data.movie.studio&&(data.out.text+='        Studio: '+data.movie.studio);
                        data.out.text+='\n';
                        data.out.text+='Cast(abr.): ';
                        data.movie.abridged_cast&&(data.movie.abridged_cast.forEach(function(c){data.out.text+=c.name+(c.characters?' as '+c.characters[0]:'')+', '}));
                        data.out.text=data.out.text.slice(0,-2)+'\n\n';
                        data.movie.synopsis&&(data.out.text+=data.movie.synopsis);
                        data.out.text+='\n\nFor more info go to <'+data.movie.links.alternate+'|the full RT page>';
                        data.movie.alternate_ids&&data.movie.alternate_ids.imdb
                            &&(data.out.text+=' or go to <http://www.imdb.com/title/tt'+data.movie.alternate_ids.imdb+'|this title on IMDB>');
                    }
                    next();
                });
                else next();
            },
            function(next){
                data.error&&(data.out.text=data.errmsg,data.out.channel='#'+data.inc.channel_name,data.out.username='Error');
                data.out.text+='\n\n'+data.inc.user_name+': '+data.inc.command+' '+data.inc.text.split('+').join(' ');
                request.post('https://aem.slack.com/services/hooks/incoming-webhook?token=***REMOVED***',{ json: data.out },
                    function(e,r){
                        next();
                    });
            }
            ], function(e) {
                //e||(res.end(inspect(data.out).replace(/\[[\d]{1,2}m/g,"")));
                e&&(res.write('no POST'));
                res.end('');
            });
    })
}).listen(port, ipaddress);     // res.end('\n\n(brought to you by RT API, OpenShift, NodeJS and Wogan ..oO..)');
console.log('Server running at '+ipaddress+':'+port);

function QueryStringToJSON(qs) {
    var pairs = qs.split('&'), result = {};
    pairs.forEach(function(pair) {
        pair = pair.split('=');
        result[pair[0]] = decodeURIComponent(pair[1] || '');
    });
    return JSON.parse(JSON.stringify(result))
}<commit_msg>postback<commit_after>#!/bin/env node

var ipaddress = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var http = require('http');
var async= require('async');
var request = require('request');
var inspect = require('eyes').inspector({  maxLength:null, stream:null });

http.createServer(function (req, res) {
    var data={};
    data.incoming="";
    req.on('data', function(d){  data.incoming+=d; })
    req.on('end',function(){
        async.series([
            function(next){
                if (data.incoming=="") next(1);
                data.inc=QueryStringToJSON(data.incoming);
                res.writeHead(200, {'Content-Type': 'text/plain'});
                request.get('http://api.rottentomatoes.com/api/public/v1.0/movies.json?q='+data.inc.text+
                    '&page_limit=1&page=1&apikey=***REMOVED***',function(e,r){
                    e&&(data.error=!0,data.errmsg='Error searching movies!');
                    if(r){
                        data.search=JSON.parse(r.body);
                        if (data.search.total&&data.search.total>0) {
                            data.error=!1;
                        } else {
                            data.error=!0;
                            data.errmsg='No movies found!';
                        }
                    }
                    next();
                });
            },
            function(next){
                data.out={};
                if (!data.error)
                request.get('http://api.rottentomatoes.com/api/public/v1.0/movies/'+data.search.movies[0].id+
                    '.json?apikey=***REMOVED***',function(e,r){
                    e&&(data.error=!0,data.errmsg='Error retrieving movie details!');
                    if(r){
                        data.movie=JSON.parse(r.body);
                        data.out.channel='#'+data.inc.channel_name;
                        data.out.username=data.movie.title;
                        data.out.text=data.movie.year+'';
                        data.movie.genres&&(data.out.text+=',    ',data.movie.genres.forEach(function(g){data.out.text+=g+', '}));
                        data.movie.runtime&&(data.out.text+='   '+data.movie.runtime+' minutes');
                        data.out.text+='\n';
                        data.out.text+='Critics Score: '
                        data.movie.ratings||(data.movie.ratings={});
                        if (!data.movie.ratings.critics_score||data.movie.ratings.critics_score==-1)
                            data.out.text+='n/a';
                        else
                            data.out.text+=data.movie.ratings.critics_score+'%';
                        data.out.text+=',       Audience Score: '
                        if (!data.movie.ratings.audience_score||data.movie.ratings.audience_score==-1)
                            data.out.text+='n/a';
                        else
                            data.out.text+=data.movie.ratings.audience_score+'%';
                        data.out.text+='\n';
                        data.out.text+='Director(abr.): ';
                        data.movie.abridged_directors&&(data.movie.abridged_directors.forEach(function(d){data.out.text+=d.name+' '}));
                        data.movie.studio&&(data.out.text+='        Studio: '+data.movie.studio);
                        data.out.text+='\n';
                        data.out.text+='Cast(abr.): ';
                        data.movie.abridged_cast&&(data.movie.abridged_cast.forEach(function(c){data.out.text+=c.name+(c.characters?' as '+c.characters[0]:'')+', '}));
                        data.out.text=data.out.text.slice(0,-2)+'\n\n';
                        //data.movie.synopsis&&(data.out.text+=data.movie.synopsis);
                        data.out.text+='For more info go to <'+data.movie.links.alternate+'|the full RT page>';
                        data.movie.alternate_ids&&data.movie.alternate_ids.imdb
                            &&(data.out.text+=' or go to <http://www.imdb.com/title/tt'+data.movie.alternate_ids.imdb+'|this title on IMDB>');
                    }
                    next();
                });
                else next();
            },
            function(next){
                data.error&&(data.out.text=data.errmsg,data.out.channel='#'+data.inc.channel_name,data.out.username='Error');
                data.out.text+='\n\n'+data.inc.user_name+': '+data.inc.command+' '+data.inc.text.split('+').join(' ');
                request.post('https://aem.slack.com/services/hooks/incoming-webhook?token=***REMOVED***',{ json: data.out },
                    function(e,r){
                        next();
                    });
            }
            ], function(e) {
                //e||(res.end(inspect(data.out).replace(/\[[\d]{1,2}m/g,"")));
                e&&(res.write('no POST'));
                res.end('');
            });
    })
}).listen(port, ipaddress);     // res.end('\n\n(brought to you by RT API, OpenShift, NodeJS and Wogan ..oO..)');
console.log('Server running at '+ipaddress+':'+port);

function QueryStringToJSON(qs) {
    var pairs = qs.split('&'), result = {};
    pairs.forEach(function(pair) {
        pair = pair.split('=');
        result[pair[0]] = decodeURIComponent(pair[1] || '');
    });
    return JSON.parse(JSON.stringify(result))
}<|endoftext|>


<commit_before>var procstreams = require('procstreams');
var http = require('http');
var express = require('express');
var app = express();
var config = require('./config.json');
var path = require('path');
var bodyParser = require('body-parser');

app.use(bodyParser());
// 設定、啟動server
app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

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

config.targets.forEach(function (target) {
    var run = function (req, res) {
        var version = req.body.version;

        var isEMPTY = /^\s*$/i;
        if (isEMPTY.test(version)) {
            res.end("version number is required.");
            return;
        }

        var isHEAD = /^\s*head\s*$/i;
        if (target.requireVersion && (isHEAD.test(version))) {
            res.end("version number is required.");
            return;
        }

        var log = 'Update ' + target.name + ":";
        var opt = { cwd: target.path };
        log += "\n    at: " + new Date().toLocaleString();
        log += "\n    options: " + JSON.stringify(opt);
        var keeplocal = [].concat(target.keeplocal || []);
        if (keeplocal.length > 0)
            log += "\n    keeplocal: " + JSON.stringify(keeplocal);
        log += "\n";

        var cmdstream = null;
        var haserr = false;
        function command(cmd, logresult) {
            if (logresult !== false)
                logresult = true;
            if (cmdstream == null)
                cmdstream = procstreams(cmd, null, opt);
            else
                cmdstream = cmdstream.and(cmd, null, opt);

            cmdstream.data(function (err, stdout, stderr) {
                if (logresult) {
                    log += '\n' + cmd;
                    if (err)
                        log += "\n!" + JSON.stringify(err) + "";
                    if (stderr)
                        log += "\n*" + stderr + "";
                    if (stdout)
                        log += "\n>" + (stdout || "");
                    if (!stdout && !err && !stderr) {
                        log += "\n>no result.";
                    }
                    if (!log.match(/\n$/))
                        log += "\n";
                }

                console.log(cmd);
                if (err)
                    console.log("!" + JSON.stringify(err));
                if (stderr)
                    console.log("*" + stderr);
                console.log(">" + stdout); // prints number of lines in the file lines.txt

                if (err) {
                    haserr = true;
                    setTimeout(function () {
                        res.end(log);
                        if (target.mail) {
                            var nodemailer = require('nodemailer');
                            var transporter = nodemailer.createTransport(target.mail.smtpTransportOptions);
                            var mailOptions = {
                                from: target.mail.from, // sender address
                                to: target.mail.to, // list of receivers
                                subject: target.name + " updated failed!!!" , // Subject line
                                text: log // plaintext body
                            };
                            transporter.sendMail(mailOptions, function (error, info) {
                                if (error) {
                                    console.log('Mail error: ' + error);
                                } else {
                                    console.log('Mail sent: ' + info.response);
                                }
                            });
                        }
                    }, 800);
                }
            })
        }
        command('rm -rf ' + __dirname + '/__keeplocal');
        command('mkdir ' + __dirname + '/__keeplocal');
        keeplocal.forEach(function (file, index) {
            command('/bin/cp -f ' + file + ' ' + __dirname + '/__keeplocal/l' + index + '.l');
        });

        command('git fetch');

        if (version && version != "HEAD") {
            command('git show ' + version);
            command('git checkout -f ' + version);
        }
        else
            command('git checkout -f');

        keeplocal.forEach(function (file, index) {
            command('mv ' + file + ' ' + __dirname + '/__keeplocal/del' + index + '.l');
            command('mv ' + __dirname + '/__keeplocal/l' + index + '.l ' + file);
        });

        if (target.writeTag) {

            function pad2(n) {  // always returns a string
                return (n < 10 ? '0' : '') + n;
            }
            function pad3(n) {  // always returns a string
                return (n < 10 ? '00' : (n < 100 ? '0' : '')) + n;
            }

            var time = new Date();
            var deployT = time.getFullYear() + "." +
                pad2(time.getMonth() + 1) + "." +
                pad2(time.getDate()) + "-" +
                pad2(time.getHours()) + "." +
                pad2(time.getMinutes()) + "." +
                pad2(time.getSeconds()) + "." +
                pad3(time.getMilliseconds());
            var deployM = time.getFullYear() + "/" +
                pad2(time.getMonth() + 1) + "/" +
                pad2(time.getDate()) + " " +
                pad2(time.getHours()) + ":" +
                pad2(time.getMinutes()) + ":" +
                pad2(time.getSeconds());
            command("git tag -a " + deployT + " -m'" + deployM + "'", false);
            command('git push --tags', false);
        }
        cmdstream.on('exit', function () {
            setTimeout(function () {
                if (!haserr) {
                    res.end(log);
                    if (target.mail) {
                        var nodemailer = require('nodemailer');
                        var transporter = nodemailer.createTransport(target.mail.smtpTransportOptions);
                        var mailOptions = {
                            from: target.mail.from, // sender address
                            to: target.mail.to, // list of receivers
                            subject: target.name + " updated." , // Subject line
                            text: log // plaintext body
                        };
                        transporter.sendMail(mailOptions, function (error, info) {
                            if (error) {
                                console.log('Mail error: ' + error);
                            } else {
                                console.log('Mail sent: ' + info.response);
                            }
                            if (target.finalCommand) {
                                console.log('finalCommand: ' + target.finalCommand);
                                command(target.finalCommand, false);
                            }
                        });
                    } else {
                        if (target.finalCommand) {
                            console.log('finalCommand: ' + target.finalCommand);
                            command(target.finalCommand, false);
                        }
                    }
                }
            }, 1000);
        });
    };
    app.post('/' + target.name, run);
    app.get('/' + target.name, function (req, res) {
        res.render('root', { name: target.name });
    });
});
http.createServer(app).listen(config.port, function () {
    console.log('Express server listening on port ' + config.port);
});
<commit_msg>修改HEAD判斷<commit_after>var procstreams = require('procstreams');
var http = require('http');
var express = require('express');
var app = express();
var config = require('./config.json');
var path = require('path');
var bodyParser = require('body-parser');

app.use(bodyParser());
// 設定、啟動server
app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

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

config.targets.forEach(function (target) {
    var run = function (req, res) {
        var version = req.body.version;

        var isEMPTY = /^\s*$/i;
        if (isEMPTY.test(version)) {
            res.end("version number is required.");
            return;
        }

        var isHEAD = /^\s*head\s*$/i;
        if (target.requireVersion && (isHEAD.test(version))) {
            res.end("version number is required.");
            return;
        }

        var log = 'Update ' + target.name + ":";
        var opt = { cwd: target.path };
        log += "\n    at: " + new Date().toLocaleString();
        log += "\n    options: " + JSON.stringify(opt);
        var keeplocal = [].concat(target.keeplocal || []);
        if (keeplocal.length > 0)
            log += "\n    keeplocal: " + JSON.stringify(keeplocal);
        log += "\n";

        var cmdstream = null;
        var haserr = false;
        function command(cmd, logresult) {
            if (logresult !== false)
                logresult = true;
            if (cmdstream == null)
                cmdstream = procstreams(cmd, null, opt);
            else
                cmdstream = cmdstream.and(cmd, null, opt);

            cmdstream.data(function (err, stdout, stderr) {
                if (logresult) {
                    log += '\n' + cmd;
                    if (err)
                        log += "\n!" + JSON.stringify(err) + "";
                    if (stderr)
                        log += "\n*" + stderr + "";
                    if (stdout)
                        log += "\n>" + (stdout || "");
                    if (!stdout && !err && !stderr) {
                        log += "\n>no result.";
                    }
                    if (!log.match(/\n$/))
                        log += "\n";
                }

                console.log(cmd);
                if (err)
                    console.log("!" + JSON.stringify(err));
                if (stderr)
                    console.log("*" + stderr);
                console.log(">" + stdout); // prints number of lines in the file lines.txt

                if (err) {
                    haserr = true;
                    setTimeout(function () {
                        res.end(log);
                        if (target.mail) {
                            var nodemailer = require('nodemailer');
                            var transporter = nodemailer.createTransport(target.mail.smtpTransportOptions);
                            var mailOptions = {
                                from: target.mail.from, // sender address
                                to: target.mail.to, // list of receivers
                                subject: target.name + " updated failed!!!" , // Subject line
                                text: log // plaintext body
                            };
                            transporter.sendMail(mailOptions, function (error, info) {
                                if (error) {
                                    console.log('Mail error: ' + error);
                                } else {
                                    console.log('Mail sent: ' + info.response);
                                }
                            });
                        }
                    }, 800);
                }
            })
        }
        command('rm -rf ' + __dirname + '/__keeplocal');
        command('mkdir ' + __dirname + '/__keeplocal');
        keeplocal.forEach(function (file, index) {
            command('/bin/cp -f ' + file + ' ' + __dirname + '/__keeplocal/l' + index + '.l');
        });

        command('git fetch');

        if (version && isHEAD.test(version))
            command('git checkout -f');
        else {
            command('git show ' + version);
            command('git checkout -f ' + version);
        }

        keeplocal.forEach(function (file, index) {
            command('mv ' + file + ' ' + __dirname + '/__keeplocal/del' + index + '.l');
            command('mv ' + __dirname + '/__keeplocal/l' + index + '.l ' + file);
        });

        if (target.writeTag) {

            function pad2(n) {  // always returns a string
                return (n < 10 ? '0' : '') + n;
            }
            function pad3(n) {  // always returns a string
                return (n < 10 ? '00' : (n < 100 ? '0' : '')) + n;
            }

            var time = new Date();
            var deployT = time.getFullYear() + "." +
                pad2(time.getMonth() + 1) + "." +
                pad2(time.getDate()) + "-" +
                pad2(time.getHours()) + "." +
                pad2(time.getMinutes()) + "." +
                pad2(time.getSeconds()) + "." +
                pad3(time.getMilliseconds());
            var deployM = time.getFullYear() + "/" +
                pad2(time.getMonth() + 1) + "/" +
                pad2(time.getDate()) + " " +
                pad2(time.getHours()) + ":" +
                pad2(time.getMinutes()) + ":" +
                pad2(time.getSeconds());
            command("git tag -a " + deployT + " -m'" + deployM + "'", false);
            command('git push --tags', false);
        }
        cmdstream.on('exit', function () {
            setTimeout(function () {
                if (!haserr) {
                    res.end(log);
                    if (target.mail) {
                        var nodemailer = require('nodemailer');
                        var transporter = nodemailer.createTransport(target.mail.smtpTransportOptions);
                        var mailOptions = {
                            from: target.mail.from, // sender address
                            to: target.mail.to, // list of receivers
                            subject: target.name + " updated." , // Subject line
                            text: log // plaintext body
                        };
                        transporter.sendMail(mailOptions, function (error, info) {
                            if (error) {
                                console.log('Mail error: ' + error);
                            } else {
                                console.log('Mail sent: ' + info.response);
                            }
                            if (target.finalCommand) {
                                console.log('finalCommand: ' + target.finalCommand);
                                command(target.finalCommand, false);
                            }
                        });
                    } else {
                        if (target.finalCommand) {
                            console.log('finalCommand: ' + target.finalCommand);
                            command(target.finalCommand, false);
                        }
                    }
                }
            }, 1000);
        });
    };
    app.post('/' + target.name, run);
    app.get('/' + target.name, function (req, res) {
        res.render('root', { name: target.name });
    });
});
http.createServer(app).listen(config.port, function () {
    console.log('Express server listening on port ' + config.port);
});
<|endoftext|>


<commit_before>const hapi = require('hapi');
const axios = require('axios');
const path = require('path');
const base64 = require('base-64');

const server = new hapi.Server({
    cache : [{
            name      : 'diskCache',
            engine    : require('catbox-disk'),
            cachePath: path.join(__dirname,'cache'),
            cleanEvery: 86400000,
            partition : 'cache'
    }]
});

server.connection({
    host: process.env.HOST || '0.0.0.0',
    port: process.env.PORT || 8080
});

server.register(require('inert'), (err) => {
    if(err)
        throw err;
});

const getLicense = (account, repo, next) =>{
    const githubApiUrl = 'https://api.github.com/repos/' + account + '/'+ repo;
    axios.get(githubApiUrl + '/contents/.gitlicense')
    .then((res) => {
        content = JSON.parse(base64.decode(res.data.content));
        for(let license in content){
            const url = content[license];
            next(null,{
                license: license,
                url: url
                });
            }
        })
    .catch((err) => {
        axios.get(githubApiUrl + '/license',{
            headers: {'Accept':'application/vnd.github.drax-preview+json'}
        })
        .then((res) =>{
            next(null,{
                license: res.data.license.spdx_id,
                url: res.data.html_url
            });
        })
        .catch((err) => {
            next(err,null);
        });
    })
}

server.method('getLicense', getLicense,{
    cache:{
        cache:'diskCache',
        expiresIn: 86400000,
        generateTimeout: false
    }
});

const getBadge = (license, color, next) =>{
    const shieldsUrl = "https://img.shields.io/badge/license-"+ license + "-" + color + ".svg";
    axios.get(shieldsUrl)
    .then((res) =>{
        next(null,res.data);
    })
    .catch((err) =>{
        next(err,null);
    })
}

server.method('getBadge', getBadge,{
    cache:{
        cache:'diskCache',
        expiresIn: 86400000,
        generateTimeout: false
    }
});

const errorBadge = path.join(__dirname,'public/problem-unknown-red.svg');
server.route({
    path: '/{account}/{repo}/badge',
    method: 'GET',
    handler: (request, reply) => {
        const {account,repo} = request.params;
        const color = request.query.color || "brightgreen";
        server.methods.getLicense(account,repo, (err,result) => {
            if(err){
                reply.file(errorBadge).type('image/svg+xml');
            }
            else{
                server.methods.getBadge(result.license, color,(err, result) =>{
                    if(err){
                        reply.file(errorBadge).type('image/svg+xml');
                    }
                    else{
                        reply(result).type('image/svg+xml');
                    }
                })
            }
        })
    }
});

server.route({
    path: '/{account}/{repo}/license',
    method: 'GET',
    handler: (request, reply) =>{
        const {account, repo} = request.params;
        server.methods.getLicense(account, repo, (err,result) =>{
            if(err){
                reply.redirect('/');
            }else{
                reply.redirect(result.url);
            }
        })
    }
})

server.route({
    path: '/',
    method: 'GET',
    handler: (request, reply) =>{
        reply("Hello World");
    }
})
server.start(function(err) {
    if(err)
        console.log(err);
    else
        console.log('Server started: ' + server.info.uri);
});
<commit_msg>fix replace - in licenses' name with --<commit_after>const hapi = require('hapi');
const axios = require('axios');
const path = require('path');
const base64 = require('base-64');

const server = new hapi.Server({
    cache : [{
            name      : 'diskCache',
            engine    : require('catbox-disk'),
            cachePath: path.join(__dirname,'cache'),
            cleanEvery: 86400000,
            partition : 'cache'
    }]
});

server.connection({
    host: process.env.HOST || 'localhost',
    port: process.env.PORT || 3000,
    router: {
        isCaseSensitive: false,
        stripTrailingSlash: true
    },
    routes: {cors: true}
});

server.register(require('inert'), (err) => {
    if(err)
        throw err;
});

const getLicense = (account, repo, next) =>{
    const githubApiUrl = 'https://api.github.com/repos/' + account + '/'+ repo;
    axios.get(githubApiUrl + '/contents/.gitlicense')
    .then((res) => {
        content = JSON.parse(base64.decode(res.data.content));
        for(let license in content){
            const url = content[license];
            next(null,{
                license: license,
                url: url
                });
            }
        })
    .catch((err) => {
        axios.get(githubApiUrl + '/license',{
            headers: {'Accept':'application/vnd.github.drax-preview+json'}
        })
        .then((res) =>{
            next(null,{
                license: res.data.license.spdx_id,
                url: res.data.html_url
            });
        })
        .catch((err) => {
            next(err,null);
        });
    })
}

server.method('getLicense', getLicense,{
    cache:{
        cache:'diskCache',
        expiresIn: 86400000,
        generateTimeout: false
    }
});

const getBadge = (license, color, next) =>{
    const shieldsUrl = "https://img.shields.io/badge/license-"+ license.split('-').join('--') + "-" + color + ".svg";
    axios.get(shieldsUrl)
    .then((res) =>{
        next(null,res.data);
    })
    .catch((err) =>{
        next(err,null);
    })
}

server.method('getBadge', getBadge,{
    cache:{
        cache:'diskCache',
        expiresIn: 86400000,
        generateTimeout: false
    }
});

const errorBadge = path.join(__dirname,'public/problem-unknown-red.svg');
server.route({
    path: '/{account}/{repo}/badge',
    method: 'GET',
    handler: (request, reply) => {
        const {account,repo} = request.params;
        const color = request.query.color || "brightgreen";
        server.methods.getLicense(account,repo, (err,result) => {
            if(err){
                console.log("xxx");
                reply.file(errorBadge).type('image/svg+xml');
            }
            else{
                server.methods.getBadge(result.license, color,(err, result) =>{
                    if(err){
                        console.log("YYY");
                        reply.file(errorBadge).type('image/svg+xml');
                    }
                    else{
                        reply(result).type('image/svg+xml');
                    }
                })
            }
        })
    }
});

server.route({
    path: '/{account}/{repo}/license',
    method: 'GET',
    handler: (request, reply) =>{
        const {account, repo} = request.params;
        server.methods.getLicense(account, repo, (err,result) =>{
            if(err){
                reply.redirect('/');
            }else{
                reply.redirect(result.url);
            }
        })
    }
})

server.route({
    path: '/',
    method: 'GET',
    handler: (request, reply) =>{
        reply("Hello World");
    }
})
server.start(function(err) {
    if(err)
        console.log(err);
    else
        console.log('Server started: ' + server.info.uri);
});
<|endoftext|>