<commit_before>
var passport = require('passport'),
  // LocalStrategy = require('passport-local').Strategy,
  // TwitterStrategy = require('passport-twitter').Strategy,
  FacebookStrategy = require('passport-facebook-canvas').Strategy;
  // FacebookStrategy = require('passport-facebook').Strategy;

/**
 * Configure advanced options for the Express server inside of Sails.
 *
 * For more information on configuration, check out:
 * http://sailsjs.org/#documentation
 */
/*global User*/

module.exports.http = {

  middleware: {
    400: function ( req, res, next ) {
      return res.badRequest();
    },
    404: function ( req, res, next ) {
      return res.notFound();
    },
    500: function ( req, res, next ) {
      return res.serverError();
    }
  },
  customMiddleware: function (app) {
    sails.log.debug('+ Init Sails Midleware');

    var express = require('../node_modules/sails/node_modules/express');
    var path = require('path');

    app.set('tz', 'UTC-5');
    app.use('/', express.static(path.resolve(sails.config.paths.public)));
    app.use('/website/static', express.static(path.resolve(__dirname, '../web-scraper/public')));
    app.use('/content/image', express.static(path.resolve(__dirname, '../content/image')));

    passport.use(new FacebookStrategy({
      clientID: sails.config.application_auth.facebookClientID,
      clientSecret: sails.config.application_auth.facebookClientSecret,
      callbackURL: sails.config.application_auth.facebookCallbackURL,
      profileFields: sails.config.application_auth.facebookAppProfileField,
      enableProof: true
    }, verifyHandler));

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

passport.serializeUser(function (user, done) {
  // sails.log.debug("serializeUser:", user);
  done(null, user.uid);
});

passport.deserializeUser(function (uid, done) {
  // sails.log.debug("deserializeUser:", uid);
  User.findOne({uid: uid}, function (err, user) {
    if(!err && user)
      done(err, user);
    else {
      sails.log.warn('Invalid deserializeUser');
      done(err,null);
    }
  });
});

var verifyHandler = function (token, tokenSecret, profile, done) {
  process.nextTick(function () {
    // Check handler
    // sails.log.debug('=> verifyHandler with ', token, tokenSecret);

    // Debug of information returned by Facebook
    // sails.log.debug('+ Profile Facebook >',profile);

    User.findOne({ or: [
      { uid: profile.id },
      { name: profile.displayName || profile.name ,
        email: profile.email || profile.emails[0].value || profile._json.email }
      ]}, function (err, user) {

      try{
      if (user) {
        // sails.log.debug(user);

        user.token = token;
        if(user.uid !== profile.id)
        {
          User.update({id: user.id },{uid: profile.id}).exec(function(err,updated){
            if(err){
              return done(err,null);
            }
            sails.log('+ Update info of user',updated)
            user.uid = profile.id;
            return done(null, user);
          });

        }else{
          return done(null, user);
        }

      } else {

        var data = {
          provider: profile.provider || 'facebook',
          uid: profile.id,
          name: profile.displayName || profile.name
        };

        if ( profile._json || profile.email || profile.emails[0]) {
          data.email =  profile.email || profile.emails[0].value || profile._json.email;
        }

        if (profile.name && (profile.name.givenName || profile.first_name)) {
          data.firstname = (profile.name.givenName || profile.first_name);
        }
        if (profile.name && (profile.name.familyName || profile.last_name)) {
          data.lastname = profile.name.familyName || profile.last_name;
        }

        if(_.isUndefined(data.name) || _.isEmpty(data.name)){
          data.name = data.firstname+' '+ (profile.middle_name || '')+ data.lastname;
        }

        if (profile.gender) {
          data.gender = profile.gender;
        }
        if (profile.birthday || profile._json) {
          data.birthday = profile.birthday || profile._json.birthday;
        }
        if (profile.profileUrl || profile.link  ) {
          data.profileUrl = profile.profileUrl || profile.link;
        }

        User.create(data, function (err, user) {
          sails.log.debug('+ User create',user);
          return done(err, user);
        });

      }
      }
      catch(e){
        sails.log.warn('- Passport Facebook',e);
      }
    });
  });
};
<commit_msg>Update express file<commit_after>
var passport = require('passport'),
  // LocalStrategy = require('passport-local').Strategy,
  // TwitterStrategy = require('passport-twitter').Strategy,
  FacebookStrategy = require('passport-facebook-canvas').Strategy;
  // FacebookStrategy = require('passport-facebook').Strategy;

/**
 * Configure advanced options for the Express server inside of Sails.
 *
 * For more information on configuration, check out:
 * http://sailsjs.org/#documentation
 */
/*global User*/

module.exports.http = {

  middleware: {
    400: function ( req, res, next ) {
      return res.badRequest();
    },
    404: function ( req, res, next ) {
      return res.notFound();
    },
    500: function ( req, res, next ) {
      return res.serverError();
    }
  },
  customMiddleware: function (app) {
    sails.log.debug('+ Init Sails Midleware');

    var express = require('../node_modules/sails/node_modules/express');
    var path = require('path');

    app.set('tz', 'UTC-5');
    app.use('/', express.static(path.resolve(sails.config.paths.public)));
    app.use('/website/static', express.static(path.resolve(__dirname, '../web-scraper/public')));
    app.use('/content/image', express.static(path.resolve(__dirname, '../content/image')));

    passport.use(new FacebookStrategy({
      clientID: sails.config.application_auth.facebookClientID,
      clientSecret: sails.config.application_auth.facebookClientSecret,
      callbackURL: sails.config.application_auth.facebookCallbackURL,
      profileFields: sails.config.application_auth.facebookAppProfileField,
      enableProof: true
    }, verifyHandler));

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

passport.serializeUser(function (user, done) {
  // sails.log.debug("serializeUser:", user);
  done(null, user.uid);
});

passport.deserializeUser(function (uid, done) {
  // sails.log.debug("deserializeUser:", uid);
  User.findOne({uid: uid}, function (err, user) {
    if(!err && user)
      done(err, user);
    else {
      sails.log.warn('Invalid deserializeUser');
      done(err,null);
    }
  });
});

var verifyHandler = function (token, tokenSecret, profile, done) {
  process.nextTick(function () {
    // Check handler
    // sails.log.debug('=> verifyHandler with ', token, tokenSecret);

    // Debug of information returned by Facebook
    // sails.log.debug('+ Profile Facebook >',profile);

    User.findOne({ or: [
      { uid: profile.id },
      { name: profile.displayName || profile.name ,
        email: profile.email || profile.emails[0].value || profile._json.email }
      ]}, function (err, user) {

      try{
      if (user) {
        // sails.log.debug(user);

        user.token = token;
        if(user.uid !== profile.id)
        {
          User.update({id: user.id },{uid: profile.id}).exec(function(err,updated){
            if(err){
              return done(err,null);
            }
            sails.log('+ Update info of user',updated)
            user.uid = profile.id;
            return done(null, user);
          });

        }else{
          return done(null, user);
        }

      } else {

        var data = {
          provider: profile.provider || 'facebook',
          uid: profile.id,
          name: profile.displayName || profile.name
        };

        if ( (profile._json && profile._json.email) || profile.email || profile.emails[0]) {
          data.email =  profile.email || profile.emails[0].value || profile._json.email;
        }

        if (profile.name && (profile.name.givenName || profile.first_name)) {
          data.firstname = (profile.name.givenName || profile.first_name);
        }
        if (profile.name && (profile.name.familyName || profile.last_name)) {
          data.lastname = profile.name.familyName || profile.last_name;
        }

        if(_.isUndefined(data.name) || _.isEmpty(data.name)){
          data.name = data.firstname+' '+ (profile.middle_name || '')+ (data.lastname || '');
        }

        if (profile.gender) {
          data.gender = profile.gender;
        }
        if (profile.birthday || (profile._json && profile._json.birthday)) {
          data.birthday = profile.birthday || profile._json.birthday;
        }
        if (profile.profileUrl || profile.link  ) {
          data.profileUrl = profile.profileUrl || profile.link;
        }

        User.create(data, function (err, user) {
          sails.log.debug('+ User create',user);
          return done(err, user);
        });

      }
      }
      catch(e){
        sails.log.warn('- Passport Facebook',e);
      }
    });
  });
};
<|endoftext|>


<commit_before>module.exports = function(skill, info, bot, message, db) {
    var channelID = {
    channel: "bar"
    };
  db.save(channelID, function(err, id){
  // id is a unique ID
    });
  var userData = message.text.match(/\<(.*?)\>/g);  //suss out any @mentions of users
  if (userData) {
    // if there is a user is mentioned initiate the challenge!
    //console.log(userData[0].replace(/[^\w\s]/gi, ''));
    var challenged = userData[0].replace(/[^\w\s]/gi, '');

    bot.api.users.info({user: challenged}, (error, response) => {
        bot.reply(message, ':rotating_light: @' + response.user.name + ' you have been challenged to a game of ROCK:mountain: , PAPER:spiral_note_pad: , SCISSORS:scissors:! Prepare to defend your honor!');
    });
    //playerShoot(message.user);
    bot.startPrivateConversation(message, privateConvo(bot, message));
    //bot.reply(message,'Let\'s rumble' + userData[0].replace(/[^\w\s]/gi, ''));
  } else {//if no user challenged
    bot.reply(message, 'You didn\'t challenge anyone you chicken shit! :chicken: :poop:');
  }

function privateConvo(bot, message) {
  const { user, channel } = message;

  return (err, convo) => {
    if (err) throw err;
    var rnd = Math.floor(Math.random()* 65);
    var encouragementArray = [
    'I believe in you!',
    'I\'m sure you\'ll do your best!',
    'you\'re already a winner in my book!',
    'nothing can stop you!',
    'you have the eye of the tiger',
    'you have the heart of a champion',
    'your lucky numbers are ' + rnd + ', ' + rnd + ', ' + rnd + ', ' + rnd + ', ' + rnd + '.',
    'take no prisoners!',
    'Rock! On second thought- Paper! No Wait! Scissors...actually IDK',
    'Paper! No- Rock! No Wait! Scissors; I made things worse, sorry.',
    'Shoot them signs junior!',
    'Paper is on a roll!',
    'Cut em with scissors!',
    'Steady like a rock!',
    'give no quarter, and expect none either!',
    'no retreat, no surrender!',
    'I\'m not friends with losers, so try not to lose, eh?',
    'If you\'re not first you\'re last!',
    'if you lose, don\'t bother coming home.',
    'nothing can conquer your indomitable spirit!'
    ];
    var randomEncouragement = Math.floor(Math.random()* encouragementArray.length);
    convo.ask('Do you want to play `paper`, `rock`, or `scissors`? No matter what you choose, just remember- ' + encouragementArray[randomEncouragement], [
      {
        pattern: 'paper|rock|scissors',
        callback(response, convo) {
          // since no further messages are queued after this,
          // the conversation will end naturally with status === 'completed'
          convo.next();
        },
      }, {
        default: true,
        callback(response, convo) {
          convo.repeat();
          convo.next();
        },
      },
    ], { key: 'rockPaperScissors' }); // store the results in a field called rockPaperScissors

    convo.on('end', (convo) => {
      if (convo.status === 'completed') {
        const prc = convo.extractResponse('rockPaperScissors');

        db.get(channel, (err, data) => {
          if (err) throw err;

          const updateData = data;
          updateData.players[user].played = prc;

          const { players } = updateData;
          const playerIDs = Object.keys(players);

          // check if only one player has played
          const onlyOnePlayed = playerIDs.find((id) => players[id].played === '');

          if (onlyOnePlayed) {
            db.save(updateData, (err) => {
              if (err) throw err;

              bot.reply(message, `<@${user}> has played!`);
            });
          } else {
            const gameResults = playerIDs.map((id) => `<@${id}> played ${players[id].played}`);

            bot.reply(message, gameResults.join(' & '));

            // reset the game data
            db.save({ id: updateData.id }, (err) => {
              if (err) throw err;
            });
          }
        });
      } else {
        // this happens if the conversation ended prematurely for some reason
        bot.reply(message, 'OK, nevermind!');
      }
    });
  };
}

  var gameEngine = require('./Rock-Paper-Spock');

    //bot.api.users.info({user: message.user}, (error, response) => {
        //bot.reply(message, 'Rock Paper Scissors (lizard, spock, spiderman, batman, wizard, glock?)');
    //})

  var instance = new gameEngine(gameEngine.DefaultRules);
  instance.addPlayer({id: 1, sign: "paper"});
  instance.addPlayer({id: 2, sign: "rock"});
  instance.play();
  console.log(instance.winner);
  //note players that won-lost, add support for W-L records
  //bot.reply(message, 'test successful. maybe code something more useful next time?');
};
<commit_msg>Update RockPaperScissors.js<commit_after>module.exports = function(skill, info, bot, message, db) {
  db.save(message.channel, '', function(err, id){
  // id is a unique ID
    });
  var userData = message.text.match(/\<(.*?)\>/g);  //suss out any @mentions of users
  if (userData) {
    // if there is a user is mentioned initiate the challenge!
    //console.log(userData[0].replace(/[^\w\s]/gi, ''));
    var challenged = userData[0].replace(/[^\w\s]/gi, '');

    bot.api.users.info({user: challenged}, (error, response) => {
        bot.reply(message, ':rotating_light: @' + response.user.name + ' you have been challenged to a game of ROCK:mountain: , PAPER:spiral_note_pad: , SCISSORS:scissors:! Prepare to defend your honor!');
    });
    //playerShoot(message.user);
    bot.startPrivateConversation(message, privateConvo(bot, message));
    //bot.reply(message,'Let\'s rumble' + userData[0].replace(/[^\w\s]/gi, ''));
  } else {//if no user challenged
    bot.reply(message, 'You didn\'t challenge anyone you chicken shit! :chicken: :poop:');
  }

function privateConvo(bot, message) {
  const { user, channel } = message;

  return (err, convo) => {
    if (err) throw err;
    var rnd = Math.floor(Math.random()* 65);
    var encouragementArray = [
    'I believe in you!',
    'I\'m sure you\'ll do your best!',
    'you\'re already a winner in my book!',
    'nothing can stop you!',
    'you have the eye of the tiger',
    'you have the heart of a champion',
    'your lucky numbers are ' + rnd + ', ' + rnd + ', ' + rnd + ', ' + rnd + ', ' + rnd + '.',
    'take no prisoners!',
    'Rock! On second thought- Paper! No Wait! Scissors...actually IDK',
    'Paper! No- Rock! No Wait! Scissors; I made things worse, sorry.',
    'Shoot them signs junior!',
    'Paper is on a roll!',
    'Cut em with scissors!',
    'Steady like a rock!',
    'give no quarter, and expect none either!',
    'no retreat, no surrender!',
    'I\'m not friends with losers, so try not to lose, eh?',
    'If you\'re not first you\'re last!',
    'if you lose, don\'t bother coming home.',
    'nothing can conquer your indomitable spirit!'
    ];
    var randomEncouragement = Math.floor(Math.random()* encouragementArray.length);
    convo.ask('Do you want to play `paper`, `rock`, or `scissors`? No matter what you choose, just remember- ' + encouragementArray[randomEncouragement], [
      {
        pattern: 'paper|rock|scissors',
        callback(response, convo) {
          // since no further messages are queued after this,
          // the conversation will end naturally with status === 'completed'
          convo.next();
        },
      }, {
        default: true,
        callback(response, convo) {
          convo.repeat();
          convo.next();
        },
      },
    ], { key: 'rockPaperScissors' }); // store the results in a field called rockPaperScissors

    convo.on('end', (convo) => {
      if (convo.status === 'completed') {
        const prc = convo.extractResponse('rockPaperScissors');

        db.get(channel, (err, data) => {
          if (err) throw err;

          const updateData = data;
          updateData.players[user].played = prc;

          const { players } = updateData;
          const playerIDs = Object.keys(players);

          // check if only one player has played
          const onlyOnePlayed = playerIDs.find((id) => players[id].played === '');

          if (onlyOnePlayed) {
            db.save(updateData, (err) => {
              if (err) throw err;

              bot.reply(message, `<@${user}> has played!`);
            });
          } else {
            const gameResults = playerIDs.map((id) => `<@${id}> played ${players[id].played}`);

            bot.reply(message, gameResults.join(' & '));

            // reset the game data
            db.save({ id: updateData.id }, (err) => {
              if (err) throw err;
            });
          }
        });
      } else {
        // this happens if the conversation ended prematurely for some reason
        bot.reply(message, 'OK, nevermind!');
      }
    });
  };
}

  var gameEngine = require('./Rock-Paper-Spock');

    //bot.api.users.info({user: message.user}, (error, response) => {
        //bot.reply(message, 'Rock Paper Scissors (lizard, spock, spiderman, batman, wizard, glock?)');
    //})

  var instance = new gameEngine(gameEngine.DefaultRules);
  instance.addPlayer({id: 1, sign: "paper"});
  instance.addPlayer({id: 2, sign: "rock"});
  instance.play();
  console.log(instance.winner);
  //note players that won-lost, add support for W-L records
  //bot.reply(message, 'test successful. maybe code something more useful next time?');
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var fs = require('fs'),
	http = require('http'),
	https = require('https'),
	express = require('express'),
	morgan = require('morgan'),
	bodyParser = require('body-parser'),
	session = require('express-session'),
	compress = require('compression'),
	methodOverride = require('method-override'),
	cookieParser = require('cookie-parser'),
	helmet = require('helmet'),
	passport = require('passport'),
	mongoStore = require('connect-mongo')({
		session: session
	}),
	flash = require('connect-flash'),
	config = require('./config'),
	consolidate = require('consolidate'),
	path = require('path');

module.exports = function(db) {
	// Initialize express app
	var app = express();

	// Globbing model files
	config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});

	// Setting application local variables
	app.locals.title = config.app.title;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.facebookAppId = config.facebook.clientID;
	app.locals.jsFiles = config.getJavaScriptAssets();
	app.locals.cssFiles = config.getCSSAssets();

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		res.locals.url = req.protocol + '://' + req.headers.host + req.url;
		next();
	});

	// Should be placed before express.static
	app.use(compress({
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Showing stack errors
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded({
		extended: true
	}));
	app.use(bodyParser.json());
	app.use(methodOverride());

	// CookieParser should be above session
	app.use(cookieParser());

	// Express MongoDB session storage
	app.use(session({
		saveUninitialized: true,
		resave: true,
		secret: config.sessionSecret,
		store: new mongoStore({
			db: db.connection.db,
			collection: config.sessionCollection
		})
	}));

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

	// connect flash for flash messages
	app.use(flash());

	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.xssFilter());
	app.use(helmet.nosniff());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');

	// Setting the app router and static folder
	app.use(express.static(path.resolve('./public')));

	// Globbing routing files
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});

	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Error page
		res.status(500).render('500', {
			error: err.stack
		});
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found'
		});
	});

	if (process.env.NODE_ENV === 'secure') {
		// Log SSL usage
		console.log('Securely using https protocol');

		// Load SSL key and certificate
		var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8');
		var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8');

		// Create HTTPS Server
		var httpsServer = https.createServer({
			key: privateKey,
			cert: certificate
		}, app);

		// Return HTTPS server instance
		return httpsServer;
	}

	// Return Express server instance
	return app;
};<commit_msg>Fix issue with mongodb connection<commit_after>'use strict';

