<commit_before>var _ = require('lodash')
  , _s = require('underscore.string')
  , async = require('async')
  , dotty = require('dotty')
  , passport = require('passport')
  , passwordHash = require('password-hash');

module.exports = function (app, options) {
  var assembleUser = function (obj) {
    var user = {};

    _.each(options.accessLevels, function (lvl) {
      user[lvl] = {};
    });

    _.each(obj, function (val, key) {
      dotty.put(user, key, val);
    });

    return user;
  };

  var findUserId = function (model, user, callback) {
    if (_.isFunction(options.local.findUserId)) {
      return options.local.findUserId(model, user, callback);
    }

    var found = null;

    async.some(options.local.findUserId, function (path, callback) {
      path = path.split('.');

      var val = dotty.get(user, path)
        , coll = getUserCollection(path.shift())
        , doc = path.join('.')
        , target = {$query: {}};

      target.$query[doc] = val;
      var query = model.query(coll, target);

      model.fetch(query, function (err) {
        if (err) return callback(err);
        var userId = dotty.get(query.get(), '0.id');
        if (userId) found = userId;
        callback(userId);
      });
    }, function (userId) {
      callback(null, found);
    });
  };

  var getUserCollection = function (lvl) {
    if (!lvl) lvl = options.accessLevels[0];
    return options.collectionName + _s.capitalize(lvl);
  };

  options = _.merge(options || {}, {
    accessLevels: [
      'public',
      'private'
    ],
    clientConfigPath: '$auth',
    collectionName: 'users',
    local: {
      findUserId: [
        'private.local.email',
        'public.local.username'
      ],
      password: {
        hash: {},
        maximumLength: 100,
        minimumLength: 6,
        path: 'private.local.password'
      },
    },
    providers: {
      schema: {
        'public': ['displayName', 'photos', 'username'],
        'private': '*'
      },
      strategies: {},
      path: 'providers'
    },
    session: {
      idPath: 'user.id',
      isRegisteredPath: 'user.isRegistered'
    },
    signInRoute: '/signin',
    signOutRoute: '/signout',
    signUpRoute: '/signup'
  });

  if (_.isString(options.local.findUserId)) {
    options.local.findUserId = [options.local.findUserId];
  }

  if (!options.accessLevels) {
    options.accessLevels = [''];
  }

  _.each(options.accessLevels, function (lvl) {
    var schema = options.providers.schema;
    if (!schema[lvl]) schema[lvl] = [];
    if (_.isString(schema[lvl])) schema[lvl] = [schema[lvl]];
  });

  _.each(options.providers.strategies, function (strategy, name) {
    _.merge(strategy, {
      callback: {
        popup: true,
        url: '/auth/' + name + '/callback'
      },
      config: {},
      module: 'passport-' + name,
      options: {
        url: '/auth/' + name
      },
      verify: function (callback) {
        return function () {
          var req = arguments[0]
            , profile = _.last(arguments, 2)[0]
            , profileId = arguments.length === 4 ? arguments[1] : profile.id
            , done = _.last(arguments);

          callback(req, profileId, profile, done);
        };
      }
    }, strategy);

    strategy.config.passReqToCallback = true;
  });

  return {
    init: function () {
      app.use(passport.initialize());
      app.use(passport.session());

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

      passport.deserializeUser(function (userId, done) {
        return done(null, {id: userId});
      });

      _.each(options.providers.strategies, function (strategy, name) {
        var Strategy = require(strategy.module).Strategy;

        passport.use(new Strategy(strategy.config, strategy.verify(
          function (req, profileId, profile, done) {
            var model = req.getModel()
              , target = {$query: {}}
              , coll = getUserCollection(options.accessLevels[0])
              , doc = options.providers.path + '.' + name + '.id'
              , query = model.query(coll, target)
              , userId = model.get('_session.' + options.session.idPath);

            target.$query[doc] = profileId;

            model.fetch(query, function (err) {
              if (err) return done(err);
              userId = dotty.get(query.get(), '0.id') || userId;

              _.each(options.accessLevels, function (lvl) {
                var coll = getUserCollection(lvl)
                  , part = model.at(coll + '.' + userId)
                  , prov = part.at(options.providers.path + '.' + name);

                part.fetch(function (err) {
                  if (err) return done(err);
                  part.set('id', userId);
                  part.set('registered', true);
                  prov.set('id', profileId)

                  _.each(options.providers.schema[lvl], function (path) {
                    if (path === '*') {
                      prov.set(profile);
                      profile = {};
                    } else {
                      var val = dotty.get(profile, path);
                      if (!val) return;
                      prov.set(path, val);
                      dotty.remove(profile, path);
                    }
                  });
                });
              });

              model.set('_session.' + options.session.idPath, userId);
              model.set('_session.' + options.session.isRegisteredPath, true);
              dotty.put(req.session, options.session.idPath, userId);
              dotty.put(req.session, options.session.isRegisteredPath, true);
              done(null, {id: userId});
            });
          }
        )));
      });

      return function (req, res, next) {
        var model = req.getModel()
          , userId = dotty.get(req.session, options.session.idPath);

        if (userId) {
          var coll = getUserCollection(options.accessLevels[0])
            , part = model.at(coll + '.' + userId);

          part.fetch(function (err) {
            if (err) return next(err);
            model.set('_session.' + options.session.isRegisteredPath, part.get('registered'));
          });
        } else {
          userId = model.id();
          dotty.put(req.session, options.session.idPath, userId);

          _.each(options.accessLevels, function (lvl) {
            model.add(getUserCollection(lvl), {id: userId, registered: false});
          });

          model.set('_session.' + options.session.isRegisteredPath, false);
        }

        model.set('_session.' + options.session.idPath, userId);
        model.set(options.clientConfigPath + '.accessLevels', options.accessLevels);
        model.set(options.clientConfigPath + '.session', options.session);
        model.set(options.clientConfigPath + '.signOutRoute', options.signOutRoute);
        next();
      };
    },
    routes: function () {
      _.each(options.providers.strategies, function (strategy, name) {

        app.get(strategy.options.url, passport.authenticate(name, strategy.options));

        app.get(strategy.callback.url, passport.authenticate(name, strategy.callback), function (req, res) {
          if (!strategy.callback.popup) return res.redirect('/');

          var model = req.getModel()
            , userId = model.get('_session.' + options.session.idPath);

          // blank page with a script that immediately closes the window
          var script = _s.sprintf("<script>"
            + "if (opener && opener.location) {"
            + "opener.DERBY.app.model.set('_session.%s', '%s');"
            + "opener.DERBY.app.model.set('_session.%s', true);"
            + "}"
            + "window.close();"
            + "</script>",
            options.session.idPath,
            userId,
            options.session.isRegisteredPath
          );

          res.send(script);
        });
      });

      app.post(options.signInRoute, function (req, res) {
        var model = req.getModel()
          , user = assembleUser(req.body)
          , pass = dotty.get(user, options.local.password.path);

        findUserId(model, user, function (err, userId) {
          var failure = function (err) {
            if (err) console.error(err);
            return res.send();
          }

          var success = function () {
            dotty.put(req.session, options.session.idPath, userId);
            model.set('_session.' + options.session.idPath, userId);
            model.set('_session.' + options.session.isRegisteredPath, true);
            return res.send({id: userId, isRegistered: true});
          }

          if (err) return failure(err);
          if (!userId) return failure();
          if (!options.local.password) return success();

          var coll = getUserCollection(options.local.password.path.split('.')[0])
            , part = model.at(coll + '.' + userId)
            , path = options.local.password.path.split('.').slice(1).join('.')

          part.fetch(function (err) {
            if (err) return failure(err);
            var dbPass = part.get(path);

            if (options.local.password.hash) {
              return passwordHash.verify(pass, dbPass) ? success() : failure();
            }

            return dbPass === pass ? success() : failure();
          });
        });
      });

      app.post(options.signOutRoute, function (req, res) {
        var model = req.getModel()
          , userId = dotty.get(req.session, options.session.idPath)
          , user = model.at(getUserCollection() + '.' + userId);

        user.fetch(function (err) {
          if (err) return res.send(500, {err: err});
          if (!user.get('registered')) return res.send(400, {error: 'already signed out'});
          var userId = model.id();
          dotty.put(req.session, options.session.idPath, userId);

          _.each(options.accessLevels, function (lvl) {
            model.add(getUserCollection(lvl), {id: userId, registered: false});
          });

          model.set('_session.' + options.session.isRegisteredPath, false);
          return res.send({id: userId});
        });
      });

      app.post(options.signUpRoute, function (req, res) {
        var model = req.getModel()
          , user = assembleUser(req.body)
          , userId = dotty.get(req.session, options.session.idPath);

        if (options.local.password && options.local.password.hash) {
          var pass = dotty.get(user, options.local.password.path)
            , hash = passwordHash.generate(pass, options.local.password.hash);

          // replace user password with hashed password
          dotty.put(user, options.local.password.path, hash);
        }

        _.each(options.accessLevels, function (lvl) {
          var part = model.at(getUserCollection(lvl) + '.' + userId);

          part.fetch(function (err) {
            if (err) return res.send(500, {error: err});
            var obj = _.merge(part.get(), user[lvl], {registered: true});
            part.set(obj);
          });
        });

        return res.send();
      });

      return function (req, res, next) {
        next();
      };
    }
  }
};<commit_msg>add _json.picture to public, allow strategy name to be specified<commit_after>var _ = require('lodash')
  , _s = require('underscore.string')
  , async = require('async')
  , dotty = require('dotty')
  , passport = require('passport')
  , passwordHash = require('password-hash');

