<commit_before>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'Memecrunch',
    version:'0.2',
    prepareImgLinks:function (callback) {
        var res = [];

        hoverZoom.urlReplace(res,
            'a[href*="memecrunch.com/meme/"]:not([href$="image.png"])',
            /(.*)\/?$/,
            '$1/image.png'
        );

        //sample url: http://thumbs9.memecrunch.com/meme/CBWLN/un-cumple-la-patgona-lucia-unas-47-primaveras/image.png?w=92
        // remove ?...
        hoverZoom.urlReplace(res,
            'img[src]',
            /\?.*/,
            ''
        );

        callback($(res));
    }
});
<commit_msg>Fix for plug-in: Memecrunch<commit_after>var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'Memecrunch',
    version:'0.3',
    prepareImgLinks:function (callback) {
        var res = [];

        hoverZoom.urlReplace(res,
            'a[href*="memecrunch.com/meme/"]:not([href$="image.png"])',
            /(.*)\/?$/,
            '$1/image.png'
        );

        //sample url: http://thumbs9.memecrunch.com/meme/CBWLN/un-cumple-la-patgona-lucia-unas-47-primaveras/image.png?w=92
        // remove ?...
        hoverZoom.urlReplace(res,
            'img[src*="memecrunch.com/meme/"]',
            /\?.*/,
            ''
        );

        callback($(res), this.name);
    }
});
<|endoftext|>


<commit_before>import * as types from '../constants/actionTypes';
import initialState from './initialState';
function sortByOrder(a,b) {
  return a.order > b.order ? 1 : (a.order < b.order ? -1 : 0);
}

export default function authReducer(state = initialState.app, action) {
  switch (action.type) {
    case types.REMOVE_MESSAGE:
      return {
        ...state,
        messages: state.messages
          .filter(m => m.id !== action.id)
          .sort(sortByOrder)
          .map((m, i) => { m.order = i; return m; })
      };
    case types.FADE_MESSAGE:
      return {
        ...state,
        messages: [
          ...state.messages.filter(m => m.id !== action.id),
          {
            ...state.messages.filter(m => m.id === action.id)[0],
            hidden: true
          }
        ].sort(sortByOrder)
      };
    case types.CLEAR_MESSAGES:
      return {
        ...state,
        messages: []
      };
    case types.SHOW_MESSAGE:
      return {
        ...state,
        messages: [
          ...state.messages,
          { ...action, order: state.messages.length }
        ]
      };
    default:
      return state;
  }
}
<commit_msg>remove state mutation in appReducer<commit_after>import * as types from '../constants/actionTypes';
import initialState from './initialState';
function sortByOrder(a,b) {
  return a.order > b.order ? 1 : (a.order < b.order ? -1 : 0);
}

export default function authReducer(state = initialState.app, action) {
  switch (action.type) {
    case types.REMOVE_MESSAGE:
      return {
        ...state,
        messages: [...state.messages]
          .filter(m => m.id !== action.id)
          .sort(sortByOrder)
          .map((m, i) => { return { ...m, order: i }; })
      };
    case types.FADE_MESSAGE:
      return {
        ...state,
        messages: [
          ...state.messages.filter(m => m.id !== action.id),
          {
            ...state.messages.filter(m => m.id === action.id)[0],
            hidden: true
          }
        ].sort(sortByOrder)
      };
    case types.CLEAR_MESSAGES:
      return {
        ...state,
        messages: []
      };
    case types.SHOW_MESSAGE:
      return {
        ...state,
        messages: [
          ...state.messages,
          { ...action, order: state.messages.length }
        ]
      };
    default:
      return state;
  }
}
<|endoftext|>


<commit_before>// Check various bits of the HELO string
var net_utils = require('./net_utils');

var checks = [
    'helo_init',             // config loading, multiplicity detection
    'helo_no_dot',           // HELO has no "dot" in hostname
    'helo_match_re',         // List of regexps
    'helo_raw_ip',           // HELO raw IP
    'helo_is_dynamic',       // HELO looks dynamic
    'helo_big_company',      // Well known HELOs that must match rdns
    'helo_literal_mismatch', // IP literal that doesn't match remote IP
    'helo_valid_tld',        // hostname has a valid TLD
    'helo_match_rdns',       // hostname matches rDNS
    'helo_mismatch',         // hostname differs between invocations
];

var cfg;
var reject = true;

exports.register = function () {
    var plugin = this;

    for (var i=0; i < checks.length; i++) {
        var hook = checks[i];
        plugin.register_hook('helo', hook);
        plugin.register_hook('ehlo', hook);
    }
};

exports.hook_connect = function (next, connection) {
    cfg = this.config.get('helo.checks.ini'); // { booleans: ['main.reject'], });
    if (cfg.main.reject !== undefined) reject = cfg.main.reject;
    return next();
};

exports.helo_init = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (!hc) {     // first HELO result
        connection.results.add(plugin, {helo_host: helo});
        return next();
    }

    // we've been here before
    connection.results.add(plugin, {multi: true});

    return next();
};

exports.helo_mismatch = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    var prev_helo = hc.helo_host;
    if (!prev_helo) {
        connection.results.add(plugin, {skip: 'mismatch'});
        return next();
    }

    if (prev_helo === helo) {
        connection.results.add(plugin, {pass: 'mismatch'});
        return next();
    }

    connection.results.add(plugin, {fail: 'mismatch(' + prev_helo + ' / ' + helo + ')'});
    return next();
};

exports.helo_no_dot = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!cfg.main.check_no_dot      ||
        (cfg.main.skip_private_ip   &&
        net_utils.is_rfc1918(connection.remote_ip)))
    {
        connection.results.add(plugin, {skip: 'no_dot'});
        return next();
    }

    if (!/\./.test(helo)) {
        connection.results.add(plugin, {fail: 'no_dot'});
        if (reject) return next(DENY, 'HELO must have a dot');
    }
    else {
        connection.results.add(plugin, {pass: 'no_dot'});
    }

    return next();
};

exports.helo_match_re = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    var regexps = plugin.config.get('helo.checks.regexps', 'list');

    var fail=0;
    for (var i=0; i < regexps.length; i++) {
        var re = new RegExp('^' + regexps[i] + '$');
        if (re.test(helo)) {
            connection.results.add(plugin, {fail: 'match_re(' + regexps[i] + ')'});
            fail++;
        }
    }
    if (fail && reject) return next(DENY, "BAD HELO");
    if (!fail) connection.results.add(plugin, {pass: 'match_re'});
    return next();
};

exports.helo_match_rdns = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!cfg.main.check_rdns_match) {
        connection.results.add(plugin, {skip: 'rdns_match(config)'});
        return next();
    }

    if (!helo) {
        connection.results.add(plugin, {fail: 'rdns_match(empty)'});
        return next();
    }

    if (helo.match(/^\[(?:[0-9\.]+)\]$/)) {
        connection.results.add(plugin, {fail: 'rdns_match(literal)'});
        return next();
    }

    var r_host = connection.remote_host;
    if (r_host && helo === r_host) {
        connection.results.add(plugin, {pass: 'rdns_match(exact)'});
        return next();
    }

    if (net_utils.get_organizational_domain(r_host) ===
        net_utils.get_organizational_domain(helo)) {
        connection.results.add(plugin, {pass: 'rdns_match(org_dom)'});
        return next();
    }

    connection.results.add(plugin, {fail: 'rdns_match'});
    return next();
};

exports.helo_raw_ip = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!cfg.main.check_raw_ip) {
        connection.results.add(plugin, {skip: 'raw_ip(config)'});
        return next();
    }
    if (cfg.main.skip_private_ip && net_utils.is_rfc1918(connection.remote_ip)) {
        connection.results.add(plugin, {skip: 'raw_ip(private)'});
        return next();
    }

    // RFC 2821, 4.1.1.1  Address literals must be in brackets
    // RAW IPs must be formatted: "[1.2.3.4]" not "1.2.3.4" in HELO
    if(/^\d+\.\d+\.\d+\.\d+$/.test(helo)) {
        connection.results.add(plugin, {fail: 'raw_ip(invalid literal)'});
        if (reject) return next(DENY, "Invalid address format in HELO");
        return next();
    }

    connection.results.add(plugin, {pass: 'raw_ip'});
    return next();
};

exports.helo_is_dynamic = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!cfg.main.check_dynamic) {
        connection.results.add(plugin, {skip: 'dynamic(config)'});
        return next();
    }
    if (cfg.main.skip_private_ip && net_utils.is_rfc1918(connection.remote_ip)) {
        connection.results.add(plugin, {skip: 'dynamic(private)'});
        return next();
    }

    // Skip if no dots or an IP literal or address
    if (!/\./.test(helo)) {
        connection.results.add(plugin, {skip: 'dynamic(no dots)'});
        return next();
    }

    if (/^\[?\d+\.\d+\.\d+\.\d+\]?$/.test(helo)) {
        connection.results.add(plugin, {skip: 'dynamic(literal)'});
        return next();
    }

    if (net_utils.is_ip_in_str(connection.remote_ip, helo)) {
        connection.results.add(plugin, {fail: 'dynamic'});
        if (reject) return next(DENY, 'HELO is dynamic');
        return next();
    }

    connection.results.add(plugin, {pass: 'dynamic'});
    return next();
};

