<commit_before>(function(window) {
	chrome.socketsExtended = {
		_classes: {},
		tcp: {},
		udp: {},
		tcpServer: {}
	};

	/*!
	 * EventEmitter v4.2.7 - git.io/ee
	 * Oliver Caldwell
	 * MIT license
	 * @preserve
	 */
	(function(){"use strict";function t(){}function r(t,n){for(var e=t.length;e--;)if(t[e].listener===n)return e;return-1}function n(e){return function(){return this[e].apply(this,arguments)}}var e=t.prototype,i=this,s=i.EventEmitter;e.getListeners=function(n){var r,e,t=this._getEvents();if(n instanceof RegExp){r={};for(e in t)t.hasOwnProperty(e)&&n.test(e)&&(r[e]=t[e])}else r=t[n]||(t[n]=[]);return r},e.flattenListeners=function(t){var e,n=[];for(e=0;e<t.length;e+=1)n.push(t[e].listener);return n},e.getListenersAsObject=function(n){var e,t=this.getListeners(n);return t instanceof Array&&(e={},e[n]=t),e||t},e.addListener=function(i,e){var t,n=this.getListenersAsObject(i),s="object"==typeof e;for(t in n)n.hasOwnProperty(t)&&-1===r(n[t],e)&&n[t].push(s?e:{listener:e,once:!1});return this},e.on=n("addListener"),e.addOnceListener=function(e,t){return this.addListener(e,{listener:t,once:!0})},e.once=n("addOnceListener"),e.defineEvent=function(e){return this.getListeners(e),this},e.defineEvents=function(t){for(var e=0;e<t.length;e+=1)this.defineEvent(t[e]);return this},e.removeListener=function(i,s){var n,e,t=this.getListenersAsObject(i);for(e in t)t.hasOwnProperty(e)&&(n=r(t[e],s),-1!==n&&t[e].splice(n,1));return this},e.off=n("removeListener"),e.addListeners=function(e,t){return this.manipulateListeners(!1,e,t)},e.removeListeners=function(e,t){return this.manipulateListeners(!0,e,t)},e.manipulateListeners=function(r,t,i){var e,n,s=r?this.removeListener:this.addListener,o=r?this.removeListeners:this.addListeners;if("object"!=typeof t||t instanceof RegExp)for(e=i.length;e--;)s.call(this,t,i[e]);else for(e in t)t.hasOwnProperty(e)&&(n=t[e])&&("function"==typeof n?s.call(this,e,n):o.call(this,e,n));return this},e.removeEvent=function(e){var t,r=typeof e,n=this._getEvents();if("string"===r)delete n[e];else if(e instanceof RegExp)for(t in n)n.hasOwnProperty(t)&&e.test(t)&&delete n[t];else delete this._events;return this},e.removeAllListeners=n("removeEvent"),e.emitEvent=function(r,o){var e,i,t,s,n=this.getListenersAsObject(r);for(t in n)if(n.hasOwnProperty(t))for(i=n[t].length;i--;)e=n[t][i],e.once===!0&&this.removeListener(r,e.listener),s=e.listener.apply(this,o||[]),s===this._getOnceReturnValue()&&this.removeListener(r,e.listener);return this},e.trigger=n("emitEvent"),e.emit=function(e){var t=Array.prototype.slice.call(arguments,1);return this.emitEvent(e,t)},e.setOnceReturnValue=function(e){return this._onceReturnValue=e,this},e._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},e._getEvents=function(){return this._events||(this._events={})},t.noConflict=function(){return i.EventEmitter=s,t},"function"==typeof define&&define.amd?define(function(){return t}):"object"==typeof module&&module.exports?module.exports=t:this.EventEmitter=t}).call(this);

	/**
	 * Object that holds reference to open sockets, used to track down and emit events when they are globally emitted
	 * @type {Object}
	 */
	var socketList = {
		tcp: {},
		udp: {},
		tcpServer: {}
	};

	/**
	 * Create a new ChromeTcpSocket
	 * @param  {Object}   properties SocketProperties sent to the chrome.sockets.tcp.create
	 * @param  {Function} cb         Callback function(ChromeTcpSocket)
	 */
	chrome.socketsExtended.tcp.open = function(properties, cb) {
		chrome.sockets.tcp.create(properties, function(createInfo) {
			var socket = new ChromeTcpSocket(createInfo.socketId);
			socket.on('closed', onSocketClosed);
			socketList.tcp[createInfo.socketId] = socket;
			cb(socket);
		});
	};

	/**
	 * Create a new ChromeTcpServerSocket
	 * @param  {Object}   properties SocketProperties sent to the chrome.sockets.tcpServer.create
	 * @param  {Function} cb         Callback function(ChromeTcpServerSocket)
	 */
	chrome.socketsExtended.tcpServer.open = function(properties, cb) {
		chrome.sockets.tcpServer.create(properties, function(createInfo) {
			var socket = new ChromeTcpServerSocket(createInfo.socketId);
			socket.on('closed', onSocketClosed);
			socketList.tcpServer[createInfo.socketId] = socket;
			cb(socket);
		});
	};

	/**
	 * Create a new ChromeUdpSocket
	 * @param  {Object}   properties SocketProperties sent to the chrome.sockets.udpServer.create
	 * @param  {Function} cb         Callback function(ChromeUdpServerSocket)
	 */
	chrome.socketsExtended.udp.open = function(properties, cb) {
		chrome.sockets.udp.create(properties, function(createInfo) {
			var socket = new ChromeUdpSocket(createInfo.socketId);
			socket.on('closed', onSocketClosed);
			socketList.udp[createInfo.socketId] = socket;
			cb(socket);
		})
	};

	/**
	 * Closes ALL tcp sockets! Even ones not created using this wrapper.
	 * @param  {Function} cb Callback function
	 */
	chrome.socketsExtended.tcp.closeAll = function(cb) {
		chrome.sockets.tcp.getSockets(function(sockets) {
			for (var n = 0; n < sockets.length; n++) {
				chrome.sockets.tcp.close(sockets[n].socketId);
			}
			cb && cb();
		});
	};

	/**
	 * Closes ALL udp sockets! Even ones not created using this wrapper.
	 * @param  {Function} cb Callback function
	 */
	chrome.socketsExtended.udp.closeAll = function(cb) {
		chrome.sockets.udp.getSockets(function(sockets) {
			for (var n = 0; n < sockets.length; n++) {
				chrome.sockets.udp.close(sockets[n].socketId);
			}
			cb && cb();
		});
	};

	/**
	 * Closes ALL tcpSerer sockets! Even ones not created using this wrapper.
	 * @param  {Function} cb Callback function
	 */
	chrome.socketsExtended.tcpServer.closeAll = function(cb) {
		chrome.sockets.tcpServer.getSockets(function(sockets) {
			for (var n = 0; n < sockets.length; n++) {
				chrome.sockets.tcpServer.close(sockets[n].socketId);
			}
			cb && cb();
		});
	};

	/**
	 * Bound to ALL SOCKETS THAT GET CREATED - this releases all event listeners and drops references to the socket object
	 */
	var onSocketClosed = function() {
		socketList[this.type][this.socketId] = null;
		delete socketList[this.type][this.socketId];
		this.removeAllListeners();
	};

	/**
	 * onReceive handler for TCP - finds the appropriate ChromeTcpSocket objects and emit receive with the info
	 * @param  {Object} receiveInfo Data emitted from the chrome.sockets.tcp.onReceive handler
	 */
	chrome.sockets.tcp.onReceive.addListener(function(receiveInfo) {
		var socketId = receiveInfo.socketId;
		if (socketList.tcp[socketId]) {
			socketList.tcp[socketId].emit('receive', receiveInfo);
		}
	});

	/**
	 * onReceiveError handler for TCP - finds the appropriate ChromeTcpSocket objects and emit receiveError with the info
	 * @param  {Object} receiveErrorInfo Data emitted from the chrome.sockets.tcp.onReceive handler
	 */
	chrome.sockets.tcp.onReceiveError.addListener(function(receiveErrorInfo) {
		if (receiveErrorInfo && receiveErrorInfo.socketId && socketList.tcp[receiveErrorInfo.socketId]) {
			socketList.tcp[receiveErrorInfo.socketId].emit('receiveError', receiveErrorInfo.resultCode);
		}
	});

	/**
	 * onReceive handler for UDP - finds the appropriate ChromeUdpSocket objects and emit receive with the info
	 * @param  {Object} receiveInfo Data emitted from the chrome.sockets.udp.onReceive handler
	 */
	chrome.sockets.udp.onReceive.addListener(function(receiveInfo) {
		if (socketList.udp[receiveInfo.socketId]) {
			socketList.udp[receiveInfo.socketId].emit('receive', receiveInfo);
		}
	});

	/**
	 * onReceiveError handler for UDP - finds the appropriate ChromeTcpSocket objects and emit receiveError with the info
	 * @param  {Object} receiveErrorInfo Data emitted from the chrome.sockets.udp.onReceive handler
	 */
	chrome.sockets.udp.onReceiveError.addListener(function(receiveErrorInfo) {
		if (receiveErrorInfo && receiveErrorInfo.socketId && socketList.udp[receiveErrorInfo.socketId]) {
			socketList.udp[receiveErrorInfo.socketId].emit('receiveError', receiveErrorInfo.resultCode);
		}
	});

	/**
	 * onAccept handler for TCP Server sockets - finds the appropriate ChromeTcpServerSocket and emit a new ChromeTcpSocket
	 * to represent the new socket connection to a client
	 * @param  {Object} acceptInfo Server socketId and clientSocketId
	 */
	chrome.sockets.tcpServer.onAccept.addListener(function(acceptInfo) {
		if (socketList.tcpServer[acceptInfo.socketId]) {
			var socket = new ChromeTcpSocket(acceptInfo.clientSocketId);
			socket.on('closed', onSocketClosed);
			socketList.tcp[acceptInfo.clientSocketId] = socket;
			socketList.tcpServer[acceptInfo.socketId].emit('accept', socket);
		}
	});

	/**
	 * onAcceptError handler for TCP Server sockets - finds the appropriate ChromeTcpServerSocket and emit the error info
	 * @param  {Object} acceptErrorInfo Data emitted from the chrome.sockets.tcpServer.onAccept handler
	 */
	chrome.sockets.tcpServer.onAcceptError.addListener(function(acceptErrorInfo) {
		if (acceptErrorInfo && acceptErrorInfo.socketId && socketList.udp[acceptErrorInfo.socketId]) {
			socketList.tcpServer[acceptErrorInfo.socketId].emit('receiveError', acceptErrorInfo.resultCode);
		}
	});

	// BASE CLASS
	var ChromeSocket = function(type) {
		EventEmitter.call(this);
		this._api = chrome.sockets[type];
		this.type = type;
	}
	ChromeSocket.prototype = Object.create(EventEmitter.prototype);

	ChromeSocket.prototype.update = function(properties, cb) {
		this._api.update(this.socketId, properties, cb);
	};

	ChromeSocket.prototype.setPaused = function(paused, cb) {
		this._api.setPaused(this.socketId, paused, cb);
	};

	ChromeSocket.prototype.close = function(cb) {
		var self = this;
		this._api.close(this.socketId, function() {
			self.emit('closed');
		});
	};

	ChromeSocket.prototype.getInfo = function(cb) {
		this._api.getInfo(this.socketId, cb);
	};

	// TCP
	var ChromeTcpSocket = function(socketId) {
		ChromeSocket.call(this, 'tcp');
		this.socketId = socketId;
	};
	ChromeTcpSocket.prototype = Object.create(ChromeSocket.prototype);

	ChromeTcpSocket.prototype.setKeepAlive = function(enable, delay, cb) {
		chrome.sockets.tcp.setKeepAlive(this.socketId, enable, delay, cb);
	};

	ChromeTcpSocket.prototype.setNoDelay = function(noDelay, cb) {
		chrome.sockets.tcp.setNoDelay(this.socketId, noDelay, cb);
	};

	ChromeTcpSocket.prototype.connect = function(host, port, cb) {
		chrome.sockets.tcp.connect(this.socketId, host, port, cb);
	};

	ChromeTcpSocket.prototype.disconnect = function(cb) {
		chrome.sockets.tcp.disconnect(this.socketId, cb);
	};

	ChromeTcpSocket.prototype.send = function(arrayBuffer, cb) {
		chrome.sockets.tcp.send(this.socketId, arrayBuffer, cb);
	};

	// UDP
	var ChromeUdpSocket = function(socketId) {
		ChromeSocket.call(this, 'udp');
		this.socketId = socketId;
	};
	ChromeUdpSocket.prototype = Object.create(ChromeSocket.prototype);

	ChromeUdpSocket.prototype.bind = function(address, port, cb) {
		chrome.sockets.udp.bind(this.socketId, address, port, cb);
	};

	ChromeUdpSocket.prototype.send = function(arrayBuffer, host, port, cb) {
		chrome.sockets.udp.send(this.socketId, arrayBuffer, host, port, cb);
	};

	ChromeUdpSocket.prototype.joinGroup = function(address, cb) {
		chrome.sockets.udp.joinGroup(this.socketId, address, cb);
	};

	ChromeUdpSocket.prototype.leaveGroup = function(address, cb) {
		chrome.sockets.udp.leaveGroup(this.socketId, address, cb);
	};

	ChromeUdpSocket.prototype.setMulticastTimeToLive = function(ttl, cb) {
		chrome.sockets.udp.setMulticastTimeToLive(this.socketId, ttl, cb);
	};

	ChromeUdpSocket.prototype.setMulticastLoopbackMode = function(enabled, cb) {
		chrome.sockets.udp.setMulticastLoopbackMode(this.socketId, enabled, cb);
	};

	ChromeUdpSocket.prototype.getJoinedGroups = function(cb) {
		chrome.sockets.udp.getJoinedGroups(this.socketId, cb);
	};

	// TCP SERVER
	var ChromeTcpServerSocket = function(socketId) {
		ChromeSocket.call(this, 'tcpServer');
		this.socketId = socketId;
	};
	ChromeTcpServerSocket.prototype = Object.create(ChromeSocket.prototype);

	ChromeTcpServerSocket.prototype.listen = function(host, port, cb) {
		chrome.sockets.tcpServer.listen(this.socketId, host, port, cb);
	};

	ChromeTcpServerSocket.prototype.disconnect = function(cb) {
		chrome.sockets.tcpServer.disconnect(this.socketId, cb);
	};

	chrome.socketsExtended._classes['ChromeTcpSocket'] = ChromeTcpSocket;
	chrome.socketsExtended._classes['ChromeUdpSocket'] = ChromeUdpSocket;
	chrome.socketsExtended._classes['ChromeTcpServerSocket'] = ChromeTcpServerSocket;
})(window);<commit_msg>try-catches<commit_after>(function(window) {
	chrome.socketsExtended = {
		_classes: {},
		tcp: {},
		udp: {},
		tcpServer: {}
	};

	/*!
	 * EventEmitter v4.2.7 - git.io/ee
	 * Oliver Caldwell
	 * MIT license
	 * @preserve
	 */
	(function(){"use strict";function t(){}function r(t,n){for(var e=t.length;e--;)if(t[e].listener===n)return e;return-1}function n(e){return function(){return this[e].apply(this,arguments)}}var e=t.prototype,i=this,s=i.EventEmitter;e.getListeners=function(n){var r,e,t=this._getEvents();if(n instanceof RegExp){r={};for(e in t)t.hasOwnProperty(e)&&n.test(e)&&(r[e]=t[e])}else r=t[n]||(t[n]=[]);return r},e.flattenListeners=function(t){var e,n=[];for(e=0;e<t.length;e+=1)n.push(t[e].listener);return n},e.getListenersAsObject=function(n){var e,t=this.getListeners(n);return t instanceof Array&&(e={},e[n]=t),e||t},e.addListener=function(i,e){var t,n=this.getListenersAsObject(i),s="object"==typeof e;for(t in n)n.hasOwnProperty(t)&&-1===r(n[t],e)&&n[t].push(s?e:{listener:e,once:!1});return this},e.on=n("addListener"),e.addOnceListener=function(e,t){return this.addListener(e,{listener:t,once:!0})},e.once=n("addOnceListener"),e.defineEvent=function(e){return this.getListeners(e),this},e.defineEvents=function(t){for(var e=0;e<t.length;e+=1)this.defineEvent(t[e]);return this},e.removeListener=function(i,s){var n,e,t=this.getListenersAsObject(i);for(e in t)t.hasOwnProperty(e)&&(n=r(t[e],s),-1!==n&&t[e].splice(n,1));return this},e.off=n("removeListener"),e.addListeners=function(e,t){return this.manipulateListeners(!1,e,t)},e.removeListeners=function(e,t){return this.manipulateListeners(!0,e,t)},e.manipulateListeners=function(r,t,i){var e,n,s=r?this.removeListener:this.addListener,o=r?this.removeListeners:this.addListeners;if("object"!=typeof t||t instanceof RegExp)for(e=i.length;e--;)s.call(this,t,i[e]);else for(e in t)t.hasOwnProperty(e)&&(n=t[e])&&("function"==typeof n?s.call(this,e,n):o.call(this,e,n));return this},e.removeEvent=function(e){var t,r=typeof e,n=this._getEvents();if("string"===r)delete n[e];else if(e instanceof RegExp)for(t in n)n.hasOwnProperty(t)&&e.test(t)&&delete n[t];else delete this._events;return this},e.removeAllListeners=n("removeEvent"),e.emitEvent=function(r,o){var e,i,t,s,n=this.getListenersAsObject(r);for(t in n)if(n.hasOwnProperty(t))for(i=n[t].length;i--;)e=n[t][i],e.once===!0&&this.removeListener(r,e.listener),s=e.listener.apply(this,o||[]),s===this._getOnceReturnValue()&&this.removeListener(r,e.listener);return this},e.trigger=n("emitEvent"),e.emit=function(e){var t=Array.prototype.slice.call(arguments,1);return this.emitEvent(e,t)},e.setOnceReturnValue=function(e){return this._onceReturnValue=e,this},e._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},e._getEvents=function(){return this._events||(this._events={})},t.noConflict=function(){return i.EventEmitter=s,t},"function"==typeof define&&define.amd?define(function(){return t}):"object"==typeof module&&module.exports?module.exports=t:this.EventEmitter=t}).call(this);

	/**
	 * Object that holds reference to open sockets, used to track down and emit events when they are globally emitted
	 * @type {Object}
	 */
	var socketList = {
		tcp: {},
		udp: {},
		tcpServer: {}
	};

	/**
	 * Create a new ChromeTcpSocket
	 * @param  {Object}   properties SocketProperties sent to the chrome.sockets.tcp.create
	 * @param  {Function} cb         Callback function(ChromeTcpSocket)
	 */
	chrome.socketsExtended.tcp.open = function(properties, cb) {
		chrome.sockets.tcp.create(properties, function(createInfo) {
			var socket = new ChromeTcpSocket(createInfo.socketId);
			socket.on('closed', onSocketClosed);
			socketList.tcp[createInfo.socketId] = socket;
			cb(socket);
		});
	};

	/**
	 * Create a new ChromeTcpServerSocket
	 * @param  {Object}   properties SocketProperties sent to the chrome.sockets.tcpServer.create
	 * @param  {Function} cb         Callback function(ChromeTcpServerSocket)
	 */
	chrome.socketsExtended.tcpServer.open = function(properties, cb) {
		chrome.sockets.tcpServer.create(properties, function(createInfo) {
			var socket = new ChromeTcpServerSocket(createInfo.socketId);
			socket.on('closed', onSocketClosed);
			socketList.tcpServer[createInfo.socketId] = socket;
			cb(socket);
		});
	};

	/**
	 * Create a new ChromeUdpSocket
	 * @param  {Object}   properties SocketProperties sent to the chrome.sockets.udpServer.create
	 * @param  {Function} cb         Callback function(ChromeUdpServerSocket)
	 */
	chrome.socketsExtended.udp.open = function(properties, cb) {
		chrome.sockets.udp.create(properties, function(createInfo) {
			var socket = new ChromeUdpSocket(createInfo.socketId);
			socket.on('closed', onSocketClosed);
			socketList.udp[createInfo.socketId] = socket;
			cb(socket);
		})
	};

	/**
	 * Closes ALL tcp sockets! Even ones not created using this wrapper.
	 * @param  {Function} cb Callback function
	 */
	chrome.socketsExtended.tcp.closeAll = function(cb) {
		chrome.sockets.tcp.getSockets(function(sockets) {
			for (var n = 0; n < sockets.length; n++) {
				chrome.sockets.tcp.close(sockets[n].socketId);
			}
			cb && cb();
		});
	};

	/**
	 * Closes ALL udp sockets! Even ones not created using this wrapper.
	 * @param  {Function} cb Callback function
	 */
	chrome.socketsExtended.udp.closeAll = function(cb) {
		chrome.sockets.udp.getSockets(function(sockets) {
			for (var n = 0; n < sockets.length; n++) {
				chrome.sockets.udp.close(sockets[n].socketId);
			}
			cb && cb();
		});
	};

	/**
	 * Closes ALL tcpSerer sockets! Even ones not created using this wrapper.
	 * @param  {Function} cb Callback function
	 */
	chrome.socketsExtended.tcpServer.closeAll = function(cb) {
		chrome.sockets.tcpServer.getSockets(function(sockets) {
			for (var n = 0; n < sockets.length; n++) {
				chrome.sockets.tcpServer.close(sockets[n].socketId);
			}
			cb && cb();
		});
	};

	/**
	 * Bound to ALL SOCKETS THAT GET CREATED - this releases all event listeners and drops references to the socket object
	 */
	var onSocketClosed = function() {
		socketList[this.type][this.socketId] = null;
		delete socketList[this.type][this.socketId];
		this.removeAllListeners();
	};

	/**
	 * onReceive handler for TCP - finds the appropriate ChromeTcpSocket objects and emit receive with the info
	 * @param  {Object} receiveInfo Data emitted from the chrome.sockets.tcp.onReceive handler
	 */
	chrome.sockets.tcp.onReceive.addListener(function(receiveInfo) {
		var socketId = receiveInfo.socketId;
		if (socketList.tcp[socketId]) {
			socketList.tcp[socketId].emit('receive', receiveInfo);
		}
	});

	/**
	 * onReceiveError handler for TCP - finds the appropriate ChromeTcpSocket objects and emit receiveError with the info
	 * @param  {Object} receiveErrorInfo Data emitted from the chrome.sockets.tcp.onReceive handler
	 */
	chrome.sockets.tcp.onReceiveError.addListener(function(receiveErrorInfo) {
		if (receiveErrorInfo && receiveErrorInfo.socketId && socketList.tcp[receiveErrorInfo.socketId]) {
			socketList.tcp[receiveErrorInfo.socketId].emit('receiveError', receiveErrorInfo.resultCode);
		}
	});

	/**
	 * onReceive handler for UDP - finds the appropriate ChromeUdpSocket objects and emit receive with the info
	 * @param  {Object} receiveInfo Data emitted from the chrome.sockets.udp.onReceive handler
	 */
	chrome.sockets.udp.onReceive.addListener(function(receiveInfo) {
		if (socketList.udp[receiveInfo.socketId]) {
			socketList.udp[receiveInfo.socketId].emit('receive', receiveInfo);
		}
	});

	/**
	 * onReceiveError handler for UDP - finds the appropriate ChromeTcpSocket objects and emit receiveError with the info
	 * @param  {Object} receiveErrorInfo Data emitted from the chrome.sockets.udp.onReceive handler
	 */
	chrome.sockets.udp.onReceiveError.addListener(function(receiveErrorInfo) {
		if (receiveErrorInfo && receiveErrorInfo.socketId && socketList.udp[receiveErrorInfo.socketId]) {
			socketList.udp[receiveErrorInfo.socketId].emit('receiveError', receiveErrorInfo.resultCode);
		}
	});

	/**
	 * onAccept handler for TCP Server sockets - finds the appropriate ChromeTcpServerSocket and emit a new ChromeTcpSocket
	 * to represent the new socket connection to a client
	 * @param  {Object} acceptInfo Server socketId and clientSocketId
	 */
	chrome.sockets.tcpServer.onAccept.addListener(function(acceptInfo) {
		if (socketList.tcpServer[acceptInfo.socketId]) {
			var socket = new ChromeTcpSocket(acceptInfo.clientSocketId);
			socket.on('closed', onSocketClosed);
			socketList.tcp[acceptInfo.clientSocketId] = socket;
			socketList.tcpServer[acceptInfo.socketId].emit('accept', socket);
		}
	});

	/**
	 * onAcceptError handler for TCP Server sockets - finds the appropriate ChromeTcpServerSocket and emit the error info
	 * @param  {Object} acceptErrorInfo Data emitted from the chrome.sockets.tcpServer.onAccept handler
	 */
	chrome.sockets.tcpServer.onAcceptError.addListener(function(acceptErrorInfo) {
		if (acceptErrorInfo && acceptErrorInfo.socketId && socketList.udp[acceptErrorInfo.socketId]) {
			socketList.tcpServer[acceptErrorInfo.socketId].emit('receiveError', acceptErrorInfo.resultCode);
		}
	});

	// BASE CLASS
	var ChromeSocket = function(type) {
		EventEmitter.call(this);
		this._api = chrome.sockets[type];
		this.type = type;
	}
	ChromeSocket.prototype = Object.create(EventEmitter.prototype);

	ChromeSocket.prototype.update = function(properties, cb) {
		this._api.update(this.socketId, properties, cb);
	};

	ChromeSocket.prototype.setPaused = function(paused, cb) {
		this._api.setPaused(this.socketId, paused, cb);
	};

	ChromeSocket.prototype.close = function(cb) {
		var self = this;
		try {
			this._api.close(this.socketId, function() {
				self.emit('closed');
			});
		} catch(e) {
			self.emit('closed');
		}
	};

	ChromeSocket.prototype.getInfo = function(cb) {
		this._api.getInfo(this.socketId, cb);
	};

	// TCP
	var ChromeTcpSocket = function(socketId) {
		ChromeSocket.call(this, 'tcp');
		this.socketId = socketId;
	};
	ChromeTcpSocket.prototype = Object.create(ChromeSocket.prototype);

	ChromeTcpSocket.prototype.setKeepAlive = function(enable, delay, cb) {
		chrome.sockets.tcp.setKeepAlive(this.socketId, enable, delay, cb);
	};

	ChromeTcpSocket.prototype.setNoDelay = function(noDelay, cb) {
		chrome.sockets.tcp.setNoDelay(this.socketId, noDelay, cb);
	};

	ChromeTcpSocket.prototype.connect = function(host, port, cb) {
		chrome.sockets.tcp.connect(this.socketId, host, port, cb);
	};

	ChromeTcpSocket.prototype.disconnect = function(cb) {
		try {
			chrome.sockets.tcp.disconnect(this.socketId, cb);
		} catch(e) {

		}
	};

	ChromeTcpSocket.prototype.send = function(arrayBuffer, cb) {
		chrome.sockets.tcp.send(this.socketId, arrayBuffer, cb);
	};

	// UDP
	var ChromeUdpSocket = function(socketId) {
		ChromeSocket.call(this, 'udp');
		this.socketId = socketId;
	};
	ChromeUdpSocket.prototype = Object.create(ChromeSocket.prototype);

	ChromeUdpSocket.prototype.bind = function(address, port, cb) {
		chrome.sockets.udp.bind(this.socketId, address, port, cb);
	};

	ChromeUdpSocket.prototype.send = function(arrayBuffer, host, port, cb) {
		chrome.sockets.udp.send(this.socketId, arrayBuffer, host, port, cb);
	};

	ChromeUdpSocket.prototype.joinGroup = function(address, cb) {
		chrome.sockets.udp.joinGroup(this.socketId, address, cb);
	};

	ChromeUdpSocket.prototype.leaveGroup = function(address, cb) {
		chrome.sockets.udp.leaveGroup(this.socketId, address, cb);
	};

	ChromeUdpSocket.prototype.setMulticastTimeToLive = function(ttl, cb) {
		chrome.sockets.udp.setMulticastTimeToLive(this.socketId, ttl, cb);
	};

	ChromeUdpSocket.prototype.setMulticastLoopbackMode = function(enabled, cb) {
		chrome.sockets.udp.setMulticastLoopbackMode(this.socketId, enabled, cb);
	};

	ChromeUdpSocket.prototype.getJoinedGroups = function(cb) {
		chrome.sockets.udp.getJoinedGroups(this.socketId, cb);
	};

	// TCP SERVER
	var ChromeTcpServerSocket = function(socketId) {
		ChromeSocket.call(this, 'tcpServer');
		this.socketId = socketId;
	};
	ChromeTcpServerSocket.prototype = Object.create(ChromeSocket.prototype);

	ChromeTcpServerSocket.prototype.listen = function(host, port, cb) {
		chrome.sockets.tcpServer.listen(this.socketId, host, port, cb);
	};

	ChromeTcpServerSocket.prototype.disconnect = function(cb) {
		try {
			chrome.sockets.tcpServer.disconnect(this.socketId, cb);
		} catch(e) {

		}
	};

	chrome.socketsExtended._classes['ChromeTcpSocket'] = ChromeTcpSocket;
	chrome.socketsExtended._classes['ChromeUdpSocket'] = ChromeUdpSocket;
	chrome.socketsExtended._classes['ChromeTcpServerSocket'] = ChromeTcpServerSocket;
})(window);<|endoftext|>