/**
 * Module dependencies.
 */
var fs = require('fs'),
	http = require('http'),
	https = require('https'),
	express = require('express'),
	morgan = require('morgan'),
	bodyParser = require('body-parser'),
	session = require('express-session'),
	compress = require('compression'),
	methodOverride = require('method-override'),
	cookieParser = require('cookie-parser'),
	helmet = require('helmet'),
	passport = require('passport'),
	mongoStore = require('connect-mongo')({
		session: session
	}),
	flash = require('connect-flash'),
	config = require('./config'),
	consolidate = require('consolidate'),
	path = require('path');

module.exports = function(db) {
	// Initialize express app
	var app = express();

	// Globbing model files
	config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
		require(path.resolve(modelPath));
	});

	// Setting application local variables
	app.locals.title = config.app.title;
	app.locals.description = config.app.description;
	app.locals.keywords = config.app.keywords;
	app.locals.facebookAppId = config.facebook.clientID;
	app.locals.jsFiles = config.getJavaScriptAssets();
	app.locals.cssFiles = config.getCSSAssets();

	// Passing the request url to environment locals
	app.use(function(req, res, next) {
		res.locals.url = req.protocol + '://' + req.headers.host + req.url;
		next();
	});

	// Should be placed before express.static
	app.use(compress({
		filter: function(req, res) {
			return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
		},
		level: 9
	}));

	// Showing stack errors
	app.set('showStackError', true);

	// Set swig as the template engine
	app.engine('server.view.html', consolidate[config.templateEngine]);

	// Set views path and view engine
	app.set('view engine', 'server.view.html');
	app.set('views', './app/views');

	// Environment dependent middleware
	if (process.env.NODE_ENV === 'development') {
		// Enable logger (morgan)
		app.use(morgan('dev'));

		// Disable views cache
		app.set('view cache', false);
	} else if (process.env.NODE_ENV === 'production') {
		app.locals.cache = 'memory';
	}

	// Request body parsing middleware should be above methodOverride
	app.use(bodyParser.urlencoded({
		extended: true
	}));
	app.use(bodyParser.json());
	app.use(methodOverride());

	// CookieParser should be above session
	app.use(cookieParser());

	// Express MongoDB session storage
	app.use(session({
		saveUninitialized: true,
		resave: true,
		secret: config.sessionSecret,
		store: new mongoStore({
			mongooseConnection: db.connection,
			collection: config.sessionCollection
		})
	}));

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

	// connect flash for flash messages
	app.use(flash());

	// Use helmet to secure Express headers
	app.use(helmet.xframe());
	app.use(helmet.xssFilter());
	app.use(helmet.nosniff());
	app.use(helmet.ienoopen());
	app.disable('x-powered-by');

	// Setting the app router and static folder
	app.use(express.static(path.resolve('./public')));

	// Globbing routing files
	config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
		require(path.resolve(routePath))(app);
	});

	// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
	app.use(function(err, req, res, next) {
		// If the error object doesn't exists
		if (!err) return next();

		// Log it
		console.error(err.stack);

		// Error page
		res.status(500).render('500', {
			error: err.stack
		});
	});

	// Assume 404 since no middleware responded
	app.use(function(req, res) {
		res.status(404).render('404', {
			url: req.originalUrl,
			error: 'Not Found'
		});
	});

	if (process.env.NODE_ENV === 'secure') {
		// Log SSL usage
		console.log('Securely using https protocol');

		// Load SSL key and certificate
		var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8');
		var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8');

		// Create HTTPS Server
		var httpsServer = https.createServer({
			key: privateKey,
			cert: certificate
		}, app);

		// Return HTTPS server instance
		return httpsServer;
	}

	// Return Express server instance
	return app;
};
<|endoftext|>


