<commit_before>// Dependency modules
var events        = require('events');

// Local modules
var baClient      = require('./lib/bacnet-client');
var baEnum        = require('./lib/bacnet-enum');

/**
 * To be able to communicate to BACNET devices, you have to initialize a new bacstack instance.
 * @class bacstack
 * @param {object=} settings - The options object used for parameterizing the bacstack.
 * @param {number=} [settings.port=47808] - BACNET communication port for listening and sending.
 * @param {string=} settings.interface - Specific BACNET communication interface if different from primary one.
 * @param {string=} [settings.broadcastAddress=255.255.255.255] - The address used for broadcast messages.
 * @param {number=} [settings.adpuTimeout=3000] - The timeout in milliseconds until a transaction should be interpreted as error.
 * @example
 * var bacnet = require('bacstack');
 *
 * var client = new bacnet({
 *   port: 47809,                          // Use BAC1 as communication port
 *   interface: '192.168.251.10',          // Listen on a specific interface
 *   broadcastAddress: '192.168.251.255',  // Use the subnet broadcast address
 *   adpuTimeout: 6000                     // Wait twice as long for response
 * });
 */
module.exports = function(settings) {
  var self = new events.EventEmitter();

  settings = settings || {};
  var options = {
    port: settings.port || 47808,
    interface: settings.interface,
    transport: settings.transport,
    broadcastAddress: settings.broadcastAddress || '255.255.255.255',
    adpuTimeout: settings.adpuTimeout || 3000
  };

  var client = new baClient(options);

  client.events.on('iAm', function(address, deviceId, maxAdpu, segmentation, vendorId) {

    /**
     * @event bacstack.iAm
     * @param {string} address - The IP address of the detected device.
     * @param {number} deviceId - The BACNET device-id of the detected device.
     * @param {number} maxAdpu - The max ADPU size the detected device is supporting.
     * @param {number} segmentation - The type of segmentation the detected device is supporting.
     * @param {number} vendorId - The BACNET vendor-id of the detected device.
     * @example
     * var bacnet = require('bacstack');
     * var client = new bacnet();
     *
     * client.on('iAm', function(address, deviceId, maxAdpu, segmentation, vendorId) {
     *   console.log('address: ', address, ' - deviceId: ', deviceId, ' - maxAdpu: ', maxAdpu, ' - segmentation: ', segmentation, ' - vendorId: ', vendorId);
     * });
     */
    self.emit('iAm', address, deviceId, maxAdpu, segmentation, vendorId);
  });

  client.events.on('error', function(err) {

    /**
     * @event bacstack.error
     * @param {error} err - The IP address of the detected device.
     * @example
     * var bacnet = require('bacstack');
     * var client = new bacnet();
     *
     * client.on('error', function(err) {
     *   console.log('Error occurred: ', err);
     *   client.close();
     * });
     */
    self.emit('error', err);
  });

  /**
   * The whoIs command discovers all BACNET devices in a network.
   * @function bacstack.whoIs
   * @param {number=} lowLimit - Minimal device instance number to search for.
   * @param {number=} highLimit - Maximal device instance number to search for.
   * @param {string=} address - Unicast address if command should device directly.
   * @fires bacstack.iAm
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.whoIs();
   */
  self.whoIs = function(lowLimit, highLimit, address) {
    client.whoIs(lowLimit, highLimit, address);
  };

  /**
   * The timeSync command sets the time of a target device.
   * @function bacstack.timeSync
   * @param {string} address - IP address of the target device.
   * @param {date} dateTime - The date and time to set on the target device.
   * @param {boolean} [isUtc=false] - Identifier if UTC time sync service shall be used.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.timeSync('192.168.1.43', new Date(), true);
   */
  self.timeSync = function(address, dateTime, isUtc) {
    client.timeSync(address, dateTime, isUtc);
  };

  /**
   * The readProperty command reads a single property of an object from a device.
   * @function bacstack.readProperty
   * @param {string} address - IP address of the target device.
   * @param {number} objectType - The BACNET object type to read.
   * @param {number} objectInstance - The BACNET object instance to read.
   * @param {number} propertyId - The BACNET property id in the specified object to read.
   * @param {number=} arrayIndex - The array index of the property to be read.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.readProperty('192.168.1.43', 8, 44301, 28, null, function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.readProperty = function(address, objectType, objectInstance, propertyId, arrayIndex, next) {
    client.readProperty(address, objectType, objectInstance, propertyId, arrayIndex, next);
  };

  /**
   * The writeProperty command writes a single property of an object to a device.
   * @function bacstack.writeProperty
   * @param {string} address - IP address of the target device.
   * @param {number} objectType - The BACNET object type to write.
   * @param {number} objectInstance - The BACNET object instance to write.
   * @param {number} propertyId - The BACNET property id in the specified object to write.
   * @param {number} priority - The priority to be used for writing to the property.
   * @param {object[]} valueList - A list of values to be written to the specified property.
   * @param {BacnetApplicationTags} valueList.tag - The data-type of the value to be written.
   * @param {number} valueList.value - The actual value to be written.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.writeProperty('192.168.1.43', 8, 44301, 28, 12, [
   *   {tag: bacnet.enum.BacnetApplicationTags.BACNET_APPLICATION_TAG_REAL, value: 100}
   * ], function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.writeProperty = function(address, objectType, objectInstance, propertyId, priority, valueList, next) {
    client.writeProperty(address, objectType, objectInstance, propertyId, priority, valueList, next);
  };

  /**
   * The readPropertyMultiple command reads multiple properties in multiple objects from a device.
   * @function bacstack.readPropertyMultiple
   * @param {string} address - IP address of the target device.
   * @param {object[]} propertyIdAndArrayIndex - List of object and property specifications to be read.
   * @param {object} propertyIdAndArrayIndex.objectIdentifier - Specifies which object to read.
   * @param {number} propertyIdAndArrayIndex.objectIdentifier.type - The BACNET object type to read.
   * @param {number} propertyIdAndArrayIndex.objectIdentifier.instance - The BACNET object instance to read.
   * @param {object[]} propertyIdAndArrayIndex.propertyReferences - List of properties to be read.
   * @param {number} propertyIdAndArrayIndex.propertyReferences.propertyIdentifier - The BACNET property id in the specified object to read. Also supports 8 for all properties.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * var requestArray = [
   *   {objectIdentifier: {type: 8, instance: 4194303}, propertyReferences: [{propertyIdentifier: 8}]}
   * ];
   * client.readPropertyMultiple('192.168.1.43', requestArray, function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.readPropertyMultiple = function(address, propertyIdAndArrayIndex, next) {
    client.readPropertyMultiple(address, propertyIdAndArrayIndex, next);
  };

  /**
   * The writePropertyMultiple command writes multiple properties in multiple objects to a device.
   * @function bacstack.writePropertyMultiple
   * @param {string} address - IP address of the target device.
   * @param {object[]} valueList - List of object and property specifications to be written.
   * @param {object} valueList.objectIdentifier - Specifies which object to read.
   * @param {number} valueList.objectIdentifier.type - The BACNET object type to read.
   * @param {number} valueList.objectIdentifier.instance - The BACNET object instance to read.
   * @param {object[]} valueList.values - List of properties to be written.
   * @param {object} valueList.values.property - Property specifications to be written.
   * @param {number} valueList.values.property.propertyIdentifier - The BACNET property id in the specified object to write.
   * @param {number} valueList.values.property.propertyArrayIndex - The array index of the property to be written.
   * @param {object[]} valueList.values.value - A list of values to be written to the specified property.
   * @param {BacnetApplicationTags} valueList.values.value.tag - The data-type of the value to be written.
   * @param {object} valueList.values.value.value - The actual value to be written.
   * @param {number} valueList.values.priority - The priority to be used for writing to the property.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * var valueList = [
   *   {objectIdentifier: {type: 8, instance: 44301}, values: [
   *     {property: {propertyIdentifier: 28, propertyArrayIndex: 12}, value: [{tag: bacnet.enum.BacnetApplicationTags.BACNET_APPLICATION_TAG_BOOLEAN, value: true}], priority: 8}
   *   ]}
   * ];
   * client.readPropertyMultiple('192.168.1.43', valueList, function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.writePropertyMultiple = function(address, valueList, next) {
    client.writePropertyMultiple(address, valueList, next);
  };

  /**
   * The deviceCommunicationControl command enables or disables network communication of the target device.
   * @function bacstack.deviceCommunicationControl
   * @param {string} address - IP address of the target device.
   * @param {number} timeDuration - The time to hold the network communication state in seconds. 0 for infinite.
   * @param {BacnetEnableDisable} enableDisable - The network communication state to set.
   * @param {string=} password - The optional password used to set the network communication state.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.deviceCommunicationControl('192.168.1.43', 0, bacnet.enum.BacnetEnableDisable.DISABLE, 'Test1234$', function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.deviceCommunicationControl = function(address, timeDuration, enableDisable, password, next) {
    client.deviceCommunicationControl(address, timeDuration, enableDisable, password, next);
  };

  /**
   * The reinitializeDevice command initiates a restart of the target device.
   * @function bacstack.reinitializeDevice
   * @param {string} address - IP address of the target device.
   * @param {BacnetReinitializedStates} state - The type of restart to be initiated.
   * @param {string=} password - The optional password used to restart the device.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.reinitializeDevice('192.168.1.43', bacnet.enum.BacnetReinitializedStates.BACNET_REINIT_COLDSTART, 'Test1234$', function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.reinitializeDevice = function(address, state, password, next) {
    client.reinitializeDevice(address, state, password, next);
  };

  /**
   * Unloads the current BACstack instance and closes the underlying UDP socket.
   * @function bacstack.close
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.close();
   */
  self.close = function() {
    client.close();
  };

  return self;
};

// Public enums
module.exports.enum = baEnum;
<commit_msg>docs(index): use correct function call in inline-code example<commit_after>// Dependency modules
var events        = require('events');

// Local modules
var baClient      = require('./lib/bacnet-client');
var baEnum        = require('./lib/bacnet-enum');

/**
 * To be able to communicate to BACNET devices, you have to initialize a new bacstack instance.
 * @class bacstack
 * @param {object=} settings - The options object used for parameterizing the bacstack.
 * @param {number=} [settings.port=47808] - BACNET communication port for listening and sending.
 * @param {string=} settings.interface - Specific BACNET communication interface if different from primary one.
 * @param {string=} [settings.broadcastAddress=255.255.255.255] - The address used for broadcast messages.
 * @param {number=} [settings.adpuTimeout=3000] - The timeout in milliseconds until a transaction should be interpreted as error.
 * @example
 * var bacnet = require('bacstack');
 *
 * var client = new bacnet({
 *   port: 47809,                          // Use BAC1 as communication port
 *   interface: '192.168.251.10',          // Listen on a specific interface
 *   broadcastAddress: '192.168.251.255',  // Use the subnet broadcast address
 *   adpuTimeout: 6000                     // Wait twice as long for response
 * });
 */
