<commit_before>// Organize this piece of shit later
var http    = require('http'),
    express = require('express'),
    agent   = require('superagent'),
    Promise = require('promise'),
    app     = express();

var port = process.env.PORT || 8080
var router = express.Router();

var urls = {
  // lastfm's URL is absolutely ridiculous why isn't JSON default wtf
  // "telegram"   : "",
  "lastfm" : "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks" +
            "&user=ltrlly&api_key=" +  process.env.LASTFM_KEY + "&format=json",
  "github"   : "https://api.github.com/users/lwwws",
  // "echo"     : ""
}

// asssssynchronous  mMMMMMM good shit
function getPage(url) {
  return new Promise(function(resolve, reject) {
    agent.get(url).end(function(err, res) {
      if (err) return reject(err)
      resolve(res.body)
    });
  })
}

var json = {
  "sleeping":false,
  "last_online":{}
}

router.get('/', function(req, res) {
  Promise.all(
    Object.keys(urls).map(function(key) {
      return getPage(urls[key]).then(function(data) {
        json.last_online[key] = data;
      })
    })
  ).then(function() {
    res.json(json)
  })
})

app.use('/', router)
app.listen(port)
<commit_msg>Okay sweet, thank you Jacob again<commit_after>// Organize this piece of shit later
var http    = require('http'),
    express = require('express'),
    agent   = require('superagent'),
    Promise = require('promise'),
    app     = express();

var port = process.env.PORT || 8080
var router = express.Router();

var urls = {
  // lastfm's URL is absolutely ridiculous why isn't JSON default wtf
  // "telegram"   : "",
  "lastfm" : "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks" +
            "&user=ltrlly&api_key=" + process.env.LASTFM_KEY + "&format=json",
  "github"   : "https://api.github.com/users/lwwws",
  // "echo"     : ""
}

// asssssynchronous  mMMMMMM good shit
function getPage(url) {
  return new Promise(function(resolve, reject) {
    agent.get(url).end(function(err, res) {
      if (err) return reject(err)
      resolve(res.body)
    });
  })
}

var json = {
  "sleeping":false,
  "last_online":{}
}

router.get('/', function(req, res) {
  Promise.all(
    Object.keys(urls).map(function(key) {
      return getPage(urls[key]).then(function(data) {
        switch(key) {
          case 'lastfm':
            json.last_online[key] = data.recenttracks.track[0].date['#text'];
            break;
          case 'github':
            json.last_online[key] = data.updated_at;
            break;
        }
      })
    })
  ).then(function() {
    res.json(json)
  })
})

app.use('/', router)
app.listen(port)
<|endoftext|>


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

"use strict";

// static server bit taken from https://gist.github.com/rpflorence/701407

var fs = require( "fs" );
var path = require( "path" );
var glob = require( "glob" );
var http = require( "http" );
var url = require( "url" );
var port = process.argv[ 2 ] || 8888;
require( "sugar" );
Object.extend();

http.createServer(function(request, response) {
    var uri = url.parse(request.url).pathname,
        filename = path.join(process.cwd(), uri);
    console.log( uri, filename );
    if ( uri === "/images" || uri === "/images/" ) {
        response.writeHead( 200, {
            "Content-Type": "application/javascript"
        } );
        response.write( "var images = " + JSON.stringify( makeMatchList( "images" ) ) );
        response.end();
    } else {
        fs.exists(filename, function(exists) {
            // should probably also return 404 for server.js
            if (!exists) {
                response.writeHead(404, {
                    "Content-Type": "text/plain"
                });
                response.write("404 Not Found\n");
                response.end();
                return;
            }

            if (fs.statSync(filename).isDirectory()) filename += '/index.html';

            fs.readFile(filename, "binary", function(err, file) {
                if (err) {
                    response.writeHead(500, {
                        "Content-Type": "text/plain"
                    });
                    response.write(err + "\n");
                    response.end();
                    return;
                }

                response.writeHead(200);
                response.write(file, "binary");
                response.end();
            });
        });
    }
}).listen( parseInt( port, 10 ) );

console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");

var makeMatchList = function( image_dir ) {
    var matches = glob.sync( "**", {
        cwd: image_dir
    } );
    matches = filterMatches( matches, image_dir );
    var map = matchesToMap( matches, image_dir );
    return map;
};

var filterMatches = function( matches, image_dir ) {
    return matches.filter( function( match ) {
        if ( match === "" ) {
            return false;
        }
        return fs.statSync( image_dir + "/" + match ).isFile();
    } );
};

var matchesToMap = function( matches, image_dir ) {
    var map = {};
    matches.each( function( match ) {
        var key = path.dirname( match ).toUpperCase();
        if ( !Object.isArray( map[ key ] ) ) {
            map[ key ] = [];
        }
	map[ key ].push( image_dir + "/" + match );
    } );
    return map;
};

makeMatchList( "images" );
<commit_msg>Fix indentation.<commit_after>#!/usr/bin/env node

"use strict";

// static server bit taken from https://gist.github.com/rpflorence/701407

var fs = require( "fs" );
var path = require( "path" );
var glob = require( "glob" );
var http = require( "http" );
var url = require( "url" );
var port = process.argv[ 2 ] || 8888;
require( "sugar" );
Object.extend();

http.createServer(function(request, response) {
    var uri = url.parse(request.url).pathname,
        filename = path.join(process.cwd(), uri);
    console.log( uri, filename );
    if ( uri === "/images" || uri === "/images/" ) {
        response.writeHead( 200, {
            "Content-Type": "application/javascript"
        } );
        response.write( "var images = " + JSON.stringify( makeMatchList( "images" ) ) );
        response.end();
    } else {
        fs.exists(filename, function(exists) {
            // should probably also return 404 for server.js
            if (!exists) {
                response.writeHead(404, {
                    "Content-Type": "text/plain"
                });
                response.write("404 Not Found\n");
                response.end();
                return;
            }

            if (fs.statSync(filename).isDirectory()) filename += '/index.html';

            fs.readFile(filename, "binary", function(err, file) {
                if (err) {
                    response.writeHead(500, {
                        "Content-Type": "text/plain"
                    });
                    response.write(err + "\n");
                    response.end();
                    return;
                }

                response.writeHead(200);
                response.write(file, "binary");
                response.end();
            });
        });
    }
}).listen( parseInt( port, 10 ) );

console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");

var makeMatchList = function( image_dir ) {
    var matches = glob.sync( "**", {
        cwd: image_dir
    } );
    matches = filterMatches( matches, image_dir );
    var map = matchesToMap( matches, image_dir );
    return map;
};

var filterMatches = function( matches, image_dir ) {
    return matches.filter( function( match ) {
        if ( match === "" ) {
            return false;
        }
        return fs.statSync( image_dir + "/" + match ).isFile();
    } );
};

var matchesToMap = function( matches, image_dir ) {
    var map = {};
    matches.each( function( match ) {
        var key = path.dirname( match ).toUpperCase();
        if ( !Object.isArray( map[ key ] ) ) {
            map[ key ] = [];
        }
        map[ key ].push( image_dir + "/" + match );
    } );
    return map;
};

makeMatchList( "images" );
<|endoftext|>


<commit_before>var express = require('express');
var _ = require('lodash');
var bodyParser = require('body-parser');
var cors = require('cors');
var pg = require('pg');
var morgan = require('morgan');
var onFinished = require('on-finished');
var communesHelper = require('./helpers/communes');
var aoc = require('./controllers/aoc');
var codesPostaux = require('./controllers/codes-postaux');
var qp = require('./controllers/quartiers-prioritaires');
var cadastre = require('./controllers/cadastre');

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

app.use(bodyParser.json());
app.use(cors());

var env = process.env.NODE_ENV;

if (env === 'production') {
    app.use(morgan(':date[clf] :req[x-real-ip] :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'));
}

if (env === 'development') {
    app.use(morgan('dev'));
}

/* Middlewares */
function pgClient(req, res, next) {
    pg.connect(process.env.PG_URI || 'postgres://localhost/apicarto', function (err, client, done) {
        if (err) return next(err);
        req.pgClient = client;
        req.pgEnd = _.once(done);
        onFinished(res, req.pgEnd);
        next();
    });
}

/* Routes */
app.post('/aoc/api/beta/aoc/in', pgClient, communesHelper.intersects({ ref: 'ign-parcellaire' }), aoc.in);
app.get('/codes-postaux/communes/:codePostal', codesPostaux.communes);
app.post('/quartiers-prioritaires/search', pgClient, qp.search);
app.use('/cadastre', cadastre({
    key: process.env.GEOPORTAIL_KEY || process.env.npm_package_config_geoportailKey,
    referer: process.env.GEOPORTAIL_REFERER || process.env.npm_package_config_geoportailReferer || 'http://localhost'
}));

/* Ready! */
app.listen(port, function () {
    console.log('Start listening on port %d', port);
});

module.exports = app;
<commit_msg>Slightly improve access log<commit_after>var express = require('express');
var _ = require('lodash');
var bodyParser = require('body-parser');
var cors = require('cors');
var pg = require('pg');
var morgan = require('morgan');
var onFinished = require('on-finished');
var communesHelper = require('./helpers/communes');
var aoc = require('./controllers/aoc');
var codesPostaux = require('./controllers/codes-postaux');
var qp = require('./controllers/quartiers-prioritaires');
var cadastre = require('./controllers/cadastre');

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

app.use(bodyParser.json());
app.use(cors());

var env = process.env.NODE_ENV;