<commit_before>// ==UserScript==
// @name         RLCS
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Chat-like functionality for Reddit Live
// @author       FatherDerp, Stjerneklar
// @include      https://www.reddit.com/live/*
// @exclude      https://www.reddit.com/live/
// @exclude      https://www.reddit.com/live
// @exclude      https://www.reddit.com/live/*/edit*
// @exclude      https://www.reddit.com/live/*/contributors*
// @require      http://code.jquery.com/jquery-latest.js
// @grant   GM_addStyle
// ==/UserScript==
$(document).ready(function() {
    $("body").append('

');
    $('.liveupdate-listing').appendTo('#rlc-chat');
    $('#new-update-form').appendTo('#rlc-messagebox');
    $('#liveupdate-header').prependTo('#rlc-sidebar');
    $('#liveupdate-options').prependTo('#rlc-sidebar');
    $('.main-content aside.sidebar').appendTo('#rlc-sidebar');
    $(document).keydown(function(e){
      if (e.keyCode == 13) {
          $(".save-button .btn").click();
      }
  });
    $('body').on('contextmenu', ".liveupdate .author", function (event) {
        event.preventDefault();
        var username = String($(this).text()).trim();
        var source = String($(".usertext-edit.md-container textarea").val());
        // Focus textarea and set the value of textarea
        $(".usertext-edit.md-container textarea").focus().val("").val(source + " " + username + " ");
    });
});
/*add css styles, every line must end with \  */
      GM_addStyle(" \
/* Custom elements */\
#rlc-main { \
    width: 70%; \
    height: 100%; \
    position: fixed; \
    top: 63px; \
    left:0; \
} \
#rlc-sidebar { \
    width: 30%; \
    height: 100%; \
    position: fixed; \
    top: 63px; \
    right:0; \
} \
/*general modifications*/\
#liveupdate-options {\
    position: absolute;\
    top:116px;\
    left: 5px;\
} \
.res-nightmode #liveupdate-options {color:white;}\
/* hard removal */\
.footer-parent, \
#rlc-main .liveupdate-listing .separator,\
#rlc-main .liveupdate-listing li.liveupdate ul.buttonrow,\
#rlc-main .liveupdate-listing li.liveupdate time:before,\
.help-toggle, \
.reddiquette,\
body > .content { display: none!important; }\
/*chat window*/\
#rlc-main .liveupdate-listing { \
    max-width: 100%; \
    overflow-y: scroll;  \
    height: calc(100vh - 138px); \
    padding:5px;\
    box-sizing:border-box;\
    display: flex; \
    flex-direction: column-reverse; \
} \
#rlc-main .liveupdate-listing .liveupdate .body {\
    max-width: none!important;\
    margin-bottom: 0!important;\
    padding:2px!important;\
}  \
#rlc-main .liveupdate-listing .liveupdate {  \
    border-top:1px solid grey;\
    padding-top:2px; \
    height: auto!important; \
    overflow:visible!important;\
} \
#rlc-main .liveupdate-listing a.author {\
    display: block;\
    width: 12%;\
    float: left;\
    margin: 0;\
    text-align: right;\
    } \
#rlc-main .liveupdate-listing .liveupdate time {\
    padding: 0;\
    width: 12%;\
    float:left;\
    margin: 0;\
    text-align: right;\
} \
#rlc-main .liveupdate-listing .liveupdate .body div.md {\
    width: 86%;\
    display: block;\
    float: right;\
    margin-bottom:0;\
    max-width: none;\
} \
/*message input and send button*/\
#new-update-form .usertext {\
    max-width: 100%;\
    float: left;\
    width: 100%;\
} \
.usertext-edit .md {min-width: 100%!important;} \
div#new-update-form textarea { \
    height:45px;\
    overflow:hidden;  \
} \
div#new-update-form { \
    width: 100%; \
    margin: 0; \
} \
.usertext-edit.md-container { \
    max-width: 100%; \
    margin: 0; \
} \
.usertext-edit.md-container {  position: relative;}  \
#new-update-form .bottom-area { \
    position: absolute; \
    top: 4px; \
    right: 15px; \
    left: 15px; \
    text-align: center; \
    letter-spacing: 1px; \
} \
#new-update-form .save-button .btn { \
    width: 100%; \
    text-transform: capitalize; \
} \
.usertext-edit.md-container { \
    margin-top: 3px; \
} \
.usertext-edit.md-container textarea { \
    padding:2px; \
} \
/*sidebar*/\
aside.sidebar.side.md-container { \
    max-width:100%;\
    width:98%;\
} \
#liveupdate-header {\
    width: 100%;\
    margin:0!important;\
    padding:0!important;\
    text-align:center;\
    max-width: none;\
} \
");
<commit_msg>force opacity on sidebar for better visibility in non night mode<commit_after>// ==UserScript==
// @name         RLCS
// @namespace    http://tampermonkey.net/
// @version      1.01
// @description  Chat-like functionality for Reddit Live
// @author       FatherDerp, Stjerneklar
// @include      https://www.reddit.com/live/*
// @exclude      https://www.reddit.com/live/
// @exclude      https://www.reddit.com/live
// @exclude      https://www.reddit.com/live/*/edit*
// @exclude      https://www.reddit.com/live/*/contributors*
// @require      http://code.jquery.com/jquery-latest.js
// @grant   GM_addStyle
// ==/UserScript==
$(document).ready(function() {
    $("body").append('

');
    $('.liveupdate-listing').appendTo('#rlc-chat');
    $('#new-update-form').appendTo('#rlc-messagebox');
    $('#liveupdate-header').prependTo('#rlc-sidebar');
    $('#liveupdate-options').prependTo('#rlc-sidebar');
    $('.main-content aside.sidebar').appendTo('#rlc-sidebar');
    $("#nightSwitchToggle").click();
    $(document).keydown(function(e){
      if (e.keyCode == 13) {
          $(".save-button .btn").click();
      }
  });
    $('body').on('contextmenu', ".liveupdate .author", function (event) {
        event.preventDefault();
        var username = String($(this).text()).trim();
        var source = String($(".usertext-edit.md-container textarea").val());
        // Focus textarea and set the value of textarea
        $(".usertext-edit.md-container textarea").focus().val("").val(source + " " + username + " ");
    });
});
/*add css styles, every line must end with \  */
      GM_addStyle(" \
/* Custom elements */\
#rlc-main { \
    width: 70%; \
    height: 100%; \
    position: fixed; \
    top: 63px; \
    left:0; \
} \
#rlc-sidebar { \
    width: 30%; \
    height: 100%; \
    position: fixed; \
    top: 63px; \
    right:0; \
} \
#rlc-sidebar *, #rlc-main * {opacity:1!important}; \
/*general modifications*/\
#liveupdate-options {\
    position: absolute;\
    top:116px;\
    left: 5px;\
} \
.res-nightmode #liveupdate-options {color:white;}\
/* hard removal */\
.footer-parent, \
#rlc-main .liveupdate-listing .separator,\
#rlc-main .liveupdate-listing li.liveupdate ul.buttonrow,\
#rlc-main .liveupdate-listing li.liveupdate time:before,\
.help-toggle, \
.reddiquette,\
body > .content { display: none!important; }\
/*chat window*/\
#rlc-main .liveupdate-listing { \
    max-width: 100%; \
    overflow-y: scroll;  \
    height: calc(100vh - 138px); \
    padding:5px;\
    box-sizing:border-box;\
    display: flex; \
    flex-direction: column-reverse; \
} \
#rlc-main .liveupdate-listing .liveupdate .body {\
    max-width: none!important;\
    margin-bottom: 0!important;\
    padding:2px!important;\
}  \
#rlc-main .liveupdate-listing .liveupdate {  \
    border-top:1px solid grey;\
    padding-top:2px; \
    height: auto!important; \
    overflow:visible!important;\
} \
#rlc-main .liveupdate-listing a.author {\
    display: block;\
    width: 12%;\
    float: left;\
    margin: 0;\
    text-align: right;\
    } \
#rlc-main .liveupdate-listing .liveupdate time {\
    padding: 0;\
    width: 12%;\
    float:left;\
    margin: 0;\
    text-align: right;\
} \
#rlc-main .liveupdate-listing .liveupdate .body div.md {\
    width: 86%;\
    display: block;\
    float: right;\
    margin-bottom:0;\
    max-width: none;\
} \
/*message input and send button*/\
#new-update-form .usertext {\
    max-width: 100%;\
    float: left;\
    width: 100%;\
} \
.usertext-edit .md {min-width: 100%!important;} \
div#new-update-form textarea { \
    height:45px;\
    overflow:hidden;  \
} \
div#new-update-form { \
    width: 100%; \
    margin: 0; \
} \
.usertext-edit.md-container { \
    max-width: 100%; \
    margin: 0; \
} \
.usertext-edit.md-container {  position: relative;}  \
#new-update-form .bottom-area { \
    position: absolute; \
    top: 4px; \
    right: 15px; \
    left: 15px; \
    text-align: center; \
    letter-spacing: 1px; \
} \
#new-update-form .save-button .btn { \
    width: 100%; \
    text-transform: capitalize; \
} \
.usertext-edit.md-container { \
    margin-top: 3px; \
} \
.usertext-edit.md-container textarea { \
    padding:2px; \
} \
/*sidebar*/\
aside.sidebar.side.md-container { \
    max-width:100%;\
    width:98%;\
} \
#liveupdate-header {\
    width: 100%;\
    margin:0!important;\
    padding:0!important;\
    text-align:center;\
    max-width: none;\
} \
");
<|endoftext|>


<commit_before>'use strict';

var NET   = require('net');
var PORTS = {};

function CreateServer(
  port,
  callback
){

  if(
    (typeof port === 'number')
  ){

    port = parseFloat(port);

    if(
      (PORTS[port.toString()])
    ){

      process.nextTick(CreateServer,port,callback);

      return;
    }

    PORTS[port.toString()] = true;

    NET.createServer()
    .on('error',function CreateServerError(error){

      this.close(function CreateServerErrorClose(){

        delete PORTS[port.toString()];

        if(error.code === 'EADDRINUSE'){

          callback(null,false,port);
        }
        else{

          callback(true,error,port);
        }
      });
    })
    .listen(port,function CreateServerListening(){

      this.close(function CreateServerListeningClose(){

        delete PORTS[port.toString()];

        callback(null,true,port);
      });
    });
  }
  else{

    callback(null,false);
  }
}

module.exports = CreateServer;

<commit_msg>Callback only to valid functions.<commit_after>'use strict';

var NET   = require('net');
var PORTS = {};

function CreateServer(
  port,
  callback
){

  if(
    (typeof port === 'number')
  ){

    port = parseFloat(port);

    if(
      (PORTS[port.toString()])
    ){

      process.nextTick(CreateServer,port,callback);

      return;
    }

    PORTS[port.toString()] = true;

    NET.createServer()
    .on('error',function CreateServerError(error){

      this.close(function CreateServerErrorClose(){

        delete PORTS[port.toString()];

        if(error.code === 'EADDRINUSE'){

          callback(null,false,port);
        }
        else{

          callback(true,error,port);
        }
      });
    })
    .listen(port,function CreateServerListening(){

      this.close(function CreateServerListeningClose(){

        delete PORTS[port.toString()];

        callback(null,true,port);
      });
    });
  }
  else if(typeof callback === 'function') callback(null,false);
}

module.exports = CreateServer;

<|endoftext|>


<commit_before>$(document).ready(function() {
    $(function(){
    var Rooms = Backbone.Collection.extend({
        model: Room,
        url: 'rooms',
        parse: function(response) {
            _.each(response, function(room) {
                room.id = room._id;
            })
            return response;
        }
    });

    var Room = Backbone.Model.extend({
        defaults: {
            name: null
        }
    });

    var Event = Backbone.Model.extend({
        defaults: {
            dtstart: null,
            start: null,
            dtend: null,
            end: null,
            title: null
        }
    });

    var Events = Backbone.Collection.extend({
        model: Event,
        url: '/events',
        parse: function(response) {
            _.each(response, function(event) {
                event.id = event._id;
                event.start = event.dtstart;
                event.end = event.dtend;
            })
            return response;
        }
    });

    var EventsView = Backbone.View.extend({
        initialize: function(){
            _.bindAll(this);

            this.collection.bind('reset', this.addAll);
            this.collection.bind('add', this.addOne);
            this.collection.bind('change', this.change);
            this.collection.bind('destroy', this.destroy);

            this.eventView = new EventView();
        },
        render: function() {
            this.el.fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,basicWeek,basicDay'
                },
                selectable: true,
                selectHelper: true,
                editable: true,
                ignoreTimezone: false,
                select: this.select,
                eventClick: this.eventClick,
                eventDrop: this.eventDropOrResize,
                eventResize: this.eventDropOrResize
            });
        },
        addAll: function() {
            this.el.fullCalendar('addEventSource', this.collection.toJSON());
        },
        addOne: function(event) {
            this.el.fullCalendar('renderEvent', event.toJSON());
        },
        select: function(startDate, endDate) {
            this.eventView.collection = this.collection;
            this.eventView.model = new Event({start: startDate, end: endDate});
            this.eventView.render();
        },
        eventClick: function(fcEvent) {
            this.eventView.model = this.collection.get(fcEvent.id);
            this.eventView.render();
        },
        change: function(event) {
            // Look up the underlying event in the calendar and update its details from the model
            var fcEvent = this.el.fullCalendar('clientEvents', event.get('id'))[0];
            fcEvent.title = event.get('title');
            fcEvent.color = event.get('color');
            this.el.fullCalendar('updateEvent', fcEvent);
        },
        eventDropOrResize: function(fcEvent) {
            // Lookup the model that has the ID of the event and update its attributes
            this.collection.get(fcEvent.id).save({start: fcEvent.start, end: fcEvent.end});
        },
        destroy: function(event) {
            this.el.fullCalendar('removeEvents', event.id);
        }
    });

    var EventView = Backbone.View.extend({
        el: $('#eventDialog'),
        initialize: function() {
            _.bindAll(this);
        },
        render: function() {
            var buttons = {'Ok': this.save};
            if (!this.model.isNew()) {
                _.extend(buttons, {'Delete': this.destroy});
            }
            _.extend(buttons, {'Cancel': this.close});

            this.el.dialog({
                modal: true,
                title: (this.model.isNew() ? 'New' : 'Edit') + ' Event',
                buttons: buttons,
                open: this.open
            });

            return this;
        },
        open: function() {
            this.$('#title').val(this.model.get('title'));
            var room = new RoomsSelectView({el: this.$('#rooms')});
            room.render({selected: this.model.get('room')});
        },
        save: function() {
            this.model.set({
                'title': this.$('#title').val(),
                'room': this.$('#room :selected').val()});

            if (this.model.isNew()) {
                this.collection.create(this.model, {success: this.close});
            } else {
                this.model.save({}, {success: this.close});
            }
        },
        close: function() {
            this.el.dialog('close');
        },
        destroy: function() {
            this.model.destroy({success: this.close});
        }
    });

    var RoomsSelectView = Backbone.View.extend({
        render: function(options) {
            var select = $('<select name="rooms"/>');
            rooms.each(function(room) {
                var selected = options.selected == room.id;
                select.append('<option value="'+room.id +'"'+ (options.selected  ? ' selected' : '') +'>'+room.get('name')+'</option>');
            });
            this.el.html(select);
        }
    });

    var events = new Events();
    var rooms = new Rooms();
    new EventsView({el: $("#main"), collection: events}).render();
    events.fetch();
    rooms.fetch();
});
});
<commit_msg>handle location property as the room id<commit_after>$(document).ready(function() {
    $(function(){
    var Rooms = Backbone.Collection.extend({
        model: Room,
        url: 'rooms',
        parse: function(response) {
            _.each(response, function(room) {
                room.id = room._id;
            })
            return response;
        }
    });

    var Room = Backbone.Model.extend({
        defaults: {
            name: null
        }
    });

    var Event = Backbone.Model.extend({
        defaults: {
            dtstart: null,
            start: null,
            dtend: null,
            end: null,
            title: null,
            location: null
        }
    });

    var Events = Backbone.Collection.extend({
        model: Event,
        url: '/events',
        parse: function(response) {
            _.each(response, function(event) {
                event.id = event._id;
                event.start = event.dtstart;
                event.end = event.dtend;
            })
            return response;
        }
    });

    var EventsView = Backbone.View.extend({
        initialize: function(){
            _.bindAll(this);

            this.collection.bind('reset', this.addAll);
            this.collection.bind('add', this.addOne);
            this.collection.bind('change', this.change);
            this.collection.bind('destroy', this.destroy);

            this.eventView = new EventView();
        },
        render: function() {
            this.el.fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,basicWeek,basicDay'
                },
                selectable: true,
                selectHelper: true,
                editable: true,
                ignoreTimezone: false,
                select: this.select,
                eventClick: this.eventClick,
                eventDrop: this.eventDropOrResize,
                eventResize: this.eventDropOrResize
            });
        },
        addAll: function() {
            this.el.fullCalendar('addEventSource', this.collection.toJSON());
        },
        addOne: function(event) {
            this.el.fullCalendar('renderEvent', event.toJSON());
        },
        select: function(startDate, endDate) {
            this.eventView.collection = this.collection;
            this.eventView.model = new Event({start: startDate, end: endDate});
            this.eventView.render();
        },
        eventClick: function(fcEvent) {
            this.eventView.model = this.collection.get(fcEvent.id);
            this.eventView.render();
        },
        change: function(event) {
            // Look up the underlying event in the calendar and update its details from the model
            var fcEvent = this.el.fullCalendar('clientEvents', event.get('id'))[0];
            fcEvent.title = event.get('title');
            fcEvent.color = event.get('color');
            this.el.fullCalendar('updateEvent', fcEvent);
        },
        eventDropOrResize: function(fcEvent) {
            // Lookup the model that has the ID of the event and update its attributes
            this.collection.get(fcEvent.id).save({start: fcEvent.start, end: fcEvent.end});
        },
        destroy: function(event) {
            this.el.fullCalendar('removeEvents', event.id);
        }
    });

    var EventView = Backbone.View.extend({
        el: $('#eventDialog'),
        initialize: function() {
            _.bindAll(this);
        },
        render: function() {
            var buttons = {'Ok': this.save};
            if (!this.model.isNew()) {
                _.extend(buttons, {'Delete': this.destroy});
            }
            _.extend(buttons, {'Cancel': this.close});

            this.el.dialog({
                modal: true,
                title: (this.model.isNew() ? 'New' : 'Edit') + ' Event',
                buttons: buttons,
                open: this.open
            });

            return this;
        },
        open: function() {
            this.$('#title').val(this.model.get('title'));
            var room = new RoomsSelectView({el: this.$('#rooms')});
            room.render({selected: this.model.get('location')});
        },
        save: function() {
            this.model.set({
                'title': this.$('#title').val(),
                'room': this.$('#room :selected').val()});

            if (this.model.isNew()) {
                this.collection.create(this.model, {success: this.close});
            } else {
                this.model.save({}, {success: this.close});
            }
        },
        close: function() {
            this.el.dialog('close');
        },
        destroy: function() {
            this.model.destroy({success: this.close});
        }
    });

    var RoomsSelectView = Backbone.View.extend({
        render: function(options) {
            var select = $('<select name="rooms"/>');
            rooms.each(function(room) {
                var selected = options.selected == room.id;
                console.log(options.selected, room.id, selected)
                select.append('<option value="'+room.id +'"'+ (selected  ? ' selected' : '') +'>'+room.get('name')+'</option>');
            });
            this.el.html(select);
        }
    });

    var events = new Events();
    var rooms = new Rooms();
    new EventsView({el: $("#main"), collection: events}).render();
    events.fetch();
    rooms.fetch();
});
});
<|endoftext|>


