<commit_before>'use strict';
var express = require('express'),
    app = express(),
    fs = require('fs'),
    http = require('http').Server(app),
    io = require('socket.io')(http);

var question,
    questionsList = JSON.parse(fs.readFileSync('./generatedCountries.json', 'utf8'));

var users = [],
    lastUser = '';

question = getRandomQuestion();

sendQuestion();

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

    io.emit('leaders', users);

  socket.on('user created', function(user){
    io.emit('user greeting', 'Hello, ' + user + '!');
    users.push({name: user, connectionId: socket.id, points: 0, correctAnswersRow: 0});
    io.emit('online users', users);
  });

    io.emit('online users', users);

  socket.on('message', function(msg){
    var answer = msg.message;
    io.emit('message', msg);
    io.emit('answer', checkTheAnswer(answer, socket));

      io.emit('leaders', users);
  });

  socket.on('disconnect', function(){
    for(var i in users){
        if(users[i].connectionId === socket.id){
            users.splice(i, 1);
        }
    }
       io.emit('online users', users);
  });

});

app.set('port', (process.env.PORT || 3000))
app.use(express.static('public'));

http.listen(app.get('port'), function(){
  console.log('listening on *:3000');
});

function sendQuestion(){
    app.get('/question', function(request, response) {
        response.send(question);
    });
}

function getRandomQuestion(){
    var randomQuestion = questionsList[Math.floor(Math.random()*questionsList.length)];
    return JSON.parse(randomQuestion);
}

function checkTheAnswer(userAnswer, socket){

    if(question.answer.toLowerCase() === userAnswer.toLowerCase()){
        users.map(function(user){
            if(user.connectionId === socket.id){

                user.correctAnswersRow = user.correctAnswersRow +1;

                user.points = user.points + user.correctAnswersRow;

            }
            else{
                user.correctAnswersRow = 0;
            }
        });
        question = getRandomQuestion();
        return question;
    }

}

<commit_msg>points system implementation with sorting<commit_after>'use strict';
var express = require('express'),
    app = express(),
    fs = require('fs'),
    http = require('http').Server(app),
    io = require('socket.io')(http);

var question,
    questionsList = JSON.parse(fs.readFileSync('./generatedCountries.json', 'utf8'));

var users = [],
    lastUser = '';

question = getRandomQuestion();

sendQuestion();

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

    io.emit('leaders', users.sort(function(obj1, obj2){
        return obj2.points - obj1.points;
    }));

  socket.on('user created', function(user){
    io.emit('user greeting', 'Hello, ' + user + '!');
    users.push({name: user, connectionId: socket.id, points: 0, correctAnswersRow: 0});
    io.emit('online users', users);
  });

    io.emit('online users', users);

  socket.on('message', function(msg){
    var answer = msg.message;
    io.emit('message', msg);
    io.emit('answer', checkTheAnswer(answer, socket));

      io.emit('leaders', users.sort(function(obj1, obj2){
          return obj2.points - obj1.points;
      }));
  });

  socket.on('disconnect', function(){
    for(var i in users){
        if(users[i].connectionId === socket.id){
            users.splice(i, 1);
        }
    }
       io.emit('online users', users);
  });

});

app.set('port', (process.env.PORT || 3000))
app.use(express.static('public'));

http.listen(app.get('port'), function(){
  console.log('listening on *:3000');
});

function sendQuestion(){
    app.get('/question', function(request, response) {
        response.send(question);
    });
}

function getRandomQuestion(){
    var randomQuestion = questionsList[Math.floor(Math.random()*questionsList.length)];
    return JSON.parse(randomQuestion);
}

function checkTheAnswer(userAnswer, socket){

    if(question.answer.toLowerCase() === userAnswer.toLowerCase()){
        users.map(function(user){
            if(user.connectionId === socket.id){

                user.correctAnswersRow = user.correctAnswersRow +1;

                user.points = user.points + user.correctAnswersRow;

            }
            else{
                user.correctAnswersRow = 0;
            }
        });
        question = getRandomQuestion();
        return question;
    }

}

<|endoftext|>


<commit_before>'use strict';
// Requier all the dependences.
var express               = require('express'),
    bodyParser            = require('body-parser'),
    mongoose              = require('mongoose'),
    passport              = require('passport'),
    seedDB                = require('./seeds'),
    LocalStrategy         = require('passport-local'),
    passportLocalMongoose = require('passport-local-mongoose');

// ===============
// DB Setup ======
// ===============

// Connect to the mongodb database.
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/yelp_camp');

// ===============
// App Setup ======
// ===============

// Set the app
var app = express();

// Create fake data to display.
seedDB();

// Require Models.
var Campground = require('./models/campground'),
    Comment    = require('./models/comment'),
    User       = require('./models/user');

// Serve the assets like css, js and fonts files.
app.use(express.static(__dirname + '/public'));

// Configure the app:
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));

// =====================
// Passport Setup ======
// =====================
app.use(require('express-session')({
    secret: "The world is yours",
    resave: false,
    saveOnInitialized: false
}));
app.use(passport.initialize());
app.use( passport.session() );
passport.use( new LocalStrategy(User.authenticate()));
passport.serializeUser( User.serializeUser() );
passport.deserializeUser( User.deserializeUser() );

// =============
// ROUTES ======
// =============

app.get('/', function(req, res){
    res.render('home');
});

// Index - Show all the campgrounds.
app.get('/campgrounds', function(req, res){
    // get all campgrounds from DB.
    Campground.find({}, function(err, campgrounds){
        if (err) {
            console.log('ERROR: ' + err);
        } else {
            // If no errors occurs then render the campgrounds
            // templae with the data retrive from DB.
            res.render('campgrounds/index', { campgrounds: campgrounds });
        }
    });
} );

// NEW - Display form to make a camp.
app.get('/campgrounds/new', function(req, res){
    res.render('campgrounds/new');
});

// CREATE - Add a new camp to the DB.
app.post('/campgrounds', function(req, res){
    // Get the data from the Request Body.
    var name = req.body.name;
    var img  = req.body.img;
    var desc = req.body.desc;
    var data = { name: name, image: img, description: desc };

    Campground.create( data, function(err, data){
        if (err) {
            console.log('ERROR: ' + err);
        } else {
            console.log('Added new campground: ' + data.name);
            // Redirect back to the campgrounds page.
            res.redirect('/campgrounds');
        }
    });
});

// SHOW - show info about one camp.
app.get('/campgrounds/:id', function(req, res) {
    var id = req.params.id;
    Campground.findById(id).populate('comments').exec(function(err, data){
        if (err) {
            console.log('ERROR: ' + err);
        } else {
            res.render('campgrounds/show', { camp: data });
        }
    });
});

// =====================
// Comments Routes
// =====================

app.get('/campgrounds/:id/comments/new', isLoggedIn,function(req, res){
    Campground.findById(req.params.id, function(err, campground){
        if (err) {
            console.log('Error: ' + err);
        } else {
            res.render('comments/new', { campground: campground });
        }
    });
});

app.post('/campgrounds/:id/comments', isLoggedIn,function(req, res){
    Campground.findById(req.params.id, function(err, campground){
        if (err) {
            console.log('Error: ' + err);
            res.redirect('/campgrounds/' + req.params.id);
        } else {
            Comment.create(req.body.comment, function(err, comment){
                if (err) {
                    console.log('Error: ' + err);
                } else {
                    campground.comments.push(comment);
                    campground.save();
                    res.redirect('/campgrounds/' + campground._id);
                }
            });
        }
    });
});

// =====================
// Auth Routes
// =====================

app.get('/register', function(req, res) {
    res.render('register');
});

app.post('/register', function(req, res) {
    var newUser = new User({ username: req.body.username });
    User.register(newUser, req.body.password, function(err, user){
        if (err) {
            console.log('Error: ' + err);
            return res.render('register');
        }

        passport.authenticate('local')(req, res, function() {
            res.redirect('/campgrounds');
        });

    });
});

app.get('/login', function(req, res) {
    res.render('login');
});

app.post('/login', passport.authenticate('local', {
    'successRedirect': "/campgrounds",
    'failureRedirect': "/login"
}));

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

// Middleware.
function isLoggedIn(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect("/login");
}

