<commit_before>var CANVAS_WIDTH = 2000;
var CANVAS_HEIGHT = 2000;

var OnlinePlayer = require('./public/online-player');
var GamePackager = require('./lib/game-packager');
var FoodGenerator = require('./lib/food-generator');
var gamePackager = new GamePackager();

var foodGen = new FoodGenerator(CANVAS_WIDTH, CANVAS_HEIGHT);

const EXPRESS = require('express');
const APP = EXPRESS();
const PORT = process.env.PORT || 8181;
const HTTP = require('http').Server(APP).listen(PORT, function() {
  console.log('Listening on port ' + PORT + '.');
});
const IO = require('socket.io')(HTTP);

var players = [];
var food    = [];
var boosts  = [];
var viruses = [];
var playersToDelete = [];
var gameState = null;

APP.use(EXPRESS.static('public'));
APP.get('/', function(req, res) {
  res.sendFile(__dirname + '/public/index.html');
});

IO.on('connection', socketHandshake);

function gameLoop() {
  foodGen.replaceFood(food, boosts, players, viruses);
  for(var i = 0; i < playersToDelete.length; i++){
    deletePlayer(playersToDelete[i]);
  }
  playersToDelete = [];
  gameState = gamePackager.buildGameState(players, food, boosts, viruses);
  IO.sockets.emit('gameState', gameState);
}

setInterval(gameLoop, 45);

function findPlayer(socketID) {
  for(var i = 0; i < players.length; i++) {
    if (players[i].id === socketID) {
      return players[i];
    }
  }
}

function socketHandshake(socket) {
  if(IO.engine.clientsCount === 1) {
    food = foodGen.seedFood(players);
    boosts = foodGen.seedSpeedBoosts(players);
    viruses = foodGen.seedViruses(players);
  }
  var player_name = ("Player " + (players.length + 1));
  var startingX = Math.floor((Math.random() * CANVAS_WIDTH) + 5)
  var startingY = Math.floor((Math.random() * CANVAS_HEIGHT) + 5)
  players.push(new OnlinePlayer(socket.id, player_name, startingX, startingY));

  socket.on('message', function(channel, message){
    if (channel === 'userInfo') {
      var playerToUpdate = findPlayer(socket.id);
      playerToUpdate.name = message[0];
      playerToUpdate.color = '#' + message[1];
    }

    if (channel === 'keysPressed') {
      var player = findPlayer(socket.id);
      if(typeof player !== "undefined"){
        player.resetBoosts();
        player.move(message);
        player.eatFood.call(player, food);
        player.eatBoosts.call(player, boosts);
        player.eatViruses.call(player, viruses);
        if(players.length > 0){
          player.eatPlayer(players);
        }
      }
    }
  });

  socket.on('disconnect', function() {
    playersToDelete.push(socket.id);
    console.log('A user has disconnected.', IO.engine.clientsCount);
  });

  console.log('A user has connected.', IO.engine.clientsCount);
  IO.sockets.emit('usersConnected', IO.engine.clientsCount);
  socket.emit('status', 'You are connected!');

  gameState = gameState || gamePackager.buildGameState(players, food, boosts, viruses);

  socket.emit("gameState", gameState);
  socket.emit('playerInitialized');
}

function deletePlayer(socketID) {
  for(var i = 0; i < players.length; i++) {
    if (players[i].id === socketID) {
      console.log('Disconnected player: ' + players[i].name);
      players.splice(i, 1);
    }
  }
}
<commit_msg>Merging master<commit_after>var CANVAS_WIDTH = 2000;
var CANVAS_HEIGHT = 2000;

var OnlinePlayer = require('./public/online-player');
var GamePackager = require('./lib/game-packager');
var FoodGenerator = require('./lib/food-generator');
var gamePackager = new GamePackager();

var foodGen = new FoodGenerator(CANVAS_WIDTH, CANVAS_HEIGHT);

const EXPRESS = require('express');
const APP = EXPRESS();
const PORT = process.env.PORT || 8181;
const HTTP = require('http').Server(APP).listen(PORT, function() {
  console.log('Listening on port ' + PORT + '.');
});
const IO = require('socket.io')(HTTP);

var players = [];
var food    = [];
var boosts  = [];
var viruses = [];
var playersToDelete = [];
var gameState = null;

APP.use(EXPRESS.static('public'));
APP.get('/', function(req, res) {
  res.sendFile(__dirname + '/public/index.html');
});

IO.on('connection', socketHandshake);

function gameLoop() {
  foodGen.replaceFood(food, boosts, players, viruses);
  for(var i = 0; i < playersToDelete.length; i++){
    deletePlayer(playersToDelete[i]);
  }
  playersToDelete = [];
  gameState = gamePackager.buildGameState(players, food, boosts, viruses);
  IO.sockets.emit('gameState', gameState);
}

setInterval(gameLoop, 45);

function findPlayer(socketID) {
  for(var i = 0; i < players.length; i++) {
    if (players[i].id === socketID) {
      return players[i];
    }
  }
}

function socketHandshake(socket) {
  if(IO.engine.clientsCount === 1) {
    food = foodGen.seedFood(players);
    boosts = foodGen.seedSpeedBoosts(players);
    viruses = foodGen.seedViruses(players);
  }
  var player_name = ("Player " + (players.length + 1));
  var startingX = Math.floor((Math.random() * CANVAS_WIDTH) + 5)
  var startingY = Math.floor((Math.random() * CANVAS_HEIGHT) + 5)
  players.push(new OnlinePlayer(socket.id, player_name, startingX, startingY));

  socket.on('message', function(channel, message){
    if (channel === 'userInfo') {
      var playerToUpdate = findPlayer(socket.id);
      playerToUpdate.name = message[0];
      playerToUpdate.color = '#' + message[1];
    }

    if (channel === 'keysPressed') {
      var player = findPlayer(socket.id);
      if(typeof player !== "undefined"){
        player.resetBoosts();
        player.move(message);
        player.eatFood.call(player, food);
        player.eatBoosts.call(player, boosts);
        player.eatViruses.call(player, viruses);
        if(players.length > 0){
          player.eatPlayer(players);
        }
      }
    }
  });

  socket.on('disconnect', function() {
    playersToDelete.push(socket.id);
    console.log('A user has disconnected.', IO.engine.clientsCount);
  });

  console.log('A user has connected.', IO.engine.clientsCount);
  IO.sockets.emit('usersConnected', IO.engine.clientsCount);
  socket.emit('status', 'You are connected!');

  gameState = gameState || gamePackager.buildGameState(players, food, boosts, viruses);

  socket.emit("gameState", gameState);
  socket.emit('playerInitialized');
}

function deletePlayer(socketID) {
  for(var i = 0; i < players.length; i++) {
    if (players[i].id === socketID) {
      console.log('Disconnected player: ' + players[i].name);
      players.splice(i, 1);
    }
  }
}

<|endoftext|>


<commit_before>const internalIp = require('internal-ip');
const express = require('express');
const app = express();
const mongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId;
const assert = require('assert');
const bodyParser = require('body-parser');

const port = 3001;
const mongoDBPort = 37001;
const ip = internalIp.v4();

// Connection URL
const url = 'mongodb://localhost:' + mongoDBPort + '/random-user-api';

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

app.get('/', (req, res) => {
    res.redirect("/health-check");
});

app.get('/health-check', (req, res) => {
    mongoClient.connect(url, (err, db) => {
      assert.equal(null, err);

      res.set('Content-Type', 'text/plain');
      res.status(200);
      res.send("Connected successfully to server!\n");

      db.close();
    });
});

app.route('/add-user')
    .get((req, res, next) => {
        res.sendFile(__dirname + "/views/add-user.html");
    })
    .post((req, res, next) => {
        mongoClient.connect(url, (err, db) => {
            assert.equal(null, err);
            const collection = db.collection('users');
            collection.insertOne({
                "firstName": req.body.firstName,
                "lastName": req.body.lastName,
            }, {
                w: 'majority',
                wtimeout: 10000,
                serializeFunctions: true
            }, (err, result) => {
                assert.equal(err, null);
                assert.equal(1, result.insertedCount);

                res.set('Content-Type', 'text/plain');
                res.status(200);
                res.send("Successfully added " + req.body.firstName + " " + req.body.lastName + " to database.\n");

                db.close();
            });
        });
    });

app.route('/get-user')
    .get((req, res, next) => {
        res.sendFile(__dirname + "/views/get-user.html");
    })
    .post((req, res, next) => {
        mongoClient.connect(url, (err, db) => {
            assert.equal(null, err);

            const query = {};
            if (req.body.firstName) {
                query.firstName = req.body.firstName;
            }
            if (req.body.lastName) {
                query.lastName = req.body.lastName;
            }
            if (req.body.uid) {
                query._id = ObjectId(req.body.uid);
            }

            const collection = db.collection('users');
            collection.find(query).toArray((err, docs) => {
                assert.equal(err, null);
                assert.notEqual(docs.length, 0);

                res.set('Content-Type', 'text/plain');
                res.status(200);
                res.json(docs);

                db.close();
            });
        });
    });

app.route('/delete-user')
    .get((req, res, next) => {
        res.sendFile(__dirname + "/views/delete-user.html");
    })
    .post((req, res, next) => {
        mongoClient.connect(url, (err, db) => {
            assert.equal(null, err);

            const query = {};
            if (req.body.uid) {
                query._id = ObjectId(req.body.uid);
            }

            const collection = db.collection('users');
            assert.equal(query.hasOwnProperty("_id"), true);
            collection.findOneAndDelete(query, (err, result) => {
                assert.equal(err, null);

                res.set('Content-Type', 'text/plain');
                res.status(200);
                res.send("Removed the document with the uid: " + query._id);

                db.close();
            });

        });
    });