module.exports = function(settings) {
  var self = new events.EventEmitter();

  settings = settings || {};
  var options = {
    port: settings.port || 47808,
    interface: settings.interface,
    transport: settings.transport,
    broadcastAddress: settings.broadcastAddress || '255.255.255.255',
    adpuTimeout: settings.adpuTimeout || 3000
  };

  var client = new baClient(options);

  client.events.on('iAm', function(address, deviceId, maxAdpu, segmentation, vendorId) {

    /**
     * @event bacstack.iAm
     * @param {string} address - The IP address of the detected device.
     * @param {number} deviceId - The BACNET device-id of the detected device.
     * @param {number} maxAdpu - The max ADPU size the detected device is supporting.
     * @param {number} segmentation - The type of segmentation the detected device is supporting.
     * @param {number} vendorId - The BACNET vendor-id of the detected device.
     * @example
     * var bacnet = require('bacstack');
     * var client = new bacnet();
     *
     * client.on('iAm', function(address, deviceId, maxAdpu, segmentation, vendorId) {
     *   console.log('address: ', address, ' - deviceId: ', deviceId, ' - maxAdpu: ', maxAdpu, ' - segmentation: ', segmentation, ' - vendorId: ', vendorId);
     * });
     */
    self.emit('iAm', address, deviceId, maxAdpu, segmentation, vendorId);
  });

  client.events.on('error', function(err) {

    /**
     * @event bacstack.error
     * @param {error} err - The IP address of the detected device.
     * @example
     * var bacnet = require('bacstack');
     * var client = new bacnet();
     *
     * client.on('error', function(err) {
     *   console.log('Error occurred: ', err);
     *   client.close();
     * });
     */
    self.emit('error', err);
  });

  /**
   * The whoIs command discovers all BACNET devices in a network.
   * @function bacstack.whoIs
   * @param {number=} lowLimit - Minimal device instance number to search for.
   * @param {number=} highLimit - Maximal device instance number to search for.
   * @param {string=} address - Unicast address if command should device directly.
   * @fires bacstack.iAm
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.whoIs();
   */
  self.whoIs = function(lowLimit, highLimit, address) {
    client.whoIs(lowLimit, highLimit, address);
  };

  /**
   * The timeSync command sets the time of a target device.
   * @function bacstack.timeSync
   * @param {string} address - IP address of the target device.
   * @param {date} dateTime - The date and time to set on the target device.
   * @param {boolean} [isUtc=false] - Identifier if UTC time sync service shall be used.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.timeSync('192.168.1.43', new Date(), true);
   */
  self.timeSync = function(address, dateTime, isUtc) {
    client.timeSync(address, dateTime, isUtc);
  };

  /**
   * The readProperty command reads a single property of an object from a device.
   * @function bacstack.readProperty
   * @param {string} address - IP address of the target device.
   * @param {number} objectType - The BACNET object type to read.
   * @param {number} objectInstance - The BACNET object instance to read.
   * @param {number} propertyId - The BACNET property id in the specified object to read.
   * @param {number=} arrayIndex - The array index of the property to be read.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.readProperty('192.168.1.43', 8, 44301, 28, null, function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.readProperty = function(address, objectType, objectInstance, propertyId, arrayIndex, next) {
    client.readProperty(address, objectType, objectInstance, propertyId, arrayIndex, next);
  };

  /**
   * The writeProperty command writes a single property of an object to a device.
   * @function bacstack.writeProperty
   * @param {string} address - IP address of the target device.
   * @param {number} objectType - The BACNET object type to write.
   * @param {number} objectInstance - The BACNET object instance to write.
   * @param {number} propertyId - The BACNET property id in the specified object to write.
   * @param {number} priority - The priority to be used for writing to the property.
   * @param {object[]} valueList - A list of values to be written to the specified property.
   * @param {BacnetApplicationTags} valueList.tag - The data-type of the value to be written.
   * @param {number} valueList.value - The actual value to be written.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.writeProperty('192.168.1.43', 8, 44301, 28, 12, [
   *   {tag: bacnet.enum.BacnetApplicationTags.BACNET_APPLICATION_TAG_REAL, value: 100}
   * ], function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.writeProperty = function(address, objectType, objectInstance, propertyId, priority, valueList, next) {
    client.writeProperty(address, objectType, objectInstance, propertyId, priority, valueList, next);
  };

  /**
   * The readPropertyMultiple command reads multiple properties in multiple objects from a device.
   * @function bacstack.readPropertyMultiple
   * @param {string} address - IP address of the target device.
   * @param {object[]} propertyIdAndArrayIndex - List of object and property specifications to be read.
   * @param {object} propertyIdAndArrayIndex.objectIdentifier - Specifies which object to read.
   * @param {number} propertyIdAndArrayIndex.objectIdentifier.type - The BACNET object type to read.
   * @param {number} propertyIdAndArrayIndex.objectIdentifier.instance - The BACNET object instance to read.
   * @param {object[]} propertyIdAndArrayIndex.propertyReferences - List of properties to be read.
   * @param {number} propertyIdAndArrayIndex.propertyReferences.propertyIdentifier - The BACNET property id in the specified object to read. Also supports 8 for all properties.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * var requestArray = [
   *   {objectIdentifier: {type: 8, instance: 4194303}, propertyReferences: [{propertyIdentifier: 8}]}
   * ];
   * client.readPropertyMultiple('192.168.1.43', requestArray, function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.readPropertyMultiple = function(address, propertyIdAndArrayIndex, next) {
    client.readPropertyMultiple(address, propertyIdAndArrayIndex, next);
  };

  /**
   * The writePropertyMultiple command writes multiple properties in multiple objects to a device.
   * @function bacstack.writePropertyMultiple
   * @param {string} address - IP address of the target device.
   * @param {object[]} valueList - List of object and property specifications to be written.
   * @param {object} valueList.objectIdentifier - Specifies which object to read.
   * @param {number} valueList.objectIdentifier.type - The BACNET object type to read.
   * @param {number} valueList.objectIdentifier.instance - The BACNET object instance to read.
   * @param {object[]} valueList.values - List of properties to be written.
   * @param {object} valueList.values.property - Property specifications to be written.
   * @param {number} valueList.values.property.propertyIdentifier - The BACNET property id in the specified object to write.
   * @param {number} valueList.values.property.propertyArrayIndex - The array index of the property to be written.
   * @param {object[]} valueList.values.value - A list of values to be written to the specified property.
   * @param {BacnetApplicationTags} valueList.values.value.tag - The data-type of the value to be written.
   * @param {object} valueList.values.value.value - The actual value to be written.
   * @param {number} valueList.values.priority - The priority to be used for writing to the property.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * var valueList = [
   *   {objectIdentifier: {type: 8, instance: 44301}, values: [
   *     {property: {propertyIdentifier: 28, propertyArrayIndex: 12}, value: [{tag: bacnet.enum.BacnetApplicationTags.BACNET_APPLICATION_TAG_BOOLEAN, value: true}], priority: 8}
   *   ]}
   * ];
   * client.writePropertyMultiple('192.168.1.43', valueList, function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.writePropertyMultiple = function(address, valueList, next) {
    client.writePropertyMultiple(address, valueList, next);
  };

  /**
   * The deviceCommunicationControl command enables or disables network communication of the target device.
   * @function bacstack.deviceCommunicationControl
   * @param {string} address - IP address of the target device.
   * @param {number} timeDuration - The time to hold the network communication state in seconds. 0 for infinite.
   * @param {BacnetEnableDisable} enableDisable - The network communication state to set.
   * @param {string=} password - The optional password used to set the network communication state.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.deviceCommunicationControl('192.168.1.43', 0, bacnet.enum.BacnetEnableDisable.DISABLE, 'Test1234$', function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.deviceCommunicationControl = function(address, timeDuration, enableDisable, password, next) {
    client.deviceCommunicationControl(address, timeDuration, enableDisable, password, next);
  };

  /**
   * The reinitializeDevice command initiates a restart of the target device.
   * @function bacstack.reinitializeDevice
   * @param {string} address - IP address of the target device.
   * @param {BacnetReinitializedStates} state - The type of restart to be initiated.
   * @param {string=} password - The optional password used to restart the device.
   * @param {function} next - The callback containing an error, in case of a failure and value object in case of success.
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.reinitializeDevice('192.168.1.43', bacnet.enum.BacnetReinitializedStates.BACNET_REINIT_COLDSTART, 'Test1234$', function(err, value) {
   *   console.log('value: ', value);
   * });
   */
  self.reinitializeDevice = function(address, state, password, next) {
    client.reinitializeDevice(address, state, password, next);
  };

  /**
   * Unloads the current BACstack instance and closes the underlying UDP socket.
   * @function bacstack.close
   * @example
   * var bacnet = require('bacstack');
   * var client = new bacnet();
   *
   * client.close();
   */
  self.close = function() {
    client.close();
  };

  return self;
};

// Public enums
module.exports.enum = baEnum;
<|endoftext|>


<commit_before>'use strict';
const app = require('app');
const fs = require('fs');
const path = require('path');
const BrowserWindow = require('browser-window');

// report crashes to the Electron project
require('crash-reporter').start();

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

// prevent window being garbage collected
let mainWindow;

function onClosed() {
	// dereference the window
	// for multiple windows store them in an array
	mainWindow = null;
}

function createMainWindow() {
	const win = new BrowserWindow({
		width: 800,
		height: 600,
		'web-preferences': {
			// fails without this because of CommonJS script detection
			'node-integration': false
		}
	});

	win.loadUrl('https://crusader.hipchat.com/chat/');
	win.on('closed', onClosed);

	return win;
}

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

app.on('activate-with-no-open-windows', () => {
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	const settingsFile = path.join(app.getPath('userData'), 'settings.json');

	let settings = {
		teams: []
	};

	fs.access(settingsFile, fs.F_OK, function (err) {
		// Create settings file if it doesn't exist.
		if (err) {
			fs.writeFileSync(settingsFile, JSON.stringify(settings), 'utf8');
		} else {
			let file = fs.readFileSync(settingsFile, 'utf8');
			settings = JSON.parse(file);
		}

		mainWindow = createMainWindow();
	});
});
<commit_msg>Open multiple windows<commit_after>'use strict';
const app = require('app');
const fs = require('fs');
const path = require('path');
const BrowserWindow = require('browser-window');

// report crashes to the Electron project
require('crash-reporter').start();

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

// prevent window being garbage collected
var windows = [];

function onClosed() {
	// dereference the window
	// for multiple windows store them in an array
	windows.forEach(function(window){
		window = null;
	});
}

function createWindow(provider, i) {
	const win = new BrowserWindow({
		'min-width': 800,
		'min-height': 600,
		'web-preferences': {
			// fails without this because of CommonJS script detection
			'node-integration': false
		}
	});

	win.loadUrl('https://' + provider);
	win.on('closed', onClosed);

	return win;
}

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});

app.on('ready', () => {
	const settingsFile = path.join(app.getPath('userData'), 'settings.json');

	let settings = {
		teams: ['google.se','google.se']
	};

	fs.access(settingsFile, fs.F_OK, function (err) {
		// Create settings file if it doesn't exist.
		if (err) {
			fs.writeFileSync(settingsFile, JSON.stringify(settings), 'utf8');
		} else {
			let file = fs.readFileSync(settingsFile, 'utf8');
			settings = JSON.parse(file);
		}

		settings.teams.forEach(function(team, index){
			windows.push(createWindow(team, index));
		});
	});
});
<|endoftext|>