// Request Listener.
app.listen(process.env.PORT || 3000, process.env.IP, function() {
    console.log('The YelpCamp server has started');
});
<commit_msg>Add and config multer package for upload files. Add req.user Middleware.<commit_after>(function(){
    'use strict';
    // Requier all the dependences.
    var express               = require('express'),
        bodyParser            = require('body-parser'),
        mongoose              = require('mongoose'),
        passport              = require('passport'),
        seedDB                = require('./seeds'),
        multer                = require('multer'),
        crypto                = require('crypto'),
        mime                  = require('mime'),
        LocalStrategy         = require('passport-local'),
        passportLocalMongoose = require('passport-local-mongoose');

    // ===============
    // DB Setup ======
    // ===============

    // Connect to the mongodb database.
    mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/yelp_camp');

    // ===============
    // App Setup ======
    // ===============

    // Set the app
    var app = express();

    // Create fake data to display.
    seedDB();

    // Require Models.
    var Campground = require('./models/campground'),
        Comment    = require('./models/comment'),
        User       = require('./models/user');

    // Serve the assets like css, js and fonts files.
    app.use(express.static(__dirname + '/public'));

    // Configure the app:
    app.set('view engine', 'ejs');
    app.use(bodyParser.urlencoded({ extended: true }));

    // =====================
    // Passport Setup ======
    // =====================
    app.use(require('express-session')({
        secret: "The world is yours",
        resave: false,
        saveOnInitialized: false
    }));
    app.use(passport.initialize());
    app.use( passport.session() );
    passport.use( new LocalStrategy(User.authenticate()));
    passport.serializeUser( User.serializeUser() );
    passport.deserializeUser( User.deserializeUser() );

    // Middleware to pass users in every template.
    app.use(function(req, res, next) {
        res.locals.user = req.user;
        next();
    });

    // Config multer for upload picture:
    var uploading = multer({
        limits: { fileSize: 1000000, files: 1},
        storage: multer.diskStorage({
            destination: function(req, file, cb) {
                cb(null, __dirname + '/public/img/user_pictures');
            },
            filename: function (req, file, cb) {
                crypto.pseudoRandomBytes(16, function (err, raw) {
                    cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype));
                });
            }
        })
    });

    // =============
    // ROUTES ======
    // =============

    app.get('/', function(req, res){
        res.render('home');
    });

    // Index - Show all the campgrounds.
    app.get('/campgrounds', function(req, res){
        // get all campgrounds from DB.
        Campground.find({}, function(err, campgrounds){
            if (err) {
                console.log('ERROR: ' + err);
            } else {
                // If no errors occurs then render the campgrounds
                // templae with the data retrive from DB.
                res.render('campgrounds/index', { campgrounds: campgrounds });
            }
        });
    } );

    // NEW - Display form to make a camp.
    app.get('/campgrounds/new', function(req, res){
        res.render('campgrounds/new');
    });

    // CREATE - Add a new camp to the DB.
    app.post('/campgrounds', function(req, res){
        // Get the data from the Request Body.
        var name = req.body.name;
        var img  = req.body.img;
        var desc = req.body.desc;
        var data = { name: name, image: img, description: desc };

        Campground.create( data, function(err, data){
            if (err) {
                console.log('ERROR: ' + err);
            } else {
                console.log('Added new campground: ' + data.name);
                // Redirect back to the campgrounds page.
                res.redirect('/campgrounds');
            }
        });
    });

    // SHOW - show info about one camp.
    app.get('/campgrounds/:id', function(req, res) {
        var id = req.params.id;
        Campground.findById(id).populate('comments').exec(function(err, data){
            if (err) {
                console.log('ERROR: ' + err);
            } else {
                res.render('campgrounds/show', { camp: data });
            }
        });
    });

    // =====================
    // Comments Routes
    // =====================

    app.get('/campgrounds/:id/comments/new', isLoggedIn,function(req, res){
        Campground.findById(req.params.id, function(err, campground){
            if (err) {
                console.log('Error: ' + err);
            } else {
                res.render('comments/new', { campground: campground });
            }
        });
    });

    app.post('/campgrounds/:id/comments', isLoggedIn,function(req, res){
        Campground.findById(req.params.id, function(err, campground){
            if (err) {
                console.log('Error: ' + err);
                res.redirect('/campgrounds/' + req.params.id);
            } else {
                Comment.create(req.body.comment, function(err, comment){
                    if (err) {
                        console.log('Error: ' + err);
                    } else {
                        campground.comments.push(comment);
                        campground.save();
                        res.redirect('/campgrounds/' + campground._id);
                    }
                });
            }
        });
    });

    // =====================
    // Auth Routes
    // =====================

    app.get('/register', function(req, res) {
        res.render('register');
    });

    app.post('/register', uploading.single('picture'), function(req, res, next) {
        var newUser = new User({
            username: req.body.username,
            name: req.body.name,
            age: req.body.age,
            email: req.body.email,
            picture: req.file.filename
        });
        User.register(newUser, req.body.password, function(err, user){
            if (err) {
                console.log('Error: ' + err);
                return res.render('register');
            }
            console.log(req.body);
            console.log(req.file);
            passport.authenticate('local')(req, res, function() {
                res.redirect('/campgrounds');
            });

        });
    });

    app.get('/login', function(req, res) {
        res.render('login');
    });

    app.post('/login', passport.authenticate('local', {
        'successRedirect': "/campgrounds",
        'failureRedirect': "/login"
    }));

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

    // Middleware.
    function isLoggedIn(req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        }
        res.redirect("/login");
    }

    // Request Listener.
    app.listen(process.env.PORT || 3000, process.env.IP, function() {
        console.log('The YelpCamp server has started');
    });

})();
<|endoftext|>


<commit_before>var thumbContainers = document.querySelectorAll('.thumbz');
Array.prototype.forEach.call(thumbContainers, function(el) {
	var imgs = el.dataset.imgs.split(',');
	var preload = el.dataset.preload;

	if (!el.src)
		el.src = imgs[0];

	if (preload) {
		imgs.forEach(function(img) {
			var newImage = new Image();
			newImage.src = img;
		});
	}

});

document.addEventListener('mousemove', changeSource, false);
document.addEventListener('touchstart', changeSource, false);
document.addEventListener('touchmove', changeSource, false);

function changeSource(e) {
	var el = e.target;
	if (!el.dataset.imgs)
		return;
	var imgs = el.dataset.imgs.split(',');

	var active = 0;
	var width = el.offsetWidth;
	var section = width / imgs.length;
	var position = e.clientX - el.offsetLeft;
	if (e.type === 'touchmove' || e.type === 'touchstart') {
		position = e.touches[0].clientX;
	}

	for (var i = 0; i < imgs.length; i++) {
		if (position > section * i && active != i) {
			active = i;
		}
	}
	var file = imgs[active].split('/')[1];
	if (el.src.indexOf(file) < 0)
		el.src = imgs[active];
}
<commit_msg>white space<commit_after>var thumbContainers = document.querySelectorAll('.thumbz');
Array.prototype.forEach.call(thumbContainers, function(el) {
	var imgs = el.dataset.imgs.split(',');
	var preload = el.dataset.preload;

	if (!el.src)
		el.src = imgs[0];

	if (preload) { //populates browser cache, otherwise images are loaded on changeSource() if not already in cache
		imgs.forEach(function(img) {
			var newImage = new Image();
			newImage.src = img;
		});
	}

});

document.addEventListener('mousemove', changeSource, false);
document.addEventListener('touchstart', changeSource, false);
document.addEventListener('touchmove', changeSource, false);

function changeSource(e) {
	var el = e.target;
	if (!el.dataset.imgs)
		return;
	var imgs = el.dataset.imgs.split(',');

	var active = 0;
	var width = el.offsetWidth;
	var section = width / imgs.length;
	var position = e.clientX - el.offsetLeft;
	if (e.type === 'touchmove' || e.type === 'touchstart') {
		position = e.touches[0].clientX;
	}

	for (var i = 0; i < imgs.length; i++) {
		if (position > section * i && active != i) {
			active = i;
		}
	}
	var file = imgs[active].split('/')[1];
	if (el.src.indexOf(file) < 0)
		el.src = imgs[active];
}
<|endoftext|>


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

var couchapp = require('./main.js')
  , watch = require('watch')
  , path = require('path')
  , fs = require('fs')
  ;

function abspath (pathname) {
  if (pathname[0] === '/') return pathname
  return path.join(process.cwd(), path.normalize(pathname));
}

function copytree (source, dest) {
  watch.walk(source, function (err  , files) {
    for (i in files) {
      (function (i) {
        if (files[i].isDirectory()) {
          try {
            fs.mkdirSync(i.replace(source, dest), 0755)
          } catch(e) {
            console.log('Could not create '+dest)
          }
        } else {
          fs.readFile(i, function (err, data) {
            if (err) throw err;
            fs.writeFile(i.replace(source, dest), data, function (err) {
              if (err) throw err;
            });
          })
        }
      })(i);
    }
  })
}

function boiler (app) {
  if (app) {
    try { fs.mkdirSync(path.join(process.cwd(), app)) }
    catch(e) {};
  }
  app = app || '.'

  copytree(path.join(__dirname, 'boiler'), path.join(process.cwd(), app));

}

function onBeforePushSync() {
  if (beforePushSyncListener && typeof beforePushSyncListener.onBeforePushSync === "function") {
    beforePushSyncListener.onBeforePushSync();
  }
}
function onAfterPushSync() {
  if (afterPushSyncListener && typeof afterPushSyncListener.onAfterPushSync === "function") {
    afterPushSyncListener.onAfterPushSync();
  }
}
var _isUsingDirectoryConfig;
function isUsingDirectoryConfig() {
  if(_isUsingDirectoryConfig != null)
    return _isUsingDirectoryConfig;
  return _isUsingDirectoryConfig = (process.argv[2].trim() === "-dc");
}

