<commit_before>/**
 * Copyright (c) Microsoft.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var __ = require('underscore');
var util = require('util');
var utils = require('../../../util/utils');
var $ = utils.getLocaleString;
var constants = require('./constants');
var resourceUtils = require('../resource/resourceUtils');
var tagUtils = require('../tag/tagUtils');

function ExpressRoute(cli, networkManagementClient) {
  this.networkManagementClient = networkManagementClient;
  this.output = cli.output;
  this.interaction = cli.interaction;
}

__.extend(ExpressRoute.prototype, {

  /**
   * Circuit methods.
   */
  createCircuit: function (resourceGroupName, circuitName, options, _) {
    var self = this;

    var parameters = {
      name: circuitName,
      location: options.location,
      sku: {},
      serviceProviderProperties: {
        serviceProviderName: options.serviceProviderName,
        peeringLocation: options.peeringLocation
      }
    };

    parameters = self._parseCircuit(parameters, options, true);

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" already exists in the resource group "%s"'), circuitName, resourceGroupName));
    }

    var progress = self.interaction.progress(util.format($('Creating express route circuit "%s"'), circuitName));
    try {
      circuit = self.networkManagementClient.expressRouteCircuits.createOrUpdate(resourceGroupName, circuitName, parameters, _);
    } finally {
      progress.end();
    }
    self._showCircuit(circuit, resourceGroupName, circuitName);
  },

  setCircuit: function (resourceGroupName, circuitName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('A express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    circuit = self._parseCircuit(circuit, options, false);

    var progress = self.interaction.progress(util.format($('Updating express route circuit "%s"'), circuitName));
    try {
      circuit = self.networkManagementClient.expressRouteCircuits.createOrUpdate(resourceGroupName, circuitName, circuit, _);
    } finally {
      progress.end();
    }
    self._showCircuit(circuit, resourceGroupName, circuitName);
  },

  listCircuits: function (options, _) {
    var self = this;

    var progress = self.interaction.progress($('Looking up express route circuits'));
    var circuits = null;

    try {
      if (options.resourceGroup) {
        circuits = self.networkManagementClient.expressRouteCircuits.list(options.resourceGroup, _);
      } else {
        circuits = self.networkManagementClient.expressRouteCircuits.listAll(_);
      }
    } finally {
      progress.end();
    }

    self.interaction.formatOutput(circuits, function (circuits) {
      if (circuits.length === 0) {
        self.output.warn($('No express route circuits found'));
      } else {
        self.output.table(circuits, function (row, circuit) {
          row.cell($('Name'), circuit.name);
          row.cell($('Location'), circuit.location);
          var resInfo = resourceUtils.getResourceInformation(circuit.id);
          row.cell($('Resource group'), resInfo.resourceGroup);
          row.cell($('Provisioning state'), circuit.provisioningState);
          row.cell($('Provider name'), circuit.serviceProviderProperties.serviceProviderName);
          row.cell($('Peering location'), circuit.serviceProviderProperties.peeringLocation);
          row.cell($('Bandwidth, Mbps'), circuit.serviceProviderProperties.bandwidthInMbps);
          row.cell($('Circuit state'), circuit.circuitProvisioningState);
          row.cell($('SKU'), circuit.sku.name);
        });
      }
    });
  },

  showCircuit: function (resourceGroupName, circuitName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    self._showCircuit(circuit, resourceGroupName, circuitName);
  },

  deleteCircuit: function (resourceGroupName, circuitName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    if (!options.quiet && !self.interaction.confirm(util.format($('Delete express route circuit "%s"? [y/n] '), circuitName), _)) {
      return;
    }

    var progress = self.interaction.progress(util.format($('Deleting express route circuit "%s"'), circuitName));
    try {
      self.networkManagementClient.expressRouteCircuits.deleteMethod(resourceGroupName, circuitName, _);
    } finally {
      progress.end();
    }
  },

  getCircuit: function (resourceGroupName, circuitName, _) {
    var self = this;
    var progress = self.interaction.progress(util.format($('Looking up the express route circuit "%s"'), circuitName));
    try {
      var circuit = self.networkManagementClient.expressRouteCircuits.get(resourceGroupName, circuitName, null, _);
      return circuit;
    } catch (e) {
      if (e.statusCode === 404) {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  /**
   * Service provider methods.
   */
  listProviders: function (options, _) {
    var self = this;

    var progress = self.interaction.progress($('Looking up express route service providers'));
    var providers = null;

    try {
      providers = self.networkManagementClient.expressRouteServiceProviders.list(_);
    } finally {
      progress.end();
    }

    self.interaction.formatOutput(providers, function (providers) {
      if (providers.length === 0) {
        self.output.warn($('No express route service providers found'));
      } else {
        self.output.table(providers, function (row, provider) {
          row.cell($('Name'), provider.name);
          var bandwidths = provider.properties.bandwidthsOffered.map(function (b) {
            return b.offerName;
          });
          row.cell($('Bandwidths offered'), bandwidths);
          row.cell($('Peering locations'), provider.properties.peeringLocations.join());
        });
      }
    });
  },

  /**
   * Circuit Authorization methods.
   */
  createAuthorization: function (resourceGroupName, circuitName, authName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    var circuitAuth = self.getAuthorization(resourceGroupName, circuitName, authName, _);
    if (circuitAuth) {
      throw new Error(util.format($('An express route circuit authorization with name "%s" already exists in circuit "%s" in the resource group "%s"'), authName, circuitName, resourceGroupName));
    }

    circuitAuth = {
      name: authName
    };
    if (options.key) {
      circuitAuth.authorizationKey = options.key.toString('base64');
    }

    var progress = self.interaction.progress(util.format($('Creating express route circuit authorization "%s" in circuit "%s"'), authName, circuitName));
    var circuitAuthorization;
    try {
      circuitAuthorization = self.networkManagementClient.expressRouteCircuitAuthorizations.createOrUpdate(resourceGroupName, circuitName, authName, circuitAuth, _);
    } finally {
      progress.end();
    }
    self._showCircuitAuthorization(circuitAuthorization, resourceGroupName, circuitName);
  },

  setAuthorization: function (resourceGroupName, circuitName, authName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    var circuitAuth = self.getAuthorization(resourceGroupName, circuitName, authName, _);
    if (!circuitAuth) {
      throw new Error(util.format($('An express route circuit authorization with name "%s" not found in circuit "%s" in the resource group "%s"'), authName, circuitName, resourceGroupName));
    }

    if (options.key) {
      circuitAuth.authorizationKey = options.key.toString('base64');
    }

    var progress = self.interaction.progress(util.format($('Setting express route circuit authorization "%s"in circuit "%s"'), authName, circuitName));
    var circuitAuthorization;
    try {
      circuitAuthorization = self.networkManagementClient.expressRouteCircuitAuthorizations.createOrUpdate(resourceGroupName, circuitName, authName, circuitAuth, _);
    } finally {
      progress.end();
    }

    self._showCircuitAuthorization(circuitAuthorization, resourceGroupName, circuitName);
  },

  showAuthorization: function (resourceGroupName, circuitName, authName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    var circuitAuth = self.getAuthorization(resourceGroupName, circuitName, authName, _);
    if (!circuitAuth) {
      throw new Error(util.format($('An express route circuit authorization with name "%s" not found in the circuit "%s" in resource group "%s"'), authName, circuitName, resourceGroupName));
    }

    self._showCircuitAuthorization(circuitAuth, resourceGroupName, circuitName);
  },

  deleteAuthorization: function (resourceGroupName, circuitName, authName, options, _) {
    var self = this;
    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }
    var circuitAuth = self.getAuthorization(resourceGroupName, circuitName, authName, _);
    if (!circuitAuth) {
      throw new Error(util.format($('An express route circuit authorization with name "%s" not found in the circuit "%s" in resource group "%s"'), authName, circuitName, resourceGroupName));
    }

    if (!options.quiet && !self.interaction.confirm(util.format($('Delete express route circuit authorization "%s" in circuit "%s"? [y/n] '), authName, circuitName), _)) {
      return;
    }

    var progress = self.interaction.progress(util.format($('Deleting express route circuit authorization "%s" in circuit "%s"'), authName, circuitName));
    try {
      self.networkManagementClient.expressRouteCircuitAuthorizations.deleteMethod(resourceGroupName, circuitName, authName, null, _);
    } finally {
      progress.end();
    }
  },

  listAuthorization: function (resourceGroupName, circuitName, options, _) {
    var self = this;
    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    var progress = self.interaction.progress($('Getting the express route circuit authorizations'));
    var circuits = null;
    try {
      circuits = self.networkManagementClient.expressRouteCircuitAuthorizations.list(resourceGroupName, circuitName, _);
    } finally {
      progress.end();
    }
    self.interaction.formatOutput(circuits, function (circuits) {
      if (circuits.length === 0) {
        self.output.warn($('No express route circuit authorizations found'));
      } else {
        self.output.table(circuits, function (row, circuitAuth) {
          row.cell($('Name'), circuitAuth.name);
          row.cell($('Use status'), circuitAuth.authorizationUseStatus);
          row.cell($('Provisioning state'), circuitAuth.provisioningState);
        });
      }
    });
  },

  getAuthorization: function (resourceGroupName, circuitName, authName, _) {
    var self = this;
    var progress = self.interaction.progress(util.format($('Looking up the express route circuit authorization "%s" in circuit "%s"'), authName, circuitName));
    try {
      var circuit = self.networkManagementClient.expressRouteCircuitAuthorizations.get(resourceGroupName, circuitName, authName, null, _);
      return circuit;
    } catch (e) {
      if (e.statusCode === 404) {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  /**
   * Private methods
   */
  _parseCircuit: function (circuit, options, useDefaults) {
    var self = this;

    if (options.bandwidthInMbps) {
      if (isNaN(options.bandwidthInMbps)) {
        throw new Error($('--bandwidth-in-mbps parameter must be an integer'));
      }
      circuit.serviceProviderProperties.bandwidthInMbps = parseInt(options.bandwidthInMbps);
    } else if (useDefaults) {
      var defBandwidth = constants.expressRoute.defBandwidthInMbps;
      self.output.warn(util.format($('Using default bandwidth: %s'), defBandwidth));
      circuit.serviceProviderProperties.bandwidthInMbps = defBandwidth;
    }

    if (options.skuTier) {
      circuit.sku.tier = utils.verifyParamExistsInCollection(constants.expressRoute.tier, options.skuTier, '--sku-tier');
    } else if (useDefaults) {
      var defTier = constants.expressRoute.tier[0];
      self.output.warn(util.format($('Using default sku tier: %s'), defTier));
      circuit.sku.tier = defTier;
    }

    if (options.skuFamily) {
      circuit.sku.family = utils.verifyParamExistsInCollection(constants.expressRoute.family, options.skuFamily, '--sku-family');
    } else if (useDefaults) {
      var defFamily = constants.expressRoute.family[0];
      self.output.warn(util.format($('Using default sku family: %s'), defFamily));
      circuit.sku.family = defFamily;
    }

    if (circuit.sku.tier && circuit.sku.family) {
      circuit.sku.name = circuit.sku.tier + '_' + circuit.sku.family;
    }

    if (options.tags) {
      if (utils.argHasValue(options.tags)) {
        tagUtils.appendTags(circuit, options);
      } else {
        circuit.tags = {};
      }
    }

    return circuit;
  },

  _showCircuit: function (circuit, resourceGroupName, circuitName) {
    var self = this;

    self.interaction.formatOutput(circuit, function (circuit) {
      if (circuit === null) {
        self.output.warn(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
        return;
      }

      self.output.nameValue($('Id'), circuit.id);
      self.output.nameValue($('Name'), circuit.name);
      self.output.nameValue($('Type'), circuit.type);
      self.output.nameValue($('Location'), circuit.location);
      self.output.nameValue($('Provisioning state'), circuit.provisioningState);
      self.output.nameValue($('Tags'), tagUtils.getTagsInfo(circuit.tags));
      self.output.nameValue($('Circuit provisioning state'), circuit.circuitProvisioningState);
      self.output.nameValue($('Service Key'), circuit.serviceKey);

      self.output.header($('Service provider'));
      self.output.nameValue($('Name'), circuit.serviceProviderProperties.serviceProviderName, 2);
      self.output.nameValue($('Provisioning state'), circuit.serviceProviderProvisioningState, 2);
      self.output.nameValue($('Peering location'), circuit.serviceProviderProperties.peeringLocation, 2);
      self.output.nameValue($('Bandwidth in Mbps'), circuit.serviceProviderProperties.bandwidthInMbps, 2);

      self.output.header($('SKU'));
      self.output.nameValue($('Name'), circuit.sku.name, 2);
      self.output.nameValue($('Tier'), circuit.sku.tier, 2);
      self.output.nameValue($('Family'), circuit.sku.family, 2);
    });
  },

  _showCircuitAuthorization: function (circuitAuth, resourceGroupName, circuitName) {
    var self = this;

    self.interaction.formatOutput(circuitAuth, function (circuitAuth) {
      if (circuitAuth === null) {
        self.output.warn(util.format($('An express route circuit authorization with name "%s" not found in the circuit "%s" in resource group "%s"'), name, circuitName, resourceGroupName));
        return;
      }

      var resourceInfo = resourceUtils.getResourceInformation(circuitAuth.id);
      self.output.nameValue($('Id'), circuitAuth.id);
      self.output.nameValue($('Name'), circuitAuth.name);
      self.output.nameValue($('Type'), resourceInfo.resourceType);
      self.output.nameValue($('Use status'), circuitAuth.authorizationUseStatus);
      self.output.nameValue($('Authorization Key'), circuitAuth.authorizationKey);
      self.output.nameValue($('Provisioning state'), circuitAuth.provisioningState);
    });
  }
});

module.exports = ExpressRoute;<commit_msg>Removed extra-error message when ARM express-route authorization item was not found.<commit_after>/**
 * Copyright (c) Microsoft.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var __ = require('underscore');
var util = require('util');
var utils = require('../../../util/utils');
var $ = utils.getLocaleString;
var constants = require('./constants');
var resourceUtils = require('../resource/resourceUtils');
var tagUtils = require('../tag/tagUtils');

function ExpressRoute(cli, networkManagementClient) {
  this.networkManagementClient = networkManagementClient;
  this.output = cli.output;
  this.interaction = cli.interaction;
}

__.extend(ExpressRoute.prototype, {

  /**
   * Circuit methods.
   */
  createCircuit: function (resourceGroupName, circuitName, options, _) {
    var self = this;

    var parameters = {
      name: circuitName,
      location: options.location,
      sku: {},
      serviceProviderProperties: {
        serviceProviderName: options.serviceProviderName,
        peeringLocation: options.peeringLocation
      }
    };

    parameters = self._parseCircuit(parameters, options, true);

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" already exists in the resource group "%s"'), circuitName, resourceGroupName));
    }

    var progress = self.interaction.progress(util.format($('Creating express route circuit "%s"'), circuitName));
    try {
      circuit = self.networkManagementClient.expressRouteCircuits.createOrUpdate(resourceGroupName, circuitName, parameters, _);
    } finally {
      progress.end();
    }
    self._showCircuit(circuit, resourceGroupName, circuitName);
  },

  setCircuit: function (resourceGroupName, circuitName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('A express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    circuit = self._parseCircuit(circuit, options, false);

    var progress = self.interaction.progress(util.format($('Updating express route circuit "%s"'), circuitName));
    try {
      circuit = self.networkManagementClient.expressRouteCircuits.createOrUpdate(resourceGroupName, circuitName, circuit, _);
    } finally {
      progress.end();
    }
    self._showCircuit(circuit, resourceGroupName, circuitName);
  },

  listCircuits: function (options, _) {
    var self = this;

    var progress = self.interaction.progress($('Looking up express route circuits'));
    var circuits = null;

    try {
      if (options.resourceGroup) {
        circuits = self.networkManagementClient.expressRouteCircuits.list(options.resourceGroup, _);
      } else {
        circuits = self.networkManagementClient.expressRouteCircuits.listAll(_);
      }
    } finally {
      progress.end();
    }

    self.interaction.formatOutput(circuits, function (circuits) {
      if (circuits.length === 0) {
        self.output.warn($('No express route circuits found'));
      } else {
        self.output.table(circuits, function (row, circuit) {
          row.cell($('Name'), circuit.name);
          row.cell($('Location'), circuit.location);
          var resInfo = resourceUtils.getResourceInformation(circuit.id);
          row.cell($('Resource group'), resInfo.resourceGroup);
          row.cell($('Provisioning state'), circuit.provisioningState);
          row.cell($('Provider name'), circuit.serviceProviderProperties.serviceProviderName);
          row.cell($('Peering location'), circuit.serviceProviderProperties.peeringLocation);
          row.cell($('Bandwidth, Mbps'), circuit.serviceProviderProperties.bandwidthInMbps);
          row.cell($('Circuit state'), circuit.circuitProvisioningState);
          row.cell($('SKU'), circuit.sku.name);
        });
      }
    });
  },

  showCircuit: function (resourceGroupName, circuitName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    self._showCircuit(circuit, resourceGroupName, circuitName);
  },

  deleteCircuit: function (resourceGroupName, circuitName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    if (!options.quiet && !self.interaction.confirm(util.format($('Delete express route circuit "%s"? [y/n] '), circuitName), _)) {
      return;
    }

    var progress = self.interaction.progress(util.format($('Deleting express route circuit "%s"'), circuitName));
    try {
      self.networkManagementClient.expressRouteCircuits.deleteMethod(resourceGroupName, circuitName, _);
    } finally {
      progress.end();
    }
  },

  getCircuit: function (resourceGroupName, circuitName, _) {
    var self = this;
    var progress = self.interaction.progress(util.format($('Looking up the express route circuit "%s"'), circuitName));
    try {
      var circuit = self.networkManagementClient.expressRouteCircuits.get(resourceGroupName, circuitName, null, _);
      return circuit;
    } catch (e) {
      if (e.statusCode === 404) {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  /**
   * Service provider methods.
   */
  listProviders: function (options, _) {
    var self = this;

    var progress = self.interaction.progress($('Looking up express route service providers'));
    var providers = null;

    try {
      providers = self.networkManagementClient.expressRouteServiceProviders.list(_);
    } finally {
      progress.end();
    }

    self.interaction.formatOutput(providers, function (providers) {
      if (providers.length === 0) {
        self.output.warn($('No express route service providers found'));
      } else {
        self.output.table(providers, function (row, provider) {
          row.cell($('Name'), provider.name);
          var bandwidths = provider.properties.bandwidthsOffered.map(function (b) {
            return b.offerName;
          });
          row.cell($('Bandwidths offered'), bandwidths);
          row.cell($('Peering locations'), provider.properties.peeringLocations.join());
        });
      }
    });
  },

  /**
   * Circuit Authorization methods.
   */
  createAuthorization: function (resourceGroupName, circuitName, authName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    var circuitAuth = self.getAuthorization(resourceGroupName, circuitName, authName, _);
    if (circuitAuth) {
      throw new Error(util.format($('An express route circuit authorization with name "%s" already exists in circuit "%s" in the resource group "%s"'), authName, circuitName, resourceGroupName));
    }

    circuitAuth = {
      name: authName
    };
    if (options.key) {
      circuitAuth.authorizationKey = options.key.toString('base64');
    }

    var progress = self.interaction.progress(util.format($('Creating express route circuit authorization "%s" in circuit "%s"'), authName, circuitName));
    var circuitAuthorization;
    try {
      circuitAuthorization = self.networkManagementClient.expressRouteCircuitAuthorizations.createOrUpdate(resourceGroupName, circuitName, authName, circuitAuth, _);
    } finally {
      progress.end();
    }
    self._showCircuitAuthorization(circuitAuthorization, resourceGroupName, circuitName);
  },

  setAuthorization: function (resourceGroupName, circuitName, authName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    var circuitAuth = self.getAuthorization(resourceGroupName, circuitName, authName, _);
    if (!circuitAuth) {
      throw new Error(util.format($('An express route circuit authorization with name "%s" not found in circuit "%s" in the resource group "%s"'), authName, circuitName, resourceGroupName));
    }

    if (options.key) {
      circuitAuth.authorizationKey = options.key.toString('base64');
    }

    var progress = self.interaction.progress(util.format($('Setting express route circuit authorization "%s"in circuit "%s"'), authName, circuitName));
    var circuitAuthorization;
    try {
      circuitAuthorization = self.networkManagementClient.expressRouteCircuitAuthorizations.createOrUpdate(resourceGroupName, circuitName, authName, circuitAuth, _);
    } finally {
      progress.end();
    }

    self._showCircuitAuthorization(circuitAuthorization, resourceGroupName, circuitName);
  },

  showAuthorization: function (resourceGroupName, circuitName, authName, options, _) {
    var self = this;

    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    var circuitAuth = self.getAuthorization(resourceGroupName, circuitName, authName, _);
    self._showCircuitAuthorization(circuitAuth, resourceGroupName, circuitName);
  },

  deleteAuthorization: function (resourceGroupName, circuitName, authName, options, _) {
    var self = this;
    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }
    var circuitAuth = self.getAuthorization(resourceGroupName, circuitName, authName, _);
    if (!circuitAuth) {
      throw new Error(util.format($('An express route circuit authorization with name "%s" not found in the circuit "%s" in resource group "%s"'), authName, circuitName, resourceGroupName));
    }

    if (!options.quiet && !self.interaction.confirm(util.format($('Delete express route circuit authorization "%s" in circuit "%s"? [y/n] '), authName, circuitName), _)) {
      return;
    }

    var progress = self.interaction.progress(util.format($('Deleting express route circuit authorization "%s" in circuit "%s"'), authName, circuitName));
    try {
      self.networkManagementClient.expressRouteCircuitAuthorizations.deleteMethod(resourceGroupName, circuitName, authName, null, _);
    } finally {
      progress.end();
    }
  },

  listAuthorization: function (resourceGroupName, circuitName, options, _) {
    var self = this;
    var circuit = self.getCircuit(resourceGroupName, circuitName, _);
    if (!circuit) {
      throw new Error(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
    }

    var progress = self.interaction.progress($('Getting the express route circuit authorizations'));
    var circuits = null;
    try {
      circuits = self.networkManagementClient.expressRouteCircuitAuthorizations.list(resourceGroupName, circuitName, _);
    } finally {
      progress.end();
    }
    self.interaction.formatOutput(circuits, function (circuits) {
      if (circuits.length === 0) {
        self.output.warn($('No express route circuit authorizations found'));
      } else {
        self.output.table(circuits, function (row, circuitAuth) {
          row.cell($('Name'), circuitAuth.name);
          row.cell($('Use status'), circuitAuth.authorizationUseStatus);
          row.cell($('Provisioning state'), circuitAuth.provisioningState);
        });
      }
    });
  },

  getAuthorization: function (resourceGroupName, circuitName, authName, _) {
    var self = this;
    var progress = self.interaction.progress(util.format($('Looking up the express route circuit authorization "%s" in circuit "%s"'), authName, circuitName));
    try {
      var circuit = self.networkManagementClient.expressRouteCircuitAuthorizations.get(resourceGroupName, circuitName, authName, null, _);
      return circuit;
    } catch (e) {
      if (e.statusCode === 404) {
        return null;
      }
      throw e;
    } finally {
      progress.end();
    }
  },

  /**
   * Private methods
   */
  _parseCircuit: function (circuit, options, useDefaults) {
    var self = this;

    if (options.bandwidthInMbps) {
      if (isNaN(options.bandwidthInMbps)) {
        throw new Error($('--bandwidth-in-mbps parameter must be an integer'));
      }
      circuit.serviceProviderProperties.bandwidthInMbps = parseInt(options.bandwidthInMbps);
    } else if (useDefaults) {
      var defBandwidth = constants.expressRoute.defBandwidthInMbps;
      self.output.warn(util.format($('Using default bandwidth: %s'), defBandwidth));
      circuit.serviceProviderProperties.bandwidthInMbps = defBandwidth;
    }

    if (options.skuTier) {
      circuit.sku.tier = utils.verifyParamExistsInCollection(constants.expressRoute.tier, options.skuTier, '--sku-tier');
    } else if (useDefaults) {
      var defTier = constants.expressRoute.tier[0];
      self.output.warn(util.format($('Using default sku tier: %s'), defTier));
      circuit.sku.tier = defTier;
    }

    if (options.skuFamily) {
      circuit.sku.family = utils.verifyParamExistsInCollection(constants.expressRoute.family, options.skuFamily, '--sku-family');
    } else if (useDefaults) {
      var defFamily = constants.expressRoute.family[0];
      self.output.warn(util.format($('Using default sku family: %s'), defFamily));
      circuit.sku.family = defFamily;
    }

    if (circuit.sku.tier && circuit.sku.family) {
      circuit.sku.name = circuit.sku.tier + '_' + circuit.sku.family;
    }

    if (options.tags) {
      if (utils.argHasValue(options.tags)) {
        tagUtils.appendTags(circuit, options);
      } else {
        circuit.tags = {};
      }
    }

    return circuit;
  },

  _showCircuit: function (circuit, resourceGroupName, circuitName) {
    var self = this;

    self.interaction.formatOutput(circuit, function (circuit) {
      if (circuit === null) {
        self.output.warn(util.format($('An express route circuit with name "%s" not found in the resource group "%s"'), circuitName, resourceGroupName));
        return;
      }

      self.output.nameValue($('Id'), circuit.id);
      self.output.nameValue($('Name'), circuit.name);
      self.output.nameValue($('Type'), circuit.type);
      self.output.nameValue($('Location'), circuit.location);
      self.output.nameValue($('Provisioning state'), circuit.provisioningState);
      self.output.nameValue($('Tags'), tagUtils.getTagsInfo(circuit.tags));
      self.output.nameValue($('Circuit provisioning state'), circuit.circuitProvisioningState);
      self.output.nameValue($('Service Key'), circuit.serviceKey);

      self.output.header($('Service provider'));
      self.output.nameValue($('Name'), circuit.serviceProviderProperties.serviceProviderName, 2);
      self.output.nameValue($('Provisioning state'), circuit.serviceProviderProvisioningState, 2);
      self.output.nameValue($('Peering location'), circuit.serviceProviderProperties.peeringLocation, 2);
      self.output.nameValue($('Bandwidth in Mbps'), circuit.serviceProviderProperties.bandwidthInMbps, 2);

      self.output.header($('SKU'));
      self.output.nameValue($('Name'), circuit.sku.name, 2);
      self.output.nameValue($('Tier'), circuit.sku.tier, 2);
      self.output.nameValue($('Family'), circuit.sku.family, 2);
    });
  },

  _showCircuitAuthorization: function (circuitAuth, resourceGroupName, circuitName) {
    var self = this;

    self.interaction.formatOutput(circuitAuth, function (circuitAuth) {
      if (circuitAuth === null) {
        self.output.warn(util.format($('An express route circuit authorization with name "%s" not found in the circuit "%s" in resource group "%s"'), name, circuitName, resourceGroupName));
        return;
      }

      var resourceInfo = resourceUtils.getResourceInformation(circuitAuth.id);
      self.output.nameValue($('Id'), circuitAuth.id);
      self.output.nameValue($('Name'), circuitAuth.name);
      self.output.nameValue($('Type'), resourceInfo.resourceType);
      self.output.nameValue($('Use status'), circuitAuth.authorizationUseStatus);
      self.output.nameValue($('Authorization Key'), circuitAuth.authorizationKey);
      self.output.nameValue($('Provisioning state'), circuitAuth.provisioningState);
    });
  }
});

module.exports = ExpressRoute;<|endoftext|>


<commit_before>import { FMRS_MA_2018 } from '../../../data/state/massachusetts/2018/FMRS_MA_2018';

/** Get maximum benefit/subsidy amount for client from Section 8 Project-Based
* Voucher program. Please allow the client to put in their own subsidy amount
* if needed since custom amounts are totally a thing that happen (like the PHA
* requesting a standard that is higher than 110%). An accurate amount is important
* when calculating eligibility/amounts from other benefit programs.
* Once you're enrolled in the program, which our interface is
* currently assuming to be the case, you stay in it. There are
* reasons that you leave it, but we have to discuss with the
* case managers what they want to do about those. They're weird.
* There will be extra info if subsidy amount is $0, though.
*
* @function
* @since 09/2017
*
* @see trello: https://trello.com/c/EIt2BCMQ/53-housing-choice-voucher-section-8-pseudocode-doc
* @see docs: https://docs.google.com/spreadsheets/d/14FFcrEwZVTJDc00X7V4XkicE3NYVVF0lijV1jMLe--Y/edit#gid=1209051854
* @see docs: https://docs.google.com/spreadsheets/d/14FFcrEwZVTJDc00X7V4XkicE3NYVVF0lijV1jMLe--Y/edit#gid=1209051854 (recommended by Kristin, Project Hope staff)
* @see gathered info: https://docs.google.com/spreadsheets/d/14FFcrEwZVTJDc00X7V4XkicE3NYVVF0lijV1jMLe--Y/edit#gid=1209051854
* @see codepen test: https://codepen.io/knod/pen/oeOpRz?editors=0010
*
* @todo Find out how close to 0 the benefit amount needs
* to be in order for the client to be warned.
*/
var getHousingEligibility = function ( client ) {
	/** @todo Maybe allow client to put in a custom rent amount, but
	* should be warned that this amount may not be accurate either
	* because in some cases calculations and estimates have to be made
	* for essential utilitie allowances if utilities aren't included in
	* the rent amount. Maybe a custom subsidy amount would be better?
	*/

	// Send it right back if it's missing input values
	var props = propsNeeded( client )
	if ( props.length ) {
		var details = "Not enough information. These fields need to be filled in: ";
		for (let propi = 0; propi < props.length; propi++) {
			let prop = props[ propi ];
			details += prop;
			if ( propi < props.length - 1 ) { details += ", "; }
			else { details += "."; }
		};
		return { result: "information", details: details }
	}

	// Not sure about this part
    if ( typeof client.customRentSubsidyAmount === 'number' ) {
    	return subsidyResult( client.customRentSubsidyAmount );
    }

    // (24 CFR 5.611 https://www.ecfr.gov/cgi-bin/text-idx?SID=51891282d9b5314112b0b2462cb22681&mc=true&node=se24.1.5_1611&rgn=div8, https://www.hudexchange.info/resources/documents/incomeresidentrentcalc.pdf)
    var adjusted 	= (30/100) * client.householdMonthlyAdjustedIncome,
    // (24CFR5.609 (linked from http://www.tacinc.org/media/58886/S8MS%20Full%20Book.pdf) https://www.hudexchange.info/resources/documents/incomeresidentrentcalc.pdf)
    	gross 		= 0.1 * client.householdMonthlyGrossIncome,
	// welfare rent (Does MA have welfare rent? If so, how is it calculated?
	// Does the client know the amount?)
    	welfareRent = client.welfareRent || 0,
	// Possibly also the public housing agency's own minimum rent, which doesn't
	// always exist, can be different amounts, and can sometimes we waived (pg 63 of "Book")
		PHAMinRent 	= client.PHAMinRent || 0;

	// TTP = total tenant payment
    var minTTP = Math.max( adjusted, gross, welfareRent, PHAMinRent ),
    	estimatedRent = FMRS_MA_2018[ client.areaOfResidence ][ client.numberOfBedrooms ],
	// The maximum amount a PHA (public housing agency) can give to client has a range
	// of 90% to 110% depending on how it choose to do things.
	// We're currently going to assume the minimum of that range. That is, we're going
	// to assume a PHA with a standard that sets their maximum subsidy at 90%. In this
	// way if we mislead the client, it'll at least be in a cautious direction. Maybe
	// allow the client to override that value if they want.
		maxSubsidyAllowedMin = estimatedRent * 0.9,
	// Actual subsidy takes into account what the client can pay
		subsidy = maxSubsidyAllowedMin - minTTP;

	var result = subsidyResult( subsidy );

	return result;
}

var subsidyResult = function ( subsidyAmount ) {
	/** @todo Include a warning somewhere about items
	* that are uncertain. Also, maybe provide option to
	* give even more detailed info, like that particular
	* PHA's min rent amount, the PHA's percent for their
	* standard, or just the PHA's flat subsidy amount for
	* that apartment (before other things like minTTP are
	* factored in). (This for all programs ideally. Of
	* course this whole todo is a dream goal...)
	*/
	var result = { result: 'good', details: 'All good!', benefitValue: Math.max( 0, Math.round( subsidyAmount ) ) };

	if ( subsidyAmount <= 0 ) {
		result.result 	= 'information';
		/** @todo Check accuracy of language used. */
		result.details 	= 'Your PHA must allow you the option of continuing in the HCV program for six more months. Without selecting to continue, you will be unenrolled.';
	} else if ( subsidyAmount <= 50 ) {
		result.result 	= 'information';
		/** @todo Give more specific message about which limit is getting hit. Not sure how to judge which limit is the one that's getting close, though. */
		result.details 	= 'Your income amount means your subsidy is close to $0. When it gets to $0 you might be unenrolled from the HCV program, but you should be able to choose an option to extend your enrollment.';
  }

	return result;
};  // End subsidyResult()

var requiredProps = [
	"householdMonthlyAdjustedIncome",
	"householdMonthlyGrossIncome",
	"areaOfResidence",
	"numberOfBedrooms"
];

var propsNeeded = function ( client ) {

	var missingProps = [];

	for ( let propi = 0; propi < requiredProps.length; propi++ ) {
		let key = requiredProps[ propi ];
		if ( client[ key ] === undefined ) { missingProps.push( key ); }
	}

	return missingProps;
};  // End propsNeeded()

export { getHousingEligibility };
<commit_msg>Uses new `Result` object in housing.js<commit_after>import { FMRS_MA_2018 } from '../../../data/state/massachusetts/2018/FMRS_MA_2018';
import { Result } from '../../../helpers/Result';

/** Get maximum benefit/subsidy amount for client from Section 8 Project-Based
* Voucher program. Please allow the client to put in their own subsidy amount
* if needed since custom amounts are totally a thing that happen (like the PHA
* requesting a standard that is higher than 110%). An accurate amount is important
* when calculating eligibility/amounts from other benefit programs.
* Once you're enrolled in the program, which our interface is
* currently assuming to be the case, you stay in it. There are
* reasons that you leave it, but we have to discuss with the
* case managers what they want to do about those. They're weird.
* There will be extra info if subsidy amount is $0, though.
*
* @function
* @since 09/2017
*
* @see trello: https://trello.com/c/EIt2BCMQ/53-housing-choice-voucher-section-8-pseudocode-doc
* @see docs: https://docs.google.com/spreadsheets/d/14FFcrEwZVTJDc00X7V4XkicE3NYVVF0lijV1jMLe--Y/edit#gid=1209051854
* @see docs: https://docs.google.com/spreadsheets/d/14FFcrEwZVTJDc00X7V4XkicE3NYVVF0lijV1jMLe--Y/edit#gid=1209051854 (recommended by Kristin, Project Hope staff)
* @see gathered info: https://docs.google.com/spreadsheets/d/14FFcrEwZVTJDc00X7V4XkicE3NYVVF0lijV1jMLe--Y/edit#gid=1209051854
* @see codepen test: https://codepen.io/knod/pen/oeOpRz?editors=0010
*
* @todo Find out how close to 0 the benefit amount needs
* to be in order for the client to be warned.
*/
var getHousingEligibility = function ( client ) {
	/** @todo Maybe allow client to put in a custom rent amount, but
	* should be warned that this amount may not be accurate either
	* because in some cases calculations and estimates have to be made
	* for essential utilitie allowances if utilities aren't included in
	* the rent amount. Maybe a custom subsidy amount would be better?
	*/

	// Send it right back if it's missing input values
	var props = propsNeeded( client )
	if ( props.length ) {

		// var details = 'Not enough information. These fields need to be filled in: ';
		// for (let propi = 0; propi < props.length; propi++) {
		// 	let prop = props[ propi ];
		// 	details += prop;
		// 	if ( propi < props.length - 1 ) { details += ', '; }
		// 	else { details += '.'; }
		// };

		// Until we have some reliable way of knowing the right names for the fields:
		var details = 'Some required form fields have\'t been filled in yet.';

		var result = new Result( { result: 'information', details: details } );

		return result;
	}

	// Not sure about this part
    if ( typeof client.customRentSubsidyAmount === 'number' ) {
    	return subsidyResult( client.customRentSubsidyAmount );
    }

    // (24 CFR 5.611 https://www.ecfr.gov/cgi-bin/text-idx?SID=51891282d9b5314112b0b2462cb22681&mc=true&node=se24.1.5_1611&rgn=div8, https://www.hudexchange.info/resources/documents/incomeresidentrentcalc.pdf)
    var adjusted 	= (30/100) * client.householdMonthlyAdjustedIncome,
    // (24CFR5.609 (linked from http://www.tacinc.org/media/58886/S8MS%20Full%20Book.pdf) https://www.hudexchange.info/resources/documents/incomeresidentrentcalc.pdf)
    	gross 		= 0.1 * client.householdMonthlyGrossIncome,
	// welfare rent (Does MA have welfare rent? If so, how is it calculated?
	// Does the client know the amount?)
    	welfareRent = client.welfareRent || 0,
	// Possibly also the public housing agency's own minimum rent, which doesn't
	// always exist, can be different amounts, and can sometimes we waived (pg 63 of 'Book')
		PHAMinRent 	= client.PHAMinRent || 0;

	// TTP = total tenant payment
    var minTTP = Math.max( adjusted, gross, welfareRent, PHAMinRent ),
    	estimatedRent = FMRS_MA_2018[ client.areaOfResidence ][ client.numberOfBedrooms ],
	// The maximum amount a PHA (public housing agency) can give to client has a range
	// of 90% to 110% depending on how it choose to do things.
	// We're currently going to assume the minimum of that range. That is, we're going
	// to assume a PHA with a standard that sets their maximum subsidy at 90%. In this
	// way if we mislead the client, it'll at least be in a cautious direction. Maybe
	// allow the client to override that value if they want.
		maxSubsidyAllowedMin = estimatedRent * 0.9,
	// Actual subsidy takes into account what the client can pay
		subsidy = maxSubsidyAllowedMin - minTTP;

	var result = subsidyResult( subsidy );

	return result;
}

var subsidyResult = function ( subsidyAmount ) {
	/** @todo Include a warning somewhere about items
	* that are uncertain. Also, maybe provide option to
	* give even more detailed info, like that particular
	* PHA's min rent amount, the PHA's percent for their
	* standard, or just the PHA's flat subsidy amount for
	* that apartment (before other things like minTTP are
	* factored in). (This for all programs ideally. Of
	* course this whole todo is a dream goal...)
	*/
	var result = { result: 'good', details: 'All good!', benefitValue: Math.max( 0, Math.round( subsidyAmount ) ) };

	if ( subsidyAmount <= 0 ) {
		result.result 	= 'information';
		/** @todo Check accuracy of language used. */
		result.details 	= 'Your PHA must allow you the option of continuing in the HCV program for six more months. Without selecting to continue, you will be unenrolled.';
	} else if ( subsidyAmount <= 50 ) {
		result.result 	= 'information';
		/** @todo Give more specific message about which limit is getting hit. Not sure how to judge which limit is the one that's getting close, though. */
		result.details 	= 'Your income amount means your subsidy is close to $0. When it gets to $0 you might be unenrolled from the HCV program, but you should be able to choose an option to extend your enrollment.';
  }

	return result;
};  // End subsidyResult()

var requiredProps = [
	'householdMonthlyAdjustedIncome',
	'householdMonthlyGrossIncome',
	'areaOfResidence',
	'numberOfBedrooms'
];

var propsNeeded = function ( client ) {

	var missingProps = [];

	for ( let propi = 0; propi < requiredProps.length; propi++ ) {
		let key = requiredProps[ propi ];
		if ( client[ key ] === undefined ) { missingProps.push( key ); }
	}

	return missingProps;
};  // End propsNeeded()

export { getHousingEligibility };
<|endoftext|>


<commit_before>import * as Adapter from './adapter.js';
import bidfactory from 'src/bidfactory';
import bidmanager from 'src/bidmanager';
import * as utils from 'src/utils';
import { ajax } from 'src/ajax';
import { STATUS } from 'src/constants';

const RUBICON_BIDDER_CODE = 'rubicon';

// use deferred function call since version isn't defined yet at this point
function getIntegration() {
  return 'pbjs_lite_' + $$PREBID_GLOBAL$$.version;
}

function isSecure() {
  return location.protocol === 'https:';
}

// use protocol relative urls for http or https
const FASTLANE_ENDPOINT = '//fastlane.rubiconproject.com/a/api/fastlane.json';
const VIDEO_ENDPOINT = '//fastlane-adv.rubiconproject.com/v1/auction/video';

const TIMEOUT_BUFFER = 500;

var sizeMap = {
  1: '468x60',
  2: '728x90',
  8: '120x600',
  9: '160x600',
  10: '300x600',
  15: '300x250',
  16: '336x280',
  19: '300x100',
  31: '980x120',
  32: '250x360',
  33: '180x500',
  35: '980x150',
  37: '468x400',
  38: '930x180',
  43: '320x50',
  44: '300x50',
  48: '300x300',
  54: '300x1050',
  55: '970x90',
  57: '970x250',
  58: '1000x90',
  59: '320x80',
  61: '1000x1000',
  65: '640x480',
  67: '320x480',
  68: '1800x1000',
  72: '320x320',
  73: '320x160',
  78: '980x240',
  79: '980x300',
  80: '980x400',
  83: '480x300',
  94: '970x310',
  96: '970x210',
  101: '480x320',
  102: '768x1024',
  103: '480x280',
  113: '1000x300',
  117: '320x100',
  125: '800x250',
  126: '200x600'
};
utils._each(sizeMap, (item, key) => sizeMap[item] = key);

function RubiconAdapter() {
  function _callBids(bidderRequest) {
    var bids = bidderRequest.bids || [];

    bids.forEach(bid => {
      try {
        // Video endpoint only accepts POST calls
        if (bid.mediaType === 'video') {
          ajax(
            VIDEO_ENDPOINT,
            {
              success: bidCallback,
              error: bidError
            },
            buildVideoRequestPayload(bid, bidderRequest),
            {
              withCredentials: true
            }
          );
        } else {
          ajax(
            buildOptimizedCall(bid),
            {
              success: bidCallback,
              error: bidError
            },
            undefined,
            {
              withCredentials: true
            }
          );
        }
      } catch (err) {
        utils.logError('Error sending rubicon request for placement code ' + bid.placementCode, null, err);
        addErrorBid();
      }

      function bidCallback(responseText) {
        try {
          utils.logMessage('XHR callback function called for ad ID: ' + bid.bidId);
          handleRpCB(responseText, bid);
        } catch (err) {
          if (typeof err === 'string') {
            utils.logWarn(`${err} when processing rubicon response for placement code ${bid.placementCode}`);
          } else {
            utils.logError('Error processing rubicon response for placement code ' + bid.placementCode, null, err);
          }
          addErrorBid();
        }
      }

      function bidError(err, xhr) {
        utils.logError('Request for rubicon responded with:', xhr.status, err);
        addErrorBid();
      }

      function addErrorBid() {
        let badBid = bidfactory.createBid(STATUS.NO_BID, bid);
        badBid.bidderCode = bid.bidder;
        bidmanager.addBidResponse(bid.placementCode, badBid);
      }
    });
  }

  function _getScreenResolution() {
    return [window.screen.width, window.screen.height].join('x');
  }

  function _getDigiTrustQueryParams() {
    function getDigiTrustId() {
      let digiTrustUser = window.DigiTrust && window.DigiTrust.getUser({member: 'T9QSFKPDN9'});
      return digiTrustUser && digiTrustUser.success && digiTrustUser.identity || null;
    }
    let digiTrustId = getDigiTrustId();
    // Verify there is an ID and this user has not opted out
    if (!digiTrustId || digiTrustId.privacy && digiTrustId.privacy.optout) {
      return [];
    }
    return [
      'dt.id', digiTrustId.id,
      'dt.keyv', digiTrustId.keyv
    ];
  }

  function buildVideoRequestPayload(bid, bidderRequest) {
    bid.startTime = new Date().getTime();

    let params = bid.params;

    if (!params || typeof params.video !== 'object') {
      throw 'Invalid Video Bid';
    }

    let size;
    if (params.video.playerWidth && params.video.playerHeight) {
      size = [
        params.video.playerWidth,
        params.video.playerHeight
      ];
    } else if (
        Array.isArray(bid.sizes) && bid.sizes.length > 0 &&
        Array.isArray(bid.sizes[0]) && bid.sizes[0].length > 1
    ) {
      size = bid.sizes[0];
    } else {
      throw 'Invalid Video Bid - No size provided';
    }

    let postData = {
      page_url: !params.referrer ? utils.getTopWindowUrl() : params.referrer,
      resolution: _getScreenResolution(),
      account_id: params.accountId,
      integration: getIntegration(),
      timeout: bidderRequest.timeout - (Date.now() - bidderRequest.auctionStart + TIMEOUT_BUFFER),
      stash_creatives: true,
      ae_pass_through_parameters: params.video.aeParams,
      slots: []
    };

    // Define the slot object
    let slotData = {
      site_id: params.siteId,
      zone_id: params.zoneId,
      position: params.position || 'btf',
      floor: parseFloat(params.floor) > 0.01 ? params.floor : 0.01,
      element_id: bid.placementCode,
      name: bid.placementCode,
      language: params.video.language,
      width: size[0],
      height: size[1]
    };

    // check and add inventory, keywords, visitor and size_id data
    if (params.video.size_id) {
      slotData.size_id = params.video.size_id;
    } else {
      throw 'Invalid Video Bid - Invalid Ad Type!';
    }

    if (params.inventory && typeof params.inventory === 'object') {
      slotData.inventory = params.inventory;
    }

    if (params.keywords && Array.isArray(params.keywords)) {
      slotData.keywords = params.keywords;
    }

    if (params.visitor && typeof params.visitor === 'object') {
      slotData.visitor = params.visitor;
    }

    postData.slots.push(slotData);

    return (JSON.stringify(postData));
  }

  function buildOptimizedCall(bid) {
    bid.startTime = new Date().getTime();

    var {
      accountId,
      siteId,
      zoneId,
      position,
      floor,
      keywords,
      visitor,
      inventory,
      userId,
      referrer: pageUrl
    } = bid.params;

    // defaults
    floor = (floor = parseFloat(floor)) > 0.01 ? floor : 0.01;
    position = position || 'btf';

    // use rubicon sizes if provided, otherwise adUnit.sizes
    var parsedSizes = RubiconAdapter.masSizeOrdering(Array.isArray(bid.params.sizes)
      ? bid.params.sizes.map(size => (sizeMap[size] || '').split('x')) : bid.sizes
    );

    if (parsedSizes.length < 1) {
      throw 'no valid sizes';
    }

    if (!/^\d+$/.test(accountId)) {
      throw 'invalid accountId provided';
    }

    // using array to honor ordering. if order isn't important (it shouldn't be), an object would probably be preferable
    var queryString = [
      'account_id', accountId,
      'site_id', siteId,
      'zone_id', zoneId,
      'size_id', parsedSizes[0],
      'alt_size_ids', parsedSizes.slice(1).join(',') || undefined,
      'p_pos', position,
      'rp_floor', floor,
      'rp_secure', isSecure() ? '1' : '0',
      'tk_flint', getIntegration(),
      'p_screen_res', _getScreenResolution(),
      'kw', keywords,
      'tk_user_key', userId
    ];

    if (visitor !== null && typeof visitor === 'object') {
      utils._each(visitor, (item, key) => queryString.push(`tg_v.${key}`, item));
    }

    if (inventory !== null && typeof inventory === 'object') {
      utils._each(inventory, (item, key) => queryString.push(`tg_i.${key}`, item));
    }

    queryString.push(
      'rand', Math.random(),
      'rf', !pageUrl ? utils.getTopWindowUrl() : pageUrl
    );

    queryString = queryString.concat(_getDigiTrustQueryParams());

    return queryString.reduce(
      (memo, curr, index) =>
        index % 2 === 0 && queryString[index + 1] !== undefined
        ? memo + curr + '=' + encodeURIComponent(queryString[index + 1]) + '&' : memo,
      FASTLANE_ENDPOINT + '?'
    ).slice(0, -1); // remove trailing &
  }

  let _renderCreative = (script, impId) => `

`;

  function handleRpCB(responseText, bidRequest) {
    var responseObj = JSON.parse(responseText), // can throw
      ads = responseObj.ads,
      adResponseKey = bidRequest.placementCode;

    // check overall response
    if (typeof responseObj !== 'object' || responseObj.status !== 'ok') {
      throw 'bad response';
    }

    // video ads array is wrapped in an object
    if (bidRequest.mediaType === 'video' && typeof ads === 'object') {
      ads = ads[adResponseKey];
    }

    // check the ad response
    if (!Array.isArray(ads) || ads.length < 1) {
      throw 'invalid ad response';
    }

    // if there are multiple ads, sort by CPM
    ads = ads.sort(_adCpmSort);

    ads.forEach(ad => {
      if (ad.status !== 'ok') {
        throw 'bad ad status';
      }

      // store bid response
      // bid status is good (indicating 1)
      var bid = bidfactory.createBid(STATUS.GOOD, bidRequest);
      bid.creative_id = ad.ad_id;
      bid.bidderCode = bidRequest.bidder;
      bid.cpm = ad.cpm || 0;
      bid.dealId = ad.deal;
      if (bidRequest.mediaType === 'video') {
        bid.width = bidRequest.params.video.playerWidth;
        bid.height = bidRequest.params.video.playerHeight;
        bid.vastUrl = ad.creative_depot_url;
        bid.descriptionUrl = ad.impression_id;
        bid.impression_id = ad.impression_id;
      } else {
        bid.ad = _renderCreative(ad.script, ad.impression_id);
        [bid.width, bid.height] = sizeMap[ad.size_id].split('x').map(num => Number(num));
      }

      // add server-side targeting
      bid.rubiconTargeting = (Array.isArray(ad.targeting) ? ad.targeting : [])
        .reduce((memo, item) => {
          memo[item.key] = item.values[0];
          return memo;
        }, {'rpfl_elemid': bidRequest.placementCode});

      try {
        bidmanager.addBidResponse(bidRequest.placementCode, bid);
      } catch (err) {
        utils.logError('Error from addBidResponse', null, err);
      }
    });
  }

  function _adCpmSort(adA, adB) {
    return (adB.cpm || 0.0) - (adA.cpm || 0.0);
  }

  return Object.assign(Adapter.createNew(RUBICON_BIDDER_CODE), {
    callBids: _callBids,
    createNew: RubiconAdapter.createNew
  });
}

RubiconAdapter.masSizeOrdering = function(sizes) {
  const MAS_SIZE_PRIORITY = [15, 2, 9];

  return utils.parseSizesInput(sizes)
    // map sizes while excluding non-matches
    .reduce((result, size) => {
      let mappedSize = parseInt(sizeMap[size], 10);
      if (mappedSize) {
        result.push(mappedSize);
      }
      return result;
    }, [])
    .sort((first, second) => {
      // sort by MAS_SIZE_PRIORITY priority order
      let firstPriority = MAS_SIZE_PRIORITY.indexOf(first),
        secondPriority = MAS_SIZE_PRIORITY.indexOf(second);

      if (firstPriority > -1 || secondPriority > -1) {
        if (firstPriority === -1) {
          return 1;
        }
        if (secondPriority === -1) {
          return -1;
        }
        return firstPriority - secondPriority;
      }

      // and finally ascending order
      return first - second;
    });
};

RubiconAdapter.createNew = function() {
  return new RubiconAdapter();
};

module.exports = RubiconAdapter;

<commit_msg>Missing 250x250 ad size (#1225)<commit_after>import * as Adapter from './adapter.js';
import bidfactory from 'src/bidfactory';
import bidmanager from 'src/bidmanager';
import * as utils from 'src/utils';
import { ajax } from 'src/ajax';
import { STATUS } from 'src/constants';

const RUBICON_BIDDER_CODE = 'rubicon';

// use deferred function call since version isn't defined yet at this point
function getIntegration() {
  return 'pbjs_lite_' + $$PREBID_GLOBAL$$.version;
}

function isSecure() {
  return location.protocol === 'https:';
}

// use protocol relative urls for http or https
const FASTLANE_ENDPOINT = '//fastlane.rubiconproject.com/a/api/fastlane.json';
const VIDEO_ENDPOINT = '//fastlane-adv.rubiconproject.com/v1/auction/video';

const TIMEOUT_BUFFER = 500;

var sizeMap = {
  1: '468x60',
  2: '728x90',
  8: '120x600',
  9: '160x600',
  10: '300x600',
  14: '250x250',
  15: '300x250',
  16: '336x280',
  19: '300x100',
  31: '980x120',
  32: '250x360',
  33: '180x500',
  35: '980x150',
  37: '468x400',
  38: '930x180',
  43: '320x50',
  44: '300x50',
  48: '300x300',
  54: '300x1050',
  55: '970x90',
  57: '970x250',
  58: '1000x90',
  59: '320x80',
  61: '1000x1000',
  65: '640x480',
  67: '320x480',
  68: '1800x1000',
  72: '320x320',
  73: '320x160',
  78: '980x240',
  79: '980x300',
  80: '980x400',
  83: '480x300',
  94: '970x310',
  96: '970x210',
  101: '480x320',
  102: '768x1024',
  103: '480x280',
  113: '1000x300',
  117: '320x100',
  125: '800x250',
  126: '200x600'
};
utils._each(sizeMap, (item, key) => sizeMap[item] = key);

function RubiconAdapter() {
  function _callBids(bidderRequest) {
    var bids = bidderRequest.bids || [];

    bids.forEach(bid => {
      try {
        // Video endpoint only accepts POST calls
        if (bid.mediaType === 'video') {
          ajax(
            VIDEO_ENDPOINT,
            {
              success: bidCallback,
              error: bidError
            },
            buildVideoRequestPayload(bid, bidderRequest),
            {
              withCredentials: true
            }
          );
        } else {
          ajax(
            buildOptimizedCall(bid),
            {
              success: bidCallback,
              error: bidError
            },
            undefined,
            {
              withCredentials: true
            }
          );
        }
      } catch (err) {
        utils.logError('Error sending rubicon request for placement code ' + bid.placementCode, null, err);
        addErrorBid();
      }

      function bidCallback(responseText) {
        try {
          utils.logMessage('XHR callback function called for ad ID: ' + bid.bidId);
          handleRpCB(responseText, bid);
        } catch (err) {
          if (typeof err === 'string') {
            utils.logWarn(`${err} when processing rubicon response for placement code ${bid.placementCode}`);
          } else {
            utils.logError('Error processing rubicon response for placement code ' + bid.placementCode, null, err);
          }
          addErrorBid();
        }
      }

      function bidError(err, xhr) {
        utils.logError('Request for rubicon responded with:', xhr.status, err);
        addErrorBid();
      }

      function addErrorBid() {
        let badBid = bidfactory.createBid(STATUS.NO_BID, bid);
        badBid.bidderCode = bid.bidder;
        bidmanager.addBidResponse(bid.placementCode, badBid);
      }
    });
  }

  function _getScreenResolution() {
    return [window.screen.width, window.screen.height].join('x');
  }

  function _getDigiTrustQueryParams() {
    function getDigiTrustId() {
      let digiTrustUser = window.DigiTrust && window.DigiTrust.getUser({member: 'T9QSFKPDN9'});
      return digiTrustUser && digiTrustUser.success && digiTrustUser.identity || null;
    }
    let digiTrustId = getDigiTrustId();
    // Verify there is an ID and this user has not opted out
    if (!digiTrustId || digiTrustId.privacy && digiTrustId.privacy.optout) {
      return [];
    }
    return [
      'dt.id', digiTrustId.id,
      'dt.keyv', digiTrustId.keyv
    ];
  }

  function buildVideoRequestPayload(bid, bidderRequest) {
    bid.startTime = new Date().getTime();

    let params = bid.params;

    if (!params || typeof params.video !== 'object') {
      throw 'Invalid Video Bid';
    }

    let size;
    if (params.video.playerWidth && params.video.playerHeight) {
      size = [
        params.video.playerWidth,
        params.video.playerHeight
      ];
    } else if (
        Array.isArray(bid.sizes) && bid.sizes.length > 0 &&
        Array.isArray(bid.sizes[0]) && bid.sizes[0].length > 1
    ) {
      size = bid.sizes[0];
    } else {
      throw 'Invalid Video Bid - No size provided';
    }

    let postData = {
      page_url: !params.referrer ? utils.getTopWindowUrl() : params.referrer,
      resolution: _getScreenResolution(),
      account_id: params.accountId,
      integration: getIntegration(),
      timeout: bidderRequest.timeout - (Date.now() - bidderRequest.auctionStart + TIMEOUT_BUFFER),
      stash_creatives: true,
      ae_pass_through_parameters: params.video.aeParams,
      slots: []
    };

    // Define the slot object
    let slotData = {
      site_id: params.siteId,
      zone_id: params.zoneId,
      position: params.position || 'btf',
      floor: parseFloat(params.floor) > 0.01 ? params.floor : 0.01,
      element_id: bid.placementCode,
      name: bid.placementCode,
      language: params.video.language,
      width: size[0],
      height: size[1]
    };

    // check and add inventory, keywords, visitor and size_id data
    if (params.video.size_id) {
      slotData.size_id = params.video.size_id;
    } else {
      throw 'Invalid Video Bid - Invalid Ad Type!';
    }

    if (params.inventory && typeof params.inventory === 'object') {
      slotData.inventory = params.inventory;
    }

    if (params.keywords && Array.isArray(params.keywords)) {
      slotData.keywords = params.keywords;
    }

    if (params.visitor && typeof params.visitor === 'object') {
      slotData.visitor = params.visitor;
    }

    postData.slots.push(slotData);

    return (JSON.stringify(postData));
  }

  function buildOptimizedCall(bid) {
    bid.startTime = new Date().getTime();

    var {
      accountId,
      siteId,
      zoneId,
      position,
      floor,
      keywords,
      visitor,
      inventory,
      userId,
      referrer: pageUrl
    } = bid.params;

    // defaults
    floor = (floor = parseFloat(floor)) > 0.01 ? floor : 0.01;
    position = position || 'btf';

    // use rubicon sizes if provided, otherwise adUnit.sizes
    var parsedSizes = RubiconAdapter.masSizeOrdering(Array.isArray(bid.params.sizes)
      ? bid.params.sizes.map(size => (sizeMap[size] || '').split('x')) : bid.sizes
    );

    if (parsedSizes.length < 1) {
      throw 'no valid sizes';
    }

    if (!/^\d+$/.test(accountId)) {
      throw 'invalid accountId provided';
    }

    // using array to honor ordering. if order isn't important (it shouldn't be), an object would probably be preferable
    var queryString = [
      'account_id', accountId,
      'site_id', siteId,
      'zone_id', zoneId,
      'size_id', parsedSizes[0],
      'alt_size_ids', parsedSizes.slice(1).join(',') || undefined,
      'p_pos', position,
      'rp_floor', floor,
      'rp_secure', isSecure() ? '1' : '0',
      'tk_flint', getIntegration(),
      'p_screen_res', _getScreenResolution(),
      'kw', keywords,
      'tk_user_key', userId
    ];

    if (visitor !== null && typeof visitor === 'object') {
      utils._each(visitor, (item, key) => queryString.push(`tg_v.${key}`, item));
    }

    if (inventory !== null && typeof inventory === 'object') {
      utils._each(inventory, (item, key) => queryString.push(`tg_i.${key}`, item));
    }

    queryString.push(
      'rand', Math.random(),
      'rf', !pageUrl ? utils.getTopWindowUrl() : pageUrl
    );

    queryString = queryString.concat(_getDigiTrustQueryParams());

    return queryString.reduce(
      (memo, curr, index) =>
        index % 2 === 0 && queryString[index + 1] !== undefined
        ? memo + curr + '=' + encodeURIComponent(queryString[index + 1]) + '&' : memo,
      FASTLANE_ENDPOINT + '?'
    ).slice(0, -1); // remove trailing &
  }

  let _renderCreative = (script, impId) => `

`;

  function handleRpCB(responseText, bidRequest) {
    var responseObj = JSON.parse(responseText), // can throw
      ads = responseObj.ads,
      adResponseKey = bidRequest.placementCode;

    // check overall response
    if (typeof responseObj !== 'object' || responseObj.status !== 'ok') {
      throw 'bad response';
    }

    // video ads array is wrapped in an object
    if (bidRequest.mediaType === 'video' && typeof ads === 'object') {
      ads = ads[adResponseKey];
    }

    // check the ad response
    if (!Array.isArray(ads) || ads.length < 1) {
      throw 'invalid ad response';
    }

    // if there are multiple ads, sort by CPM
    ads = ads.sort(_adCpmSort);

    ads.forEach(ad => {
      if (ad.status !== 'ok') {
        throw 'bad ad status';
      }

      // store bid response
      // bid status is good (indicating 1)
      var bid = bidfactory.createBid(STATUS.GOOD, bidRequest);
      bid.creative_id = ad.ad_id;
      bid.bidderCode = bidRequest.bidder;
      bid.cpm = ad.cpm || 0;
      bid.dealId = ad.deal;
      if (bidRequest.mediaType === 'video') {
        bid.width = bidRequest.params.video.playerWidth;
        bid.height = bidRequest.params.video.playerHeight;
        bid.vastUrl = ad.creative_depot_url;
        bid.descriptionUrl = ad.impression_id;
        bid.impression_id = ad.impression_id;
      } else {
        bid.ad = _renderCreative(ad.script, ad.impression_id);
        [bid.width, bid.height] = sizeMap[ad.size_id].split('x').map(num => Number(num));
      }

      // add server-side targeting
      bid.rubiconTargeting = (Array.isArray(ad.targeting) ? ad.targeting : [])
        .reduce((memo, item) => {
          memo[item.key] = item.values[0];
          return memo;
        }, {'rpfl_elemid': bidRequest.placementCode});

      try {
        bidmanager.addBidResponse(bidRequest.placementCode, bid);
      } catch (err) {
        utils.logError('Error from addBidResponse', null, err);
      }
    });
  }

  function _adCpmSort(adA, adB) {
    return (adB.cpm || 0.0) - (adA.cpm || 0.0);
  }

  return Object.assign(Adapter.createNew(RUBICON_BIDDER_CODE), {
    callBids: _callBids,
    createNew: RubiconAdapter.createNew
  });
}

RubiconAdapter.masSizeOrdering = function(sizes) {
  const MAS_SIZE_PRIORITY = [15, 2, 9];

  return utils.parseSizesInput(sizes)
    // map sizes while excluding non-matches
    .reduce((result, size) => {
      let mappedSize = parseInt(sizeMap[size], 10);
      if (mappedSize) {
        result.push(mappedSize);
      }
      return result;
    }, [])
    .sort((first, second) => {
      // sort by MAS_SIZE_PRIORITY priority order
      let firstPriority = MAS_SIZE_PRIORITY.indexOf(first),
        secondPriority = MAS_SIZE_PRIORITY.indexOf(second);

      if (firstPriority > -1 || secondPriority > -1) {
        if (firstPriority === -1) {
          return 1;
        }
        if (secondPriority === -1) {
          return -1;
        }
        return firstPriority - secondPriority;
      }

      // and finally ascending order
      return first - second;
    });
};

RubiconAdapter.createNew = function() {
  return new RubiconAdapter();
};

module.exports = RubiconAdapter;

<|endoftext|>


<commit_before>// file referenced from docs

const
  hex = /^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/,
  hexa = /^#[0-9a-fA-F]{4}([0-9a-fA-F]{4})?$/,
  hexOrHexa = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,
  rgb = /^rgb\(((0|[1-9][\d]?|1[\d]{0,2}|2[\d]?|2[0-4][\d]|25[0-5]),){2}(0|[1-9][\d]?|1[\d]{0,2}|2[\d]?|2[0-4][\d]|25[0-5])\)$/,
  rgba = /^rgba\(((0|[1-9][\d]?|1[\d]{0,2}|2[\d]?|2[0-4][\d]|25[0-5]),){2}(0|[1-9][\d]?|1[\d]{0,2}|2[\d]?|2[0-4][\d]|25[0-5]),(0|0\.[0-9]+[1-9]|0\.[1-9]+|1)\)$/

export const testPattern = {
  date: v => /^-?[\d]+\/[0-1]\d\/[0-3]\d$/.test(v),
  time: v => /^([0-1]?\d|2[0-3]):[0-5]\d$/.test(v),
  fulltime: v => /^([0-1]?\d|2[0-3]):[0-5]\d:[0-5]\d$/.test(v),
  timeOrFulltime: v => /^([0-1]?\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/.test(v),

  hexColor: v => hex.test(v),
  hexaColor: v => hexa.test(v),
  hexOrHexaColor: v => hexOrHexa.test(v),

  rgbColor: v => rgb.test(v),
  rgbaColor: v => rgba.test(v),
  rgbOrRgbaColor: v => rgb.test(v) || rgba.test(v),

  hexOrRgbColor: v => hex.test(v) || rgb.test(v),
  hexaOrRgbaColor: v => hexa.test(v) || rgba.test(v),
  anyColor: v => hexOrHexa.test(v) || rgb.test(v) || rgba.test(v)
}

export default {
  testPattern
}
<commit_msg>feat(ui/validations): (backport from Qv2) New rule - email (basic validation) (#13115)<commit_after>// file referenced from docs

const
  hex = /^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/,
  hexa = /^#[0-9a-fA-F]{4}([0-9a-fA-F]{4})?$/,
  hexOrHexa = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/,
  rgb = /^rgb\(((0|[1-9][\d]?|1[\d]{0,2}|2[\d]?|2[0-4][\d]|25[0-5]),){2}(0|[1-9][\d]?|1[\d]{0,2}|2[\d]?|2[0-4][\d]|25[0-5])\)$/,
  rgba = /^rgba\(((0|[1-9][\d]?|1[\d]{0,2}|2[\d]?|2[0-4][\d]|25[0-5]),){2}(0|[1-9][\d]?|1[\d]{0,2}|2[\d]?|2[0-4][\d]|25[0-5]),(0|0\.[0-9]+[1-9]|0\.[1-9]+|1)\)$/

export const testPattern = {
  date: v => /^-?[\d]+\/[0-1]\d\/[0-3]\d$/.test(v),
  time: v => /^([0-1]?\d|2[0-3]):[0-5]\d$/.test(v),
  fulltime: v => /^([0-1]?\d|2[0-3]):[0-5]\d:[0-5]\d$/.test(v),
  timeOrFulltime: v => /^([0-1]?\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/.test(v),

  // -- RFC 5322 --
  // -- Added in v2.6.6 --
  // This is a basic helper validation.
  // For something more complex (like RFC 822) you should write and use your own rule.
  // We won't be accepting PRs to enhance the one below because of the reason above.
  email: v => /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(v),

  hexColor: v => hex.test(v),
  hexaColor: v => hexa.test(v),
  hexOrHexaColor: v => hexOrHexa.test(v),

  rgbColor: v => rgb.test(v),
  rgbaColor: v => rgba.test(v),
  rgbOrRgbaColor: v => rgb.test(v) || rgba.test(v),

  hexOrRgbColor: v => hex.test(v) || rgb.test(v),
  hexaOrRgbaColor: v => hexa.test(v) || rgba.test(v),
  anyColor: v => hexOrHexa.test(v) || rgb.test(v) || rgba.test(v)
}

export default {
  testPattern
}
<|endoftext|>


<commit_before>module.exports = function (robot) {

	robot.respond(/trello get token/i, function (res_r) {

		var slackMsgs = require('./slackMsgs.js');

		var key = process.env.HUBOT_TRELLO_KEY;

		let scope = 'read,write,account';
		let name = 'Hubot';
		let expr = '30days';
		let cb_method = '';
		let return_url = '';
		let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${key}&response_type=token`;
		//https://trello.com/1/authorize?expiration=never&name=SinglePurposeToken&key=51def9cb08cf171cd0970d8607ad8f97&callback_method=fragment&return_url=https://andreasbot.herokuapp.com/hubot/trello-token
		var msg = slackMsgs.basicMessage();

		msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
		msg.attachments[0].title = "Trello Token";
		msg.attachments[0].title_link = url;
		msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
		msg.attachments[0].footer = "Trello";
		msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
		res_r.send(msg);
	})

	robot.router.get('/hubot/trello-token', function (req, res) {
		// TODO: do something with the token
		robot.logger.info(res);
		res.send(200);
	});

	robot.respond(/trello add token (.*)/i, function (res_r) {
		var token = res_r.match[1];
		//***IMPORTANT***
		// the .env assignment doesnt work with HEROKU!
		// must set up a heroku client and communicate through their api
		process.env['HUBOT_TRELLO_TOKEN'] = token;
	})
}<commit_msg>update trello token<commit_after>module.exports = function (robot) {

	robot.respond(/trello get token/i, function (res_r) {

		var slackMsgs = require('./slackMsgs.js');

		var key = process.env.HUBOT_TRELLO_KEY;

		let scope = 'read,write,account';
		let name = 'Hubot';
		let expr = '30days';
		let cb_method = '';
		let return_url = '';
		let url = `https://trello.com/1/authorize?expiration=${expr}&name=${name}&scope=${scope}&key=${key}&response_type=token`;
		//https://trello.com/1/authorize?expiration=never&name=SinglePurposeToken&key=51def9cb08cf171cd0970d8607ad8f97&callback_method=fragment&return_url=https://andreasbot.herokuapp.com/hubot/trello-token
		var msg = slackMsgs.basicMessage();

		msg.attachments[0].pretext = "Please get a token to authorize your Trello account";
		msg.attachments[0].title = "Trello Token";
		msg.attachments[0].title_link = url;
		msg.attachments[0].text = "Copy the token from the link above and run\n *trello add token <YOUR TOKEN>*";
		msg.attachments[0].footer = "Trello";
		msg.attachments[0].footer_icon = "https://d2k1ftgv7pobq7.cloudfront.net/meta/u/res/images/b428584f224c42e98d158dad366351b0/trello-mark-blue.png";
		res_r.send(msg);
	})

	robot.router.get('/hubot/trello-token', function (req, res) {
		// TODO: do something with the token
		robot.logger.info(req.body);
		res.send('Token succesfuly received. You can now close the window.');
	});

	robot.respond(/trello add token (.*)/i, function (res_r) {
		var token = res_r.match[1];
		//***IMPORTANT***
		// the .env assignment doesnt work with HEROKU!
		// must set up a heroku client and communicate through their api
		process.env['HUBOT_TRELLO_TOKEN'] = token;
	})
}<|endoftext|>


<commit_before>describe("MySQLDB", function(){});<commit_msg>beginning mysql setup<commit_after>describe("MySQLDB", function(){
	it("is there a server running", function(next) {
		var mySQLClient = '';
		// do test here
	});
});<|endoftext|>


<commit_before>'use strict';

var generators = require('yeoman-generator');

var fs = require('fs');
var util = require('util');
var path = require('path');

var chalk = require('chalk');

var underscoreString = require('underscore.string');

var Generator = module.exports = generators.Base.extend({
	constructor: function () {
		generators.Base.apply(this, arguments);

		this.s = underscoreString;
	},

	initializing: function() {
		this.pkg = require('../../package.json');

		this.appname = this.appname || path.basename(process.cwd());

		this.serverPort = 8080;
	},

	configuring: function() {
		this.config.set('script-language', this.scriptLanguage);

		this.config.save();
	},

	prompting: {
		name: function() {
			var done = this.async();

			this.prompt(
				{
					type: 'input',
					name: 'appname',
					message: 'Game Name',
					default: this.appname
				},
				function (answers) {
					this.appname = answers.appname || 'phaser-game';

					done();
				}.bind(this)
			);
		},

		scriptLanguage: function() {
			var done = this.async();

			this.prompt(
				{
					type: 'list',
					name: 'scriptLanguage',
					message: 'Boilerplate Scripting Language',
					choices: [
						{
							value: 'javascript',
							name: 'Javascript'
						},
						{
							value: 'typescript',
							name: 'Typescript'
						}
					],
					default: this.config.get('scriptLanguage') || 'javascript'
				},
				function (answers) {
					this.scriptLanguage = answers.scriptLanguage;

					done();
				}.bind(this)
			);

		},

		build: function () {
			var done = this.async();

			this.prompt(
				{
					type: 'list',
					name: 'phaserBuild',
					message: 'Phaser Build',
					choices: [
						{
							value: 'phaser.js',
							name: 'Standard'
						},
						{
							value: 'custom/phaser-arcade-physics.js',
							name: 'Arcade Physics Only'
						},
						{
							value: 'custom/phaser-no-physics.js',
							name: 'No Physics'
						},
						{
							value: 'custom/phaser-minimum.js',
							name: 'Minimum'
						}
					]
				},
				function (answers) {
					this.phaserBuild = answers.phaserBuild || 'phaser.js';

					done();
				}.bind(this)
			);
		},

		resolution: function() {
			var done = this.async();

			this.prompt(
				[
					{
						type: 'input',
						name: 'width',
						message: 'Pixel width of your game',
						validate: function(n) { return n === +n && n === (n|0); },
						filter: function(n) { return +n; },
						default: 800
					},
					{
						type: 'input',
						name: 'height',
						message: 'Pixel height of your game',
						validate: function(n) { return n === +n && n === (n|0); },
						filter: function(n) { return +n; },
						default: 600
					}
				],
				function (answers) {
					this.appResolution = {
						'width': answers.width,
						'height': answers.height
					};

					done();
				}.bind(this)
			);
		}

	},

	writing: {
/*
		gruntfile: function() {
			this.gruntfile.loadNpmTasks([
				'grunt-browserify',
				'grunt-contrib-connect',
				'grunt-contrib-copy',
				'grunt-contrib-jshint',
				'grunt-contrib-watch'
			]);

			this.gruntfile.insertConfig(
				'copy',
				JSON.stringify({
					app: {
						files: [
							{
								src: 'src/index.html',
								dest: 'dist/index.html'
							},
							{
								expand: true,
								cwd: 'src/',
								src: 'assets/images/**',
								dest: 'dist/'
							},
							{
								expand: true,
								cwd: 'src/',
								src: 'assets/fonts/**',
								dest: 'dist/'
							},
							{
								expand: true,
								cwd: 'src/',
								src: 'assets/tilemap/**',
								dest: 'dist/'
							},
							{
								src: path.join('bower_components/phaser-official/build/', this.phaserBuild),
								dest: 'dist/assets/scripts/phaser.js'
							},
						]
					}
				})
			);

			if (this.scriptLanguage === 'javascript') {
				this.gruntfile.insertConfig(
					'jshint',
					JSON.stringify({
						options: {
							jshintrc: '.jshintrc'
						},
						app: [ 'src/assets/scripts/*.js' ]
					})
				);

				this.gruntfile.insertConfig(
					'browserify',
					JSON.stringify({
						app: {
							files: {
								'dist/assets/scripts/app.js' : [
									'src/assets/scripts/index.js'
								]
							},
							options: {
								transform: [ 'browserify-shim' ],
								browserifyOptions: {
									paths: [
										'src/assets/scripts'
									]
								}
							}
						}
					})
				)
			}

			this.gruntfile.insertConfig(
				'connect',
				JSON.stringify({
					app: {
						options: {
							port: this.serverPort,
							base: 'dist/'
						}
					}
				})
			);

			this.gruntfile.insertConfig(
				'watch',
				JSON.stringify({
					app: {
						files: [
							'src/**'
						],
						tasks: [ 'default' ]
					}
				})
			);

			this.gruntfile.registerTask('default', [ 'browserify:app', 'copy:app' ]);
			this.gruntfile.registerTask('serve', [ 'default', 'connect:app', 'watch:app' ]);
		},
*/
		meta: function() {
			this.fs.copy(
				this.templatePath('common/meta/_jshintrc'),
				this.destinationPath('.jshintrc')
			);

			this.fs.copy(
				this.templatePath('common/meta/_bowerrc'),
				this.destinationPath('.bowerrc')
			);

			this.fs.copy(
				this.templatePath('common/meta/_gitignore'),
				this.destinationPath('.gitignore')
			);

			this.fs.copyTpl(
				this.templatePath('common/meta/_bower.json'),
				this.destinationPath('bower.json'),
				this
			);

			this.fs.copyTpl(
				this.templatePath('common/meta/_package.json'),
				this.destinationPath('package.json'),
				this
			);

			this.fs.copyTpl(
				this.templatePath('common/meta/README.md'),
				this.destinationPath('README.md'),
				this
			);

			// The grunt editor included with yeoman is a bit buggy
			// so until it's fixed we'll do the gruntfile this way.
			this.fs.copyTpl(
				this.templatePath('common/meta/_Gruntfile.js'),
				this.destinationPath('Gruntfile.js'),
				this
			);
		},

		app: function() {
			this.fs.copy(
				this.templatePath('common/app/assets/'),
				this.destinationPath('src/assets/')
			);

			this.fs.copyTpl(
				this.templatePath('common/app/index.html'),
				this.destinationPath('src/index.html'),
				this
			);
		},

		scripts: function() {
			this.fs.copyTpl(
				this.templatePath(path.join('scripts/', this.scriptLanguage)),
				this.destinationPath('src/assets/scripts/'),
				this
			);
		}
	},

	install: function() {
		this.installDependencies();
	}
});
<commit_msg>remove unused gruntfile writing section<commit_after>'use strict';

var generators = require('yeoman-generator');

var fs = require('fs');
var util = require('util');
var path = require('path');

var chalk = require('chalk');

var underscoreString = require('underscore.string');

var Generator = module.exports = generators.Base.extend({
	constructor: function () {
		generators.Base.apply(this, arguments);

		this.s = underscoreString;
	},

	initializing: function() {
		this.pkg = require('../../package.json');

		this.appname = this.appname || path.basename(process.cwd());

		this.serverPort = 8080;
	},

	configuring: function() {
		this.config.set('script-language', this.scriptLanguage);

		this.config.save();
	},

	prompting: {
		name: function() {
			var done = this.async();

			this.prompt(
				{
					type: 'input',
					name: 'appname',
					message: 'Game Name',
					default: this.appname
				},
				function (answers) {
					this.appname = answers.appname || 'phaser-game';

					done();
				}.bind(this)
			);
		},

		scriptLanguage: function() {
			var done = this.async();

			this.prompt(
				{
					type: 'list',
					name: 'scriptLanguage',
					message: 'Boilerplate Scripting Language',
					choices: [
						{
							value: 'javascript',
							name: 'Javascript'
						},
						{
							value: 'typescript',
							name: 'Typescript'
						}
					],
					default: this.config.get('scriptLanguage') || 'javascript'
				},
				function (answers) {
					this.scriptLanguage = answers.scriptLanguage;

					done();
				}.bind(this)
			);

		},

		build: function () {
			var done = this.async();

			this.prompt(
				{
					type: 'list',
					name: 'phaserBuild',
					message: 'Phaser Build',
					choices: [
						{
							value: 'phaser.js',
							name: 'Standard'
						},
						{
							value: 'custom/phaser-arcade-physics.js',
							name: 'Arcade Physics Only'
						},
						{
							value: 'custom/phaser-no-physics.js',
							name: 'No Physics'
						},
						{
							value: 'custom/phaser-minimum.js',
							name: 'Minimum'
						}
					]
				},
				function (answers) {
					this.phaserBuild = answers.phaserBuild || 'phaser.js';

					done();
				}.bind(this)
			);
		},

		resolution: function() {
			var done = this.async();

			this.prompt(
				[
					{
						type: 'input',
						name: 'width',
						message: 'Pixel width of your game',
						validate: function(n) { return n === +n && n === (n|0); },
						filter: function(n) { return +n; },
						default: 800
					},
					{
						type: 'input',
						name: 'height',
						message: 'Pixel height of your game',
						validate: function(n) { return n === +n && n === (n|0); },
						filter: function(n) { return +n; },
						default: 600
					}
				],
				function (answers) {
					this.appResolution = {
						'width': answers.width,
						'height': answers.height
					};

					done();
				}.bind(this)
			);
		}

	},

	writing: {
		meta: function() {
			this.fs.copy(
				this.templatePath('common/meta/_jshintrc'),
				this.destinationPath('.jshintrc')
			);

			this.fs.copy(
				this.templatePath('common/meta/_bowerrc'),
				this.destinationPath('.bowerrc')
			);

			this.fs.copy(
				this.templatePath('common/meta/_gitignore'),
				this.destinationPath('.gitignore')
			);

			this.fs.copyTpl(
				this.templatePath('common/meta/_bower.json'),
				this.destinationPath('bower.json'),
				this
			);

			this.fs.copyTpl(
				this.templatePath('common/meta/_package.json'),
				this.destinationPath('package.json'),
				this
			);

			this.fs.copyTpl(
				this.templatePath('common/meta/README.md'),
				this.destinationPath('README.md'),
				this
			);

			// The grunt editor included with yeoman is a bit buggy
			// so until it's fixed we'll do the gruntfile this way.
			this.fs.copyTpl(
				this.templatePath('common/meta/_Gruntfile.js'),
				this.destinationPath('Gruntfile.js'),
				this
			);
		},

		app: function() {
			this.fs.copy(
				this.templatePath('common/app/assets/'),
				this.destinationPath('src/assets/')
			);

			this.fs.copyTpl(
				this.templatePath('common/app/index.html'),
				this.destinationPath('src/index.html'),
				this
			);
		},

		scripts: function() {
			this.fs.copyTpl(
				this.templatePath(path.join('scripts/', this.scriptLanguage)),
				this.destinationPath('src/assets/scripts/'),
				this
			);
		}
	},

	install: function() {
		this.installDependencies();
	}
});
<|endoftext|>


<commit_before>export function initialize() {
  let application = arguments[0];
  if (arguments.length === 2) {
    //for ember 1.x
    const container = arguments[0];
    application =  arguments[1];
    container.options('hotjar:main');
  }
  // application.inject('controller', '_kmq', 'kmq:main');
  // application.inject('route',      '_kmq', 'kmq:main');
};

export default {
  name: 'ember-hotjar',

  initialize: initialize
};
<commit_msg>Added injection<commit_after>export function initialize() {
  let application = arguments[0];
  if (arguments.length === 2) {
    //for ember 1.x
    const container = arguments[0];
    application =  arguments[1];
    container.options('hotjar:main');
  }

  application.inject('controller', '_hj', 'hotjar:main');
  application.inject('route',      '_hj', 'hotjar:main');
};

export default {
  name: 'ember-hotjar',
  initialize: initialize
};
<|endoftext|>