<commit_before>/*jshint node:true*/

var port = (process.env.VCAP_APP_PORT || process.env.PORT || 6001),
    host = (process.env.VCAP_APP_HOST || 'localhost');

// Postgresql database connectivity
var pg = require('pg');

// This application uses express as it's web server
// for more info, see: http://expressjs.com
var express = require('express');

// create a new express server
var app = express();

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

// use socket.io for real-time
var io = require('socket.io')(server);

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// start server on the specified port and binding host
server.listen(port, host, function() {

	// print a message when the server starts listening
  console.log("server starting on host: " + host + ", port: " + port);
});

// Postgres confg
var psql;

// are we operating in BlueMix
if (process.env.VCAP_SERVICES) {
    var env = JSON.parse(process.env.VCAP_SERVICES);
    psql = env['postgresql-9.1'][0].credentials;
    // The Postgresql service returns the database name in the "name"
    // property but the pg.js Node.js module expects it to be in the
    // "database" property.
    psql.database = psql.name;

// or Heroku
} else if (process.env.DATABASE_URL) {
  psql = process.env.DATABASE_URL;

} else {
    // Specify local Postgresql connection properties here.
    psql = {
        database: "iss",
        host: "localhost",
        port: 5432,
        user: "",
        password: "",
        ssl: false
    };
}

// On startup, create the table if it does not exist.
pg.connect(psql, function(err, client, done) {
  if (err) {
    return console.error('Error requesting client', err);
  }

  // client.query('drop table if exists data',
  // function (err, result) {
  //   if (err) {
  //     done();
  //     return console.error('Error dropping table data', err);
  //   }

    client.query('create table if not exists data(idx smallint, value double precision, ts timestamp without time zone)',
    function (err, result) {
      done();
      if (err) {
        return console.error('Error creating table data', err);
      }
    });

  // });

});

var ddlist = require('./data_dictionary').list;

var ls = require("lightstreamer-client");
var lsClient = new ls.LightstreamerClient("http://push.lightstreamer.com","ISSLIVE");
var telemetrySub = new ls.Subscription("MERGE", ddlist , ["Value"]);

function broadcastStatus () {

  var cs = lsClient.getStatus(), c = "DISCONNECTED";

  if (cs.indexOf("STALLED") > -1) {

    c = "STALLED";

  } else if (cs.indexOf("CONNECTED") > -1) {

    c = "CONNECTED";

  } else {

    c = "DISCONNECTED";
  }

  io.emit('STATUS', {connection: c, subscription: telemetrySub.isSubscribed()});

  console.log({connection: c, subscription: telemetrySub.isSubscribed()});
}

lsClient.addListener({
  onStatusChange: function (status) {

    broadcastStatus();
  }
});

lsClient.connect();

lsClient.subscribe(telemetrySub);

var ddhash = require('./data_dictionary').hash;

telemetrySub.addListener({

  onSubscription: function() {

    broadcastStatus();
  },

  onUnsubscription: function() {

    broadcastStatus();
  },

  onItemUpdate: function(update) {

    var u = {n: update.getItemName(), v: update.getValue("Value"), t: Date.now()/1000|0};

    pg.connect(psql, function(err, client, done) {
      if (err) {
        return console.error('Error requesting postgres client', err);
      }

      client.query('insert into data (idx, value, ts) values ($1, $2, to_timestamp($3))',
      [ddhash[u.n], u.v, u.t],

      function(err, result) {
        done();

        if (err) {
          return console.error('Error inserting data', err);
        }
      });
    });

    io.emit(u.n, [{u: u.v, t: u.t}]);
  }
});

function queryUnixtime(type, unixtime, client, cb) {
client.query(
  'SELECT * from data where idx = $1 and ts > to_timestamp($2) order by ts asc',
  //"select date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec' as ts, avg(value) as value from data where idx = $1 and ts > to_timestamp($2) group by date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec' order by date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec'",
  [ddhash[type], unixtime],
  function(err, res) {
    cb(err, res);
  });
}

function queryMostRecent(type, client, cb) {

client.query('select * from data where idx = $1 and ts = (select MAX(ts) from data where idx = $1)',
  [ddhash[type]],
  function(err, res) {
    cb(err, res);
  });
}

function emitRows(socket, type, rows) {
  socket.emit(type, rows.map(function(v) { return {u: v.value.toString(), t: v.ts.getTime()/1000|0}; }));
}

io.on('connection', function (socket) {
  console.log('connection');

  broadcastStatus();

  socket.on('STATUS', function () {

    broadcastStatus();
  });

  for(var i = 0, l = ddlist.length; i<l; i++) {

    var type = ddlist[i];

    (function (type) {

      socket.on(type, function (unixtime) {

        pg.connect(psql, function(err, client, done) {
          if (err) {
            return console.error('Error requesting client', err);
          }

          if(unixtime === -1) {

            queryMostRecent(type, client, function(err, res) {
              done();
              if (err) {
                return console.error('Error querying type: ' + type, err);
              }
              emitRows(socket, type, res.rows);
            });

          } else {

            queryUnixtime(type, unixtime, client, function(err, res) {

              if (err) {
                return console.error('Error querying type: ' + type, err);
              }
              if (res.rows.length === 0) {

                queryMostRecent(type, client, function(err, res) {
                  done();
                  if (err) {
                    return console.error('Error querying type: ' + type, err);
                  }
                  emitRows(socket, type, res.rows);
                });

              } else {
                done();
                emitRows(socket, type, res.rows);
              }

          });
         }
        });
      });
    })(type);

  }
});

<commit_msg>bind to host 0.0.0.0 by default<commit_after>/*jshint node:true*/

var port = (process.env.VCAP_APP_PORT || process.env.PORT || 6001),
    host = (process.env.VCAP_APP_HOST || '0.0.0.0');

// Postgresql database connectivity
var pg = require('pg');

// This application uses express as it's web server
// for more info, see: http://expressjs.com
var express = require('express');

// create a new express server
var app = express();

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

// use socket.io for real-time
var io = require('socket.io')(server);

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// start server on the specified port and binding host
server.listen(port, host, function() {

	// print a message when the server starts listening
  console.log("server starting on host: " + host + ", port: " + port);
});

// Postgres confg
var psql;

// are we operating in BlueMix
if (process.env.VCAP_SERVICES) {
    var env = JSON.parse(process.env.VCAP_SERVICES);
    psql = env['postgresql-9.1'][0].credentials;
    // The Postgresql service returns the database name in the "name"
    // property but the pg.js Node.js module expects it to be in the
    // "database" property.
    psql.database = psql.name;

// or Heroku
} else if (process.env.DATABASE_URL) {
  psql = process.env.DATABASE_URL;

} else {
    // Specify local Postgresql connection properties here.
    psql = {
        database: "iss",
        host: "localhost",
        port: 5432,
        user: "",
        password: "",
        ssl: false
    };
}

// On startup, create the table if it does not exist.
pg.connect(psql, function(err, client, done) {
  if (err) {
    return console.error('Error requesting client', err);
  }

  // client.query('drop table if exists data',
  // function (err, result) {
  //   if (err) {
  //     done();
  //     return console.error('Error dropping table data', err);
  //   }

    client.query('create table if not exists data(idx smallint, value double precision, ts timestamp without time zone)',
    function (err, result) {
      done();
      if (err) {
        return console.error('Error creating table data', err);
      }
    });

  // });

});

var ddlist = require('./data_dictionary').list;

var ls = require("lightstreamer-client");
var lsClient = new ls.LightstreamerClient("http://push.lightstreamer.com","ISSLIVE");
var telemetrySub = new ls.Subscription("MERGE", ddlist , ["Value"]);

function broadcastStatus () {

  var cs = lsClient.getStatus(), c = "DISCONNECTED";

  if (cs.indexOf("STALLED") > -1) {

    c = "STALLED";

  } else if (cs.indexOf("CONNECTED") > -1) {

    c = "CONNECTED";

  } else {

    c = "DISCONNECTED";
  }

  io.emit('STATUS', {connection: c, subscription: telemetrySub.isSubscribed()});

  console.log({connection: c, subscription: telemetrySub.isSubscribed()});
}

lsClient.addListener({
  onStatusChange: function (status) {

    broadcastStatus();
  }
});

lsClient.connect();

lsClient.subscribe(telemetrySub);

var ddhash = require('./data_dictionary').hash;

telemetrySub.addListener({

  onSubscription: function() {

    broadcastStatus();
  },

  onUnsubscription: function() {

    broadcastStatus();
  },

  onItemUpdate: function(update) {

    var u = {n: update.getItemName(), v: update.getValue("Value"), t: Date.now()/1000|0};

    pg.connect(psql, function(err, client, done) {
      if (err) {
        return console.error('Error requesting postgres client', err);
      }

      client.query('insert into data (idx, value, ts) values ($1, $2, to_timestamp($3))',
      [ddhash[u.n], u.v, u.t],

      function(err, result) {
        done();

        if (err) {
          return console.error('Error inserting data', err);
        }
      });
    });

    io.emit(u.n, [{u: u.v, t: u.t}]);
  }
});

function queryUnixtime(type, unixtime, client, cb) {
client.query(
  'SELECT * from data where idx = $1 and ts > to_timestamp($2) order by ts asc',
  //"select date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec' as ts, avg(value) as value from data where idx = $1 and ts > to_timestamp($2) group by date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec' order by date_trunc('minute', ts) + date_part('second', ts)::int / 10 * interval '10 sec'",
  [ddhash[type], unixtime],
  function(err, res) {
    cb(err, res);
  });
}

function queryMostRecent(type, client, cb) {

client.query('select * from data where idx = $1 and ts = (select MAX(ts) from data where idx = $1)',
  [ddhash[type]],
  function(err, res) {
    cb(err, res);
  });
}

function emitRows(socket, type, rows) {
  socket.emit(type, rows.map(function(v) { return {u: v.value.toString(), t: v.ts.getTime()/1000|0}; }));
}

io.on('connection', function (socket) {
  console.log('connection');

  broadcastStatus();

  socket.on('STATUS', function () {

    broadcastStatus();
  });

  for(var i = 0, l = ddlist.length; i<l; i++) {

    var type = ddlist[i];

    (function (type) {

      socket.on(type, function (unixtime) {

        pg.connect(psql, function(err, client, done) {
          if (err) {
            return console.error('Error requesting client', err);
          }

          if(unixtime === -1) {

            queryMostRecent(type, client, function(err, res) {
              done();
              if (err) {
                return console.error('Error querying type: ' + type, err);
              }
              emitRows(socket, type, res.rows);
            });

          } else {

            queryUnixtime(type, unixtime, client, function(err, res) {

              if (err) {
                return console.error('Error querying type: ' + type, err);
              }
              if (res.rows.length === 0) {

                queryMostRecent(type, client, function(err, res) {
                  done();
                  if (err) {
                    return console.error('Error querying type: ' + type, err);
                  }
                  emitRows(socket, type, res.rows);
                });

              } else {
                done();
                emitRows(socket, type, res.rows);
              }

          });
         }
        });
      });
    })(type);

  }
});

<|endoftext|>


<commit_before>var fs = require('fs');
var xml2js = require('xml2js');
var request = require('request');
var express = require('express');
var app = express();

var parser = new xml2js.Parser();