if (process.mainModule && process.mainModule.filename === __filename) {
  var node
    , bin
    , command
    , app
    , couch
    , configDirectory
    , configFileNames
    , apps = []
    , beforePushSyncListener
    , afterPushSyncListener
    ;

  //check for directory-based config, if so then read rather than shift() the arguments: will need to read them again later
  if (isUsingDirectoryConfig()) {
    node = process.argv[0];
    bin = process.argv[1];
    command = process.argv[3];
    configDirectory = process.argv[4];
    couch = process.argv[5];
    configFileNames = fs.readdirSync(configDirectory);
    if (configFileNames) {
      configFileNames.forEach(function (value, index) {
        //any files starting with "app" are included as app files e.g. app.js, app_number1.js etc.
        if (value.indexOf("app") == 0) {
          apps.push(path.join(configDirectory, value));
        }
        //"before" listener must be called beforepushsync.js and be in the config directory
        else if (value.toLowerCase().trim() === "beforepushsync.js") {
          beforePushSyncListener = require(abspath(path.join(configDirectory, "beforepushsync.js")));
        }
        //"after" listener must be called afterpushsync.js and be in the config directory
        else if (value.toLowerCase().trim() === "afterpushsync.js") {
          afterPushSyncListener = require(abspath(path.join(configDirectory, "afterpushsync.js")));
        }
      });
    }
  }
  else {
    node = process.argv.shift();
    bin = process.argv.shift();
    command = process.argv.shift();
    app = process.argv.shift();
    couch = process.argv.shift();
  }

  if (command == 'help' || command == undefined) {
    console.log(
      [ "couchapp -- utility for creating couchapps"
        , ""
        , "Usage:"
        , "(backwardly compatible without switch - single app file)"
        , "  couchapp <command> app.js http://localhost:5984/dbname [opts]"
        , "(directory based config specified by switch - multiple app files and pre- and post-processing capability)"
        , " couchapp -dc <command> <appconfigdirectory> http://localhost:5984/dbname"
        , ""
        , "Commands:"
        , "  push   : Push app once to server."
        , "  sync   : Push app then watch local files for changes."
        , "  boiler : Create a boiler project."
        , "  serve  : Serve couchapp from development webserver"
        , "            you can specify some options "
        , "            -p port  : list on port portNum [default=3000]"
        , "            -d dir   : attachments directory [default='attachments']"
        , "            -l       : log rewrites to couchdb [default='false']"
      ]
      .join('\n')
    )
    process.exit();
  }

  if (isUsingDirectoryConfig()) {
    if (command == 'boiler') {
      for (i in apps) {
        boiler(apps[i]);
      }
    } else {
      onBeforePushSync();
      for (i in apps) {
        //an immediately executed function is used so the loop counter variable is available
        //in createApp's callback function: multiple calls to push/sync are supported and
        //onAfterPushSync is supplied as the callback function on the last call
        (function keepLoopCounter(i) {
          couchapp.createApp(require(abspath(apps[i])), couch, function (app) {
            if (command == 'push') {
              app.push(i == apps.length - 1 ? onAfterPushSync : null);
            }
            else if (command == 'sync') {
              app.sync(i == apps.length ? onAfterPushSync : null);
            }
          });
        })(i);
      }

    }
  }
  else {
    if (command == 'boiler') {
      boiler(app);
    } else {
      couchapp.createApp(require(abspath(app)), couch, function (app) {
        if (command == 'push') app.push()
        else if (command == 'sync') app.sync()
        else if (command == 'serve') serve(app);

      })
    }
  }

}

// Start a development web server on app
function serve(app) {
  var url = require('url');
  var port = 3000,
      staticDir = 'attachments',
      tmpDir = '/tmp/couchapp-compile-' + process.pid,
      logDbRewrites = false;
  var arg;
  while(arg = process.argv.shift()){
    if(arg == '-p'){
      port = parseInt(process.argv.shift());
    }
    if(arg == '-d'){
      staticDir = process.argv.shift();
    }
    if(arg == '-l'){
      logDbRewrites = true;
    }
  }
  var dbUrlObj = url.parse(couch);

  var proxyPaths = {}
  var dbPrefix = '../../';
  for (var i in app.doc.rewrites){
    var rw = app.doc.rewrites[i];
    // Rewrites starting with '../../' are proxied to the database
    if (rw.to.indexOf(dbPrefix) == 0){
      var proxyPath = rw.from;
      if(proxyPath[proxyPath.length -1] == '*') {
        proxyPath = proxyPath.substring(0,proxyPath.length-1)
      }
      var dbPath = rw.to.substring(dbPrefix.length);
      if(dbPath[dbPath.length - 1] == '*'){
        dbPath = dbPath.substring(0,dbPath.length-1)
      }
      if(dbPath.indexOf('*') >=0 ){
        if(logDbRewrites){
          console.log("Don't know how to proxy '" + rw.from + "' to CouchDB at " + rw.from );
        }
      } else {
        proxyPaths[proxyPath] =
          dbUrlObj.protocol + '//' + dbUrlObj.host +
          path.normalize(dbUrlObj.pathname + dbPath);
          if(logDbRewrites){
            console.log("Proxying rewrite '" + proxyPath + "' to CouchDB at " + proxyPaths[proxyPath] );
          }
      }
    }
  }

  var connect = require('connect');
  var httpProxy = require('http-proxy'),
      connect   = require('connect'),
      connectCompiler;
  try{
      connectCompiler = require('connect-compiler');
  } catch(e) {}

  var proxy = new httpProxy.HttpProxy({
    target: {
      host: dbUrlObj.host,
      hostname: dbUrlObj.hostname,
      port: dbUrlObj.port,
      https: dbUrlObj.protocol == 'https:',
    }
  });
  var app = connect()
    .use(connect.logger('dev'))
    .use(connect.static(staticDir));
  if(connectCompiler){
    console.log('Will compile assets with connect-assets.');
    var ignore = [];
    var quote = function(str) {
      return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    }
    for(var prefix in proxyPaths){
      ignore.push(quote(prefix));
    }
    if(ignore.length){
      //console.log("Asset compile ignore paths:", '^(' +  ignore.join('|') + ')');
      ignore  = new RegExp('^(' +  ignore.join('|') + ')');
    } else {
      ignore = null;
    }
    app.use(connectCompiler({
      enabled: ['coffee'] ,
      src: staticDir,
      dest: tmpDir,
      ignore :  ignore,
    }))
    .use(connect.static(tmpDir));
  }
  app.use(function(req, res, next) {
      for(var prefix in proxyPaths){
        var dbPath = proxyPaths[prefix];
        if (req.url.indexOf(prefix) === 0) {
          var dbURL = req.url.replace(prefix,dbPath);
          if(logDbRewrites){
            console.log("*** ", req.url , ' -> ', dbURL);
          }
          req.url = dbURL;
          req.headers['host'] = dbUrlObj.host;
          proxy.proxyRequest(req, res);
          return;
        }
      }
      var body = '404 Not found.\nNo static file or db route matched.';
      res.statusCode = 404;
      res.setHeader('Content-Length', body.length);
      res.end(body);
     })
    .use(connect.errorHandler())
    .listen(port);
  console.log("Serving couchapp at: http://0.0.0.0:" + port +"/");

  //Cleanup the temp directory on exit
  var cleanup = function(){
    var rmDir = function(dirPath) {
      try { var files = fs.readdirSync(dirPath); }
      catch(e) { return; }
      if (files.length > 0)
        for (var i = 0; i < files.length; i++) {
          var filePath = dirPath + '/' + files[i];
          if (fs.statSync(filePath).isFile())
            fs.unlinkSync(filePath);
          else
            rmDir(filePath);
        }
      fs.rmdirSync(dirPath);
    };
    rmDir(tmpDir);
  };
  process.on('exit',cleanup);
  process.on('SIGINT',function(){
    cleanup()
    process.exit();
  });
}

exports.boilerDirectory = path.join(__dirname, 'boiler')

