<commit_before>var express = require('express');
var sys = require('sys');
var exec = require('child_process').exec;
var http = require('http');
var path = require('path');
var twilio = require('twilio');
var _ = require('underscore');
var fs = require('fs');
var bodyParser = require('body-parser');
var morgan = require('morgan');

var app = express();
var appPort = process.env.PORT;
var MAX_SMS_LENGTH = 160; // As defined by Twilio: http://www.twilio.com/docs/errors/21605
var MAX_SEARCH_RESULTS = 10;

var twilioFromNumber= process.env.FROM_NUMBER;
var myMobileNumber = process.env.CONTROL_NUMBER;
var twilioClient = require('twilio')(process.env.TWILIO_SID, process.env.TWILIO_AUTH_TOKEN);
var historyFile = "history.json";
var commandIndexFile = "index.json";
var debug = process.env.DEBUG || false;

var couchPotatoApi = {
    host: 'localhost',
    port: 5050,
    path: '/couchpotato/api/' + process.env.COUCHPOTATO_API_KEY + '/',
    method: 'GET'
};

var sickbeardApi = {
    host: 'localhost',
    port: 8081,
    path: '/sickbeard/api/' + process.env.SICKBEARD_API_KEY + '/',
};

app.disable('x-powered-by');
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({
    extended: true
}));

if (process.env.TRUST_PROXY == 1) {
    app.enable('trust proxy');
}

// Handle the request
app.post('/', function(req, res) {
    // If enabled, trust proxied requests. Otherwise, the validateExpressRequest() will always fail
    if (app.get('trust proxy')) {
        req.headers['host'] = req.headers['x-forwarded-host'];
    }

    // Make sure the request came from Twilio
    if (!debug && twilio.validateExpressRequest(req, process.env.TWILIO_AUTH_TOKEN) === false) {
        console.log("Request not from Twilio");
        return res.status(403).send({status: 'forbidden'});
    }

    // Make sure the request came from my number
    if (!debug && req.body.From.trim() != myMobileNumber) {
        console.log("Request not from " + myMobileNumber);
        return res.status(403).send({status: 'forbidden'});
    }

    // Trim the request string
    req.body.Body = req.body.Body.trim();

    // Store the request in the history
    add_history({
        "date": new Date(),
        "request": req.body.Body
    });

    var application = null;
    var action = null;
    var extra = null;
    if (req.body.Body) {
        if (!req.body.Body.match(/ /)) {
            application = req.body.Body.toLowerCase();
        } else {
            var routes = req.body.Body.split(" ");

            application = routes[0].toLowerCase();
            if (routes.length > 0) {
                action = routes[1].toLowerCase();
                if (routes.length > 1) {
                    extra = _.rest(routes, 2).join(" ")
                }
            }
        }
    }

    // Expand shortcuts
    if (application == 'm' || application == 'movie') {
        application = 'couchpotato';
    } else if (application == 't' || application == 'tv') {
        application = 'sickbeard';
    }

    console.log("Got request", application, action);

    var response;
    if (application == "status") {
        exec('uptime', function callback(error, stdout, stderr) {
            send_sms(stdout);
        });
    } else if (application == "couchpotato") {
        if (action == "search") {
            response = couchpotato_search(extra);
        } else if (action == "add") {
            response = couchpotato_add(extra);
        } else {
            response = application + ': unknown action';
        }
    } else if (application == "sickbeard") {
        if (action == "search") {
            response = sickbeard_search(extra);
        } else if (action == "add") {
            response = sickbeard_add(extra);
        } else {
            response = application + ': unknown action';
        }
    } else {
        response = "Unknown application: " + application;
    }

    if (response === null) {
        response = "Error processing request: " + req.body.Body;
    }

    // Respond to the user with a message
    var twResp = new twilio.TwimlResponse();
    twResp.sms(response);

    res.type('text/xml');
    return res.send(twResp.toString());
});

/**
 * Get the next command index
 *
 * @return integer
 */
var maxCommandIndex = 20;
function get_next_command_index() {
    var commandIndex = 0;
    if (fs.existsSync(commandIndexFile)) {
        commandIndex = parseInt(fs.readFileSync(commandIndexFile));
    }
    commandIndex++;

    // Rollover to keep the indexes short
    if (commandIndex > maxCommandIndex) {
        commandIndex = 1;
    }

    fs.writeFileSync(commandIndexFile, commandIndex);

    return commandIndex;
}

/**
 * Get the history
 *
 * @return array
 */
function get_history() {
    var history = [];
    if (fs.existsSync(historyFile)) {
        try {
            history = JSON.parse(fs.readFileSync(historyFile));
        } catch (e) {
            console.log("Could not parse " + historyFile);
        }
    }

    if (!_.isArray(history)) {
        history = [];
    }

    return history;
}

/**
 * Add an entry to the history
 *
 * @param object entry The history entry to add
 */
var maxHistoryIndex = 60;
function add_history(entry) {
    var history = get_history();
    history.push(entry);

    // Trim any old history
    if (history.length > maxHistoryIndex) {
        history.shift();
    }

    fs.writeFileSync(historyFile, JSON.stringify(history, null, 4));
}

/**
 * Add a movie to the wanted list
 *
 * @param  string movie_name The movie name
 *
 * @return string
 */
function couchpotato_search(movie_name) {
    if (_.isEmpty(movie_name)) {
        return 'Usage: couchpotato search [name of movie]';
    }

    var options = _.clone(couchPotatoApi);
    options.path += "movie.search/?q=" + encodeURIComponent(movie_name);

    http_get(options,
        function (result) {
            if (result.success === true && result.movies !== undefined) {
                var searchResults = [];
                for (i=0; i < result.movies.length && i < MAX_SEARCH_RESULTS; i++) {
                    var movie = result.movies[i];
                    var movieTitle = movie.original_title + " (" + movie.year + ")";

                    if (movie.in_library !== false) {
                        queue_sms(movieTitle + ' is already in your library');
                    } else if (movie.in_wanted !== false) {
                        queue_sms(movieTitle + ' is already in your wanted list');
                    } else {
                        var commandId = get_next_command_index();
                        add_history({
                            "command_id": commandId,
                            "app": "couchpotato",
                            "imdb": movie.imdb,
                            "title": movieTitle
                        });

                        queue_sms(commandId + ". " + movieTitle);
                    }
                }

                send_sms_queue();
            } else {
                send_sms('No matches found for ' + movie_name);
            }
        },
        function(e) {
            var errorMessage = "couchpotato_search error: " + e.message;
            console.log(e.message);
            send_sms(errorMessage);
        }
    );
}

/**
 * Add a movie to couch potato
 *
 * @param string command_id The command id for the movie
 */
function couchpotato_add(command_id) {
    if (_.isEmpty(command_id)) {
        throw "Invalid command id";
    }

    var history = get_history().reverse();
    var movie = _.find(history, function (item) {
        if (item['app'] == "couchpotato" && item['command_id'] == command_id) {
            return true;
        }
    });

    if (!movie) {
        return send_sms('Invalid selection: ' + command_id);
    }

    imdb_id = movie['imdb'].trim();
    var options = _.clone(couchPotatoApi);
    options.path += "movie.add/?identifier=" + imdb_id;

    http_get(options,
        function (result) {
            if (result.success === true)  {
                send_sms(movie['title'] + ' added to wanted list');
            } else {
                send_sms('Could not add ' + movie['title'] + ' to wanted list');
            }
        },
        function(e) {
            var errorMessage = "couchpotato_add error: " + e.message;
            console.log(e.message);
            send_sms(errorMessage);
        }
    );
}

/**
 * Add a tv show to sickbeard
 *
 * @param  string show_name The tv show name
 *
 * @return string
 */
function sickbeard_search(show_name) {
    if (_.isEmpty(show_name)) {
        throw "Invalid show name";
    }

    var options = _.clone(sickbeardApi);
    options.path += "?cmd=sb.searchtvdb&lang=en&name=" + encodeURIComponent(show_name);

    http_get(options,
        function (result) {
            if (result.result == 'success') {
                if (result.data.results.length === 0) {
                    send_sms('No matches found for ' + show_name);
                    return;
                }

                for (i=0; i < result.data.results.length && i < MAX_SEARCH_RESULTS; i++) {
                    var show = result.data.results[i];
                    if (show.first_aired !== null) {
                        show.year = show.first_aired.replace(/-.*$/, '');
                    } else {
                        show.year = null;
                    }
                    var showTitle = show.name + " (" + show.year + ")";

                    var commandId = get_next_command_index();
                    add_history({
                        "command_id": commandId,
                        "app": "sickbeard",
                        "tvdbid": show.tvdbid,
                        "title": showTitle
                    });

                    queue_sms(commandId + ". " + showTitle);
                }

                send_sms_queue();
            } else {
                send_sms('Could not add ' + show_name + ': ' + result.message);
            }
        },
        function(e) {
            var errorMessage = "sickbeard_search error: " + e.message;
            console.log(e.message);
            send_sms(errorMessage);
        }
    );
}

/**
 * Add a tv show to sickbeard
 *
 * @param string tvdb_id The tvdb id for the tv show
 */
function sickbeard_add(command_id) {
    if (_.isEmpty(command_id)) {
        throw "Invalid command id";
    }

    var history = get_history().reverse();
    var show = _.find(history, function (item) {
        if (item['app'] == "sickbeard" && item['command_id'] == command_id) {
            return true;
        }
    });

    if (!show) {
        return send_sms('Invalid selection: ' + command_id);
    }

    var tvdb_id = show['tvdbid'];
    var options = _.clone(sickbeardApi);
    options.path += "?cmd=show.addnew&tvdbid=" + tvdb_id;

    http_get(options,
        function (result) {
            if (result.result == 'success') {
                send_sms(show['title'] + ' added!');
            } else {
                send_sms('Could not add ' + show['title'] + ': ' + result.message);
            }
        },
        function(e) {
            var errorMessage = "sickbeard_add error: " + e.message;
            console.log(e.message);
            send_sms(errorMessage);
        }
    );
}

/**
 * Make a HTTP GET request
 *
 * @param object options The url parameters
 * @param function callback_success Call this function on success
 * @param function callback_error call this function on error
 */
function http_get(options, callback_success, callback_error) {
    http.get(options, function (http_res) {
        var data = "";

        http_res.on("data", function (chunk) {
            data += chunk;
        });

        http_res.on("end", function () {
            result = JSON.parse(data);
            callback_success(result);
        });
    }).on('error', callback_error);
}

/**
 * Send an SMS message
 *
 * @param  string body The SMS body
 */
function send_sms(body) {
    var options = {
        to: myMobileNumber,
        from: twilioFromNumber,
        body: body.trim()
    };

    console.log("Sending SMS", JSON.stringify(options));

    if (!debug) {
        twilioClient.sms.messages.create(options, function(error, responseData) {
            if (error) {
                console.log(responseData);
            }
        });
    }
}

