<commit_before>var url = require('url');
var config = require ('./config.js');
var configData = config.data;
var http = require('http');
var https = require('https');
var qs = require ('querystring');
var secure_post = false;
var pull_field = configData.pullField || "ref";

// start up our pull server
function startServer (instance_data, checkAndUpdateEnvironment, cb){
    // create a server to listen for pull requests
    function handleRequests (req, res){
        function parseURL (req){
            var url_in = url.parse (req.url, true);
            req.query = url_in.query;
            req.href = url_in.href;
        }
        function bodyParser (req, res, func){
            if (req.method == 'POST') {
                var body = '';
                req.on('data', function (data) {
                    body += data;
                    if (body.length > 524488) { // limit the most data someone can send to 1/2 a meg
                        request.connection.destroy();
                    }
                });
                req.on('end', function () {
                    try{req.body = JSON.parse (body);}
                    catch (e){req.body = qs.parse (body);}
                    if (func){func (req, res);}
                });
            }
        }
        if (req.url.search ("/pull") !== -1){ // handle a command to pull
            var valid_request = true;
            parseURL (req);
            if (configData.pullSecret){
                valid_request = (req.query.secret == configData.pullSecret) ? true : false;
            }
            if (valid_request){
                bodyParser (req, res, function (){
                    var listensTo = (instance_data && instance_data.listensTo) ? instance_data.listensTo : "";
                    req.body[pull_field] = req.body[pull_field] || "";
                    if (req.body[pull_field].search (listensTo) !== -1){
                        if (req.body.args){
                            configData.pullArgs = req.body.args;
                            config.update ();
                        }

                        var _master = req.query.master;
                        checkAndUpdateEnvironment (function (){
                            res.writeHead(200, {'Content-Type': 'text/plain'});
                            res.end("Pull Accepted");
                            var date = new Date ();
                            console.log ("\nPull Command, master:" + _master + " @" + date.toString ());
                            //console.log ("	body:%j", req.body);
                        }, req.query.master, req, res);
                    }
                    else{
                        var msg = "\nIgnoring Pull Request, wrong branch. \n\tListening for: " + listensTo +
                            "\n\t Recieved:" + req.body[pull_field];
                        console.log (msg);
                        res.writeHead(404, {'Content-Type': 'text/plain'});
                        res.end("Ignoring Pull Request, wrong branch.");
                    }
                });
            }
            else{
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end("Pull Not Authorized");
                console.log ("\nPull Not Authorized @" + date.toString ());
                console.log ("	Secret passed in:" + !!(req.query.secret));
                console.log ("	Secret required:" + !!configData.pullSecret);
                console.log ("	Secrets Match:" + (configData.pullSecret === req.query.secret));
            }
        }
        else{
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end("Not Found");
        }
    }
    var http_port = (configData.pullPort || 8000), key, cert, options;
    if (configData.pullKey && configData.pullCert){
        try {key = fs.readFileSync (configData.pullKey);}
        catch (err) {key = null;}
        try {cert = fs.readFileSync (configData.pullCert);}
        catch (err) {cert = null;}
        if (key && cert) {
            options = {key:key, cert:cert,
                ciphers: 'ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH',
                honorCipherOrder: true
            };
        }
        if (options && configData.pullPassphrase){
            options.passphrase = configData.pullPassphrase;
        }
        if (options && configData.pullCa && configData.pullCa.length){
            var ca = [];
            configData.pullCa.forEach (function (_ca){
                try {__ca = fs.readFileSync (_ca, {encoding: "aascii"});}
                catch (err) {__ca = null;}
                if (__ca){ ca.push (__ca);}
            });
            if (ca.length){
                options.ca = ca;
            }
        }
    }
    if (key && cert){
        secure_post = true;
        console.log ("\nHTTPS Pull Server Started. Listening on Port:" + http_port);
        https.createServer (options, handleRequests).listen (http_port);
    }
    else{
        secure_post = false;
        console.log ("\nWARNING cert and key not specified or invalid. Falling back to HTTP");
        console.log ("HTTP Pull Server Started. Listening on Port:" + http_port);
        http.createServer (handleRequests).listen (http_port);
    }
    cb && cb ();
}

exports.startServer = startServer;
<commit_msg>debugging code<commit_after>var url = require('url');
var config = require ('./config.js');
var configData = config.data;
var http = require('http');
var https = require('https');
var qs = require ('querystring');
var secure_post = false;
var pull_field = configData.pullField || "ref";

// start up our pull server
function startServer (instance_data, checkAndUpdateEnvironment, cb){
    // create a server to listen for pull requests
    function handleRequests (req, res){
        function parseURL (req){
            var url_in = url.parse (req.url, true);
            req.query = url_in.query;
            req.href = url_in.href;
        }
        function bodyParser (req, res, func){
            if (req.method == 'POST') {
                var body = '';
                req.on('data', function (data) {
                    body += data;
                    if (body.length > 524488) { // limit the most data someone can send to 1/2 a meg
                        request.connection.destroy();
                    }
                });
                req.on('end', function () {
                    try{req.body = JSON.parse (body);}
                    catch (e){req.body = qs.parse (body);}
                    if (func){func (req, res);}
                });
            }
        }
        if (req.url.search ("/pull") !== -1){ // handle a command to pull
            var valid_request = true;
            parseURL (req);
            if (configData.pullSecret){
                valid_request = (req.query.secret == configData.pullSecret) ? true : false;
            }
            if (valid_request){
                bodyParser (req, res, function (){
                    var listensTo = (instance_data && instance_data.listensTo) ? instance_data.listensTo : "";
                    req.body[pull_field] = req.body[pull_field] || "";
                    if (req.body[pull_field].search (listensTo) !== -1){
                        if (req.body.args){
                            var args;
                            try {args = JSON.parse (req.body.args);}
                            catch (e){}
                            configData.pullArgs = args || req.body.args;
                            config.update ();
                        }

                        var _master = req.query.master;
                        checkAndUpdateEnvironment (function (){
                            res.writeHead(200, {'Content-Type': 'text/plain'});
                            res.end("Pull Accepted");
                            var date = new Date ();
                            console.log ("\nPull Command, master:" + _master + " @" + date.toString ());
                            //console.log ("	body:%j", req.body);
                        }, req.query.master, req, res);
                    }
                    else{
                        var msg = "\nIgnoring Pull Request, wrong branch. \n\tListening for: " + listensTo +
                            "\n\t Recieved:" + req.body[pull_field];
                        console.log (msg);
                        res.writeHead(404, {'Content-Type': 'text/plain'});
                        res.end("Ignoring Pull Request, wrong branch.");
                    }
                });
            }
            else{
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end("Pull Not Authorized");
                console.log ("\nPull Not Authorized @" + date.toString ());
                console.log ("	Secret passed in:" + !!(req.query.secret));
                console.log ("	Secret required:" + !!configData.pullSecret);
                console.log ("	Secrets Match:" + (configData.pullSecret === req.query.secret));
            }
        }
        else{
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end("Not Found");
        }
    }
    var http_port = (configData.pullPort || 8000), key, cert, options;
    if (configData.pullKey && configData.pullCert){
        try {key = fs.readFileSync (configData.pullKey);}
        catch (err) {key = null;}
        try {cert = fs.readFileSync (configData.pullCert);}
        catch (err) {cert = null;}
        if (key && cert) {
            options = {key:key, cert:cert,
                ciphers: 'ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH',
                honorCipherOrder: true
            };
        }
        if (options && configData.pullPassphrase){
            options.passphrase = configData.pullPassphrase;
        }
        if (options && configData.pullCa && configData.pullCa.length){
            var ca = [];
            configData.pullCa.forEach (function (_ca){
                try {__ca = fs.readFileSync (_ca, {encoding: "aascii"});}
                catch (err) {__ca = null;}
                if (__ca){ ca.push (__ca);}
            });
            if (ca.length){
                options.ca = ca;
            }
        }
    }
    if (key && cert){
        secure_post = true;
        console.log ("\nHTTPS Pull Server Started. Listening on Port:" + http_port);
        https.createServer (options, handleRequests).listen (http_port);
    }
    else{
        secure_post = false;
        console.log ("\nWARNING cert and key not specified or invalid. Falling back to HTTP");
        console.log ("HTTP Pull Server Started. Listening on Port:" + http_port);
        http.createServer (handleRequests).listen (http_port);
    }
    cb && cb ();
}

exports.startServer = startServer;
<|endoftext|>


<commit_before>var Hapi = require('hapi'),
    settings = require('./config/settings');

var server = new Hapi.Server('localhost', settings.port);

// Add the server routes
server.route(require('./config/routes'));

//Start the server
server.start(function() {
    //Log to the console the host and port info
    console.log('Server started at: ' + server.info.uri);
});<commit_msg>loading models to server<commit_after>var Hapi = require('hapi'),
    settings = require('./config/settings'),
    models = require('./models/models');

var server = new Hapi.Server('localhost', settings.port);

// Add the server routes
server.route(require('./config/routes'));

//Start the server
server.start(function() {
    //Log to the console the host and port info
    console.log('Server started at: ' + server.info.uri);
});<|endoftext|>


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

var express = require('express');
var os = require('os');
var app = express();
var https = require('https');
var watch = require('node-watch');
var fs = require('fs');
var program = require('commander');
var chalk = require('chalk');
var clipboard = require('copy-paste');

var version = JSON.parse(fs.readFileSync(__dirname + '/package.json')).version;

var server = https.createServer({
    key: fs.readFileSync(__dirname + '/ssl/server.key'),
    cert: fs.readFileSync(__dirname + '/ssl/server.crt'),
    ca: fs.readFileSync(__dirname + '/ssl/ca.crt')
}, app);

var io = require('socket.io')(server);

program
    .usage('[options]')
    .version(version)
    .option('-p, --port <port>', 'Port number', 3000)
    .option('--no-color', 'Disable coloring')
    .option('--no-copy', 'Disable sending the JavaScript command to the clipboard')
    .parse(process.argv)

if (!program.color) {
    chalk.enable = false;
}

var revision = 'default';
var cwd = process.cwd();

var hosts = getNetworks().map(function (network) {
    return 'https://' + network.address + ':' + program.port;
});
var host = hosts[0];

var inClipboardMsg = '';

if (program.copy) {
    clipboard.copy('window.enableLiveReload(' + JSON.stringify(hosts) + ');');
    inClipboardMsg = chalk.yellow(' (it\'s already in your clipboard)');
}

server.listen(program.port, function () {
    console.log('Server listening on port', chalk.bold(program.port));
    console.log('')
    console.log(chalk.underline('To enable live reload do this:'));
    console.log('');
    console.log(chalk.bold(' *'), 'Open an article in', chalk.bold.blue('LayoutPreview'));
    console.log(chalk.bold(' *'), 'Open the', chalk.bold.blue('Web Inspector console'));
    console.log(chalk.bold(' *') + ' Run the following ' + chalk.bold.blue('JavaScript') + ' command%s:', inClipboardMsg);
    console.log('');
    console.log(chalk.white('    window.enableLiveReload(%s);'), chalk.green(JSON.stringify(hosts)));
    console.log('');
    console.log('NB! If you get', chalk.red('net::ERR_INSECURE_RESPONSE'), 'go to', chalk.yellow.bold(host + '/ready'), 'and allow the browser to use the self-signed certificate');
    console.log(chalk.bold('**********************************************************'));
    console.log('');
});