app.route('/update-user')
    .get((req, res, next) => {
        res.sendFile(__dirname + "/views/update-user.html");
    })
    .post((req, res, next) => {
        mongoClient.connect(url, (err, db) => {
            assert.equal(null, err);

            const query = {};
            const updates = {};
            if (req.body.uid) {
                query._id = ObjectId(req.body.uid);
            }
            if (req.body.firstName) {
                updates.firstName = req.body.firstName;
            }
            if (req.body.lastName) {
                updates.lastName = req.body.lastName;
            }

            const collection = db.collection('users');
            assert.equal(query.hasOwnProperty("_id"), true);

            collection.findOneAndUpdate(query, { $set: updates }, (err, result) => {
                assert.equal(err, null);

                res.set('Content-Type', 'text/plain');
                res.status(200);
                res.send("Updated the data for uid: " + query._id);

                db.close();
            });

        });
    });

app.listen(port, (err) => {
    if (err) {
        console.log(err);
        return;
    }

    console.log(' --------------------------------------------');
    console.log(' Server now running on the following ports...');
    console.log(' --------------------------------------------');
    console.log(`       Local: http://0.0.0.0:${port}`);
    console.log(`       External: http://${ip}:${port}`);
    console.log(' --------------------------------------------');
});
<commit_msg>:package: refactored output to be json payloads<commit_after>const internalIp = require('internal-ip');
const express = require('express');
const app = express();
const mongoClient = require('mongodb').MongoClient;
const ObjectId = require('mongodb').ObjectId;
const assert = require('assert');
const bodyParser = require('body-parser');

const port = 3001;
const mongoDBPort = 37001;
const ip = internalIp.v4();

// Connection URL
const url = 'mongodb://localhost:' + mongoDBPort + '/random-user-api';

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

app.get('/', (req, res) => {
    res.redirect("/health-check");
});

app.get('/health-check', (req, res) => {
    mongoClient.connect(url, (err, db) => {
      assert.equal(null, err);

      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.json({
          "status": 200,
          "message": "Connected successfully to server!\n"
      });

      db.close();
    });
});

app.route('/add-user')
    .get((req, res, next) => {
        res.sendFile(__dirname + "/views/add-user.html");
    })
    .post((req, res, next) => {
        mongoClient.connect(url, (err, db) => {
            assert.equal(null, err);
            const collection = db.collection('users');
            collection.insertOne({
                "firstName": req.body.firstName,
                "lastName": req.body.lastName,
            }, {
                w: 'majority',
                wtimeout: 10000,
                serializeFunctions: true
            }, (err, result) => {
                assert.equal(err, null);
                assert.equal(1, result.insertedCount);

                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.json({
                    "status": 200,
                    "message": "Successfully added " + req.body.firstName + " " + req.body.lastName + " to database.\n"
                });

                db.close();
            });
        });
    });

app.route('/get-user')
    .get((req, res, next) => {
        res.sendFile(__dirname + "/views/get-user.html");
    })
    .post((req, res, next) => {
        mongoClient.connect(url, (err, db) => {
            assert.equal(null, err);

            const query = {};
            if (req.body.firstName) {
                query.firstName = req.body.firstName;
            }
            if (req.body.lastName) {
                query.lastName = req.body.lastName;
            }
            if (req.body.uid) {
                query._id = ObjectId(req.body.uid);
            }

            const collection = db.collection('users');
            collection.find(query).toArray((err, docs) => {
                assert.equal(err, null);
                assert.notEqual(docs.length, 0);

                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.json({
                    "status": 200,
                    "data": docs
                });

                db.close();
            });
        });
    });

app.route('/delete-user')
    .get((req, res, next) => {
        res.sendFile(__dirname + "/views/delete-user.html");
    })
    .post((req, res, next) => {
        mongoClient.connect(url, (err, db) => {
            assert.equal(null, err);

            const query = {};
            if (req.body.uid) {
                query._id = ObjectId(req.body.uid);
            }

            const collection = db.collection('users');
            assert.equal(query.hasOwnProperty("_id"), true);
            collection.findOneAndDelete(query, (err, result) => {
                assert.equal(err, null);

                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.json({
                    "status": 200,
                    "message": "Removed the document with the uid: " + query._id
                });

                db.close();
            });

        });
    });

app.route('/update-user')
    .get((req, res, next) => {
        res.sendFile(__dirname + "/views/update-user.html");
    })
    .post((req, res, next) => {
        mongoClient.connect(url, (err, db) => {
            assert.equal(null, err);

            const query = {};
            const updates = {};
            if (req.body.uid) {
                query._id = ObjectId(req.body.uid);
            }
            if (req.body.firstName) {
                updates.firstName = req.body.firstName;
            }
            if (req.body.lastName) {
                updates.lastName = req.body.lastName;
            }

            const collection = db.collection('users');
            assert.equal(query.hasOwnProperty("_id"), true);

            collection.findOneAndUpdate(query, { $set: updates }, (err, result) => {
                assert.equal(err, null);

                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.json({
                    "status": 200,
                    "message": "Updated the data for uid: " + query._id
                });

                db.close();
            });

        });
    });

app.listen(port, (err) => {
    if (err) {
        console.log(err);
        return;
    }

    console.log(' --------------------------------------------');
    console.log(' Server now running on the following ports...');
    console.log(' --------------------------------------------');
    console.log(`       Local: http://0.0.0.0:${port}`);
    console.log(`       External: http://${ip}:${port}`);
    console.log(' --------------------------------------------');
});
<|endoftext|>


<commit_before>import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import router from './router';
import socket from 'socket.io';
import http from 'http';
import socketStart from './sockets/init';

const app = express();

// litle hacky for now - but if the Papertrail API exists, then we
// must be on heroku - so set the port differently
if(process.env.PAPERTRAIL_API_TOKEN) {
    const port = 80;
}
else {
    const port = 8081;
}

app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

router(app);
app.listen(port);
console.log('listening on: ' + port);

// Websocket server
const server = require('http').createServer(app);
const io = socket(server);
socketStart(io);
server.listen(3000);
<commit_msg>attempting to fix server port on heroku<commit_after>import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import router from './router';
import socket from 'socket.io';
import http from 'http';
import socketStart from './sockets/init';

const app = express();

// litle hacky for now - but if the Papertrail API exists, then we
// must be on heroku - so set the port differently

const port = 80;

if(process.env.PAPERTRAIL_API_TOKEN) {
    const port = 80;
}
else {
    const port = 8081;
}

app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

router(app);
app.listen(port);
console.log('listening on: ' + port);

// Websocket server
const server = require('http').createServer(app);
const io = socket(server);
socketStart(io);
server.listen(3000);
<|endoftext|>


<commit_before>/*
* SERVER - The Server
*/

'use strict'

// PATH & PATHS - The Path(s): needs to be at the top
var path = require('../libraries/path');
var paths = require('../paths/paths');

/*
* APPLICATIONS - The Applications
*/
//OLD var app = require('../applications/application.js');
var app = require(path.join(paths.applications, '/application.js'));
/*
* ENVIRONMENTS - The Environments
*
* param: app
*/
//OLD var environments = require('../environments/environments.js')(app);
var environments = require(path.join(paths.environments, '/environments.js'))(app);
/*
* ROUTES - The Routes
*
* param: app
*/
//OLD var routes = require('../routes/routes.js')(app);
var routes = require(path.join(paths.routes, '/routes.js'))(app);
/*
* LISTENERS - The Listeners (always put last)
*
* param: app
*/
//OLD var listeners = require('../listeners/listeners.js')(app);
var listeners = require(path.join(paths.listeners, '/listeners.js'))(app);
<commit_msg>Modified<commit_after>/*
* SERVER - The Server
*/

'use strict'

/*
* PATH & PATHS - The Path(s): needs to be at the top
*/
var path = require('../libraries/path');
var paths = require('../paths/paths');

/*
* APPLICATIONS - The Applications
*/
var app = require(path.join(paths.applications, '/application.js'));
/*
* ENVIRONMENTS - The Environments
*
* param: app
*/
var environments = require(path.join(paths.environments, '/environments.js'))(app);
/*
* ROUTES - The Routes
*
* param: app
*/
var routes = require(path.join(paths.routes, '/routes.js'))(app);
/*
* LISTENERS - The Listeners: always put last
*
* param: app
*/
var listeners = require(path.join(paths.listeners, '/listeners.js'))(app);
<|endoftext|>


<commit_before>var express = require('express');
var favicon = require('serve-favicon');
var logger = require('morgan');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

var indexPath = path.join(__dirname, '/public/index.html')
var publicPath = express.static(path.join(__dirname, '/public'))

app.use('/public', publicPath)
app.get('/', function(req, res) {
    res.sendFile(indexPath);
});

module.exports = app;
<commit_msg>fix index link<commit_after>var express = require('express');
var favicon = require('serve-favicon');
var logger = require('morgan');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

var indexPath = path.join(__dirname, '/public/index.html')
var publicPath = express.static(path.join(__dirname, '/'))

app.use('/public', publicPath)
app.get('/', function(req, res) {
    res.sendFile(indexPath);
});

module.exports = app;
<|endoftext|>


<commit_before>var fs = require('fs');
var http = require('http');
var url = require('url');
var querystring = require('querystring');
var child_process = require('child_process');

var host = '0.0.0.0'
var port = process.env.PORT || 8779;

var documentation = fs.readFileSync('Readme.md');

function wkhtmltopdf_command() {
  return 'wkhtmltopdf'
}