module.exports = function (app, options) {
  var assembleUser = function (obj) {
    var user = {};

    _.each(options.accessLevels, function (lvl) {
      user[lvl] = {};
    });

    _.each(obj, function (val, key) {
      dotty.put(user, key, val);
    });

    return user;
  };

  var findUserId = function (model, user, callback) {
    if (_.isFunction(options.local.findUserId)) {
      return options.local.findUserId(model, user, callback);
    }

    var found = null;

    async.some(options.local.findUserId, function (path, callback) {
      path = path.split('.');

      var val = dotty.get(user, path)
        , coll = getUserCollection(path.shift())
        , doc = path.join('.')
        , target = {$query: {}};

      target.$query[doc] = val;
      var query = model.query(coll, target);

      model.fetch(query, function (err) {
        if (err) return callback(err);
        var userId = dotty.get(query.get(), '0.id');
        if (userId) found = userId;
        callback(userId);
      });
    }, function (userId) {
      callback(null, found);
    });
  };

  var getUserCollection = function (lvl) {
    if (!lvl) lvl = options.accessLevels[0];
    return options.collectionName + _s.capitalize(lvl);
  };

  options = _.merge(options || {}, {
    accessLevels: [
      'public',
      'private'
    ],
    clientConfigPath: '$auth',
    collectionName: 'users',
    local: {
      findUserId: [
        'private.local.email',
        'public.local.username'
      ],
      password: {
        hash: {},
        maximumLength: 100,
        minimumLength: 6,
        path: 'private.local.password'
      },
    },
    providers: {
      schema: {
        'public': ['_json.picture', 'displayName', 'photos', 'username'],
        'private': '*'
      },
      strategies: {},
      path: 'providers'
    },
    session: {
      idPath: 'user.id',
      isRegisteredPath: 'user.isRegistered'
    },
    signInRoute: '/signin',
    signOutRoute: '/signout',
    signUpRoute: '/signup'
  });

  if (_.isString(options.local.findUserId)) {
    options.local.findUserId = [options.local.findUserId];
  }

  if (!options.accessLevels) {
    options.accessLevels = [''];
  }

  _.each(options.accessLevels, function (lvl) {
    var schema = options.providers.schema;
    if (!schema[lvl]) schema[lvl] = [];
    if (_.isString(schema[lvl])) schema[lvl] = [schema[lvl]];
  });

  _.each(options.providers.strategies, function (strategy, name) {
    _.merge(strategy, {
      callback: {
        popup: true,
        url: '/auth/' + name + '/callback'
      },
      config: {},
      module: 'passport-' + name,
      name: 'Strategy',
      options: {
        url: '/auth/' + name
      },
      verify: function (callback) {
        return function () {
          var req = arguments[0]
            , profile = _.last(arguments, 2)[0]
            , profileId = arguments.length === 4 ? arguments[1] : profile.id
            , done = _.last(arguments);

          callback(req, profileId, profile, done);
        };
      }
    }, _.defaults);

    strategy.config.passReqToCallback = true;
  });

  return {
    init: function () {
      app.use(passport.initialize());
      app.use(passport.session());

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

      passport.deserializeUser(function (userId, done) {
        return done(null, {id: userId});
      });

      _.each(options.providers.strategies, function (strategy, name) {
        var Strategy = require(strategy.module)[strategy.name];

        passport.use(new Strategy(strategy.config, strategy.verify(
          function (req, profileId, profile, done) {
            var model = req.getModel()
              , target = {$query: {}}
              , coll = getUserCollection(options.accessLevels[0])
              , doc = options.providers.path + '.' + name + '.id'
              , query = model.query(coll, target)
              , userId = model.get('_session.' + options.session.idPath);

            target.$query[doc] = profileId;

            model.fetch(query, function (err) {
              if (err) return done(err);
              userId = dotty.get(query.get(), '0.id') || userId;

              _.each(options.accessLevels, function (lvl) {
                var coll = getUserCollection(lvl)
                  , part = model.at(coll + '.' + userId)
                  , prov = part.at(options.providers.path + '.' + name);

                part.fetch(function (err) {
                  if (err) return done(err);
                  part.set('id', userId);
                  part.set('registered', true);
                  prov.set('id', profileId)

                  _.each(options.providers.schema[lvl], function (path) {
                    if (path === '*') {
                      prov.set(profile);
                      profile = {};
                    } else {
                      var val = dotty.get(profile, path);
                      if (!val) return;
                      prov.set(path, val);
                      dotty.remove(profile, path);
                    }
                  });
                });
              });

              model.set('_session.' + options.session.idPath, userId);
              model.set('_session.' + options.session.isRegisteredPath, true);
              dotty.put(req.session, options.session.idPath, userId);
              dotty.put(req.session, options.session.isRegisteredPath, true);
              done(null, {id: userId});
            });
          }
        )));
      });

      return function (req, res, next) {
        var model = req.getModel()
          , userId = dotty.get(req.session, options.session.idPath);

        if (userId) {
          var coll = getUserCollection(options.accessLevels[0])
            , part = model.at(coll + '.' + userId);

          part.fetch(function (err) {
            if (err) return next(err);
            model.set('_session.' + options.session.isRegisteredPath, part.get('registered'));
          });
        } else {
          userId = model.id();
          dotty.put(req.session, options.session.idPath, userId);

          _.each(options.accessLevels, function (lvl) {
            model.add(getUserCollection(lvl), {id: userId, registered: false});
          });

          model.set('_session.' + options.session.isRegisteredPath, false);
        }

        model.set('_session.' + options.session.idPath, userId);
        model.set(options.clientConfigPath + '.accessLevels', options.accessLevels);
        model.set(options.clientConfigPath + '.session', options.session);
        model.set(options.clientConfigPath + '.signOutRoute', options.signOutRoute);
        next();
      };
    },
    routes: function () {
      _.each(options.providers.strategies, function (strategy, name) {

        app.get(strategy.options.url, passport.authenticate(name, strategy.options));

        app.get(strategy.callback.url, passport.authenticate(name, strategy.callback), function (req, res) {
          if (!strategy.callback.popup) return res.redirect('/');

          var model = req.getModel()
            , userId = model.get('_session.' + options.session.idPath);

          // blank page with a script that immediately closes the window
          var script = _s.sprintf("<script>"
            + "if (opener && opener.location) {"
            + "opener.DERBY.app.model.set('_session.%s', '%s');"
            + "opener.DERBY.app.model.set('_session.%s', true);"
            + "}"
            + "window.close();"
            + "</script>",
            options.session.idPath,
            userId,
            options.session.isRegisteredPath
          );

          res.send(script);
        });
      });

      app.post(options.signInRoute, function (req, res) {
        var model = req.getModel()
          , user = assembleUser(req.body)
          , pass = dotty.get(user, options.local.password.path);

        findUserId(model, user, function (err, userId) {
          var failure = function (err) {
            if (err) console.error(err);
            return res.send();
          }

          var success = function () {
            dotty.put(req.session, options.session.idPath, userId);
            model.set('_session.' + options.session.idPath, userId);
            model.set('_session.' + options.session.isRegisteredPath, true);
            return res.send({id: userId, isRegistered: true});
          }

          if (err) return failure(err);
          if (!userId) return failure();
          if (!options.local.password) return success();

          var coll = getUserCollection(options.local.password.path.split('.')[0])
            , part = model.at(coll + '.' + userId)
            , path = options.local.password.path.split('.').slice(1).join('.')

          part.fetch(function (err) {
            if (err) return failure(err);
            var dbPass = part.get(path);

            if (options.local.password.hash) {
              return passwordHash.verify(pass, dbPass) ? success() : failure();
            }

            return dbPass === pass ? success() : failure();
          });
        });
      });

      app.post(options.signOutRoute, function (req, res) {
        var model = req.getModel()
          , userId = dotty.get(req.session, options.session.idPath)
          , user = model.at(getUserCollection() + '.' + userId);

        user.fetch(function (err) {
          if (err) return res.send(500, {err: err});
          if (!user.get('registered')) return res.send(400, {error: 'already signed out'});
          var userId = model.id();
          dotty.put(req.session, options.session.idPath, userId);

          _.each(options.accessLevels, function (lvl) {
            model.add(getUserCollection(lvl), {id: userId, registered: false});
          });

          model.set('_session.' + options.session.isRegisteredPath, false);
          return res.send({id: userId});
        });
      });

      app.post(options.signUpRoute, function (req, res) {
        var model = req.getModel()
          , user = assembleUser(req.body)
          , userId = dotty.get(req.session, options.session.idPath);

        if (options.local.password && options.local.password.hash) {
          var pass = dotty.get(user, options.local.password.path)
            , hash = passwordHash.generate(pass, options.local.password.hash);

          // replace user password with hashed password
          dotty.put(user, options.local.password.path, hash);
        }

        _.each(options.accessLevels, function (lvl) {
          var part = model.at(getUserCollection(lvl) + '.' + userId);

          part.fetch(function (err) {
            if (err) return res.send(500, {error: err});
            var obj = _.merge(part.get(), user[lvl], {registered: true});
            part.set(obj);
          });
        });

        return res.send();
      });

      return function (req, res, next) {
        next();
      };
    }
  }
};<|endoftext|>


<commit_before>const Discord = require("discord.js"),
    fs = require('fs'),
    client = new Discord.Client(),
	ytdl = require('ytdl-core'),
	ffmpeg = require('fluent-ffmpeg'),
	exec = require('child_process').exec,
	yts = require('youtube-search'),
	pip = require('public-ip'),
    config = require('./auth.json'),
	server_cfg = require('./server/server.json');

var connections = [];
var queues = {
	"-1": [
		{
		}
	]
};

var servers_joined = 0;

const spinner_array = [ "-", "\\", "|", "/" ];
var spinner_index = -1;

const wide_chars = "ａｂｃｄｅｆｇｈｉｊｋｌｍｎｏｐｑｒｓｔｕｖｗｘｙｚＡＢＣＤＥＦＧＨＩＪＫＬＭＮＯＰＱＲＳＴＵＶＷＸＹＺ ０１２３４５６７８９！＃＄％＆＇（）＊＋－．，／：；＜＞＠＝？［］｛｝～｜＿"
const normal_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789!#$%&'()*+-.,/:;<>@=?[]{}~|_"

function get_spinner()
{
	spinner_index++;
    return spinner_array[spinner_index%4];
}

function play(connection, id, msg)
{
	return new Promise((resolve, reject) =>
	{
		connections[connection.channelID] = connection;
		if (connection.playing)
		{
			reject(new Error("Already playing a song!"));
		}
		var already_downloaded = fs.existsSync(`./downloads/${id}p.wav`);
		if (!already_downloaded)
		{
			var dl_msg;
			var last_progress_update = 0;
			msg.channel.sendMessage("Downloading...").then(m => {
				dl_msg = m;
				ytdl("http://www.youtube.com/watch?v="+id, { filter: 'audioonly' }).on('progress', (chunk, downloaded, total) => {
					//console.log(`PROGRESS: ${downloaded}/${total}`)
					last_progress_update++;
					// idk
					if (last_progress_update % 100 == 0 || downloaded >= total)
					{
						dl_msg.edit("Downloading... "+ ((downloaded >= total) ? ":100: %" : ("`"+get_spinner()+"`")))
						.then(() => {
							if (downloaded >= total)
							{
									//console.log(downloaded, total)
									msg.channel.sendMessage("Processing...");
									console.log("Downloaded http://youtu.be/"+id);
									var command = ffmpeg(`./downloads/${id}.ogg`).format("wav").audioBitrate('48k').on('end', (stdout, stderr) => {
										console.log("Successfully converted https://youtu.be/"+ id);
										msg.channel.sendMessage("(1/2) FFmpeg conversion done.");
										// Floral Shoppe: ~60% tempo, P4 down (-500 cents).
										exec(`sox ./downloads/${id}.wav ./downloads/${id}p.wav tempo 0.6 pitch -500`, (error, stdout, stderr) => {
											msg.channel.sendMessage("(2/2) SoX effects done. Will begin streaming.");
											var stream = fs.createReadStream(`./downloads/${id}p.wav`);
											connection.playStream(stream).on('end', () => {resolve();});
											var saved = (fs.statSync("./downloads/"+id+".wav").size + fs.statSync("./downloads/"+id+".ogg").size)/1024.0/1024.0;
											exec(`rm ./downloads/${id}.ogg ./downloads/${id}.wav`, (error, stdout, stderr) => {
												console.log(`Conserved ${saved.toFixed(2)} MB deleting old files for http://youtu.be/${id}`);
											});
											//bot.createMessage(now.txt, `Playing **${now.name}**`);
											//return stream;
										});
									}).save(`./downloads/${id}.wav`);
								}
						})
						.catch(console.error);
						last_progress_update = Date.now();
					}
				}).pipe(fs.createWriteStream(`./downloads/${id}.ogg`));
			}).catch((err) => {
				reject(new Error(err));
			});
		}
		else
		{
			console.log(`No need to download http://youtu.be/${id}; I have it cached.`);
			msg.channel.sendMessage("Already downloaded & processed. Streaming cached version...");
			var stream = fs.createReadStream("./downloads/"+id+'p.wav');
			connection.playStream(stream).on('end', () => {resolve();});
			//return stream;
			//bot.createMessage(now.txt, `Playing **${now.name}**`);
		}
	});
}

function pre_play(msg, id)
{
	msg.delete();
	if (!msg.member.voiceChannel)
	{
		msg.reply("You need to be in a voice channel.");
	}
	else
	{
			// "Initializing" a list item
			var new_to_queue = false;
			if (!queues[msg.guild.id] || queues[msg.guild.id].length == 0)
			{
				new_to_queue = true;
				queues[msg.guild.id] = [];
			}
			ytdl.getInfo("https://youtube.com/watch?v="+id, options=null, (err, info) => {
				if (err)
				{
					console.error(err);
				}
				console.log(`Fetched title for http://youtu.be/${id}: "${info.title}"`);
				queues[msg.guild.id].push({
					"url": id,
					"requester": msg.author.username,
					"vc": msg.member.voiceChannel,
					"tc": msg.channel,
					"title": info.title
				});

				if (new_to_queue) next_in_queue(msg, 0);
				else msg.reply("I've added your song request to the queue.");
			});
	}
}

// Start here
client.login(config.token);

/*client.on('guildMemberAdd', member => {
	console.log(member.nickname+" ["+member.id+"] joined the guild");
	if (member.id == client.user.id)
		member.setNickname("VAPOURBOT / 蒸気ロボット");
});*/