<commit_before>/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
           ______     ______     ______   __  __     __     ______
          /\  == \   /\  __ \   /\__  _\ /\ \/ /    /\ \   /\__  _\
          \ \  __<   \ \ \/\ \  \/_/\ \/ \ \  _"-.  \ \ \  \/_/\ \/
           \ \_____\  \ \_____\    \ \_\  \ \_\ \_\  \ \_\    \ \_\
            \/_____/   \/_____/     \/_/   \/_/\/_/   \/_/     \/_/

This is a sample Slack bot built with Botkit.

This bot demonstrates many of the core features of Botkit:

* Connect to Slack using the real time API
* Receive messages based on "spoken" patterns
* Reply to messages
* Use the conversation system to ask questions
* Use the built in storage system to store and retrieve information
  for a user.

# RUN THE BOT:

  Get a Bot token from Slack:

    -> http://my.slack.com/services/new/bot

  Run your bot from the command line:

    token=<MY TOKEN> node slack_bot.js

# USE THE BOT:

  Find your bot inside Slack to send it a direct message.

  Say: "Hello"

  The bot will reply "Hello!"

  Say: "who are you?"

  The bot will tell you its name, where it is running, and for how long.

  Say: "Call me <nickname>"

  Tell the bot your nickname. Now you are friends.

  Say: "who am I?"

  The bot will tell you your nickname, if it knows one for you.

  Say: "shutdown"

  The bot will ask if you are sure, and then shut itself down.

  Make sure to invite your bot into other channels using /invite @<my bot>!