exports.server = http.createServer(function (req, res) {
  u = url.parse(req.url);
  if (u.pathname == '/') {
    if (req.method != 'GET') {
      res.writeHead(405, {'Content-Type': 'text/plain'});
      res.end('Only GET method allowed');
      return;
    }
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(documentation);
  } else if (u.pathname == '/pdf') {
    if (req.method != 'POST') {
      res.writeHead(405, {'Content-Type': 'text/plain'});
      res.end('Only POST method allowed');
      return;
    }
    var body = '';
    req.on('data', function(data) { body += data });
    req.on('end', function() {
      var post = querystring.parse(body);
      var html = post.html;
      if (html) {
        var child = child_process.spawn(wkhtmltopdf_command(), ['-', '-']);
        var buffers = [];
        child.stdout.on('data', function(data) { buffers.push(data) });
        child.on('exit', function(code) {
          if (code === 0) {
            var buffer = Buffer.concat(buffers);
            res.writeHead(200, {
              'Content-Type': 'application/pdf',
              //'Content-Length': buffer.length
            });
            res.end(buffer);
          } else {
            console.log('Error while running wkhtmltopdf: Error ' + code);
            res.writeHead(500, {'Content-Type': 'text/plain'});
            res.end('Error while running wkhtmltopdf');
          }
        });
        child.stdin.on('error', function() { });
        child.stdin.end(html);
      } else {
        res.writeHead(400, {'Content-Type': 'text/plain'});
        res.end('Form parameter "html" required');
      }
    });
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Not found');
  }
}).listen(port, host);

console.log('Listening on http://'+host+':'+port);

<commit_msg>Refactoring: separate real request handling from boilerplate.<commit_after>var fs = require('fs');
var http = require('http');
var url = require('url');
var querystring = require('querystring');
var child_process = require('child_process');

var host = '0.0.0.0'
var port = process.env.PORT || 8779;

var wkhtmltopdf = 'wkhtmltopdf' // command to execute
var documentation = fs.readFileSync('Readme.md');

function handleHtmlToPdf(html, res) {
  var child = child_process.spawn(wkhtmltopdf, ['-', '-']);
  var buffers = [];
  child.stdout.on('data', function(data) { buffers.push(data) });
  child.on('exit', function(code) {
    if (code === 0) {
      var buffer = Buffer.concat(buffers);
      res.writeHead(200, {
        'Content-Type': 'application/pdf',
        //'Content-Length': buffer.length
      });
      res.end(buffer);
    } else {
      console.log('Error while running wkhtmltopdf: Error ' + code);
        res.writeHead(500, {'Content-Type': 'text/plain'});
      res.end('Error while running wkhtmltopdf');
    }
  });
  child.stdin.on('error', function() { });
  child.stdin.end(html);
}

exports.server = http.createServer(function (req, res) {
  u = url.parse(req.url);
  if (u.pathname == '/') {
    if (req.method != 'GET') {
      res.writeHead(405, {'Content-Type': 'text/plain'});
      res.end('Only GET method allowed');
      return;
    }
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(documentation);
  } else if (u.pathname == '/pdf') {
    if (req.method != 'POST') {
      res.writeHead(405, {'Content-Type': 'text/plain'});
      res.end('Only POST method allowed');
      return;
    }
    var body = '';
    req.on('data', function(data) { body += data });
    req.on('end', function() {
      var post = querystring.parse(body);
      var html = post.html;
      if (html) {
        handleHtmlToPdf(html, res);
      } else {
        res.writeHead(400, {'Content-Type': 'text/plain'});
        res.end('Form parameter "html" required');
      }
    });
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Not found');
  }
}).listen(port, host);

console.log('Listening on http://'+host+':'+port);

<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const mongoose = require('mongoose');
const app = new express();
const debug = require('debug')('fit-O-matic:server');
const morgan = require('morgan');
const cors = require('cors');
const dotenv = require('dotenv');

dotenv.load();

const errors = require('./lib/error-middleware.js');
const authRouter = require('./routes/auth-route.js');
const bikeGeoRouter = require('./routes/geo-route.js');
const basic = require('./routes/basic-route.js');
const profileRouter = require('./routes/profile-route.js');
const mfrRouter = require('./routes/mfr-route.js');
const bikeRouter = require('./routes/bike-route.js');

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

mongoose.connect(process.env.MONGODB_URI);

app.use(cors());
app.use(morgan('dev'));
app.use(basic);
app.use(authRouter);
app.use(profileRouter);
app.use(bikeGeoRouter);
app.use(mfrRouter);
app.use(bikeRouter);
app.use(errors);
app.listen(PORT, () => debug('server up:', PORT));
<commit_msg>index page with image<commit_after>'use strict';

const express = require('express');
const mongoose = require('mongoose');
const app = new express();
const debug = require('debug')('fit-O-matic:server');
const morgan = require('morgan');
const cors = require('cors');
const dotenv = require('dotenv');

dotenv.load();

const errors = require('./lib/error-middleware.js');
const authRouter = require('./routes/auth-route.js');
const bikeGeoRouter = require('./routes/geo-route.js');
const basic = require('./routes/basic-route.js');
const profileRouter = require('./routes/profile-route.js');
const mfrRouter = require('./routes/mfr-route.js');
const bikeRouter = require('./routes/bike-route.js');

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

mongoose.connect(process.env.MONGODB_URI);

app.use(cors());
app.use(morgan('dev'));
app.use(basic);
app.use(authRouter);
app.use(profileRouter);
app.use(bikeGeoRouter);
app.use(mfrRouter);
app.use(bikeRouter);
app.use(errors);
app.listen(PORT, () => debug('server up on:', PORT));
<|endoftext|>


<commit_before>var http = require('http'),
    async = require('async'),
    request = require('request'),
    cacheInterval = 1000 * 60;

var cache = {};
setInterval(function () { cache = {}; }, cacheInterval);

// ghetto called, they want their template back!
var template =
  "<!DOCTYPE html>" +
  "" +
  "  " +
  "    <meta charset='utf-8' />" +
  "    <title>node.js vs RoR</title>" +
  "    <link rel='stylesheet' href='http://twitter.github.com/bootstrap/1.3.0/bootstrap.min.css'>" +
  "    " +
  "  " +
  "  " +
  "
" +
  "
" +
  "
" +
  "
node.js
" +
  "
%(nodejs)
" +
  "
" +
  "
" +
  "
Ruby on Rails
" +
  "
%(ror)
" +
  "
" +
  "
" +
  "
" +
  "
" +
  "
%(text)
" +
  "
" +
  "
" +
  "
" +
  "
" +
  "
" +
  "        by Maciej Małecki: Twitter, GitHub" +
  "
" +
  "        Source" +
  "
" +
  "
" +
  "  " +
  "";

http.createServer(function (req, res) {
  var ror, nodejs;

  res.writeHead(200, {'Content-Type': 'text/html'});
  if (cache.output) {
    return res.end(cache.output);
  }

  async.parallel({
    ror: function (callback) {
      request(
        'http://github.com/api/v2/json/repos/show/rails/rails',
        function (error, response, body) {
          ror = JSON.parse(body).repository.watchers;
          callback(null, ror);
        }
      );
    },
    nodejs: function (callback) {
      request(
        'http://github.com/api/v2/json/repos/show/joyent/node',
        function (error, response, body) {
          nodejs = JSON.parse(body).repository.watchers;
          callback(null, nodejs);
        }
      );
    }
  }, function (err, watchers) {
    var text = (watchers.ror > watchers.nodejs) ? "Not quite there... yet!" : "Wooooooooo!";
    cache.output = template
                   .replace('%(nodejs)', watchers.nodejs)
                   .replace('%(ror)', watchers.ror)
                   .replace('%(text)', text);
    res.end(cache.output);
  });
}).listen(8000);

console.log('http server running on port 8000');

<commit_msg>[ux] But what's going on?<commit_after>var http = require('http'),
    async = require('async'),
    request = require('request'),
    cacheInterval = 1000 * 60;

var cache = {};
setInterval(function () { cache = {}; }, cacheInterval);

// ghetto called, they want their template back!
var template =
  "<!DOCTYPE html>" +
  "" +
  "  " +
  "    <meta charset='utf-8' />" +
  "    <title>node.js vs RoR</title>" +
  "    <link rel='stylesheet' href='http://twitter.github.com/bootstrap/1.3.0/bootstrap.min.css'>" +
  "    " +
  "  " +
  "  " +
  "
" +
  "
" +
  "
" +
  "
node.js
" +
  "
%(nodejs)
" +
  "
GitHub watchers
" +
  "
" +
  "
" +
  "
Ruby on Rails
" +
  "
%(ror)
" +
  "
GitHub watchers
" +
  "
" +
  "
" +
  "
" +
  "
" +
  "
%(text)
" +
  "
" +
  "
" +
  "
" +
  "
" +
  "
" +
  "        by Maciej Małecki: Twitter, GitHub" +
  "
" +
  "        Source" +
  "
" +
  "
" +
  "  " +
  "";

http.createServer(function (req, res) {
  var ror, nodejs;

  res.writeHead(200, {'Content-Type': 'text/html'});
  if (cache.output) {
    return res.end(cache.output);
  }

  async.parallel({
    ror: function (callback) {
      request(
        'http://github.com/api/v2/json/repos/show/rails/rails',
        function (error, response, body) {
          ror = JSON.parse(body).repository.watchers;
          callback(null, ror);
        }
      );
    },
    nodejs: function (callback) {
      request(
        'http://github.com/api/v2/json/repos/show/joyent/node',
        function (error, response, body) {
          nodejs = JSON.parse(body).repository.watchers;
          callback(null, nodejs);
        }
      );
    }
  }, function (err, watchers) {
    var text = (watchers.ror > watchers.nodejs) ? "Not quite there... yet!" : "Wooooooooo!";
    cache.output = template
                   .replace('%(nodejs)', watchers.nodejs)
                   .replace('%(ror)', watchers.ror)
                   .replace('%(text)', text);
    res.end(cache.output);
  });
}).listen(8000);

console.log('http server running on port 8000');

<|endoftext|>


<commit_before>var http = require('http');
var rangeParser = require('range-parser');
var mime = require('mime');
var partFile = require('part-file');
var Readable = require('readable-stream');
var piece = require('./piece');

var MIN_BUFFER = 1.5 * 1000 * 1000;