app.get('/', function(req, res){
  request('http://www.norfolkva.gov/cultural_affairs/public_art_downtown.xml',
    function (error, response, body) {
      if (!error && response.statusCode == 200) {
        //console.log(body); // Print the google web page.
        parser.parseString(body, function (err, result) {
        console.log('Done');
        var converted = JSON.stringify(result, undefined, 2);
        console.log(converted);
        res.send(converted);
        });
      }
    });
});

console.log("Listening on Port 3000");
app.listen(3000);
<commit_msg>setting up environment variables<commit_after>var fs = require('fs');
var xml2js = require('xml2js');
var request = require('request');
var express = require('express');
var app = express();

var parser = new xml2js.Parser();

app.get('/', function(req, res){
  request('http://www.norfolkva.gov/cultural_affairs/public_art_downtown.xml',
    function (error, response, body) {
      if (!error && response.statusCode == 200) {
        //console.log(body); // Print the google web page.
        parser.parseString(body, function (err, result) {
        console.log('Done');
        var converted = JSON.stringify(result, undefined, 2);
        console.log(converted);
        res.send(converted);
        });
      }
    });
});

var port = Number(process.env.PORT || 3000);
console.log("Listening on Port" + port);
app.listen(port);
<|endoftext|>


<commit_before>'use strict';

import express from 'express';
import mongoose from 'mongoose';
import moment from 'moment';
import path from 'path';
import exphbs from 'express-handlebars';
import favicon from 'serve-favicon';
import logger from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import compress from 'compression';
import session from 'express-session';
import validator from 'express-validator';
import Store from 'connect-mongo';
import passport from 'passport';
import nconf from 'nconf';

// Routes
import router from './routes';

// Config
import passportConfig from './config/passport';

nconf.argv()
     .env({ separator: '__' })
     .file('./config/settings.json');

const sessionSecret = nconf.get('SESSION_SECRET');
const dbConnectionString = nconf.get('DB:CONNECTION_STRING');

let app = express();
let MongoStore = Store({ session: session });

// Connect to mongo
mongoose.connect(dbConnectionString);
mongoose.connection.on('error', () => console.error('MongoDB Connection Error. Make sure MongoDB is running.'));
mongoose.connection.on('disconnect', () => mongoose.connect(dbConnectionString));

// Setup handlebars
let hbs = new exphbs.create({
    layoutsDir: path.resolve(__dirname, 'views/shared'),
    partialsDir: path.resolve(__dirname, 'views/shared'),
    defaultLayout: 'layout',
    helpers: {
        checkedIf: function(condition) {
            return (condition) ? 'checked' : '';
        },
        formatDate: function(date) {
            return moment(date).fromNow();
        }
    }
});

// middleware
// view engine setup
app.set('port', nconf.get('port') || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars')
app.use(compress());
app.use(validator());
app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
    secret: sessionSecret,
    store: new MongoStore({
        url: dbConnectionString,
        autoReconnect: true,
        collection: 'session'
    }),
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, './public')));
app.use((req, res, next) => {
    if (req.user) {
        res.cookie('user', JSON.stringify(req.user));
        res.locals.user = req.user;
    }
    next();
});

import agenda from './service';
import agendaUI from 'agenda-ui';

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

// Agenda UI middleware
app.get('/jobs', agendaUI(agenda, {poll: 30000}));

// Routes
app.use(router);

// Catch 404 and forward to error handler
app.use((req, res, next) => {
    let err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// Error handlers
// Stacktraces passed
app.use((err, req, res, next) => {
    res.status(err.status || res.statusCode || 500).send({
        success: false,
        message: err.message,
        errors: err.errors || err
    });
});

export default app;
<commit_msg>fix agenda middleware<commit_after>'use strict';

import express from 'express';
import mongoose from 'mongoose';
import moment from 'moment';
import path from 'path';
import exphbs from 'express-handlebars';
import favicon from 'serve-favicon';
import logger from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import compress from 'compression';
import session from 'express-session';
import validator from 'express-validator';
import Store from 'connect-mongo';
import passport from 'passport';
import nconf from 'nconf';

// Routes
import router from './routes';

// Config
import passportConfig from './config/passport';

nconf.argv()
     .env({ separator: '__' })
     .file('./config/settings.json');

const sessionSecret = nconf.get('SESSION_SECRET');
const dbConnectionString = nconf.get('DB:CONNECTION_STRING');

let app = express();
let MongoStore = Store({ session: session });

// Connect to mongo
mongoose.connect(dbConnectionString);
mongoose.connection.on('error', () => console.error('MongoDB Connection Error. Make sure MongoDB is running.'));
mongoose.connection.on('disconnect', () => mongoose.connect(dbConnectionString));

// Setup handlebars
let hbs = new exphbs.create({
    layoutsDir: path.resolve(__dirname, 'views/shared'),
    partialsDir: path.resolve(__dirname, 'views/shared'),
    defaultLayout: 'layout',
    helpers: {
        checkedIf: function(condition) {
            return (condition) ? 'checked' : '';
        },
        formatDate: function(date) {
            return moment(date).fromNow();
        }
    }
});

// middleware
// view engine setup
app.set('port', nconf.get('port') || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars')
app.use(compress());
app.use(validator());
app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
    secret: sessionSecret,
    store: new MongoStore({
        url: dbConnectionString,
        autoReconnect: true,
        collection: 'session'
    }),
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, './public')));
app.use((req, res, next) => {
    if (req.user) {
        res.cookie('user', JSON.stringify(req.user));
        res.locals.user = req.user;
    }
    next();
});

import agenda from './service';
import agendaUI from 'agenda-ui';

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

// Agenda UI middleware
app.use('/jobs', agendaUI(agenda, {poll: 30000}));

// Routes
app.use(router);

// Catch 404 and forward to error handler
app.use((req, res, next) => {
    let err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// Error handlers
// Stacktraces passed
app.use((err, req, res, next) => {
    res.status(err.status || res.statusCode || 500).send({
        success: false,
        message: err.message,
        errors: err.errors || err
    });
});

export default app;
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
const express = require('express');
const request = require('request');
const http = require('http');
const https = require('https');
const bodyParser = require('body-parser');
const logger = require('morgan');
const errorHandler = require('errorhandler');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const passport = require('passport');
const expressValidator = require('express-validator');
const expressJwt = require('express-jwt');
const jwt = require('jsonwebtoken');

const crypto = require('crypto');

const Client = require('./models/Client');

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 */
dotenv.load({path: '.env'});

/**
 * HTTPS Credentials (Use in Production)
 */
// var credentials = {
//   key: process.env.PRIVATE_KEY,
//   cert: process.env.CERTIFICATE
// };

/**
 * Controllers (route handlers).
 */
const userController = require('./controllers/user');
const clientController = require('./controllers/client');

/**
 * API keys and Passport configuration.
 */
const passportConfig = require('./config/passport');

/**
 * JWT Authentication
 */
const authenticate = expressJwt({secret: process.env.SECRET});

/**
 * Create Express server.
 */
const app = express();

/**
 * Connect to MongoDB.
 */
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', () => {
    console.error('MongoDB Connection Error. Please make sure that MongoDB is running.');
    process.exit(1);
});

/**
 * Express configuration.
 */
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressValidator());
app.use(passport.initialize());

/**
 * Server responses
 */
 const respond = {
     auth: function(req, res) {
         res.status(200).json({
           user: req.user,
           token: req.token
         });
     },
     token: function(req, res) {
         res.status(201).json({
           refreshToken: req.refreshToken
         });
     },
     revoke: function(req, res) {
         res.status(200).json({
           success: "Refresh token has been revoked!"
         });
     }
 }

/**
 * API routes.
 */

app.get('/', function(req, res) {
    res.status(200).json({
        title: 'SPA-AUTH-STARTER',
        author: 'Bogdan Pshonyak',
        routes: [
            {
                path: '/login',
                type: 'POST',
                desc: 'Login with email and password',
                protected: false
            }, {
                path: '/signup',
                type: 'POST',
                desc: 'Register with email and password',
                protected: false
            }, {
                path: '/account/profile',
                type: 'GET',
                desc: 'Retrieve user profile information',
                protected: true
            }, {
                path: '/account/password',
                type: 'POST',
                desc: 'Change a local users password',
                protected: true
            }, {
                path: '/account/delete',
                type: 'POST',
                desc: 'Delete a user',
                protected: true
            }, {
                path: '/auth/facebook',
                type: 'GET',
                desc: 'Authenticate user with their facebook account',
                protected: false
            }
        ]
    });
});

app.get('/profile', authenticate, function(req, res) {
    res.status(200).json(req.user);
});

app.post('/login', userController.postLogin, serializeUser, generateAccessToken, respond.auth);
// app.get('/logout', userController.logout);
// app.get('/forgot', userController.getForgot);
// app.post('/forgot', userController.postForgot);
// app.get('/reset/:token', userController.getReset);
// app.post('/reset/:token', userController.postReset);
app.post('/signup', userController.postSignup, serializeUser, generateAccessToken, respond.auth);
// app.get('/account', authenticate, userController.getAccount);
app.get('/account/profile', authenticate, userController.getProfile);
app.post('/account/password', authenticate, userController.postUpdatePassword);
app.post('/account/delete', authenticate, userController.postDeleteAccount);
app.get('/account/unlink/:provider', authenticate, userController.getOauthUnlink);

/**
 * OAuth authentication routes. (Sign in)
 */

app.get('/auth/facebook', passport.authenticate('facebook', {
    session: false,
    scope: ['email', 'user_location']
}));

app.get('/auth/facebook/callback', passport.authenticate('facebook', {
    session: false,
    failureRedirect: '/'
}), serializeUser, generateAccessToken, respond.auth);

app.get('/token', authenticate, generateRefreshToken, respond.token);
app.post('/token/refresh', validateRefreshToken, generateAccessToken, respond.auth);
app.post('/token/revoke', revokeRefreshToken, respond.revoke);

/**
 * Helper Funtions
 */

function serializeUser(req, res, next) {
    req.user = { id: req.user.id };
    next();
}

function validateRefreshToken(req, res, next) {

    req.user = {
        id: req.body.id
    }

    clientController.validateToken(req.body.id, req.body.refreshToken, function(valid) {

        if(!valid) {
            res.status(500).json({
              error: "Failed to validate refresh token."
            });
        } else {
            next();
        }
    });
}

function revokeRefreshToken(req, res, next) {

    req.user = {
        id: req.body.id
    }

    clientController.revokeToken(req.body.id, req.body.refreshToken, function(valid) {

        if(!valid) {
            res.status(500).json({
              error: "Failed to revoke refresh token."
            });
        } else {
            next();
        }
    });

}

function generateAccessToken(req, res, next) {
    // Define token body
    req.token = jwt.sign({
        id: req.user.id
    }, process.env.SECRET, {
        expiresIn: 5 * 60
    });
    next();
}

function generateRefreshToken(req, res, next) {
    clientController.createOrUpdateClient(req.user.id, function(refreshToken, err) {
        if (err)
            console.log(err);

        console.log(refreshToken);
        req.refreshToken = refreshToken;
        next();
    });
}

/**
 * Error Handler. (SHOULD ONLY BE USED IN DEVELOPMENT)
 */
app.use(errorHandler());

/**
 * Start server (development).
 */
http.createServer(app).listen(3000, function() {
    console.log('Server listening on port ', 3000);
});

/**
 * Start server (production).
 */
