<commit_before>'use strict';

const Hapi = require('hapi');

const server = new Hapi.Server();
server.connection({ port: 3000 });

server.route({
  method: 'GET',
  path: '/{name}',
  handler: function (request, reply) {
    reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
  }
});

server.route({
  method: ['PUT', 'POST'],
  path: '/maprequest',
  handler: function (request, reply) {
    var lat, lng, name, pic;
    console.log("payload: " + request.payload);
    var payload = request.payload;
    console.log(typeof request.payload);

    // The format of the payload is: { '14 : 34 : jos : female_3.png': '' } BUT...

    // From the phone, it comes in as an object (not locally, but only from App Inventor calls)
    if (typeof payload === 'object') {
      lat = Object.keys(payload)[0].split(' : ')[0];
      lng = Object.keys(payload)[0].split(' : ')[1];
      name = Object.keys(payload)[0].split(' : ')[2];
      pic = Object.keys(payload)[0].split(' : ')[3];
    }

    // Cannot reproduce the object encoding locally so creating an additional parser
    if (typeof payload === 'string'){
      payload = payload.split("'")[1];
      lat = payload.split(' : ')[0];
      lng = payload.split(' : ')[1];
      name = payload.split(' : ')[2];
      pic = payload.split(' : ')[3];
    }

    //TODO (jos) Push to DB

    console.log(lat + ' '  + lng + ' ' + name + ' ' + pic);
    reply('Done');
  }
});

server.register(require('inert'), (err) => {

  if (err) {
    throw err;
  }

  server.route({
    method: 'GET',
    path: '/{param*}',
    handler: {
      directory: {
        path: 'public',
        index: true
      }
    }
  });
});

server.start((err) => {

  if (err) {
    throw err;
  }
  console.log('Server running at:', server.info.uri);
});
<commit_msg>hooking the db code into the server<commit_after>'use strict';

const Hapi = require('hapi');
const r = require('rethinkdb');
const db = require('./db_calls');

const server = new Hapi.Server();
server.connection({ port: 3000 });

server.route({
  method: 'GET',
  path: '/{name}',
  handler: function (request, reply) {
    reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
  }
});

server.route({
  method: ['PUT', 'POST'],
  path: '/maprequest',
  handler: function (request, reply) {
    var lat, lng, name, pic;
    console.log("payload: " + request.payload);
    var payload = request.payload;
    console.log(typeof request.payload);

    // The format of the payload is: { '14 : 34 : jos : female_3.png': '' } BUT...

    // From the phone, it comes in as an object (not locally, but only from App Inventor calls)
    if (typeof payload === 'object') {
      lat = Object.keys(payload)[0].split(' : ')[0];
      lng = Object.keys(payload)[0].split(' : ')[1];
      name = Object.keys(payload)[0].split(' : ')[2];
      pic = Object.keys(payload)[0].split(' : ')[3];
    }

    // Cannot reproduce the object encoding locally so creating an additional parser
    if (typeof payload === 'string'){
      payload = payload.split("'")[1];
      lat = payload.split(' : ')[0];
      lng = payload.split(' : ')[1];
      name = payload.split(' : ')[2];
      pic = payload.split(' : ')[3];
    }

    var currentMarker = {
      lat: lat,
      lng: lng,
      name: name,
      pic: pic
    };
    db.storeInDB(currentMarker, function(err, result){
      if (err) return console.log(err); //TODO (jos) Do something with this
      console.log(result); //TODO (jos) probably all to be done with the result.
    });
    reply('Done');
  }
});

server.register(require('inert'), (err) => {

  if (err) {
    throw err;
  }

  server.route({
    method: 'GET',
    path: '/{param*}',
    handler: {
      directory: {
        path: 'public',
        index: true
      }
    }
  });
});

var connection = null;
server.start((err) => {

  if (err) {
    throw err;
  }

  //TODO (jos) make host an ENV variable
  r.connect( {host: '192.168.99.100', port: 28015}, function(err, conn) {
    if (err) throw err;
    connection = conn;
    db.setConnection(connection);
    console.log('Server running at:', server.info.uri);
  })
});
<|endoftext|>


<commit_before>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');
var bodyParser  = require('body-parser');

var mongo = require('mongodb');
var monk = require('monk');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;
        self.dbhost      = process.env.OPENSHIFT_MONGODB_DB_HOST || self.ipaddress;
        self.dbport      = process.env.OPENSHIFT_MONGODB_DB_PORT || 27017;
        self.dbname      = process.env.OPENSHIFT_MONGODB_DB_NAME || 'mailflowjs';
    };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.app = express();
self.app.use(bodyParser.urlencoded({ extended: true }));
self.app.use(bodyParser.json());

        self.db = monk(self.dbhost + ':' + self.dbport + '/'+ self.dbname);

self.app.use(function(req,res,next){
    req.db = self.db;
    next();
});
	    self.app.get("/", function(req, res) {
		res.json({ messages: '//messages/' });
	    });

	    self.app.post("/events/", function(req, res) {
                var events = req.body.mandrill_events || [];
                console.log(events);
                var newMessage;
                var event;
                var collection = req.db.get('messages');
                for (var i in events) {
                    event = events[i];
                    newMessage = {
                        received: new Date(),
                        fromEmail: event.msg.from_email,
                        fromName: event.msg.from_name,
                        toEmail: event.msg.email,
                        body: event.msg.text,
                        subject: event.msg.subject
                   };
                   console.log(newMessage);
                   collection.insert(newMessage);
                }
		res.send(204);
	    });

	    self.app.get("/events/", function(req, res) {
		res.send(204);
	    });

	    self.app.get("/messages/", function(req, res) {
		    var collection = req.db.get('messages');
		    collection.find({},{},function(e,docs){
                        docs = docs || [];
 		        res.json(docs);
		    });
	    });
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();

zapp.initialize();
zapp.start();

<commit_msg>format is actually: an object with a mandrill_events slot whose value is the freaking array of events<commit_after>#!/bin/env node
//  OpenShift sample Node application
var express = require('express');
var fs      = require('fs');
var bodyParser  = require('body-parser');

var mongo = require('mongodb');
var monk = require('monk');

/**
 *  Define the sample application.
 */
var SampleApp = function() {

    //  Scope.
    var self = this;

    /*  ================================================================  */
    /*  Helper functions.                                                 */
    /*  ================================================================  */

    /**
     *  Set up server IP address and port # using env variables/defaults.
     */
    self.setupVariables = function() {
        //  Set the environment variables we need.
        self.ipaddress = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1";
        self.port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;
        self.dbhost      = process.env.OPENSHIFT_MONGODB_DB_HOST || self.ipaddress;
        self.dbport      = process.env.OPENSHIFT_MONGODB_DB_PORT || 27017;
        self.dbname      = process.env.OPENSHIFT_MONGODB_DB_NAME || 'mailflowjs';
    };

    /**
     *  terminator === the termination handler
     *  Terminate server on receipt of the specified signal.
     *  @param {string} sig  Signal to terminate on.
     */
    self.terminator = function(sig){
        if (typeof sig === "string") {
           console.log('%s: Received %s - terminating sample app ...',
                       Date(Date.now()), sig);
           process.exit(1);
        }
        console.log('%s: Node server stopped.', Date(Date.now()) );
    };

    /**
     *  Setup termination handlers (for exit and a list of signals).
     */
    self.setupTerminationHandlers = function(){
        //  Process on exit and signals.
        process.on('exit', function() { self.terminator(); });

        // Removed 'SIGPIPE' from the list - bugz 852598.
        ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT',
         'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGTERM'
        ].forEach(function(element, index, array) {
            process.on(element, function() { self.terminator(element); });
        });
    };

    /**
     *  Initialize the server (express) and create the routes and register
     *  the handlers.
     */
    self.initializeServer = function() {
        self.app = express();
self.app.use(bodyParser.urlencoded({ extended: true }));
self.app.use(bodyParser.json());

        self.db = monk(self.dbhost + ':' + self.dbport + '/'+ self.dbname);

self.app.use(function(req,res,next){
    req.db = self.db;
    next();
});
	    self.app.get("/", function(req, res) {
		res.json({ messages: '//messages/' });
	    });

	    self.app.post("/events/", function(req, res) {
                var events = req.body.mandrill_events || [];
                console.log(typeof events);
                if (typeof events === "string") {
                    events = JSON.parse(events);
                }
                console.log(events);
                var newMessage;
                var event;
                var collection = req.db.get('messages');
                for (var i in events) {
                    event = events[i];
                    newMessage = {
                        received: new Date(),
                        fromEmail: event.msg.from_email,
                        fromName: event.msg.from_name,
                        toEmail: event.msg.email,
                        body: event.msg.text,
                        subject: event.msg.subject
                   };
                   console.log(newMessage);
                   collection.insert(newMessage);
                }
		res.send(204);
	    });

	    self.app.get("/events/", function(req, res) {
		res.send(204);
	    });

	    self.app.get("/messages/", function(req, res) {
		    var collection = req.db.get('messages');
		    collection.find({},{},function(e,docs){
                        docs = docs || [];
 		        res.json(docs);
		    });
	    });
    };

    /**
     *  Initializes the sample application.
     */
    self.initialize = function() {
        self.setupVariables();
        self.setupTerminationHandlers();

        // Create the express server and routes.
        self.initializeServer();
    };

    /**
     *  Start the server (starts up the sample application).
     */
    self.start = function() {
        //  Start the app on the specific interface (and port).
        self.app.listen(self.port, self.ipaddress, function() {
            console.log('%s: Node server started on %s:%d ...',
                        Date(Date.now() ), self.ipaddress, self.port);
        });
    };

};   /*  Sample Application.  */