var pipeline = function(inp, out) {
	inp.pipe(out);
	out.on('close', function() {
		inp.destroy();
	});
};

module.exports = function(torrent, file, destination) {
	var piecesToBuffer = Math.max(Math.ceil(MIN_BUFFER / torrent.pieceLength), 3);

	var PieceStream = function(range) {
		Readable.call(this);
		range = range || {start:0, end:file.length-1};
		this.position = ((range.start + file.offset) / torrent.pieceLength) | 0;
		this.remaining = range.end - range.start + 1;
		this.skip = (range.start + file.offset) % torrent.pieceLength;
		this.destroyed = false;
		this._buffer = this.position + Math.min(piecesToBuffer, (this.remaining / torrent.pieceLength) | 0);
		this._onreadable = null;
	};

	PieceStream.prototype.__proto__ = Readable.prototype;

	PieceStream.prototype._read = function() {
		if (!this.remaining) return this.push(null);

		var self = this;
		var onread = function(err, data) {
			if (err) return self.emit('error', err);
			if (self.skip) data = data.slice(self.skip);
			if (data.length > self.remaining) data = data.slice(0, self.remaining);
			self.skip = 0;
			self.remaining -= data.length;
			if (!self.destroyed) self.push(data);
		};

		if (!this.buffering()) return dest.read(this.position++ - start, onread);

		this._onreadable = function(index) {
			if (self.buffering()) return;
			dest.removeListener('readable', self._onreadable);
			dest.read(self.position++ - start, onread);
		};

		dest.on('readable', this._onreadable);
	};

	PieceStream.prototype.buffering = function() {
		for (var i = this.position; i < this._buffer; i++) {
			if (!dest.readable(i - start)) return true;
		}
		return !dest.readable(this.position - start);
	};

	PieceStream.prototype.destroy = function() {
		this.destroyed = true;
		if (this._onreadable) dest.removeListener('readable', this._onreadable);
		this.emit('close');
	};

	var missing = [];

	var start = (file.offset / torrent.pieceLength) | 0;
	var end = ((file.offset + file.length + 1) / torrent.pieceLength) | 0;
	var dest = partFile(destination, torrent.pieceLength, torrent.pieces.slice(start, end+1));

	var prioritize = function(i) {
		missing.sort(function(a, b) {
			if (a >= i && b < i) return -1;
			if (b >= i && a < i) return 1;
			return a - b;
		});
	};

	var stream = function(range) {
		var s = new PieceStream(range);
		prioritize(s.position);
		return s;
	};

	var lastFile = torrent.files[torrent.files.length-1];
	var pieces = torrent.pieces.map(function(_, i) {
		if (i < start) return;
		if (i > end) return;

		missing.push(i);

		if (i === torrent.pieces.length-1) return piece(((lastFile.length + lastFile.offset) % torrent.pieceLength) || torrent.pieceLength);
		return piece(torrent.pieceLength);
	});

	var server = http.createServer(function(request, response) {
		var range = request.headers.range;

		request.connection.setTimeout(0);
		response.setHeader('Accept-Ranges', 'bytes');
		response.setHeader('Content-Type', mime.lookup(file.name));

		range = range && rangeParser(file.length, range)[0];

		if (!range) {
			response.setHeader('Content-Length', file.length);
			if (request.method === 'HEAD') return response.end();
			pipeline(stream(), response);
			return;
		}

		response.statusCode = 206;
		response.setHeader('Content-Length', range.end - range.start + 1);
		response.setHeader('Content-Range', 'bytes '+range.start+'-'+range.end+'/'+file.length);

		if (request.method === 'HEAD') return response.end();
		pipeline(stream(range), response);
	});

	dest.on('readable', function(index) {
		index += start;
		var i = missing.indexOf(index);
		pieces[index] = null;
		if (i > -1) missing.splice(i, 1);
		server.emit('readable', index);
	});

	prioritize(0);

	server.missing = missing;
	server.filename = file.name;
	server.destination = destination;

	server.sizeof = function(index, offset) {
		var p = pieces[index];
		return p ? p.sizeof(offset) : 0;
	};

	server.select = function(index) {
		var p = pieces[index];
		return p ? p.select() : -1;
	};

	server.deselect = function(index, offset) {
		var p = pieces[index];
		if (p) p.deselect(offset);
	};

	server.write = function(index, offset, block) {
		var p = pieces[index];
		if (!p) return;

		var buffer = p.write(offset, block);
		if (!buffer) return;

		dest.write(index - start, buffer, function(err) {
			if (err) return p.reset();
		});
	};

	server.read = function(index, offset, length, callback) {
		dest.read(index - start, function(err, buffer) {
			if (err) return callback(err);
			callback(null, buffer.slice(offset, offset+length));
		});
	};

	return server;
};
<commit_msg>min buffer is 1.5 mb<commit_after>var http = require('http');
var rangeParser = require('range-parser');
var mime = require('mime');
var partFile = require('part-file');
var Readable = require('readable-stream');
var piece = require('./piece');

var MIN_BUFFER = 1.5 * 1000 * 1000;

var pipeline = function(inp, out) {
	inp.pipe(out);
	out.on('close', function() {
		inp.destroy();
	});
};

module.exports = function(torrent, file, destination) {
	var piecesToBuffer = Math.max(Math.ceil(MIN_BUFFER / torrent.pieceLength), 1);

	var PieceStream = function(range) {
		Readable.call(this);
		range = range || {start:0, end:file.length-1};
		this.position = ((range.start + file.offset) / torrent.pieceLength) | 0;
		this.remaining = range.end - range.start + 1;
		this.skip = (range.start + file.offset) % torrent.pieceLength;
		this.destroyed = false;
		this._buffer = this.position + Math.min(piecesToBuffer, (this.remaining / torrent.pieceLength) | 0);
		this._onreadable = null;
	};

	PieceStream.prototype.__proto__ = Readable.prototype;

	PieceStream.prototype._read = function() {
		if (!this.remaining) return this.push(null);

		var self = this;
		var onread = function(err, data) {
			if (err) return self.emit('error', err);
			if (self.skip) data = data.slice(self.skip);
			if (data.length > self.remaining) data = data.slice(0, self.remaining);
			self.skip = 0;
			self.remaining -= data.length;
			if (!self.destroyed) self.push(data);
		};

		if (!this.buffering()) return dest.read(this.position++ - start, onread);

		this._onreadable = function(index) {
			if (self.buffering()) return;
			dest.removeListener('readable', self._onreadable);
			dest.read(self.position++ - start, onread);
		};

		dest.on('readable', this._onreadable);
	};

	PieceStream.prototype.buffering = function() {
		for (var i = this.position; i < this._buffer; i++) {
			if (!dest.readable(i - start)) return true;
		}
		return !dest.readable(this.position - start);
	};

	PieceStream.prototype.destroy = function() {
		this.destroyed = true;
		if (this._onreadable) dest.removeListener('readable', this._onreadable);
		this.emit('close');
	};

	var missing = [];

	var start = (file.offset / torrent.pieceLength) | 0;
	var end = ((file.offset + file.length + 1) / torrent.pieceLength) | 0;
	var dest = partFile(destination, torrent.pieceLength, torrent.pieces.slice(start, end+1));

	var prioritize = function(i) {
		missing.sort(function(a, b) {
			if (a >= i && b < i) return -1;
			if (b >= i && a < i) return 1;
			return a - b;
		});
	};

	var stream = function(range) {
		var s = new PieceStream(range);
		prioritize(s.position);
		return s;
	};

	var lastFile = torrent.files[torrent.files.length-1];
	var pieces = torrent.pieces.map(function(_, i) {
		if (i < start) return;
		if (i > end) return;

		missing.push(i);

		if (i === torrent.pieces.length-1) return piece(((lastFile.length + lastFile.offset) % torrent.pieceLength) || torrent.pieceLength);
		return piece(torrent.pieceLength);
	});

	var server = http.createServer(function(request, response) {
		var range = request.headers.range;

		request.connection.setTimeout(0);
		response.setHeader('Accept-Ranges', 'bytes');
		response.setHeader('Content-Type', mime.lookup(file.name));

		range = range && rangeParser(file.length, range)[0];

		if (!range) {
			response.setHeader('Content-Length', file.length);
			if (request.method === 'HEAD') return response.end();
			pipeline(stream(), response);
			return;
		}

		response.statusCode = 206;
		response.setHeader('Content-Length', range.end - range.start + 1);
		response.setHeader('Content-Range', 'bytes '+range.start+'-'+range.end+'/'+file.length);

		if (request.method === 'HEAD') return response.end();
		pipeline(stream(range), response);
	});

	dest.on('readable', function(index) {
		index += start;
		var i = missing.indexOf(index);
		pieces[index] = null;
		if (i > -1) missing.splice(i, 1);
		server.emit('readable', index);
	});

	prioritize(0);

	server.missing = missing;
	server.filename = file.name;
	server.destination = destination;

	server.sizeof = function(index, offset) {
		var p = pieces[index];
		return p ? p.sizeof(offset) : 0;
	};

	server.select = function(index) {
		var p = pieces[index];
		return p ? p.select() : -1;
	};

	server.deselect = function(index, offset) {
		var p = pieces[index];
		if (p) p.deselect(offset);
	};

	server.write = function(index, offset, block) {
		var p = pieces[index];
		if (!p) return;

		var buffer = p.write(offset, block);
		if (!buffer) return;

		dest.write(index - start, buffer, function(err) {
			if (err) return p.reset();
		});
	};

	server.read = function(index, offset, length, callback) {
		dest.read(index - start, function(err, buffer) {
			if (err) return callback(err);
			callback(null, buffer.slice(offset, offset+length));
		});
	};

	return server;
};
<|endoftext|>


<commit_before>#!/bin/env node

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var fs      = require('fs');
var mongodb = require('mongodb');