// https.createServer(credentials,app).listen(3000, function() {
//   console.log('server listening on port ', 3000);
// });
<commit_msg>removed blot<commit_after>/**
 * Module dependencies.
 */
const express = require('express');
const request = require('request');
const http = require('http');
const bodyParser = require('body-parser');
const logger = require('morgan');
const errorHandler = require('errorhandler');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const passport = require('passport');
const expressValidator = require('express-validator');
const expressJwt = require('express-jwt');
const jwt = require('jsonwebtoken');

/**
 * Load environment variables from .env file, where API keys and passwords are configured.
 */
dotenv.load({path: '.env'});

/**
 * Controllers (route handlers).
 */
const userController = require('./controllers/user');
const clientController = require('./controllers/client');

/**
 * API keys and Passport configuration.
 */
const passportConfig = require('./config/passport');

/**
 * JWT Authentication
 */
const authenticate = expressJwt({secret: process.env.SECRET});

/**
 * Create Express server.
 */
const app = express();

/**
 * Connect to MongoDB.
 */
mongoose.connect(process.env.MONGODB_URI || process.env.MONGOLAB_URI);
mongoose.connection.on('error', () => {
    console.error('MongoDB Connection Error. Please make sure that MongoDB is running.');
    process.exit(1);
});

/**
 * Express configuration.
 */
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressValidator());
app.use(passport.initialize());

/**
 * Server responses
 */
 const respond = {
     auth: function(req, res) {
         res.status(200).json({
           user: req.user,
           token: req.token
         });
     },
     token: function(req, res) {
         res.status(201).json({
           refreshToken: req.refreshToken
         });
     },
     revoke: function(req, res) {
         res.status(200).json({
           success: "Refresh token has been revoked!"
         });
     }
 }

/**
 * API routes.
 */

app.get('/', function(req, res) {
    res.status(200).json({
        API: 'JWT-AUTH-STARTER'
    });
});

app.get('/profile', authenticate, function(req, res) {
    res.status(200).json(req.user);
});

app.post('/login', userController.postLogin, serializeUser, generateAccessToken, respond.auth);
// app.get('/logout', userController.logout);
// app.get('/forgot', userController.getForgot);
// app.post('/forgot', userController.postForgot);
// app.get('/reset/:token', userController.getReset);
// app.post('/reset/:token', userController.postReset);
app.post('/signup', userController.postSignup, serializeUser, generateAccessToken, respond.auth);
// app.get('/account', authenticate, userController.getAccount);
app.get('/account/profile', authenticate, userController.getProfile);
app.post('/account/password', authenticate, userController.postUpdatePassword);
app.post('/account/delete', authenticate, userController.postDeleteAccount);
app.get('/account/unlink/:provider', authenticate, userController.getOauthUnlink);

/**
 * OAuth authentication routes. (Sign in)
 */

app.get('/auth/facebook', passport.authenticate('facebook', {
    session: false,
    scope: ['email', 'user_location']
}));

app.get('/auth/facebook/callback', passport.authenticate('facebook', {
    session: false,
    failureRedirect: '/'
}), serializeUser, generateAccessToken, respond.auth);

app.get('/token', authenticate, generateRefreshToken, respond.token);
app.post('/token/refresh', validateRefreshToken, generateAccessToken, respond.auth);
app.post('/token/revoke', revokeRefreshToken, respond.revoke);

/**
 * Helper Funtions
 */

function serializeUser(req, res, next) {
    req.user = { id: req.user.id };
    next();
}

function validateRefreshToken(req, res, next) {

    req.user = {
        id: req.body.id
    }

    clientController.validateToken(req.body.id, req.body.refreshToken, function(valid) {

        if(!valid) {
            res.status(500).json({
              error: "Failed to validate refresh token."
            });
        } else {
            next();
        }
    });
}

function revokeRefreshToken(req, res, next) {

    req.user = {
        id: req.body.id
    }

    clientController.revokeToken(req.body.id, req.body.refreshToken, function(valid) {

        if(!valid) {
            res.status(500).json({
              error: "Failed to revoke refresh token."
            });
        } else {
            next();
        }
    });

}

function generateAccessToken(req, res, next) {
    // Define token body
    req.token = jwt.sign({
        id: req.user.id
    }, process.env.SECRET, {
        expiresIn: 5 * 60
    });
    next();
}

function generateRefreshToken(req, res, next) {
    clientController.createOrUpdateClient(req.user.id, function(refreshToken, err) {
        if (err)
            console.log(err);

        console.log(refreshToken);
        req.refreshToken = refreshToken;
        next();
    });
}

/**
 * Error Handler. (SHOULD ONLY BE USED IN DEVELOPMENT)
 */
app.use(errorHandler());

/**
 * Start server (development).
 */
http.createServer(app).listen(3000, function() {
    console.log('Server listening on port ', 3000);
});
<|endoftext|>


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

var formidable = require('formidable'),
    http = require('http'),
    util = require('util'),
    os = require('os'),
    fs = require('fs'),
    crypto = require('crypto'),
    uploadDir = os.tmpDir() + "/uplodr",
    config = require('./config.js');

if (typeof config.customUploadDir !== 'undefined')
  uploadDir = config.customUploadDir;

mkdirIfNotExist(uploadDir);

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // current date/time of session, use UTC to avoid DST
    var date = new Date();
    var dateString = '' + date.getUTCFullYear()
              + twoDigits(date.getUTCMonth()+1)
              + twoDigits(date.getUTCDate())
              + '-'
              + twoDigits(date.getUTCHours())
              + twoDigits(date.getUTCMinutes())
              + twoDigits(date.getUTCSeconds());
    var newUploadDir = uploadDir
                     + '/' + dateString
                     + '-' + randomCharacters(5);
    mkdirIfNotExist(newUploadDir);
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.uploadDir = newUploadDir;
    form.parse(req, function(err, fields, files) {
      // metadata
      var metafile = newUploadDir + 'metadata.txt';
      fs.appendFile(metafile,
        util.inspect({fields: fields, files: files}),
        function(err){
          if (err) throw err;
        }
      );
      console.log('uplodr: new %s', metafile);
      // files.upload, "upload" is the name of the input field
      processUpload(files.upload);
      processUpload(files.upload2);
      processUpload(files.upload3);
      processUpload(files.upload4);
      processUpload(files.upload5);
      // response to browser
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload.\n\n');
      // res.end(util.inspect({fields: fields, files: files}));
      res.end();
    });
    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title">
'+
    '<input type="file" name="upload">
'+
    '<input type="file" name="upload2">
'+
    '<input type="file" name="upload3">
'+
    '<input type="file" name="upload4">
'+
    '<input type="file" name="upload5">
'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(80);

function mkdirIfNotExist(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir);
  if (!fs.existsSync(dir)) {
    return false;
  } else {
    return fs.statSync(dir).isDirectory();
  }
}

function twoDigits(num) {
  if (Number(num) < 10) {
    return '0' + Number(num);
  } else {
    return num;
  }
}

function randomCharacters (count, characters) {
  characters = characters
    || "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var result = new Array(count),
      randomByte = crypto.randomBytes(count);
  for (var i = 0; i < count; i++) {
    result[i] = characters[randomByte[i] % characters.length]
  };
  return result.join('');
}

function processUpload(inputName) {
  if (typeof inputName !== 'undefined') {
    if (inputName.size !== 0) {
      if (inputName.name.lastIndexOf('.') > 0) {
        var parts = inputName.name.split('.');
        var extension = parts.pop();
        var newUploadDir = inputName.name.split('/');
        newUploadDir.pop();
        if (String(extension).length > 0) {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join().replace(/,/g,'')
            + '.' + extension;
        } else {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join().replace(/,/g,'');
        }
        fs.rename(inputName.path, safename, function(err){
          if (err) throw err;
        });
      }
      return true;
    }
  }
  return false;
}
<commit_msg>add slash<commit_after>#!/usr/bin/env node

var formidable = require('formidable'),
    http = require('http'),
    util = require('util'),
    os = require('os'),
    fs = require('fs'),
    crypto = require('crypto'),
    uploadDir = os.tmpDir() + "/uplodr",
    config = require('./config.js');

if (typeof config.customUploadDir !== 'undefined')
  uploadDir = config.customUploadDir;

mkdirIfNotExist(uploadDir);

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // current date/time of session, use UTC to avoid DST
    var date = new Date();
    var dateString = '' + date.getUTCFullYear()
              + twoDigits(date.getUTCMonth()+1)
              + twoDigits(date.getUTCDate())
              + '-'
              + twoDigits(date.getUTCHours())
              + twoDigits(date.getUTCMinutes())
              + twoDigits(date.getUTCSeconds());
    var newUploadDir = uploadDir
                     + '/' + dateString
                     + '-' + randomCharacters(5);
    mkdirIfNotExist(newUploadDir);
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.uploadDir = newUploadDir;
    form.parse(req, function(err, fields, files) {
      // metadata
      var metafile = newUploadDir + '/metadata.txt';
      fs.appendFile(metafile,
        util.inspect({fields: fields, files: files}),
        function(err){
          if (err) throw err;
        }
      );
      console.log('uplodr: new %s', metafile);
      // files.upload, "upload" is the name of the input field
      processUpload(files.upload);
      processUpload(files.upload2);
      processUpload(files.upload3);
      processUpload(files.upload4);
      processUpload(files.upload5);
      // response to browser
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload.\n\n');
      // res.end(util.inspect({fields: fields, files: files}));
      res.end();
    });
    return;
  }

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(
    '<form action="/upload" enctype="multipart/form-data" method="post">'+
    '<input type="text" name="title">
'+
    '<input type="file" name="upload">
'+
    '<input type="file" name="upload2">
'+
    '<input type="file" name="upload3">
'+
    '<input type="file" name="upload4">
'+
    '<input type="file" name="upload5">
'+
    '<input type="submit" value="Upload">'+
    '</form>'
  );
}).listen(80);

function mkdirIfNotExist(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir);
  if (!fs.existsSync(dir)) {
    return false;
  } else {
    return fs.statSync(dir).isDirectory();
  }
}

function twoDigits(num) {
  if (Number(num) < 10) {
    return '0' + Number(num);
  } else {
    return num;
  }
}

function randomCharacters (count, characters) {
  characters = characters
    || "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var result = new Array(count),
      randomByte = crypto.randomBytes(count);
  for (var i = 0; i < count; i++) {
    result[i] = characters[randomByte[i] % characters.length]
  };
  return result.join('');
}