<commit_before>var Scout = require('zetta-scout');
var util = require('util');
var SSDPClient = require('node-ssdp').Client;
var request = require('request');
var xml2js = require('xml2js');
var url = require('url');

var WemoClient = require('./wemo/client');
var WemoServer = require('./wemo/server');
var WemoBulb = require('./devices/bulb');
var WemoInsight = require('./devices/insight');
var WemoMotion = require('./devices/motion');
var WemoSwitch = require('./devices/switch');

var WemoScout = module.exports = function() {
  Scout.call(this);
};
util.inherits(WemoScout, Scout);

WemoScout.prototype.init = function(next) {
  this.clients = {};
  this.callbackServer = new WemoServer();
  this.search();
  setInterval(this.search.bind(this), 5000);
  next();
};

WemoScout.prototype.initDevice = function(type, Class, device, bridge) {
  var self = this;
  var query = this.server.where({ type: type, UDN: device.UDN });
  this.server.find(query, function(err, results){
    if (results && results.length > 0) {
      self.provision(results[0], Class, device, bridge, self.callbackServer);
    } else {
      self.discover(Class, device, bridge, self.callbackServer);
    }
  });
};

WemoScout.prototype.search = function() {
  var self = this;

  var handleUDPResponse = function(msg, statusCode, rinfo) {
    request.get(msg.LOCATION, function(err, res, xml) {
      if (!err) {
        xml2js.parseString(xml, function(err, json) {
          if (!err) {
            var location = url.parse(msg.LOCATION);
            var device = {
              host: location.hostname,
              port: location.port,
              callbackURL: self.callbackServer.getCallbackURL()
            };
            for (var key in json.root.device[0]) {
              device[key] = json.root.device[0][key][0];
            }
            self.foundDevice(device);
          }
        });
      }
    });
  };

  var ssdpClient = new SSDPClient();
  ssdpClient.on('response', handleUDPResponse);
  ssdpClient.search('urn:Belkin:service:basicevent:1');
};

WemoScout.prototype.foundDevice = function(device) {
  if (this.clients[device.UDN]) {
    // device has already been initialized
    return;
  }

  var client = this.clients[device.UDN] = new WemoClient(device);
  switch (device.deviceType) {
    case 'urn:Belkin:device:bridge:1':
      client.getEndDevices(function(err, device){
        if (!err) {
          this.initDevice('wemo-bulb', WemoBulb, device, client);
        }
      }.bind(this));
      client.subscribe('urn:Belkin:service:bridge:1');
      break;
    case 'urn:Belkin:device:insight:1':
      this.initDevice('wemo-insight', WemoInsight, device, client);
      client.subscribe('urn:Belkin:service:insight:1');
      client.subscribe('urn:Belkin:service:basicevent:1');
      break;
    case 'urn:Belkin:device:sensor:1':
      this.initDevice('wemo-motion', WemoMotion, device, client);
      client.subscribe('urn:Belkin:service:basicevent:1');
      break;
    case 'urn:Belkin:device:controllee:1':
      this.initDevice('wemo-switch', WemoSwitch, device, client);
      client.subscribe('urn:Belkin:service:basicevent:1');
      break;
    default:
      this.server.info('Found unsupported Wemo device: ' + device.deviceType, device);
  }
};
<commit_msg>Fix for UDP discovery returning devices we were not looking for<commit_after>var Scout = require('zetta-scout');
var util = require('util');
var SSDPClient = require('node-ssdp').Client;
var request = require('request');
var xml2js = require('xml2js');
var url = require('url');

var WemoClient = require('./wemo/client');
var WemoServer = require('./wemo/server');
var WemoBulb = require('./devices/bulb');
var WemoInsight = require('./devices/insight');
var WemoMotion = require('./devices/motion');
var WemoSwitch = require('./devices/switch');

var WemoScout = module.exports = function() {
  Scout.call(this);
};
util.inherits(WemoScout, Scout);

WemoScout.prototype.init = function(next) {
  this.clients = {};
  this.callbackServer = new WemoServer();
  this.search();
  setInterval(this.search.bind(this), 5000);
  next();
};

WemoScout.prototype.initDevice = function(type, Class, device, bridge) {
  var self = this;
  var query = this.server.where({ type: type, UDN: device.UDN });
  this.server.find(query, function(err, results){
    if (results && results.length > 0) {
      self.provision(results[0], Class, device, bridge, self.callbackServer);
    } else {
      self.discover(Class, device, bridge, self.callbackServer);
    }
  });
};

WemoScout.prototype.search = function() {
  var self = this;

  var handleUDPResponse = function(msg, statusCode, rinfo) {
    request.get(msg.LOCATION, function(err, res, xml) {
      if (!err) {
        xml2js.parseString(xml, function(err, json) {
          if (!err) {
            var location = url.parse(msg.LOCATION);
            var device = {
              host: location.hostname,
              port: location.port,
              callbackURL: self.callbackServer.getCallbackURL()
            };
            for (var key in json.root.device[0]) {
              device[key] = json.root.device[0][key][0];
            }
            self.foundDevice(device);
          }
        });
      }
    });
  };

  var ssdpClient = new SSDPClient();
  ssdpClient.on('response', handleUDPResponse);
  ssdpClient.search('urn:Belkin:service:basicevent:1');
};

WemoScout.prototype.foundDevice = function(device) {
  if (!device.deviceType.match(/^urn:Belkin:device/)) {
    // search returned something we were not looking for
    return;
  }

  if (this.clients[device.UDN]) {
    // device has already been initialized
    return;
  }

  var client = this.clients[device.UDN] = new WemoClient(device);
  switch (device.deviceType) {
    case 'urn:Belkin:device:bridge:1':
      client.getEndDevices(function(err, device){
        if (!err) {
          this.initDevice('wemo-bulb', WemoBulb, device, client);
        }
      }.bind(this));
      client.subscribe('urn:Belkin:service:bridge:1');
      break;
    case 'urn:Belkin:device:insight:1':
      this.initDevice('wemo-insight', WemoInsight, device, client);
      client.subscribe('urn:Belkin:service:insight:1');
      client.subscribe('urn:Belkin:service:basicevent:1');
      break;
    case 'urn:Belkin:device:sensor:1':
      this.initDevice('wemo-motion', WemoMotion, device, client);
      client.subscribe('urn:Belkin:service:basicevent:1');
      break;
    case 'urn:Belkin:device:controllee:1':
      this.initDevice('wemo-switch', WemoSwitch, device, client);
      client.subscribe('urn:Belkin:service:basicevent:1');
      break;
    default:
      this.server.info('Found unsupported Wemo device: ' + device.deviceType, device);
  }
};
<|endoftext|>


<commit_before>/**
 * Created by aldiraraharja on 1/15/17.
 */
const express = require('express');
const LineClient = require('@line/bot-sdk').Client;
const middleware = require('@line/bot-sdk').middleware;
const path = require('path');
const axios = require('axios');
const config = require('./config');
const YTSClient = require('./yts_client/yts-client');
const LineHandler = require('./line/handler');
const FirebaseClient = require('./firebase_client');
const Torrent = require('./torrent/Torrent');
const OSClient = require('./opensubs_client');

const torrentClient = new Torrent();
const osClient = new OSClient();

const app = express();
const lineConfig = {
  channelAccessToken: config.LINE_CHANNEL_ACCESS_TOKEN,
  channelSecret: config.LINE_CHANNEL_SECRET,
};

const client = new LineClient(lineConfig);
const ystClient = new YTSClient(config.YTS_BASE_URL);
const firebaseClient = new FirebaseClient()
const handler = new LineHandler(client, ystClient, firebaseClient, osClient);

app.use(express.static(path.resolve(__dirname, 'homepage', 'build')));

app.use('/line', middleware(lineConfig), (req, res) => {
  handler.handleRequest(req.body);
  return res.sendStatus(200);
});

app.use('/data/:id', torrentClient.serveFile);
app.use('/subs/:id', (req, res) => {
  firebaseClient.getFirestore()
    .doc(`session/${req.params.id}`)
    .get()
    .then(snapshot => {
      const subsLink = snapshot.data().subs;
      console.log(`requesting ${subsLink}`);
      axios.get(subsLink, {responseType: 'arraybuffer'})
        .then(response => {
          res.send(response.data);
        })
        .catch(err => {
          res.send(err);
        });
    });
});

app.get('*', (req, res) => {
  return res.sendFile(path.resolve(__dirname, 'homepage', 'build', 'index.html'));
})

app.listen(process.env.PORT || 8080, () => {
  console.log('Bot is up!');
});<commit_msg>rough ssr attempt<commit_after>/**
 * Created by aldiraraharja on 1/15/17.
 */
const express = require('express');
const LineClient = require('@line/bot-sdk').Client;
const middleware = require('@line/bot-sdk').middleware;
const path = require('path');
const axios = require('axios');
const config = require('./config');
const YTSClient = require('./yts_client/yts-client');
const LineHandler = require('./line/handler');
const FirebaseClient = require('./firebase_client');
const Torrent = require('./torrent/Torrent');
const OSClient = require('./opensubs_client');
const react = require('react');
const reactServer = require('react-dom/server');
const homepageApp = require('./homepage/src/App');

const torrentClient = new Torrent();
const osClient = new OSClient();

const app = express();
const lineConfig = {
  channelAccessToken: config.LINE_CHANNEL_ACCESS_TOKEN,
  channelSecret: config.LINE_CHANNEL_SECRET,
};

const client = new LineClient(lineConfig);
const ystClient = new YTSClient(config.YTS_BASE_URL);
const firebaseClient = new FirebaseClient()
const handler = new LineHandler(client, ystClient, firebaseClient, osClient);

app.use(express.static(path.resolve(__dirname, 'homepage', 'build')));

app.use('/line', middleware(lineConfig), (req, res) => {
  handler.handleRequest(req.body);
  return res.sendStatus(200);
});

app.use('/data/:id', torrentClient.serveFile);
app.use('/subs/:id', (req, res) => {
  firebaseClient.getFirestore()
    .doc(`session/${req.params.id}`)
    .get()
    .then(snapshot => {
      const subsLink = snapshot.data().subs;
      console.log(`requesting ${subsLink}`);
      axios.get(subsLink, {responseType: 'arraybuffer'})
        .then(response => {
          res.send(response.data);
        })
        .catch(err => {
          res.send(err);
        });
    });
});

app.get('*', (req, res) => {
  const ssr = reactServer.renderToString(react.createElement(homepageApp));
  return res.send(`
  <!DOCTYPE html>
  <html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <meta name="propeller" content="5ec466a460c8ef6d317039e530520417" />
    <!--
        manifest.json provides metadata used when your web app is added to the
        homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
      -->
    <meta property="og:title" content="Watch HD Movies from chatbot" />
    <meta property="og:url" content="https://ytsmoviebot.herokuapp.com/" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link rel="stylesheet" href="https://video-react.js.org/assets/video-react.css" />
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-110194612-1"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag() { dataLayer.push(arguments); }
      gtag('js', new Date());

      gtag('config', 'UA-110194612-1');
    </script>
    <title>YTS Watch</title>
  </head>

  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    ${ssr}
    <script src="https://d.line-scdn.net/r/web/social-plugin/js/thirdparty/loader.min.js" async="async" defer="defer"></script>
    <script async="async" type="text/javascript" src="//go.mobisla.com/notice.php?p=1485033&interactive=1&pushup=1"></script>
  </body>

  </html>
  `);
  // return res.sendFile(path.resolve(__dirname, 'homepage', 'build', 'index.html'));
})