var apiApp = function () {

    var self = this;

    self.getConf = function () {

        console.log("mongo");
        // 1. KONFIGURAATIO

        // default to a 'localhost' configuration:
        var connection_string = '127.0.0.1:27017/barbababa';
        // if OPENSHIFT env variables are present, use the available connection info:
        if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD){
          connection_string = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
          process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" +
          process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
          process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
          process.env.OPENSHIFT_APP_NAME;
        }
    return connection_string;
    };

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

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

    router.get("/", function (req, res) {
        res.json({
            "error": false,
            "message": "Hello World"
        });
    });

    //Routing example
    router.route("/test").get(function (req, res) {
        var response = {
            "text": "hello world!"
        };
        res.json(response);
    });
    router.route("/bars").get(function(req, res){
        var connection_string = self.getConf();
        var MongoClient = require('mongodb').MongoClient;
        // the client db connection scope is wrapped in a callback:
        MongoClient.connect('mongodb://' + connection_string, function (err, db) {
            if (err) throw err;
            var collection = db.collection('bars').find().limit(100).toArray(function (err, docs) {
                console.dir(docs);
                res.send(docs);
                db.close();
            });
        });
    });

    router.route("/saveBar").post(function(req, res){
        var connection_string = self.getConf();
        var MongoClient = require('mongodb').MongoClient;
        // the client db connection scope is wrapped in a callback:
        MongoClient.connect('mongodb://' + connection_string, function (err, db) {
            var name = req.body.name;
            var address = req.body.address;
            var postCode = req.body.postCode;
            var city = req.body.city;
            var lat = parseFloat(req.body.lat);
            var lon = parseFloat(req.body.lon);
            self.db.collection('bars').insertOne(
                {   'name':name,
                    'address':address,
                    'postCode':postCode,
                    'city': city,
                    'location':[lon,lat]},
                    function(err, records){
                        if (err) { throw err; }
                res.send('success');
            });
            db.close();
        });
    });

    app.use('/', router);

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function () {
        //  Start the app on the specific interface (and port).
        var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
        var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
        app.listen(port, ipaddress, function () {
            console.log((new Date()) + ' Server is listening on port 8080');
        });
    };
};

var zapp = new apiApp();
zapp.start();<commit_msg>webform update<commit_after>#!/bin/env node

var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var router = express.Router();
var fs      = require('fs');
var mongodb = require('mongodb');
var assert = require('assert');

var apiApp = function () {

    var self = this;

    self.getConf = function () {

        console.log("mongo");
        // 1. KONFIGURAATIO

        // default to a 'localhost' configuration:
        var connection_string = '127.0.0.1:27017/barbababa';
        // if OPENSHIFT env variables are present, use the available connection info:
        if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD){
          connection_string = process.env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
          process.env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" +
          process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
          process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
          process.env.OPENSHIFT_APP_NAME;
        }
    return connection_string;
    };

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

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

    router.get("/", function (req, res) {
        res.json({
            "error": false,
            "message": "Hello World"
        });
    });

    //Routing example
    router.route("/test").get(function (req, res) {
        var response = {
            "text": "hello world!"
        };
        res.json(response);
    });
    router.route("/bars").get(function(req, res){
        var connection_string = self.getConf();
        var MongoClient = require('mongodb').MongoClient;
        // the client db connection scope is wrapped in a callback:
        MongoClient.connect('mongodb://' + connection_string, function (err, db) {
            if (err) throw err;
            var collection = db.collection('bars').find().limit(100).toArray(function (err, docs) {
                console.dir(docs);
                res.send(docs);
                db.close();
            });
        });
    });

    router.route("/saveBar").post(function(req, res){
        var name = req.body.name;
        var address = req.body.address;
        var postCode = req.body.postCode;
        var city = req.body.city;
        var lat = parseFloat(req.body.lat);
        var lon = parseFloat(req.body.lon);
        var connection_string = self.getConf();
        var MongoClient = require('mongodb').MongoClient;
        // the client db connection scope is wrapped in a callback:
        MongoClient.connect('mongodb://' + connection_string, function (err, db) {
            self.db.collection('bars').insertOne(
                {
                    'name':name,
                    'address':address,
                    'postCode':postCode,
                    'city': city,
                    'location':[lon,lat]
                },
                function(err, result) {
                    assert.equal(err, null);
                    console.log("Inserted a document into the bars collection.");
                    db.close();
                });
        });
    });

    app.use('/', router);

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function () {
        //  Start the app on the specific interface (and port).
        var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
        var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
        app.listen(port, ipaddress, function () {
            console.log((new Date()) + ' Server is listening on port 8080');
        });
    };
};

var zapp = new apiApp();
zapp.start();<|endoftext|>


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

var port = process.argv[ 2 ] || 8020;
var cwd = process.cwd();

var root = path.join( cwd, "/public/" );

var contentTypes = {
    ".html": "text/html",
    ".css": "text/css",
    ".svg": "image/svg+xml"
};

function getFile( uri ){
    var file = uri;

    if( !file || file == "/" ){
        file = "index.html";
    }

    return file;
}

function getContentType( p ){
    var content = contentTypes[ path.extname( p ) ];

    if( content ){
        content = { "Content-Type": content };
    }

    return content;
}

function serveFile( p, response ){
    fs.readFile(
        p,
        "binary",
        ( err, file ) => {
            if( err ){
                response.writeHead( 500, { "Content-Type": "text/plain" } );
                response.write( err + "\n" );
                response.end();
            }
            else{
                let content = getContentType( p ) || "binary";

                /* eslint no-console: "off", no-debugger: "off", vars-on-top: "off", "no-unused-vars": "off" */
                console.log( `<== .${p}` );

                response.writeHead( 200 );
                response.write( file, content );
                response.end();
            }
        }
    );
}

function handleRequest( p, response, request ){
    fs.access( p, ( error ) => {
        if( error ){
            p = path.join( root, "/index.html" );

            serveFile( p, response );
        }
        else{
            serveFile( p, response );
        }
    } );
}

function notFound( p, response ){
    response.writeHead( 404 );
    response.end();
}

function serve( request, response ){
    var uri = url.parse( request.url ).pathname;
    var file = getFile( uri );
    var filename = path.join( root, file );

    console.log( `==> ${uri}` );
    handleRequest( filename, response, request );
}

console.log( "Creating a server..." );

http
    .createServer( serve )
    .listen( parseInt( port, 10 ) );

console.log( `Listening on :${port}` );
<commit_msg>Add compression to the server<commit_after>var http = require( "http" );
var zlib = require( "zlib" );
var url = require( "url" );
var path = require( "path" );
var fs = require( "fs" );

var port = process.argv[ 2 ] || 8020;
var cwd = process.cwd();

var root = path.join( cwd, "/public/" );

var contentTypes = {
    ".html": "text/html",
    ".css": "text/css",
    ".js": "application/javascript",
    ".svg": "image/svg+xml"
};

function getFile( uri ){
    var file = uri;

    if( !file || file == "/" ){
        file = "index.html";
    }

    return file;
}

function getContentType( p ){
    return contentTypes[ path.extname( p ) ];
}

function canCompress( request ){
    var accept = request.headers[ "accept-encoding" ] || "";

    return accept.match( /\b(?:gzip|deflate)\b/ );
}

function compression( request ){
    var enc = request.headers[ "accept-encoding" ] || "";
    var alg = false;

    if( /\bdeflate\b/.test( enc ) ){
        alg = "deflate";
    }
    else if( /\bgzip\b/.test( enc ) ){
        alg = "gzip";
    }

    return alg;
}

function serveFile( p, response, request ){
    fs.readFile(
        p,
        "utf8",
        ( err, file ) => {
            let shouldCompress = canCompress( request );
            let code = 200;
            let headers = {};
            let content = "";

            function finishStream( error, compressedResultBuffer, raw ){
                if( !error && !raw  ){
                    headers[ "Content-Encoding" ] = compression( request );
                    raw = compressedResultBuffer;
                }

                if( error ){
                    headers[ "Content-Type" ] = "text/plain";
                    raw = "compression error";
                }

                headers[ "Content-Length" ] = Buffer.byteLength( raw );

                response.writeHead( code, headers );
                response.end( raw, "utf8" );

                if( code == 200 ){
                    /* eslint no-console: "off", no-debugger: "off", vars-on-top: "off", "no-unused-vars": "off" */
                    console.log( `<== .${p}` );
                }
            }

            if( err ){
                headers[ "Content-Type" ] = "text/plain";
                code = 500;
                content = err + "\n";
            }
            else{
                headers[ "Content-Type" ] = getContentType( p );
                code = 200;
                content = file;
            }

            headers[ "Content-Type" ] += "; charset=utf-8";

            switch( compression( request ) ){
                case "gzip":
                    zlib.gzip( content, finishStream );
                    break;

                case "deflate":
                    zlib.deflate( content, finishStream );
                    break;

                default:
                    finishStream( null, null, content );
            }
        }
    );
}

function handleRequest( p, response, request ){
    fs.access( p, ( error ) => {
        if( error ){
            p = path.join( root, "/index.html" );
        }

        serveFile( p, response, request );
    } );
}

function notFound( p, response ){
    response.writeHead( 404 );
    response.end();
}

function serve( request, response ){
    var uri = url.parse( request.url ).pathname;
    var file = getFile( uri );
    var filename = path.join( root, file );

    console.log( `==> ${uri}` );
    handleRequest( filename, response, request );
}

console.log( "Creating a server..." );

http
    .createServer( serve )
    .listen( parseInt( port, 10 ) );

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


<commit_before>#!/bin/env node
//  OpenShift sample Node application
var http = require('http');

//Get the environment variables we need.
var ipaddr  = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port    = process.env.OPENSHIFT_NODEJS_PORT || 8080;