/**
 *  main():  Main code.
 */
var zapp = new SampleApp();

zapp.initialize();
zapp.start();

<|endoftext|>


<commit_before>var DEFAULTFILESPATH = __dirname + '/public/files/'
var DEFAULTDOWNLOADPATH = __dirname + '/public/downloads/'
var DEFAULTTORRENTPATH = __dirname + '/torrents.txt'
var DEFAULTLOGPATH = __dirname + '/log.txt'

// file management
var fs = require('fs')
fs.writeFile(DEFAULTLOGPATH, '', 'utf-8', function(err) {
  if (err) log(err)
})

// Child process
var cp = require('child_process')

// Setup basic express server
var auth = require('http-auth')
var basic = auth.basic({
  realm: 'Protected area. Please disperse !',
  file: __dirname + '/.htpasswd'
})

// setup http server
var express = require('express')
var app = express()
var compression = require('compression')
app.use(compression())
var http = require('http')
http.globalAgent.maxSockets = Infinity
var server = http.createServer(basic, app)
var port = process.env.PORT || 80
server.listen(port, function() {
  log('Server listening at port ' + port)
})

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

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

// Torrent memory tab
var TorrentUrlToChild = {}
var TorrentHashToChild = {}
var TorrentUrlToHash = {}
var TorrentWaitList = []

// Auto start torrent in file
fs.writeFile(DEFAULTTORRENTPATH, '', 'utf-8', function(err) {
  if (err) throw err
})
setInterval(startPointTorrent, 30000)

// Search Api
var CPBAPI = require('cpasbien-api')
var CpasbienApi = new CPBAPI()

app.get('/files/', function(req, res) {
  var filename = DEFAULTFILESPATH + req.query.f
  fs.stat(filename, function(err, stats) {
    if (stats) {
      res.setHeader('Content-disposition', 'attachment; filename="' + req.query.f + '"')
      res.setHeader('Content-Length', stats.size)
      res.setHeader('Content-type', 'application/octet-stream')
      var fReadStream = fs.createReadStream(filename)
      fReadStream.pipe(res)
    } else {
      res.end("Le fichier n'existe pas")
    }
  })
})

io.on('connection', function(socket) {
  socket.on('ready', function() {
    for (var key in TorrentHashToChild) {
      TorrentHashToChild[key].send({
        'type': 'info'
      })
    }

    socket.on('download-t', function(url) {
      startTorrent(url)
    })
  })

  socket.on('list-d', function(dir) {
    fs.readdir(DEFAULTFILESPATH + dir, function(err, files) {
      if (err) return log(err)
      var list = {}
      var totalSize = 0
      if (files.length > 0) {
        files.forEach(function(file) {
          var stats = fs.statSync(DEFAULTFILESPATH + dir + file)
          if (stats.isFile()) {
            list[file] = stats
          } else {
            stats.size = sizeRecursif(DEFAULTFILESPATH + dir + file)
            list[file] = stats
          }
          list[file].isfile = stats.isFile()
          list[file].isdir = stats.isDirectory()

          totalSize += stats.size

          if (Object.keys(list).length === files.length) {
            socket.emit('list-d', {
              'totalSize': totalSize,
              'files': list
            })
          }
        })
      } else {
        socket.emit('list-d', {})
      }
    })
  })

  socket.on('remove-t', function(hash) {
    log('Remove torrent: ' + hash)
    TorrentHashToChild[hash].send({
      'type': 'remove'
    })
    socket.emit('finish-t', hash)
  })

  socket.on('remove-d', function(file) {
    log('Remove file: ' + file)
    fs.stat(DEFAULTFILESPATH + file, function(err, stats) {
      if (err) return log(err)
      if (stats.isDirectory()) {
        removeRecursif(DEFAULTFILESPATH + file)
        socket.emit('update-d')
      } else {
        fs.unlink(DEFAULTFILESPATH + file, function(err) {
          if (err) return log(err)
          socket.emit('update-d')
        })
      }
    })
  })

  socket.on('rename-d', function(data) {
    log('Rename: ' + data.oldname + ' In: ' + data.newname)
    fs.rename(DEFAULTFILESPATH + data.path + '/' + data.oldname, DEFAULTFILESPATH + data.path + '/' + data.newname, function(err) {
      if (err) return log(err)
      socket.emit('update-d')
    })
  })

  socket.on('mkdir', function(data) {
    log('Mkdir: ' + data.path + '/' + data.name)
    fs.mkdir(DEFAULTFILESPATH + data.path + '/' + data.name, function() {
      socket.emit('update-d')
    })
  })

  socket.on('mv', function(data) {
    fs.rename(DEFAULTFILESPATH + data.path + data.file, DEFAULTFILESPATH + data.path + data.folder + '/' + data.file, function(err) {
      if (err) return log(err)
      socket.emit('update-d')
    })
  })

  socket.on('search-t', function(query) {
    log('Search: ' + query)
    CpasbienApi.Search(query, {
      scope: 'tvshow',
      language: 'FR'
    }).then(function(data) {
      socket.emit('search-t', {
        'type': 'series',
        'data': data
      })
    })
    CpasbienApi.Search(query, {
      scope: 'tvshow',
      language: 'EN'
    }).then(function(data) {
      socket.emit('search-t', {
        'type': 'series',
        'data': data
      })
    })
    CpasbienApi.Search(query).then(function(data) {
      socket.emit('search-t', {
        'type': 'films',
        'data': data
      })
    })
  })

  socket.on('last-t', function() {
    CpasbienApi.Latest({
      scope: 'tvshow'
    }).then(function(data) {
      data.items = data.items.slice(0, 10)
      socket.emit('search-t', {
        'type': 'series',
        'data': data
      })
    })
    CpasbienApi.Latest().then(function(data) {
      data.items = data.items.slice(0, 10)
      socket.emit('search-t', {
        'type': 'films',
        'data': data
      })
    })
  })
})

function getDate() {
  var date = new Date()
  return date.getDate() + '/' + (date.getMonth() + 1) + ' ' + (date.getHours() + 1) + ':' + (date.getMinutes() + 1) + ':' + (date.getSeconds() + 1)
}

function log(text) {
  console.log(text)
  fs.appendFile(DEFAULTLOGPATH, '[' + getDate() + '] ' + text + '\n', 'utf8', function(err) {
    if (err) throw err
  })
}

function startTorrent(url) {
  log('Trying to download: ' + url)

  // evite de lancer deux fois le meme torrent
  if (TorrentUrlToChild[url] == null) {
    // Si trop de torrent en cours
    if (Object.keys(TorrentUrlToChild).length < 3) {
      var n = cp.fork(__dirname + '/tclient.js')
      TorrentUrlToChild[url] = n
      io.sockets.emit('start-t')
      n.on('message', function(data) {
        switch (data.type) {
          case 'finish':
            io.sockets.emit('finish-t', data.hash)
            n.kill('SIGHUP')
            delete TorrentUrlToChild[url]
            delete TorrentUrlToHash[url]
            delete TorrentHashToChild[data.hash]
            fs.renameSync(DEFAULTDOWNLOADPATH + data.name, DEFAULTFILESPATH + data.name)
              // Relance un torrent si il y en a en attente
            if (TorrentWaitList.length > 0) {
              var newUrl = TorrentWaitList[0]
              startTorrent(newUrl)
              TorrentWaitList.shift()
            }
            break
          case 'info':
            io.sockets.emit('list-t', data.torrent)
            TorrentHashToChild[data.torrent.hash] = n
            TorrentUrlToHash[url] = data.torrent.hash
            break
          case 'remove':
            io.sockets.emit('finish-t', data.hash)
            n.kill('SIGHUP')
            delete TorrentUrlToChild[url]
            delete TorrentUrlToHash[url]
            delete TorrentHashToChild[data.hash]
            fs.unlinkSync(DEFAULTDOWNLOADPATH + data.name)
              // Relance un torrent si il y en a en attente
            if (TorrentWaitList.length > 0) {
              startTorrent(TorrentWaitList[0])
              TorrentWaitList.shift()
            }
        }
      })

      n.on('exit', function(code, signal) {
        if (signal !== 'SIGHUP') {
          log('Child: ' + url + ' \n exit with code: ' + code)
          io.sockets.emit('error-t', TorrentUrlToHash[url])
          delete TorrentUrlToChild[url]
          delete TorrentHashToChild[TorrentUrlToHash[url]]
          delete TorrentUrlToHash[url]
          startTorrent(url)
        }
      })
      n.send({
        'type': 'download',
        'torrent': url
      })

    } else {
      log('Too much client. Adding torrent to the waitlist.')
        // On push dans la liste d'attente
      if (TorrentWaitList.indexOf(url) === -1) {
        TorrentWaitList.push(url)
      }
    }
  } else {
    log('Torrent is already downloading.')
  }
}

function removeRecursif(path) {
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(function(file, index) {
      var curPath = path + '/' + file
      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        removeRecursif(curPath)
      } else { // delete file
        fs.unlinkSync(curPath)
      }
    })
    fs.rmdirSync(path)
  }
}

function sizeRecursif(path) {
  var size = 0
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(function(file, index) {
      var curPath = path + '/' + file
      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        size += sizeRecursif(curPath)
      } else { // read size
        size += fs.statSync(curPath).size
      }
    })
    return size
  }
}