client.on('message', msg => {
	//console.log(msg.content)
	if (msg.content.startsWith(config.prefix+"vapor ") || msg.content.startsWith(config.prefix+"vapour "))
	{
		var yt_regex = /(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\/?\?(?:\S*?&?v\=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})/g;
		var url = msg.content.replace(new RegExp("\\"+config.prefix+"(vapor|vapour)\ "), "")
		//console.log(url);
		var ex = yt_regex.exec(url);
		var id = ex ? ex[1] : null;
		//console.log(id);
		if (!id)
		{
			yts(url, {maxResults: 1, key: config.yt_key }, (err, results) => {
				//console.log(results)
				if (err)
				{
					console.error(err);
					msg.reply(`Failed to search for video \`${url}\``);
				}
				else
				{
					pre_play(msg, results[0].id);
				}
			});
		}
		else
		{
			pre_play(msg, id);
		}
	}
	else if (msg.content.startsWith(config.prefix+"nick"))
	{
		msg.delete();
		msg.author.sendMessage("ｎｉｃｅ ｍｅｍｅ ｋｉｄｄｏ");
		msg.channel.guild.members.find("id", client.user.id).setNickname("VAPOURBOT / 蒸気ロボット");
	}
	else if (msg.content.startsWith(config.prefix+"queue"))
	{
		if (queues[msg.guild.id] && queues[msg.guild.id][0])
		{
			var str = "\n";
			queues[msg.guild.id].forEach((e, i) => {
				str += `${i+1}. **${e.title}** (\`https://youtu.be/${e.url}\`) - Requested by **${e.requester}**\n`;
			});
			msg.reply(str);
		}
		else
			msg.reply("There are no songs currently in the queue -- now's your chance! Play a song with `>vapour [YouTube URL]`.");
	}
	else if (msg.content.startsWith(config.prefix+"wide "))
	{
		var str = msg.content.replace(config.prefix+"wide ", "");
		var new_str = [];
		for (var i=0; i<str.length; i++)
		{
			new_str[i] = wide_chars[normal_chars.indexOf(str[i])] ? wide_chars[normal_chars.indexOf(str[i])] : str[i];
		}
		msg.channel.sendMessage(new_str.join(""));
	}
	else if (msg.content.startsWith(config.prefix+"spacify "))
	{
		var str = msg.content.replace(config.prefix+"spacify ", "");
		var new_str = "";
		for (var i=0; i<str.length; i++)
		{
			new_str += (str[i] + " ");
		}
		msg.channel.sendMessage(new_str);
	}
	else if (msg.content.startsWith(config.prefix+"help"))
	{
		pip.v4().then(ip => {
			msg.reply(`\n\`${config.prefix}vapour [YouTube video]\` - plays a YouTube video (by name or URL) in vaporwave style.\n`+
				`\`${config.prefix}vapor [YouTube video]\` - same function as \`${config.prefix}vapour\`.\n`+
				`\`${config.prefix}queue\` - Displays the current queue of requested songs and who requested them.\n`+
				`\`${config.prefix}wide [text]\` - Converts normal text into ｗｉｄｅ ｔｅｘｔ．\n`+
				`\`${config.prefix}spacify [text]\` - Converts normal text into s p a c i f i e d  t e x t .\n`+
				`\`${config.prefix}help\` - Shows this message.\n`+
				`You can view and download the songs I have processed at http://${ip}${(server_cfg.port == 80) ? "" : ":"+ server_cfg.port}/`);
		});
	}
	else
	{
	}
});

// Loops through queue.
function next_in_queue(msg, index)
{
	var id = msg.guild.id;
	var current = queues[id][index];
	current.vc.join().then(connection => {
		console.log("Connected to voice in guild "+ msg.guild.id);
		play(connection, current.url, msg).then(() => {
			var next = queues[id][index + 1];
			console.log("Stream ended in guild "+ msg.guild.id +". "+ (next ? "Now playing http://youtu.be/"+next.title : "Queue is done.") );
			if (next)
			{
				msg.channel.sendMessage(`Now Playing: **${next.title}** - \`https://youtu.be/${next.url}\` (requested by **${next.requester}**)`);
				// dat recursion
				next_in_queue(msg, index + 1);
			}
			else
			{
				msg.channel.sendMessage("I've played every song in the queue.");
				current.vc.leave();
				queues[id] = [];
			}
		}).catch((err) => {
			console.error(err);
		});
	});
}

client.on('voiceStateUpdate', (oldMember, newMember) => {
    if (queues[newMember.guild.id])
	{
        var vc = newMember.voiceChannel ? newMember.voiceChannel : oldMember.voiceChannel;
		if (vc.members.array().length == 1 && vc.members.array()[0].user.equals(client.user))
		{
			vc.leave();
			queues[vc.guild.id][queues[vc.guild.id].length-1].tc.sendMessage("Nobody's in the voice channel anymore, so I ended the queue.");
			queues[vc.guild.id] = [];
		}
	}
});

client.on('ready', () => {
    console.log('Logged in.');
	setInterval(() => {
		client.user.setStatus('online', `${config.prefix}help | Serving ${client.guilds.array().length} servers`);
	}, 5000);
});
<commit_msg>Additional dependencies<commit_after>const Discord = require("discord.js"),
    fs = require('fs'),
    client = new Discord.Client(),
	ytdl = require('ytdl-core'),
	ffmpeg = require('fluent-ffmpeg'),
	exec = require('child_process').exec,
	yts = require('youtube-search'),
	pip = require('public-ip'),
    config = require('./auth.json'),
	server_cfg = require('./server/server.json'),
	request = require('request'),
	md = require("html-md"),
	async = require("async"),
	wolfram = require('wolfram').createClient(config.wolfram_key);

var connections = [];
var queues = {
	"-1": [
		{
		}
	]
};

var servers_joined = 0;

const spinner_array = [ "-", "\\", "|", "/" ];
var spinner_index = -1;

const wide_chars = "ａｂｃｄｅｆｇｈｉｊｋｌｍｎｏｐｑｒｓｔｕｖｗｘｙｚＡＢＣＤＥＦＧＨＩＪＫＬＭＮＯＰＱＲＳＴＵＶＷＸＹＺ ０１２３４５６７８９！＃＄％＆＇（）＊＋－．，／：；＜＞＠＝？［］｛｝～｜＿"
const normal_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789!#$%&'()*+-.,/:;<>@=?[]{}~|_"

function get_spinner()
{
	spinner_index++;
    return spinner_array[spinner_index%4];
}

function play(connection, id, msg)
{
	return new Promise((resolve, reject) =>
	{
		connections[connection.channelID] = connection;
		if (connection.playing)
		{
			reject(new Error("Already playing a song!"));
		}
		var already_downloaded = fs.existsSync(`./downloads/${id}p.wav`);
		if (!already_downloaded)
		{
			var dl_msg;
			var last_progress_update = 0;
			msg.channel.sendMessage("Downloading...").then(m => {
				dl_msg = m;
				ytdl("http://www.youtube.com/watch?v="+id, { filter: 'audioonly' }).on('progress', (chunk, downloaded, total) => {
					//console.log(`PROGRESS: ${downloaded}/${total}`)
					last_progress_update++;
					// idk
					if (last_progress_update % 100 == 0 || downloaded >= total)
					{
						dl_msg.edit("Downloading... "+ ((downloaded >= total) ? ":100: %" : ("`"+get_spinner()+"`")))
						.then(() => {
							if (downloaded >= total)
							{
									//console.log(downloaded, total)
									msg.channel.sendMessage("Processing...");
									console.log("Downloaded http://youtu.be/"+id);
									var command = ffmpeg(`./downloads/${id}.ogg`).format("wav").audioBitrate('48k').on('end', (stdout, stderr) => {
										console.log("Successfully converted https://youtu.be/"+ id);
										msg.channel.sendMessage("(1/2) FFmpeg conversion done.");
										// Floral Shoppe: ~60% tempo, P4 down (-500 cents).
										exec(`sox ./downloads/${id}.wav ./downloads/${id}p.wav tempo 0.6 pitch -500`, (error, stdout, stderr) => {
											msg.channel.sendMessage("(2/2) SoX effects done. Will begin streaming.");
											var stream = fs.createReadStream(`./downloads/${id}p.wav`);
											connection.playStream(stream).on('end', () => {resolve();});
											var saved = (fs.statSync("./downloads/"+id+".wav").size + fs.statSync("./downloads/"+id+".ogg").size)/1024.0/1024.0;
											exec(`rm ./downloads/${id}.ogg ./downloads/${id}.wav`, (error, stdout, stderr) => {
												console.log(`Conserved ${saved.toFixed(2)} MB deleting old files for http://youtu.be/${id}`);
											});
											//bot.createMessage(now.txt, `Playing **${now.name}**`);
											//return stream;
										});
									}).save(`./downloads/${id}.wav`);
								}
						})
						.catch(console.error);
						last_progress_update = Date.now();
					}
				}).pipe(fs.createWriteStream(`./downloads/${id}.ogg`));
			}).catch((err) => {
				reject(new Error(err));
			});
		}
		else
		{
			console.log(`No need to download http://youtu.be/${id}; I have it cached.`);
			msg.channel.sendMessage("Already downloaded & processed. Streaming cached version...");
			var stream = fs.createReadStream("./downloads/"+id+'p.wav');
			connection.playStream(stream).on('end', () => {resolve();});
			//return stream;
			//bot.createMessage(now.txt, `Playing **${now.name}**`);
		}
	});
}

function pre_play(msg, id)
{
	msg.delete();
	if (!msg.member.voiceChannel)
	{
		msg.reply("You need to be in a voice channel.");
	}
	else
	{
			// "Initializing" a list item
			var new_to_queue = false;
			if (!queues[msg.guild.id] || queues[msg.guild.id].length == 0)
			{
				new_to_queue = true;
				queues[msg.guild.id] = [];
			}
			ytdl.getInfo("https://youtube.com/watch?v="+id, options=null, (err, info) => {
				if (err)
				{
					console.error(err);
				}
				console.log(`Fetched title for http://youtu.be/${id}: "${info.title}"`);
				queues[msg.guild.id].push({
					"url": id,
					"requester": msg.author.username,
					"vc": msg.member.voiceChannel,
					"tc": msg.channel,
					"title": info.title
				});

				if (new_to_queue) next_in_queue(msg, 0);
				else msg.reply("I've added your song request to the queue.");
			});
	}
}

// Start here
client.login(config.token);

/*client.on('guildMemberAdd', member => {
	console.log(member.nickname+" ["+member.id+"] joined the guild");
	if (member.id == client.user.id)
		member.setNickname("VAPOURBOT / 蒸気ロボット");
});*/

client.on('message', msg => {
	//console.log(msg.content)
	if (msg.content.startsWith(config.prefix+"vapor ") || msg.content.startsWith(config.prefix+"vapour "))
	{
		var yt_regex = /(?:youtube\.com\/\S*(?:(?:\/e(?:mbed))?\/|watch\/?\?(?:\S*?&?v\=))|youtu\.be\/)([a-zA-Z0-9_-]{6,11})/g;
		var url = msg.content.replace(new RegExp("\\"+config.prefix+"(vapor|vapour)\ "), "")
		//console.log(url);
		var ex = yt_regex.exec(url);
		var id = ex ? ex[1] : null;
		//console.log(id);
		if (!id)
		{
			yts(url, {maxResults: 1, key: config.yt_key }, (err, results) => {
				//console.log(results)
				if (err)
				{
					console.error(err);
					msg.reply(`Failed to search for video \`${url}\``);
				}
				else
				{
					pre_play(msg, results[0].id);
				}
			});
		}
		else
		{
			pre_play(msg, id);
		}
	}
	else if (msg.content.startsWith(config.prefix+"nick"))
	{
		msg.delete();
		msg.author.sendMessage("ｎｉｃｅ ｍｅｍｅ ｋｉｄｄｏ");
		msg.channel.guild.members.find("id", client.user.id).setNickname("VAPOURBOT / 蒸気ロボット");
	}
	else if (msg.content.startsWith(config.prefix+"queue"))
	{
		if (queues[msg.guild.id] && queues[msg.guild.id][0])
		{
			var str = "\n";
			queues[msg.guild.id].forEach((e, i) => {
				str += `${i+1}. **${e.title}** (\`https://youtu.be/${e.url}\`) - Requested by **${e.requester}**\n`;
			});
			msg.reply(str);
		}
		else
			msg.reply("There are no songs currently in the queue -- now's your chance! Play a song with `>vapour [YouTube URL]`.");
	}
	else if (msg.content.startsWith(config.prefix+"wide "))
	{
		var str = msg.content.replace(config.prefix+"wide ", "");
		var new_str = [];
		for (var i=0; i<str.length; i++)
		{
			new_str[i] = wide_chars[normal_chars.indexOf(str[i])] ? wide_chars[normal_chars.indexOf(str[i])] : str[i];
		}
		msg.channel.sendMessage(new_str.join(""));
	}
	else if (msg.content.startsWith(config.prefix+"spacify "))
	{
		var str = msg.content.replace(config.prefix+"spacify ", "");
		var new_str = "";
		for (var i=0; i<str.length; i++)
		{
			new_str += (str[i] + " ");
		}
		msg.channel.sendMessage(new_str);
	}
	else if (msg.content.startsWith(config.prefix+"help"))
	{
		pip.v4().then(ip => {
			msg.reply(`\n\`${config.prefix}vapour [YouTube video]\` - plays a YouTube video (by name or URL) in vaporwave style.\n`+
				`\`${config.prefix}vapor [YouTube video]\` - same function as \`${config.prefix}vapour\`.\n`+
				`\`${config.prefix}queue\` - Displays the current queue of requested songs and who requested them.\n`+
				`\`${config.prefix}wide [text]\` - Converts normal text into ｗｉｄｅ ｔｅｘｔ．\n`+
				`\`${config.prefix}spacify [text]\` - Converts normal text into s p a c i f i e d  t e x t .\n`+
				`\`${config.prefix}help\` - Shows this message.\n`+
				`You can view and download the songs I have processed at http://${ip}${(server_cfg.port == 80) ? "" : ":"+ server_cfg.port}/`);
		});
	}
	else
	{
	}
});