http.createServer(function (req, res) {
	var addr = "unknown";
	var out = "";
	if (req.headers.hasOwnProperty('x-forwarded-for')) {
		addr = req.headers['x-forwarded-for'];
	} else if (req.headers.hasOwnProperty('remote-addr')){
		addr = req.headers['remote-addr'];
	}

	if (req.headers.hasOwnProperty('accept')) {
		if (req.headers['accept'].toLowerCase() == "application/json") {
			  res.writeHead(200, {'Content-Type': 'application/json'});
			  res.end(JSON.stringify({'ip': addr}, null, 4) + "\n");
			  return ;
		}
	}

  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write("Welcome to Node.js on OpenShift!\n\n");
  res.end("Your IP address seems to be " + addr + "\n");
}).listen(port, ipaddr);
console.log("Server running at http://" + ipaddr + ":" + port + "/");
<commit_msg>test changes<commit_after>#!/bin/env node
//  OpenShift sample Node application
var http = require('http');
var express = require('express');

//Get the environment variables we need.
var ipaddr  = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
var port    = process.env.OPENSHIFT_NODEJS_PORT || 8080;

http.createServer(function (req, res) {
	var addr = "unknown";
	var out = "";
	if (req.headers.hasOwnProperty('x-forwarded-for')) {
		addr = req.headers['x-forwarded-for'];
	} else if (req.headers.hasOwnProperty('remote-addr')){
		addr = req.headers['remote-addr'];
	}

	if (req.headers.hasOwnProperty('accept')) {
		if (req.headers['accept'].toLowerCase() == "application/json") {
			  res.writeHead(200, {'Content-Type': 'application/json'});
			  res.end(JSON.stringify({'ip': addr}, null, 4) + "\n");
			  return ;
		}
	}

  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write("Welcome to Node.js on OpenShift!\n\n");
  res.end("Your IP address seems to be " + addr + "\n");
}).listen(port, ipaddr);
console.log("Server running at http://" + ipaddr + ":" + port + "/");
<|endoftext|>


<commit_before>//This is the main entrypoint for starting up our server.
//If loaded as the main module, will start the server and start fetching
//comments from wordpress.  See bottom of file for the startup code

//Tested on node v6.10.2

//Run this in an anonymous function to avoid accidentally creating global variables
(function() {

//Dependencies
var pg = require('pg');
var fs = require('fs');
var fibers = require('fibers');
var block = require('./block');
var Block = block.Block;
var request = require('request');
var querystring = require('querystring');
var express = require('express');
var url = require('url')

//How soon we kick off the loading-new-comments process after the last one finishes
var LOAD_COMMENTS_EVERY = 10*1000;
//How long we wait before retrying the loading-new-comments process if it fails
var FAIL_RETRY = 5*60*1000;
//The number of pages of results we load before committing the transaction
var MAX_PAGES = 10;

//cache our loaded configuration
var _config_cache;

//Track how caught up we are
var latestTimestamp = null;
//If we hit an error fetching comments, save it
var lastError = null;

//Loads our configuration from config.json.  This is a git-ignored file
//that we use to store credentials + settings that we don't want to check
//into git
function get_config() {
    //If we haven't yet, load it from disk
    if (!_config_cache) {
        try {
            _config_cache = JSON.parse(fs.readFileSync('config.json', 'utf8'));
        } catch (err) {
            //If we can't load config, we have to shutdown
            console.log('Unable to load and parse config.json.  Error was:');
            console.log(err.stack);
            process.exit(1);
        }
    }
    return _config_cache;
}

//store our pool of postgres clients
var _pool_cache;

//Returns our pool of postgres clients
function get_pool() {
    //If we haven't created a pool yet, create it now
    if (!_pool_cache) {
        var postgres = get_config().postgres;
        if (!postgres) {
            //If we don't have settings for postgres, this is a fatal error
            var msg = 'No "postgres" object found in config.json.  Expecting an object';
            msg += ' with some or all of these fields: "user", "database", "password",';
            msg += ' "host", "port", "max", "idleTimeoutMillis".  See new pg.Pool at ';
            msg += 'https://github.com/brianc/node-postgres';
            console.log(msg);

            process.exit(1);
        }
        _pool_cache = new pg.Pool(postgres);
    }
    return _pool_cache;
}

//Runs a function passing in a postgres client with a sync query function, which we release on completion
function withClient(fn) {
    var client = block.await(get_pool().connect())
    try {
        var c = {
            query: function (sql, params) {
                return block.await(client.query(sql, params));
            }
        }
        return fn(c);
    } finally {
        client.release();
    }
}

//Runs a function passing in a postgres client.  Starts a transaction, and automatically
//rolls back on error or commits on success
function transaction(fn) {
    withClient(function(client) {
        try {
            client.query('BEGIN');
            ret = fn(client);
            client.query('COMMIT');
            return ret;
        } catch (err) {
            client.query('ROLLBACK');
            throw err;
        }
    });
}

//Fetches all the comments that have come in since we last fetched,
//and persists them to the database as a single transaction.
function fetchComments() {
    //Track the latest timestamp for this operation.  On commit, we update the global
    //latestTimestamp variable
    var lt = null;

    //We run this entire operation as a transaction to protect against accidentally
    //having two comment-fetching processes running at once
    transaction(function(client) {
        //Acquire a lock so that only one process does this at a time
        client.query('SELECT pg_advisory_xact_lock(352342)');

        //Find our most recent comment, so we can get comments after that one
        var res = client.query('SELECT timestamp FROM public.comments ORDER BY timestamp DESC LIMIT 1');
        var start;
        if (res.rows[0]) {
             start = parseInt(res.rows[0].timestamp);
        } else {
            //Start from the beginning of time (plus a bit because Wordpress errors if start = 0)
            start = 86400000;
        }

        //We maintain a cache of comment ids to author names, because comments will
        //generally be in reply to recently posted comments, so it makes sense to remember
        //so we don't have to constantly query the database
        var ids_to_author_name = {}

        //Given a comment id, looks up the author name
        function getAuthorName(id) {
            //If we have it already, just return it
            if (ids_to_author_name[id]) {
                return ids_to_author_name[id];
            }

            //Otherwise, look it up from the database
            res = client.query("SELECT data->'author_name'::text as author_name FROM public.comments WHERE id = $1", [id])
            if (!res.rows[0] || !res.rows[0].author_name) { return null; }
            ids_to_author_name[id] = res.rows[0].author_name;
            return ids_to_author_name[id];
        }

        //Start from the first page of results, and go until there are no more results
        //or we are at MAX_PAGES
        var page = 1;
        while (page <= MAX_PAGES) {

            //Build the parameters to make the call to the wordpress API
            var url = get_config().api_base + '/wp-json/wp/v2/comments?'
            var params = {
                page: page,
                per_page: 100,
                after: (new Date(start)).toISOString(),
                order: 'asc'
            }
            url = url + querystring.stringify(params);

            //Temporary debugging:
            //console.log('Fetching ' + url);

            //Do the request and error if it's not a 200 response
            var block = Block();
            request(url, block.make_cb());
            response = block.wait();
            if (response.statusCode !== 200) {
                throw new Error('Non-200 response from ' + url + ': ' + response.statusCode + ' ' + response.body)
            }

            var comments = JSON.parse(response.body);

            //If there are no comments, we're at the end of the pagination, so break out of the while loop
            if (comments.length === 0) { break; }

            //Go through each comment, calculate the timestamp and in_reply_to fields,
            //and persist to the database
            var comment, timestamp, in_reply_to, params;
            for (var i = 0; i < comments.length; i++) {
                comment = comments[i];

                //update our ids_to_author_name hash
                ids_to_author_name[comment.id] = comment.author_name;

                timestamp = (new Date(comment.date_gmt)).valueOf();
                if (timestamp < lt) {
                    throw new Error('assertion error: got out-of-order timestamps');
                }
                lt = timestamp

                in_reply_to = []

                //See if there any explicit @ references
                //Currently, we count anything from an @ to a non-alphanumeric, non-space
                //character as the author name.  (This is because usually they'll be a
                //comma or a <p> at the end of the name).
                //We trim whitespace
                var regex = /@([a-zA-Z0-9\. ]+)/g
                while (match = regex.exec(comment.content.rendered)) {
                    in_reply_to.push(match[1].trim());

                    //TODO: can we compare unrecognized author names against our comment
                    //database and see if we can guess who they were referring to?
                }

                //See if there is a parent post
                if (comment.parent && getAuthorName(comment.parent)) {
                    in_reply_to.push(getAuthorName(comment.parent));
                }

                //Write the comment to postgres
                params = [comment.id, comment, timestamp, in_reply_to]
                client.query("INSERT INTO public.comments (id, data, timestamp, in_reply_to) VALUES ($1,$2,$3,$4)", params)

                //Temporary debugging
                //console.log('Added: ' + JSON.stringify(params, null, 4));
            }

            page++;
        }
    });

    //We've successfully committed, so update the latest timestamp,
    //and clear last error
    latestTimestamp = lt;
    lastError = null;

    //Temporary debugging
    //console.log('Successfully committed');
}

//Express route that displays the status of the comment downloading
function statusEndpoint (req, res, next) {
    try {
        var msg = 'Status: ';
        if (lastError) {
            msg += 'unhealthy\n\nLast error:\n' + lastError.stack
        } else if (latestTimestamp) {
            msg += 'healthy'
        } else {
            msg += 'starting up'
        }
        if (latestTimestamp) {
            msg += '\n\n\nCaught up to: ' + String(new Date(latestTimestamp))
        }
        res.end(msg);

    } catch (err) {
        console.log(err);
        next(err);
    }
}

//Express route that returns a JSON list of replies
function replies(req, res, next) {
    //Run this on a synchronous coroutine to enable waiting
    block.run(function() {
        try {
            //Parse the querystring.  We support author_name, from, page
            var params, author_name, from, page, page_size;
            params = url.parse(req.url, true).query;
            author_name = params.author_name;
            from = parseInt(params.from);
            if (params.page) {
                page = parseInt(params.page);
            } else {
                page = 1;
            }
            if (params.page_size) {
                page_size = parseInt(params.page_size);
            } else {
                page_size = 10;
            }

            //Sends a 400 message to the client
            function return400 (msg) {
                res.statusCode = 400;
                res.end(msg);
            }

            //Validate the parameters
            if (!author_name) {
                return return400('Missing "author_name" parameter in querystring');
            }
            if (Number.isNaN(from)) {
                return return400('Invalid or missing "from" paramater: should be a unix timestamp in miliseconds');
            }
            if (Number.isNaN(page) || page < 1) {
                return return400('Invalid "page" parameter: should be an integer >= 1');
            }
            if (Number.isNaN(page_size) || page_size < 1 || page_size > 100) {
                return return400('Invalid "page_size" parameter: should be an integer between 1 and 100');
            }

            //Get a postgres client and do a search for comments that match these parameters
            var rows = withClient(function(client) {
                var limit, offset;
                //Currently we return at most 100 replies per call
                limit = page_size;
                offset = limit * (page - 1);

                sql = "SELECT data FROM public.comments WHERE in_reply_to @> ARRAY[$1] AND timestamp > $2 ORDER BY timestamp LIMIT $3 OFFSET $4";

                return client.query(sql, [author_name, from, limit, offset]).rows;
            });

            //Build the results to return to the client
            var results = [];
            for (var i = 0; i < rows.length; i++) {
                results.push(rows[i].data);
            }

            //And send them
            res.end(JSON.stringify(results));

        } catch (err) {
            //On error, log it, then return to the client
            console.log('Error handling ' + req.url + ':');
            console.log(err.stack);
            next(err);
        }
    });
}

//Starts up our API server
function startServer() {
    var app = express();

    //install the replies endpoint
    app.get('/replies', replies);

    //install the status endpoint
    app.get('/', statusEndpoint);

    port = get_config().port;
    app.listen(port, function(err) {
        if (err) {
            console.log('Unable to listen on port ' + port + ': ');
            console.log(err);
            process.exit(1);
        }
        console.log('Listening on port ' + port);
    });
}

//Reads in the latest comments from the WordPress api, processes them,
//and then persists them to our postgres database
function getLatestComments() {
    //Kick off a synchronous coroutine
    block.run(function() {
        try {
            fetchComments();

            //We successfully completed, so do this again in 30 seconds
            setTimeout(getLatestComments, LOAD_COMMENTS_EVERY);
        }
        catch (err) {
            //Record the latest failure for monitoring purposes
            lastError = err;

            //Try again in 5 minutes
            console.log('error fetching comments:');
            console.log(err.stack);
            setTimeout(getLatestComments, FAIL_RETRY);
        }
    });
}

//If this file is the entry point, start up our server and begin
//fetching comments
if (require.main === module) {
    //Confirm we've configured an api base url
    if (!get_config().api_base) {
        console.log('Please set "api_base" in config.json.  E.g., http://slatestarcodex.com');
        process.exit(1);
    }
    //Confirm we've configured a port to listen on
    if (!get_config().port) {
        console.log('Please set "port" in config.json. E.g., 80.');
        process.exit(1);
    }

    startServer();
    getLatestComments();

    //if we have an uncaught exception, we want to log it (but not immediately exit)
    process.on('uncaughtException', function (err) {
        console.log('uncaught exception:');
        console.log(err.stack);
    });
}

})()<commit_msg>if caught up, display caught up, not starting up<commit_after>//This is the main entrypoint for starting up our server.
//If loaded as the main module, will start the server and start fetching
//comments from wordpress.  See bottom of file for the startup code