function startPointTorrent() {
  log('Scan for new torrent.')
  fs.readFile(DEFAULTTORRENTPATH, 'utf-8', function(err, data) {
    if (err) return log(err)
    var torrents = data.split('\n')
    fs.writeFile(DEFAULTTORRENTPATH, '', 'utf-8', function(err) {
      if (err) return log(err)
      torrents.forEach(function(element) {
        if (element !== '') {
          startTorrent(element)
        }
      })
    })
  })
}
<commit_msg>Log download with the http-auth user<commit_after>var DEFAULTFILESPATH = __dirname + '/public/files/'
var DEFAULTDOWNLOADPATH = __dirname + '/public/downloads/'
var DEFAULTTORRENTPATH = __dirname + '/torrents.txt'
var DEFAULTLOGPATH = __dirname + '/log.txt'

// file management
var fs = require('fs')
fs.writeFile(DEFAULTLOGPATH, '', 'utf-8', function(err) {
  if (err) log(err)
})

// Child process
var cp = require('child_process')

// Setup basic express server
var auth = require('http-auth')
var basic = auth.basic({
  realm: 'Protected area. Please disperse !',
  file: __dirname + '/.htpasswd'
})

// setup http server
var express = require('express')
var app = express()
var compression = require('compression')
app.use(compression())
var http = require('http')
http.globalAgent.maxSockets = Infinity
var server = http.createServer(basic, app)
var port = process.env.PORT || 80
server.listen(port, function() {
  log('Server listening at port ' + port)
})

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

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

// Torrent memory tab
var TorrentUrlToChild = {}
var TorrentHashToChild = {}
var TorrentUrlToHash = {}
var TorrentWaitList = []

// Auto start torrent in file
fs.writeFile(DEFAULTTORRENTPATH, '', 'utf-8', function(err) {
  if (err) throw err
})
setInterval(startPointTorrent, 30000)

// Search Api
var CPBAPI = require('cpasbien-api')
var CpasbienApi = new CPBAPI()

app.get('/files/', function(req, res) {
  var filename = DEFAULTFILESPATH + req.query.f
  log(req.user+" download: "+req.query.f)
  fs.stat(filename, function(err, stats) {
    if (stats) {
      res.setHeader('Content-disposition', 'attachment; filename="' + req.query.f + '"')
      res.setHeader('Content-Length', stats.size)
      res.setHeader('Content-type', 'application/octet-stream')
      var fReadStream = fs.createReadStream(filename)
      fReadStream.pipe(res)
    } else {
      res.end("Le fichier n'existe pas")
    }
  })
})

io.on('connection', function(socket) {
  socket.on('ready', function() {
    for (var key in TorrentHashToChild) {
      TorrentHashToChild[key].send({
        'type': 'info'
      })
    }

    socket.on('download-t', function(url) {
      startTorrent(url)
    })
  })

  socket.on('list-d', function(dir) {
    fs.readdir(DEFAULTFILESPATH + dir, function(err, files) {
      if (err) return log(err)
      var list = {}
      var totalSize = 0
      if (files.length > 0) {
        files.forEach(function(file) {
          var stats = fs.statSync(DEFAULTFILESPATH + dir + file)
          if (stats.isFile()) {
            list[file] = stats
          } else {
            stats.size = sizeRecursif(DEFAULTFILESPATH + dir + file)
            list[file] = stats
          }
          list[file].isfile = stats.isFile()
          list[file].isdir = stats.isDirectory()

          totalSize += stats.size

          if (Object.keys(list).length === files.length) {
            socket.emit('list-d', {
              'totalSize': totalSize,
              'files': list
            })
          }
        })
      } else {
        socket.emit('list-d', {})
      }
    })
  })

  socket.on('remove-t', function(hash) {
    log('Remove torrent: ' + hash)
    TorrentHashToChild[hash].send({
      'type': 'remove'
    })
    socket.emit('finish-t', hash)
  })

  socket.on('remove-d', function(file) {
    log('Remove file: ' + file)
    fs.stat(DEFAULTFILESPATH + file, function(err, stats) {
      if (err) return log(err)
      if (stats.isDirectory()) {
        removeRecursif(DEFAULTFILESPATH + file)
        socket.emit('update-d')
      } else {
        fs.unlink(DEFAULTFILESPATH + file, function(err) {
          if (err) return log(err)
          socket.emit('update-d')
        })
      }
    })
  })

  socket.on('rename-d', function(data) {
    log('Rename: ' + data.oldname + ' In: ' + data.newname)
    fs.rename(DEFAULTFILESPATH + data.path + '/' + data.oldname, DEFAULTFILESPATH + data.path + '/' + data.newname, function(err) {
      if (err) return log(err)
      socket.emit('update-d')
    })
  })

  socket.on('mkdir', function(data) {
    log('Mkdir: ' + data.path + '/' + data.name)
    fs.mkdir(DEFAULTFILESPATH + data.path + '/' + data.name, function() {
      socket.emit('update-d')
    })
  })

  socket.on('mv', function(data) {
    fs.rename(DEFAULTFILESPATH + data.path + data.file, DEFAULTFILESPATH + data.path + data.folder + '/' + data.file, function(err) {
      if (err) return log(err)
      socket.emit('update-d')
    })
  })

  socket.on('search-t', function(query) {
    log('Search: ' + query)
    CpasbienApi.Search(query, {
      scope: 'tvshow',
      language: 'FR'
    }).then(function(data) {
      socket.emit('search-t', {
        'type': 'series',
        'data': data
      })
    })
    CpasbienApi.Search(query, {
      scope: 'tvshow',
      language: 'EN'
    }).then(function(data) {
      socket.emit('search-t', {
        'type': 'series',
        'data': data
      })
    })
    CpasbienApi.Search(query).then(function(data) {
      socket.emit('search-t', {
        'type': 'films',
        'data': data
      })
    })
  })

  socket.on('last-t', function() {
    CpasbienApi.Latest({
      scope: 'tvshow'
    }).then(function(data) {
      data.items = data.items.slice(0, 10)
      socket.emit('search-t', {
        'type': 'series',
        'data': data
      })
    })
    CpasbienApi.Latest().then(function(data) {
      data.items = data.items.slice(0, 10)
      socket.emit('search-t', {
        'type': 'films',
        'data': data
      })
    })
  })
})

function getDate() {
  var date = new Date()
  return date.getDate() + '/' + (date.getMonth() + 1) + ' ' + (date.getHours() + 1) + ':' + (date.getMinutes() + 1) + ':' + (date.getSeconds() + 1)
}

function log(text) {
  console.log(text)
  fs.appendFile(DEFAULTLOGPATH, '[' + getDate() + '] ' + text + '\n', 'utf8', function(err) {
    if (err) throw err
  })
}

function startTorrent(url) {
  log('Trying to download: ' + url)

  // evite de lancer deux fois le meme torrent
  if (TorrentUrlToChild[url] == null) {
    // Si trop de torrent en cours
    if (Object.keys(TorrentUrlToChild).length < 3) {
      var n = cp.fork(__dirname + '/tclient.js')
      TorrentUrlToChild[url] = n
      io.sockets.emit('start-t')
      n.on('message', function(data) {
        switch (data.type) {
          case 'finish':
            io.sockets.emit('finish-t', data.hash)
            n.kill('SIGHUP')
            delete TorrentUrlToChild[url]
            delete TorrentUrlToHash[url]
            delete TorrentHashToChild[data.hash]
            fs.renameSync(DEFAULTDOWNLOADPATH + data.name, DEFAULTFILESPATH + data.name)
              // Relance un torrent si il y en a en attente
            if (TorrentWaitList.length > 0) {
              var newUrl = TorrentWaitList[0]
              startTorrent(newUrl)
              TorrentWaitList.shift()
            }
            break
          case 'info':
            io.sockets.emit('list-t', data.torrent)
            TorrentHashToChild[data.torrent.hash] = n
            TorrentUrlToHash[url] = data.torrent.hash
            break
          case 'remove':
            io.sockets.emit('finish-t', data.hash)
            n.kill('SIGHUP')
            delete TorrentUrlToChild[url]
            delete TorrentUrlToHash[url]
            delete TorrentHashToChild[data.hash]
            fs.unlinkSync(DEFAULTDOWNLOADPATH + data.name)
              // Relance un torrent si il y en a en attente
            if (TorrentWaitList.length > 0) {
              startTorrent(TorrentWaitList[0])
              TorrentWaitList.shift()
            }
        }
      })

      n.on('exit', function(code, signal) {
        if (signal !== 'SIGHUP') {
          log('Child: ' + url + ' \n exit with code: ' + code)
          io.sockets.emit('error-t', TorrentUrlToHash[url])
          delete TorrentUrlToChild[url]
          delete TorrentHashToChild[TorrentUrlToHash[url]]
          delete TorrentUrlToHash[url]
          startTorrent(url)
        }
      })
      n.send({
        'type': 'download',
        'torrent': url
      })

    } else {
      log('Too much client. Adding torrent to the waitlist.')
        // On push dans la liste d'attente
      if (TorrentWaitList.indexOf(url) === -1) {
        TorrentWaitList.push(url)
      }
    }
  } else {
    log('Torrent is already downloading.')
  }
}

function removeRecursif(path) {
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(function(file, index) {
      var curPath = path + '/' + file
      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        removeRecursif(curPath)
      } else { // delete file
        fs.unlinkSync(curPath)
      }
    })
    fs.rmdirSync(path)
  }
}

function sizeRecursif(path) {
  var size = 0
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(function(file, index) {
      var curPath = path + '/' + file
      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        size += sizeRecursif(curPath)
      } else { // read size
        size += fs.statSync(curPath).size
      }
    })
    return size
  }
}