<commit_before>'use strict';

/* global moment */
angular.module('core').service('SimulationService', [
    function () {

        this.toggle = false;
        this.d3Data = {};

        this.run = function (roadmap) {

            this.d3Data = this.transformToD3Format(this.runSimulation(roadmap.epics));
            this.d3Data.start = roadmap.start;

            var rows = [];
            //var keys = Object.keys(this.d3Data.data);
            for (var i = 0; i <= this.d3Data.rows; i++) {
                rows[i] = [];
                var total = 0;

                for (var j = 0; j < this.d3Data.data.length; j++) {

                    var item = this.d3Data.data[j];
                    if (parseInt(item.row) === i) {
                        rows[i].push({score: item.score, col: item.col});
                        total += item.score;
                    }
                }

                rows[i].sort(function (a, b) {
                    return a.col - b.col;
                });

               // console.log(total);

                //console.log(rows[i]);
                var current = 0;
                for (j = 0; j < rows[i].length; j++) {
                    var point = rows[i][j];
                    //console.log(point);
                    current += point.score;
                    point.probability = current / total;
                    //console.log(this.d3Data.data[i+'-'+j].score);
                }
            }

            for (var k = 0; k < this.d3Data.data.length; k++) {

                var dataPoint = this.d3Data.data[k];
                for (var l=0; l<rows[dataPoint.row].length; l++) {

                    if (rows[dataPoint.row][l].col === dataPoint.col) {
                        dataPoint.probability = rows[dataPoint.row][l].probability;
                    }
                }
            }

            this.populateColLabels(this.d3Data, roadmap.start);
            this.populateRowLabels(roadmap.epics);
            this.toggle = !this.toggle;

        };

        this.populateRowLabels = function (epics) {
            var rowLabels = [];
            epics.forEach(function (epic) {
                rowLabels.push(epic.name);
            }, this);

            this.d3Data.rowLabels = rowLabels;
        };

        this.populateColLabels = function (d3Data, startDate) {
            var colLabels = [];
            var date = moment(startDate);
            for (var d = 0; d < d3Data.cols; d++) {
                date.add(1, 'days');
                if (d % 14 === 0) {
                    colLabels.push(date.format('D/MM'));
                } else {
                    colLabels.push('');
                }
            }
            this.d3Data.colLabels = colLabels;
        };

        this.transformToD3Format = function (rawData) {
            var data = [];
            var maxRow = 0;
            var maxCol = 0;

            Object.keys(rawData).forEach(function (key) {
                var row = key.split('-')[0];
                var col = key.split('-')[1];

                if (row > maxRow) {
                    maxRow = row;
                }

                if (parseInt(col) > maxCol) {
                    maxCol = col;
                }
                data.push({score: rawData[key], row: row, col: col});
            });
            return {rows: maxRow, cols: maxCol, data: data};
        };

        this.runSimulation = function (epics) {

            var overlap = 0.5;
            var result = [];
            for (var x = 0; x < 10000; x++) {
                var map = [];

                for (var j = 0; j < epics.length; j++) {
                    var epic = epics[j];
                    map.push({
                        active: false,
                        val: Math.max(1, this.random(epic.estimated, epic.deviation))
                    });

                }

                var total = 0;
                var originals = [];
                for (j = 0; j < map.length; j++) {
                    total += map[j].val;
                    originals.push(map[j].val);
                }

                map[0].active = true;

                var deliveries = [];

                for (var i = 0; i <= total; i++) {

                    var activeEpics = 0;
                    for (j = 0; j < map.length; j++) {
                        if (map[j].active) {
                            activeEpics++;
                        }
                    }

                    for (var k = 0; k < map.length; k++) {
                        var item = map[k];
                        if (item.active) {
                            item.val -= (1.0 / activeEpics);
                            if (item.val < 0) {
                                item.active = false;
                                deliveries[k] = i;
                            }
                            if (item.val < overlap * originals[k]) {
                                if (map.length > k + 1) {
                                    if (map[k + 1].val > 0) {
                                        map[k + 1].active = true;
                                    }
                                }
                            }
                        }
                    }

                }
                for (i = 0; i < deliveries.length; i++) {
                    var index = i + '-' + deliveries[i];
                    if (result[index]) {
                        result[index] += 1;
                    } else {
                        result[index] = 1;
                    }
                }
            }

            return result;
        };

        this.random = function (µ, σ) {
            var x, y, r;
            do {
                x = Math.random() * 2 - 1;
                y = Math.random() * 2 - 1;
                r = x * x + y * y;
            } while (!r || r > 1);
            return µ + (σ / 3.0) * x * Math.sqrt(-2 * Math.log(r) / r);
        };
    }
]);
<commit_msg>now rollover shows probability<commit_after>'use strict';

