<commit_before>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
    elements - An array of Elements.
  @credit:
    Prism, Highlight, SHJS, Rainbow, Prettify
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header4': {pattern: /\#{4,}/gm, regex: /\#{4,}.+/gm},
    'header3': {pattern: /\#{3}/gm, regex: /\#{3}.+/gm},
    'header2': {pattern: /\#{2}/gm, regex: /\#{2}.+/gm},
    'header1': {pattern: /\#/gm, regex: /\#.+/gm}
  };
  var style = {
    'bold': {pattern: /\*{2}/gm, regex: /\*{2}(.*?)\*{2}/gm},
    'italic': {pattern: /\*/gm, regex: /\*(.*?)\*/gm},
    'underline': {pattern: /\_/gm, regex: /\_{2}(.*?)\_{2}/gm},
    'strike': {pattern: /\~/gm, regex: /\~{2}(.*?)\~{2}/gm},
    'highlight': {pattern: /\=/gm, regex: /\={2}(.*?)\={2}/gm},
    'superscript': {pattern: /\+/gm, regex: /\+{2}(.*?)\+{2}/gm},
    'subscript': {pattern: /\-/gm, regex: /\-{2}(.*?)\-{2}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /[]/gm, regex: /^\-{4,}/gm},
    'rule-dash': {pattern: /[]/gm, regex: /^\.{4,}/gm},
    'rule-dotted': {pattern: /[]/gm, regex: /^\.{4,}/gm}
  };
  var quote = {
    'quote-code': {pattern: /\`/gm, regex: /\`(.*?)\`/gm},
    'quote-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\[([\s\S]*?)\]\}/gm},
    'quote-plain': {pattern: /(\{\[|\]\})/gm, regex: /\{\[([\s\S]*?)\]\}/gm}
  };
  var code = {
    'code-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\(([\s\S]*?)\)\}/gm},
    'code-plain': {pattern: /(\{\(|\)\})/gm, regex: /\{\(([\s\S]*?)\)\}/gm}
  };
  var list = {
    'list-solid': {pattern: /(\-|\n)/gm, regex: /(^\-(?!\-{3,}).+\n){1,}/gm},
    'list-empty': {pattern: /(\*|\n)/gm, regex: /(^\*(?!\*{3,}).+\n){1,}/gm},
    'list-square': {pattern: /(\#|\n)/gm, regex: /(^\#(?!\#{3,}).+\n){1,}/gm},
    'list-number': {pattern: /(\0\.|\n)/gm, regex: /(^\0\..+\n){1,}/gm},
    'list-roman': {pattern: /(\1\.|\n)/gm, regex: /(^\1\..+\n){1,}/gm},
    'list-letter': {pattern: /(\a\.|\n)/gm, regex: /(^\a\..+\n){1,}/gm},
    'checklist': {pattern: /(\[[Xx\s]?\]|\n)/gm, regex: /(^\[[Xx\s]?\].+\n){1,}/gm}
  };
  var image = {
    'image': {pattern: /[]/gm, regex: /\!\[(.*?)\]\((.*?)\)/gm}
  };
  var link = {
    'url-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)/gm},
    'url-plain': {pattern: /[]/gm, regex: /\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b/gm},
    'email': {pattern: /[]/gm, regex: /\b(([\w\d\.\_\%\+\-]+)\@([\w\d\.\-]+)(\.\w{2,}))\b/gm}
  };

  /*============================================================
  ============================Private===========================
  ============================================================*/

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Quote=============================
  ============================================================*/
  exports.Quote = function(doc) {
    for (key in quote) {
      doc = doc.replace(quote[key].regex, function(match) {
        if (key == 'quote-code') {
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key + ' nohighlight language-none';
          return '' + exports.Trim(temp) + '';
        } else if (key == 'quote-extra') {
          var extra = exports.Prepare(match).split(']{['),
            credit = extra[0].split('[')[1],
            quote = extra[1].split(']}')[0],
            classes = prefix + key;
          return '
"' + exports.Trim(quote) + '"
' + exports.Trim(credit) + '
';
        } else {
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key;
          return '
"' + exports.Trim(temp) + '"
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Code==============================
  ============================================================*/
  exports.Code = function(doc) {
    for (key in code) {
      doc = doc.replace(code[key].regex, function(match) {
        if (key == 'code-extra') {
          var extra = exports.Prepare(match).split(']{('),
            first = extra[0].split('[')[1].split('|'),
            second = extra[1].split(')}')[0],
            language = exports.Trim(first[0]).toLowerCase(),
            service = exports.Trim(first[1]).toLowerCase(),
            classes = prefix + key + ' language-' + language + ' sh_' + language + ' prettyprint lang-' + language,
            dataClasses = language;
          exports.LoadScript('Syntax/' + service + '/script.js');
          exports.LoadStyle('Syntax/' + service + '/' + exports.theme + '.css');
          return '
' + second + '
';
        } else {
          var temp = exports.Prepare(match).replace(code[key].pattern, ''),
            classes = 'nohighlight language-none';
          return '
' + temp + '
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in list) {
      doc = doc.replace(list[key].regex, function(match) {
        if (key == 'list-solid' || key == 'list-empty' || key == 'list-square') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else if (key == 'list-number' || key == 'list-roman' || key == 'list-letter') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else {
          return '' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(/\[[Xx\s]?\]/gm, ''),
              tag = (new RegExp(/\[\s?\]/gm)).test(line) ? 'unchecked' : 'checked';
            return '' + exports.Trim(temp) + '';
          }) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Image=============================
  ============================================================*/
  exports.Image = function(doc) {
    for (key in image) {
      doc = doc.replace(image[key].regex, function(match) {
        var extra = exports.Prepare(match).split(']('),
          alt = exports.Trim(extra[0].split('![')[1]).toLowerCase(),
          path = exports.Trim(extra[1].split(')')[0]).toLowerCase();
        return '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    for (key in link) {
      doc = doc.replace(link[key].regex, function(match) {
        if (key == 'url-extra') {
          var extra = exports.Prepare(match).split(']('),
            title = extra[0].split('[')[1],
            url = extra[1].split(']')[0];
          return '' + exports.Trim(title) + '';
        } else {
          return '' + exports.Trim(match) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/\n/gm, '
');
  };

  /*============================================================
  ============================Syntax============================
  ============================================================*/
  exports.Syntax = function(elements) {
    for (var a = 0; a < elements.length; a++) {
      var element = elements[a],
        code = element.innerHTML,
        fixed = code.replace(/\
/gm, '\n');
      element.innerHTML = fixed;
    }
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<commit_msg>Update extension.js<commit_after>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
    elements - An array of Elements.
  @credit:
    Prism, Highlight, SHJS, Rainbow, Prettify
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header4': {pattern: /\#{4,}/gm, regex: /\#{4,}.+/gm},
    'header3': {pattern: /\#{3}/gm, regex: /\#{3}.+/gm},
    'header2': {pattern: /\#{2}/gm, regex: /\#{2}.+/gm},
    'header1': {pattern: /\#/gm, regex: /\#.+/gm}
  };
  var style = {
    'bold': {pattern: /\*{2}/gm, regex: /\*{2}(.*?)\*{2}/gm},
    'italic': {pattern: /\*/gm, regex: /\*(.*?)\*/gm},
    'underline': {pattern: /\_/gm, regex: /\_{2}(.*?)\_{2}/gm},
    'strike': {pattern: /\~/gm, regex: /\~{2}(.*?)\~{2}/gm},
    'highlight': {pattern: /\=/gm, regex: /\={2}(.*?)\={2}/gm},
    'superscript': {pattern: /\+/gm, regex: /\+{2}(.*?)\+{2}/gm},
    'subscript': {pattern: /\-/gm, regex: /\-{2}(.*?)\-{2}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /[]/gm, regex: /^\-{4,}/gm},
    'rule-dash': {pattern: /[]/gm, regex: /^\.{4,}/gm},
    'rule-dotted': {pattern: /[]/gm, regex: /^\.{4,}/gm}
  };
  var quote = {
    'quote-code': {pattern: /\`/gm, regex: /\`(.*?)\`/gm},
    'quote-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\[([\s\S]*?)\]\}/gm},
    'quote-plain': {pattern: /(\{\[|\]\})/gm, regex: /\{\[([\s\S]*?)\]\}/gm}
  };
  var code = {
    'code-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\{\(([\s\S]*?)\)\}/gm},
    'code-plain': {pattern: /(\{\(|\)\})/gm, regex: /\{\(([\s\S]*?)\)\}/gm}
  };
  var list = {
    'list-solid': {pattern: /(\-|\n)/gm, regex: /(^\-(?!\-{3,}).+\n){1,}/gm},
    'list-empty': {pattern: /(\*|\n)/gm, regex: /(^\*(?!\*{3,}).+\n){1,}/gm},
    'list-square': {pattern: /(\#|\n)/gm, regex: /(^\#(?!\#{3,}).+\n){1,}/gm},
    'list-number': {pattern: /(\0\.|\n)/gm, regex: /(^\0\..+\n){1,}/gm},
    'list-roman': {pattern: /(\1\.|\n)/gm, regex: /(^\1\..+\n){1,}/gm},
    'list-letter': {pattern: /(\a\.|\n)/gm, regex: /(^\a\..+\n){1,}/gm},
    'checklist': {pattern: /(\[[Xx\s]?\]|\n)/gm, regex: /(^\[[Xx\s]?\].+\n){1,}/gm}
  };
  var image = {
    'image': {pattern: /[]/gm, regex: /\!\[(.*?)\]\((.*?)\)/gm}
  };
  var link = {
    'url-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)/gm},
    'url-plain': {pattern: /[]/gm, regex: /\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b/gm},
    'email': {pattern: /[]/gm, regex: /\b(([\w\d\.\_\%\+\-]+)\@([\w\d\.\-]+)(\.\w{2,}))\b/gm}
  };

  /*============================================================
  ============================Private===========================
  ============================================================*/

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Quote=============================
  ============================================================*/
  exports.Quote = function(doc) {
    for (key in quote) {
      doc = doc.replace(quote[key].regex, function(match) {
        if (key == 'quote-code') {
          console.log(key);
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key + ' nohighlight language-none';
          return '' + exports.Trim(temp) + '';
        } else if (key == 'quote-extra') {
          var extra = exports.Prepare(match).split(']{['),
            credit = extra[0].split('[')[1],
            quote = extra[1].split(']}')[0],
            classes = prefix + key;
          return '
"' + exports.Trim(quote) + '"
' + exports.Trim(credit) + '
';
        } else {
          var temp = exports.Prepare(match).replace(quote[key].pattern, ''),
            classes = prefix + key;
          return '
"' + exports.Trim(temp) + '"
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Code==============================
  ============================================================*/
  exports.Code = function(doc) {
    for (key in code) {
      doc = doc.replace(code[key].regex, function(match) {
        if (key == 'code-extra') {
          var extra = exports.Prepare(match).split(']{('),
            first = extra[0].split('[')[1].split('|'),
            second = extra[1].split(')}')[0],
            language = exports.Trim(first[0]).toLowerCase(),
            service = exports.Trim(first[1]).toLowerCase(),
            classes = prefix + key + ' language-' + language + ' sh_' + language + ' prettyprint lang-' + language,
            dataClasses = language;
          exports.LoadScript('Syntax/' + service + '/script.js');
          exports.LoadStyle('Syntax/' + service + '/' + exports.theme + '.css');
          return '
' + second + '
';
        } else {
          var temp = exports.Prepare(match).replace(code[key].pattern, ''),
            classes = 'nohighlight language-none';
          return '
' + temp + '
';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in list) {
      doc = doc.replace(list[key].regex, function(match) {
        if (key == 'list-solid' || key == 'list-empty' || key == 'list-square') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else if (key == 'list-number' || key == 'list-roman' || key == 'list-letter') {
          return '
' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(list[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '
';
        } else {
          return '' + match.replace(/.+\n/gm, function(line) {
            var temp = exports.Prepare(line).replace(/\[[Xx\s]?\]/gm, ''),
              tag = (new RegExp(/\[\s?\]/gm)).test(line) ? 'unchecked' : 'checked';
            return '' + exports.Trim(temp) + '';
          }) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ============================Image=============================
  ============================================================*/
  exports.Image = function(doc) {
    for (key in image) {
      doc = doc.replace(image[key].regex, function(match) {
        var extra = exports.Prepare(match).split(']('),
          alt = exports.Trim(extra[0].split('![')[1]).toLowerCase(),
          path = exports.Trim(extra[1].split(')')[0]).toLowerCase();
        return '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    for (key in link) {
      doc = doc.replace(link[key].regex, function(match) {
        if (key == 'url-extra') {
          var extra = exports.Prepare(match).split(']('),
            title = extra[0].split('[')[1],
            url = extra[1].split(']')[0];
          return '' + exports.Trim(title) + '';
        } else {
          return '' + exports.Trim(match) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/\n/gm, '
');
  };

  /*============================================================
  ============================Syntax============================
  ============================================================*/
  exports.Syntax = function(elements) {
    for (var a = 0; a < elements.length; a++) {
      var element = elements[a],
        code = element.innerHTML,
        fixed = code.replace(/\
/gm, '\n');
      element.innerHTML = fixed;
    }
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<|endoftext|>


<commit_before>const config = require('../../config')
var Promise = require('bluebird').Promise
const NodeClam = require('clamscan')

var clam
try {
  clam = new NodeClam().init({
    remove_infected: config.CLAM_REMOVE_INFECTED,
    quarantine_infected: false,
    clamdscan: {
      path: config.CLAM_AV_PATH,
      config_file: config.CLAM_AV_CONF_PATH
    }
  })
} catch (error) {
  // Suppress clamscan error if disabled
  if (config.ENABLE_MALWARE_SCANNING !== 'true' &&
      !error.message.includes('No valid & active virus scanning binaries are active and available!')) {
    throw error
  }
}

module.exports.scan = function (filePath) {
  if (config.ENABLE_MALWARE_SCANNING === 'true') {
    clam.then(clamscan => {
      clamscan.is_infected(filePath, (error, file, isInfected, viruses) => {
        if (error) throw error
        return isInfected
      })
    })
  } else {
    return Promise.resolve(false)
  }
}
<commit_msg>Updating ClamAV to the latest version<commit_after>const config = require('../../config')
var Promise = require('bluebird').Promise
const NodeClam = require('clamscan')

var clam
try {
  clam = new NodeClam().init({
    remove_infected: config.CLAM_REMOVE_INFECTED,
    quarantine_infected: false,
    clamdscan: {
      path: config.CLAM_AV_PATH,
      config_file: config.CLAM_AV_CONF_PATH
    }
  })
} catch (error) {
  // Suppress clamscan error if disabled
  if (config.ENABLE_MALWARE_SCANNING !== 'true' &&
      !error.message.includes('No valid & active virus scanning binaries are active and available!')) {
    throw error
  }
}

module.exports.scan = function (filePath) {
  if (config.ENABLE_MALWARE_SCANNING === 'true') {
    clam.then(clamscan => {
      clamscan.is_infected(filePath, (error, file, isInfected, viruses) => {
        if (error) throw error
        return Promise.resolve(isInfected)
      })
    })
  } else {
    return Promise.resolve(false)
  }
}
<|endoftext|>


<commit_before>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
  @credit:
    Prism, Highlight, SHJS, Rainbow, Prettify
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header4': {pattern: /\#{4,}/gm, regex: /\#{4,}.+/gm},
    'header3': {pattern: /\#{3}/gm, regex: /\#{3}.+/gm},
    'header2': {pattern: /\#{2}/gm, regex: /\#{2}.+/gm},
    'header1': {pattern: /\#{1}/gm, regex: /\#{1}.+/gm}
  };
  var style = {
    'bold': {pattern: /\*{2}/gm, regex: /\*{2}(.*?)\*{2}/gm},
    'italic': {pattern: /\*{1}/gm, regex: /\*{1}(.*?)\*{1}/gm},
    'underline': {pattern: /\.{1,}/gm, regex: /\.{1,}(.*?)\.{1,}/gm},
    'strike': {pattern: /\~{1,}/gm, regex: /\~{1,}(.*?)\~{1,}/gm},
    'highlight': {pattern: /\={1,}/gm, regex: /\={1,}(?!\")(.*?)\={1,}/gm},
    'superscript': {pattern: /\^{2}/gm, regex: /\^{2}(.*?)\^{2}/gm},
    'subscript': {pattern: /\^{1}/gm, regex: /\^{1}(.*?)\^{1}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /[]/gm, regex: /^\-{4,}/gm},
    'rule-dash': {pattern: /[]/gm, regex: /^\.{4,}/gm}
  };
  var block = {
    'pre-extra': {pattern: /[]/gm, regex: /^\[(.*?)\|(.*?)\]\`{3,}([\s\S]*?)\`{3,}/gm},
    'quote-extra': {pattern: /[]/gm, regex: /^\[(.*?)\]\`{2}([\s\S]*?)\`{2}/gm},
    'pre': {pattern: /\`{3,}/gm, regex: /^\`{3,}([\s\S]*?)\`{3,}/gm},
    'quote': {pattern: /\`{2}/gm, regex: /^\`{2}([\s\S]*?)\`{2}/gm},
    'code': {pattern: /\`{1}/gm, regex: /\`{1}(.*?)\`{1}/gm}
  };
  var list = {
    'unordered': {pattern: /\-{1}/gm, regex: /(^\-{1}(?!\-{3,}).+\n){1,}/gm},
    'ordered': {pattern: /\d{1,}\./gm, regex: /(^\d{1,}\..+\n){1,}/gm},
    'checklist': {pattern: /[]/gm, regex: /(^\[[Xx]?\].+\n){1,}/gm}
  };
  var link = {
    'url-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)/gm},
    'url': {pattern: /[]/gm, regex: /\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b/gm},
    'email': {pattern: /[]/gm, regex: /\b(([\w\d\.\_\%\+\-]+)\@([\w\d\.\-]+)(\.\w{2,}))\b/gm}
  };

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Block=============================
  ============================================================*/
  exports.Block = function(doc) {
    for (key in block) {
      doc = doc.replace(block[key].regex, function(match) {
        if (key == 'pre-extra') {
          var extra = exports.Prepare(match).split(']```'),
            first = extra[0].split('[')[1].split('|'),
            second = extra[1].split('```')[0],
            language = exports.Trim(first[0]).toLowerCase(),
            service = exports.Trim(first[1]).toLowerCase(),
            classes = 'language-' + language + ' sh_' + language + ' prettyprint lang-' + language,
            dataClasses = 'data-language="' + language + '"';
          exports.LoadScript('Syntax/' + service + '/script.js');
          exports.LoadStyle('Syntax/' + service + '/' + exports.theme + '.css');
          return '
' + exports.Trim(second) + '
';
        } else if (key == 'quote-extra') {
          var extra = exports.Prepare(match).split(']``'),
            credit = extra[0].split('[')[1],
            quote = extra[1].split('``')[0];
          return '' + exports.Trim(quote) + '' + exports.Trim(credit) + '';
        } else {
          var temp = exports.Prepare(match).replace(block[key].pattern, ''),
            classes = 'nohighlight language-none';
          if (key == 'pre') {
            return '
' + exports.Trim(temp) + '
';
          } else if (key == 'quote') {
            return '' + exports.Trim(temp) + '';
          } else {
            return '' + exports.Trim(temp) + '';
          }
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        if (key == 'unordered' || key == 'ordered') {
          var tag = key == 'unordered' ? 'ul' : 'ol';
          return '<' + tag + ' class="' + prefix + key + '">' + match.replace(/.+/gm, function(line) {
            var temp = exports.Prepare(line).replace(style[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '</' + tag + '>';
        } else {
          return '' + match.replace(/.+/gm, function(line) {
            var temp = exports.Prepare(line).replace(/\[\]/gm, ''),
              tag = (new RegExp('\[\]', 'gm')).test(line) ? 'unchecked' : 'checked' ;
            return '' + exports.Trim(temp) + '';
          }) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    for (key in link) {
      doc = doc.replace(link[key].regex, function(match) {
        if (key == 'url-extra') {
          var extra = exports.Prepare(match).split(']('),
            title = extra[0].split('[')[1],
            url = extra[1].split(']')[0];
          return '' + exports.Trim(title) + '';
        } else {
          return '' + exports.Trim(match) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/\n/gm, '
');
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<commit_msg>Update extension.js<commit_after>/*
  Convert the contents of an HTML DOM element into a
  styled text document for an easier reading
  experience or to bring out certain features in the
  document. You can create your own README document.

  if (redistribute == true) {
    return credit;
  }

  --------------------------------------------------

  @DocTyp
  @author: Alexander Hovy
  @param:
    exports - Contains all the public variables and functions of the module.
    doc - The elements text that will be Docified.
  @credit:
    Prism, Highlight, SHJS, Rainbow, Prettify
*/
(function(exports) {
  /*============================================================
  ===========================Variables==========================
  ============================================================*/
  var prefix = 'doctyp-';
  var header = {
    'header4': {pattern: /\#{4,}/gm, regex: /\#{4,}.+/gm},
    'header3': {pattern: /\#{3}/gm, regex: /\#{3}.+/gm},
    'header2': {pattern: /\#{2}/gm, regex: /\#{2}.+/gm},
    'header1': {pattern: /\#{1}/gm, regex: /\#{1}.+/gm}
  };
  var style = {
    'bold': {pattern: /\*{2}/gm, regex: /\*{2}(.*?)\*{2}/gm},
    'italic': {pattern: /\*{1}/gm, regex: /\*{1}(.*?)\*{1}/gm},
    'underline': {pattern: /\.\.{1,}/gm, regex: /\.\.{1,}(.*?)\.\.{1,}/gm},
    'strike': {pattern: /\~{1,}/gm, regex: /\~{1,}(.*?)\~{1,}/gm},
    'highlight': {pattern: /\={1,}/gm, regex: /\={1,}(?!\")(.*?)\={1,}/gm},
    'superscript': {pattern: /\^{2}/gm, regex: /\^{2}(.*?)\^{2}/gm},
    'subscript': {pattern: /\^{1}/gm, regex: /\^{1}(.*?)\^{1}/gm}
  };
  var rule = {
    'rule-solid': {pattern: /[]/gm, regex: /^\-{4,}/gm},
    'rule-dash': {pattern: /[]/gm, regex: /^\.{4,}/gm}
  };
  var block = {
    'pre-extra': {pattern: /[]/gm, regex: /^\[(.*?)\|(.*?)\]\`{3,}([\s\S]*?)\`{3,}/gm},
    'quote-extra': {pattern: /[]/gm, regex: /^\[(.*?)\]\`{2}([\s\S]*?)\`{2}/gm},
    'pre': {pattern: /\`{3,}/gm, regex: /^\`{3,}([\s\S]*?)\`{3,}/gm},
    'quote': {pattern: /\`{2}/gm, regex: /^\`{2}([\s\S]*?)\`{2}/gm},
    'code': {pattern: /\`{1}/gm, regex: /\`{1}(.*?)\`{1}/gm}
  };
  var list = {
    'unordered': {pattern: /\-{1}/gm, regex: /(^\-{1}(?!\-{3,}).+\n){1,}/gm},
    'ordered': {pattern: /\d{1,}\./gm, regex: /(^\d{1,}\..+\n){1,}/gm},
    'checklist': {pattern: /[]/gm, regex: /(^\[[Xx]?\].+\n){1,}/gm}
  };
  var link = {
    'url-extra': {pattern: /[]/gm, regex: /\[(.*?)\]\((.*?)(https?|ftp|file)\:\/{2}(.*?)\)/gm},
    'url': {pattern: /[]/gm, regex: /\b((https?|ftp|file)\:\/{2}([\w\d\.]+)([\/\?\&\w\d\=\,\.\+\:\;\@\$\%\#\!\_\-]+)?)\b/gm},
    'email': {pattern: /[]/gm, regex: /\b(([\w\d\.\_\%\+\-]+)\@([\w\d\.\-]+)(\.\w{2,}))\b/gm}
  };

  /*============================================================
  ============================Header============================
  ============================================================*/
  exports.Header = function(doc) {
    for (key in header) {
      doc = doc.replace(header[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(header[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Style=============================
  ============================================================*/
  exports.Style = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        var temp = exports.Prepare(match).replace(style[key].pattern, '');
        return '' + exports.Trim(temp) + '';
      });
    }
    return doc;
  };

  /*============================================================
  =============================Rule=============================
  ============================================================*/
  exports.Rule = function(doc) {
    for (key in rule) {
      doc = doc.replace(rule[key].regex, function(match) {
        return '
';
      });
    }
    return doc;
  };

  /*============================================================
  ============================Block=============================
  ============================================================*/
  exports.Block = function(doc) {
    for (key in block) {
      doc = doc.replace(block[key].regex, function(match) {
        if (key == 'pre-extra') {
          var extra = exports.Prepare(match).split(']```'),
            first = extra[0].split('[')[1].split('|'),
            second = extra[1].split('```')[0],
            language = exports.Trim(first[0]).toLowerCase(),
            service = exports.Trim(first[1]).toLowerCase(),
            classes = 'language-' + language + ' sh_' + language + ' prettyprint lang-' + language,
            dataClasses = 'data-language="' + language + '"';
          exports.LoadScript('Syntax/' + service + '/script.js');
          exports.LoadStyle('Syntax/' + service + '/' + exports.theme + '.css');
          return '
' + exports.Trim(second) + '
';
        } else if (key == 'quote-extra') {
          var extra = exports.Prepare(match).split(']``'),
            credit = extra[0].split('[')[1],
            quote = extra[1].split('``')[0];
          return '' + exports.Trim(quote) + '' + exports.Trim(credit) + '';
        } else {
          var temp = exports.Prepare(match).replace(block[key].pattern, ''),
            classes = 'nohighlight language-none';
          if (key == 'pre') {
            return '
' + exports.Trim(temp) + '
';
          } else if (key == 'quote') {
            return '' + exports.Trim(temp) + '';
          } else {
            return '' + exports.Trim(temp) + '';
          }
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================List=============================
  ============================================================*/
  exports.List = function(doc) {
    for (key in style) {
      doc = doc.replace(style[key].regex, function(match) {
        if (key == 'unordered' || key == 'ordered') {
          var tag = key == 'unordered' ? 'ul' : 'ol';
          return '<' + tag + ' class="' + prefix + key + '">' + match.replace(/.+/gm, function(line) {
            var temp = exports.Prepare(line).replace(style[key].pattern, '');
            return '
' + exports.Trim(temp) + '
';
          }) + '</' + tag + '>';
        } else {
          return '' + match.replace(/.+/gm, function(line) {
            var temp = exports.Prepare(line).replace(/\[\]/gm, ''),
              tag = (new RegExp('\[\]', 'gm')).test(line) ? 'unchecked' : 'checked' ;
            return '' + exports.Trim(temp) + '';
          }) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  =============================Link=============================
  ============================================================*/
  exports.Link = function(doc) {
    for (key in link) {
      doc = doc.replace(link[key].regex, function(match) {
        if (key == 'url-extra') {
          var extra = exports.Prepare(match).split(']('),
            title = extra[0].split('[')[1],
            url = extra[1].split(']')[0];
          return '' + exports.Trim(title) + '';
        } else {
          return '' + exports.Trim(match) + '';
        }
      });
    }
    return doc;
  };

  /*============================================================
  ===========================Cleaning===========================
  ============================================================*/
  exports.Prepare = function(doc) {
    return doc.replace(/\<(\/)?span(.*?)\>/gm, '');
  };
  exports.Trim = function(doc) {
    return doc.replace(/(^\s+|\s+$)/gm, '');
  };
  exports.Clean = function(doc) {
    return doc.replace(/\n/gm, '
');
  };

  /*============================================================
  ============================Export============================
  ============================================================*/
  return exports;
})(DocTyp || {});
<|endoftext|>


<commit_before>import { alias } from '@ember/object/computed';
import Service, { inject as service } from '@ember/service';

import * as Sentry from '@sentry/browser';
import { race, rawTimeout, task, waitForEvent } from 'ember-concurrency';
import window from 'ember-window-mock';

import ajax from '../utils/ajax';
import * as localStorage from '../utils/local-storage';

export default class SessionService extends Service {
  @service store;
  @service notifications;
  @service router;

  savedTransition = null;

  @alias('loadUserTask.last.value.currentUser') currentUser;
  @alias('loadUserTask.last.value.ownedCrates') ownedCrates;

  get isLoggedIn() {
    return localStorage.getItem('isLoggedIn') === '1';
  }

  set isLoggedIn(value) {
    if (value) {
      localStorage.setItem('isLoggedIn', '1');
    } else {
      localStorage.removeItem('isLoggedIn');
    }
  }

  /**
   * This task will open a popup window, query the `/api/private/session/begin` API
   * endpoint and then navigate the popup window to the received URL.
   *
   * Example URL:
   * https://github.com/login/oauth/authorize?client_id=...&state=...&scope=read%3Aorg
   *
   * Once the user has allowed the OAuth flow access the page will redirect him
   * to the `github-authorize` route of this application.
   *
   * The task will then wait for the window to send a message back and evaluate
   * whether the OAuth flow was successful.
   *
   * @see https://developer.github.com/v3/oauth/#redirect-users-to-request-github-access
   * @see `github-authorize` route
   */
  @task(function* () {
    let windowDimensions = [
      'width=1000',
      'height=450',
      'toolbar=0',
      'scrollbars=1',
      'status=1',
      'resizable=1',
      'location=1',
      'menuBar=0',
    ].join(',');

    let win = window.open('', '_blank', windowDimensions);
    if (!win) {
      return;
    }

    win.document.write('Please wait while we redirect you…');
    win.document.close();

    // we can't call `window.open()` with this URL directly, because it might trigger
    // the popup window prevention mechanism of the browser, since the async opening
    // can not be associated with the original user click event
    let { url } = yield ajax(`/api/private/session/begin`);
    win.location = url;

    let event = yield race([waitForEvent(window, 'message'), this.windowCloseWatcherTask.perform(win)]);
    if (event.closed) {
      this.notifications.warning('Login was canceled because the popup window was closed.');
      return;
    }

    win.close();
    if (event.origin !== window.location.origin || !event.data) {
      return;
    }

    let { code, state } = event.data;
    if (!code || !state) {
      return;
    }

    let response = yield fetch(`/api/private/session/authorize?code=${code}&state=${state}`);
    if (!response.ok) {
      let json = yield response.json();

      if (json && json.errors) {
        this.notifications.error(`Failed to log in: ${json.errors[0].detail}`);
      } else {
        this.notifications.error('Failed to log in');
      }
      return;
    }

    this.isLoggedIn = true;

    yield this.loadUserTask.perform();

    // perform the originally saved transition, if it exists
    let transition = this.savedTransition;
    if (transition) {
      transition.retry();
    }
  })
  loginTask;

  @task(function* (window) {
    while (true) {
      if (window.closed) {
        return { closed: true };
      }
      yield rawTimeout(10);
    }
  })
  windowCloseWatcherTask;

  @task(function* () {
    yield ajax(`/api/private/session`, { method: 'DELETE' });

    this.savedTransition = null;
    this.isLoggedIn = false;

    this.loadUserTask.cancelAll({ resetState: true });
    Sentry.setUser(null);

    this.router.transitionTo('index');
  })
  logoutTask;

  @(task(function* () {
    if (!this.isLoggedIn) return {};

    let response;
    try {
      response = yield ajax('/api/v1/me');
    } catch {
      return {};
    }

    let currentUser = this.store.push(this.store.normalize('user', response.user));
    let ownedCrates = response.owned_crates.map(c => this.store.push(this.store.normalize('owned-crate', c)));

    let { id } = currentUser;
    Sentry.setUser({ id });

    return { currentUser, ownedCrates };
  }).drop())
  loadUserTask;
}
<commit_msg>services/session: Wait for `cancelAll()` to finish<commit_after>import { alias } from '@ember/object/computed';
import Service, { inject as service } from '@ember/service';

import * as Sentry from '@sentry/browser';
import { race, rawTimeout, task, waitForEvent } from 'ember-concurrency';
import window from 'ember-window-mock';

import ajax from '../utils/ajax';
import * as localStorage from '../utils/local-storage';

export default class SessionService extends Service {
  @service store;
  @service notifications;
  @service router;

  savedTransition = null;

  @alias('loadUserTask.last.value.currentUser') currentUser;
  @alias('loadUserTask.last.value.ownedCrates') ownedCrates;

  get isLoggedIn() {
    return localStorage.getItem('isLoggedIn') === '1';
  }

  set isLoggedIn(value) {
    if (value) {
      localStorage.setItem('isLoggedIn', '1');
    } else {
      localStorage.removeItem('isLoggedIn');
    }
  }

  /**
   * This task will open a popup window, query the `/api/private/session/begin` API
   * endpoint and then navigate the popup window to the received URL.
   *
   * Example URL:
   * https://github.com/login/oauth/authorize?client_id=...&state=...&scope=read%3Aorg
   *
   * Once the user has allowed the OAuth flow access the page will redirect him
   * to the `github-authorize` route of this application.
   *
   * The task will then wait for the window to send a message back and evaluate
   * whether the OAuth flow was successful.
   *
   * @see https://developer.github.com/v3/oauth/#redirect-users-to-request-github-access
   * @see `github-authorize` route
   */
  @task(function* () {
    let windowDimensions = [
      'width=1000',
      'height=450',
      'toolbar=0',
      'scrollbars=1',
      'status=1',
      'resizable=1',
      'location=1',
      'menuBar=0',
    ].join(',');

    let win = window.open('', '_blank', windowDimensions);
    if (!win) {
      return;
    }

    win.document.write('Please wait while we redirect you…');
    win.document.close();

    // we can't call `window.open()` with this URL directly, because it might trigger
    // the popup window prevention mechanism of the browser, since the async opening
    // can not be associated with the original user click event
    let { url } = yield ajax(`/api/private/session/begin`);
    win.location = url;

    let event = yield race([waitForEvent(window, 'message'), this.windowCloseWatcherTask.perform(win)]);
    if (event.closed) {
      this.notifications.warning('Login was canceled because the popup window was closed.');
      return;
    }

    win.close();
    if (event.origin !== window.location.origin || !event.data) {
      return;
    }

    let { code, state } = event.data;
    if (!code || !state) {
      return;
    }

    let response = yield fetch(`/api/private/session/authorize?code=${code}&state=${state}`);
    if (!response.ok) {
      let json = yield response.json();

      if (json && json.errors) {
        this.notifications.error(`Failed to log in: ${json.errors[0].detail}`);
      } else {
        this.notifications.error('Failed to log in');
      }
      return;
    }

    this.isLoggedIn = true;

    yield this.loadUserTask.perform();

    // perform the originally saved transition, if it exists
    let transition = this.savedTransition;
    if (transition) {
      transition.retry();
    }
  })
  loginTask;

  @task(function* (window) {
    while (true) {
      if (window.closed) {
        return { closed: true };
      }
      yield rawTimeout(10);
    }
  })
  windowCloseWatcherTask;

  @task(function* () {
    yield ajax(`/api/private/session`, { method: 'DELETE' });

    this.savedTransition = null;
    this.isLoggedIn = false;

    yield this.loadUserTask.cancelAll({ resetState: true });
    Sentry.setUser(null);

    this.router.transitionTo('index');
  })
  logoutTask;

  @(task(function* () {
    if (!this.isLoggedIn) return {};

    let response;
    try {
      response = yield ajax('/api/v1/me');
    } catch {
      return {};
    }

    let currentUser = this.store.push(this.store.normalize('user', response.user));
    let ownedCrates = response.owned_crates.map(c => this.store.push(this.store.normalize('owned-crate', c)));

    let { id } = currentUser;
    Sentry.setUser({ id });

    return { currentUser, ownedCrates };
  }).drop())
  loadUserTask;
}
<|endoftext|>


<commit_before>/*
 * CSSMIN: Compress CSS files
 */
module.exports = {
    installLibCss: {
        options: {
            compatibility: 'ie8',
            relativeTo: 'css/',
            target: 'css/'
        },
        files: {
            'css/lib.css': [
                'lib/jquery-ui-1.10.3/jquery-ui.custom.min.css',            // 20 kb
                'bower_components/magnific-popup/dist/magnific-popup.css',  //  9 kb
                'lib/select2/select2.css',                                  // 19 kb
                'lib/jquery-fileupload/jquery-fileupload-ui.css'            //  2 kb
            ]
        }
    }
};
<commit_msg>Make usage of grunt templates in cssmin task<commit_after>/*
 * CSSMIN: Compress CSS files
 */
module.exports = {
    installLibCss: {
        options: {
            compatibility: 'ie8',
            relativeTo: 'css/',
            target: 'css/'
        },
        files: {
            '<%= path.dest.css %>/lib.css': [
                '<%= path.src.lib %>/jquery-ui-1.10.3/jquery-ui.custom.min.css',            // 20 kb
                '<%= path.src.bower %>/magnific-popup/dist/magnific-popup.css',  //  9 kb
                '<%= path.src.lib %>/select2/select2.css',                                  // 19 kb
                '<%= path.src.lib %>/jquery-fileupload/jquery-fileupload-ui.css'            //  2 kb
            ]
        }
    }
};
<|endoftext|>


<commit_before>import React, { useState } from "react";
import classes from "./Marketplace.module.css";
import Block from "../../components/UI/Block/Block";
import TrendingSearches from "../../components/TrendingSearches/TrendingSearches";
import RecentBuys from "../../components/RecentBuys/RecentBuysList";
import Button from "../../components/UI/Button/Button";
import ChartCard from "../../components/ChartCard/ChartCard";

const Marketplace = (props) => {
  const [searchEntry, setSearchEntry] = useState("");
  const [purchaseAmount, setPurchaseAmount] = useState(0);
  const [loadingData, setLoadingData] = useState(false);
  const [chartData, setChartData] = useState();

  const onSearchChange = (e) => {
    setSearchEntry(e.target.value);
  };

  const onAmountChange = (e) => {
    setPurchaseAmount(e.target.value);
    console.log(e.target.value);
  };

  const onSearchEntered = () => {
    if (searchEntry.trim() === "") {
      return;
    }
    setLoadingData(true);
    fetchContextData(searchEntry)
      .then((data) => {
        setChartData(data);
      })
      .then(() => {
        setLoadingData(false);
      });
  };

  const fetchContextData = async (entry) => {
    const formattedData = await fetch(`./contextData?search_term=${entry}`)
      .then((response) => response.json())
      .then((data) => {
        const averagedData = data.map((datapoint) => datapoint / 24);
        return formatChartData(averagedData);
      })
      .catch((e) => {
        console.log(e);
        return null;
      });
    return formattedData;
  };

  const formatChartData = (data) => {
    const chartData = [];
    chartData.push(["x", "Popularity"]);
    for (let i = 0; i < data.length; i++) {
      chartData.push([i, data[i]]);
    }
    return chartData;
  };

  let chartSpace = (

Search something!

  );

  if (loadingData === true) {
    chartSpace =
Loading...
;
  } else if (chartData === null) {
    chartSpace = (

        No data :(
 Try a more popular search term!

    );
  } else if (chartData !== undefined) {
    chartSpace = (
      <ChartCard
        chartInfo={{
          haxis: "Time",
          vaxis: "Net Worth",
          data: chartData,
        }}
      ></ChartCard>
    );
  }

  return (

          <input
            className={classes.SearchInput}
            placeholder="Search a trend"
            onChange={(e) => onSearchChange(e)}
          ></input>
          <Button inverted padding="3px 20px" onClick={onSearchEntered}>
            Search
          </Button>

        <Block className={classes.ChartContainer}>{chartSpace}</Block>

"search query"

            Amount to purchase:

              t$
              <input type="number" onChange={(e) => onAmountChange(e)}></input>

            Currently available:
            t$1234

          <Button>Confirm Purchase</Button>

Trending searches

          <Block className={classes.Block}>
            <TrendingSearches
              searches={props.trendingSearches}
            ></TrendingSearches>
          </Block>

What your team is buying:

          <Block className={classes.Block}>
            <RecentBuys buys={props.recentBuys}></RecentBuys>
          </Block>

  );
};

export default Marketplace;
<commit_msg>Add function for confirm purchase button<commit_after>import React, { useState } from "react";
import classes from "./Marketplace.module.css";
import Block from "../../components/UI/Block/Block";
import TrendingSearches from "../../components/TrendingSearches/TrendingSearches";
import RecentBuys from "../../components/RecentBuys/RecentBuysList";
import Button from "../../components/UI/Button/Button";
import ChartCard from "../../components/ChartCard/ChartCard";

const Marketplace = (props) => {
  const [searchEntry, setSearchEntry] = useState("");
  const [purchaseAmount, setPurchaseAmount] = useState(0);
  const [loadingData, setLoadingData] = useState(false);
  const [chartData, setChartData] = useState();

  const onSearchChange = (e) => {
    setSearchEntry(e.target.value);
  };

  const onAmountChange = (e) => {
    setPurchaseAmount(e.target.value);
  };

  const onSearchEntered = () => {
    if (searchEntry.trim() === "") {
      return;
    }
    setLoadingData(true);
    fetchContextData(searchEntry)
      .then((data) => {
        setChartData(data);
      })
      .then(() => {
        setLoadingData(false);
      });
  };

  const fetchContextData = async (entry) => {
    const formattedData = await fetch(`./contextData?search_term=${entry}`)
      .then((response) => response.json())
      .then((data) => {
        const averagedData = data.map((datapoint) => datapoint / 24);
        return formatChartData(averagedData);
      })
      .catch((e) => {
        console.log(e);
        return null;
      });
    return formattedData;
  };

  const formatChartData = (data) => {
    const chartData = [];
    chartData.push(["x", "Popularity"]);
    for (let i = 0; i < data.length; i++) {
      chartData.push([i, data[i]]);
    }
    return chartData;
  };

  let chartSpace = (

Search something!

  );

  if (loadingData === true) {
    chartSpace =
Loading...
;
  } else if (chartData === null) {
    chartSpace = (

        No data :(
 Try a more popular search term!

    );
  } else if (chartData !== undefined) {
    chartSpace = (
      <ChartCard
        chartInfo={{
          haxis: "Time",
          vaxis: "Net Worth",
          data: chartData,
        }}
      ></ChartCard>
    );
  }

  const onConfirmPurchase = () => {
    console.log(purchaseAmount);
  };

  return (

          <input
            className={classes.SearchInput}
            placeholder="Search a trend"
            onChange={(e) => onSearchChange(e)}
          ></input>
          <Button inverted padding="3px 20px" onClick={onSearchEntered}>
            Search
          </Button>

        <Block className={classes.ChartContainer}>{chartSpace}</Block>

"search query"

            Amount to purchase:

              t$
              <input type="number" onChange={(e) => onAmountChange(e)}></input>

            Currently available:
            t$1234

          <Button onClick={onConfirmPurchase}>Confirm Purchase</Button>

Trending searches

          <Block className={classes.Block}>
            <TrendingSearches
              searches={props.trendingSearches}
            ></TrendingSearches>
          </Block>

What your team is buying:

          <Block className={classes.Block}>
            <RecentBuys buys={props.recentBuys}></RecentBuys>
          </Block>

  );
};

export default Marketplace;
<|endoftext|>


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

/**
 * @fileoverview Functions for setting, getting and deleting cookies.
 *
 * @author arv@google.com (Erik Arvidsson)
 */

goog.provide('goog.net.Cookies');
goog.provide('goog.net.cookies');

goog.require('goog.string');

/**
 * A class for handling browser cookies.
 * @param {?Document} context The context document to get/set cookies on.
 * @constructor
 * @final
 */
goog.net.Cookies = function(context) {
  /**
  * The context document to get/set cookies on. If no document context is
  * passed, use a fake one with only the "cookie" attribute. This allows
  * this class to be instantiated safely in web worker environments.
  * @private {{cookie: string}}
  */
  this.document_ = context || {cookie: ''};
};

/**
 * Static constant for the size of cookies. Per the spec, there's a 4K limit
 * to the size of a cookie. To make sure users can't break this limit, we
 * should truncate long cookies at 3950 bytes, to be extra careful with dumb
 * browsers/proxies that interpret 4K as 4000 rather than 4096.
 * @const {number}
 */
goog.net.Cookies.MAX_COOKIE_LENGTH = 3950;

/**
 * Returns true if cookies are enabled.
 * @return {boolean} True if cookies are enabled.
 */
goog.net.Cookies.prototype.isEnabled = function() {
  return navigator.cookieEnabled;
};

/**
 * We do not allow '=', ';', or white space in the name.
 *
 * NOTE: The following are allowed by this method, but should be avoided for
 * cookies handled by the server.
 * - any name starting with '$'
 * - 'Comment'
 * - 'Domain'
 * - 'Expires'
 * - 'Max-Age'
 * - 'Path'
 * - 'Secure'
 * - 'Version'
 *
 * @param {string} name Cookie name.
 * @return {boolean} Whether name is valid.
 *
 * @see RFC 2109
 * @see RFC 2965
 */
goog.net.Cookies.prototype.isValidName = function(name) {
  return !(/[;=\s]/.test(name));
};

/**
 * We do not allow ';' or line break in the value.
 *
 * Spec does not mention any illegal characters, but in practice semi-colons
 * break parsing and line breaks truncate the name.
 *
 * @param {string} value Cookie value.
 * @return {boolean} Whether value is valid.
 *
 * @see RFC 2109
 * @see RFC 2965
 */
goog.net.Cookies.prototype.isValidValue = function(value) {
  return !(/[;\r\n]/.test(value));
};

/**
 * Sets a cookie.  The max_age can be -1 to set a session cookie. To remove and
 * expire cookies, use remove() instead.
 *
 * Neither the `name` nor the `value` are encoded in any way. It is
 * up to the callers of `get` and `set` (as well as all the other
 * methods) to handle any possible encoding and decoding.
 *
 * @throws {!Error} If the `name` fails #goog.net.cookies.isValidName.
 * @throws {!Error} If the `value` fails #goog.net.cookies.isValidValue.
 *
 * @param {string} name  The cookie name.
 * @param {string} value  The cookie value.
 * @param {number=} opt_maxAge  The max age in seconds (from now). Use -1 to
 *     set a session cookie. If not provided, the default is -1
 *     (i.e. set a session cookie).
 * @param {?string=} opt_path  The path of the cookie. If not present then this
 *     uses the full request path.
 * @param {?string=} opt_domain  The domain of the cookie, or null to not
 *     specify a domain attribute (browser will use the full request host name).
 *     If not provided, the default is null (i.e. let browser use full request
 *     host name).
 * @param {boolean=} opt_secure Whether the cookie should only be sent over
 *     a secure channel.
 */
goog.net.Cookies.prototype.set = function(
    name, value, opt_maxAge, opt_path, opt_domain, opt_secure) {
  if (!this.isValidName(name)) {
    throw new Error('Invalid cookie name "' + name + '"');
  }
  if (!this.isValidValue(value)) {
    throw new Error('Invalid cookie value "' + value + '"');
  }

  if (!goog.isDef(opt_maxAge)) {
    opt_maxAge = -1;
  }

  var domainStr = opt_domain ? ';domain=' + opt_domain : '';
  var pathStr = opt_path ? ';path=' + opt_path : '';
  var secureStr = opt_secure ? ';secure' : '';

  var expiresStr;

  // Case 1: Set a session cookie.
  if (opt_maxAge < 0) {
    expiresStr = '';

    // Case 2: Remove the cookie.
    // Note: We don't tell people about this option in the function doc because
    // we prefer people to use remove() to remove cookies.
  } else if (opt_maxAge == 0) {
    // Note: Don't use Jan 1, 1970 for date because NS 4.76 will try to convert
    // it to local time, and if the local time is before Jan 1, 1970, then the
    // browser will ignore the Expires attribute altogether.
    var pastDate = new Date(1970, 1 /*Feb*/, 1);  // Feb 1, 1970
    expiresStr = ';expires=' + pastDate.toUTCString();

    // Case 3: Set a persistent cookie.
  } else {
    var futureDate = new Date(goog.now() + opt_maxAge * 1000);
    expiresStr = ';expires=' + futureDate.toUTCString();
  }

  this.setCookie_(
      name + '=' + value + domainStr + pathStr + expiresStr + secureStr);
};

/**
 * Returns the value for the first cookie with the given name.
 * @param {string} name  The name of the cookie to get.
 * @param {string=} opt_default  If not found this is returned instead.
 * @return {string|undefined}  The value of the cookie. If no cookie is set this
 *     returns opt_default or undefined if opt_default is not provided.
 */
goog.net.Cookies.prototype.get = function(name, opt_default) {
  var nameEq = name + '=';
  var parts = this.getParts_();
  for (var i = 0, part; i < parts.length; i++) {
    part = goog.string.trim(parts[i]);
    // startsWith
    if (part.lastIndexOf(nameEq, 0) == 0) {
      return part.substr(nameEq.length);
    }
    if (part == name) {
      return '';
    }
  }
  return opt_default;
};

/**
 * Removes and expires a cookie.
 * @param {string} name  The cookie name.
 * @param {?string=} opt_path  The path of the cookie, or null to expire a cookie
 *     set at the full request path. If not provided, the default is '/'
 *     (i.e. path=/).
 * @param {?string=} opt_domain  The domain of the cookie, or null to expire a
 *     cookie set at the full request host name. If not provided, the default is
 *     null (i.e. cookie at full request host name).
 * @return {boolean} Whether the cookie existed before it was removed.
 */
goog.net.Cookies.prototype.remove = function(name, opt_path, opt_domain) {
  var rv = this.containsKey(name);
  this.set(name, '', 0, opt_path, opt_domain);
  return rv;
};

/**
 * Gets the names for all the cookies.
 * @return {Array<string>} An array with the names of the cookies.
 */
goog.net.Cookies.prototype.getKeys = function() {
  return this.getKeyValues_().keys;
};

/**
 * Gets the values for all the cookies.
 * @return {Array<string>} An array with the values of the cookies.
 */
goog.net.Cookies.prototype.getValues = function() {
  return this.getKeyValues_().values;
};

/**
 * @return {boolean} Whether there are any cookies for this document.
 */
goog.net.Cookies.prototype.isEmpty = function() {
  return !this.getCookie_();
};

/**
 * @return {number} The number of cookies for this document.
 */
goog.net.Cookies.prototype.getCount = function() {
  var cookie = this.getCookie_();
  if (!cookie) {
    return 0;
  }
  return this.getParts_().length;
};

/**
 * Returns whether there is a cookie with the given name.
 * @param {string} key The name of the cookie to test for.
 * @return {boolean} Whether there is a cookie by that name.
 */
goog.net.Cookies.prototype.containsKey = function(key) {
  // substring will return empty string if the key is not found, so the get
  // function will only return undefined
  return goog.isDef(this.get(key));
};

/**
 * Returns whether there is a cookie with the given value. (This is an O(n)
 * operation.)
 * @param {string} value  The value to check for.
 * @return {boolean} Whether there is a cookie with that value.
 */
goog.net.Cookies.prototype.containsValue = function(value) {
  // this O(n) in any case so lets do the trivial thing.
  var values = this.getKeyValues_().values;
  for (var i = 0; i < values.length; i++) {
    if (values[i] == value) {
      return true;
    }
  }
  return false;
};

/**
 * Removes all cookies for this document.  Note that this will only remove
 * cookies from the current path and domain.  If there are cookies set using a
 * subpath and/or another domain these will still be there.
 */
goog.net.Cookies.prototype.clear = function() {
  var keys = this.getKeyValues_().keys;
  for (var i = keys.length - 1; i >= 0; i--) {
    this.remove(keys[i]);
  }
};

/**
 * Private helper function to allow testing cookies without depending on the
 * browser.
 * @param {string} s The cookie string to set.
 * @private
 */
goog.net.Cookies.prototype.setCookie_ = function(s) {
  this.document_.cookie = s;
};

/**
 * Private helper function to allow testing cookies without depending on the
 * browser. IE6 can return null here.
 * @return {string} Returns the `document.cookie`.
 * @private
 */
goog.net.Cookies.prototype.getCookie_ = function() {
  return this.document_.cookie;
};

/**
 * @return {!Array<string>} The cookie split on semi colons.
 * @private
 */
goog.net.Cookies.prototype.getParts_ = function() {
  return (this.getCookie_() || '').split(';');
};

/**
 * Gets the names and values for all the cookies.
 * @return {{keys:!Array<string>, values:!Array<string>}} An object with keys
 *     and values.
 * @private
 */
goog.net.Cookies.prototype.getKeyValues_ = function() {
  var parts = this.getParts_();
  var keys = [], values = [], index, part;
  for (var i = 0; i < parts.length; i++) {
    part = goog.string.trim(parts[i]);
    index = part.indexOf('=');

    if (index == -1) {  // empty name
      keys.push('');
      values.push(part);
    } else {
      keys.push(part.substring(0, index));
      values.push(part.substring(index + 1));
    }
  }
  return {keys: keys, values: values};
};

// TODO(closure-team): This should be a singleton getter instead of a static
// instance.
/**
 * A static default instance.
 * @const {!goog.net.Cookies}
 */
goog.net.cookies =
    new goog.net.Cookies(typeof document == 'undefined' ? null : document);

/**
 * Getter for the static instance of goog.net.Cookies.
 * @return {!goog.net.Cookies}
 */
goog.net.Cookies.getInstance = function() {
  return goog.net.cookies;
};
<commit_msg>Update documentation for cookies.remove(...).<commit_after>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Functions for setting, getting and deleting cookies.
 *
 * @author arv@google.com (Erik Arvidsson)
 */

goog.provide('goog.net.Cookies');
goog.provide('goog.net.cookies');

goog.require('goog.string');

/**
 * A class for handling browser cookies.
 * @param {?Document} context The context document to get/set cookies on.
 * @constructor
 * @final
 */
goog.net.Cookies = function(context) {
  /**
  * The context document to get/set cookies on. If no document context is
  * passed, use a fake one with only the "cookie" attribute. This allows
  * this class to be instantiated safely in web worker environments.
  * @private {{cookie: string}}
  */
  this.document_ = context || {cookie: ''};
};

/**
 * Static constant for the size of cookies. Per the spec, there's a 4K limit
 * to the size of a cookie. To make sure users can't break this limit, we
 * should truncate long cookies at 3950 bytes, to be extra careful with dumb
 * browsers/proxies that interpret 4K as 4000 rather than 4096.
 * @const {number}
 */
goog.net.Cookies.MAX_COOKIE_LENGTH = 3950;

/**
 * Returns true if cookies are enabled.
 * @return {boolean} True if cookies are enabled.
 */
goog.net.Cookies.prototype.isEnabled = function() {
  return navigator.cookieEnabled;
};

/**
 * We do not allow '=', ';', or white space in the name.
 *
 * NOTE: The following are allowed by this method, but should be avoided for
 * cookies handled by the server.
 * - any name starting with '$'
 * - 'Comment'
 * - 'Domain'
 * - 'Expires'
 * - 'Max-Age'
 * - 'Path'
 * - 'Secure'
 * - 'Version'
 *
 * @param {string} name Cookie name.
 * @return {boolean} Whether name is valid.
 *
 * @see RFC 2109
 * @see RFC 2965
 */
goog.net.Cookies.prototype.isValidName = function(name) {
  return !(/[;=\s]/.test(name));
};

/**
 * We do not allow ';' or line break in the value.
 *
 * Spec does not mention any illegal characters, but in practice semi-colons
 * break parsing and line breaks truncate the name.
 *
 * @param {string} value Cookie value.
 * @return {boolean} Whether value is valid.
 *
 * @see RFC 2109
 * @see RFC 2965
 */
goog.net.Cookies.prototype.isValidValue = function(value) {
  return !(/[;\r\n]/.test(value));
};

/**
 * Sets a cookie.  The max_age can be -1 to set a session cookie. To remove and
 * expire cookies, use remove() instead.
 *
 * Neither the `name` nor the `value` are encoded in any way. It is
 * up to the callers of `get` and `set` (as well as all the other
 * methods) to handle any possible encoding and decoding.
 *
 * @throws {!Error} If the `name` fails #goog.net.cookies.isValidName.
 * @throws {!Error} If the `value` fails #goog.net.cookies.isValidValue.
 *
 * @param {string} name  The cookie name.
 * @param {string} value  The cookie value.
 * @param {number=} opt_maxAge  The max age in seconds (from now). Use -1 to
 *     set a session cookie. If not provided, the default is -1
 *     (i.e. set a session cookie).
 * @param {?string=} opt_path  The path of the cookie. If not present then this
 *     uses the full request path.
 * @param {?string=} opt_domain  The domain of the cookie, or null to not
 *     specify a domain attribute (browser will use the full request host name).
 *     If not provided, the default is null (i.e. let browser use full request
 *     host name).
 * @param {boolean=} opt_secure Whether the cookie should only be sent over
 *     a secure channel.
 */
goog.net.Cookies.prototype.set = function(
    name, value, opt_maxAge, opt_path, opt_domain, opt_secure) {
  if (!this.isValidName(name)) {
    throw new Error('Invalid cookie name "' + name + '"');
  }
  if (!this.isValidValue(value)) {
    throw new Error('Invalid cookie value "' + value + '"');
  }

  if (!goog.isDef(opt_maxAge)) {
    opt_maxAge = -1;
  }

  var domainStr = opt_domain ? ';domain=' + opt_domain : '';
  var pathStr = opt_path ? ';path=' + opt_path : '';
  var secureStr = opt_secure ? ';secure' : '';

  var expiresStr;

  // Case 1: Set a session cookie.
  if (opt_maxAge < 0) {
    expiresStr = '';

    // Case 2: Remove the cookie.
    // Note: We don't tell people about this option in the function doc because
    // we prefer people to use remove() to remove cookies.
  } else if (opt_maxAge == 0) {
    // Note: Don't use Jan 1, 1970 for date because NS 4.76 will try to convert
    // it to local time, and if the local time is before Jan 1, 1970, then the
    // browser will ignore the Expires attribute altogether.
    var pastDate = new Date(1970, 1 /*Feb*/, 1);  // Feb 1, 1970
    expiresStr = ';expires=' + pastDate.toUTCString();

    // Case 3: Set a persistent cookie.
  } else {
    var futureDate = new Date(goog.now() + opt_maxAge * 1000);
    expiresStr = ';expires=' + futureDate.toUTCString();
  }

  this.setCookie_(
      name + '=' + value + domainStr + pathStr + expiresStr + secureStr);
};

/**
 * Returns the value for the first cookie with the given name.
 * @param {string} name  The name of the cookie to get.
 * @param {string=} opt_default  If not found this is returned instead.
 * @return {string|undefined}  The value of the cookie. If no cookie is set this
 *     returns opt_default or undefined if opt_default is not provided.
 */
goog.net.Cookies.prototype.get = function(name, opt_default) {
  var nameEq = name + '=';
  var parts = this.getParts_();
  for (var i = 0, part; i < parts.length; i++) {
    part = goog.string.trim(parts[i]);
    // startsWith
    if (part.lastIndexOf(nameEq, 0) == 0) {
      return part.substr(nameEq.length);
    }
    if (part == name) {
      return '';
    }
  }
  return opt_default;
};

/**
 * Removes and expires a cookie.
 * @param {string} name  The cookie name.
 * @param {?string=} opt_path  The path of the cookie. If null or not present,
 *     expires the cookie set at the full request path.
 * @param {?string=} opt_domain  The domain of the cookie, or null to expire a
 *     cookie set at the full request host name. If not provided, the default is
 *     null (i.e. cookie at full request host name).
 * @return {boolean} Whether the cookie existed before it was removed.
 */
goog.net.Cookies.prototype.remove = function(name, opt_path, opt_domain) {
  var rv = this.containsKey(name);
  this.set(name, '', 0, opt_path, opt_domain);
  return rv;
};

/**
 * Gets the names for all the cookies.
 * @return {Array<string>} An array with the names of the cookies.
 */
goog.net.Cookies.prototype.getKeys = function() {
  return this.getKeyValues_().keys;
};

/**
 * Gets the values for all the cookies.
 * @return {Array<string>} An array with the values of the cookies.
 */
goog.net.Cookies.prototype.getValues = function() {
  return this.getKeyValues_().values;
};

/**
 * @return {boolean} Whether there are any cookies for this document.
 */
goog.net.Cookies.prototype.isEmpty = function() {
  return !this.getCookie_();
};

/**
 * @return {number} The number of cookies for this document.
 */
goog.net.Cookies.prototype.getCount = function() {
  var cookie = this.getCookie_();
  if (!cookie) {
    return 0;
  }
  return this.getParts_().length;
};

/**
 * Returns whether there is a cookie with the given name.
 * @param {string} key The name of the cookie to test for.
 * @return {boolean} Whether there is a cookie by that name.
 */
goog.net.Cookies.prototype.containsKey = function(key) {
  // substring will return empty string if the key is not found, so the get
  // function will only return undefined
  return goog.isDef(this.get(key));
};

/**
 * Returns whether there is a cookie with the given value. (This is an O(n)
 * operation.)
 * @param {string} value  The value to check for.
 * @return {boolean} Whether there is a cookie with that value.
 */
goog.net.Cookies.prototype.containsValue = function(value) {
  // this O(n) in any case so lets do the trivial thing.
  var values = this.getKeyValues_().values;
  for (var i = 0; i < values.length; i++) {
    if (values[i] == value) {
      return true;
    }
  }
  return false;
};

/**
 * Removes all cookies for this document.  Note that this will only remove
 * cookies from the current path and domain.  If there are cookies set using a
 * subpath and/or another domain these will still be there.
 */
goog.net.Cookies.prototype.clear = function() {
  var keys = this.getKeyValues_().keys;
  for (var i = keys.length - 1; i >= 0; i--) {
    this.remove(keys[i]);
  }
};

/**
 * Private helper function to allow testing cookies without depending on the
 * browser.
 * @param {string} s The cookie string to set.
 * @private
 */
goog.net.Cookies.prototype.setCookie_ = function(s) {
  this.document_.cookie = s;
};

/**
 * Private helper function to allow testing cookies without depending on the
 * browser. IE6 can return null here.
 * @return {string} Returns the `document.cookie`.
 * @private
 */
goog.net.Cookies.prototype.getCookie_ = function() {
  return this.document_.cookie;
};

/**
 * @return {!Array<string>} The cookie split on semi colons.
 * @private
 */
goog.net.Cookies.prototype.getParts_ = function() {
  return (this.getCookie_() || '').split(';');
};

/**
 * Gets the names and values for all the cookies.
 * @return {{keys:!Array<string>, values:!Array<string>}} An object with keys
 *     and values.
 * @private
 */
goog.net.Cookies.prototype.getKeyValues_ = function() {
  var parts = this.getParts_();
  var keys = [], values = [], index, part;
  for (var i = 0; i < parts.length; i++) {
    part = goog.string.trim(parts[i]);
    index = part.indexOf('=');

    if (index == -1) {  // empty name
      keys.push('');
      values.push(part);
    } else {
      keys.push(part.substring(0, index));
      values.push(part.substring(index + 1));
    }
  }
  return {keys: keys, values: values};
};

// TODO(closure-team): This should be a singleton getter instead of a static
// instance.
/**
 * A static default instance.
 * @const {!goog.net.Cookies}
 */
goog.net.cookies =
    new goog.net.Cookies(typeof document == 'undefined' ? null : document);

/**
 * Getter for the static instance of goog.net.Cookies.
 * @return {!goog.net.Cookies}
 */
goog.net.Cookies.getInstance = function() {
  return goog.net.cookies;
};
<|endoftext|>


<commit_before>angular.module('home', [
  'utils'
])

.controller('homeController', [
  '$scope',
  '$http',
  '$state',
  '$stateParams',
  '$location',
  '$rootScope',
  'fileTransfer',
  'linkGeneration',
  'webRTC',
  'packetHandlers',
  'fileUpload',
  function($scope, $http, $state, $stateParams, $location, $rootScope, fileTransfer, linkGeneration, webRTC, packetHandlers, fileUpload) {
    console.log('home controller loaded');

    fileTransfer.myItems = [];
    fileTransfer.conn = [];

    var disconnectingSenderId = null;
    var generateLink = function() {
      $scope.hash = linkGeneration.guid().then(function(val) {
        $scope.hash = val;
        $state.go('room', {
          roomHash: $scope.hash
        });
      });
    };

    $scope.uploadAlert = true;

    $scope.uploadedFiles = {};

    document.getElementById('filesId').addEventListener('change', function() {

      $scope.uploadAlert = false;
      $('#lightningBoltButton').addClass('glowing');

      console.log('home input listener');
      var files = this.files;
      for (var i = 0; i < files.length; i++) {
        if (fileTransfer.myItems.indexOf(files[i]) > -1) {
          continue;
        }
        files[i].beenSent = false;
        fileTransfer.myItems.push(files[i]);
      }

      if (fileTransfer.connected) {
        fileTransfer.conn.forEach(function(connection) {
          webRTC.clearQueue(fileTransfer.myItems, connection);
        });
      }

      fileTransfer.myItems.forEach(function(item, idx, collection) {
        $scope.uploadedFiles[idx] = {
          name: item.name,
          size: fileUpload.convertFileSize(item.size),
          type: item.type
        };
      });
      $scope.$apply();

      console.log('upload myItems', $scope.uploadedFiles);

      if (!fileTransfer.peer) {

        fileTransfer.peer = webRTC.createPeer();
        console.log('SENDER peer created');
        fileTransfer.peer.on('open', function(id) {
          disconnectingSenderId = id;
          $http({
              method: 'POST',
              url: '/api/webrtc/users',
              data: {
                userId: id,
                hash: $scope.hash
              }
            })
            .then(function(result) {
              console.log('SENDER\'s POST response', result.data);
            });
        });
        fileTransfer.peer.on('connection', function(conn) {
          $('#lightningBoltButton').addClass('connectedToPeer');
          // TODO: add text to show that user is connected
          fileTransfer.conn.push(conn);
          console.log('peerJS connection object', conn);

          conn.on('open', function() {
            fileTransfer.connected = true;
            fileTransfer.conn.forEach(function(connection) {
              webRTC.clearQueue(fileTransfer.myItems, connection);
            });
          });

          conn.on('data', function(data) {
            console.log('incoming packet');
            if (data.type === 'file-accepted') {
              packetHandlers.accepted(data, conn, $rootScope);
            } else if (data.type === 'file-offer') {
              packetHandlers.offer(data, conn, $rootScope);
            } else if (data.type === 'file-chunk') {
              packetHandlers.chunk(data, $rootScope);
            }
          });
        });
        generateLink();
      }

      window.onbeforeunload = function(e) {
        e.preventDefault();
        //stops notification from showing
      };

      window.addEventListener('beforeunload', function() {
        console.log("DISCONNECTED");
        $http({
          method: 'POST',
          url: '/api/webrtc/deleteSenderObject',
          data: {
            userId: disconnectingSenderId
          }
        });
      });

    });

  }
]);
<commit_msg>[chore] added modals factory to homeController.js<commit_after>angular.module('home', [
  'utils'
])

.controller('homeController', [
  '$scope',
  '$http',
  '$state',
  '$stateParams',
  '$location',
  '$rootScope',
  'fileTransfer',
  'linkGeneration',
  'webRTC',
  'packetHandlers',
  'fileUpload',
  'modals',
  function($scope, $http, $state, $stateParams, $location, $rootScope, fileTransfer, linkGeneration, webRTC, packetHandlers, fileUpload, modals) {
    console.log('home controller loaded');

    fileTransfer.myItems = [];
    fileTransfer.conn = [];

    var disconnectingSenderId = null;
    var generateLink = function() {
      $scope.hash = linkGeneration.guid().then(function(val) {
        $scope.hash = val;
        $state.go('room', {
          roomHash: $scope.hash
        });
      });
    };

    $scope.uploadAlert = true;

    $scope.uploadedFiles = {};

    document.getElementById('filesId').addEventListener('change', function() {

      $scope.uploadAlert = false;
      $('#lightningBoltButton').addClass('glowing');

      console.log('home input listener');
      var files = this.files;
      for (var i = 0; i < files.length; i++) {
        if (fileTransfer.myItems.indexOf(files[i]) > -1) {
          continue;
        }
        files[i].beenSent = false;
        fileTransfer.myItems.push(files[i]);
      }

      if (fileTransfer.connected) {
        fileTransfer.conn.forEach(function(connection) {
          webRTC.clearQueue(fileTransfer.myItems, connection);
        });
      }

      fileTransfer.myItems.forEach(function(item, idx, collection) {
        $scope.uploadedFiles[idx] = {
          name: item.name,
          size: fileUpload.convertFileSize(item.size),
          type: item.type
        };
      });
      $scope.$apply();

      console.log('upload myItems', $scope.uploadedFiles);

      if (!fileTransfer.peer) {

        fileTransfer.peer = webRTC.createPeer();
        console.log('SENDER peer created');
        fileTransfer.peer.on('open', function(id) {
          disconnectingSenderId = id;
          $http({
              method: 'POST',
              url: '/api/webrtc/users',
              data: {
                userId: id,
                hash: $scope.hash
              }
            })
            .then(function(result) {
              console.log('SENDER\'s POST response', result.data);
            });
        });
        fileTransfer.peer.on('connection', function(conn) {
          $('#lightningBoltButton').addClass('connectedToPeer');
          // TODO: add text to show that user is connected
          fileTransfer.conn.push(conn);
          console.log('peerJS connection object', conn);

          conn.on('open', function() {
            fileTransfer.connected = true;
            fileTransfer.conn.forEach(function(connection) {
              webRTC.clearQueue(fileTransfer.myItems, connection);
            });
          });

          conn.on('data', function(data) {
            console.log('incoming packet');
            if (data.type === 'file-accepted') {
              packetHandlers.accepted(data, conn, $rootScope);
            } else if (data.type === 'file-offer') {
              packetHandlers.offer(data, conn, $rootScope);
            } else if (data.type === 'file-chunk') {
              packetHandlers.chunk(data, $rootScope);
            }
          });
        });
        generateLink();
      }

      window.onbeforeunload = function(e) {
        e.preventDefault();
        //stops notification from showing
      };

      window.addEventListener('beforeunload', function() {
        console.log("DISCONNECTED");
        $http({
          method: 'POST',
          url: '/api/webrtc/deleteSenderObject',
          data: {
            userId: disconnectingSenderId
          }
        });
      });

    });

  }]);
<|endoftext|>


<commit_before>var MoochSentinel = {
    statuses: [],

    updateStatuses: function () {
        console.log("MoochSentinel.updateStatuses()");
        if (GitHub.hasLogin())
            GitHub.requestStatus();

        if (BitBucket.hasLogin())
            BitBucket.requestStatus();

        if (CodeForces.hasLogin())
            CodeForces.requestStatus();
    },

    isOk: function () {
        var me = this, result = false;
        $.each(me.statuses, function (idx, status) {
            if (status.value) {
                result = true;
            }
        });
        console.log('Mooch statuses: ', me.statuses);
        console.log('Mooch status: ', result);
        return result;
    },

    blockedUrls: function () {
        return localStorage['blockedUrls'] ? localStorage['blockedUrls'].split(',') : [];
    },

    render: function () {
        console.log('rerendering badge...');
        var color = null;
        if (this.isOk()) {
            var msg = 'Okay';
            color = '#0F0';
        } else {
            var msg = 'Blocked';
            color = '#F00';
        }
        chrome.browserAction.setBadgeText({text: msg});
        if (color) {
            chrome.browserAction.setBadgeBackgroundColor({color: color});
        }
    },

    isDateValid: function (date) {
        var sameDay = function (date1, date2) {
          if (typeof date1.toDateString !== 'function') date1 = new Date(date1);
          return date1.toDateString() == date2.toDateString();
        };
        return date && sameDay(date, new Date());
    },

    hasStatuses: function () {
        return this.statuses && this.statuses.length > 0;
    },

    findStatus: function (name) {
        var me = this, result = null;
        if (me.hasStatuses()) {
            $.each(me.statuses, function (idx, status) {
                if (status.name == name) {
                    result = status;
                }
            })
        }
        return result;
    },

    setStatus: function (name, value, okDate, error) {
        var me = this;
        var existing = me.findStatus(name);
        if (existing) {
            existing.value = value;
            existing.okDate = okDate;
            existing.error = error;
        } else {
            me.statuses.push({name: name, value: value, okDate: okDate, error: error});
        }

        if (value) {
          var historyDates = localStorage['historyDates'] || "";
          if (historyDates.indexOf(okDate / 1000) == -1) {
            historyDates += ",";
            historyDates += okDate / 1000;
          }
          localStorage['historyDates'] = historyDates;
        }
    },

    updateBlockingFilter: function () {
        var options = {
            urls: MoochSentinel.blockedUrls().length > 0 ? MoochSentinel.blockedUrls() : ["<disabled>"],
            types: ["main_frame"]
        }

      chrome.webRequest.onBeforeRequest.removeListener(MoochSentinel._blockingFilter);
      chrome.webRequest.onBeforeRequest.addListener(MoochSentinel._blockingFilter, options, ["blocking"]);
    },

    _blockingFilter: function (details) {
          // we don't have to block if no status has been checked yet
          if (MoochSentinel.hasStatuses() && !MoochSentinel.isOk()) {
            var redirect = chrome.extension.getURL('blocked.html');
            console.log("interrupting request to ", details.url);
            console.log("redirect: " + redirect);
            return redirect ? { redirectUrl: redirect } : {cancel: true};
          }
          return null;
    }

}

/***
* request should look like {requestType: 'status', name: 'service name', ok: true/false, okDate: timestamp }
*/
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        console.log('message', arguments);
        var wasOk = MoochSentinel.isOk();
        if (request['requestType'] && request['requestType'] == 'status') {
            request.ok = MoochSentinel.isDateValid(request.okDate) && !request.error;
            MoochSentinel.setStatus(request.name, request.ok, request.okDate, request.error);
            MoochSentinel.render();

            var statusChanged = (MoochSentinel.isOk() != wasOk);
            if (statusChanged) {
              chrome.runtime.sendMessage({requestType: 'statusChanged'});
            }
        }

        if (request['requestType'] && request['requestType'] == 'optionsChanged') {
          console.log("Recieved optionsChanged message");
          MoochSentinel.updateBlockingFilter();
          MoochSentinel.updateStatuses();
        }
    });

chrome.runtime.onMessageExternal.addListener(
    function (request, sender) {
        if (sender.update)
            MoochSentinel.updateStatuses();
    });

MoochSentinel.updateBlockingFilter();
<commit_msg>grammar fix<commit_after>var MoochSentinel = {
    statuses: [],

    updateStatuses: function () {
        console.log("MoochSentinel.updateStatuses()");
        if (GitHub.hasLogin())
            GitHub.requestStatus();

        if (BitBucket.hasLogin())
            BitBucket.requestStatus();

        if (CodeForces.hasLogin())
            CodeForces.requestStatus();
    },

    isOk: function () {
        var me = this, result = false;
        $.each(me.statuses, function (idx, status) {
            if (status.value) {
                result = true;
            }
        });
        console.log('Mooch statuses: ', me.statuses);
        console.log('Mooch status: ', result);
        return result;
    },

    blockedUrls: function () {
        return localStorage['blockedUrls'] ? localStorage['blockedUrls'].split(',') : [];
    },

    render: function () {
        console.log('rerendering badge...');
        var color = null;
        if (this.isOk()) {
            var msg = 'Okay';
            color = '#0F0';
        } else {
            var msg = 'Blocked';
            color = '#F00';
        }
        chrome.browserAction.setBadgeText({text: msg});
        if (color) {
            chrome.browserAction.setBadgeBackgroundColor({color: color});
        }
    },

    isDateValid: function (date) {
        var sameDay = function (date1, date2) {
          if (typeof date1.toDateString !== 'function') date1 = new Date(date1);
          return date1.toDateString() == date2.toDateString();
        };
        return date && sameDay(date, new Date());
    },

    hasStatuses: function () {
        return this.statuses && this.statuses.length > 0;
    },

    findStatus: function (name) {
        var me = this, result = null;
        if (me.hasStatuses()) {
            $.each(me.statuses, function (idx, status) {
                if (status.name == name) {
                    result = status;
                }
            })
        }
        return result;
    },

    setStatus: function (name, value, okDate, error) {
        var me = this;
        var existing = me.findStatus(name);
        if (existing) {
            existing.value = value;
            existing.okDate = okDate;
            existing.error = error;
        } else {
            me.statuses.push({name: name, value: value, okDate: okDate, error: error});
        }

        if (value) {
          var historyDates = localStorage['historyDates'] || "";
          if (historyDates.indexOf(okDate / 1000) == -1) {
            historyDates += ",";
            historyDates += okDate / 1000;
          }
          localStorage['historyDates'] = historyDates;
        }
    },

    updateBlockingFilter: function () {
        var options = {
            urls: MoochSentinel.blockedUrls().length > 0 ? MoochSentinel.blockedUrls() : ["<disabled>"],
            types: ["main_frame"]
        }

      chrome.webRequest.onBeforeRequest.removeListener(MoochSentinel._blockingFilter);
      chrome.webRequest.onBeforeRequest.addListener(MoochSentinel._blockingFilter, options, ["blocking"]);
    },

    _blockingFilter: function (details) {
          // we don't have to block if no status has been checked yet
          if (MoochSentinel.hasStatuses() && !MoochSentinel.isOk()) {
            var redirect = chrome.extension.getURL('blocked.html');
            console.log("interrupting request to ", details.url);
            console.log("redirect: " + redirect);
            return redirect ? { redirectUrl: redirect } : {cancel: true};
          }
          return null;
    }

}

/***
* request should look like {requestType: 'status', name: 'service name', ok: true/false, okDate: timestamp }
*/
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        console.log('message', arguments);
        var wasOk = MoochSentinel.isOk();
        if (request['requestType'] && request['requestType'] == 'status') {
            request.ok = MoochSentinel.isDateValid(request.okDate) && !request.error;
            MoochSentinel.setStatus(request.name, request.ok, request.okDate, request.error);
            MoochSentinel.render();

            var statusChanged = (MoochSentinel.isOk() != wasOk);
            if (statusChanged) {
              chrome.runtime.sendMessage({requestType: 'statusChanged'});
            }
        }

        if (request['requestType'] && request['requestType'] == 'optionsChanged') {
          console.log("Received optionsChanged message");
          MoochSentinel.updateBlockingFilter();
          MoochSentinel.updateStatuses();
        }
    });

chrome.runtime.onMessageExternal.addListener(
    function (request, sender) {
        if (sender.update)
            MoochSentinel.updateStatuses();
    });

MoochSentinel.updateBlockingFilter();
<|endoftext|>