app.listen(process.env.PORT || 8080, () => {
  console.log('Bot is up!');
});<|endoftext|>


<commit_before>// Rules are grouped by the same sections as http://eslint.org/docs/rules/

const possibleErrors = {
  // Disallow the use of `console`
  'no-console': 2,

  // Ensure objects do not contain duplicate keys
  'no-dupe-keys': 2,

  // No multiline statements that look like separate statements
  'no-unexpected-multiline': 2
};

const bestPractices = {
  // Require curly braces around multi-line blocks
  curly: [2, 'multi-line'],

  // Use dot notation wherever possible
  'dot-notation': 2,

  // Use === and !== in all cases
  eqeqeq: 2,

  // Do not use arguments.caller / arguments.callee
  'no-caller': 2,

  // Disallow lexical declarations in case clauses
  'no-case-declarations': 2,

  // Do not use `eval`
  'no-eval': 2,

  // Empty Block Statements
  'no-empty': 2,

  // Do not extend native/builtin objects
  'no-extend-native': 2,

  // Do not use `bind` unnecessarily
  'no-extra-bind': 2,

  // Allow the use of fallthrough in switch statements
  'no-fallthrough': 0,

  // No leading or trailing decimal points in numeric literals
  'no-floating-decimal': 2,

  // No short-notation coercion (e.g. with `~` or `!!`)
  'no-implicit-coercion': 2,

  // No siblings of `eval` (e.g. `new Function('..')`)
  'no-implied-eval': 2,

  // No multiple spaces (except indentation)
  'no-multi-spaces': 2,

  // No reassigning native/builtin objects
  'no-native-reassign': 2,

  // No unused expressions (e.g. `"Hello world";` )
  'no-unused-expressions': [2, { allowShortCircuit: true, allowTernary: true }],

  // No `with` statements
  'no-with': 2
};

const strict = {
  strict: [2, 'global']
};

const variables = {
  // No deleting variables
  'no-delete-var': 2,

  // No shadowing restricted names (e.g. `arguments`)
  'no-shadow-restricted-names': 2,

  // No shadowing variables declared in the outer scope
  'no-shadow': 2,

  // No initializing variables to `undefined
  'no-undef-init': 2,

  // No using variables before they're defined, except function declarations
  'no-use-before-define': [2, 'nofunc']
};

const node = {

};

const stylistic = {
  // Avoid leading/trailing spaces in arrays
  'array-bracket-spacing': 2,

  // Use leading/trailing spaces within blocks
  'block-spacing': 2,

  // Use One True Brace Style, with single-line blocks allowed
  'brace-style': [2, '1tbs', { allowSingleLine: true }],

  // Use camelCase variable naming
  camelcase: 2,

  // Use spaces after commas, not before
  'comma-spacing': 2,

  // Use commas are at the of the line, not the beginning
  'comma-style': 2,

  // Use a line terminator at the end of every file
  'eol-last': 2,

  // Two-space indentation, always
  indent: [2, 2, {SwitchCase: 1}],

  // Use whitespace after colons in object keys
  'key-spacing': 2,

  // Disallow `continue`
  'no-continue': 2,

  // Disallow `if` as the only statement in an `else` block
  'no-lonely-if': 2,

  // No mixing tabs and spaces
  'no-mixed-spaces-and-tabs': 2,

  // No spaces in function calls
  'no-spaced-func': 2,

  // No trailing spaces at the end of the line
  'no-trailing-spaces': 2,

  // Allow dangling underscores
  'no-underscore-dangle': 0,

  // Always use spaces inside of curly braces
  'object-curly-spacing': [2, 'always'],

  // No combining `var` declarations
  'one-var': [2, 'never'],

  // No quotes around keys when unnecessary
  'quote-props': [2, 'as-needed'],

  // Strings are single-quoted, unless doing so would require escaping
  quotes: [2, 'single', 'avoid-escape'],

  // No spaces before semicolons; always spaces after
  'semi-spacing': 2,

  // Always use semicolons
  semi: 2,

  // Always use a space after keywords
  'space-after-keywords': 2,

  // Disallow space before function parentheses
  'space-before-function-paren': [2, 'never'],

  // Always use a space before keywords
  'space-before-keywords': 2,

  // Never use leading/trailing spaces in parentheses
  'space-in-parens': 2,

  // Use spaces around infix operators
  'space-infix-ops': 2,

  // Use spaces following certain keywords
  'space-return-throw-case': 2,

  // Use spaces following unary operators (e.g. `new`)
  'space-unary-ops': 2,

  // No trailing/dangling commas on multi-line objects and arrays
  'comma-dangle': [2, 'never']
};

const es6 = {
  // Use spaces around arrows
  'arrow-spacing': 2,

  // Require parentheses around arrow-function arguments
  'arrow-parens': 2,

  // Ensure `super()` is used in subclasses
  'constructor-super': 2,

  // Ensure the generator asterisk is after the space
  'generator-star-spacing': 2,

  // Do not overwrite class definitions
  'no-class-assign': 2,

  // Do not modify variables declared with `const`
  'no-const-assign': 2,

  // Don't duplicate class members
  'no-dupe-class-members': 2,

  // Don't refer to `this` before calling `super()` in constructors
  'no-this-before-super': 2,

  // Always use object shorthand whevener possible
  'object-shorthand': [2, 'always'],

  // Use `const` whenever a variable is not modified
  'prefer-const': 2,

  // Don't use `apply` where the spread operator could be used instead
  'prefer-spread': 2,

  // Do not use `var`
  'no-var': 2
};

const cruft = {
  // don't allow `.only` in tests
  'mocha/no-exclusive-tests': 2
};

module.exports = {
  extends: ['eslint:recommended'],

  env: {
    browser: true,
    node: true,
    jasmine: true,
    es6: true
  },

  plugins: [
    'mocha'
  ],

  rules: Object.assign({}, possibleErrors, bestPractices, strict, variables, stylistic, node, es6, cruft)
};
<commit_msg>Add missing word to comma-style comment<commit_after>// Rules are grouped by the same sections as http://eslint.org/docs/rules/

const possibleErrors = {
  // Disallow the use of `console`
  'no-console': 2,

  // Ensure objects do not contain duplicate keys
  'no-dupe-keys': 2,

  // No multiline statements that look like separate statements
  'no-unexpected-multiline': 2
};

const bestPractices = {
  // Require curly braces around multi-line blocks
  curly: [2, 'multi-line'],

  // Use dot notation wherever possible
  'dot-notation': 2,

  // Use === and !== in all cases
  eqeqeq: 2,

  // Do not use arguments.caller / arguments.callee
  'no-caller': 2,

  // Disallow lexical declarations in case clauses
  'no-case-declarations': 2,

  // Do not use `eval`
  'no-eval': 2,

  // Empty Block Statements
  'no-empty': 2,

  // Do not extend native/builtin objects
  'no-extend-native': 2,

  // Do not use `bind` unnecessarily
  'no-extra-bind': 2,

  // Allow the use of fallthrough in switch statements
  'no-fallthrough': 0,

  // No leading or trailing decimal points in numeric literals
  'no-floating-decimal': 2,

  // No short-notation coercion (e.g. with `~` or `!!`)
  'no-implicit-coercion': 2,

  // No siblings of `eval` (e.g. `new Function('..')`)
  'no-implied-eval': 2,

  // No multiple spaces (except indentation)
  'no-multi-spaces': 2,

  // No reassigning native/builtin objects
  'no-native-reassign': 2,

  // No unused expressions (e.g. `"Hello world";` )
  'no-unused-expressions': [2, { allowShortCircuit: true, allowTernary: true }],

  // No `with` statements
  'no-with': 2
};

const strict = {
  strict: [2, 'global']
};

const variables = {
  // No deleting variables
  'no-delete-var': 2,

  // No shadowing restricted names (e.g. `arguments`)
  'no-shadow-restricted-names': 2,

  // No shadowing variables declared in the outer scope
  'no-shadow': 2,

  // No initializing variables to `undefined
  'no-undef-init': 2,

  // No using variables before they're defined, except function declarations
  'no-use-before-define': [2, 'nofunc']
};

const node = {

};

const stylistic = {
  // Avoid leading/trailing spaces in arrays
  'array-bracket-spacing': 2,

  // Use leading/trailing spaces within blocks
  'block-spacing': 2,

  // Use One True Brace Style, with single-line blocks allowed
  'brace-style': [2, '1tbs', { allowSingleLine: true }],

  // Use camelCase variable naming
  camelcase: 2,

  // Use spaces after commas, not before
  'comma-spacing': 2,

  // Use commas are at the end of the line, not the beginning
  'comma-style': 2,

  // Use a line terminator at the end of every file
  'eol-last': 2,

  // Two-space indentation, always
  indent: [2, 2, {SwitchCase: 1}],

  // Use whitespace after colons in object keys
  'key-spacing': 2,

  // Disallow `continue`
  'no-continue': 2,

  // Disallow `if` as the only statement in an `else` block
  'no-lonely-if': 2,

  // No mixing tabs and spaces
  'no-mixed-spaces-and-tabs': 2,

  // No spaces in function calls
  'no-spaced-func': 2,

  // No trailing spaces at the end of the line
  'no-trailing-spaces': 2,

  // Allow dangling underscores
  'no-underscore-dangle': 0,

  // Always use spaces inside of curly braces
  'object-curly-spacing': [2, 'always'],

  // No combining `var` declarations
  'one-var': [2, 'never'],

  // No quotes around keys when unnecessary
  'quote-props': [2, 'as-needed'],

  // Strings are single-quoted, unless doing so would require escaping
  quotes: [2, 'single', 'avoid-escape'],

  // No spaces before semicolons; always spaces after
  'semi-spacing': 2,

  // Always use semicolons
  semi: 2,

  // Always use a space after keywords
  'space-after-keywords': 2,

  // Disallow space before function parentheses
  'space-before-function-paren': [2, 'never'],

  // Always use a space before keywords
  'space-before-keywords': 2,

  // Never use leading/trailing spaces in parentheses
  'space-in-parens': 2,

  // Use spaces around infix operators
  'space-infix-ops': 2,

  // Use spaces following certain keywords
  'space-return-throw-case': 2,

  // Use spaces following unary operators (e.g. `new`)
  'space-unary-ops': 2,

  // No trailing/dangling commas on multi-line objects and arrays
  'comma-dangle': [2, 'never']
};