if (env === 'production') {
    morgan.token('real-ip', req => req.headers['x-forwarded-for'].split(',')[0]);
    app.use(morgan(':date[clf] :real-ip :method :url HTTP/:http-version :status :res[content-length] - :response-time ms - :user-agent'));
}

if (env === 'development') {
    app.use(morgan('dev'));
}

/* Middlewares */
function pgClient(req, res, next) {
    pg.connect(process.env.PG_URI || 'postgres://localhost/apicarto', function (err, client, done) {
        if (err) return next(err);
        req.pgClient = client;
        req.pgEnd = _.once(done);
        onFinished(res, req.pgEnd);
        next();
    });
}

/* Routes */
app.post('/aoc/api/beta/aoc/in', pgClient, communesHelper.intersects({ ref: 'ign-parcellaire' }), aoc.in);
app.get('/codes-postaux/communes/:codePostal', codesPostaux.communes);
app.post('/quartiers-prioritaires/search', pgClient, qp.search);
app.use('/cadastre', cadastre({
    key: process.env.GEOPORTAIL_KEY || process.env.npm_package_config_geoportailKey,
    referer: process.env.GEOPORTAIL_REFERER || process.env.npm_package_config_geoportailReferer || 'http://localhost'
}));

/* Ready! */
app.listen(port, function () {
    console.log('Start listening on port %d', port);
});

module.exports = app;
<|endoftext|>


<commit_before>#!/bin/env node
/* server
 */

module.exports = (function() {
  'use strict';

  var express = require('express');
  var expressSession = require('express-session');

  // validation library for whatever comes in through the forms
  var expressValidator = require('express-validator');

  //var async = require('async');
  var fs = require('fs');

  var sugar = require('sugar');

  var bodyParser = require('body-parser');
  var errorhandler = require('errorhandler');
  var flash = require('connect-flash');
  var passport = require('passport');
  var basicAuth = require('basic-auth-connect');
  var LocalStrategy = require('passport-local').Strategy;
  var moment   = require('moment');

  var app = express();

  app.use(expressSession({
    secret: 'mySecretKey',
    saveUninitialized: true,
    resave: true
  }));

  app.use(function(req, res, next){
    res.locals.moment = moment;
    next();
  });

  app.use(flash());
  app.use(passport.initialize());
  app.use(passport.session());

  // Chekcs if user is authenticated
  var isAuthenticated = function (req,res,next){
    if (req.hostname === 'localhost') { // req.hostname === 'localhost'

     db.users.findOne({
       username: 'sebi.kovacs+102@gmail.com'
     }, function (err, user) {

       req.user = user;
       return next()

     })

    } else {

     if (req.isAuthenticated()){
       return next();
     } else {
       res.redirect("/signin");
     }
    }
  };

  var adminAuth = basicAuth(function(user, pass, callback) {
    var user, pass;
    var admin = false;

    // if(process.env.OPENSHIFT_APP_NAME) {
    //   admin = (user === config.superadmin.user && pass === config.superadmin.pass);
    // } else {
    //   admin = true;
    // }

    admin = (user === config.superadmin.user && pass === config.superadmin.pass);

    callback(null, admin);
  });

  // configs
  var config = require('./data/config.js');

  // config express
  app.use(bodyParser.json({
    limit: '50mb'
  }));

  app.use(bodyParser.urlencoded({
    limit: '50mb',
    extended: true
  }));

  app.use(expressValidator());

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

  app.use(express.static(__dirname + config.publicDir));

  app.use(errorhandler());

  // allow self-signed ssl
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

  // CORS headers
  app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');

    next();
  });

  // datastore
  var Datastore = require('nedb');
  var db = {};

  db.alerts = new Datastore({
    filename: config.dataDir + config.dbDir + '/alerts.db',
    autoload: true
  });

  db.events = new Datastore({
    filename: config.dataDir + config.dbDir + '/events.db',
    autoload: true
  });

  db.users = new Datastore({
    filename: config.dataDir + config.dbDir + '/users.db',
    autoload: true
  });

  db.calendars = new Datastore({
    filename: config.dataDir + config.dbDir + '/calendars.db',
    autoload: true
  });

  db.contacts = new Datastore({
    filename: config.dataDir + config.dbDir + '/contacts.db',
    autoload: true
  });

  db.templates = new Datastore({
    filename: config.dataDir + config.dbDir + '/templates.db',
    autoload: true
  });

  // alert routes
  var events = require('./app/controllers/events.js')(config, db);
  var superadmin = require('./app/controllers/superadmin.js')(config, db);

  app.get('/api/1/events/:calendarId', events.list);
  app.post('/api/1/:calendarId/events/', events.create);
  app.put('/api/1/:calendarId/events/', events.update);
  app.delete('/api/1/:calendarId/events/:eventId', events.remove);

  // send reminders
  app.get('/api/1/event/remind/', events.remind);

  // dashboard routes
  var dashboard = require('./app/controllers/dashboard.js')(config, db);

  app.get('/dashboard', isAuthenticated , dashboard.view);

  // auth routes
  var auth = require('./app/controllers/authenticate.js')(config, db);

  app.get('/signup', auth.signupView);

  app.post('/signup', auth.signup);

  app.get('/signin', auth.signinView);

  app.post('/signin', auth.signin);

  /* Settings routes
  */
  var settings = require('./app/controllers/settings.js')(config, db);

  app.get('/settings/account', isAuthenticated, settings.view);

  app.post('/settings/account', isAuthenticated, settings.update);

  app.post('/onboarding', isAuthenticated, settings.updateOnboarding);

  app.get('/api/1/settings/:userId', isAuthenticated, settings.getUser);

  /* Backend templates routes
  */
  app.get('/settings/templates', isAuthenticated, settings.templatesView)
  app.post('/settings/templates', isAuthenticated, settings.addTemplate)
  app.get('/settings/templates/:id', isAuthenticated, settings.deleteTemplate)
  app.get('/t/templatesJson/:userId', isAuthenticated, settings.templatesJson)

  /* Contacts Routes
  */
  var contacts = require('./app/controllers/contacts.js')(config, db);

  app.get('/api/1/contacts/:calendarId', isAuthenticated, contacts.list);
  app.post('/api/1/contacts/:calendarId', isAuthenticated, contacts.updateContact);
  app.get('/api/1/contacts/:calendarId/delete/:contactId', isAuthenticated, contacts.deleteContact);

  /* Superadmin routes
  */
  app.get('/sa/dashboard', adminAuth, superadmin.dashboard);
  app.get('/sa/delete-user/:userId', adminAuth, superadmin.deleteUser);

  // Logout
  app.get('/signout', function(req, res) {
    req.logout();
    res.redirect('/signin');
  });

  // start express server
  app.listen(config.port, config.ipAddress, function() {
    console.log(
      '%s: Node server started on %s:%d ...',
      Date(Date.now()),
      config.ipAddress,
      config.port
    );
  });

  return app;

}());
<commit_msg>update<commit_after>#!/bin/env node
/* server
 */