app.get('/ready', function (req, res) {
    res.send('Congratulations! You are ready to start using LayoutPreview live reload!');
});

app.use(express.static(cwd + '/assets', {
    setHeaders: function (res, path, stat) {
        res.set('Access-Control-Allow-Origin', '*');
    }
}));

var builders = [
    require('./builders/scss'),
    require('./builders/templates'),
    require('./builders/less')
];

io.on('connection', function (socket) {
    host = 'https://' + socket.handshake.headers.host;

    socket.on('revision', function (rev) {
        console.log('Assets revision', chalk.bold.magenta(rev) + "\n");

        revision = rev;
        startWatching();
    });

    socket.on('disconnect', function () {
        console.log(chalk.red('Client disconnected'));
    });
});

function buildAll() {
    builders.forEach(function (builder) {
        runBuilder(builder);
    });
}

function runBuilder(builder) {
    builder.build({
        revision: revision,
        host: host
    }, function (result) {
        console.log("[%s]\tbuild [ %s ]", chalk.bold.blue(builder.description || builder.type), chalk.bold.green('OK'));
        io.sockets.emit(builder.type, result);
    });
}

var isWatching = false;

function startWatching() {
    if (isWatching) {
        buildAll();
        return;
    }

    builders.forEach(function (builder) {
        if (!builder.activate) {
            watchBuilder(builder);
        } else {
            builder.activate()
                .then(function () {
                    watchBuilder(builder);
                })
                .catch(function (error) {
                    console.log(chalk.red(error));
                });
        }
    });

    isWatching = true;
}

function watchBuilder(builder) {
    runBuilder(builder);

    console.log(
        'Watching %s for %s',
        chalk.bold.magenta(builder.files.replace(cwd, '.')),
        chalk.bold.blue(builder.type)
    );

    watch(builder.files, function (filename) {
        if (!builder.filterFile(filename)) {
            return;
        }

        console.log(
            "[%s]\t%s changed",
            chalk.bold.blue(builder.type),
            chalk.bold.magenta(filename.replace(cwd, '.'))
        );

        runBuilder(builder);
    });
}

function getNetworks() {
    var interfaces = os.networkInterfaces();

    var ips = [];

    Object.keys(interfaces).forEach(function (iface) {
        var networks = interfaces[iface].filter(function (network) {
            return network.family === 'IPv4' && !network.internal;
        });

        networks.forEach(function (network) {
            ips.push({iface: iface, address: network.address});
        });
    });

    return ips;
}
<commit_msg>Fix wording<commit_after>#!/usr/bin/env node

var express = require('express');
var os = require('os');
var app = express();
var https = require('https');
var watch = require('node-watch');
var fs = require('fs');
var program = require('commander');
var chalk = require('chalk');
var clipboard = require('copy-paste');

var version = JSON.parse(fs.readFileSync(__dirname + '/package.json')).version;

var server = https.createServer({
    key: fs.readFileSync(__dirname + '/ssl/server.key'),
    cert: fs.readFileSync(__dirname + '/ssl/server.crt'),
    ca: fs.readFileSync(__dirname + '/ssl/ca.crt')
}, app);

var io = require('socket.io')(server);

program
    .usage('[options]')
    .version(version)
    .option('-p, --port <port>', 'Port number', 3000)
    .option('--no-color', 'Disable coloring')
    .option('--no-copy', 'Disable copying the JavaScript command to the clipboard')
    .parse(process.argv)

if (!program.color) {
    chalk.enable = false;
}

var revision = 'default';
var cwd = process.cwd();

var hosts = getNetworks().map(function (network) {
    return 'https://' + network.address + ':' + program.port;
});
var host = hosts[0];

var inClipboardMsg = '';

if (program.copy) {
    clipboard.copy('window.enableLiveReload(' + JSON.stringify(hosts) + ');');
    inClipboardMsg = chalk.yellow(' (it\'s already in your clipboard)');
}

server.listen(program.port, function () {
    console.log('Server listening on port', chalk.bold(program.port));
    console.log('')
    console.log(chalk.underline('To enable live reload do this:'));
    console.log('');
    console.log(chalk.bold(' *'), 'Open an article in', chalk.bold.blue('LayoutPreview'));
    console.log(chalk.bold(' *'), 'Open the', chalk.bold.blue('Web Inspector console'));
    console.log(chalk.bold(' *') + ' Run the following ' + chalk.bold.blue('JavaScript') + ' command%s:', inClipboardMsg);
    console.log('');
    console.log(chalk.white('    window.enableLiveReload(%s);'), chalk.green(JSON.stringify(hosts)));
    console.log('');
    console.log('NB! If you get', chalk.red('net::ERR_INSECURE_RESPONSE'), 'go to', chalk.yellow.bold(host + '/ready'), 'and allow the browser to use the self-signed certificate');
    console.log(chalk.bold('**********************************************************'));
    console.log('');
});

app.get('/ready', function (req, res) {
    res.send('Congratulations! You are ready to start using LayoutPreview live reload!');
});

app.use(express.static(cwd + '/assets', {
    setHeaders: function (res, path, stat) {
        res.set('Access-Control-Allow-Origin', '*');
    }
}));

var builders = [
    require('./builders/scss'),
    require('./builders/templates'),
    require('./builders/less')
];

io.on('connection', function (socket) {
    host = 'https://' + socket.handshake.headers.host;

    socket.on('revision', function (rev) {
        console.log('Assets revision', chalk.bold.magenta(rev) + "\n");

        revision = rev;
        startWatching();
    });

    socket.on('disconnect', function () {
        console.log(chalk.red('Client disconnected'));
    });
});

function buildAll() {
    builders.forEach(function (builder) {
        runBuilder(builder);
    });
}

function runBuilder(builder) {
    builder.build({
        revision: revision,
        host: host
    }, function (result) {
        console.log("[%s]\tbuild [ %s ]", chalk.bold.blue(builder.description || builder.type), chalk.bold.green('OK'));
        io.sockets.emit(builder.type, result);
    });
}

var isWatching = false;

function startWatching() {
    if (isWatching) {
        buildAll();
        return;
    }

    builders.forEach(function (builder) {
        if (!builder.activate) {
            watchBuilder(builder);
        } else {
            builder.activate()
                .then(function () {
                    watchBuilder(builder);
                })
                .catch(function (error) {
                    console.log(chalk.red(error));
                });
        }
    });

    isWatching = true;
}

function watchBuilder(builder) {
    runBuilder(builder);

    console.log(
        'Watching %s for %s',
        chalk.bold.magenta(builder.files.replace(cwd, '.')),
        chalk.bold.blue(builder.type)
    );

    watch(builder.files, function (filename) {
        if (!builder.filterFile(filename)) {
            return;
        }

        console.log(
            "[%s]\t%s changed",
            chalk.bold.blue(builder.type),
            chalk.bold.magenta(filename.replace(cwd, '.'))
        );

        runBuilder(builder);
    });
}

function getNetworks() {
    var interfaces = os.networkInterfaces();

    var ips = [];

    Object.keys(interfaces).forEach(function (iface) {
        var networks = interfaces[iface].filter(function (network) {
            return network.family === 'IPv4' && !network.internal;
        });

        networks.forEach(function (network) {
            ips.push({iface: iface, address: network.address});
        });
    });

    return ips;
}
<|endoftext|>


<commit_before>var Protocol = require('protocol');
var Url = require('fire-url');
var Path = require('fire-path');
var Fs = require('fire-fs');

// native protocol register

// register protocol editor-framework://
Protocol.registerProtocol('editor-framework', function(request) {
    var url = decodeURIComponent(request.url);
    var data = Url.parse(url);
    var relativePath = data.hostname;
    if ( data.pathname ) {
        relativePath = Path.join( relativePath, data.pathname );
    }
    var file = Path.join( Editor.frameworkPath, relativePath );
    return new Protocol.RequestFileJob(file);
});

// register protocol app://
Protocol.registerProtocol('app', function(request) {
    var url = decodeURIComponent(request.url);
    var data = Url.parse(url);
    var relativePath = data.hostname;
    if ( data.pathname ) {
        relativePath = Path.join( relativePath, data.pathname );
    }
    var file = Path.join( Editor.cwd, relativePath );
    return new Protocol.RequestFileJob(file);
});

// DISABLE
// // register protocol bower://
// Protocol.registerProtocol('bower', function(request) {
//     var url = decodeURIComponent(request.url);
//     var data = Url.parse(url);
//     var relativePath = data.hostname;
//     if ( data.pathname ) {
//         relativePath = Path.join( relativePath, data.pathname );
//     }
//     var file = Path.join( Editor.cwd, 'bower_components', relativePath );
//     return new Protocol.RequestFileJob(file);
// });

// register protocol packages://

Protocol.registerProtocol('packages', function(request) {
    var url = decodeURIComponent(request.url);
    var data = Url.parse(url);

    var packagePath = Editor.Package.packagePath(data.hostname);
    if ( packagePath ) {
        var packageInfo = Editor.Package.packageInfo(packagePath);
        if ( packageInfo ) {
            var file = Path.join( packageInfo._destPath, data.pathname );
            return new Protocol.RequestFileJob(file);
        }
    }
    return new Protocol.RequestErrorJob(-6); // net::ERR_FILE_NOT_FOUND
});

// register protocol widgets://
Protocol.registerProtocol('widgets', function(request) {
    var url = decodeURIComponent(request.url);
    var data = Url.parse(url);

    var info = Editor.Package.widgetInfo(data.hostname);
    if ( info ) {
        var file = Path.join( info.path, data.pathname );
        return new Protocol.RequestFileJob(file);
    }
    return new Protocol.RequestErrorJob(-6); // net::ERR_FILE_NOT_FOUND
});

// Editor.url protocol register

Editor._protocol2fn = {};

function _url2path ( base ) {
    return function ( urlInfo ) {
        if ( urlInfo.pathname ) {
            return Path.join( base, urlInfo.host, urlInfo.pathname );
        }
        return Path.join( base, urlInfo.host );
    };
}

function _packages2path ( urlInfo ) {
    var packagePath = Editor.Package.packagePath(urlInfo.hostname);
    if ( packagePath ) {
        return Path.join( packagePath, urlInfo.pathname );
    }
    return '';
}

/**
 * Convert a url by its protocol to a filesystem path. This function is useful when you try to
 * get some internal file. You can use {@link Editor.registerProtocol} to register and map your filesystem
 * path to url. By default, Editor Framework register `editor-framework://` and `app://` protocol.
 * @param {string} url
 * @example
 * // it will return "{your-app-path}/foobar/foobar.js"
 * Editor.url('app://foobar/foobar.js');
 */
Editor.url = function ( url ) {
    var urlInfo = Url.parse(url);

    if ( !urlInfo.protocol ) {
        Editor.error( 'Invalid url %s.', url );
        return null;
    }

    var fn = Editor._protocol2fn[urlInfo.protocol];
    if ( !fn ) {
        Editor.error( 'Failed to load url %s, please register the protocol for it.', url );
        return null;
    }

    return fn(urlInfo);
};

/**
 * Require module through url path
 * @param {string} url
 */