/* global moment */
angular.module('core').service('SimulationService', [
    function () {

        this.toggle = false;
        this.d3Data = {};

        this.run = function (roadmap) {

            this.d3Data = this.transformToD3Format(this.runSimulation(roadmap.epics));
            this.d3Data.start = roadmap.start;

            var rows = [];
            //var keys = Object.keys(this.d3Data.data);
            for (var i = 0; i <= this.d3Data.rows; i++) {
                rows[i] = [];
                var total = 0;

                for (var j = 0; j < this.d3Data.data.length; j++) {

                    var item = this.d3Data.data[j];
                    if (parseInt(item.row) === i) {
                        rows[i].push({score: item.score, col: item.col});
                        total += item.score;
                    }
                }

                rows[i].sort(function (a, b) {
                    return a.col - b.col;
                });

               // console.log(total);

                //console.log(rows[i]);
                var current = 0;
                for (j = 0; j < rows[i].length; j++) {
                    var point = rows[i][j];
                    //console.log(point);
                    current += point.score;
                    point.probability = current / total;
                    //console.log(this.d3Data.data[i+'-'+j].score);
                }
            }

            for (var k = 0; k < this.d3Data.data.length; k++) {

                var dataPoint = this.d3Data.data[k];
                for (var l=0; l<rows[dataPoint.row].length; l++) {

                    if (rows[dataPoint.row][l].col === dataPoint.col) {
                        dataPoint.probability = rows[dataPoint.row][l].probability;
                    }
                }
            }

            this.populateColLabels(this.d3Data, roadmap.start);
            this.populateRowLabels(roadmap.epics);
            this.toggle = !this.toggle;

        };

        this.populateRowLabels = function (epics) {
            var rowLabels = [];
            epics.forEach(function (epic) {
                rowLabels.push(epic.name);
            }, this);

            this.d3Data.rowLabels = rowLabels;
        };

        this.populateColLabels = function (d3Data, startDate) {
            var colLabels = [];
            var date = moment(startDate);
            for (var d = 0; d < d3Data.cols; d++) {
                date.add(1, 'days');
                if (d % 14 === 0) {
                    colLabels.push(date.format('D/MM'));
                } else {
                    colLabels.push('');
                }
            }
            this.d3Data.colLabels = colLabels;
        };

        this.transformToD3Format = function (rawData) {
            var data = [];
            var maxRow = 0;
            var maxCol = 0;

            Object.keys(rawData).forEach(function (key) {
                var row = key.split('-')[0];
                var col = key.split('-')[1];

                if (row > maxRow) {
                    maxRow = row;
                }

                if (parseInt(col) > maxCol) {
                    maxCol = col;
                }
                data.push({score: rawData[key], row: row, col: col});
            });
            return {rows: maxRow, cols: maxCol, data: data};
        };

        this.runSimulation = function (epics) {

            var overlap = 0.3;
            var result = [];
            for (var x = 0; x < 10000; x++) {
                var map = [];

                for (var j = 0; j < epics.length; j++) {
                    var epic = epics[j];
                    map.push({
                        active: false,
                        val: Math.max(1, this.random(epic.estimated, epic.deviation))
                    });

                }

                var total = 0;
                var originals = [];
                for (j = 0; j < map.length; j++) {
                    total += map[j].val;
                    originals.push(map[j].val);
                }

                map[0].active = true;

                var deliveries = [];

                for (var i = 0; i <= total; i++) {

                    var activeEpics = 0;
                    for (j = 0; j < map.length; j++) {
                        if (map[j].active) {
                            activeEpics++;
                        }
                    }

                    for (var k = 0; k < map.length; k++) {
                        var item = map[k];
                        if (item.active) {
                            item.val -= (1.0 / activeEpics);
                            if (item.val < 0) {
                                item.active = false;
                                deliveries[k] = i;
                            }
                            if (item.val < overlap * originals[k]) {
                                if (map.length > k + 1) {
                                    if (map[k + 1].val > 0) {
                                        map[k + 1].active = true;
                                    }
                                }
                            }
                        }
                    }

                }
                for (i = 0; i < deliveries.length; i++) {
                    var index = i + '-' + deliveries[i];
                    if (result[index]) {
                        result[index] += 1;
                    } else {
                        result[index] = 1;
                    }
                }
            }

            return result;
        };

        this.random = function (µ, σ) {
            var x, y, r;
            do {
                x = Math.random() * 2 - 1;
                y = Math.random() * 2 - 1;
                r = x * x + y * y;
            } while (!r || r > 1);
            return µ + (σ / 3.0) * x * Math.sqrt(-2 * Math.log(r) / r);
        };
    }
]);
<|endoftext|>


<commit_before>/**
 * This file is part of the Qwest resource factory package.
 * (c) Ondřej Záruba <zarubaondra@gmail.com>
 *
 * For the full copyright and license information, please view
 * the license.md file that was distributed with this source code.
**/

import Promise from 'bluebird'
import qwest from 'qwest'
import objectAssign from 'object-assign'

class ResourceFactory {

  constructor() {
    this.before = []
    this.after = []
  }

  /**
   * Add a new before request event
   * @param {Function} callback Before callback
   */
  addBeforeEvent(callback) {
    this.before.push(callback)
  }

  /**
   * Remove specific before event
   * @param  {Function} callback Before callback
   */
  removeBeforeEvent(callback) {
    let index = this.before.indexOf(callback)
    if (index !== -1) {
      this.before.splice(index, 1)
    }
  }

  /**
   * Adda new after request event
   * @param {Function} callback After callback
   */
  addAfterEvent(callback) {
    this.after.push(callback)
  }

  /**
   * Remove specific after event
   * @param  {Function} callback After callback
   */
  removeAfterEvent(callback) {
    let index = this.after.indexOf(callback)
    if (index !== -1) {
      this.after.splice(index, 1)
    }
  }

  /**
   * Create object of api methods
   * @param  {string} url Target URL
   * @param  {object} api Api configuration
   * @return {object}     Object of api methods
   */
  create(url, api) {
    let methods = {}

    let before = null
    if (api.hasOwnProperty('before')) {
      before = api.before
      delete api.before
    }

    let after = null
    if (api.hasOwnProperty('after')) {
      after = api.after
      delete api.after
    }

    for(let method in api) {
      let options = api[method]
      if (before !== null) {
        options.before = before
      }
      if (after !== null) {
        options.after = after
      }
      methods[method] = this._createQwest(url, options)
    }

    return methods
  }

  /**
   * Private method for parse parameters into URL
   * @param  {string} url    Target URL
   * @param  {object} params List of params
   * @return {string}        Output URL
   */
  _parseUrl(url, params = null) {
    if (params == null) {
      params = {}
    }
    let urlMatches = url.match(/^http(s)?:\/\/[^\/]+(.*)$/);
    if (urlMatches.length < 3) {
      throw "Invalid URL";
    }
    let uri, defaultUri
    uri = defaultUri = urlMatches[2];
    let matches = uri.match(/:([^:]+):/g) || [];
    for (let i = 0, len = matches.length; i < len; i++) {
      let match = matches[i];
      let paramName = match.substr(1, match.length - 2);
      if (params[paramName] != null) {
        let value = params[paramName];
        uri = uri.replace(match, value);
        delete params[paramName];
      } else {
        uri = uri.replace(match, "");
      }
    }
    uri = uri.replace(/\/{2,}/g, "/");
    url = url.replace(defaultUri, uri);

    return url;
  }

  /**
   * Private method for create instance of qwest
   * @param  {string} url     Target URL
   * @param  {object} options List of params
   * @return {object}         qwest instance
   */
  _createQwest(url, options) {

    const qwestConfiguration = {
      dataType: 'json'
    }

    const before = (xhr) => {
      this.before.forEach((callback) => {
        callback(xhr)
      })
      if (options.hasOwnProperty('before') && typeof(options.before) === 'function') {
        options.before(xhr)
      }
    }

    const after = (xhr, response) => {
      this.after.forEach((callback) => {
        callback(xhr, response)
      })
      if (options.hasOwnProperty('after') && typeof(options.after) === 'function') {
        options.after(xhr)
      }
    }

    const callback = (params = {}) => {
      return new Promise((resolve, reject) => {
        const realParams = objectAssign({}, options.params, params)
        const qwestInstance = qwest.map(options.method, this._parseUrl(url, realParams), realParams, qwestConfiguration, before)
        .then((xhr, response) => {
          after(xhr, response)
          resolve(response, xhr)
        }).catch((xhr, response, e) => {
          reject(err, response, xhr)
        })
      })
    }

    return callback
  }

}

export default new ResourceFactory()<commit_msg>Added header setter<commit_after>/**
 * This file is part of the Qwest resource factory package.
 * (c) Ondřej Záruba <zarubaondra@gmail.com>
 *
 * For the full copyright and license information, please view
 * the license.md file that was distributed with this source code.
**/

import Promise from 'bluebird'
import qwest from 'qwest'
import objectAssign from 'object-assign'

class ResourceFactory {

  constructor() {
    this.before = []
    this.after = []
    this.headers = []
  }

  setHeader(name, value) {
    this.headers[name] = value
  }

  /**
   * Add a new before request event
   * @param {Function} callback Before callback
   */
  addBeforeEvent(callback) {
    this.before.push(callback)
  }

  /**
   * Remove specific before event
   * @param  {Function} callback Before callback
   */
  removeBeforeEvent(callback) {
    let index = this.before.indexOf(callback)
    if (index !== -1) {
      this.before.splice(index, 1)
    }
  }