module.exports = (function() {
  'use strict';

  var express = require('express');
  var expressSession = require('express-session');

  // validation library for whatever comes in through the forms
  var expressValidator = require('express-validator');

  //var async = require('async');
  var fs = require('fs');

  var sugar = require('sugar');

  var bodyParser = require('body-parser');
  var errorhandler = require('errorhandler');
  var flash = require('connect-flash');
  var passport = require('passport');
  var basicAuth = require('basic-auth-connect');
  var LocalStrategy = require('passport-local').Strategy;
  var moment   = require('moment');

  var app = express();

  app.use(expressSession({
    secret: 'mySecretKey',
    saveUninitialized: true,
    resave: true
  }));

  app.use(function(req, res, next){
    res.locals.moment = moment;
    next();
  });

  app.use(flash());
  app.use(passport.initialize());
  app.use(passport.session());

  // Chekcs if user is authenticated
  var isAuthenticated = function (req,res,next){
    if (req.hostname === 'localhost') { // req.hostname === 'localhost'

     db.users.findOne({
       username: 'sebi.kovacs+102@gmail.com'
     }, function (err, user) {

       req.user = user;
       return next()

     })

    } else {

     if (req.isAuthenticated()){
       return next();
     } else {
       res.redirect("/signin");
     }
    }
  };

  var adminAuth = basicAuth(function(user, pass, callback) {
    var user, pass;
    var admin = false;

    // if(process.env.OPENSHIFT_APP_NAME) {
    //   admin = (user === config.superadmin.user && pass === config.superadmin.pass);
    // } else {
    //   admin = true;
    // }

    admin = (user === config.superadmin.user && pass === config.superadmin.pass);

    callback(null, admin);
  });

  // configs
  var config;

  if (process.env.OPENSHIFT_APP_NAME) {
    config = require('../data/config.js');
  } else {
    config = require('./data/config.js');
  }

  // config express
  app.use(bodyParser.json({
    limit: '50mb'
  }));

  app.use(bodyParser.urlencoded({
    limit: '50mb',
    extended: true
  }));

  app.use(expressValidator());

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

  app.use(express.static(__dirname + config.publicDir));

  app.use(errorhandler());

  // allow self-signed ssl
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

  // CORS headers
  app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');

    next();
  });

  // datastore
  var Datastore = require('nedb');
  var db = {};

  db.alerts = new Datastore({
    filename: config.dataDir + config.dbDir + '/alerts.db',
    autoload: true
  });

  db.events = new Datastore({
    filename: config.dataDir + config.dbDir + '/events.db',
    autoload: true
  });

  db.users = new Datastore({
    filename: config.dataDir + config.dbDir + '/users.db',
    autoload: true
  });

  db.calendars = new Datastore({
    filename: config.dataDir + config.dbDir + '/calendars.db',
    autoload: true
  });

  db.contacts = new Datastore({
    filename: config.dataDir + config.dbDir + '/contacts.db',
    autoload: true
  });

  db.templates = new Datastore({
    filename: config.dataDir + config.dbDir + '/templates.db',
    autoload: true
  });

  // alert routes
  var events = require('./app/controllers/events.js')(config, db);
  var superadmin = require('./app/controllers/superadmin.js')(config, db);

  app.get('/api/1/events/:calendarId', events.list);
  app.post('/api/1/:calendarId/events/', events.create);
  app.put('/api/1/:calendarId/events/', events.update);
  app.delete('/api/1/:calendarId/events/:eventId', events.remove);

  // send reminders
  app.get('/api/1/event/remind/', events.remind);

  // dashboard routes
  var dashboard = require('./app/controllers/dashboard.js')(config, db);

  app.get('/dashboard', isAuthenticated , dashboard.view);

  // auth routes
  var auth = require('./app/controllers/authenticate.js')(config, db);

  app.get('/signup', auth.signupView);

  app.post('/signup', auth.signup);

  app.get('/signin', auth.signinView);

  app.post('/signin', auth.signin);

  /* Settings routes
  */
  var settings = require('./app/controllers/settings.js')(config, db);

  app.get('/settings/account', isAuthenticated, settings.view);

  app.post('/settings/account', isAuthenticated, settings.update);

  app.post('/onboarding', isAuthenticated, settings.updateOnboarding);

  app.get('/api/1/settings/:userId', isAuthenticated, settings.getUser);

  /* Backend templates routes
  */
  app.get('/settings/templates', isAuthenticated, settings.templatesView)
  app.post('/settings/templates', isAuthenticated, settings.addTemplate)
  app.get('/settings/templates/:id', isAuthenticated, settings.deleteTemplate)
  app.get('/t/templatesJson/:userId', isAuthenticated, settings.templatesJson)

  /* Contacts Routes
  */
  var contacts = require('./app/controllers/contacts.js')(config, db);

  app.get('/api/1/contacts/:calendarId', isAuthenticated, contacts.list);
  app.post('/api/1/contacts/:calendarId', isAuthenticated, contacts.updateContact);
  app.get('/api/1/contacts/:calendarId/delete/:contactId', isAuthenticated, contacts.deleteContact);

  /* Superadmin routes
  */
  app.get('/sa/dashboard', adminAuth, superadmin.dashboard);
  app.get('/sa/delete-user/:userId', adminAuth, superadmin.deleteUser);

  // Logout
  app.get('/signout', function(req, res) {
    req.logout();
    res.redirect('/signin');
  });

  // start express server
  app.listen(config.port, config.ipAddress, function() {
    console.log(
      '%s: Node server started on %s:%d ...',
      Date(Date.now()),
      config.ipAddress,
      config.port
    );
  });

  return app;

}());
<|endoftext|>


<commit_before>var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var compression = require('compression');
var favicon = require('serve-favicon');
var logger = require('morgan');
var async = require('async');
var colors = require('colors');
var mongoose = require('mongoose');
var request = require('request');
var React = require('react');
var ReactDOM = require('react-dom');
var Router = require('react-router');
var swig  = require('swig');
var xml2js = require('xml2js');
var _ = require('underscore');

var config = require('./config');
var routes = require('./app/routes');
var Character = require('./models/character');

var app = express();

mongoose.connect(config.database);
mongoose.connection.on('error', function() {
  console.info('Error: Could not connect to MongoDB. Did you forget to run `mongod`?'.red);
});

app.set('port', process.env.PORT || 3000);
app.use(compression());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(favicon(path.join(__dirname, 'public', 'favicon.png')));
app.use(express.static(path.join(__dirname, 'public')));

/**
 * GET /api/characters
 * Returns 2 random characters of the same gender that have not been voted yet.
 */
app.get('/api/characters', function(req, res, next) {
  var choices = ['Female', 'Male'];
  var randomGender = _.sample(choices);

  Character.find({ random: { $near: [Math.random(), 0] } })
    .where('voted', false)
    .where('gender', randomGender)
    .limit(2)
    .exec(function(err, characters) {
      if (err) return next(err);

      if (characters.length === 2) {
        return res.send(characters);
      }

      var oppositeGender = _.first(_.without(choices, randomGender));

      Character
        .find({ random: { $near: [Math.random(), 0] } })
        .where('voted', false)
        .where('gender', oppositeGender)
        .limit(2)
        .exec(function(err, characters) {
          if (err) return next(err);

          if (characters.length === 2) {
            return res.send(characters);
          }

          Character.update({}, { $set: { voted: false } }, { multi: true }, function(err) {
            if (err) return next(err);
            res.send([]);
          });
        });
    });
});

/**
 * PUT /api/characters
 * Update winning and losing count for both characters.
 */
app.put('/api/characters', function(req, res, next) {
  var winner = req.body.winner;
  var loser = req.body.loser;

  if (!winner || !loser) {
    return res.status(400).send({ message: 'Voting requires two characters.' });
  }

  if (winner === loser) {
    return res.status(400).send({ message: 'Cannot vote for and against the same character.' });
  }

  async.parallel([
      function(callback) {
        Character.findOne({ characterId: winner }, function(err, winner) {
          callback(err, winner);
        });
      },
      function(callback) {
        Character.findOne({ characterId: loser }, function(err, loser) {
          callback(err, loser);
        });
      }
    ],
    function(err, results) {
      if (err) return next(err);

      var winner = results[0];
      var loser = results[1];

      if (!winner || !loser) {
        return res.status(404).send({ message: 'One of the characters no longer exists.' });
      }

      if (winner.voted || loser.voted) {
        return res.status(200).end();
      }

      async.parallel([
        function(callback) {
          winner.wins++;
          winner.voted = true;
          winner.random = [Math.random(), 0];
          winner.save(function(err) {
            callback(err);
          });
        },
        function(callback) {
          loser.losses++;
          loser.voted = true;
          loser.random = [Math.random(), 0];
          loser.save(function(err) {
            callback(err);
          });
        }
      ], function(err) {
        if (err) return next(err);
        res.status(200).end();
      });
    });
});

/**
 * GET /api/characters/shame
 * Returns 100 lowest ranked characters.
 */
app.get('/api/characters/shame', function(req, res, next) {
  Character
    .find()
    .sort('-losses')
    .limit(100)
    .exec(function(err, characters) {
      if (err) return next(err);
      res.send(characters);
    });
});

/**
 * GET /api/characters/top
 * Return 100 highest ranked characters. Filter by gender, race and bloodline.
 */
app.get('/api/characters/top', function(req, res, next) {
  var params = req.query;
  var conditions = {};

  _.each(params, function(value, key) {
    conditions[key] = new RegExp('^' + value + '$', 'i');
  });

  Character
    .find(conditions)
    .sort('-wins')
    .limit(100)
    .exec(function(err, characters) {
      if (err) return next(err);

      characters.sort(function(a, b) {
        if (a.wins / (a.wins + a.losses) < b.wins / (b.wins + b.losses)) { return 1; }
        if (a.wins / (a.wins + a.losses) > b.wins / (b.wins + b.losses)) { return -1; }
        return 0;
      });

      res.send(characters);
    });
});

/**
 * GET /api/characters/count
 * Returns the total number of characters.
 */
app.get('/api/characters/count', function(req, res, next) {
  Character.count({}, function(err, count) {
    if (err) return next(err);
    res.send({ count: count });
  });
});

/**
 * GET /api/characters/search
 * Looks up a character by name. (case-insensitive)
 */
app.get('/api/characters/search', function(req, res, next) {
  var characterName = new RegExp(req.query.name, 'i');

  Character.findOne({ name: characterName }, function(err, character) {
    if (err) return next(err);

    if (!character) {
      return res.status(404).send({ message: 'Character not found.' });
    }

    res.send(character);
  });
});

/**
 * GET /api/characters/:id
 * Returns detailed character information.
 */
app.get('/api/characters/:id', function(req, res, next) {
  var id = req.params.id;

  Character.findOne({ characterId: id }, function(err, character) {
    if (err) return next(err);

    if (!character) {
      return res.status(404).send({ message: 'Character not found.' });
    }

    res.send(character);
  });
});

/**
 * POST /api/characters
 * Adds new character to the database.
 */
app.post('/api/characters', function(req, res, next) {
  var gender = req.body.gender;
  var characterName = req.body.name;
  var characterIdLookupUrl = 'https://api.eveonline.com/eve/CharacterID.xml.aspx?names=' + characterName;

  var parser = new xml2js.Parser();

  async.waterfall([
    function(callback) {
      request.get(characterIdLookupUrl, function(err, request, xml) {
        if (err) return next(err);
        parser.parseString(xml, function(err, parsedXml) {
          if (err) return next(err);
          try {
            var characterId = parsedXml.eveapi.result[0].rowset[0].row[0].$.characterID;

            Character.findOne({ characterId: characterId }, function(err, character) {
              if (err) return next(err);

              if (character) {
                return res.status(409).send({ message: character.name + ' is already in the database.' });
              }

              callback(err, characterId);
            });
          } catch (e) {
            return res.status(400).send({ message: 'XML Parse Error' });
          }
        });
      });
    },
    function(characterId) {
      var characterInfoUrl = 'https://api.eveonline.com/eve/CharacterInfo.xml.aspx?characterID=' + characterId;

      request.get({ url: characterInfoUrl }, function(err, request, xml) {
        if (err) return next(err);
        parser.parseString(xml, function(err, parsedXml) {
          if (err) return res.send(err);
          try {
            var name = parsedXml.eveapi.result[0].characterName[0];
            var race = parsedXml.eveapi.result[0].race[0];
            var bloodline = parsedXml.eveapi.result[0].bloodline[0];

            var character = new Character({
              characterId: characterId,
              name: name,
              race: race,
              bloodline: bloodline,
              gender: gender,
              random: [Math.random(), 0]
            });

            character.save(function(err) {
              if (err) return next(err);
              res.send({ message: characterName + ' has been added successfully!' });
            });
          } catch (e) {
            res.status(404).send({ message: characterName + ' is not a registered citizen of New Eden.' });
          }
        });
      });
    }
  ]);
});

