<commit_before>"use strict";

const wrtc_adapter = require("webrtc-adapter-test")
	, enums = {
		RESPONSE_NONE: Symbol("Miscellaneous Response"),
		RESPONSE_ICE: Symbol("ICE Candidate Response"),
		RESPONSE_SDP_ANSWER: Symbol("SDP Reply Response"),
		RESPONSE_SDP_OFFER: Symbol("SDP Offer Response"),

		MSG_SDP_ANSWER: Symbol("SDP Reply Message"),
		MSG_SDP_OFFER: Symbol("SDP Offer Message"),
		MSG_ICE: Symbol("ICE Candidate Message"),

		CHANNEL_BOUND: Symbol("Channel is bound to resource manager."),
		CHANNEL_CLOSED: Symbol("Channel is closed.")
	};

const defaultConfig = {
	channel: null,
	conn_ttl: 10000,
	rtc_facade: wrtc_adapter,
	rtc_config: { iceServers: [{urls: ["stun:stun.l.google.com:19302", "stun:stun.ekiga.net"] }] }
};

function WebRTCResourceManager(config){
	this._channelRegistry = {};
	this._connectionRegistry = {};

	let _lookupChannel = id => {
		// Takes a string id, and returns the channel matching that id.
		return this._channelRegistry[id];
	},
	_insertChannel = channel => {
		//Place a channel object into the registry based upon its internalID.
		this._channelRegistry[channel.internalID] = channel;
	},
	_newConnection = (id, channel, response) => {
		let conn = new this.config.rtc_facade.RTCPeerConnection(this.config.rtc_config),
			trConn = new TrackedConnection(id, conn);

		_insertConnection(id, trConn);

		conn.onicecandidate = function(evt) {
			if(evt.candidate)
				channel.send(id, enums.MSG_ICE, evt.candidate);
		}

		conn.ondatachannel = function(evt){
			console.log("Received Channel from other partner.")
			console.log(trConn.dataChannels.__default)
			console.log(evt.channel)
			trConn.registerDataChannel(evt.channel);
		}

		if(response)
			_fireOnConnected(conn);

		return trConn;
	},
	_lookupConnection = id => {
		// Check to see if a connection exists in the registry already.
		return this._connectionRegistry[id];
	},
	_insertConnection = (id, connection) => {
		//Place a Connection object into the registry based upon its internalID.
		this._connectionRegistry[id] = connection;
	},
	_validateChannel = channel => {
		// Check to see if an object is a valid channel
		return (channel.internalID && typeof channel.internalID === "string")
				&& (channel.send && typeof channel.send === "function")
				&& (channel.onmessage && typeof channel.onmessage === "function")
				&& (!channel.onbind || typeof channel.onbind === "function")
				&& (!channel.onclose || typeof channel.onclose === "function");
	},
	_bindChannel = channel => {
		// Bind a channel to this manager object. Change its state accordingly.
		_insertChannel(channel);
		channel._manager = this;
		channel.state = enums.CHANNEL_BOUND;

		let onbindresult;
		if(channel.onbind){
			onbindresult = channel.onbind();
		}

		if(!(onbindresult instanceof Promise))
			channel._ready = Promise.resolve(true);
		else
			channel._ready = onbindresult;

	},
	_closeChannel = channel => {
		// Close a channel properly, change its state.
		if(channel.close)
			channel.close();
		channel.state = enums.CHANNEL_CLOSED;
	},
	_channelFromObjectOrId = channel => {
		if(typeof channel === "string"){
			channel = _lookupChannel(channel);
		}

		if(channel === null || channel === undefined)
			throw new Error("Channel lookup failed - id does not correspond to a registered channel instance.");
		else if(channel._manager !== this)
			throw new Error("Channel is not bound to this manager instance.");
		else
			return channel;

		return null;
	},
	_validateConfig = config => {
		return (config.channel && _validateChannel(config.channel))
				&& (config.rtc_facade && typeof config.rtc_facade === "object")
				&& (config.rtc_config && typeof config.rtc_config === "object");
	},
	_mergeConfig = config => {
		let out = {};

		for(var propName in defaultConfig)
			if(defaultConfig.hasOwnProperty(propName))
				out[propName] = defaultConfig[propName];

		for(var propName in config)
			if(config.hasOwnProperty(propName) && (out[propName] === null || out[propName] === undefined))
				out[propName] = config[propName];

		return out;
	},
	_fireOnConnected = (conn) => {
		if(this.onconnection)
			this.onconnection(conn);
	};

	//Public methods.

	this.connectTo = (id, channel) => {
		// Return an instance of a given connection by its id.
		// This increments a connection's usage counter.
		// If the channel supplied is an id, look it up in the registry.
		//		If it has been bound to this, use it. If bound to another manager, throw.
		// 		Otherwise, add it to the registry if it has yet to be bound.

		let look = _lookupConnection(id),
			prom;

		if(!look){
			if(!channel)
				channel = this.config.channel;
			else{
				try{
					channel = _channelFromObjectOrId(channel);
				} catch (e){
					if(channel.state === enums.CHANNEL_BOUND || channel.state === enums.CHANNEL_CLOSED)
						throw e;
					else
						this.register(channel);
				}
			}

			look = _newConnection(id, channel);

			// let dataChan = look.connection.createDataChannel("__default", null);
			let dataChan = {};

			let ready = channel._ready
				.then(result => {
					if(result){
						dataChan = look.addDataChannel("__default");
						return look.connection.createOffer({});
					}
					else
						return new Promise((res,rej)=>{rej("Channel failed to become ready for connection or is not allowing outbound offers.");});
				})
				.then(result => {
					return look.connection.setLocalDescription(result);
				})
				.then(
					result => {
						channel.send(id, enums.MSG_SDP_OFFER, look.connection.localDescription);
						return true;
					},
					reason => {
						console.log(reason);
						return false;
					}
				);

			prom = new Promise((resolve,reject)=>{
				// dataChan.then(
				// 	result => resolve(look),
				// 	reason => reject(reason)
				// );
				// if(ready){
					dataChan.onopen = () => resolve(look);
					dataChan.onerror = err => reject(err);
				// }
			});

		} else {
			prom = new Promise((resolve, reject)=>{
				resolve(look);
			});
		}

		return prom;
	};

	this.close = id => {
		// Close a connection with the given id.
		// If you have a TrackedConnection instance you'd be better off just calling .close on that.
		_lookupConnection(id).close();
	};

	this.getConnection = id => {
		// Return an instance of a given connection by its id.
		// This shouldn't affect a connection's usages counter.
		return _lookupConnection(id);
	};

	this.response = (msg, channel) => {
		// Call this function to to pass a response from a channel to the correct channel handler.
		// channel may either be a channel object or an id - in both cases the channel object MUST
		// be registered to the controller.
		channel = _channelFromObjectOrId(channel);

		let input = channel.onmessage(msg),
			target = _lookupConnection(input.id),
			data = input.data;

		if(!target && input.id)
			target = _newConnection(input.id, channel, true);

		switch(input.type){
			case(enums.RESPONSE_NONE):
				break;
			case(enums.RESPONSE_ICE):
				console.log("ICE candidate picked up by manager.");
				console.log(data);
				target.connection.addIceCandidate(new this.config.rtc_facade.RTCIceCandidate(data))
					.then(
					  	result => console.log("Successfully added ICE candidate to connection "+input.id),
					  	reason => console.log("Unsuccessful in adding ICE candidate to connection "+input.id+": "+reason)
					);
				break;
			case(enums.RESPONSE_SDP_OFFER):
				console.log("SDP offer picked up by manager.")
				target.connection.setRemoteDescription(new this.config.rtc_facade.RTCSessionDescription(data))
					.then((res) => {
						return target.connection.createAnswer()
					})
					.then((res) => {
						return target.connection.setLocalDescription(res)
					})
					.then(
						result => channel.send(input.id, enums.MSG_SDP_ANSWER, target.connection.localDescription),
						reason => {throw new Error("Failed to respond to SDP offer: "+reason);}
					);
				break;
			case(enums.RESPONSE_SDP_ANSWER):
				console.log("SDP answer picked up by manager.");
				target.connection.setRemoteDescription(new this.config.rtc_facade.RTCSessionDescription(data))
				.then(
					  	result => console.log("Successfully added SDP Answer to connection "+input.id),
					  	reason => console.log("Unsuccessful in adding SDP Answer to connection "+input.id+": "+reason)
					);
				break;
			default:
				throw new Error("Illegal input type sent as response to connection driver.");
		}
	};

	this.register = channel => {
		// Called to add a channel handler to the channel registry.
		// Strict limit of one handler per id - duplicate entry should close the old before inserting the new.
		let lookup = _lookupChannel(channel.internalID);

		if(lookup && lookup !== channel)
			_closeChannel(lookup);

		if(_validateChannel(channel))
			_bindChannel(channel);
		else
			throw new TypeError("The supplied channel is not of a valid format.");
	};

	this.renameConnection = (oldName, newName) => {
		if(!(typeof oldName === "string" && typeof newName === "string"))
			throw new TypeError("Invalid parameters for renameConnection - one or both are not of type \"string\".");
		if(!this._connectionRegistry[oldName])
			throw new ReferenceError("Invalid parameter for old name at renameConnection - no corresponding connection exists.");
		if(this._connectionRegistry[newName])
			throw new ReferenceError("Error for new name at renameConnection - connection of name "+newName+" already exists.");

		this._connectionRegistry[newName] = this._connectionRegistry[oldName]
		delete this._connectionRegistry[oldName];
	}

	this.onconnection = undefined;

	// Initialisation code

	this.config = _mergeConfig(config);

	if(!_validateConfig(this.config))
		throw new TypeError("An 'rtc_facade', 'rtc_config' and 'channel' must be defined for WebRTC to be used.");

	this.register(this.config.channel);
}