function processUpload(inputName) {
  if (typeof inputName !== 'undefined') {
    if (inputName.size !== 0) {
      if (inputName.name.lastIndexOf('.') > 0) {
        var parts = inputName.name.split('.');
        var extension = parts.pop();
        var newUploadDir = inputName.name.split('/');
        newUploadDir.pop();
        if (String(extension).length > 0) {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join().replace(/,/g,'')
            + '.' + extension;
        } else {
          var safename = newUploadDir + '/'
            + parts.join().match(/[a-zA-Z0-9]+/g).join().replace(/,/g,'');
        }
        fs.rename(inputName.path, safename, function(err){
          if (err) throw err;
        });
      }
      return true;
    }
  }
  return false;
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";

require("amd-loader");
try {
    require("heapdump");
} catch(e) {}

var path = require("path");
var architect = require("architect");
var optimist = require("optimist");
var async = require("async");
var os = require("os");
var urls = require("c9/urls");
var child_process = require("child_process");
require("c9/setup_paths.js");

if (process.version.match(/^v0/) && parseFloat(process.version.substr(3)) < 10) {
    console.warn("You're using Node.js version " + process.version
        + ". Version 0.10 or higher is recommended. Some features will not work.");
}

var DEFAULT_CONFIG = "s";
var DEFAULT_SETTINGS = getDefaultSettings();

var shortcuts = {
    "dev":       ["ide", "preview", "user-content", "vfs", "api", "sapi", "proxy", "redis", "profile", "oldclient", "homepage", "apps-proxy", "-s", "devel"],
    "onlinedev": ["ide", "preview", "user-content", "vfs", "api", "proxy", "oldclient", "homepage", "apps-proxy", "profile", "-s", "onlinedev"],
    "beta":      ["ide", "preview", "user-content", "vfs", "proxy", "-s", "beta"],
    "s":         ["standalone", "-s", "standalone"],
};
shortcuts.localdev = shortcuts.onlinedev.concat([
    "-s", "beta",
    "--ide.packed", "false",
    "--ide.cdn", "false", "--homepage.cdn", "false",
    "--force-sudo",
    "--api.port", "8281",
    "--infra_port", "8282",
    "--api_url", "http://127.0.0.1:8281",
    "--domains", "c9.local",
    "--cdn.abbreviateVersion", "true",
]);
shortcuts.odev = shortcuts.onlinedev; // For backwards compatibility, if you see this in 2016 remove this line
var delayLoadConfigs = [
    // Services that are usually not immediately needed
    "preview", "user-content", "api", "apps-proxy", "worker",
    // Services that are very slow to load, blocking others
    "profile",
];

module.exports = main;

if (!module.parent)
    main(process.argv.slice(2));

function getDefaultSettings() {
    var hostname = os.hostname();

    var suffix = hostname.trim().split("-").pop() || "";
    var modes = {
        "workflowstaging": "workflow-staging",
        "prod": "deploy",
        "beta": "beta",
        "dev": "devel",
        "onlinedev": "onlinedev",
        "test": "test"
    };
    return modes[suffix] || "devel";
}

module.exports.getDefaultSettings = getDefaultSettings;

function main(argv, config, onLoaded) {
    var inContainer = os.hostname().match(/-\d+$/);

    var options = optimist(argv)
        .usage("Usage: $0 [CONFIG_NAME] [--help]")
        .alias("s", "settings")
        .default("settings", DEFAULT_SETTINGS)
        .describe("settings", "Settings file to use")
        .describe("dump", "dump config file as JSON")
        .describe("domains", "Primary and any secondary top-level domains to use (e.g, c9.io,c9.dev)")
        .describe("exclude", "Exclude specified service")
        .describe("include", "Include only specified service")
        .default("domains", inContainer && process.env.C9_HOSTNAME || process.env.C9_DOMAINS)
        .boolean("help")
        .describe("help", "Show command line options.");

    var configs = options.argv._;
    if (!configs.length)
        configs = [config || DEFAULT_CONFIG];
    if (options.argv.exclude && !Array.isArray(options.argv.exclude.length))
        options.argv.exclude = [options.argv.exclude];

    var expanded = expandShortCuts(configs);

    if (expanded.length > configs.length)
        return main(expanded.concat(argv.filter(function(arg) {
            return !shortcuts[arg];
        })), config, onLoaded);

    if (options.argv.include)
        expanded = [].concat(options.argv.include);

    var delayed = expanded.filter(function(c) { return delayLoadConfigs.indexOf(c) !== -1 });
    var notDelayed = expanded.filter(function(c) { return delayLoadConfigs.indexOf(c) === -1 });

    if (options.argv["force-sudo"])
        return child_process.execFile("sudo", ["echo -n"], main.bind(null, argv.filter(function(a) {
            return a !== "--force-sudo";
        }), config, onLoaded));

    startConfigs(notDelayed, function() {
        startConfigs(delayed, function() {
            console.log("Cloud9 is up and running");
        });
    });

    function startConfigs(configs, done) {
        async.each(configs, function(config, next) {
            if (options.argv.exclude && options.argv.exclude.indexOf(config) > -1)
                return next();
            start(config, options, function(err, result, path) {
                onLoaded && onLoaded(err, result, path);
                next(err);
            });
        }, done);
    }
}

function expandShortCuts(configs) {
    var results = configs.slice();
    for (var i = 0; i < results.length; i++) {
        var expanded = shortcuts[results[i]];
        if (expanded) {
            results.splice.apply(results, [i, 1].concat(expanded));
            i += expanded.length - 1;
        }
    }
    return results;
}

function start(configName, options, callback) {
    console.log("Starting", configName);

    var argv = options.argv;
    var settingsName = argv.settings;

    if (typeof settingsName != "string")
        settingsName = settingsName.pop();

    var configPath = configName;
    if (configPath[0] !== "/")
        configPath = path.join(__dirname, "/configs/", configName);

    var settings = require(path.join(__dirname, "./settings", settingsName))();

    argv.domains = argv.domains || settings.domains;
    if (settings.c9 && argv.domains)
        urls.replaceDomains(settings, argv.domains);

    var plugins = require(configPath)(settings, options);

    if (argv.help) {
        options.usage("Usage: $0 " + configName);
        options.showHelp();
    }

    if (!plugins)
        return;

    if (module.exports.onResolvePlugins)
        module.exports.onResolvePlugins(plugins, __dirname + "/plugins");

    architect.resolveConfig(plugins, __dirname + "/plugins", function(err, config) {
        if (err) {
            console.error(err);
            process.exit(1);
        }

        if (argv.dump) {
            console.log(JSON.stringify(config, null, 2));
            return callback && callback(null, config);
        }

        if (argv._getConfig)
            return callback && callback(null, config, configPath);

        var app = architect.createApp(config, function (err, app) {
            if (err) {
                console.trace("Error while starting '%s':", configPath);
                console.log(err, err.stack);
                process.exit(1);
            }
            console.log("Started '%s' with config '%s'!", configPath, settingsName);

            callback && callback(null, app);
        });

        app.on("service", function(name, plugin) {
            if (typeof plugin !== "function")
                plugin.name = name;
        });
    });
}<commit_msg>Disable raygun for localdev<commit_after>#!/usr/bin/env node
"use strict";

require("amd-loader");
try {
    require("heapdump");
} catch(e) {}

var path = require("path");
var architect = require("architect");
var optimist = require("optimist");
var async = require("async");
var os = require("os");
var urls = require("c9/urls");
var child_process = require("child_process");
require("c9/setup_paths.js");

if (process.version.match(/^v0/) && parseFloat(process.version.substr(3)) < 10) {
    console.warn("You're using Node.js version " + process.version
        + ". Version 0.10 or higher is recommended. Some features will not work.");
}

var DEFAULT_CONFIG = "s";
var DEFAULT_SETTINGS = getDefaultSettings();

var shortcuts = {
    "dev":       ["ide", "preview", "user-content", "vfs", "api", "sapi", "proxy", "redis", "profile", "oldclient", "homepage", "apps-proxy", "-s", "devel"],
    "onlinedev": ["ide", "preview", "user-content", "vfs", "api", "proxy", "oldclient", "homepage", "apps-proxy", "profile", "-s", "onlinedev"],
    "beta":      ["ide", "preview", "user-content", "vfs", "proxy", "-s", "beta"],
    "s":         ["standalone", "-s", "standalone"],
};
shortcuts.localdev = shortcuts.onlinedev.concat([
    "-s", "beta",
    "--ide.packed", "false",
    "--ide.cdn", "false",
    "--ide.forceDev", "true",
    "--homepage.cdn", "false",
    "--helpWithSudo",
    "--api.port", "8281",
    "--infra_port", "8282",
    "--api_url", "http://127.0.0.1:8281",
    "--domains", "c9.local",
    "--cdn.abbreviateVersion", "true",
]);
shortcuts.odev = shortcuts.onlinedev; // For backwards compatibility, if you see this in 2016 remove this line
var delayLoadConfigs = [
    // Services that are usually not immediately needed
    "preview", "user-content", "api", "apps-proxy", "worker",
    // Services that are very slow to load, blocking others
    "profile",
];

module.exports = main;

if (!module.parent)
    main(process.argv.slice(2));

function getDefaultSettings() {
    var hostname = os.hostname();

    var suffix = hostname.trim().split("-").pop() || "";
    var modes = {
        "workflowstaging": "workflow-staging",
        "prod": "deploy",
        "beta": "beta",
        "dev": "devel",
        "onlinedev": "onlinedev",
        "test": "test"
    };
    return modes[suffix] || "devel";
}

module.exports.getDefaultSettings = getDefaultSettings;

function main(argv, config, onLoaded) {
    var inContainer = os.hostname().match(/-\d+$/);

    var options = optimist(argv)
        .usage("Usage: $0 [CONFIG_NAME] [--help]")
        .alias("s", "settings")
        .default("settings", DEFAULT_SETTINGS)
        .describe("settings", "Settings file to use")
        .describe("dump", "dump config file as JSON")
        .describe("domains", "Primary and any secondary top-level domains to use (e.g, c9.io,c9.dev)")
        .describe("exclude", "Exclude specified service")
        .describe("include", "Include only specified service")
        .default("domains", inContainer && process.env.C9_HOSTNAME || process.env.C9_DOMAINS)
        .boolean("help")
        .describe("help", "Show command line options.");

    var configs = options.argv._;
    if (!configs.length)
        configs = [config || DEFAULT_CONFIG];
    if (options.argv.exclude && !Array.isArray(options.argv.exclude.length))
        options.argv.exclude = [options.argv.exclude];

    var expanded = expandShortCuts(configs);

    if (expanded.length > configs.length)
        return main(expanded.concat(argv.filter(function(arg) {
            return !shortcuts[arg];
        })), config, onLoaded);

    if (options.argv.include)
        expanded = [].concat(options.argv.include);

    var delayed = expanded.filter(function(c) { return delayLoadConfigs.indexOf(c) !== -1 });
    var notDelayed = expanded.filter(function(c) { return delayLoadConfigs.indexOf(c) === -1 });

    if (options.helpWithSudo)
        return child_process.execFile("sudo", ["echo -n"], main.bind(null, argv.filter(function(a) {
            return a !== "--helpWithSudo";
        }), config, onLoaded));

    startConfigs(notDelayed, function() {
        startConfigs(delayed, function() {
            console.log("Cloud9 is up and running");
        });
    });

    function startConfigs(configs, done) {
        async.each(configs, function(config, next) {
            if (options.argv.exclude && options.argv.exclude.indexOf(config) > -1)
                return next();
            start(config, options, function(err, result, path) {
                onLoaded && onLoaded(err, result, path);
                next(err);
            });
        }, done);
    }
}

function expandShortCuts(configs) {
    var results = configs.slice();
    for (var i = 0; i < results.length; i++) {
        var expanded = shortcuts[results[i]];
        if (expanded) {
            results.splice.apply(results, [i, 1].concat(expanded));
            i += expanded.length - 1;
        }
    }
    return results;
}

function start(configName, options, callback) {
    console.log("Starting", configName);

    var argv = options.argv;
    var settingsName = argv.settings;

    if (typeof settingsName != "string")
        settingsName = settingsName.pop();

    var configPath = configName;
    if (configPath[0] !== "/")
        configPath = path.join(__dirname, "/configs/", configName);

    var settings = require(path.join(__dirname, "./settings", settingsName))();

    argv.domains = argv.domains || settings.domains;
    if (settings.c9 && argv.domains)
        urls.replaceDomains(settings, argv.domains);

    var plugins = require(configPath)(settings, options);

    if (argv.help) {
        options.usage("Usage: $0 " + configName);
        options.showHelp();
    }

    if (!plugins)
        return;

    if (module.exports.onResolvePlugins)
        module.exports.onResolvePlugins(plugins, __dirname + "/plugins");

    architect.resolveConfig(plugins, __dirname + "/plugins", function(err, config) {
        if (err) {
            console.error(err);
            process.exit(1);
        }

        if (argv.dump) {
            console.log(JSON.stringify(config, null, 2));
            return callback && callback(null, config);
        }

        if (argv._getConfig)
            return callback && callback(null, config, configPath);

        var app = architect.createApp(config, function (err, app) {
            if (err) {
                console.trace("Error while starting '%s':", configPath);
                console.log(err, err.stack);
                process.exit(1);
            }
            console.log("Started '%s' with config '%s'!", configPath, settingsName);

            callback && callback(null, app);
        });

        app.on("service", function(name, plugin) {
            if (typeof plugin !== "function")
                plugin.name = name;
        });
    });
}<|endoftext|>


<commit_before>var sys = require("sys");
var connect = require("connect");
var express = require("express");
var fs = require("fs");
var http = require("http");
var target_queries = require("./targets");

cport = process.env.COUCHDB_PORT || 5984;
chost = process.env.COUCHDB_HOST || "localhost";
cuser = process.env.COUCHDB_USER;
cpass = process.env.COUCHDB_PASSWORD;
// sys.puts("Connecting to "+cuser+"|"+cpass+"|"+chost+"|"+cport);

if (cuser) {
    var couchdb = require("couchdb").createClient(cport, chost, cuser, cpass);
} else {
    var couchdb = require("couchdb").createClient(cport, chost);
}
var db = couchdb.db("arewefirstyet");

var pub = __dirname + '/public';
var app = express.createServer(
    express.staticProvider(pub)
);

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

var is_first = 0;
var active_series = [];
var resetting = false;

function find_url_for_label(label) {
    var found = null;
    target_queries.forEach(function(elem, idx) {
        if (elem.name === label) {
            found = elem.url;
        }
    });
    return found;
}

var target_url = "/ajax/services/search/web?v=1.0&q={QUERY}&start={PAGE}"
var MAX_PAGES = 10;
var MAX_SPIN = 50;

var user_agents = [
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13",
    "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/533.17.8 (KHTML, like Gecko) Version/5.0.1 Safari/533.17.8",
    "Mozilla/5.0 (Windows; U; Windows NT 6.1; ja-JP) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16",
    "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/7.0.540.0 Safari/534.10",
    "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/7.0.540.0 Safari/534.10",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.9 (KHTML, like Gecko) Chrome/7.0.531.0 Safari/534.9",
    "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/534.4 (KHTML, like Gecko) Chrome/6.0.481.0 Safari/534.4",
    "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.462.0 Safari/534.3"
];

function seek (target_url, page, is_found, callback) {
    var ua = user_agents[Math.floor(Math.random()*user_agents.length)];
    var paged_target_url = target_url.replace("{PAGE}", page);
    var google = http.createClient(80, "ajax.googleapis.com");
    var request = google.request('GET',
                                 paged_target_url,
                                 {
                                     "Host": "ajax.googleapis.com",
                                     "User-Agent": ua
                                 });
    request.end();
    request.on("response", function (response) {
        var body = "";
        response.on("data", function(chunker) {
            body += chunker;
        });
        response.on("end", function() {
            var data = JSON.parse(body);
            if (data.responseData) {
                var juicybits = data.responseData.results;
                var found_index = -1;
                juicybits.forEach(function(bit, bitcount) {
                    if (is_found(bit.url)) {
                        found_index = page*4 + bitcount;
                        // urls.push({url: bit.url, name: bit.titleNoFormatting})
                    }
                    if (found_index == -1) {
                        // urls.push({url: bit.url, name: bit.titleNoFormatting})
                    }
                });

                if (page == MAX_SPIN) {
                    callback(MAX_SPIN*4);
                } else if (found_index >= 0)
                    callback(found_index+1);
                else {
                    seek(target_url, page+1, is_found, callback);
                }
            } else {
                sys.p("Failure on "+paged_target_url);
            }
        });

    });
}

function pad(n){return n<10 ? '0'+n : n}
function keyify(i) {  return i.name.toLowerCase().replace(/[^a-z0-9]/g,""); }
function reset_active_series() {
    is_first = 0;
    resetting = true;
    active_series.length = 0;
    db.view("ordering", "byid", {}, function (err, r) {
        if (err) {
            for (var e in err) { sys.puts(""+e+": "+err[e]) }
            resetting = false;
        } else {
            var current_target_count = 0;
            var previous_target = null;
            var curry_data = [];
            var curry_label = "";
            r.rows.forEach(function (elem, idx) {
                var current = elem.value
                if (current._id.split(":")[0] != previous_target) {
                    if (previous_target) {
                        if (curry_data[curry_data.length-1][1] == 1) { is_first += 1; }
                        active_series.push({
                            label: curry_label,
                            data: JSON.parse(JSON.stringify(curry_data))
                        })
                    }
                    current_target_count = 0;
                    curry_data.length = 0;
                    previous_target = current._id.split(":")[0];
                    curry_label = current.target;
                }
                if (current_target_count < 20) {
                    var d = (new Date(Date.UTC(parseInt(current.date.slice(0,4), 10), parseInt(current.date.slice(4,6), 10), parseInt(current.date.slice(6,8), 10), 0, 0, 0, 0))).getTime();
                    curry_data.push([d, current.placement]);
                    current_target_count += 1;
                }
            });

            if (previous_target) {
                if (curry_data[curry_data.length-1][1] == 1) { is_first += 1; }
                active_series.push({
                    label: curry_label,
                    data: curry_data
                })
            }
            resetting = false;
        }
    })
}

function query_placement() {
    var nao = (new Date());
    var idx = 0;
    target_queries.forEach(function(target, idx) {

        var callback = (function (t) {
            return (function (found_index) {
                var timestamp = ""+nao.getFullYear()+pad(nao.getUTCMonth())+pad(nao.getUTCDate());
                db.saveDoc(keyify(t)+":"+timestamp, {"target": t.name, "query": t.query, "date": timestamp, "placement": found_index}, function (err, doc) {
                    if (err) { throw new Error(JSON.stringify(err)) }
                });
                idx += 1;
            });
        })(target);
        seek(target_url.replace("{QUERY}", target.query), 0, function(val) {
            return (val.indexOf(target.target) >= 0);
        }, callback);
    });
}

// reset on boot;
reset_active_series();

app.get("/reset", function (req, res) {
    reset_active_series();
    res.send("OK");
})

app.get("/seek", function(req, res) {
    query_placement();
    res.render("seek.ejs");
});

app.get("/", function (req, res) {
    var f = (is_first > (active_series.length/2) ? "Yes" : "No");
    f += " ("+is_first+")"
    var current_rankings = [];
    for (var idx in active_series)   {
        rankings = active_series[idx].data;
        current_rankings.push({ label: active_series[idx].label, ranking: rankings[rankings.length-1][1], url: find_url_for_label(active_series[idx].label) });
    }
    res.render("index.ejs", { locals: {
        data: JSON.stringify(active_series),
        first: f,
        rankings: current_rankings
    }});
})

app.listen(process.env.NODE_PORT || 80);<commit_msg>Reseeking allowed.<commit_after>var sys = require("sys");
var connect = require("connect");
var express = require("express");
var fs = require("fs");
var http = require("http");
var target_queries = require("./targets");

cport = process.env.COUCHDB_PORT || 5984;
chost = process.env.COUCHDB_HOST || "localhost";
cuser = process.env.COUCHDB_USER;
cpass = process.env.COUCHDB_PASSWORD;

debug = process.env.DEBUG;
// sys.puts("Connecting to "+cuser+"|"+cpass+"|"+chost+"|"+cport);

if (cuser) {
    var couchdb = require("couchdb").createClient(cport, chost, cuser, cpass);
} else {
    var couchdb = require("couchdb").createClient(cport, chost);
}
var db = couchdb.db("arewefirstyet");

var pub = __dirname + '/public';
var app = express.createServer(
    express.staticProvider(pub)
);

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

var is_first = 0;
var active_series = [];
var resetting = false;

function find_url_for_label(label) {
    var found = null;
    target_queries.forEach(function(elem, idx) {
        if (elem.name === label) {
            found = elem.url;
        }
    });
    return found;
}

var target_url = "/ajax/services/search/web?v=1.0&q={QUERY}&start={PAGE}"
var MAX_PAGES = 10;
var MAX_SPIN = 50;

var user_agents = [
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13",
    "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/533.17.8 (KHTML, like Gecko) Version/5.0.1 Safari/533.17.8",
    "Mozilla/5.0 (Windows; U; Windows NT 6.1; ja-JP) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16",
    "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/7.0.540.0 Safari/534.10",
    "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/7.0.540.0 Safari/534.10",
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.9 (KHTML, like Gecko) Chrome/7.0.531.0 Safari/534.9",
    "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/534.4 (KHTML, like Gecko) Chrome/6.0.481.0 Safari/534.4",
    "Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.462.0 Safari/534.3"
];

function seek (target_url, page, is_found, callback) {
    var ua = user_agents[Math.floor(Math.random()*user_agents.length)];
    var paged_target_url = target_url.replace("{PAGE}", page);
    var google = http.createClient(80, "ajax.googleapis.com");
    var request = google.request('GET',
                                 paged_target_url,
                                 {
                                     "Host": "ajax.googleapis.com",
                                     "User-Agent": ua
                                 });
    if (debug)
      console.log("Requesting "+paged_target_url);
    request.end();
    request.on("response", function (response) {
        var body = "";
        response.on("data", function(chunker) {
            body += chunker;
        });
        response.on("end", function() {
            var data = JSON.parse(body);
            if (data.responseData) {
                var juicybits = data.responseData.results;
                var found_index = -1;
                juicybits.forEach(function(bit, bitcount) {
                    if (is_found(bit.url)) {
                        found_index = page*4 + bitcount;
                        // urls.push({url: bit.url, name: bit.titleNoFormatting})
                    }
                    if (found_index == -1) {
                        // urls.push({url: bit.url, name: bit.titleNoFormatting})
                    }
                });

                if (page == MAX_SPIN) {
                    callback(MAX_SPIN*4);
                } else if (found_index >= 0)
                    callback(found_index+1);
                else {
                    seek(target_url, page+1, is_found, callback);
                }
            } else {
                sys.p("Failure on "+paged_target_url);
            }
        });

    });
}

function pad(n){return n<10 ? '0'+n : n}
function keyify(i) {  return i.name.toLowerCase().replace(/[^a-z0-9]/g,""); }
function reset_active_series() {
    is_first = 0;
    resetting = true;
    active_series.length = 0;
    db.view("ordering", "byid", {}, function (err, r) {
        if (err) {
            for (var e in err) { sys.puts(""+e+": "+err[e]) }
            resetting = false;
        } else {
            var current_target_count = 0;
            var previous_target = null;
            var curry_data = [];
            var curry_label = "";
            r.rows.forEach(function (elem, idx) {
                var current = elem.value
                if (current._id.split(":")[0] != previous_target) {
                    if (previous_target) {
                        if (curry_data[curry_data.length-1][1] == 1) { is_first += 1; }
                        active_series.push({
                            label: curry_label,
                            data: JSON.parse(JSON.stringify(curry_data))
                        })
                    }
                    current_target_count = 0;
                    curry_data.length = 0;
                    previous_target = current._id.split(":")[0];
                    curry_label = current.target;
                }
                if (current_target_count < 20) {
                    var d = (new Date(Date.UTC(parseInt(current.date.slice(0,4), 10), parseInt(current.date.slice(4,6), 10), parseInt(current.date.slice(6,8), 10), 0, 0, 0, 0))).getTime();
                    curry_data.push([d, current.placement]);
                    current_target_count += 1;
                }
            });

            if (previous_target) {
                if (curry_data[curry_data.length-1][1] == 1) { is_first += 1; }
                active_series.push({
                    label: curry_label,
                    data: curry_data
                })
            }
            resetting = false;
        }
    })
}

function query_placement() {
    var nao = (new Date());
    var idx = 0;
    target_queries.forEach(function(target, idx) {

        var callback = (function (t) {
            return (function (found_index) {
                var timestamp = ""+nao.getFullYear()+pad(nao.getUTCMonth())+pad(nao.getUTCDate());
                db.saveDoc(keyify(t)+":"+timestamp, {"target": t.name, "query": t.query, "date": timestamp, "placement": found_index}, function (err, doc) {
                    if (err) {
                      console.log(JSON.stringify(err))
                    }
                });
                idx += 1;
            });
        })(target);
        seek(target_url.replace("{QUERY}", target.query), 0, function(val) {
            return (val.indexOf(target.target) >= 0);
        }, callback);
    });
}

// reset on boot;
reset_active_series();

app.get("/reset", function (req, res) {
    reset_active_series();
    res.send("OK");
})

app.get("/seek", function(req, res) {
    query_placement();
    res.render("seek.ejs");
});

app.get("/", function (req, res) {
    var f = (is_first > (active_series.length/2) ? "Yes" : "No");
    f += " ("+is_first+")"
    var current_rankings = [];
    for (var idx in active_series)   {
        rankings = active_series[idx].data;
        current_rankings.push({ label: active_series[idx].label, ranking: rankings[rankings.length-1][1], url: find_url_for_label(active_series[idx].label) });
    }
    res.render("index.ejs", { locals: {
        data: JSON.stringify(active_series),
        first: f,
        rankings: current_rankings
    }});
})

app.listen(process.env.NODE_PORT || 80);<|endoftext|>


<commit_before>'use strict';

var ex = require('express')();
var http = require('http').Server(ex);
var io = require('socket.io')(http);
var fs = require("fs");

var g = require('./custom-modules/globals.js').Globals;
var settings = require('./custom-modules/settings.js').Settings();
var res = require('./custom-modules/resources.js');
var h = require('./custom-modules/helpers.js');

var map = require('./custom-modules/map.js');
var inv = require('./custom-modules/inventory.js');
var om = require('./custom-modules/object-manager.js');

var sm = new (require('./custom-modules/session-manager.js')).SessionManager();
g.sm = sm;
var objManager = new om.ObjManager(map);
g.om = objManager;
var dto = new (require('./custom-modules/dto.js')).DTO(io, sm);
g.dto = dto;
var app = new (require('./custom-modules/app.js')).App(dto, objManager);
g.app = app;
app.Start();

io.on('connection', (socket) => {
	console.log('session started');
	socket.room = 'unauthenticated';
	socket.join(socket.room);
	socket.on('disconnect', function() {
		console.log('session disconnected');
		if(sm.CloseSession(socket, objManager))
			io.sockets.in(socket.room).emit('message', {user: 'server', text: 'user disconnected', time: Date.now()});
		socket.leave(socket.room);
	});

	socket.on('cli-message', (message) => {
		io.sockets.in(socket.room).emit('message', {
			user : 'user',//data.name,
			text : message,
			timestamp : Date.now()
		});
	});
	socket.on('cli-login', (message) => {
		if(message.u != '') {
			socket.leave(socket.room);
			socket.room = 'authenticated';
			socket.join(socket.room);
			var id = sm.LoadUser(message.u,socket,objManager);
			if(id>=0) {
				socket.name = message.u;
				io.sockets.in(socket.room).emit('message', {user: 'server', text: 'user '+ message.u+' connected', time: Date.now()});
				socket.emit('login-confirm', {
					id : id,
					sid: sm.nextSes-1,
					created: true,
					data: {
						objdata: JSON.stringify(objManager.obj),
						mapdata: JSON.stringify(app.map.grid),
						pfmatrix: JSON.stringify(app.map.pf.pfMatrix),
						itemdata: JSON.stringify(res.itemList),
						npcdata: JSON.stringify(res.npcList),
						mobdata: JSON.stringify(res.mobList),
						questdata: JSON.stringify(res.questList)
					}
				});
				console.log('user authenticated');
			} else {
				socket.emit('login-confirm', {
					id : -1,
					sid: -1,
					created: false,
					data: {
						error: 'Login failed: user ' + message.u + ' does not exist'
					}
				});
			}
		}
	});
	socket.on('cli-register', (message) => {
		if(message.u != '') {
			var file = "./saved-data/users/" + message.u + ".dat";
			if(fs.existsSync(file)) {
				console.log('user ' + message.u + ' already exist!');
				socket.emit('register-confirm', {
					sid: -1,
					error: 'user ' + message.u + ' already exists!'
				});
			} else {
				socket.leave(socket.room);
				socket.room = 'authenticated';
				socket.join(socket.room);
				socket.name = message.u;
				io.sockets.in(socket.room).emit('message', {user: 'server', text: 'user '+ message.u + ' connected', time: Date.now()});
				socket.emit('register-confirm', {
					sid: 0
				});
				console.log('user registered');
			}
		}
	});
	socket.on('cli-create', (message) => {
		var id = sm.CreateUser(message.u,socket,objManager);
		socket.emit('create-confirm', {
			id : id,
			created: true,
			data: {
				objdata: JSON.stringify(objManager.obj),
				mapdata: JSON.stringify(app.map.grid),
				pfmatrix: JSON.stringify(app.map.pf.pfMatrix),
				itemdata: JSON.stringify(res.itemList),
				npcdata: JSON.stringify(res.npcList),
				mobdata: JSON.stringify(res.mobList)
			}
		});
		console.log('user of type '+message.c+' created');
	});

	// Socket user interface events
	socket.on('ui', function(data) {
		var obj = objManager.Get(sm.sessions[sm.StripSID(socket.id)].oid);
		if (obj.action =="dead") {
			if(data.type=='respawn')
				objManager.RespawnUser(obj.id);
			return;
		}

		switch(data.type) {
			case 'mcl':
				obj.moveTo(h.V2(data.data.x,data.data.y),app.map);
				break;
			case 'mclo':
				var t =  objManager.Get(data.data);
				if(t) {
					if(obj.alliance == t.alliance || t.alliance == 0) {
						console.log(obj.name+' follow '+t.name);
						obj.follow(t.id);
					} else {
						console.log(obj.name+' attack '+t.name);
						obj.attack(t.id);
					}
				}
				//console.log(obj.name+' target '+t.name);
				break;
			case 'mcr':
				break;
			case 'drop':
				data = data.data;
				var from,
					to;
				if(data.from && data.to) {
					from = data.from.split("_");
					to = data.to.split("_");
				} else {
					console.log('drop error! data:');
					console.log(data);
					break;
				}
				var fromobj = objManager.Get(from[0]),
					frominv = {},
					toobj = objManager.Get(to[0]),
					toinv = {};
				if (from[1] == 'i') {
					frominv = fromobj.inv;
				}
				else if (from[1] == 'l') {
					frominv = fromobj.loadout;
				} else
					console.log('inv undefined: '+from[1]);
				if (to[1] == 'i') {
					toinv = toobj.inv;
				}
				else if (to[1] == 'l') {
					toinv = toobj.loadout;
				} else
					console.log('inv undefined: '+to[1]);

				var err = inv.MoveItem(frominv.slot[from[2]],toinv.slot[to[2]]);
				if (err!='') {
					console.log(err);
				} else {
					if(from[0] == to[0]) {
						if (toobj.type == 'char') {
							if (from[1] == 'l' || to[1] == 'l') {
								toobj.status = 2;
								toobj.recalcData();
							} else {
								dto.SendTo(to[0],'update_inv',JSON.stringify({l:fromobj.loadout,i:fromobj.inv}));
							}
						}
					} else {
						fromobj.status = 2;
						toobj.status = 2;
					}
				}
				break;
			case 'buy':
				var data = data.data,
					item = res.itemList[data.iid],
					npc = res.npcList[data.npc],
					price = item.value*data.qty*npc.priceMod;

				if(price<obj.money) {obj.inv.AddItemInv(data.iid,data.qty); obj.money -= price; obj.status = 2;} else {console.log('not enough money '+price);}
				break;
			case 'sell':
				var data = data.data,
					item = res.itemList[data.iid],
					npc = res.npcList[data.npc],
					diff = data.qty - obj.inv.RemoveItemInv(data.iid, data.qty);

				if (diff!=0) {
					obj.money += item.value*(diff)/npc.priceMod;
					obj.status = 2;
				}
				break;
			default:
				console.log('Error: unknown "ui" data type '+ data.type);
				break;
		}
	});

	// Socket quest events
	socket.on('quest', function(data) {
		switch(data.type) {
			case 'accept':
				var obj = objManager.Get(sm.sessions[sm.StripSID(socket.id)].oid),
					q = h.objectFindByKey(obj.quest,'id',data.id);
				if(!q) {
					console.log(obj.name + ' accepted quest '+ res.questList[data.id].name);
					obj.quest.push({
						id: data.id,
						status: 'started'
					});
					obj.status = 2;
				}
				break;
			case 'finish':
				var obj = objManager.Get(sm.sessions[sm.StripSID(socket.id)].oid);
				break;
			case 'cancel':
				var obj = objManager.Get(sm.sessions[sm.StripSID(socket.id)].oid),
					q = h.indexFindByKey(obj.quest,'id',data.id);
				if(q!=-1) {
					console.log(obj.name + ' cancelled quest '+ res.questList[data.id].name);
					obj.quest.splice(q, 1);
					obj.status = 2;
				}
				break;
			default:
				console.log('Error: unknown "quest" data type '+ data.type);
				break;
		}
	});
});

function ProcessCommand(socket, data) {
	var command = data.msg.split(" ");
	command[0] =  command[0].substring(1,command[0].length);

	switch(command[0]) {
		case 'start':
			if(!app.playing) {
				app.Start();
			} else {
				console.log('app already running!');
			}
			break;
		case 'stop':
			if(app.playing) {
				app.Stop();
			} else {
				console.log('app already stopped!');
			}
			break;
		case 'save':
			app.Save();
			break;
		case 'load':
			app.Load();
			break;
		default:
			console.log('Unknown command: ' + command[0]);
	}
}

http.listen(5000, () => {
  console.log('started on port 5000');
});
<commit_msg>Server handshake added<commit_after>'use strict';

var ex = require('express')();
var http = require('http').Server(ex);
var io = require('socket.io')(http);
var fs = require("fs");

var g = require('./custom-modules/globals.js').Globals;
var settings = require('./custom-modules/settings.js').Settings();
var res = require('./custom-modules/resources.js');
var h = require('./custom-modules/helpers.js');

var map = require('./custom-modules/map.js');
var inv = require('./custom-modules/inventory.js');
var om = require('./custom-modules/object-manager.js');

var sm = new (require('./custom-modules/session-manager.js')).SessionManager();
g.sm = sm;
var objManager = new om.ObjManager(map);
g.om = objManager;
var dto = new (require('./custom-modules/dto.js')).DTO(io, sm);
g.dto = dto;
var app = new (require('./custom-modules/app.js')).App(dto, objManager);
g.app = app;
app.Start();

io.on('connection', (socket) => {
	console.log('session started');
	socket.room = 'unauthenticated';
	socket.join(socket.room);

	socket.emit('server-handshake', {
		appName:'Enria',
		appSubName:'Online',
		appVersion:'1.0.0'
	});

	socket.on('disconnect', function() {
		console.log('session disconnected');
		if(sm.CloseSession(socket, objManager))
			io.sockets.in(socket.room).emit('message', {user: 'server', text: 'user disconnected', time: Date.now()});
		socket.leave(socket.room);
	});

	socket.on('cli-message', (message) => {
		io.sockets.in(socket.room).emit('message', {
			user : 'user',//data.name,
			text : message,
			timestamp : Date.now()
		});
	});
	socket.on('cli-login', (message) => {
		if(message.u != '') {
			socket.leave(socket.room);
			socket.room = 'authenticated';
			socket.join(socket.room);
			var id = sm.LoadUser(message.u,socket,objManager);
			if(id>=0) {
				socket.name = message.u;
				io.sockets.in(socket.room).emit('message', {user: 'server', text: 'user '+ message.u+' connected', time: Date.now()});
				socket.emit('login-confirm', {
					id : id,
					sid: sm.nextSes-1,
					created: true,
					data: {
						objdata: JSON.stringify(objManager.obj),
						mapdata: JSON.stringify(app.map.grid),
						pfmatrix: JSON.stringify(app.map.pf.pfMatrix),
						itemdata: JSON.stringify(res.itemList),
						npcdata: JSON.stringify(res.npcList),
						mobdata: JSON.stringify(res.mobList),
						questdata: JSON.stringify(res.questList)
					}
				});
				console.log('user authenticated');
			} else {
				socket.emit('login-confirm', {
					id : -1,
					sid: -1,
					created: false,
					data: {
						error: 'Login failed: user ' + message.u + ' does not exist'
					}
				});
			}
		}
	});
	socket.on('cli-register', (message) => {
		if(message.u != '') {
			var file = "./saved-data/users/" + message.u + ".dat";
			if(fs.existsSync(file)) {
				console.log('user ' + message.u + ' already exist!');
				socket.emit('register-confirm', {
					sid: -1,
					error: 'user ' + message.u + ' already exists!'
				});
			} else {
				socket.leave(socket.room);
				socket.room = 'authenticated';
				socket.join(socket.room);
				socket.name = message.u;
				io.sockets.in(socket.room).emit('message', {user: 'server', text: 'user '+ message.u + ' connected', time: Date.now()});
				socket.emit('register-confirm', {
					sid: 0
				});
				console.log('user registered');
			}
		}
	});
	socket.on('cli-create', (message) => {
		var id = sm.CreateUser(message.u,socket,objManager);
		socket.emit('create-confirm', {
			id : id,
			created: true,
			data: {
				objdata: JSON.stringify(objManager.obj),
				mapdata: JSON.stringify(app.map.grid),
				pfmatrix: JSON.stringify(app.map.pf.pfMatrix),
				itemdata: JSON.stringify(res.itemList),
				npcdata: JSON.stringify(res.npcList),
				mobdata: JSON.stringify(res.mobList)
			}
		});
		console.log('user of type '+message.c+' created');
	});

	// Socket user interface events
	socket.on('ui', function(data) {
		var obj = objManager.Get(sm.sessions[sm.StripSID(socket.id)].oid);
		if (obj.action =="dead") {
			if(data.type=='respawn')
				objManager.RespawnUser(obj.id);
			return;
		}

		switch(data.type) {
			case 'mcl':
				obj.moveTo(h.V2(data.data.x,data.data.y),app.map);
				break;
			case 'mclo':
				var t =  objManager.Get(data.data);
				if(t) {
					if(obj.alliance == t.alliance || t.alliance == 0) {
						console.log(obj.name+' follow '+t.name);
						obj.follow(t.id);
					} else {
						console.log(obj.name+' attack '+t.name);
						obj.attack(t.id);
					}
				}
				//console.log(obj.name+' target '+t.name);
				break;
			case 'mcr':
				break;
			case 'drop':
				data = data.data;
				var from,
					to;
				if(data.from && data.to) {
					from = data.from.split("_");
					to = data.to.split("_");
				} else {
					console.log('drop error! data:');
					console.log(data);
					break;
				}
				var fromobj = objManager.Get(from[0]),
					frominv = {},
					toobj = objManager.Get(to[0]),
					toinv = {};
				if (from[1] == 'i') {
					frominv = fromobj.inv;
				}
				else if (from[1] == 'l') {
					frominv = fromobj.loadout;
				} else
					console.log('inv undefined: '+from[1]);
				if (to[1] == 'i') {
					toinv = toobj.inv;
				}
				else if (to[1] == 'l') {
					toinv = toobj.loadout;
				} else
					console.log('inv undefined: '+to[1]);

				var err = inv.MoveItem(frominv.slot[from[2]],toinv.slot[to[2]]);
				if (err!='') {
					console.log(err);
				} else {
					if(from[0] == to[0]) {
						if (toobj.type == 'char') {
							if (from[1] == 'l' || to[1] == 'l') {
								toobj.status = 2;
								toobj.recalcData();
							} else {
								dto.SendTo(to[0],'update_inv',JSON.stringify({l:fromobj.loadout,i:fromobj.inv}));
							}
						}
					} else {
						fromobj.status = 2;
						toobj.status = 2;
					}
				}
				break;
			case 'buy':
				var data = data.data,
					item = res.itemList[data.iid],
					npc = res.npcList[data.npc],
					price = item.value*data.qty*npc.priceMod;

				if(price<obj.money) {obj.inv.AddItemInv(data.iid,data.qty); obj.money -= price; obj.status = 2;} else {console.log('not enough money '+price);}
				break;
			case 'sell':
				var data = data.data,
					item = res.itemList[data.iid],
					npc = res.npcList[data.npc],
					diff = data.qty - obj.inv.RemoveItemInv(data.iid, data.qty);

				if (diff!=0) {
					obj.money += item.value*(diff)/npc.priceMod;
					obj.status = 2;
				}
				break;
			default:
				console.log('Error: unknown "ui" data type '+ data.type);
				break;
		}
	});

	// Socket quest events
	socket.on('quest', function(data) {
		switch(data.type) {
			case 'accept':
				var obj = objManager.Get(sm.sessions[sm.StripSID(socket.id)].oid),
					q = h.objectFindByKey(obj.quest,'id',data.id);
				if(!q) {
					console.log(obj.name + ' accepted quest '+ res.questList[data.id].name);
					obj.quest.push({
						id: data.id,
						status: 'started'
					});
					obj.status = 2;
				}
				break;
			case 'finish':
				var obj = objManager.Get(sm.sessions[sm.StripSID(socket.id)].oid);
				break;
			case 'cancel':
				var obj = objManager.Get(sm.sessions[sm.StripSID(socket.id)].oid),
					q = h.indexFindByKey(obj.quest,'id',data.id);
				if(q!=-1) {
					console.log(obj.name + ' cancelled quest '+ res.questList[data.id].name);
					obj.quest.splice(q, 1);
					obj.status = 2;
				}
				break;
			default:
				console.log('Error: unknown "quest" data type '+ data.type);
				break;
		}
	});
});

function ProcessCommand(socket, data) {
	var command = data.msg.split(" ");
	command[0] =  command[0].substring(1,command[0].length);

	switch(command[0]) {
		case 'start':
			if(!app.playing) {
				app.Start();
			} else {
				console.log('app already running!');
			}
			break;
		case 'stop':
			if(app.playing) {
				app.Stop();
			} else {
				console.log('app already stopped!');
			}
			break;
		case 'save':
			app.Save();
			break;
		case 'load':
			app.Load();
			break;
		default:
			console.log('Unknown command: ' + command[0]);
	}
}

http.listen(5000, "0.0.0.0", () => {
  console.log('started on port 5000');
});
<|endoftext|>


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

'use strict'

var http = require('http')
  , querystring = require('querystring')
  , mime = require('mime')
  , fs = require('fs')
  , url = require('url')
  , util = require('util')
  , minimatch = require('minimatch')
  , httpProxy = require('http-proxy')
  , path = require('path')
  , optimist = require('optimist')

var argv = optimist.
  usage(
    'This server providers a utility to wrap JavaScript\n' +
    'with calls to earhorn$. Additionally, it lets earhorn$\n' +
    'write changes to the file system.\n\n' +
    'Example:\n\n' +
    '  ./server.js --port 8001 --pattern "**/*.js"\n\n' +
    '  This would add earhorn$ to every JavaScript file\n' +
    '  running from the current directory (not recommended\n' +
    '  on large codebases).').
  describe('port', 'Port to run on.').
  describe('cors', 'Access-Control-Allow-Origin header, if specified').
  describe('pattern', 'Url pattern add earhorn$ calls to').
  describe('patternFile', 'File with newline-delimited url patterns').
  describe('verbose', 'Whether to enable verbose logging').
  describe('folder', 'Folder to add earhorn$ calls to').
  describe('runProxy', 'Whether to reverse proxy').
  describe('proxyPort', 'Port of site to reverse proxy').
  describe('proxyHost', 'Host of site to reverse proxy').
  demand('port').
  boolean('runProxy').
  boolean('verbose').
  default('folder', '.').
  default('proxyHost', 'localhost').
  argv

var patternFile = argv.patternFile
  , pattern = argv.pattern
  , cors = argv.cors
  , port = +argv.port
  , folder = argv.folder
  , verbose = argv.verbose || false
  , runProxy = argv.runProxy
  , proxyHost = argv.proxyHost
  , proxyPort = +argv.proxyPort
  , proxy = new httpProxy.RoutingProxy()
  , patterns = []
  , earhornIndexAliases = [ "/earhorn/", "/earhorn/index.html" ]
  , indexFilePath = __dirname + '/index.html'

if(patternFile && pattern) throw '--pattern and --patternFile both specified'
if(patternFile) patterns = fs.readFileSync(patternFile).split('\n')
else if(pattern) patterns = [pattern]
if(proxyPort && !runProxy) throw '--proxyPort specified but no --runProxy'
if(runProxy && !proxyPort) throw '--runProxy specified but no --proxyPort'
if(runProxy && !proxyHost) throw '--runProxy specified but no --proxyHost'
if(verbose) console.log(argv)

function handleError(err, res, code) {
  console.error(err)
  res.statusCode = code || 500
  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify(err))
}