/**
 * GET /api/stats
 * Returns characters statistics.
 */
app.get('/api/stats', function(req, res, next) {
  async.parallel([
      function(callback) {
        Character.count({}, function(err, count) {
          callback(err, count);
        });
      },
      function(callback) {
        Character.count({ race: 'Amarr' }, function(err, amarrCount) {
          callback(err, amarrCount);
        });
      },
      function(callback) {
        Character.count({ race: 'Caldari' }, function(err, caldariCount) {
          callback(err, caldariCount);
        });
      },
      function(callback) {
        Character.count({ race: 'Gallente' }, function(err, gallenteCount) {
          callback(err, gallenteCount);
        });
      },
      function(callback) {
        Character.count({ race: 'Minmatar' }, function(err, minmatarCount) {
          callback(err, minmatarCount);
        });
      },
      function(callback) {
        Character.count({ gender: 'Male' }, function(err, maleCount) {
          callback(err, maleCount);
        });
      },
      function(callback) {
        Character.count({ gender: 'Female' }, function(err, femaleCount) {
          callback(err, femaleCount);
        });
      },
      function(callback) {
        Character.aggregate({ $group: { _id: null, total: { $sum: '$wins' } } }, function(err, totalVotes) {
            var total = totalVotes.length ? totalVotes[0].total : 0;
            callback(err, total);
          }
        );
      },
      function(callback) {
        Character
          .find()
          .sort('-wins')
          .limit(100)
          .select('race')
          .exec(function(err, characters) {
            if (err) return next(err);

            var raceCount = _.countBy(characters, function(character) { return character.race; });
            var max = _.max(raceCount, function(race) { return race });
            var inverted = _.invert(raceCount);
            var topRace = inverted[max];
            var topCount = raceCount[topRace];

            callback(err, { race: topRace, count: topCount });
          });
      },
      function(callback) {
        Character
          .find()
          .sort('-wins')
          .limit(100)
          .select('bloodline')
          .exec(function(err, characters) {
            if (err) return next(err);

            var bloodlineCount = _.countBy(characters, function(character) { return character.bloodline; });
            var max = _.max(bloodlineCount, function(bloodline) { return bloodline });
            var inverted = _.invert(bloodlineCount);
            var topBloodline = inverted[max];
            var topCount = bloodlineCount[topBloodline];

            callback(err, { bloodline: topBloodline, count: topCount });
          });
      }
    ],
    function(err, results) {
      if (err) return next(err);

      res.send({
        totalCount: results[0],
        amarrCount: results[1],
        caldariCount: results[2],
        gallenteCount: results[3],
        minmatarCount: results[4],
        maleCount: results[5],
        femaleCount: results[6],
        totalVotes: results[7],
        leadingRace: results[8],
        leadingBloodline: results[9]
      });
    });
});

/**
 * POST /api/report
 * Reports a character. Character is removed after 4 reports.
 */
app.post('/api/report', function(req, res, next) {
  var characterId = req.body.characterId;

  Character.findOne({ characterId: characterId }, function(err, character) {
    if (err) return next(err);

    if (!character) {
      return res.status(404).send({ message: 'Character not found.' });
    }

    character.reports++;

    if (character.reports > 4) {
      character.remove();
      return res.send({ message: character.name + ' has been deleted.' });
    }

    character.save(function(err) {
      if (err) return next(err);
      res.send({ message: character.name + ' has been reported.' });
    });
  });
});

app.use(function(req, res) {
  Router.run(routes, req.path, function(Handler) {
    var html = React.renderToString(React.createElement(Handler));
    var page = swig.renderFile('views/index.html', { html: html });
    res.send(page);
  });
});

app.use(function(err, req, res, next) {
  console.log(err.stack.red);
  res.status(err.status || 500);
  res.send({ message: err.message });
});

/**
 * Socket.io stuff.
 */
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var onlineUsers = 0;

io.sockets.on('connection', function(socket) {
  onlineUsers++;

  io.sockets.emit('onlineUsers', { onlineUsers: onlineUsers });

  socket.on('disconnect', function() {
    onlineUsers--;
    io.sockets.emit('onlineUsers', { onlineUsers: onlineUsers });
  });
});

server.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});<commit_msg>react-router 1.0 server-side updates<commit_after>var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');
var compression = require('compression');
var favicon = require('serve-favicon');
var logger = require('morgan');
var async = require('async');
var colors = require('colors');
var mongoose = require('mongoose');
var request = require('request');
var React = require('react');
var ReactDOM = require('react-dom/server');
var Router = require('react-router');
var RoutingContext = Router.RoutingContext;
var swig  = require('swig');
var xml2js = require('xml2js');
var _ = require('underscore');

var config = require('./config');
var routes = require('./app/routes');
var Character = require('./models/character');

var app = express();

mongoose.connect(config.database);
mongoose.connection.on('error', function() {
  console.info('Error: Could not connect to MongoDB. Did you forget to run `mongod`?'.red);
});

app.set('port', process.env.PORT || 3000);
app.use(compression());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(favicon(path.join(__dirname, 'public', 'favicon.png')));
app.use(express.static(path.join(__dirname, 'public')));

/**
 * GET /api/characters
 * Returns 2 random characters of the same gender that have not been voted yet.
 */
app.get('/api/characters', function(req, res, next) {
  var choices = ['Female', 'Male'];
  var randomGender = _.sample(choices);

  Character.find({ random: { $near: [Math.random(), 0] } })
    .where('voted', false)
    .where('gender', randomGender)
    .limit(2)
    .exec(function(err, characters) {
      if (err) return next(err);

      if (characters.length === 2) {
        return res.send(characters);
      }

      var oppositeGender = _.first(_.without(choices, randomGender));

      Character
        .find({ random: { $near: [Math.random(), 0] } })
        .where('voted', false)
        .where('gender', oppositeGender)
        .limit(2)
        .exec(function(err, characters) {
          if (err) return next(err);

          if (characters.length === 2) {
            return res.send(characters);
          }

          Character.update({}, { $set: { voted: false } }, { multi: true }, function(err) {
            if (err) return next(err);
            res.send([]);
          });
        });
    });
});

/**
 * PUT /api/characters
 * Update winning and losing count for both characters.
 */
app.put('/api/characters', function(req, res, next) {
  var winner = req.body.winner;
  var loser = req.body.loser;

  if (!winner || !loser) {
    return res.status(400).send({ message: 'Voting requires two characters.' });
  }

  if (winner === loser) {
    return res.status(400).send({ message: 'Cannot vote for and against the same character.' });
  }

  async.parallel([
      function(callback) {
        Character.findOne({ characterId: winner }, function(err, winner) {
          callback(err, winner);
        });
      },
      function(callback) {
        Character.findOne({ characterId: loser }, function(err, loser) {
          callback(err, loser);
        });
      }
    ],
    function(err, results) {
      if (err) return next(err);

      var winner = results[0];
      var loser = results[1];

      if (!winner || !loser) {
        return res.status(404).send({ message: 'One of the characters no longer exists.' });
      }

      if (winner.voted || loser.voted) {
        return res.status(200).end();
      }

      async.parallel([
        function(callback) {
          winner.wins++;
          winner.voted = true;
          winner.random = [Math.random(), 0];
          winner.save(function(err) {
            callback(err);
          });
        },
        function(callback) {
          loser.losses++;
          loser.voted = true;
          loser.random = [Math.random(), 0];
          loser.save(function(err) {
            callback(err);
          });
        }
      ], function(err) {
        if (err) return next(err);
        res.status(200).end();
      });
    });
});

/**
 * GET /api/characters/shame
 * Returns 100 lowest ranked characters.
 */
app.get('/api/characters/shame', function(req, res, next) {
  Character
    .find()
    .sort('-losses')
    .limit(100)
    .exec(function(err, characters) {
      if (err) return next(err);
      res.send(characters);
    });
});

/**
 * GET /api/characters/top
 * Return 100 highest ranked characters. Filter by gender, race and bloodline.
 */
app.get('/api/characters/top', function(req, res, next) {
  var params = req.query;
  var conditions = {};

  _.each(params, function(value, key) {
    conditions[key] = new RegExp('^' + value + '$', 'i');
  });

  Character
    .find(conditions)
    .sort('-wins')
    .limit(100)
    .exec(function(err, characters) {
      if (err) return next(err);

      characters.sort(function(a, b) {
        if (a.wins / (a.wins + a.losses) < b.wins / (b.wins + b.losses)) { return 1; }
        if (a.wins / (a.wins + a.losses) > b.wins / (b.wins + b.losses)) { return -1; }
        return 0;
      });

      res.send(characters);
    });
});

/**
 * GET /api/characters/count
 * Returns the total number of characters.
 */