/**
 * Add an SMS message to the queue
 *
 * @param string message The message to send
 */
var sms_queue = [];
function queue_sms(message) {
    if (message.length > MAX_SMS_LENGTH) {
        console.log("Not adding message to queue, message is too long: " + message);
        return;
    }

    sms_queue.push(message);
}

/**
 * Send all queued SMS messages
 *
 * Bundle the SMS messages up so we send as many lines as possible per message
 */
function send_sms_queue() {
    if (sms_queue.length > 0) {
        var messageBuffer = '';
        for (var i in sms_queue) {
            if (sms_queue[i].length > MAX_SMS_LENGTH) {
                console.log("Not sending message from queue, message is too long: " + sms_queue[i]);
                continue;
            }

            if ((messageBuffer + sms_queue[i] + 1).length > MAX_SMS_LENGTH) {
                send_sms(messageBuffer);
                messageBuffer = '';
            } else {
                messageBuffer += sms_queue[i] + "\n";
            }
        }

        messageBuffer = messageBuffer.trim();
        if (messageBuffer.length > 0) {
            send_sms(messageBuffer);
        }
    } else {
        console.log("SMS queue empty, not sending anything");
    }

    sms_queue = [];
}

// Start the show!
app.listen(appPort);
console.log('Listening on port ' + appPort + '...');
<commit_msg>Modify how trust proxy works<commit_after>var express = require('express');
var sys = require('sys');
var exec = require('child_process').exec;
var http = require('http');
var path = require('path');
var twilio = require('twilio');
var _ = require('underscore');
var fs = require('fs');
var bodyParser = require('body-parser');
var morgan = require('morgan');

var app = express();
var appPort = process.env.PORT;
var MAX_SMS_LENGTH = 160; // As defined by Twilio: http://www.twilio.com/docs/errors/21605
var MAX_SEARCH_RESULTS = 10;

var twilioFromNumber= process.env.FROM_NUMBER;
var myMobileNumber = process.env.CONTROL_NUMBER;
var twilioClient = require('twilio')(process.env.TWILIO_SID, process.env.TWILIO_AUTH_TOKEN);
var historyFile = "history.json";
var commandIndexFile = "index.json";
var debug = process.env.DEBUG || false;

var couchPotatoApi = {
    host: 'localhost',
    port: 5050,
    path: '/couchpotato/api/' + process.env.COUCHPOTATO_API_KEY + '/',
    method: 'GET'
};

var sickbeardApi = {
    host: 'localhost',
    port: 8081,
    path: '/sickbeard/api/' + process.env.SICKBEARD_API_KEY + '/',
};

app.disable('x-powered-by');
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({
    extended: true
}));

if (process.env.TRUST_PROXY == 1) {
    app.enable('trust proxy');
}

// Handle the request
app.post('/', function(req, res) {
    // If enabled, trust proxied requests. Otherwise, the validateExpressRequest() will always fail
    if (app.get('trust proxy') && req.headers['x-forwarded-host']) {
        req.headers['host'] = req.headers['x-forwarded-host'];
    }

    // Make sure the request came from Twilio
    if (twilio.validateExpressRequest(req, process.env.TWILIO_AUTH_TOKEN) === false) {
        console.log("Request not from Twilio");
        return res.status(403).send({status: 'forbidden'});
    }

    // Make sure the request came from my number
    if (!debug && req.body.From.trim() != myMobileNumber) {
        console.log("Request not from " + myMobileNumber);
        return res.status(403).send({status: 'forbidden'});
    }

    // Trim the request string
    req.body.Body = req.body.Body.trim();

    // Store the request in the history
    add_history({
        "date": new Date(),
        "request": req.body.Body
    });

    var application = null;
    var action = null;
    var extra = null;
    if (req.body.Body) {
        if (!req.body.Body.match(/ /)) {
            application = req.body.Body.toLowerCase();
        } else {
            var routes = req.body.Body.split(" ");

            application = routes[0].toLowerCase();
            if (routes.length > 0) {
                action = routes[1].toLowerCase();
                if (routes.length > 1) {
                    extra = _.rest(routes, 2).join(" ")
                }
            }
        }
    }

    // Expand shortcuts
    if (application == 'm' || application == 'movie') {
        application = 'couchpotato';
    } else if (application == 't' || application == 'tv') {
        application = 'sickbeard';
    }

    console.log("Got request", application, action);

    var response;
    if (application == "status") {
        exec('uptime', function callback(error, stdout, stderr) {
            send_sms(stdout);
        });
    } else if (application == "couchpotato") {
        if (action == "search") {
            response = couchpotato_search(extra);
        } else if (action == "add") {
            response = couchpotato_add(extra);
        } else {
            response = application + ': unknown action';
        }
    } else if (application == "sickbeard") {
        if (action == "search") {
            response = sickbeard_search(extra);
        } else if (action == "add") {
            response = sickbeard_add(extra);
        } else {
            response = application + ': unknown action';
        }
    } else {
        response = "Unknown application: " + application;
    }

    if (response === null) {
        response = "Error processing request: " + req.body.Body;
    }

    // Respond to the user with a message
    var twResp = new twilio.TwimlResponse();
    twResp.sms(response);

    res.type('text/xml');
    return res.send(twResp.toString());
});

/**
 * Get the next command index
 *
 * @return integer
 */
var maxCommandIndex = 20;
function get_next_command_index() {
    var commandIndex = 0;
    if (fs.existsSync(commandIndexFile)) {
        commandIndex = parseInt(fs.readFileSync(commandIndexFile));
    }
    commandIndex++;

    // Rollover to keep the indexes short
    if (commandIndex > maxCommandIndex) {
        commandIndex = 1;
    }

    fs.writeFileSync(commandIndexFile, commandIndex);

    return commandIndex;
}

/**
 * Get the history
 *
 * @return array
 */
function get_history() {
    var history = [];
    if (fs.existsSync(historyFile)) {
        try {
            history = JSON.parse(fs.readFileSync(historyFile));
        } catch (e) {
            console.log("Could not parse " + historyFile);
        }
    }

    if (!_.isArray(history)) {
        history = [];
    }

    return history;
}

/**
 * Add an entry to the history
 *
 * @param object entry The history entry to add
 */
var maxHistoryIndex = 60;
function add_history(entry) {
    var history = get_history();
    history.push(entry);

    // Trim any old history
    if (history.length > maxHistoryIndex) {
        history.shift();
    }

    fs.writeFileSync(historyFile, JSON.stringify(history, null, 4));
}

/**
 * Add a movie to the wanted list
 *
 * @param  string movie_name The movie name
 *
 * @return string
 */
function couchpotato_search(movie_name) {
    if (_.isEmpty(movie_name)) {
        return 'Usage: couchpotato search [name of movie]';
    }

    var options = _.clone(couchPotatoApi);
    options.path += "movie.search/?q=" + encodeURIComponent(movie_name);

    http_get(options,
        function (result) {
            if (result.success === true && result.movies !== undefined) {
                var searchResults = [];
                for (i=0; i < result.movies.length && i < MAX_SEARCH_RESULTS; i++) {
                    var movie = result.movies[i];
                    var movieTitle = movie.original_title + " (" + movie.year + ")";

                    if (movie.in_library !== false) {
                        queue_sms(movieTitle + ' is already in your library');
                    } else if (movie.in_wanted !== false) {
                        queue_sms(movieTitle + ' is already in your wanted list');
                    } else {
                        var commandId = get_next_command_index();
                        add_history({
                            "command_id": commandId,
                            "app": "couchpotato",
                            "imdb": movie.imdb,
                            "title": movieTitle
                        });

                        queue_sms(commandId + ". " + movieTitle);
                    }
                }

                send_sms_queue();
            } else {
                send_sms('No matches found for ' + movie_name);
            }
        },
        function(e) {
            var errorMessage = "couchpotato_search error: " + e.message;
            console.log(e.message);
            send_sms(errorMessage);
        }
    );
}

/**
 * Add a movie to couch potato
 *
 * @param string command_id The command id for the movie
 */
function couchpotato_add(command_id) {
    if (_.isEmpty(command_id)) {
        throw "Invalid command id";
    }

    var history = get_history().reverse();
    var movie = _.find(history, function (item) {
        if (item['app'] == "couchpotato" && item['command_id'] == command_id) {
            return true;
        }
    });

    if (!movie) {
        return send_sms('Invalid selection: ' + command_id);
    }

    imdb_id = movie['imdb'].trim();
    var options = _.clone(couchPotatoApi);
    options.path += "movie.add/?identifier=" + imdb_id;

    http_get(options,
        function (result) {
            if (result.success === true)  {
                send_sms(movie['title'] + ' added to wanted list');
            } else {
                send_sms('Could not add ' + movie['title'] + ' to wanted list');
            }
        },
        function(e) {
            var errorMessage = "couchpotato_add error: " + e.message;
            console.log(e.message);
            send_sms(errorMessage);
        }
    );
}

/**
 * Add a tv show to sickbeard
 *
 * @param  string show_name The tv show name
 *
 * @return string
 */
function sickbeard_search(show_name) {
    if (_.isEmpty(show_name)) {
        throw "Invalid show name";
    }

    var options = _.clone(sickbeardApi);
    options.path += "?cmd=sb.searchtvdb&lang=en&name=" + encodeURIComponent(show_name);

    http_get(options,
        function (result) {
            if (result.result == 'success') {
                if (result.data.results.length === 0) {
                    send_sms('No matches found for ' + show_name);
                    return;
                }

                for (i=0; i < result.data.results.length && i < MAX_SEARCH_RESULTS; i++) {
                    var show = result.data.results[i];
                    if (show.first_aired !== null) {
                        show.year = show.first_aired.replace(/-.*$/, '');
                    } else {
                        show.year = null;
                    }
                    var showTitle = show.name + " (" + show.year + ")";

                    var commandId = get_next_command_index();
                    add_history({
                        "command_id": commandId,
                        "app": "sickbeard",
                        "tvdbid": show.tvdbid,
                        "title": showTitle
                    });

                    queue_sms(commandId + ". " + showTitle);
                }

                send_sms_queue();
            } else {
                send_sms('Could not add ' + show_name + ': ' + result.message);
            }
        },
        function(e) {
            var errorMessage = "sickbeard_search error: " + e.message;
            console.log(e.message);
            send_sms(errorMessage);
        }
    );
}

/**
 * Add a tv show to sickbeard
 *
 * @param string tvdb_id The tvdb id for the tv show
 */