//Tested on node v6.10.2

//Run this in an anonymous function to avoid accidentally creating global variables
(function() {

//Dependencies
var pg = require('pg');
var fs = require('fs');
var fibers = require('fibers');
var block = require('./block');
var Block = block.Block;
var request = require('request');
var querystring = require('querystring');
var express = require('express');
var url = require('url')

//How soon we kick off the loading-new-comments process after the last one finishes
var LOAD_COMMENTS_EVERY = 10*1000;
//How long we wait before retrying the loading-new-comments process if it fails
var FAIL_RETRY = 5*60*1000;
//The number of pages of results we load before committing the transaction
var MAX_PAGES = 10;

//cache our loaded configuration
var _config_cache;

//Track how caught up we are
var latestTimestamp = null;
//If we hit an error fetching comments, save it
var lastError = null;

//Loads our configuration from config.json.  This is a git-ignored file
//that we use to store credentials + settings that we don't want to check
//into git
function get_config() {
    //If we haven't yet, load it from disk
    if (!_config_cache) {
        try {
            _config_cache = JSON.parse(fs.readFileSync('config.json', 'utf8'));
        } catch (err) {
            //If we can't load config, we have to shutdown
            console.log('Unable to load and parse config.json.  Error was:');
            console.log(err.stack);
            process.exit(1);
        }
    }
    return _config_cache;
}

//store our pool of postgres clients
var _pool_cache;

//Returns our pool of postgres clients
function get_pool() {
    //If we haven't created a pool yet, create it now
    if (!_pool_cache) {
        var postgres = get_config().postgres;
        if (!postgres) {
            //If we don't have settings for postgres, this is a fatal error
            var msg = 'No "postgres" object found in config.json.  Expecting an object';
            msg += ' with some or all of these fields: "user", "database", "password",';
            msg += ' "host", "port", "max", "idleTimeoutMillis".  See new pg.Pool at ';
            msg += 'https://github.com/brianc/node-postgres';
            console.log(msg);

            process.exit(1);
        }
        _pool_cache = new pg.Pool(postgres);
    }
    return _pool_cache;
}

//Runs a function passing in a postgres client with a sync query function, which we release on completion
function withClient(fn) {
    var client = block.await(get_pool().connect())
    try {
        var c = {
            query: function (sql, params) {
                return block.await(client.query(sql, params));
            }
        }
        return fn(c);
    } finally {
        client.release();
    }
}

//Runs a function passing in a postgres client.  Starts a transaction, and automatically
//rolls back on error or commits on success
function transaction(fn) {
    withClient(function(client) {
        try {
            client.query('BEGIN');
            ret = fn(client);
            client.query('COMMIT');
            return ret;
        } catch (err) {
            client.query('ROLLBACK');
            throw err;
        }
    });
}

//Fetches all the comments that have come in since we last fetched,
//and persists them to the database as a single transaction.
function fetchComments() {
    //Track the latest timestamp for this operation.  On commit, we update the global
    //latestTimestamp variable
    var lt = null;

    //We run this entire operation as a transaction to protect against accidentally
    //having two comment-fetching processes running at once
    transaction(function(client) {
        //Acquire a lock so that only one process does this at a time
        client.query('SELECT pg_advisory_xact_lock(352342)');

        //Find our most recent comment, so we can get comments after that one
        var res = client.query('SELECT timestamp FROM public.comments ORDER BY timestamp DESC LIMIT 1');
        var start;
        if (res.rows[0]) {
             start = parseInt(res.rows[0].timestamp);
        } else {
            //Start from the beginning of time (plus a bit because Wordpress errors if start = 0)
            start = 86400000;
        }

        //We maintain a cache of comment ids to author names, because comments will
        //generally be in reply to recently posted comments, so it makes sense to remember
        //so we don't have to constantly query the database
        var ids_to_author_name = {}

        //Given a comment id, looks up the author name
        function getAuthorName(id) {
            //If we have it already, just return it
            if (ids_to_author_name[id]) {
                return ids_to_author_name[id];
            }

            //Otherwise, look it up from the database
            res = client.query("SELECT data->'author_name'::text as author_name FROM public.comments WHERE id = $1", [id])
            if (!res.rows[0] || !res.rows[0].author_name) { return null; }
            ids_to_author_name[id] = res.rows[0].author_name;
            return ids_to_author_name[id];
        }

        //Start from the first page of results, and go until there are no more results
        //or we are at MAX_PAGES
        var page = 1;
        while (page <= MAX_PAGES) {

            //Build the parameters to make the call to the wordpress API
            var url = get_config().api_base + '/wp-json/wp/v2/comments?'
            var params = {
                page: page,
                per_page: 100,
                after: (new Date(start)).toISOString(),
                order: 'asc'
            }
            url = url + querystring.stringify(params);

            //Temporary debugging:
            //console.log('Fetching ' + url);

            //Do the request and error if it's not a 200 response
            var block = Block();
            request(url, block.make_cb());
            response = block.wait();
            if (response.statusCode !== 200) {
                throw new Error('Non-200 response from ' + url + ': ' + response.statusCode + ' ' + response.body)
            }

            var comments = JSON.parse(response.body);

            //If there are no comments, we're at the end of the pagination, so break out of the while loop
            if (comments.length === 0) { break; }

            //Go through each comment, calculate the timestamp and in_reply_to fields,
            //and persist to the database
            var comment, timestamp, in_reply_to, params;
            for (var i = 0; i < comments.length; i++) {
                comment = comments[i];

                //update our ids_to_author_name hash
                ids_to_author_name[comment.id] = comment.author_name;

                timestamp = (new Date(comment.date_gmt)).valueOf();
                if (timestamp < lt) {
                    throw new Error('assertion error: got out-of-order timestamps');
                }
                lt = timestamp

                in_reply_to = []

                //See if there any explicit @ references
                //Currently, we count anything from an @ to a non-alphanumeric, non-space
                //character as the author name.  (This is because usually they'll be a
                //comma or a <p> at the end of the name).
                //We trim whitespace
                var regex = /@([a-zA-Z0-9\. ]+)/g
                while (match = regex.exec(comment.content.rendered)) {
                    in_reply_to.push(match[1].trim());

                    //TODO: can we compare unrecognized author names against our comment
                    //database and see if we can guess who they were referring to?
                }

                //See if there is a parent post
                if (comment.parent && getAuthorName(comment.parent)) {
                    in_reply_to.push(getAuthorName(comment.parent));
                }

                //Write the comment to postgres
                params = [comment.id, comment, timestamp, in_reply_to]
                client.query("INSERT INTO public.comments (id, data, timestamp, in_reply_to) VALUES ($1,$2,$3,$4)", params)

                //Temporary debugging
                //console.log('Added: ' + JSON.stringify(params, null, 4));
            }

            page++;
        }
    });

    //We've successfully committed, so update the latest timestamp,
    //and clear last error
    if (lt === null) {
        latestTimestamp = 'up-to-date';
    } else {
        latestTimestamp = lt;
    }
    lastError = null;

    //Temporary debugging
    //console.log('Successfully committed');
}

//Express route that displays the status of the comment downloading
function statusEndpoint (req, res, next) {
    try {
        var msg = 'Status: ';
        if (lastError) {
            msg += 'unhealthy\n\nLast error:\n' + lastError.stack
        } else if (latestTimestamp) {
            msg += 'healthy'
        } else {
            msg += 'starting up'
        }
        if (latestTimestamp === 'up-to-date') {
            msg += '\n\n\nCaught up to the present time'
        } else if (latestTimestamp) {
            msg += '\n\n\nCaught up to: ' + String(new Date(latestTimestamp))
        }
        res.end(msg);

    } catch (err) {
        console.log(err);
        next(err);
    }
}

//Express route that returns a JSON list of replies
function replies(req, res, next) {
    //Run this on a synchronous coroutine to enable waiting
    block.run(function() {
        try {
            //Parse the querystring.  We support author_name, from, page
            var params, author_name, from, page, page_size;
            params = url.parse(req.url, true).query;
            author_name = params.author_name;
            from = parseInt(params.from);
            if (params.page) {
                page = parseInt(params.page);
            } else {
                page = 1;
            }
            if (params.page_size) {
                page_size = parseInt(params.page_size);
            } else {
                page_size = 10;
            }

            //Sends a 400 message to the client
            function return400 (msg) {
                res.statusCode = 400;
                res.end(msg);
            }

            //Validate the parameters
            if (!author_name) {
                return return400('Missing "author_name" parameter in querystring');
            }
            if (Number.isNaN(from)) {
                return return400('Invalid or missing "from" paramater: should be a unix timestamp in miliseconds');
            }
            if (Number.isNaN(page) || page < 1) {
                return return400('Invalid "page" parameter: should be an integer >= 1');
            }
            if (Number.isNaN(page_size) || page_size < 1 || page_size > 100) {
                return return400('Invalid "page_size" parameter: should be an integer between 1 and 100');
            }

            //Get a postgres client and do a search for comments that match these parameters
            var rows = withClient(function(client) {
                var limit, offset;
                //Currently we return at most 100 replies per call
                limit = page_size;
                offset = limit * (page - 1);

                sql = "SELECT data FROM public.comments WHERE in_reply_to @> ARRAY[$1] AND timestamp > $2 ORDER BY timestamp LIMIT $3 OFFSET $4";

                return client.query(sql, [author_name, from, limit, offset]).rows;
            });

            //Build the results to return to the client
            var results = [];
            for (var i = 0; i < rows.length; i++) {
                results.push(rows[i].data);
            }

            //And send them
            res.end(JSON.stringify(results));

        } catch (err) {
            //On error, log it, then return to the client
            console.log('Error handling ' + req.url + ':');
            console.log(err.stack);
            next(err);
        }
    });
}

//Starts up our API server
function startServer() {
    var app = express();

    //install the replies endpoint
    app.get('/replies', replies);

    //install the status endpoint
    app.get('/', statusEndpoint);

    port = get_config().port;
    app.listen(port, function(err) {
        if (err) {
            console.log('Unable to listen on port ' + port + ': ');
            console.log(err);
            process.exit(1);
        }
        console.log('Listening on port ' + port);
    });
}

//Reads in the latest comments from the WordPress api, processes them,
//and then persists them to our postgres database
function getLatestComments() {
    //Kick off a synchronous coroutine
    block.run(function() {
        try {
            fetchComments();

            //We successfully completed, so do this again in 30 seconds
            setTimeout(getLatestComments, LOAD_COMMENTS_EVERY);
        }
        catch (err) {
            //Record the latest failure for monitoring purposes
            lastError = err;

            //Try again in 5 minutes
            console.log('error fetching comments:');
            console.log(err.stack);
            setTimeout(getLatestComments, FAIL_RETRY);
        }
    });
}

//If this file is the entry point, start up our server and begin
//fetching comments
if (require.main === module) {
    //Confirm we've configured an api base url
    if (!get_config().api_base) {
        console.log('Please set "api_base" in config.json.  E.g., http://slatestarcodex.com');
        process.exit(1);
    }
    //Confirm we've configured a port to listen on
    if (!get_config().port) {
        console.log('Please set "port" in config.json. E.g., 80.');
        process.exit(1);
    }

    startServer();
    getLatestComments();

    //if we have an uncaught exception, we want to log it (but not immediately exit)
    process.on('uncaughtException', function (err) {
        console.log('uncaught exception:');
        console.log(err.stack);
    });
}

})()<|endoftext|>