const es6 = {
  // Use spaces around arrows
  'arrow-spacing': 2,

  // Require parentheses around arrow-function arguments
  'arrow-parens': 2,

  // Ensure `super()` is used in subclasses
  'constructor-super': 2,

  // Ensure the generator asterisk is after the space
  'generator-star-spacing': 2,

  // Do not overwrite class definitions
  'no-class-assign': 2,

  // Do not modify variables declared with `const`
  'no-const-assign': 2,

  // Don't duplicate class members
  'no-dupe-class-members': 2,

  // Don't refer to `this` before calling `super()` in constructors
  'no-this-before-super': 2,

  // Always use object shorthand whevener possible
  'object-shorthand': [2, 'always'],

  // Use `const` whenever a variable is not modified
  'prefer-const': 2,

  // Don't use `apply` where the spread operator could be used instead
  'prefer-spread': 2,

  // Do not use `var`
  'no-var': 2
};

const cruft = {
  // don't allow `.only` in tests
  'mocha/no-exclusive-tests': 2
};

module.exports = {
  extends: ['eslint:recommended'],

  env: {
    browser: true,
    node: true,
    jasmine: true,
    es6: true
  },

  plugins: [
    'mocha'
  ],

  rules: Object.assign({}, possibleErrors, bestPractices, strict, variables, stylistic, node, es6, cruft)
};
<|endoftext|>


<commit_before>var http = require('http'),
    https = require('https'),
    request = require('request'),
    BbPromise = require('bluebird');

var debug = false;

var baseURL = 'https://app.earnshark.com/prod/product/';

var appDir = 'http://earnsharkbeta.com.s3-website-eu-west-1.amazonaws.com/';

exports.isTest = function(newdebug) {
    debug = newdebug;
};

// Adding new Subscription
exports.addNewSubscription = function(product_id, key, body) {
    if (debug) {
        return new BbPromise(function(resolve, reject) {
            resolve('{ "status":"success", "message":"Subscription created without notifications and without invoice" }')
        });
    } else {

        var url = baseURL + product_id + '/addsubscriptionfromapi?key=' + key;

        var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/json'
            },
            options = {
                url: url,
                method: 'POST',
                headers: headers,
                json: body
            };

        return new BbPromise(function(resolve, reject) {
            request(options, function(error, response, body) {
                if (error) {
                    reject(error)
                } else {
                    resolve(response.body)
                }
            });
        });

    }

};

// Get User account Information
exports.getAccountInformation = function(product_id, key, account_id) {

    if (debug) {
        return new BbPromise(function(resolve, reject) {
            resolve('[ { "Date":"01/01/2016", "Cost":{ "value":"100", "currency":"USD" }, "Name":"5 Users Plan", "Product_ID":1, "Customer_ID":1, "Customer_Name":"Customer Name", "Account_ID":"123456", "Metadata":"{\"users\":\"10 users\"}", "Subscription_ID":1, "Tags":[ "10users" ], "License_ID":1, "Invalid":false, "Expired":false, "Billing_Cycle":{ "value":1, "type":"Monthly" }, "Description":"10 Users per month / 100", "Tenant_ID":"eu-west-1:00000000-0000-0000-0000-000000000000" } ]')
        });
    } else {

        var url = baseURL + product_id + '/subscriptioninfo/' + account_id + '?key=' + key;

        var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/json'
            },
            options = {
                url: url,
                method: 'GET',
                headers: headers
            };

        return new BbPromise(function(resolve, reject) {
            request(options, function(error, response, body) {
                if (error) {
                    reject(error)
                } else {
                    resolve(response.body)
                }
            });
        });

    }
};

// Renew/Update a Subscription
exports.renewSubscription = function(product_id, key, subscription_id,new_license_id) {
    if (debug) {
        return new BbPromise(function(resolve, reject) {
            resolve('{ "Date":"01/01/2016", "Cost":{ "value":"100", "currency":"USD" }, "Name":"5 Users Plan", "Product_ID":1, "Customer_ID":1, "Customer_Name":"Customer Name", "Account_ID":"123456", "Metadata":"{\"users\":\"10 users\"}", "Subscription_ID":1, "Tags":[ "10users" ], "License_ID":1, "Invalid":false, "Expired":false, "Billing_Cycle":{ "value":1, "type":"Monthly" }, "Description":"10 Users per month / 100", "Tenant_ID":"eu-west-1:00000000-0000-0000-0000-000000000000" }')
        });
    } else {

        var url = baseURL + product_id + '/subscription/' + subscription_id +'/apiRenewSubscription/'+ new_license_id +'?key=' + key;

        var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/json'
            },
            options = {
                url: url,
                method: 'GET',
                headers: headers
            };

        return new BbPromise(function(resolve, reject) {
            request(options, function(error, response, body) {
                if (error) {
                    reject(error)
                } else {
                    resolve(response.body)
                }
            });
        });

    }
};

// Get Information about a single license
exports.getLicenseInformation = function(product_id, key, license_id) {
    if (debug) {
        return new BbPromise(function(resolve, reject) {
            resolve('{ "Name":"License Name", "Cost":{ "value":"100", "currency":"USD" }, "Tags":[ "10 User Package" ], "License_ID":1, "Product_ID":1, "Description":"10 Users per month / 100", "Billing_Cycle":{ "value":1, "type":"Monthly" }, "Metadata":"{\"users\":\"10\"}" }')
        });
    } else {

        var url = baseURL + product_id + '/license/' + license_id + '/getlicensefromapi?key=' + key;
        var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/json'
            },
            options = {
                url: url,
                method: 'GET',
                headers: headers
            };

        return new BbPromise(function(resolve, reject) {
            request(options, function(error, response, body) {
                if (error) {
                    reject(error)
                } else {
                    resolve(response.body)
                }
            });
        });
    }
};

// Get All the Licenses for a Product
exports.getAllLicensesOfProduct = function(product_id, key) {
    if (debug) {
        return new BbPromise(function(resolve, reject) {
            resolve('[{"Name":"License Name","Cost":{"value":"10","currency":"USD"},"Tags":["free","test","trial"],"License_ID":1,"Product_ID":1,"Description":"Test","Billing_Cycle":{"value":1,"type":"Monthly"},"Metadata":"{}"}]')
        });
    } else {

        var url = baseURL + product_id + '/license/all?key=' + key;
        var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/json'
            },
            options = {
                url: url,
                method: 'GET',
                headers: headers
            };

        return new BbPromise(function(resolve, reject) {
            request(options, function(error, response, body) {
                if (error) {
                    reject(error)
                } else {
                    resolve(response.body)
                }
            });
        });
    }
};

// Generate the payment url for license payments
exports.getPaymentURL = function(product_id, key, account_id, redirect) {
    return appDir + 'payment.html?redirect=' + redirect + '&productID=' + product_id + '&accountID=' + account_id + '&key=' + key;
};<commit_msg>Added endpoint to Retrieve All Payment Transactions for an Account<commit_after>var http = require('http'),
    https = require('https'),
    request = require('request'),
    BbPromise = require('bluebird');

var debug = false;

var baseURL = 'https://app.earnshark.com/prod/product/';

var appDir = 'http://earnsharkbeta.com.s3-website-eu-west-1.amazonaws.com/';

exports.isTest = function(newdebug) {
    debug = newdebug;
};

// Adding new Subscription
exports.addNewSubscription = function(product_id, key, body) {
    if (debug) {
        return new BbPromise(function(resolve, reject) {
            resolve('{ "status":"success", "message":"Subscription created without notifications and without invoice" }')
        });
    } else {

        var url = baseURL + product_id + '/addsubscriptionfromapi?key=' + key;

        var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/json'
            },
            options = {
                url: url,
                method: 'POST',
                headers: headers,
                json: body
            };

        return new BbPromise(function(resolve, reject) {
            request(options, function(error, response, body) {
                if (error) {
                    reject(error)
                } else {
                    resolve(response.body)
                }
            });
        });

    }

};

// Get User account Information
exports.getAccountInformation = function(product_id, key, account_id) {

    if (debug) {
        return new BbPromise(function(resolve, reject) {
            resolve('[ { "Date":"01/01/2016", "Cost":{ "value":"100", "currency":"USD" }, "Name":"5 Users Plan", "Product_ID":1, "Customer_ID":1, "Customer_Name":"Customer Name", "Account_ID":"123456", "Metadata":"{\"users\":\"10 users\"}", "Subscription_ID":1, "Tags":[ "10users" ], "License_ID":1, "Invalid":false, "Expired":false, "Billing_Cycle":{ "value":1, "type":"Monthly" }, "Description":"10 Users per month / 100", "Tenant_ID":"eu-west-1:00000000-0000-0000-0000-000000000000" } ]')
        });
    } else {

        var url = baseURL + product_id + '/subscriptioninfo/' + account_id + '?key=' + key;

        var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/json'
            },
            options = {
                url: url,
                method: 'GET',
                headers: headers
            };

        return new BbPromise(function(resolve, reject) {
            request(options, function(error, response, body) {
                if (error) {
                    reject(error)
                } else {
                    resolve(response.body)
                }
            });
        });

    }
};

// Renew/Update a Subscription
exports.renewSubscription = function(product_id, key, subscription_id,new_license_id) {
    if (debug) {
        return new BbPromise(function(resolve, reject) {
            resolve('{ "Date":"01/01/2016", "Cost":{ "value":"100", "currency":"USD" }, "Name":"5 Users Plan", "Product_ID":1, "Customer_ID":1, "Customer_Name":"Customer Name", "Account_ID":"123456", "Metadata":"{\"users\":\"10 users\"}", "Subscription_ID":1, "Tags":[ "10users" ], "License_ID":1, "Invalid":false, "Expired":false, "Billing_Cycle":{ "value":1, "type":"Monthly" }, "Description":"10 Users per month / 100", "Tenant_ID":"eu-west-1:00000000-0000-0000-0000-000000000000" }')
        });
    } else {

        var url = baseURL + product_id + '/subscription/' + subscription_id +'/apiRenewSubscription/'+ new_license_id +'?key=' + key;

        var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/json'
            },
            options = {
                url: url,
                method: 'GET',
                headers: headers
            };

        return new BbPromise(function(resolve, reject) {
            request(options, function(error, response, body) {
                if (error) {
                    reject(error)
                } else {
                    resolve(response.body)
                }
            });
        });

    }
};

// Get Information about a single license
exports.getLicenseInformation = function(product_id, key, license_id) {
    if (debug) {
        return new BbPromise(function(resolve, reject) {
            resolve('{ "Name":"License Name", "Cost":{ "value":"100", "currency":"USD" }, "Tags":[ "10 User Package" ], "License_ID":1, "Product_ID":1, "Description":"10 Users per month / 100", "Billing_Cycle":{ "value":1, "type":"Monthly" }, "Metadata":"{\"users\":\"10\"}" }')
        });
    } else {

        var url = baseURL + product_id + '/license/' + license_id + '/getlicensefromapi?key=' + key;
        var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/json'
            },
            options = {
                url: url,
                method: 'GET',
                headers: headers
            };

        return new BbPromise(function(resolve, reject) {
            request(options, function(error, response, body) {
                if (error) {
                    reject(error)
                } else {
                    resolve(response.body)
                }
            });
        });
    }
};

