<commit_before>/*!
 * parse-comments <https://github.com/jonschlinkert/parse-comments>
 * Originally based on https://github.com/caolan/scrawl
 *
 * Copyright (c) 2014 Jon Schlinkert, contributors
 * Licensed under the MIT License (MIT)
 */

'use strict';

/**
 * Module dependencies
 */

var _ = require('lodash');
var arrayify = require('arrayify-compact');
var codeContext = require('code-context');
var lineCount = require('count-lines');
var inflect = require('inflection');
var range = require('extract-range');
var utils = require('./lib/utils');

var parser = module.exports = function parser(str, options) {
  var opts = _.extend({}, options);
  var arr = [];

  var context = codeContext(str);
  var len = context.length;
  var newObj = {};

  context.forEach(function (obj, i) {
    obj = obj || {};

    if (i < len + 1) {

      if (obj.type === 'comment') {
        var num = 0;
        if (context.length > 1) {
          num = i + 1;
        }

        var ctx = context[num];
        if (ctx) {
          var comment = range(str, obj.begin, obj.end);
          ctx.string = comment;

          var parsed = parser.extractComments(comment, opts);
          _.extend(ctx, parsed[0]);

          if (ctx.api !== 'private') {
            arr.push(_.omit(parser.normalizeHeading(ctx)));
          }
        }
      }
    }
  });

   return arr;
};

/**
 * Parse the parameters from a string.
 *
 * @param  {String} `param`
 * @return {Object}
 */

parser.parseParams = function(param) {
  var re = /(?:^\{([^\}]+)\}\s+)?(?:\[([\S]+)\]\s*)?(?:`([\S]+)`\s*)?([\s\S]*)?/;
  var match = param.match(re);

  var params = {
    type: match[1],
    name: match[3],
    description: (match[4] || '').replace(/^\s*-\s*/, '')
  };

  if (match[2]) {
    parser.parseSubprop(match, params);
  }

  return params;
};

/**
 * Parse the subproperties from parameters.
 *
 * @param  {String} `param`
 * @return {Object}
 */

parser.parseSubprop = function(match, params) {
  var subprop = match[2];

  if (/\./.test(subprop)) {
    var parts = subprop.split('.');
    var def = parts[1].split('=');
    params.name = def[0];
    params._default = def[1] || null;
    subprop = parts[0];
  }

  params.parent = subprop;
  return params;
};

/**
 * Parse the parameters from a string.
 *
 * @param  {String} `param`
 * @return {Object}
 */

parser.mergeSubprops = function(comments, subprop) {
  if (comments.hasOwnProperty(subprop) && typeof comments[subprop] === 'object') {
    var o = {};

    comments[subprop].forEach(function (child) {
      o[child.parent] = o[child.parent] || [];
      o[child.parent].push(child);
      delete child.parent;
    });

    if (comments.hasOwnProperty('params')) {
      comments.params = comments.params.map(function (param) {
        if (o[param.name]) {
          param[subprop] = o[param.name];
        }
        return param;
      });
    }

  }
  return comments;
};

/**
 * Parse `@return` comments.
 *
 * @param  {String} `str`
 * @return {Object}
 */

parser.parseReturns = function(str) {
  var match = /^\{([^\}]+)\}/.exec(str);
  if (match) {
    return match[1];
  }
  return;
};

/**
 * Parse the "lead" from a description.
 *
 * @param  {String} `str`
 * @return {Object}
 */

parser.parseLead = function(str) {
  var re = /^([\s\S]+?)(?:\n\n)/;

  var lead = '';
  var description = str.replace(re, function (match, a) {
    lead += a.replace(/\n/g, ' ');
    return match.replace(a, '');
  });

  return {
    desc: description,
    lead: lead
  };
};

/**
 * Parse the method name from a string.
 *
 * @param  {String} `str`
 * @return {Object}
 */