exports.helo_big_company = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    var rdns = connection.remote_host;

    if (!cfg.bigco) {
        connection.results.add(plugin, {err: 'big_co(config missing)'});
        return next();
    }
    if (!cfg.bigco[helo]) {
        connection.results.add(plugin, {skip: 'big_co(config)'});
        return next();
    }

    var allowed_rdns = cfg.bigco[helo].split(/,/);
    for (var i=0; i < allowed_rdns.length; i++) {
        var re = new RegExp(allowed_rdns[i].replace(/\./g, '\\.') + '$');
        if (re.test(rdns)) {
            connection.results.add(plugin, {pass: 'big_co'});
            return next();
        }
    }

    connection.results.add(plugin, {fail: 'big_co'});
    if (reject) return next(DENY, "You are not who you say you are");
    return next();
};

exports.helo_literal_mismatch = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!cfg.main.check_literal_mismatch) {
        connection.results.add(plugin, {skip: 'literal_mismatch(config)'});
        return next();
    }
    if (cfg.main.skip_private_ip && net_utils.is_rfc1918(connection.remote_ip)) {
        connection.results.add(plugin, {skip: 'literal_mismatch(private)'});
        return next();
    }

    var literal = /^\[(\d+\.\d+\.\d+\.\d+)\]$/.exec(helo);
    if (!literal) {
        connection.results.add(plugin, {pass: 'literal_mismatch'});
        return next();
    }

    if (parseInt(cfg.main.check_literal_mismatch) === 2) {
        // Only match the /24
        if (literal[1].split(/\./).splice(0,3).join('.') !==
            connection.remote_ip.split(/\./).splice(0,3).join('.'))
        {
            connection.results.add(plugin, {fail: 'literal_mismatch'});
            if (reject) return next(DENY, 'HELO IP literal not in the same /24 as your IP address');
            return next();
        }
        connection.results.add(plugin, {pass: 'literal_mismatch'});
        return next();
    }

    if (literal[1] !== connection.remote_ip) {
        connection.results.add(plugin, {pass: 'literal_mismatch'});
        if (reject) return next(DENY, 'HELO IP literal does not match your IP address');
        return next();
    }

    connection.results.add(plugin, {pass: 'literal_mismatch'});
    return next();
};

exports.helo_valid_tld = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!cfg.main.require_valid_tld) {
        connection.results.add(plugin, {skip: 'valid_tld(config)'});
        return next();
    }
    if (cfg.main.skip_private_ip && net_utils.is_rfc1918(connection.remote_ip)) {
        connection.results.add(plugin, {skip: 'valid_tld(private)'});
        return next();
    }

    if (/^\[\d+\.\d+\.\d+\.\d+\]$/.test(helo)) {
        connection.results.add(plugin, {skip: 'valid_tld(literal)'});
        return next();
    }

    var tld = (helo.split(/\./).reverse())[0];
    if (net_utils.is_public_suffix(tld)) {
        connection.results.add(plugin, {pass: 'valid_tld'});
        return next();
    }

    connection.results.add(plugin, {fail: 'valid_tld('+tld+')'});
    if (reject) return next(DENY, "HELO must have a valid TLD");
    return next();
};
<commit_msg>helo: remove helo_ prefix from function names<commit_after>// Check various bits of the HELO string
var net_utils = require('./net_utils');

var checks = [
    'init',               // config loading, multiplicity detection
    'no_dot',             // HELO has no "dot" in hostname
    'match_re',           // List of regexps
    'raw_ip',             // HELO raw IP
    'is_dynamic',         // HELO looks dynamic
    'big_company',        // Well known HELOs that must match rdns
    'literal_mismatch',   // IP literal that doesn't match remote IP
    'valid_tld',          // hostname has a valid TLD
    'match_rdns',         // hostname matches rDNS
    'mismatch',           // hostname differs between invocations
];

exports.register = function () {
    var plugin = this;

    plugin.cfg = this.config.get('helo.checks.ini', { booleans: [], });

    for (var i=0; i < checks.length; i++) {
        var hook = checks[i];
        plugin.register_hook('helo', hook);
        plugin.register_hook('ehlo', hook);
    }
};

exports.hook_connect = function (next, connection) {
    this.cfg = this.config.get('helo.checks.ini', { booleans: [], });
    return next();
};

exports.init = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (!hc) {     // first HELO result
        connection.results.add(plugin, {helo_host: helo});
        return next();
    }

    // we've been here before
    connection.results.add(plugin, {multi: true});

    return next();
};

exports.mismatch = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    var prev_helo = hc.helo_host;
    if (!prev_helo) {
        connection.results.add(plugin, {skip: 'mismatch'});
        return next();
    }

    if (prev_helo === helo) {
        connection.results.add(plugin, {pass: 'mismatch'});
        return next();
    }

    connection.results.add(plugin, {fail: 'mismatch(' + prev_helo + ' / ' + helo + ')'});
    return next();
};

exports.no_dot = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!plugin.cfg.main.check_no_dot      ||
        (plugin.cfg.main.skip_private_ip   &&
        net_utils.is_rfc1918(connection.remote_ip)))
    {
        connection.results.add(plugin, {skip: 'no_dot'});
        return next();
    }

    if (!/\./.test(helo)) {
        connection.results.add(plugin, {fail: 'no_dot'});
        if (plugin.cfg.reject.no_dot) return next(DENY, 'HELO must have a dot');
    }
    else {
        connection.results.add(plugin, {pass: 'no_dot'});
    }

    return next();
};

exports.match_re = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    var regexps = plugin.config.get('helo.checks.regexps', 'list');

    var fail=0;
    for (var i=0; i < regexps.length; i++) {
        var re = new RegExp('^' + regexps[i] + '$');
        if (re.test(helo)) {
            connection.results.add(plugin, {fail: 'match_re(' + regexps[i] + ')'});
            fail++;
        }
    }
    if (fail && plugin.cfg.reject.match_re) return next(DENY, "BAD HELO");
    if (!fail) connection.results.add(plugin, {pass: 'match_re'});
    return next();
};

exports.match_rdns = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!plugin.cfg.main.check_rdns_match) {
        connection.results.add(plugin, {skip: 'rdns_match(config)'});
        return next();
    }

    if (!helo) {
        connection.results.add(plugin, {fail: 'rdns_match(empty)'});
        return next();
    }

    if (helo.match(/^\[(?:[0-9\.]+)\]$/)) {
        connection.results.add(plugin, {fail: 'rdns_match(literal)'});
        return next();
    }

    var r_host = connection.remote_host;
    if (r_host && helo === r_host) {
        connection.results.add(plugin, {pass: 'rdns_match(exact)'});
        return next();
    }

    if (net_utils.get_organizational_domain(r_host) ===
        net_utils.get_organizational_domain(helo)) {
        connection.results.add(plugin, {pass: 'rdns_match(org_dom)'});
        return next();
    }

    connection.results.add(plugin, {fail: 'rdns_match'});
    return next();
};

exports.raw_ip = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!plugin.cfg.main.check_raw_ip) {
        connection.results.add(plugin, {skip: 'raw_ip(config)'});
        return next();
    }
    if (plugin.cfg.main.skip_private_ip && net_utils.is_rfc1918(connection.remote_ip)) {
        connection.results.add(plugin, {skip: 'raw_ip(private)'});
        return next();
    }

    // RFC 2821, 4.1.1.1  Address literals must be in brackets
    // RAW IPs must be formatted: "[1.2.3.4]" not "1.2.3.4" in HELO
    if(/^\d+\.\d+\.\d+\.\d+$/.test(helo)) {
        connection.results.add(plugin, {fail: 'raw_ip(invalid literal)'});
        if (plugin.cfg.reject.raw_ip) return next(DENY, "Invalid address format in HELO");
        return next();
    }

    connection.results.add(plugin, {pass: 'raw_ip'});
    return next();
};

exports.is_dynamic = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!plugin.cfg.main.check_dynamic) {
        connection.results.add(plugin, {skip: 'dynamic(config)'});
        return next();
    }
    if (plugin.cfg.main.skip_private_ip && net_utils.is_rfc1918(connection.remote_ip)) {
        connection.results.add(plugin, {skip: 'dynamic(private)'});
        return next();
    }

    // Skip if no dots or an IP literal or address
    if (!/\./.test(helo)) {
        connection.results.add(plugin, {skip: 'dynamic(no dots)'});
        return next();
    }

    if (/^\[?\d+\.\d+\.\d+\.\d+\]?$/.test(helo)) {
        connection.results.add(plugin, {skip: 'dynamic(literal)'});
        return next();
    }

    if (net_utils.is_ip_in_str(connection.remote_ip, helo)) {
        connection.results.add(plugin, {fail: 'dynamic'});
        if (plugin.cfg.reject.is_dynamic) return next(DENY, 'HELO is dynamic');
        return next();
    }

    connection.results.add(plugin, {pass: 'dynamic'});
    return next();
};

exports.big_company = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    var rdns = connection.remote_host;

    if (!plugin.cfg.bigco) {
        connection.results.add(plugin, {err: 'big_co(config missing)'});
        return next();
    }
    if (!plugin.cfg.bigco[helo]) {
        connection.results.add(plugin, {skip: 'big_co(config)'});
        return next();
    }

    var allowed_rdns = plugin.cfg.bigco[helo].split(/,/);
    for (var i=0; i < allowed_rdns.length; i++) {
        var re = new RegExp(allowed_rdns[i].replace(/\./g, '\\.') + '$');
        if (re.test(rdns)) {
            connection.results.add(plugin, {pass: 'big_co'});
            return next();
        }
    }

    connection.results.add(plugin, {fail: 'big_co'});
    if (plugin.cfg.reject.big_company) return next(DENY, "You are not who you say you are");
    return next();
};