var server = http.createServer(function (req, res) {

  if(req.url === '/earhorn') {
    res.statusCode = 302
    res.setHeader('Location', '/earhorn/')
    return res.end()
  }

  var parsedUrl = url.parse(req.url)
    , query = querystring.parse(parsedUrl.query)
    , pathname = parsedUrl.pathname
    , isEarhornDir = !pathname.indexOf('/earhorn/')
    , isIndex = earhornIndexAliases.indexOf(pathname) >= 0

  var filePath = path.resolve(
    isIndex ? indexFilePath :
    isEarhornDir ? __dirname + '/..' + pathname :
    folder + pathname)

  var type = mime.lookup(filePath)
    , isJs = type === 'application/javascript'

  var matches = patterns.filter(function(p) {
    if(!isJs) return false
    var match = minimatch(pathname, p)
    if(verbose) console.log('testing match', pathname, p, ':', match)
    return match
  })

  if(runProxy && !matches.length && !isIndex && !isEarhornDir) {
    console.log(req.method, req.url, '=>', proxyHost + ':' + proxyPort)
    return proxy.proxyRequest(req, res, { host: proxyHost, port: proxyPort })
  }

  console.log(req.method, req.url, '->', filePath)

  if(pathname.indexOf('..') >= 0)
    return handleError('ellipses in path are invalid', res)

  if(req.method === 'PUT' && !isIndex && !isEarhornDir) {

    var pendingError = null
      , stream = fs.createWriteStream(filePath)

    stream.on('close', function() {
      if(pendingError)
        writeError(pendingError)
      else res.end()
    })

    stream.on('error', function(err) {
      pendingError = err
    })

    req.pipe(stream)

  } else if(req.method === 'HEAD' || req.method === 'GET')

    fs.stat(filePath, function(err, stats) {

      if(err) return handleError(err, res)

      res.setHeader('Last-Modified', stats.mtime)
      res.setHeader("Expires", "Sat, 01 Jan 2000 00:00:00 GMT")
      res.setHeader("Cache-Control",
          "no-store, no-cache, must-revalidate, max-age=0")
      res.setHeader("Cache-Control", "post-check=0, pre-check=0")
      res.setHeader("Pragma", "no-cache")
      res.setHeader('Content-Type', type)

      if(cors) res.setHeader('Access-Control-Allow-Origin', cors)

      fs.readFile(filePath, function(err, data) {

        if(err) return handleError(err, res)

        if(matches.length && !isIndex && !isEarhornDir) {

          var slashIndex = req.url.lastIndexOf('/')
            , name = req.url.substring(slashIndex + 1)
            , ref = 'http://' + req.headers.host + req.url

          data = 'earhorn$("' + ref + '", true, function() {' + data + '})()'
        }

        res.setHeader('Content-Length', Buffer.byteLength(data))

        return req.method === 'HEAD' ? return res.end() : res.end(data)
      })
    })

  else writeError(req.method, res, 405) // Method not allowed.
})