function TrackedConnection(id, rtcConn){
	// let _usages = 0;

	// Object.defineProperty(this, {
	// 	"usages": {
	// 		"get": () => {return _usages;}
	// 	}
	// })

	let _lookupExisting = label => {
		let look;

		if(label)
			look = this.dataChannels[label];
		else
			look = this.dataChannels.__default;

		if(!look)
			throw new Error(label ? "No such data channel for label "+label+"."
				: "No default channel present to send data."
			);

		return look;
	};

	this.id = id;

	this.connection = rtcConn;

	this.dataChannels = {
		__default: null
	};

	// this.openStatus = "closed";

	this.addDataChannel = label => {
		// Add another data connection onto this RTCPeerConnection.
		// If we use a duplicate label, just take that connection instead.
		// Return a promise.
		let dChan = this.dataChannels[label];
		if(!dChan){
			this.registerDataChannel(this.connection.createDataChannel(label, null));
			dChan = this.dataChannels[label];
		}

		return dChan;
	};

	this.registerDataChannel = (dChan) => {
		// let prom = new Promise((resolve, reject) => {
		// 	dChan.onopen = () => {resolve(dChan)};
		// 	dChan.onerror = err => reject(err);
		// 	dChan.onmessage = (msg) => console.log("MESSAGE: "+msg)
		// });

		this.dataChannels[dChan.label] = dChan;

		// return prom;
		return dChan;
	};

	this.send = (msg, label) => {
		_lookupExisting(label)
		// .then(result => result.send(msg));
		.send(msg)
	};

	this.close = () => {
		// Decrement usages by 1.
		// If _usages hits zero, place a timeout function to kill this item if it gains no more users
		// before TTL
		// TODO - closes for real right now.

		this.connection.close();
	};

	this.on = (event, handler, label) => {
		debugger;
		_lookupExisting(label)["on"+event] = handler
		// .then(result => {console.log(result);result["on"+event] = handler;console.log(result.onmessage);});
	};
}

module.exports = {
	create(config){
		return new WebRTCResourceManager(config);
	},

	WebRTCResourceManager,
	TrackedConnection,
	enums
};
<commit_msg>Logging to track some errors occuring in chord.<commit_after>"use strict";

const wrtc_adapter = require("webrtc-adapter-test")
	, enums = {
		RESPONSE_NONE: Symbol("Miscellaneous Response"),
		RESPONSE_ICE: Symbol("ICE Candidate Response"),
		RESPONSE_SDP_ANSWER: Symbol("SDP Reply Response"),
		RESPONSE_SDP_OFFER: Symbol("SDP Offer Response"),

		MSG_SDP_ANSWER: Symbol("SDP Reply Message"),
		MSG_SDP_OFFER: Symbol("SDP Offer Message"),
		MSG_ICE: Symbol("ICE Candidate Message"),

		CHANNEL_BOUND: Symbol("Channel is bound to resource manager."),
		CHANNEL_CLOSED: Symbol("Channel is closed.")
	};

const defaultConfig = {
	channel: null,
	conn_ttl: 10000,
	rtc_facade: wrtc_adapter,
	rtc_config: { iceServers: [{urls: ["stun:stun.l.google.com:19302", "stun:stun.ekiga.net"] }] }
};

function WebRTCResourceManager(config){
	this._channelRegistry = {};
	this._connectionRegistry = {};

	let _lookupChannel = id => {
		// Takes a string id, and returns the channel matching that id.
		return this._channelRegistry[id];
	},
	_insertChannel = channel => {
		//Place a channel object into the registry based upon its internalID.
		this._channelRegistry[channel.internalID] = channel;
	},
	_newConnection = (id, channel, response) => {
		console.log("Inside Conductor:")
		console.log(this)
		console.log(this.config)
		console.log(this.config.rtc_facade)

		let conn = new this.config.rtc_facade.RTCPeerConnection(this.config.rtc_config),
			trConn = new TrackedConnection(id, conn);

		_insertConnection(id, trConn);

		conn.onicecandidate = function(evt) {
			if(evt.candidate)
				channel.send(id, enums.MSG_ICE, evt.candidate);
		}

		conn.ondatachannel = function(evt){
			console.log("Received Channel from other partner.")
			console.log(trConn.dataChannels.__default)
			console.log(evt.channel)
			trConn.registerDataChannel(evt.channel);
		}

		if(response)
			_fireOnConnected(conn);

		return trConn;
	},
	_lookupConnection = id => {
		// Check to see if a connection exists in the registry already.
		return this._connectionRegistry[id];
	},
	_insertConnection = (id, connection) => {
		//Place a Connection object into the registry based upon its internalID.
		this._connectionRegistry[id] = connection;
	},
	_validateChannel = channel => {
		// Check to see if an object is a valid channel
		return (channel.internalID && typeof channel.internalID === "string")
				&& (channel.send && typeof channel.send === "function")
				&& (channel.onmessage && typeof channel.onmessage === "function")
				&& (!channel.onbind || typeof channel.onbind === "function")
				&& (!channel.onclose || typeof channel.onclose === "function");
	},
	_bindChannel = channel => {
		// Bind a channel to this manager object. Change its state accordingly.
		_insertChannel(channel);
		channel._manager = this;
		channel.state = enums.CHANNEL_BOUND;

		let onbindresult;
		if(channel.onbind){
			onbindresult = channel.onbind();
		}

		if(!(onbindresult instanceof Promise))
			channel._ready = Promise.resolve(true);
		else
			channel._ready = onbindresult;

	},
	_closeChannel = channel => {
		// Close a channel properly, change its state.
		if(channel.close)
			channel.close();
		channel.state = enums.CHANNEL_CLOSED;
	},
	_channelFromObjectOrId = channel => {
		if(typeof channel === "string"){
			channel = _lookupChannel(channel);
		}

		if(channel === null || channel === undefined)
			throw new Error("Channel lookup failed - id does not correspond to a registered channel instance.");
		else if(channel._manager !== this)
			throw new Error("Channel is not bound to this manager instance.");
		else
			return channel;

		return null;
	},
	_validateConfig = config => {
		return (config.channel && _validateChannel(config.channel))
				&& (config.rtc_facade && typeof config.rtc_facade === "object")
				&& (config.rtc_config && typeof config.rtc_config === "object");
	},
	_mergeConfig = config => {
		let out = {};

		for(var propName in defaultConfig)
			if(defaultConfig.hasOwnProperty(propName))
				out[propName] = defaultConfig[propName];

		for(var propName in config)
			if(config.hasOwnProperty(propName) && (out[propName] === null || out[propName] === undefined))
				out[propName] = config[propName];

		return out;
	},
	_fireOnConnected = (conn) => {
		if(this.onconnection)
			this.onconnection(conn);
	};

	//Public methods.

	this.connectTo = (id, channel) => {
		// Return an instance of a given connection by its id.
		// This increments a connection's usage counter.
		// If the channel supplied is an id, look it up in the registry.
		//		If it has been bound to this, use it. If bound to another manager, throw.
		// 		Otherwise, add it to the registry if it has yet to be bound.

		let look = _lookupConnection(id),
			prom;

		if(!look){
			if(!channel)
				channel = this.config.channel;
			else{
				try{
					channel = _channelFromObjectOrId(channel);
				} catch (e){
					if(channel.state === enums.CHANNEL_BOUND || channel.state === enums.CHANNEL_CLOSED)
						throw e;
					else
						this.register(channel);
				}
			}

			look = _newConnection(id, channel);

			// let dataChan = look.connection.createDataChannel("__default", null);
			let dataChan = {};

			let ready = channel._ready
				.then(result => {
					if(result){
						dataChan = look.addDataChannel("__default");
						return look.connection.createOffer({});
					}
					else
						return new Promise((res,rej)=>{rej("Channel failed to become ready for connection or is not allowing outbound offers.");});
				})
				.then(result => {
					return look.connection.setLocalDescription(result);
				})
				.then(
					result => {
						channel.send(id, enums.MSG_SDP_OFFER, look.connection.localDescription);
						return true;
					},
					reason => {
						console.log(reason);
						return false;
					}
				);

			prom = new Promise((resolve,reject)=>{
				// dataChan.then(
				// 	result => resolve(look),
				// 	reason => reject(reason)
				// );
				// if(ready){
					dataChan.onopen = () => resolve(look);
					dataChan.onerror = err => reject(err);
				// }
			});

		} else {
			prom = new Promise((resolve, reject)=>{
				resolve(look);
			});
		}

		return prom;
	};

	this.close = id => {
		// Close a connection with the given id.
		// If you have a TrackedConnection instance you'd be better off just calling .close on that.
		_lookupConnection(id).close();
	};

	this.getConnection = id => {
		// Return an instance of a given connection by its id.
		// This shouldn't affect a connection's usages counter.
		return _lookupConnection(id);
	};

	this.response = (msg, channel) => {
		// Call this function to to pass a response from a channel to the correct channel handler.
		// channel may either be a channel object or an id - in both cases the channel object MUST
		// be registered to the controller.
		channel = _channelFromObjectOrId(channel);

		let input = channel.onmessage(msg),
			target = _lookupConnection(input.id),
			data = input.data;

		if(!target && input.id)
			target = _newConnection(input.id, channel, true);

		switch(input.type){
			case(enums.RESPONSE_NONE):
				break;
			case(enums.RESPONSE_ICE):
				console.log("ICE candidate picked up by manager.");
				console.log(data);
				target.connection.addIceCandidate(new this.config.rtc_facade.RTCIceCandidate(data))
					.then(
					  	result => console.log("Successfully added ICE candidate to connection "+input.id),
					  	reason => console.log("Unsuccessful in adding ICE candidate to connection "+input.id+": "+reason)
					);
				break;
			case(enums.RESPONSE_SDP_OFFER):
				console.log("SDP offer picked up by manager.")
				target.connection.setRemoteDescription(new this.config.rtc_facade.RTCSessionDescription(data))
					.then((res) => {
						return target.connection.createAnswer()
					})
					.then((res) => {
						return target.connection.setLocalDescription(res)
					})
					.then(
						result => channel.send(input.id, enums.MSG_SDP_ANSWER, target.connection.localDescription),
						reason => {throw new Error("Failed to respond to SDP offer: "+reason);}
					);
				break;
			case(enums.RESPONSE_SDP_ANSWER):
				console.log("SDP answer picked up by manager.");
				target.connection.setRemoteDescription(new this.config.rtc_facade.RTCSessionDescription(data))
				.then(
					  	result => console.log("Successfully added SDP Answer to connection "+input.id),
					  	reason => console.log("Unsuccessful in adding SDP Answer to connection "+input.id+": "+reason)
					);
				break;
			default:
				throw new Error("Illegal input type sent as response to connection driver.");
		}
	};

	this.register = channel => {
		// Called to add a channel handler to the channel registry.
		// Strict limit of one handler per id - duplicate entry should close the old before inserting the new.
		let lookup = _lookupChannel(channel.internalID);

		if(lookup && lookup !== channel)
			_closeChannel(lookup);

		if(_validateChannel(channel))
			_bindChannel(channel);
		else
			throw new TypeError("The supplied channel is not of a valid format.");
	};

	this.renameConnection = (oldName, newName) => {
		if(!(typeof oldName === "string" && typeof newName === "string"))
			throw new TypeError("Invalid parameters for renameConnection - one or both are not of type \"string\".");
		if(!this._connectionRegistry[oldName])
			throw new ReferenceError("Invalid parameter for old name at renameConnection - no corresponding connection exists.");
		if(this._connectionRegistry[newName])
			throw new ReferenceError("Error for new name at renameConnection - connection of name "+newName+" already exists.");

		this._connectionRegistry[newName] = this._connectionRegistry[oldName]
		delete this._connectionRegistry[oldName];
	}

	this.onconnection = undefined;

	// Initialisation code

	this.config = _mergeConfig(config);

	if(!_validateConfig(this.config))
		throw new TypeError("An 'rtc_facade', 'rtc_config' and 'channel' must be defined for WebRTC to be used.");

	this.register(this.config.channel);
}