// Loops through queue.
function next_in_queue(msg, index)
{
	var id = msg.guild.id;
	var current = queues[id][index];
	current.vc.join().then(connection => {
		console.log("Connected to voice in guild "+ msg.guild.id);
		play(connection, current.url, msg).then(() => {
			var next = queues[id][index + 1];
			console.log("Stream ended in guild "+ msg.guild.id +". "+ (next ? "Now playing http://youtu.be/"+next.title : "Queue is done.") );
			if (next)
			{
				msg.channel.sendMessage(`Now Playing: **${next.title}** - \`https://youtu.be/${next.url}\` (requested by **${next.requester}**)`);
				// dat recursion
				next_in_queue(msg, index + 1);
			}
			else
			{
				msg.channel.sendMessage("I've played every song in the queue.");
				current.vc.leave();
				queues[id] = [];
			}
		}).catch((err) => {
			console.error(err);
		});
	});
}

client.on('voiceStateUpdate', (oldMember, newMember) => {
    if (queues[newMember.guild.id])
	{
        var vc = newMember.voiceChannel ? newMember.voiceChannel : oldMember.voiceChannel;
		if (vc.members.array().length == 1 && vc.members.array()[0].user.equals(client.user))
		{
			vc.leave();
			queues[vc.guild.id][queues[vc.guild.id].length-1].tc.sendMessage("Nobody's in the voice channel anymore, so I ended the queue.");
			queues[vc.guild.id] = [];
		}
	}
});

client.on('ready', () => {
    console.log('Logged in.');
	setInterval(() => {
		client.user.setStatus('online', `${config.prefix}help | Serving ${client.guilds.array().length} servers`);
	}, 5000);
});
<|endoftext|>


<commit_before>var Twit = require('twit');
var config = require('./config');
var fs = require('fs');
var giphy = require('giphy-api')('46fd06f1e7a44308af73e966081749e4');
console.log('Running Reply Bot')
//Oauth
var T = new Twit(config);

//Setup a stream
var stream = T.stream('user');

function random (low, high) {
    return Math.random() * (high - low) + low;
}

function TweetIt(txt) {

  var tweet = {
    status: txt
  }

  T.post('statuses/update', tweet, status);

  function status(err, data, response) {

    if (err) {
      console.log('Oh No! Something went wrong.');
      console.log(err);
    } else {
      console.log('Whoo it worked!');

    }
  }

}

function reply(tweet) {

  var recipiants = tweet.in_reply_to_screen_name;
  var sender = tweet.user.screen_name;
  var text = tweet.text;

  console.log(recipiants + ' ' + sender + ' ' + text);

  var params = {
    tag: text,
    rating: 'pg'
  }

  giphy.random(params, function(err, res){

    if(err) {
      console.log('Issue with Gif');

    } else {
    console.log('working!')
      var gif_url = res.data.url;
      var randnum = random(0,1000);
      if (recipiants == 'I_am_MrBot') {
        var rply = '@' + sender + ' ' + 'Thanks for the tweet! ' + randnum + ' ' + gif_url;
        console.log(rply);
        TweetIt(rply);
      }
    }
  });
}

stream.on('tweet', reply);
<commit_msg>Changed tweet message<commit_after>var Twit = require('twit');
var config = require('./config');
var fs = require('fs');
var giphy = require('giphy-api')('46fd06f1e7a44308af73e966081749e4');
console.log('Running Reply Bot')
//Oauth
var T = new Twit(config);

//Setup a stream
var stream = T.stream('user');

function random (low, high) {
    return Math.random() * (high - low) + low;
}

function TweetIt(txt) {

  var tweet = {
    status: txt
  }

  T.post('statuses/update', tweet, status);

  function status(err, data, response) {

    if (err) {
      console.log('Oh No! Something went wrong.');
      console.log(err);
    } else {
      console.log('Whoo it worked!');

    }
  }

}

function reply(tweet) {

  var recipiants = tweet.in_reply_to_screen_name;
  var sender = tweet.user.screen_name;
  var text = tweet.text;

  console.log(recipiants + ' ' + sender + ' ' + text);

  var params = {
    tag: text,
    rating: 'pg'
  }

  giphy.random(params, function(err, res){

    if(err) {
      console.log('Issue with Gif');

    } else {
    console.log('working!')
      var gif_url = res.data.url;
      var randnum = random(0,1000);
      if (recipiants == 'I_am_MrBot') {
        var rply = '@' + sender + ' ' + 'Here have a gif!  ' + ' ' + gif_url;
        console.log(rply);
        TweetIt(rply);
      }
    }
  });
}

stream.on('tweet', reply);
<|endoftext|>


<commit_before>const winston = require('winston');
const Telegraf = require('telegraf');
const commandParts = require('telegraf-command-parts');
const CronJob = require('cron').CronJob;
const secrets = require('./lib/secrets').load();
const {getUnreadMessages} = require('./lib/scraper');
const hashTracker = require('./lib/hashTracker');

let job;

const webmailLinkKeyboard = Telegraf.Extra
  .markdown()
  .markup((m) => m.inlineKeyboard([
    Telegraf.Markup.urlButton('Apri WebMail', 'https://webmail.studenti.unipi.it/horde/imp/')
  ]));

async function checkSecrets() {
  if (!secrets.telegram_token) {
    throw 'Non hai configurato il token del bot Telegram.';
  }
  if (!secrets.telegram_password) {
    throw 'Non hai configurato la password per il bot Telegram.';
  }
}

function formatNewMessage(message) {
  return 'Hai un nuovo messaggio! 📬\n\n' +
    `*Mittente*: ${message.from}\n` +
    `*Oggetto*: ${message.subject}\n` +
    `*Dimensione*: ${message.size}`
}

async function setCronjob(bot, chatid) {
  async function doCronjob() {
    winston.info('Running cronjob for chat ID', chatid, '...');
    let unseen = (await getUnreadMessages(secrets));
    if (unseen.length > 0) {
      for (let i = 0; i < unseen.length; i++) {
        let msg = formatNewMessage(unseen[i]);
        let msgHash = hashTracker.md5(msg);
        if (!hashTracker.isSeen(msgHash)) {
          bot.telegram.sendMessage(chatid, msg, webmailLinkKeyboard);
          hashTracker.setSeen(msgHash);
        }
      }
    }
    winston.info('Done running cronjob for chat ID', chatid, '.');
  }

  // noinspection JSUnusedGlobalSymbols
  job = new CronJob({
    cronTime: '0 0 * * * *',
    onTick: await doCronjob,
  });
  job.start();
  await doCronjob();
}

checkSecrets()
  .then(() => {
    const bot = new Telegraf(secrets.telegram_token);

    bot.use(commandParts());

    bot.command('start', (ctx) => {
      let isPasswordOk = (ctx.state.command.args || '') === secrets.telegram_password;
      winston.info(ctx.chat.id, ctx.from.username, '/start', isPasswordOk ? 'PASS OK' : 'PASS KO');
      ctx.reply(isPasswordOk ? '👍✅ ⇒ 🔛' : '👎🚫');
      if (isPasswordOk) {
        setCronjob(bot, ctx.chat.id);
      }
    });

    bot.command('stop', (ctx) => {
      let isPasswordOk = (ctx.state.command.args || '') === secrets.telegram_password;
      winston.info(ctx.chat.id, ctx.from.username, '/stop', isPasswordOk ? 'PASS OK' : 'PASS KO');
      ctx.reply(isPasswordOk ? '👍✅ ⇒ 📴' : '👎🚫');
      if (isPasswordOk) {
        cleanup(false);
      }
    });

    bot.command('ping', (ctx) => {
      winston.info(ctx.chat.id, ctx.from.username, '/ping');
      ctx.reply('pong!');
    });

    bot.startPolling();
  })
  .catch((e) => {
    winston.error(e);
  });

// Cleanups & Promises handling

function cleanup(exit) {
  if (job && job.running) job.stop();
  if (exit) process.exit();
}

process.on('exit', () => {
  cleanup(true);
});
process.on('SIGINT', () => {
  cleanup(true);
});
process.on('SIGUSR1', () => {
  cleanup(true);
});
process.on('SIGUSR2', () => {
  cleanup(true);
});
process.on('uncaughtException', () => {
  cleanup(true);
});

process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
});
<commit_msg>Intervallo di controllo email portato a 15min<commit_after>const winston = require('winston');
const Telegraf = require('telegraf');
const commandParts = require('telegraf-command-parts');
const CronJob = require('cron').CronJob;
const secrets = require('./lib/secrets').load();
const {getUnreadMessages} = require('./lib/scraper');
const hashTracker = require('./lib/hashTracker');

let job;

const webmailLinkKeyboard = Telegraf.Extra
  .markdown()
  .markup((m) => m.inlineKeyboard([
    Telegraf.Markup.urlButton('Apri WebMail', 'https://webmail.studenti.unipi.it/horde/imp/')
  ]));

async function checkSecrets() {
  if (!secrets.telegram_token) {
    throw 'Non hai configurato il token del bot Telegram.';
  }
  if (!secrets.telegram_password) {
    throw 'Non hai configurato la password per il bot Telegram.';
  }
}

function formatNewMessage(message) {
  return 'Hai un nuovo messaggio! 📬\n\n' +
    `*Mittente*: ${message.from}\n` +
    `*Oggetto*: ${message.subject}\n` +
    `*Dimensione*: ${message.size}`
}

async function setCronjob(bot, chatid) {
  async function doCronjob() {
    winston.info('Running cronjob for chat ID', chatid, '...');
    let unseen = (await getUnreadMessages(secrets));
    if (unseen.length > 0) {
      for (let i = 0; i < unseen.length; i++) {
        let msg = formatNewMessage(unseen[i]);
        let msgHash = hashTracker.md5(msg);
        if (!hashTracker.isSeen(msgHash)) {
          bot.telegram.sendMessage(chatid, msg, webmailLinkKeyboard);
          hashTracker.setSeen(msgHash);
        }
      }
    }
    winston.info('Done running cronjob for chat ID', chatid, '.');
  }

  // noinspection JSUnusedGlobalSymbols
  job = new CronJob({
    cronTime: '0 */15 * * * *',
    onTick: await doCronjob,
  });
  job.start();
  await doCronjob();
}