<commit_msg>Optionally read CouchDB url from .couchapp.json (because I don't want passwords on my command line).<commit_after>#!/usr/bin/env node

var couchapp = require('./main.js')
  , watch = require('watch')
  , path = require('path')
  , fs = require('fs')
  ;

function abspath (pathname) {
  if (pathname[0] === '/') return pathname
  return path.join(process.cwd(), path.normalize(pathname));
}

function copytree (source, dest) {
  watch.walk(source, function (err  , files) {
    for (i in files) {
      (function (i) {
        if (files[i].isDirectory()) {
          try {
            fs.mkdirSync(i.replace(source, dest), 0755)
          } catch(e) {
            console.log('Could not create '+dest)
          }
        } else {
          fs.readFile(i, function (err, data) {
            if (err) throw err;
            fs.writeFile(i.replace(source, dest), data, function (err) {
              if (err) throw err;
            });
          })
        }
      })(i);
    }
  })
}

function boiler (app) {
  if (app) {
    try { fs.mkdirSync(path.join(process.cwd(), app)) }
    catch(e) {};
  }
  app = app || '.'

  copytree(path.join(__dirname, 'boiler'), path.join(process.cwd(), app));

}

function onBeforePushSync() {
  if (beforePushSyncListener && typeof beforePushSyncListener.onBeforePushSync === "function") {
    beforePushSyncListener.onBeforePushSync();
  }
}
function onAfterPushSync() {
  if (afterPushSyncListener && typeof afterPushSyncListener.onAfterPushSync === "function") {
    afterPushSyncListener.onAfterPushSync();
  }
}
var _isUsingDirectoryConfig;
function isUsingDirectoryConfig() {
  if(_isUsingDirectoryConfig != null)
    return _isUsingDirectoryConfig;
  return _isUsingDirectoryConfig = (process.argv[2].trim() === "-dc");
}

if (process.mainModule && process.mainModule.filename === __filename) {
  var node
    , bin
    , command
    , app
    , couch
    , configDirectory
    , configFileNames
    , apps = []
    , beforePushSyncListener
    , afterPushSyncListener
    ;

  //check for directory-based config, if so then read rather than shift() the arguments: will need to read them again later
  if (isUsingDirectoryConfig()) {
    node = process.argv[0];
    bin = process.argv[1];
    command = process.argv[3];
    configDirectory = process.argv[4];
    couch = process.argv[5];
    configFileNames = fs.readdirSync(configDirectory);
    if (configFileNames) {
      configFileNames.forEach(function (value, index) {
        //any files starting with "app" are included as app files e.g. app.js, app_number1.js etc.
        if (value.indexOf("app") == 0) {
          apps.push(path.join(configDirectory, value));
        }
        //"before" listener must be called beforepushsync.js and be in the config directory
        else if (value.toLowerCase().trim() === "beforepushsync.js") {
          beforePushSyncListener = require(abspath(path.join(configDirectory, "beforepushsync.js")));
        }
        //"after" listener must be called afterpushsync.js and be in the config directory
        else if (value.toLowerCase().trim() === "afterpushsync.js") {
          afterPushSyncListener = require(abspath(path.join(configDirectory, "afterpushsync.js")));
        }
      });
    }
  }
  else {
    node = process.argv.shift();
    bin = process.argv.shift();
    command = process.argv.shift();
    app = process.argv.shift();
    couch = process.argv.shift();
  }

  if (command == 'help' || command == undefined) {
    console.log(
      [ "couchapp -- utility for creating couchapps"
        , ""
        , "Usage:"
        , "(backwardly compatible without switch - single app file)"
        , "  couchapp <command> app.js http://localhost:5984/dbname [opts]"
        , "(directory based config specified by switch - multiple app files and pre- and post-processing capability)"
        , " couchapp -dc <command> <appconfigdirectory> http://localhost:5984/dbname"
        , ""
        , "Commands:"
        , "  push   : Push app once to server."
        , "  sync   : Push app then watch local files for changes."
        , "  boiler : Create a boiler project."
        , "  serve  : Serve couchapp from development webserver"
        , "            you can specify some options "
        , "            -p port  : list on port portNum [default=3000]"
        , "            -d dir   : attachments directory [default='attachments']"
        , "            -l       : log rewrites to couchdb [default='false']"
      ]
      .join('\n')
    )
    process.exit();
  }

  if (couch == undefined) {
    try {
      couch = JSON.parse(fs.readFileSync('.couchapp.json')).couch;
    } catch (e) {
      // Discard exception: absent or malformed config file
    }
  }

  if (isUsingDirectoryConfig()) {
    if (command == 'boiler') {
      for (i in apps) {
        boiler(apps[i]);
      }
    } else {
      onBeforePushSync();
      for (i in apps) {
        //an immediately executed function is used so the loop counter variable is available
        //in createApp's callback function: multiple calls to push/sync are supported and
        //onAfterPushSync is supplied as the callback function on the last call
        (function keepLoopCounter(i) {
          couchapp.createApp(require(abspath(apps[i])), couch, function (app) {
            if (command == 'push') {
              app.push(i == apps.length - 1 ? onAfterPushSync : null);
            }
            else if (command == 'sync') {
              app.sync(i == apps.length ? onAfterPushSync : null);
            }
          });
        })(i);
      }

    }
  }
  else {
    if (command == 'boiler') {
      boiler(app);
    } else {
      couchapp.createApp(require(abspath(app)), couch, function (app) {
        if (command == 'push') app.push()
        else if (command == 'sync') app.sync()
        else if (command == 'serve') serve(app);

      })
    }
  }

}

// Start a development web server on app
function serve(app) {
  var url = require('url');
  var port = 3000,
      staticDir = 'attachments',
      tmpDir = '/tmp/couchapp-compile-' + process.pid,
      logDbRewrites = false;
  var arg;
  while(arg = process.argv.shift()){
    if(arg == '-p'){
      port = parseInt(process.argv.shift());
    }
    if(arg == '-d'){
      staticDir = process.argv.shift();
    }
    if(arg == '-l'){
      logDbRewrites = true;
    }
  }
  var dbUrlObj = url.parse(couch);

  var proxyPaths = {}
  var dbPrefix = '../../';
  for (var i in app.doc.rewrites){
    var rw = app.doc.rewrites[i];
    // Rewrites starting with '../../' are proxied to the database
    if (rw.to.indexOf(dbPrefix) == 0){
      var proxyPath = rw.from;
      if(proxyPath[proxyPath.length -1] == '*') {
        proxyPath = proxyPath.substring(0,proxyPath.length-1)
      }
      var dbPath = rw.to.substring(dbPrefix.length);
      if(dbPath[dbPath.length - 1] == '*'){
        dbPath = dbPath.substring(0,dbPath.length-1)
      }
      if(dbPath.indexOf('*') >=0 ){
        if(logDbRewrites){
          console.log("Don't know how to proxy '" + rw.from + "' to CouchDB at " + rw.from );
        }
      } else {
        proxyPaths[proxyPath] =
          dbUrlObj.protocol + '//' + dbUrlObj.host +
          path.normalize(dbUrlObj.pathname + dbPath);
          if(logDbRewrites){
            console.log("Proxying rewrite '" + proxyPath + "' to CouchDB at " + proxyPaths[proxyPath] );
          }
      }
    }
  }

  var connect = require('connect');
  var httpProxy = require('http-proxy'),
      connect   = require('connect'),
      connectCompiler;
  try{
      connectCompiler = require('connect-compiler');
  } catch(e) {}

  var proxy = new httpProxy.HttpProxy({
    target: {
      host: dbUrlObj.host,
      hostname: dbUrlObj.hostname,
      port: dbUrlObj.port,
      https: dbUrlObj.protocol == 'https:',
    }
  });
  var app = connect()
    .use(connect.logger('dev'))
    .use(connect.static(staticDir));
  if(connectCompiler){
    console.log('Will compile assets with connect-assets.');
    var ignore = [];
    var quote = function(str) {
      return (str+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
    }
    for(var prefix in proxyPaths){
      ignore.push(quote(prefix));
    }
    if(ignore.length){
      //console.log("Asset compile ignore paths:", '^(' +  ignore.join('|') + ')');
      ignore  = new RegExp('^(' +  ignore.join('|') + ')');
    } else {
      ignore = null;
    }
    app.use(connectCompiler({
      enabled: ['coffee'] ,
      src: staticDir,
      dest: tmpDir,
      ignore :  ignore,
    }))
    .use(connect.static(tmpDir));
  }
  app.use(function(req, res, next) {
      for(var prefix in proxyPaths){
        var dbPath = proxyPaths[prefix];
        if (req.url.indexOf(prefix) === 0) {
          var dbURL = req.url.replace(prefix,dbPath);
          if(logDbRewrites){
            console.log("*** ", req.url , ' -> ', dbURL);
          }
          req.url = dbURL;
          req.headers['host'] = dbUrlObj.host;
          proxy.proxyRequest(req, res);
          return;
        }
      }
      var body = '404 Not found.\nNo static file or db route matched.';
      res.statusCode = 404;
      res.setHeader('Content-Length', body.length);
      res.end(body);
     })
    .use(connect.errorHandler())
    .listen(port);
  console.log("Serving couchapp at: http://0.0.0.0:" + port +"/");

  //Cleanup the temp directory on exit
  var cleanup = function(){
    var rmDir = function(dirPath) {
      try { var files = fs.readdirSync(dirPath); }
      catch(e) { return; }
      if (files.length > 0)
        for (var i = 0; i < files.length; i++) {
          var filePath = dirPath + '/' + files[i];
          if (fs.statSync(filePath).isFile())
            fs.unlinkSync(filePath);
          else
            rmDir(filePath);
        }
      fs.rmdirSync(dirPath);
    };
    rmDir(tmpDir);
  };
  process.on('exit',cleanup);
  process.on('SIGINT',function(){
    cleanup()
    process.exit();
  });
}

exports.boilerDirectory = path.join(__dirname, 'boiler')

<|endoftext|>


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

var net = require('net')
var minimist = require('minimist')
var speedometer = require('speedometer')
var log = require('single-line-stream')
var pretty = require('pretty-bytes')
var pump = require('pump')

var argv = minimist(process.argv.slice(2), {
  alias: {from: 'f', monitor: 'm', help: 'h', to: 't'}
})

if (argv.help) {
  console.error(
    'Usage: tcp-throughput-proxy [options]\n' +
    '  --from, -f     [port]\n' +
    '  --to, -t       [host:port]\n' +
    '  --monitor, -m  [from-port + 1]\n'
  )
  process.exit(0)
}

var proxyPort = 0
var proxyHost = null

if (argv.to) {
  proxyPort = typeof argv.to === 'number' ? argv.to : argv.to.split(':')[1]
  proxyHost = typeof argv.to === 'number' ? '127.0.0.1' : argv.to.split(':')[0]
}

if (!argv.from) argv.from = proxyPort || 10000
if (!argv.monitor) argv.monitor = argv.from + 1

var speed = speedometer()
var connections = 0

var server = net.createServer(function (socket) {
  onsocket(socket)
  if (proxyPort) pump(socket, net.connect(proxyPort, proxyHost), socket)

  connections++
  socket.on('close', function () {
    connections--
  })
  socket.on('data', function (data) {
    speed(data.length)
  })
})

var monitor = net.createServer(function (socket) {
  onsocket(socket)

  var stream = log()
  var interval = setInterval(progress, 500)
  stream.pipe(socket)

  socket.on('close', function () {
    clearInterval(interval)
  })

  function progress () {
    stream.write(connections + ' open connections\nReceiving ' + pretty(speed()) + '/s\n')
  }
})

monitor.listen(argv.monitor, function () {
  server.listen(argv.from, function () {
    if (argv.to) console.log('Proxing to %s from %d', proxyHost + ':' + proxyPort, argv.from)
    else console.log('Server is listening on %d', argv.from)
    console.log('Monitor server is listening on %d', argv.monitor)
  })
})

function onsocket (socket) {
  socket.on('end', function () {
    socket.end()
  })
  socket.on('error', function () {
    socket.destroy()
  })
}
<commit_msg>track sending speed also<commit_after>#!/usr/bin/env node

var net = require('net')
var minimist = require('minimist')
var speedometer = require('speedometer')
var log = require('single-line-stream')
var pretty = require('pretty-bytes')
var pump = require('pump')

var argv = minimist(process.argv.slice(2), {
  alias: {from: 'f', monitor: 'm', help: 'h', to: 't'}
})

if (argv.help) {
  console.error(
    'Usage: tcp-throughput-proxy [options]\n' +
    '  --from, -f     [port]\n' +
    '  --to, -t       [host:port]\n' +
    '  --monitor, -m  [from-port + 1]\n'
  )
  process.exit(0)
}

var proxyPort = 0
var proxyHost = null

if (argv.to) {
  proxyPort = typeof argv.to === 'number' ? argv.to : argv.to.split(':')[1]
  proxyHost = typeof argv.to === 'number' ? '127.0.0.1' : argv.to.split(':')[0]
}

if (!argv.from) argv.from = proxyPort || 10000
if (!argv.monitor) argv.monitor = argv.from + 1

var receiving = speedometer()
var sending = argv.to ? speedometer() : null
var connections = 0

var server = net.createServer(function (socket) {
  if (proxyPort) pump(socket, net.connect(proxyPort, proxyHost).on('data', onsend), socket)
  connections++
  socket.on('end', onend)
  socket.on('error', onerror)
  socket.on('close', onclose)
  socket.on('data', onreceive)
})

var monitor = net.createServer(function (socket) {
  socket.on('end', onend)
  socket.on('error', onerror)

  var stream = log()
  var interval = setInterval(progress, 500)
  stream.pipe(socket)

  socket.on('close', function () {
    clearInterval(interval)
  })

  function progress () {
    stream.write(
      connections + ' open connections\n' +
      'Receiving ' + pretty(receiving()) + '/s\n' +
      (sending ? 'Sending ' + pretty(sending()) + '/s\n' : '')
    )
  }
})

monitor.listen(argv.monitor, function () {
  server.listen(argv.from, function () {
    if (argv.to) console.log('Proxing to %s from %d', proxyHost + ':' + proxyPort, argv.from)
    else console.log('Server is listening on %d', argv.from)
    console.log('Monitor server is listening on %d', argv.monitor)
  })
})

function onreceive (data) {
  receiving(data.length)
}

function onsend (data) {
  sending(data.length)
}

function onclose () {
  connections--
}

function onerror () {
  this.destroy()
}

function onend () {
  this.end()
}
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const cheerio = require('cheerio');
const request = require('superagent');

// Discord client
const bot = new Discord.Client();

const prefix = "!";

bot.on('ready', () => {
        bot.user.setGame('!commands for help');
});

bot.on('message', (message) => {

    if (!message.content.startsWith(prefix)) return;

    var args = message.content.substring(prefix.length).split(" ");
    var query = message.content.substring(6);
    var charLook = message.content.substring(9);
    var aqChar = message.content.substring(8);

    if (message.channel.id === '334783038162468864' || '248515210082648064') {
        switch (args[0].toLowerCase()) {
            case "commands":
                message.channel.send("The following are the commands used in this channel.");
                message.channel.send({embed: {
                    color: 3447003,
                    fields: [{
                        name: "!aqwchar",
                        value: "Syntax: !aqwchar <Player>\nThis looks up the character page of your desire.",
                    },
                    {
                        name: "!sellback",
                        value: "Syntax: !sellback <Price> <AC/Gold>\nThis tells you the sellback price of the item. AC Items will tell produce 'Before/After 24 Hours' values.",
                    },
                    {
                        name: "!wiki",
                        value: "Syntax: !wiki <query>\nThis searches the AQW wikidot for the query you have inputed.",
                    }]
                }});
            break;
            case "aqwchar":
                var char = charLook.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("Link: http://www.aq.com/character.asp?id=" + char.join("%20"));
                }
                else message.channel.sendMessage("Please specify a name after !aqwchar");
                break;
            case "sellback":
                var price = args[1];
                var curr = args[2];

                function isInt(price) {
                    return !isNaN(price) && price > 0 && (function(price) { return (price | 0) === price; })(parseFloat(price)); }

                if (isInt(price) == true) {
                    if ((/Gold/i).test(curr) == true) {
                        message.channel.sendMessage("The sellback price is** " + Math.ceil(price * 0.25) + " Gold.**");
                    }
                    else if ((/AC/i).test(curr) == true) {
                        message.channel.sendMessage("Before 24 hours: **" + Math.ceil(price * 0.90) + " AC**" + "\nAfter 24 hours: **" + Math.ceil(price * 0.25) + " AC**");
                    }
                    else message.reply("Please use the following syntax: !sellback <Price> <AC/Gold>")
                }
                else if (price > 0 || price == 0) {
                        message.channel.sendMessage("Please enter a (smaller) non-zero positive integer.");
                }
                else message.channel.sendMessage("That's not right!");
                break;
            case "wiki":
                var term = query.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("Wiki search: http://aqwwiki.wikidot.com/search:site/q/" + term.join("+")); }
                else message.channel.sendMessage("Please specify what you want to search after !wiki");
                break;
        }
    }

    if (message.channel.id === '355188935900790786') {
        switch (args[0].toLowerCase()) {
            case "commands":
                message.channel.send("The following are the commands used in this channel.");
                message.channel.send({embed: {
                    color: 3447003,
                    fields: [{
                        name: "!3dchar",
                        value: "Syntax: !3dchar <Player>\nThis looks up the character page of your desire.",
                    },
                    {
                        name: "!wiki",
                        value: "Syntax: !wiki <query>\nThis searches the AQ3D wikidot for the query you have inputed.",
                    }]
                }});
            break;
           /* case "3dchar":
                var char = aqChar.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("https://game.aq3d.com/account/Character?id=" + char.join("%20"));
                }
                else message.channel.sendMessage("Please specify a name after !3dchar");
                break; */
            case "wiki":
                var term = query.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("Wiki search: http://aq-3d.wikidot.com/search:site/q/" + term.join("%20")); }
                else message.channel.sendMessage("Please specify what you want to search after !wiki");
                break;
        }
    }
});