server.listen(port)

console.log('Earhorn server listening on', port)
<commit_msg>Fix syntax error<commit_after>#!/usr/bin/env node

'use strict'

var http = require('http')
  , querystring = require('querystring')
  , mime = require('mime')
  , fs = require('fs')
  , url = require('url')
  , util = require('util')
  , minimatch = require('minimatch')
  , httpProxy = require('http-proxy')
  , path = require('path')
  , optimist = require('optimist')

var argv = optimist.
  usage(
    'This server providers a utility to wrap JavaScript\n' +
    'with calls to earhorn$. Additionally, it lets earhorn$\n' +
    'write changes to the file system.\n\n' +
    'Example:\n\n' +
    '  ./server.js --port 8001 --pattern "**/*.js"\n\n' +
    '  This would add earhorn$ to every JavaScript file\n' +
    '  running from the current directory (not recommended\n' +
    '  on large codebases).').
  describe('port', 'Port to run on.').
  describe('cors', 'Access-Control-Allow-Origin header, if specified').
  describe('pattern', 'Url pattern add earhorn$ calls to').
  describe('patternFile', 'File with newline-delimited url patterns').
  describe('verbose', 'Whether to enable verbose logging').
  describe('folder', 'Folder to add earhorn$ calls to').
  describe('runProxy', 'Whether to reverse proxy').
  describe('proxyPort', 'Port of site to reverse proxy').
  describe('proxyHost', 'Host of site to reverse proxy').
  demand('port').
  boolean('runProxy').
  boolean('verbose').
  default('folder', '.').
  default('proxyHost', 'localhost').
  argv