app.get('/api/characters/count', function(req, res, next) {
  Character.count({}, function(err, count) {
    if (err) return next(err);
    res.send({ count: count });
  });
});

/**
 * GET /api/characters/search
 * Looks up a character by name. (case-insensitive)
 */
app.get('/api/characters/search', function(req, res, next) {
  var characterName = new RegExp(req.query.name, 'i');

  Character.findOne({ name: characterName }, function(err, character) {
    if (err) return next(err);

    if (!character) {
      return res.status(404).send({ message: 'Character not found.' });
    }

    res.send(character);
  });
});

/**
 * GET /api/characters/:id
 * Returns detailed character information.
 */
app.get('/api/characters/:id', function(req, res, next) {
  var id = req.params.id;

  Character.findOne({ characterId: id }, function(err, character) {
    if (err) return next(err);

    if (!character) {
      return res.status(404).send({ message: 'Character not found.' });
    }

    res.send(character);
  });
});

/**
 * POST /api/characters
 * Adds new character to the database.
 */
app.post('/api/characters', function(req, res, next) {
  var gender = req.body.gender;
  var characterName = req.body.name;
  var characterIdLookupUrl = 'https://api.eveonline.com/eve/CharacterID.xml.aspx?names=' + characterName;

  var parser = new xml2js.Parser();

  async.waterfall([
    function(callback) {
      request.get(characterIdLookupUrl, function(err, request, xml) {
        if (err) return next(err);
        parser.parseString(xml, function(err, parsedXml) {
          if (err) return next(err);
          try {
            var characterId = parsedXml.eveapi.result[0].rowset[0].row[0].$.characterID;

            Character.findOne({ characterId: characterId }, function(err, character) {
              if (err) return next(err);

              if (character) {
                return res.status(409).send({ message: character.name + ' is already in the database.' });
              }

              callback(err, characterId);
            });
          } catch (e) {
            return res.status(400).send({ message: 'XML Parse Error' });
          }
        });
      });
    },
    function(characterId) {
      var characterInfoUrl = 'https://api.eveonline.com/eve/CharacterInfo.xml.aspx?characterID=' + characterId;

      request.get({ url: characterInfoUrl }, function(err, request, xml) {
        if (err) return next(err);
        parser.parseString(xml, function(err, parsedXml) {
          if (err) return res.send(err);
          try {
            var name = parsedXml.eveapi.result[0].characterName[0];
            var race = parsedXml.eveapi.result[0].race[0];
            var bloodline = parsedXml.eveapi.result[0].bloodline[0];

            var character = new Character({
              characterId: characterId,
              name: name,
              race: race,
              bloodline: bloodline,
              gender: gender,
              random: [Math.random(), 0]
            });

            character.save(function(err) {
              if (err) return next(err);
              res.send({ message: characterName + ' has been added successfully!' });
            });
          } catch (e) {
            res.status(404).send({ message: characterName + ' is not a registered citizen of New Eden.' });
          }
        });
      });
    }
  ]);
});

/**
 * GET /api/stats
 * Returns characters statistics.
 */
app.get('/api/stats', function(req, res, next) {
  async.parallel([
      function(callback) {
        Character.count({}, function(err, count) {
          callback(err, count);
        });
      },
      function(callback) {
        Character.count({ race: 'Amarr' }, function(err, amarrCount) {
          callback(err, amarrCount);
        });
      },
      function(callback) {
        Character.count({ race: 'Caldari' }, function(err, caldariCount) {
          callback(err, caldariCount);
        });
      },
      function(callback) {
        Character.count({ race: 'Gallente' }, function(err, gallenteCount) {
          callback(err, gallenteCount);
        });
      },
      function(callback) {
        Character.count({ race: 'Minmatar' }, function(err, minmatarCount) {
          callback(err, minmatarCount);
        });
      },
      function(callback) {
        Character.count({ gender: 'Male' }, function(err, maleCount) {
          callback(err, maleCount);
        });
      },
      function(callback) {
        Character.count({ gender: 'Female' }, function(err, femaleCount) {
          callback(err, femaleCount);
        });
      },
      function(callback) {
        Character.aggregate({ $group: { _id: null, total: { $sum: '$wins' } } }, function(err, totalVotes) {
            var total = totalVotes.length ? totalVotes[0].total : 0;
            callback(err, total);
          }
        );
      },
      function(callback) {
        Character
          .find()
          .sort('-wins')
          .limit(100)
          .select('race')
          .exec(function(err, characters) {
            if (err) return next(err);

            var raceCount = _.countBy(characters, function(character) { return character.race; });
            var max = _.max(raceCount, function(race) { return race });
            var inverted = _.invert(raceCount);
            var topRace = inverted[max];
            var topCount = raceCount[topRace];

            callback(err, { race: topRace, count: topCount });
          });
      },
      function(callback) {
        Character
          .find()
          .sort('-wins')
          .limit(100)
          .select('bloodline')
          .exec(function(err, characters) {
            if (err) return next(err);

            var bloodlineCount = _.countBy(characters, function(character) { return character.bloodline; });
            var max = _.max(bloodlineCount, function(bloodline) { return bloodline });
            var inverted = _.invert(bloodlineCount);
            var topBloodline = inverted[max];
            var topCount = bloodlineCount[topBloodline];

            callback(err, { bloodline: topBloodline, count: topCount });
          });
      }
    ],
    function(err, results) {
      if (err) return next(err);

      res.send({
        totalCount: results[0],
        amarrCount: results[1],
        caldariCount: results[2],
        gallenteCount: results[3],
        minmatarCount: results[4],
        maleCount: results[5],
        femaleCount: results[6],
        totalVotes: results[7],
        leadingRace: results[8],
        leadingBloodline: results[9]
      });
    });
});

/**
 * POST /api/report
 * Reports a character. Character is removed after 4 reports.
 */
app.post('/api/report', function(req, res, next) {
  var characterId = req.body.characterId;

  Character.findOne({ characterId: characterId }, function(err, character) {
    if (err) return next(err);

    if (!character) {
      return res.status(404).send({ message: 'Character not found.' });
    }

    character.reports++;

    if (character.reports > 4) {
      character.remove();
      return res.send({ message: character.name + ' has been deleted.' });
    }

    character.save(function(err) {
      if (err) return next(err);
      res.send({ message: character.name + ' has been reported.' });
    });
  });
});

app.use(function(req, res) {
  Router.match({ routes: routes, location: req.url }, function(err, redirectLocation, renderProps) {
    if (err) {
      res.send(500, err.message)
    } else if (redirectLocation) {
      res.redirect(302, redirectLocation.pathname + redirectLocation.search)
    } else if (renderProps) {
      var html = ReactDOM.renderToString(<RoutingContext {...renderProps} />);
      var page = swig.renderFile('views/index.html', { html: html });
      res.send(200, page);
    } else {
      res.send(404, 'Page Not Found')
    }
  });
});

app.use(function(err, req, res, next) {
  console.log(err.stack.red);
  res.status(err.status || 500);
  res.send({ message: err.message });
});

/**
 * Socket.io stuff.
 */
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var onlineUsers = 0;

io.sockets.on('connection', function(socket) {
  onlineUsers++;

  io.sockets.emit('onlineUsers', { onlineUsers: onlineUsers });

  socket.on('disconnect', function() {
    onlineUsers--;
    io.sockets.emit('onlineUsers', { onlineUsers: onlineUsers });
  });
});

server.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});<|endoftext|>


<commit_before>var express = require('express');
var favicon = require('serve-favicon');
var morgan  = require('morgan');
var path    = require('path');
var fs      = require('fs');

var port      = process.env.NODE_PORT || 80;

var app = express();