exports.literal_mismatch = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!plugin.cfg.main.check_literal_mismatch) {
        connection.results.add(plugin, {skip: 'literal_mismatch(config)'});
        return next();
    }
    if (plugin.cfg.main.skip_private_ip && net_utils.is_rfc1918(connection.remote_ip)) {
        connection.results.add(plugin, {skip: 'literal_mismatch(private)'});
        return next();
    }

    var literal = /^\[(\d+\.\d+\.\d+\.\d+)\]$/.exec(helo);
    if (!literal) {
        connection.results.add(plugin, {pass: 'literal_mismatch'});
        return next();
    }

    if (parseInt(plugin.cfg.main.check_literal_mismatch) === 2) {
        // Only match the /24
        if (literal[1].split(/\./).splice(0,3).join('.') !==
            connection.remote_ip.split(/\./).splice(0,3).join('.'))
        {
            connection.results.add(plugin, {fail: 'literal_mismatch'});
            if (plugin.cfg.reject.literal_mismatch) return next(DENY, 'HELO IP literal not in the same /24 as your IP address');
            return next();
        }
        connection.results.add(plugin, {pass: 'literal_mismatch'});
        return next();
    }

    if (literal[1] !== connection.remote_ip) {
        connection.results.add(plugin, {pass: 'literal_mismatch'});
        if (plugin.cfg.reject.literal_mismatch) return next(DENY, 'HELO IP literal does not match your IP address');
        return next();
    }

    connection.results.add(plugin, {pass: 'literal_mismatch'});
    return next();
};

exports.valid_tld = function (next, connection, helo) {
    var plugin = this;

    var hc = connection.results.get('helo.checks');
    if (hc && hc.multi) return next();

    if (!plugin.cfg.main.require_valid_tld) {
        connection.results.add(plugin, {skip: 'valid_tld(config)'});
        return next();
    }
    if (plugin.cfg.main.skip_private_ip && net_utils.is_rfc1918(connection.remote_ip)) {
        connection.results.add(plugin, {skip: 'valid_tld(private)'});
        return next();
    }

    if (/^\[\d+\.\d+\.\d+\.\d+\]$/.test(helo)) {
        connection.results.add(plugin, {skip: 'valid_tld(literal)'});
        return next();
    }

    var tld = (helo.split(/\./).reverse())[0];
    if (net_utils.is_public_suffix(tld)) {
        connection.results.add(plugin, {pass: 'valid_tld'});
        return next();
    }

    connection.results.add(plugin, {fail: 'valid_tld('+tld+')'});
    if (plugin.cfg.reject.valid_tld) return next(DENY, "HELO must have a valid TLD");
    return next();
};
<|endoftext|>


<commit_before>/**
	The MIT License (MIT)

	Copyright (c) 2014 MyChannel-Apps.de

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	@author		Adrian Preuß, Bizarrus
*/

require('framework/KFramework.js');

var App = (new function() {
	/* App Events */
	this.onAppStart = function() {
		Hooks.do('onAppStart');
	};

	this.onPrepareShutdown = function(secondsTillShutdown) {
		Hooks.do('onPrepareShutdown', secondsTillShutdown);
	};

	this.onShutdown = function() {
		Hooks.do('onShutdown');

		/* Required if you using Cronjobs! */
		Cron.onShutdown();
	};

	/* User Events */
	this.onUserJoined = function(user) {
		Hooks.do('onUserJoined', user);
	};

	this.onUserLeft = function(user) {
		Hooks.do('onUserLeft', user);
	};

	/* Access Events */
	this.mayJoinChannel = function(user) {
		Hooks.do('mayJoinChannel', user);
	};

	/* Message Events */
	this.maySendPublicMessage = function(publicMessage) {
		Hooks.do('maySendPublicMessage', publicMessage);
	};

	this.onPrivateMessage = function(privareMessage) {
		Hooks.do('onPrivateMessage', privareMessage);
	};

	this.onPublicMessage = function(publicMessage) {
		Hooks.do('onPublicMessage', publicMessage);
	};

	/* Knuddel Events */
	this.onKnuddelReceived = function(sender, receiver, knuddelAmount) {
		Hooks.do('onKnuddelReceived', sender, receiver, knuddelAmount);
	};

	/* DICE Events */
	this.onUserDiced = function(diceEvent) {
		Hooks.do('onUserDiced', diceEvent);
	};

	/* Chat Commands */
	this.chatCommands = {};
}());<commit_msg>Hook-Example<commit_after>/**
	The MIT License (MIT)

	Copyright (c) 2014 MyChannel-Apps.de

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	@author		Adrian Preuß, Bizarrus
*/

require('framework/KFramework.js');

// Example Hooks
Hooks.add('onAppStart', function() {
	Bot.public('App wurde gestartet!');
});

Hooks.add('onUserJoined', function(user) {
	Bot.private(user, 'Willkommen!');
}, 5);

var App = (new function() {
	/* App Events */
	this.onAppStart = function() {
		Hooks.do('onAppStart');
	};

	this.onPrepareShutdown = function(secondsTillShutdown) {
		Hooks.do('onPrepareShutdown', secondsTillShutdown);
	};

	this.onShutdown = function() {
		Hooks.do('onShutdown');

		/* Required if you using Cronjobs! */
		Cron.onShutdown();
	};

	/* User Events */
	this.onUserJoined = function(user) {
		Hooks.do('onUserJoined', user);
	};

	this.onUserLeft = function(user) {
		Hooks.do('onUserLeft', user);
	};

	/* Access Events */
	this.mayJoinChannel = function(user) {
		Hooks.do('mayJoinChannel', user);
	};

	/* Message Events */
	this.maySendPublicMessage = function(publicMessage) {
		Hooks.do('maySendPublicMessage', publicMessage);
	};

	this.onPrivateMessage = function(privareMessage) {
		Hooks.do('onPrivateMessage', privareMessage);
	};

	this.onPublicMessage = function(publicMessage) {
		Hooks.do('onPublicMessage', publicMessage);
	};

	/* Knuddel Events */
	this.onKnuddelReceived = function(sender, receiver, knuddelAmount) {
		Hooks.do('onKnuddelReceived', sender, receiver, knuddelAmount);
	};

	/* DICE Events */
	this.onUserDiced = function(diceEvent) {
		Hooks.do('onUserDiced', diceEvent);
	};

	/* Chat Commands */
	this.chatCommands = {};
}());<|endoftext|>


<commit_before><commit_msg>Testcase for hidden contract editor delete button<commit_after><|endoftext|>


<commit_before>
/* Contains all source code modules assigned to RG. */

const RG = require('./rg.js');

// No deps to RG.SubElems
RG.Random = require('./random.js');
RG.Mixin = require('./mixin.js');
RG.Geometry = require('./geometry.js');
RG.Object = require('./object.js');
RG.Time = require('./time.js');
RG.Template = require('./template.js');

// Minor deps to other exports
RG.Component = require('./component.js');
RG.Item = require('./item.js');
RG.Spell = require('./spell.js');
RG.System = require('./system.js');
RG.BTree = require('./aisequence.js');
RG.Brain = require('./brain.js');
RG.Inv = require('./inv.js');
RG.Actor = require('./actor.js');
RG.Element = require('./element.js');

RG.Map = require('./map.js');
RG.World = require('./world.js');

RG.Effects = require('../data/effects.js');
RG.ObjectShell = require('./objectshellparser.js');

RG.Game = require('./game.js');
RG.Factory = require('./factory.js');

RG.Names = require('../data/name-gen.js');
RG.Overworld = require('./overworld.js');

RG.Game.FromJSON = require('./game.fromjson.js');

RG.Factory.Game = require('./factory.game.js');

module.exports = RG;

<commit_msg>Added RG.Animation.<commit_after>
/* Contains all source code modules assigned to RG. */

const RG = require('./rg.js');

// No deps to RG.SubElems
RG.Random = require('./random.js');
RG.Mixin = require('./mixin.js');
RG.Geometry = require('./geometry.js');
RG.Object = require('./object.js');
RG.Time = require('./time.js');
RG.Template = require('./template.js');
RG.Animation = require('./animation.js');

// Minor deps to other exports
RG.Component = require('./component.js');
RG.Item = require('./item.js');
RG.Spell = require('./spell.js');
RG.System = require('./system.js');
RG.BTree = require('./aisequence.js');
RG.Brain = require('./brain.js');
RG.Inv = require('./inv.js');
RG.Actor = require('./actor.js');
RG.Element = require('./element.js');

RG.Map = require('./map.js');
RG.World = require('./world.js');

RG.Effects = require('../data/effects.js');
RG.ObjectShell = require('./objectshellparser.js');

RG.Game = require('./game.js');
RG.Factory = require('./factory.js');

RG.Names = require('../data/name-gen.js');
RG.Overworld = require('./overworld.js');

RG.Game.FromJSON = require('./game.fromjson.js');

RG.Factory.Game = require('./factory.game.js');

module.exports = RG;

<|endoftext|>


<commit_before>import React, { Component } from 'react';