Editor.require = function ( url ) {
    return require( Editor.url(url) );
};

/**
 * Register a protocol so that {@link Editor.url} can use it to convert an url to the filesystem path.
 * The `fn` accept an url Object via [url.parse](https://iojs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost)
 * @param {string} protocol
 * @param {function} fn
 * @example
 * var Path = require('path');
 *
 * var _url2path = function ( base ) {
 *     return function ( urlInfo ) {
 *         if ( urlInfo.pathname ) {
 *             return Path.join( base, urlInfo.host, urlInfo.pathname );
 *         }
 *         return Path.join( base, urlInfo.host );
 *     };
 * };
 *
 * Editor.registerProtocol('editor-framework', _url2path(Editor.frameworkPath));
 */
Editor.registerProtocol = function ( protocol, fn ) {
    Editor._protocol2fn[protocol+':'] = fn;
};

Editor.registerProtocol('editor-framework', _url2path(Editor.frameworkPath));
Editor.registerProtocol('app', _url2path(Editor.cwd));
Editor.registerProtocol('packages', _packages2path);
<commit_msg>remove widgets protocol<commit_after>var Protocol = require('protocol');
var Url = require('fire-url');
var Path = require('fire-path');
var Fs = require('fire-fs');

// native protocol register

// register protocol editor-framework://
Protocol.registerProtocol('editor-framework', function(request) {
    var url = decodeURIComponent(request.url);
    var data = Url.parse(url);
    var relativePath = data.hostname;
    if ( data.pathname ) {
        relativePath = Path.join( relativePath, data.pathname );
    }
    var file = Path.join( Editor.frameworkPath, relativePath );
    return new Protocol.RequestFileJob(file);
});

// register protocol app://
Protocol.registerProtocol('app', function(request) {
    var url = decodeURIComponent(request.url);
    var data = Url.parse(url);
    var relativePath = data.hostname;
    if ( data.pathname ) {
        relativePath = Path.join( relativePath, data.pathname );
    }
    var file = Path.join( Editor.cwd, relativePath );
    return new Protocol.RequestFileJob(file);
});

// register protocol packages://

Protocol.registerProtocol('packages', function(request) {
    var url = decodeURIComponent(request.url);
    var data = Url.parse(url);

    var packagePath = Editor.Package.packagePath(data.hostname);
    if ( packagePath ) {
        var packageInfo = Editor.Package.packageInfo(packagePath);
        if ( packageInfo ) {
            var file = Path.join( packageInfo._destPath, data.pathname );
            return new Protocol.RequestFileJob(file);
        }
    }
    return new Protocol.RequestErrorJob(-6); // net::ERR_FILE_NOT_FOUND
});

// DISABLE: this make protocol can not use relative path
// // register protocol bower://
// Protocol.registerProtocol('bower', function(request) {
//     var url = decodeURIComponent(request.url);
//     var data = Url.parse(url);
//     var relativePath = data.hostname;
//     if ( data.pathname ) {
//         relativePath = Path.join( relativePath, data.pathname );
//     }
//     var file = Path.join( Editor.cwd, 'bower_components', relativePath );
//     return new Protocol.RequestFileJob(file);
// });

// DISABLE: same reason as bower
// // register protocol widgets://
// Protocol.registerProtocol('widgets', function(request) {
//     var url = decodeURIComponent(request.url);
//     var data = Url.parse(url);

//     var info = Editor.Package.widgetInfo(data.hostname);
//     if ( info ) {
//         var file = Path.join( info.path, data.pathname );
//         return new Protocol.RequestFileJob(file);
//     }
//     return new Protocol.RequestErrorJob(-6); // net::ERR_FILE_NOT_FOUND
// });

// Editor.url protocol register

Editor._protocol2fn = {};

function _url2path ( base ) {
    return function ( urlInfo ) {
        if ( urlInfo.pathname ) {
            return Path.join( base, urlInfo.host, urlInfo.pathname );
        }
        return Path.join( base, urlInfo.host );
    };
}

function _packages2path ( urlInfo ) {
    var packagePath = Editor.Package.packagePath(urlInfo.hostname);
    if ( packagePath ) {
        return Path.join( packagePath, urlInfo.pathname );
    }
    return '';
}

/**
 * Convert a url by its protocol to a filesystem path. This function is useful when you try to
 * get some internal file. You can use {@link Editor.registerProtocol} to register and map your filesystem
 * path to url. By default, Editor Framework register `editor-framework://` and `app://` protocol.
 * @param {string} url
 * @example
 * // it will return "{your-app-path}/foobar/foobar.js"
 * Editor.url('app://foobar/foobar.js');
 */
Editor.url = function ( url ) {
    var urlInfo = Url.parse(url);

    if ( !urlInfo.protocol ) {
        Editor.error( 'Invalid url %s.', url );
        return null;
    }

    var fn = Editor._protocol2fn[urlInfo.protocol];
    if ( !fn ) {
        Editor.error( 'Failed to load url %s, please register the protocol for it.', url );
        return null;
    }

    return fn(urlInfo);
};

/**
 * Require module through url path
 * @param {string} url
 */
Editor.require = function ( url ) {
    return require( Editor.url(url) );
};

/**
 * Register a protocol so that {@link Editor.url} can use it to convert an url to the filesystem path.
 * The `fn` accept an url Object via [url.parse](https://iojs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost)
 * @param {string} protocol
 * @param {function} fn
 * @example
 * var Path = require('path');
 *
 * var _url2path = function ( base ) {
 *     return function ( urlInfo ) {
 *         if ( urlInfo.pathname ) {
 *             return Path.join( base, urlInfo.host, urlInfo.pathname );
 *         }
 *         return Path.join( base, urlInfo.host );
 *     };
 * };
 *
 * Editor.registerProtocol('editor-framework', _url2path(Editor.frameworkPath));
 */
Editor.registerProtocol = function ( protocol, fn ) {
    Editor._protocol2fn[protocol+':'] = fn;
};

Editor.registerProtocol('editor-framework', _url2path(Editor.frameworkPath));
Editor.registerProtocol('app', _url2path(Editor.cwd));
Editor.registerProtocol('packages', _packages2path);
<|endoftext|>


<commit_before>console.log('This process is pid ' + process.pid);

var net = require("net");
var fs = require("fs");
var http = require("http");
var _ = require("underscore");
var express = require("express");
var io = require("socket.io");
var connect = require("connect");
var SessionSockets = require("session.socket.io");

var config = require("./config.js");

console.log(config);
var generalOpt = config.generalOpt;
var ircOpt = config.ircOpt;
var httpOpt = config.httpOpt;

if (generalOpt.timezone) {
    process.env.TZ = generalOpt.timezone;
    console.log(new Date().toString());
}

var logs = [];
var lastServerMsg = null;
var broadcasting = [];

var ircSeparator = "\n\r";

var logId = 0;
function newLogItem(type, msg) {
    var newlog = {type: type, id: logId++, msg: msg, timestamp: new Date().getTime()};
    var isAutoPingPong = ((type === "sc" && msg.substring(0, 4) === "PING") || (type === "cs" && msg.substring(0, 4) === "PONG"));
    if (generalOpt.logPingPong || !isAutoPingPong) {
        logs.push(newlog);
    }
    return newlog;
}

var client;
var fixedTyping = "";
function write(msg) {
    client.write(msg);
    client.write(ircSeparator);
    broadcastNewLogs([newLogItem("cs", msg)]);
}
function startIRC() {
    client = net.connect({host: "chat.freenode.net", port: 6667}, function() {
        broadcastNewLogs([newLogItem("log", "Client connected")]);
        console.log("Client connected");
        // USER Joonsoo . . :Joonsoo Jeon
        // NICK Joonsoo1
        write("USER " + ircOpt.username + " . . :" + ircOpt.fullname);
        write("NICK " + ircOpt.nickname);
    });
    client.on("data", function(data) {
        var lines = data.toString().split("\r\n");
        var finePackets = (lines[lines.length - 1] === "");
        if (finePackets) {
            lines.pop();
            if (lines.length === 0) return;
        }
        var newlogs = [];
        if (lastServerMsg) {
            lastServerMsg.msg += lines[0];
            newlogs.push(lastServerMsg);
        } else {
            lastServerMsg = newLogItem("sc", lines[0]);
            newlogs.push(lastServerMsg);
        }
        for (var i = 1; i < lines.length; i++) {
            lastServerMsg = newLogItem("sc", lines[i]);
            newlogs.push(lastServerMsg);
        }
        broadcastNewLogs(newlogs);
        for (var i = 0; i < newlogs.length - 1; i++) {
            processMsg(newlogs[i]);
        }
        if (finePackets) {
            lastServerMsg = null;
            processMsg(newlogs[newlogs.length - 1]);
        }
    });
    client.on("end", function() {
        broadcastNewLogs([newLogItem("log", "Connection closed")]);
    });
}
startIRC();

function broadcastNewLogs(newlogs) {
    _.each(broadcasting, function (socket) {
        socket.emit("log", newlogs);
    });
}
function processMsg(log) {
    if (log.msg.substring(0, 4) === "PING") {
        write("PONG" + log.msg.substring(4));
    }
}

var app = express();

var cookieParser = express.cookieParser(generalOpt.cookieSecret);
var sessionStore = new connect.middleware.session.MemoryStore();

app.use(express.bodyParser());
app.use(cookieParser);
app.use(express.session({
    key: generalOpt.sessionKey,
    store: sessionStore
}));

var sessionIds = [];
var createSessionId = function() {
    var generateRandomKey = function() {
        return "" + Math.round(Math.random() * 10000);
    }
    var randomKey = generateRandomKey();
    while (_.contains(sessionIds, randomKey)) {
        randomKey = generateRandomKey();
    }
    return randomKey;
};
var isValidSessionId = function(sessionId) {
    console.log(sessionIds, sessionId);
    return _.contains(sessionIds, sessionId);
}
app.post("/login", function(req, res) {
    if (req.body.passphrase === generalOpt.password) {
        var newSessionId = createSessionId();
        sessionIds.push(newSessionId);
        req.session.cookie.maxAge = 1000*24*60*60*1000;     // remeber this user for 1000 days
        req.session.verified = newSessionId;
        broadcastNewLogs([newLogItem("syslog", "New session: " + newSessionId)]);
    } else {
        req.session.destroy();
    }
    broadcastAllSessions();
    res.redirect("/");
});
app.get("/logout", function(req, res) {
    if (req.session && isValidSessionId(req.session.verified)) {
        var verified = req.session.verified;
        broadcastNewLogs([newLogItem("syslog", "Session closed: " + verified)]);
        setTimeout(function() {
            _.each(broadcasting, function(socket) {
                if (socket.__verified === verified) {
                    socket.emit("logout");
                    setTimeout(function() {
                        socket.disconnect();
                    }, 200);
                }
            });
        }, 200);
    }
    sessionIds = _.without(sessionIds, req.session.verified);
    broadcastAllSessions();
    req.session.destroy();
    res.redirect("/");
});
app.get("/", function(req, res) {
    console.log("/");
    console.log(req.session);
    if (req.session && isValidSessionId(req.session.verified)) {
        res.sendfile(__dirname + "/tmpl/index.html");
    } else {
        res.sendfile(__dirname + "/tmpl/login.html");
    }
});
app.get("/alllogs", function(req, res) {
    if (req.session && isValidSessionId(req.session.verified)) {
        res.send(logs);
    } else {
        res.redirect("/");
    }
});