checkSecrets()
  .then(() => {
    const bot = new Telegraf(secrets.telegram_token);

    bot.use(commandParts());

    bot.command('start', (ctx) => {
      let isPasswordOk = (ctx.state.command.args || '') === secrets.telegram_password;
      winston.info(ctx.chat.id, ctx.from.username, '/start', isPasswordOk ? 'PASS OK' : 'PASS KO');
      ctx.reply(isPasswordOk ? '👍✅ ⇒ 🔛' : '👎🚫');
      if (isPasswordOk) {
        setCronjob(bot, ctx.chat.id);
      }
    });

    bot.command('stop', (ctx) => {
      let isPasswordOk = (ctx.state.command.args || '') === secrets.telegram_password;
      winston.info(ctx.chat.id, ctx.from.username, '/stop', isPasswordOk ? 'PASS OK' : 'PASS KO');
      ctx.reply(isPasswordOk ? '👍✅ ⇒ 📴' : '👎🚫');
      if (isPasswordOk) {
        cleanup(false);
      }
    });

    bot.command('ping', (ctx) => {
      winston.info(ctx.chat.id, ctx.from.username, '/ping');
      ctx.reply('pong!');
    });

    bot.startPolling();
  })
  .catch((e) => {
    winston.error(e);
  });

// Cleanups & Promises handling

function cleanup(exit) {
  if (job && job.running) job.stop();
  if (exit) process.exit();
}

process.on('exit', () => {
  cleanup(true);
});
process.on('SIGINT', () => {
  cleanup(true);
});
process.on('SIGUSR1', () => {
  cleanup(true);
});
process.on('SIGUSR2', () => {
  cleanup(true);
});
process.on('uncaughtException', () => {
  cleanup(true);
});

process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
});
<|endoftext|>


<commit_before>(function (root, factory) {
  if (typeof define === "function" && define.amd) {
    define(["rater-js"], factory);
  }else if (typeof module === "object" && module.exports) {
    module.exports = factory();
  }else {
    root.rater = factory();
  }
}(this, function() {

	return function rater(options) {

       if (typeof options.element === "undefined") {
		   throw new Error("element required");
	   }

		//private fields
		var stars = options.max || 5;
		var starWidth = 18;

		var rating;
		var my_rating;
		var elem = options.element;
		elem.classList.add("star-rating");
		var div = document.createElement("div");
		div.classList.add("star-value");
		elem.appendChild(div);
		div = document.createElement("div");
		div.classList.add("star-bg");
		elem.appendChild(div);
		elem.style.width = starWidth * stars + "px";
		var callback = options.rateCallback;
		var disabled =  !!options.readOnly;
		var block = false;
		var disableText;
		var isRating = false;

		if (!options.readOnly) {
			disableText = options.disableText || "Thank you for your vote!";
		}

		var ratingText = options.ratingText || "Set a rating of {rating}";

		//private methods
		function onMouseMove(e) {

			if (disabled === true || block === true || isRating) {
				return;
			}

			var xCoor = e.offsetX;
			var width = elem.offsetWidth;
			var percent = (xCoor/width) * 100;

			if (percent < 101) {
				my_rating = Math.ceil((percent / 100) * stars);
				elem.setAttribute("data-title", ratingText.replace("{rating}", my_rating));
				elem.querySelector(".star-value").style.width = my_rating/stars * 100 + "%";
			}
		}

		function onStarOut(e) {
			block = false;
			if (typeof rating != "undefined") {
				elem.querySelector(".star-value").style.width = rating/stars * 100 + "%";
				elem.setAttribute("data-rating", rating);
			}else {
				elem.querySelector(".star-value").style.width = "0%";
				elem.setAttribute("data-rating", undefined);
			}
		}

		function onStarClick(e) {
			if (disabled === true) {
				return;
			}

			if(isRating){
				return;
			}

			if(typeof callback !== "undefined" ){
				isRating = true;
				callback.call(this, my_rating, function() {
					isRating = false;
				});
			}

			block = true;
		}

		//public methods
		function disable() {
			disabled = true;
			elem.setAttribute("data-title", disableText);
		}

		function enable() {
			disabled = false;
			elem.setAttribute("data-title", undefined);
		}

		function setAvgRating(value) {
			rating = value;

			if (typeof value !== "undefined") {
				elem.querySelector(".star-value").style.width = value/stars * 100 + "%";
			} else {
				elem.querySelector(".star-value").style.width = "0px";
			}

			elem.setAttribute("data-rating", value);
		}

		function getAvgRating() {
			return rating;
		}

		function getMyRating() {
			return my_rating;
		}

		function setMyRating(rating) {
			my_rating = rating;
			elem.setAttribute("data-title", ratingText.replace("{rating}", my_rating));
			elem.querySelector(".star-value").style.width = my_rating/stars * 100 + "%";
		}

		function dispose() {
			if (!elem) {
				return;
			}

			elem.removeEventListener("mousemove", onMouseMove);
			elem.removeEventListener("mouseout", onStarOut);
			elem.removeEventListener("click", onStarClick);
		}

		setAvgRating(options.rating);
		elem.addEventListener("mousemove", onMouseMove);
		elem.addEventListener("mouseout", onStarOut);

		var module = {
			setAvgRating:setAvgRating,
			getAvgRating:getAvgRating,
			getMyRating:getMyRating,
			setMyRating:setMyRating,
			disable:disable,
			enable:enable,
			dispose:dispose
		};

		elem.addEventListener("click", onStarClick.bind(module));

		return module;
	}

})); <commit_msg>remove title while rating<commit_after>(function (root, factory) {
  if (typeof define === "function" && define.amd) {
    define(["rater-js"], factory);
  }else if (typeof module === "object" && module.exports) {
    module.exports = factory();
  }else {
    root.rater = factory();
  }
}(this, function() {

	return function rater(options) {

       if (typeof options.element === "undefined") {
		   throw new Error("element required");
	   }

		//private fields
		var stars = options.max || 5;
		var starWidth = 18;

		var rating;
		var my_rating;
		var elem = options.element;
		elem.classList.add("star-rating");
		var div = document.createElement("div");
		div.classList.add("star-value");
		elem.appendChild(div);
		div = document.createElement("div");
		div.classList.add("star-bg");
		elem.appendChild(div);
		elem.style.width = starWidth * stars + "px";
		var callback = options.rateCallback;
		var disabled =  !!options.readOnly;
		var block = false;
		var disableText;
		var isRating = false;
		var isBusyText = options.isBusyText;

		if (!options.readOnly) {
			disableText = options.disableText || "Thank you for your vote!";
		}

		var ratingText = options.ratingText || "Set a rating of {rating}";

		//private methods
		function onMouseMove(e) {

			if (disabled === true || block === true || isRating) {
				return;
			}

			var xCoor = e.offsetX;
			var width = elem.offsetWidth;
			var percent = (xCoor/width) * 100;

			if (percent < 101) {
				my_rating = Math.ceil((percent / 100) * stars);
				elem.setAttribute("data-title", ratingText.replace("{rating}", my_rating));
				elem.querySelector(".star-value").style.width = my_rating/stars * 100 + "%";
			}
		}

		function onStarOut(e) {
			block = false;
			if (typeof rating != "undefined") {
				elem.querySelector(".star-value").style.width = rating/stars * 100 + "%";
				elem.setAttribute("data-rating", rating);
			}else {
				elem.querySelector(".star-value").style.width = "0%";
				elem.setAttribute("data-rating", undefined);
			}
		}

		function onStarClick(e) {
			if (disabled === true) {
				return;
			}

			if(isRating){
				return;
			}

			if(typeof callback !== "undefined" ){
				isRating = true;
				if(typeof isBusyText === "undefined"){
					elem.removeAttribute("data-title");
				} else {
					elem.removeAttribute("data-title", isBusyText);
				}

				callback.call(this, my_rating, function() {
					isRating = false;
				});
			}

			block = true;
		}

		//public methods
		function disable() {
			disabled = true;
			elem.setAttribute("data-title", disableText);
		}

		function enable() {
			disabled = false;
			elem.setAttribute("data-title", undefined);
		}

		function setAvgRating(value) {
			rating = value;

			if (typeof value !== "undefined") {
				elem.querySelector(".star-value").style.width = value/stars * 100 + "%";
			} else {
				elem.querySelector(".star-value").style.width = "0px";
			}

			elem.setAttribute("data-rating", value);
		}

		function getAvgRating() {
			return rating;
		}

		function getMyRating() {
			return my_rating;
		}

		function setMyRating(rating) {
			my_rating = rating;
			elem.setAttribute("data-title", ratingText.replace("{rating}", my_rating));
			elem.querySelector(".star-value").style.width = my_rating/stars * 100 + "%";
		}

		function dispose() {
			if (!elem) {
				return;
			}

			elem.removeEventListener("mousemove", onMouseMove);
			elem.removeEventListener("mouseout", onStarOut);
			elem.removeEventListener("click", onStarClick);
		}

		setAvgRating(options.rating);
		elem.addEventListener("mousemove", onMouseMove);
		elem.addEventListener("mouseout", onStarOut);

		var module = {
			setAvgRating:setAvgRating,
			getAvgRating:getAvgRating,
			getMyRating:getMyRating,
			setMyRating:setMyRating,
			disable:disable,
			enable:enable,
			dispose:dispose
		};

		elem.addEventListener("click", onStarClick.bind(module));

		return module;
	}

})); <|endoftext|>


<commit_before>var Trigger = require('level-trigger')
var range   = require('./range')
var next
if(typeof setImmediate == 'undefined')
  next = process.nextTick
else
  next = setImmediate

next = setTimeout

module.exports = function (db, mapDb, map, reduce, initial) {
  if('string' === typeof mapDb) mapDb = db.sublevel(mapDb)

  //store the keys a value has been mapped to.
  var mapper = mapDb.sublevel('mapped')

  if(!map)
    throw new Error('expected a map function')

  //when record is inserted, pull out what it was mapped to last time.
  var maps = Trigger(db, 'maps', function (id, done) {
    mapper.get(id, function (err, oldKeys) {
      oldKeys = oldKeys ? JSON.parse(oldKeys) : []
      var newKeys = []

      db.get(id, function (err, value) {
        var batch = [], async = false

        //don't map if it's delete, just delete the old maps
        if(value != null)
          map(id, value, function (key, value) {
            var array = 'string' === typeof key ? [key] : key || []
            if(true == async) return console.error('map must not emit async')
            if(value == null || key == null) return
            array.push(id)
            batch.push({key: range.stringify(array), value: value, type: 'put'})
            newKeys.push(range.stringify(array))
          })

        async = true

        oldKeys.forEach(function (k) {
          if(!~newKeys.indexOf(k)) batch.push({key: k, type: 'del'})
        })

        batch.push({
          key: id,
          value: JSON.stringify(newKeys),
          type: 'put',
          prefix: mapper
        })

        mapDb.batch(batch, done)
      })
    })
  })

  var reduces

  if(reduce)
    reduces = Trigger(mapDb, 'reduces', function (ch) {
      var a = range.parse(ch.key);
      if(!a.length) return
      a.pop()
      return JSON.stringify(a)
    },
    function (a, done) {
      var array = JSON.parse(a)
      var acc = initial
      mapDb.createReadStream(range.range(array.concat(true)))
        .on('data', function (e) {
          try {
            acc = reduce(acc, e.value)
          } catch (err) {
          console.error(err); return done(err); this.destroy() }
        })
        .on('end', function () {
          var batch
          mapDb.batch([batch = {
            key  : range.stringify(array),
            value: ''+acc,
            type : acc == null ? 'del' : 'put'
          }], function (err) {
            if(err) return done(err)

            mapDb.emit('reduce', array, acc)
            done()
          })
        })
    })

  mapDb.start = function () {
    maps.start()
    reduces && reduces.start()
    return mapDb
  }

  //patch streams so that they can handle

  var createReadStream = mapDb.createReadStream

  mapDb.createReadStream = function (opts) {
    opts = opts || {}
    if(opts.range) {
      var r = range.range(opts.range)
      opts.start = opts.min = r.min
      opts.end = opts.max  = r.max
    }
    return createReadStream.call(this, opts)
  }

  mapDb.createViewStream = function(opts) {
    var stream = this.createReadStream(opts)
    stream.on('data', function(d) {
      stream.emit('row', {
        key: range.parse(d.key),
        value: d.value
      })
    })
    return stream
  }

  var oldGet = mapDb.get

  mapDb.get = function(key){
    if(Array.isArray(key)) key = range.stringify(key)
    return oldGet.apply(this, arguments)
  }

  return mapDb
}
<commit_msg>mutate key instead of emitting new event<commit_after>var Trigger = require('level-trigger')
var range   = require('./range')
var next
if(typeof setImmediate == 'undefined')
  next = process.nextTick