function startPointTorrent() {
  log('Scan for new torrent.')
  fs.readFile(DEFAULTTORRENTPATH, 'utf-8', function(err, data) {
    if (err) return log(err)
    var torrents = data.split('\n')
    fs.writeFile(DEFAULTTORRENTPATH, '', 'utf-8', function(err) {
      if (err) return log(err)
      torrents.forEach(function(element) {
        if (element !== '') {
          startTorrent(element)
        }
      })
    })
  })
}
<|endoftext|>


<commit_before>/*

2013 Alan Languirand
@13protons

*/

var express = require('express')
    , lessMiddleware = require('less-middleware')
    , http = require('http')
    , url = require('url')
    , fs = require('fs')
    , path = require('path')
    , ejs = require('ejs')
    , passport = require('passport')
    , GitHubStrategy = require('passport-github').Strategy
    , extend = require('node.extend')
    , app = express()
    , Firebase = require('firebase')
    , config = require('./config'); //make sure it's pointing in the right direction. config.js doesn't sync w/ git

var fbURL = config['FIREBASE_FORGE']; //firebase endpoint

var resources = {
            "headers":  {"title": "Headers", "type": "header", "updateURL": fbURL + "/resources/headers", "id": "headers", "rel": "/headers", "color": "blue"},
            "verbs":    {"title": "Verbs", "type": "verb", "updateURL": fbURL + "/resources/verbs", "id": "verbs", "rel": "/verbs", "color": "green"},
            "codes":    {"title": "Codes", "type": "code", "updateURL": fbURL + "/resources/codes", "id": "codes", "rel": "/codes", "color": "yellow"}
        };

    //Configure sessions and passport
    app.use(express.cookieParser(config['SESSION_SECRET'])); //make it a good one
    app.use(express.session({secret: config['SESSION_SECRET']}));
    app.use(passport.initialize());
    app.use(passport.session());

    // Use the GitHubStrategy within Passport.
    //   Strategies in Passport require a `verify` function, which accept
    //   credentials (in this case, an accessToken, refreshToken, and GitHub
    //   profile), and invoke a callback with a user object.
    passport.use(new GitHubStrategy({
        clientID: config['GITHUB_CLIENT'],
        clientSecret: config['GITHUB_SECRET'],
        callbackURL: "http://apiatlas.herokuapp.com/auth/github/callback" //change for production
      },
      function(accessToken, refreshToken, profile, done) {
        // asynchronous verification, for effect...
        process.nextTick(function () {
            //save provider, id, display
            var p = {
                "provider": profile.provider,
                "id": profile.id,
                "displayName": profile.displayName,
            }
            var user = new Firebase(fbURL + '/users/' + profile.id);
            user.once('value', function(snapshot){
                if(snapshot.val() == null){
                    //create that user
                    console.log('creating user...');
                    var users = new Firebase(fbURL + '/users');
                    users.child(p.id).set(p, function(e){
                        if(e){console.log('problem creating user', e);}
                        else{console.log('created user');}
                    });
                }
            });
            console.log('logged in: ', p);
            return done(null, p);
        });
      }
    ));

    passport.serializeUser(function(user, done) {
      done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        var user = new Firebase(fbURL + '/users/' + id);
        user.once('value', function(snapshot){
            done(null, snapshot.val());
        });
    });

	app.engine('.html', require('ejs').__express);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'html');

    //less is more?
	app.use(lessMiddleware({
	    src      : __dirname + '/public',
	    compress : true
	  }));

	app.use(express.static(path.join(__dirname, 'public'))); //  "public" off of current is root

    //default page
    app.get('/', function(req, res) {

        //should this be automated or stuck in config.js? Not yet, but probably in a more flexible version

        res.render(__dirname + '/views/vis.ejs', {
                "resources": resources,
                "page": "home",
                "user": getUser(req),
                "name": "",
                "data": resources //JSON.stringify(output)
            });

	});

    app.get('/logout', function(req, res){
            if(typeof(req.query.last) == "undefined"){ req.session.last = '/'; }
            else{ req.session.last = req.query.last }

            req.logout();
            req.session['auth'] = false;
            res.redirect(req.session.last);
        });

    //Simple login
    //app.get('/auth/github', passport.authenticate('github'));

    //Handle "?last=x if available
    app.get('/auth/github', function(req, res, next) {
        if(typeof(req.query.last) == "undefined"){ req.session.last = '/login'; }
        else{ req.session.last = req.query.last }

          passport.authenticate('github', function(err, user, info) {
            if (err) { return next(err); }
            if (!user) { return res.redirect(req.session.last); }
            req.logIn(user, function(err) {
              if (err) { return next(err); }
              return res.redirect(req.session.last);
            });
          })(req, res, next);
    });

    app.get('/auth/github/callback',

      passport.authenticate('github', { failureRedirect: '/login' }),
      function(req, res) {
          req.session['auth'] = true;
        res.redirect(req.session.last);

      });

    app.get('/:type/:title', function(req, res){
        user = null;
        var full_user = getUser(req);
        if(full_user !== null){user = full_user.id;}

        var d = {
            "type": req.params.type,
            "title": req.params.title,
            "uid": "",
            "name": ""

        }
        //var user = req.user.id;
        d.uid =  d.type + d.title;
        d.name = "resources/" + d.type + "/" + d.title;
        var resource = new Firebase(fbURL + '/' + d.name);
        resource.once('value', function(snap_r){
            //if logged in, we'd look for the user ID in the users up & down objects and raise "you voted" flag
            var data = snap_r.val();
            data.priority = snap_r.getPriority();
            console.log("GET ", d.name);
            var v = req.query.vote;

            if(user == null){
                render_resource()
            }else {
            console.log(fbURL, user, d.name);
            var didVote = new Firebase(fbURL + '/users/' + user + '/votes/' + d.name);
            didVote.once('value', function(snap_d){
                    data.your_vote = snap_d.val();

                    //this if block actually does the voting!
                    if(typeof(v) != "undefined" && user !== null){

    //voting! Yup, that's 12 possible references to update
                        var update = {
                            resource: {
                                self: new Firebase(fbURL + '/' + d.name + '/votes/raw'),
                                down: new Firebase(fbURL + '/' + d.name + '/votes/down'),
                                up: new Firebase(fbURL + '/' + d.name + '/votes/up'),
                                total: new Firebase(fbURL + '/' + d.name + '/votes/total'),
                                user: new Firebase(fbURL + '/' + d.name + '/votes/raw/' + user)
                            },
                            user: {
                                self: new Firebase(fbURL + '/users/' + user + '/votes/'),
                                down: new Firebase(fbURL + '/users/' + user + '/votes/down'),
                                up: new Firebase(fbURL + '/users/' + user + '/votes/up'),
                                total: new Firebase(fbURL + '/users/' + user + '/votes/total'),
                                resource: new Firebase(fbURL + '/users/' + user + '/votes/' + d.name)
                            },
                            raw: {
                                self: new Firebase(fbURL + '/votes'),
                                total: new Firebase(fbURL + '/votes/total'),
                                user: new Firebase(fbURL + '/votes/' + d.name + '/' + user)
                            }

                        }
                        function vote(boolean){
                            var targetResourceName = d.name;
                            update.resource.self.child(user).set(boolean);
                            update.user.self.child(targetResourceName).set(boolean);
                            update.raw.self.child(d.name).child(user).set(boolean);

                            //update vote for resource
                            update.resource.total.transaction(function(c) { return c + 1; });
                            update.user.total.transaction(function(c) { return c + 1; });
                            update.raw.total.transaction(function(c) { return c + 1; });

                            if(boolean){
                                update.resource.up.transaction(function(c) { return c + 1; });
                                update.user.up.transaction(function(c) { return c + 1; });
                            }else{
                                update.resource.down.transaction(function(c) { return c + 1; });
                                update.user.down.transaction(function(c) { return c + 1; });
                            }

                        }
                        function reduceTotals(x){
                                //remove previous votes
                                update.resource.user.remove();
                                update.user.resource.remove();
                                update.raw.user.remove();

                                //decrement total counters
                                update.resource.total.transaction(function(c) { return c - 1; });
                                update.user.total.transaction(function(c) { return c - 1; });
                                update.raw.total.transaction(function(c) { return c - 1; });

                                if(data.your_vote === false || data.your_vote === null){
                                    update.resource.down.transaction(function(c) { return c - 1; });
                                    update.user.down.transaction(function(c) { return c - 1; });
                                }

                                if(data.your_vote === true || data.your_vote === null){
                                    update.resource.up.transaction(function(c) { return c - 1; });
                                    update.user.up.transaction(function(c) { return c - 1; });
                                }

                        }
                        if(v == "remove" && data.your_vote !== null){
                           console.log("remove vote");
                           reduceTotals(data.your_vote);
                           }
                        if(v == "up" && data.your_vote !== true){
                            //vote up
                            if(data.your_vote === false){
                                console.log('changing down to up');
                                reduceTotals(data.your_vote);
                            }
                            vote(true);
                        }
                        if(v == "down" && data.your_vote !== false){
                            //vote down
                            if(data.your_vote === true){
                                console.log('changing up to down');
                                reduceTotals(data.your_vote);
                            }
                            vote(false);
                        }
                        //res.redirect(req._parsedUrl.pathname);
                        res.send();

                    }else {
                        render_resource();
                    }

            });

            }

            function render_resource(){
                        data.votes.percent = 0;
                        if(data.votes.total > 0){ data.votes.percent = Math.round((data.votes.up/data.votes.total) * 100); }
                        data.votes.percent_display = data.votes.percent + "%";

                        data = extend(data, resources[d.type]);

                        console.log(data);

                        res.render(__dirname + '/views/resource_show.ejs', {
                            "r": data,
                            "page": "resource",
                            "user": full_user,
                            "name": "/"+ d.type +"/"+ d.title,
                            "updateURL": resource
                        });

            }

        });

    });

    app.get('/:page', function(req, res) {
        user = getUser(req);
	  	fs.stat(__dirname + '/views/' + req.params.page + ".ejs", function(err){
	  		if(err){
				res.render('404', {
                    "page":  "not_found",
                    "user": user,
                    "name": "/404"
                });
	  		}else{
	  			res.render(__dirname + '/views/' + req.params.page + ".ejs", {
                    "data": resources,
                    "page": req.params.page,
                    "user": user,
                    "name": "/" + req.params.page
                });

	  		}
	  	});

	});

    /*
	app.locals({
	  table  : function(list) {
	    var template = fs.readFileSync(__dirname + '/views/table.ejs', 'utf-8');
	    return ejs.render(template, list);
	  },
      message: ""

	});
*/
	var port = process.env.PORT || 3000;
	app.listen(port);

	console.log('Listening on port %d', port);

    function getUser(req){
        var user = null;
        if(typeof(req.user) != 'undefined'){
            user = req.user ;
        }
        return user;
    }