app.use(express.static(__dirname + "/static"));

var httpServer = http.createServer(app);

httpServer.listen(httpOpt.port);

var allSocketsData = function() {
    return _.countBy(broadcasting, function(socket) { return socket.__verified; });
};
var broadcastAllSessions = function() {
    _.each(broadcasting, function(socket) {
        socket.emit("allSessions", {sessionId: socket.__session.verified, allSessions: sessionIds, allSockets: allSocketsData()});
    });
};

var iolisten = io.listen(httpServer);
iolisten.set('log level', 0);
var sockets = new SessionSockets(iolisten, sessionStore, cookieParser, generalOpt.sessionKey);
var socketAddr = function(socket) {
    var address = socket.handshake.address;
    return address.address + ":" + address.port;
}
sockets.on('connection', function(err, socket, session) {
    console.log("socket connection");
    console.log(session);
    if (err || (!session || !isValidSessionId(session.verified))) {
        console.log("invalid socket session");
        socket.disconnect();
        return;
    }
    console.log("new socket accepted");
    var addresses = _.map(broadcasting, socketAddr);
    socket.__session = session;
    socket.__verified = session.verified;
    broadcastNewLogs([newLogItem("syslog2", socket.__verified + "(" + socketAddr(socket) + ") connected")]);
    broadcasting.push(socket);
    if (logs.length > 50) {
        socket.emit("log", logs.slice(logs.length - 50));
    } else {
        socket.emit("log", logs);
    }
    if (fixedTyping) {
        socket.emit("fixedTyping", fixedTyping);
    }
    broadcastAllSessions();
    // allSessions will be emitted twice generally - when /login succeeded, when socket connected
    socket.on("clearSessions", function(data) {
        broadcastNewLogs([newLogItem("syslog", "/session " + session.verified + " cleared all other sessions")]);
        var aliveSockets = [];
        _.each(broadcasting, function(socket) {
            if (socket.__verified === session.verified) {
                aliveSockets.push(socket);
            } else {
                socket.emit("kickout");
                setTimeout(function() {
                    socket.disconnect();
                }, 200);
            }
        });
        sessionIds = [session.verified];
        broadcasting = aliveSockets;
        broadcastAllSessions();
    });
    var addresses = _.map(broadcasting, socketAddr);
    socket.on("send", function(data) {
        var lowerCased = data.toLowerCase().trim();
        if (lowerCased === "/restart") {
            broadcastNewLogs([newLogItem("log", "/restart")]);
            if (client) client.end();
            client = null;
            startIRC();
        } else if (lowerCased === "/save") {
            saveLog(function (filename, err) {
                if (err) {
                    broadcastNewLogs([newLogItem("syslog", "/error while saving to " + filename + " -- " + JSON.stringify(err))]);
                } else {
                    broadcastNewLogs([newLogItem("syslog", "/saved to " + filename)]);
                }
            });
        } else if (lowerCased === "/clear") {
            saveLog(function (filename, err) {
                if (err) {
                    broadcastNewLogs([newLogItem("syslog", "/error while saving to " + filename + " -- " + JSON.stringify(err))]);
                } else {
                    logs = [];
                    broadcastNewLogs([newLogItem("syslog", "/clear logs after save logs to " + filename)]);
                }
            });
        } else {
            write(data);
        }
    });
    socket.on("older", function(data) {
        var oldest = data.clientOldest;
        if (oldest !== undefined) {
            var oldestIndex;
            for (var i = 0; i < logs.length; i++) {
                if (logs[i].id >= oldest) {
                    oldestIndex = i;
                    break;
                }
            }
            socket.emit("older", logs.slice(Math.max(0, oldestIndex - 50), oldestIndex));
        }
    });
    socket.on("fixedTyping", function (data) {
        fixedTyping = data;
        _.each(broadcasting, function (socket) {
            socket.emit("fixedTyping", fixedTyping);
        });
    });
    socket.on("disconnect", function () {
        broadcasting = _.reject(broadcasting, function(conn) { return conn === socket; });
        var addresses = _.map(broadcasting, socketAddr);
        broadcastNewLogs([newLogItem("syslog2", socket.__verified + "(" + socketAddr(socket) + ") disconnected")]);
        broadcastAllSessions();
    });
});

var saveLog = function (donecb) {
    console.log("Saving logs...");
    var filename = "./logs/SelfIRC-logs-" + (new Date().toString()) + ".txt";
    fs.writeFile(filename, JSON.stringify(logs), function(err) {
        console.log(err);
        if (donecb) {
            donecb(filename, err);
        }
    });
    return filename;
};
setInterval(saveLog, 8*60*60*1000);		// every 8 hours
process.on("exit", saveLog);			// on exit
<commit_msg>Update server.js<commit_after>console.log('This process is pid ' + process.pid);

var net = require("net");
var fs = require("fs");
var http = require("http");
var _ = require("underscore");
var express = require("express");
var io = require("socket.io");
var connect = require("connect");
var SessionSockets = require("session.socket.io");

var config = require("./config.js");

console.log(config);
var generalOpt = config.generalOpt;
var ircOpt = config.ircOpt;
var httpOpt = config.httpOpt;

if (generalOpt.timezone) {
    process.env.TZ = generalOpt.timezone;
    console.log(new Date().toString());
}

var logs = [];
var lastServerMsg = null;
var broadcasting = [];

var ircSeparator = "\n\r";

var logId = 0;
function newLogItem(type, msg) {
    var newlog = {type: type, id: logId++, msg: msg, timestamp: new Date().getTime()};
    var isAutoPingPong = ((type === "sc" && msg.substring(0, 4) === "PING") || (type === "cs" && msg.substring(0, 4) === "PONG"));
    if (generalOpt.logPingPong || !isAutoPingPong) {
        logs.push(newlog);
    }
    return newlog;
}

var client;
var fixedTyping = "";
function write(msg) {
    client.write(msg);
    client.write(ircSeparator);
    broadcastNewLogs([newLogItem("cs", msg)]);
}
function startIRC() {
    client = net.connect({host: "chat.freenode.net", port: 6667}, function() {
        broadcastNewLogs([newLogItem("log", "Client connected")]);
        console.log("Client connected");
        // USER Joonsoo . . :Joonsoo Jeon
        // NICK Joonsoo1
        write("USER " + ircOpt.username + " . . :" + ircOpt.fullname);
        write("NICK " + ircOpt.nickname);
    });
    client.on("data", function(data) {
        var lines = data.toString().split("\r\n");
        var finePackets = (lines[lines.length - 1] === "");
        if (finePackets) {
            lines.pop();
            if (lines.length === 0) return;
        }
        var newlogs = [];
        if (lastServerMsg) {
            lastServerMsg.msg += lines[0];
            newlogs.push(lastServerMsg);
        } else {
            lastServerMsg = newLogItem("sc", lines[0]);
            newlogs.push(lastServerMsg);
        }
        for (var i = 1; i < lines.length; i++) {
            lastServerMsg = newLogItem("sc", lines[i]);
            newlogs.push(lastServerMsg);
        }
        broadcastNewLogs(newlogs);
        for (var i = 0; i < newlogs.length - 1; i++) {
            processMsg(newlogs[i]);
        }
        if (finePackets) {
            lastServerMsg = null;
            processMsg(newlogs[newlogs.length - 1]);
        }
    });
    client.on("end", function() {
        broadcastNewLogs([newLogItem("log", "Connection closed")]);
    });
}
startIRC();

function broadcastNewLogs(newlogs) {
    _.each(broadcasting, function (socket) {
        socket.emit("log", newlogs);
    });
}
function processMsg(log) {
    if (log.msg.substring(0, 4) === "PING") {
        write("PONG" + log.msg.substring(4));
    }
}

var app = express();

var cookieParser = express.cookieParser(generalOpt.cookieSecret);
var sessionStore = new connect.middleware.session.MemoryStore();

app.use(express.bodyParser());
app.use(cookieParser);
app.use(express.session({
    key: generalOpt.sessionKey,
    store: sessionStore
}));

var sessionIds = [];
var createSessionId = function() {
    var generateRandomKey = function() {
        return "" + Math.round(Math.random() * 10000);
    }
    var randomKey = generateRandomKey();
    while (_.contains(sessionIds, randomKey)) {
        randomKey = generateRandomKey();
    }
    return randomKey;
};
var isValidSessionId = function(sessionId) {
    console.log(sessionIds, sessionId);
    return _.contains(sessionIds, sessionId);
}
app.post("/login", function(req, res) {
    if (req.body.passphrase === generalOpt.password) {
        var newSessionId = createSessionId();
        sessionIds.push(newSessionId);
        req.session.cookie.maxAge = 1000*24*60*60*1000;     // remeber this user for 1000 days
        req.session.verified = newSessionId;
        broadcastNewLogs([newLogItem("syslog", "New session: " + newSessionId)]);
    } else {
        req.session.destroy();
    }
    broadcastAllSessions();
    res.redirect("/");
});
app.get("/logout", function(req, res) {
    if (req.session && isValidSessionId(req.session.verified)) {
        var verified = req.session.verified;
        broadcastNewLogs([newLogItem("syslog", "Session closed: " + verified)]);
        setTimeout(function() {
            _.each(broadcasting, function(socket) {
                if (socket.__verified === verified) {
                    socket.emit("logout");
                    setTimeout(function() {
                        socket.disconnect();
                    }, 200);
                }
            });
        }, 200);
    }
    sessionIds = _.without(sessionIds, req.session.verified);
    broadcastAllSessions();
    req.session.destroy();
    res.redirect("/");
});
app.get("/", function(req, res) {
    console.log("/");
    console.log(req.session);
    if (req.session && isValidSessionId(req.session.verified)) {
        res.sendfile(__dirname + "/tmpl/index.html");
    } else {
        res.sendfile(__dirname + "/tmpl/login.html");
    }
});
app.get("/alllogs", function(req, res) {
    if (req.session && isValidSessionId(req.session.verified)) {
        res.send(logs);
    } else {
        res.redirect("/");
    }
});

app.use(express.static(__dirname + "/static"));

var httpServer = http.createServer(app);

httpServer.listen(httpOpt.port);

var allSocketsData = function() {
    return _.countBy(broadcasting, function(socket) { return socket.__verified; });
};
var broadcastAllSessions = function() {
    _.each(broadcasting, function(socket) {
        socket.emit("allSessions", {sessionId: socket.__session.verified, allSessions: sessionIds, allSockets: allSocketsData()});
    });
};