export default class Main extends Component {
  constructor(props) {
    super(props);
    this.recognition = this.initializeSpeechRecognition();
  }

  initializeSpeechRecognition() {
    let recognition = new webkitSpeechRecognition();
    recognition.lang = 'ja';

    // 録音終了時トリガー
    recognition.addEventListener('result', (event) => {
      console.log(event.results.item(0).item(0).transcript)
    }, false);

    return recognition;
  }

  record() {
    // 録音開始
    this.recognition.start();
  }

  speech() {
    speechSynthesis.speak(
      new SpeechSynthesisUtterance(this.refs.record.value)
    );
  }

  render() {
    return(

Web Speech API

          <button onClick={ () => this.speech() }>Speech</button>
          <input type="text" ref="record"/>

          <button onClick={ () => this.record() }>Record</button>

    );
  }
}
<commit_msg>refactoring<commit_after>import React, { Component } from 'react';

export default class Main extends Component {
  constructor(props) {
    super(props);
    this.recognition = this.initializeSpeechRecognition();
  }

  initializeSpeechRecognition() {
    let recognition = new webkitSpeechRecognition();
    recognition.lang = 'ja';

    recognition.onresult = (event) => {
      console.log(event.results[0][0].transcript)
    }

    return recognition;
  }

  record() {
    // 録音開始
    this.recognition.start();
  }

  speech() {
    speechSynthesis.speak(
      new SpeechSynthesisUtterance(this.refs.speech.value)
    );
  }

  render() {
    return(

Web Speech API

          <button onClick={ () => this.speech() }>Speech</button>
          <input type="text" ref="speech"/>

          <button onClick={ () => this.record() }>Record</button>

    );
  }
}
<|endoftext|>


<commit_before>var responseBuilder = require('./response-builder');
var Error = require('./error');
module.exports = {
    'GET' : function get(clientRequest, serverResponse, id, queryParams, service){
            //Check and see if this get has an ID associated with it.
            if(id != undefined && id != ''){
                console.log('GET method on resource: ' + service.resourceName + ' with id: ' + id);
                service.getById(id,
                    function(err, response){
                        if(err){
                            responseBuilder.sendErrorResponse(serverResponse, err)
                        }else {
                            responseBuilder.sendSingleResponse(serverResponse, 200, clientRequest.headers['host'], service.resourceName, response)
                        }

                    });
            //No ID means it is against a collection
            } else {
                console.log('GET method called on resource: ' + service.resourceName + ' without id');
                //Set up sort field from query param.
                var sortField = undefined;
                if(queryParams.sort != undefined){
                    sortField = queryParams.sort;
                    delete queryParams['sort'];
                }

                //Set up pagination data from query params.
                var paginationData = {};
                if(queryParams.pageNumber != undefined){
                    paginationData.pageNumber =  parseInt(queryParams.pageNumber);
                    delete queryParams['pageNumber'];
                } else {
                    paginationData.pageNumber =  1;
                }
                if(queryParams.pageSize != undefined){
                    paginationData.pageSize =  parseInt(queryParams.pageSize);
                    delete queryParams['pageSize'];
                } else {
                    paginationData.pageSize = 10;
                }
                console.log('Query data setup as:\n' +  JSON.stringify(queryParams) + '\n' + sortField + '\n' + JSON.stringify(paginationData));

                queryAndSendResponse(serverResponse, clientRequest.headers['host'], service, queryParams, sortField, paginationData);
            }
    },

    'POST' : function post(clientRequest, serverResponse, body, resource){
        console.log('POST method on resource: ' + resource.resourceName);
        try {
            var bodyObject = JSON.parse(body);
        } catch(err){
            responseBuilder.sendErrorResponse(serverResponse, new Error(400, 'Invalid JSON sent.\n' + err));
        }
        if(bodyObject != undefined) {
            resource.post(bodyObject,function(err,response){
                if(err){
                    responseBuilder.sendErrorResponse(serverResponse, error);
                }
                else{
                    responseBuilder.sendSingleResponse(serverResponse, 201, clientRequest.headers['host'], resource.resourceName, response)
                }
            })
        }
    },

    'PUT' : function put(clientRequest, serverResponse, body, id, service){
        console.log('PUT method on resource: ' + service.resourceName + ' with id: ' + id);
        if(id == ''){
            responseBuilder.sendErrorResponse(serverResponse, new Error(400, 'Cannot put a collection root.'));
        } else {
            try {
                var bodyObject = JSON.parse(body);
            } catch(err){
                responseBuilder.sendErrorResponse(serverResponse, new Error(400, 'Invalid JSON sent.\n' + err));
            }
            if(bodyObject != undefined){
                service.put(id, bodyObject, function(err){
                    if(err){
                        responseBuilder.sendErrorResponse(serverResponse, err)
                    } else{
                        responseBuilder.sendEmptyResponse(serverResponse)
                    }
                })
            }
        }
    },

    'DELETE' : function del(clientRequest, serverResponse, id, service){
        console.log('DELETE method on resource: ' + service.resourceName + ' with id: ' + id);
        if(id != undefined){
            service.del(id, function(err){
                if(err){
                    responseBuilder.sendErrorResponse(serverResponse, err);
                } else{
                    responseBuilder.sendEmptyResponse(serverResponse)
                }
            })
        } else {
            responseBuilder.sendErrorResponse(serverResponse, new Error(400, 'Bad Request: Cannot Delete Collection.'));
        }
    },
};

function queryAndSendResponse(serverResponse, host, service, queryParams, sortField, paginationData) {
    var items = []
    service.find(queryParams, sortField, paginationData,
        function(err, responses){
            if(err){
                responseBuilder.sendErrorResponse(serverResponse, err);
            }
            console.log('Building multiple responses from query.');
            for(var current in responses){
                var response = responses[current];
                responseBuilder.addLocation(host, service.resourceName, response.id, response.body);
                items.push(response.body);
            }

            var body = JSON.stringify(items);
            var bodyLength = Buffer.byteLength(body, 'utf-8');
            responseBuilder.writeHeaders(serverResponse, bodyLength, 200);
            serverResponse.end(body);
        }
    );
};

<commit_msg>Typo on error<commit_after>var responseBuilder = require('./response-builder');
var Error = require('./error');
module.exports = {
    'GET' : function get(clientRequest, serverResponse, id, queryParams, service){
            //Check and see if this get has an ID associated with it.
            if(id != undefined && id != ''){
                console.log('GET method on resource: ' + service.resourceName + ' with id: ' + id);
                service.getById(id,
                    function(err, response){
                        if(err){
                            responseBuilder.sendErrorResponse(serverResponse, err)
                        }else {
                            responseBuilder.sendSingleResponse(serverResponse, 200, clientRequest.headers['host'], service.resourceName, response)
                        }

                    });
            //No ID means it is against a collection
            } else {
                console.log('GET method called on resource: ' + service.resourceName + ' without id');
                //Set up sort field from query param.
                var sortField = undefined;
                if(queryParams.sort != undefined){
                    sortField = queryParams.sort;
                    delete queryParams['sort'];
                }

                //Set up pagination data from query params.
                var paginationData = {};
                if(queryParams.pageNumber != undefined){
                    paginationData.pageNumber =  parseInt(queryParams.pageNumber);
                    delete queryParams['pageNumber'];
                } else {
                    paginationData.pageNumber =  1;
                }
                if(queryParams.pageSize != undefined){
                    paginationData.pageSize =  parseInt(queryParams.pageSize);
                    delete queryParams['pageSize'];
                } else {
                    paginationData.pageSize = 10;
                }
                console.log('Query data setup as:\n' +  JSON.stringify(queryParams) + '\n' + sortField + '\n' + JSON.stringify(paginationData));

                queryAndSendResponse(serverResponse, clientRequest.headers['host'], service, queryParams, sortField, paginationData);
            }
    },

    'POST' : function post(clientRequest, serverResponse, body, resource){
        console.log('POST method on resource: ' + resource.resourceName);
        try {
            var bodyObject = JSON.parse(body);
        } catch(err){
            responseBuilder.sendErrorResponse(serverResponse, new Error(400, 'Invalid JSON sent.\n' + err));
        }
        if(bodyObject != undefined) {
            resource.post(bodyObject,function(err,response){
                if(err){
                    responseBuilder.sendErrorResponse(serverResponse, err);
                }
                else{
                    responseBuilder.sendSingleResponse(serverResponse, 201, clientRequest.headers['host'], resource.resourceName, response)
                }
            })
        }
    },

    'PUT' : function put(clientRequest, serverResponse, body, id, service){
        console.log('PUT method on resource: ' + service.resourceName + ' with id: ' + id);
        if(id == ''){
            responseBuilder.sendErrorResponse(serverResponse, new Error(400, 'Cannot put a collection root.'));
        } else {
            try {
                var bodyObject = JSON.parse(body);
            } catch(err){
                responseBuilder.sendErrorResponse(serverResponse, new Error(400, 'Invalid JSON sent.\n' + err));
            }
            if(bodyObject != undefined){
                service.put(id, bodyObject, function(err){
                    if(err){
                        responseBuilder.sendErrorResponse(serverResponse, err)
                    } else{
                        responseBuilder.sendEmptyResponse(serverResponse)
                    }
                })
            }
        }
    },

    'DELETE' : function del(clientRequest, serverResponse, id, service){
        console.log('DELETE method on resource: ' + service.resourceName + ' with id: ' + id);
        if(id != undefined){
            service.del(id, function(err){
                if(err){
                    responseBuilder.sendErrorResponse(serverResponse, err);
                } else{
                    responseBuilder.sendEmptyResponse(serverResponse)
                }
            })
        } else {
            responseBuilder.sendErrorResponse(serverResponse, new Error(400, 'Bad Request: Cannot Delete Collection.'));
        }
    },
};