function sickbeard_add(command_id) {
    if (_.isEmpty(command_id)) {
        throw "Invalid command id";
    }

    var history = get_history().reverse();
    var show = _.find(history, function (item) {
        if (item['app'] == "sickbeard" && item['command_id'] == command_id) {
            return true;
        }
    });

    if (!show) {
        return send_sms('Invalid selection: ' + command_id);
    }

    var tvdb_id = show['tvdbid'];
    var options = _.clone(sickbeardApi);
    options.path += "?cmd=show.addnew&tvdbid=" + tvdb_id;

    http_get(options,
        function (result) {
            if (result.result == 'success') {
                send_sms(show['title'] + ' added!');
            } else {
                send_sms('Could not add ' + show['title'] + ': ' + result.message);
            }
        },
        function(e) {
            var errorMessage = "sickbeard_add error: " + e.message;
            console.log(e.message);
            send_sms(errorMessage);
        }
    );
}

/**
 * Make a HTTP GET request
 *
 * @param object options The url parameters
 * @param function callback_success Call this function on success
 * @param function callback_error call this function on error
 */
function http_get(options, callback_success, callback_error) {
    http.get(options, function (http_res) {
        var data = "";

        http_res.on("data", function (chunk) {
            data += chunk;
        });

        http_res.on("end", function () {
            result = JSON.parse(data);
            callback_success(result);
        });
    }).on('error', callback_error);
}

/**
 * Send an SMS message
 *
 * @param  string body The SMS body
 */
function send_sms(body) {
    var options = {
        to: myMobileNumber,
        from: twilioFromNumber,
        body: body.trim()
    };

    console.log("Sending SMS", JSON.stringify(options));

    if (!debug) {
        twilioClient.sms.messages.create(options, function(error, responseData) {
            if (error) {
                console.log(responseData);
            }
        });
    }
}

/**
 * Add an SMS message to the queue
 *
 * @param string message The message to send
 */
var sms_queue = [];
function queue_sms(message) {
    if (message.length > MAX_SMS_LENGTH) {
        console.log("Not adding message to queue, message is too long: " + message);
        return;
    }

    sms_queue.push(message);
}

/**
 * Send all queued SMS messages
 *
 * Bundle the SMS messages up so we send as many lines as possible per message
 */
function send_sms_queue() {
    if (sms_queue.length > 0) {
        var messageBuffer = '';
        for (var i in sms_queue) {
            if (sms_queue[i].length > MAX_SMS_LENGTH) {
                console.log("Not sending message from queue, message is too long: " + sms_queue[i]);
                continue;
            }

            if ((messageBuffer + sms_queue[i] + 1).length > MAX_SMS_LENGTH) {
                send_sms(messageBuffer);
                messageBuffer = '';
            } else {
                messageBuffer += sms_queue[i] + "\n";
            }
        }

        messageBuffer = messageBuffer.trim();
        if (messageBuffer.length > 0) {
            send_sms(messageBuffer);
        }
    } else {
        console.log("SMS queue empty, not sending anything");
    }

    sms_queue = [];
}

// Start the show!
app.listen(appPort);
console.log('Listening on port ' + appPort + '...');
<|endoftext|>


<commit_before>var async = require('async');
var naan = require('naan');
var _ = require('underscore');
var util = require('util');

exports.uniqueness = {};

exports.uniqueness.create = function(label, keys, callback) {
  if (!Array.isArray(keys)) keys = [keys];

  label = encodeURIComponent(label);
  var body = { property_keys: keys };

  var endpoint = util.format('schema/constraint/%s/uniqueness', label);
  var op = this.operation(endpoint, 'POST', body);
  this.call(op, function(err, index) {
    if (err) callback(err);
    else callback(null, index);
  });
};

exports.uniqueness.list = function(label, key, callback) {
  if (typeof key == 'function') {
    callback = key;
    key = null;
  }

  label = encodeURIComponent(label);
  var endpoint = util.format('schema/constraint/%s/uniqueness', label);

  if (key) {
    key = encodeURIComponent(key);
    endpoint += '/' + key;
  }

  var op = this.operation(endpoint, 'GET');
  this.call(op, function(err, constraints) {
    if (err) callback(err);
    else callback(null, constraints);
  });
};

exports.uniqueness.drop = function(label, key, callback) {
  label = encodeURIComponent(label);
  key = encodeURIComponent(key);
  var endpoint = util.format('schema/constraint/%s/uniqueness/%s', label, key);
  var op = this.operation(endpoint, 'DELETE');
  this.call(op, function(err) {
    if (err) callback(err);
    else callback();
  });
};

exports.list = function(label, callback) {
  if (typeof label == 'function') {
    callback = label;
    label = null;
  }

  var endpoint = 'schema/constraint';

  if (label) endpoint += '/' + encodeURIComponent(label);

  var op = this.operation(endpoint, 'GET');
  this.call(op, function(err, constraints) {
    if (err) callback(err);
    else callback(null, constraints);
  });
};
<commit_msg>constraints: createIfNone for uniqueness constraints<commit_after>var async = require('async');
var naan = require('naan');
var _ = require('underscore');
var util = require('util');

exports.uniqueness = {};

exports.uniqueness.create = function(label, keys, callback) {
  if (!Array.isArray(keys)) keys = [keys];

  label = encodeURIComponent(label);
  var body = { property_keys: keys };

  var endpoint = util.format('schema/constraint/%s/uniqueness', label);
  var op = this.operation(endpoint, 'POST', body);
  this.call(op, function(err, index) {
    if (err) callback(err);
    else callback(null, index);
  });
};

exports.uniqueness.createIfNone = function(label, keys, callback) {
  var self = this;
  exports.uniqueness.create.call(this, label, keys, function(err, constraint) {
    if (!err) callback(null, constraint);
    else if (err.statusCode != 409) callback(err);
    else {
      exports.uniqueness.list.call(self, label, keys, function(err, constraint) {
        if (err) callback(err);
        else callback(null, constraint[0]);
      });
    }
  });
};

exports.uniqueness.list = function(label, key, callback) {
  if (typeof key == 'function') {
    callback = key;
    key = null;
  }

  label = encodeURIComponent(label);
  var endpoint = util.format('schema/constraint/%s/uniqueness', label);

  if (key) {
    key = encodeURIComponent(key);
    endpoint += '/' + key;
  }

  var op = this.operation(endpoint, 'GET');
  this.call(op, function(err, constraints) {
    if (err) callback(err);
    else callback(null, constraints);
  });
};

exports.uniqueness.drop = function(label, key, callback) {
  label = encodeURIComponent(label);
  key = encodeURIComponent(key);
  var endpoint = util.format('schema/constraint/%s/uniqueness/%s', label, key);
  var op = this.operation(endpoint, 'DELETE');
  this.call(op, function(err) {
    if (err) callback(err);
    else callback();
  });
};

exports.list = function(label, callback) {
  if (typeof label == 'function') {
    callback = label;
    label = null;
  }

  var endpoint = 'schema/constraint';

  if (label) endpoint += '/' + encodeURIComponent(label);

  var op = this.operation(endpoint, 'GET');
  this.call(op, function(err, constraints) {
    if (err) callback(err);
    else callback(null, constraints);
  });
};
<|endoftext|>


<commit_before>/* @file server.js
 * @brief The entire logic for the Directory API, which is just a thin shim
 * around CMU LDAP.
 *
 * @author Shalom Yiblet (shalom@scottylabs)
 * @author Oscar Bezi (bezi@scottylabs)
 */
'use strict';

// =============================================================================
// Config
// =============================================================================
/* @brief URL of the CMU LDAP server. */
var ldapURL = 'ldap://ldap.andrew.cmu.edu';

/* @brief The port to listen on. */
var port = 8080;

/* @brief Returned on 500 err codes. */
var errString = 'Something went wrong.';

// =============================================================================
// LDAP
// =============================================================================
var ldap = require('ldapjs');

var client = ldap.createClient({
  url: ldapURL,
});

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

var app = express();
app.use(morgan('combined'));

// =============================================================================
// Some helper functions.
// =============================================================================

/* @brief Nice date format for startup time. */
var dateFormat = require('dateformat');

/* @brief Searches for an AndrewID using LDAP.
 * @param String andrewID The AndrewID to look for.
 * @param Function callback The callback.
 */
var search = function (andrewId, callback) {
  var options = {
    filter: `(cmuAndrewID=${andrewId})`,
    scope: 'sub',
  };

  client.search('ou=person, dc=cmu, dc=edu', options, function (err, str) {
    if (err) { callback(err); return; }

    var results = [];

    str.on('searchEntry', function (entry) {
      results.push(entry.object);
    });

    str.on('error', function (e) {
      callback(e);
    });

    str.on('end', function () {
      callback(null, results);
    });
  });
};

/* @brief Error checking middleware that's the same for both endpoints.  */
var errCheck = function (req, res, next) {
  search (req.params.id, function (err, response) {
    if (err) {
      res.status(500);
      res.end(errString);
      return;
    }

    if (response.length > 1) {
      res.status(500);
      res.end(errString);
      return;
    }

    if (response.length === 0) {
      res.status(404);
      res.end('Person not found.');
      return;
    }

    var raw = response[0];
    req.rawData = raw;
    next();
  });
};

// =============================================================================
// Routes.
// =============================================================================
app.get('/andrewId/:id/raw', errCheck, function (req, res) {
  res.json(req.rawData);
});

app.get('/andrewId/:id', errCheck, function (req, res) {
  var raw = req.rawData;

  var department = Array.isArray(raw.cmuDepartment)
    ? raw.cmuDepartment
    : [raw.cmuDepartment];

  var person = {
    // All requests will have these fields.
    andrewID: raw.cmuAndrewId,

    first_name: raw.givenName,
    middle_name: raw.cmuMiddleName,
    last_name: raw.sn,

    preferred_email: raw.mail,

    // This may or may not be in the query.
    campus: raw.cmuCampus,
    department: department,
    affiliation: raw.eduPersonPrimaryAffiliation,
    student_level: raw.cmuStudentLevel,
    student_class: raw.cmuStudentClass,
    names: raw.cn,
    job_title: raw.title,
    office: raw.postalAddress,
  };

  res.json(person);
});

// Start up the server.
app.listen(port,
  () => {
    var now = dateFormat(new Date (), "dddd, mmmm dS, yyyy, h:MM:ss TT");
    console.log(`Directory API up and running on port ${ port }: ${ now }.`)
  }
);
<commit_msg>Caches results for 5 minutes<commit_after>/* @file server.js
 * @brief The entire logic for the Directory API, which is just a thin shim
 * around CMU LDAP.
 *
 * @author Shalom Yiblet (shalom@scottylabs)
 * @author Oscar Bezi (bezi@scottylabs)
 */
'use strict';

// =============================================================================
// Config
// =============================================================================
/* @brief URL of the CMU LDAP server. */
var ldapURL = 'ldap://ldap.andrew.cmu.edu';

/* @brief The port to listen on. */
var port = 8080;

/* @brief Returned on 500 err codes. */
var errString = 'Something went wrong.';