bot.login('MzU1MjM4MDcyODY4MTQzMTE0.DKcxNw.lczUqB0eXEWhpKwMqTNn-t-UhWk')<commit_msg>token<commit_after>const Discord = require('discord.js');
const cheerio = require('cheerio');
const request = require('superagent');

// Discord client
const bot = new Discord.Client();

const prefix = "!";

bot.on('ready', () => {
        bot.user.setGame('!commands for help');
});

bot.on('message', (message) => {

    if (!message.content.startsWith(prefix)) return;

    var args = message.content.substring(prefix.length).split(" ");
    var query = message.content.substring(6);
    var charLook = message.content.substring(9);
    var aqChar = message.content.substring(8);

    if (message.channel.id === '334783038162468864' || '248515210082648064') {
        switch (args[0].toLowerCase()) {
            case "commands":
                message.channel.send("The following are the commands used in this channel.");
                message.channel.send({embed: {
                    color: 3447003,
                    fields: [{
                        name: "!aqwchar",
                        value: "Syntax: !aqwchar <Player>\nThis looks up the character page of your desire.",
                    },
                    {
                        name: "!sellback",
                        value: "Syntax: !sellback <Price> <AC/Gold>\nThis tells you the sellback price of the item. AC Items will tell produce 'Before/After 24 Hours' values.",
                    },
                    {
                        name: "!wiki",
                        value: "Syntax: !wiki <query>\nThis searches the AQW wikidot for the query you have inputed.",
                    }]
                }});
            break;
            case "aqwchar":
                var char = charLook.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("Link: http://www.aq.com/character.asp?id=" + char.join("%20"));
                }
                else message.channel.sendMessage("Please specify a name after !aqwchar");
                break;
            case "sellback":
                var price = args[1];
                var curr = args[2];

                function isInt(price) {
                    return !isNaN(price) && price > 0 && (function(price) { return (price | 0) === price; })(parseFloat(price)); }

                if (isInt(price) == true) {
                    if ((/Gold/i).test(curr) == true) {
                        message.channel.sendMessage("The sellback price is** " + Math.ceil(price * 0.25) + " Gold.**");
                    }
                    else if ((/AC/i).test(curr) == true) {
                        message.channel.sendMessage("Before 24 hours: **" + Math.ceil(price * 0.90) + " AC**" + "\nAfter 24 hours: **" + Math.ceil(price * 0.25) + " AC**");
                    }
                    else message.reply("Please use the following syntax: !sellback <Price> <AC/Gold>")
                }
                else if (price > 0 || price == 0) {
                        message.channel.sendMessage("Please enter a (smaller) non-zero positive integer.");
                }
                else message.channel.sendMessage("That's not right!");
                break;
            case "wiki":
                var term = query.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("Wiki search: http://aqwwiki.wikidot.com/search:site/q/" + term.join("+")); }
                else message.channel.sendMessage("Please specify what you want to search after !wiki");
                break;
        }
    }

    if (message.channel.id === '355188935900790786') {
        switch (args[0].toLowerCase()) {
            case "commands":
                message.channel.send("The following are the commands used in this channel.");
                message.channel.send({embed: {
                    color: 3447003,
                    fields: [{
                        name: "!3dchar",
                        value: "Syntax: !3dchar <Player>\nThis looks up the character page of your desire.",
                    },
                    {
                        name: "!wiki",
                        value: "Syntax: !wiki <query>\nThis searches the AQ3D wikidot for the query you have inputed.",
                    }]
                }});
            break;
            case "wiki":
                var term = query.split(" ");
                if (typeof args[1] !== 'undefined') {
                    message.channel.sendMessage("Wiki search: http://aq-3d.wikidot.com/search:site/q/" + term.join("%20")); }
                else message.channel.sendMessage("Please specify what you want to search after !wiki");
                break;
        }
    }
});
var token = process.env.BOT_TOKEN;
bot.login(token)<|endoftext|>