# EXTEND THE BOT:

  Botkit has many features for building cool and useful bots!

  Read all about it here:

    -> http://howdy.ai/botkit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

if (!process.env.SLACK_TOKEN) {
    console.log('Error: Specify SLACK_TOKEN in environment');
    process.exit(1);
}

var Botkit = require('./lib/Botkit.js');
var os = require('os');

var controller = Botkit.slackbot({
    debug: false
});

var bot = controller.spawn({
    token: process.env.SLACK_TOKEN
}).startRTM();

var HarQuotes = [
        "Attack each day with an enthusiasm unknown to mankind.",
        "Realistic expectations for life are that we are going to be better today than we were yesterday, be better tomorrow than we were today.",
        "I don't take vacations. I don't get sick. I don't observe major holidays. I'm a jack hammer.",
        "I love being part of something that is working toward a greater goal, and there's no more satisfaction in life than achieving those goals as a team and being a part of that team.",
        "It can be a great temptation to rest on the field and let the opponent have a play without making him pay for every inch. I must hold his pain where it is. Mine does not matter. ... The punishment I inflict, his fatigue, and that he is up against something that he does not comprehend is everything.",
        "There are no turnarounds at Michigan. This is greatness. Long tradition of it.",
        "I was and still am happier than a pig in slop.",
        "That is a plan for success. So the key is simple: just work.",
        "Winning as a team is better than anything. It's great to share success.",
        "I have always believed that you win as part of a team effort. I've learned that if everybody does a little bit, it adds up to a lot.",
        "In the northern snowlands, down to the tropics' sunny scenes, he's catching the football. Where they throw a football, he'll be catching it.",
        "What will happen will happen, what won't happen won't happen.",
        "Fans have a constitutional right to expect success and have high expectations...",
        "I am now in control of all things.",
        "Anything is always a possibility. Wouldn't talk about what we would have done or what we would do. Everything is a possibility.",
        "I love people, I really do. I'm a people person. I think that's a strength of mine. I love being around people, especially in a team setting.",
        "People often think that there's a general who makes all the difference, but I would reject that. It's a team effort. It's the power of the wedge.",
        "I have never asked to be the highest-paid coach in football. I have never asked to be paid like a Super Bowl-winning coach. I have never asked for more power.",
        "You're kind of numb after 50 shots to the head.",
        "All human beings have a great agency for being part of a team.",
        "Hustle. Hustling at all times. Better today than yesterday, better tomorrow than today.",
        "I drank a lot of milk, Andrea. A lot of milk. Whole milk, though. Not the candy-ass two percent or skim milk.",
        "It's more than personal. I can't screw it up. I have to do good.",
        "I shook his hand too hard. I mean I really went in and it was strong and kind of a slap-grab-handshake. So, that was on me. Personally I can get better at the post-game handshake and we'll attempt to do that. I don't think there's any reason for an apology.",
        "Yeah, it's like coming out of the mother's womb. You're in a nice, warm, cozy environment, and you're reborn. And now you are out into the chaos, lights and everybody looking at you. And it’s wonderful.",
        "I’m not a food critic, merely a blunt instrument who only knows football.",
        "The football gods have provided us heat and sun to shape the body and carve the mind.",
        "Our guys were playing checkers and the little game with the triangle where you try to get it down to one golf tee. They had fun doing that. It was good. I got great pancakes and bacon. The best.",
        "I know we'll be best friends within a year's time.",
        "My default is 'yes' when asked to do things.",
        "Do not be deceived. You will reap what you sow.",
        "I own other pants.",
        "We have some great Supreme Court members, tremendous Supreme Court currently that we have, but I'd love to see Judge Judy on the Supreme Court. I just love everything about her.",
        "Question of the day: Does anyone find whining to be attractive? Just curious.",
        "Good to see Director Smith being relevant again after the tattoo fiasco. Welcome back!",
        "Have a Great day! A Great week! A Great month! and a Great year! and Go Blue!",
        "Well, you open it up - a brand new can of olives - and turn it over, and no olives come out.",
        "A birdwatcher knows the gist of a bird by just watching it.",
        "When you lie in Judge Judy's court room, it's over.",
        "Guilty as charged for fueling the hype...Well deserved.",
        "Honey badger don't care about no lights!",
        "If anybody knows how to reach them, I'd like to reunite my all-time favorite band Hootie and The Blowfish.",
        "I have a memory like an elephant...I never forget.",
        "It’s going to get real-real, and it’s going to get real-real, real fast for these young guys.",
        "I reduce a lot of drag by not having to choose what your going to wear everyday.",
        "So I anticipate the we’ll have some precipitation, some weather, and that will be a great thing for us.",
        "Trust is big to me. I'm a big fan of the Judge Judy show. When you lie in Judge Judy's courtroom, it's over. Your credibility is completely lost and you stand no chance of winning that case. I learned that from her. It's very powerful. And true. If somebody lies to you, how can you trust anything they say after that?",
        "A shout out from @JudgeJudy would make anyone's day, thank you! The BEST! & Excellence are easy to spot, Judge Judy is it's highest level.",
        "If worms had machine guns, then birds wouldn't be scared of them, you know?",
        "I've been trying to advise them to get two costumes, to be go-getters. Hit the neighborhood in one costume. Better to jog or run from house to house, then you can get more candy than anybody else. Then come home and make a quick change into a second costume and hit those same houses again.",
        "Zoo lions get tired of zebra after a while and want filet mignon. Not jungle lions.",
        "I take a vitamin every day; it's called a steak.",
        "That's kind of the way the pickle squirted this year.",
        "There’s a battle rhythm, a body clock that tells you it’s time for football. For me, it’s always I know when I get my first football dream. That’s my body clock telling me it’s time to compete.",
    ]