  /**
   * Adda new after request event
   * @param {Function} callback After callback
   */
  addAfterEvent(callback) {
    this.after.push(callback)
  }

  /**
   * Remove specific after event
   * @param  {Function} callback After callback
   */
  removeAfterEvent(callback) {
    let index = this.after.indexOf(callback)
    if (index !== -1) {
      this.after.splice(index, 1)
    }
  }

  /**
   * Create object of api methods
   * @param  {string} url Target URL
   * @param  {object} api Api configuration
   * @return {object}     Object of api methods
   */
  create(url, api) {
    let methods = {}

    let before = null
    if (api.hasOwnProperty('before')) {
      before = api.before
      delete api.before
    }

    let after = null
    if (api.hasOwnProperty('after')) {
      after = api.after
      delete api.after
    }

    for(let method in api) {
      let options = api[method]
      if (before !== null) {
        options.before = before
      }
      if (after !== null) {
        options.after = after
      }
      methods[method] = this._createQwest(url, options)
    }

    return methods
  }

  /**
   * Private method for parse parameters into URL
   * @param  {string} url    Target URL
   * @param  {object} params List of params
   * @return {string}        Output URL
   */
  _parseUrl(url, params = null) {
    if (params == null) {
      params = {}
    }
    let urlMatches = url.match(/^http(s)?:\/\/[^\/]+(.*)$/);
    if (urlMatches.length < 3) {
      throw "Invalid URL";
    }
    let uri, defaultUri
    uri = defaultUri = urlMatches[2];
    let matches = uri.match(/:([^:]+):/g) || [];
    for (let i = 0, len = matches.length; i < len; i++) {
      let match = matches[i];
      let paramName = match.substr(1, match.length - 2);
      if (params[paramName] != null) {
        let value = params[paramName];
        uri = uri.replace(match, value);
        delete params[paramName];
      } else {
        uri = uri.replace(match, "");
      }
    }
    uri = uri.replace(/\/{2,}/g, "/");
    url = url.replace(defaultUri, uri);

    return url;
  }

  /**
   * Private method for create instance of qwest
   * @param  {string} url     Target URL
   * @param  {object} options List of params
   * @return {object}         qwest instance
   */
  _createQwest(url, options) {

    const qwestConfiguration = {
      dataType: 'json'
      headers: this.headers
    }

    const before = (xhr) => {
      this.before.forEach((callback) => {
        callback(xhr)
      })
      if (options.hasOwnProperty('before') && typeof(options.before) === 'function') {
        options.before(xhr)
      }
    }

    const after = (xhr, response) => {
      this.after.forEach((callback) => {
        callback(xhr, response)
      })
      if (options.hasOwnProperty('after') && typeof(options.after) === 'function') {
        options.after(xhr)
      }
    }

    const callback = (params = {}) => {
      return new Promise((resolve, reject) => {
        const realParams = objectAssign({}, options.params, params)
        const qwestInstance = qwest.map(options.method, this._parseUrl(url, realParams), realParams, qwestConfiguration, before)
        .then((xhr, response) => {
          after(xhr, response)
          resolve(response, xhr)
        }).catch((xhr, response, e) => {
          reject(err, response, xhr)
        })
      })
    }

    return callback
  }

}

export default new ResourceFactory()<|endoftext|>


<commit_before>/**
 * Copyright 2014 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

// Module dependencies
var express    = require('express'),
  favicon      = require('serve-favicon'),
  errorhandler = require('errorhandler'),
  secure       = require('express-secure-only'),
  bodyParser   = require('body-parser'),
  morgan       = require('morgan'),
  csrf         = require('csurf'),
  cookieParser = require('cookie-parser'),
  fs           = require('fs');

module.exports = function (app) {
  app.set('view engine', 'ejs');
  app.enable('trust proxy');

  var logStream = fs.createWriteStream(__dirname + '/../logs/access.log', {flags: 'a'});
  // setup the logger
  app.use('/api/', morgan('combined', {stream: logStream}));

  // use only https
  var env = process.env.NODE_ENV || 'development';
  if ('production' === env) {
    console.log('redirect http to https');
    //app.use(secure());
    app.use(errorhandler());
  }

  // Configure Express
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(bodyParser.json());

  // Setup static public directory
  app.use(express.static(__dirname + '/../public'));
  app.use(favicon(__dirname + '/../public/images/favicon.ico'));

  // cookies
  var secret = Math.random().toString(36).substring(7);
  app.use(cookieParser(secret));

  var errorMessage = {
    error:'Too many requests, please try again in 30 seconds.',
    code: 429
  };

  // rate limiting
  var rateLimit = require('express-rate-limit');
  var limiter = rateLimit({
    windowMs: 30 * 1000, // seconds
    delayMs: 0,
    max: 3,
    message: JSON.stringify(errorMessage),
    global: false
  });

  // csrf
  var csrfProtection = csrf({ cookie: true });
  app.get('/', csrfProtection, function(req, res) {
    res.render('index', { ct: req.csrfToken() });
  });

  // apply to all requests that begin with /api/
  // csfr token and rate limiting.
  app.use('/api/', csrfProtection, limiter);
};
<commit_msg>redirect http to https<commit_after>/**
 * Copyright 2014 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

// Module dependencies
var express    = require('express'),
  favicon      = require('serve-favicon'),
  errorhandler = require('errorhandler'),
  secure       = require('express-secure-only'),
  bodyParser   = require('body-parser'),
  morgan       = require('morgan'),
  csrf         = require('csurf'),
  cookieParser = require('cookie-parser'),
  fs           = require('fs');

module.exports = function (app) {
  app.set('view engine', 'ejs');
  app.enable('trust proxy');

  var logStream = fs.createWriteStream(__dirname + '/../logs/access.log', {flags: 'a'});
  // setup the logger
  app.use('/api/', morgan('combined', {stream: logStream}));

  // use only https
  var env = process.env.NODE_ENV || 'development';
  if ('production' === env) {
    console.log('redirect http to https');
    app.use(secure());
    app.use(errorhandler());
  }

  // Configure Express
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(bodyParser.json());

  // Setup static public directory
  app.use(express.static(__dirname + '/../public'));
  app.use(favicon(__dirname + '/../public/images/favicon.ico'));

  // cookies
  var secret = Math.random().toString(36).substring(7);
  app.use(cookieParser(secret));

  var errorMessage = {
    error:'Too many requests, please try again in 30 seconds.',
    code: 429
  };

  // rate limiting
  var rateLimit = require('express-rate-limit');
  var limiter = rateLimit({
    windowMs: 30 * 1000, // seconds
    delayMs: 0,
    max: 3,
    message: JSON.stringify(errorMessage),
    global: false
  });

  // csrf
  var csrfProtection = csrf({ cookie: true });
  app.get('/', csrfProtection, function(req, res) {
    res.render('index', { ct: req.csrfToken() });
  });

  // apply to all requests that begin with /api/
  // csfr token and rate limiting.
  app.use('/api/', csrfProtection, limiter);
};
<|endoftext|>


<commit_before>/* eslint no-unused-expressions:0, max-nested-callbacks: [2, 5] */
"use strict";
import HttpResponseHandler from "../../../../common/src/HttpResponseHandler.js";
import FacebookRouteHelper from "../../../src/routes/helpers/FacebookRouteHelper.js";
import FacebookRequestHandler from "../../../src/facebook/FacebookRequestHandler.js";
import sinon from "sinon";
import { assert } from "chai";

describe.only("FacebookRouteHelper", () => {
    let request = null, facebookRequestHandler = null, accessToken = null, pageName = null;
    before("FacebookRouteHelper", () => {
        accessToken = "test_access_token";
        pageName = "test_page";
        request = {
            "query": {
                "pageName": pageName,
                "accessToken": accessToken
            }
        };

    });

    describe("pageRouter", () => {
        beforeEach("pageRouter", () => {
            facebookRequestHandler = new FacebookRequestHandler(accessToken);
        });
        it("should set the the facebook feeds on response", (done) => {

            let facebookRequestHandlerMock = sinon.mock(FacebookRequestHandler).expects("instance");
            facebookRequestHandlerMock.withArgs(accessToken).returns(facebookRequestHandler);
            let facebookRequestHandlerStub = sinon.stub(facebookRequestHandler, "pageFeeds");
            let feeds = [
                {
                    "message": "Lammasingi village in #AndhraPradesh is a meteorological oddity. \n\nFind out how - bit.ly/1Y19P17",
                    "created_time": "2015-12-11T08:02:59+0000",
                    "id": "163974433696568_958425464251457"
                }];
            let response = {
                "status": (status) => {
                    assert.strictEqual(HttpResponseHandler.codes.OK, status);
                    return response;
                },
                "json": (json) => {
                    assert.deepEqual({ "feeds": feeds }, json);
                    done();
                }
            };

            facebookRequestHandlerStub.withArgs(pageName).returns(Promise.resolve(feeds));

            let facebookRouteHelper = new FacebookRouteHelper(request, response);
            facebookRouteHelper.pageRouter();
            FacebookRequestHandler.instance.restore();
        });

        it("should set the error on the response in case if feeds can not be fetched from facebook", (done) => {

            let facebookRequestHandlerMock = sinon.mock(FacebookRequestHandler).expects("instance");
            facebookRequestHandlerMock.withArgs(accessToken).returns(facebookRequestHandler);
            let facebookRequestHandlerStub = sinon.stub(facebookRequestHandler, "pageFeeds");
            let error = {
                "message": "Error validating access token: Session has expired on Thursday, 10-Dec-15 04:00:00 PST. The current time is Thursday, 10-Dec-15 20:23:54 PST.",
                "type": "OAuthException",
                "code": 190,
                "error_subcode": 463,
                "fbtrace_id": "AWpk5h2ceG6"
            };
            let response = {
                "status": (status) => {
                    assert.strictEqual(HttpResponseHandler.codes.NOT_FOUND, status);
                    return response;
                },
                "json": (json) => {
                    assert.deepEqual(error, json);
                    done();
                }
            };

            facebookRequestHandlerStub.withArgs(pageName).returns(Promise.reject(error));

            let facebookRouteHelper = new FacebookRouteHelper(request, response);
            facebookRouteHelper.pageRouter();
            FacebookRequestHandler.instance.restore();
        });

    });
});
<commit_msg>Vik - removed only in server test cases<commit_after>/* eslint no-unused-expressions:0, max-nested-callbacks: [2, 5] */
"use strict";
import HttpResponseHandler from "../../../../common/src/HttpResponseHandler.js";
import FacebookRouteHelper from "../../../src/routes/helpers/FacebookRouteHelper.js";
import FacebookRequestHandler from "../../../src/facebook/FacebookRequestHandler.js";
import sinon from "sinon";
import { assert } from "chai";