var iolisten = io.listen(httpServer);
iolisten.set('log level', 0);
var sockets = new SessionSockets(iolisten, sessionStore, cookieParser, generalOpt.sessionKey);
var socketAddr = function(socket) {
    var address = socket.handshake.address;
    return address.address + ":" + address.port;
}
sockets.on('connection', function(err, socket, session) {
    console.log("socket connection");
    console.log(session);
    if (err || (!session || !isValidSessionId(session.verified))) {
        console.log("invalid socket session");
        socket.disconnect();
        return;
    }
    console.log("new socket accepted");
    var addresses = _.map(broadcasting, socketAddr);
    socket.__session = session;
    socket.__verified = session.verified;
    broadcastNewLogs([newLogItem("syslog2", socket.__verified + "(" + socketAddr(socket) + ") connected")]);
    broadcasting.push(socket);
    if (logs.length > 50) {
        socket.emit("log", logs.slice(logs.length - 50));
    } else {
        socket.emit("log", logs);
    }
    if (fixedTyping) {
        socket.emit("fixedTyping", fixedTyping);
    }
    broadcastAllSessions();
    // allSessions will be emitted twice generally - when /login succeeded, when socket connected
    socket.on("clearSessions", function(data) {
        broadcastNewLogs([newLogItem("syslog", "/session " + session.verified + " cleared all other sessions")]);
        var aliveSockets = [];
        _.each(broadcasting, function(socket) {
            if (socket.__verified === session.verified) {
                aliveSockets.push(socket);
            } else {
                socket.emit("kickout");
                setTimeout(function() {
                    socket.disconnect();
                }, 200);
            }
        });
        sessionIds = [session.verified];
        broadcasting = aliveSockets;
        broadcastAllSessions();
    });
    var addresses = _.map(broadcasting, socketAddr);
    socket.on("send", function(data) {
        var lowerCased = data.toLowerCase().trim();
        if (lowerCased === "/restart") {
            broadcastNewLogs([newLogItem("log", "/restart")]);
            if (client) client.end();
            client = null;
            startIRC();
        } else if (lowerCased === "/save") {
            saveLog(function (filename, err) {
                if (err) {
                    broadcastNewLogs([newLogItem("syslog", "/error while saving to " + filename + " -- " + JSON.stringify(err))]);
                } else {
                    broadcastNewLogs([newLogItem("syslog", "/saved to " + filename)]);
                }
            });
        } else if (lowerCased === "/clear") {
            saveLog(function (filename, err) {
                if (err) {
                    broadcastNewLogs([newLogItem("syslog", "/error while saving to " + filename + " -- " + JSON.stringify(err))]);
                } else {
                    logs = [];
                    broadcastNewLogs([newLogItem("syslog", "/clear logs after save logs to " + filename)]);
                }
            });
        } else {
            write(data);
        }
    });
    socket.on("older", function(data) {
        var oldest = data.clientOldest;
        if (oldest !== undefined) {
            var oldestIndex;
            for (var i = 0; i < logs.length; i++) {
                if (logs[i].id >= oldest) {
                    oldestIndex = i;
                    break;
                }
            }
            socket.emit("older", logs.slice(Math.max(0, oldestIndex - 50), oldestIndex));
        }
    });
    socket.on("fixedTyping", function (data) {
        fixedTyping = data;
        _.each(broadcasting, function (socket) {
            socket.emit("fixedTyping", fixedTyping);
        });
    });
    socket.on("disconnect", function () {
        broadcasting = _.reject(broadcasting, function(conn) { return conn === socket; });
        var addresses = _.map(broadcasting, socketAddr);
        broadcastNewLogs([newLogItem("syslog2", socket.__verified + "(" + socketAddr(socket) + ") disconnected")]);
        broadcastAllSessions();
    });
});

var saveLog = function (donecb) {
    console.log("Saving logs...");
    var filename = "./SelfIRC-logs-" + (new Date().toString()) + ".txt";
    fs.writeFile(filename, JSON.stringify(logs), function(err) {
        console.log(err);
        if (donecb) {
            donecb(filename, err);
        }
    });
    return filename;
};
setInterval(saveLog, 8*60*60*1000);		// every 8 hours
process.on("exit", saveLog);			// on exit
<|endoftext|>


<commit_before>var
    http = require('http'),
    express = require('express'),
    compress = require('compression'),
    api = require("./core/api"),
    app = express()
    ;

var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'

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

    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    next();
});

http.createServer(app).listen(server_port, server_ip_address, function(){
    console.log('Express server listening on port ' + app.get('port'));
});

app.get('/', function (req, res) {
    res.send("Hello World!")
});

app.get('/cinemas', function (req, res) {
    api.getCinemas().then(function(cinemas){
        res.json(cinemas);
    })
});

module.exports = app;<commit_msg>Fix typo<commit_after>var
    http = require('http'),
    express = require('express'),
    compress = require('compression'),
    api = require("./core/api"),
    app = express()
    ;

var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'

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

    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    next();
});

http.createServer(app).listen(server_port, server_ip_address, function(){
    console.log('Express server listening on port ' + server_port);
});

app.get('/', function (req, res) {
    res.send("Hello World!")
});

app.get('/cinemas', function (req, res) {
    api.getCinemas().then(function(cinemas){
        res.json(cinemas);
    })
});

module.exports = app;<|endoftext|>


<commit_before>var express = require('express'),
	readline = require('readline'),
	fs=require('fs');
	app = express(),
	port = 8080;	// Porta por defeito

var exec = require('child_process').exec,
	spawn=require('child_process').spawn,
    player=null,
    ringer=null;

var playStatus=0,playList=[],playHistory=[];
//playstatus, 0-> no file, 1-> playing, 2-> paused
var playMode=1;
//playmode 1->FM,2->MPG321,3->broadcast stream, to be implemented later

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
//configuracao
app.configure(function() {
    app.engine('html', require('ejs').renderFile);

    app.use(express.bodyParser({ keepExtensions: true, uploadDir: 'tmp/' }));

    //app.use(express.directory(__dirname+'/public'));

    app.use(express.static(__dirname+'/public'));

    app.set('view engine', 'ejs');

	app.use(function (req, res, next) {
	    res.setHeader('Server', 'RPi Radio station');

	    return next();
	});

	app.enable('trust proxy');
	app.disable('x-powered-by');

	app.use('/', app.router);
});

var args = process.argv.splice(2),
	p = null;

if (args.length > 0) {
	p = parseInt(args[0]);
	if( p )
		port = p ;

	p = null;
}

console.log('Escuta na porta: ' + port);
app.listen(port);

// Funcoes

function respondToJSON(req, res, out, statusCode) {
	var size;

	out = JSON.stringify( out );
	size = Buffer.byteLength( out, 'UTF-8' );

	res.writeHead( statusCode,
				   { 'Content-Type': 'application/json; charset=utf-8',
					 'Content-Length': size} );

	res.write( out );
	res.end();
}

function play(music)
{
	console.log("playing:",music.name, music.path);
	if (playMode==1) // FM transmiter
		player=exec("avconv -i "+music.path+" -ac 1 -ar 22050 -b 352k -f wav - | sudo ./pifm - 100.0" );
	else if (playMode==2) // Audio Line Output
		player=spawn("mpg321",[music.path]); //colunas do RPI
	//this else is for testing purposes
	else player=spawn("sudo ./pifm tmp/audio.wav 100.0");
	player.on("exit",function(code,signal){
		console.log("player finish");
		var music=playList.shift();
		fs.unlink(music.path);
		playHistory.push(music.name);//.shift -> same as queue.pop, remove current file from list, add it to top of history
		if (playList.length==0)
		{
			playStatus=0;
			player=null;
		}
		else
		{
			play(playList[0]);
		}
	});
	playStatus=1;
}

/*
 *	Routes
 */

app.post('/ring',function (req,res) {
	if (!ringer) //do not ring if already ringing
	{
		console.log("ringing");
		if (playStatus==1)
		{
			console.log("pause for ring");
			player.kill("SIGSTOP");
		}
		setTimeout(function(){
			ringer=spawn("mpg321",["ringdingding.mp3"]);
			ringer.on("exit",function(code,signal){
				if (playStatus==1)
				{
					player.kill("SIGCONT");
				}
				console.log("ringer exit");
				ringer=null;
			});
		},100);
	}
	var out={};
	out.status="Ringing";
	res.redirect('/');
});

app.get('/',function(req,res)
{
	res.render('index',{'playStatus':playStatus,'playList':playList,'playHistory':playHistory});
});

app.post('/play',function(req,res)
{
	var music={};
	music.name=req.files.music.name;
	music.path=req.files.music.path;
	var out={};

	if (!music.name||!music.name.match(/.mp3$/))
	{
		fs.unlink(music.path);
		console.log("request not mp3");
		res.redirect('/');
		return;

	}

	console.log("added playlist ",music.name);
	if (!player)
	{
		playList.push(music);
		play(music);
		out.status="Excelent choice!";
	}
	else
	{
		if (playList.length>25)
		{
			out.status="Queue limit reached :(";
		}
		else
		{
			playList.push(music);
			out.status="In queue, but Excelent choice!";
			out.queuePosition=playList.length;
		}
	}
	res.redirect('/');
});

//local files only
/*app.get('/play/:file',function (req,res) {
	var file=req.params.file;
	var out={};
	if (!player)
	{
		playList.push(file);
		play(file);
		out.status="Excelent choice!";
	}
	else
	{
		if (playList.length>25)
		{
			out.status="Queue limit reached :(";
		}
		else
		{
			playList.push(file);
			out.status="In queue, but Excelent choice!";
			out.queuePosition=playList.length;
		}
	}
	respondToJSON(req,res,out,200);
});*/

app.post('/play/pause',function (req,res) {

	var out={};
	if (playStatus==1 )
	{
		player.kill("SIGSTOP");
		out.status="paused";
		playStatus=2;
	}
	else
	{
		out.status="no music playing";
	}
	res.redirect('/');
});

app.post('/play/resume',function (req,res) {

	var out={};
	if (playStatus==2 )
	{
		player.kill("SIGCONT");
		out.status="resuming";
		playStatus=1;
	}
	else
	{
		out.status="no music paused";
	}
	res.redirect('/');
});

app.post('/play/skip',function (req,res) {
	var out={};
	if (playStatus!=0&&playList.length>0)
	{
		player.kill("SIGKILL");
		out.status="skipped";
	}
	else out.status="no music to skip";
	res.redirect('/');
});

app.post('/playmode',function(req,res){
	var mode=Number(req.body.mode);
	if (mode&&mode>0&&mode<4) playMode=mode;
	res.redirect('/');
});

 app.all('*', function (req, res) {

	console.log('Pedido no encontrado: ' + req.path + " [" + req.method + "]");

	respondToJSON( req, res, { error: 'Pgina no encontrada'}, 404 );
});

rl.on("line", function(cmd) {

 	console.log(cmd );
	if (cmd=="testespawn") player=spawn("sudo ./pifm tmp/audio.wav 100.0");
  	if (cmd=="testeexec") player=exec("sudo ./pifm tmp/audio.wav 100.0");

	if (playStatus!=0 )
      {
          if (cmd=="pause")
              {

                  player.kill("SIGSTOP");
                 console.log("x");
              }
        if (cmd=="resume")
            {
                    player.kill("SIGCONT");
                    console.log("x2");
            }
      }
  if (cmd=="exit")rl.close();
});

<commit_msg>spawn pifm at start, redirect av stdout to pifm stdin<commit_after>var express = require('express'),
	readline = require('readline'),
	fs=require('fs');
	app = express(),
	port = 8080;	// Porta por defeito

var exec = require('child_process').exec,
	spawn=require('child_process').spawn,
    player=null,
	radio=spawn("sudo",["./pifm","-","100.0"]),
    ringer=null;