parser.parseHeading = function(str) {
  var re = /(#{1,6})\s+(\.?[\s\S]+?)(?:(\([\s\S]+\)?)|$)/;
  var match = str.match(re);
  if (match) {
    return {
      level: match[1].split('').length,
      text: match[2].replace(/^\s*|\s*$/gm, ''),
    };
  }
};

/**
 * Parse the method name from a string.
 *
 * @param  {String} `str`
 * @return {Object}
 */

parser.splitHeading = function (str) {
  var lines = str.split(/\n\n/g);
  var obj = {}, non = [];

  lines.forEach(function (line) {
    if (/^#/.test(line)) {
      obj = parser.parseHeading(line);
    } else {
      non.push(line);
    }
  });
  return {heading: obj, desc: non};
};

/**
 * Normalize the title based on the given fields.
 *
 * @param  {String} `obj`
 * @return {Object}
 */

parser.normalizeHeading = function(obj) {
  var o = _.extend({}, obj);
  o.name = obj.name || '';
  o.heading = {};
  o.heading.level = 2;

  // @method tags
  if (o.hasOwnProperty('method')) {
    o.type = 'method';
  }

  // @class tags
  if (o.hasOwnProperty('class')) {
    o.type = 'class';
    o.heading.level = 1;
  } else {
    o.heading.level = 2;
  }

  var heading =
    o.name ||
    o.class ||
    o.method || '';

  o.heading.text = heading.replace(/^`|`$/g, '');
  o.name = o.heading.text;
  return o;
};

/**
 * Parse `@tags`.
 *
 * @param  {Object} `comment` A comment object.
 * @param  {Object} `options`
 * @return {Object}
 */

parser.parseTags = function (comment, options) {
  var opts = options || {};
  var extracted = {};

  // strip trailing whitespace from description
  if (comment.description) {
    comment.description = utils.trimRight(comment.description);
    extracted = parser.splitHeading(comment.description);

    // Extract headings from comments
    comment.description = extracted.desc.join('\n\n');

    // Extract leads from comments
    var parsedDesc = parser.parseLead(comment.description);
    comment.lead = parsedDesc.lead;
    comment.description = parsedDesc.desc;
  }

  var h = extracted.heading || {};
  comment.heading = h;
  comment.name = h.text;

  if (h && !h.text) {
    _.extend(comment, parser.normalizeHeading(comment));
  }
  comment.name = (comment.name || '').replace(/`/g, '');

  // @example tags, strip trailing whitespace
  if (comment.example) {
    comment.example = utils.trimRight(comment.example);
  }

  // parse @param tags (`singular: plural`)
  var props = _.extend({
    return  : 'returns',
    param   : 'params',
    property: 'properties',
    option  : 'options'
  }, opts.subprops);

  props = _.omit(props, ['api', 'constructor', 'class', 'static', 'type']);

  _.keys(props).forEach(function(key) {
    var value = props[key];
    if (comment[key]) {

      var arr = comment[key] || [];
      comment[value] = arrayify(arr).map(function (str) {
        return parser.parseParams(str);
      });
    }
  });

  return comment;
};

parser.parseComment = function (content, options) {
  var opts = options || {};

  var re = /^(\s*@[\S]+)\s*(.*)/;
  var afterTags = false;
  var lines = content.split('\n');
  var afterNewLine = false;
  var lastTag;
  var props = [];

  var i = 0;

  var comment = lines.reduce(function (c, str) {
    var line = utils.stripStars(str);
    if (/\s*@/.test(line)) {
      line = line.replace(/^\s+/, '');
    }

    if (line) {
      var match = line.match(re);

      if (match) {
        afterTags = true;
        var tagname = match[1].replace(/@/, '');
        props.push(tagname);

        var tagvalue = match[2].replace(/^\s+/, '');
        lastTag = tagname;
        if (c.hasOwnProperty(tagname)) {
          // tag already exists
          if (!Array.isArray(c[tagname])) {
            c[tagname] = [c[tagname]];
          }

          c[tagname].push(tagvalue);
        } else {
          // new tag
          c[tagname] = tagvalue || true;
        }
      } else if (lastTag && !afterNewLine) {
        var val = line.replace(/^\s+/, '');
        if (Array.isArray(c[lastTag])) {
          c[lastTag][c[lastTag].length - 1] += ' ' + val;
        } else {
          c[lastTag] += ' ' + val;
        }
      } else {
        lastTag = null;
        if (!afterTags) {
          if (c.description) {
            c.description += '\n' + line;
          } else {
            c.description = line;
          }
        } else {
          if (c.example) {
            c.example += '\n' + line;
          } else {
            c.example = line;
          }
        }
      }
      afterNewLine = false;
    } else {
      afterNewLine = true;
      if (!afterTags) {
        if (c.description) {
          c.description += '\n' + line;
        }
      } else {
        if (c.example) {
          c.example += '\n' + line;
        }
      }
    }
    i++;
    return c;
  }, {});

  var singular = _.keys(opts.subprops);
  var plural = _.values(opts.subprops);

  var diff = _.difference(props, singular).filter(function (prop) {
    return prop !== 'param' &&
      prop !== 'constructor' &&
      prop !== 'return' &&
      prop !== 'static' &&
      prop !== 'class' &&
      prop !== 'type' &&
      prop !== 'api';
  });

  var pluralized = diff.map(function(name) {
    return inflect.pluralize(name);
  });

  singular = _.union(diff, singular);
  plural = _.union([], pluralized, plural);

  var comments = this.parseTags(comment, {
    subprops: _.zipObject(singular, plural)
  });

  // Pass custom subprops (plural/arrays)
  plural.forEach(function (prop) {
    this.mergeSubprops(comments, prop);
  }.bind(this));

  return comments;
};

/**
 * Parse comments
 * @param   {String}  str
 * @return  {String}
 */

parser.extractComments = function (str, options) {
  var opts = _.extend({}, options);

  var re = /\/\*{1,2}([\s\S]*?)\*\//g;
  var data = [];

  var lineNumber = 1;
  var match;

  while (match = re.exec(str)) {
    var _str = str;

    // add lines from before the comments
    lineNumber += lineCount(_str.substr(0, match.index));
    str = str.substr(match.index + match[1].length);
    var params = parser.parseComment(match[1], opts);

    params.line = lineNumber;

    // Allow @words to be escaped with a single backtick, e.g. `@word,
    // then remove the backtick before the final result.
    if (params.description) {
      params.description = params.description.replace(/^`@/gm, '@');
    }

    data.push(params);

    // add lines from the comment itself
    lineNumber += lineCount(_str.substr(match.index, match[1].length));
  }
  return data;
};
<commit_msg>refactoring<commit_after>/*!
 * parse-comments <https://github.com/jonschlinkert/parse-comments>
 * Originally based on https://github.com/caolan/scrawl
 *
 * Copyright (c) 2014 Jon Schlinkert, contributors
 * Licensed under the MIT License (MIT)
 */

'use strict';

/**
 * Module dependencies
 */

var _ = require('lodash');
var arrayify = require('arrayify-compact');
var codeBlocks = require('gfm-code-blocks');
var codeContext = require('code-context');
var inflect = require('inflection');
var utils = require('./lib/utils');

var parser = function parser(str) {
  var comments = parser.codeContext(str);

  return comments.filter(function (o) {
    return !_.isEmpty(o);
  });
};

parser.nolinks = [];
parser.links = {};

/**
 * Extract code comments, and merge in code context.
 *
 * @param  {String} `str`
 * @return {Array} Array of comment objects.
 */

parser.codeContext = function(str) {
  var context = codeContext(str);

  return context.map(function (o, i) {
    var comment = {};
    o = o || {};

    var next = i;
    if (i < context.length - 1) {
      next = i + 1;
    }

    if (o.hasOwnProperty('comment')) {
      o.comment = parser.parseComment(o.comment);
      if (o.comment.api && o.comment.api === 'public') {
        comment = _.extend({}, o, o.comment);
        comment.context = context[next];
        parser.parseExamples(comment);
        parser.parseDescription(comment);
        // console.log(comment)

      }
    }

    delete comment.comment;
    delete comment.type;
    return comment;
  });
};

/**
 * Normalize descriptions.
 *
 * @param  {Object} `comment`
 * @return {Object}
 */

parser.normalizeDesc = function(o) {
  // strip trailing whitespace from description
  comment.description = utils.trimRight(comment.description);

  // split
  o = parser.splitHeading(comment.description);
  heading = o.heading;

  // Extract headings from comments
  comment.description = o.desc.join('\n\n');

  // Extract leads from comments
  var parsedDesc = parser.parseLead(comment.description);
  comment.lead = parsedDesc.lead;
  comment.description = parsedDesc.desc;
  return o;
};

/**
 * Parse code examples from a `comment.description`.
 *
 * @param  {Object} `comment`
 * @return {Object}
 */

parser.parseDescription = function (comment) {
  var o = {},
    heading = {};

  // strip trailing whitespace from description
  if (comment.description) {
    // comment.description = utils.trimRight(comment.description);

    // // split
    // o = parser.splitHeading(comment.description);
    // heading = o.heading;

    // // Extract headings from comments
    // comment.description = o.desc.join('\n\n');

    // // Extract leads from comments
    // var parsedDesc = parser.parseLead(comment.description);
    // comment.lead = parsedDesc.lead;
    // comment.description = parsedDesc.desc;
  }

  if (heading && !heading.text) {
    comment.heading = heading;
    comment.name = heading.text;

    _.extend(comment, parser.normalizeHeading(comment));
  }

  comment.name = (comment.name || '').replace(/`/g, '');

  // @example tags, strip trailing whitespace
  if (comment.example) {
    comment.example = utils.trimRight(comment.example);
  }
};

/**
 * Parse code examples from a `comment.description`.
 *
 * @param  {Object} `comment`
 * @return {Object}
 */

parser.parseExamples = function(comment) {
  var examples = codeBlocks(comment.description);
  if (!_.isEmpty(examples)) {
    comment.examples = examples;
  }
  return comment;
};

/**
 * Parse the parameters from a string.
 *
 * @param  {String} `param`
 * @return {Object}
 */

parser.parseParams = function(param) {
  var re = /(?:^\{([^\}]+)\}\s+)?(?:\[([\S]+)\]\s*)?(?:`([\S]+)`\s*)?([\s\S]*)?/;
  var match = param.match(re);

  var params = {
    type: match[1],
    name: match[3],
    description: (match[4] || '').replace(/^\s*-\s*/, '')
  };

  if (match[2]) {
    parser.parseSubprop(match, params);
  }

  return params;
};

/**
 * Parse the subproperties from parameters.
 *
 * @param  {String} `param`
 * @return {Object}
 */

parser.parseSubprop = function(match, params) {
  var subprop = match[2];

  if (/\./.test(subprop)) {
    var parts = subprop.split('.');
    var def = parts[1].split('=');
    params.name = def[0];
    params._default = def[1] || null;
    subprop = parts[0];
  }

  params.parent = subprop;
  return params;
};

/**
 * Parse the parameters from a string.
 *
 * @param  {String} `param`
 * @return {Object}
 */

parser.mergeSubprops = function(comments, subprop) {
  if (comments.hasOwnProperty(subprop) && typeof comments[subprop] === 'object') {
    var o = {};

    comments[subprop].forEach(function (child) {
      o[child.parent] = o[child.parent] || [];
      o[child.parent].push(child);
      delete child.parent;
    });

    if (comments.hasOwnProperty('params')) {
      comments.params = comments.params.map(function (param) {
        if (o[param.name]) {
          param[subprop] = o[param.name];
        }
        return param;
      });
    }

  }
  return comments;
};

/**
 * Parse `@return` comments.
 *
 * @param  {String} `str`
 * @return {Object}
 */

parser.parseReturns = function(str) {
  var match = /^\{([^\}]+)\}/.exec(str);
  if (match) {
    return match[1];
  }
  return;
};

/**
 * Parse the "lead" from a description.
 *
 * @param  {String} `str`
 * @return {Object}
 */

parser.parseLead = function(str) {
  var re = /^([\s\S]+?)(?:\n\n)/;

  var lead = '';
  var description = str.replace(re, function (match, a) {
    lead += a.replace(/\n/g, ' ');
    return match.replace(a, '');
  });

  return {
    desc: description,
    lead: lead
  };
};

/**
 * Parse the method name from a string.
 *
 * @param  {String} `str`
 * @return {Object}
 */

parser.parseHeading = function(str) {
  var re = /(#{1,6})\s+(\.?[\s\S]+?)(?:(\([\s\S]+\)?)|$)/;
  var match = str.match(re);
  if (match) {
    return {
      level: match[1].split('').length,
      text: match[2].replace(/^\s*|\s*$/gm, ''),
    };
  }
};

/**
 * Parse the method name from a string.
 *
 * @param  {String} `str`
 * @return {Object}
 */

parser.splitHeading = function (str) {
  var lines = str.split(/\n\n/g);
  var obj = {}, non = [];

  lines.forEach(function (line) {
    if (/^#/.test(line)) {
      obj = parser.parseHeading(line);
    } else {
      non.push(line);
    }
  });
  return {heading: obj, desc: non};
};

/**
 * Normalize the title based on the given fields.
 *
 * @param  {String} `obj`
 * @return {Object}
 */

parser.normalizeHeading = function(obj) {
  var o = _.extend({}, obj);
  obj.context = obj.context || {};

  o.name = obj.name || obj.context.name || null;

  o.heading = {};
  o.heading.level = 2;

  // @method tags
  if (o.hasOwnProperty('method')) {
    o.type = 'method';
  }

  // @class tags
  if (o.hasOwnProperty('class')) {
    o.type = 'class';
    o.heading.level = 1;
  } else {
    o.heading.level = 2;
  }

  var heading =
    o.name ||
    o.class ||
    o.method || '';

  // Strip backticks from headings
  o.heading.text = heading.replace(/^`|`$/g, '');
  o.name = o.heading.text;

  // optionally prefix prototype methods with `.`
  if (o.context && o.context.type &&
    /prototype (?:method|property)/.test(o.context.type)) {
    o.heading.prefix = '.';
  }

  return o;
};

/**
 * Parse sub-headings from a string.
 *
 * @param  {String} `str`
 * @return {Object}
 */

parser.parseSubHeading = function(str) {
  var re = /^\*\*([\s\S]+?):?\*\*(?!\*)/;
  var match = str.match(re);
  if (match) {
    return match[1];
  }
};

/**
 * Parse links.
 *
 * @param  {String} `str`
 * @return {Object}
 */

parser.parseLink = function(str) {
  var re = /^!?\[((?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*)\]\(\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*\)/;
  var match = str.match(re);
  if (match) {
    return {
      text: match[1],
      url: match[2],
      alt: match[3]
    }
  }
};

/**
 * Parse nolinks.
 *
 * @param  {String} `str`
 * @return {Object}
 */

parser.parseNolink = function(str) {
  var nolink = /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/;
  var ref = /^!?\[((?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*)\]\s*\[([^\]]*)\]/;
  var match;
  if (match = str.match(nolink)) {
    return match[0];
  } else if (match = str.match(ref)) {
    return match[0];
  }
};

/**
 * Parse `@tags`.
 *
 * @param  {Object} `comment` A comment object.
 * @param  {Object} `options`
 * @return {Object}
 */

parser.parseTags = function (comment, options) {
  var opts = options || {};

  // parse @param tags (`singular: plural`)
  var props = _.extend({
    return  : 'returns',
    param   : 'params',
    property: 'properties',
    option  : 'options'
  }, opts.subprops);

  props = _.omit(props, ['api', 'constructor', 'class', 'static', 'type']);

  _.keys(props).forEach(function(key) {
    var value = props[key];
    if (comment[key]) {

      var arr = comment[key] || [];
      comment[value] = arrayify(arr).map(function (str) {
        return parser.parseParams(str);
      });
    }
  });

  return comment;
};

parser.parseComment = function (content, options) {
  content = content.replace(/\r/g, '');
  var opts = options || {};

  var afterNewLine = false;
  var afterTags = false;
  var props = [];
  var lastTag;
  var i = 0;

  var lines = content.split(/\n/g);

  var comment = lines.reduce(function (c, str) {
    var line = utils.stripStars(str);
    if (/\s*@/.test(line)) {
      line = line.replace(/^\s+/, '');
    }

    if (line) {
      var href = parser.parseLink(line);
      if (href) {
        parser.links[href.text] = href;
      }

      var nolink = parser.parseNolink(line);
      if (nolink) {
        parser.nolinks.push(nolink);
      }

      c.subheads = c.subheads || [];
      var subhead = parser.parseSubHeading(line);
      if (subhead) {
        c.subheads.push(subhead);
      }

      var match = line.match(/^(\s*@[\S]+)\s*(.*)/);
      if (match) {
        afterTags = true;
        var tagname = match[1].replace(/@/, '');
        props.push(tagname);

        var tagvalue = match[2].replace(/^\s+/, '');
        lastTag = tagname;
        if (c.hasOwnProperty(tagname)) {
          // tag already exists
          if (!Array.isArray(c[tagname])) {
            c[tagname] = [c[tagname]];
          }

          c[tagname].push(tagvalue);
        } else {
          // new tag
          c[tagname] = tagvalue || true;
        }
      } else if (lastTag && !afterNewLine) {
        var val = line.replace(/^\s+/, '');
        if (Array.isArray(c[lastTag])) {
          c[lastTag][c[lastTag].length - 1] += ' ' + val;
        } else {
          c[lastTag] += ' ' + val;
        }
      } else {
        lastTag = null;
        if (!afterTags) {
          if (c.description) {
            c.description += '\n' + line;
          } else {
            c.description = line;
          }
        } else {
          if (c.example) {
            c.example += '\n' + line;
          } else {
            c.example = line;
          }
        }
      }
      afterNewLine = false;
    } else {
      afterNewLine = true;
      if (!afterTags) {
        if (c.description) {
          c.description += '\n' + line;
        }
      } else {
        if (c.example) {
          c.example += '\n' + line;
        }
      }
    }
    i++;
    return c;
  }, {});

  var singular = _.keys(opts.subprops);
  var plural = _.values(opts.subprops);

  var diff = _.difference(props, singular).filter(function (prop) {
    return prop !== 'param' &&
      prop !== 'constructor' &&
      prop !== 'return' &&
      prop !== 'static' &&
      prop !== 'class' &&
      prop !== 'type' &&
      prop !== 'api';
  });

  var pluralized = diff.map(function(name) {
    return inflect.pluralize(name);
  });

  singular = _.union(diff, singular);
  plural = _.union([], pluralized, plural);

  var comments = this.parseTags(comment, {
    subprops: _.zipObject(singular, plural)
  });

  // Pass custom subprops (plural/arrays)
  plural.forEach(function (prop) {
    this.mergeSubprops(comments, prop);
  }.bind(this));

  return comments;
};

var fs = require('fs');
var str = fs.readFileSync('test/fixtures/assemble.js', 'utf8');
var p = parser(str);
var util = require('util');

// console.log(util.inspect(p, null, 10));

module.exports = parser;<|endoftext|>


<commit_before>const DISCORD = require('discord.js');
const FUBUKI = new DISCORD.Client();

let config = require('./config');
let booru = require('./booru.js');
let remind = require('./remind.js');
let musicplayer = require('./musicplayer.js');

FUBUKI.on('ready', () => {
  console.log('Ready');
});

FUBUKI.on('message', message => {
  let cmds = message.content.toLowerCase().split(' ');

  switch (cmds[0]) {
    case '!ping':
      message.channel.sendMessage('pong')
        .then(console.log(cmds));
      break;
    case '!sleep':
      message.channel.sendMessage('Logging off. Bye!')
        .then(console.log('Logging off.'));
      setTimeout(function(){
        FUBUKI.destroy();
        process.exit(0);
      }, 500);
      break;
    case '!booru':
      booru.getDanbooru(message, cmds);
      break;
    case '!b':
      booru.getDanbooru(message, cmds);
      message.delete()
      break;
    case '!bsafe':
      let newCmd = cmds;
      newCmd.push('rating:safe');
      booru.getDanbooru(message, newCmd);
      message.delete()
      break;
    case '!remindme':
      remind.remindMe(message);
      break;
    case '!play':
      musicplayer.play(message);
      message.delete()
        .then(msg => console.log('Deleted message from ' + msg.author))
        .catch(console.log("Failed to delete message: " + message.content));
      break;
    case '!connect':
      musicplayer.connect(message.guild);
      break;
    case '!disconnect':
      musicplayer.disconnect(message.guild);
      break;
    case '!remindme':
      remind.remindMe(message);
      break;
    case '!play':
      musicplayer.play(message);
      message.delete()
        .then(msg => console.log('Deleted message from ' + msg.author))
        .catch(console.log("Failed to delete message: " + message.content));
      break;
    case '!connect':
      musicplayer.connect(message.guild);
      break;
    case '!disconnect':
      musicplayer.disconnect(message.guild);
      break;
    case '!remindme':
      remind.remindMe(message);
      break;
    case '!play':
      musicplayer.play(message);
      message.delete()
        .then(msg => console.log('Deleted message from ' + msg.author))
        .catch(console.log("Failed to delete message: " + message.content));
      break;
    case '!connect':
      musicplayer.connect(message.guild);
      break;
    case '!disconnect':
      musicplayer.disconnect(message.guild);
      break;
    case '!remindme':
      remind.remindMe(message);
      break;
    case '!play':
      musicplayer.play(message);
      break;
    case '!connect':
      musicplayer.connect(message.guild);
      break;
    case '!disconnect':
      musicplayer.disconnect(message.guild);
      break;
    case '!skip':
      musicplayer.skip(message);
      break;
    case '!repeat':
      musicplayer.repeat(message);
      break;
    case '!nowplaying':
      musicplayer.nowPlaying(message.channel);
      break;
    case '!radio':
      musicplayer.radio(message);
      message.delete()
        .then(msg => console.log('Deleted message from ' + msg.author))
        .catch(console.log("Failed to delete message: " + message.content));
      break;
    case '!stopradio':
      musicplayer.stopRadio();
      break;
    case '!help':
      let helpText = 'The following commands are avalible to this bot:\n\n'
        '!ping Reply with "pong" if the bot is still functional.\n\n' +
        '!booru [tags] or !b [tags] Returns a link to a random Danbooru post' +
          ' with the given tags. If you have more than one tag, seperate' +
          ' them with a space.\n\n' +
        '!bsafe [tags] Functions the same as !booru and !b, but appends' +
        ' "rating:safe" to your request automatically.\n\n' +
        '!help The bot will DM you this help text.\n\n' +
        '!remindme [Message] in [number] [hour(s)/minute(s)] and [number] ' +
          '[hour(s)/minute(s)] The bot will @ you after the specified time. ' +
          'You can omit the "and" and everything after if desired. ' +
          'Case does not matter.' +
        '!connect The bot joins the music channel.' +
        '!play [youtube link] The bot plays the selected link in ' +
          'the music channel. If it was already playing something ' +
          'your link is added to the queue.' +
        '!disconnect The bot leaves the music channel ' +
          'and clears the queue of links to playback.' +
        '!skip Skips the current song in the queue.' +
        '!repeat Repeats the current song being played. This will be ' +
          'the last song played if no songs are currently playing.';
      message.channel.sendMessage('Help is on the way! Check your DMs.')
      message.author.sendMessage(helpText);
      break;
    default:
  }
});

FUBUKI.on('disconnected', function() {
  console.log('Disconnected');
  process.exit(1);
});

FUBUKI.login(config.discord_token);
<commit_msg>Delete redundant commands in index.js<commit_after>const DISCORD = require('discord.js');
const FUBUKI = new DISCORD.Client();

let config = require('./config');
let booru = require('./booru.js');
let remind = require('./remind.js');
let musicplayer = require('./musicplayer.js');

FUBUKI.on('ready', () => {
  console.log('Ready');
});

FUBUKI.on('message', message => {
  let cmds = message.content.toLowerCase().split(' ');

  switch (cmds[0]) {
    case '!ping':
      message.channel.sendMessage('pong')
        .then(console.log(cmds));
      break;
    case '!sleep':
      message.channel.sendMessage('Logging off. Bye!')
        .then(console.log('Logging off.'));
      message.delete();
      setTimeout(function(){
        FUBUKI.destroy();
        process.exit(0);
      }, 500);
      break;
    case '!booru':
      booru.getDanbooru(message, cmds);
      message.delete();
      break;
    case '!b':
      booru.getDanbooru(message, cmds);
      message.delete();
      break;
    case '!bsafe':
      let newCmd = cmds;
      newCmd.push('rating:safe');
      booru.getDanbooru(message, newCmd);
      message.delete();
      break;
    case '!remindme':
      remind.remindMe(message);
      break;
    case '!play':
      musicplayer.play(message);
      message.delete()
        .then(msg => console.log('Deleted message from ' + msg.author))
        .catch(console.log("Failed to delete message: " + message.content));
      break;
    case '!connect':
      musicplayer.connect(message.guild);
      break;
    case '!disconnect':
      musicplayer.disconnect(message.guild);
      break;
    case '!skip':
      musicplayer.skip(message);
      break;
    case '!repeat':
      musicplayer.repeat(message);
      break;
    case '!nowplaying':
      musicplayer.nowPlaying(message.channel);
      break;
    case '!radio':
      musicplayer.radio(message);
      message.delete()
        .then(msg => console.log('Deleted message from ' + msg.author))
        .catch(console.log("Failed to delete message: " + message.content));
      break;
    case '!stopradio':
      musicplayer.stopRadio();
      break;
    case '!help':
      let helpText = 'The following commands are avalible to this bot:\n\n'
        '!ping Reply with "pong" if the bot is still functional.\n\n' +
        '!booru [tags] or !b [tags] Returns a link to a random Danbooru post' +
          ' with the given tags. If you have more than one tag, seperate' +
          ' them with a space.\n\n' +
        '!bsafe [tags] Functions the same as !booru and !b, but appends' +
        ' "rating:safe" to your request automatically.\n\n' +
        '!help The bot will DM you this help text.\n\n' +
        '!remindme [Message] in [number] [hour(s)/minute(s)] and [number] ' +
          '[hour(s)/minute(s)] The bot will @ you after the specified time. ' +
          'You can omit the "and" and everything after if desired. ' +
          'Case does not matter.' +
        '!connect The bot joins the music channel.' +
        '!play [youtube link] The bot plays the selected link in ' +
          'the music channel. If it was already playing something ' +
          'your link is added to the queue.' +
        '!disconnect The bot leaves the music channel ' +
          'and clears the queue of links to playback.' +
        '!skip Skips the current song in the queue.' +
        '!repeat Repeats the current song being played. This will be ' +
          'the last song played if no songs are currently playing.';
      message.channel.sendMessage('Help is on the way! Check your DMs.')
      message.author.sendMessage(helpText);
      break;
    default:
  }
});

FUBUKI.on('disconnected', function() {
  console.log('Disconnected');
  process.exit(1);
});

FUBUKI.login(config.discord_token);
<|endoftext|>


<commit_before>// function store (skates, coffee){
//   var skateStrings = String(skates)
//     while(skateStrings.length < 3)
//     skateStrings = "0" + skateStrings
//     document.write(skateStrings + "skateboards")
//   var coffeeStrings = String(coffee)
//     while(coffeeStrings.lenght < 3)
//     coffeeStrings = "0" + coffeeStrings
//     document.write(coffeeStrings + "coffee")
// }
// store(4,1)

// function labelPrint(number,label) {
//   var numberString = String(number)
//   while (numberString.lenght < 3)
//     numberString = numberString
//   console.log(numberString + " " + label);
// }
//
// document.write(labelPrint(3,5))

// function noOne(a){
//   return document.write(44)
// }
//
// noOne()
//
// function pushes() {
//   var newArray = []
//   newArray.push("
"+ "hello2")
//   console.log(pushes('peter'));
//   document.write(newArray)
// }
//
// pushes("hello")

// var arra = []
//
// arra.push("no1","no2","no3","no4")
//
// console.log(arra);
// document.write(arra)
//
// arra.join(" ")
//
// console.log('join',  arra.join(" "));
// console.log('pop', arra.pop("no2"))
// console.log('pop try thinky', arra.pop([3]))
// console.log('push new stuff', arra.push("new shit"));
//
// document.write("
",arra);

// var person = {
//   name: "peter",
//   surname: "kona",
//   car: ['tesla',
//        'vw',
//        'ford',
//        'mustang',
//        'skoda']
// }

// function vlogLog(){
// console.log(person.peter + ' ' + person.car[0]);
// }

// function getName(){
//   document.write(person.name + " " + person.surname)
// }
//
// getName()
//
// vlogLog()
//
//
// var anObject = {
//   left:1,
//   right:2
// }
//
// delete anObject.left
//
// document.write(" ", anObject.right)
// console.log(anObject);

// var book = []
//
// function addEntry(events,days){
//   book.push({
//     events: events,
//     days: days
//   })
// }
//
// addEntry(["work", "touched tree", "pizza", "running",
//           "television"], ["1:10","2:30","5:20"]);
//
//
// var days = []
// function addDays(day,hours) {
//   days.push({
//     days:days,
//     hours:hours
//   })
// }
//
// addDays(["monday", "tuesday",'saturday'],["1:10","2:30","5:20"])
//
// document.write(days)
<commit_msg>for each<commit_after>// function store (skates, coffee){
//   var skateStrings = String(skates)
//     while(skateStrings.length < 3)
//     skateStrings = "0" + skateStrings
//     document.write(skateStrings + "skateboards")
//   var coffeeStrings = String(coffee)
//     while(coffeeStrings.lenght < 3)
//     coffeeStrings = "0" + coffeeStrings
//     document.write(coffeeStrings + "coffee")
// }
// store(4,1)

// function labelPrint(number,label) {
//   var numberString = String(number)
//   while (numberString.lenght < 3)
//     numberString = numberString
//   console.log(numberString + " " + label);
// }
//
// document.write(labelPrint(3,5))

// function noOne(a){
//   return document.write(44)
// }
//
// noOne()
//
// function pushes() {
//   var newArray = []
//   newArray.push("
"+ "hello2")
//   console.log(pushes('peter'));
//   document.write(newArray)
// }
//
// pushes("hello")

// var arra = []
//
// arra.push("no1","no2","no3","no4")
//
// console.log(arra);
// document.write(arra)
//
// arra.join(" ")
//
// console.log('join',  arra.join(" "));
// console.log('pop', arra.pop("no2"))
// console.log('pop try thinky', arra.pop([3]))
// console.log('push new stuff', arra.push("new shit"));
//
// document.write("
",arra);

// var person = {
//   name: "peter",
//   surname: "kona",
//   car: ['tesla',
//        'vw',
//        'ford',
//        'mustang',
//        'skoda']
// }

// function vlogLog(){
// console.log(person.peter + ' ' + person.car[0]);
// }

// function getName(){
//   document.write(person.name + " " + person.surname)
// }
//
// getName()
//
// vlogLog()
//
//
// var anObject = {
//   left:1,
//   right:2
// }
//
// delete anObject.left
//
// document.write(" ", anObject.right)
// console.log(anObject);

// var book = []
//
// function addEntry(events,days){
//   book.push({
//     events: events,
//     days: days
//   })
// }
//
// addEntry(["work", "touched tree", "pizza", "running",
//           "television"], ["1:10","2:30","5:20"]);
//
//
// var days = []
// function addDays(day,hours) {
//   days.push({
//     days:days,
//     hours:hours
//   })
// }
//
// addDays(["monday", "tuesday",'saturday'],["1:10","2:30","5:20"])
//
// document.write(days)
var array = [1,2,3,4]
for (var i = 0; i < array.length; i++){
  var current = array[i]
  console.log(current);
}

var names = ["peter", "nani", "kubo", "yvetka", "ludo"]

function getAllNames() {
  for(var i = 0;i < names.length;i++){
    var newNam = names[0] + " " + names[2]
    document.write(newNam)
    console.log(newNam)
  }
  for(var j = 0;j < names.length;j++){
    var newFam = names[4] + " " + names[2]
      document.write(newFam)
      console.log(newFam)
  }
}
function getFam(){
  for(var j = 0;j < names.length;j++){
    var newFam = names[j]
      document.write(newFam)
      console.log(newFam);
  }
}

// getAllNames()
// getFam()

var arr1 = ['x','x','x','x']
var arr2 = ['o','o','o','o']

function fun(){
  for (var i = 0;i<arr1.length;i++){
    var newOne = arr1[i]
      document.write(newOne)
      console.log(newOne)
      for (var j=0;j<arr2.length;j++){
        var newTwo = arr2[i]
          document.write(newTwo)
          console.log(newTwo)
   }
   console.log('hello', newTwo)
   console.log('from two', newOne)
     document.write(newTwo)
          document.write(newOne)
    }
}

// fun()

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}

forEach(["Peter", "Kona", "Granfalloon"], console.log);

// var numbers = [1,2], sum = 0
// forEach(numbers, function(number){
//   sum += number
// })
document.write(sum);

var names = ["Peter Kona", "Nani Kona"],sum = 0
  forEach(names,function(number){
    sum += number
  })
  document.write('
' + sum);
<|endoftext|>


<commit_before>const express = require('express');
const path = require('path');

const DEFAULT_PORT = 3000;

const port = process.env.PORT || DEFAULT_PORT;
const app = express();

if (process.env.NODE_ENV === 'DEV') {
  // Step 1: Create & configure a webpack compiler
  const webpack = require('webpack');
  const webpackConfig = require('./webpack.config');
  const compiler = webpack(webpackConfig);

  // Step 2: Attach the dev middleware to the compiler & the server
  app.use(
    require('webpack-dev-middleware')(compiler, {
      noInfo: true,
      publicPath: webpackConfig.output.publicPath,
    }),
  );

  // Step 3: Attach the hot middleware to the compiler & the server
  app.use(
    require('webpack-hot-middleware')(compiler, {
      heartbeat: 10000,
      // eslint-disable-next-line no-console
      log: console.log,
      path: '/__webpack_hmr',
    }),
  );
}

app.use('/', express.static(path.join(__dirname, 'dist')));

const server = app.listen(port, () => {
  server.keepAliveTimeout = 0;
  process.stdout.write(`listening on port ${port}\n`);
});
<commit_msg>removed trailing commas<commit_after>const express = require('express');
const path = require('path');

const DEFAULT_PORT = 3000;

const port = process.env.PORT || DEFAULT_PORT;
const app = express();

if (process.env.NODE_ENV === 'DEV') {
  // Step 1: Create & configure a webpack compiler
  const webpack = require('webpack');
  const webpackConfig = require('./webpack.config');
  const compiler = webpack(webpackConfig);

  // Step 2: Attach the dev middleware to the compiler & the server
  app.use(
    require('webpack-dev-middleware')(compiler, {
      noInfo: true,
      publicPath: webpackConfig.output.publicPath,
    })
  );

  // Step 3: Attach the hot middleware to the compiler & the server
  app.use(
    require('webpack-hot-middleware')(compiler, {
      heartbeat: 10000,
      // eslint-disable-next-line no-console
      log: console.log,
      path: '/__webpack_hmr',
    })
  );
}

app.use('/', express.static(path.join(__dirname, 'dist')));

const server = app.listen(port, () => {
  server.keepAliveTimeout = 0;
  process.stdout.write(`listening on port ${port}\n`);
});
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter,
    util = require("util"),
    protos = require("./protos"),
    protoMask = 0x80000000,
    bignumber = require("bignumber.js"),
    CSGO = exports;

var CSGOClient = function CSGOClient(steamUser, steamGC, debug) {
  EventEmitter.call(this);

  this.debug = debug || false;
  this._user = steamUser;
  this._gc = steamGC;
  this._appid = 730;
  this.chatChannels = []; // Map channel names to channel data.
  this._gcReady = false;
  this._gcClientHelloIntervalId = null;

  var self = this;
  this._gc.on('message', function(type, message, callback) {
    callback = callback || null;

    var kMsg = type.msg & ~protoMask;
    if (self.debug) {
      util.log("CS:GO fromGC: " + kMsg);  // TODO:  Turn type-protoMask into key name.
    }
    if (kMsg in self._handlers) {
      if (callback) {
        self._handlers[kMsg].call(self, message, callback);
      }
      else {
        self._handlers[kMsg].call(self, message);
      }
    }
    else {
      self.emit("unhandled", kMsg);
    }
  });

  this._gc._client.on('message', function(type, message, callback) {
    callback = callback || null;

    var kMsg = type.msg & ~protoMask;
    if (kMsg in self._handlers) {
      if (callback) {
        self._handlers[kMsg].call(self, message, callback);
      }
      else {
        self._handlers[kMsg].call(self, message);
      }
    }
    else {
      self.emit("unhandled_steam", kMsg);
    }
  });

  this._sendClientHello = function() {
    if (self.debug) {
      util.log("Sending ClientHello");
    }
    if (!self._gc) {
      util.log("GC went missing");
    }
    else {
      self._gc.send({msg: CSGO.EGCBaseClientMsg.k_EMsgGCClientHello, proto: {}},
          new protos.CMsgClientHello({}).toBuffer());
    }
  };
};
util.inherits(CSGOClient, EventEmitter);

require("./generated/messages");

CSGOClient.prototype.ServerRegion = CSGO.ServerRegion;
CSGOClient.prototype.GameMode = CSGO.GameMode;

CSGOClient.prototype.ToAccountID = function(accid){
  return new bignumber(accid).minus('76561197960265728')-0;
};

CSGOClient.prototype.ToSteamID = function(accid){
  return new bignumber(accid).plus('76561197960265728')+"";
};

// Methods
CSGOClient.prototype.launch = function() {
  /* Reports to Steam that we are running Counter-Strike: Global Offensive. Initiates communication with GC with EMsgGCClientHello */
  if (this.debug) {
    util.log("Launching CS:GO");
  }
  this._user.gamesPlayed({
    games_played: [{
      game_id: '730'
    }]
  });

  // Keep knocking on the GCs door until it accepts us.
  this._gcClientHelloIntervalId = setInterval(this._sendClientHello, 2500);
};

CSGOClient.prototype.exit = function() {
  /* Reports to Steam we are not running any apps. */
  if (this.debug) {
    util.log("Exiting CS:GO");
  }

  /* stop knocking if exit comes before ready event */
  if (this._gcClientHelloIntervalId) {
    clearInterval(this._gcClientHelloIntervalId);
    this._gcClientHelloIntervalId = null;
  }
  this._gcReady = false;
  this._user.gamesPlayed({
    games_played: [{}]
  });
};

// Handlers

var handlers = CSGOClient.prototype._handlers = {};

handlers[CSGO.EGCBaseClientMsg.k_EMsgGCClientWelcome] = function clientWelcomeHandler(message) {
  /* Response to our k_EMsgGCClientHello, now we can execute other GC commands. */

  // Only execute if _gcClientHelloIntervalID, otherwise it's already been handled (and we don't want to emit multiple 'ready');
  if (this._gcClientHelloIntervalId) {
    clearInterval(this._gcClientHelloIntervalId);
    this._gcClientHelloIntervalId = null;

    if (this.debug) {
      util.log("Received client welcome.");
    }
    this._gcReady = true;
    this.emit("ready");
  }
};

handlers[CSGO.EGCBaseClientMsg.k_EMsgGCClientConnectionStatus] = function gcClientConnectionStatus(message) {
  /* Catch and handle changes in connection status, cuz reasons u know. */

  var status = protos.CMsgConnectionStatus.decode(message).status;

  switch (status) {
    case CSGO.GCConnectionStatus.GCConnectionStatus_HAVE_SESSION:
      if (this.debug) {
        util.log("GC Connection Status regained.");
      }

      // Only execute if _gcClientHelloIntervalID, otherwise it's already been handled (and we don't want to emit multiple 'ready');
      if (this._gcClientHelloIntervalId) {
        clearInterval(this._gcClientHelloIntervalId);
        this._gcClientHelloIntervalId = null;

        this._gcReady = true;
        this.emit("ready");
      }
      break;

    default:
      if (this.debug) {
        util.log("GC Connection Status unreliable - " + status);
      }

      // Only execute if !_gcClientHelloIntervalID, otherwise it's already been handled (and we don't want to emit multiple 'unready');
      if (!this._gcClientHelloIntervalId) {
        this._gcClientHelloIntervalId = setInterval(this._sendClientHello, 2500); // Continually try regain GC session

        this._gcReady = false;
        this.emit("unready");
      }
      break;
  }
};

CSGO.CSGOClient = CSGOClient;

require("./handlers/match");
<commit_msg>Dota compatibility<commit_after>var EventEmitter = require('events').EventEmitter,
    util = require("util"),
    protos = require("./protos"),
    protoMask = 0x80000000,
    bignumber = require("bignumber.js"),
    CSGO = exports;

var CSGOClient = function CSGOClient(steamUser, steamGC, debug) {
  EventEmitter.call(this);

  this.debug = debug || false;
  this._user = steamUser;
  this._gc = steamGC;
  this._appid = 730;
  this.chatChannels = []; // Map channel names to channel data.
  this._gcReady = false;
  this._gcClientHelloIntervalId = null;

  var self = this;
  this._gc.on('message', function(type, message, callback) {
    callback = callback || null;

    var kMsg = type.msg & ~protoMask;
    if (self.debug) {
      util.log("CS:GO fromGC: " + kMsg);  // TODO:  Turn type-protoMask into key name.
    }
    if (kMsg in self._handlers) {
      if (callback) {
        self._handlers[kMsg].call(self, message, callback);
      }
      else {
        self._handlers[kMsg].call(self, message);
      }
    }
    else {
      self.emit("unhandled", kMsg);
    }
  });

  this._gc._client.on('message', function(type, message, callback) {
    callback = callback || null;

    var kMsg = type.msg & ~protoMask;
    if (kMsg in self._handlers) {
      if (callback) {
        self._handlers[kMsg].call(self, message, callback);
      }
      else {
        self._handlers[kMsg].call(self, message);
      }
    }
    else {
      self.emit("unhandled_steam", kMsg);
    }
  });

  this._sendClientHello = function() {
    if (self.debug) {
      util.log("Sending ClientHello");
    }
    if (!self._gc) {
      util.log("GC went missing");
    }
    else {
      self._gc.send({msg: CSGO.EGCBaseClientMsg.k_EMsgGCClientHello, proto: {}},
          new protos.CMsgClientHello({}).toBuffer());
    }
  };
};
util.inherits(CSGOClient, EventEmitter);

require("./generated/messages");

CSGOClient.prototype.ServerRegion = CSGO.ServerRegion;
CSGOClient.prototype.GameMode = CSGO.GameMode;

CSGOClient.prototype.ToAccountID = function(accid){
  return new bignumber(accid).minus('76561197960265728')-0;
};

CSGOClient.prototype.ToSteamID = function(accid){
  return new bignumber(accid).plus('76561197960265728')+"";
};

// Methods
CSGOClient.prototype.launch = function() {
  /* Reports to Steam that we are running Counter-Strike: Global Offensive. Initiates communication with GC with EMsgGCClientHello */
  if (this.debug) {
    util.log("Launching CS:GO");
  }
    this._user.gamesPlayed({
    games_played: [
      {
        game_id: 730,
        game_flags: 1
      },
      {
        game_id: 570,
        game_flags: 1
      }
    ]
  });

  // Keep knocking on the GCs door until it accepts us.
  this._gcClientHelloIntervalId = setInterval(this._sendClientHello, 2500);
};

CSGOClient.prototype.exit = function() {
  /* Reports to Steam we are not running any apps. */
  if (this.debug) {
    util.log("Exiting CS:GO");
  }

  /* stop knocking if exit comes before ready event */
  if (this._gcClientHelloIntervalId) {
    clearInterval(this._gcClientHelloIntervalId);
    this._gcClientHelloIntervalId = null;
  }
  this._gcReady = false;
  this._user.gamesPlayed({
    games_played: [{}]
  });
};

// Handlers

var handlers = CSGOClient.prototype._handlers = {};

handlers[CSGO.EGCBaseClientMsg.k_EMsgGCClientWelcome] = function clientWelcomeHandler(message) {
  /* Response to our k_EMsgGCClientHello, now we can execute other GC commands. */

  // Only execute if _gcClientHelloIntervalID, otherwise it's already been handled (and we don't want to emit multiple 'ready');
  if (this._gcClientHelloIntervalId) {
    clearInterval(this._gcClientHelloIntervalId);
    this._gcClientHelloIntervalId = null;

    if (this.debug) {
      util.log("Received client welcome.");
    }
    this._gcReady = true;
    this.emit("ready");
  }
};

handlers[CSGO.EGCBaseClientMsg.k_EMsgGCClientConnectionStatus] = function gcClientConnectionStatus(message) {
  /* Catch and handle changes in connection status, cuz reasons u know. */

  var status = protos.CMsgConnectionStatus.decode(message).status;

  switch (status) {
    case CSGO.GCConnectionStatus.GCConnectionStatus_HAVE_SESSION:
      if (this.debug) {
        util.log("GC Connection Status regained.");
      }

      // Only execute if _gcClientHelloIntervalID, otherwise it's already been handled (and we don't want to emit multiple 'ready');
      if (this._gcClientHelloIntervalId) {
        clearInterval(this._gcClientHelloIntervalId);
        this._gcClientHelloIntervalId = null;

        this._gcReady = true;
        this.emit("ready");
      }
      break;

    default:
      if (this.debug) {
        util.log("GC Connection Status unreliable - " + status);
      }

      // Only execute if !_gcClientHelloIntervalID, otherwise it's already been handled (and we don't want to emit multiple 'unready');
      if (!this._gcClientHelloIntervalId) {
        this._gcClientHelloIntervalId = setInterval(this._sendClientHello, 2500); // Continually try regain GC session

        this._gcReady = false;
        this.emit("unready");
      }
      break;
  }
};

CSGO.CSGOClient = CSGOClient;

require("./handlers/match");
<|endoftext|>


<commit_before>var clone = require('lodash.clone');

var SUMMON = (function () {

  var commands = [];

  var escapeLuceneSyntax = function escapeLuceneSyntax(rawQueryString) {
    if (rawQueryString === undefined) {
      return undefined;
    }
    return rawQueryString.replace(luceneEscapeRegex, "\\$1");
  };

  var addCommand = function addCommand(commandName, queryString, els) {
    var command;
    if (queryString === undefined || queryString === null) {
      command = commandName+"()";
    } else {
      if (els === undefined) {
        els = defaultEscapeLucene;
      }
      command = commandName+"("+ (els ? escapeLuceneSyntax(queryString) : queryString)+")";
    }
    commands.push(command);
  };

  var clearAll = function clearAll() {
    commands = ["clearAll()"];
  };

  var defaultEscapeLucene = true;
  var luceneEscapeRegex = /([-+&|!(){}[\]^"~*?:\\])/g;

  var requestHeaders = {};
  var transport = undefined;

  var SESSION_HEADER_NAME = "x-summon-session-id";
  var SUMMON_ROLE_AUTH_HEADER_NAME = "x-summon-role-auth";

  var setSessionId = function setSessionId(id) {
    if (id === null || id === undefined) {
      delete requestHeaders[SESSION_HEADER_NAME];
    } else {
      requestHeaders[SESSION_HEADER_NAME] = id;
    }
  };

  var delegateSubmit = function delegateSubmit(fail, fun, instance) {
    fun.call(instance, fail, ret.submit, ret);
  }

  var submit = function submit(fail, auth) {
    //TODO cancel any pre-existing submit callbacks
    var len = commands.length;
    var url = "/2.0.0/search?";
    if (len > 0) {
      url += "s.cmd="+encodeURIComponent(commands[0]);
      for (var i = 1; i < len; i++) {
        url += encodeURIComponent(commands[i]);
      }
    }
    var headers;
console.log("asldkfjkasdf"+JSON.stringify(auth));
    if (auth === null || auth === undefined) {
      headers = requestHeaders;
    } else {
      headers = clone(requestHeaders);
      headers[SUMMON_ROLE_AUTH_HEADER_NAME] = auth.iv + ';' + auth.ciphertext;
    }
    transport(url, done, fail, headers);
  };

  var data = undefined;

  var callbacks = [];

  var addCallback = function addCallback(fun) {
    callbacks.push(fun);
    if (data !== undefined) {
      fun(data);
    }
  };

  var updateData = function updateData(val) {
    data = val;
    invokeCallbacks();
  };

  var invokeCallbacks = function invokeCallbacks() {
    var len = callbacks.length;
    for (var i = 0; i < len; i++) {
      callbacks[i](data);
    }
  };

  var done = function done(data) {
    setSessionId(data.sessionId);
    updateData(data);
  };

  var ret = {
    submit: submit,
    delegateSubmit: delegateSubmit,
    setTextQuery: function setTextQuery(queryString, escapeLuceneSyntax) {
      return addCommand('setTextQuery', queryString, escapeLuceneSyntax);
    },
    addFacetValueFilters: function addFacetValueFilters(facetValueFilters) {
      return addCommand('addFacetValueFilters', facetValueFilters, false);
    },
    setPageSize: function setPageSize(size) {
      return addCommand('setPageSize', size, false);
    },
    setHoldingsOnly: function setHoldingsOnly(holdingsOnly) {
      return addCommand('setHoldingsOnly', holdingsOnly, false);
    },
    clearAll: clearAll,
    setTransportFunction: function(fun) {
      transport = fun;
    },
    addCallback: addCallback,
    escapeLuceneSyntax: escapeLuceneSyntax
  };

  return ret;
})();

var jQuery = require('jquery');

SUMMON.setTransportFunction(function(url, done, fail, headers) {
  console.log("request URL: "+url);
  jQuery.ajax(url, {
    "headers": headers,
    "dataType": "json"
  }).done(done).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(errorThrown);
    if (fail !== undefined) {
      fail(errorThrown);
    }
  });
});

module.exports = SUMMON;

<commit_msg>added comma to the list of characters that need to be escaped for Lucene<commit_after>var clone = require('lodash.clone');

var SUMMON = (function () {

  var commands = [];

  var escapeLuceneSyntax = function escapeLuceneSyntax(rawQueryString) {
    if (rawQueryString === undefined) {
      return undefined;
    }
    return rawQueryString.replace(luceneEscapeRegex, "\\$1");
  };

  var addCommand = function addCommand(commandName, queryString, els) {
    var command;
    if (queryString === undefined || queryString === null) {
      command = commandName+"()";
    } else {
      if (els === undefined) {
        els = defaultEscapeLucene;
      }
      command = commandName+"("+ (els ? escapeLuceneSyntax(queryString) : queryString)+")";
    }
    commands.push(command);
  };

  var clearAll = function clearAll() {
    commands = ["clearAll()"];
  };

  var defaultEscapeLucene = true;
  var luceneEscapeRegex = /([-+&|!(){}[\]^"~*?:,\\])/g;

  var requestHeaders = {};
  var transport = undefined;

  var SESSION_HEADER_NAME = "x-summon-session-id";
  var SUMMON_ROLE_AUTH_HEADER_NAME = "x-summon-role-auth";

  var setSessionId = function setSessionId(id) {
    if (id === null || id === undefined) {
      delete requestHeaders[SESSION_HEADER_NAME];
    } else {
      requestHeaders[SESSION_HEADER_NAME] = id;
    }
  };

  var delegateSubmit = function delegateSubmit(fail, fun, instance) {
    fun.call(instance, fail, ret.submit, ret);
  }

  var submit = function submit(fail, auth) {
    //TODO cancel any pre-existing submit callbacks
    var len = commands.length;
    var url = "/2.0.0/search?";
    if (len > 0) {
      url += "s.cmd="+encodeURIComponent(commands[0]);
      for (var i = 1; i < len; i++) {
        url += encodeURIComponent(commands[i]);
      }
    }
    var headers;
console.log("asldkfjkasdf"+JSON.stringify(auth));
    if (auth === null || auth === undefined) {
      headers = requestHeaders;
    } else {
      headers = clone(requestHeaders);
      headers[SUMMON_ROLE_AUTH_HEADER_NAME] = auth.iv + ';' + auth.ciphertext;
    }
    transport(url, done, fail, headers);
  };

  var data = undefined;

  var callbacks = [];

  var addCallback = function addCallback(fun) {
    callbacks.push(fun);
    if (data !== undefined) {
      fun(data);
    }
  };

  var updateData = function updateData(val) {
    data = val;
    invokeCallbacks();
  };

  var invokeCallbacks = function invokeCallbacks() {
    var len = callbacks.length;
    for (var i = 0; i < len; i++) {
      callbacks[i](data);
    }
  };

  var done = function done(data) {
    setSessionId(data.sessionId);
    updateData(data);
  };

  var ret = {
    submit: submit,
    delegateSubmit: delegateSubmit,
    setTextQuery: function setTextQuery(queryString, escapeLuceneSyntax) {
      return addCommand('setTextQuery', queryString, escapeLuceneSyntax);
    },
    addFacetValueFilters: function addFacetValueFilters(facetValueFilters) {
      return addCommand('addFacetValueFilters', facetValueFilters, false);
    },
    setPageSize: function setPageSize(size) {
      return addCommand('setPageSize', size, false);
    },
    setHoldingsOnly: function setHoldingsOnly(holdingsOnly) {
      return addCommand('setHoldingsOnly', holdingsOnly, false);
    },
    clearAll: clearAll,
    setTransportFunction: function(fun) {
      transport = fun;
    },
    addCallback: addCallback,
    escapeLuceneSyntax: escapeLuceneSyntax
  };

  return ret;
})();

var jQuery = require('jquery');

SUMMON.setTransportFunction(function(url, done, fail, headers) {
  console.log("request URL: "+url);
  jQuery.ajax(url, {
    "headers": headers,
    "dataType": "json"
  }).done(done).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(errorThrown);
    if (fail !== undefined) {
      fail(errorThrown);
    }
  });
});

module.exports = SUMMON;

<|endoftext|>


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

'use strict';

// Packages
const chalk = require('chalk');
const clear = require('clear');
const CLI = require('clui');
const Spinner = CLI.Spinner;
const figlet = require('figlet');
const inquirer = require('inquirer');
const _ = require('lodash');
const git = require('simple-git')();
const touch = require('touch');
const fs = require('fs');
const download = require('download-git-repo');
const shell = require('shelljs');
const username = require('git-user-name');

// Files imports
const files = require('./lib/files');
const questions = require('./lib/questions');

// Declaring global variables
let gitDetected;
let projectName;
let projectDirectory;

// Clear terminal
clear();

// Init cli head
console.log(chalk.yellow(figlet.textSync('|| WASA-CLI ||', {horizontalLayout: 'full'})));
console.log(chalk.cyan('Welcome to the Wasa Builder. Let\'s initiliaze together your boilerplate !'));

// Check if there is this already a git repo
const wasaInit = () => {
  if (files.directoryExists('.git')) {
    gitDetected = true;
    askContinue();
  } else {
    askProjectName();
  }
}

// Ask continue (git repository detected)
const askContinue = () => {
  questions.gitContinue(function() {
    if (arguments[0].gitContinue) {
      askProjectName();
    } else {
      console.log(chalk.red.bold('Process aborted,') + ' we advise you to move to a new directory.');
      process.exit();
    }
  })
}

// Ask project name
const askProjectName = () => {
  questions.projectName(function() {
    projectName = arguments[0].projectName.toLowerCase();
    console.log(`Your project will be named ${chalk.blue.bold(projectName)}.`);
    askProjectDirectory();
  });
}

// Ask project location
const askProjectDirectory = () => {
  questions.projectDirectory(projectName, function() {
    if (arguments[0].projectDirectory.length == 0) {
      projectDirectory = projectName;
    } else {
      projectDirectory = arguments[0].projectDirectory.toLowerCase();
    }
    console.log('You project will be installed in the directory ' + chalk.blue.bold('./') + chalk.blue.bold(projectDirectory));
    if (gitDetected) {
      // if git detected skip add repo
      dlBoilerplate();
    } else {
      askProjectGit();
    }
  })
}

// Ask project git
const askProjectGit = () => {
  questions.projectGit(function() {
    if (arguments[0].projectGit == 1) {
      askGitRepo();
    } else {
      fs.mkdirSync(projectDirectory);
      dlBoilerplate();
    }
  })
}

// Ask git repository
const askGitRepo = () => {
  questions.gitRepo(function() {
    const gitRepo = arguments[0].gitRepo;
    // clone desired repository
    const status = new Spinner(chalk.white('Cloning repository, please wait...'));
    status.start();
    git.clone(gitRepo, projectDirectory).exec(function() {
      status.stop();
      console.log('Repository successfully cloned.');
      dlBoilerplate();
    });
  })
}

// W&S Agency Boilerplate Download
const dlBoilerplate = () => {
  console.log(chalk.blue.bold('We will now download the WASA Boilerplate.'));
  setTimeout(() => {
    const status = new Spinner(chalk.white('Downloading boilerplate, please wait...'));
    status.start();
    download('waitandseeagency/wasa-boilerplate#dev', `${projectDirectory}/`, function(err) {
      status.stop();
      if (err) {
        console.log('An error occured.');
      } else {
        console.log('We successfully downloaded the WASA Boilerplate.');
        initDependencies();
      }
    });
  }, 2000)
}

const initDependencies = () => {
  const current = process.cwd();
  try {
    process.chdir(current+'/'+projectDirectory);
  }
  catch (err) {
    console.log('chdir: ' + err);
  }
  console.log(chalk.blue.bold('We will know install the dependencies.'));
  setTimeout(() => {
    if (shell.exec('npm install').code !== 0) {
      shell.echo('Error: npm install failed :/ !');
      shell.exit(1);
    } else {
      console.log('Dependencies successfully installed.');
      updateProject();
    }
  })
}

const updateProject = () => {
  console.log(chalk.blue.bold('We are now making the final touches!'));
  fs.readFile('package.json', 'utf-8', function(err, data){
    if (err) throw err;

    const newValue = data
      .replace(/"name": "wasa-boilerplate"/g, `"name": "${projectName}"`)
      .replace(/"author": "Wait And See Agency"/g, `"author": "${username()}"`);

    fs.writeFile('package.json', newValue, 'utf-8', function (err) {
      if (err) throw err;
      console.log('Project install complete, you\'re all set !');
    });
  });
}

// Start wasa-cli
wasaInit();
<commit_msg>feat(cli): update loaders<commit_after>#!/usr/bin/env node

'use strict';

// Packages
const chalk = require('chalk');
const clear = require('clear');
const CLI = require('clui');
const Spinner = CLI.Spinner;
const figlet = require('figlet');
const inquirer = require('inquirer');
const _ = require('lodash');
const git = require('simple-git')();
const touch = require('touch');
const fs = require('fs');
const download = require('download-git-repo');
const shell = require('shelljs');
const username = require('git-user-name');

// Files imports
const files = require('./lib/files');
const questions = require('./lib/questions');

// Declaring global variables
let gitDetected;
let projectName;
let projectDirectory;

// Clear terminal
clear();

// Init cli head
console.log(chalk.yellow(figlet.textSync('|| WASA-CLI ||', {horizontalLayout: 'full'})));
console.log(chalk.cyan('Welcome to the Wasa Builder. Let\'s initiliaze together your boilerplate !'));

// Check if there is this already a git repo
const wasaInit = () => {
  if (files.directoryExists('.git')) {
    gitDetected = true;
    askContinue();
  } else {
    askProjectName();
  }
}

// Ask continue (git repository detected)
const askContinue = () => {
  questions.gitContinue(function() {
    if (arguments[0].gitContinue) {
      askProjectName();
    } else {
      console.log(chalk.red.bold('Process aborted,') + ' we advise you to move to a new directory.');
      process.exit();
    }
  })
}

// Ask project name
const askProjectName = () => {
  questions.projectName(function() {
    projectName = arguments[0].projectName.toLowerCase();
    console.log(`Your project will be named ${chalk.blue.bold(projectName)}.`);
    askProjectDirectory();
  });
}

// Ask project location
const askProjectDirectory = () => {
  questions.projectDirectory(projectName, function() {
    if (arguments[0].projectDirectory.length == 0) {
      projectDirectory = projectName;
    } else {
      projectDirectory = arguments[0].projectDirectory.toLowerCase();
    }
    console.log('You project will be installed in the directory ' + chalk.blue.bold('./') + chalk.blue.bold(projectDirectory));
    if (gitDetected) {
      // if git detected skip add repo
      dlBoilerplate();
    } else {
      askProjectGit();
    }
  })
}

// Ask project git
const askProjectGit = () => {
  questions.projectGit(function() {
    if (arguments[0].projectGit == 1) {
      askGitRepo();
    } else {
      fs.mkdirSync(projectDirectory);
      dlBoilerplate();
    }
  })
}

// Ask git repository
const askGitRepo = () => {
  questions.gitRepo(function() {
    const gitRepo = arguments[0].gitRepo;
    // clone desired repository
    const status = new Spinner(chalk.white('Cloning repository, please wait...'));
    status.start();
    git.clone(gitRepo, projectDirectory).exec(function() {
      status.stop();
      console.log('Repository successfully cloned.');
      dlBoilerplate();
    });
  })
}

// W&S Agency Boilerplate Download
const dlBoilerplate = () => {
  console.log(chalk.blue.bold('We will now download the WASA Boilerplate.'));
  setTimeout(() => {
    const status = new Spinner(chalk.white('Downloading boilerplate, please wait...'));
    status.start();
    download('waitandseeagency/wasa-boilerplate#dev', `${projectDirectory}/`, function(err) {
      status.stop();
      if (err) {
        console.log('An error occured.');
      } else {
        console.log('We successfully downloaded the WASA Boilerplate.');
        initDependencies();
      }
    });
  }, 2000)
}

const initDependencies = () => {
  const current = process.cwd();
  try {
    process.chdir(current+'/'+projectDirectory);
  }
  catch (err) {
    console.log('chdir: ' + err);
  }
  console.log(chalk.blue.bold('We will know install the dependencies. This might take a moment, please wait.'));
  setTimeout(() => {
    if (shell.exec('npm install').code !== 0) {
      shell.echo('Error: npm install failed :/ !');
      shell.exit(1);
    } else {
      console.log('Dependencies successfully installed.');
      updateProject();
    }
  })
}

const updateProject = () => {
  console.log(chalk.blue.bold('We are now making the final touches!'));
  const status = new Spinner(chalk.white('Please wait...'));
  status.start();
  setTimeout(() => {
    fs.readFile('package.json', 'utf-8', function(err, data){
      if (err) throw err;

      const newValue = data
      .replace(/"name": "wasa-boilerplate"/g, `"name": "${projectName}"`)
      .replace(/"author": "Wait And See Agency"/g, `"author": "${username()}"`);

      fs.writeFile('package.json', newValue, 'utf-8', function (err) {
        if (err) {
          throw err;
        } else {
          status.stop();
          console.log('Project install complete, you\'re all set !');
        }
      });
    });
  }, 1000);
}

// Start wasa-cli
wasaInit();
<|endoftext|>


<commit_before>// configuration
var config = require('./config.json');

// 3rd party
const express = require('express');
const app = express();
const fs = require('fs');
const ffmpeg = require('fluent-ffmpeg');

// classes
const DirEntry = require('./DirEntry.js');
const Directory = require('./Directory.js');
const MediaFile = require('./MediaFile.js');

app.get('/hello', function (req, res) {
	res.send('hello world!');
});

app.get('/dir', function (req, res) {
	var queryPath = req.query.path;
	if (typeof queryPath === 'undefined') {
		queryPath = '';
	}
	var realPath = config.baseDir + '/' + queryPath;

	var dirContents;
	try {
		dirContents = fs.readdirSync(realPath);
		dirContents.sort();
	} catch (Err) {
		res.send('Unable to read path ' + realPath);
		return;
	}

	var dirEntries = [];
	for (var fileName of dirContents) {
		var filePath = queryPath + '/' + fileName;
		var realPath = config.baseDir + '/' + filePath;
		var stat = fs.statSync(realPath);
		if (stat.isDirectory()) {
			var dirUrl = req.protocol + '://' + req.hostname + ':' + req.socket.localPort + '/dir?path=' + encodeURIComponent(queryPath + '/' + fileName);
			dirEntries.push(new Directory(fileName, realPath, dirUrl));
		} else if (stat.isFile()) {
			var extIndex = fileName.lastIndexOf('.');
			if (extIndex > 0) {
				var ext = fileName.substring(extIndex + 1);
				if (config.extensions.indexOf(ext) > -1) {
					var playUrl = req.protocol + '://' + req.hostname + ':' + req.socket.localPort + '/play?path=' + encodeURIComponent(queryPath + '/' + fileName);
					dirEntries.push(new MediaFile(fileName, realPath, playUrl));
				}
			}
		}
	}
	res.contentType('application/json');
	res.send(JSON.stringify(dirEntries, null, 4));
});

app.get('/play', function (req, res) {
	res.header('Accept-Ranges', 'bytes');
	res.setHeader('Content-Type', 'audio/mpeg');

	var range = req.headers.range;
	if (range == null) {
		range = 'bytes=0-';
	}
	// console.log('range: ' + range);
	var equalsIndex = range.indexOf('=');
	var dashIndex = range.indexOf('-');
	var startByte = Number(range.substring(equalsIndex + 1, dashIndex));
	var endByte = range.substring(dashIndex + 1);

	var queryPath = req.query.path;
	var realPath = config.baseDir + '/' + queryPath;
	var extIndex = realPath.lastIndexOf('.');
	var ext = null;
	if (extIndex > 0) {
		ext = realPath.substring(extIndex + 1);
	}
	if (ext == null || ext == 'mp3') {
		// read file directly and send as is
		var fileSize = fs.statSync(realPath).size;
		if (endByte.length == 0) {
			endByte = fileSize - 1;
		} else {
			endByte = Number(endByte);
		}
		// console.log('startByte: ' + startByte);
		// console.log('endByte:   ' + endByte);
		res.setHeader('Content-Range', 'bytes ' + startByte + '-' + endByte + '/' + fileSize);
		res.setHeader('Content-Length', endByte - startByte + 1);
		res.status(206);
		fs.createReadStream(realPath, { start: startByte, end: endByte }).pipe(res);
	} else {
		// convert to mp3 using ffmpeg
		var duration = req.query.duration;
		var fileSize = Math.floor(duration * (256 * 1000 / 8));
		if (endByte.length == 0) {
			endByte = fileSize - 1;
		} else {
			endByte = Number(endByte);
		}
		// console.log('startByte: ' + startByte);
		// console.log('endByte:   ' + endByte);
		res.setHeader('Content-Range', 'bytes ' + startByte + '-' + endByte + '/' + fileSize);
		res.setHeader('Content-Length', endByte - startByte + 1);
		res.status(206);

		var startTime = 0;
		if (startByte > 0) {
			startTime = startByte / (256 * 1000 / 8);
		}
		var endTime = endByte / (256 * 1000 / 8);
		// console.log('startTime: ' + startTime);
		// console.log('endTime:   ' + endTime);

		var command = ffmpeg(realPath).audioCodec('libmp3lame').audioChannels(2)
			.audioFrequency(44100).audioBitrate(256).format('mp3').noVideo()
			.seek(startTime).duration(endTime - startTime)
			.on('start', function () {
				console.log('pid: ' + command.pid);
				//console.log('Processing started:  ' + realPath);
			})
			.on('error', function (err) {
				if (!err.toString().includes('Output stream closed')) {
					console.log('Processing error:    ' + realPath + ' : ' + err.message);
				}
			})
			.on('end', function () {
				//console.log('Processing finished: ' + realPath);
			})
			.pipe(res, { end: true });

		// kill ffmpeg after 10 minutes just in case
		setTimeout(function () {
			command.kill('SIGKILL');
			console.log('ffmpeg process reached timeout and was killed.');
		}, 600000);
	}
});

// serve client-side web app
app.use(express.static('www'));
// serve client-side dependencies
app.use('/node_modules', express.static('node_modules'));

app.listen(3000, function () {
	console.log('node_music_streamer running on port 3000...');
});
<commit_msg>more debugging<commit_after>// configuration
var config = require('./config.json');

// 3rd party
const express = require('express');
const app = express();
const fs = require('fs');
const ffmpeg = require('fluent-ffmpeg');

// classes
const DirEntry = require('./DirEntry.js');
const Directory = require('./Directory.js');
const MediaFile = require('./MediaFile.js');

app.get('/hello', function (req, res) {
	res.send('hello world!');
});

app.get('/dir', function (req, res) {
	var queryPath = req.query.path;
	if (typeof queryPath === 'undefined') {
		queryPath = '';
	}
	var realPath = config.baseDir + '/' + queryPath;

	var dirContents;
	try {
		dirContents = fs.readdirSync(realPath);
		dirContents.sort();
	} catch (Err) {
		res.send('Unable to read path ' + realPath);
		return;
	}

	var dirEntries = [];
	for (var fileName of dirContents) {
		var filePath = queryPath + '/' + fileName;
		var realPath = config.baseDir + '/' + filePath;
		var stat = fs.statSync(realPath);
		if (stat.isDirectory()) {
			var dirUrl = req.protocol + '://' + req.hostname + ':' + req.socket.localPort + '/dir?path=' + encodeURIComponent(queryPath + '/' + fileName);
			dirEntries.push(new Directory(fileName, realPath, dirUrl));
		} else if (stat.isFile()) {
			var extIndex = fileName.lastIndexOf('.');
			if (extIndex > 0) {
				var ext = fileName.substring(extIndex + 1);
				if (config.extensions.indexOf(ext) > -1) {
					var playUrl = req.protocol + '://' + req.hostname + ':' + req.socket.localPort + '/play?path=' + encodeURIComponent(queryPath + '/' + fileName);
					dirEntries.push(new MediaFile(fileName, realPath, playUrl));
				}
			}
		}
	}
	res.contentType('application/json');
	res.send(JSON.stringify(dirEntries, null, 4));
});

app.get('/play', function (req, res) {
	res.header('Accept-Ranges', 'bytes');
	res.setHeader('Content-Type', 'audio/mpeg');

	var range = req.headers.range;
	if (range == null) {
		range = 'bytes=0-';
	}
	// console.log('range: ' + range);
	var equalsIndex = range.indexOf('=');
	var dashIndex = range.indexOf('-');
	var startByte = Number(range.substring(equalsIndex + 1, dashIndex));
	var endByte = range.substring(dashIndex + 1);

	var queryPath = req.query.path;
	var realPath = config.baseDir + '/' + queryPath;
	var extIndex = realPath.lastIndexOf('.');
	var ext = null;
	if (extIndex > 0) {
		ext = realPath.substring(extIndex + 1);
	}
	if (ext == null || ext == 'mp3') {
		// read file directly and send as is
		var fileSize = fs.statSync(realPath).size;
		if (endByte.length == 0) {
			endByte = fileSize - 1;
		} else {
			endByte = Number(endByte);
		}
		// console.log('startByte: ' + startByte);
		// console.log('endByte:   ' + endByte);
		res.setHeader('Content-Range', 'bytes ' + startByte + '-' + endByte + '/' + fileSize);
		res.setHeader('Content-Length', endByte - startByte + 1);
		res.status(206);
		fs.createReadStream(realPath, { start: startByte, end: endByte }).pipe(res);
	} else {
		// convert to mp3 using ffmpeg
		var duration = req.query.duration;
		var fileSize = Math.floor(duration * (256 * 1000 / 8));
		if (endByte.length == 0) {
			endByte = fileSize - 1;
		} else {
			endByte = Number(endByte);
		}
		// console.log('startByte: ' + startByte);
		// console.log('endByte:   ' + endByte);
		res.setHeader('Content-Range', 'bytes ' + startByte + '-' + endByte + '/' + fileSize);
		res.setHeader('Content-Length', endByte - startByte + 1);
		res.status(206);

		var startTime = 0;
		if (startByte > 0) {
			startTime = startByte / (256 * 1000 / 8);
		}
		var endTime = endByte / (256 * 1000 / 8);
		// console.log('startTime: ' + startTime);
		// console.log('endTime:   ' + endTime);

		var command = ffmpeg(realPath).audioCodec('libmp3lame').audioChannels(2)
			.audioFrequency(44100).audioBitrate(256).format('mp3').noVideo()
			.seek(startTime).duration(endTime - startTime)
			.on('start', function () {
				console.log('pid: ' + command.ffmpegProc.pid);
				//console.log('Processing started:  ' + realPath);
			})
			.on('error', function (err) {
				if (!err.toString().includes('Output stream closed')) {
					console.log('Processing error:    ' + realPath + ' : ' + err.message);
				}
			})
			.on('end', function () {
				//console.log('Processing finished: ' + realPath);
			})
			.pipe(res, { end: true });

		// kill ffmpeg after 10 minutes just in case
		setTimeout(function () {
			command.kill('SIGKILL');
			console.log('ffmpeg process reached timeout and was killed.');
		}, 600000);
	}
});

// serve client-side web app
app.use(express.static('www'));
// serve client-side dependencies
app.use('/node_modules', express.static('node_modules'));

app.listen(3000, function () {
	console.log('node_music_streamer running on port 3000...');
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var Promise = require('rsvp').Promise;
var Plugin = require('broccoli-plugin');
var helpers = require('broccoli-kitchen-sink-helpers');
var walkSync = require('walk-sync');
var mapSeries = require('promise-map-series');
var symlinkOrCopySync = require('symlink-or-copy').sync;
var copyDereferenceSync = require('copy-dereference').sync;
var Cache = require('./lib/cache');
var debugGenerator = require('debug');
var keyForFile = require('./lib/key-for-file');
var md5Hex = require('md5-hex');
var Processor = require('./lib/processor');
var defaultProccessor = require('./lib/strategies/default');
var hashForDep = require('hash-for-dep');

module.exports = Filter;

Filter.prototype = Object.create(Plugin.prototype);
Filter.prototype.constructor = Filter;
function Filter(inputTree, options) {
  if (!this || !(this instanceof Filter) ||
      Object.getPrototypeOf(this) === Filter.prototype) {
    throw new TypeError('Filter is an abstract class and must be sub-classed');
  }

  var name = 'broccoli-persistent-filter:' + (this.constructor.name);
  if (this.description) {
    name += ' > [' + this.description + ']';
  }

  this._debug = debugGenerator(name);

  Plugin.call(this, [inputTree]);

  this.processor = new Processor(options);
  this.processor.setStrategy(defaultProccessor);

  /* Destructuring assignment in node 0.12.2 would be really handy for this! */
  if (options) {
    if (options.extensions != null)
      this.extensions = options.extensions;
    if (options.targetExtension != null)
      this.targetExtension = options.targetExtension;
    if (options.inputEncoding != null)
      this.inputEncoding = options.inputEncoding;
    if (options.outputEncoding != null)
      this.outputEncoding = options.outputEncoding;
    if (options.persist) {
      this.processor.setStrategy(require('./lib/strategies/persistent'));
    }
  }

  this.processor.init(this);

  this._cache = new Cache();
  this._canProcessCache = Object.create(null);
  this._destFilePathCache = Object.create(null);
}

Filter.prototype.build = function build() {
  var self = this;
  var srcDir = this.inputPaths[0];
  var destDir = this.outputPath;
  var paths = walkSync(srcDir);

  this._cache.deleteExcept(paths).forEach(function(key) {
    fs.unlinkSync(this.cachePath + '/' + key);
  }, this);

  return mapSeries(paths, function rebuildEntry(relativePath) {
    var destPath = destDir + '/' + relativePath;
    if (relativePath.slice(-1) === '/') {
      mkdirp.sync(destPath);
    } else {
      if (self.canProcessFile(relativePath)) {
        return self.processAndCacheFile(srcDir, destDir, relativePath);
      } else {
        var srcPath = srcDir + '/' + relativePath;
        symlinkOrCopySync(srcPath, destPath);
      }
    }
  });
};

/*
 The cache key to be used for this plugins set of dependencies. By default
 a hash is created based on `package.json` and nested dependencies.

 Implement this to customize the cache key (for example if you need to
 account for non-NPM dependencies).

 @public
 @method cacheKey
 @returns {String}
 */
Filter.prototype.cacheKey = function() {
  return hashForDep(this.baseDir());
};

/* @public
 *
 * @method baseDir
 * @returns {String} absolute path to the root of the filter...
 */
Filter.prototype.baseDir = function() {
  throw Error('Filter must implement prototype.baseDir');
};

/**
 * @public
 *
 * optionally override this to build a more rhobust cache key
 * @param  {String} string The contents of a file that is being processed
 * @return {String}        A cache key
 */
Filter.prototype.cacheKeyProcessString = function(string, relativePath) {
  return md5Hex(string + 0x00 + relativePath);
};

Filter.prototype.canProcessFile =
    function canProcessFile(relativePath) {
  return !!this.getDestFilePath(relativePath);
};

Filter.prototype.getDestFilePath = function getDestFilePath(relativePath) {
  if (this.extensions == null) return relativePath;

  for (var i = 0, ii = this.extensions.length; i < ii; ++i) {
    var ext = this.extensions[i];
    if (relativePath.slice(-ext.length - 1) === '.' + ext) {
      if (this.targetExtension != null) {
        relativePath =
            relativePath.slice(0, -ext.length) + this.targetExtension;
      }
      return relativePath;
    }
  }
  return null;
};

Filter.prototype.processAndCacheFile =
    function processAndCacheFile(srcDir, destDir, relativePath) {
  var self = this;
  var cacheEntry = this._cache.get(relativePath);
  var outputRelativeFile = self.getDestFilePath(relativePath);

  if (cacheEntry) {
    var hashResult = hash(srcDir, cacheEntry.inputFile);

    if (cacheEntry.hash.hash === hashResult.hash) {
      this._debug('cache hit: %s', relativePath);

      return symlinkOrCopyFromCache(cacheEntry, destDir, outputRelativeFile);
    } else {
      this._debug('cache miss: %s \n  - previous: %o \n  - next:     %o ', relativePath, cacheEntry.hash.key, hashResult.key);
    }

  } else {
    this._debug('cache prime: %s', relativePath);
  }

  return Promise.resolve().
      then(function asyncProcessFile() {
        return self.processFile(srcDir, destDir, relativePath);
      }).
      then(copyToCache,
      // TODO(@caitp): error wrapper is for API compat, but is not particularly
      // useful.
      // istanbul ignore next
      function asyncProcessFileErrorWrapper(e) {
        if (typeof e !== 'object') e = new Error('' + e);
        e.file = relativePath;
        e.treeDir = srcDir;
        throw e;
      });

  function copyToCache() {
    var entry = {
      hash: hash(srcDir, relativePath),
      inputFile: relativePath,
      outputFile: destDir + '/' + outputRelativeFile,
      cacheFile: self.cachePath + '/' + outputRelativeFile
    };

    if (fs.existsSync(entry.cacheFile)) {
      fs.unlinkSync(entry.cacheFile);
    } else {
      mkdirp.sync(path.dirname(entry.cacheFile));
    }

    copyDereferenceSync(entry.outputFile, entry.cacheFile);

    return self._cache.set(relativePath, entry);
  }
};

Filter.prototype.processFile =
    function processFile(srcDir, destDir, relativePath) {
  var self = this;
  var inputEncoding = this.inputEncoding;
  var outputEncoding = this.outputEncoding;
  if (inputEncoding === void 0) inputEncoding = 'utf8';
  if (outputEncoding === void 0) outputEncoding = 'utf8';
  var contents = fs.readFileSync(
      srcDir + '/' + relativePath, { encoding: inputEncoding });

  return this.processor.processString(this, contents, relativePath).then(function asyncOutputFilteredFile(result) {
    var outputString = result.string;
    var outputPath = self.getDestFilePath(relativePath);
    if (outputPath == null) {
      throw new Error('canProcessFile("' + relativePath + '") is true, but getDestFilePath("' + relativePath + '") is null');
    }
    outputPath = destDir + '/' + outputPath;
    mkdirp.sync(path.dirname(outputPath));
    fs.writeFileSync(outputPath, outputString, {
      encoding: outputEncoding
    });

    return self.processor.done(self, result);
  });
};

Filter.prototype.processString =
    function unimplementedProcessString(contents, relativePath) {
  throw new Error(
      'When subclassing cauliflower-filter you must implement the ' +
      '`processString()` method.');
};

function hash(src, filePath) {
  var path = src + '/' + filePath;
  var key = keyForFile(path);

  return {
    key: key,
    hash: helpers.hashStrings([
      path,
      key.size,
      key.mode,
      key.mtime
    ])
  };
}

function symlinkOrCopyFromCache(entry, dest, relativePath) {
  mkdirp.sync(path.dirname(entry.outputFile));

  symlinkOrCopySync(entry.cacheFile, dest + '/' + relativePath);
}
<commit_msg>allow the strategy to return a string or promise (while still catching exceptions as we should)<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var Promise = require('rsvp').Promise;
var Plugin = require('broccoli-plugin');
var helpers = require('broccoli-kitchen-sink-helpers');
var walkSync = require('walk-sync');
var mapSeries = require('promise-map-series');
var symlinkOrCopySync = require('symlink-or-copy').sync;
var copyDereferenceSync = require('copy-dereference').sync;
var Cache = require('./lib/cache');
var debugGenerator = require('debug');
var keyForFile = require('./lib/key-for-file');
var md5Hex = require('md5-hex');
var Processor = require('./lib/processor');
var defaultProccessor = require('./lib/strategies/default');
var hashForDep = require('hash-for-dep');

module.exports = Filter;

Filter.prototype = Object.create(Plugin.prototype);
Filter.prototype.constructor = Filter;
function Filter(inputTree, options) {
  if (!this || !(this instanceof Filter) ||
      Object.getPrototypeOf(this) === Filter.prototype) {
    throw new TypeError('Filter is an abstract class and must be sub-classed');
  }

  var name = 'broccoli-persistent-filter:' + (this.constructor.name);
  if (this.description) {
    name += ' > [' + this.description + ']';
  }

  this._debug = debugGenerator(name);

  Plugin.call(this, [inputTree]);

  this.processor = new Processor(options);
  this.processor.setStrategy(defaultProccessor);

  /* Destructuring assignment in node 0.12.2 would be really handy for this! */
  if (options) {
    if (options.extensions != null)
      this.extensions = options.extensions;
    if (options.targetExtension != null)
      this.targetExtension = options.targetExtension;
    if (options.inputEncoding != null)
      this.inputEncoding = options.inputEncoding;
    if (options.outputEncoding != null)
      this.outputEncoding = options.outputEncoding;
    if (options.persist) {
      this.processor.setStrategy(require('./lib/strategies/persistent'));
    }
  }

  this.processor.init(this);

  this._cache = new Cache();
  this._canProcessCache = Object.create(null);
  this._destFilePathCache = Object.create(null);
}

Filter.prototype.build = function build() {
  var self = this;
  var srcDir = this.inputPaths[0];
  var destDir = this.outputPath;
  var paths = walkSync(srcDir);

  this._cache.deleteExcept(paths).forEach(function(key) {
    fs.unlinkSync(this.cachePath + '/' + key);
  }, this);

  return mapSeries(paths, function rebuildEntry(relativePath) {
    var destPath = destDir + '/' + relativePath;
    if (relativePath.slice(-1) === '/') {
      mkdirp.sync(destPath);
    } else {
      if (self.canProcessFile(relativePath)) {
        return self.processAndCacheFile(srcDir, destDir, relativePath);
      } else {
        var srcPath = srcDir + '/' + relativePath;
        symlinkOrCopySync(srcPath, destPath);
      }
    }
  });
};

/*
 The cache key to be used for this plugins set of dependencies. By default
 a hash is created based on `package.json` and nested dependencies.

 Implement this to customize the cache key (for example if you need to
 account for non-NPM dependencies).

 @public
 @method cacheKey
 @returns {String}
 */
Filter.prototype.cacheKey = function() {
  return hashForDep(this.baseDir());
};

/* @public
 *
 * @method baseDir
 * @returns {String} absolute path to the root of the filter...
 */
Filter.prototype.baseDir = function() {
  throw Error('Filter must implement prototype.baseDir');
};

/**
 * @public
 *
 * optionally override this to build a more rhobust cache key
 * @param  {String} string The contents of a file that is being processed
 * @return {String}        A cache key
 */
Filter.prototype.cacheKeyProcessString = function(string, relativePath) {
  return md5Hex(string + 0x00 + relativePath);
};

Filter.prototype.canProcessFile =
    function canProcessFile(relativePath) {
  return !!this.getDestFilePath(relativePath);
};

Filter.prototype.getDestFilePath = function getDestFilePath(relativePath) {
  if (this.extensions == null) return relativePath;

  for (var i = 0, ii = this.extensions.length; i < ii; ++i) {
    var ext = this.extensions[i];
    if (relativePath.slice(-ext.length - 1) === '.' + ext) {
      if (this.targetExtension != null) {
        relativePath =
            relativePath.slice(0, -ext.length) + this.targetExtension;
      }
      return relativePath;
    }
  }
  return null;
};

Filter.prototype.processAndCacheFile =
    function processAndCacheFile(srcDir, destDir, relativePath) {
  var self = this;
  var cacheEntry = this._cache.get(relativePath);
  var outputRelativeFile = self.getDestFilePath(relativePath);

  if (cacheEntry) {
    var hashResult = hash(srcDir, cacheEntry.inputFile);

    if (cacheEntry.hash.hash === hashResult.hash) {
      this._debug('cache hit: %s', relativePath);

      return symlinkOrCopyFromCache(cacheEntry, destDir, outputRelativeFile);
    } else {
      this._debug('cache miss: %s \n  - previous: %o \n  - next:     %o ', relativePath, cacheEntry.hash.key, hashResult.key);
    }

  } else {
    this._debug('cache prime: %s', relativePath);
  }

  return Promise.resolve().
      then(function asyncProcessFile() {
        return self.processFile(srcDir, destDir, relativePath);
      }).
      then(copyToCache,
      // TODO(@caitp): error wrapper is for API compat, but is not particularly
      // useful.
      // istanbul ignore next
      function asyncProcessFileErrorWrapper(e) {
        if (typeof e !== 'object') e = new Error('' + e);
        e.file = relativePath;
        e.treeDir = srcDir;
        throw e;
      });

  function copyToCache() {
    var entry = {
      hash: hash(srcDir, relativePath),
      inputFile: relativePath,
      outputFile: destDir + '/' + outputRelativeFile,
      cacheFile: self.cachePath + '/' + outputRelativeFile
    };

    if (fs.existsSync(entry.cacheFile)) {
      fs.unlinkSync(entry.cacheFile);
    } else {
      mkdirp.sync(path.dirname(entry.cacheFile));
    }

    copyDereferenceSync(entry.outputFile, entry.cacheFile);

    return self._cache.set(relativePath, entry);
  }
};

function invoke(context, fn, args) {
  return new Promise(function(resolve) {
    resolve(fn.apply(context, args));
  });
}

Filter.prototype.processFile =
    function processFile(srcDir, destDir, relativePath) {
  var self = this;
  var inputEncoding = this.inputEncoding;
  var outputEncoding = this.outputEncoding;
  if (inputEncoding === void 0) inputEncoding = 'utf8';
  if (outputEncoding === void 0) outputEncoding = 'utf8';
  var contents = fs.readFileSync(
      srcDir + '/' + relativePath, { encoding: inputEncoding });

  var string = invoke(this.processor, this.processor.processString, [this, contents, relativePath]);

  return string.then(function asyncOutputFilteredFile(result) {
    var outputString = result.string;
    var outputPath = self.getDestFilePath(relativePath);
    if (outputPath == null) {
      throw new Error('canProcessFile("' + relativePath + '") is true, but getDestFilePath("' + relativePath + '") is null');
    }
    outputPath = destDir + '/' + outputPath;
    mkdirp.sync(path.dirname(outputPath));
    fs.writeFileSync(outputPath, outputString, {
      encoding: outputEncoding
    });

    return self.processor.done(self, result);
  });
};

Filter.prototype.processString =
    function unimplementedProcessString(contents, relativePath) {
  throw new Error(
      'When subclassing cauliflower-filter you must implement the ' +
      '`processString()` method.');
};

function hash(src, filePath) {
  var path = src + '/' + filePath;
  var key = keyForFile(path);

  return {
    key: key,
    hash: helpers.hashStrings([
      path,
      key.size,
      key.mode,
      key.mtime
    ])
  };
}

function symlinkOrCopyFromCache(entry, dest, relativePath) {
  mkdirp.sync(path.dirname(entry.outputFile));

  symlinkOrCopySync(entry.cacheFile, dest + '/' + relativePath);
}
<|endoftext|>


<commit_before><commit_msg>adding source to index.js<commit_after>/*jslint node: true */
'use strict';

// Declare variables used
var	express,
    app,
	port,
	shortid,
	base_url,
	bodyParser,
	client,
	rtg;

// initializing the variables
express = require('express');
app = express();
port = process.env.PORT || 5000;
shortid = require('shortid');
bodyParser = require('body-parser');
base_url = process.env.BASE_URL || 'http://localhost:5000';

// Set up connection to Redis
if (process.env.REDISTOGO_URL) {
  rtg  = require("url").parse(process.env.REDISTOGO_URL);
  client = require("redis").createClient(rtg.port, rtg.hostname);
  client.auth(rtg.auth.split(":")[1]);
} else {
  client = require('redis').createClient();
}

// Set up templating
app.set('views', __dirname + '/views');
app.set('view engine', "jade");
app.engine('jade', require('jade').__express);

// Set URL
app.set('base_url', base_url);

// Handle POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

// Define index route
app.get('/', function (req, res) {
  res.render('index');
});

// Serve static files
app.use(express.static(__dirname + '/static'));

// Listen
app.listen(port);
console.log('Listening on port ' + port);
<|endoftext|>