function TrackedConnection(id, rtcConn){
	// let _usages = 0;

	// Object.defineProperty(this, {
	// 	"usages": {
	// 		"get": () => {return _usages;}
	// 	}
	// })

	let _lookupExisting = label => {
		let look;

		if(label)
			look = this.dataChannels[label];
		else
			look = this.dataChannels.__default;

		if(!look)
			throw new Error(label ? "No such data channel for label "+label+"."
				: "No default channel present to send data."
			);

		return look;
	};

	this.id = id;

	this.connection = rtcConn;

	this.dataChannels = {
		__default: null
	};

	// this.openStatus = "closed";

	this.addDataChannel = label => {
		// Add another data connection onto this RTCPeerConnection.
		// If we use a duplicate label, just take that connection instead.
		// Return a promise.
		let dChan = this.dataChannels[label];
		if(!dChan){
			this.registerDataChannel(this.connection.createDataChannel(label, null));
			dChan = this.dataChannels[label];
		}

		return dChan;
	};

	this.registerDataChannel = (dChan) => {
		// let prom = new Promise((resolve, reject) => {
		// 	dChan.onopen = () => {resolve(dChan)};
		// 	dChan.onerror = err => reject(err);
		// 	dChan.onmessage = (msg) => console.log("MESSAGE: "+msg)
		// });

		this.dataChannels[dChan.label] = dChan;

		// return prom;
		return dChan;
	};

	this.send = (msg, label) => {
		_lookupExisting(label)
		// .then(result => result.send(msg));
		.send(msg)
	};

	this.close = () => {
		// Decrement usages by 1.
		// If _usages hits zero, place a timeout function to kill this item if it gains no more users
		// before TTL
		// TODO - closes for real right now.

		this.connection.close();
	};

	this.on = (event, handler, label) => {
		debugger;
		_lookupExisting(label)["on"+event] = handler
		// .then(result => {console.log(result);result["on"+event] = handler;console.log(result.onmessage);});
	};
}

module.exports = {
	create(config){
		return new WebRTCResourceManager(config);
	},

	WebRTCResourceManager,
	TrackedConnection,
	enums
};
<|endoftext|>


<commit_before>/* global describe, context, it */
'use strict';

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');

const blizzard = require('./initialize');

chai.use(chaiAsPromised);

describe('lib/account.js', function () {

  context('API methods', function () {
    const tests = ['user', 'wow', 'sc2'];

    tests.forEach(function (test) {
      it(`should have a method "${test}"`, function (done) {
        chai.assert.isFunction(blizzard.account[test]);
        done();
      });
    });
  });

});
<commit_msg>Add test for user method<commit_after>/* global describe, context, it */
'use strict';

const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');

const blizzard = require('./initialize');

chai.use(chaiAsPromised);

describe('lib/account.js', function () {
  this.timeout(10000);

  context('API methods', function () {
    const tests = ['user', 'wow', 'sc2'];

    tests.forEach(function (test) {
      it(`should have a method "${test}"`, function (done) {
        chai.assert.isFunction(blizzard.account[test]);
        done();
      });
    });
  });

  context('.user()', function () {
    it('should eventually return a user account profile', function () {
      const user = blizzard.account.user();

      return chai.assert.eventually.deepProperty(user, 'data.battletag');
    });
  });

});
<|endoftext|>


<commit_before>var _ = require('lodash');

var NOCK_API_URL = 'https://api.github.com:443';
var NOCK_API_ENDPOINT = '/authorizations';

// POSTS
var NOCK_POST_TEST = {"scopes":[],"note":"test","note_url":""};

// BODY MESSAGES
var NOCK_BODY_BAD_USERPASS = {"message":"Bad credentials","documentation_url":"https://developer.github.com/v3"};
var NOCK_BODY_BAD_2FA = {"message":"Must specify two-factor authentication OTP code.","documentation_url":"https://developer.github.com/v3/auth#working-with-two-factor-authentication"};
var NOCK_BODY_BAD_TOKEN_EXISTS = {"message":"Validation Failed","documentation_url":"https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization","errors":[{"resource":"OauthAccess","code":"already_exists","field":"description"}]};

// BODY RESULTS
var NOCK_BODY_TOKEN = {"id":9999999,"url":"https://api.github.com/authorizations/9999999","app":{"name":"test","url":"https://developer.github.com/v3/oauth_authorizations/","client_id":"00000000000000000000"},"token":"abcdefghijklmnopqrstuvwxyzabcdefghijklmn","note":"test","note_url":"","created_at":"1970-01-01T00:00:00Z","updated_at":"1970-01-01T00:00:00Z","scopes":[]};
var NOCK_BODY_EMPTY_AUTHORIZATIONS = [];
var NOCK_BODY_ALL_AUTHORIZATIONS = [NOCK_BODY_TOKEN];

// HEADERS
var DEFAULT_HEADERS = {
    server: 'GitHub.com',
    date: 'Wed, 02 Jul 2014 00:00:00 GMT',
    'content-type': 'application/json; charset=utf-8',
    'x-github-media-type': 'github.beta; format=json',
    'x-ratelimit-reset': '1404343458',
    'x-xss-protection': '1; mode=block',
    'x-frame-options': 'deny',
    'content-security-policy': 'default-src \'none\'',
    'content-length': '160',
    'access-control-allow-credentials': 'true',
    'access-control-expose-headers': 'ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval',
    'access-control-allow-origin': '*',
    'x-github-request-id': '00000000:0000:000000:00000000',
    'strict-transport-security': 'max-age=31536000; includeSubdomains',
    'x-content-type-options': 'nosniff'
};
var RATELIMIT_NO2FA = {
    'x-ratelimit-limit': '60',
    'x-ratelimit-remaining': '59'
};
var RATELIMIT_HAS2FA = {
    'x-ratelimit-limit': '5000',
    'x-ratelimit-remaining': '4999'
};
var RESULT_HEADERS = {
    'cache-control': 'private, max-age=60, s-maxage=60',
    etag: '"abcdefghijklmnopqrstuvwxyzabcdef"',
    vary: 'Accept, Authorization, Cookie, X-GitHub-OTP'
};

var NOCK_HEADERS_BAD_USERPASS = _.defaults({
    status: '401 Unauthorized'
}, RATELIMIT_NO2FA, DEFAULT_HEADERS);

var NOCK_HEADERS_BAD_2FA = _.defaults({
    'x-github-otp': 'required; app'
}, NOCK_HEADERS_BAD_USERPASS);

var NOCK_HEADERS_BAD_TOKEN_EXISTS = _.defaults({
    status: '422 Unprocessable Entity'
}, RATELIMIT_HAS2FA, DEFAULT_HEADERS);

var NOCK_HEADERS_CREATED = _.defaults({
    status: '201 Created',
    location: 'https://api.github.com/authorizations/9999999'
}, RATELIMIT_HAS2FA, RESULT_HEADERS, DEFAULT_HEADERS);

var NOCK_HEADERS_ALL_AUTHORIZATIONS = _.defaults({
    status: '200 OK',
    'x-served-by': 'abcdefghijklmnopqrstuvwxyzabcdef'
}, RESULT_HEADERS, DEFAULT_HEADERS);
var NOCK_HEADERS_ALL_AUTHORIZATIONS_NO2FA = _.defaults({}, RATELIMIT_NO2FA);
var NOCK_HEADERS_ALL_AUTHORIZATIONS_HAS2FA = _.defaults({}, RATELIMIT_HAS2FA);

var NOCK_HEADERS_EMPTY_AUTHORIZATIONS = _.defaults({
    link: '<https://api.github.com/authorizations?page=0>; rel="last"'
}, NOCK_HEADERS_ALL_AUTHORIZATIONS);
var NOCK_HEADERS_EMPTY_AUTHORIZATIONS_NO2FA = _.defaults({}, RATELIMIT_NO2FA);
var NOCK_HEADERS_EMPTY_AUTHORIZATIONS_HAS2FA = _.defaults({}, RATELIMIT_HAS2FA);

// B A D
// Bad no 2FA: test auth
function testAuthNo2FABad () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            401,
            NOCK_BODY_BAD_USERPASS,
            NOCK_HEADERS_BAD_USERPASS
        );
}
// Bad has 2FA: test auth
function testAuthHas2FABad () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            401,
            NOCK_BODY_BAD_2FA,
            NOCK_HEADERS_BAD_2FA
        );
}
// Bad no 2FA: make new token
function makeNewNo2FABad () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            401,
            NOCK_BODY_BAD_USERPASS,
            NOCK_HEADERS_BAD_USERPASS
        );
}
// Bad has 2FA: make new token
function makeNewHas2FABad () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            401,
            NOCK_BODY_BAD_2FA,
            NOCK_HEADERS_BAD_2FA
        );
}

// G O O D
// Good no 2FA: test auth
function testAuthNo2FAGood () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            200,
            NOCK_BODY_EMPTY_AUTHORIZATIONS,
            NOCK_HEADERS_EMPTY_AUTHORIZATIONS_NO2FA
        );
}
// Good no 2FA: make new token
function makeNewNo2FAGood () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            201,
            NOCK_BODY_TOKEN,
            NOCK_HEADERS_CREATED
        );
}
// Good no 2FA: make new token, already exists
function makeNewExistsNo2FAGood () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            422,
            NOCK_BODY_BAD_TOKEN_EXISTS,
            NOCK_HEADERS_BAD_TOKEN_EXISTS
        );
}
// Good no 2FA: get existing token (gets all tokens)
function getExistingNo2FAGood () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            200,
            NOCK_BODY_ALL_AUTHORIZATIONS,
            NOCK_HEADERS_ALL_AUTHORIZATIONS_NO2FA
        );
}
// Good has 2FA: test auth
function testAuthHas2FAGood () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            401,
            NOCK_BODY_BAD_2FA,
            NOCK_HEADERS_BAD_2FA
        );
}
// Good has 2FA: make new token
function makeNewHas2FAGood () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            201,
            NOCK_BODY_TOKEN,
            NOCK_HEADERS_CREATED
        );
}
// Good has 2FA: make new token, already exists
function makeNewExistsHas2FAGood () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            422,
            NOCK_BODY_BAD_TOKEN_EXISTS,
            NOCK_HEADERS_BAD_TOKEN_EXISTS
        );
}
// Good has 2FA: get existing token (gets all tokens)
function getExistingHas2FAGood () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            200,
            NOCK_BODY_ALL_AUTHORIZATIONS,
            NOCK_HEADERS_ALL_AUTHORIZATIONS_HAS2FA
        );
}