function queryAndSendResponse(serverResponse, host, service, queryParams, sortField, paginationData) {
    var items = []
    service.find(queryParams, sortField, paginationData,
        function(err, responses){
            if(err){
                responseBuilder.sendErrorResponse(serverResponse, err);
            }
            console.log('Building multiple responses from query.');
            for(var current in responses){
                var response = responses[current];
                responseBuilder.addLocation(host, service.resourceName, response.id, response.body);
                items.push(response.body);
            }

            var body = JSON.stringify(items);
            var bodyLength = Buffer.byteLength(body, 'utf-8');
            responseBuilder.writeHeaders(serverResponse, bodyLength, 200);
            serverResponse.end(body);
        }
    );
};

<|endoftext|>


<commit_before>// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngResource'])

.config(function($stateProvider, $urlRouterProvider, $httpProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider.state('home', {
    url: "/",
    templateUrl: "templates/home.html",
    controller: 'HomeCtrl'
  })

  .state('register', {
    url: "/register",
    templateUrl: "templates/two.html",
    controller: 'RegisterCtrl'
  })

  .state('login', {
    url: "/login",
    templateUrl: "templates/one.html",
    controller: 'LoginCtrl'
  })

  .state('one', {
    url: "/one",
    templateURL: "templates/one.html"
  })

   .state('two', {
   url: "/two",
   templateURL: "templates/two.html",
   controller: 'TwoCtrl'
  })

   .state('three', {
    url: "/home/:three",
    templateURL: "templates/three.html",
    controller: 'ThreeCtrl'
  })

   .state('all', {
   url: "/all",
   templateURL: "templates/all.html",
   controller: 'HomeCtrl'
  })

  .state('1B1', {
  url: "/1B1",
  templateURL: "templates/1B1.html",
  controller: '1B1Ctrl'
  })

   .state('1B2', {
   url: "/1B2",
   templateURL: "templates/1B2.html",
   controller: '1B2Ctrl'
  })

  .state('1B3', {
  url: "/1B3",
  templateURL: "templates/1B3.html",
  controller: '1B3Ctrl'
  })

  .state('2B1', {
  url: "/2B1",
  templateURL: "templates/2B1.html",
  controller: '2B1Ctrl'
  })

   .state('2B2', {
   url: "/2B2",
   templateURL: "templates/2B2.html",
   controller: '2B2Ctrl'
  })

  .state('2B3', {
  url: "/2B3",
  templateURL: "templates/2B3.html",
  controller: '2B3Ctrl'
  })

    .state('2B4', {
  url: "/2B4",
  templateURL: "templates/2B4.html",
  controller: '2B4Ctrl'
  })

   .state('2B5', {
   url: "/2B5",
   templateURL: "templates/2B5.html",
   controller: '2B5Ctrl'
  })

  .state('2B6', {
  url: "/2B6",
  templateURL: "templates/2B6.html",
  controller: '2B6Ctrl'
  })

    .state('3B1', {
  url: "/3B1",
  templateURL: "templates/3B1.html",
  controller: '3B1Ctrl'
  })

   .state('3B2', {
   url: "/3B2",
   templateURL: "templates/3B2.html",
   controller: '3B2Ctrl'
  })

  .state('3B3', {
  url: "/3B3",
  templateURL: "templates/3B3.html",
  controller: '3B3Ctrl'
  })

    .state('3B4', {
  url: "/3B4",
  templateURL: "templates/3B4.html",
  controller: '3B4Ctrl'
  })

   .state('3B5', {
   url: "/3B5",
   templateURL: "templates/3B5.html",
   controller: '3B5Ctrl'
  })

  .state('3B6', {
  url: "/3B6",
  templateURL: "templates/3B6.html",
  controller: '3B6Ctrl'
  })

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/');

  // Register middleware to ensure our auth token is passed to the server
  $httpProvider.interceptors.push('TokenInterceptor');

})

.run(function($window, $location, $ionicPlatform, $rootScope, AuthenticationService) {
  $rootScope.user = {
    name: $window.sessionStorage.name,
    is_admin: $window.sessionStorage.is_admin
  };

  if ($rootScope.user.is_admin) {
    AuthenticationService.isAdmin = true;
  }

  $rootScope.$on("$stateChangeStart", function(event, toState) {
    //redirect only if both isAuthenticated is false and no token is set

    if (['home', 'login', 'logout', 'register', 'one', 'two', 'three', 'all', '1B1', '1B2', '1B3', '2B1', '2B2', '2B3', '2B4', '2B5', '2B6', '3B1', '3B2', '3B3', '3B4', '3B5', '3B6'].indexOf(toState.name) === -1) {
      if (!AuthenticationService.isAuthenticated && !$window.localStorage.token) {
        event.preventDefault();
        $location.path("/home");
      }
    }

  });

  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})
<commit_msg>Update app.js<commit_after>// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ngResource'])

.config(function($stateProvider, $urlRouterProvider, $httpProvider) {

  // Ionic uses AngularUI Router which uses the concept of states
  // Learn more here: https://github.com/angular-ui/ui-router
  // Set up the various states which the app can be in.
  // Each state's controller can be found in controllers.js
  $stateProvider.state('home', {
    url: "/",
    templateUrl: "templates/home.html",
    controller: 'HomeCtrl'
  })

  .state('register', {
    url: "/register",
    templateUrl: "templates/two.html",
    controller: 'RegisterCtrl'
  })

  .state('login', {
    url: "/login",
    templateUrl: "templates/one.html",
    controller: 'LoginCtrl'
  })

  .state('one', {
    url: "/one",
    templateURL: "templates/one.html"
  })

   .state('two', {
   url: "/two",
   templateURL: "templates/two.html",
   controller: 'TwoCtrl'
  })

   .state('three', {
    url: "/three",
    templateURL: "templates/three.html",
    controller: 'ThreeCtrl'
  })

   .state('all', {
   url: "/all",
   templateURL: "templates/all.html",
   controller: 'HomeCtrl'
  })

  .state('1B1', {
  url: "/1B1",
  templateURL: "templates/1B1.html",
  controller: '1B1Ctrl'
  })

   .state('1B2', {
   url: "/1B2",
   templateURL: "templates/1B2.html",
   controller: '1B2Ctrl'
  })

  .state('1B3', {
  url: "/1B3",
  templateURL: "templates/1B3.html",
  controller: '1B3Ctrl'
  })

  .state('2B1', {
  url: "/2B1",
  templateURL: "templates/2B1.html",
  controller: '2B1Ctrl'
  })

   .state('2B2', {
   url: "/2B2",
   templateURL: "templates/2B2.html",
   controller: '2B2Ctrl'
  })

  .state('2B3', {
  url: "/2B3",
  templateURL: "templates/2B3.html",
  controller: '2B3Ctrl'
  })

    .state('2B4', {
  url: "/2B4",
  templateURL: "templates/2B4.html",
  controller: '2B4Ctrl'
  })

   .state('2B5', {
   url: "/2B5",
   templateURL: "templates/2B5.html",
   controller: '2B5Ctrl'
  })

  .state('2B6', {
  url: "/2B6",
  templateURL: "templates/2B6.html",
  controller: '2B6Ctrl'
  })

    .state('3B1', {
  url: "/3B1",
  templateURL: "templates/3B1.html",
  controller: '3B1Ctrl'
  })

   .state('3B2', {
   url: "/3B2",
   templateURL: "templates/3B2.html",
   controller: '3B2Ctrl'
  })

  .state('3B3', {
  url: "/3B3",
  templateURL: "templates/3B3.html",
  controller: '3B3Ctrl'
  })

    .state('3B4', {
  url: "/3B4",
  templateURL: "templates/3B4.html",
  controller: '3B4Ctrl'
  })

   .state('3B5', {
   url: "/3B5",
   templateURL: "templates/3B5.html",
   controller: '3B5Ctrl'
  })

  .state('3B6', {
  url: "/3B6",
  templateURL: "templates/3B6.html",
  controller: '3B6Ctrl'
  })

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/');

  // Register middleware to ensure our auth token is passed to the server
  $httpProvider.interceptors.push('TokenInterceptor');

})

.run(function($window, $location, $ionicPlatform, $rootScope, AuthenticationService) {
  $rootScope.user = {
    name: $window.sessionStorage.name,
    is_admin: $window.sessionStorage.is_admin
  };

  if ($rootScope.user.is_admin) {
    AuthenticationService.isAdmin = true;
  }

  $rootScope.$on("$stateChangeStart", function(event, toState) {
    //redirect only if both isAuthenticated is false and no token is set

    if (['home', 'login', 'logout', 'register', 'one', 'two', 'three', 'all', '1B1', '1B2', '1B3', '2B1', '2B2', '2B3', '2B4', '2B5', '2B6', '3B1', '3B2', '3B3', '3B4', '3B5', '3B6'].indexOf(toState.name) === -1) {
      if (!AuthenticationService.isAuthenticated && !$window.localStorage.token) {
        event.preventDefault();
        $location.path("/home");
      }
    }

  });

  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})
