<commit_before>var assert = require('assert');
var rewire = require('rewire');

var parseBundlePlugin = require('../src/parse_bundle_plugin');
var readBundlePlugins = rewire('../src/read_bundle_plugins');

describe('parseBundlePlugin', function() {
  describe('input is valid, bundles output', function() {
    it('should have one entry', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        stats_file: "output.json",
        static_url_root: "static",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/")[0] !== "undefined");
      done();
    });
  });
  describe('input is missing name, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        src_file: "src/file.js",
        stats_file: "output.json",
        static_url_root: "static",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is missing src_file, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        stats_file: "output.json",
        static_url_root: "static",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is missing stats_file, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        static_url_root: "static",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is missing static_dir, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        static_url_root: "static",
        stats_file: "output.json",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is missing locale_data_folder, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        static_url_root: "static",
        stats_file: "output.json",
        static_dir: "kolibri/plugin/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is missing plugin_path, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        static_url_root: "static",
        stats_file: "output.json",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is valid, has externals flag and core_name value, externals output', function() {
    it('should have one entry', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        external: true,
        stats_file: "output.json",
        static_dir: "kolibri/plugin/test",
        static_url_root: "static",
        core_name: "test_core",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/")[1] !== "undefined");
      done();
    });
  });
  describe('input is valid, has core flag', function() {
    it('should have its name set to kolibriGlobal', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        external: true,
        core_name: "kolibriGlobal",
        stats_file: "output.json",
        static_url_root: "static",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert.equal(parseBundlePlugin(data, "/")[0].output.library, "kolibriGlobal");
      done();
    });
  });
});