else
  next = setImmediate

next = setTimeout

module.exports = function (db, mapDb, map, reduce, initial) {
  if('string' === typeof mapDb) mapDb = db.sublevel(mapDb)

  //store the keys a value has been mapped to.
  var mapper = mapDb.sublevel('mapped')

  if(!map)
    throw new Error('expected a map function')

  //when record is inserted, pull out what it was mapped to last time.
  var maps = Trigger(db, 'maps', function (id, done) {
    mapper.get(id, function (err, oldKeys) {
      oldKeys = oldKeys ? JSON.parse(oldKeys) : []
      var newKeys = []

      db.get(id, function (err, value) {
        var batch = [], async = false

        //don't map if it's delete, just delete the old maps
        if(value != null)
          map(id, value, function (key, value) {
            var array = 'string' === typeof key ? [key] : key || []
            if(true == async) return console.error('map must not emit async')
            if(value == null || key == null) return
            array.push(id)
            batch.push({key: range.stringify(array), value: value, type: 'put'})
            newKeys.push(range.stringify(array))
          })

        async = true

        oldKeys.forEach(function (k) {
          if(!~newKeys.indexOf(k)) batch.push({key: k, type: 'del'})
        })

        batch.push({
          key: id,
          value: JSON.stringify(newKeys),
          type: 'put',
          prefix: mapper
        })

        mapDb.batch(batch, done)
      })
    })
  })

  var reduces

  if(reduce)
    reduces = Trigger(mapDb, 'reduces', function (ch) {
      var a = range.parse(ch.key);
      if(!a.length) return
      a.pop()
      return JSON.stringify(a)
    },
    function (a, done) {
      var array = JSON.parse(a)
      var acc = initial
      mapDb.createReadStream(range.range(array.concat(true)))
        .on('data', function (e) {
          try {
            acc = reduce(acc, e.value)
          } catch (err) {
          console.error(err); return done(err); this.destroy() }
        })
        .on('end', function () {
          var batch
          mapDb.batch([batch = {
            key  : range.stringify(array),
            value: ''+acc,
            type : acc == null ? 'del' : 'put'
          }], function (err) {
            if(err) return done(err)

            mapDb.emit('reduce', array, acc)
            done()
          })
        })
    })

  mapDb.start = function () {
    maps.start()
    reduces && reduces.start()
    return mapDb
  }

  //patch streams so that they can handle

  var createReadStream = mapDb.createReadStream

  mapDb.createReadStream = function (opts) {
    opts = opts || {}
    if(opts.range) {
      var r = range.range(opts.range)
      opts.start = opts.min = r.min
      opts.end = opts.max  = r.max
    }
    return createReadStream.call(this, opts)
  }

  mapDb.createViewStream = function(opts) {
    var stream = this.createReadStream(opts)
    stream.on('data', function(d) {
      d.key = range.parse(d.key)
    })
    return stream
  }

  var oldGet = mapDb.get

  mapDb.get = function(key){
    if(Array.isArray(key)) key = range.stringify(key)
    return oldGet.apply(this, arguments)
  }

  return mapDb
}
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import { Dimensions, Text, StyleSheet } from 'react-native';

const flattenStyle = StyleSheet.flatten;

const ScalableText = ({ style, children, ...props }) => {
  const fontSize = flattenStyle(style).fontSize || 14;
  const { width } = Dimensions.get('window');
  const scaledFontSize = Math.round(fontSize * width / 375);

  return (
    <Text style={[style, { fontSize: scaledFontSize }]} {...props}>
      {children}
    </Text>
  );
};

ScalableText.propTypes = {
  style: Text.propTypes.style,
  children: PropTypes.node.isRequired
};

export default ScalableText;
<commit_msg>Added default props for style. Empty style raised error before<commit_after>import React, { PropTypes } from 'react';
import { Dimensions, Text, StyleSheet } from 'react-native';

const flattenStyle = StyleSheet.flatten;

const ScalableText = ({ style, children, ...props }) => {
  const fontSize = flattenStyle(style).fontSize || 14;
  const { width } = Dimensions.get('window');
  const scaledFontSize = Math.round(fontSize * width / 375);

  return (
    <Text style={[style, { fontSize: scaledFontSize }]} {...props}>
      {children}
    </Text>
  );
};

ScalableText.propTypes = {
  style: Text.propTypes.style,
  children: PropTypes.node.isRequired
};

ScalableText.defaultProps = {
  style: {}
};

export default ScalableText;
<|endoftext|>


<commit_before>'use strict';

function MonoFlanger(context, config) {
    var feedbackGain = config.feedback || 0.5,
        delayTime = config.delay || 0.005,
        lfoGain = config.gain || 0.002,
        lfoFreq = config.frequency || 0.25;

    var input = context.createGain();
    var delay = context.createDelay();
    var feedback = context.createGain();
    var lfo = context.createOscillator();
    var gain = context.createGain();
    var output = context.createGain();

    delay.delayTime.value = delayTime; // 5-25ms delay (0.005 > 0.025)
    feedback.gain.value = feedbackGain; // 0 > 1

    lfo.type = 'sine';
    lfo.frequency.value = lfoFreq; // 0.05 > 5
    gain.gain.value = lfoGain; // 0.0005 > 0.005

    input.connect(output);
    input.connect(delay);
    delay.connect(output);
    delay.connect(feedback);
    feedback.connect(input);

    lfo.connect(gain);
    gain.connect(delay.delayTime);
    lfo.start(0);

    var node = input;
    node.name = 'Flanger';
    node._output = output;

    Object.defineProperties(node, {
        delay: {
            get: function() { return delay.delayTime.value; },
            set: function(value) { delay.delayTime.value = value; }
        },
        lfoFrequency: {
            get: function() { return lfo.frequency.value; },
            set: function(value) { lfo.frequency.value = value; }
        },
        lfoGain: {
            get: function() { return gain.gain.value; },
            set: function(value) { gain.gain.value = value; }
        },
        feedback: {
            get: function() { return feedback.gain.value; },
            set: function(value) { feedback.gain.value = value; }
        }
    });

    return node;
}

function StereoFlanger(context, config) {
    var feedbackGain = config.feedback || 0.5,
        delayTime = config.delay || 0.003,
        lfoGain = config.gain || 0.005,
        lfoFreq = config.frequency || 0.5;

    var input = context.createGain();
    var splitter = context.createChannelSplitter(2);
    var merger = context.createChannelMerger(2);
    var feedbackL = context.createGain();
    var feedbackR = context.createGain();
    var lfo = context.createOscillator();
    var lfoGainL = context.createGain();
    var lfoGainR = context.createGain();
    var delayL = context.createDelay();
    var delayR = context.createDelay();
    var output = context.createGain();

    feedbackL.gain.value = feedbackR.gain.value = feedbackGain;
    delayL.delayTime.value = delayR.delayTime.value = delayTime;

    lfo.type = 'sine';
    lfo.frequency.value = lfoFreq;
    lfoGainL.gain.value = lfoGain;
    lfoGainR.gain.value = 0 - lfoGain;

    input.connect(splitter);

    splitter.connect(delayL, 0);
    splitter.connect(delayR, 1);

    delayL.connect(feedbackL);
    delayR.connect(feedbackR);

    feedbackL.connect(delayR);
    feedbackR.connect(delayL);

    delayL.connect(merger, 0, 0);
    delayR.connect(merger, 0, 1);

    merger.connect(output);
    input.connect(output);

    lfo.connect(lfoGainL);
    lfo.connect(lfoGainR);
    lfoGainL.connect(delayL.delayTime);
    lfoGainR.connect(delayR.delayTime);
    lfo.start();

    var node = input;
    node.name = 'StereoFlanger';
    node._output = output;

    Object.defineProperties(node, {
        delay: {
            get: function() { return delayL.delayTime.value; },
            set: function(value) { delayL.delayTime.value = delayR.delayTime.value = value; }
        },
        lfoFrequency: {
            get: function() { return lfo.frequency.value; },
            set: function(value) { lfo.frequency.value = value; }
        },
        lfoGain: {
            get: function() { return lfoGainL.gain.value; },
            set: function(value) { lfoGainL.gain.value = lfoGainR.gain.value = value; }
        },
        feedback: {
            get: function() { return feedbackL.gain.value; },
            set: function(value) { feedbackL.gain.value = feedbackR.gain.value = value; }
        }
    });

    return node;
}

function Flanger(context, config) {
    config = config || {};
    return config.stereo ? new StereoFlanger(context, config) : new MonoFlanger(context, config);
}

module.exports = Flanger;
<commit_msg>fix flanger lfo start for safari<commit_after>'use strict';

function MonoFlanger(context, config) {
    var feedbackGain = config.feedback || 0.5,
        delayTime = config.delay || 0.005,
        lfoGain = config.gain || 0.002,
        lfoFreq = config.frequency || 0.25;

    var input = context.createGain();
    var delay = context.createDelay();
    var feedback = context.createGain();
    var lfo = context.createOscillator();
    var gain = context.createGain();
    var output = context.createGain();

    delay.delayTime.value = delayTime; // 5-25ms delay (0.005 > 0.025)
    feedback.gain.value = feedbackGain; // 0 > 1

    lfo.type = 'sine';
    lfo.frequency.value = lfoFreq; // 0.05 > 5
    gain.gain.value = lfoGain; // 0.0005 > 0.005

    input.connect(output);
    input.connect(delay);
    delay.connect(output);
    delay.connect(feedback);
    feedback.connect(input);

    lfo.connect(gain);
    gain.connect(delay.delayTime);
    lfo.start(0);

    var node = input;
    node.name = 'Flanger';
    node._output = output;

    Object.defineProperties(node, {
        delay: {
            get: function() { return delay.delayTime.value; },
            set: function(value) { delay.delayTime.value = value; }
        },
        lfoFrequency: {
            get: function() { return lfo.frequency.value; },
            set: function(value) { lfo.frequency.value = value; }
        },
        lfoGain: {
            get: function() { return gain.gain.value; },
            set: function(value) { gain.gain.value = value; }
        },
        feedback: {
            get: function() { return feedback.gain.value; },
            set: function(value) { feedback.gain.value = value; }
        }
    });

    return node;
}

function StereoFlanger(context, config) {
    var feedbackGain = config.feedback || 0.5,
        delayTime = config.delay || 0.003,
        lfoGain = config.gain || 0.005,
        lfoFreq = config.frequency || 0.5;

    var input = context.createGain();
    var splitter = context.createChannelSplitter(2);
    var merger = context.createChannelMerger(2);
    var feedbackL = context.createGain();
    var feedbackR = context.createGain();
    var lfo = context.createOscillator();
    var lfoGainL = context.createGain();
    var lfoGainR = context.createGain();
    var delayL = context.createDelay();
    var delayR = context.createDelay();
    var output = context.createGain();

    feedbackL.gain.value = feedbackR.gain.value = feedbackGain;
    delayL.delayTime.value = delayR.delayTime.value = delayTime;

    lfo.type = 'sine';
    lfo.frequency.value = lfoFreq;
    lfoGainL.gain.value = lfoGain;
    lfoGainR.gain.value = 0 - lfoGain;

    input.connect(splitter);

    splitter.connect(delayL, 0);
    splitter.connect(delayR, 1);

    delayL.connect(feedbackL);
    delayR.connect(feedbackR);

    feedbackL.connect(delayR);
    feedbackR.connect(delayL);

    delayL.connect(merger, 0, 0);
    delayR.connect(merger, 0, 1);

    merger.connect(output);
    input.connect(output);

    lfo.connect(lfoGainL);
    lfo.connect(lfoGainR);
    lfoGainL.connect(delayL.delayTime);
    lfoGainR.connect(delayR.delayTime);
    lfo.start(0);

    var node = input;
    node.name = 'StereoFlanger';
    node._output = output;

    Object.defineProperties(node, {
        delay: {
            get: function() { return delayL.delayTime.value; },
            set: function(value) { delayL.delayTime.value = delayR.delayTime.value = value; }
        },
        lfoFrequency: {
            get: function() { return lfo.frequency.value; },
            set: function(value) { lfo.frequency.value = value; }
        },
        lfoGain: {
            get: function() { return lfoGainL.gain.value; },
            set: function(value) { lfoGainL.gain.value = lfoGainR.gain.value = value; }
        },
        feedback: {
            get: function() { return feedbackL.gain.value; },
            set: function(value) { feedbackL.gain.value = feedbackR.gain.value = value; }
        }
    });

    return node;
}