var patternFile = argv.patternFile
  , pattern = argv.pattern
  , cors = argv.cors
  , port = +argv.port
  , folder = argv.folder
  , verbose = argv.verbose || false
  , runProxy = argv.runProxy
  , proxyHost = argv.proxyHost
  , proxyPort = +argv.proxyPort
  , proxy = new httpProxy.RoutingProxy()
  , patterns = []
  , earhornIndexAliases = [ "/earhorn/", "/earhorn/index.html" ]
  , indexFilePath = __dirname + '/index.html'

if(patternFile && pattern) throw '--pattern and --patternFile both specified'
if(patternFile) patterns = fs.readFileSync(patternFile).split('\n')
else if(pattern) patterns = [pattern]
if(proxyPort && !runProxy) throw '--proxyPort specified but no --runProxy'
if(runProxy && !proxyPort) throw '--runProxy specified but no --proxyPort'
if(runProxy && !proxyHost) throw '--runProxy specified but no --proxyHost'
if(verbose) console.log(argv)

function handleError(err, res, code) {
  console.error(err)
  res.statusCode = code || 500
  res.setHeader('Content-Type', 'application/json')
  res.end(JSON.stringify(err))
}

var server = http.createServer(function (req, res) {

  if(req.url === '/earhorn') {
    res.statusCode = 302
    res.setHeader('Location', '/earhorn/')
    return res.end()
  }

  var parsedUrl = url.parse(req.url)
    , query = querystring.parse(parsedUrl.query)
    , pathname = parsedUrl.pathname
    , isEarhornDir = !pathname.indexOf('/earhorn/')
    , isIndex = earhornIndexAliases.indexOf(pathname) >= 0

  var filePath = path.resolve(
    isIndex ? indexFilePath :
    isEarhornDir ? __dirname + '/..' + pathname :
    folder + pathname)

  var type = mime.lookup(filePath)
    , isJs = type === 'application/javascript'

  var matches = patterns.filter(function(p) {
    if(!isJs) return false
    var match = minimatch(pathname, p)
    if(verbose) console.log('testing match', pathname, p, ':', match)
    return match
  })

  if(runProxy && !matches.length && !isIndex && !isEarhornDir) {
    console.log(req.method, req.url, '=>', proxyHost + ':' + proxyPort)
    return proxy.proxyRequest(req, res, { host: proxyHost, port: proxyPort })
  }

  console.log(req.method, req.url, '->', filePath)

  if(pathname.indexOf('..') >= 0)
    return handleError('ellipses in path are invalid', res)

  if(req.method === 'PUT' && !isIndex && !isEarhornDir) {

    var pendingError = null
      , stream = fs.createWriteStream(filePath)

    stream.on('close', function() {
      if(pendingError)
        writeError(pendingError)
      else res.end()
    })

    stream.on('error', function(err) {
      pendingError = err
    })

    req.pipe(stream)

  } else if(req.method === 'HEAD' || req.method === 'GET')

    fs.stat(filePath, function(err, stats) {

      if(err) return handleError(err, res)

      res.setHeader('Last-Modified', stats.mtime)
      res.setHeader("Expires", "Sat, 01 Jan 2000 00:00:00 GMT")
      res.setHeader("Cache-Control",
          "no-store, no-cache, must-revalidate, max-age=0")
      res.setHeader("Cache-Control", "post-check=0, pre-check=0")
      res.setHeader("Pragma", "no-cache")
      res.setHeader('Content-Type', type)

      if(cors) res.setHeader('Access-Control-Allow-Origin', cors)

      fs.readFile(filePath, function(err, data) {

        if(err) return handleError(err, res)

        if(matches.length && !isIndex && !isEarhornDir) {

          var slashIndex = req.url.lastIndexOf('/')
            , name = req.url.substring(slashIndex + 1)
            , ref = 'http://' + req.headers.host + req.url

          data = 'earhorn$("' + ref + '", true, function() {' + data + '})()'
        }

        res.setHeader('Content-Length', Buffer.byteLength(data))

        return req.method === 'HEAD' ? res.end() : res.end(data)
      })
    })

  else writeError(req.method, res, 405) // Method not allowed.
})