// =============================================================================
// LDAP
// =============================================================================
var ldap = require('ldapjs');

var client = ldap.createClient({
  url: ldapURL,
});

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

var app = express();
app.use(morgan('combined'));

// =============================================================================
// Cache
// =============================================================================

var cache = {};
var keepLength = 1 * 60 * 1000; // 5 minutes

/* @brief Saves data to cache
 * @param String andrewID The AndrewID the data represents.
 * @param Array results The results from search()
 */
var saveToCache = function (andrewId, results) {
  if (results.length == 0) return; // don't save if not found

  cache[andrewId] = {
    'date': new Date(),
    'rawData': results
  }
};

/* @brief Checks the cache for data for an andrewId
 * @param String andrewID The AndrewID to look for.
 */
var checkCache = function (andrewId) {
  console.log("checking cache");
  if (!cache[andrewId]) return null;

  var obj = cache[andrewId],
      timeElapsed = new Date() - obj['date'];

  if (timeElapsed <= keepLength) return obj['rawData'];

  return null;
};

// =============================================================================
// Some helper functions.
// =============================================================================

/* @brief Nice date format for startup time. */
var dateFormat = require('dateformat');

/* @brief Searches for an AndrewID using LDAP.
 * @param String andrewID The AndrewID to look for.
 * @param Function callback The callback.
 */
var search = function (andrewId, callback) {
  var cachedObj = checkCache(andrewId);
  if (cachedObj) {
    callback(null, cachedObj);
    return;
  }

  var options = {
    filter: `(cmuAndrewID=${andrewId})`,
    scope: 'sub',
  };

  client.search('ou=person, dc=cmu, dc=edu', options, function (err, str) {
    if (err) { callback(err); return; }

    var results = [];

    str.on('searchEntry', function (entry) {
      results.push(entry.object);
    });

    str.on('error', function (e) {
      callback(e);
    });

    str.on('end', function () {
      saveToCache(andrewId, results);
      callback(null, results);
    });
  });
};

/* @brief Error checking middleware that's the same for both endpoints.  */
var errCheck = function (req, res, next) {
  search (req.params.id, function (err, response) {
    if (err) {
      res.status(500);
      res.end(errString);
      return;
    }

    if (response.length > 1) {
      res.status(500);
      res.end(errString);
      return;
    }

    if (response.length === 0) {
      res.status(404);
      res.end('Person not found.');
      return;
    }

    var raw = response[0];
    req.rawData = raw;
    next();
  });
};

// =============================================================================
// Routes.
// =============================================================================
app.get('/andrewId/:id/raw', errCheck, function (req, res) {
  res.json(req.rawData);
});

app.get('/andrewId/:id', errCheck, function (req, res) {
  var raw = req.rawData;

  var department = Array.isArray(raw.cmuDepartment)
    ? raw.cmuDepartment
    : [raw.cmuDepartment];

  var person = {
    // All requests will have these fields.
    andrewID: raw.cmuAndrewId,

    first_name: raw.givenName,
    middle_name: raw.cmuMiddleName,
    last_name: raw.sn,

    preferred_email: raw.mail,

    // This may or may not be in the query.
    campus: raw.cmuCampus,
    department: department,
    affiliation: raw.eduPersonPrimaryAffiliation,
    student_level: raw.cmuStudentLevel,
    student_class: raw.cmuStudentClass,
    names: raw.cn,
    job_title: raw.title,
    office: raw.postalAddress,
  };

  res.json(person);
});

// Start up the server.
app.listen(port,
  () => {
    var now = dateFormat(new Date (), "dddd, mmmm dS, yyyy, h:MM:ss TT");
    console.log(`Directory API up and running on port ${ port }: ${ now }.`)
  }
);
<|endoftext|>


<commit_before>'use strict'

const webpack = require('webpack')
const webpackDevServer = require('webpack-dev-server')
const config = require('./webpack.config')

new webpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    historyApiFallback: true,
    stats: { colors: true }
}).listen(3000, (err) => {
    if (err) {
        return console.log(err)
    }

    console.log('listening on http://localhost:3000')
})<commit_msg>Add inline parameter for the config hot module reload.<commit_after>'use strict'

const webpack = require('webpack')
const webpackDevServer = require('webpack-dev-server')
const config = require('./webpack.config')

new webpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    inline: true,
    historyApiFallback: true,
    stats: { colors: true }
}).listen(3000, (err) => {
    if (err) {
        return console.log(err)
    }

    console.log('listening on http://localhost:3000')
})<|endoftext|>


<commit_before>"use strict";
var glob = require("glob"),
    cobody = require("co-body"),
    multipart = require('co-multipart'),
    override = require("koa-override-method"),
    fs = require("fs"),
    pathModule = require("path"),
    koaTrieRouter = require("koa-trie-router"),
    methods = require("methods"),
    debugModule = require("debug"),
    compose = require("koa-compose"),
    debug = debugModule("koala-puree:controllers");

function genController(file, name, remove) {
    remove = remove === undefined ? false : remove;
    var path = pathModule.join(file), handlers;
    if ( remove ) {
        delete require.cache[path];
    }
    debug(`generating controller: ${path}`);
    handlers = require(path);
    return handlers;
}

exports = module.exports = function pureecontrollers(){

    return {
        setup: function* (next) {
            debug("beginning controller middleware setup");
            var app = this;
            function* overrideMethodMiddleware(next){
                var body, parts;
                debug("body middleware", this.req.url);
        // only parse if it is form, cause if not, this is not a problem
                if ( /application\/x-www-form-urlencoded/.test(this.req.headers["content-type"])) {
                    if ( this.request.method === "POST" && this.req.headers["content-type"] ) {
                        debug("this is here &&&&&&&&&&&&&&&&&", this.req.headers);
                        if ( !this.req.headers["content-length"] && !this.req.headers["transfer-encoding"] ) {
                            debug("it doesnt have content-length neither does it have transfer-encoding, set it empty")
                            body = {};
                        } else {
                            if (this.req.headers['content-type'].match(/multipart/)) {
                                parts = yield* multipart(this);
                                body = parts.fields.reduce((prev, cur, index, arr) => {
                                    prev[cur[0]] = cur[1];
                                    return prev;
                                })
                                body.files = parts.files;
                            } else {
                                body = yield cobody(this);
                            }
                            let method = override.call(this, body);
                            this.request.method = method;
                            this.req.method = method;
                            delete body._method;
                        }
                    }
                }
                var self = this;
                this.req.body = function*(){

                    debug("body generator");
                    debug("req.body req headers:",self.req.headers);
                    if ( !self.req.headers["content-length"] && !self.req.headers["transfer-encoding"] ) {
                        debug("it doesnt have content-length neither does it have transfer-encoding, set it empty")
                        body = {};
                        return body;
                    }
                    if ( body ) {
                        debug("body is already parsed before", body);
                        return body;
                    }
                    if (self.req.headers['content-type'].match(/multipart/)) {
                        debug("this header contains multipart")
                        parts = yield* multipart(this);
                        body = parts.fields.reduce((prev, cur, index, arr) => {
                            debug(cur)
                            prev[cur[0]] = cur[1];
                            return prev;
                        },{})
                        body.files = parts.files;
                        debug('body is now', body);
                    } else {
                        body = yield cobody(this);
                    }
                    delete body._method;
                    return body;
                };
                yield* next;
                if ( parts ) {
                    parts.dispose();
                }
            }
            app._app.use(overrideMethodMiddleware);
            debug("moving to next plugin setup");
            debug("starting here&&&&&&&&&&&&&&&&&&&&&*****************");
            yield* next;
            debug("back again after next plugin");

            this._router = koaTrieRouter(app._app);
            app._app.use(this._router);

            debug("adding methods to router and app");
            for ( let method of methods ) {
                app[method] = function(route, fn){
                    if ( arguments.length < 2 ) {
                        throw `${method} ${route} handler has to have at least one fn`;
                    }
                    if ( arguments.length > 2 || Array.isArray(fn)) {
                        var fns = Array.isArray(fn) ? fn : [].slice.call(arguments,1);

                        fn = compose(fns);
                    }
                    app._app[method](route, fn);
                };
            }
            debug("adding group to app");
            var keysMap = {
                index: ["get", ""],
                show: ["get", "/:id"],
                del: ["del", "/:id"],
                update: ["put", "/:id"],
                create: ["post", ""],
                edit: ["get", "/:id/edit"],
                new: ["get", "/:id/new"]
            };
            function resources(path, obj) {
        // requires various methods to be defined
                debug("looping through in resources helper");
                var mw = [].slice.call(arguments, 1);
                obj = mw.pop();
                var self = this;
                for ( var key in keysMap ) {

                    var val = keysMap[key];
                    var fn = obj[key] || obj.prototype[key];

                    if ( fn ) {

                        (function(fn, val){
                            debug("found the key?", key, obj);
                            self[val[0]](path+val[1], mw.concat(function*(){
                                return yield fn.call(this, this.req, this.res, this.app);
                            }));
                        })(fn, val);
                    }

                }
            }
            app.group = function(path/*, fn*/){
                debug("group is called with "+path);
                var router = [], mw = [].slice.call(arguments, 1, arguments.length -1);
                for ( let method of methods ) {
                    router[method] = function() {

                        var args = [].slice.call(arguments, 0);
                        debug("group router is triggered: "+args[0]+" transform into "+path+args[0]);
                        args[0] = path+args[0];
                        args.splice.apply(args, [1,0].concat(mw));
                        debug(args);
                        app[method].apply(app, args);
                    };
                }
                router.resources = function(/*path, obj*/) {
                    resources.apply(router, arguments);
                };
                arguments[arguments.length-1](router);
            };
            app.resources = function(/*path, obj*/) {
                resources.apply(app, arguments);
            };
      // add a new middleware between trie-router to allow namespacing
            debug("loading controllers");
            try {
                yield (new Promise(function(resolve, reject) {
                    debug(`beginning controller middleware`);
                    var update = function(){
                        app._router.router.trie.child = Object.create(null);
                        app._router.router.trie.children = [];
                        app.controllers = {};
                        glob(pathModule.resolve(app._basePath,"./app/controller/**/*.js"), function (er, files) {

                            if ( er ) { return reject(er); }
                            for ( var f of files ) {
                                var name = f.substr(15,f.length-18);
                                app.controllers[name] = genController(f, name, app._app.env !== "production");
                                app.controllers[name](app, debugModule([app._config.name,"controller",name]));
                                debug(`loaded ${name} into app.controllers`);
                            }
                            debug(`complete initalizing controllers`);
                            resolve();
                        });
                    };

                    update();
                    if ( app._app.env !== "production" ) {
                        fs.watch(pathModule.resolve(app._basePath,"./app/controller/"), function(){
                            debug("something updated");
                            update();
                        });
                    }
                }));
            } catch(e) {
                debug("failed to load", e);
            }
            debug("completing controller middleware setup");
        }
    };

};
<commit_msg>making it watch and resolve recursively, so all sub folders can be used too for app/controllers<commit_after>"use strict";
var glob = require("glob"),
    cobody = require("co-body"),
    multipart = require('co-multipart'),
    override = require("koa-override-method"),
    fs = require("fs"),
    pathModule = require("path"),
    koaTrieRouter = require("koa-trie-router"),
    methods = require("methods"),
    debugModule = require("debug"),
    compose = require("koa-compose"),
    debug = debugModule("koala-puree:controllers");