describe("FacebookRouteHelper", () => {
    let request = null, facebookRequestHandler = null, accessToken = null, pageName = null;
    before("FacebookRouteHelper", () => {
        accessToken = "test_access_token";
        pageName = "test_page";
        request = {
            "query": {
                "pageName": pageName,
                "accessToken": accessToken
            }
        };

    });

    describe("pageRouter", () => {
        beforeEach("pageRouter", () => {
            facebookRequestHandler = new FacebookRequestHandler(accessToken);
        });
        it("should set the the facebook feeds on response", (done) => {

            let facebookRequestHandlerMock = sinon.mock(FacebookRequestHandler).expects("instance");
            facebookRequestHandlerMock.withArgs(accessToken).returns(facebookRequestHandler);
            let facebookRequestHandlerStub = sinon.stub(facebookRequestHandler, "pageFeeds");
            let feeds = [
                {
                    "message": "Lammasingi village in #AndhraPradesh is a meteorological oddity. \n\nFind out how - bit.ly/1Y19P17",
                    "created_time": "2015-12-11T08:02:59+0000",
                    "id": "163974433696568_958425464251457"
                }];
            let response = {
                "status": (status) => {
                    assert.strictEqual(HttpResponseHandler.codes.OK, status);
                    return response;
                },
                "json": (json) => {
                    assert.deepEqual({ "feeds": feeds }, json);
                    done();
                }
            };

            facebookRequestHandlerStub.withArgs(pageName).returns(Promise.resolve(feeds));

            let facebookRouteHelper = new FacebookRouteHelper(request, response);
            facebookRouteHelper.pageRouter();
            FacebookRequestHandler.instance.restore();
        });

        it("should set the error on the response in case if feeds can not be fetched from facebook", (done) => {

            let facebookRequestHandlerMock = sinon.mock(FacebookRequestHandler).expects("instance");
            facebookRequestHandlerMock.withArgs(accessToken).returns(facebookRequestHandler);
            let facebookRequestHandlerStub = sinon.stub(facebookRequestHandler, "pageFeeds");
            let error = {
                "message": "Error validating access token: Session has expired on Thursday, 10-Dec-15 04:00:00 PST. The current time is Thursday, 10-Dec-15 20:23:54 PST.",
                "type": "OAuthException",
                "code": 190,
                "error_subcode": 463,
                "fbtrace_id": "AWpk5h2ceG6"
            };
            let response = {
                "status": (status) => {
                    assert.strictEqual(HttpResponseHandler.codes.NOT_FOUND, status);
                    return response;
                },
                "json": (json) => {
                    assert.deepEqual(error, json);
                    done();
                }
            };

            facebookRequestHandlerStub.withArgs(pageName).returns(Promise.reject(error));

            let facebookRouteHelper = new FacebookRouteHelper(request, response);
            facebookRouteHelper.pageRouter();
            FacebookRequestHandler.instance.restore();
        });

    });
});
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var swig = require('swig');
var subdomainOffset = process.env.SUBDOMAIN_OFFSET || 0;
var secrets = require('./secrets');
var http     = require('http');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')({ session: session });
var mongoose = require('mongoose');
var passport = require('passport');
var bodyParser = require('body-parser');
var compress = require('compression')();
var lodash = require('lodash');
// var Authentication = require('./authentication');
var expressValidator = require('express-validator');
var errorHandler = require('./lib/error');
var viewHelper = require('./lib/view-helper');
var flash = require('express-flash');
var cors = require('cors');
var corsOptions = {
  origin: '*'
};
var staticDir;
var server   = http.createServer(app);
var io       = require('socket.io').listen(server);
//config files ================================================================

var credentials = require('./credentials.json');

var docker   = require('docker.io')({
  socketPath: false,
  host: 'http://'+credentials.host, port: '4243'});

// socket function =============================================================
require('./lib/sockets.js')(io, credentials, docker);

// setup db
mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});

var corsOptions = {
  origin: '*'
};

// express setup
var app = express();

if (app.get('env') === 'production') {
  app.locals.production = true;
  swig.setDefaults({ cache: 'memory' });
  staticDir = path.join(__dirname + '/../public');
} else {
  app.locals.production = false;
  swig.setDefaults({ cache: false });
  staticDir = path.join(__dirname + '/../public');
}

// This is where all the magic happens!
app.engine('html', swig.renderFile);
app.set('views', path.join(__dirname, '../server/views'));
app.set('view engine', 'html');
app.locals._ = lodash;
app.locals.stripePubKey = secrets.stripeOptions.stripePubKey;

app.use(favicon(path.join(__dirname + '/../public/favicon.ico')));
app.use(logger('dev'));

app.use(compress);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());
app.use(cookieParser());

app.use(express.static(staticDir));
if(app.get('env') !== 'production'){
  app.use('/styles', express.static(__dirname + '/../.tmp/styles'));
  // app.use('/', routes.styleguide);
}

app.use(session({
  resave: true,
  saveUninitialized: true,
  cookie: {
    maxAge: 60 * 1000 // 1 minute
  },
  secret: secrets.sessionSecret,
  store: new MongoStore({
    url: secrets.db,
    aautoReconnect: true
  })
}));

// setup passport authentication
app.use(passport.initialize());
app.use(passport.session());

// other
app.use(flash());
app.use(cors(corsOptions));

var passportMiddleware = require('./lib/passport');
passportMiddleware(passport);

// setup view helper
app.use(viewHelper);

// setup routes
var routes = require('../server/routes');
routes(app, passport, docker);

/// catch 404 and forwarding to error handler
app.use(errorHandler.notFound);

/// error handlers
if (app.get('env') === 'development') {
  app.use(errorHandler.development);
} else {
  app.use(errorHandler.production);
}

module.exports = app;
<commit_msg>Remove duplicates<commit_after>'use strict';

var express = require('express');
var swig = require('swig');
var subdomainOffset = process.env.SUBDOMAIN_OFFSET || 0;
var secrets = require('./secrets');
var http     = require('http');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')({ session: session });
var mongoose = require('mongoose');
var passport = require('passport');
var bodyParser = require('body-parser');
var compress = require('compression')();
var lodash = require('lodash');
// var Authentication = require('./authentication');
var expressValidator = require('express-validator');
var errorHandler = require('./lib/error');
var viewHelper = require('./lib/view-helper');
var flash = require('express-flash');
var cors = require('cors');
var corsOptions = {
  origin: '*'
};
var staticDir;
var server   = http.createServer(app);
var io       = require('socket.io').listen(server);
//config files ================================================================

var credentials = require('./credentials.json');

var docker   = require('docker.io')({
  socketPath: false,
  host: 'http://'+credentials.host, port: '4243'});

// socket function =============================================================
require('./lib/sockets.js')(io, credentials, docker);

// setup db
mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});

// express setup
var app = express();

if (app.get('env') === 'production') {
  app.locals.production = true;
  swig.setDefaults({ cache: 'memory' });
  staticDir = path.join(__dirname + '/../public');
} else {
  app.locals.production = false;
  swig.setDefaults({ cache: false });
  staticDir = path.join(__dirname + '/../public');
}

// This is where all the magic happens!
app.engine('html', swig.renderFile);
app.set('views', path.join(__dirname, '../server/views'));
app.set('view engine', 'html');
app.locals._ = lodash;
app.locals.stripePubKey = secrets.stripeOptions.stripePubKey;

app.use(favicon(path.join(__dirname + '/../public/favicon.ico')));
app.use(logger('dev'));

app.use(compress);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());
app.use(cookieParser());

app.use(express.static(staticDir));
if(app.get('env') !== 'production'){
  app.use('/styles', express.static(__dirname + '/../.tmp/styles'));
  // app.use('/', routes.styleguide);
}