app.use(morgan('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(favicon(path.join(__dirname, 'public', 'images', 'logo.ico')));
app.set('view engine', 'ejs');

app.get('/', function (req, res) {
    getI18N(function (err, languages) {
        if (err){
            console.log(err);
        }
        var custom = 'en';
        var selected = req.query.lang || custom;
        var customStrings;
        var selectedStrings;
        for (var i=0; i<languages.length; i++){
            if (languages[i].id == selected){
                selectedStrings = languages[i].strings;
            }
            if (languages[i].id == custom){
                customStrings = languages[i].strings;
            }
        }
        res.render('index.ejs', { languages : languages, strings : selectedStrings || customStrings });
    });
});

function getI18N(done){
    var dir = path.join(__dirname, 'public', 'i18n');
    var languages = [];

    fs.readdir(dir,function(err, files){
        if (err){
            return done(err, languages);
        }
        var count = 0;
        files.forEach(function(file){
            fs.readFile(path.join(dir, file),'utf-8',function(err, language){
                if (err){
                    return done(err, languages);
                }
                var json = JSON.parse(language);
                languages.push(json);
                if (++count == files.length){
                    return done(null, languages);
                }
            });
        });
    });
}

var server = app.listen(port, function () {
  	var host = server.address().address;
  	var port = server.address().port;
  	console.log('Fabulinus Index Server listening at http://%s:%s', host, port);
});<commit_msg>changed port to 3000<commit_after>var express = require('express');
var favicon = require('serve-favicon');
var morgan  = require('morgan');
var path    = require('path');
var fs      = require('fs');

var port      = process.env.NODE_PORT || 3000;

var app = express();

app.use(morgan('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(favicon(path.join(__dirname, 'public', 'images', 'logo.ico')));
app.set('view engine', 'ejs');

app.get('/', function (req, res) {
    getI18N(function (err, languages) {
        if (err){
            console.log(err);
        }
        var custom = 'en';
        var selected = req.query.lang || custom;
        var customStrings;
        var selectedStrings;
        for (var i=0; i<languages.length; i++){
            if (languages[i].id == selected){
                selectedStrings = languages[i].strings;
            }
            if (languages[i].id == custom){
                customStrings = languages[i].strings;
            }
        }
        res.render('index.ejs', { languages : languages, strings : selectedStrings || customStrings });
    });
});

function getI18N(done){
    var dir = path.join(__dirname, 'public', 'i18n');
    var languages = [];

    fs.readdir(dir,function(err, files){
        if (err){
            return done(err, languages);
        }
        var count = 0;
        files.forEach(function(file){
            fs.readFile(path.join(dir, file),'utf-8',function(err, language){
                if (err){
                    return done(err, languages);
                }
                var json = JSON.parse(language);
                languages.push(json);
                if (++count == files.length){
                    return done(null, languages);
                }
            });
        });
    });
}

var server = app.listen(port, function () {
  	var host = server.address().address;
  	var port = server.address().port;
  	console.log('Fabulinus Index Server listening at http://%s:%s', host, port);
});<|endoftext|>


<commit_before>/**
 * Module dependencies
 */
var express = require('express');
var bodyParser = require('body-parser');
// TODO: Enviar la configuracion de conexion a base de datos a un archivo de configuracion
var mongoose = require('mongoose');

// Choose the environment of work
var environment = 'devLocal';
var config = require('./config/environment.json')[environment];
mongoose.connect('mongodb://localhost:27017/' + config.nosqlDatabase);

// Create our express application
var app = express();

// Using body-parser in our application
app.use(bodyParser.urlencoded({
    extended: true
}));

/**
 * ROUTER
 */
// Create our Express router
var router  = express.Router();

// http://localhost:3000/api
router.get('/', function(req, res) {
    res.json({ message: 'Your API is running!' });
});
/**
 * ===============================================
 */

// Use our environment defined port or value on our config file /config/environment.json
var port = process.env.PORT || config.port;

// Register all our routes with a prefix: /api or /v1
// This poject is created to be hosted in a subdomain dedicated to authentication and authorization
// Example of an URL with the prefix: auth.happyauth.com/v0
app.use(config.version, router);

// Start the server
app.listen(port);
console.log('API running on http://localhost:' + port + config.version + '/');
<commit_msg>Implemented user routes, delete dummy endpoint and initialized passport<commit_after>/**
 * Module dependencies
 */
var express = require('express');
var bodyParser = require('body-parser');
var passport = require('passport');
// TODO: Enviar la configuracion de conexion a base de datos a un archivo de configuracion
var mongoose = require('mongoose');

// Choose the environment of work
var environment = 'devLocal';
var config = require('./config/environment.json')[environment];
mongoose.connect('mongodb://localhost:27017/' + config.nosqlDatabase);

// Create our express application
var app = express();

// Using body-parser in our application
app.use(bodyParser.urlencoded({
    extended: true
}));

// Use the passport package in our application
app.use(passport.initialize());

/**
 * ROUTER
 */
// Create our Express router
var router  = express.Router();

// Declare all routes
var userRoutes = require('./routes/users');
var authRoutes = require('./routes/auth');

// -----------------------------------
//Create endpoints handlers for /users
// /users
router.route('/users')
    .post(userRoutes.postUsers)
    .get(authRoutes.isAuthenticated, userRoutes.getUsers);
// /users/:id
router.route('/users/:id')
    .get(authRoutes.isAuthenticated, userRoutes.getUserById);
// -----------------------------------
/**
 * ===============================================
 */

// Use our environment defined port or value on our config file /config/environment.json
var port = process.env.PORT || config.port;

// Register all our routes with a prefix: /api or /v1
// This poject is created to be hosted in a subdomain dedicated to authentication and authorization
// Example of an URL with the prefix: auth.happyauth.com/v0
app.use(config.version, router);

// Start the server
app.listen(port);
console.log('API running on http://localhost:' + port + config.version + '/');
<|endoftext|>


<commit_before>var express = require('express'),
    app = express(),
    cors = require('cors'),
    compression = require('compression'),
    DB = require('./lib/db'),
    dotenv = require('dotenv'),
    csv = require('to-csv');

// load vars
dotenv.load();

app.use(compression());
app.use(cors());

app.use(function(req, res, next) {
  req.db = new DB({
    databaseURL: process.env.DATABASE_URL,
    debug: true
  });
  next();
});

app.get('/', function(req, res) {
  res.redirect(301,
    'https://io-builtwithember-addons-data.s3.amazonaws.com/addons.json');
});

app.get('/stats', function(req, res) {
  req.db.getMetric('total')
    .then(function(rows) {
      res.json(rows);
      req.db.close();
    })
    .catch(function(err) {
      console.error(err);
      res.status(500).json({error: 'error'});
      req.db.close();
    });
});

app.get('/stats.csv', function(req, res) {
  req.db.getMetric('total')
    .then(function(rows) {
      res.set('Content-Type', 'text/csv').send(csv(rows));
      req.db.close();
    })
    .catch(function(err) {
      console.error(err);
      res.status(500).json({error: 'error'});
      req.db.close();
    });
});

app.listen(process.env.PORT, function() {
  console.log('listening on port %d', process.env.PORT);
});
<commit_msg>Adds /graph which redirects to graph<commit_after>var express = require('express'),
    app = express(),
    cors = require('cors'),
    compression = require('compression'),
    DB = require('./lib/db'),
    dotenv = require('dotenv'),
    csv = require('to-csv');

// load vars
dotenv.load();

app.use(compression());
app.use(cors());

app.use(function(req, res, next) {
  req.db = new DB({
    databaseURL: process.env.DATABASE_URL,
    debug: true
  });
  next();
});

app.get('/', function(req, res) {
  res.redirect(301,
    'https://io-builtwithember-addons-data.s3.amazonaws.com/addons.json');
});

app.get('/stats', function(req, res) {
  req.db.getMetric('total')
    .then(function(rows) {
      res.json(rows);
      req.db.close();
    })
    .catch(function(err) {
      console.error(err);
      res.status(500).json({error: 'error'});
      req.db.close();
    });
});

app.get('/stats.csv', function(req, res) {
  req.db.getMetric('total')
    .then(function(rows) {
      res.set('Content-Type', 'text/csv').send(csv(rows));
      req.db.close();
    })
    .catch(function(err) {
      console.error(err);
      res.status(500).json({error: 'error'});
      req.db.close();
    });
});

app.get('/graph', function(req, res) {
  res.redirect(301,
    'http://www.charted.co/?{%22dataUrl%22:%22http://ember-addons-server.herokuapp.com/stats.csv%22,%22charts%22:[{%22type%22:%22line%22,%22title%22:%22Ember%20Addons%22,%22note%22:%22This%20chart%20shows%20the%20number%20of%20available%20addons%20for%20ember-cli%20on%20npmjs.org.%20http://emberaddons.com%22}]}');
});

app.listen(process.env.PORT, function() {
  console.log('listening on port %d', process.env.PORT);
});
<|endoftext|>


<commit_before>/*
 * fis
 * http://fis.baidu.com/
 */

'use strict';

exports.name = 'server';
exports.usage = '<command> [options]';
exports.desc = 'launch a php-cgi server';
exports.register = function(commander){

    var child_process = require('child_process');
    var spawn = child_process.spawn;

    function getConf(){
        return fis.project.getTempPath('server/conf.json');
    }

    function stop(callback){
        //del log file
        var log = fis.util(__dirname, 'log.txt');
        if(fis.util.exists(log)){
            fis.util.fs.unlinkSync(log);
        }
        var tmp = fis.util(__dirname, 'pid');
        if(fis.util.exists(tmp)){
            var pid = fis.util.fs.readFileSync(tmp, 'utf8').trim().split(/\s*,\s*/);
            var list, msg = '';
            var isWin = fis.util.isWin();
            if(isWin){
                list = spawn('tasklist');
            } else {
                list = spawn('ps');
            }
            list.stdout.on('data', function(chunk){
                msg += chunk.toString('utf8').toLowerCase();
            });
            list.on('exit', function(){
                var names = {
                    'node' : 0,
                    'java' : 1
                };
                msg.split(/[\r\n]+/).forEach(function(item){
                    var match = item.match(/\b(node|java)\b/i);
                    if(match){
                        var iMatch = item.match(/\d+/);
                        var index = match[1].toLowerCase();
                        if(iMatch && iMatch[0] == pid[names[index]]){
                            process.kill(iMatch[0], 'SIGKILL');
                        }
                    }
                });
                fis.util.fs.unlinkSync(tmp);
                if(callback){
                    callback();
                }
            });
        } else {
            if(callback){
                callback();
            }
        }
    }

    function matchVersion(str){
        var version = false;
        var reg = /\b\d+(\.\d+){2}/;
        var match = str.match(reg);
        if(match){
            version = match[0];
        }
        return version;
    }

    function open(path){
        var cmd = fis.util.escapeShellArg(path);
        if(fis.util.isWin()){
            cmd = 'start "" ' + cmd;
        } else {
            cmd = 'open ' + cmd;
        }
        child_process.exec(cmd);
    }

    function start(opt){
        var tmp = getConf();
        if(opt){
            fis.util.write(tmp, JSON.stringify(opt));
        } else {
            if(fis.util.exists(tmp)){
                opt = fis.util.readJSON(tmp);
            } else {
                opt = {};
            }
        }

        if(opt.root){
            if(fis.util.exists(opt.root)){
                if(!fis.util.isDir(opt.root)){
                    fis.log.error('document root [' + opt.root + '] is not a directory');
                }
            } else {
                fis.util.mkdir(opt.root);
            }
        } else {
            fis.log.error('invalid document root');
        }

        //check java
        process.stdout.write('checking java support : ');
        var java = spawn('java', ['-version']);
        var javaVersion = false;
        java.stderr.on('data', function(data){
            if(!javaVersion){
                javaVersion = matchVersion(data.toString('utf8'));
                if(javaVersion){
                    process.stdout.write('version ' + javaVersion + '\n');
                }
            }
        });
        java.on('error', function(err){
            fis.log.error(err);
        });
        java.on('exit', function(){
            if(javaVersion){
                //check php-cgi
                process.stdout.write('checking php-cgi support : ');
                var php = spawn(opt['php_exec'] ? opt['php_exec'] : 'php-cgi', ['-v']);
                var phpVersion = false;
                php.stdout.on('data', function(data){
                    if(!phpVersion){
                        phpVersion = matchVersion(data.toString('utf8'));
                        if(phpVersion){
                            process.stdout.write('version ' + phpVersion + '\n');
                        }
                    }
                });
                php.on('error', function(err){
                    fis.log.error(err);
                });
                php.on('exit', function(){
                    if(phpVersion){
                        process.stdout.write('starting fis-server on port : ');

                        var timeout = Math.max(opt.timeout * 1000, 5000);
                        delete opt.timeout;

                        var cmd = [
                            fis.util.escapeShellCmd(process.execPath),
                            fis.util.escapeShellArg(fis.util(__dirname, 'child.js'))
                        ].join(' ');
                        fis.util.map(opt, function(key, value){
                            if(typeof value === 'string'){
                                value = fis.util.escapeShellArg(value);
                            }
                            cmd += ' --' + key + ' ' + value;
                        });

                        //watch log
                        var log = fis.util(__dirname, '/log.txt');
                        fis.util.write(log, '');
                        var lastModified = fis.util.mtime(log).getTime();
                        var startTime = (new Date).getTime();
                        var lastIndex = 0;
                        var errMsg = 'server fails to start at port [' + opt.port + '], error: ';
                        fis.log.debug('start command : ' + cmd);
                        fis.util.nohup(cmd, { cwd : __dirname });
                        var timer = setInterval(function(){
                            if((new Date).getTime() - startTime < timeout){
                                var mtime = fis.util.mtime(log).getTime();
                                if(lastModified !== mtime){
                                    lastModified = mtime;
                                    var content = fis.util.fs.readFileSync(log).toString('utf8').substring(lastIndex);
                                    lastIndex += content.length;
                                    if(content.indexOf('Started SelectChannelConnector@') > 0){
                                        clearInterval(timer);
                                        process.stdout.write(opt.port + '\n');
                                        if(opt.rewrite){
                                            var script = fis.util(opt.root, opt.script || 'index.php');
                                            if(!fis.util.exists(script)){
                                                fis.util.copy(__dirname + '/index.php', script);
                                            }
                                        }
                                        setTimeout(function(){
                                            open('http://localhost' + (opt.port == 80 ? '/' : ':' + opt.port + '/'));
                                        }, 200);
                                    } else if(content.indexOf('Exception:') > 0) {
                                        clearInterval(timer);
                                        var match = content.match(/exception:\s+([^\r\n:]+)/i);
                                        if(match){
                                            errMsg += match[1];
                                        } else {
                                            errMsg += 'unknown';
                                        }
                                        process.stdout.write('\n');
                                        fis.log.error(errMsg);
                                    }
                                }
                            } else {
                                process.stdout.write('\n');
                                fis.log.error(errMsg + 'timeout');
                            }
                        }, 100);
                    } else {
                        fis.log.error('unsupported php-cgi environment');
                    }
                });
            } else {
                fis.log.error('unsupported java environment');
            }
        });
    }

    function getRoot(root){
        if(fis.util.exists(root)){
            if(!fis.util.isDir(root)){
                fis.log.error('invalid document root');
            }
        } else {
            fis.util.mkdir(root);
        }
        return fis.util.realpath(root);
    }

    function printObj(obj, prefix){
        prefix = prefix || '';
        for(var key in obj){
            if(obj.hasOwnProperty(key)){
                if(typeof obj[key] === 'object'){
                    printObj(obj[key], prefix + key + '.');
                } else {
                    console.log(prefix + key + '=' + obj[key]);
                }
            }
        }
    }

    function install(name, version, extract, remote){
        version = version === '*' ? 'latest' : ( version || 'latest' );
        var url = remote + '/server/' + name + '/' + version + '.tar';
        process.stdout.write('download module [' + name + '@' + version + '] ... ');
        fis.util.download(url, function(err){
            if(err){
                process.stdout.write('fail\n');
                fis.log.error( 'unable to download module [' +
                    name + '@' + version + '] from [' + url + '], error [' + err + ']');
            } else {
                process.stdout.write('ok\n');
                var pkg = fis.util(extract, 'package.json');
                if(fis.util.isFile(pkg)){
                    var info = fis.util.readJSON(pkg);
                    fis.util.fs.unlinkSync(pkg);
                    fis.util.map(info.dependencies || {}, function(name, version){
                        install(name, version, extract, remote);
                    });
                }
            }
        }, extract);
    }

    commander
        .option('-p, --port <int>', 'server listen port', parseInt, 8080)
        .option('--root <path>', 'document root', getRoot, fis.project.getTempPath('www'))
        .option('--script <name>', 'rewrite entry file name', String)
        .option('--timeout <seconds>', 'start timeout', parseInt, 15)
        .option('--php_exec <path>', 'path to php-cgi executable file', String)
        .option('--php_exec_args <args>', 'php-cgi arguments', String)
        .option('--php_fcgi_children <int>', 'the number of php-cgi processes', parseInt)
        .option('--php_fcgi_max_requests <int>', 'the max number of requests', parseInt)
        .option('--no-rewrite', 'disable rewrite feature', Boolean)
        .option('--repos <url>', 'install repository', String)
        .action(function(){
            var args = Array.prototype.slice.call(arguments);
            var options = args.pop();
            var cmd = args.shift();
            var conf = getConf();
            switch (cmd){
                case 'start':
                    var opt = {};
                    fis.util.map(options, function(key, value){
                        if(typeof value !== 'object' && key[0] !== '_'){
                            opt[key] = value;
                        }
                    });
                    stop(function(){ start(opt); });
                    break;
                case 'stop':
                    stop();
                    break;
                case 'restart':
                    stop(start);
                    break;
                case 'install':
                    var names = args.shift();
                    if(typeof names === 'string'){
                        var remote = options.repos || fis.config.get(
                            'system.repos', fis.project.DEFAULT_REMOTE_REPOS
                        ).replace(/\/$/, '') + '/server';
                        var option = {
                            extract : options['root'],
                            remote : remote
                        };
                        names.split(',').forEach(function(name){
                            name = name.split('@');
                            fis.util.install(name[0], name[1], option);
                        });
                    } else {
                        fis.log.error('invalid server component name');
                    }
                    break;
                case 'info':
                    if(fis.util.isFile(conf)){
                        conf = fis.util.readJSON(conf);
                        printObj(conf);
                    } else {
                        console.log('nothing...');
                    }
                    break;
                case 'open':
                    if(fis.util.isFile(conf)){
                        conf = fis.util.readJSON(conf);
                        if(fis.util.isDir(conf.root)){
                            open(conf.root);
                        }
                    }
                    break;
                case 'clean':
                    process.stdout.write('\n δ'.bold.yellow);
                    var now = Date.now();
                    fis.util.del(options['root'], null, /\/WEB-INF\//);
                    process.stdout.write((Date.now() - now + 'ms').green.bold);
                    process.stdout.write('\n');
                    break;
                default :
                    commander.help();
            }
        });

    commander
        .command('start')
        .description('start server');

    commander
        .command('stop')
        .description('shutdown server');

    commander
        .command('restart')
        .description('restart server');

    commander
        .command('info')
        .description('output server info');

    commander
        .command('open')
        .description('open document root directory');

    commander
        .command('clean')
        .description('delete all files in document root');

    commander
        .command('install <name>')
        .description('install server framework');
};<commit_msg>实现clean功能<commit_after>/*
 * fis
 * http://fis.baidu.com/
 */

'use strict';

exports.name = 'server';
exports.usage = '<command> [options]';
exports.desc = 'launch a php-cgi server';
exports.register = function(commander){

    var child_process = require('child_process');
    var spawn = child_process.spawn;

    function getConf(){
        return fis.project.getTempPath('server/conf.json');
    }

    function stop(callback){
        //del log file
        var log = fis.util(__dirname, 'log.txt');
        if(fis.util.exists(log)){
            fis.util.fs.unlinkSync(log);
        }
        var tmp = fis.util(__dirname, 'pid');
        if(fis.util.exists(tmp)){
            var pid = fis.util.fs.readFileSync(tmp, 'utf8').trim().split(/\s*,\s*/);
            var list, msg = '';
            var isWin = fis.util.isWin();
            if(isWin){
                list = spawn('tasklist');
            } else {
                list = spawn('ps');
            }
            list.stdout.on('data', function(chunk){
                msg += chunk.toString('utf8').toLowerCase();
            });
            list.on('exit', function(){
                var names = {
                    'node' : 0,
                    'java' : 1
                };
                msg.split(/[\r\n]+/).forEach(function(item){
                    var match = item.match(/\b(node|java)\b/i);
                    if(match){
                        var iMatch = item.match(/\d+/);
                        var index = match[1].toLowerCase();
                        if(iMatch && iMatch[0] == pid[names[index]]){
                            process.kill(iMatch[0], 'SIGKILL');
                        }
                    }
                });
                fis.util.fs.unlinkSync(tmp);
                if(callback){
                    callback();
                }
            });
        } else {
            if(callback){
                callback();
            }
        }
    }

    function matchVersion(str){
        var version = false;
        var reg = /\b\d+(\.\d+){2}/;
        var match = str.match(reg);
        if(match){
            version = match[0];
        }
        return version;
    }

    function open(path){
        var cmd = fis.util.escapeShellArg(path);
        if(fis.util.isWin()){
            cmd = 'start "" ' + cmd;
        } else {
            cmd = 'open ' + cmd;
        }
        child_process.exec(cmd);
    }

    function start(opt){
        var tmp = getConf();
        if(opt){
            fis.util.write(tmp, JSON.stringify(opt));
        } else {
            if(fis.util.exists(tmp)){
                opt = fis.util.readJSON(tmp);
            } else {
                opt = {};
            }
        }

        if(opt.root){
            if(fis.util.exists(opt.root)){
                if(!fis.util.isDir(opt.root)){
                    fis.log.error('document root [' + opt.root + '] is not a directory');
                }
            } else {
                fis.util.mkdir(opt.root);
            }
        } else {
            fis.log.error('invalid document root');
        }

        //check java
        process.stdout.write('checking java support : ');
        var java = spawn('java', ['-version']);
        var javaVersion = false;
        java.stderr.on('data', function(data){
            if(!javaVersion){
                javaVersion = matchVersion(data.toString('utf8'));
                if(javaVersion){
                    process.stdout.write('version ' + javaVersion + '\n');
                }
            }
        });
        java.on('error', function(err){
            fis.log.error(err);
        });
        java.on('exit', function(){
            if(javaVersion){
                //check php-cgi
                process.stdout.write('checking php-cgi support : ');
                var php = spawn(opt['php_exec'] ? opt['php_exec'] : 'php-cgi', ['-v']);
                var phpVersion = false;
                php.stdout.on('data', function(data){
                    if(!phpVersion){
                        phpVersion = matchVersion(data.toString('utf8'));
                        if(phpVersion){
                            process.stdout.write('version ' + phpVersion + '\n');
                        }
                    }
                });
                php.on('error', function(err){
                    fis.log.error(err);
                });
                php.on('exit', function(){
                    if(phpVersion){
                        process.stdout.write('starting fis-server on port : ');

                        var timeout = Math.max(opt.timeout * 1000, 5000);
                        delete opt.timeout;

                        var cmd = [
                            fis.util.escapeShellCmd(process.execPath),
                            fis.util.escapeShellArg(fis.util(__dirname, 'child.js'))
                        ].join(' ');
                        fis.util.map(opt, function(key, value){
                            if(typeof value === 'string'){
                                value = fis.util.escapeShellArg(value);
                            }
                            cmd += ' --' + key + ' ' + value;
                        });

                        //watch log
                        var log = fis.util(__dirname, '/log.txt');
                        fis.util.write(log, '');
                        var lastModified = fis.util.mtime(log).getTime();
                        var startTime = (new Date).getTime();
                        var lastIndex = 0;
                        var errMsg = 'server fails to start at port [' + opt.port + '], error: ';
                        fis.log.debug('start command : ' + cmd);
                        fis.util.nohup(cmd, { cwd : __dirname });
                        var timer = setInterval(function(){
                            if((new Date).getTime() - startTime < timeout){
                                var mtime = fis.util.mtime(log).getTime();
                                if(lastModified !== mtime){
                                    lastModified = mtime;
                                    var content = fis.util.fs.readFileSync(log).toString('utf8').substring(lastIndex);
                                    lastIndex += content.length;
                                    if(content.indexOf('Started SelectChannelConnector@') > 0){
                                        clearInterval(timer);
                                        process.stdout.write(opt.port + '\n');
                                        if(opt.rewrite){
                                            var script = fis.util(opt.root, opt.script || 'index.php');
                                            if(!fis.util.exists(script)){
                                                fis.util.copy(__dirname + '/index.php', script);
                                            }
                                        }
                                        setTimeout(function(){
                                            open('http://localhost' + (opt.port == 80 ? '/' : ':' + opt.port + '/'));
                                        }, 200);
                                    } else if(content.indexOf('Exception:') > 0) {
                                        clearInterval(timer);
                                        var match = content.match(/exception:\s+([^\r\n:]+)/i);
                                        if(match){
                                            errMsg += match[1];
                                        } else {
                                            errMsg += 'unknown';
                                        }
                                        process.stdout.write('\n');
                                        fis.log.error(errMsg);
                                    }
                                }
                            } else {
                                process.stdout.write('\n');
                                fis.log.error(errMsg + 'timeout');
                            }
                        }, 100);
                    } else {
                        fis.log.error('unsupported php-cgi environment');
                    }
                });
            } else {
                fis.log.error('unsupported java environment');
            }
        });
    }

    function getRoot(root){
        if(fis.util.exists(root)){
            if(!fis.util.isDir(root)){
                fis.log.error('invalid document root');
            }
        } else {
            fis.util.mkdir(root);
        }
        return fis.util.realpath(root);
    }

    function printObj(obj, prefix){
        prefix = prefix || '';
        for(var key in obj){
            if(obj.hasOwnProperty(key)){
                if(typeof obj[key] === 'object'){
                    printObj(obj[key], prefix + key + '.');
                } else {
                    console.log(prefix + key + '=' + obj[key]);
                }
            }
        }
    }

    function install(name, version, extract, remote){
        version = version === '*' ? 'latest' : ( version || 'latest' );
        var url = remote + '/server/' + name + '/' + version + '.tar';
        process.stdout.write('download module [' + name + '@' + version + '] ... ');
        fis.util.download(url, function(err){
            if(err){
                process.stdout.write('fail\n');
                fis.log.error( 'unable to download module [' +
                    name + '@' + version + '] from [' + url + '], error [' + err + ']');
            } else {
                process.stdout.write('ok\n');
                var pkg = fis.util(extract, 'package.json');
                if(fis.util.isFile(pkg)){
                    var info = fis.util.readJSON(pkg);
                    fis.util.fs.unlinkSync(pkg);
                    fis.util.map(info.dependencies || {}, function(name, version){
                        install(name, version, extract, remote);
                    });
                }
            }
        }, extract);
    }

    commander
        .option('-p, --port <int>', 'server listen port', parseInt, 8080)
        .option('--root <path>', 'document root', getRoot, fis.project.getTempPath('www'))
        .option('--script <name>', 'rewrite entry file name', String)
        .option('--timeout <seconds>', 'start timeout', parseInt, 15)
        .option('--php_exec <path>', 'path to php-cgi executable file', String)
        .option('--php_exec_args <args>', 'php-cgi arguments', String)
        .option('--php_fcgi_children <int>', 'the number of php-cgi processes', parseInt)
        .option('--php_fcgi_max_requests <int>', 'the max number of requests', parseInt)
        .option('--no-rewrite', 'disable rewrite feature', Boolean)
        .option('--repos <url>', 'install repository', String)
        .action(function(){
            var args = Array.prototype.slice.call(arguments);
            var options = args.pop();
            var cmd = args.shift();
            var conf = getConf();
            switch (cmd){
                case 'start':
                    var opt = {};
                    fis.util.map(options, function(key, value){
                        if(typeof value !== 'object' && key[0] !== '_'){
                            opt[key] = value;
                        }
                    });
                    stop(function(){ start(opt); });
                    break;
                case 'stop':
                    stop();
                    break;
                case 'restart':
                    stop(start);
                    break;
                case 'install':
                    var names = args.shift();
                    if(typeof names === 'string'){
                        var remote = options.repos || fis.config.get(
                            'system.repos', fis.project.DEFAULT_REMOTE_REPOS
                        ).replace(/\/$/, '') + '/server';
                        var option = {
                            extract : options['root'],
                            remote : remote
                        };
                        names.split(',').forEach(function(name){
                            name = name.split('@');
                            fis.util.install(name[0], name[1], option);
                        });
                    } else {
                        fis.log.error('invalid server component name');
                    }
                    break;
                case 'info':
                    if(fis.util.isFile(conf)){
                        conf = fis.util.readJSON(conf);
                        printObj(conf);
                    } else {
                        console.log('nothing...');
                    }
                    break;
                case 'open':
                    if(fis.util.isFile(conf)){
                        conf = fis.util.readJSON(conf);
                        if(fis.util.isDir(conf.root)){
                            open(conf.root);
                        }
                    }
                    break;
                case 'clean':
                    process.stdout.write('\n δ'.bold.yellow);
                    var now = Date.now();
                    fis.util.del(options['root'], null, /\/WEB-INF\//);
                    process.stdout.write((Date.now() - now + 'ms').green.bold);
                    process.stdout.write('\n');
                    break;
                default :
                    commander.help();
            }
        });

    commander
        .command('start')
        .description('start server');

    commander
        .command('stop')
        .description('shutdown server');

    commander
        .command('restart')
        .description('restart server');

    commander
        .command('info')
        .description('output server info');

    commander
        .command('open')
        .description('open document root directory');

    commander
        .command('clean')
        .description('clean files in document root');

    commander
        .command('install <name>')
        .description('install server framework');
};<|endoftext|>