var JudyQuotes = [
           "A shout out from @JudgeJudy would make anyone's day, thank you! The BEST! & Excellence are easy to spot, Judge Judy is it's highest level.",
           "Big Congrats to Judge Judy on signing her contract extension thru 2020 from a Devout Fan!",
           "Trust is big to me. I'm a big fan of the Judge Judy show. When you lie in Judge Judy's courtroom, it's over. Your credibility is completely lost and you stand no chance of winning that case. I learned that from her. It's very powerful. And true. If somebody lies to you, how can you trust anything they say after that?",
           "When you lie in Judge Judy's court room, it's over.",
           "We have some great Supreme Court members, tremendous Supreme Court currently that we have, but I'd love to see Judge Judy on the Supreme Court. I just love everything about her.",
           ]

controller.hears([''], 'direct_message,direct_mention,mention', function(bot, message) {

    var chooseQuote  = HarQuotes[Math.random() * HarQuotes.length | 0]

    bot.reply(message, chooseQuote)

    });

controller.hears(['Harbaugh', 'Go Blue', 'Hail', 'Good morning', 'Michigan', 'khaki'], 'ambient', function(bot, message) {

    var chooseQuote  = HarQuotes[Math.random() * HarQuotes.length | 0]

    bot.reply(message, chooseQuote)

    });