<|endoftext|>


<commit_before>let sequence,sequence2,endpoint,endpoint2,offset,offset2;

let throttle = __.throttle_factory(16);

function init() {

  console.log("init");

  sequence = __.fill_array(7,idx => {
    return __.pitch2freq(__.scales("major")[idx] + __.random(2,7) * 12);
  });

  sequence2 = __.fill_array(7,idx => {
    return __.pitch2freq(__.scales("major")[idx] + __.random(2,7) * 12);
  });

  endpoint = __.random(4,7);
  endpoint2 = __.random(4,7);

  offset = __.random(0,3);
  offset2 = __.random(0,3);

}

__().square({id:"sq2"}).gain(0).panner(-1).out();
__().square({id:"sq1"}).gain(0).panner(1).out().play()

__.loop(130,function(index,data,array){

  __("#sq1").frequency(__.array_next(sequence,offset,endpoint));
  __("#sq2").frequency(__.array_next(sequence2,offset2,endpoint2));

  if(throttle()) {
    init();
  }

});

init();

__.loop("start");
__("gain").volume(1/2);

<commit_msg>Delete major-madness.js<commit_after><|endoftext|>


<commit_before>class TabPage extends React.Component{
    constructor(props){
        super(props);
    }
    render(){
        return (
{this.props.content}
);
    }
}
function TabButton(props){
    return (<button className={"tablinks"} onClick={()=>{openTab(props.openTarget)}} id={"tabBtn"+props.tabBtnId} key={"tabBtn"+props.tabBtnId}>{props.label}</button>);
}
function openTab(tabId){
    var contents  = document.getElementsByClassName("tabcontent");
    var links = document.getElementsByClassName("tablinks");
    for(var i=0;i<contents.length;i++) contents[i].removeAttribute("style");
    for(var i=0;i<links.length;i++) links[i].removeAttribute("active");
    document.getElementById("tab"+tabId.toString()).setAttribute("style","display:block;");
    document.getElementById("tabBtn"+tabId.toString()).setAttribute("active","");
}
class pso2tools{
    /**
     *
     * @param {string} dbFile file path to database
     */
    constructor(dbFile){
        if(!path.isAbsolute(dbFile)){
            dbFile = path.join(__dirname, dbFile);
        }
        var initDB = false;
        this._dbFile = dbFile;
        if(!fs.existsSync(dbFile)){
            initDB = true;
        }
        this.db = require("sqlite-sync");
        this.db.connect(dbFile);
        if(initDB){
            this.dbInitialize();
        }
        this.loadedModules = {};
        this.settings = {
            "pso2DocumentLocation": path.join(process.env.HOME, "Documents\\SEGA\\PHANTASYSTARONLINE2")
        }
        var settingsFile = path.join(process.cwd(),"settings.json");
        if(fs.existsSync(settingsFile)){
            var settings = JSON.parse(fs.readFileSync(settingsFile,{encoding:"utf8"}));
            this.settings = Object.assign(this.settings, settings);
        }

    }

    dbInitialize(){
        this.db.run("CREATE TABLE IF NOT EXISTS `characters`(\
            `cid` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\
            `CName` TEXT NULL);")
        this.db.run("CREATE TABLE IF NOT EXISTS `installed_modules`(\
            `module_name` TEXT PRIMARY KEY);")
    }

    _dbInstallModule(moduleName, moduleDbInit){
        // Check if module is installed
        var db = this.db;
        var r = db.run("SELECT module_name FROM `installed_modules` WHERE module_name = ? ;",[moduleName]);
        if(r.length == 0){
            // module not installed, install module
            console.log("New module detected: "+ moduleName);
            moduleDbInit();
            db.run("INSERT INTO installed_modules(module_name) VALUES (?)",[moduleName.toString()]);
        }else{
            console.log("Module " + moduleName + " has already installed");
        }
    }

    /**
     *
     * @param {string} moduleName
     * @param {pso2tools_module} moduleLoader
     */
    loadModule(moduleLoader){
        var temp = new moduleLoader(this);
        if(temp){
            this.loadedModules[moduleLoader.name] = temp;
            this._dbInstallModule(moduleLoader.name, ((me)=>{return ()=>me.loadedModules[moduleLoader.name].dbInitialize();})(this));
        }
    }

    addCharacter(CName){
        return this.db.run("INSERT INTO characters(CName) VALUES (?)",[CName]);
    }

    listCharacter(){
        return this.db.run("SELECT cid, CName FROM characters");
    }

    render(){
        // Listing character list
        var characters = this.listCharacter();

        // Rendering the result of character overview table
        var tbl = [];
        for(var i=0; i<characters.length; i++){
            var tblResults = [{characters[i].CName}	];
            Object.keys(this.loadedModules).forEach((key)=>{
                var result = this.loadedModules[key].renderCharTable(characters[i].cid);
                if(result!=null){
                    tblResults.push(result);
                }
            });
            tbl.push(
{tblResults}
)
        }
        tbl.push(
<input type={"text"} id={"addCharName"}/>	<button onClick={()=>{this.addCharacter(document.getElementById("addCharName").value);document.getElementById("addCharName").value="";this.render();}}>{"Add Character"}</button>
);

        var tabPages = [<TabPage content={

{tbl}

} tabId="-1" key={"tab-1"}></TabPage>];
        var tabButtons = [TabButton({"openTarget":-1, "label": "Overview", "tabBtnId":-1})];

        // rendering modules' tab pages
        for(i in this.loadedModules){
            var toolTab = this.loadedModules[i].renderTab();
            if(toolTab!=null){
                tabPages.push(<TabPage content={toolTab.content} tabId={i} key={"tab-tool-"+i}></TabPage>);
                tabButtons.push(TabButton({"openTarget":i, "label":toolTab.label, "tabBtnId": i}));
            }
        }

        tabButtons.push(
);

        // rendering result for module's tab tools
        for(var i=0; i<characters.length; i++){
            var toolResults = [];
            Object.keys(this.loadedModules).forEach((key)=>{
                var result = this.loadedModules[key].renderToolBlock(characters[i].cid);
                if(result!=null){
                    toolResults.push(
{result}
);
                }
            });
            //Creating new tab
            tabPages.push(<TabPage content={
{toolResults}
} tabId={characters[i].cid} key={"tab"+characters[i].cid.toString()}></TabPage>);
            tabButtons.push(TabButton({"openTarget":characters[i].cid, "label": characters[i].CName, "tabBtnId": characters[i].cid.toString()}));
        }

        ReactDOM.render(
{tabPages}
, document.getElementById("tabContainers"));
        ReactDOM.render(
{tabButtons}
, document.getElementById("tabButtons"));
    }
}<commit_msg>process.env.HOME not exist after build<commit_after>class TabPage extends React.Component{
    constructor(props){
        super(props);
    }
    render(){
        return (
{this.props.content}
);
    }
}
function TabButton(props){
    return (<button className={"tablinks"} onClick={()=>{openTab(props.openTarget)}} id={"tabBtn"+props.tabBtnId} key={"tabBtn"+props.tabBtnId}>{props.label}</button>);
}
function openTab(tabId){
    var contents  = document.getElementsByClassName("tabcontent");
    var links = document.getElementsByClassName("tablinks");
    for(var i=0;i<contents.length;i++) contents[i].removeAttribute("style");
    for(var i=0;i<links.length;i++) links[i].removeAttribute("active");
    document.getElementById("tab"+tabId.toString()).setAttribute("style","display:block;");
    document.getElementById("tabBtn"+tabId.toString()).setAttribute("active","");
}
class pso2tools{
    /**
     *
     * @param {string} dbFile file path to database
     */
    constructor(dbFile){
        if(!path.isAbsolute(dbFile)){
            dbFile = path.join(__dirname, dbFile);
        }
        var initDB = false;
        this._dbFile = dbFile;
        if(!fs.existsSync(dbFile)){
            initDB = true;
        }
        this.db = require("sqlite-sync");
        this.db.connect(dbFile);
        if(initDB){
            this.dbInitialize();
        }
        this.loadedModules = {};
        this.settings = {
            "pso2DocumentLocation": path.join(process.env.USERPROFILE, "Documents\\SEGA\\PHANTASYSTARONLINE2")
        }
        var settingsFile = path.join(process.cwd(),"settings.json");
        if(fs.existsSync(settingsFile)){
            var settings = JSON.parse(fs.readFileSync(settingsFile,{encoding:"utf8"}));
            this.settings = Object.assign(this.settings, settings);
        }

    }

    dbInitialize(){
        this.db.run("CREATE TABLE IF NOT EXISTS `characters`(\
            `cid` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\
            `CName` TEXT NULL);")
        this.db.run("CREATE TABLE IF NOT EXISTS `installed_modules`(\
            `module_name` TEXT PRIMARY KEY);")
    }

    _dbInstallModule(moduleName, moduleDbInit){
        // Check if module is installed
        var db = this.db;
        var r = db.run("SELECT module_name FROM `installed_modules` WHERE module_name = ? ;",[moduleName]);
        if(r.length == 0){
            // module not installed, install module
            console.log("New module detected: "+ moduleName);
            moduleDbInit();
            db.run("INSERT INTO installed_modules(module_name) VALUES (?)",[moduleName.toString()]);
        }else{
            console.log("Module " + moduleName + " has already installed");
        }
    }