function genController(file, name, remove) {
    remove = remove === undefined ? false : remove;
    var path = pathModule.join(file), handlers;
    if ( remove ) {
        delete require.cache[path];
    }
    debug(`generating controller: ${path}`);
    handlers = require(path);
    return handlers;
}

exports = module.exports = function pureecontrollers(){

    return {
        setup: function* (next) {
            debug("beginning controller middleware setup");
            var app = this;
            function* overrideMethodMiddleware(next){
                var body, parts;
                debug("body middleware", this.req.url);
        // only parse if it is form, cause if not, this is not a problem
                if ( /application\/x-www-form-urlencoded/.test(this.req.headers["content-type"])) {
                    if ( this.request.method === "POST" && this.req.headers["content-type"] ) {
                        debug("this is here &&&&&&&&&&&&&&&&&", this.req.headers);
                        if ( !this.req.headers["content-length"] && !this.req.headers["transfer-encoding"] ) {
                            debug("it doesnt have content-length neither does it have transfer-encoding, set it empty")
                            body = {};
                        } else {
                            if (this.req.headers['content-type'].match(/multipart/)) {
                                parts = yield* multipart(this);
                                body = parts.fields.reduce((prev, cur, index, arr) => {
                                    prev[cur[0]] = cur[1];
                                    return prev;
                                })
                                body.files = parts.files;
                            } else {
                                body = yield cobody(this);
                            }
                            let method = override.call(this, body);
                            this.request.method = method;
                            this.req.method = method;
                            delete body._method;
                        }
                    }
                }
                var self = this;
                this.req.body = function*(){

                    debug("body generator");
                    debug("req.body req headers:",self.req.headers);
                    if ( !self.req.headers["content-length"] && !self.req.headers["transfer-encoding"] ) {
                        debug("it doesnt have content-length neither does it have transfer-encoding, set it empty")
                        body = {};
                        return body;
                    }
                    if ( body ) {
                        debug("body is already parsed before", body);
                        return body;
                    }
                    if (self.req.headers['content-type'].match(/multipart/)) {
                        debug("this header contains multipart")
                        parts = yield* multipart(this);
                        body = parts.fields.reduce((prev, cur, index, arr) => {
                            debug(cur)
                            prev[cur[0]] = cur[1];
                            return prev;
                        },{})
                        body.files = parts.files;
                        debug('body is now', body);
                    } else {
                        body = yield cobody(this);
                    }
                    delete body._method;
                    return body;
                };
                yield* next;
                if ( parts ) {
                    parts.dispose();
                }
            }
            app._app.use(overrideMethodMiddleware);
            debug("moving to next plugin setup");
            debug("starting here&&&&&&&&&&&&&&&&&&&&&*****************");
            yield* next;
            debug("back again after next plugin");

            this._router = koaTrieRouter(app._app);
            app._app.use(this._router);

            debug("adding methods to router and app");
            for ( let method of methods ) {
                app[method] = function(route, fn){
                    if ( arguments.length < 2 ) {
                        throw `${method} ${route} handler has to have at least one fn`;
                    }
                    if ( arguments.length > 2 || Array.isArray(fn)) {
                        var fns = Array.isArray(fn) ? fn : [].slice.call(arguments,1);

                        fn = compose(fns);
                    }
                    app._app[method](route, fn);
                };
            }
            debug("adding group to app");
            var keysMap = {
                index: ["get", ""],
                show: ["get", "/:id"],
                del: ["del", "/:id"],
                update: ["put", "/:id"],
                create: ["post", ""],
                edit: ["get", "/:id/edit"],
                new: ["get", "/:id/new"]
            };
            function resources(path, obj) {
        // requires various methods to be defined
                debug("looping through in resources helper");
                var mw = [].slice.call(arguments, 1);
                obj = mw.pop();
                var self = this;
                for ( var key in keysMap ) {

                    var val = keysMap[key];
                    var fn = obj[key] || obj.prototype[key];

                    if ( fn ) {

                        (function(fn, val){
                            debug("found the key?", key, obj);
                            self[val[0]](path+val[1], mw.concat(function*(){
                                return yield fn.call(this, this.req, this.res, this.app);
                            }));
                        })(fn, val);
                    }

                }
            }
            app.group = function(path/*, fn*/){
                debug("group is called with "+path);
                var router = [], mw = [].slice.call(arguments, 1, arguments.length -1);
                for ( let method of methods ) {
                    router[method] = function() {

                        var args = [].slice.call(arguments, 0);
                        debug("group router is triggered: "+args[0]+" transform into "+path+args[0]);
                        args[0] = path+args[0];
                        args.splice.apply(args, [1,0].concat(mw));
                        debug(args);
                        app[method].apply(app, args);
                    };
                }
                router.resources = function(/*path, obj*/) {
                    resources.apply(router, arguments);
                };
                arguments[arguments.length-1](router);
            };
            app.resources = function(/*path, obj*/) {
                resources.apply(app, arguments);
            };
      // add a new middleware between trie-router to allow namespacing
            debug("loading controllers");
            try {
                yield (new Promise(function(resolve, reject) {
                    debug(`beginning controller middleware`);
                    var update = function(){
                        app._router.router.trie.child = Object.create(null);
                        app._router.router.trie.children = [];
                        app.controllers = {};
                        glob(pathModule.resolve(app._basePath,"./app/controller/**/*.js"), function (er, files) {

                            if ( er ) { return reject(er); }
                            for ( var f of files ) {
                                var name = f.substr(15,f.length-18);
                                app.controllers[name] = genController(f, name, app._app.env !== "production");
                                app.controllers[name](app, debugModule([app._config.name,"controller",name]));
                                debug(`loaded ${name} into app.controllers`);
                            }
                            debug(`complete initalizing controllers`);
                            resolve();
                        });
                    };

                    update();
                    if ( app._app.env !== "production" ) {
                        fs.watch(pathModule.resolve(app._basePath,"./app/controller/"), {recursive: true}, function(){
                            debug("something updated");
                            update();
                        });
                    }
                }));
            } catch(e) {
                debug("failed to load", e);
            }
            debug("completing controller middleware setup");
        }
    };

};
<|endoftext|>


<commit_before>var _ = require('lodash');
var fs = require("fs");
var path = require("path");
var express = require("express");

// Options
var options = {
  favicon: "./favicon.ico",
  index: "./index.html",
  port: 8000,
  host: "0.0.0.0",
  folders: {
    "app": "dist/release",
    "assets/js/libs": "dist/release",
    "assets/css": "dist/release",
    "assets/vendor/bootstrap/img": "assets/vendor/bootstrap/img"
  },
  files: {
    "favicon.ico": "favicon.ico"
  }
}

var site = express.createServer();
console.log("Listening on http://" + options.host + ":" + options.port);

// Allow users to override the root.
var root = "/";

// Process stylus stylesheets.
site.get(/.styl$/, function (req, res) {
  var url = req.url.split("assets/css/")[1];
  var file = path.join("assets/css", url);

  fs.readFile(file, function (err, contents) {
    grunt.helper("stylus", contents.toString(), {
      paths: ["assets/css/", require("nib").path]
    }, function (css) {
      res.header("Content-type", "text/css");
      res.send(css);
    });
  });
});

// Process LESS stylesheets.
site.get(/.less$/, function (req, res) {
  var url = req.url.split("assets/css/")[1];
  var file = path.join("assets/css", url);

  fs.readFile(file, function (err, contents) {
    grunt.helper("less", contents.toString(), {
      paths: ["assets/css/"]
    }, function (css) {
      res.header("Content-type", "text/css");
      res.send(css);
    });
  });
});

// Map static folders.
Object.keys(options.folders).sort().reverse().forEach(function (key) {
  site.get(root + key + "/*", function (req, res, next) {
    // Find filename.
    var filename = req.url.slice((root + key).length)
    // If there are query parameters, remove them.
    filename = filename.split("?")[0];

    res.sendfile(path.join(options.folders[key] + filename));
  });
});

// Map static files.
if (_.isObject(options.files)) {
  Object.keys(options.files).sort().reverse().forEach(function (key) {
    site.get(root + key, function (req, res) {
      return res.sendfile(options.files[key]);
    });
  });
}

// Serve favicon.ico.
site.use(express.favicon(options.favicon));

// Ensure all routes go home, client side app..
site.all("*", function (req, res) {
  fs.createReadStream(options.index).pipe(res);
});

// Actually listen
site.listen(options.port, options.host);
<commit_msg>Port from enviroment<commit_after>var _ = require('lodash');
var fs = require("fs");
var path = require("path");
var express = require("express");

// Options
var options = {
  favicon: "./favicon.ico",
  index: "./index.html",
  port: process.env.PORT || 8000,
  host: "0.0.0.0",
  folders: {
    "app": "dist/release",
    "assets/js/libs": "dist/release",
    "assets/css": "dist/release",
    "assets/vendor/bootstrap/img": "assets/vendor/bootstrap/img"
  },
  files: {
    "favicon.ico": "favicon.ico"
  }
}

var site = express.createServer();
console.log("Listening on http://" + options.host + ":" + options.port);

// Allow users to override the root.
var root = "/";

// Process stylus stylesheets.
site.get(/.styl$/, function (req, res) {
  var url = req.url.split("assets/css/")[1];
  var file = path.join("assets/css", url);

  fs.readFile(file, function (err, contents) {
    grunt.helper("stylus", contents.toString(), {
      paths: ["assets/css/", require("nib").path]
    }, function (css) {
      res.header("Content-type", "text/css");
      res.send(css);
    });
  });
});

// Process LESS stylesheets.
site.get(/.less$/, function (req, res) {
  var url = req.url.split("assets/css/")[1];
  var file = path.join("assets/css", url);

  fs.readFile(file, function (err, contents) {
    grunt.helper("less", contents.toString(), {
      paths: ["assets/css/"]
    }, function (css) {
      res.header("Content-type", "text/css");
      res.send(css);
    });
  });
});

// Map static folders.
Object.keys(options.folders).sort().reverse().forEach(function (key) {
  site.get(root + key + "/*", function (req, res, next) {
    // Find filename.
    var filename = req.url.slice((root + key).length)
    // If there are query parameters, remove them.
    filename = filename.split("?")[0];

    res.sendfile(path.join(options.folders[key] + filename));
  });
});