var playStatus=0,playList=[],playHistory=[];
//playstatus, 0-> no file, 1-> playing, 2-> paused
var playMode=1;
//playmode 1->FM,2->MPG321,3->broadcast stream, to be implemented later

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
//configuracao
app.configure(function() {
    app.engine('html', require('ejs').renderFile);

    app.use(express.bodyParser({ keepExtensions: true, uploadDir: 'tmp/' }));

    //app.use(express.directory(__dirname+'/public'));

    app.use(express.static(__dirname+'/public'));

    app.set('view engine', 'ejs');

	app.use(function (req, res, next) {
	    res.setHeader('Server', 'RPi Radio station');

	    return next();
	});

	app.enable('trust proxy');
	app.disable('x-powered-by');

	app.use('/', app.router);
});

var args = process.argv.splice(2),
	p = null;

if (args.length > 0) {
	p = parseInt(args[0]);
	if( p )
		port = p ;

	p = null;
}

console.log('Escuta na porta: ' + port);
app.listen(port);

// Funcoes

function respondToJSON(req, res, out, statusCode) {
	var size;

	out = JSON.stringify( out );
	size = Buffer.byteLength( out, 'UTF-8' );

	res.writeHead( statusCode,
				   { 'Content-Type': 'application/json; charset=utf-8',
					 'Content-Length': size} );

	res.write( out );
	res.end();
}

function play(music)
{
	console.log("playing:",music.name, music.path);
	if (playMode==1) // FM transmiter
	{
		player=spawn("avconv",["-i",music.path,"-ac","1.","-ar","22050","-b","352k","-f","wav","-"]);
		player.stdout.on("data",function(data){
			console.log("data");
			radio.stdin.write(data);
		});
	}
	else if (playMode==2) // Audio Line Output
		player=spawn("mpg321",[music.path]); //colunas do RPI
	//this else is for testing purposes
	else player=spawn("sudo ./pifm tmp/audio.wav 100.0");
	player.on("exit",function(code,signal){
		console.log("player finish");
		var music=playList.shift();
		fs.unlink(music.path);
		playHistory.push(music.name);//.shift -> same as queue.pop, remove current file from list, add it to top of history
		if (playList.length==0)
		{
			playStatus=0;
			player=null;
		}
		else
		{
			play(playList[0]);
		}
	});
	playStatus=1;
}

/*
 *	Routes
 */

app.post('/ring',function (req,res) {
	if (!ringer) //do not ring if already ringing
	{
		console.log("ringing");
		if (playStatus==1)
		{
			console.log("pause for ring");
			player.kill("SIGSTOP");
		}
		setTimeout(function(){
			ringer=spawn("mpg321",["ringdingding.mp3"]);
			ringer.on("exit",function(code,signal){
				if (playStatus==1)
				{
					player.kill("SIGCONT");
				}
				console.log("ringer exit");
				ringer=null;
			});
		},100);
	}
	var out={};
	out.status="Ringing";
	res.redirect('/');
});

app.get('/',function(req,res)
{
	res.render('index',{'playStatus':playStatus,'playList':playList,'playHistory':playHistory});
});

app.post('/play',function(req,res)
{
	var music={};
	music.name=req.files.music.name;
	music.path=req.files.music.path;
	var out={};

	if (!music.name||!music.name.match(/.mp3$/))
	{
		fs.unlink(music.path);
		console.log("request not mp3");
		res.redirect('/');
		return;

	}

	console.log("added playlist ",music.name);
	if (!player)
	{
		playList.push(music);
		play(music);
		out.status="Excelent choice!";
	}
	else
	{
		if (playList.length>25)
		{
			out.status="Queue limit reached :(";
		}
		else
		{
			playList.push(music);
			out.status="In queue, but Excelent choice!";
			out.queuePosition=playList.length;
		}
	}
	res.redirect('/');
});

//local files only
/*app.get('/play/:file',function (req,res) {
	var file=req.params.file;
	var out={};
	if (!player)
	{
		playList.push(file);
		play(file);
		out.status="Excelent choice!";
	}
	else
	{
		if (playList.length>25)
		{
			out.status="Queue limit reached :(";
		}
		else
		{
			playList.push(file);
			out.status="In queue, but Excelent choice!";
			out.queuePosition=playList.length;
		}
	}
	respondToJSON(req,res,out,200);
});*/

app.post('/play/pause',function (req,res) {

	var out={};
	if (playStatus==1 )
	{
		player.kill("SIGSTOP");
		out.status="paused";
		playStatus=2;
	}
	else
	{
		out.status="no music playing";
	}
	res.redirect('/');
});

app.post('/play/resume',function (req,res) {

	var out={};
	if (playStatus==2 )
	{
		player.kill("SIGCONT");
		out.status="resuming";
		playStatus=1;
	}
	else
	{
		out.status="no music paused";
	}
	res.redirect('/');
});

app.post('/play/skip',function (req,res) {
	var out={};
	if (playStatus!=0&&playList.length>0)
	{
		player.kill("SIGKILL");
		out.status="skipped";
	}
	else out.status="no music to skip";
	res.redirect('/');
});

app.post('/playmode',function(req,res){
	var mode=Number(req.body.mode);
	if (mode&&mode>0&&mode<4) playMode=mode;
	res.redirect('/');
});

 app.all('*', function (req, res) {

	console.log('Pedido no encontrado: ' + req.path + " [" + req.method + "]");

	respondToJSON( req, res, { error: 'Pgina no encontrada'}, 404 );
});

rl.on("line", function(cmd) {
	//All this code is for testing purpose, shall be commented later
 	console.log(cmd );
	if (cmd=="testespawn") player=spawn("sudo",["./pifm","tmp/audio.wav","100.0"]);
  	if (cmd=="testeexec") player=exec("sudo ./pifm tmp/audio.wav 100.0");

	if (playStatus!=0 )
      {
          if (cmd=="pause")
              {

                  player.kill("SIGSTOP");
                 console.log("x");
              }
        if (cmd=="resume")
            {
                    player.kill("SIGCONT");
                    console.log("x2");
            }
      }
  if (cmd=="exit")rl.close();
});

<|endoftext|>


<commit_before>var version = 'v0.1-alpha';
var port = 8081;

var app = require('express')();
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var User = require('./app/models/User').User;
var Channel = require('./app/models/Channel').Channel;

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

var users = [];
var channels = [];

function findUser(id) {
    for (var i in users) {
        var user = users[i];
        if (user.id == id) {
            return user;
        }
    }
}

function findChannel(name) {
    for (var i in channels) {
        var channel = channels[i];
        if (channel.name == name) {
            return channel;
        }
    }
    channel = new Channel(name);
    channels.push(channel);
    return channel;
}

function findUsersInChannel(name) {
    var usersInChannel = [];
    for (var i in users) {
        var user = users[i];
        for (var j in user.channels) {
            var channel = user.channels[j];
            if (channel.name == name) {
                usersInChannel.push(user);
                break;
            }
        }
    }
    return usersInChannel;
}

// API

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/app/api.html');
});

// Info

app.get('/info', function(req, res) {
    res.send({ 'version':version });
});

// List users

app.get('/users/', function(req, res) {
    var displayedUsers = [];
    for (var i in users) {
        var user = User.create(users[i]);
        user.id = undefined;
        displayedUsers.push(user);
    }
    res.send(displayedUsers);
});

// Register

app.post('/users/register/:nick', function(req, res) {
    var availableNick = req.params.nick;
    var nick = null;
    var index = 0;
    do {
        var available = true;
        for (var i in users) {
            var user = users[i];
            if (index == 0 && user.nick == availableNick){
                available = false;
                break;
            }
            if (user.nick == availableNick + '_' + index) {
                available = false;
                break;
            }
        }
        if (available) {
            nick = availableNick;
            if (index > 0) {
                nick += '_' + index;
            }
        }
        else {
            index++;
        }
    } while (nick == null);

    user = new User(nick);
    users.push(user);
    res.send(user);
});

// Whois

app.get('/users/whois/:nick', function(req, res) {
    var user = null;
    for (var i in users) {
        var oneUser = users[i];
        if (oneUser.nick == req.params.nick) {
            user = User.create(oneUser);
            break;
        }
    }
    if (user == null) {
        res.send({ 'error': 'Unknown nick.' });
    }
    else {
        user.id = undefined;
        res.send(user);
    }
});

// List channels

app.get('/channels/', function(req, res){
    res.send(channels);
});

// Join channel

app.put('/channels/:channel/join/id/:id/', function(req, res) {
    var user = findUser(req.params.id);
    var channel = findChannel(req.params.channel);
    user.channels.push(channel);
    res.send(findUsersInChannel(channel.name));
});

// Leave channel

app.delete('/channels/:channel/leave/id/:id', function(req, res) {
    var user = findUser(req.params.id);
    var channel = findChannel(req.params.channel);
    var index = user.channels.indexOf(channel);
    if (index > -1)
    {
        user.channels.splice(index, 1);
        if (!channel.keep && findUsersInChannel(channel.name).length == 0) {
            var index = channels.indexOf(channel);
            if (index > -1) {
                channels.splice(index, 1);
            }
        }
    }
    else {
        res.send({ 'error': 'Not in channel, can\'t leave.' });
    }
    res.send(user);
});

// Talk in channel

app.put('/channels/:channel/id/:id/say/', function(req, res) {
    var user = findUser(req.params.id);
    var channel = findChannel(req.params.channel);
    var message = req.body.message;

    if (!user.isInChannel(channel.name)) {
        user.channels.put(channel);
    }

    var usersInChannel = findUsersInChannel(channel.name);
    for (var i in usersInChannel) {
        var userInChannel = usersInChannel[i];
        userInChannel.buffer.push({ 'type': 'message', 'user': user.nick, 'message': message });
    }
    res.send();
});

// Error handling

app.get('*', function(req, res) {
    res.send({ 'error': 'Unknown route or method.' });
});

app.post('*', function(req, res) {
    res.send({ 'error': 'Unknown route or method.' });
});

app.put('*', function(req, res) {
    res.send({ 'error': 'Unknown route or method.' });
});

app.delete('*', function(req, res) {
    res.send({ 'error': 'Unknown route or method.' });
});

// Server listening

http.listen(port, function() {
    console.log('Server started on port ' + port);
});
<commit_msg>logging everything<commit_after>var version = 'v0.1-alpha';
var port = 8081;

var app = require('express')();
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var User = require('./app/models/User').User;
var Channel = require('./app/models/Channel').Channel;

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

var users = [];
var channels = [];

function findUser(id) {
    for (var i in users) {
        var user = users[i];
        if (user.id == id) {
            return user;
        }
    }
}

function findChannel(name) {
    for (var i in channels) {
        var channel = channels[i];
        if (channel.name == name) {
            return channel;
        }
    }
    channel = new Channel(name);
    channels.push(channel);
    return channel;
}

function findUsersInChannel(name) {
    var usersInChannel = [];
    for (var i in users) {
        var user = users[i];
        for (var j in user.channels) {
            var channel = user.channels[j];
            if (channel.name == name) {
                usersInChannel.push(user);
                break;
            }
        }
    }
    return usersInChannel;
}

// API

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/app/api.html');
    console.log('# delivering API');
});