function Flanger(context, config) {
    config = config || {};
    return config.stereo ? new StereoFlanger(context, config) : new MonoFlanger(context, config);
}

module.exports = Flanger;
<|endoftext|>


<commit_before>'use strict';

module.exports = require('./lib/model/model');<commit_msg>also need to update path in index file<commit_after>'use strict';

module.exports = require('./lib/thermal/model');<|endoftext|>


<commit_before>var fs = require('fs');
var _ = require('lodash');
var Mustache = require('mustache');
var schema = require('resume-schema');

var d = new Date();
var curyear = d.getFullYear();

var resumeObject = schema.resumeJson;

function render(resumeObject) {

resumeObject.basics.capitalName = (resumeObject.basics.name).toUpperCase();
resumeObject.basics.capitalLabel = (resumeObject.basics.label).toUpperCase();

	if (resumeObject.basics.email) {
		resumeObject.emailBool = true;
	}

	if (resumeObject.basics.phone) {
		resumeObject.phoneBool = true;
	}

	if (resumeObject.basics.website) {
		resumeObject.websiteBool = true;
	}

	if (resumeObject.basics.summary) {
		resumeObject.aboutBool = true;
	}

	if (resumeObject.basics.profiles) {
		if (resumeObject.basics.profiles[0].network) {
			_.each(resumeObject.basics.profiles, function(w){
				if ((w.network == 'Twitter' || w.network == 'twitter') && w.url == '' && w.username != '') {
					w.url = "https://twitter.com/" + w.username;
				}
				if ((w.network == 'facebook' || w.network == 'Facebook' || w.network == 'FaceBook') && w.url == '' && w.username != '') {
					w.url = "https://facebook.com/" + w.username;
				}
				if ((w.network == 'Linkedin' || w.network == 'linkedin' || w.network == 'LinkedIn') && w.url == '' && w.username != '') {
					w.url = "https://linkedin.com/in/" + w.username;
				}
			});
		}
	}

	if (resumeObject.work) {
		if (resumeObject.work[0].company) {
			resumeObject.workBool = true;
			_.each(resumeObject.work, function(w){
				if (w.startDate) {
					w.startDateYear = (w.startDate || "").substr(0,4);
					switch (w.startDate.substr(5,2)) {
						case '01':
							w.startDateMonth = "January ";
							break;
						case '02':
							w.startDateMonth = "February ";
							break;
						case '03':
							w.startDateMonth = "March ";
							break;
						case '04':
							w.startDateMonth = "April ";
							break;
						case '05':
							w.startDateMonth = "May ";
							break;
						case '06':
							w.startDateMonth = "June ";
							break;
						case '07':
							w.startDateMonth = "July ";
							break;
						case '08':
							w.startDateMonth = "August ";
							break;
						case '09':
							w.startDateMonth = "September ";
							break;
						case '10':
							w.startDateMonth = "October ";
							break;
						case '11':
							w.startDateMonth = "November ";
							break;
						case '12':
							w.startDateMonth = "December ";
							break;
						}
				}
				if(w.endDate) {
					w.endDateYear = (w.endDate || "").substr(0,4);
					switch ((w.endDate || "").substr(5,2)) {
						case '01':
							w.endDateMonth = "January ";
							break;
						case '02':
							w.endDateMonth = "February ";
							break;
						case '03':
							w.endDateMonth = "March ";
							break;
						case '04':
							w.endDateMonth = "April ";
							break;
						case '05':
							w.endDateMonth = "May ";
							break;
						case '06':
							w.endDateMonth = "June ";
							break;
						case '07':
							w.endDateMonth = "July ";
							break;
						case '08':
							w.endDateMonth = "August ";
							break;
						case '09':
							w.endDateMonth = "September ";
							break;
						case '10':
							w.endDateMonth = "October ";
							break;
						case '11':
							w.endDateMonth = "November ";
							break;
						case '12':
							w.endDateMonth = "December ";
							break;
						}
				} else {
					w.endDateYear = 'Present'
				}
				if (w.highlights) {
					if (w.highlights[0]) {
						if (w.highlights[0] != "") {
							w.workHighlights = true;
						}
					}
				}
			});
		}
	}

	if (resumeObject.education) {
		if (resumeObject.education[0].institution) {
			resumeObject.educationBool = true;
			_.each(resumeObject.education, function(e){
			    if( !e.area || !e.studyType ){
			      e.educationDetail = (e.area == null ? '' : e.area) + (e.studyType == null ? '' : e.studyType);
			    } else {
			      e.educationDetail = e.area + ", "+ e.studyType;
			    }
				if (e.startDate) {
					e.startDateYear = e.startDate.substr(0,4);
					switch (e.startDate.substr(5,2)) {
						case '01':
							e.startDateMonth = "January ";
							break;
						case '02':
							e.startDateMonth = "February ";
							break;
						case '03':
							e.startDateMonth = "March ";
							break;
						case '04':
							e.startDateMonth = "April ";
							break;
						case '05':
							e.startDateMonth = "May ";
							break;
						case '06':
							e.startDateMonth = "June ";
							break;
						case '07':
							e.startDateMonth = "July ";
							break;
						case '08':
							e.startDateMonth = "August ";
							break;
						case '09':
							e.startDateMonth = "September ";
							break;
						case '10':
							e.startDateMonth = "October ";
							break;
						case '11':
							e.startDateMonth = "November ";
							break;
						case '12':
							e.startDateMonth = "December ";
							break;
					}
				} else {
					e.endDateMonth = "";
				}
				if (e.endDate) {
					e.endDateYear = e.endDate.substr(0,4);
					switch (e.endDate.substr(5,2)) {
						case '01':
							e.endDateMonth = "January ";
							break;
						case '02':
							e.endDateMonth = "February ";
							break;
						case '03':
							e.endDateMonth = "March ";
							break;
						case '04':
							e.endDateMonth = "April ";
							break;
						case '05':
							e.endDateMonth = "May ";
							break;
						case '06':
							e.endDateMonth = "June ";
							break;
						case '07':
							e.endDateMonth = "July ";
							break;
						case '08':
							e.endDateMonth = "August ";
							break;
						case '09':
							e.endDateMonth = "September ";
							break;
						case '10':
							e.endDateMonth = "October ";
							break;
						case '11':
							e.endDateMonth = "November ";
							break;
						case '12':
							e.endDateMonth = "December ";
							break;
					}
					if (e.endDateYear > curyear) {
						e.endDateYear += " (expected)";
					}
				} else {
					e.endDateYear = 'Present'
					e.endDateMonth = '';
				}
				if (e.courses) {
					if (e.courses[0]) {
						if (e.courses[0] != "") {
							e.educationCourses = true;
						}
					}
				}
			});
		}
	}

	if (resumeObject.awards) {
		if (resumeObject.awards[0].title) {
			resumeObject.awardsBool = true;
			_.each(resumeObject.awards, function(a){
				a.year = (a.date || "").substr(0,4);
				a.day = (a.date || "").substr(8,2);
				switch ((a.date || "").substr(5,2)) {
					case '01':
						a.month = "January";
						break;
					case '02':
						a.month = "February";
						break;
					case '03':
						a.month = "March";
						break;
					case '04':
						a.month = "April";
						break;
					case '05':
						a.month = "May";
						break;
					case '06':
						a.month = "June";
						break;
					case '07':
						a.month = "July";
						break;
					case '08':
						a.month = "August";
						break;
					case '09':
						a.month = "September";
						break;
					case '10':
						a.month = "October";
						break;
					case '11':
						a.month = "November";
						break;
					case '12':
						a.month = "December";
						break;
				}
			});
		}
	}

	if (resumeObject.publications) {
		if (resumeObject.publications[0].name) {
			resumeObject.publicationsBool = true;
			_.each(resumeObject.publications, function(a){
				a.year = (a.releaseDate || "").substr(0,4);
				a.day = (a.releaseDate || "").substr(8,2);
				switch ((a.releaseDate || "").substr(5,2)) {
					case '01':
						a.month = "January";
						break;
					case '02':
						a.month = "February";
						break;
					case '03':
						a.month = "March";
						break;
					case '04':
						a.month = "April";
						break;
					case '05':
						a.month = "May";
						break;
					case '06':
						a.month = "June";
						break;
					case '07':
						a.month = "July";
						break;
					case '08':
						a.month = "August";
						break;
					case '09':
						a.month = "September";
						break;
					case '10':
						a.month = "October";
						break;
					case '11':
						a.month = "November";
						break;
					case '12':
						a.month = "December";
						break;
				}
			});
		}
	}

	if (resumeObject.skills) {
		if (resumeObject.skills[0].name) {
			resumeObject.skillsBool = true;
		}
	}

	if (resumeObject.interests) {
		if (resumeObject.interests[0].name) {
			resumeObject.interestsBool = true;
		}
	}

	if (resumeObject.languages) {
		if (resumeObject.languages[0].language) {
			resumeObject.languagesBool = true;
		}
	}

	if (resumeObject.references) {
		if (resumeObject.references[0].name) {
			resumeObject.referencesBool = true;
		}
	}

	var theme = fs.readFileSync(__dirname + '/resume.template', 'utf8');
	var resumeHTML = Mustache.render(theme, resumeObject);

	return resumeHTML;
};
module.exports = {
	render: render
}<commit_msg>Sanity check, do not assume object in 0-th array index, fixes exception for empty array entries.<commit_after>var fs = require('fs');
var _ = require('lodash');
var Mustache = require('mustache');
var schema = require('resume-schema');

var d = new Date();
var curyear = d.getFullYear();

var resumeObject = schema.resumeJson;