describe('readBundlePlugins', function() {
  var data = [];

  beforeEach(function() {
    readBundlePlugins.__set__("execSync", function() {});
    readBundlePlugins.__set__("fs.readFileSync", function() {
      return JSON.stringify(data);
    });
  });

  describe('two valid inputs, output', function() {
    it('should have two entries', function (done) {
      data = [
        {
          name: "kolibri.plugin.test.test_plugin",
          src_file: "src/file.js",
          stats_file: "output.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        },
        {
          name: "kolibri.plugin.test.test_plugin1",
          src_file: "src/file1.js",
          stats_file: "output1.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        }
      ];
      assert(readBundlePlugins("", "").length === 2);
      done();
    });
  });
  describe('one valid input out of two, output', function() {
    it('should have one entry', function (done) {
      data = [
        {
          name: "kolibri.plugin.test.test_plugin",
          stats_file: "output.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        },
        {
          name: "kolibri.plugin.test.test_plugin1",
          src_file: "src/file1.js",
          stats_file: "output1.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        }
      ];
      assert(readBundlePlugins("", "").length === 1);
      done();
    });
  });
  describe('no valid input, output', function() {
    it('should have no entries', function (done) {
      data = [
        {
          name: "kolibri.plugin.test.test_plugin",
          stats_file: "output.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        },
        {
          name: "kolibri.plugin.test.test_plugin1",
          stats_file: "output1.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        }
      ];
      assert(readBundlePlugins("", "").length === 0);
      done();
    });
  });
  describe('two external flags on inputs, one with core_name value, externals output', function() {
    it('should have one entry', function (done) {
      data = [
        {
          name: "kolibri.plugin.test.test_plugin",
          src_file: "src/file.js",
          stats_file: "output.json",
          external: true,
          static_dir: "kolibri/plugin/test",
          static_url_root: "static",
          core_name: "test_global",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        },
        {
          name: "kolibri.plugin.test.test_plugin1",
          src_file: "src/file1.js",
          stats_file: "output1.json",
          external: true,
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        }
      ];
      assert(Object.keys(readBundlePlugins("", function(){return {};})[0].externals).length === 1);
      done();
    });
  });
  describe('two identically named external flags on inputs, externals output', function() {
    it('should have one entry', function (done) {
      data = [
        {
          name: "kolibri.plugin.test.test_plugin",
          src_file: "src/file.js",
          stats_file: "output.json",
          external: true,
          static_dir: "kolibri/plugin/test",
          static_url_root: "static",
          core_name: "test_global",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        },
        {
          name: "kolibri.plugin.test.test_plugin",
          src_file: "src/file1.js",
          stats_file: "output1.json",
          external: true,
          static_dir: "kolibri/plugin/test",
          static_url_root: "static",
          core_name: "test_global",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        }
      ];
      assert(Object.keys(readBundlePlugins("", function(){return {};})[0].externals).length === 1);
      done();
    });
  });
});
<commit_msg>Fixes rewire in mocha test.<commit_after>var assert = require('assert');
var rewire = require('rewire');

var parseBundlePlugin = require('../src/parse_bundle_plugin');
var readBundlePlugins = rewire('../src/read_bundle_plugins');

describe('parseBundlePlugin', function() {
  describe('input is valid, bundles output', function() {
    it('should have one entry', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        stats_file: "output.json",
        static_url_root: "static",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/")[0] !== "undefined");
      done();
    });
  });
  describe('input is missing name, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        src_file: "src/file.js",
        stats_file: "output.json",
        static_url_root: "static",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is missing src_file, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        stats_file: "output.json",
        static_url_root: "static",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is missing stats_file, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        static_url_root: "static",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is missing static_dir, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        static_url_root: "static",
        stats_file: "output.json",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is missing locale_data_folder, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        static_url_root: "static",
        stats_file: "output.json",
        static_dir: "kolibri/plugin/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is missing plugin_path, bundles output', function() {
    it('should be undefined', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        static_url_root: "static",
        stats_file: "output.json",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test"
      };
      assert(typeof parseBundlePlugin(data, "/") === "undefined");
      done();
    });
  });
  describe('input is valid, has externals flag and core_name value, externals output', function() {
    it('should have one entry', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        external: true,
        stats_file: "output.json",
        static_dir: "kolibri/plugin/test",
        static_url_root: "static",
        core_name: "test_core",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert(typeof parseBundlePlugin(data, "/")[1] !== "undefined");
      done();
    });
  });
  describe('input is valid, has core flag', function() {
    it('should have its name set to kolibriGlobal', function (done) {
      var data = {
        name: "kolibri.plugin.test.test_plugin",
        src_file: "src/file.js",
        external: true,
        core_name: "kolibriGlobal",
        stats_file: "output.json",
        static_url_root: "static",
        static_dir: "kolibri/plugin/test",
        locale_data_folder: "kolibri/locale/test",
        plugin_path: "kolibri/plugin"
      };
      assert.equal(parseBundlePlugin(data, "/")[0].output.library, "kolibriGlobal");
      done();
    });
  });
});

describe('readBundlePlugins', function() {
  var data = [];

  beforeEach(function() {
    readBundlePlugins.__set__("readWebpackJson", function() {
      return data;
    });
  });

  describe('two valid inputs, output', function() {
    it('should have two entries', function (done) {
      data = [
        {
          name: "kolibri.plugin.test.test_plugin",
          src_file: "src/file.js",
          stats_file: "output.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        },
        {
          name: "kolibri.plugin.test.test_plugin1",
          src_file: "src/file1.js",
          stats_file: "output1.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        }
      ];
      assert(readBundlePlugins("", "").length === 2);
      done();
    });
  });
  describe('one valid input out of two, output', function() {
    it('should have one entry', function (done) {
      data = [
        {
          name: "kolibri.plugin.test.test_plugin",
          stats_file: "output.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        },
        {
          name: "kolibri.plugin.test.test_plugin1",
          src_file: "src/file1.js",
          stats_file: "output1.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        }
      ];
      assert(readBundlePlugins("", "").length === 1);
      done();
    });
  });
  describe('no valid input, output', function() {
    it('should have no entries', function (done) {
      data = [
        {
          name: "kolibri.plugin.test.test_plugin",
          stats_file: "output.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        },
        {
          name: "kolibri.plugin.test.test_plugin1",
          stats_file: "output1.json",
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        }
      ];
      assert(readBundlePlugins("", "").length === 0);
      done();
    });
  });
  describe('two external flags on inputs, one with core_name value, externals output', function() {
    it('should have one entry', function (done) {
      data = [
        {
          name: "kolibri.plugin.test.test_plugin",
          src_file: "src/file.js",
          stats_file: "output.json",
          external: true,
          static_dir: "kolibri/plugin/test",
          static_url_root: "static",
          core_name: "test_global",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        },
        {
          name: "kolibri.plugin.test.test_plugin1",
          src_file: "src/file1.js",
          stats_file: "output1.json",
          external: true,
          static_url_root: "static",
          static_dir: "kolibri/plugin/test",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        }
      ];
      assert(Object.keys(readBundlePlugins("", function(){return {};})[0].externals).length === 1);
      done();
    });
  });
  describe('two identically named external flags on inputs, externals output', function() {
    it('should have one entry', function (done) {
      data = [
        {
          name: "kolibri.plugin.test.test_plugin",
          src_file: "src/file.js",
          stats_file: "output.json",
          external: true,
          static_dir: "kolibri/plugin/test",
          static_url_root: "static",
          core_name: "test_global",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        },
        {
          name: "kolibri.plugin.test.test_plugin",
          src_file: "src/file1.js",
          stats_file: "output1.json",
          external: true,
          static_dir: "kolibri/plugin/test",
          static_url_root: "static",
          core_name: "test_global",
          locale_data_folder: "kolibri/locale/test",
          plugin_path: "kolibri/plugin"
        }
      ];
      assert(Object.keys(readBundlePlugins("", function(){return {};})[0].externals).length === 1);
      done();
    });
  });
});
<|endoftext|>


<commit_before>'use strict'

var AbstractTransport = require('./abstract')
var merge = require('merge')
var net = require('net')
var nicAddresses = require('./addresses/nic')
var NetStringStream = require('./session/netstring')
var OneTpError = require('../error')
var runtime = require('mm-runtime-info')
var util = require('util')
var winston = require('winston-debug')
var winstonWrapper = require('winston-meta-wrapper')

/**
 * Tcp transport
 *
 * @constructor
 * @fires TcpTransport#listening
 * @fires TcpTransport#connection
 * @fires TcpTransport#connect
 * @fires TcpTransport#error
 * @fires TcpTransport#close
 */
function TcpTransport (args) {
  if (!(this instanceof TcpTransport)) {
    return new TcpTransport(args)
  }
  AbstractTransport.call(this)
  // verify runtime compatibility
  if (!TcpTransport.isCompatibleWithRuntime()) {
    var errorMsg = 'TCP transport cannot be used on this runtime'
    this._error(errorMsg)
  }
  // logging
  this._log = winstonWrapper(winston)
  this._log.addMeta({
    module: '1tp:transports:tcp'
  })
  // init
  this._args = merge(Object.create(TcpTransport.DEFAULTS), args)
  this._connectingSockets = {}
  // create listening socket
  this._createServerSocket(this._args)
  // done
  this._log.debug('created tcp transport with args ' + JSON.stringify(this._args))
}

// Inherit from abstract transport
util.inherits(TcpTransport, AbstractTransport)

TcpTransport.DEFAULTS = {
  allowHalfOpen: false,
  pauseOnConnect: false,
  connectTimeout: 100
}

TcpTransport.isCompatibleWithRuntime = function () {
  return !runtime.isBrowser() && !runtime.isCordovaApp()
}

TcpTransport.prototype._createServerSocket = function (socketOpts) {
  var self = this
  this._muteSocketErrorListeners = false
  this._server = net.createServer(socketOpts)
  this._server.on('connection', this._onConnection())
  this._server.on('error', function (error) {
    if (self._muteSocketErrorListeners) {
      return
    }
    self._log.error(error)
    self._error(error)
  })
}

TcpTransport.prototype._onConnection = function () {
  var self = this
  return function (socket) {
    var netstring = new NetStringStream()
    netstring.attachToEncoder(socket)
    netstring.attachToDecoder(socket)
    var peerConnectionInfo = {
      transportType: self.transportType(),
      transportInfo: {
        address: socket.remoteAddress,
        port: socket.remotePort
      }
    }
    self._fireConnectionEvent(netstring, self, peerConnectionInfo)
  }
}

TcpTransport.prototype.transportType = function () {
  return 'tcp'
}

TcpTransport.prototype.listen = function (listeningInfo, onSuccess, onFailure) {
  this._log.debug('listen to ' + JSON.stringify(listeningInfo))
  var port, address
  if (listeningInfo !== undefined) {
    // verify listeningInfo
    if (listeningInfo.transportType !== this.transportType()) {
      var transportTypeError = 'incorrect listeningInfo: unexpected transportType -- ignoring request'
      this._log.error(transportTypeError)
      this._error(transportTypeError, onFailure)
      return
    }
    if (listeningInfo.transportInfo === undefined) {
      var transportInfoUndefined = 'incorrect connectionInfo: transportInfo is undefined'
      this._log.error(transportInfoUndefined)
      this._error(transportInfoUndefined, onFailure)
      return
    }
    port = listeningInfo.transportInfo.port
    address = listeningInfo.transportInfo.address
  }

  var self = this
  // fire up
  port = (port === undefined) ? 0 : port
  // prepare to process errors during bind operation
  var onBindError = function (error) {
    self._error(error, onFailure)
  }
  // mute existing error listeners during bind operation
  this._muteSocketErrorListeners = true
  // register temp error listener
  this._server.once('error', onBindError)
  // bind tcp server socket
  this._server.listen(port, address, function () {
    // drop error listener
    self.removeListener('error', onBindError)
    // unmute existing error listeners
    self._muteSocketErrorListeners = true
    // create connection info
    var myConnectionInfo = {
      transportType: self.transportType(),
      transportInfo: {
        // address will be added below
        port: self._server.address().port
      },
      version: self.version
    }
    // if address was specified in listening info, then reuse it
    if (address) {
      myConnectionInfo.transportInfo.address = self._server.address().address
      self._myConnectionInfo = myConnectionInfo
      self._log.debug('tcp socket bound, connectionInfo = ' + JSON.stringify(myConnectionInfo))
      self._fireListeningEvent(myConnectionInfo, onSuccess)
    } else {
      // otherwise, retrieve local ip address
      nicAddresses.getIpAddressesP()
        .then(function (addresses) {
          var myConnectionInfos = addresses.map(function (localAddress) {
            var connectionInfo = {
              transportType: myConnectionInfo.transportType,
              transportInfo: {
                address: localAddress,
                // INVARIANT thomasdelaet: port numbers must be the same when creating separate transport info instances for different local ipAddresses
                port: myConnectionInfo.transportInfo.port
              },
              version: self.version
            }
            return connectionInfo
          })
          self._log.debug('tcp socket bound, connectionInfo = ' + JSON.stringify(myConnectionInfos))
          self._fireListeningEvent(myConnectionInfos, onSuccess)
        })
        .catch(function (error) {
          self._error(error, onFailure)
        })
    }
  })
}

TcpTransport.prototype.connect = function (peerConnectionInfo, onSuccess, onFailure) {
  this._log.debug('connect to ' + JSON.stringify(peerConnectionInfo))
  // verify peerConnectionInfo
  if (peerConnectionInfo.transportType !== this.transportType()) {
    var transportTypeError = 'incorrect connectionInfo: unexpected transportType -- ignoring request'
    this._log.error(transportTypeError)
    this._error(transportTypeError, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo === undefined) {
    var transportInfoUndefined = 'incorrect connectionInfo: transportInfo is undefined'
    this._log.error(transportInfoUndefined)
    this._error(transportInfoUndefined, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo.address === undefined || peerConnectionInfo.transportInfo.port === undefined) {
    var addressError = 'incorrect connectionInfo: address and/or port attribute is undefined'
    this._log.error(addressError)
    this._error(addressError, onFailure)
    return
  }
  // establish connection
  var self = this
  var socket = net.connect(peerConnectionInfo.transportInfo.port, peerConnectionInfo.transportInfo.address, function () {
    self._log.debug('connection established with endpoint ' + JSON.stringify(peerConnectionInfo))
    // stop and remove timer
    clearTimeout(socket._1tpConnectionTimeout)
    delete socket._1tpConnectionTimeout
    // delete socket from connectingSockets
    delete self._connectingSockets[peerConnectionInfo.transportInfo]
    // create netstring stream + pipe socket to this stream
    var netstring = new NetStringStream()
    netstring.attachToEncoder(socket)
    netstring.attachToDecoder(socket)
    // fire connect event
    self._fireConnectEvent(netstring, peerConnectionInfo, onSuccess)
  })
  socket.on('error', function (error) {
    // stop and remove connection timer if present
    if (socket._1tpConnectionTimeout) {
      // stop and remove timer
      clearTimeout(socket._1tpConnectionTimeout)
      delete socket._1tpConnectionTimeout
      // delete socket from connectingSockets
      delete self._connectingSockets[peerConnectionInfo.transportInfo]
    }
    self._log.error(error)
    self._error(error, onFailure)
  })
  // store socket in case the scheduler wants to abort it
  this._connectingSockets[peerConnectionInfo.transportInfo] = socket
  // set timeout
  socket._1tpConnectionTimeout = setTimeout(function () {
    // abort handshake init
    self.abort(
      peerConnectionInfo,
      function () {
        // create and display error message
        var handshakeAbortedMessage = 'handshake aborted'
        self._log.error(handshakeAbortedMessage)
        // when ready, fire error event
        self._error(new OneTpError(OneTpError.CODES.handshakeAborted, handshakeAbortedMessage), onFailure)
      },
      onFailure
    )
  }, this._args.connectTimeout)
}

TcpTransport.prototype.abort = function (peerConnectionInfo, onSuccess, onFailure) {
  this._log.debug('aborting handshake with ' + JSON.stringify(peerConnectionInfo))
  // verify peerConnectionInfo
  if (peerConnectionInfo.transportType !== this.transportType()) {
    var transportTypeError = 'incorrect connectionInfo: unexpected transportType -- Ignoring request'
    this._log.error(transportTypeError)
    this._error(transportTypeError, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo === undefined) {
    var transportInfoUndefined = 'incorrect connectionInfo: transportInfo is undefined'
    this._log.error(transportInfoUndefined)
    this._error(transportInfoUndefined, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo.address === undefined || peerConnectionInfo.transportInfo.port === undefined) {
    var addressError = 'incorrect connectionInfo: address and/or port attribute is undefined'
    this._log.error(addressError)
    this._error(addressError, onFailure)
    return
  }
  var socket = this._connectingSockets[peerConnectionInfo.transportInfo]
  if (!socket) {
    var noSocketMessage = 'cannot find socket for connectionInfo ' + JSON.stringify(peerConnectionInfo.transportInfo)
    this._log.error(noSocketMessage)
    this._error(new OneTpError(OneTpError.CODES.nothingToAbort, noSocketMessage), onFailure)
    return
  }
  var self = this
  // once socket is destroyed
  socket.once('close', function () {
    // stop and remove timer
    clearTimeout(socket._1tpConnectionTimeout)
    delete socket._1tpConnectionTimeout
    // delete socket from connectingSockets
    delete self._connectingSockets[peerConnectionInfo.transportInfo]
    // done
    onSuccess()
  })
  // destroy socket
  socket.destroy()
}

TcpTransport.prototype.close = function (onSuccess, onFailure) {
  var self = this
  this._server.close(function () {
    self._fireCloseEvent(onSuccess)
  })
}

module.exports = TcpTransport
<commit_msg>avoid issues with :: addresses<commit_after>'use strict'

var AbstractTransport = require('./abstract')
var merge = require('merge')
var net = require('net')
var nicAddresses = require('./addresses/nic')
var NetStringStream = require('./session/netstring')
var OneTpError = require('../error')
var runtime = require('mm-runtime-info')
var util = require('util')
var winston = require('winston-debug')
var winstonWrapper = require('winston-meta-wrapper')

/**
 * Tcp transport
 *
 * @constructor
 * @fires TcpTransport#listening
 * @fires TcpTransport#connection
 * @fires TcpTransport#connect
 * @fires TcpTransport#error
 * @fires TcpTransport#close
 */
function TcpTransport (args) {
  if (!(this instanceof TcpTransport)) {
    return new TcpTransport(args)
  }
  AbstractTransport.call(this)
  // verify runtime compatibility
  if (!TcpTransport.isCompatibleWithRuntime()) {
    var errorMsg = 'TCP transport cannot be used on this runtime'
    this._error(errorMsg)
  }
  // logging
  this._log = winstonWrapper(winston)
  this._log.addMeta({
    module: '1tp:transports:tcp'
  })
  // init
  this._args = merge(Object.create(TcpTransport.DEFAULTS), args)
  this._connectingSockets = {}
  // create listening socket
  this._createServerSocket(this._args)
  // done
  this._log.debug('created tcp transport with args ' + JSON.stringify(this._args))
}

// Inherit from abstract transport
util.inherits(TcpTransport, AbstractTransport)

TcpTransport.DEFAULTS = {
  allowHalfOpen: false,
  pauseOnConnect: false,
  connectTimeout: 100
}

TcpTransport.isCompatibleWithRuntime = function () {
  return !runtime.isBrowser() && !runtime.isCordovaApp()
}

TcpTransport.prototype._createServerSocket = function (socketOpts) {
  var self = this
  this._muteSocketErrorListeners = false
  this._server = net.createServer(socketOpts)
  this._server.on('connection', this._onConnection())
  this._server.on('error', function (error) {
    if (self._muteSocketErrorListeners) {
      return
    }
    self._log.error(error)
    self._error(error)
  })
}

TcpTransport.prototype._onConnection = function () {
  var self = this
  return function (socket) {
    var netstring = new NetStringStream()
    netstring.attachToEncoder(socket)
    netstring.attachToDecoder(socket)
    var peerConnectionInfo = {
      transportType: self.transportType(),
      transportInfo: {
        address: socket.remoteAddress,
        port: socket.remotePort
      }
    }
    self._fireConnectionEvent(netstring, self, peerConnectionInfo)
  }
}

TcpTransport.prototype.transportType = function () {
  return 'tcp'
}

TcpTransport.prototype.listen = function (listeningInfo, onSuccess, onFailure) {
  this._log.debug('listen to ' + JSON.stringify(listeningInfo))
  var port = 0
  var address = '0.0.0.0'
  if (listeningInfo !== undefined) {
    // verify listeningInfo
    if (listeningInfo.transportType !== this.transportType()) {
      var transportTypeError = 'incorrect listeningInfo: unexpected transportType -- ignoring request'
      this._log.error(transportTypeError)
      this._error(transportTypeError, onFailure)
      return
    }
    if (listeningInfo.transportInfo === undefined) {
      var transportInfoUndefined = 'incorrect connectionInfo: transportInfo is undefined'
      this._log.error(transportInfoUndefined)
      this._error(transportInfoUndefined, onFailure)
      return
    }
    port = listeningInfo.transportInfo.port
    address = listeningInfo.transportInfo.address
  }

  var self = this
  // prepare to process errors during bind operation
  var onBindError = function (error) {
    self._error(error, onFailure)
  }
  // mute existing error listeners during bind operation
  this._muteSocketErrorListeners = true
  // register temp error listener
  this._server.once('error', onBindError)
  // bind tcp server socket
  this._server.listen(port, address, function () {
    // drop error listener
    self.removeListener('error', onBindError)
    // unmute existing error listeners
    self._muteSocketErrorListeners = true
    // create connection info
    var myConnectionInfo = {
      transportType: self.transportType(),
      transportInfo: {
        // address will be added below
        port: self._server.address().port
      },
      version: self.version
    }
    // if address was specified in listening info, then reuse it
    if (address !== '0.0.0.0' && address !== '::') {
      myConnectionInfo.transportInfo.address = self._server.address().address
      self._myConnectionInfo = myConnectionInfo
      self._log.debug('tcp socket bound, connectionInfo = ' + JSON.stringify(myConnectionInfo))
      self._fireListeningEvent(myConnectionInfo, onSuccess)
    } else {
      // otherwise, retrieve local ip address
      nicAddresses.getIpAddressesP()
        .then(function (addresses) {
          var myConnectionInfos = addresses.map(function (localAddress) {
            var connectionInfo = {
              transportType: myConnectionInfo.transportType,
              transportInfo: {
                address: localAddress,
                // INVARIANT thomasdelaet: port numbers must be the same when creating separate transport info instances for different local ipAddresses
                port: myConnectionInfo.transportInfo.port
              },
              version: self.version
            }
            return connectionInfo
          })
          self._log.debug('tcp socket bound, connectionInfo = ' + JSON.stringify(myConnectionInfos))
          self._fireListeningEvent(myConnectionInfos, onSuccess)
        })
        .catch(function (error) {
          self._error(error, onFailure)
        })
    }
  })
}

TcpTransport.prototype.connect = function (peerConnectionInfo, onSuccess, onFailure) {
  this._log.debug('connect to ' + JSON.stringify(peerConnectionInfo))
  // verify peerConnectionInfo
  if (peerConnectionInfo.transportType !== this.transportType()) {
    var transportTypeError = 'incorrect connectionInfo: unexpected transportType -- ignoring request'
    this._log.error(transportTypeError)
    this._error(transportTypeError, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo === undefined) {
    var transportInfoUndefined = 'incorrect connectionInfo: transportInfo is undefined'
    this._log.error(transportInfoUndefined)
    this._error(transportInfoUndefined, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo.address === undefined || peerConnectionInfo.transportInfo.port === undefined) {
    var addressError = 'incorrect connectionInfo: address and/or port attribute is undefined'
    this._log.error(addressError)
    this._error(addressError, onFailure)
    return
  }
  // establish connection
  var self = this
  var socket = net.connect(peerConnectionInfo.transportInfo.port, peerConnectionInfo.transportInfo.address, function () {
    self._log.debug('connection established with endpoint ' + JSON.stringify(peerConnectionInfo))
    // stop and remove timer
    clearTimeout(socket._1tpConnectionTimeout)
    delete socket._1tpConnectionTimeout
    // delete socket from connectingSockets
    delete self._connectingSockets[peerConnectionInfo.transportInfo]
    // create netstring stream + pipe socket to this stream
    var netstring = new NetStringStream()
    netstring.attachToEncoder(socket)
    netstring.attachToDecoder(socket)
    // fire connect event
    self._fireConnectEvent(netstring, peerConnectionInfo, onSuccess)
  })
  socket.on('error', function (error) {
    // stop and remove connection timer if present
    if (socket._1tpConnectionTimeout) {
      // stop and remove timer
      clearTimeout(socket._1tpConnectionTimeout)
      delete socket._1tpConnectionTimeout
      // delete socket from connectingSockets
      delete self._connectingSockets[peerConnectionInfo.transportInfo]
    }
    self._log.error(error)
    self._error(error, onFailure)
  })
  // store socket in case the scheduler wants to abort it
  this._connectingSockets[peerConnectionInfo.transportInfo] = socket
  // set timeout
  socket._1tpConnectionTimeout = setTimeout(function () {
    // abort handshake init
    self.abort(
      peerConnectionInfo,
      function () {
        // create and display error message
        var handshakeAbortedMessage = 'handshake aborted'
        self._log.error(handshakeAbortedMessage)
        // when ready, fire error event
        self._error(new OneTpError(OneTpError.CODES.handshakeAborted, handshakeAbortedMessage), onFailure)
      },
      onFailure
    )
  }, this._args.connectTimeout)
}

TcpTransport.prototype.abort = function (peerConnectionInfo, onSuccess, onFailure) {
  this._log.debug('aborting handshake with ' + JSON.stringify(peerConnectionInfo))
  // verify peerConnectionInfo
  if (peerConnectionInfo.transportType !== this.transportType()) {
    var transportTypeError = 'incorrect connectionInfo: unexpected transportType -- Ignoring request'
    this._log.error(transportTypeError)
    this._error(transportTypeError, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo === undefined) {
    var transportInfoUndefined = 'incorrect connectionInfo: transportInfo is undefined'
    this._log.error(transportInfoUndefined)
    this._error(transportInfoUndefined, onFailure)
    return
  }
  if (peerConnectionInfo.transportInfo.address === undefined || peerConnectionInfo.transportInfo.port === undefined) {
    var addressError = 'incorrect connectionInfo: address and/or port attribute is undefined'
    this._log.error(addressError)
    this._error(addressError, onFailure)
    return
  }
  var socket = this._connectingSockets[peerConnectionInfo.transportInfo]
  if (!socket) {
    var noSocketMessage = 'cannot find socket for connectionInfo ' + JSON.stringify(peerConnectionInfo.transportInfo)
    this._log.error(noSocketMessage)
    this._error(new OneTpError(OneTpError.CODES.nothingToAbort, noSocketMessage), onFailure)
    return
  }
  var self = this
  // once socket is destroyed
  socket.once('close', function () {
    // stop and remove timer
    clearTimeout(socket._1tpConnectionTimeout)
    delete socket._1tpConnectionTimeout
    // delete socket from connectingSockets
    delete self._connectingSockets[peerConnectionInfo.transportInfo]
    // done
    onSuccess()
  })
  // destroy socket
  socket.destroy()
}

TcpTransport.prototype.close = function (onSuccess, onFailure) {
  var self = this
  this._server.close(function () {
    self._fireCloseEvent(onSuccess)
  })
}

module.exports = TcpTransport
<|endoftext|>


<commit_before>const
  fs = require('fs'),
  path = require('path'),
  minimatch = require('minimatch'),
  objectHash = require('object-hash'),
  Emitter = require('events').EventEmitter;

let hasBabel = true;

try {
  require('babel-core');
} catch (e) {
  hasBabel = false;
}

const compiler = module.exports = new Emitter();

compiler.setMaxListeners(Infinity);

compiler.compileAtomaticFiles = (files) => {

  return files
    .filter(({filename}) => minimatch(path.basename(filename), compiler.matchPattern))
    .map((file) => {

      const
        {filename, componentName, extension, data, timestamp} = file,
        atomaticFile = path.join(compiler.path, componentName + '.atomatic'),
        hash = objectHash.MD5({componentName, browserify: true});

      if (!file._lastBrowserify || file._lastBrowserify < timestamp) {
        const {source: template, locals} = compiler.compileFile({
            filename,
            componentName,
            extension,
            data,
            hash,
            timestamp,
            saveHtml: null,
            saveLocals: null,
            renderHook: null
          },
          compiler.global, false);
        fs.writeFileSync(atomaticFile, JSON.stringify({template, locals}, null, 2));

        file._lastBrowserify = timestamp;
      }

      return componentName;
    });
};

compiler.compile = (content, cb) => {
  compiler.compiledAtomaticFiles.map(componentName => {
    content = content.replace(new RegExp(`(\'|\")+(${componentName})(\'|\")+`, 'g'), `$1${compiler.path}/${componentName}.atomatic$3`);
  });

  cb(null, content)
};
<commit_msg>enable seperated browserify templates and trigger change event for external usage<commit_after>const
  fs = require('fs'),
  path = require('path'),
  minimatch = require('minimatch'),
  objectHash = require('object-hash'),
  Emitter = require('events').EventEmitter;

let hasBabel = true;

try {
  require('babel-core');
} catch (e) {
  hasBabel = false;
}

const compiler = module.exports = new Emitter();

compiler.setMaxListeners(Infinity);

compiler.compileAtomaticFiles = (files) => {

  return files
    .filter(({filename}) => minimatch(path.basename(filename), compiler.matchPattern))
    .map((file) => {

      const
        {filename, componentName, extension, data, timestamp} = file,
        atomaticFile = path.join(compiler.path, componentName + '.atomatic'),
        hash = objectHash.MD5({componentName, browserify: true});

      if (!file._lastBrowserify || file._lastBrowserify < timestamp) {
        const {source: template, locals} = compiler.compileFile({
            filename,
            componentName,
            extension,
            data,
            hash,
            timestamp,
            saveHtml: null,
            saveLocals: null,
            renderHook: null
          },
          compiler.global, false);
        fs.writeFileSync(atomaticFile, JSON.stringify({template, locals}, null, 2));

        file._lastBrowserify = timestamp;
      }

      return componentName;
    });
};

compiler.compile = (content, cb) => {
  compiler.compiledAtomaticFiles.map(componentName => {
    const
      cleanedComponentName = path.basename(componentName, path.extname(componentName)),
      regex = new RegExp(`(\'|\")+(${cleanedComponentName})(\'|\")+`, 'g'),
      value = `$1${compiler.path}/${componentName}.atomatic$3`;

    content = content.replace(regex, value);
  });

  cb(null, content)
};
<|endoftext|>


<commit_before>'use strict';
const moment = require('moment');
require('moment-timezone');

module.exports = function TwitchMessages(client) {
  let modChannel;
  if (client.user.id === '120105547633524736') {
    modChannel = client.channels.get('140025699867164673');
  } else {
    modChannel = client.channels.get('252275732628242432');
  }
  const streamInfoSocket = require('socket.io-client')('ws://info.annemunition.tv');
  streamInfoSocket.on('connect', () => {
    client.logger.info('connected to streamInfo websocket');
  });
  streamInfoSocket.on('disconnect', () => {
    client.logger.warn('disconnected from streamInfo websocket');
  });
  streamInfoSocket.on('discord_ban_event', data => {
    if (!data) return;
    if (typeof data !== 'object') return;
    if (Array.isArray(data)) return;
    if (!modChannel) return;
    client.logger.debug('discord_ban_event received');
    let username = data.messages && data.messages[0] ?
      data.messages[0].userstate['display-name'] || data.username :
      data.username;
    if (username.toLowerCase() !== data.username.toLowerCase()) username = data.username;
    const messages = data.messages
      .sort(x => -parseInt(x.userstate['tmi-sent-ts']))
      .map(x => {
        const time = moment(parseInt(x.userstate['tmi-sent-ts']));
        return `\`\`[${time.tz('America/Los_Angeles').format('MM/DD/YY HH:mm:ss')}]\`\` ${x.message}`;
      });
    const embed = new client.Discord.RichEmbed()
      .setTitle(`'${username}' was banned from Twitch Chat`)
      .setColor('DARK_ORANGE')
      .setTimestamp(moment())
      .setDescription(messages.join('\n'));
    if (data.reason) embed.addField('Reason: ', data.reason);
    modChannel.send({ embed }).catch(client.logger.error);
  });

  streamInfoSocket.on('discord_unban_event', username => {
    if (!username) return;
    if (!modChannel) return;
    client.logger.debug('discord_unban_event received');
    const embed = new client.Discord.RichEmbed()
      .setTitle(`'${username}' was un-banned from Twitch Chat`)
      .setColor('DARK_BLUE')
      .setTimestamp(moment());
    modChannel.send({ embed }).catch(client.logger.error);
  });
};
<commit_msg>PS ban/unban<commit_after>'use strict';
const moment = require('moment');
require('moment-timezone');

module.exports = function TwitchMessages(client) {
  let modChannel;
  if (client.user.id === '120105547633524736') {
    modChannel = client.channels.get('140025699867164673');
  } else {
    modChannel = client.channels.get('252275732628242432');
  }
  const streamInfoSocket = require('socket.io-client')('ws://info.annemunition.tv');
  streamInfoSocket.on('connect', () => {
    client.logger.info('connected to streamInfo websocket');
  });
  streamInfoSocket.on('disconnect', () => {
    client.logger.warn('disconnected from streamInfo websocket');
  });
  streamInfoSocket.on('discord_ban_event', data => {
    if (!data) return;
    if (typeof data !== 'object') return;
    if (Array.isArray(data)) return;
    if (!modChannel) return;
    client.logger.debug('discord_ban_event received');
    const messages = data.messages
      .sort(x => -parseInt(x.userstate['tmi-sent-ts']))
      .map(x => {
        const time = moment(parseInt(x.userstate['tmi-sent-ts']));
        return `\`\`[${time.tz('America/Los_Angeles').format('MM/DD/YY HH:mm:ss')}]\`\` ${x.message}`;
      });
    let title = `'${data.banee}' was banned from Twitch Chat by '${data.banear}'`;
    if (data.reason) title += ` for: '${data.reason}'`;
    const embed = new client.Discord.RichEmbed()
      .setTitle(title)
      .setColor('DARK_ORANGE')
      .setTimestamp(moment(data.time))
      .setDescription(messages.join('\n'));
    modChannel.send({ embed }).catch(client.logger.error);
  });

  streamInfoSocket.on('discord_unban_event', data => {
    if (!data) return;
    if (typeof data !== 'object') return;
    if (Array.isArray(data)) return;
    if (!modChannel) return;
    client.logger.debug('discord_unban_event received');
    const embed = new client.Discord.RichEmbed()
      .setTitle(`'${data.banee}' was un-banned from Twitch Chat by '${data.banear}'`)
      .setColor('DARK_BLUE')
      .setTimestamp(moment(data.time));
    modChannel.send({ embed }).catch(client.logger.error);
  });
};
<|endoftext|>


<commit_before><commit_msg>removed header and footer and newlines from cert when displayed console log style<commit_after><|endoftext|>


<commit_before>angular.module('feedbackcontrol', [])
.directive('transform', function(FeedbackSignal) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var currentUrl = window.location.pathname;
                var me = $(element);
                var data = FeedbackSignal.data;

                if(currentUrl.match(/published|contacts/g)) {

                    if(me.attr('return-policy') == 1) {
                        hide_the_children(me);
                    }

                    if(data.status != "fileas") {
                        if(data.status == "feature") {
                            var state = {
                                activate: {'background-position': '-64px -31px'}
                              , deactivate_sibling: {'background-position': '-32px 0px'}
                              , activation_color: {'background-color': '#FFFFE0'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "publish", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.publish', 'Publish Feedback', state);
                        }

                        if(data.status == "publish") {
                            var state = {
                                activate: {'background-position': '-32px -31px'}
                              , deactivate_sibling: {'background-position': '-64px 0px'}
                              , activation_color: {'background-color': '#FFF'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "feature", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.feature', 'Feature Feedback', state);
                        }
                    } else {
                        hide_the_children(me);
                    }

                } else if(currentUrl.match(/filed/g)) {

                    var data_status = data.status;

                    if(data_status == "publish" || data_status == "feature" || data_status == "delete") {
                        hide_the_children(me);
                    }

                } else {
                    hide_the_children(me);
                }

                e.preventDefault();
            });
        }
    }
})
.directive('undo', function(FeedbackSignal, FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                if (FeedbackSignal.data.id instanceof Array) {
                    for(var i=0; i < FeedbackSignal.data.id.length ; i++) {
                        var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "]");
                        feedback.show();
                        $(feedback).parents('.feedback-group').show();
                    }
                } else {
                    var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "]");
                    feedback.show();
                    $(feedback).parents('.feedback-group').show();
                }

                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('close', function(FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('feedcheckbox', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            var checkbox = $(element);

            checkbox.bind('change', function() {
                if(checkbox.is(":checked")) {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#F7F7F7'});
                } else {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#FFF'});
                }
            });

        }
    }
})
.directive('statuschange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'status');
            })
        }
    }
})
.directive('prioritychange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'priority');
            })
        }
    }
})
.directive('deleteBlock', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                console.log(this);
                /*
                 $(this).parent().fadeOut(400, function() {
                     var div = $(this).parent('.uploaded-images-and-links');
                     //$(this).remove();

                     var remove_images = {
                        'small_url'    :$(this).find('.small-image-url').val(),
                        'medium_url'   :$(this).find('.medium-image-url').val(),
                        'large_url'    :$(this).find('.large-image-url').val()
                     }

                    var attachments = new Array;
                    if(div.find('.uploaded_image').length>0){
                        var new_uploaded_images = new Array;
                        div.find('.the-thumb').each(function(){
                            new_uploaded_images.push({
                                'name'    :$(this).find('.image-name').val(),
                            });
                        });
                    }

                    if(div.find('.attached_link').length > 0){
                        var new_attached_link = {
                            title           : div.find('.link-title').val(),
                            description     : div.find('.link-description').val(),
                            image           : div.find('.link-image').val(),
                            url             : div.find('.link-url').val(),
                            video           : div.find('.link-video').val(),
                        }
                    };

                    var remaining = {
                        uploaded_images : new_uploaded_images,
                        attached_link   : new_attached_link
                    }

                    console.log(remaining);
                    console.log(remove_images);
                    console.log(div.find('.attachment_feedback_id').val());
                });
                */
                e.preventDefault();
            });
        }
    }
})