<commit_before>

const Discord = require('discord.js');
const bot = new Discord.Client();

const authJson = require('./auth.json');
const token = authJson.token;
const unirest = require("unirest");

var newUsers = new Discord.Collection();

var myUsername;
var myFullUsername;
var myId;
var myPrefix = '$';

/****************************************************/
/* INITIALIZATION ----------------------------------*/
/****************************************************/

bot.on("ready", () => {
  myUsername = bot.user.username;
  myFullUsername = bot.user.username + '#' + bot.user.discriminator;
  myId = bot.user.id;

  console.log(`Log-in successful as user ${myUsername}, userstring ${myFullUsername}, and ID ${myId}.`);
  console.log(`Ready to server in ${bot.channels.size} channels on ${bot.guilds.size} servers, for a total of ${bot.users.size} users.`);
});

/****************************************************/
/* EVENTS (MESSAGE) --------------------------------*/
/****************************************************/

bot.on('message', (message) => {
  // Only continues if message has prefix & is by user
  let prefix = '`';
  if (!message.content.startsWith(prefix)) return;
  if(message.author.bot) return;

  // Commands
  if (message.content === prefix + 'ping') {
    message.reply('pong');
  }

  else if (message.content.startsWith(prefix + 'ping2')) {
    message.channel.sendMessage('pong2!');
  }

  else if (message.content.startsWith(prefix + 'foo')) {
    message.channel.sendMessage('bar');
  }

  else if (message.content.startsWith(prefix + 'repeat ')) {
    message.channel.sendMessage(message.content.slice(8));
  }

  else if (message.content === prefix + 'what is my avatar') {
    // send the user's avatar URL
    message.reply(message.author.avatarURL);
  }
});

bot.on("guildMemberAdd", (member) => {
  newUsers.set(member.user.id, member.user);
});

/****************************************************/
/* EVENTS (MESSAGE 2) ------------------------------*/
/****************************************************/

bot.on('message', (msg) => {

  let prefix = myPrefix;
  // make sure the message has the proper prefix
  if (!msg.content.startsWith(prefix)) return;
  // make sure the message is not sent by the self or other bots
  if (msg.author.bot) return;

  // immediately log "the message author (username + discriminator) has triggered a message event! (message: ______)
  console.log(`[MESSAGE EVENT] ${msg.author.username}#${msg.author.discriminator} || Message: "${msg.content}"`);

  // split message by space and separate command from arguments.
  let cmdText = msg.content.split(" ")[0].slice(1).toLowerCase();
  var args;
  if (msg.content.split(" ").length > 1) {
    args = msg.content.split(" ").slice(1);
  }

  // using the bot (Client) and the original message context, run the command.
  let cmd = commandsInfo[cmdText];
  if (!cmd) {
    msg.channel.sendMessage(`Sorry, I don't recognize this as a valid command: \`${cmdText}\`.`);
  } else {
    cmd.process(bot, msg, args);
  }

});

/****************************************************/
/* EVENTS (DISCONNECTION) --------------------------*/
/****************************************************/
// All commands are in lowercase. Inputs will be converted to lowercase.

var commandsInfo = {
  "who": {
    description: "Bot introduces themselves.",
    process: (bot, oMsg) => {
      oMsg.channel.sendMessage(`Hi. My full name is ${bot.user.username}#${bot.user.discriminator}, but you can call me ${bot.user.username}.`);
      return;
    }
  },

  "id": {
    description: "Return the ID, either of the specified user or of the message author.",
    process: (bot, oMsg) => {
      oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, your user ID is ${oMsg.author.id}.`);
      return;
    }
  },

  "nickname": {
    description: "Return the nickname of the message author.",
    process: (bot, oMsg) => {
      let nickname = getNickname(oMsg.author.id, oMsg.guild);
      if (!nickname) {
        oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, you don't appear to have a nickname on this guild!`);
      } else {
        oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, your nickname on this server seems to be ${nickname}!`);
      }

      return;
    }
  },

  "setprefix": {
    description: "Change the prefix used to summon the bot. Must be 1 character. Default is $.",
    usage: "<newprefix>",
    process: (bot, oMsg, args) => {
      if (args.length != 1 || args[0].length != 1) {
        oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, you must specify exactly one 1-character prefix.`);
      } else {
        oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, my command prefix is now ${args[0]}.`);
        myPrefix = args[0];
      }

      return;
    }
  },

  "pokedex": {
    description: "Search the pokedex for a pokemon species based on dex number.",
    usage: "<National Dex number>",
    process: (bot, oMsg, args) => {
      // Make sure input is valid
      if (args.length < 1 || isNaN(args[0])) {
        oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, :writing_hand: :1234:`);
        return;
      }

      var RequestPokeapi = unirest.get("http://pokeapi.co/api/v2/pokemon-species/" + args[0]);

      RequestPokeapi.header({
        'Accept': 'application/json',
        'User-Agent': 'Unirest Node.js for Oasiris\'s Discord HristBot'
      })
      .end((res) => {
        var data = res.body;
        var info;

        if (!data || data.detail == "Not found.") {
          oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, please supply a valid Pokedex ID. Note that Sun/Moon pokemon are not yet available!`);
          return;
        }

        // Some pre-processing to keep code organized
        // Padding the ID
        data.id = String(data.id);
        var paddedId = data.id[2] ? data.id : (data.id[1] ? `0${data.id}` : `00${data.id}`);

        // Gender
        var genderDetails;
        if (data.gender_rate == -1)
          genderDetails = "Genderless";
        else {
          var femaleRate = Math.round(data.gender_rate / 8 * 1000) / 10;
          var maleRate = 100 - femaleRate;
          genderDetails = `${maleRate}% male, ${femaleRate}% female`;
        }

        // Hatch steps
        var minHatch, maxHatch, hatchArray = new Array(4);
        hatchArray[0] = 256 * data.hatch_counter;
        hatchArray[1] = 256 * (data.hatch_counter + 1);
        hatchArray[2] = 255 * (data.hatch_counter + 1);
        hatchArray[3] = 257 * data.hatch_counter;
        hatchArray.sort((a, b) => a - b);
        minHatch = hatchArray[0];
        maxHatch = hatchArray[3];

        // Egg group
        var eggGroupString;
        if (data.egg_groups.length == 2)
          eggGroupString = capStr(data.egg_groups[0].name) + " and " + capStr(data.egg_groups[1].name);
        else
          eggGroupString = capStr(data.egg_groups[0].name);

        // Evolves-from
        var evolvesFromString;
        if (data.evolves_from_species == null)
          evolvesFromString = "Basic Pokemon";
        else
          evolvesFromString = `Evolves from ${capStr(data.evolves_from_species.name)}`;

        // generation-i --> Generation I
        var genNumeral = data.generation.name.slice(11).toUpperCase();

        // Pokedex entries.
        var entriesString = "";
        var flavorTextArr = data.flavor_text_entries;
        flavorTextArr = flavorTextArr.filter((ele) => {return (ele.language.name == "en" && (ele.version.name == "alpha-sapphire" || ele.version.name == "omega-ruby" || ele.version.name == "y" || ele.version.name == "x"))});
        // console.log(flavorTextArr);

        // console.log(flavorTextArr[1].flavor_text);
        // console.log(entriesString.indexOf(flavorTextArr[1].flavor_text));

        for (ele in flavorTextArr) {
          entry = removeLineBreaks(flavorTextArr[ele].flavor_text);
          if (entriesString.indexOf(entry) == -1) {
            entriesString += '"' + entry + '"\n';
          }
        }

        info = `#${paddedId}`
             + "\n" + `${capStr(data.names[0].name)}`
             + "\n" + `${capStr(data.genera[0].genus)} Pokemon`
             + "\n" + `Color: ${capStr(data.color.name)}`
             + "\n" + `Body: ${capStr(data.shape.name)}`
             + "\n"
             + "\n" + evolvesFromString
             + "\n" + `Introduced in Generation ${genNumeral}`
             + "\n" + `Found in ${capStr(data.habitat ? data.habitat.name : "unknown")} areas`
             + "\n"
             + "\n" + genderDetails
             + "\n" + `Catch rate: ${data.capture_rate}`
             + "\n" + `Hatch time: ${minHatch} - ${maxHatch} steps`
             + "\n" + `Leveling rate: ${capStr(data.growth_rate.name)}`
             + "\n" + `Base friendship: ${data.base_happiness}`
             + "\n" + `Egg Groups: ${eggGroupString}`
             + "\n"
             + "\n" + "Pokedex Entries:"
             + "\n" + entriesString;

        oMsg.channel.sendMessage(info);
      });

      return;
    }
  },