// - - - G E T T E R S - - -

var responses = {
    testAuth: {
        no2FA: {
            good: testAuthNo2FAGood,
            bad: testAuthNo2FABad
        },
        has2FA: {
            good: testAuthHas2FAGood,
            bad: testAuthHas2FABad
        }
    },
    makeNew: {
        no2FA: {
            good: makeNewNo2FAGood,
            bad: makeNewNo2FABad
        },
        has2FA: {
            good: makeNewHas2FAGood,
            bad: makeNewHas2FABad
        }
    },
    makeNewExists: {
        no2FA: {
            good: makeNewExistsNo2FAGood
        },
        has2FA: {
            good: makeNewExistsHas2FAGood
        }
    },
    getExisting: {
        no2FA: {
            good: getExistingNo2FAGood
        },
        has2FA: {
            good: getExistingHas2FAGood
        }
    }
};

function ApiResponse (nock) {
    var self = this;
    function createPrototype (obj, methods) {
        var _ = require('lodash');
        _.each(methods, function (method, name) {
            if (!_.isFunction(method)) {
                obj[name] = {};
                createPrototype(obj[name], method);
            } else {
                obj[name] = _.bind(method, self);
            }
        });
    }
    createPrototype(this, responses);
    this.nock = nock;
    return this;
}

module.exports = function main (nock) {
    return new ApiResponse(nock);
};
<commit_msg>Group good api responses like the bad ones.<commit_after>var _ = require('lodash');

var NOCK_API_URL = 'https://api.github.com:443';
var NOCK_API_ENDPOINT = '/authorizations';

// POSTS
var NOCK_POST_TEST = {"scopes":[],"note":"test","note_url":""};

// BODY MESSAGES
var NOCK_BODY_BAD_USERPASS = {"message":"Bad credentials","documentation_url":"https://developer.github.com/v3"};
var NOCK_BODY_BAD_2FA = {"message":"Must specify two-factor authentication OTP code.","documentation_url":"https://developer.github.com/v3/auth#working-with-two-factor-authentication"};
var NOCK_BODY_BAD_TOKEN_EXISTS = {"message":"Validation Failed","documentation_url":"https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization","errors":[{"resource":"OauthAccess","code":"already_exists","field":"description"}]};

// BODY RESULTS
var NOCK_BODY_TOKEN = {"id":9999999,"url":"https://api.github.com/authorizations/9999999","app":{"name":"test","url":"https://developer.github.com/v3/oauth_authorizations/","client_id":"00000000000000000000"},"token":"abcdefghijklmnopqrstuvwxyzabcdefghijklmn","note":"test","note_url":"","created_at":"1970-01-01T00:00:00Z","updated_at":"1970-01-01T00:00:00Z","scopes":[]};
var NOCK_BODY_EMPTY_AUTHORIZATIONS = [];
var NOCK_BODY_ALL_AUTHORIZATIONS = [NOCK_BODY_TOKEN];

// HEADERS
var DEFAULT_HEADERS = {
    server: 'GitHub.com',
    date: 'Wed, 02 Jul 2014 00:00:00 GMT',
    'content-type': 'application/json; charset=utf-8',
    'x-github-media-type': 'github.beta; format=json',
    'x-ratelimit-reset': '1404343458',
    'x-xss-protection': '1; mode=block',
    'x-frame-options': 'deny',
    'content-security-policy': 'default-src \'none\'',
    'content-length': '160',
    'access-control-allow-credentials': 'true',
    'access-control-expose-headers': 'ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval',
    'access-control-allow-origin': '*',
    'x-github-request-id': '00000000:0000:000000:00000000',
    'strict-transport-security': 'max-age=31536000; includeSubdomains',
    'x-content-type-options': 'nosniff'
};
var RATELIMIT_NO2FA = {
    'x-ratelimit-limit': '60',
    'x-ratelimit-remaining': '59'
};
var RATELIMIT_HAS2FA = {
    'x-ratelimit-limit': '5000',
    'x-ratelimit-remaining': '4999'
};
var RESULT_HEADERS = {
    'cache-control': 'private, max-age=60, s-maxage=60',
    etag: '"abcdefghijklmnopqrstuvwxyzabcdef"',
    vary: 'Accept, Authorization, Cookie, X-GitHub-OTP'
};

var NOCK_HEADERS_BAD_USERPASS = _.defaults({
    status: '401 Unauthorized'
}, RATELIMIT_NO2FA, DEFAULT_HEADERS);

var NOCK_HEADERS_BAD_2FA = _.defaults({
    'x-github-otp': 'required; app'
}, NOCK_HEADERS_BAD_USERPASS);

var NOCK_HEADERS_BAD_TOKEN_EXISTS = _.defaults({
    status: '422 Unprocessable Entity'
}, RATELIMIT_HAS2FA, DEFAULT_HEADERS);

var NOCK_HEADERS_CREATED = _.defaults({
    status: '201 Created',
    location: 'https://api.github.com/authorizations/9999999'
}, RATELIMIT_HAS2FA, RESULT_HEADERS, DEFAULT_HEADERS);

var NOCK_HEADERS_ALL_AUTHORIZATIONS = _.defaults({
    status: '200 OK',
    'x-served-by': 'abcdefghijklmnopqrstuvwxyzabcdef'
}, RESULT_HEADERS, DEFAULT_HEADERS);
var NOCK_HEADERS_ALL_AUTHORIZATIONS_NO2FA = _.defaults({}, RATELIMIT_NO2FA);
var NOCK_HEADERS_ALL_AUTHORIZATIONS_HAS2FA = _.defaults({}, RATELIMIT_HAS2FA);

var NOCK_HEADERS_EMPTY_AUTHORIZATIONS = _.defaults({
    link: '<https://api.github.com/authorizations?page=0>; rel="last"'
}, NOCK_HEADERS_ALL_AUTHORIZATIONS);
var NOCK_HEADERS_EMPTY_AUTHORIZATIONS_NO2FA = _.defaults({}, RATELIMIT_NO2FA);
var NOCK_HEADERS_EMPTY_AUTHORIZATIONS_HAS2FA = _.defaults({}, RATELIMIT_HAS2FA);

// B A D
// Bad no 2FA: test auth
function testAuthNo2FABad () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            401,
            NOCK_BODY_BAD_USERPASS,
            NOCK_HEADERS_BAD_USERPASS
        );
}
// Bad has 2FA: test auth
function testAuthHas2FABad () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            401,
            NOCK_BODY_BAD_2FA,
            NOCK_HEADERS_BAD_2FA
        );
}
// Bad no 2FA: make new token
function makeNewNo2FABad () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            401,
            NOCK_BODY_BAD_USERPASS,
            NOCK_HEADERS_BAD_USERPASS
        );
}
// Bad has 2FA: make new token
function makeNewHas2FABad () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            401,
            NOCK_BODY_BAD_2FA,
            NOCK_HEADERS_BAD_2FA
        );
}

// G O O D
// Good no 2FA: test auth
function testAuthNo2FAGood () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            200,
            NOCK_BODY_EMPTY_AUTHORIZATIONS,
            NOCK_HEADERS_EMPTY_AUTHORIZATIONS_NO2FA
        );
}
// Good has 2FA: test auth
function testAuthHas2FAGood () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            401,
            NOCK_BODY_BAD_2FA,
            NOCK_HEADERS_BAD_2FA
        );
}
// Good no 2FA: make new token
function makeNewNo2FAGood () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            201,
            NOCK_BODY_TOKEN,
            NOCK_HEADERS_CREATED
        );
}
// Good has 2FA: make new token
function makeNewHas2FAGood () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            201,
            NOCK_BODY_TOKEN,
            NOCK_HEADERS_CREATED
        );
}
// Good no 2FA: make new token, already exists
function makeNewExistsNo2FAGood () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            422,
            NOCK_BODY_BAD_TOKEN_EXISTS,
            NOCK_HEADERS_BAD_TOKEN_EXISTS
        );
}
// Good has 2FA: make new token, already exists
function makeNewExistsHas2FAGood () {
    this.nock(NOCK_API_URL)
        .post(NOCK_API_ENDPOINT, NOCK_POST_TEST)
        .reply(
            422,
            NOCK_BODY_BAD_TOKEN_EXISTS,
            NOCK_HEADERS_BAD_TOKEN_EXISTS
        );
}
// Good no 2FA: get existing token (gets all tokens)
function getExistingNo2FAGood () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            200,
            NOCK_BODY_ALL_AUTHORIZATIONS,
            NOCK_HEADERS_ALL_AUTHORIZATIONS_NO2FA
        );
}
// Good has 2FA: get existing token (gets all tokens)
function getExistingHas2FAGood () {
    this.nock(NOCK_API_URL)
        .get(NOCK_API_ENDPOINT)
        .reply(
            200,
            NOCK_BODY_ALL_AUTHORIZATIONS,
            NOCK_HEADERS_ALL_AUTHORIZATIONS_HAS2FA
        );
}

// - - - G E T T E R S - - -

var responses = {
    testAuth: {
        no2FA: {
            good: testAuthNo2FAGood,
            bad: testAuthNo2FABad
        },
        has2FA: {
            good: testAuthHas2FAGood,
            bad: testAuthHas2FABad
        }
    },
    makeNew: {
        no2FA: {
            good: makeNewNo2FAGood,
            bad: makeNewNo2FABad
        },
        has2FA: {
            good: makeNewHas2FAGood,
            bad: makeNewHas2FABad
        }
    },
    makeNewExists: {
        no2FA: {
            good: makeNewExistsNo2FAGood
        },
        has2FA: {
            good: makeNewExistsHas2FAGood
        }
    },
    getExisting: {
        no2FA: {
            good: getExistingNo2FAGood
        },
        has2FA: {
            good: getExistingHas2FAGood
        }
    }
};