function log(x){
    console.log(x);
}
<commit_msg>redirect environment<commit_after>/*

2013 Alan Languirand
@13protons

*/

var express = require('express')
    , lessMiddleware = require('less-middleware')
    , http = require('http')
    , url = require('url')
    , fs = require('fs')
    , path = require('path')
    , ejs = require('ejs')
    , passport = require('passport')
    , GitHubStrategy = require('passport-github').Strategy
    , extend = require('node.extend')
    , app = express()
    , Firebase = require('firebase')
    , config = require('./config'); //make sure it's pointing in the right direction. config.js doesn't sync w/ git

var fbURL = config['FIREBASE_FORGE']; //firebase endpoint

var resources = {
            "headers":  {"title": "Headers", "type": "header", "updateURL": fbURL + "/resources/headers", "id": "headers", "rel": "/headers", "color": "blue"},
            "verbs":    {"title": "Verbs", "type": "verb", "updateURL": fbURL + "/resources/verbs", "id": "verbs", "rel": "/verbs", "color": "green"},
            "codes":    {"title": "Codes", "type": "code", "updateURL": fbURL + "/resources/codes", "id": "codes", "rel": "/codes", "color": "yellow"}
        };

    //Configure sessions and passport
    app.use(express.cookieParser(config['SESSION_SECRET'])); //make it a good one
    app.use(express.session({secret: config['SESSION_SECRET']}));
    app.use(passport.initialize());
    app.use(passport.session());

    // Use the GitHubStrategy within Passport.
    //   Strategies in Passport require a `verify` function, which accept
    //   credentials (in this case, an accessToken, refreshToken, and GitHub
    //   profile), and invoke a callback with a user object.
    passport.use(new GitHubStrategy({
        clientID: config['GITHUB_CLIENT'],
        clientSecret: config['GITHUB_SECRET'],
        callbackURL: config['REDIRECT'] //change for production
      },
      function(accessToken, refreshToken, profile, done) {
        // asynchronous verification, for effect...
        process.nextTick(function () {
            //save provider, id, display
            var p = {
                "provider": profile.provider,
                "id": profile.id,
                "displayName": profile.displayName,
            }
            var user = new Firebase(fbURL + '/users/' + profile.id);
            user.once('value', function(snapshot){
                if(snapshot.val() == null){
                    //create that user
                    console.log('creating user...');
                    var users = new Firebase(fbURL + '/users');
                    users.child(p.id).set(p, function(e){
                        if(e){console.log('problem creating user', e);}
                        else{console.log('created user');}
                    });
                }
            });
            console.log('logged in: ', p);
            return done(null, p);
        });
      }
    ));

    passport.serializeUser(function(user, done) {
      done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        var user = new Firebase(fbURL + '/users/' + id);
        user.once('value', function(snapshot){
            done(null, snapshot.val());
        });
    });

	app.engine('.html', require('ejs').__express);
	app.set('views', __dirname + '/views');
	app.set('view engine', 'html');

    //less is more?
	app.use(lessMiddleware({
	    src      : __dirname + '/public',
	    compress : true
	  }));

	app.use(express.static(path.join(__dirname, 'public'))); //  "public" off of current is root

    //default page
    app.get('/', function(req, res) {

        //should this be automated or stuck in config.js? Not yet, but probably in a more flexible version

        res.render(__dirname + '/views/vis.ejs', {
                "resources": resources,
                "page": "home",
                "user": getUser(req),
                "name": "",
                "data": resources //JSON.stringify(output)
            });

	});

    app.get('/logout', function(req, res){
            if(typeof(req.query.last) == "undefined"){ req.session.last = '/'; }
            else{ req.session.last = req.query.last }
            req.session.destroy(function (err) {
                //res.redirect('/'); //Inside a callback… bulletproof!
                req.session['auth'] = false;
                res.redirect(req.session.last);
              });
            //req.logout();

        });

    //Simple login
    //app.get('/auth/github', passport.authenticate('github'));

    //Handle "?last=x if available
    app.get('/auth/github', function(req, res, next) {
        if(typeof(req.query.last) == "undefined"){ req.session.last = '/login'; }
        else{ req.session.last = req.query.last }

          passport.authenticate('github', function(err, user, info) {
            if (err) { return next(err); }
            if (!user) { return res.redirect(req.session.last); }
            req.logIn(user, function(err) {
              if (err) { return next(err); }
              return res.redirect(req.session.last);
            });
          })(req, res, next);
    });

    app.get('/auth/github/callback',

      passport.authenticate('github', { failureRedirect: '/login' }),
      function(req, res) {
          req.session['auth'] = true;
            res.redirect(req.session.last);

      });

    app.get('/:type/:title', function(req, res){
        user = null;
        var full_user = getUser(req);
        if(full_user !== null){user = full_user.id;}

        var d = {
            "type": req.params.type,
            "title": req.params.title,
            "uid": "",
            "name": ""

        }
        //var user = req.user.id;
        d.uid =  d.type + d.title;
        d.name = "resources/" + d.type + "/" + d.title;
        var resource = new Firebase(fbURL + '/' + d.name);
        resource.once('value', function(snap_r){
            //if logged in, we'd look for the user ID in the users up & down objects and raise "you voted" flag
            var data = snap_r.val();
            data.priority = snap_r.getPriority();
            console.log("GET ", d.name);
            var v = req.query.vote;

            if(user == null){
                render_resource();
            }else {
            console.log(fbURL, user, d.name);
            var didVote = new Firebase(fbURL + '/users/' + user + '/votes/' + d.name);
            didVote.once('value', function(snap_d){
                    data.your_vote = snap_d.val();

                    //this if block actually does the voting!
                    if(typeof(v) != "undefined" && user !== null){

    //voting! Yup, that's 12 possible references to update
                        var update = {
                            resource: {
                                self: new Firebase(fbURL + '/' + d.name + '/votes/raw'),
                                down: new Firebase(fbURL + '/' + d.name + '/votes/down'),
                                up: new Firebase(fbURL + '/' + d.name + '/votes/up'),
                                total: new Firebase(fbURL + '/' + d.name + '/votes/total'),
                                user: new Firebase(fbURL + '/' + d.name + '/votes/raw/' + user)
                            },
                            user: {
                                self: new Firebase(fbURL + '/users/' + user + '/votes/'),
                                down: new Firebase(fbURL + '/users/' + user + '/votes/down'),
                                up: new Firebase(fbURL + '/users/' + user + '/votes/up'),
                                total: new Firebase(fbURL + '/users/' + user + '/votes/total'),
                                resource: new Firebase(fbURL + '/users/' + user + '/votes/' + d.name)
                            },
                            raw: {
                                self: new Firebase(fbURL + '/votes'),
                                total: new Firebase(fbURL + '/votes/total'),
                                user: new Firebase(fbURL + '/votes/' + d.name + '/' + user)
                            }

                        }
                        function vote(boolean){
                            var targetResourceName = d.name;
                            update.resource.self.child(user).set(boolean);
                            update.user.self.child(targetResourceName).set(boolean);
                            update.raw.self.child(d.name).child(user).set(boolean);

                            //update vote for resource
                            update.resource.total.transaction(function(c) { return c + 1; });
                            update.user.total.transaction(function(c) { return c + 1; });
                            update.raw.total.transaction(function(c) { return c + 1; });

                            if(boolean){
                                update.resource.up.transaction(function(c) { return c + 1; });
                                update.user.up.transaction(function(c) { return c + 1; });
                            }else{
                                update.resource.down.transaction(function(c) { return c + 1; });
                                update.user.down.transaction(function(c) { return c + 1; });
                            }

                        }
                        function reduceTotals(x){
                                //remove previous votes
                                update.resource.user.remove();
                                update.user.resource.remove();
                                update.raw.user.remove();

                                //decrement total counters
                                update.resource.total.transaction(function(c) { return c - 1; });
                                update.user.total.transaction(function(c) { return c - 1; });
                                update.raw.total.transaction(function(c) { return c - 1; });

                                if(data.your_vote === false || data.your_vote === null){
                                    update.resource.down.transaction(function(c) { return c - 1; });
                                    update.user.down.transaction(function(c) { return c - 1; });
                                }

                                if(data.your_vote === true || data.your_vote === null){
                                    update.resource.up.transaction(function(c) { return c - 1; });
                                    update.user.up.transaction(function(c) { return c - 1; });
                                }

                        }
                        if(v == "remove" && data.your_vote !== null){
                           console.log("remove vote");
                           reduceTotals(data.your_vote);
                           }
                        if(v == "up" && data.your_vote !== true){
                            //vote up
                            if(data.your_vote === false){
                                console.log('changing down to up');
                                reduceTotals(data.your_vote);
                            }
                            vote(true);
                        }
                        if(v == "down" && data.your_vote !== false){
                            //vote down
                            if(data.your_vote === true){
                                console.log('changing up to down');
                                reduceTotals(data.your_vote);
                            }
                            vote(false);
                        }
                        //res.redirect(req._parsedUrl.pathname);
                        res.send();

                    }else {
                        render_resource();
                    }

            });

            }

            function render_resource(){
                        data.votes.percent = 0;
                        if(data.votes.total > 0){ data.votes.percent = Math.round((data.votes.up/data.votes.total) * 100); }
                        data.votes.percent_display = data.votes.percent + "%";

                        data = extend(data, resources[d.type]);

                        console.log(data);

                        res.render(__dirname + '/views/resource_show.ejs', {
                            "r": data,
                            "page": "resource",
                            "user": full_user,
                            "name": "/"+ d.type +"/"+ d.title,
                            "updateURL": resource
                        });

            }

        });

    });

    app.get('/:page', function(req, res) {
        user = getUser(req);
	  	fs.stat(__dirname + '/views/' + req.params.page + ".ejs", function(err){
	  		if(err){
				res.render('404', {
                    "page":  "not_found",
                    "user": user,
                    "name": "/404"
                });
	  		}else{
	  			res.render(__dirname + '/views/' + req.params.page + ".ejs", {
                    "data": resources,
                    "page": req.params.page,
                    "user": user,
                    "name": "/" + req.params.page
                });

	  		}
	  	});

	});

    /*
	app.locals({
	  table  : function(list) {
	    var template = fs.readFileSync(__dirname + '/views/table.ejs', 'utf-8');
	    return ejs.render(template, list);
	  },
      message: ""

	});
*/
	var port = process.env.PORT || 3000;
	app.listen(port);

	console.log('Listening on port %d', port);

    function getUser(req){
        var user = null;
        if(typeof(req.user) != 'undefined'){
            user = req.user ;
        }
        return user;
    }