controller.hears(['Harbaugh', 'Go Blue', 'Hail', 'Good morning', 'Michigan', 'khaki'], 'ambient', function(bot, message) {

    var chooseQuote  = JudyQuotes[Math.random() * JudyQuotes.length | 0]

    bot.reply(message, chooseQuote)

    });

controller.hears(['shutdown'], 'direct_message,direct_mention,mention', function(bot, message) {

    bot.startConversation(message, function(err, convo) {

        convo.ask('Are you sure you want me to shutdown?', [
            {
                pattern: bot.utterances.yes,
                callback: function(response, convo) {
                    convo.say('Bye!');
                    convo.next();
                    setTimeout(function() {
                        process.exit();
                    }, 3000);
                }
            },
        {
            pattern: bot.utterances.no,
            default: true,
            callback: function(response, convo) {
                convo.say('*Phew!*');
                convo.next();
            }
        }
        ]);
    });
});

controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'],
    'direct_message,direct_mention,mention', function(bot, message) {

        var hostname = os.hostname();
        var uptime = formatUptime(process.uptime());

        bot.reply(message,
            ':robot_face: I am a bot named <@' + bot.identity.name +
             '>. I have been running for ' + uptime + ' on ' + hostname + '.');

    });

function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}
<commit_msg>I'm an idiot<commit_after>/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
           ______     ______     ______   __  __     __     ______
          /\  == \   /\  __ \   /\__  _\ /\ \/ /    /\ \   /\__  _\
          \ \  __<   \ \ \/\ \  \/_/\ \/ \ \  _"-.  \ \ \  \/_/\ \/
           \ \_____\  \ \_____\    \ \_\  \ \_\ \_\  \ \_\    \ \_\
            \/_____/   \/_____/     \/_/   \/_/\/_/   \/_/     \/_/

This is a sample Slack bot built with Botkit.

This bot demonstrates many of the core features of Botkit:

* Connect to Slack using the real time API
* Receive messages based on "spoken" patterns
* Reply to messages
* Use the conversation system to ask questions
* Use the built in storage system to store and retrieve information
  for a user.

# RUN THE BOT:

  Get a Bot token from Slack:

    -> http://my.slack.com/services/new/bot

  Run your bot from the command line:

    token=<MY TOKEN> node slack_bot.js

# USE THE BOT:

  Find your bot inside Slack to send it a direct message.

  Say: "Hello"

  The bot will reply "Hello!"

  Say: "who are you?"

  The bot will tell you its name, where it is running, and for how long.

  Say: "Call me <nickname>"

  Tell the bot your nickname. Now you are friends.

  Say: "who am I?"

  The bot will tell you your nickname, if it knows one for you.

  Say: "shutdown"

  The bot will ask if you are sure, and then shut itself down.

  Make sure to invite your bot into other channels using /invite @<my bot>!

# EXTEND THE BOT:

  Botkit has many features for building cool and useful bots!

  Read all about it here:

    -> http://howdy.ai/botkit

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

if (!process.env.SLACK_TOKEN) {
    console.log('Error: Specify SLACK_TOKEN in environment');
    process.exit(1);
}

var Botkit = require('./lib/Botkit.js');
var os = require('os');

var controller = Botkit.slackbot({
    debug: false
});

var bot = controller.spawn({
    token: process.env.SLACK_TOKEN
}).startRTM();

var HarQuotes = [
        "Attack each day with an enthusiasm unknown to mankind.",
        "Realistic expectations for life are that we are going to be better today than we were yesterday, be better tomorrow than we were today.",
        "I don't take vacations. I don't get sick. I don't observe major holidays. I'm a jack hammer.",
        "I love being part of something that is working toward a greater goal, and there's no more satisfaction in life than achieving those goals as a team and being a part of that team.",
        "It can be a great temptation to rest on the field and let the opponent have a play without making him pay for every inch. I must hold his pain where it is. Mine does not matter. ... The punishment I inflict, his fatigue, and that he is up against something that he does not comprehend is everything.",
        "There are no turnarounds at Michigan. This is greatness. Long tradition of it.",
        "I was and still am happier than a pig in slop.",
        "That is a plan for success. So the key is simple: just work.",
        "Winning as a team is better than anything. It's great to share success.",
        "I have always believed that you win as part of a team effort. I've learned that if everybody does a little bit, it adds up to a lot.",
        "In the northern snowlands, down to the tropics' sunny scenes, he's catching the football. Where they throw a football, he'll be catching it.",
        "What will happen will happen, what won't happen won't happen.",
        "Fans have a constitutional right to expect success and have high expectations...",
        "I am now in control of all things.",
        "Anything is always a possibility. Wouldn't talk about what we would have done or what we would do. Everything is a possibility.",
        "I love people, I really do. I'm a people person. I think that's a strength of mine. I love being around people, especially in a team setting.",
        "People often think that there's a general who makes all the difference, but I would reject that. It's a team effort. It's the power of the wedge.",
        "I have never asked to be the highest-paid coach in football. I have never asked to be paid like a Super Bowl-winning coach. I have never asked for more power.",
        "You're kind of numb after 50 shots to the head.",
        "All human beings have a great agency for being part of a team.",
        "Hustle. Hustling at all times. Better today than yesterday, better tomorrow than today.",
        "I drank a lot of milk, Andrea. A lot of milk. Whole milk, though. Not the candy-ass two percent or skim milk.",
        "It's more than personal. I can't screw it up. I have to do good.",
        "I shook his hand too hard. I mean I really went in and it was strong and kind of a slap-grab-handshake. So, that was on me. Personally I can get better at the post-game handshake and we'll attempt to do that. I don't think there's any reason for an apology.",
        "Yeah, it's like coming out of the mother's womb. You're in a nice, warm, cozy environment, and you're reborn. And now you are out into the chaos, lights and everybody looking at you. And it’s wonderful.",
        "I’m not a food critic, merely a blunt instrument who only knows football.",
        "The football gods have provided us heat and sun to shape the body and carve the mind.",
        "Our guys were playing checkers and the little game with the triangle where you try to get it down to one golf tee. They had fun doing that. It was good. I got great pancakes and bacon. The best.",
        "I know we'll be best friends within a year's time.",
        "My default is 'yes' when asked to do things.",
        "Do not be deceived. You will reap what you sow.",
        "I own other pants.",
        "We have some great Supreme Court members, tremendous Supreme Court currently that we have, but I'd love to see Judge Judy on the Supreme Court. I just love everything about her.",
        "Question of the day: Does anyone find whining to be attractive? Just curious.",
        "Good to see Director Smith being relevant again after the tattoo fiasco. Welcome back!",
        "Have a Great day! A Great week! A Great month! and a Great year! and Go Blue!",
        "Well, you open it up - a brand new can of olives - and turn it over, and no olives come out.",
        "A birdwatcher knows the gist of a bird by just watching it.",
        "When you lie in Judge Judy's court room, it's over.",
        "Guilty as charged for fueling the hype...Well deserved.",
        "Honey badger don't care about no lights!",
        "If anybody knows how to reach them, I'd like to reunite my all-time favorite band Hootie and The Blowfish.",
        "I have a memory like an elephant...I never forget.",
        "It’s going to get real-real, and it’s going to get real-real, real fast for these young guys.",
        "I reduce a lot of drag by not having to choose what your going to wear everyday.",
        "So I anticipate the we’ll have some precipitation, some weather, and that will be a great thing for us.",
        "Trust is big to me. I'm a big fan of the Judge Judy show. When you lie in Judge Judy's courtroom, it's over. Your credibility is completely lost and you stand no chance of winning that case. I learned that from her. It's very powerful. And true. If somebody lies to you, how can you trust anything they say after that?",
        "A shout out from @JudgeJudy would make anyone's day, thank you! The BEST! & Excellence are easy to spot, Judge Judy is it's highest level.",
        "If worms had machine guns, then birds wouldn't be scared of them, you know?",
        "I've been trying to advise them to get two costumes, to be go-getters. Hit the neighborhood in one costume. Better to jog or run from house to house, then you can get more candy than anybody else. Then come home and make a quick change into a second costume and hit those same houses again.",
        "Zoo lions get tired of zebra after a while and want filet mignon. Not jungle lions.",
        "I take a vitamin every day; it's called a steak.",
        "That's kind of the way the pickle squirted this year.",
        "There’s a battle rhythm, a body clock that tells you it’s time for football. For me, it’s always I know when I get my first football dream. That’s my body clock telling me it’s time to compete.",
    ]