function ApiResponse (nock) {
    var self = this;
    function createPrototype (obj, methods) {
        var _ = require('lodash');
        _.each(methods, function (method, name) {
            if (!_.isFunction(method)) {
                obj[name] = {};
                createPrototype(obj[name], method);
            } else {
                obj[name] = _.bind(method, self);
            }
        });
    }
    createPrototype(this, responses);
    this.nock = nock;
    return this;
}

module.exports = function main (nock) {
    return new ApiResponse(nock);
};
<|endoftext|>


<commit_before>module.exports.name = "builder";
module.exports.run = function(creep) {
    // if no energy, get energy.
    var target = Game.getObjectById(creep.memory.target_id);
    // if no target, then the planners messed up.

    var mode = creep.memory.build_mode;
    var rc;
    if(mode == "build") {
        rc = creep.build(target);
    } else if(mode == "repair") {
        rc = creep.repair(target);
    } else {
        console.log(creep.name + " - bad builder mode - " + mode);
        return;
    }

    if(rc == ERR_NOT_IN_RANGE)
        creep.moveTo(target);
};
<commit_msg>Minor modifications to the builder role<commit_after>module.exports.name = "builder";
module.exports.run = function(creep) {
    // if no energy, get energy.
    var target = Game.getObjectById(creep.memory.target_id);
    // if no target, then the planners messed up.
    if(!target) {
        creep.memory.idle = true;
        return;
    }

    var rc;
    if(target.progressTotal) {
        rc = creep.build(target);
    } else if(target.hitsMax) {
        rc = creep.repair(target);
    } else {
        console.log(creep.name + " - bad builder target - " + target);
        return;
    }

    if(rc == ERR_NOT_IN_RANGE)
        creep.moveTo(target);
};
<|endoftext|>


<commit_before>const assert = require('assert');
const _ = require('lodash');
const { ScreepsAPI } = require('../');
const auth = require('./credentials')

describe('api.raw.user', function() {

  this.slow(2000);

  describe('.badge (badge)', function() {
    it('should do untested things (for now)')
  })

  describe('.respawn ()', function() {
    it('should do untested things (for now)')
  })

  describe('.setActiveBranch (branch, activeName)', function() {
    it('should do untested things (for now)')
  })

  describe('.cloneBranch (branch, newName, defaultModules)', function() {
    it('should do untested things (for now)')
  })

  describe('.deleteBranch (branch)', function() {
    it('should do untested things (for now)')
  })

  describe('.notifyPrefs (prefs)', function() {
    it('should do untested things (for now)')
  })

  describe('.tutorialDone ()', function() {
    it('should do untested things (for now)')
  })

  describe('.email (email)', function() {
    it('should do untested things (for now)')
  })

  describe('.worldStartRoom (shard)', function() {
    it('should do untested things (for now)')
  })

  describe('.worldStatus ()', function() {
    it('should do untested things (for now)')
  })

  describe('.branches ()', function() {
    it('should do untested things (for now)')
  })

  describe('.code.get (branch)', function() {
    it('should do untested things (for now)')
  })

  describe('.code.set (branch, modules, _hash)', function() {
    it('should do untested things (for now)')
  })

  describe('.respawnProhibitedRooms ()', function() {
    it('should do untested things (for now)')
  })

  describe('.memory.get (path, shard = DEFAULT_SHARD)', function() {
    it('should do untested things (for now)')
  })

  describe('.memory.set (path, value, shard = DEFAULT_SHARD)', function() {
    it('should do untested things (for now)')
  })

  describe('.segment.get (segment, shard = DEFAULT_SHARD)', function() {
    it('should do untested things (for now)')
  })

  describe('.segment.set (segment, data, shard = DEFAULT_SHARD)', function() {
    it('should do untested things (for now)')
  })

  describe('.find (username)', function() {
    it('should do untested things (for now)')
  })

  describe('.findById (id)', function() {
    it('should do untested things (for now)')
  })

  describe('.stats (interval)', function() {
    it('should do untested things (for now)')
  })

  describe('.rooms (id)', function() {
    it('should do untested things (for now)')
  })

  describe('.overview (interval, statName)', function() {
    it('should do untested things (for now)')
  })

  describe('.moneyHistory (page = 0)', function() {
    it('should do untested things (for now)')
  })

  describe('.console (expression, shard = DEFAULT_SHARD)', function() {
    it('should do untested things (for now)')
  })

})<commit_msg>Added api.raw.user.badge() test.<commit_after>const assert = require('assert');
const _ = require('lodash');
const { ScreepsAPI } = require('../');
const auth = require('./credentials')

describe('api.raw.user', function() {

  this.slow(2000);

  describe('.badge (badge)', function() {
    it('should send a request to /api/user/badge which sets user badge',  async function() {
      let opts = _.omit(auth, ['email', 'password'])
      let api = new ScreepsAPI(opts)
      await api.auth(auth.email, auth.password)
      // Save previous badge
      let res = await api.me()
      let initialBadge = res.badge
      // Set new badge
      let newBadge = { type: 16, color1: '#000000', color2: '#000000', color3:'#000000', param: 100, flip: false }
      res = await api.raw.user.badge(newBadge)
      assert.equal(res.ok, 1, 'incorrect server response: ok should be 1')
      // Check that badge was effectively changed
      res = await api.me()
      _.each(res.badge, (value, key) => {
        assert.equal(value, newBadge[key], `badge ${key} is incorrect`)
      })
      // Reset badge
      res = await api.raw.user.badge(initialBadge)
    })
  })

  describe('.respawn ()', function() {
    it('should do untested things (for now)')
  })

  describe('.setActiveBranch (branch, activeName)', function() {
    it('should do untested things (for now)')
  })

  describe('.cloneBranch (branch, newName, defaultModules)', function() {
    it('should do untested things (for now)')
  })

  describe('.deleteBranch (branch)', function() {
    it('should do untested things (for now)')
  })

  describe('.notifyPrefs (prefs)', function() {
    it('should do untested things (for now)')
  })

  describe('.tutorialDone ()', function() {
    it('should do untested things (for now)')
  })

  describe('.email (email)', function() {
    it('should do untested things (for now)')
  })

  describe('.worldStartRoom (shard)', function() {
    it('should do untested things (for now)')
  })

  describe('.worldStatus ()', function() {
    it('should do untested things (for now)')
  })

  describe('.branches ()', function() {
    it('should do untested things (for now)')
  })

  describe('.code.get (branch)', function() {
    it('should do untested things (for now)')
  })

  describe('.code.set (branch, modules, _hash)', function() {
    it('should do untested things (for now)')
  })

  describe('.respawnProhibitedRooms ()', function() {
    it('should do untested things (for now)')
  })

  describe('.memory.get (path, shard = DEFAULT_SHARD)', function() {
    it('should do untested things (for now)')
  })

  describe('.memory.set (path, value, shard = DEFAULT_SHARD)', function() {
    it('should do untested things (for now)')
  })

  describe('.segment.get (segment, shard = DEFAULT_SHARD)', function() {
    it('should do untested things (for now)')
  })

  describe('.segment.set (segment, data, shard = DEFAULT_SHARD)', function() {
    it('should do untested things (for now)')
  })

  describe('.find (username)', function() {
    it('should do untested things (for now)')
  })

  describe('.findById (id)', function() {
    it('should do untested things (for now)')
  })

  describe('.stats (interval)', function() {
    it('should do untested things (for now)')
  })

  describe('.rooms (id)', function() {
    it('should do untested things (for now)')
  })

  describe('.overview (interval, statName)', function() {
    it('should do untested things (for now)')
  })

  describe('.moneyHistory (page = 0)', function() {
    it('should do untested things (for now)')
  })

  describe('.console (expression, shard = DEFAULT_SHARD)', function() {
    it('should do untested things (for now)')
  })

})<|endoftext|>


<commit_before>import * as ajax from './ajax';

class RouterConfig {
  constructor() {
    this.module = null;
    /**
     * @property {object} publicKey
     * @property {string} publicKey.n
     * @property {string} publicKey.e
     */
    this.encryption = {
      publicKey: null,
    };
  }
}

let config = new RouterConfig();

/*
'autoapn_enabled': g_feature.autoapn_enabled === '1',
'checklogin_enabled': g_feature.login === '1',
'ap_station_enabled': g_feature.ap_station_enabled === '1',
'voip_adcance_enable': voiceadvancesetting === '1',
*/

/**
 * @typedef ConfigModuleSwitch
 * @property {string} ussd_enabled
 * @property {string} bbou_enabled
 * @property {string} sms_enabled
 * @property {string} sdcard_enabled
 * @property {string} wifi_enabled
 * @property {string} statistic_enabled
 * @property {string} help_enabled
 * @property {string} stk_enabled
 * @property {string} pb_enabled
 * @property {string} dlna_enabled
 * @property {string} ota_enabled
 * @property {string} wifioffload_enabled
 * @property {string} cradle_enabled
 * @property {string} multssid_enable
 * @property {string} ipv6_enabled
 * @property {string} monthly_volume_enabled
 * @property {string} powersave_enabled
 * @property {string} sntp_enabled
 * @property {string} encrypt_enabled
 * @property {string} dataswitch_enabled
 * @property {string} ddns_enabled
 * @property {string} sambashare_enabled
 * @property {string} poweroff_enabled
 * @property {string} fw_macfilter_enabled
 * @property {string} ecomode_enabled
 * @property {string} zonetime_enabled
 * @property {string} diagnosis_enabled
 * @property {string} localupdate_enabled
 * @property {string} cbs_enabled
 * @property {string} voip_enabled
 * @property {string} qrcode_enabled
 * @property {string} charger_enbaled
 * @property {string} vpn_enabled
 * @property {string} cs_enable
 * @property {string} tr069_enabled
 * @property {string} antenna_enabled
 * @property {string} aclui_enabled
 * @property {string} static_route_enabled
 * @property {string} static_route6_enabled
 * @property {string} loginusername_enable
 */

/**
  * @return {Promise<ConfigModuleSwitch>}
  */
function _getModuleSwitch() {
  return ajax.getAjaxData({url: 'api/global/module-switch'});
}