/*
guild.roles.map((roleObject) => {

return roleObject;
});

check for:
hoist
members (in collection form)
name
position
mentionable
permissions
*/

}

/****************************************************/
/* HELPER COMMANDS ---------------------------------*/
/****************************************************/

// Given a user ID, returns the guild nickname.
var getNickname = (str, guild) => {
  str = String(str);
  if (str.trim().length != 18) return;
  return guild.members.get(str).nickname;
};

var capStr = (str) => str.charAt(0).toUpperCase() + str.slice(1);

var removeLineBreaks = (str) => {
  return String(str).replace(/\r?\n|\r/g, " ");
};

/****************************************************/
/* SERVER LOGIN   ----------------------------------*/
/****************************************************/

bot.login(token); <commit_msg>Increased functionality of pokedex & split command lists<commit_after>
// Core dependencies
const Discord = require('discord.js');
const bot = new Discord.Client();
const authJson = require('./auth.json');
const token = authJson.token;

// Extra dependencies
const unirest = require("unirest");

// Imported data JSONs
const simpleDex = require("./data/simplePokedex-v1");

var newUsers = new Discord.Collection();

var myUsername;
var myFullUsername;
var myId;
var myPrefix = '$';

/****************************************************/
/* INITIALIZATION ----------------------------------*/
/****************************************************/

bot.on("ready", () => {
  myUsername = bot.user.username;
  myFullUsername = bot.user.username + '#' + bot.user.discriminator;
  myId = bot.user.id;

  console.log(`Log-in successful as user ${myUsername}, userstring ${myFullUsername}, and ID ${myId}.`);
  console.log(`Ready to server in ${bot.channels.size} channels on ${bot.guilds.size} servers, for a total of ${bot.users.size} users.`);
});

/****************************************************/
/* EVENTS (MESSAGE) --------------------------------*/
/****************************************************/

bot.on('message', (message) => {
  // Only continues if message has prefix & is by user
  let prefix = '`';
  if (!message.content.startsWith(prefix)) return;
  if(message.author.bot) return;

  // Commands
  if (message.content === prefix + 'ping') {
    message.reply('pong');
  }

  else if (message.content.startsWith(prefix + 'ping2')) {
    message.channel.sendMessage('pong2!');
  }

  else if (message.content.startsWith(prefix + 'foo')) {
    message.channel.sendMessage('bar');
  }

  else if (message.content.startsWith(prefix + 'repeat ')) {
    message.channel.sendMessage(message.content.slice(8));
  }

  else if (message.content === prefix + 'what is my avatar') {
    // send the user's avatar URL
    message.reply(message.author.avatarURL);
  }
});

bot.on("guildMemberAdd", (member) => {
  newUsers.set(member.user.id, member.user);
});

/****************************************************/
/* EVENTS (MESSAGE 2) ------------------------------*/
/****************************************************/

bot.on('message', (msg) => {

  let prefix = myPrefix;
  // make sure the message has the proper prefix
  if (!msg.content.startsWith(prefix)) return;
  // make sure the message is not sent by the self or other bots
  if (msg.author.bot) return;

  // immediately log "the message author (username + discriminator) has triggered a message event! (message: ______)
  console.log(`[MESSAGE EVENT] ${msg.author.username}#${msg.author.discriminator} || Message: "${msg.content}"`);

  // split message by space and separate command from arguments.
  let cmdText = msg.content.split(" ")[0].slice(1).toLowerCase();
  var args;
  if (msg.content.split(" ").length > 1) {
    args = msg.content.split(" ").slice(1);
  }

  // Compile all commands into a list
  var listOfCommands = mergeCommands([commandsInfo, commandsPokemon]);

  // SPECIAL COMMAND: "help" or "commands"
  if (cmdText == "help" || cmdText == "commands") {
    commandsHelp.help.process(bot, msg, listOfCommands);
    return;
  }

  // using the bot (Client) and the original message context, run the command.
  let cmd = listOfCommands[cmdText];
  if (!cmd) {
    msg.channel.sendMessage(`Sorry, I don't recognize this as a valid command: \`${cmdText}\`.`);
  } else {
    cmd.process(bot, msg, args);
  }

});

/****************************************************/
/* LIST OF COMMANDS --------------------------------*/
/****************************************************/
// All commands are in lowercase. Inputs will be converted to lowercase.

var commandsHelp = {
  "help": {
    description: "Displays every other command with a helpful description.",
    process: (bot, oMsg, listOfCommands) => {
      var res = "Here's all of the commands I have:\n\n";
      for (c in listOfCommands) {
        // If the command has a "usage" key, spit that out too.
        // Example: '  • @Aqua servers - Lists servers this bot is currently connected to.'a
        var usage = listOfCommands[c].usage;
        if (!usage) usage = "";
        else usage = " " + usage;

        var desc = listOfCommands[c].description;
        if (!desc) desc = "";
        else desc = "- " + desc;

        res += `  • \`${myPrefix}${c}${usage}\` ${desc}\n`;
      } // end for loop
      oMsg.channel.sendMessage(res);
      return;
    }
  }

};

var commandsInfo = {
  "who": {
    description: "Bot introduces themselves.",
    process: (bot, oMsg) => {
      oMsg.channel.sendMessage(`Hi. My full name is ${bot.user.username}#${bot.user.discriminator}, but you can call me ${bot.user.username}.`);
      return;
    }
  },

  "id": {
    description: "Return the ID, either of the specified user or of the message author.",
    process: (bot, oMsg) => {
      oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, your user ID is ${oMsg.author.id}.`);
      return;
    }
  },

  "nickname": {
    description: "Return the nickname of the message author.",
    process: (bot, oMsg) => {
      let nickname = getNickname(oMsg.author.id, oMsg.guild);
      if (!nickname) {
        oMsg.channel.sendMessage(`${oMsg.author.username}, you don't appear to have a nickname on this guild!`);
      } else {
        oMsg.channel.sendMessage(`${oMsg.author.username}, your nickname on this server seems to be ${nickname}!`);
      }

      return;
    }
  },

  "abeljohn": {
    description: "Summon an image of our leader and savior, Abel John Jacob.",
    process: (bot, oMsg) => {
      let imageUrl = "http://i.imgur.com/JqKzbUw.jpg";
      oMsg.channel.sendMessage(imageUrl);

      return;
    }
  },

  "setprefix": {
    description: "Change the prefix used to summon the bot. Must be 1 character. Default is $.",
    usage: "<newprefix>",
    process: (bot, oMsg, args) => {
      if (args.length != 1 || args[0].length != 1) {
        oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, you must specify exactly one 1-character prefix.`);
      } else {
        oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, my command prefix is now ${args[0]}.`);
        myPrefix = args[0];
      }

      return;
    }
  },

};