// Get All the Licenses for a Product
exports.getAllLicensesOfProduct = function(product_id, key) {
    if (debug) {
        return new BbPromise(function(resolve, reject) {
            resolve('[{"Name":"License Name","Cost":{"value":"10","currency":"USD"},"Tags":["free","test","trial"],"License_ID":1,"Product_ID":1,"Description":"Test","Billing_Cycle":{"value":1,"type":"Monthly"},"Metadata":"{}"}]')
        });
    } else {

        var url = baseURL + product_id + '/license/all?key=' + key;
        var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/json'
            },
            options = {
                url: url,
                method: 'GET',
                headers: headers
            };

        return new BbPromise(function(resolve, reject) {
            request(options, function(error, response, body) {
                if (error) {
                    reject(error)
                } else {
                    resolve(response.body)
                }
            });
        });
    }
};

// Retrieve All Payment Transactions for an Account
exports.getAccountPayments = function(product_id, account_id ,key) {
    if (debug) {
        return new BbPromise(function(resolve, reject) {
            resolve('[ { "Amount":"100", "Created_At":"1474872974062", "Currency":"USD", "Product_ID":1, "PayPal_Transaction":"PAY-11111111111", "Updated_At":"1474872974062", "Account_ID":"local", "PayPal_Payer_ID":"111111", "Subscription_ID":1, "Payment_Processed":true, "Payout_ID":"12345", "Payment_Sent":true, "PayPal_Payment_ID":"PAY-11111111111" } ]')
        });
    } else {

        var url = baseURL + product_id + '/account/'+account_id+'/transactions?key=' + key;
        var headers = {
                'User-Agent': 'Super Agent/0.0.1',
                'Content-Type': 'application/json'
            },
            options = {
                url: url,
                method: 'GET',
                headers: headers
            };

        return new BbPromise(function(resolve, reject) {
            request(options, function(error, response, body) {
                if (error) {
                    reject(error)
                } else {
                    resolve(response.body)
                }
            });
        });
    }
};

// Generate the payment url for license payments
exports.getPaymentURL = function(product_id, key, account_id, redirect) {
    return appDir + 'payment.html?redirect=' + redirect + '&productID=' + product_id + '&accountID=' + account_id + '&key=' + key;
};<|endoftext|>


<commit_before>var net = module.exports;
var events = require('events');
var util = require('util');
var Buffer = require('buffer').Buffer;

var stringToArrayBuffer = function(str) {
  var buffer = new ArrayBuffer(str.length);
  var uint8Array = new Uint8Array(buffer);
  for(var i = 0; i < str.length; i++) {
    uint8Array[i] = str.charCodeAt(i);
  }
  return buffer;
};

var bufferToArrayBuffer = function(buffer) {
  return stringToArrayBuffer(buf.toString())
};

var arrayBufferToBuffer = function(arrayBuffer) {
  var buffer = new Buffer(arrayBuffer.byteLength);
  var uint8Array = new Uint8Array(arrayBuffer);
  for(var i = 0; i < uint8Array.length; i++) {
    buffer.writeUInt8(uint8Array[i], i);
  }
  return buffer;
};

net.createServer = function(options, connectionListener) {};
net.connect = net.createConnection = function() {
  var options = {};
  var args = arguments;
  if(typeof args[0] === 'object') {
    options.port = args[0].port;
    options.host = args[0].host || "127.0.0.1";
  }
  else if(typeof args[0] === 'number') {
    // there is a port
    options.port = args[0];
    if(typeof args[1] === 'string') {
      options.host = args[1];
    }
  }
  else if(typeof args[0] === 'string') {
    return; // can't do this.
  }

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};

  var socket = new net.Socket(options, function() {
    socket.connect(options, cb);
  });

  return socket;
};

net.Server = function() {
  var _maxConnections = 0;
  this.__defineGetter__("maxConnections", function() { return _maxConnections; });

  var _connections = 0;
  this.__defineGetter__("connections", function() { return _connections; });
};

net.Server.prototype.listen = function() {};
net.Server.prototype.close = function() {};
net.Server.prototype.address = function() {};

net.Socket = function(options, createCallback) {
  var self = this;
  options = options || {};
  createCallback = createCallback || function() {};
  this._fd = options.fd;
  this._type = options.type;
  //assert(this._type === "tcp6", "Only tcp4 is allowed");
  //assert(this._type === "unix", "Only tcp4 is allowed");
  this._type = allowHalfOpen = options.allowHalfOpen;
  this._socketInfo = 0;
  this._encoding;

  chrome.socket.create("tcp", {}, function(createInfo) {
    self._socketInfo = createInfo;
    createCallback();
    // start trying to read
    self._read();
  });
};

util.inherits(net.Socket, events.EventEmitter);

/*
  Events:
    close
    connect
    data
    drain
    end
    error
    timeout
*/

/*
  Methods
*/

net.Socket.prototype.connect = function() {
  var self = this;
  var options = {};
  var args = arguments;

  if(typeof args[0] === 'object') {
    // we have an options object.
    options.port = args[0].port;
    options.host = args[0].host || "127.0.0.1";
  }
  else if (typeof args[0] === 'string') {
    // throw an error, we can't do named pipes.
  }
  else if (typeof args[0] === 'number') {
    // assume port. and host.
    options.port = args[0];
    options.host = "127.0.0.1";
    if(typeof args[1] === 'string') {
      options.host = args[1];
    }
  }

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};
  self.on('connect', cb);

  chrome.socket.connect(self._socketInfo.socketId, options.host, options.port, function(result) {
    if(result == 0) {
      self.emit('connect');
    }
    else {
      self.emit('error', new Error("Unable to connect"));
    }
  });
};

net.Socket.prototype.destroy = function() {
  chrome.socket.destroy(this._socketInfo.socketId);
};
net.Socket.prototype.destroySoon = function() {};
net.Socket.prototype.setEncoding = function(encoding) {
  this._encoding = encoding;
};

net.Socket.prototype.setNoDelay = function(noDelay) {
  noDelay = (noDelay === undefined) ? true : noDelay;
  chrome.socket.setNoDely(self._socketInfo.socketId, noDelay, function() {});
};

net.Socket.prototype.setKeepAlive = function(enable, delay) {
  enable = (enable === 'undefined') ? false : enable;
  delay = (delay === 'undefined') ? 0 : delay;
  chrome.socket.setKeepAlive(self._socketInfo.socketId, enable, initialDelay, function() {});
};

net.Socket.prototype._read = function() {
  var self = this;
  chrome.socket.read(self._socketInfo.socketId, function(readInfo) {
    if(readInfo.resultCode < 0) return;
    // ArrayBuffer to Buffer if no encoding.
    var buffer = arrayBufferToBuffer(readInfo.data);
    self.emit('data', buffer);
  });

  // enque another read soon. TODO: Is there are better way to controll speed.
  self._readTimer = setTimeout(self._read.bind(self), 100);
}

net.Socket.prototype.write = function(data, encoding, callback) {
  var buffer;
  var self = this;

  encoding = encoding || "UTF8";
  callback = callback || function() {};

  if(typeof data === 'string') {
    buffer = stringToArrayBuffer(data);
  }
  else if(data instanceof Buffer) {
    buffer = bufferToArrayBuffer(data);
  }
  else {
    // throw an error because we can't do anything.
  }

  self._resetTimeout();

  chrome.socket.write(self._socketInfo.socketId, buffer, function(writeInfo) {
    callback();
  });

  return true;
};

net.Socket.prototype._resetTimeout = function() {
  var self = this;
  if(!!self._timeout == false) clearTimeout(self._timeout);
  if(!!self._timeoutValue) self._timeout = setTimeout(function() { self.emit('timeout') }, self._timeoutValue);
};

net.Socket.prototype.setTimeout = function(timeout, callback) {
  this._timeoutValue = timeout;
  this._resetTimeout();
};

net.Socket.prototype.ref = function() {};
net.Socket.prototype.unref = function() {};
net.Socket.prototype.pause = function() {};
net.Socket.prototype.resume = function() {};
net.Socket.prototype.end = function() {};

Object.defineProperty(net.Socket.prototype, 'readyState', {
  get: function() {}
});

Object.defineProperty(net.Socket.prototype, 'bufferSize', {
  get: function() {}
});
<commit_msg>Preparing for end functionality<commit_after>var net = module.exports;
var events = require('events');
var util = require('util');
var Buffer = require('buffer').Buffer;

var stringToArrayBuffer = function(str) {
  var buffer = new ArrayBuffer(str.length);
  var uint8Array = new Uint8Array(buffer);
  for(var i = 0; i < str.length; i++) {
    uint8Array[i] = str.charCodeAt(i);
  }
  return buffer;
};

var bufferToArrayBuffer = function(buffer) {
  return stringToArrayBuffer(buf.toString())
};

var arrayBufferToBuffer = function(arrayBuffer) {
  var buffer = new Buffer(arrayBuffer.byteLength);
  var uint8Array = new Uint8Array(arrayBuffer);
  for(var i = 0; i < uint8Array.length; i++) {
    buffer.writeUInt8(uint8Array[i], i);
  }
  return buffer;
};

net.createServer = function(options, connectionListener) {};
net.connect = net.createConnection = function() {
  var options = {};
  var args = arguments;
  if(typeof args[0] === 'object') {
    options.port = args[0].port;
    options.host = args[0].host || "127.0.0.1";
  }
  else if(typeof args[0] === 'number') {
    // there is a port
    options.port = args[0];
    if(typeof args[1] === 'string') {
      options.host = args[1];
    }
  }
  else if(typeof args[0] === 'string') {
    return; // can't do this.
  }

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};

  var socket = new net.Socket(options, function() {
    socket.connect(options, cb);
  });

  return socket;
};

net.Server = function() {
  var _maxConnections = 0;
  this.__defineGetter__("maxConnections", function() { return _maxConnections; });

  var _connections = 0;
  this.__defineGetter__("connections", function() { return _connections; });
};

net.Server.prototype.listen = function() {};
net.Server.prototype.close = function() {};
net.Server.prototype.address = function() {};

net.Socket = function(options, createCallback) {
  var self = this;
  options = options || {};
  createCallback = createCallback || function() {};
  this._fd = options.fd;
  this._type = options.type;
  //assert(this._type === "tcp6", "Only tcp4 is allowed");
  //assert(this._type === "unix", "Only tcp4 is allowed");
  this._type = allowHalfOpen = options.allowHalfOpen;
  this._socketInfo = 0;
  this._encoding;

  chrome.socket.create("tcp", {}, function(createInfo) {
    self._socketInfo = createInfo;
    createCallback();
    // start trying to read
    self._read();
  });
};

util.inherits(net.Socket, events.EventEmitter);

/*
  Events:
    close
    connect
    data
    drain
    end
    error
    timeout
*/

/*
  Methods
*/

net.Socket.prototype.connect = function() {
  var self = this;
  var options = {};
  var args = arguments;

  if(typeof args[0] === 'object') {
    // we have an options object.
    options.port = args[0].port;
    options.host = args[0].host || "127.0.0.1";
  }
  else if (typeof args[0] === 'string') {
    // throw an error, we can't do named pipes.
  }
  else if (typeof args[0] === 'number') {
    // assume port. and host.
    options.port = args[0];
    options.host = "127.0.0.1";
    if(typeof args[1] === 'string') {
      options.host = args[1];
    }
  }

  var cb = args[args.length -1];
  cb = (typeof cb === 'function') ? cb : function() {};
  self.on('connect', cb);

  chrome.socket.connect(self._socketInfo.socketId, options.host, options.port, function(result) {
    if(result == 0) {
      self.emit('connect');
    }
    else {
      self.emit('error', new Error("Unable to connect"));
    }
  });
};