/**
 * @typedef ConfigModuleSwitchBoolean
 * @property {boolean} ussd_enabled
 * @property {boolean} bbou_enabled
 * @property {boolean} sms_enabled
 * @property {boolean} sdcard_enabled
 * @property {boolean} wifi_enabled
 * @property {boolean} statistic_enabled
 * @property {boolean} help_enabled
 * @property {boolean} stk_enabled
 * @property {boolean} pb_enabled
 * @property {boolean} dlna_enabled
 * @property {boolean} ota_enabled
 * @property {boolean} wifioffload_enabled
 * @property {boolean} cradle_enabled
 * @property {boolean} multssid_enable
 * @property {boolean} ipv6_enabled
 * @property {boolean} monthly_volume_enabled
 * @property {boolean} powersave_enabled
 * @property {boolean} sntp_enabled
 * @property {boolean} encrypt_enabled
 * @property {boolean} dataswitch_enabled
 * @property {boolean} ddns_enabled
 * @property {boolean} sambashare_enabled
 * @property {boolean} poweroff_enabled
 * @property {boolean} fw_macfilter_enabled
 * @property {boolean} ecomode_enabled
 * @property {boolean} zonetime_enabled
 * @property {boolean} diagnosis_enabled
 * @property {boolean} localupdate_enabled
 * @property {boolean} cbs_enabled
 * @property {boolean} voip_enabled
 * @property {boolean} qrcode_enabled
 * @property {boolean} charger_enbaled
 * @property {boolean} vpn_enabled
 * @property {boolean} cs_enable
 * @property {boolean} tr069_enabled
 * @property {boolean} antenna_enabled
 * @property {boolean} aclui_enabled
 * @property {boolean} static_route_enabled
 * @property {boolean} static_route6_enabled
 * @property {boolean} loginusername_enable
 */

/**
  * @return {Promise<ConfigModuleSwitchBoolean>}
  */
export function getModuleSwitch() {
  if (!config.module) {
    return _getModuleSwitch().then((data) => {
      config.module = {};
      for (let key in data) {
        if (Object.prototype.hasOwnProperty.call(data, key)) {
          config.module[key] = data[key] === '1';
        }
      }
      return config.module;
    });
  } else {
    return Promise.resolve(config.module);
  }
}

/**
 * @typedef ApiWebserverPublicKey
 * @property {string} encpubkeyn
 * @property {string} encpubkeye
 */

/**
 * @return {Promise<ApiWebserverPublicKey>}
 */
function _getPublicEncryptionKey() {
  return ajax.getAjaxData({url: 'api/webserver/publickey'});
}

export function getPublicEncryptionKey() {
  if (!config.encryption.publicKey) {
    return _getPublicEncryptionKey().then((data) => {
      config.encryption.publicKey = {};
      config.encryption.publicKey.n = data.encpubkeyn;
      config.encryption.publicKey.e = data.encpubkeye;
      return config.encryption.publicKey;
    });
  } else {
    return config.encryption.publicKey;
  }
}
<commit_msg>Fix not returning promise bug<commit_after>import * as ajax from './ajax';

class RouterConfig {
  constructor() {
    this.module = null;
    /**
     * @property {object} publicKey
     * @property {string} publicKey.n
     * @property {string} publicKey.e
     */
    this.encryption = {
      publicKey: null,
    };
  }
}

let config = new RouterConfig();

/*
'autoapn_enabled': g_feature.autoapn_enabled === '1',
'checklogin_enabled': g_feature.login === '1',
'ap_station_enabled': g_feature.ap_station_enabled === '1',
'voip_adcance_enable': voiceadvancesetting === '1',
*/

/**
 * @typedef ConfigModuleSwitch
 * @property {string} ussd_enabled
 * @property {string} bbou_enabled
 * @property {string} sms_enabled
 * @property {string} sdcard_enabled
 * @property {string} wifi_enabled
 * @property {string} statistic_enabled
 * @property {string} help_enabled
 * @property {string} stk_enabled
 * @property {string} pb_enabled
 * @property {string} dlna_enabled
 * @property {string} ota_enabled
 * @property {string} wifioffload_enabled
 * @property {string} cradle_enabled
 * @property {string} multssid_enable
 * @property {string} ipv6_enabled
 * @property {string} monthly_volume_enabled
 * @property {string} powersave_enabled
 * @property {string} sntp_enabled
 * @property {string} encrypt_enabled
 * @property {string} dataswitch_enabled
 * @property {string} ddns_enabled
 * @property {string} sambashare_enabled
 * @property {string} poweroff_enabled
 * @property {string} fw_macfilter_enabled
 * @property {string} ecomode_enabled
 * @property {string} zonetime_enabled
 * @property {string} diagnosis_enabled
 * @property {string} localupdate_enabled
 * @property {string} cbs_enabled
 * @property {string} voip_enabled
 * @property {string} qrcode_enabled
 * @property {string} charger_enbaled
 * @property {string} vpn_enabled
 * @property {string} cs_enable
 * @property {string} tr069_enabled
 * @property {string} antenna_enabled
 * @property {string} aclui_enabled
 * @property {string} static_route_enabled
 * @property {string} static_route6_enabled
 * @property {string} loginusername_enable
 */

/**
  * @return {Promise<ConfigModuleSwitch>}
  */
function _getModuleSwitch() {
  return ajax.getAjaxData({url: 'api/global/module-switch'});
}

/**
 * @typedef ConfigModuleSwitchBoolean
 * @property {boolean} ussd_enabled
 * @property {boolean} bbou_enabled
 * @property {boolean} sms_enabled
 * @property {boolean} sdcard_enabled
 * @property {boolean} wifi_enabled
 * @property {boolean} statistic_enabled
 * @property {boolean} help_enabled
 * @property {boolean} stk_enabled
 * @property {boolean} pb_enabled
 * @property {boolean} dlna_enabled
 * @property {boolean} ota_enabled
 * @property {boolean} wifioffload_enabled
 * @property {boolean} cradle_enabled
 * @property {boolean} multssid_enable
 * @property {boolean} ipv6_enabled
 * @property {boolean} monthly_volume_enabled
 * @property {boolean} powersave_enabled
 * @property {boolean} sntp_enabled
 * @property {boolean} encrypt_enabled
 * @property {boolean} dataswitch_enabled
 * @property {boolean} ddns_enabled
 * @property {boolean} sambashare_enabled
 * @property {boolean} poweroff_enabled
 * @property {boolean} fw_macfilter_enabled
 * @property {boolean} ecomode_enabled
 * @property {boolean} zonetime_enabled
 * @property {boolean} diagnosis_enabled
 * @property {boolean} localupdate_enabled
 * @property {boolean} cbs_enabled
 * @property {boolean} voip_enabled
 * @property {boolean} qrcode_enabled
 * @property {boolean} charger_enbaled
 * @property {boolean} vpn_enabled
 * @property {boolean} cs_enable
 * @property {boolean} tr069_enabled
 * @property {boolean} antenna_enabled
 * @property {boolean} aclui_enabled
 * @property {boolean} static_route_enabled
 * @property {boolean} static_route6_enabled
 * @property {boolean} loginusername_enable
 */

/**
  * @return {Promise<ConfigModuleSwitchBoolean>}
  */
export function getModuleSwitch() {
  if (!config.module) {
    return _getModuleSwitch().then((data) => {
      config.module = {};
      for (let key in data) {
        if (Object.prototype.hasOwnProperty.call(data, key)) {
          config.module[key] = data[key] === '1';
        }
      }
      return config.module;
    });
  } else {
    return Promise.resolve(config.module);
  }
}

/**
 * @typedef ApiWebserverPublicKey
 * @property {string} encpubkeyn
 * @property {string} encpubkeye
 */

/**
 * @return {Promise<ApiWebserverPublicKey>}
 */
function _getPublicEncryptionKey() {
  return ajax.getAjaxData({url: 'api/webserver/publickey'});
}

export function getPublicEncryptionKey() {
  if (!config.encryption.publicKey) {
    return _getPublicEncryptionKey().then((data) => {
      config.encryption.publicKey = {};
      config.encryption.publicKey.n = data.encpubkeyn;
      config.encryption.publicKey.e = data.encpubkeye;
      return config.encryption.publicKey;
    });
  } else {
    return Promise.resolve(config.encryption.publicKey);
  }
}
<|endoftext|>


<commit_before>/* jshint node: true */
/**
 * Wake Up Platform
 * (c) Telefonica Digital, 2013 - All rights reserved
 * License: GNU Affero V3 (see LICENSE file)
 * Fernando Rodríguez Sela <frsela@tid.es>
 */

module.exports.info = {
  name: 'aboutRouter',
  type: 'router',
  virtualpath: 'about',
  alias: [
    ''            // No path => default router
  ],
  description: 'This module shows the about page to the client'
};