// Map static files.
if (_.isObject(options.files)) {
  Object.keys(options.files).sort().reverse().forEach(function (key) {
    site.get(root + key, function (req, res) {
      return res.sendfile(options.files[key]);
    });
  });
}

// Serve favicon.ico.
site.use(express.favicon(options.favicon));

// Ensure all routes go home, client side app..
site.all("*", function (req, res) {
  fs.createReadStream(options.index).pipe(res);
});

// Actually listen
site.listen(options.port, options.host);
<|endoftext|>


<commit_before>const fs = require('fs');
const express = require('express');
const app = express();
const morgan = require('morgan');

/*
Set up lunr
 */
console.info('Load indices...');
const lunr = require('lunr');
const indices = {
  icd10: lunr.Index.load(JSON.parse(fs.readFileSync('./lunr_index/icd10_index.json'))),
  radlex: lunr.Index.load(JSON.parse(fs.readFileSync('./lunr_index/radlex_index.json'))),
  combined: lunr.Index.load(JSON.parse(fs.readFileSync('./lunr_index/combined_index.json'))),
};
console.info('...done');

/*
Set up lexicons
 */
console.info('Load lexicons...');
const lexicons = {
  icd10: JSON.parse(fs.readFileSync('./sources/icd10/icd10.json')),
  radlex: JSON.parse(fs.readFileSync('./sources/radlex/radlex.json')),
};
let combinedLexicons = [];
for (key in lexicons) {
  combinedLexicons = combinedLexicons.concat(lexicons[key]);
}
lexicons.combined = combinedLexicons;
console.info('...done');

/*
Config
 */
const resultLimit = 20;
app.use(morgan('combined'));

/*
Routes
 */
app.use(express.static('public'));

app.get('/search', function (req, res) {
  const query = req.query.q;
  const lexicon = req.query.l || 'combined';

  const start = new Date();

  const result = indices[lexicon].search(query).slice(0, resultLimit);
  const fullResult = {
    result: result.map((r) => {
      return {
        doc: lexicons[lexicon][r.ref],
        score: r.score,
      }
    }),
    lexicon,
    perf: {
      numSearched: lexicons[lexicon].length,
      milliseconds: new Date() - start,
    }
  };
  return res.send(fullResult);
});

app.get('/prefetch', function (req, res) {
  const lexicon = req.query.l || 'combined';
  return res.send([]);
})

const port = process.env.PORT || 3000;
app.listen(port, function () {
  console.log(`Lex-search server listening on port ${port}`);
});
<commit_msg>Change logging to include response time<commit_after>const fs = require('fs');
const express = require('express');
const app = express();
const morgan = require('morgan');

/*
Set up lunr
 */
console.info('Load indices...');
const lunr = require('lunr');
const indices = {
  icd10: lunr.Index.load(JSON.parse(fs.readFileSync('./lunr_index/icd10_index.json'))),
  radlex: lunr.Index.load(JSON.parse(fs.readFileSync('./lunr_index/radlex_index.json'))),
  combined: lunr.Index.load(JSON.parse(fs.readFileSync('./lunr_index/combined_index.json'))),
};
console.info('...done');

/*
Set up lexicons
 */
console.info('Load lexicons...');
const lexicons = {
  icd10: JSON.parse(fs.readFileSync('./sources/icd10/icd10.json')),
  radlex: JSON.parse(fs.readFileSync('./sources/radlex/radlex.json')),
};
let combinedLexicons = [];
for (key in lexicons) {
  combinedLexicons = combinedLexicons.concat(lexicons[key]);
}
lexicons.combined = combinedLexicons;
console.info('...done');

/*
Config
 */
const resultLimit = 20;
app.use(morgan('short'));

/*
Routes
 */
app.use(express.static('public'));

app.get('/search', function (req, res) {
  const query = req.query.q;
  const lexicon = req.query.l || 'combined';

  const start = new Date();

  const result = indices[lexicon].search(query).slice(0, resultLimit);
  const fullResult = {
    result: result.map((r) => {
      return {
        doc: lexicons[lexicon][r.ref],
        score: r.score,
      }
    }),
    lexicon,
    perf: {
      numSearched: lexicons[lexicon].length,
      milliseconds: new Date() - start,
    }
  };
  return res.send(fullResult);
});

app.get('/prefetch', function (req, res) {
  const lexicon = req.query.l || 'combined';
  return res.send([]);
})

const port = process.env.PORT || 3000;
app.listen(port, function () {
  console.log(`Lex-search server listening on port ${port}`);
});
<|endoftext|>


<commit_before>const express = require('express')
const app = express()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const path = require('path')
const ip = require('ip')
const TelegramBot = require('node-telegram-bot-api')
const { TELEGRAM_TOKEN, TELEGRAM_CHAT_ID } = process.env

const Game = require('../common/Game.js')
const C = require('../common/constants.js')

let bot
if (TELEGRAM_TOKEN != null) {
  bot = new TelegramBot(TELEGRAM_TOKEN)
}

app.use(express.static('public'))
app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, '..', 'public', 'index.html'))
})

const map = [
  '###############',
  '# 5  ###  3   #',
  '# #   4  ### 2#',
  '#6########### #',
  '# ##########  #',
  '# 7   8  91   #',
  '###############'
].map((row) => row.split(''))

/*
const map = [
  '###################',
  '#                 #',
  '#    ############ #',
  '#   ##  ####      #',
  '#   #  ##### ######',
  '#   ##  ####      #',
  '#    ##### ###### #',
  '#          91     #',
  '#          91     #',
  '###################'
].map((row) => row.split(''))
*/

const game = new Game(map, true)
let timerId
function tickAndSchedule () {
  game.tick()
  timerId = setTimeout(tickAndSchedule, Date.now() + C.TIME_STEP - game.lastTick)
}
tickAndSchedule()

function logMessage (msg) {
  console.log(msg)
  if (bot) bot.sendMessage(TELEGRAM_CHAT_ID, msg)
}

let firstPlayer = true
io.on('connection', function (socket) {
  console.log(`${socket.client.id} connected`)

  socket.on('game:join', (username, debug) => {
    if (typeof username !== 'string' || username.trim().length === 0) {
      username = 'Anonymous'
    }
    debug = Boolean(debug)

    // send telegram notification on first user join
    if (firstPlayer) {
      firstPlayer = false
      logMessage(`server up - ${username} joined game! beep boop`)
    }

    game.onPlayerJoin(socket, username, debug)
  })

  socket.on('player:events', (events, turnIndex) => {
    const shipId = game.getShipIdForSocket(socket)
    if (shipId == null) return // TO-DO: some kind of error sent to the client
    try {
      game.onPlayerEvents(shipId, events, turnIndex)
    } catch (e) {
      if (e instanceof C.InvalidTurnError) {
        console.log(`${socket.client.id} got lost`)
        game.bootstrapSocket(socket)
      }
    }
  })

  socket.on('player:lost', () => {
    console.log(`${socket.client.id} requesting bootstrap`)
    game.bootstrapSocket(socket)
  })

  socket.on('game:ping', () => socket.emit('game:pong', Date.now()))

  socket.on('disconnect', () => {
    const shipId = game.getShipIdForSocket(socket)
    if (shipId == null) return
    game.onPlayerLeave(socket)
  })
})

const PORT = process.env.PORT || 3000
http.listen(PORT, function () {
  console.log(`listening on ${ip.address()}:${PORT}`)
})

function beforeExit () {
  console.log('beforeExit')
  if (TELEGRAM_TOKEN == null) return
  console.log('sending reb  t notification via telegram')
  bot.sendMessage(TELEGRAM_CHAT_ID, 'reb  ting')
  .then(function () { console.log(arguments) })
  .catch(function () { console.log(arguments) })
}
process.on('beforeExit', beforeExit)

process.on('SIGTERM', () => {
  console.log('got SIGTERM')
  clearTimeout(timerId)
  http.close((err) => {
    if (err) throw err
    console.log('closed server')
    beforeExit()
  })
})

setInterval(() => {
  logMessage(`- ${Object.keys(io.sockets.sockets).length} players connected`)
}, 60 * 1000)<commit_msg>Log instead any join/leave<commit_after>const express = require('express')
const app = express()
const http = require('http').Server(app)
const io = require('socket.io')(http)
const path = require('path')
const ip = require('ip')
const TelegramBot = require('node-telegram-bot-api')
const { TELEGRAM_TOKEN, TELEGRAM_CHAT_ID } = process.env

const Game = require('../common/Game.js')
const C = require('../common/constants.js')

let bot
if (TELEGRAM_TOKEN != null) {
  bot = new TelegramBot(TELEGRAM_TOKEN)
}

app.use(express.static('public'))
app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, '..', 'public', 'index.html'))
})

const map = [
  '###############',
  '# 5  ###  3   #',
  '# #   4  ### 2#',
  '#6########### #',
  '# ##########  #',
  '# 7   8  91   #',
  '###############'
].map((row) => row.split(''))

/*
const map = [
  '###################',
  '#                 #',
  '#    ############ #',
  '#   ##  ####      #',
  '#   #  ##### ######',
  '#   ##  ####      #',
  '#    ##### ###### #',
  '#          91     #',
  '#          91     #',
  '###################'
].map((row) => row.split(''))
*/

const game = new Game(map, true)
let timerId
function tickAndSchedule () {
  game.tick()
  timerId = setTimeout(tickAndSchedule, Date.now() + C.TIME_STEP - game.lastTick)
}
tickAndSchedule()

function logMessage (msg) {
  console.log(msg)
  if (bot) bot.sendMessage(TELEGRAM_CHAT_ID, msg)
}

io.on('connection', function (socket) {
  let username
  socket.on('game:join', (givenUsername, debug) => {
    if (typeof givenUsername !== 'string' ||
        givenUsername.trim().length === 0) {
      username = 'Anonymous'
    } else {
      username = givenUsername.slice(0, 20)
    }
    debug = Boolean(debug)

    logMessage(`- ${username} joined - ${Object.keys(io.sockets.sockets).length} players connected`)

    game.onPlayerJoin(socket, username, debug)
  })

  socket.on('player:events', (events, turnIndex) => {
    const shipId = game.getShipIdForSocket(socket)
    if (shipId == null) return // TO-DO: some kind of error sent to the client
    try {
      game.onPlayerEvents(shipId, events, turnIndex)
    } catch (e) {
      if (e instanceof C.InvalidTurnError) {
        console.log(`${socket.client.id} got lost`)
        game.bootstrapSocket(socket)
      }
    }
  })

  socket.on('player:lost', () => {
    console.log(`${socket.client.id} requesting bootstrap`)
    game.bootstrapSocket(socket)
  })

  socket.on('game:ping', () => socket.emit('game:pong', Date.now()))

  socket.on('disconnect', () => {
    const shipId = game.getShipIdForSocket(socket)
    if (shipId == null) return
    game.onPlayerLeave(socket)
    logMessage(`- ${username} left - ${Object.keys(io.sockets.sockets).length} players connected`)
  })
})