function published_state(obj, sibling_id, msg, state) {
    obj.parents('.dashboard-feedback').css(state.activation_color);
    obj.css(state.activate);
    obj.children('.action-tooltip').children('span').html("Return to Inbox");
    obj.siblings(sibling_id).css(state.deactivate_sibling);
    obj.siblings(sibling_id).children('.action-tooltip').children('span').html(msg);
    obj.siblings(sibling_id).attr('return-policy', 0);
    obj.siblings(sibling_id).attr('data-feed', state.state_change);
    obj.attr('return-policy', 1);
    obj.attr('data-feed', state.state_change_inbox);
}

function hide_the_children(obj) {
    obj.parents('.dashboard-feedback').hide();
    var child_count = obj.parents('.feedback-group').children('.dashboard-feedback:visible');
    if(child_count.length == 0) {
        obj.parents('.feedback-group').hide();
    }

    $(".checky-box-container").show();
}
<commit_msg>no API touch<commit_after>angular.module('feedbackcontrol', [])
.directive('transform', function(FeedbackSignal) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var currentUrl = window.location.pathname;
                var me = $(element);
                var data = FeedbackSignal.data;

                if(currentUrl.match(/published|contacts/g)) {

                    if(me.attr('return-policy') == 1) {
                        hide_the_children(me);
                    }

                    if(data.status != "fileas") {
                        if(data.status == "feature") {
                            var state = {
                                activate: {'background-position': '-64px -31px'}
                              , deactivate_sibling: {'background-position': '-32px 0px'}
                              , activation_color: {'background-color': '#FFFFE0'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "publish", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.publish', 'Publish Feedback', state);
                        }

                        if(data.status == "publish") {
                            var state = {
                                activate: {'background-position': '-32px -31px'}
                              , deactivate_sibling: {'background-position': '-64px 0px'}
                              , activation_color: {'background-color': '#FFF'}
                              , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                              , state_change: '{"status": "feature", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                            }
                            published_state(me, '.feature', 'Feature Feedback', state);
                        }
                    } else {
                        hide_the_children(me);
                    }

                } else if(currentUrl.match(/filed/g)) {

                    var data_status = data.status;

                    if(data_status == "publish" || data_status == "feature" || data_status == "delete") {
                        hide_the_children(me);
                    }

                } else {
                    hide_the_children(me);
                }

                e.preventDefault();
            });
        }
    }
})
.directive('undo', function(FeedbackSignal, FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                if (FeedbackSignal.data.id instanceof Array) {
                    for(var i=0; i < FeedbackSignal.data.id.length ; i++) {
                        var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "]");
                        feedback.show();
                        $(feedback).parents('.feedback-group').show();
                    }
                } else {
                    var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "]");
                    feedback.show();
                    $(feedback).parents('.feedback-group').show();
                }

                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('close', function(FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('feedcheckbox', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            var checkbox = $(element);

            checkbox.bind('change', function() {
                if(checkbox.is(":checked")) {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#F7F7F7'});
                } else {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#FFF'});
                }
            });

        }
    }
})
.directive('statuschange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'status');
            })
        }
    }
})
.directive('prioritychange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "=feedid"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                FeedbackService.inline_change($(this).val(), scope.feedid, 'priority');
            })
        }
    }
})
.directive('deleteBlock', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                $(this).parents('.custom-att').fadeOut(400, function() {
                    var div = $(this).parents('.uploaded-images-and-links');
                    console.log(div);
                });
                /*
                 $(this).parent().fadeOut(400, function() {
                     var div = $(this).parent('.uploaded-images-and-links');
                     //$(this).remove();

                     var remove_images = {
                        'small_url'    :$(this).find('.small-image-url').val(),
                        'medium_url'   :$(this).find('.medium-image-url').val(),
                        'large_url'    :$(this).find('.large-image-url').val()
                     }

                    var attachments = new Array;
                    if(div.find('.uploaded_image').length>0){
                        var new_uploaded_images = new Array;
                        div.find('.the-thumb').each(function(){
                            new_uploaded_images.push({
                                'name'    :$(this).find('.image-name').val(),
                            });
                        });
                    }

                    if(div.find('.attached_link').length > 0){
                        var new_attached_link = {
                            title           : div.find('.link-title').val(),
                            description     : div.find('.link-description').val(),
                            image           : div.find('.link-image').val(),
                            url             : div.find('.link-url').val(),
                            video           : div.find('.link-video').val(),
                        }
                    };

                    var remaining = {
                        uploaded_images : new_uploaded_images,
                        attached_link   : new_attached_link
                    }

                    console.log(remaining);
                    console.log(remove_images);
                    console.log(div.find('.attachment_feedback_id').val());
                });
                */
                e.preventDefault();
            });
        }
    }
})