function log(x){
    console.log(x);
}
<|endoftext|>


<commit_before>module.exports = function (suppressLogs) {
    var //fs = require('fs'),
        connect = require('connect'),
        express = require('express'),
        orm = require('orm'),
        app = express(),
        emitter = require('./event-emitter')(),
        swig = require('swig'),
        passport = require('passport'),
        flash = require('connect-flash'),
        http = require('http'),
        roles = require('./lib/roles'),
        swigHelpers = require('./helpers/swig'),
        enums = require('./enums'),
        router = require('./routing/router'),
        log = require('./log'),
        controllers = {},
        db_url;

    //initial log functions.
    log.init(enums);

    controllers.questions = require('./controllers/questions');
    controllers.question_comments = require('./controllers/question_comments');
    controllers.answers = require('./controllers/answers');
    controllers.answer_comments = require('./controllers/answer_comments');
    controllers.users = require('./controllers/users');
    controllers.ratings = require('./controllers/ratings');

    // Following line replaced to avoid warnings –
    // see https://github.com/senchalabs/connect/wiki/Connect-3.0
    app.use(express.bodyParser());

    app.use(connect.urlencoded());
    app.use(connect.json());

    // To allow use of all HTTP methods in the browser through use of _method variable
    app.use(express.methodOverride());

    app.set('port', process.env.PORT || 3000);

    app.engine('html', swig.renderFile);
    app.set('view engine', 'html');
    app.set('views', __dirname + '/views');
    // Swig will cache templates for you, but you can disable
    // that and use Express's caching instead, if you like:
    app.set('view cache', false);
    // To disable Swig's cache, do the following:
    swig.setDefaults({ cache: false });
    // NOTE: You should always cache templates in a production environment.
    // Don't leave both of these to `false` in production!

    // Set up swig helpers for compilation/rendering pages.
    swigHelpers(swig);

    // Static file handling
    // app.use(express.static(__dirname + '/static'));

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

    //prevent big package and return 413 error
    app.use(connect.limit('5kb'));

    // Overwrite demo.sh at the start of execution because it is appended to.
    //if (enums.document) {
    //    fs.writeFile(enums.demo, '#!/bin/bash\n\n', function (err) {
    //        if (err) {
    //            throw err;
    //        }
    //    });
    //}

    if (process.env.DATABASE_URL === undefined) {
    	db_url = "sqlite://app.db";
    } else {
    	//console.log('db:', process.env.DATABASE_URL);
    	db_url = "postgres://" + process.env.DATABASE_URL;
    }

    // Set up the ORM to SQLite.
    app.use(orm.express(db_url, {
        define: function (db, models, next) {

            // Instance.cache is an important setting.
            // By default the cache is enabled but this means
            // that fields set not in the create() function will not be
            // picked up by the model (all fields successfully save into DB).
            db.settings.set('instance.cache', false);

            db.load("./models", function (err) {
                if (err === null || err === undefined) {
                    if (!suppressLogs) {
                        console.logger.info('Model loaded');
                    }
                } else {
                    console.logger.error('Model loading failed:');
                    console.logger.error(err);
                }

                models.Post = db.models.post;
                models.Question = db.models.question;
                models.Answer = db.models.answer;
                models.QuestionComment = db.models.question_comment;
                models.AnswerComment = db.models.answer_comment;
                models.Rating = db.models.rating;
                models.User = db.models.user;
                models.Local = db.models.local;
                models.Facebook = db.models.facebook;

                // Post is the base class.
                // Questions, answers and comments are types of Post.

                db.sync(function () {
                    emitter.emit('model-synced');
                    if (!suppressLogs) {
                        console.logger.info("Model synchronised");
                    }
                });
            });
            next();
        }
    }));

    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.session({ secret: 'cat' }, {maxAge: new Date(Date.now() + 3600000)}));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(roles.user.middleware());
    app.use(flash());
    app.use(app.router);

//    app.listen();
//
//    if (!suppressLogs) {
//        console.logger.info('Server started on ' + enums.options.hostname + ':' + enums.options.port);
//    }
//
//    // Configure the routes.
    router(app, controllers);
    http.createServer(app).listen(app.get('port'), function(){
        console.log('Express server listening on port ' + app.get('port'));
    });

    //process.on('SIGINT', function () {
    //    console.logger.info('Server stopped.');
    //    process.exit(1);
    //});
};<commit_msg>this is a test<commit_after>// test
module.exports = function (suppressLogs) {
    var //fs = require('fs'),
        connect = require('connect'),
        express = require('express'),
        orm = require('orm'),
        app = express(),
        emitter = require('./event-emitter')(),
        swig = require('swig'),
        passport = require('passport'),
        flash = require('connect-flash'),
        http = require('http'),
        roles = require('./lib/roles'),
        swigHelpers = require('./helpers/swig'),
        enums = require('./enums'),
        router = require('./routing/router'),
        log = require('./log'),
        controllers = {},
        db_url;

    //initial log functions.
    log.init(enums);

    controllers.questions = require('./controllers/questions');
    controllers.question_comments = require('./controllers/question_comments');
    controllers.answers = require('./controllers/answers');
    controllers.answer_comments = require('./controllers/answer_comments');
    controllers.users = require('./controllers/users');
    controllers.ratings = require('./controllers/ratings');

    // Following line replaced to avoid warnings –
    // see https://github.com/senchalabs/connect/wiki/Connect-3.0
    app.use(express.bodyParser());

    app.use(connect.urlencoded());
    app.use(connect.json());

    // To allow use of all HTTP methods in the browser through use of _method variable
    app.use(express.methodOverride());

    app.set('port', process.env.PORT || 3000);

    app.engine('html', swig.renderFile);
    app.set('view engine', 'html');
    app.set('views', __dirname + '/views');
    // Swig will cache templates for you, but you can disable
    // that and use Express's caching instead, if you like:
    app.set('view cache', false);
    // To disable Swig's cache, do the following:
    swig.setDefaults({ cache: false });
    // NOTE: You should always cache templates in a production environment.
    // Don't leave both of these to `false` in production!

    // Set up swig helpers for compilation/rendering pages.
    swigHelpers(swig);

    // Static file handling
    // app.use(express.static(__dirname + '/static'));

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

    //prevent big package and return 413 error
    app.use(connect.limit('5kb'));

    // Overwrite demo.sh at the start of execution because it is appended to.
    //if (enums.document) {
    //    fs.writeFile(enums.demo, '#!/bin/bash\n\n', function (err) {
    //        if (err) {
    //            throw err;
    //        }
    //    });
    //}

    if (process.env.DATABASE_URL === undefined) {
    	db_url = "sqlite://app.db";
    } else {
    	//console.log('db:', process.env.DATABASE_URL);
    	db_url = "postgres://" + process.env.DATABASE_URL;
    }

    // Set up the ORM to SQLite.
    app.use(orm.express(db_url, {
        define: function (db, models, next) {

            // Instance.cache is an important setting.
            // By default the cache is enabled but this means
            // that fields set not in the create() function will not be
            // picked up by the model (all fields successfully save into DB).
            db.settings.set('instance.cache', false);

            db.load("./models", function (err) {
                if (err === null || err === undefined) {
                    if (!suppressLogs) {
                        console.logger.info('Model loaded');
                    }
                } else {
                    console.logger.error('Model loading failed:');
                    console.logger.error(err);
                }

                models.Post = db.models.post;
                models.Question = db.models.question;
                models.Answer = db.models.answer;
                models.QuestionComment = db.models.question_comment;
                models.AnswerComment = db.models.answer_comment;
                models.Rating = db.models.rating;
                models.User = db.models.user;
                models.Local = db.models.local;
                models.Facebook = db.models.facebook;

                // Post is the base class.
                // Questions, answers and comments are types of Post.

                db.sync(function () {
                    emitter.emit('model-synced');
                    if (!suppressLogs) {
                        console.logger.info("Model synchronised");
                    }
                });
            });
            next();
        }
    }));

    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.session({ secret: 'cat' }, {maxAge: new Date(Date.now() + 3600000)}));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(roles.user.middleware());
    app.use(flash());
    app.use(app.router);