var JudyQuotes = [
           "A shout out from @JudgeJudy would make anyone's day, thank you! The BEST! & Excellence are easy to spot, Judge Judy is it's highest level.",
           "Big Congrats to Judge Judy on signing her contract extension thru 2020 from a Devout Fan!",
           "Trust is big to me. I'm a big fan of the Judge Judy show. When you lie in Judge Judy's courtroom, it's over. Your credibility is completely lost and you stand no chance of winning that case. I learned that from her. It's very powerful. And true. If somebody lies to you, how can you trust anything they say after that?",
           "When you lie in Judge Judy's court room, it's over.",
           "We have some great Supreme Court members, tremendous Supreme Court currently that we have, but I'd love to see Judge Judy on the Supreme Court. I just love everything about her.",
           ]

controller.hears([''], 'direct_message,direct_mention,mention', function(bot, message) {

    var chooseQuote  = HarQuotes[Math.random() * HarQuotes.length | 0]

    bot.reply(message, chooseQuote)

    });

controller.hears(['Harbaugh', 'Go Blue', 'Hail', 'Good morning', 'Michigan', 'khaki'], 'ambient', function(bot, message) {

    var chooseQuote  = HarQuotes[Math.random() * HarQuotes.length | 0]

    bot.reply(message, chooseQuote)

    });

controller.hears(['Judge Judy'], 'ambient', function(bot, message) {

    var chooseQuote  = JudyQuotes[Math.random() * JudyQuotes.length | 0]

    bot.reply(message, chooseQuote)

    });

controller.hears(['shutdown'], 'direct_message,direct_mention,mention', function(bot, message) {

    bot.startConversation(message, function(err, convo) {

        convo.ask('Are you sure you want me to shutdown?', [
            {
                pattern: bot.utterances.yes,
                callback: function(response, convo) {
                    convo.say('Bye!');
                    convo.next();
                    setTimeout(function() {
                        process.exit();
                    }, 3000);
                }
            },
        {
            pattern: bot.utterances.no,
            default: true,
            callback: function(response, convo) {
                convo.say('*Phew!*');
                convo.next();
            }
        }
        ]);
    });
});

controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'],
    'direct_message,direct_mention,mention', function(bot, message) {

        var hostname = os.hostname();
        var uptime = formatUptime(process.uptime());

        bot.reply(message,
            ':robot_face: I am a bot named <@' + bot.identity.name +
             '>. I have been running for ' + uptime + ' on ' + hostname + '.');

    });

function formatUptime(uptime) {
    var unit = 'second';
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'minute';
    }
    if (uptime > 60) {
        uptime = uptime / 60;
        unit = 'hour';
    }
    if (uptime != 1) {
        unit = unit + 's';
    }

    uptime = uptime + ' ' + unit;
    return uptime;
}
<|endoftext|>


<commit_before>"use strict";

var Parser = require('./Parser'),
    Methods = require('./Methods'),
    UrlNormalizer = require('./UrlNormalizer'),
    inherits = require('inherits'),
    HttpClient = require('./HttpClient'),
    Promise = require('bluebird'),
    _ = require('lodash');

var BaseHttpClient = function (http) {
    this._http = http;
};

inherits(BaseHttpClient, HttpClient);

BaseHttpClient.prototype.unwrapResponse = function () {
    return false;
};

BaseHttpClient.prototype.credentialsRequestsEnabled = function () {
    return false;
};

BaseHttpClient.prototype.get = function (url, parser, headers) {
    return this._handleRequest(url, Methods.GET, null, parser, headers);
};

BaseHttpClient.prototype.post = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.POST, data, parser, headers);
};

BaseHttpClient.prototype.put = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.PUT, data, parser, headers);
};

BaseHttpClient.prototype.delete = function (url, parser, headers) {
    return this._handleRequest(url, Methods.DELETE, null, parser, headers);
};

BaseHttpClient.prototype.jsonp = function (url, parser, headers) {
    url = UrlNormalizer.normalizeJsonp(url);
    return this._handleRequest(url, Methods.JSONP, null, parser, headers);
};

BaseHttpClient.prototype.multipart = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.MULTIPART, data, parser, headers);
};

BaseHttpClient.prototype._handleRequest = function (url, method, data, parser, headers) {
    return new Promise(_.bind(function (resolve, reject) {
        parser = parser || new Parser();
        var unwrapResponse = this.unwrapResponse();
        this._getNetworkPromise(url, method, data, headers)
            .success(function (response, status, headers, config) {
                if (!unwrapResponse)
                    resolve(parser.parse(response));
                else
                    resolve([parser.parse(response), status, headers, config]);
            })
            .error(function (error, status, headers, config) {
                if (!unwrapResponse)
                    reject(error);
                else
                    reject({data: error, status: status, headers: headers, config: config});
            });
    }, this));
};

BaseHttpClient.prototype._getNetworkPromise = function (url, method, data, headers) {
    var credentialsEnabled = this.credentialsRequestsEnabled(),
        config = {headers: headers, withCredentials: credentialsEnabled};
    if (method === Methods.MULTIPART) {
        config.transformRequest = angular.identity;
        config.headers = config.headers || {};
        config.headers['Content-Type'] = undefined;
    }
    switch (method) {
        case Methods.GET:
            return this._http.get(url, config);
        case Methods.POST:
        case Methods.MULTIPART:
            return this._http.post(url, data, config);
        case Methods.PUT:
            return this._http.put(url, data, config);
        case Methods.DELETE:
            return this._http.delete(url, config);
        case Methods.JSONP:
            return this._http.jsonp(url, config);
    }
};

module.exports = BaseHttpClient;
<commit_msg>Edit base http client to support plain responses<commit_after>"use strict";

var Parser = require('./Parser'),
    Methods = require('./Methods'),
    UrlNormalizer = require('./UrlNormalizer'),
    inherits = require('inherits'),
    HttpClient = require('./HttpClient'),
    Promise = require('bluebird'),
    _ = require('lodash');

var BaseHttpClient = function (http) {
    this._http = http;
};

inherits(BaseHttpClient, HttpClient);

BaseHttpClient.prototype.unwrapResponse = function () {
    return false;
};

BaseHttpClient.prototype.credentialsRequestsEnabled = function () {
    return false;
};

BaseHttpClient.prototype.get = function (url, parser, headers) {
    return this._handleRequest(url, Methods.GET, null, parser, headers);
};

BaseHttpClient.prototype.post = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.POST, data, parser, headers);
};

BaseHttpClient.prototype.put = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.PUT, data, parser, headers);
};

BaseHttpClient.prototype.delete = function (url, parser, headers) {
    return this._handleRequest(url, Methods.DELETE, null, parser, headers);
};

BaseHttpClient.prototype.jsonp = function (url, parser, headers) {
    url = UrlNormalizer.normalizeJsonp(url);
    return this._handleRequest(url, Methods.JSONP, null, parser, headers);
};

BaseHttpClient.prototype.multipart = function (url, data, parser, headers) {
    return this._handleRequest(url, Methods.MULTIPART, data, parser, headers);
};

BaseHttpClient.prototype._handleRequest = function (url, method, data, parser, headers, plainResponse) {
    return new Promise(_.bind(function (resolve, reject) {
        parser = parser || new Parser();
        var unwrapResponse = this.unwrapResponse();
        this._getNetworkPromise(url, method, data, headers, plainResponse)
            .success(function (response, status, headers, config) {
                if (!unwrapResponse)
                    resolve(parser.parse(response));
                else
                    resolve([parser.parse(response), status, headers, config]);
            })
            .error(function (error, status, headers, config) {
                if (!unwrapResponse)
                    reject(error);
                else
                    reject({data: error, status: status, headers: headers, config: config});
            });
    }, this));
};

BaseHttpClient.prototype._getNetworkPromise = function (url, method, data, headers, plainResponse) {
    var config = {
        headers: headers,
        withCredentials: this.credentialsRequestsEnabled()
    };
    if (plainResponse)
        config.transformResponse = undefined;
    if (method === Methods.MULTIPART) {
        config.transformRequest = angular.identity;
        config.headers = config.headers || {};
        config.headers['Content-Type'] = undefined;
    }
    switch (method) {
        case Methods.GET:
            return this._http.get(url, config);
        case Methods.POST:
        case Methods.MULTIPART:
            return this._http.post(url, data, config);
        case Methods.PUT:
            return this._http.put(url, data, config);
        case Methods.DELETE:
            return this._http.delete(url, config);
        case Methods.JSONP:
            return this._http.jsonp(url, config);
    }
};

module.exports = BaseHttpClient;
<|endoftext|>


<commit_before>
var GS = require("../getsource.js");
var RG = GS.getSource("RG", "./src/rg.js");

RG.Object = {};

RG.Object.Defense = function() {

    var _attack   = 1;
    var _defense  = 1;
    var _protection = 0;

    this.getAttack = function() {return _attack;};
    this.setAttack = function(attack) { _attack = attack; };

    /** Defense related methods.*/
    this.getDefense = function() { return _defense; };
    this.setDefense = function(defense) { _defense = defense; };

    this.getProtection = function() {return _protection;};
    this.setProtection = function(prot) {return _protection;};

};

RG.Object.Defense.prototype.copy = function(rhs) {
    this.setAttack(rhs.getAttack());
    this.setDefense(rhs.getDefense());
    this.setProtection(rhs.getProtection());
};

RG.Object.Defense.prototype.equals = function(rhs) {
    var res = this.getAttack() === rhs.getAttack() &&
        this.getDefense() === rhs.getDefense() &&
        this.getProtection() === rhs.getProtection();
    return res;
};

RG.Object.Defense.prototype.toJSON = function() {
    var json = {
        setAttack: this.getAttack(),
        setDefense: this.getDefense(),
        setProtection: this.getProtection(),
    };
    return json;
};

RG.Object.Damage = function() {
    RG.Object.Defense.call(this);

    var _damage   = new RG.Die(1, 4, 0);
    var _range    = 1;

    /** Attack methods. */
    this.setAttackRange = function(range) {_range = range;};
    this.getAttackRange = function() {return _range; };

    this.setDamage = function(dStr) {
        if (typeof dStr === "string") {
            _damage = RG.FACT.createDie(dStr);
        }
        else if (typeof dStr === "object") {
            _damage = dStr;
        }
    };

    this.getDamage = function() {
        if (this.hasOwnProperty("getWeapon")) {
            var weapon = this.getWeapon();
            if (!RG.isNullOrUndef([weapon])) {
                return weapon.getDamage();
            }
        }
        return _damage.roll();
    };

    this.getDamageDie = function() {
        return _damage;
    };

    this.setDamageDie = function(str) {
        this.setDamage(str);
    };

};
RG.extend2(RG.Object.Damage, RG.Object.Defense);

RG.Object.Damage.prototype.copy = function(rhs) {
    RG.Object.Defense.prototype.copy.call(this, rhs);
    this.setAttackRange(rhs.getAttackRange());
    var die = new RG.Die();
    die.copy(rhs.getDamageDie());
    this.setDamage(die);
};

RG.Object.Damage.prototype.equals = function(rhs) {
    var res = RG.Object.Defense.prototype.equals.call(this, rhs);
    if (res) {
        res = this.getDamageDie().equals(rhs.getDamageDie());
        res = res && this.getAttackRange() === rhs.getAttackRange();
    }
    return res;
};