function published_state(obj, sibling_id, msg, state) {
    obj.parents('.dashboard-feedback').css(state.activation_color);
    obj.css(state.activate);
    obj.children('.action-tooltip').children('span').html("Return to Inbox");
    obj.siblings(sibling_id).css(state.deactivate_sibling);
    obj.siblings(sibling_id).children('.action-tooltip').children('span').html(msg);
    obj.siblings(sibling_id).attr('return-policy', 0);
    obj.siblings(sibling_id).attr('data-feed', state.state_change);
    obj.attr('return-policy', 1);
    obj.attr('data-feed', state.state_change_inbox);
}

function hide_the_children(obj) {
    obj.parents('.dashboard-feedback').hide();
    var child_count = obj.parents('.feedback-group').children('.dashboard-feedback:visible');
    if(child_count.length == 0) {
        obj.parents('.feedback-group').hide();
    }

    $(".checky-box-container").show();
}
<|endoftext|>


<commit_before>const Fs = require('fs');
const Path = require('path');

const Hoek = require('hoek');

const FindNodeVersion = require('./find-node-version');

module.exports = function (options, done) {
  Hoek.assert(options !== undefined, 'options is required');
  Hoek.assert(Fs.existsSync(options.directory), 'Output directory not found');

  var packagePath = Path.resolve(
    options.directory,
    'bundle',
    'programs',
    'server',
    'package.json');

  //
  // Manual parsing of the package.json allows mocking of the read.
  //
  var packageContents = JSON.parse(Fs.readFileSync(packagePath));

  packageContents.engines = { node: FindNodeVersion(options) };
  packageContents.main = '../../main.js';
  packageContents.scripts = { start: 'node ../../main' };

  Hoek.merge(packageContents, options.json || {});

  //
  // The generated package.json is read-only, but removing it prior to writing
  //    will allow updates.
  //
  Fs.unlinkSync(packagePath);
  Fs.writeFile(packagePath, JSON.stringify(packageContents, null, 2), done);
};
<commit_msg>Fix# 143 - EPERM error in Windows<commit_after>const Fs = require('fs');
const Path = require('path');