module.exports.entrypoint = function router_about(parsedURL, body, req, res) {
  res.setHeader('Content-Type', 'text/html;charset=UTF-8');
  res.statusCode = 200;
  res.write('');
  res.write(
    '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">');
  res.write('');
  res.write('
WakeUp mobile platform
');
  res.write('
Global node ' + process.configuration._version + '
');
  res.write('© Telefónica Digital, 2013
');
  res.write('');
};
<commit_msg>Updated about page (copyright information)<commit_after>/* jshint node: true */
/**
 * Wake Up Platform
 * (c) Telefonica Digital, 2013 - All rights reserved
 * License: GNU Affero V3 (see LICENSE file)
 * Fernando Rodríguez Sela <frsela@tid.es>
 */

module.exports.info = {
  name: 'aboutRouter',
  type: 'router',
  virtualpath: 'about',
  alias: [
    ''            // No path => default router
  ],
  description: 'This module shows the about page to the client'
};

module.exports.entrypoint = function router_about(parsedURL, body, req, res) {
  res.setHeader('Content-Type', 'text/html;charset=UTF-8');
  res.statusCode = 200;
  res.write('');
  res.write(
    '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">');
  res.write('');
  res.write('
WakeUp mobile platform
');
  res.write('
Global node ' + process.configuration._version + '
');
  res.write('© Telefónica Digital, 2014
');
  res.write('');
};
<|endoftext|>


<commit_before>var RaspiCam = require("raspicam");
var debounce = require("debounce");
var cameraConfig = {
	mode : "photo",
	timelapse : 100,
	debounceTime : 500
};

var cameraFilePath = __dirname + "/../public/images/camera/photo/";

exports.photo = function(request, response){
	var name = new Date().getTime() + ".jpg";
	cameraConfig.output = cameraFilePath + name;
	var camera = new RaspiCam(cameraConfig);
	camera.on("change", debounce(camera.stop, cameraConfig.debounceTime));
	camera.on("exit", function(){
		response.send({ message : "Successfully captured image", name : name });
	});
	camera.start();
}<commit_msg>Removed debounce time from the list of options<commit_after>var RaspiCam = require("raspicam");
var debounce = require("debounce");
var cameraConfig = {
	mode : "photo",
	timelapse : 100
};
var debounceTime = 500;

var cameraFilePath = __dirname + "/../public/images/camera/photo/";

exports.photo = function(request, response){
	var name = new Date().getTime() + ".jpg";
	cameraConfig.output = cameraFilePath + name;
	var camera = new RaspiCam(cameraConfig);
	camera.on("change", debounce(camera.stop, debounceTime));
	camera.on("exit", function(){
		response.send({ message : "Successfully captured image", name : name });
	});
	camera.start();
}<|endoftext|>


<commit_before>var test = require('tape');
var shot = require('shot');
var serverFile = require('../server.js');

test("check back end test set-up, 1 equals 1", function(t) {
  t.equal(1, 1, "success!");
  t.end();
});
<commit_msg>more  tests<commit_after>var test = require('tape');
var shot = require('shot');
var serverFile = require('../server.js');

test("check back end test set-up, 1 equals 1", function(t) {
  t.equal(1, 1, "success!");
  t.end();
});
test("server sends a response", function(t) {
  var req = {
    method: "GET",
    url: '/meows'
  };
  shot.inject(serverFile.handler, req, function(res) {

    t.equal(!!res.responseText, true, "success!");
    t.end();
  });
});
<|endoftext|>


<commit_before>var
    jQuery = jQuery,
    DO = DO;

(function ($) {
    "use strict";

	$.fn.extend({
        /*
         * @params = {url, sendData, process}
        */
        autocomplete: function (params, callback) {
            var
                found = [],
                self = $(this),
                domObjText,
                searchIndex,
                prevSliceTextNoSearch,
                sliceFound,
                remainderSliceTextNoSearch,
                spanSliceFound,
                copyng,
                jqObj;

            if (params instanceof jQuery) {
                jqObj = params;

                self.on("keyup", function (e) {

                    jqObj.each(function (i, domObj) {

                        domObjText = domObj.textContent.trim();
                        searchIndex = domObjText.toLowerCase()
                            .search(self.val().toLowerCase());
                        if (searchIndex > -1) {

                            prevSliceTextNoSearch = domObjText
                                .slice(0, searchIndex);

                            sliceFound = domObjText.slice(prevSliceTextNoSearch
                                .length, prevSliceTextNoSearch.length +
                                    self.val().length);

                            remainderSliceTextNoSearch = domObjText
                                .slice(prevSliceTextNoSearch.length +
                                    sliceFound.length, domObjText.length);

                            spanSliceFound = $("");

                            copyng = $(domObj.cloneNode());
                            copyng.append(prevSliceTextNoSearch);
                            copyng.append(spanSliceFound);
                            spanSliceFound.addClass("do-ui-slice-found");
                            spanSliceFound.text(sliceFound);
                            copyng.append(remainderSliceTextNoSearch);

                            found.unshift(copyng);
                        }
                    });

                    if (self.val()) {
                        callback(e, found);
                    } else {
                        callback(e, []);
                    }

                    found = [];
                });
            } else if (params instanceof Object) {
                self.on("keypress", function (e) {
                    params.initRemoteQuery(e, function (a) {
                        if (a instanceof jQuery) {
                            self.off("keypress");
                            self.autocomplete(a, callback);
                        }
                    });
                });
            }
        }

    });

}(jQuery));
<commit_msg>muda nome de chave para melhor legibiidade<commit_after>var
    jQuery = jQuery,
    DO = DO;

(function ($) {
    "use strict";

	$.fn.extend({
        /*
         * @params = {url, sendData, process}
        */
        autocomplete: function (params, callback) {
            var
                found = [],
                self = $(this),
                domObjText,
                searchIndex,
                prevSliceTextNoSearch,
                sliceFound,
                remainderSliceTextNoSearch,
                spanSliceFound,
                copyng,
                jqObj;

            if (params instanceof jQuery) {
                jqObj = params;

                self.on("keyup", function (e) {

                    jqObj.each(function (i, domObj) {

                        domObjText = domObj.textContent.trim();
                        searchIndex = domObjText.toLowerCase()
                            .search(self.val().toLowerCase());
                        if (searchIndex > -1) {

                            prevSliceTextNoSearch = domObjText
                                .slice(0, searchIndex);

                            sliceFound = domObjText.slice(prevSliceTextNoSearch
                                .length, prevSliceTextNoSearch.length +
                                    self.val().length);

                            remainderSliceTextNoSearch = domObjText
                                .slice(prevSliceTextNoSearch.length +
                                    sliceFound.length, domObjText.length);

                            spanSliceFound = $("");

                            copyng = $(domObj.cloneNode());
                            copyng.append(prevSliceTextNoSearch);
                            copyng.append(spanSliceFound);
                            spanSliceFound.addClass("do-ui-slice-found");
                            spanSliceFound.text(sliceFound);
                            copyng.append(remainderSliceTextNoSearch);

                            found.unshift(copyng);
                        }
                    });

                    if (self.val()) {
                        callback(e, found);
                    } else {
                        callback(e, []);
                    }

                    found = [];
                });
            } else if (params instanceof Object) {
                self.on("keypress", function (e) {
                    params.init(e, function (a) {
                        if (a instanceof jQuery) {
                            self.off("keypress");
                            self.autocomplete(a, callback);
                        }
                    });
                });
            }
        }

    });

}(jQuery));
<|endoftext|>


<commit_before>//= require esphinx/support/jquery
//= require esphinx_ui

var
    jQuery,
    esPhinx;

(function ($module) {
    "use strict";

    // $.fn.resolveTabs = function (args) {
    //     var
    //         self = $(this),
    //         container;

    //     if (args) {

    //         resolveTabsNav(self, args);
    //         if (args.selectOnload) {
    //             selectOnload(self);
    //         }

    //         if (args.container) {
    //             container = args.container;
    //             if (container.prop("tagName") !== "UL") {
    //                 container = container.closest("ul");
    //                 args.container = container;
    //             }

    //             container.addClass("esphinx-ui-tabs-container");
    //             container.find("li").addClass("esphinx-ui-tabs-container-option");
    //             resolveTabsContainer(args);
    //             showContentOnload(self, args);
    //         }

    //     }

    //     return self;
    // };

    $module.extend({
        navigators: {
            // function are object in js
            tabs: {
                new: function () {
                    const
                        MODULE_CSS = "esphinx-ui";

                    var
                        $ = jQuery,
                        constructor = $module.navigators.tabs.new,
                        nav,
                        container,
                        opts,
                        args,

                        resolveTabsNav = function (nav, args) {
                            var
                                parent,
                                tabs,
                                tab,
                                anchor;

                            parent = nav.closest("div");
                            nav.addClass(MODULE_CSS + "-tabs-nav");

                            if (args) {
                                if (args.selectOnload) {
                                    nav.addClass(MODULE_CSS + "-tabs-select-in-loading");
                                }
                            } else {
                                throw new Error("2 arguments required.");
                            }

                            tabs = nav.find("li");
                            tabs.each(function (i, o) {
                                tab = $(o);
                                anchor = tab.find("a");
                                if (!anchor.length) {
                                    anchor = $("");
                                    anchor.append(tab.text().trim());
                                    tab.empty();
                                    tab.append(anchor);
                                }
                                anchor.attr("id", MODULE_CSS + "-tab-nav-" + (i + 1));
                                anchor.attr("href", "#" + anchor.attr("id"));
                            });
                            if (!args.selectOnload) {
                                nav.find("a:first").removeAttr("href");
                            }
                        },

                        resolveTabsContainer = function (args) {
                            var
                                items = args.container
                                    .find("li." + MODULE_CSS + "-tabs-container-option"),
                                li;
                            items.each(function (i, o) {
                                li = $(o);
                                li.attr("data-parent-tab", MODULE_CSS + "-tab-nav-" + (i + 1));
                            });
                        },

                        selectTab = function (handle) {
                            var
                                tabs,
                                tabSelected,
                                target;

                            debugger
                            if (handle instanceof jQuery.Event) {
                                target = $(handle.target);
                                if (handle.type === "click") {
                                    if (target.closest("ul")
                                        .is(MODULE_CSS + "." + MODULE_CSS + "-ui-tabs-select-in-loading")) {
                                        location.hash = target.attr("id");
                                    }
                                }
                            } else {
                                target = handle;
                            }

                            tabs = target.closest("ul").find("li");

                            tabSelected = tabs.findWithoutAttr("a", "href");

                            if (tabSelected.length) {
                                tabSelected.attr("href", location.hash);
                            }

                            tabs.find("a").removeClass(MODULE_CSS + "-tab-selected");
                            target.addClass(MODULE_CSS + "-tab-selected");

                            target.removeAttr("href");
                        },

                        // showContent = function (handle, args) {
                        showContent = function (handle) {
                            var
                                target = $(handle.target),
                                id = target.attr("id"),
                                nav = target.closest("ul"),
                                container = nav.siblings("." + MODULE_CSS + "-ui-tabs-container");

                            container.find("li." + MODULE_CSS + "-tabs-container-option").hide();
                            container.find("[data-parent-tab='" + id + "']").show();
                        },

                        selectOnload = function (nav) {
                            var
                                URLHash = location.hash,
                                href,
                                anchor;

                            if (URLHash) {
                                selectTab(nav.findByAttr("a", "href", URLHash));
                            } else {
                                href = location.pathname.match(/[a-z\/\_\-]+[a-z]+/);
                                anchor = nav.findWithoutAttr("a", "href");
                                if (anchor.length) {
                                    selectTab(nav.findByAttr("a", "href", URLHash));
                                } else {
                                    selectTab(nav.find("a:first"));
                                }
                            }
                        },

                        showContentOnload = function (nav, args) {
                            var
                                id = nav.findWithoutAttr("a", "href").attr("id");

                            args.container.find("li." + MODULE_CSS + "-tabs-container-option").hide();
                            args.container.find("[data-parent-tab='" + id + "']").show();

                            // selected = container.find("li.#{tabAnchor.attr("class")}")
                            // selected = container.find("li#{tabAnchor.attr("href")}")
                            //  if selected.length == 0
                            //    url = $(this).data("url")
                            //    if url
                            //      content = $("

").addClass tabAnchor.attr("class")
                            //      container.append content

                            //      format = $(this).data("format")
                            //      if !format
                            //        format = "js"

                            //      $.get url, {format: format},
                            //        (data, status, xhr)->
                            //          if format == "html"
                            //            content.html data
                        },

                        resolveTabs = function (nav, container, opts) {
                            if (opts) {
                                resolveTabsNav(nav, opts);
                                if (opts.selectOnload) {
                                    selectOnload(nav);
                                }

                                if (container) {
                                    if (container.prop("tagName") !== "UL") {
                                        container = container.closest("ul");
                                        // parece que o container é usado em outro lugar, por isso foi mudado aqui
                                        // opts.container = container;
                                    }

                                    container
                                        .addClass(MODULE_CSS + "-tabs-container");
                                    container.find("li").addClass(MODULE_CSS + "-tabs-container-option");
                                    resolveTabsContainer(opts);
                                    showContentOnload(self, opts);
                                }

                            }

                            return self;
                        };

                    if (!(this instanceof constructor)) {
                        return new constructor(arguments);
                    } else {
                        args = arguments.flatten();
                        nav = args[0];
                        container = args[1];
                        if (args[2]) {
                            resolveTabs(args[2]);
                        }
                        resolveTabs(nav, container, opts);
                    }

                    this.select = function (e) {
                        selectTab(e);
                        showContent(e);
                        // showContent(e, args);
                        // selectTab(e, args);
                    }
                }
            }
        }
    });

}(esPhinx.ui));
<commit_msg>partially fixes code<commit_after>//= require esphinx/support/jquery
//= require esphinx_ui

var
    jQuery,
    esPhinx;

(function ($module) {
    "use strict";

    $module.extend({
        navigators: {
            tabs: {
                new: function () {
                    const
                        MODULE_CSS = "esphinx-ui";

                    var
                        $ = jQuery,
                        constructor = $module.navigators.tabs.new,
                        nav,
                        container,
                        opts,
                        args,

                        resolveTabsNav = function () {
                            var
                                parent,
                                tabs,
                                tab,
                                anchor;

                            parent = nav.closest("div");
                            nav.addClass(MODULE_CSS + "-tabs-nav");

                            if (opts) {
                                if (opts.selectOnload) {
                                    nav.addClass(MODULE_CSS + "-tabs-select-in-loading");
                                }
                            } else {
                                throw new Error("2 arguments required.");
                            }

                            tabs = nav.find("li");
                            tabs.each(function (i, o) {
                                tab = $(o);
                                anchor = tab.find("a");
                                if (!anchor.length) {
                                    anchor = $("");
                                    anchor.append(tab.text().trim());
                                    tab.empty();
                                    tab.append(anchor);
                                }
                                anchor.attr("id", MODULE_CSS + "-tab-nav-" + (i + 1));
                                anchor.attr("href", "#" + anchor.attr("id"));
                            });

                            if (!opts.selectOnload) {
                                nav.find("a:first").removeAttr("href");
                            }
                        },

                        resolveTabsContainer = function () {
                            var
                                items = container
                                    .find("li." + MODULE_CSS + "-tabs-container-option"),
                                li;

                            items.each(function (i, o) {
                                li = $(o);
                                li.attr("data-nav", MODULE_CSS + "-tab-nav-" + (i + 1));
                            });
                        },

                        selectOnload = function (nav) {
                            var
                                URLHash = location.hash,
                                href,
                                anchor;

                            if (URLHash) {
                                selectTab(nav.findByAttr("a", "href", URLHash));
                            } else {
                                href = location.pathname.match(/[a-z\/\_\-]+[a-z]+/);
                                anchor = nav.findWithoutAttr("a", "href");
                                if (anchor.length) {
                                    selectTab(nav.findByAttr("a", "href", URLHash));
                                } else {
                                    selectTab(nav.find("a:first"));
                                }
                            }
                        },

                        showContentOnload = function (nav, args) {
                            var
                                id = nav.findWithoutAttr("a", "href").attr("id");

                            container.find("li." + MODULE_CSS + "-tabs-container-option").hide();
                            container.find("[data-nav='" + id + "']").show();

                            // selected = container.find("li.#{tabAnchor.attr("class")}")
                            // selected = container.find("li#{tabAnchor.attr("href")}")
                            //  if selected.length == 0
                            //    url = $(this).data("url")
                            //    if url
                            //      content = $("

").addClass tabAnchor.attr("class")
                            //      container.append content

                            //      format = $(this).data("format")
                            //      if !format
                            //        format = "js"

                            //      $.get url, {format: format},
                            //        (data, status, xhr)->
                            //          if format == "html"
                            //            content.html data
                        },

                        resolveTabs = function () {
                            if (opts) {
                                resolveTabsNav(nav, opts);
                                if (opts.selectOnload) {
                                    selectOnload(nav);
                                }

                                if (container) {
                                    if (container.prop("tagName") !== "UL") {
                                        // debugger
                                        container = container.closest("ul");
                                    }

                                    container
                                        .addClass(MODULE_CSS + "-tabs-container");
                                    container.find("li").addClass(MODULE_CSS + "-tabs-container-option");
                                    resolveTabsContainer(opts);
                                    showContentOnload(nav, opts);
                                }

                            }
                        },

                        showContent = function (e) {
                            var
                                target = $(e.target),
                                id = target.attr("id");

                            container.find("li." + MODULE_CSS + "-tabs-container-option").hide();
                            container.find("[data-nav='" + id + "']").show();
                        },

                        selectTab = function (handle) {
                            var
                                tabs,
                                tabSelected,
                                target;

                            if (handle instanceof jQuery.Event) {
                                target = $(handle.target);
                                if (handle.type === "click") {
                                    if (target.closest("ul")
                                        .is("." + MODULE_CSS + "-tabs-select-in-loading")) {
                                        location.hash = target.attr("id");
                                    }
                                }
                            } else {
                                target = handle;
                            }

                            tabs = target.closest("ul").find("li");

                            tabSelected = tabs.findWithoutAttr("a", "href");

                            if (tabSelected.length) {
                                tabSelected.attr("href", location.hash);
                            }

                            tabs.find("a")
                                .removeClass(MODULE_CSS + "-tab-selected");
                            target.addClass(MODULE_CSS + "-tab-selected");

                            target.removeAttr("href");
                        };

                    if (!(this instanceof constructor)) {
                        return new constructor(arguments);
                    } else {
                        args = arguments.flatten();
                        nav = args[0];
                        container = args[1];
                        if (args[2]) {
                            opts = args[2];
                        }

                        resolveTabs();
                    }

                    this.select = function (e) {
                        selectTab(e);
                        showContent(e);
                    }
                }
            }
        }
    });

}(esPhinx.ui));
<|endoftext|>


<commit_before>var sys = require("sys");
var ansi = require("buster-test/lib/buster-test/ansi-out");

module.exports = {
    create: function (opt) {
        var reporter = Object.create(this);
        reporter.ansi = ansi.create(opt);
        reporter.list = reporter.ansi.labeledList(opt && opt.io);

        return reporter;
    },

    listen: function (runner) {
        runner.bind(this, {
            "progress:test:success": "testSuccess",
            "progress:test:error": "testError",
            "progress:test:failure": "testFailure",
            "progress:test:timeout": "testTimeout"
        });

        return this;
    },

    testSuccess: function (test) {
        this.print(test.client, this.ansi.green("."));
    },

    testError: function (test) {
        this.print(test.client, this.ansi.yellow("E"));
    },

    testFailure: function (test) {
        this.print(test.client, this.ansi.red("F"));
    },

    testTimeout: function (test) {
        this.print(test.client, this.ansi.red("T"));
    },

    displayProgress: function (client, output) {
        if (!this.list) {
            return this.bufferOutput(client, output);
        }

        this.print(client, output);
    },

    print: function (client, output) {
        this.list.print(this.clients[client.id], output);
    },

    addClient: function (clientId, agent) {
        this.clients = this.clients || {};
        var agentStr = agent.toString();
        this.clients[clientId] = agentStr;
        this.list.add(agentStr);
    }
};
<commit_msg>Use buster-terminal for string formatting<commit_after>var sys = require("sys");
var terminal = require("buster-terminal");

module.exports = {
    create: function (opt) {
        var reporter = Object.create(this);
        reporter.terminal = terminal.create(opt);
        reporter.list = terminal.labeledList.create(opt && opt.io);

        return reporter;
    },

    listen: function (runner) {
        runner.bind(this, {
            "progress:test:success": "testSuccess",
            "progress:test:error": "testError",
            "progress:test:failure": "testFailure",
            "progress:test:timeout": "testTimeout"
        });

        return this;
    },

    testSuccess: function (test) {
        this.print(test.client, this.terminal.green("."));
    },

    testError: function (test) {
        this.print(test.client, this.terminal.yellow("E"));
    },

    testFailure: function (test) {
        this.print(test.client, this.terminal.red("F"));
    },

    testTimeout: function (test) {
        this.print(test.client, this.terminal.red("T"));
    },

    displayProgress: function (client, output) {
        if (!this.list) {
            return this.bufferOutput(client, output);
        }

        this.print(client, output);
    },

    print: function (client, output) {
        this.list.print(this.clients[client.id], output);
    },

    addClient: function (clientId, agent) {
        this.clients = this.clients || {};
        var agentStr = agent.toString();
        this.clients[clientId] = agentStr;
        this.list.add(agentStr);
    }
};
<|endoftext|>


<commit_before>var $db = require('../lib/mongo');
var debug = require('debug')('wol:leaderboard');

exports.process = function(game, match) {
    // create player entry
    var $players = $db.get(game +'_players');
    match.players.forEach(function(player) {
        /* typically Computer */
        if (!player.nam) {
            player.nam = 'Computer';
            return;
        }

        var stats = {
            $push: {games: match.idno},
            $inc: {points: 2}
        };

        $players.update({name: player.nam}, stats, {upsert: true});
    });
};
<commit_msg>add player stats and game entry for wolv1 games<commit_after>var $db = require('../lib/mongo');
var debug = require('debug')('wol:leaderboard');

exports.process = function(game, match) {
    // create player entry
    var $players = $db.get(game +'_players');
    match.players.forEach(function(player) {
        /* typically Computer */
        if (!player.nam) {
            player.nam = 'Computer';
            return;
        }

        var stats = {
            $push: {games: match.idno},
            $inc: {points: 2}
        };

        $players.update({name: player.nam}, stats, {upsert: true});

        /* tack on stats so it can be referenced in game object */
        player.__gained = stats.$inc;
    });

    // create game entry
    delete match.buffer;
    $db.get(game +'_games').insert(match);
};
<|endoftext|>