// Info

app.get('/info', function(req, res) {
    res.send({ 'version':version });
    console.log('* Info requested');
});

// List users

app.get('/users/', function(req, res) {
    var displayedUsers = [];
    for (var i in users) {
        var user = User.create(users[i]);
        user.id = undefined;
        displayedUsers.push(user);
    }
    res.send(displayedUsers);
    console.log('* User list requested');
});

// Register

app.post('/users/register/:nick', function(req, res) {
    var availableNick = req.params.nick;
    var nick = null;
    var index = 0;
    do {
        var available = true;
        for (var i in users) {
            var user = users[i];
            if (index == 0 && user.nick == availableNick){
                available = false;
                break;
            }
            if (user.nick == availableNick + '_' + index) {
                available = false;
                break;
            }
        }
        if (available) {
            nick = availableNick;
            if (index > 0) {
                nick += '_' + index;
            }
        }
        else {
            index++;
        }
    } while (nick == null);

    user = new User(nick);
    users.push(user);
    res.send(user);
    console.log('* ' + user.nick + ' is connected');
});

// Whois

app.get('/users/whois/:nick', function(req, res) {
    var user = null;
    for (var i in users) {
        var oneUser = users[i];
        if (oneUser.nick == req.params.nick) {
            user = User.create(oneUser);
            break;
        }
    }
    if (user == null) {
        res.send({ 'error': 'Unknown nick.' });
    }
    else {
        user.id = undefined;
        res.send(user);
    }
    console.log('* Whois on ' + user.nick);
});

// List channels

app.get('/channels/', function(req, res){
    res.send(channels);
    console.log('* Channel list requested');
});

// Join channel

app.put('/channels/:channel/join/id/:id/', function(req, res) {
    var user = findUser(req.params.id);
    var channel = findChannel(req.params.channel);
    user.channels.push(channel);
    res.send(findUsersInChannel(channel.name));
    console.log('* ' + user.nick + ' joined ' + channel.name);
});

// Leave channel

app.delete('/channels/:channel/leave/id/:id', function(req, res) {
    var user = findUser(req.params.id);
    var channel = findChannel(req.params.channel);
    var index = user.channels.indexOf(channel);
    if (index > -1)
    {
        user.channels.splice(index, 1);
        if (!channel.keep && findUsersInChannel(channel.name).length == 0) {
            var index = channels.indexOf(channel);
            if (index > -1) {
                channels.splice(index, 1);
            }
        }
        console.log('* ' + user.nick + ' left ' + channel.name);
    }
    else {
        res.send({ 'error': 'Not in channel, can\'t leave.' });
    }
    res.send(user);
});

// Talk in channel

app.put('/channels/:channel/id/:id/say/', function(req, res) {
    var user = findUser(req.params.id);
    var channel = findChannel(req.params.channel);
    var message = req.body.message;

    if (!user.isInChannel(channel.name)) {
        user.channels.put(channel);
    }

    var usersInChannel = findUsersInChannel(channel.name);
    for (var i in usersInChannel) {
        var userInChannel = usersInChannel[i];
        userInChannel.buffer.push({ 'type': 'message', 'user': user.nick, 'message': message });
    }
    res.send();
    console.log('<' + user.nick + '> ' + message);
});

// Error handling

app.get('*', function(req, res) {
    res.send({ 'error': 'Unknown route or method.' });
    console.log('# Unknown route: GET ' + req.baseUrl);
});

app.post('*', function(req, res) {
    res.send({ 'error': 'Unknown route or method.' });
    console.log('# Unknown route: POST ' + req.baseUrl);
});

app.put('*', function(req, res) {
    res.send({ 'error': 'Unknown route or method.' });
    console.log('# Unknown route: PUT ' + req.baseUrl);
});

app.delete('*', function(req, res) {
    res.send({ 'error': 'Unknown route or method.' });
    console.log('# Unknown route: DELETE ' + req.baseUrl);
});

// Server listening

http.listen(port, function() {
    console.log('Server started on port ' + port);
});
<|endoftext|>


<commit_before>const _ = require('lodash')
const chalk = require('chalk')
const assert = require('assert')
const inquirer = require('inquirer')
const SerialPort = require('serialport')
const comm = require('./lib/Comm.js')
require('draftlog').into(console)

const Match = require('./lib/Match')
const MatchSimulated = require('./lib/MatchSimulated')
const MatchVSSSimulated = require('./lib/MatchVSSSimulated')

const players = require('require-smart')('./players')
const test_players = require('require-smart')('./players/tests')

const Coach = require('./lib/Coach')

const PORT = 10006
const HOST = '224.5.23.2'

const sleep = ms => new Promise((res, rej) => setTimeout(res, ms))
const TAG = 'server'

const RUN_MODES = {1: 'REAL_LIFE', 2: 'SIMULATED', 3: 'ASSIST'}
/*
Variavel RUN_MODE args:
  1: REAL_LIFE, Executa o fluxo completo, usado para partidas reais
  2: SIMULATED, modo simulado, usando stack SIR-LAB
  3: ASSIST   , modo assistido, onde o NoPlan recebe dados do
  SSL-Vision mas não envia para lugar algum
*/

const run_mode = process.env.RUN_MODE

assert.notEqual(run_mode, null, chalk.red('MISSING PARAMETER: RUN_MODE'))
assert.ok(run_mode in RUN_MODES, chalk.red('WRONG PARAMETER: RUN_MODE, must be 1, 2 or 3'))

const isSimulated = run_mode==2
const usePrediction = false
const noStation = run_mode==3

async function startup(){
  console.info(TAG, chalk.yellow('Startup'))
  console.info(TAG, chalk.yellow('Run mode: '), chalk.green(RUN_MODES[run_mode]))
  // FIXME: Se a simulação não esta confiavel vale tentar usar?
  // console.info(TAG, chalk.yellow('usePrediction'), usePrediction)

  let MatchClass = (isSimulated ? MatchSimulated : Match)

  if(noStation) {
    MatchClass = MatchVSSSimulated // Mudar no futuro
  }

  let match = new MatchClass({
    // Vision: Dados referentes ao input de dados da visão
    // Coach: Dados de configuração do Coach que ira orquestrar a partida
    // Driver: dados referentes ao output de dados de envio para os robos
    vision: { PORT, HOST },
    coach: Coach,
    robotsProperties: {robot_1: {vision_id: 1, radio_id:1}},
    driver: {
      port: ((isSimulated || noStation) ? null : await getPort('/dev/ttyUSB0')),
      debug: false,
      baudRate: 115200,
    }
  })

  await match.init()
  console.log('Listening in:', PORT)

  await comm(match, {PORT:8080})

}

process.on('unhandledRejection', (e) => {
  console.error('Unhandled Rejection')
  console.error(e)
  process.exit(1)
})

startup()

async function getPort(prefered) {
  let ports = await SerialPort.list()
  let found = _.find(ports, {comName: prefered})
  if (found)
    return prefered

  console.log(`Port '${prefered}' not available`)

  let answer = await inquirer.prompt({
    type: 'list',
    name: 'port',
    choices: _.map(ports, 'comName'),
    message: 'Select Cursor port'
  })

  return answer.port
}
<commit_msg>Make server more simple<commit_after>const fs = require("fs");
const _ = require('lodash')
const chalk = require('chalk')
const assert = require('assert')
const inquirer = require('inquirer')
const SerialPort = require('serialport')
const comm = require('./lib/Comm.js')
require('draftlog').into(console)

const Match = require('./lib/Match')
const MatchSimulated = require('./lib/MatchSimulated')
const MatchVSSSimulated = require('./lib/MatchVSSSimulated')

const players = require('require-smart')('./players')
const test_players = require('require-smart')('./players/tests')

const Coach = require('./lib/Coach')

const PORT = 10006
const HOST = '224.5.23.2'

const sleep = ms => new Promise((res, rej) => setTimeout(res, ms))
const TAG = 'server'

const RUN_MODES = {1: 'REAL_LIFE', 2: 'SIMULATED', 3: 'ASSIST'}
/*
Variavel RUN_MODE args:
  1: REAL_LIFE, Executa o fluxo completo, usado para partidas reais
  2: SIMULATED, modo simulado, usando stack SIR-LAB
  3: ASSIST   , modo assistido, onde o NoPlan recebe dados do
  SSL-Vision mas não envia para lugar algum
*/

const run_mode = process.env.RUN_MODE

assert.notEqual(run_mode, null, chalk.red('MISSING PARAMETER: RUN_MODE'))
assert.ok(run_mode in RUN_MODES, chalk.red('WRONG PARAMETER: RUN_MODE, must be 1, 2 or 3'))

async function startup(){
  console.info(TAG, chalk.yellow('Startup'))
  console.info(TAG, chalk.yellow('Run mode: '), chalk.green(RUN_MODES[run_mode]))
  // FIXME: Se a simulação não esta confiavel vale tentar usar?
  // console.info(TAG, chalk.yellow('usePrediction'), usePrediction)

  let MatchClass = null
  switch (run_mode) {
    case 1:
      MatchClass = Match
    case 2:
      MatchClass = MatchSimulated
    case 3:
      MatchClass = MatchVSSSimulated

  }

  let match = new MatchClass({
    // Vision: Dados referentes ao input de dados da visão
    // Coach: Dados de configuração do Coach que ira orquestrar a partida
    // Driver: dados referentes ao output de dados de envio para os robos
    vision: { PORT, HOST },
    coach: Coach,
    robotsProperties: {robot_1: {vision_id: 1, radio_id:1}},
    driver: {
      port: (run_mode in [2, 3] ? null : await getPort('/dev/ttyUSB0')),
      debug: false,
      baudRate: 115200,
    }
  })

  await match.init()
  console.log('Listening in:', PORT)

  await comm(match, {PORT:8080})

}

process.on('unhandledRejection', (e) => {
  console.error('Unhandled Rejection')
  console.error(e)
  process.exit(1)
})

startup()

async function getPort(prefered) {
  let ports = await SerialPort.list()
  let found = _.find(ports, {comName: prefered})
  if (found)
    return prefered

  console.log(`Port '${prefered}' not available`)

  let answer = await inquirer.prompt({
    type: 'list',
    name: 'port',
    choices: _.map(ports, 'comName'),
    message: 'Select Cursor port'
  })

  return answer.port
}
<|endoftext|>


<commit_before>const expect = require('chai').expect;
const std = require('../../src/index');