net.Socket.prototype.destroy = function() {
  chrome.socket.destroy(this._socketInfo.socketId);
};
net.Socket.prototype.destroySoon = function() {};
net.Socket.prototype.setEncoding = function(encoding) {
  this._encoding = encoding;
};

net.Socket.prototype.setNoDelay = function(noDelay) {
  noDelay = (noDelay === undefined) ? true : noDelay;
  chrome.socket.setNoDely(self._socketInfo.socketId, noDelay, function() {});
};

net.Socket.prototype.setKeepAlive = function(enable, delay) {
  enable = (enable === 'undefined') ? false : enable;
  delay = (delay === 'undefined') ? 0 : delay;
  chrome.socket.setKeepAlive(self._socketInfo.socketId, enable, initialDelay, function() {});
};

net.Socket.prototype._read = function() {
  var self = this;
  chrome.socket.read(self._socketInfo.socketId, function(readInfo) {
    if(readInfo.resultCode < 0) return;
    // ArrayBuffer to Buffer if no encoding.
    var buffer = arrayBufferToBuffer(readInfo.data);
    self.emit('data', buffer);
  });

  // enque another read soon. TODO: Is there are better way to controll speed.
  self._readTimer = setTimeout(self._read.bind(self), 100);
}

net.Socket.prototype.write = function(data, encoding, callback) {
  var buffer;
  var self = this;

  encoding = encoding || "UTF8";
  callback = callback || function() {};

  if(typeof data === 'string') {
    buffer = stringToArrayBuffer(data);
  }
  else if(data instanceof Buffer) {
    buffer = bufferToArrayBuffer(data);
  }
  else {
    // throw an error because we can't do anything.
  }

  self._resetTimeout();

  chrome.socket.write(self._socketInfo.socketId, buffer, function(writeInfo) {
    callback();
  });

  return true;
};

net.Socket.prototype._resetTimeout = function() {
  var self = this;
  if(!!self._timeout == false) clearTimeout(self._timeout);
  if(!!self._timeoutValue) self._timeout = setTimeout(function() { self.emit('timeout') }, self._timeoutValue);
};

net.Socket.prototype.setTimeout = function(timeout, callback) {
  this._timeoutValue = timeout;
  this._resetTimeout();
};

net.Socket.prototype.ref = function() {};
net.Socket.prototype.unref = function() {};
net.Socket.prototype.pause = function() {};
net.Socket.prototype.resume = function() {};
net.Socket.prototype.end = function() {

};

Object.defineProperty(net.Socket.prototype, 'readyState', {
  get: function() {}
});

Object.defineProperty(net.Socket.prototype, 'bufferSize', {
  get: function() {}
});
<|endoftext|>


<commit_before>// __Dependencies__
var url = require('url');
var express = require('express');
var mongoose = require('mongoose');
var Controller = require('./Controller');

// __Private Members__
var controllers = [];

function swaggerTypeFor (type) {
  if (type === String) return 'string';
  if (type === Number) return 'double';
  if (type === Date) return 'Date';
  if (type === mongoose.Schema.Types.Buffer) throw new Error('Not implemented');
  if (type === Boolean) return 'boolean';
  if (type === mongoose.Schema.Types.Mixed) throw new Error('Not implemented');
  if (type === mongoose.Schema.Types.ObjectId) return 'string';
  if (type === mongoose.Schema.Types.Oid) return 'string';
  if (type === mongoose.Schema.Types.Array) return 'Array';
  throw new Error('Unrecognized type:' + type);
};

// A method for capitalizing the first letter of a string
function capitalize (s) {
  if (!s) return s;
  if (s.length === 1) return s.toUpperCase();
  return s[0].toUpperCase() + s.substring(1);
}

// A method for generating a Swagger resource listing
function generateResourceListing (controllers) {
  var listing = {
    apiVersion: '0.0.1', // TODO
    swaggerVersion: '1.1',
    basePath: 'http://127.0.0.1:8012/api/v1', // TODO
    apis: [],
    models: {}
  };

  controllers.forEach(function (controller) {
    var modelName = capitalize(controller.get('singular'));
    listing.models[modelName] = generateModelDefinition(controller);
    listing.apis.push(generateApiDefinition(controller, true));
    listing.apis.push(generateApiDefinition(controller, false));
  });

  return listing;
}

// A method used to generate a Swagger model definition for a controller
function generateModelDefinition (controller) {
  var definition = {};
  var schema = controller.get('schema');

  definition.id = capitalize(controller.get('singular'));
  definition.properties = {};

  Object.keys(schema.paths).forEach(function (name) {
    var property = {};
    var path = schema.paths[name];

    if (path.selected === false) return;
    // TODO also check controller options

    property.type = swaggerTypeFor(path.options.type);
    property.required = path.options.required || (name === '_id');

    // Set enum values if applicable
    if (path.enumValues && path.enumValues.length > 0) {
      property.allowableValues = { valueType: 'LIST', values: path.enumValues };
    }

    // Set allowable values range if min or max is present
    if (!isNaN(path.options.min) || !isNaN(path.options.max)) {
      property.allowableValues = { valueType: 'RANGE' };
    }

    if (!isNaN(path.options.min)) {
      property.allowableValues.min = path.options.min;
    }

    if (!isNaN(path.options.max)) {
      property.allowableValues.max = path.options.max;
    }

    definition.properties[name] = property;
  });

  return definition;
}

// A method used to generate a Swagger API definition for a controller
function generateApiDefinition (controller, plural) {
  var definition = {};

  definition.path = '/' + controller.get('plural');
  // if (!plural) definition.path += '/{id}'; // TODO why is this breaking swagger-ui?

  if (plural) definition.description = 'Operations about ' + controller.get('plural');
  else definition.description = 'Operations about a given ' + controller.get('singular');

  definition.operations = [];

  controller.activeVerbs().forEach(function (verb) {
    var operation = {};
    var titlePlural = capitalize(controller.get('plural'));
    var titleSingular = capitalize(controller.get('singular'));

    // Don't do post/put for single/plural
    if (verb === 'post' && !plural) return;
    if (verb === 'put' && plural) return;

    operation.httpMethod = verb.toUpperCase();

    if (plural) operation.nickname = verb + titlePlural;
    else operation.nickname = verb + titleSingular + 'ById';

    if (plural) operation.responseClass = [ titleSingular ];
    else operation.responseClass = titleSingular;

    operation.parameters = []; // TODO

    if (plural) operation.summary = capitalize(verb) + ' some ' + controller.get('plural');
    else operation.summary = capitalize(verb) + ' a ' + controller.get('singular') + ' by its unique ID';

    operation.errorResponses = []; // TODO 404

    definition.operations.push(operation);
  });

  return definition;
}

// __Module Definition__
var baucis = module.exports = function (options) {
  options || (options = {});

  var app = express();

  // Set options on the app
  Object.keys(options).forEach(function (key) {
    app.set(key, options[key]);
  });

  app.set('controllers', controllers);

  // Mount all published controllers to the baucis app
  controllers.forEach(function (controller) {
    var route = url.resolve('/', controller.get('plural'));
    controller.initialize();
    app.use(route, controller);
  });

  // Activate Swagger resource listing if the option is enabled
  if (app.get('swagger') === true) {
    app.get('/api-docs.json', function (request, response, next) {
      response.json(generateResourceListing(app.get('controllers')));
    });
  }

  controllers = [];

  return app;
};

// __Public Methods__
baucis.rest = function (options) {
  var controller = Controller(options);

  // Publish unless told not to
  if (options.publish !== false) controllers.push(controller);

  return controller;
};
<commit_msg>Looking for invalid resource listing section?<commit_after>// __Dependencies__
var url = require('url');
var express = require('express');
var mongoose = require('mongoose');
var Controller = require('./Controller');

// __Private Members__
var controllers = [];

function swaggerTypeFor (type) {
  if (type === String) return 'string';
  if (type === Number) return 'double';
  if (type === Date) return 'Date';
  if (type === mongoose.Schema.Types.Buffer) throw new Error('Not implemented');
  if (type === Boolean) return 'boolean';
  if (type === mongoose.Schema.Types.Mixed) throw new Error('Not implemented');
  if (type === mongoose.Schema.Types.ObjectId) return 'string';
  if (type === mongoose.Schema.Types.Oid) return 'string';
  if (type === mongoose.Schema.Types.Array) return 'Array';
  throw new Error('Unrecognized type:' + type);
};

// A method for capitalizing the first letter of a string
function capitalize (s) {
  if (!s) return s;
  if (s.length === 1) return s.toUpperCase();
  return s[0].toUpperCase() + s.substring(1);
}

// A method for generating a Swagger resource listing
function generateResourceListing (controllers) {
  var listing = {
    apiVersion: '0.0.1', // TODO
    swaggerVersion: '1.1',
    basePath: 'http://127.0.0.1:8012/api/v1', // TODO
    apis: [],
    models: {}
  };

  controllers.forEach(function (controller) {
    var modelName = capitalize(controller.get('singular'));
    listing.models[modelName] = generateModelDefinition(controller);
    listing.apis.push(generateApiDefinition(controller, true));
    //listing.apis.push(generateApiDefinition(controller, false));
  });

  return listing;
}

// A method used to generate a Swagger model definition for a controller
function generateModelDefinition (controller) {
  var definition = {};
  var schema = controller.get('schema');

  definition.id = capitalize(controller.get('singular'));
  definition.properties = {};

  Object.keys(schema.paths).forEach(function (name) {
    var property = {};
    var path = schema.paths[name];

    if (path.selected === false) return;
    // TODO also check controller options

    property.type = swaggerTypeFor(path.options.type);
    property.required = path.options.required || (name === '_id');

    // Set enum values if applicable
    if (path.enumValues && path.enumValues.length > 0) {
      property.allowableValues = { valueType: 'LIST', values: path.enumValues };
    }

    // Set allowable values range if min or max is present
    if (!isNaN(path.options.min) || !isNaN(path.options.max)) {
      property.allowableValues = { valueType: 'RANGE' };
    }

    if (!isNaN(path.options.min)) {
      property.allowableValues.min = path.options.min;
    }

    if (!isNaN(path.options.max)) {
      property.allowableValues.max = path.options.max;
    }

    definition.properties[name] = property;
  });

  return definition;
}