const Hoek = require('hoek');

const FindNodeVersion = require('./find-node-version');

module.exports = function (options, done) {
  Hoek.assert(options !== undefined, 'options is required');
  Hoek.assert(Fs.existsSync(options.directory), 'Output directory not found');

  var packagePath = Path.resolve(
    options.directory,
    'bundle',
    'programs',
    'server',
    'package.json');

  //
  // Manual parsing of the package.json allows mocking of the read.
  //
  var packageContents = JSON.parse(Fs.readFileSync(packagePath));

  packageContents.engines = { node: FindNodeVersion(options) };
  packageContents.main = '../../main.js';
  packageContents.scripts = { start: 'node ../../main' };

  Hoek.merge(packageContents, options.json || {});

  //
  // The generated package.json is read-only, but removing it prior to writing
  //    will allow updates.
  //
  // Node 0.10.xx + Windows Hack .. Windows does not allow an unlink of a Read-Only file ..
  // So we chmod it to be rw by owner...
  // This was fixed in node 0.12 + but still is an issue in 0.10.XX which Meteor uses..
  if ( FindNodeVersion(options).substring(0,4) === "0.10" && process.platform === "win32") {
  	Fs.chmodSync( packagePath, "0644") ;
  }

  Fs.unlinkSync(packagePath);
  Fs.writeFile(packagePath, JSON.stringify(packageContents, null, 2), done);
};
<|endoftext|>