<commit_before>const express = require('express');
const app = express();
const bodyParser = require('body-parser');

// apps
const crossword = require('./src/crosswords/execution');

app.set('port', process.env.PORT || 5000);
app.use(express.static(`${__dirname}/dist`));

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// views is directory for all template files
// app.set('views', `${__dirname}/views`);
// app.set('view engine', 'ejs');
/*
app.get('/dist', (request, response) => response.render(`${__dirname}dist/index`));
app.get('/', (request, response) => response.render(`${__dirname}src/index`));
*/

// ROUTES FOR OUR API
// =============================================================================
// get an instance of the express Router
var router = express.Router();
// middleware to use for all requests
router.use(function (req, res, next) {
    // do logging
    console.log('Something is happening!', new Date().toJSON());
    // console.log('params:', req.params);
    // console.log('body:', req.body);
    // validations, authorization checks, or conditional serving could also go here
    //console.log('grid:', req.params.grid || 'no grid');

    // make sure we go to the next routes and don't stop here
    next();
});

// test route to make sure everything is working (accessed at GET http://localhost:5000/api)
router.get('/', function (req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

// more routes for our API will happen here
// get a random crossword puzzle
router.route('/random')
    // define the get verb
    .get(function (req, res) {
        crossword.getCrossword()
            .then(crossword => {
                if (crossword === null) {
                    res.json({ grid: 'No solution found for random' });
                }
                else {
                    res.json(crossword);
                }
            })
            .catch(error => {
                console.log(error);
                res.send(error);
            });
    });

// get a crossword puzzle for a specific grid structure
router.route('/full/:grid')
    // define the get verb
    .get(function (req, res) {
        console.log('grid parsed', JSON.parse(req.params.grid));
        crossword.getCrossword(JSON.parse(req.params.grid))
            .then(crossword => {
                if (crossword === null) {
                    res.json({ grid: 'No solution found for ' + req.params.grid });
                }
                else {
                    res.json(crossword);
                }
                //console.log('response', res);
            })
            .catch(error => {
                console.log('error', error);
                res.send(error);
            });
    });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/apicw', router);

app.listen(app.get('port'), () => console.log('Node app is running on port', app.get('port'), 'and path is', __dirname));
<commit_msg>Convert js object to json.<commit_after>const express = require('express');
const app = express();
const bodyParser = require('body-parser');

// apps
const crossword = require('./src/crosswords/execution');

app.set('port', process.env.PORT || 5000);
app.use(express.static(`${__dirname}/dist`));

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// views is directory for all template files
// app.set('views', `${__dirname}/views`);
// app.set('view engine', 'ejs');
/*
app.get('/dist', (request, response) => response.render(`${__dirname}dist/index`));
app.get('/', (request, response) => response.render(`${__dirname}src/index`));
*/

// ROUTES FOR OUR API
// =============================================================================
// get an instance of the express Router
var router = express.Router();
// middleware to use for all requests
router.use(function (req, res, next) {
    // do logging
    console.log('\nSomething is happening!', new Date().toJSON());
    // console.log('params:', req.params);
    // console.log('body:', req.body);
    // validations, authorization checks, or conditional serving could also go here
    //console.log('grid:', req.params.grid || 'no grid');

    // make sure we go to the next routes and don't stop here
    next();
});

// test route to make sure everything is working (accessed at GET http://localhost:5000/api)
router.get('/', function (req, res) {
    res.json({ message: 'hooray! welcome to our api!' });
});

// more routes for our API will happen here
// get a random crossword puzzle
router.route('/random')
    // define the get verb
    .get(function (req, res) {
        console.log('Random crossword requested');
        crossword.getCrossword()
            .then(crossword => {
                if (crossword === null) {
                    res.json({ grid: 'No solution found for random' });
                }
                else {
                    //console.log('cr random', crossword);
                    res.json(JSON.stringify(crossword));
                }
            })
            .catch(error => {
                console.log('error:', error);
                res.send(error);
            });
    });

// get a crossword puzzle for a specific grid structure
router.route('/full/:grid')
    // define the get verb
    .get(function (req, res) {
        console.log('Full crossord requested. Structure:', JSON.parse(req.params.grid));
        crossword.getCrossword(JSON.parse(req.params.grid))
            .then(crossword => {
                if (crossword === null) {
                    res.json({ grid: 'No solution found for ' + req.params.grid });
                }
                else {
                    //console.log('cr full', crossword);
                    res.json(JSON.stringify(crossword));
                }
                //console.log('response', res);
            })
            .catch(error => {
                console.log('error', error);
                res.send(error);
            });
    });

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/apicw', router);

app.listen(app.get('port'), () => console.log('Node app is running on port', app.get('port'), 'and path is', __dirname));
<|endoftext|>