const PORT = process.env.PORT || 3000
http.listen(PORT, function () {
  console.log(`listening on ${ip.address()}:${PORT}`)
})

function beforeExit () {
  console.log('beforeExit')
  if (TELEGRAM_TOKEN == null) return
  console.log('sending reb  t notification via telegram')
  bot.sendMessage(TELEGRAM_CHAT_ID, 'reb  ting')
  .then(function () { console.log(arguments) })
  .catch(function () { console.log(arguments) })
}
process.on('beforeExit', beforeExit)

process.on('SIGTERM', () => {
  console.log('got SIGTERM')
  clearTimeout(timerId)
  http.close((err) => {
    if (err) throw err
    console.log('closed server')
    beforeExit()
  })
})<|endoftext|>


<commit_before>//Modules & set up =========================================================
var express      = require('express');
var app          = express();
var port         = 1337 || process.env.PORT;
var morgan       = require('morgan');
var session      = require('express-session');
var bodyParser   = require('body-parser');
var passport     = require('passport');
var mongoose     = require('mongoose');
var credentials  = require('./config/credentials');
var aws          = require('aws-sdk');
const MongoStore = require('connect-mongo')(session);

var AWS_ACCESS_KEY  = process.env.AWS_ACCESS_KEY;
var AWS_SECRET_KEY  = process.env.AWS_SECRET_KEY;

//Config =========================================================
mongoose.connect(credentials.db.url);

aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY});

//config passport
require('./config/passport')(passport);

//app middlewares
//only show logs with arent testing
if (process.env.NODE_ENV !== 'test') {
    app.use(morgan('dev'));
}
app.use(express.static(__dirname + '/public'));

// set the view engine to ejs
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

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

//TODO(Hudo): Check all config options for session in the docs.
app.use(session({
    secret: credentials.sessionSecret,
    resave: false,
    saveUninitialized: true,
    store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());

//Routes =========================================================
require('./routes')(app, passport, aws)

//Server =========================================================
app.listen(port, function() {
    console.log('Listenning on port: ' + port);
});

module.exports = app;
module.exports.mongoose = mongoose;<commit_msg>Fix Url<commit_after>//Modules & set up =========================================================
var express      = require('express');
var app          = express();
var port         = 1337 || process.env.PORT;
var morgan       = require('morgan');
var session      = require('express-session');
var bodyParser   = require('body-parser');
var passport     = require('passport');
var mongoose     = require('mongoose');
var credentials  = require('./config/credentials');
var aws          = require('aws-sdk');
const MongoStore = require('connect-mongo')(session);

var AWS_ACCESS_KEY  = process.env.AWS_ACCESS_KEY;
var AWS_SECRET_KEY  = process.env.AWS_SECRET_KEY;

//Config =========================================================
mongoose.connect(credentials.db_url);

aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY});

//config passport
require('./config/passport')(passport);

//app middlewares
//only show logs with arent testing
if (process.env.NODE_ENV !== 'test') {
    app.use(morgan('dev'));
}
app.use(express.static(__dirname + '/public'));

// set the view engine to ejs
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

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