function render(resumeObject) {

resumeObject.basics.capitalName = (resumeObject.basics.name).toUpperCase();
resumeObject.basics.capitalLabel = (resumeObject.basics.label).toUpperCase();

	if (resumeObject.basics.email) {
		resumeObject.emailBool = true;
	}

	if (resumeObject.basics.phone) {
		resumeObject.phoneBool = true;
	}

	if (resumeObject.basics.website) {
		resumeObject.websiteBool = true;
	}

	if (resumeObject.basics.summary) {
		resumeObject.aboutBool = true;
	}

	if (resumeObject.basics.profiles) {
		if (resumeObject.basics.profiles[0] && resumeObject.basics.profiles[0].network) {
			_.each(resumeObject.basics.profiles, function(w){
				if ((w.network == 'Twitter' || w.network == 'twitter') && w.url == '' && w.username != '') {
					w.url = "https://twitter.com/" + w.username;
				}
				if ((w.network == 'facebook' || w.network == 'Facebook' || w.network == 'FaceBook') && w.url == '' && w.username != '') {
					w.url = "https://facebook.com/" + w.username;
				}
				if ((w.network == 'Linkedin' || w.network == 'linkedin' || w.network == 'LinkedIn') && w.url == '' && w.username != '') {
					w.url = "https://linkedin.com/in/" + w.username;
				}
			});
		}
	}

	if (resumeObject.work) {
		if (resumeObject.work[0] && resumeObject.work[0].company) {
			resumeObject.workBool = true;
			_.each(resumeObject.work, function(w){
				if (w.startDate) {
					w.startDateYear = (w.startDate || "").substr(0,4);
					switch (w.startDate.substr(5,2)) {
						case '01':
							w.startDateMonth = "January ";
							break;
						case '02':
							w.startDateMonth = "February ";
							break;
						case '03':
							w.startDateMonth = "March ";
							break;
						case '04':
							w.startDateMonth = "April ";
							break;
						case '05':
							w.startDateMonth = "May ";
							break;
						case '06':
							w.startDateMonth = "June ";
							break;
						case '07':
							w.startDateMonth = "July ";
							break;
						case '08':
							w.startDateMonth = "August ";
							break;
						case '09':
							w.startDateMonth = "September ";
							break;
						case '10':
							w.startDateMonth = "October ";
							break;
						case '11':
							w.startDateMonth = "November ";
							break;
						case '12':
							w.startDateMonth = "December ";
							break;
						}
				}
				if(w.endDate) {
					w.endDateYear = (w.endDate || "").substr(0,4);
					switch ((w.endDate || "").substr(5,2)) {
						case '01':
							w.endDateMonth = "January ";
							break;
						case '02':
							w.endDateMonth = "February ";
							break;
						case '03':
							w.endDateMonth = "March ";
							break;
						case '04':
							w.endDateMonth = "April ";
							break;
						case '05':
							w.endDateMonth = "May ";
							break;
						case '06':
							w.endDateMonth = "June ";
							break;
						case '07':
							w.endDateMonth = "July ";
							break;
						case '08':
							w.endDateMonth = "August ";
							break;
						case '09':
							w.endDateMonth = "September ";
							break;
						case '10':
							w.endDateMonth = "October ";
							break;
						case '11':
							w.endDateMonth = "November ";
							break;
						case '12':
							w.endDateMonth = "December ";
							break;
						}
				} else {
					w.endDateYear = 'Present'
				}
				if (w.highlights) {
					if (w.highlights[0]) {
						if (w.highlights[0] != "") {
							w.workHighlights = true;
						}
					}
				}
			});
		}
	}

	if (resumeObject.education) {
		if (resumeObject.education[0] && resumeObject.education[0].institution) {
			resumeObject.educationBool = true;
			_.each(resumeObject.education, function(e){
			    if( !e.area || !e.studyType ){
			      e.educationDetail = (e.area == null ? '' : e.area) + (e.studyType == null ? '' : e.studyType);
			    } else {
			      e.educationDetail = e.area + ", "+ e.studyType;
			    }
				if (e.startDate) {
					e.startDateYear = e.startDate.substr(0,4);
					switch (e.startDate.substr(5,2)) {
						case '01':
							e.startDateMonth = "January ";
							break;
						case '02':
							e.startDateMonth = "February ";
							break;
						case '03':
							e.startDateMonth = "March ";
							break;
						case '04':
							e.startDateMonth = "April ";
							break;
						case '05':
							e.startDateMonth = "May ";
							break;
						case '06':
							e.startDateMonth = "June ";
							break;
						case '07':
							e.startDateMonth = "July ";
							break;
						case '08':
							e.startDateMonth = "August ";
							break;
						case '09':
							e.startDateMonth = "September ";
							break;
						case '10':
							e.startDateMonth = "October ";
							break;
						case '11':
							e.startDateMonth = "November ";
							break;
						case '12':
							e.startDateMonth = "December ";
							break;
					}
				} else {
					e.endDateMonth = "";
				}
				if (e.endDate) {
					e.endDateYear = e.endDate.substr(0,4);
					switch (e.endDate.substr(5,2)) {
						case '01':
							e.endDateMonth = "January ";
							break;
						case '02':
							e.endDateMonth = "February ";
							break;
						case '03':
							e.endDateMonth = "March ";
							break;
						case '04':
							e.endDateMonth = "April ";
							break;
						case '05':
							e.endDateMonth = "May ";
							break;
						case '06':
							e.endDateMonth = "June ";
							break;
						case '07':
							e.endDateMonth = "July ";
							break;
						case '08':
							e.endDateMonth = "August ";
							break;
						case '09':
							e.endDateMonth = "September ";
							break;
						case '10':
							e.endDateMonth = "October ";
							break;
						case '11':
							e.endDateMonth = "November ";
							break;
						case '12':
							e.endDateMonth = "December ";
							break;
					}
					if (e.endDateYear > curyear) {
						e.endDateYear += " (expected)";
					}
				} else {
					e.endDateYear = 'Present'
					e.endDateMonth = '';
				}
				if (e.courses) {
					if (e.courses[0]) {
						if (e.courses[0] != "") {
							e.educationCourses = true;
						}
					}
				}
			});
		}
	}

	if (resumeObject.awards) {
		if (resumeObject.awards[0] && resumeObject.awards[0].title) {
			resumeObject.awardsBool = true;
			_.each(resumeObject.awards, function(a){
				a.year = (a.date || "").substr(0,4);
				a.day = (a.date || "").substr(8,2);
				switch ((a.date || "").substr(5,2)) {
					case '01':
						a.month = "January";
						break;
					case '02':
						a.month = "February";
						break;
					case '03':
						a.month = "March";
						break;
					case '04':
						a.month = "April";
						break;
					case '05':
						a.month = "May";
						break;
					case '06':
						a.month = "June";
						break;
					case '07':
						a.month = "July";
						break;
					case '08':
						a.month = "August";
						break;
					case '09':
						a.month = "September";
						break;
					case '10':
						a.month = "October";
						break;
					case '11':
						a.month = "November";
						break;
					case '12':
						a.month = "December";
						break;
				}
			});
		}
	}

	if (resumeObject.publications) {
		if (resumeObject.publications[0] && resumeObject.publications[0].name) {
			resumeObject.publicationsBool = true;
			_.each(resumeObject.publications, function(a){
				a.year = (a.releaseDate || "").substr(0,4);
				a.day = (a.releaseDate || "").substr(8,2);
				switch ((a.releaseDate || "").substr(5,2)) {
					case '01':
						a.month = "January";
						break;
					case '02':
						a.month = "February";
						break;
					case '03':
						a.month = "March";
						break;
					case '04':
						a.month = "April";
						break;
					case '05':
						a.month = "May";
						break;
					case '06':
						a.month = "June";
						break;
					case '07':
						a.month = "July";
						break;
					case '08':
						a.month = "August";
						break;
					case '09':
						a.month = "September";
						break;
					case '10':
						a.month = "October";
						break;
					case '11':
						a.month = "November";
						break;
					case '12':
						a.month = "December";
						break;
				}
			});
		}
	}

	if (resumeObject.skills) {
		if (resumeObject.skills[0] && resumeObject.skills[0].name) {
			resumeObject.skillsBool = true;
		}
	}

	if (resumeObject.interests) {
		if (resumeObject.interests[0] && resumeObject.interests[0].name) {
			resumeObject.interestsBool = true;
		}
	}

	if (resumeObject.languages) {
		if (resumeObject.languages[0] && resumeObject.languages[0].language) {
			resumeObject.languagesBool = true;
		}
	}

	if (resumeObject.references) {
		if (resumeObject.references[0] && resumeObject.references[0].name) {
			resumeObject.referencesBool = true;
		}
	}

	var theme = fs.readFileSync(__dirname + '/resume.template', 'utf8');
	var resumeHTML = Mustache.render(theme, resumeObject);

	return resumeHTML;
};
module.exports = {
	render: render
}<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter
var next         = process.nextTick
var SubDb        = require('./sub')
var fixRange     = require('level-fix-range')

var Hooks   = require('level-hooks')

module.exports   = function (db, options) {
  if (db.sublevel) return db

  options = options || {}

  //use \xff (255) as the seperator,
  //so that sections of the database will sort after the regular keys
  var sep = options.sep = options.sep || '\xff'
  db._options = options

  Hooks(db)

  db.sublevels = {}

  db.sublevel = function (prefix, options) {
    if(db.sublevels[prefix])
      return db.sublevels[prefix]
    return new SubDb(db, prefix, options || this._options)
  }

  db.methods = {}

  db.prefix = function (key) {
    return '' + (key || '')
  }

  db.pre = function (range, hook) {
    if(!hook)
      hook = range, range = {
        max  : sep
      }
    return db.hooks.pre(range, hook)
  }

  db.post = function (range, hook) {
    if(!hook)
      hook = range, range = {
        max : sep
      }
    return db.hooks.post(range, hook)
  }

  function safeRange(fun) {
    return function (opts) {
      opts = opts || {}
      fixRange(opts)

      if(opts.reverse) opts.start = opts.start || sep
      else             opts.end   = opts.end || sep

      return fun.call(db, opts)
    }
  }

  db.readStream =
  db.createReadStream  = safeRange(db.createReadStream)
  db.keyStream =
  db.createKeyStream   = safeRange(db.createKeyStream)
  db.valuesStream =
  db.createValueStream = safeRange(db.createValueStream)

  var batch = db.batch
  db.batch = function (changes, opts, cb) {
    if(!Array.isArray(changes))
      throw new Error('batch must be passed an Array')
    changes.forEach(function (e) {
      if(e.prefix) {
        if('function' === typeof e.prefix.prefix)
          e.key = e.prefix.prefix(e.key)
        else if('string'  === typeof e.prefix)
          e.key = e.prefix + e.key
      }
    })
    batch.call(db, changes, opts, cb)
  }
  return db
}

<commit_msg>Don't rely on fixRange's side effects, fixes #21<commit_after>var EventEmitter = require('events').EventEmitter
var next         = process.nextTick
var SubDb        = require('./sub')
var fixRange     = require('level-fix-range')

var Hooks   = require('level-hooks')

module.exports   = function (db, options) {
  if (db.sublevel) return db

  options = options || {}

  //use \xff (255) as the seperator,
  //so that sections of the database will sort after the regular keys
  var sep = options.sep = options.sep || '\xff'
  db._options = options

  Hooks(db)

  db.sublevels = {}

  db.sublevel = function (prefix, options) {
    if(db.sublevels[prefix])
      return db.sublevels[prefix]
    return new SubDb(db, prefix, options || this._options)
  }

  db.methods = {}

  db.prefix = function (key) {
    return '' + (key || '')
  }

  db.pre = function (range, hook) {
    if(!hook)
      hook = range, range = {
        max  : sep
      }
    return db.hooks.pre(range, hook)
  }

  db.post = function (range, hook) {
    if(!hook)
      hook = range, range = {
        max : sep
      }
    return db.hooks.post(range, hook)
  }

  function safeRange(fun) {
    return function (opts) {
      opts = opts || {}
      opts = fixRange(opts)

      if(opts.reverse) opts.start = opts.start || sep
      else             opts.end   = opts.end || sep

      return fun.call(db, opts)
    }
  }

  db.readStream =
  db.createReadStream  = safeRange(db.createReadStream)
  db.keyStream =
  db.createKeyStream   = safeRange(db.createKeyStream)
  db.valuesStream =
  db.createValueStream = safeRange(db.createValueStream)

  var batch = db.batch
  db.batch = function (changes, opts, cb) {
    if(!Array.isArray(changes))
      throw new Error('batch must be passed an Array')
    changes.forEach(function (e) {
      if(e.prefix) {
        if('function' === typeof e.prefix.prefix)
          e.key = e.prefix.prefix(e.key)
        else if('string'  === typeof e.prefix)
          e.key = e.prefix + e.key
      }
    })
    batch.call(db, changes, opts, cb)
  }
  return db
}

<|endoftext|>


<commit_before>'use strict';

// just in case is not used after gulp/bin
//
try {
  var gulp = require('gulp');
} catch (err){
  var gutil = require('gulp-util');
  gutil.log('gulp is not installed locally');
  gutil.log('try `npm install gulp`');
  process.exit(1);
}

var readline = require('readline');
var completer = require('./lib/completer');

// create a simple readline interface
//
var repl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  completer: function completion(line){
    return completer(gulp, line);
  }
});

// dispatch tasks only if line wasn't empty
//
repl.on('line', function onLine(line){
  line = line.trim();
  if(!line){ return gulp.repl.prompt(); }
  var runner = gulp.parallel || gulp.start;
  var result = runner.apply(gulp, line.split(/[ ]+/));
  if(typeof result === 'function'){ // gulp#4.0
    result();
  }
});

exports = module.exports = repl;
<commit_msg>fix: bug after reword of the module<commit_after>'use strict';

// just in case is not used after gulp/bin
//
try {
  var gulp = require('gulp');
} catch (err){
  var gutil = require('gulp-util');
  gutil.log('gulp is not installed locally');
  gutil.log('try `npm install gulp`');
  process.exit(1);
}

var readline = require('readline');
var completer = require('./lib/completer');

// create a simple readline interface
//
var repl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  completer: function completion(line){
    return completer(gulp, line);
  }
});

// dispatch tasks only if line wasn't empty
//
repl.on('line', function onLine(line){
  line = line.trim();
  if(!line){ return repl.prompt(); }
  var runner = gulp.parallel || gulp.start;
  var result = runner.apply(gulp, line.split(/[ ]+/));
  if(typeof result === 'function'){ // gulp#4.0
    result();
  }
});

exports = module.exports = repl;
<|endoftext|>