// A method used to generate a Swagger API definition for a controller
function generateApiDefinition (controller, plural) {
  var definition = {};

  definition.path = '/' + controller.get('plural');
  if (!plural) definition.path += '/{id}'; // TODO why is this breaking swagger-ui?

  if (plural) definition.description = 'Operations about ' + controller.get('plural');
  else definition.description = 'Operations about a given ' + controller.get('singular');

  definition.operations = [];

  controller.activeVerbs().forEach(function (verb) {
    var operation = {};
    var titlePlural = capitalize(controller.get('plural'));
    var titleSingular = capitalize(controller.get('singular'));

    // Don't do post/put for single/plural
    if (verb === 'post' && !plural) return;
    if (verb === 'put' && plural) return;

    operation.httpMethod = verb.toUpperCase();

    if (plural) operation.nickname = verb + titlePlural;
    else operation.nickname = verb + titleSingular + 'ById';

    if (plural) operation.responseClass = [ titleSingular ];
    else operation.responseClass = titleSingular;

    operation.parameters = [];

    operation.parameters.push({ // TODO
      paramType: 'query',
      name: 'skip',
      description: 'How many documents to skip.',
      dataType: 'int',
      required: false,
      allowMultiple: false
    });

    if (plural) operation.summary = capitalize(verb) + ' some ' + controller.get('plural');
    else operation.summary = capitalize(verb) + ' a ' + controller.get('singular') + ' by its unique ID';

    operation.errorResponses = []; // TODO 404

    definition.operations.push(operation);
  });

  return definition;
}

// __Module Definition__
var baucis = module.exports = function (options) {
  options || (options = {});

  var app = express();

  // Set options on the app
  Object.keys(options).forEach(function (key) {
    app.set(key, options[key]);
  });

  app.set('controllers', controllers);

  // Mount all published controllers to the baucis app
  controllers.forEach(function (controller) {
    var route = url.resolve('/', controller.get('plural'));
    controller.initialize();
    app.use(route, controller);
  });

  // Activate Swagger resource listing if the option is enabled
  if (app.get('swagger') === true) {
    app.get('/api-docs.json', function (request, response, next) {
      response.json(generateResourceListing(app.get('controllers')));
    });
  }

  controllers = [];

  return app;
};

// __Public Methods__
baucis.rest = function (options) {
  var controller = Controller(options);

  // Publish unless told not to
  if (options.publish !== false) controllers.push(controller);

  return controller;
};
<|endoftext|>


<commit_before>var loaderUtils = require('loader-utils');
var autoprefixer = require('autoprefixer');
var path = require('path');
var fs = require('fs');

module.exports = function (source) {
  if (this.cacheable) {
    this.cacheable();
  }

  var options = loaderUtils.parseQuery(this.query);
  var processed;
  var browsers = ['> 1%', 'last 2 versions',
  'Firefox ESR', 'Opera 12.1'];

  if (options.browsers) {
    if (Array.isArray(options.browsers)) {
      browsers = options.browsers;
    } else {
      browsers = options.browsers.split(',');
    }
  }

  processed = autoprefixer.apply(autoprefixer, browsers)
    .process(source);

  this.callback(null, processed.css, processed.map);
};
<commit_msg>Remove unnecessary requires<commit_after>var loaderUtils = require('loader-utils');
var autoprefixer = require('autoprefixer');

module.exports = function (source) {
  if (this.cacheable) {
    this.cacheable();
  }

  var options = loaderUtils.parseQuery(this.query);
  var processed;
  var browsers = ['> 1%', 'last 2 versions',
  'Firefox ESR', 'Opera 12.1'];

  if (options.browsers) {
    if (Array.isArray(options.browsers)) {
      browsers = options.browsers;
    } else {
      browsers = options.browsers.split(',');
    }
  }

  processed = autoprefixer.apply(autoprefixer, browsers)
    .process(source);

  this.callback(null, processed.css, processed.map);
};
<|endoftext|>


<commit_before>'use strict';

var through = require('through2')
  , pumpify = require('pumpify')
  , split = require('split')
  , regex = /^[ \t]+$/;

//
// Expose the transform.
//
module.exports = condenseify;

/**
 * Browserify transform to condense multiple blank lines
 * into a single blank line.
 *
 * @param {String} file File name
 * @param {Object} [options] Options object
 * @returns {Stream} Transform stream
 * @api public
 */
function condenseify(file, options) {
  if (/\.json$/.test(file)) return through();

  var appendNewLine = true
    , isBlank = false;

  options = options || {};

  function transform(line, encoding, next) {
    /* jshint validthis: true */
    if (!line.length) {
      isBlank = true;
      return next();
    }

    line = line.toString();
    if (!options['keep-non-empty'] && regex.test(line)) return next();

    if (isBlank) {
      isBlank = false;
      this.push('\n');
    }
    appendNewLine = false;
    this.push(line +'\n');
    next();
  }

  function flush(done) {
    /* jshint validthis: true */
    if (appendNewLine) this.push('\n');
    done();
  }

  return pumpify(split(), through(transform, flush));
}
<commit_msg>[minor] Use buffers to prevent node from doing unwanted checks<commit_after>'use strict';

var through = require('through2')
  , pumpify = require('pumpify')
  , split = require('split');

//
// Expose the transform.
//
module.exports = condenseify;

/**
 * Browserify transform to condense multiple blank lines
 * into a single blank line.
 *
 * @param {String} file File name
 * @param {Object} [options] Options object
 * @returns {Stream} Transform stream
 * @api public
 */
function condenseify(file, options) {
  if (/\.json$/.test(file)) return through();

  var eol = new Buffer('\n')
    , appendNewLine = true
    , regex = /^[ \t]+$/
    , isBlank = false;

  options = options || {};

  function transform(line, encoding, next) {
    /* jshint validthis: true */
    var length = line.length;

    if (!length) {
      isBlank = true;
      return next();
    }

    if (!options['keep-non-empty'] && regex.test(line)) return next();

    if (isBlank) {
      isBlank = false;
      this.push(eol);
    }
    appendNewLine = false;
    this.push(Buffer.concat([ line, eol ], ++length));
    next();
  }

  function flush(done) {
    /* jshint validthis: true */
    if (appendNewLine) this.push(eol);
    done();
  }

  return pumpify(split(), through(transform, flush));
}
<|endoftext|>


<commit_before>'use strict'

var Struct = require('observ-struct')
var Observ = require('observ')
var Path = require('observ-path')
var Table = require('tafel')
var series = require('run-series')
var partial = require('ap').partial
var Event = require('weakmap-event')
var filter = require('filter-pipe')
var watchIf = require('observ-listen-if/watch')
var createStore = require('weakmap-shim/create-store')
var Hooks = require('route-hook')
var assign = require('xtend/mutable')
var get = require('value-get')

var store = createStore()

function Router (data) {
  data = data || {}

  var state = Struct({
    path: Path(data.path),
    watching: Observ(false),
    active: Observ()
  })

  createTable(state)
  createHooks(state)

  watchIf(
    state.watching,
    state.path,
    partial(onPath, state)
  )

  return state
}

var NotFoundEvent = Event()
Router.onNotFound = NotFoundEvent.listen

var ErrorEvent = Event()
Router.onError = ErrorEvent.listen

Router.watch = function watch (state) {
  state.watching.set(true)
}

function onPath (state, path) {
  var match = routes(state).match(path)
  if (!match) {
    return NotFoundEvent.broadcast(state, {
      path: path
    })
  }
  Router.transition(state, match.key, match.params)
}

Router.transition = function transition (state, route, params, callback) {
  var current = hooks(state, state.active(), state.params())
  var next = hooks(state, route, params)
  var fail = partial(ErrorEvent.broadcast, state)

  series([
    partial(current, 'leave.before'),
    partial(current, 'leave.after'),
    partial(next, 'enter.before'),
    enter
  ], done)

  function enter (callback) {
    activate(state, route, params)
    callback()
    next('enter.after', filter(Boolean, fail))
  }

  function done (err) {
    if (err) fail(err)
    callback(err)
  }
}

Router.route = function route (state, options) {
  return routes(state).add(options)
}

Router.render = function render (state) {
  if (state.active) return
  return store(state.active).render()
}

function activate (state, route, params) {
  state.active.set(route)
  state.params.set(params)
}

function createTable (state) {
  store(state).table = Table()
}

function table (state) {
  return store(state).table
}

function routes (state) {
  return {
    add: add,
    match: match
  }

  function add (options) {
    var key = table(state).add(options)
    assign(store(key), options, {
      hooks: Hooks()
    })
    return key
  }

  function match (path) {
    return table(state).match(path)
  }
}

function createHooks (state) {
  store(state).hooks = Hooks()
}

function hooks (state, route, params) {
  return function runner (type, callback) {
    series([run(state), run(route, params)], callback)

    function run (key, arg) {
      return function runHooks (callback) {
        var fns = get(store(key).hooks, type).map(function (fn) {
          return partial(fn, arg)
        })
        series(fns, callback)
      }
    }
  }
}
<commit_msg>Export router<commit_after>'use strict'

var Struct = require('observ-struct')
var Observ = require('observ')
var Path = require('observ-path')
var Table = require('tafel')
var series = require('run-series')
var partial = require('ap').partial
var Event = require('weakmap-event')
var filter = require('filter-pipe')
var watchIf = require('observ-listen-if/watch')
var createStore = require('weakmap-shim/create-store')
var Hooks = require('route-hook')
var assign = require('xtend/mutable')
var get = require('value-get')

module.exports = Router

var store = createStore()

function Router (data) {
  data = data || {}

  var state = Struct({
    path: Path(data.path),
    watching: Observ(false),
    active: Observ()
  })

  createTable(state)
  createHooks(state)

  watchIf(
    state.watching,
    state.path,
    partial(onPath, state)
  )

  return state
}

var NotFoundEvent = Event()
Router.onNotFound = NotFoundEvent.listen

var ErrorEvent = Event()
Router.onError = ErrorEvent.listen

Router.watch = function watch (state) {
  state.watching.set(true)
}

function onPath (state, path) {
  var match = routes(state).match(path)
  if (!match) {
    return NotFoundEvent.broadcast(state, {
      path: path
    })
  }
  Router.transition(state, match.key, match.params)
}

Router.transition = function transition (state, route, params, callback) {
  var current = hooks(state, state.active(), state.params())
  var next = hooks(state, route, params)
  var fail = partial(ErrorEvent.broadcast, state)

  series([
    partial(current, 'leave.before'),
    partial(current, 'leave.after'),
    partial(next, 'enter.before'),
    enter
  ], done)

  function enter (callback) {
    activate(state, route, params)
    callback()
    next('enter.after', filter(Boolean, fail))
  }

  function done (err) {
    if (err) fail(err)
    callback(err)
  }
}

Router.route = function route (state, options) {
  return routes(state).add(options)
}

Router.render = function render (state) {
  if (state.active) return
  return store(state.active).render()
}

function activate (state, route, params) {
  state.active.set(route)
  state.params.set(params)
}

function createTable (state) {
  store(state).table = Table()
}

function table (state) {
  return store(state).table
}

function routes (state) {
  return {
    add: add,
    match: match
  }

  function add (options) {
    var key = table(state).add(options)
    assign(store(key), options, {
      hooks: Hooks()
    })
    return key
  }

  function match (path) {
    return table(state).match(path)
  }
}

function createHooks (state) {
  store(state).hooks = Hooks()
}

function hooks (state, route, params) {
  return function runner (type, callback) {
    series([run(state), run(route, params)], callback)

    function run (key, arg) {
      return function runHooks (callback) {
        var fns = get(store(key).hooks, type).map(function (fn) {
          return partial(fn, arg)
        })
        series(fns, callback)
      }
    }
  }
}
<|endoftext|>