app.use(session({
  resave: true,
  saveUninitialized: true,
  cookie: {
    maxAge: 60 * 1000 // 1 minute
  },
  secret: secrets.sessionSecret,
  store: new MongoStore({
    url: secrets.db,
    aautoReconnect: true
  })
}));

// setup passport authentication
app.use(passport.initialize());
app.use(passport.session());

// other
app.use(flash());
app.use(cors(corsOptions));

var passportMiddleware = require('./lib/passport');
passportMiddleware(passport);

// setup view helper
app.use(viewHelper);

// setup routes
var routes = require('../server/routes');
routes(app, passport, docker);

/// catch 404 and forwarding to error handler
app.use(errorHandler.notFound);

/// error handlers
if (app.get('env') === 'development') {
  app.use(errorHandler.development);
} else {
  app.use(errorHandler.production);
}

module.exports = app;
<|endoftext|>


<commit_before>/* global define:false */
define([
	'lodash',
	'microevent',
	'jazzmidibridge',
	'app/model/event_bus',
	'app/view/modal'
], function(_, MicroEvent, JMB, eventBus, Modal) {
	"use strict";

	/**
	 * The midi source is responsible for handling midi messages
	 * from both external keyboard devices and onscreen devices as well
	 * as handling midi control changes.
	 *
	 * It interfaces with external devices using the Jazz Midi Bridge
	 * (JMB) and uses the event bus to broadcast interesting events
	 * to other application components.
	 */
	var MidiSource = function(config) {
		this.config = config || {};
		this.init();
	};

	_.extend(MidiSource.prototype, {
		// global event bus
		eventBus: eventBus,

		// api for midi access via jazz midi bridge
		midiAccess: null,

		// midi channel settings
		channel: 0,

		// transposition settings
		transpose: 0,

		// midi instruments
		defaultInstrumentNum: 0, // default instrument

		// midi note velocity settings
		noteVelocity: 127, // range: 0-127
		defaultNoteVelocity: 127,
		reducedNoteVelocity: 84,

		// midi device settings
		outputDevices: [], // list of available outputs
		inputDevices: [], // list of available inputs
		output: null, // selected output device
		input: null, // selected input device
		defaultDevices: { outputIndex: 0, inputIndex: 0 },

		// mappings for MIDI control changes
		midiControlMap: {
			'pedal': {
				'64': 'sustain',
				'66': 'sostenuto',
				'67': 'soft',
				'sustain': 64,
				'sostenuto': 66,
				'soft': 67
			}
		},

		// Initializes the MIDI router to send and receive MIDI messages.
		init: function() {
			if(!this.config.hasOwnProperty('chords')) {
				throw new Error("missing config property");
			}

			this.chords = this.config.chords;

			_.bindAll(this, [
				'onMidiMessage',
				'onNoteChange',
				'onPedalChange',
				'onInstrumentChange',
				'onTransposeChange'
			]);

			this.onJMBInit = this.execAfter(this.onJMBInit, this.initListeners);
			this.onJMBError = this.execAfter(this.onJMBError, this.initListeners);

			JMB.init(this.onJMBInit, this.onJMBError);
		},

		// Initializes the Jazz Midi Bridge (JMB) and related event handlers.
		onJMBInit: function(MIDIAccess) {
			if(MIDIAccess) {
				this.midiAccess = MIDIAccess;
				this.detectDevices();
				this.selectDefaultDevices();
			}
		},

		// Handles error on Jazz Midi Bridge error
		onJMBError: function() {
			var title = 'Jazz MIDI Plugin Required';
			var msg = '
Your browser is missing the Jazz MIDI plugin. '
				+ 'This browser plugin is required to produce sound with the on-screen keyboard or to '
				+ 'connect and use your own MIDI keyboard.
'
				+ '
Please download and install the Jazz MIDI plugin here:
'
				+ 'http://jazz-soft.net/.
';

			Modal.msg(title, msg);
		},

		// Detects midi devices.
		detectDevices: function() {
			if(this.midiAccess) {
				this.outputDevices = this.midiAccess.enumerateOutputs() || [];
				this.inputDevices = this.midiAccess.enumerateInputs() || [];
				this.trigger('devices', this.inputDevices, this.outputDevices, this.defaultDevices);
			}
		},

		// Scans for changes to midi devices.
		scanDevices: function() {
			JMB.rescan();
		},

		// Selects a default midi input and output device (if any).
		selectDefaultDevices: function() {
			var outputs = this.outputDevices;
			var inputs = this.inputDevices;
			if(outputs && outputs.length > 0) {
				this.output = outputs[this.defaultDevices.outputIndex];
			}
			if(inputs && inputs.length > 0) {
				this.input = inputs[this.defaultDevices.inputIndex];
			}
		},

		// Selects a device for input/output.
		selectDevice: function(type, index) {
			switch(type) {
				case 'input':
					if(this.inputDevices.length > 0) {
						this.input = this.inputDevices[index];
					}
					break;
				case 'output':
					if(this.outputDevices.length > 0) {
						this.output = this.outputDevices[index];
					}
					break;
			}
		},

		// Initializes listeners.
		initListeners: function() {
			this.eventBus.bind('note', this.onNoteChange);
			this.eventBus.bind('pedal', this.onPedalChange);
			this.eventBus.bind('instrument', this.onInstrumentChange);
			this.eventBus.bind('transpose', this.onTransposeChange);

			if(this.input) {
				this.input.addEventListener('midimessage', this.onMidiMessage);
			}
		},

		// Toggles a note state.
		toggleNote: function(noteState, noteNumber) {
			return this.chords.current()[noteState==='on'?'noteOn':'noteOff'](noteNumber);
		},

		// Clears all notes.
		clearNotes: function() {
			this.chords.current().clear();
		},

		// Handles a midi message.
		onMidiMessage: function(msg) {
			var command = msg.command;
			var noteNum;

			// SPECIAL CASE: "note on" with 0 velocity implies "note off"
			if(command === JMB.NOTE_ON && !msg.data2) {
				command = JMB.NOTE_OFF;
			}

			switch(command) {
				case JMB.NOTE_ON:
					noteNum = msg.data1;
					this.eventBus.trigger('note', 'on', noteNum, this.noteVelocity || msg.data2);
					break;
				case JMB.NOTE_OFF:
					noteNum = msg.data1;
					this.eventBus.trigger('note', 'off', noteNum, this.noteVelocity || msg.data2);
					break;
				case JMB.CONTROL_CHANGE:
					if(this.midiControlMap.pedal.hasOwnProperty(msg.data1)) {
						this.eventBus.trigger('pedal', this.midiControlMap.pedal[msg.data1], msg.data2 === 0 ? 'off' : 'on');
					}
					break;
				default:
					console.log("midi message not handled: ", msg);
			}
		},

		// Handles note output (not from an external device).
		onNoteChange: function(noteState, noteNumber) {
			var transposedNoteNumber = noteNumber + this.transpose;;
			var command = (noteState === 'on' ? JMB.NOTE_ON : JMB.NOTE_OFF);

			this.toggleNote(noteState, transposedNoteNumber);
			this.sendMIDIMessage(command, transposedNoteNumber, this.noteVelocity);

			console.log("note change", noteNumber, "transposed to", transposedNoteNumber, "with transpose", this.transpose);
		},

		// Handles sustain, sostenuto, soft pedal events.
		onPedalChange: function(pedal, state) {
			var command = JMB.CONTROL_CHANGE;
			var controlNumber = this.midiControlMap.pedal[pedal];
			var controlValue = (state === 'off' ? 0 : 127);

			if(pedal === 'soft') {
				this.noteVelocity = (state === 'off' ? this.defaultNoteVelocity : this.reducedNoteVelocity);
			} else if(pedal === 'sustain') {
				if(state === 'on') {
					this.chords.current().sustainNotes();
				} else if(state === 'off') {
					this.chords.bank();
				}
			}

			this.sendMIDIMessage(command, controlNumber, controlValue, this.channel);
		},

		// Handles change of instrument.
		onInstrumentChange: function(instrumentNum) {
			var command = JMB.PROGRAM_CHANGE;
			instrumentNum = instrumentNum < 0 ? this.defaultInstrumentNum : instrumentNum;

			this.sendMIDIMessage(command, instrumentNum, 0, this.channel);
		},

		// Handles transpose events.
		onTransposeChange: function(value) {
			var TRANSPOSE_MIN = -12, TRANSPOSE_MAX = 12;

			if(value >= TRANSPOSE_MIN && value <= TRANSPOSE_MAX) {
				this.transpose = value;
			} else {
				this.transpose = 0;
			}
		},

		// Outputs a MIDI message via the Jazz MIDI bridge
		sendMIDIMessage: function() {
			var msg, output = this.output, midiAccess = this.midiAccess;
			if(this.midiAccess) {
				msg = midiAccess.createMIDIMessage.apply(midiAccess, arguments);
				if(output) {
					output.sendMIDIMessage(msg);
				}
			}
		},

		// Execute the second fn after the first one, returning the result of the first
		execAfter: function(firstFn, secondFn) {
			var that = this;
			return function() {
				var result = firstFn.apply(that, arguments);
				secondFn.call(that);
				return result;
			};
		}
	});

	MicroEvent.mixin(MidiSource); // make object observable

	return MidiSource;
});
<commit_msg>remove logging stmt<commit_after>/* global define:false */
define([
	'lodash',
	'microevent',
	'jazzmidibridge',
	'app/model/event_bus',
	'app/view/modal'
], function(_, MicroEvent, JMB, eventBus, Modal) {
	"use strict";

	/**
	 * The midi source is responsible for handling midi messages
	 * from both external keyboard devices and onscreen devices as well
	 * as handling midi control changes.
	 *
	 * It interfaces with external devices using the Jazz Midi Bridge
	 * (JMB) and uses the event bus to broadcast interesting events
	 * to other application components.
	 */
	var MidiSource = function(config) {
		this.config = config || {};
		this.init();
	};

	_.extend(MidiSource.prototype, {
		// global event bus
		eventBus: eventBus,

		// api for midi access via jazz midi bridge
		midiAccess: null,

		// midi channel settings
		channel: 0,

		// transposition settings
		transpose: 0,

		// midi instruments
		defaultInstrumentNum: 0, // default instrument

		// midi note velocity settings
		noteVelocity: 127, // range: 0-127
		defaultNoteVelocity: 127,
		reducedNoteVelocity: 84,

		// midi device settings
		outputDevices: [], // list of available outputs
		inputDevices: [], // list of available inputs
		output: null, // selected output device
		input: null, // selected input device
		defaultDevices: { outputIndex: 0, inputIndex: 0 },

		// mappings for MIDI control changes
		midiControlMap: {
			'pedal': {
				'64': 'sustain',
				'66': 'sostenuto',
				'67': 'soft',
				'sustain': 64,
				'sostenuto': 66,
				'soft': 67
			}
		},

		// Initializes the MIDI router to send and receive MIDI messages.
		init: function() {
			if(!this.config.hasOwnProperty('chords')) {
				throw new Error("missing config property");
			}

			this.chords = this.config.chords;

			_.bindAll(this, [
				'onMidiMessage',
				'onNoteChange',
				'onPedalChange',
				'onInstrumentChange',
				'onTransposeChange'
			]);

			this.onJMBInit = this.execAfter(this.onJMBInit, this.initListeners);
			this.onJMBError = this.execAfter(this.onJMBError, this.initListeners);

			JMB.init(this.onJMBInit, this.onJMBError);
		},

		// Initializes the Jazz Midi Bridge (JMB) and related event handlers.
		onJMBInit: function(MIDIAccess) {
			if(MIDIAccess) {
				this.midiAccess = MIDIAccess;
				this.detectDevices();
				this.selectDefaultDevices();
			}
		},

		// Handles error on Jazz Midi Bridge error
		onJMBError: function() {
			var title = 'Jazz MIDI Plugin Required';
			var msg = '
Your browser is missing the Jazz MIDI plugin. '
				+ 'This browser plugin is required to produce sound with the on-screen keyboard or to '
				+ 'connect and use your own MIDI keyboard.
'
				+ '
Please download and install the Jazz MIDI plugin here:
'
				+ 'http://jazz-soft.net/.
';

			Modal.msg(title, msg);
		},

		// Detects midi devices.
		detectDevices: function() {
			if(this.midiAccess) {
				this.outputDevices = this.midiAccess.enumerateOutputs() || [];
				this.inputDevices = this.midiAccess.enumerateInputs() || [];
				this.trigger('devices', this.inputDevices, this.outputDevices, this.defaultDevices);
			}
		},

		// Scans for changes to midi devices.
		scanDevices: function() {
			JMB.rescan();
		},

		// Selects a default midi input and output device (if any).
		selectDefaultDevices: function() {
			var outputs = this.outputDevices;
			var inputs = this.inputDevices;
			if(outputs && outputs.length > 0) {
				this.output = outputs[this.defaultDevices.outputIndex];
			}
			if(inputs && inputs.length > 0) {
				this.input = inputs[this.defaultDevices.inputIndex];
			}
		},

		// Selects a device for input/output.
		selectDevice: function(type, index) {
			switch(type) {
				case 'input':
					if(this.inputDevices.length > 0) {
						this.input = this.inputDevices[index];
					}
					break;
				case 'output':
					if(this.outputDevices.length > 0) {
						this.output = this.outputDevices[index];
					}
					break;
			}
		},

		// Initializes listeners.
		initListeners: function() {
			this.eventBus.bind('note', this.onNoteChange);
			this.eventBus.bind('pedal', this.onPedalChange);
			this.eventBus.bind('instrument', this.onInstrumentChange);
			this.eventBus.bind('transpose', this.onTransposeChange);

			if(this.input) {
				this.input.addEventListener('midimessage', this.onMidiMessage);
			}
		},

		// Toggles a note state.
		toggleNote: function(noteState, noteNumber) {
			return this.chords.current()[noteState==='on'?'noteOn':'noteOff'](noteNumber);
		},

		// Clears all notes.
		clearNotes: function() {
			this.chords.current().clear();
		},

		// Handles a midi message.
		onMidiMessage: function(msg) {
			var command = msg.command;
			var noteNum;

			// SPECIAL CASE: "note on" with 0 velocity implies "note off"
			if(command === JMB.NOTE_ON && !msg.data2) {
				command = JMB.NOTE_OFF;
			}

			switch(command) {
				case JMB.NOTE_ON:
					noteNum = msg.data1;
					this.eventBus.trigger('note', 'on', noteNum, this.noteVelocity || msg.data2);
					break;
				case JMB.NOTE_OFF:
					noteNum = msg.data1;
					this.eventBus.trigger('note', 'off', noteNum, this.noteVelocity || msg.data2);
					break;
				case JMB.CONTROL_CHANGE:
					if(this.midiControlMap.pedal.hasOwnProperty(msg.data1)) {
						this.eventBus.trigger('pedal', this.midiControlMap.pedal[msg.data1], msg.data2 === 0 ? 'off' : 'on');
					}
					break;
				default:
					console.log("midi message not handled: ", msg);
			}
		},

		// Handles note output (not from an external device).
		onNoteChange: function(noteState, noteNumber) {
			var transposedNoteNumber = noteNumber + this.transpose;;
			var command = (noteState === 'on' ? JMB.NOTE_ON : JMB.NOTE_OFF);

			this.toggleNote(noteState, transposedNoteNumber);
			this.sendMIDIMessage(command, transposedNoteNumber, this.noteVelocity);
		},

		// Handles sustain, sostenuto, soft pedal events.
		onPedalChange: function(pedal, state) {
			var command = JMB.CONTROL_CHANGE;
			var controlNumber = this.midiControlMap.pedal[pedal];
			var controlValue = (state === 'off' ? 0 : 127);

			if(pedal === 'soft') {
				this.noteVelocity = (state === 'off' ? this.defaultNoteVelocity : this.reducedNoteVelocity);
			} else if(pedal === 'sustain') {
				if(state === 'on') {
					this.chords.current().sustainNotes();
				} else if(state === 'off') {
					this.chords.bank();
				}
			}

			this.sendMIDIMessage(command, controlNumber, controlValue, this.channel);
		},

		// Handles change of instrument.
		onInstrumentChange: function(instrumentNum) {
			var command = JMB.PROGRAM_CHANGE;
			instrumentNum = instrumentNum < 0 ? this.defaultInstrumentNum : instrumentNum;

			this.sendMIDIMessage(command, instrumentNum, 0, this.channel);
		},

		// Handles transpose events.
		onTransposeChange: function(value) {
			var TRANSPOSE_MIN = -12, TRANSPOSE_MAX = 12;

			if(value >= TRANSPOSE_MIN && value <= TRANSPOSE_MAX) {
				this.transpose = value;
			} else {
				this.transpose = 0;
			}
		},

		// Outputs a MIDI message via the Jazz MIDI bridge
		sendMIDIMessage: function() {
			var msg, output = this.output, midiAccess = this.midiAccess;
			if(this.midiAccess) {
				msg = midiAccess.createMIDIMessage.apply(midiAccess, arguments);
				if(output) {
					output.sendMIDIMessage(msg);
				}
			}
		},

		// Execute the second fn after the first one, returning the result of the first
		execAfter: function(firstFn, secondFn) {
			var that = this;
			return function() {
				var result = firstFn.apply(that, arguments);
				secondFn.call(that);
				return result;
			};
		}
	});

	MicroEvent.mixin(MidiSource); // make object observable

	return MidiSource;
});
<|endoftext|>


<commit_before>function loadTopmenu() {
        var iframe = document.createElement("iframe");
        iframe.setAttribute("src", "/topmenu.html");
        iframe.setAttribute("width", "100%");
        iframe.setAttribute("height", "51px");
        iframe.frameBorder = 0;
        document.body.insertBefore(iframe, document.body.firstChild);
        document.title += ' [SF <%= scope.function_hiera(["sf_version"]) %>]';
};

if (document.body) {
    loadTopmenu();
} else {
    window.onload = function() {loadTopmenu();};
};
<commit_msg>Fix bug in Jenkins configuration page<commit_after>function loadTopmenu() {
        var iframe = document.createElement("iframe");
        iframe.setAttribute("src", "/topmenu.html");
        iframe.setAttribute("width", "100%");
        iframe.setAttribute("height", "51px");
        iframe.frameBorder = 0;
        document.body.insertBefore(iframe, document.body.firstChild);
        document.title += ' [SF <%= scope.function_hiera(["sf_version"]) %>]';
};

if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", loadTopmenu, false);
} else {
    window.onload = loadTopmenu;
}
<|endoftext|>