    /**
     *
     * @param {string} moduleName
     * @param {pso2tools_module} moduleLoader
     */
    loadModule(moduleLoader){
        var temp = new moduleLoader(this);
        if(temp){
            this.loadedModules[moduleLoader.name] = temp;
            this._dbInstallModule(moduleLoader.name, ((me)=>{return ()=>me.loadedModules[moduleLoader.name].dbInitialize();})(this));
        }
    }

    addCharacter(CName){
        return this.db.run("INSERT INTO characters(CName) VALUES (?)",[CName]);
    }

    listCharacter(){
        return this.db.run("SELECT cid, CName FROM characters");
    }

    render(){
        // Listing character list
        var characters = this.listCharacter();

        // Rendering the result of character overview table
        var tbl = [];
        for(var i=0; i<characters.length; i++){
            var tblResults = [{characters[i].CName}	];
            Object.keys(this.loadedModules).forEach((key)=>{
                var result = this.loadedModules[key].renderCharTable(characters[i].cid);
                if(result!=null){
                    tblResults.push(result);
                }
            });
            tbl.push(
{tblResults}
)
        }
        tbl.push(
<input type={"text"} id={"addCharName"}/>	<button onClick={()=>{this.addCharacter(document.getElementById("addCharName").value);document.getElementById("addCharName").value="";this.render();}}>{"Add Character"}</button>
);

        var tabPages = [<TabPage content={

{tbl}

} tabId="-1" key={"tab-1"}></TabPage>];
        var tabButtons = [TabButton({"openTarget":-1, "label": "Overview", "tabBtnId":-1})];

        // rendering modules' tab pages
        for(i in this.loadedModules){
            var toolTab = this.loadedModules[i].renderTab();
            if(toolTab!=null){
                tabPages.push(<TabPage content={toolTab.content} tabId={i} key={"tab-tool-"+i}></TabPage>);
                tabButtons.push(TabButton({"openTarget":i, "label":toolTab.label, "tabBtnId": i}));
            }
        }

        tabButtons.push(
);

        // rendering result for module's tab tools
        for(var i=0; i<characters.length; i++){
            var toolResults = [];
            Object.keys(this.loadedModules).forEach((key)=>{
                var result = this.loadedModules[key].renderToolBlock(characters[i].cid);
                if(result!=null){
                    toolResults.push(
{result}
);
                }
            });
            //Creating new tab
            tabPages.push(<TabPage content={
{toolResults}
} tabId={characters[i].cid} key={"tab"+characters[i].cid.toString()}></TabPage>);
            tabButtons.push(TabButton({"openTarget":characters[i].cid, "label": characters[i].CName, "tabBtnId": characters[i].cid.toString()}));
        }

        ReactDOM.render(
{tabPages}
, document.getElementById("tabContainers"));
        ReactDOM.render(
{tabButtons}
, document.getElementById("tabButtons"));
    }
}<|endoftext|>


<commit_before>/*

*/
/* Global imports */

var fs = require('fs-extra');

var isThere = require('is-there');

var trck = require('../calls/c_tracks');
var bodyParser  = require('body-parser');

/* Public Methods */
/**
 * Starts the playback of the provided track.
 * @param response              The HTTP-Response
 * @param albumTitle            The album title
 * @param trackName             The name of the track
 */
exports.startPlayback = function(req, res) {

    var id = req.params.id;

    trck.c_TrackById(id).then(function(data){

        var path = data.Location;

        //console.log('path: ', path)
        console.log('::::::::::::::::::::: ', data)

        if (isThere(path)) {

            var destination_file = "/Users/rtb/Sites/music-playback/music/The.madpix.project_-_Wish_You_Were_Here.ogg"
            convert( path, destination_file )

            //startTrackStreaming( req, res, path );

        } else {
            console.error('Could not find file ' + path);
        }

/*
        res.end(JSON.stringify({
            status: 200,
            message: '',
            data : data
        }));
*/

    },function(err){
        reject({
            status: 200,
            message: err
        });
    });
};

/* Private Methods */

var startTrackStreaming = function(req, res, path) {

    console.log( 'path: ', path +' | '+ req.headers.range )

    //if(typeof request.headers.range !== 'undefined')
    if (!!req.headers.range)  {
        var range       = req.headers.range;
        var ranges      = range.replace(/bytes=/, "").split("-");
        var rangeStart  = ranges[0];
        var rangeEnd    = ranges[1];
        var total       = fs.statSync(path).size;

        var start = parseInt(rangeStart, 10);
        var end   = rangeEnd ? parseInt(rangeEnd, 10) : total - 1;

        res.writeHead(206, {
            'Accept-Ranges': 'bytes',
            'Content-Range': 'bytes ' + start + '-' + end + '/' + total,
            'Content-Length': (end - start) + 1,
            'Content-Type': 'audio/mpeg',
            //'Connection': 'close'
          });

        var file = fs.createReadStream(path, {start: start, end: end});
    } else {

        // un 200 causa crask in Firefox
        res.writeHead(206, {
            //'Content-Length': end,
            'Content-Type': 'audio/mpeg',
            //'Connection': 'close'
          });

        var file = fs.createReadStream(path);
    }

    //res.end();

    file.pipe(res);
    file.on('close', function () {
        res.end(0);
    });
};

function convert(source_file, destination_file) {

    console.log('oooooooo')

        //var destination_file = source_file.split('/').slice(-1)[0].replace('.flv', '.mp3');
    //var ffmpeg = 'ffmpeg -y -i '+ source_file +' -f mp3 -vn -acodec copy ' + destination_file;

    //var exec = require('child_process');

    //var ffmpeg = './ffmpeg -i '+ source_file +' -f ogg ' + destination_file;
    //var child = exec.spawn( ffmpeg ).pipe(res);

    //child.stdout.pipe(res);

     var ffmpeg = require('child_process').exec("./ffmpeg -i "+ source_file +" -f ogg " + destination_file );

        ffmpeg.stderr.on('data', function (data) {
            console.log('stderr: ' + data);
        });

        ffmpeg.stdout.on('data', function (data) {

            console.log('stdout: ' + data);

            //var file = fs.createReadStream(data, {start: start, end: end});

            //data(res);

            //var frame = new Buffer(data).toString('base64');

            var file = fs.createReadStream(data, {frame: start, end: end});

        });

        ffmpeg.stdout.pipe(output); // Write encoded chucks to the file system

}

<commit_msg>no message<commit_after>/*

*/
/* Global imports */

var fs = require('fs-extra');

var isThere = require('is-there');

var trck = require('../calls/c_tracks');
var bodyParser  = require('body-parser');

/* Public Methods */
/**
 * Starts the playback of the provided track.
 * @param response              The HTTP-Response
 * @param albumTitle            The album title
 * @param trackName             The name of the track
 */
exports.startPlayback = function(req, res) {

    var id = req.params.id;

    trck.c_TrackById(id).then(function(data){

        var path = data.Location;

        //console.log('path: ', path)
        console.log('::::::::::::::::::::: ', data)

        if (isThere(path)) {

            //var destination_file = "/Users/rtb/Sites/music-playback/music/The.madpix.project_-_Wish_You_Were_Here.ogg"
            //convert( path, destination_file )

            //startTrackStreaming( req, res, path );

            startTrackStreaming2( req, res, path );

        } else {
            console.error('Could not find file ' + path);
        }

/*
        res.end(JSON.stringify({
            status: 200,
            message: '',
            data : data
        }));
*/

    },function(err){
        reject({
            status: 200,
            message: err
        });
    });
};

/* Private Methods */

var startTrackStreaming = function(req, res, path) {

    console.log( 'path: ', path +' | '+ req.headers.range )

    //if(typeof request.headers.range !== 'undefined')
    if (!!req.headers.range)  {
        var range       = req.headers.range;
        var ranges      = range.replace(/bytes=/, "").split("-");
        var rangeStart  = ranges[0];
        var rangeEnd    = ranges[1];
        var total       = fs.statSync(path).size;

        var start = parseInt(rangeStart, 10);
        var end   = rangeEnd ? parseInt(rangeEnd, 10) : total - 1;

        res.writeHead(206, {
            'Accept-Ranges': 'bytes',
            'Content-Range': 'bytes ' + start + '-' + end + '/' + total,
            'Content-Length': (end - start) + 1,
            'Content-Type': 'audio/mpeg',
            //'Connection': 'close'
          });

        var file = fs.createReadStream(path, {start: start, end: end});
    } else {

        // un 200 causa crask in Firefox
        res.writeHead(206, {
            //'Content-Length': end,
            'Content-Type': 'audio/mpeg',
            //'Connection': 'close'
          });

        var file = fs.createReadStream(path);
    }

    //res.end();

    file.pipe(res);
    file.on('close', function () {
        res.end(0);
    });
};