//TODO(Hudo): Check all config options for session in the docs.
app.use(session({
    secret: credentials.sessionSecret,
    resave: false,
    saveUninitialized: true,
    store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());

//Routes =========================================================
require('./routes')(app, passport, aws)

//Server =========================================================
app.listen(port, function() {
    console.log('Listenning on port: ' + port);
});

module.exports = app;
module.exports.mongoose = mongoose;<|endoftext|>


<commit_before>'use strict';

require('babel-core/register')({});

var server = require('./server').default;

const PORT = process.env.PORT || 3000;

server.listen(PORT, function () {
  console.log('Server listening on: ' + PORT);
});
<commit_msg>[server] Use babel-register instead of babel-core/register<commit_after>'use strict';

require('babel-register')({});

var server = require('./server').default;

const PORT = process.env.PORT || 3000;

server.listen(PORT, function () {
  console.log('Server listening on: ' + PORT);
});
<|endoftext|>


<commit_before>// @flow

import type { $Request, $Response } from 'express';

import express from 'express';
import bodyParser from 'body-parser';
import expressSession from 'express-session';

import calendar from '../domain/calendar';
import api from './api';
import { hash, comparePasswordToHash } from './api/password';

const app = express();
app.use(bodyParser.json());
app.use(
  expressSession({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false,
  }),
);

const users = [];

app.post('/api/user/create', (req: $Request, res) => {
  send(api.createUser(req.body, users, hash), res);
});

app.post('/api/login', (req: $Request, res) => {
  send(
    api.loginUser(
      req.body,
      users,
      saveUserInSession(req),
      comparePasswordToHash,
    ),
    res,
  );
});

function saveUserInSession(req: $Request) {
  return (user: User) => {
    // $FlowFixMe: Not in flow-typed
    req.session.user = user;
  };
}

function send(
  result: | { status: number, body?: mixed }
    | Promise<{ status: number, body?: mixed }>,
  res: $Response,
) {
  if (result instanceof Promise) {
    result
      .then(plain => sendPlain(plain, res))
      .catch(() => sendPlain({ status: 500 }, res));
  } else {
    sendPlain(result, res);
  }
}

function sendPlain(result: { status: number, body?: mixed }, res: $Response) {
  res.status(result.status);
  if (result.body) {
    res.send(result.body);
  } else {
    res.send();
  }
}

app.get('/api/calendar/:year/:month', (req: Request, res) => {
  // $FlowFixMe
  const { year, month } = req.params;
  const dates = calendar.calendarMonth(year, month);

  res.send(
    dates.map((date) => {
      switch (date.date % 4) {
        case 0:
          return Object.assign({}, date, { entryHim: true, entryHer: false });
        case 1:
          return Object.assign({}, date, { entryHim: true, entryHer: true });
        case 2:
          return Object.assign({}, date, { entryHim: false, entryHer: true });
        default:
          return date;
      }
    }),
  );
});

app.listen(3000);
<commit_msg>Simplify types<commit_after>// @flow

import type { $Request, $Response } from 'express';

import express from 'express';
import bodyParser from 'body-parser';
import expressSession from 'express-session';

import calendar from '../domain/calendar';
import api from './api';
import { hash, comparePasswordToHash } from './api/password';

const app = express();
app.use(bodyParser.json());
app.use(
  expressSession({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false,
  }),
);

const users = [];

app.post('/api/user/create', (req: $Request, res) => {
  send(api.createUser(req.body, users, hash), res);
});

app.post('/api/login', (req: $Request, res) => {
  send(
    api.loginUser(
      req.body,
      users,
      saveUserInSession(req),
      comparePasswordToHash,
    ),
    res,
  );
});

function saveUserInSession(req: $Request) {
  return (user: User) => {
    // $FlowFixMe: Not in flow-typed
    req.session.user = user;
  };
}

function send(result: ApiResponse | Promise<ApiResponse>, res: $Response) {
  if (result instanceof Promise) {
    result
      .then(plain => sendPlain(plain, res))
      .catch(() => sendPlain({ status: 500 }, res));
  } else {
    sendPlain(result, res);
  }
}

function sendPlain(result: ApiResponse, res: $Response) {
  res.status(result.status);
  if (result.body) {
    res.send(result.body);
  } else {
    res.send();
  }
}

app.get('/api/calendar/:year/:month', (req: Request, res) => {
  // $FlowFixMe
  const { year, month } = req.params;
  const dates = calendar.calendarMonth(year, month);

  res.send(
    dates.map((date) => {
      switch (date.date % 4) {
        case 0:
          return Object.assign({}, date, { entryHim: true, entryHer: false });
        case 1:
          return Object.assign({}, date, { entryHim: true, entryHer: true });
        case 2:
          return Object.assign({}, date, { entryHim: false, entryHer: true });
        default:
          return date;
      }
    }),
  );
});

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


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

// Create a server with a host, port, and options
var server = Hapi.createServer('0.0.0.0', config.port, config.hapi.options);

// Bootstrap Hapi Server Plugins, passes the server object to the plugins
require('./server/config/plugins')(server);

// Require the routes and pass the server object.
var routes = require('./server/config/routes')(server);
// Add the server routes
server.route(routes);

//Start the server
server.start();

//Log to the console the host and port info
console.log('Server started at: ' + server.info.uri);<commit_msg>Removing useless require of routes<commit_after>/**
* Dependencies.
*/
var Hapi = require('hapi'),
    config = require('./server/config/settings');

// Create a server with a host, port, and options
var server = Hapi.createServer('0.0.0.0', config.port, config.hapi.options);

// Bootstrap Hapi Server Plugins, passes the server object to the plugins
require('./server/config/plugins')(server);

// Require the routes and pass the server object.
var routes = require('./server/config/routes')(server);
// Add the server routes
server.route(routes);

//Start the server
server.start();

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


<commit_before>const _ = require('lodash');
const uid = require('uid');
const read = require('fs').readFileSync;
const redux = require('redux');
const createNodeLogger = require('redux-node-logger');
const clientSource = read(require.resolve('../../dist/bundle.js'), 'utf-8');
const actions = require('./actions');
const reducer = require('./reducer');
const selectors = require('./selectors');

function swip (io, config) {
  const store = redux.createStore(reducer(config));

  io.on('connection', (socket) => {
    const id = uid();

    socket.on(actions.TYPE.CONNECT, (data) => store.dispatch(actions.connect(id, data)));
    socket.on(actions.TYPE.SWIPE, (data) => store.dispatch(actions.swipe(id, data)));
    socket.on(actions.TYPE.LEAVE_CLUSTER, () => store.dispatch(actions.leaveCluster(id)));
    socket.on(actions.TYPE.DISCONNECT, () => store.dispatch(actions.disconnect(id)));
    socket.on(actions.TYPE.CLIENT_ACTION, (data) => store.dispatch(actions.clientAction(id, data)));

    const unsubscribe = store.subscribe(() => {
      const state = store.getState();
      const client = state.clients[id];

      if (_.isNil(client)) {
        return;
      }

      const clientState = selectors.getClientState(state, id);

      socket.emit(actions.TYPE.CHANGED, clientState);
    });

    socket.on('disconnect', () => unsubscribe());
  });

  setInterval(() => store.dispatch(actions.nextState()), 33);

  attachServe(io.httpServer);
}

/* http serve adapted from socket.io */

function attachServe (srv) {
  const url = '/swip/swip.js';
  const evs = srv.listeners('request').slice(0);

  srv.removeAllListeners('request');
  srv.on('request', (req, res) => {
    if (req.url.indexOf(url) === 0) {
      serve(req, res);
    } else {
      for (let i = 0; i < evs.length; i++) {
        evs[i].call(srv, req, res);
      }
    }
  });
}

function serve (req, res) {
  res.setHeader('Content-Type', 'application/javascript');
  res.writeHead(200);
  res.end(clientSource);
}

module.exports = swip;
<commit_msg>chagned the update to 25 fps from 30 fps<commit_after>const _ = require('lodash');
const uid = require('uid');
const read = require('fs').readFileSync;
const redux = require('redux');
const createNodeLogger = require('redux-node-logger');
const clientSource = read(require.resolve('../../dist/bundle.js'), 'utf-8');
const actions = require('./actions');
const reducer = require('./reducer');
const selectors = require('./selectors');

function swip (io, config) {
  const store = redux.createStore(reducer(config));

  io.on('connection', (socket) => {
    const id = uid();

    socket.on(actions.TYPE.CONNECT, (data) => store.dispatch(actions.connect(id, data)));
    socket.on(actions.TYPE.SWIPE, (data) => store.dispatch(actions.swipe(id, data)));
    socket.on(actions.TYPE.LEAVE_CLUSTER, () => store.dispatch(actions.leaveCluster(id)));
    socket.on(actions.TYPE.DISCONNECT, () => store.dispatch(actions.disconnect(id)));
    socket.on(actions.TYPE.CLIENT_ACTION, (data) => store.dispatch(actions.clientAction(id, data)));

    const unsubscribe = store.subscribe(() => {
      const state = store.getState();
      const client = state.clients[id];

      if (_.isNil(client)) {
        return;
      }

      const clientState = selectors.getClientState(state, id);

      socket.emit(actions.TYPE.CHANGED, clientState);
    });

    socket.on('disconnect', () => unsubscribe());
  });

  setInterval(() => store.dispatch(actions.nextState()), 40);

  attachServe(io.httpServer);
}

/* http serve adapted from socket.io */

function attachServe (srv) {
  const url = '/swip/swip.js';
  const evs = srv.listeners('request').slice(0);

  srv.removeAllListeners('request');
  srv.on('request', (req, res) => {
    if (req.url.indexOf(url) === 0) {
      serve(req, res);
    } else {
      for (let i = 0; i < evs.length; i++) {
        evs[i].call(srv, req, res);
      }
    }
  });
}

function serve (req, res) {
  res.setHeader('Content-Type', 'application/javascript');
  res.writeHead(200);
  res.end(clientSource);
}

module.exports = swip;
<|endoftext|>


<commit_before>var path = require('path');

require.paths.unshift( path.join( __dirname,'vendor') )
require.paths.unshift( path.join( __dirname,'vendor','coloured-log','lib') )

var app = require('express/lib/express').createServer(),
    irc = require('IRC-js/lib/irc'),
    io = require('Socket.IO-node'),
    socket = io.listen(app);

var opts = {
    encoding: "utf-8",
};
var webClients = [];
var servers = [];

socket.on('connection', function(client){

    client.on('message', function(clientMessage){
        console.log("got a message :: "+ clientMessage.type);

        switch(clientMessage.type)
        {
            case 'connect':

                var server = new irc({
                    server: clientMessage.data.ircHost,
                    port: clientMessage.data.ircPort,
                    nick: clientMessage.data.nick,
                    encoding: opts.encoding
                });

                channels = clientMessage.data.channels;

                server.connect(function() {
                    setTimeout(function() {
                        for(i in channels) {
                            server.join(channels[i]);
                        }
                    }, 2000);
                });

                server.addListener('privmsg', function(msg) {
                    nick = msg.person.nick;
                    chan = msg.params[0];
                    message = msg.params[1];

                    var data = {channel: chan, from:nick, msg:message};

                    console.log("IRC new: "+msg.params[0]+" - "+msg.person.nick+":"+msg.params[1]+"\n");

                    if(webClients.length != 0) {
                        for(i in webClients) {
                            webClient = webClients[i];

                            if(webClient.server == this) {

                                for(j in webClient.channels) {

                                    if(chan.toLowerCase() == webClient.channels[j].toLowerCase()) {

                                        webClient.client.send(data);

                                    }
                                }
                            }
                        }
                    }

                });

                webClients.push({session:client.sessionId,client:client, server:server, channels: channels});
                console.log("got a client :: "+client.sessionId+" :: "+webClients.length);

                client.send({msgs:[],channels: channels});

                break;

            case 'privmsg':
                console.log("got a message for " + clientMessage.data.channel + " :: "+ clientMessage.data.message);

                if(webClients.length != 0) {
                    for(i in webClients) {
                        webClient = webClients[i];

                        if(webClient.session == client.sessionId) {
                            //TODO: change the from nickname
                            webClient.client.send({channel: clientMessage.data.channel, from:'me', msg:clientMessage.data.message});
                            webClient.server.privmsg(clientMessage.data.channel, clientMessage.data.message);
                        }
                    }
                }

                break;

        }
    });

    client.on('disconnect', function(){
        for(i in webClients) {
            if(webClients[i].session == client.sessionId) {
                webClients[i].server.quit("Leaving");
                webClients.splice(i,1);
            }
        }
        console.log("disconnect");
    });
});

process.on('uncaughtException', function (err) {
    //We should certainly do something here :)
    console.log(err);
});

app.listen(3000);
<commit_msg>Enhanced logger<commit_after>var path = require('path');

require.paths.unshift( path.join( __dirname,'vendor') )
require.paths.unshift( path.join( __dirname,'vendor','coloured-log','lib') )

var app = require('express/lib/express').createServer(),
    irc = require('IRC-js/lib/irc'),
    io = require('Socket.IO-node'),
    socket = io.listen(app);

var opts = {
    encoding: "utf-8",
};
var webClients = [];
var servers = [];

socket.on('connection', function(client){

    client.on('message', function(clientMessage){
        console.log("got a message :: "+ clientMessage.type);

        switch(clientMessage.type)
        {
            case 'connect':

                var server = new irc({
                    server: clientMessage.data.ircHost,
                    port: clientMessage.data.ircPort,
                    nick: clientMessage.data.nick,
                    encoding: opts.encoding
                });

                channels = clientMessage.data.channels;

                server.connect(function() {
                    setTimeout(function() {
                        for(i in channels) {
                            server.join(channels[i]);
                        }
                    }, 2000);
                });

                server.addListener('privmsg', function(msg) {
                    nick = msg.person.nick;
                    chan = msg.params[0];
                    message = msg.params[1];

                    var data = {channel: chan, from:nick, msg:message};

                    console.log("IRC new: "+msg.params[0]+" - "+msg.person.nick+":"+msg.params[1]+"\n");

                    if(webClients.length != 0) {
                        for(i in webClients) {
                            webClient = webClients[i];

                            if(webClient.server == this) {

                                for(j in webClient.channels) {

                                    if(chan.toLowerCase() == webClient.channels[j].toLowerCase()) {

                                        webClient.client.send(data);

                                    }
                                }
                            }
                        }
                    }

                });

                webClients.push({session:client.sessionId,client:client, server:server, channels: channels});
                console.log("got a client :: "+client.sessionId+" :: "+webClients.length);

                client.send({msgs:[],channels: channels});

                break;

            case 'privmsg':
                console.log("got a message for " + clientMessage.data.channel + " :: "+ clientMessage.data.message);

                if(webClients.length != 0) {
                    for(i in webClients) {
                        webClient = webClients[i];

                        if(webClient.session == client.sessionId) {
                            //TODO: change the from nickname
                            webClient.client.send({channel: clientMessage.data.channel, from:'me', msg:clientMessage.data.message});
                            webClient.server.privmsg(clientMessage.data.channel, clientMessage.data.message);
                        }
                    }
                }

                break;

        }
    });

    client.on('disconnect', function(){
        for(i in webClients) {
            if(webClients[i].session == client.sessionId) {
                webClients[i].server.quit("Leaving");
                webClients.splice(i,1);
            }
        }
        console.log("disconnect");
    });
});

process.addListener('uncaughtException', function (err, stack) {
  console.log('------------------------');
  console.log('Exception: ' + err);
  console.log(err.stack);
  console.log('------------------------');
});

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


<commit_before>var express = require('express');
var morgan = require('morgan');
var path = require('path');

var app = express();
app.use(morgan('combined'));

app.get('/', function (req, res) {
  res.sendFile(path.join('index.html'));
});

app.get('/luck.css', function (req, res) {
  res.sendFile(path.join('luck.css'));
});

app.get('/1.png', function (req, res) {
  res.sendFile(path.join('1.png'));
});

app.get('/2.png', function (req, res) {
  res.sendFile(path.join('2.png'));
});

app.get('/images.jpg', function (req, res) {
  res.sendFile(path.join('images.jpg'));
});

var port = 8080; // Use 8080 for local development because you might already have apache running on 80
app.listen(8080, function () {
  console.log(`IMAD course app listening on port ${port}!`);
});
<commit_msg>Delete server.js<commit_after><|endoftext|>


<commit_before>var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var statusController = require('./controllers/statuses');
var pushInterval = 10000;

app.use(bodyParser());
require('./config/routes')(app);
app.set('port', 3000);
app.use(require('./controllers/static'));

io.on('connection', function(socket){
    setInterval(function(){ statusController.postDetailsToClient(socket) }, pushInterval);
});

http.listen(app.get('port'), '0.0.0.0',  function () {
      console.log('Server listening on', app.get('port'));
});
<commit_msg>Add configuration for port numebr<commit_after>var bodyParser = require('body-parser');
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var statusController = require('./controllers/statuses');
var pushInterval = 10000;
var port = process.env.PORT || 3000;

app.use(bodyParser());
require('./config/routes')(app);
app.set('port', port);
app.use(require('./controllers/static'));

io.on('connection', function(socket){
    setInterval(function(){ statusController.postDetailsToClient(socket) }, pushInterval);
});

http.listen(app.get('port'), '0.0.0.0',  function () {
      console.log('Server listening on', app.get('port'));
});
<|endoftext|>


<commit_before>var tty = require('./');

var app = tty.createServer({
    shell: 'bash',
    port: 8000,
    static: process.env.HOME + '/.tty.js/static'
    // syncSession: true,
    // sessionTimeout: 3600*24*1000,
    // users: {
    //     u:"p"
    // }
});

app.get('/foo', function(req, res, next) {
  res.send('bar');
});

app.listen();
<commit_msg>Incorrect path.<commit_after>var tty = require('./');

var app = tty.createServer({
    shell: 'bash',
    port: 8000,
    static: process.env.HOME + '/.gfx.js/static'
    // syncSession: true,
    // sessionTimeout: 3600*24*1000,
    // users: {
    //     u:"p"
    // }
});

app.get('/foo', function(req, res, next) {
  res.send('bar');
});

app.listen();
<|endoftext|>