RG.Object.Damage.prototype.toString = function() {
    var msg = " A: " + this.getAttack() + ", D: " + this.getDefense() + ", ";
    msg += "Dmg: " + this.getDamageDie().toString();
    msg += ",R:" + this.getAttackRange();
    return msg;
};

RG.Object.Damage.prototype.toJSON = function() {
    var json = RG.Object.Defense.prototype.toJSON.call(this);
    json.setAttackRange = this.getAttackRange();
    json.setDamage = this.getDamageDie().toString();
    return json;
};

/** Typed objects should inherit from this. */
RG.Object.Typed = function(propType, type) {
    this.type = type;
    this._propType = propType;

    this.getPropType = function() {return this._propType;};
};

RG.Object.Typed.prototype.getType = function() {return this.type;};

RG.Object.Typed.prototype.setPropType = function(propType) {
    var index = RG.PROP_TYPES.indexOf(propType);
    if (index >= 0) {
        this._propType = propType;
    }
    else {
        RG.err("Object.Typed", "setPropType",
            "Unknown prop type: |" + propType + "|");
    }
};

RG.Object.Typed.prototype.setType = function(type) {
    this.type = type;
    RG.nullOrUndefError("Object.Typed: setType", "arg |type|", type);
};

/** This object is used by all locatable objects in the game.  */
RG.Object.Locatable = function() { // {{{2
    RG.Object.Typed.call(this, null);
    this._x = null;
    this._y = null;
    this._level = null;

}; // }}} Object.Locatable
RG.extend2(RG.Object.Locatable, RG.Object.Typed);

    RG.Object.Locatable.prototype.setX = function(x) {this._x = x; };
    RG.Object.Locatable.prototype.setY = function(y) {this._y = y; };

    RG.Object.Locatable.prototype.getX = function() {return this._x;};
    RG.Object.Locatable.prototype.getY = function() {return this._y;};

    RG.Object.Locatable.prototype.getXY = function() { return [this._x, this._y];};

    /** Simple getters/setters for coordinates.*/
    RG.Object.Locatable.prototype.setXY = function(x,y) {
        this._x = x;
        this._y = y;
    };

/** Sets the level of this locatable object.*/
RG.Object.Locatable.prototype.setLevel = function(level) {
    this._level = level;
    RG.nullOrUndefError("Object.Locatable: setLevel", "arg |level|", level);
};

RG.Object.Locatable.prototype.getLevel = function() {
    return this._level;
};

/** Returns true if object is located at a position on a level.*/
RG.Object.Locatable.prototype.isLocated = function() {
    return (this._x !== null) && (this._y !== null) && (this._level !== null);
};

/** Returns true if locatables are in same position.*/
RG.Object.Locatable.prototype.isSamePos = function(obj) {
    if (this._x !== obj.getX()) return false;
    if (this._y !== obj.getY()) return false;
    if (this._level !== obj.getLevel()) return false;
    return true;
};

/** Object.Ownable is sort of Object.Locatable but it moves with its owner. This ensures that
 * for example item coordinates are up-to-date with the carrier.*/
RG.Object.Ownable = function(owner) {
    RG.Object.Typed.call(this, null);
    var _owner = owner;

    this.isSamePos = function(obj) {return _owner.isSamePos(obj);};

    this.getLevel = function() {return _owner.getLevel();};

    this.setOwner = function(owner) {
        if (RG.isNullOrUndef([owner])) {
            RG.err("Object.Ownable", "setOwner", "Owner cannot be null.");
        }
        else {
            _owner = owner;
        }
    };

    /** Returns the owner of this object.*/
    this.getOwner = function() {return _owner;};

    this.getX = function() {
        if (_owner !== null) return _owner.getX();
        return null;
    };

    this.getY = function() {
        if (_owner !== null) return _owner.getY();
        return null;
    };

    this.getLevel = function() {
        if (_owner !== null) return _owner.getLevel();
        return null;
    };

};
RG.extend2(RG.Object.Ownable, RG.Object.Typed);

if (typeof module !== "undefined" && typeof exports !== "undefined") {
    GS.exportSource(module, exports, ["RG", "Object"], [RG, RG.Object]);
}
else {
    GS.exportSource(undefined, undefined, ["RG", "Object"], [RG, RG.Object]);
}
<commit_msg>Moved getPropType outside the object into prototype.<commit_after>
var GS = require("../getsource.js");
var RG = GS.getSource("RG", "./src/rg.js");

RG.Object = {};

RG.Object.Defense = function() {

    var _attack   = 1;
    var _defense  = 1;
    var _protection = 0;

    this.getAttack = function() {return _attack;};
    this.setAttack = function(attack) { _attack = attack; };

    /** Defense related methods.*/
    this.getDefense = function() { return _defense; };
    this.setDefense = function(defense) { _defense = defense; };

    this.getProtection = function() {return _protection;};
    this.setProtection = function(prot) {return _protection;};

};

RG.Object.Defense.prototype.copy = function(rhs) {
    this.setAttack(rhs.getAttack());
    this.setDefense(rhs.getDefense());
    this.setProtection(rhs.getProtection());
};

RG.Object.Defense.prototype.equals = function(rhs) {
    var res = this.getAttack() === rhs.getAttack() &&
        this.getDefense() === rhs.getDefense() &&
        this.getProtection() === rhs.getProtection();
    return res;
};

RG.Object.Defense.prototype.toJSON = function() {
    var json = {
        setAttack: this.getAttack(),
        setDefense: this.getDefense(),
        setProtection: this.getProtection(),
    };
    return json;
};

RG.Object.Damage = function() {
    RG.Object.Defense.call(this);

    var _damage   = new RG.Die(1, 4, 0);
    var _range    = 1;

    /** Attack methods. */
    this.setAttackRange = function(range) {_range = range;};
    this.getAttackRange = function() {return _range; };

    this.setDamage = function(dStr) {
        if (typeof dStr === "string") {
            _damage = RG.FACT.createDie(dStr);
        }
        else if (typeof dStr === "object") {
            _damage = dStr;
        }
    };

    this.getDamage = function() {
        if (this.hasOwnProperty("getWeapon")) {
            var weapon = this.getWeapon();
            if (!RG.isNullOrUndef([weapon])) {
                return weapon.getDamage();
            }
        }
        return _damage.roll();
    };

    this.getDamageDie = function() {
        return _damage;
    };

    this.setDamageDie = function(str) {
        this.setDamage(str);
    };

};
RG.extend2(RG.Object.Damage, RG.Object.Defense);

RG.Object.Damage.prototype.copy = function(rhs) {
    RG.Object.Defense.prototype.copy.call(this, rhs);
    this.setAttackRange(rhs.getAttackRange());
    var die = new RG.Die();
    die.copy(rhs.getDamageDie());
    this.setDamage(die);
};

RG.Object.Damage.prototype.equals = function(rhs) {
    var res = RG.Object.Defense.prototype.equals.call(this, rhs);
    if (res) {
        res = this.getDamageDie().equals(rhs.getDamageDie());
        res = res && this.getAttackRange() === rhs.getAttackRange();
    }
    return res;
};

RG.Object.Damage.prototype.toString = function() {
    var msg = " A: " + this.getAttack() + ", D: " + this.getDefense() + ", ";
    msg += "Dmg: " + this.getDamageDie().toString();
    msg += ",R:" + this.getAttackRange();
    return msg;
};

RG.Object.Damage.prototype.toJSON = function() {
    var json = RG.Object.Defense.prototype.toJSON.call(this);
    json.setAttackRange = this.getAttackRange();
    json.setDamage = this.getDamageDie().toString();
    return json;
};

/** Typed objects should inherit from this. */
RG.Object.Typed = function(propType, type) {
    this.type = type;
    this._propType = propType;

};

    RG.Object.Typed.prototype.getPropType = function() {return this._propType;};
RG.Object.Typed.prototype.getType = function() {return this.type;};

RG.Object.Typed.prototype.setPropType = function(propType) {
    var index = RG.PROP_TYPES.indexOf(propType);
    if (index >= 0) {
        this._propType = propType;
    }
    else {
        RG.err("Object.Typed", "setPropType",
            "Unknown prop type: |" + propType + "|");
    }
};

RG.Object.Typed.prototype.setType = function(type) {
    this.type = type;
    RG.nullOrUndefError("Object.Typed: setType", "arg |type|", type);
};

/** This object is used by all locatable objects in the game.  */
RG.Object.Locatable = function() { // {{{2
    RG.Object.Typed.call(this, null);
    this._x = null;
    this._y = null;
    this._level = null;

}; // }}} Object.Locatable
RG.extend2(RG.Object.Locatable, RG.Object.Typed);

    RG.Object.Locatable.prototype.setX = function(x) {this._x = x; };
    RG.Object.Locatable.prototype.setY = function(y) {this._y = y; };

    RG.Object.Locatable.prototype.getX = function() {return this._x;};
    RG.Object.Locatable.prototype.getY = function() {return this._y;};

    RG.Object.Locatable.prototype.getXY = function() { return [this._x, this._y];};

    /** Simple getters/setters for coordinates.*/
    RG.Object.Locatable.prototype.setXY = function(x,y) {
        this._x = x;
        this._y = y;
    };

/** Sets the level of this locatable object.*/
RG.Object.Locatable.prototype.setLevel = function(level) {
    this._level = level;
    RG.nullOrUndefError("Object.Locatable: setLevel", "arg |level|", level);
};

RG.Object.Locatable.prototype.getLevel = function() {
    return this._level;
};

/** Returns true if object is located at a position on a level.*/
RG.Object.Locatable.prototype.isLocated = function() {
    return (this._x !== null) && (this._y !== null) && (this._level !== null);
};

/** Returns true if locatables are in same position.*/
RG.Object.Locatable.prototype.isSamePos = function(obj) {
    if (this._x !== obj.getX()) return false;
    if (this._y !== obj.getY()) return false;
    if (this._level !== obj.getLevel()) return false;
    return true;
};

/** Object.Ownable is sort of Object.Locatable but it moves with its owner. This ensures that
 * for example item coordinates are up-to-date with the carrier.*/
RG.Object.Ownable = function(owner) {
    RG.Object.Typed.call(this, null);
    var _owner = owner;

    this.isSamePos = function(obj) {return _owner.isSamePos(obj);};

    this.getLevel = function() {return _owner.getLevel();};

    this.setOwner = function(owner) {
        if (RG.isNullOrUndef([owner])) {
            RG.err("Object.Ownable", "setOwner", "Owner cannot be null.");
        }
        else {
            _owner = owner;
        }
    };

    /** Returns the owner of this object.*/
    this.getOwner = function() {return _owner;};

    this.getX = function() {
        if (_owner !== null) return _owner.getX();
        return null;
    };

    this.getY = function() {
        if (_owner !== null) return _owner.getY();
        return null;
    };

    this.getLevel = function() {
        if (_owner !== null) return _owner.getLevel();
        return null;
    };

};
RG.extend2(RG.Object.Ownable, RG.Object.Typed);

if (typeof module !== "undefined" && typeof exports !== "undefined") {
    GS.exportSource(module, exports, ["RG", "Object"], [RG, RG.Object]);
}
else {
    GS.exportSource(undefined, undefined, ["RG", "Object"], [RG, RG.Object]);
}
<|endoftext|>