//    app.listen();
//
//    if (!suppressLogs) {
//        console.logger.info('Server started on ' + enums.options.hostname + ':' + enums.options.port);
//    }
//
//    // Configure the routes.
    router(app, controllers);
    http.createServer(app).listen(app.get('port'), function(){
        console.log('Express server listening on port ' + app.get('port'));
    });

    //process.on('SIGINT', function () {
    //    console.logger.info('Server stopped.');
    //    process.exit(1);
    //});
};
<|endoftext|>


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

var app = express();

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

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

server.listen(process.env.PORT || 3000);

// When the root director is requested, return the index.html page.
app.get('/',function(req,res){
    res.sendFile(__dirname + '/index.html');
});
<commit_msg>try to serve node_modules<commit_after>var express = require('express');

var app = express();

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

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

server.listen(process.env.PORT || 3000);

// When the root director is requested, return the index.html page.
app.get('/',function(req,res){
    res.sendFile(__dirname + '/index.html');
});
<|endoftext|>


<commit_before>"use strict"

/* ---------------------------------------------------------------------------
Log-HTTP2File - https://github.com/fabrom/log-http2file
Simple HTTP server to log POST request content to file
Author: Fabrice Romand <fabrice.romand@gmail.com>
README for more information
---------------------------------------------------------------------------- */

// Requirements ----
const http = require('http');
const fs = require('fs');
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const tmpdir = require('os').tmpdir();
const path = require('path');

// Variables declaration ----
var prg_package = null;
var port = (process.env.npm_package_config_port) ? process.env.npm_package_config_port : 8142;
var nb_workers = (numCPUs/2)+1;
var output_file = path.join(tmpdir, 'message.log');
var output_file_pid = output_file + '.pid';

// Retrieve request source address
function getRemoteAddress(req) {
    if (req.headers['x-forwarded-for']) {
        return req.headers['x-forwarded-for'];
    }
    return req.connection.remoteAddress;
}

// Retrieve request user-agent
function getRemoteAgent(req) {
    if (req.headers['user-agent']) {
        return req.headers['user-agent'];
    }
    return null;
}

// Retrieve remote user
function getRemoteUser(req) {
    if (req.headers['remote_user']) {
        return req.headers['remote_user'];
    }
    return null;
}

// Return Object in string is JSON, null otherwise
function isJSON(jsonString) {
    try {
      var json = JSON.parse(jsonString);
    } catch (exception) {
      json = null;
    }
    return json;
}

// Go through all workers
function eachWorker(callback) {
  for (var id in cluster.workers) {
    callback(cluster.workers[id]);
  }
}

// Fork cluster
function setWorkers() {
    for (var i = 1; i <= nb_workers; i++) {
        cluster.fork();
    }
}

// Main -----------------------------------------------------------------------

function startServer(onReadyCallBack) {

    const program = require('commander');

    prg_package = JSON.parse(fs.readFileSync(path.join(__dirname,'package.json'), 'utf8'));
    program
        .version(prg_package.version)
        .description(prg_package.description)
        .usage('[options] <outputfile>')
        .option('-w, --workers <n>', 'how many listening workers', parseInt)
        .option('-p, --port <n>', 'listening port', parseInt)
        .arguments('<outputfile>')
            .action(function (outputfile) {
                output_file = outputfile;
            })
        .parse(process.argv);

    if (cluster.isMaster) {

        console.log(prg_package.name + " v." + prg_package.version + ' - ' + prg_package.description);
        console.log("Author: " + prg_package.author + " - Homepage: " + prg_package.homepage);
        console.log("Report bugs on " + prg_package.bugs);
        console.log(`Master process id: ${process.pid}`);

        nb_workers = program.workers || nb_workers;
        port = program.port || port;

        cluster.on('exit', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} exit with code: ${code} (signal: ${signal})`);
        });

        cluster.on('listening', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} now listening on port ${port} and writing to ${output_file}...`);
        });

        output_file_pid = output_file + '.pid';
        fs.writeFileSync(output_file_pid, process.pid);

        process.on('SIGHUP', function() {
            eachWorker(function(worker) {
                worker.kill('SIGHUP');
            })
            var d = new Date();
            var d1 = d.toISOString();
            var d2 = d1.substr(0,19).replace(/-/g,'').replace(/:/g,'').replace('T','');
            var newdir = path.dirname(output_file);
            var newname = path.basename(output_file, path.extname(output_file)) + '_' + d2 + path.extname(output_file);
            fs.rename(output_file, path.join(newdir, newname), function() {
                console.log(`${path.basename(output_file)} renamed to ${newname}`);
                setWorkers();
            });
        });

        process.on('SIGINT', function() {
            eachWorker(function(worker) {
                worker.kill('SIGINT');
            });
        });

        process.on('SIGTERM', function() {
            eachWorker(function(worker) {
                worker.kill('SIGTERM');
            });
        });

        process.on('SIGBREAK', function() {
            eachWorker(function(worker) {
                worker.kill('SIGBREAK');
            });
        });

        setWorkers();

        if (onReadyCallBack) onReadyCallBack();

    } else {

        fs.open(output_file, 'a', function(err, flogd) {

            if (err) {
                console.error("can't open output file");
                cluster.worker.kill();
            } else {
                const server = http.createServer((request, response) => {
                    if (request.method !== 'POST') {
                        response.statusCode = 405;
                        response.end();
                    } else {
                        var body = '';
                        request.on('data', function (data) {
                            body += data;
                            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
                            if (body.length > 1e6) {
                                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                                request.connection.destroy();
                            }
                        });
                        request.on('end', function () {
                            var remote_address = getRemoteAddress(request);
                            var remote_user = getRemoteUser(request);
                            var body_object = isJSON(body);
                            var remote_object = {
                                    address: remote_address,
                                    user: remote_user,
                                    agent: getRemoteAgent(request)
                            };
                            if (body_object instanceof Object) {
                                body_object.remote = remote_object;
                                body = JSON.stringify(body_object);
                            };
                            fs.write(flogd, body + '\n', function(err, written, string) {
                                if (err) {
                                    console.error("can't write to output file");
                                }
                                response.statusCode = 200;
                                response.end();
                            });
                            var continuation = (body.length > 128) ? "..." : "";
                            var message = body.substr(0, 128);
                            console.log(Date.now() +
                                " [" + remote_address +
                                "][" + cluster.worker.process.pid +
                                "] " + message + continuation
                            );
                        });

                    }
                });

                server.on('clientError', (err, socket) => {
                    socket.statusCode = 400;
                    socket.end();
                });

                server.on('close', (err, socket) => {
                    fs.close(flogd);
                });

                server.listen(port);
            }
        });
    }
}

function stopServer() {
    process.kill(process.pid, 'SIGTERM');
}

function renewServer() {
    process.kill(process.pid, 'SIGHUP');
}

process.on('exit', (code) => {
    fs.unlinkSync(output_file_pid);
});

module.exports = exports
exports.start = startServer;
exports.stop = stopServer;
exports.renew = renewServer;
<commit_msg>fix pid file deletion on SIGTERM<commit_after>"use strict"

/* ---------------------------------------------------------------------------
Log-HTTP2File - https://github.com/fabrom/log-http2file
Simple HTTP server to log POST request content to file
Author: Fabrice Romand <fabrice.romand@gmail.com>
README for more information
---------------------------------------------------------------------------- */

// Requirements ----
const http = require('http');
const fs = require('fs');
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
const tmpdir = require('os').tmpdir();
const path = require('path');

// Variables declaration ----
var prg_package = null;
var port = (process.env.npm_package_config_port) ? process.env.npm_package_config_port : 8142;
var nb_workers = (numCPUs/2)+1;
var output_file = path.join(tmpdir, 'message.log');
var output_file_pid = output_file + '.pid';

// Retrieve request source address
function getRemoteAddress(req) {
    if (req.headers['x-forwarded-for']) {
        return req.headers['x-forwarded-for'];
    }
    return req.connection.remoteAddress;
}

// Retrieve request user-agent
function getRemoteAgent(req) {
    if (req.headers['user-agent']) {
        return req.headers['user-agent'];
    }
    return null;
}

// Retrieve remote user
function getRemoteUser(req) {
    if (req.headers['remote_user']) {
        return req.headers['remote_user'];
    }
    return null;
}

// Return Object in string is JSON, null otherwise
function isJSON(jsonString) {
    try {
      var json = JSON.parse(jsonString);
    } catch (exception) {
      json = null;
    }
    return json;
}

// Go through all workers
function eachWorker(callback) {
  for (var id in cluster.workers) {
    callback(cluster.workers[id]);
  }
}

// Fork cluster
function setWorkers() {
    for (var i = 1; i <= nb_workers; i++) {
        cluster.fork();
    }
}

// Main -----------------------------------------------------------------------