describe('變形工時', () => {
  describe('雙週', () => {
    it('雙週班表工時' +
       '[10, 10, 10, 10, 0, 0, 0], ' +
       '[10, 10, 10, 10, 0, 0, 0]，' +
       '為合法雙週變形工時，無加班費（勞基法 30 條）', () => {
      let result = std.transformedWorkshift([
        [10, 10, 10, 10, 0, 0, 0],
        [10, 10, 10, 10, 0, 0, 0]
      ], std.DUAL_WEEK_WORKSHIFT);
      expect(result.reference[0].id).eq('LSA-30');
    });
  });

  describe('四週', () => {
    it('四週班表工時' +
       '[0, 0, 0, 9, 9, 9, 9], ' +
       '[9, 9, 9, 9, 0, 0, 0], ' +
       '[0, 0, 9, 9, 9, 9, 9], ' +
       '[9, 9, 9, 8, 8, 0, 0]，' +
       '為合法四週變形工時，無加班費（勞基法 30-1條）', () => {
      let result = std.transformedWorkshift([
        [0, 0, 0, 9, 9, 9, 9],
        [9, 9, 9, 9, 0, 0, 0],
        [0, 0, 9, 9, 9, 9, 9],
        [9, 9, 9, 8, 8, 0, 0]
      ], std.QUAD_WEEK_WORKSHIFT);
      expect(result.reference[0].id).eq('LSA-30-1');
    });

    it('四週班表工時' +
       '[0, 0, 0, 10, 10, 10, 10], ' +
       '[10, 10, 10, 10, 10, 0, 0], ' +
       '[0, 0, 0, 0, 0, 10, 10], ' +
       '[10, 10, 10, 10, 10, 0, 0]，' +
       '為合法四週變形工時，無加班費（勞基法 30-1條）', () => {
      let result = std.transformedWorkshift([
        [0, 0, 0, 10, 10, 10, 10],
        [10, 10, 10, 10, 10, 0, 0],
        [0, 0, 0, 0, 0, 10, 10],
        [10, 10, 10, 10, 10, 0, 0]
      ], std.QUAD_WEEK_WORKSHIFT);
      expect(result.reference[0].id).eq('LSA-30-1');
    });
  });

  describe('八週', () => {
    it('八週班表工時' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 0, 0], ' +
       '[0, 0, 0, 0, 0, 0, 0], ' +
       '為合法八週變形工時，無加班費（勞基法 30條）', () => {
      let result = std.transformedWorkshift([
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]
      ], std.OCTA_WEEK_WORKSHIFT);
      expect(result.reference[0].id).eq('LSA-30-1');
    });
  });
});
<commit_msg>Expect return overtime hours per day for tranformed shift<commit_after>const expect = require('chai').expect;
const std = require('../../src/index');

describe('變形工時', () => {
  describe('雙週', () => {
    it('雙週班表工時' +
       '[10, 10, 10, 10, 0, 0, 0], ' +
       '[10, 10, 10, 10, 0, 0, 0]，' +
       '為合法雙週變形工時，無加班費（勞基法 30 條）', () => {
      let result = std.transformedWorkshift([
        [10, 10, 10, 10, 0, 0, 0],
        [10, 10, 10, 10, 0, 0, 0]
      ], std.DUAL_WEEK_WORKSHIFT);
      expect(result.overtime).eq([
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]
      ])
      expect(result.reference[0].id).eq('LSA-30');
    });
  });

  describe('四週', () => {
    it('四週班表工時' +
       '[0, 0, 0, 9, 9, 9, 9], ' +
       '[9, 9, 9, 9, 0, 0, 0], ' +
       '[0, 0, 9, 9, 9, 9, 9], ' +
       '[9, 9, 9, 8, 8, 0, 0]，' +
       '為合法四週變形工時，無加班費（勞基法 30-1條）', () => {
      let result = std.transformedWorkshift([
        [0, 0, 0, 9, 9, 9, 9],
        [9, 9, 9, 9, 0, 0, 0],
        [0, 0, 9, 9, 9, 9, 9],
        [9, 9, 9, 8, 8, 0, 0]
      ], std.QUAD_WEEK_WORKSHIFT);
      expect(result.overtime).eq([
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]
      ])
      expect(result.reference[0].id).eq('LSA-30-1');
    });

    it('四週班表工時' +
       '[0, 0, 0, 10, 10, 10, 10], ' +
       '[10, 10, 10, 10, 10, 0, 0], ' +
       '[0, 0, 0, 0, 0, 10, 10], ' +
       '[10, 10, 10, 10, 10, 0, 0]，' +
       '為合法四週變形工時，無加班費（勞基法 30-1條）', () => {
      let result = std.transformedWorkshift([
        [0, 0, 0, 10, 10, 10, 10],
        [10, 10, 10, 10, 10, 0, 0],
        [0, 0, 0, 0, 0, 10, 10],
        [10, 10, 10, 10, 10, 0, 0]
      ], std.QUAD_WEEK_WORKSHIFT);
      expect(result.overtime).eq([
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]
      ]);
      expect(result.reference[0].id).eq('LSA-30-1');
    });
  });

  describe('八週', () => {
    it('八週班表工時' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 8, 8], ' +
       '[0, 8, 8, 8, 8, 0, 0], ' +
       '[0, 0, 0, 0, 0, 0, 0], ' +
       '為合法八週變形工時，無加班費（勞基法 30條）', () => {
      let result = std.transformedWorkshift([
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 8, 8],
        [0, 8, 8, 8, 8, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]
      ], std.OCTA_WEEK_WORKSHIFT);
      expect(result.overtime).eq([
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]
      ]);
      expect(result.reference[0].id).eq('LSA-30-1');
    });
  });
});
<|endoftext|>


<commit_before>var express = require('express');
var request = require('request');
var cheerio = require('cheerio');

var app = express();
var PORT = process.env.PORT || 3000;

//ROUTES
app.get('/webhook/', function (req, res) {
  if (req.query['hub.verify_token'] === '***REMOVED***') {
    res.send(req.query['hub.challenge']);
  }
  res.send('Error, wrong validation token');
});

app.post('/webhook/', function (req, res) {
	console.log(req);
	if(typeof req.body !== 'undefined' && req.body !== null){
		console.log("VIJAY TEST - " + req.body.entry);
	  messaging_events = req.body.entry[0].messaging;
	  for (i = 0; i < messaging_events.length; i++) {
	    event = req.body.entry[0].messaging[i];
	    sender = event.sender.id;
	    if (event.message && event.message.text) {
	      text = event.message.text;
	      console.log(sender + ': ' + text);
	    }
	  }
	} else {
		console.log("Empty request in POST:/webhook");
	}
	res.sendStatus(200);
});

app.get('/init', function(req, res){
	var url = 'https://graph.facebook.com/v2.6/me/subscribed_apps?access_token='
	+'***REMOVED***'
	+'***REMOVED***'
	+'***REMOVED***';
	request(url, function(error, response, body){
		if(!error){
			res.send(body);
		} else {
			res.send(error);
		}
	});
});

app.get('/quotes/:keyword', function(req, res) {
	if(typeof req.params.keyword !== 'undefined' && null !== req.params.keyword){
		getRandomQuote(req.params.keyword, function(data){
			if(data !== '404') {
				res.status(200).send("
"+data+"
");
			} else {
				res.send("Oops!! I do not know any quote having keyword(s) '"
					+ req.params.keyword
					+ "', Let's try something else!");
			}

		});
	} else {
		res.send("Invalid Keyword");
	}
});

//SETTING STATIC SITE AND STARTING SERVER
app.use(express.static(__dirname + '/public'));

app.listen(PORT, function() {
	console.log('Server started at port ' + PORT);
});

//UTILITY FUNCTIONS

function getRandomQuote(keyword, callback) {
	var pageNum = Math.floor(Math.random() * (10)) + 1;
	var url = 'http://www.brainyquote.com/search_results.html?q=' + keyword + '&pg=' + pageNum;
	var quotes = [];
	var authors = [];
	request(url, function (error, response, body) {
	  if (!error && response.statusCode == 200) {
	    var $ = cheerio.load(response.body);
		$('.bqQuoteLink').each(function(i, elem) {
			quotes[i] = $(this).find('a').text();
			authors[i] = $(this).parent('.boxyPaddingBig').find('.bq-aut').find('a').text() || 'unknown';
		});
		if(quotes.length === 0) {
			callback("404");
		}
		var quoteNum = Math.floor(Math.random() * (quotes.length));
		console.log("URL: " + url + " ---> QuoteNumber: " + quoteNum);
		console.log("Quote: " + quotes[quoteNum].replace("  " , " ") + '" - ' + authors[quoteNum]);
		callback('"' + quotes[quoteNum].replace("  " , " ") + '" - ' + authors[quoteNum]);
	  } else {
	  	callback("Error 500 : Some error occured, please try later.");
	  }
	});
}

<commit_msg>removed logger from req<commit_after>var express = require('express');
var request = require('request');
var cheerio = require('cheerio');

var app = express();
var PORT = process.env.PORT || 3000;

//ROUTES
app.get('/webhook/', function (req, res) {
  if (req.query['hub.verify_token'] === '***REMOVED***') {
    res.send(req.query['hub.challenge']);
  }
  res.send('Error, wrong validation token');
});

app.post('/webhook/', function (req, res) {
	console.log(req);
	if(typeof req.body !== 'undefined' && req.body !== null){
		//console.log("VIJAY TEST - " + req.body.entry);
	  messaging_events = req.body.entry[0].messaging;
	  for (i = 0; i < messaging_events.length; i++) {
	    event = req.body.entry[0].messaging[i];
	    sender = event.sender.id;
	    if (event.message && event.message.text) {
	      text = event.message.text;
	      console.log(sender + ': ' + text);
	    }
	  }
	} else {
		console.log("Empty request in POST:/webhook");
	}
	res.sendStatus(200);
});

app.get('/init', function(req, res){
	var url = 'https://graph.facebook.com/v2.6/me/subscribed_apps?access_token='
	+'***REMOVED***'
	+'***REMOVED***'
	+'***REMOVED***';
	request(url, function(error, response, body){
		if(!error){
			res.send(body);
		} else {
			res.send(error);
		}
	});
});

app.get('/quotes/:keyword', function(req, res) {
	if(typeof req.params.keyword !== 'undefined' && null !== req.params.keyword){
		getRandomQuote(req.params.keyword, function(data){
			if(data !== '404') {
				res.status(200).send("
"+data+"
");
			} else {
				res.send("Oops!! I do not know any quote having keyword(s) '"
					+ req.params.keyword
					+ "', Let's try something else!");
			}

		});
	} else {
		res.send("Invalid Keyword");
	}
});

//SETTING STATIC SITE AND STARTING SERVER
app.use(express.static(__dirname + '/public'));

app.listen(PORT, function() {
	console.log('Server started at port ' + PORT);
});

//UTILITY FUNCTIONS

function getRandomQuote(keyword, callback) {
	var pageNum = Math.floor(Math.random() * (10)) + 1;
	var url = 'http://www.brainyquote.com/search_results.html?q=' + keyword + '&pg=' + pageNum;
	var quotes = [];
	var authors = [];
	request(url, function (error, response, body) {
	  if (!error && response.statusCode == 200) {
	    var $ = cheerio.load(response.body);
		$('.bqQuoteLink').each(function(i, elem) {
			quotes[i] = $(this).find('a').text();
			authors[i] = $(this).parent('.boxyPaddingBig').find('.bq-aut').find('a').text() || 'unknown';
		});
		if(quotes.length === 0) {
			callback("404");
		}
		var quoteNum = Math.floor(Math.random() * (quotes.length));
		console.log("URL: " + url + " ---> QuoteNumber: " + quoteNum);
		console.log("Quote: " + quotes[quoteNum].replace("  " , " ") + '" - ' + authors[quoteNum]);
		callback('"' + quotes[quoteNum].replace("  " , " ") + '" - ' + authors[quoteNum]);
	  } else {
	  	callback("Error 500 : Some error occured, please try later.");
	  }
	});
}

<|endoftext|>