function convert(source_file, destination_file) {

    console.log('oooooooo')

        //var destination_file = source_file.split('/').slice(-1)[0].replace('.flv', '.mp3');
    //var ffmpeg = 'ffmpeg -y -i '+ source_file +' -f mp3 -vn -acodec copy ' + destination_file;

    //var exec = require('child_process');

    //var ffmpeg = './ffmpeg -i '+ source_file +' -f ogg ' + destination_file;
    //var child = exec.spawn( ffmpeg ).pipe(res);

    //child.stdout.pipe(res);

     var ffmpeg = require('child_process').exec("./ffmpeg -i "+ source_file +" -f ogg " + destination_file );

        ffmpeg.stderr.on('data', function (data) {
            console.log('stderr: ' + data);
        });

        ffmpeg.stdout.on('data', function (data) {

            console.log('stdout: ' + data);

            //var file = fs.createReadStream(data, {start: start, end: end});

            //data(res);

            //var frame = new Buffer(data).toString('base64');

            var file = fs.createReadStream(data, {frame: start, end: end});

        });

        ffmpeg.stdout.pipe(output); // Write encoded chucks to the file system

}

var startTrackStreaming2 = function(req, res, path) {

    //path = '/Users/rtb/Music/___nevera/Eilen Jewell/2015 Sundown Over Ghost Town/02 Hallelujah Band.mp3'
    //path = 'input.mp3';
    //path = 'output.ogg';

    console.log( 'path: ', path +' | '+ req.headers.range )

    //if(typeof request.headers.range !== 'undefined')
    if (!!req.headers.range)  {
        var range       = req.headers.range;
        var ranges      = range.replace(/bytes=/, "").split("-");
        var rangeStart  = ranges[0];
        var rangeEnd    = ranges[1];
        var total       = fs.statSync(path).size;

        var start = parseInt(rangeStart, 10);
        var end   = rangeEnd ? parseInt(rangeEnd, 10) : total - 1;
        var chunksize = (end-start)+1;

        console.log('@@@@@@@ RANGE: '+ start +' - '+ end +' | '+ chunksize +' | '+ path)

    /*
        res.writeHead(206, {
            'Accept-Ranges': 'bytes',
            'Content-Range': 'bytes ' + start + '-' + end + '/' + total,
            'Content-Length': chunksize,
            'Content-Type': 'audio/mpeg',
            //'Connection': 'close'
            //'Transfer-Encoding':'chunked'
          });

        //var file = fs.createReadStream(path, {start: start, end: end});
     */

        res.writeHead(200, {
            //'Accept-Ranges': 'bytes',
            //'Content-Range': 'bytes ',
            'Content-Type': 'audio/mpeg',
        });

        //convert2(path).pipe(res, {start: start, end: end});

        //var file = convert2(path);

        //var file = fs.createReadStream(path, {start: start, end: end});

        //var file = fs.createReadStream(convert2(path).stdout, {start: start, end: end});

        //convert2(path).file().pipe(res)

        var child_process = require("child_process");

        var ffmpeg = child_process.spawn("./ffmpeg", [
            //'-re',
            '-i', path, // path
            '-f', 'ogg', // File format
            'pipe:1' // Output to STDOUT
        ]);

        ffmpeg.on('error', function(err) {
            console.log('@@@@@@@ error', err);
        })
        ffmpeg.on('exit', function(err) {
            console.log('@@@@@@@ exit', err);
        })
        ffmpeg.on('close', function(code) {
            console.log('@@@@@@@ child process exited with code ' + code);
        });

        ffmpeg.stderr.on('data', function(data) {

            //console.log('.')

            console.log('ffmpeg stderr: ' + data.toString());
        })

        ffmpeg.stdin.on('error', function() {});

        ffmpeg.stdout.on('data', function(data) {
            //console.log('stdout: ' + data.toString() );

            //var buff = new Buffer(data);

        })

        ffmpeg.stdout.pipe(res);

        res.on('close', function() {
            ffmpeg.kill();
        });

    };
};<|endoftext|>


<commit_before>const stylelint = require('stylelint')
const {requirePrimerFile} = require('../src/primer')

const ruleName = 'primer/no-override'
const CLASS_PATTERN = /(\.[-\w]+)/
const CLASS_PATTERN_ALL = new RegExp(CLASS_PATTERN, 'g')

module.exports = stylelint.createPlugin(ruleName, (enabled, options = {}) => {
  if (!enabled) {
    return noop
  }

  const {bundles = ['utilities']} = options

  const primerMeta = requirePrimerFile('dist/meta.json')
  const availableBundles = Object.keys(primerMeta.bundles)

  const immutableSelectors = new Map()
  const immutableClassSelectors = new Map()
  for (const bundle of bundles) {
    if (!availableBundles.includes(bundle)) {
      continue
    }
    const stats = requirePrimerFile(`dist/stats/${bundle}.json`)
    const selectors = stats.selectors.values.filter(selector => !!CLASS_PATTERN.test(selector))
    for (const selector of selectors) {
      immutableSelectors.set(selector, bundle)
      for (const classSelector of getClassSelectors(selector)) {
        immutableClassSelectors.set(classSelector, bundle)
      }
    }
  }

  const messages = stylelint.utils.ruleMessages(ruleName, {
    rejected: (rule, {selector, bundle}) => {
      const suffix = bundle ? ` (found in ${bundle})` : ''
      return selector
        ? `"${selector}" should not be overridden in "${rule.selector}"${suffix}.`
        : `"${rule.selector}" should not be overridden${suffix}.`
    }
  })

  return (root, result) => {
    if (!Array.isArray(bundles) || bundles.some(bundle => !availableBundles.includes(bundle))) {
      const invalidBundles = Array.isArray(bundles)
        ? `"${bundles.filter(bundle => !availableBundles.includes(bundle)).join('", "')}"`
        : '(not an array)'
      result.warn(`The "bundles" option must be an array of valid bundles; got: ${invalidBundles}`, {
        stylelintType: 'invalidOption',
        stylelintReference: 'https://github.com/primer/stylelint-config-primer#options'
      })
    }

    if (!enabled) {
      return
    }

    const report = (rule, subject) =>
      stylelint.utils.report({
        message: messages.rejected(rule, subject),
        node: rule,
        result,
        ruleName
      })

    root.walkRules(rule => {
      const subject = {rule}
      if (immutableSelectors.has(rule.selector)) {
        subject.bundle = immutableSelectors.get(rule.selector)
        report(rule, subject)
      } else {
        for (const classSelector of getClassSelectors(rule.selector)) {
          if (immutableClassSelectors.has(classSelector)) {
            subject.bundle = immutableClassSelectors.get(classSelector)
            subject.selector = classSelector
            report(rule, subject)
          }
        }
      }
    })
  }
})

function getClassSelectors(selector) {
  const match = selector.match(CLASS_PATTERN_ALL)
  return match ? [...match] : []
}

function noop() {}
<commit_msg>fix: remove unnecessary !!<commit_after>const stylelint = require('stylelint')
const {requirePrimerFile} = require('../src/primer')

const ruleName = 'primer/no-override'
const CLASS_PATTERN = /(\.[-\w]+)/
const CLASS_PATTERN_ALL = new RegExp(CLASS_PATTERN, 'g')

module.exports = stylelint.createPlugin(ruleName, (enabled, options = {}) => {
  if (!enabled) {
    return noop
  }

  const {bundles = ['utilities']} = options

  const primerMeta = requirePrimerFile('dist/meta.json')
  const availableBundles = Object.keys(primerMeta.bundles)

  const immutableSelectors = new Map()
  const immutableClassSelectors = new Map()
  for (const bundle of bundles) {
    if (!availableBundles.includes(bundle)) {
      continue
    }
    const stats = requirePrimerFile(`dist/stats/${bundle}.json`)
    const selectors = stats.selectors.values.filter(selector => CLASS_PATTERN.test(selector))
    for (const selector of selectors) {
      immutableSelectors.set(selector, bundle)
      for (const classSelector of getClassSelectors(selector)) {
        immutableClassSelectors.set(classSelector, bundle)
      }
    }
  }

  const messages = stylelint.utils.ruleMessages(ruleName, {
    rejected: (rule, {selector, bundle}) => {
      const suffix = bundle ? ` (found in ${bundle})` : ''
      return selector
        ? `"${selector}" should not be overridden in "${rule.selector}"${suffix}.`
        : `"${rule.selector}" should not be overridden${suffix}.`
    }
  })

  return (root, result) => {
    if (!Array.isArray(bundles) || bundles.some(bundle => !availableBundles.includes(bundle))) {
      const invalidBundles = Array.isArray(bundles)
        ? `"${bundles.filter(bundle => !availableBundles.includes(bundle)).join('", "')}"`
        : '(not an array)'
      result.warn(`The "bundles" option must be an array of valid bundles; got: ${invalidBundles}`, {
        stylelintType: 'invalidOption',
        stylelintReference: 'https://github.com/primer/stylelint-config-primer#options'
      })
    }

    if (!enabled) {
      return
    }

    const report = (rule, subject) =>
      stylelint.utils.report({
        message: messages.rejected(rule, subject),
        node: rule,
        result,
        ruleName
      })

    root.walkRules(rule => {
      const subject = {rule}
      if (immutableSelectors.has(rule.selector)) {
        subject.bundle = immutableSelectors.get(rule.selector)
        report(rule, subject)
      } else {
        for (const classSelector of getClassSelectors(rule.selector)) {
          if (immutableClassSelectors.has(classSelector)) {
            subject.bundle = immutableClassSelectors.get(classSelector)
            subject.selector = classSelector
            report(rule, subject)
          }
        }
      }
    })
  }
})

function getClassSelectors(selector) {
  const match = selector.match(CLASS_PATTERN_ALL)
  return match ? [...match] : []
}

function noop() {}
<|endoftext|>