/*
guild.roles.map((roleObject) => {

return roleObject;
});

check for:
hoist
members (in collection form)
name
position
mentionable
permissions
*/

var commandsPokemon = {

  "pokedex": {
    description: "Shows general information on a given Pokemon species.",
    usage: "<Pokemon name OR National Dex number>",
    process: (bot, oMsg, args) => {
      // Make sure input is valid
      if (args.length != 1) {
        oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, please supply either a Dex number or a Pokemon name.`);
        return;
      };

      var typeString = "";
      var nextEvoString = "Evolves to ";
      var simpleData; // Data on the specified Pokemon, as retrieved from the simpleDex

      // If pokemon name is entered, search local pokemon registry to dex number
      if (isNaN(args[0])) {
        let tempDex = simpleDex;
        tempDex = tempDex.filter((ele) => {
          return (ele.name.toLowerCase().indexOf(args[0].toLowerCase()) != -1);
        });

        if (tempDex.length == 1) { // The correct match
          simpleData = args[0];
          args[0] = tempDex[0].national_id;
        } else if (tempDex.length == 0) { // Misc. error handling
          oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, I couldn't find that Pokemon. Check your spelling and try again.`);
          return;
        } else if (tempDex.length > 10) {
          oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, more than 10 Pokemon match the query, "${args[0]}". Please make your search more specific.`);
          return;
        } else { // number of matches is between 2 and 10
          var res = `<@!${oMsg.author.id}>, your query returned multiple results. See below:\n\n`;
          for (p in tempDex) { // note: p is a numeral index
            res += `  • ${tempDex[p].name}\n`;
          };
          res += "\nCheck your spelling and try again.";
          oMsg.channel.sendMessage(res);
          return;
        }
      };

      // // Retrieve simpleDex data object, simpleData
      // if (!isNaN(args[0])) {
      //   let tempDex = simpleDex;
      //   tempDex = templeDex.fliter((ele) => {
      //     return args[0] == ele.national_id;
      //   });
      //   if () {
      //     simpleData = simpleDex[0];
      //   }
      // }

      // GET request to PokeAPI v2
      var RequestPokeapi = unirest.get("http://pokeapi.co/api/v2/pokemon-species/" + args[0]);
      RequestPokeapi.header({
        'Accept': 'application/json',
        'User-Agent': 'Unirest Node.js for Oasiris\'s Discord HristBot'
      })
      .end((res) => {
        var data = res.body;
        var info;

        if (!data || data.detail == "Not found.") {
          oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, please supply a valid Pokedex ID. Note that Sun/Moon pokemon are not yet available!`);
          return;
        };

        // Some pre-processing to keep code organized
        // Padding the ID
        data.id = String(data.id);
        var paddedId = data.id[2] ? data.id : (data.id[1] ? `0${data.id}` : `00${data.id}`);

        // Gender
        var genderDetails;
        if (data.gender_rate == -1) {
          genderDetails = "Genderless";
        } else {
          var femaleRate = Math.round(data.gender_rate / 8 * 1000) / 10;
          var maleRate = 100 - femaleRate;
          genderDetails = `${maleRate}% male, ${femaleRate}% female`;
        };

        // Hatch steps
        var minHatch, maxHatch, hatchArray = new Array(4);
        hatchArray[0] = 256 * data.hatch_counter;
        hatchArray[1] = 256 * (data.hatch_counter + 1);
        hatchArray[2] = 255 * (data.hatch_counter + 1);
        hatchArray[3] = 257 * data.hatch_counter;
        hatchArray.sort((a, b) => a - b);
        minHatch = hatchArray[0];
        maxHatch = hatchArray[3];

        // Egg group
        var eggGroupString;
        if (data.egg_groups.length == 2)
          eggGroupString = capStr(data.egg_groups[0].name) + " and " + capStr(data.egg_groups[1].name);
        else
          eggGroupString = capStr(data.egg_groups[0].name);

        // Evolves-from
        var evolvesFromString;
        if (data.evolves_from_species == null)
          evolvesFromString = "Basic Pokemon";
        else
          evolvesFromString = `Evolves from ${capStr(data.evolves_from_species.name)}`;

        // generation-i --> Generation I
        var genNumeral = data.generation.name.slice(11).toUpperCase();

        // Pokedex entries.
        var entriesString = "";
        var flavorTextArr = data.flavor_text_entries;
        flavorTextArr = flavorTextArr.filter((ele) => {return (ele.language.name == "en" && (ele.version.name == "alpha-sapphire" || ele.version.name == "omega-ruby" || ele.version.name == "y" || ele.version.name == "x"))});
        // console.log(flavorTextArr);

        // console.log(flavorTextArr[1].flavor_text);
        // console.log(entriesString.indexOf(flavorTextArr[1].flavor_text));

        for (ele in flavorTextArr) {
          entry = removeLineBreaks(flavorTextArr[ele].flavor_text);
          if (entriesString.indexOf(entry) == -1) {
            entriesString += '"' + entry + '"\n';
          }
        }

        info = `#${paddedId}`
             + "\n" + `${capStr(data.names[0].name)}`
             + "\n" + `${capStr(data.genera[0].genus)} Pokemon`
             + "\n" + `Color: ${capStr(data.color.name)}`
             + "\n" + `Body: ${capStr(data.shape.name)}`
             + "\n"
             + "\n" + evolvesFromString
             + "\n" + `Introduced in Generation ${genNumeral}`
             + "\n" + `Found in ${capStr(data.habitat ? data.habitat.name : "unknown")} areas`
             + "\n"
             + "\n" + genderDetails
             + "\n" + `Catch rate: ${data.capture_rate}`
             + "\n" + `Hatch time: ${minHatch} - ${maxHatch} steps`
             + "\n" + `Leveling rate: ${capStr(data.growth_rate.name)}`
             + "\n" + `Base friendship: ${data.base_happiness}`
             + "\n" + `Egg Groups: ${eggGroupString}`
             + "\n"
             + "\n" + "Pokedex Entries:"
             + "\n" + entriesString;

        oMsg.channel.sendMessage(info);
      });

      return;
    }
  },

  "battledex": {
    description: "Shows battle-related information on a given Pokemon species.",
    usage: "<Pokemon name OR National Dex number>",
    process: (bot, oMsg, args) => {
      // Make sure input is valid
      if (args.length != 1) {
        oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, please supply either a Dex number or a Pokemon name.`);
        return;
      };

      var typeString = "";
      var nextEvoString = "Evolves to ";
      var simpleData; // Data on the specified Pokemon, as retrieved from the simpleDex

      // If pokemon name is entered, search local pokemon registry to dex number
      if (isNaN(args[0])) {
        let tempDex = simpleDex;
        tempDex = tempDex.filter((ele) => {
          return (ele.name.toLowerCase().indexOf(args[0].toLowerCase()) != -1);
        });

        if (tempDex.length == 1) { // The correct match
          simpleData = args[0];
          args[0] = tempDex[0].national_id;
        } else if (tempDex.length == 0) { // Misc. error handling
          oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, I couldn't find that Pokemon. Check your spelling and try again.`);
          return;
        } else if (tempDex.length > 10) {
          oMsg.channel.sendMessage(`<@!${oMsg.author.id}>, more than 10 Pokemon match the query, "${args[0]}". Please make your search more specific.`);
          return;
        } else { // number of matches is between 2 and 10
          var res = `<@!${oMsg.author.id}>, your query returned multiple results. See below:\n\n`;
          for (p in tempDex) { // note: p is a numeral index
            res += `  • ${tempDex[p].name}\n`;
          };
          res += "\nCheck your spelling and try again.";
          oMsg.channel.sendMessage(res);
          return;
        }
      };
    } // ends process
  },

};

/****************************************************/
/* HELPER COMMANDS ---------------------------------*/
/****************************************************/

// Given a user ID, returns the guild nickname.
var getNickname = (str, guild) => {
  str = String(str);
  if (str.trim().length != 18) return;
  return guild.members.get(str).nickname;
};

// Capitalize the first level of a string.
var capStr = (str) => str.charAt(0).toUpperCase() + str.slice(1);

// Remove any line breaks from a string.
var removeLineBreaks = (str) => {
  return String(str).replace(/\r?\n|\r/g, " ");
};

// If there are multiple commands lists, merges them into one.
var mergeCommands = (argArray) => {
  var listOfCommands = {};
  for (var i = 0; i < argArray.length; i ++) {
    for (let key in argArray[i]) {
      listOfCommands[key] = argArray[i][key];
    }
  }

  return listOfCommands;
}

/****************************************************/
/* SERVER LOGIN   ----------------------------------*/
/****************************************************/

bot.login(token); <|endoftext|>