server.listen(port)

console.log('Earhorn server listening on', port)
<|endoftext|>


<commit_before>express = require('express');
app = express();
var routes = require('./backend/routes');
var categories = require('./backend/routes/categories');
var items = require('./backend/routes/items');
require('./backend/load_models');

//require('./backend/rewrites')
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

app.set('views', __dirname + '/frontend/views');
app.set('view engine', 'ejs');
app.use(require('stylus').middleware({src: __dirname + '/frontend/static/'}));
app.use(express.static(__dirname+'/frontend/static'));
app.use('/simple-reg', express.static(__dirname + '/frontend/static'));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(methodOverride());
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);

//app.use(express.errorHandler());
//app.use(express.logger('dev'));

app.get('/', routes.index );
app.get('/adminside/list', items.list );
app.put('/adminside/items/new', items.new );
app.get('/adminside/items/image/:itemId', items.image );
app.get('/adminside/categories', categories.index );
app.put('/adminside/categories/new', categories.new );

var port=process.env.PORT || 3000;
app.listen(port);
console.log('Listening on port '+port);

function logErrors(err, req, res, next) {
    console.error(err.stack);
    next(err);
}

function clientErrorHandler(err, req, res, next) {
    if (req.xhr) {
        res.send(500, { error: 'Something blew up!' });
    } else {
        next(err);
    }
}

function errorHandler(err, req, res, next) {
    res.status(500);
    res.render('error', { error: err });
}<commit_msg>orders.js model<commit_after>express = require('express');
app = express();
var routes = require('./backend/routes');
var categories = require('./backend/routes/categories');
var items = require('./backend/routes/items');
var orders = require('./backend/routes/orders');
require('./backend/mime')
//require('./backend/rewrites')
//moment = require('moment');

require('./backend/load_models');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

app.set('views', __dirname + '/frontend/views');
app.set('view engine', 'ejs');
app.use(require('stylus').middleware({src: __dirname + '/frontend/static/'}));
app.use(express.static(__dirname+'/frontend/static'));
app.use('/simple-reg', express.static(__dirname + '/frontend/static'));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(methodOverride());
app.use(logErrors);
app.use(clientErrorHandler);
app.use(errorHandler);

//app.use(express.errorHandler());
//app.use(express.logger('dev'));

app.get('/', routes.index );
app.put('/orders/submitOrder', orders.submitOrder);
app.put('/adminside/items/new', items.new );
app.get('/adminside/items/image/:itemId', items.image );
app.get('/adminside/categories', categories.index );
app.put('/adminside/categories/new', categories.new );

var port=process.env.PORT || 3000;
app.listen(port);
console.log('Listening on port '+port);

function logErrors(err, req, res, next) {
    console.error(err.stack);
    next(err);
}

function clientErrorHandler(err, req, res, next) {
    if (req.xhr) {
        res.send(500, { error: 'Something blew up!' });
    } else {
        next(err);
    }
}

function errorHandler(err, req, res, next) {
    res.status(500);
    res.render('error', { error: err });
}<|endoftext|>