function startServer(onReadyCallBack) {

    const program = require('commander');

    prg_package = JSON.parse(fs.readFileSync(path.join(__dirname,'package.json'), 'utf8'));
    program
        .version(prg_package.version)
        .description(prg_package.description)
        .usage('[options] <outputfile>')
        .option('-w, --workers <n>', 'how many listening workers', parseInt)
        .option('-p, --port <n>', 'listening port', parseInt)
        .arguments('<outputfile>')
            .action(function (outputfile) {
                output_file = outputfile;
            })
        .parse(process.argv);

    if (cluster.isMaster) {

        console.log(prg_package.name + " v." + prg_package.version + ' - ' + prg_package.description);
        console.log("Author: " + prg_package.author + " - Homepage: " + prg_package.homepage);
        console.log("Report bugs on " + prg_package.bugs);
        console.log(`Master process id: ${process.pid}`);

        nb_workers = program.workers || nb_workers;
        port = program.port || port;

        cluster.on('exit', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} exit with code: ${code} (signal: ${signal})`);
        });

        cluster.on('listening', (worker, code, signal) => {
        console.log(`worker ${worker.process.pid} now listening on port ${port} and writing to ${output_file}...`);
        });

        output_file_pid = output_file + '.pid';
        fs.writeFileSync(output_file_pid, process.pid);

        process.on('SIGHUP', function() {
            eachWorker(function(worker) {
                worker.kill('SIGHUP');
            })
            var d = new Date();
            var d1 = d.toISOString();
            var d2 = d1.substr(0,19).replace(/-/g,'').replace(/:/g,'').replace('T','');
            var newdir = path.dirname(output_file);
            var newname = path.basename(output_file, path.extname(output_file)) + '_' + d2 + path.extname(output_file);
            fs.rename(output_file, path.join(newdir, newname), function() {
                console.log(`${path.basename(output_file)} renamed to ${newname}`);
                setWorkers();
            });
        });

        process.on('SIGINT', function() {
            eachWorker(function(worker) {
                worker.kill('SIGINT');
            });
        });

        process.on('SIGTERM', function() {
            eachWorker(function(worker) {
                worker.kill('SIGTERM');
            });
        });

        process.on('SIGBREAK', function() {
            eachWorker(function(worker) {
                worker.kill('SIGBREAK');
            });
        });

        setWorkers();

        process.on('exit', (code) => {
            fs.unlinkSync(output_file_pid);
        });

        if (onReadyCallBack) onReadyCallBack();

    } else {

        fs.open(output_file, 'a', function(err, flogd) {

            if (err) {
                console.error("can't open output file");
                cluster.worker.kill();
            } else {
                const server = http.createServer((request, response) => {
                    if (request.method !== 'POST') {
                        response.statusCode = 405;
                        response.end();
                    } else {
                        var body = '';
                        request.on('data', function (data) {
                            body += data;
                            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
                            if (body.length > 1e6) {
                                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                                request.connection.destroy();
                            }
                        });
                        request.on('end', function () {
                            var remote_address = getRemoteAddress(request);
                            var remote_user = getRemoteUser(request);
                            var body_object = isJSON(body);
                            var remote_object = {
                                    address: remote_address,
                                    user: remote_user,
                                    agent: getRemoteAgent(request)
                            };
                            if (body_object instanceof Object) {
                                body_object.remote = remote_object;
                                body = JSON.stringify(body_object);
                            };
                            fs.write(flogd, body + '\n', function(err, written, string) {
                                if (err) {
                                    console.error("can't write to output file");
                                }
                                response.statusCode = 200;
                                response.end();
                            });
                            var continuation = (body.length > 128) ? "..." : "";
                            var message = body.substr(0, 128);
                            console.log(Date.now() +
                                " [" + remote_address +
                                "][" + cluster.worker.process.pid +
                                "] " + message + continuation
                            );
                        });

                    }
                });

                server.on('clientError', (err, socket) => {
                    socket.statusCode = 400;
                    socket.end();
                });

                server.on('close', (err, socket) => {
                    fs.close(flogd);
                });

                server.listen(port);
            }
        });
    }
}

function stopServer() {
    process.kill(process.pid, 'SIGTERM');
}

function renewServer() {
    process.kill(process.pid, 'SIGHUP');
}

module.exports = exports
exports.start = startServer;
exports.stop = stopServer;
exports.renew = renewServer;
<|endoftext|>


<commit_before>const bot = require('./bot')
const express = require('express')
const app = express()

app.post('/api', function (req, res) {
  res.send('Hello World!')
  bot.run()
})

app.get('/favicon.ico', function(req, res) {
    console.log("No favicon")
    res.status(404);
});

app.listen(80, function () {
  console.log('Example app listening on port 80!')
})
<commit_msg>Change Server Port<commit_after>const bot = require('./bot')
const express = require('express')
const app = express()

var port = process.env.PORT || 3000

app.post('/api', function (req, res) {
  res.send('Hello World!')
  bot.run()
})

app.get('/favicon.ico', function(req, res) {
    console.log("No favicon")
    res.status(404);
});

app.listen(port, function () {
  console.log('Example app listening on port 80!')
})
<|endoftext|>


<commit_before>function initIPAdress() {
    var adr = process.env.OPENSHIFT_NODEJS_IP;
    if (typeof adr === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using localhost');
            adr = 'localhost';
    }

    return adr;
}

var port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

var io = require('socket.io').use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://p-online.juanto3.me');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
}).listen(port, initIPAdress());
console.log('port: ' + port);
io.on('connection', function(socket) {
  var room = "";
  var username = "";
  console.log('connected');
  socket.on('create', function(data) {
    var username = data.username;
    function makeid() {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      for( var i=0; i < 6; i++ ) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      }
      return text;
    }
    var room = makeid();
    socket.join(room);
    socket.emit('roomShow', {room: room});
    console.log(username + ' created ' + room);
  });
  socket.on('join', function(data) {
    console.log('join');
    var room = data.room.toUpperCase();
    var username = data.username;
    socket.join(room);

    console.log(username + ' joined ' + room);
    socket.emit('roomShow', {room: room});
    io.to(room).emit('player', {username: username, socket: socket.id});
    console.log('player');
  });
  socket.on('sendPlayers', function(data) {
    socket.broadcast.to(data.socket).emit('playerList', {players: data.players});
  });
  socket.on('sendMessage', function(data) {
    socket.broadcast.to(data.room).emit('chatMessage', {message: data.message, username: data.username});
  });
  socket.on('startGame', function(data) {
    //var winner = io.sockets.adapter
  });
  socket.on('disconnect', function() {
    io.to(room).emit('playerDisconnect', {username: username, rip: true});
  });
});
<commit_msg>Fixed listener<commit_after>function initIPAdress() {
    var adr = process.env.OPENSHIFT_NODEJS_IP;
    if (typeof adr === "undefined") {
            //  Log errors on OpenShift but continue w/ 127.0.0.1 - this
            //  allows us to run/test the app locally.
            console.warn('No OPENSHIFT_NODEJS_IP var, using localhost');
            adr = 'localhost';
    }

    return adr;
}

var port      = process.env.OPENSHIFT_NODEJS_PORT || 8080;

var io = require('socket.io').listen(port, initIPAdress());
console.log('port: ' + port);
io.on('connection', function(socket) {
  var room = "";
  var username = "";
  console.log('connected');
  socket.on('create', function(data) {
    var username = data.username;
    function makeid() {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      for( var i=0; i < 6; i++ ) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      }
      return text;
    }
    var room = makeid();
    socket.join(room);
    socket.emit('roomShow', {room: room});
    console.log(username + ' created ' + room);
  });
  socket.on('join', function(data) {
    console.log('join');
    var room = data.room.toUpperCase();
    var username = data.username;
    socket.join(room);

    console.log(username + ' joined ' + room);
    socket.emit('roomShow', {room: room});
    io.to(room).emit('player', {username: username, socket: socket.id});
    console.log('player');
  });
  socket.on('sendPlayers', function(data) {
    socket.broadcast.to(data.socket).emit('playerList', {players: data.players});
  });
  socket.on('sendMessage', function(data) {
    socket.broadcast.to(data.room).emit('chatMessage', {message: data.message, username: data.username});
  });
  socket.on('startGame', function(data) {
    //var winner = io.sockets.adapter
  });
  socket.on('disconnect', function() {
    io.to(room).emit('playerDisconnect', {username: username, rip: true});
  });
});
<|endoftext|>


<commit_before>require('dotenv').config();

const express = require('express');
const morgan = require('morgan');
const path = require('path');
const cors = require('cors');
const betterErrors = require('better-express-errors');
const bodyParser = require('body-parser');
const app = express();
const router = require('./server/api');

// Don't enable CORS in production.
if (/^(dev|test)$/.test(process.env.NODE_ENV)) {
  app.use(cors());
}
if (process.env.NODE_ENV !== 'test') {
  // Don't log requests during testing
  app.use(morgan('dev'));
}
app.use(bodyParser.json());
app.use('/api', router);

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

app.listen(port);
app.use(betterErrors(app));

console.log(`Server listening on port: ${port}`);
module.exports = app;<commit_msg>comments for code<commit_after>//for API keys - create a .env file for google API
require('dotenv').config();

//middlware
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const cors = require('cors');
const betterErrors = require('better-express-errors');
const bodyParser = require('body-parser');
const app = express();
const router = require('./server/api');

// Don't enable CORS in production.
if (/^(dev|test)$/.test(process.env.NODE_ENV)) {
  app.use(cors());
}

if (process.env.NODE_ENV !== 'test') {
  // Don't log requests during testing
  app.use(morgan('dev'));
}

app.use(bodyParser.json());

// /api should be the home for all of our endpoints
app.use('/api', router);

//404 all other routes
app.use('*', (req, res) => {
  res.status(404).send();
});

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

app.listen(port);
app.use(betterErrors(app));

console.log(`Server listening on port: ${port}`);
module.exports = app;<|endoftext|>