<commit_before>import axios from 'axios';

const DATASET = process.env.COUNTRIES_PAGE_DATASET;
const REQUEST_URL = `${process.env.GFW_API_HOST_PROD}/query/${DATASET}?sql=`;
const CARTO_REQUEST_URL = `${process.env.CARTO_API_URL}/sql?q=`;

const SQL_QUERIES = {
  extent:
    "SELECT SUM({extentYear}) as value, SUM(area_gadm28) as total_area FROM data WHERE {location} AND thresh = {threshold} AND polyname = '{indicator}'",
  plantationsExtent:
    "SELECT SUM(area_poly_aoi) AS plantation_extent, {admin} AS region, {bound} AS label FROM data WHERE {location} AND polyname = 'plantations' GROUP BY {type} ORDER BY plantation_extent DESC",
  multiRegionExtent:
    "SELECT {region} as region, SUM({extentYear}) as extent, SUM(area_gadm28) as total FROM data WHERE {location} AND thresh = {threshold} AND polyname = '{indicator}' GROUP BY {region} ORDER BY {region}",
  gain:
    "SELECT {calc} as value FROM data WHERE {location} AND polyname = '{indicator}' AND thresh = 0",
  gainRanked:
    "SELECT {region} as region, SUM(area_gain) AS gain, FROM data WHERE {location} AND polyname = '{polyname}' AND thresh = 0 GROUP BY region",
  gainLocations:
    "SELECT {admin} as region, {calc} as gain, FROM data WHERE {location} AND thresh = 0 AND polyname = '{indicator}' {grouping} ",
  loss:
    "SELECT polyname, year_data.year as year, SUM(year_data.area_loss) as area, SUM(year_data.emissions) as emissions FROM data WHERE polyname = '{indicator}' AND {location} AND thresh= {threshold} GROUP BY polyname, iso, nested(year_data.year)",
  locations:
    "SELECT {location} as region, {extentYear} as extent, {extent} as total FROM data WHERE iso = '{iso}' AND thresh = {threshold} AND polyname = '{indicator}' {grouping}",
  locationsLoss:
    "SELECT {select} AS region, year_data.year as year, SUM(year_data.area_loss) as area_loss, FROM data WHERE polyname = '{indicator}' AND iso = '{iso}' {region} AND thresh= {threshold} GROUP BY {group}, nested(year_data.year) ORDER BY {order}",
  fao:
    "SELECT fao.iso, fao.name, forest_planted, forest_primary, forest_regenerated, fao.forest_primary, fao.extent, a.land as area_ha FROM gfw2_countries as fao INNER JOIN umd_nat_staging as a ON fao.iso = a.iso WHERE fao.forest_primary is not null AND fao.iso = '{country}' AND a.year = 2001 AND a.thresh = 30",
  faoExtent:
    'SELECT country AS iso, name, year, reforest AS rate, forest*1000 AS extent FROM table_1_forest_area_and_characteristics as fao WHERE fao.year = {period} AND reforest > 0 ORDER BY rate DESC',
  faoDeforest:
    "SELECT fao.country, fao.name, fao.deforest, fao.humdef, fao.year FROM table_1_forest_area_and_characteristics as fao WHERE fao.country = '{country}'",
  faoDeforestRank:
    'WITH mytable AS (SELECT fao.country as iso, fao.name, fao.deforest, fao.humdef FROM table_1_forest_area_and_characteristics as fao WHERE fao.year = {year} AND deforest is not null), rank AS (SELECT deforest, iso, name from mytable ORDER BY mytable.deforest DESC) SELECT row_number() over () as rank, iso, name, deforest from rank',
  faoEcoLive:
    'SELECT fao.country, fao.forempl, fao.femempl, fao.usdrev, fao.usdexp, fao.gdpusd2012, fao.totpop1000, fao.year FROM table_7_economics_livelihood as fao WHERE fao.year = 2000 or fao.year = 2005 or fao.year = 2010 or fao.year = 9999'
};

const getExtentYear = year =>
  (year === 2000 ? 'area_extent_2000' : 'area_extent');

const getLocationQuery = (country, region, subRegion) =>
  `iso = '${country}'${region ? ` AND adm1 = ${region}` : ''}${
    subRegion ? ` AND adm2 = ${subRegion}` : ''
  }`;

export const getLocations = ({
  country,
  region,
  indicator,
  threshold,
  extentYear
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.locations}`
    .replace('{location}', region ? 'adm2' : 'adm1')
    .replace(
      '{extentYear}',
      `${!region ? 'sum(' : ''}${getExtentYear(extentYear)}${
        !region ? ')' : ''
      }`
    )
    .replace('{extent}', region ? 'area_gadm28' : 'sum(area_gadm28)')
    .replace('{iso}', country)
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator)
    .replace('{grouping}', region ? `AND adm1 = '${region}'` : 'GROUP BY adm1');
  return axios.get(url);
};

export const getLocationsLoss = ({ country, region, indicator, threshold }) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.locationsLoss}`
    .replace('{select}', region ? 'adm2' : 'adm1')
    .replace('{group}', region ? 'adm2' : 'adm1')
    .replace('{order}', region ? 'adm2' : 'adm1')
    .replace('{iso}', country)
    .replace('{region}', region ? `AND adm1 = ${region} AS region` : '')
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator);
  return axios.get(url);
};

export const getExtent = ({
  country,
  region,
  subRegion,
  indicator,
  threshold,
  extentYear
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.extent}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator)
    .replace('{extentYear}', getExtentYear(extentYear));
  return axios.get(url);
};

export const getPlantationsExtent = ({
  country,
  region,
  subRegion,
  type,
  groupByRegion
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.plantationsExtent}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{admin}', region ? 'adm2' : 'adm1')
    .replace('{bound}', type)
    .replace(
      '{type}',
      groupByRegion ? `${region ? 'adm2' : 'adm1'}, ${type}` : type
    );
  return axios.get(url);
};

export const getMultiRegionExtent = ({
  country,
  region,
  subRegion,
  indicator,
  threshold,
  extentYear
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.multiRegionExtent}`
    .replace(/{region}/g, region ? 'adm2' : 'adm1')
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator)
    .replace('{extentYear}', getExtentYear(extentYear));
  return axios.get(url);
};

export const getGain = ({ country, region, subRegion, indicator }) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.gain}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{calc}', region ? 'area_gain' : 'SUM(area_gain)')
    .replace('{indicator}', indicator);
  return axios.get(url);
};

export const getGainLocations = ({ country, region, indicator }) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.gainLocations}`
    .replace('{location}', getLocationQuery(country, region))
    .replace('{admin}', region ? 'adm2' : 'adm1')
    .replace('{calc}', region ? 'area_gain' : 'SUM(area_gain)')
    .replace('{indicator}', indicator)
    .replace('{grouping}', !region ? 'GROUP BY adm1 ORDER BY adm1' : '');
  return axios.get(url);
};

export const getLoss = ({
  country,
  region,
  subRegion,
  indicator,
  threshold
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.loss}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator);
  return axios.get(url);
};

export const getFAO = ({ country }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.fao}`.replace(
    '{country}',
    country
  );
  return axios.get(url);
};

export const getFAOExtent = ({ period }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.faoExtent}`.replace(
    '{period}',
    period
  );
  return axios.get(url);
};

export const getFAODeforest = ({ country }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.faoDeforest}`.replace(
    '{country}',
    country
  );
  return axios.get(url);
};
export const getFAODeforestRank = ({ period }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.faoDeforestRank}`.replace(
    '{year}',
    period
  );
  return axios.get(url);
};

export const getFAOEcoLive = () => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.faoEcoLive}`;
  return axios.get(url);
};

export const getGainRanked = ({
  country,
  region,
  subRegion,
  indicator,
  extentYear
}) => {
  let regionValue = 'iso';
  if (subRegion) {
    regionValue = 'adm2';
  } else if (region) {
    regionValue = 'adm1';
  }

  const location = region
    ? `iso = '${country}' ${subRegion ? `AND adm1 = ${region}` : ''}`
    : '1 = 1';

  const url = `${REQUEST_URL}${SQL_QUERIES.gainRanked}`
    .replace('{region}', regionValue)
    .replace('{location}', location)
    .replace('{extentYear}', getExtentYear(extentYear))
    .replace('{polyname}', indicator);
  return axios.get(url);
};
<commit_msg>Updates to fixed threshold.<commit_after>import axios from 'axios';

const DATASET = process.env.COUNTRIES_PAGE_DATASET;
const REQUEST_URL = `${process.env.GFW_API_HOST_PROD}/query/${DATASET}?sql=`;
const CARTO_REQUEST_URL = `${process.env.CARTO_API_URL}/sql?q=`;

const SQL_QUERIES = {
  extent:
    "SELECT SUM({extentYear}) as value, SUM(area_gadm28) as total_area FROM data WHERE {location} AND thresh = {threshold} AND polyname = '{indicator}'",
  plantationsExtent:
    "SELECT SUM(area_poly_aoi) AS plantation_extent, {admin} AS region, {bound} AS label FROM data WHERE {location} AND thresh = 0 AND polyname = 'plantations' GROUP BY {type} ORDER BY plantation_extent DESC",
  multiRegionExtent:
    "SELECT {region} as region, SUM({extentYear}) as extent, SUM(area_gadm28) as total FROM data WHERE {location} AND thresh = {threshold} AND polyname = '{indicator}' GROUP BY {region} ORDER BY {region}",
  gain:
    "SELECT {calc} as value FROM data WHERE {location} AND polyname = '{indicator}' AND thresh = 0",
  gainRanked:
    "SELECT {region} as region, SUM(area_gain) AS gain, FROM data WHERE {location} AND polyname = '{polyname}' AND thresh = 0 GROUP BY region",
  gainLocations:
    "SELECT {admin} as region, {calc} as gain, FROM data WHERE {location} AND thresh = 0 AND polyname = '{indicator}' {grouping} ",
  loss:
    "SELECT polyname, year_data.year as year, SUM(year_data.area_loss) as area, SUM(year_data.emissions) as emissions FROM data WHERE polyname = '{indicator}' AND {location} AND thresh= {threshold} GROUP BY polyname, iso, nested(year_data.year)",
  locations:
    "SELECT {location} as region, {extentYear} as extent, {extent} as total FROM data WHERE iso = '{iso}' AND thresh = {threshold} AND polyname = '{indicator}' {grouping}",
  locationsLoss:
    "SELECT {select} AS region, year_data.year as year, SUM(year_data.area_loss) as area_loss, FROM data WHERE polyname = '{indicator}' AND iso = '{iso}' {region} AND thresh= {threshold} GROUP BY {group}, nested(year_data.year) ORDER BY {order}",
  fao:
    "SELECT fao.iso, fao.name, forest_planted, forest_primary, forest_regenerated, fao.forest_primary, fao.extent, a.land as area_ha FROM gfw2_countries as fao INNER JOIN umd_nat_staging as a ON fao.iso = a.iso WHERE fao.forest_primary is not null AND fao.iso = '{country}' AND a.year = 2001 AND a.thresh = 30",
  faoExtent:
    'SELECT country AS iso, name, year, reforest AS rate, forest*1000 AS extent FROM table_1_forest_area_and_characteristics as fao WHERE fao.year = {period} AND reforest > 0 ORDER BY rate DESC',
  faoDeforest:
    "SELECT fao.country, fao.name, fao.deforest, fao.humdef, fao.year FROM table_1_forest_area_and_characteristics as fao WHERE fao.country = '{country}'",
  faoDeforestRank:
    'WITH mytable AS (SELECT fao.country as iso, fao.name, fao.deforest, fao.humdef FROM table_1_forest_area_and_characteristics as fao WHERE fao.year = {year} AND deforest is not null), rank AS (SELECT deforest, iso, name from mytable ORDER BY mytable.deforest DESC) SELECT row_number() over () as rank, iso, name, deforest from rank',
  faoEcoLive:
    'SELECT fao.country, fao.forempl, fao.femempl, fao.usdrev, fao.usdexp, fao.gdpusd2012, fao.totpop1000, fao.year FROM table_7_economics_livelihood as fao WHERE fao.year = 2000 or fao.year = 2005 or fao.year = 2010 or fao.year = 9999'
};

const getExtentYear = year =>
  (year === 2000 ? 'area_extent_2000' : 'area_extent');

const getLocationQuery = (country, region, subRegion) =>
  `iso = '${country}'${region ? ` AND adm1 = ${region}` : ''}${
    subRegion ? ` AND adm2 = ${subRegion}` : ''
  }`;

export const getLocations = ({
  country,
  region,
  indicator,
  threshold,
  extentYear
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.locations}`
    .replace('{location}', region ? 'adm2' : 'adm1')
    .replace(
      '{extentYear}',
      `${!region ? 'sum(' : ''}${getExtentYear(extentYear)}${
        !region ? ')' : ''
      }`
    )
    .replace('{extent}', region ? 'area_gadm28' : 'sum(area_gadm28)')
    .replace('{iso}', country)
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator)
    .replace('{grouping}', region ? `AND adm1 = '${region}'` : 'GROUP BY adm1');
  return axios.get(url);
};

export const getLocationsLoss = ({ country, region, indicator, threshold }) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.locationsLoss}`
    .replace('{select}', region ? 'adm2' : 'adm1')
    .replace('{group}', region ? 'adm2' : 'adm1')
    .replace('{order}', region ? 'adm2' : 'adm1')
    .replace('{iso}', country)
    .replace('{region}', region ? `AND adm1 = ${region} AS region` : '')
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator);
  return axios.get(url);
};

export const getExtent = ({
  country,
  region,
  subRegion,
  indicator,
  threshold,
  extentYear
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.extent}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator)
    .replace('{extentYear}', getExtentYear(extentYear));
  return axios.get(url);
};

export const getPlantationsExtent = ({
  country,
  region,
  subRegion,
  type,
  groupByRegion
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.plantationsExtent}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{admin}', region ? 'adm2' : 'adm1')
    .replace('{bound}', type)
    .replace(
      '{type}',
      groupByRegion ? `${region ? 'adm2' : 'adm1'}, ${type}` : type
    );
  return axios.get(url);
};

export const getMultiRegionExtent = ({
  country,
  region,
  subRegion,
  indicator,
  threshold,
  extentYear
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.multiRegionExtent}`
    .replace(/{region}/g, region ? 'adm2' : 'adm1')
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator)
    .replace('{extentYear}', getExtentYear(extentYear));
  return axios.get(url);
};

export const getGain = ({ country, region, subRegion, indicator }) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.gain}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{calc}', region ? 'area_gain' : 'SUM(area_gain)')
    .replace('{indicator}', indicator);
  return axios.get(url);
};

export const getGainLocations = ({ country, region, indicator }) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.gainLocations}`
    .replace('{location}', getLocationQuery(country, region))
    .replace('{admin}', region ? 'adm2' : 'adm1')
    .replace('{calc}', region ? 'area_gain' : 'SUM(area_gain)')
    .replace('{indicator}', indicator)
    .replace('{grouping}', !region ? 'GROUP BY adm1 ORDER BY adm1' : '');
  return axios.get(url);
};

export const getLoss = ({
  country,
  region,
  subRegion,
  indicator,
  threshold
}) => {
  const url = `${REQUEST_URL}${SQL_QUERIES.loss}`
    .replace('{location}', getLocationQuery(country, region, subRegion))
    .replace('{threshold}', threshold)
    .replace('{indicator}', indicator);
  return axios.get(url);
};

export const getFAO = ({ country }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.fao}`.replace(
    '{country}',
    country
  );
  return axios.get(url);
};

export const getFAOExtent = ({ period }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.faoExtent}`.replace(
    '{period}',
    period
  );
  return axios.get(url);
};

export const getFAODeforest = ({ country }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.faoDeforest}`.replace(
    '{country}',
    country
  );
  return axios.get(url);
};
export const getFAODeforestRank = ({ period }) => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.faoDeforestRank}`.replace(
    '{year}',
    period
  );
  return axios.get(url);
};

export const getFAOEcoLive = () => {
  const url = `${CARTO_REQUEST_URL}${SQL_QUERIES.faoEcoLive}`;
  return axios.get(url);
};

export const getGainRanked = ({
  country,
  region,
  subRegion,
  indicator,
  extentYear
}) => {
  let regionValue = 'iso';
  if (subRegion) {
    regionValue = 'adm2';
  } else if (region) {
    regionValue = 'adm1';
  }

  const location = region
    ? `iso = '${country}' ${subRegion ? `AND adm1 = ${region}` : ''}`
    : '1 = 1';

  const url = `${REQUEST_URL}${SQL_QUERIES.gainRanked}`
    .replace('{region}', regionValue)
    .replace('{location}', location)
    .replace('{extentYear}', getExtentYear(extentYear))
    .replace('{polyname}', indicator);
  return axios.get(url);
};
<|endoftext|>


<commit_before>angular.module('juiceShop').controller('BasketController', [
  '$scope',
  '$sce',
  '$window',
  '$translate',
  '$uibModal',
  'BasketService',
  'ConfigurationService',
  function ($scope, $sce, $window, $translate, $uibModal, basketService, configurationService) {
    'use strict'

    $scope.couponCollapsed = true
    $scope.paymentCollapsed = true

    function load () {
      basketService.find($window.sessionStorage.bid).then(function (basket) {
        $scope.products = basket.products
        for (var i = 0; i < $scope.products.length; i++) {
          $scope.products[i].description = $sce.trustAsHtml($scope.products[i].description)
        }
      }).catch(function (err) {
        console.log(err)
      })
    }
    load()

    $scope.delete = function (id) {
      basketService.del(id).then(function () {
        load()
      }).catch(function (err) {
        console.log(err)
      })
    }

    $scope.applyCoupon = function () {
      basketService.applyCoupon($window.sessionStorage.bid, encodeURIComponent($scope.coupon)).then(function (data) {
        $scope.coupon = undefined
        $translate('DISCOUNT_APPLIED', {discount: data.discount}).then(function (discountApplied) {
          $scope.confirmation = discountApplied
        }, function (translationId) {
          $scope.confirmation = translationId
        })
        $scope.error = undefined
        $scope.form.$setPristine()
      }).catch(function (error) {
        console.log(error)
        $scope.confirmation = undefined
        $scope.error = error // Intentionally not translated to indicate that the error just passed through from backend
        $scope.form.$setPristine()
      })
    }

    $scope.checkout = function () {
      basketService.checkout($window.sessionStorage.bid).then(function (orderConfirmationPath) {
        $window.location.replace(orderConfirmationPath)
      }).catch(function (err) {
        console.log(err)
      })
    }

    $scope.inc = function (id) {
      addToQuantity(id, 1)
    }

    $scope.dec = function (id) {
      addToQuantity(id, -1)
    }

    function addToQuantity (id, value) {
      basketService.get(id).then(function (basketItem) {
        var newQuantity = basketItem.quantity + value
        basketService.put(id, {quantity: newQuantity < 1 ? 1 : newQuantity}).then(function () {
          load()
        }).catch(function (err) {
          console.log(err)
        })
      }).catch(function (err) {
        console.log(err)
      })
    }

    $scope.showBitcoinQrCode = function () {
      $uibModal.open({
        templateUrl: 'views/QrCode.html',
        controller: 'QrCodeController',
        size: 'md',
        resolve: {
          data: function () { return 'bitcoin:1AbKfgvw9psQ41NbLi8kufDQTezwG8DRZm' },
          url: function () { return '/redirect?to=https://blockchain.info/address/1AbKfgvw9psQ41NbLi8kufDQTezwG8DRZm' },
          address: function () { return '1AbKfgvw9psQ41NbLi8kufDQTezwG8DRZm' },
          title: function () { return 'TITLE_BITCOIN_ADDRESS' }
        }
      })
    }

    $scope.showDashQrCode = function () {
      $uibModal.open({
        templateUrl: 'views/QrCode.html',
        controller: 'QrCodeController',
        size: 'md',
        resolve: {
          data: function () { return 'dash:Xr556RzuwX6hg5EGpkybbv5RanJoZN17kW' },
          url: function () { return '/redirect?to=https://explorer.dash.org/address/Xr556RzuwX6hg5EGpkybbv5RanJoZN17kW' },
          address: function () { return 'Xr556RzuwX6hg5EGpkybbv5RanJoZN17kW' },
          title: function () { return 'TITLE_DASH_ADDRESS' }
        }
      })
    }

    $scope.showEtherQrCode = function () {
      $uibModal.open({
        templateUrl: 'views/QrCode.html',
        controller: 'QrCodeController',
        size: 'md',
        resolve: {
          data: function () { return '0x0f933ab9fCAAA782D0279C300D73750e1311EAE6' },
          url: function () { return 'https://etherscan.io/address/0x0f933ab9fcaaa782d0279c300d73750e1311eae6' },
          address: function () { return '0x0f933ab9fCAAA782D0279C300D73750e1311EAE6' },
          title: function () { return 'TITLE_ETHER_ADDRESS' }
        }
      })
    }

    $scope.twitterUrl = 'https://twitter.com/owasp_juiceshop'
    $scope.facebookUrl = 'https://www.facebook.com/owasp.juiceshop'
    configurationService.getApplicationConfiguration().then(function (config) {
      if (config && config.application && config.application.twitterUrl !== null) {
        $scope.twitterUrl = config.application.twitterUrl
      }
      if (config && config.application && config.application.facebookUrl !== null) {
        $scope.facebookUrl = config.application.facebookUrl
      }
    }).catch(function (err) {
      console.log(err)
    })
  }])
<commit_msg>Fix missing discount amount in coupon confirmation<commit_after>angular.module('juiceShop').controller('BasketController', [
  '$scope',
  '$sce',
  '$window',
  '$translate',
  '$uibModal',
  'BasketService',
  'ConfigurationService',
  function ($scope, $sce, $window, $translate, $uibModal, basketService, configurationService) {
    'use strict'

    $scope.couponCollapsed = true
    $scope.paymentCollapsed = true

    function load () {
      basketService.find($window.sessionStorage.bid).then(function (basket) {
        $scope.products = basket.products
        for (var i = 0; i < $scope.products.length; i++) {
          $scope.products[i].description = $sce.trustAsHtml($scope.products[i].description)
        }
      }).catch(function (err) {
        console.log(err)
      })
    }
    load()

    $scope.delete = function (id) {
      basketService.del(id).then(function () {
        load()
      }).catch(function (err) {
        console.log(err)
      })
    }

    $scope.applyCoupon = function () {
      basketService.applyCoupon($window.sessionStorage.bid, encodeURIComponent($scope.coupon)).then(function (data) {
        $scope.coupon = undefined
        $translate('DISCOUNT_APPLIED', {discount: data}).then(function (discountApplied) {
          $scope.confirmation = discountApplied
        }, function (translationId) {
          $scope.confirmation = translationId
        })
        $scope.error = undefined
        $scope.form.$setPristine()
      }).catch(function (error) {
        console.log(error)
        $scope.confirmation = undefined
        $scope.error = error // Intentionally not translated to indicate that the error just passed through from backend
        $scope.form.$setPristine()
      })
    }

    $scope.checkout = function () {
      basketService.checkout($window.sessionStorage.bid).then(function (orderConfirmationPath) {
        $window.location.replace(orderConfirmationPath)
      }).catch(function (err) {
        console.log(err)
      })
    }

    $scope.inc = function (id) {
      addToQuantity(id, 1)
    }

    $scope.dec = function (id) {
      addToQuantity(id, -1)
    }

    function addToQuantity (id, value) {
      basketService.get(id).then(function (basketItem) {
        var newQuantity = basketItem.quantity + value
        basketService.put(id, {quantity: newQuantity < 1 ? 1 : newQuantity}).then(function () {
          load()
        }).catch(function (err) {
          console.log(err)
        })
      }).catch(function (err) {
        console.log(err)
      })
    }

    $scope.showBitcoinQrCode = function () {
      $uibModal.open({
        templateUrl: 'views/QrCode.html',
        controller: 'QrCodeController',
        size: 'md',
        resolve: {
          data: function () { return 'bitcoin:1AbKfgvw9psQ41NbLi8kufDQTezwG8DRZm' },
          url: function () { return '/redirect?to=https://blockchain.info/address/1AbKfgvw9psQ41NbLi8kufDQTezwG8DRZm' },
          address: function () { return '1AbKfgvw9psQ41NbLi8kufDQTezwG8DRZm' },
          title: function () { return 'TITLE_BITCOIN_ADDRESS' }
        }
      })
    }

    $scope.showDashQrCode = function () {
      $uibModal.open({
        templateUrl: 'views/QrCode.html',
        controller: 'QrCodeController',
        size: 'md',
        resolve: {
          data: function () { return 'dash:Xr556RzuwX6hg5EGpkybbv5RanJoZN17kW' },
          url: function () { return '/redirect?to=https://explorer.dash.org/address/Xr556RzuwX6hg5EGpkybbv5RanJoZN17kW' },
          address: function () { return 'Xr556RzuwX6hg5EGpkybbv5RanJoZN17kW' },
          title: function () { return 'TITLE_DASH_ADDRESS' }
        }
      })
    }

    $scope.showEtherQrCode = function () {
      $uibModal.open({
        templateUrl: 'views/QrCode.html',
        controller: 'QrCodeController',
        size: 'md',
        resolve: {
          data: function () { return '0x0f933ab9fCAAA782D0279C300D73750e1311EAE6' },
          url: function () { return 'https://etherscan.io/address/0x0f933ab9fcaaa782d0279c300d73750e1311eae6' },
          address: function () { return '0x0f933ab9fCAAA782D0279C300D73750e1311EAE6' },
          title: function () { return 'TITLE_ETHER_ADDRESS' }
        }
      })
    }

    $scope.twitterUrl = 'https://twitter.com/owasp_juiceshop'
    $scope.facebookUrl = 'https://www.facebook.com/owasp.juiceshop'
    configurationService.getApplicationConfiguration().then(function (config) {
      if (config && config.application && config.application.twitterUrl !== null) {
        $scope.twitterUrl = config.application.twitterUrl
      }
      if (config && config.application && config.application.facebookUrl !== null) {
        $scope.facebookUrl = config.application.facebookUrl
      }
    }).catch(function (err) {
      console.log(err)
    })
  }])
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var Connection = require('./connection')
  , events = require('events')
  , util = require('util')
  , crypto = require('crypto')
  , net = require('net');

/**
 * Default options
 */

var defaultConnectOptions = {
  keepalive: 10000,
  clientId: 'mqttjs_' + crypto.randomBytes(16).toString('hex'),
  protocolId: 'MQIsdp',
  protocolVersion: 3
};

var defaultPort = 1883
  , defaultHost = 'localhost';

var nop = function(){};

/**
 * MqttClient constructor
 *
 * @param <Number> [port] - broker port
 * @param <String> [host] - broker hostname
 * @param <Object> [options] - connection options
 * (see Connection#connect)
 */
var MqttClient = module.exports.MqttClient =
function MqttClient(stream, options) {
  if (!this instanceof MqttClient) {
    return new MqttClient(stream, options);
  }

  this.stream = stream;
  this.options = options || {};

  // Defaults
  for(var k in defaultConnectOptions) {
    if ('undefined' === typeof this.options[k]) {
      this.options[k] = defaultConnectOptions[k];
    } else {
      this.options[k] = options[k];
    }
  }

  this.conn = new Connection(this.stream);

  this.nextId = 0;

  // Inflight messages
  this.inflight = {
    puback: {},
    pubrec: {},
    pubcomp: {},
    suback: {},
    unsuback: {}
  }

  // Incoming messages
  this.incoming = {
    pubrel: {}
  };

  // Send a connect packet on stream connect
  this.stream.on('connect',
      this.conn.connect.bind(this.conn, this.options));

  // Handle connack
  this.conn.on('connack', this._handleConnack.bind(this));

  // Handle incoming publish
  this.conn.on('publish', this._handlePublish.bind(this));

  // Handle incoming acks
  this.conn.on('puback', this._handleAck.bind(this));
  this.conn.on('pubrec', this._handleAck.bind(this));
  this.conn.on('pubcomp', this._handleAck.bind(this));
  this.conn.on('suback', this._handleAck.bind(this));
  this.conn.on('unsuback', this._handleAck.bind(this));

  // Handle outgoing acks
  this.conn.on('pubrel', this._handlePubrel.bind(this));

  // Echo errors
  this.conn.on('error', this.emit.bind(this));
  this.stream.on('error', this.emit.bind(this));

  // Setup ping timer
  this._setupPingTimer();

  events.EventEmitter.call(this);
};
util.inherits(MqttClient, events.EventEmitter);

/**
 * publish - publish <message> to <topic>
 *
 * @param <String> topic - topic to publish to
 * @param <String, Buffer> message - message to publish
 * @param <Object> [opts] - publish options, includes:
 *    <Number> qos - qos level to publish on
 *    <Boolean> retain - whether or not to retain the message
 * @param <Function> [callback] - function(err){}
 *    called when publish succeeds or fails
 * @api public
 */
MqttClient.prototype.publish =
function(topic, message, opts, callback) {
  var packet;

  // .publish(topic, payload, cb);
  if ('function' === typeof opts) {
    callback = opts;
    opts = null;
  }

  // Default opts
  if(!opts) opts = {qos: 0, retain: false};

  callback = callback || nop;

  packet = {
    topic: topic,
    payload: message,
    qos: opts.qos,
    retain: opts.retain,
    messageId: this.nextId
  }

  this.conn.publish(packet);

  switch (opts.qos) {
    case 0:
      // Immediately callback
      callback();
      break;
    case 1:
      // Add to puback callbacks
      this.inflight.puback[this.nextId++] = callback;
      break;
    case 2:
      // Add to pubrec callbacks
      this.inflight.pubrec[this.nextId++] = callback;
      break
    default:
      break;
  }
};

/**
 * subscribe - subscribe to <topic>
 *
 * @param <String, Array> topic - topic(s) to subscribe to
 * @param <Object> [opts] - subscription options, includes:
 *    <Number> qos - subscribe qos level
 * @param <Function> [callback] - function(err){} fires on suback
 * @api public
 */
MqttClient.prototype.subscribe =
function(topic, opts, callback) {
  var subs = [];

  // .subscribe('topic', callback)
  if ('function' === typeof opts) {
    callback = opts;
    opts = null;
  }

  // Defaults
  opts = opts || {qos: 0};
  callback = callback || nop;

  if ('string' === typeof topic) {
    subs.push({topic: topic, qos: opts.qos});
  } else if ('object' === typeof topic) {
    // TODO: harder array check
    for (var i = 0; i < topic.length; i += 1) {
      var t = topic[i];
      subs.push({topic: t, qos: opts.qos});
    }
  } else {
    // Error!
  }

  var packet = {
    subscriptions: subs,
    qos: 1,
    messageId: this.nextId,
    retain: false,
    dup: false
  };

  this.conn.subscribe(packet);
  this.inflight.suback[this.nextId++] = callback;
};

/**
 * unsubscribe - unsubscribe from topic(s)
 *
 * @param <String, Array> topic - topics to unsubscribe from
 * @param <Function> [callback] - callback fired on unsuback
 */
MqttClient.prototype.unsubscribe = function(topic, callback) {
  callback = callback || nop;
  var unsubs;

  if ('string' === typeof topic) {
    unsubs = [topic];
  } else if ('object' === typeof topic && topic.length) {
    unsubs = topic;
  }

  this.conn.unsubscribe({
    unsubscriptions: unsubs,
    messageId: this.nextId
  });

  this.inflight.unsuback[this.nextId++] = callback;
};

/**
 * _setupPingTimer
 *
 * @api private
 */

MqttClient.prototype._setupPingTimer = function() {
  this.pingTimer = setTimeout(function () {
    this.conn.pingreq();
  }.bind(this), this.options.keepalive);
};

/**
 * _handleConnack
 *
 * @param <Object> packet
 * @api private
 */

MqttClient.prototype._handleConnack = function(packet) {
  var rc = packet.returnCode;

  // TODO: move to protocol
  var errors = [
    '',
    'Unacceptable protocol version',
    'Identifier rejected',
    'Server unavailable',
    'Bad username or password',
    'Not authorized'
  ];

  if (rc === 0) {
    this.emit('connect');
  } else if (rc > 0) {
    this.emit('error',
        new Error('Connection refused: ' + errors[rc]));
  }
};

/**
 * _handlePublish
 *
 * @param <Object> packet
 * @api private
 */

MqttClient.prototype._handlePublish = function(packet) {
  var topic = packet.topic
    , message = packet.payload
    , qos = packet.qos
    , mid = packet.messageId;

  switch (qos) {
    case 0:
      this.emit('message', topic, message);
      break;
    case 1:
      this.conn.puback({messageId: mid});
      this.emit('message', topic, message);
      break;
    case 2:
      this.conn.pubrec({messageId: mid});
      this.incoming.pubrel[mid] = {topic: topic, message: message};
      break;
    default:
      break;
  }
};

/**
 * _handleAck
 *
 * @param <Object> packet
 * @api private
 */

MqttClient.prototype._handleAck = function(packet) {
  var mid = packet.messageId
    , type = packet.cmd
    , cb = this.inflight[type][mid];

  // Check if callback exists
  if(!cb) this.emit('error', new Error('Unknown message id'));

  // Process
  switch (type) {
    case 'puback':
      // Callback - we're done
      cb();
      break;
    case 'pubrec':
      // Pubrel and add to pubcomp list
      this.conn.pubrel(packet);
      this.inflight.pubcomp[mid] = cb;
      break;
    case 'pubcomp':
      // Callback - we're done
      cb();
      break;
    case 'suback':
      cb();
      break;
    case 'unsuback':
      cb();
      break;
    default:
      // code
  }

  // Remove from queue
  delete this.inflight[type][mid];
};

/**
 * _handlePubrel
 *
 * @param <Object> packet
 * @api private
 */

MqttClient.prototype._handlePubrel = function(packet) {
  var mid = packet.messageId
    , data = this.incoming.pubrel[mid];

  if (!data) this.emit('error', new Error('Unknown message id'));
  this.conn.pubcomp({messageId: mid});
  this.emit('message', data.topic, data.message);
};

/**
 * createClient -
 *
 * @param <Number> [port]
 * @param <String> [host]
 * @param <Object> [opts]
 */

module.exports.createClient = function(port, host, opts) {
  var net_client, mqtt_client;

  if ('object' === typeof port) {
    // createClient({})
    opts = port;
    port = defaultPort;
    host = defaultHost;
  } else if ('object' === typeof host) {
    // createClient(1883, {})
    opts = host;
    host = defaultHost;
  }

  net_client = net.createConnection(port, host);
  mqtt_client = new MqttClient(net_client, opts);

  return mqtt_client;
};
<commit_msg>Change MqttClient#ping from setTimeout to setInterval<commit_after>/**
 * Module dependencies
 */

var Connection = require('./connection')
  , events = require('events')
  , util = require('util')
  , crypto = require('crypto')
  , net = require('net');

/**
 * Default options
 */

var defaultConnectOptions = {
  keepalive: 10000,
  clientId: 'mqttjs_' + crypto.randomBytes(16).toString('hex'),
  protocolId: 'MQIsdp',
  protocolVersion: 3
};

var defaultPort = 1883
  , defaultHost = 'localhost';

var nop = function(){};

/**
 * MqttClient constructor
 *
 * @param <Number> [port] - broker port
 * @param <String> [host] - broker hostname
 * @param <Object> [options] - connection options
 * (see Connection#connect)
 */
var MqttClient = module.exports.MqttClient =
function MqttClient(stream, options) {
  if (!this instanceof MqttClient) {
    return new MqttClient(stream, options);
  }

  this.stream = stream;
  this.options = options || {};

  // Defaults
  for(var k in defaultConnectOptions) {
    if ('undefined' === typeof this.options[k]) {
      this.options[k] = defaultConnectOptions[k];
    } else {
      this.options[k] = options[k];
    }
  }

  this.conn = new Connection(this.stream);

  this.nextId = 0;

  // Inflight messages
  this.inflight = {
    puback: {},
    pubrec: {},
    pubcomp: {},
    suback: {},
    unsuback: {}
  }

  // Incoming messages
  this.incoming = {
    pubrel: {}
  };

  // Send a connect packet on stream connect
  this.stream.on('connect',
      this.conn.connect.bind(this.conn, this.options));

  // Handle connack
  this.conn.on('connack', this._handleConnack.bind(this));

  // Handle incoming publish
  this.conn.on('publish', this._handlePublish.bind(this));

  // Handle incoming acks
  this.conn.on('puback', this._handleAck.bind(this));
  this.conn.on('pubrec', this._handleAck.bind(this));
  this.conn.on('pubcomp', this._handleAck.bind(this));
  this.conn.on('suback', this._handleAck.bind(this));
  this.conn.on('unsuback', this._handleAck.bind(this));

  // Handle outgoing acks
  this.conn.on('pubrel', this._handlePubrel.bind(this));

  // Echo errors
  this.conn.on('error', this.emit.bind(this));
  this.stream.on('error', this.emit.bind(this));

  // Setup ping timer
  this._setupPingTimer();

  events.EventEmitter.call(this);
};
util.inherits(MqttClient, events.EventEmitter);

/**
 * publish - publish <message> to <topic>
 *
 * @param <String> topic - topic to publish to
 * @param <String, Buffer> message - message to publish
 * @param <Object> [opts] - publish options, includes:
 *    <Number> qos - qos level to publish on
 *    <Boolean> retain - whether or not to retain the message
 * @param <Function> [callback] - function(err){}
 *    called when publish succeeds or fails
 * @api public
 */
MqttClient.prototype.publish =
function(topic, message, opts, callback) {
  var packet;

  // .publish(topic, payload, cb);
  if ('function' === typeof opts) {
    callback = opts;
    opts = null;
  }

  // Default opts
  if(!opts) opts = {qos: 0, retain: false};

  callback = callback || nop;

  packet = {
    topic: topic,
    payload: message,
    qos: opts.qos,
    retain: opts.retain,
    messageId: this.nextId
  }

  this.conn.publish(packet);

  switch (opts.qos) {
    case 0:
      // Immediately callback
      callback();
      break;
    case 1:
      // Add to puback callbacks
      this.inflight.puback[this.nextId++] = callback;
      break;
    case 2:
      // Add to pubrec callbacks
      this.inflight.pubrec[this.nextId++] = callback;
      break
    default:
      break;
  }
};

/**
 * subscribe - subscribe to <topic>
 *
 * @param <String, Array> topic - topic(s) to subscribe to
 * @param <Object> [opts] - subscription options, includes:
 *    <Number> qos - subscribe qos level
 * @param <Function> [callback] - function(err){} fires on suback
 * @api public
 */
MqttClient.prototype.subscribe =
function(topic, opts, callback) {
  var subs = [];

  // .subscribe('topic', callback)
  if ('function' === typeof opts) {
    callback = opts;
    opts = null;
  }

  // Defaults
  opts = opts || {qos: 0};
  callback = callback || nop;

  if ('string' === typeof topic) {
    subs.push({topic: topic, qos: opts.qos});
  } else if ('object' === typeof topic) {
    // TODO: harder array check
    for (var i = 0; i < topic.length; i += 1) {
      var t = topic[i];
      subs.push({topic: t, qos: opts.qos});
    }
  } else {
    // Error!
  }

  var packet = {
    subscriptions: subs,
    qos: 1,
    messageId: this.nextId,
    retain: false,
    dup: false
  };

  this.conn.subscribe(packet);
  this.inflight.suback[this.nextId++] = callback;
};

/**
 * unsubscribe - unsubscribe from topic(s)
 *
 * @param <String, Array> topic - topics to unsubscribe from
 * @param <Function> [callback] - callback fired on unsuback
 */
MqttClient.prototype.unsubscribe = function(topic, callback) {
  callback = callback || nop;
  var unsubs;

  if ('string' === typeof topic) {
    unsubs = [topic];
  } else if ('object' === typeof topic && topic.length) {
    unsubs = topic;
  }

  this.conn.unsubscribe({
    unsubscriptions: unsubs,
    messageId: this.nextId
  });

  this.inflight.unsuback[this.nextId++] = callback;
};

/**
 * _setupPingTimer
 *
 * @api private
 */

MqttClient.prototype._setupPingTimer = function() {
  this.pingTimer = setInterval((function () {
    this.conn.pingreq();
  }.bind(this)), this.options.keepalive);
};

/**
 * _handleConnack
 *
 * @param <Object> packet
 * @api private
 */

MqttClient.prototype._handleConnack = function(packet) {
  var rc = packet.returnCode;

  // TODO: move to protocol
  var errors = [
    '',
    'Unacceptable protocol version',
    'Identifier rejected',
    'Server unavailable',
    'Bad username or password',
    'Not authorized'
  ];

  if (rc === 0) {
    this.emit('connect');
  } else if (rc > 0) {
    this.emit('error',
        new Error('Connection refused: ' + errors[rc]));
  }
};

/**
 * _handlePublish
 *
 * @param <Object> packet
 * @api private
 */

MqttClient.prototype._handlePublish = function(packet) {
  var topic = packet.topic
    , message = packet.payload
    , qos = packet.qos
    , mid = packet.messageId;

  switch (qos) {
    case 0:
      this.emit('message', topic, message);
      break;
    case 1:
      this.conn.puback({messageId: mid});
      this.emit('message', topic, message);
      break;
    case 2:
      this.conn.pubrec({messageId: mid});
      this.incoming.pubrel[mid] = {topic: topic, message: message};
      break;
    default:
      break;
  }
};

/**
 * _handleAck
 *
 * @param <Object> packet
 * @api private
 */

MqttClient.prototype._handleAck = function(packet) {
  var mid = packet.messageId
    , type = packet.cmd
    , cb = this.inflight[type][mid];

  // Check if callback exists
  if(!cb) this.emit('error', new Error('Unknown message id'));

  // Process
  switch (type) {
    case 'puback':
      // Callback - we're done
      cb();
      break;
    case 'pubrec':
      // Pubrel and add to pubcomp list
      this.conn.pubrel(packet);
      this.inflight.pubcomp[mid] = cb;
      break;
    case 'pubcomp':
      // Callback - we're done
      cb();
      break;
    case 'suback':
      cb();
      break;
    case 'unsuback':
      cb();
      break;
    default:
      // code
  }

  // Remove from queue
  delete this.inflight[type][mid];
};

/**
 * _handlePubrel
 *
 * @param <Object> packet
 * @api private
 */

MqttClient.prototype._handlePubrel = function(packet) {
  var mid = packet.messageId
    , data = this.incoming.pubrel[mid];

  if (!data) this.emit('error', new Error('Unknown message id'));
  this.conn.pubcomp({messageId: mid});
  this.emit('message', data.topic, data.message);
};

/**
 * createClient -
 *
 * @param <Number> [port]
 * @param <String> [host]
 * @param <Object> [opts]
 */

module.exports.createClient = function(port, host, opts) {
  var net_client, mqtt_client;

  if ('object' === typeof port) {
    // createClient({})
    opts = port;
    port = defaultPort;
    host = defaultHost;
  } else if ('object' === typeof host) {
    // createClient(1883, {})
    opts = host;
    host = defaultHost;
  }

  net_client = net.createConnection(port, host);
  mqtt_client = new MqttClient(net_client, opts);

  return mqtt_client;
};
<|endoftext|>


<commit_before>var fs = require('fs')

/**
 * Load content for 'source'
 * @param {Object} source
 * @param {Function} [next]
 */
module.exports = function load (source, next) {
	var sync = !next;

	if (!source.content) {
		if (!sync) {
			fs.readFile(source.filepath, 'utf8', function (err, content) {
				if (err) return next(err);
				source.content = content;
				return next();
			});
		} else {
			source.content = fs.readFileSync(source.filepath, 'utf8');
		}
	}
};<commit_msg>remove sync<commit_after>var fs = require('fs')

/**
 * Load content for 'source'
 * @param {Object} source
 * @param {Function} next(err)
 */
module.exports = function load (source, next) {
	if (!source.content) {
		fs.readFile(source.filepath, 'utf8', function (err, content) {
			if (err) return next(err);
			source.content = content;
			return next();
		});
	}
};<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011 Vinay Pulim <vinay@milewise.com>
 * MIT Licensed
 */

"use strict";

var HttpClient = require('./http'),
  assert = require('assert'),
  events = require('events'),
  util = require('util'),
  debug = require('debug')('node-soap'),
  findPrefix = require('./utils').findPrefix,
  _ = require('lodash');

var Client = function(wsdl, endpoint, options) {
  events.EventEmitter.call(this);

  options = options || {};
  this.wsdl = wsdl;
  this._initializeOptions(options);
  this._initializeServices(endpoint);
  this.httpClient = options.httpClient || new HttpClient(options);
};
util.inherits(Client, events.EventEmitter);

Client.prototype.addSoapHeader = function(soapHeader, name, namespace, xmlns) {
  if (!this.soapHeaders) {
    this.soapHeaders = [];
  }
  if (typeof soapHeader === 'object') {
    soapHeader = this.wsdl.objectToXML(soapHeader, name, namespace, xmlns, true);
  }
  return this.soapHeaders.push(soapHeader) - 1;
};

Client.prototype.changeSoapHeader = function(index, soapHeader, name, namespace, xmlns) {
  if (!this.soapHeaders) {
    this.soapHeaders = [];
  }
  if (typeof soapHeader === 'object') {
    soapHeader = this.wsdl.objectToXML(soapHeader, name, namespace, xmlns, true);
  }
  this.soapHeaders[index] = soapHeader;
};

Client.prototype.getSoapHeaders = function() {
  return this.soapHeaders;
};

Client.prototype.clearSoapHeaders = function() {
  this.soapHeaders = null;
};

Client.prototype.addHttpHeader = function(name, value) {
  if (!this.httpHeaders) {
    this.httpHeaders = {};
  }
  this.httpHeaders[name] = value;
};

Client.prototype.getHttpHeaders = function() {
  return this.httpHeaders;
};

Client.prototype.clearHttpHeaders = function() {
  this.httpHeaders = {};
};

Client.prototype.addBodyAttribute = function(bodyAttribute, name, namespace, xmlns) {
  if (!this.bodyAttributes) {
    this.bodyAttributes = [];
  }
  if (typeof bodyAttribute === 'object') {
    var composition = '';
    Object.getOwnPropertyNames(bodyAttribute).forEach(function(prop, idx, array) {
      composition += ' ' + prop + '="' + bodyAttribute[prop] + '"';
    });
    bodyAttribute = composition;
  }
  if (bodyAttribute.substr(0, 1) !== ' ') bodyAttribute = ' ' + bodyAttribute;
  this.bodyAttributes.push(bodyAttribute);
};

Client.prototype.getBodyAttributes = function() {
  return this.bodyAttributes;
};

Client.prototype.clearBodyAttributes = function() {
  this.bodyAttributes = null;
};

Client.prototype.setEndpoint = function(endpoint) {
  this.endpoint = endpoint;
  this._initializeServices(endpoint);
};

Client.prototype.describe = function() {
  var types = this.wsdl.definitions.types;
  return this.wsdl.describeServices();
};

Client.prototype.setSecurity = function(security) {
  this.security = security;
};

Client.prototype.setSOAPAction = function(SOAPAction) {
  this.SOAPAction = SOAPAction;
};

Client.prototype._initializeServices = function(endpoint) {
  var definitions = this.wsdl.definitions,
    services = definitions.services;
  for (var name in services) {
    this[name] = this._defineService(services[name], endpoint);
  }
};

Client.prototype._initializeOptions = function(options) {
  this.wsdl.options.attributesKey = options.attributesKey || 'attributes';
  this.wsdl.options.envelopeKey = options.envelopeKey || 'soap';
  this.wsdl.options.forceSoap12Headers = !!options.forceSoap12Headers;
};

Client.prototype._defineService = function(service, endpoint) {
  var ports = service.ports,
    def = {};
  for (var name in ports) {
    def[name] = this._definePort(ports[name], endpoint ? endpoint : ports[name].location);
  }
  return def;
};

Client.prototype._definePort = function(port, endpoint) {
  var location = endpoint,
    binding = port.binding,
    methods = binding.methods,
    def = {};
  for (var name in methods) {
    def[name] = this._defineMethod(methods[name], location);
    this[name] = def[name];
  }
  return def;
};

Client.prototype._defineMethod = function(method, location) {
  var self = this;
  var temp;
  return function(args, callback, options, extraHeaders) {
    if (typeof args === 'function') {
      callback = args;
      args = {};
    } else if (typeof options === 'function') {
      temp = callback;
      callback = options;
      options = temp;
    } else if (typeof extraHeaders === 'function') {
      temp = callback;
      callback = extraHeaders;
      extraHeaders = options;
      options = temp;
    }
    self._invoke(method, args, location, function(error, result, raw, soapHeader) {
      callback(error, result, raw, soapHeader);
    }, options, extraHeaders);
  };
};

Client.prototype._invoke = function(method, args, location, callback, options, extraHeaders) {
  var self = this,
    name = method.$name,
    input = method.input,
    output = method.output,
    style = method.style,
    defs = this.wsdl.definitions,
    envelopeKey = this.wsdl.options.envelopeKey,
    ns = defs.$targetNamespace,
    encoding = '',
    message = '',
    xml = null,
    req = null,
    soapAction,
    alias = findPrefix(defs.xmlns, ns),
    headers = {
      "Content-Type": "text/xml; charset=utf-8"
    },
    xmlnsSoap = "xmlns:" + envelopeKey + "=\"http://schemas.xmlsoap.org/soap/envelope/\"";

  if (this.wsdl.options.forceSoap12Headers) {
    headers["Content-Type"] = "application/soap+xml; charset=utf-8";
    xmlnsSoap = "xmlns:" + envelopeKey + "=\"http://www.w3.org/2003/05/soap-envelope\"";
  }

  if (this.SOAPAction) {
    soapAction = this.SOAPAction;
  } else if (method.soapAction !== undefined && method.soapAction !== null) {
    soapAction = method.soapAction;
  } else {
    soapAction = ((ns.lastIndexOf("/") !== ns.length - 1) ? ns + "/" : ns) + name;
  }

  if (!this.wsdl.options.forceSoap12Headers) {
    headers.SOAPAction = '"' + soapAction + '"';
  }

  options = options || {};

  //Add extra headers
  for (var header in this.httpHeaders ) { headers[header] = this.httpHeaders[header];  }
  for (var attr in extraHeaders) { headers[attr] = extraHeaders[attr]; }

  // Allow the security object to add headers
  if (self.security && self.security.addHeaders)
    self.security.addHeaders(headers);
  if (self.security && self.security.addOptions)
    self.security.addOptions(options);

    if ((style === 'rpc')&& ( ( input.parts || input.name==="element" ) || args === null) ) {
      assert.ok(!style || style === 'rpc', 'invalid message definition for document style binding');
      message = self.wsdl.objectToRpcXML(name, args, alias, ns,(input.name!=="element" ));
      (method.inputSoap === 'encoded') && (encoding = 'soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ');
    } else if (typeof (args) === 'string') {
    message = args;
  } else {
    assert.ok(!style || style === 'document', 'invalid message definition for rpc style binding');
    // pass `input.$lookupType` if `input.$type` could not be found
    message = self.wsdl.objectToDocumentXML(input.$name, args, input.targetNSAlias, input.targetNamespace, (input.$type || input.$lookupType));
  }
  xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
    "<" + envelopeKey + ":Envelope " +
    xmlnsSoap + " " +
    "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
    encoding +
    this.wsdl.xmlnsInEnvelope + '>' +
    ((self.soapHeaders || self.security) ?
      (
        "<" + envelopeKey + ":Header>" +
        (self.soapHeaders ? self.soapHeaders.join("\n") : "") +
        (self.security && !self.security.postProcess ? self.security.toXML() : "") +
        "</" + envelopeKey + ":Header>"
      )
      :
        ''
      ) +
    "<" + envelopeKey + ":Body" +
    (self.bodyAttributes ? self.bodyAttributes.join(' ') : '') +
    (self.security && self.security.postProcess ? ' Id="_0"' : '') +
    ">" +
    message +
    "</" + envelopeKey + ":Body>" +
    "</" + envelopeKey + ":Envelope>";

  if(self.security && self.security.postProcess){
    xml = self.security.postProcess(xml);
  }

  self.lastMessage = message;
  self.lastRequest = xml;
  self.lastEndpoint = location;

  self.emit('message', message);
  self.emit('request', xml);

  var tryJSONparse = function(body) {
    try {
      return JSON.parse(body);
    }
    catch(err) {
      return undefined;
    }
  };

  req = self.httpClient.request(location, xml, function(err, response, body) {
    var result;
    var obj;
    self.lastResponse = body;
    self.lastResponseHeaders = response && response.headers;
    self.lastElapsedTime = response && response.elapsedTime;
    self.emit('response', body, response);

    if (err) {
      callback(err);
    } else {

      try {
        obj = self.wsdl.xmlToObject(body);
      } catch (error) {
        //  When the output element cannot be looked up in the wsdl and the body is JSON
        //  instead of sending the error, we pass the body in the response.
        if(!output || !output.$lookupTypes) {
          debug('Response element is not present. Unable to convert response xml to json.');
          //  If the response is JSON then return it as-is.
          var json = _.isObject(body) ? body : tryJSONparse(body);
          if (json) {
            return callback(null, response, json);
          }
        }
        error.response = response;
        error.body = body;
        self.emit('soapError', error);
        return callback(error, response, body);
      }

      if (!output){
        // one-way, no output expected
        return callback(null, null, body, obj.Header);
      }

      if( typeof obj.Body !== 'object' ) {
        var error = new Error('Cannot parse response');
        error.response = response;
        error.body = body;
        return callback(error, obj, body);
      }

      result = obj.Body[output.$name];
      // RPC/literal response body may contain elements with added suffixes I.E.
      // 'Response', or 'Output', or 'Out'
      // This doesn't necessarily equal the ouput message name. See WSDL 1.1 Section 2.4.5
      if(!result){
        result = obj.Body[output.$name.replace(/(?:Out(?:put)?|Response)$/, '')];
      }
      if (!result) {
        ['Response', 'Out', 'Output'].forEach(function (term) {
          if (obj.Body.hasOwnProperty(name + term)) {
            return result = obj.Body[name + term];
          }
        });
      }

      callback(null, result, body, obj.Header);
    }
  }, headers, options, self);

  // Added mostly for testability, but possibly useful for debugging
  self.lastRequestHeaders = req.headers;
};

exports.Client = Client;
<commit_msg>fixes and issue that causes the module to break if no re or req.headers present in client (#852)<commit_after>/*
 * Copyright (c) 2011 Vinay Pulim <vinay@milewise.com>
 * MIT Licensed
 */

"use strict";

var HttpClient = require('./http'),
  assert = require('assert'),
  events = require('events'),
  util = require('util'),
  debug = require('debug')('node-soap'),
  findPrefix = require('./utils').findPrefix,
  _ = require('lodash');

var Client = function(wsdl, endpoint, options) {
  events.EventEmitter.call(this);

  options = options || {};
  this.wsdl = wsdl;
  this._initializeOptions(options);
  this._initializeServices(endpoint);
  this.httpClient = options.httpClient || new HttpClient(options);
};
util.inherits(Client, events.EventEmitter);

Client.prototype.addSoapHeader = function(soapHeader, name, namespace, xmlns) {
  if (!this.soapHeaders) {
    this.soapHeaders = [];
  }
  if (typeof soapHeader === 'object') {
    soapHeader = this.wsdl.objectToXML(soapHeader, name, namespace, xmlns, true);
  }
  return this.soapHeaders.push(soapHeader) - 1;
};

Client.prototype.changeSoapHeader = function(index, soapHeader, name, namespace, xmlns) {
  if (!this.soapHeaders) {
    this.soapHeaders = [];
  }
  if (typeof soapHeader === 'object') {
    soapHeader = this.wsdl.objectToXML(soapHeader, name, namespace, xmlns, true);
  }
  this.soapHeaders[index] = soapHeader;
};

Client.prototype.getSoapHeaders = function() {
  return this.soapHeaders;
};

Client.prototype.clearSoapHeaders = function() {
  this.soapHeaders = null;
};

Client.prototype.addHttpHeader = function(name, value) {
  if (!this.httpHeaders) {
    this.httpHeaders = {};
  }
  this.httpHeaders[name] = value;
};

Client.prototype.getHttpHeaders = function() {
  return this.httpHeaders;
};

Client.prototype.clearHttpHeaders = function() {
  this.httpHeaders = {};
};

Client.prototype.addBodyAttribute = function(bodyAttribute, name, namespace, xmlns) {
  if (!this.bodyAttributes) {
    this.bodyAttributes = [];
  }
  if (typeof bodyAttribute === 'object') {
    var composition = '';
    Object.getOwnPropertyNames(bodyAttribute).forEach(function(prop, idx, array) {
      composition += ' ' + prop + '="' + bodyAttribute[prop] + '"';
    });
    bodyAttribute = composition;
  }
  if (bodyAttribute.substr(0, 1) !== ' ') bodyAttribute = ' ' + bodyAttribute;
  this.bodyAttributes.push(bodyAttribute);
};

Client.prototype.getBodyAttributes = function() {
  return this.bodyAttributes;
};

Client.prototype.clearBodyAttributes = function() {
  this.bodyAttributes = null;
};

Client.prototype.setEndpoint = function(endpoint) {
  this.endpoint = endpoint;
  this._initializeServices(endpoint);
};

Client.prototype.describe = function() {
  var types = this.wsdl.definitions.types;
  return this.wsdl.describeServices();
};

Client.prototype.setSecurity = function(security) {
  this.security = security;
};

Client.prototype.setSOAPAction = function(SOAPAction) {
  this.SOAPAction = SOAPAction;
};

Client.prototype._initializeServices = function(endpoint) {
  var definitions = this.wsdl.definitions,
    services = definitions.services;
  for (var name in services) {
    this[name] = this._defineService(services[name], endpoint);
  }
};

Client.prototype._initializeOptions = function(options) {
  this.wsdl.options.attributesKey = options.attributesKey || 'attributes';
  this.wsdl.options.envelopeKey = options.envelopeKey || 'soap';
  this.wsdl.options.forceSoap12Headers = !!options.forceSoap12Headers;
};

Client.prototype._defineService = function(service, endpoint) {
  var ports = service.ports,
    def = {};
  for (var name in ports) {
    def[name] = this._definePort(ports[name], endpoint ? endpoint : ports[name].location);
  }
  return def;
};

Client.prototype._definePort = function(port, endpoint) {
  var location = endpoint,
    binding = port.binding,
    methods = binding.methods,
    def = {};
  for (var name in methods) {
    def[name] = this._defineMethod(methods[name], location);
    this[name] = def[name];
  }
  return def;
};

Client.prototype._defineMethod = function(method, location) {
  var self = this;
  var temp;
  return function(args, callback, options, extraHeaders) {
    if (typeof args === 'function') {
      callback = args;
      args = {};
    } else if (typeof options === 'function') {
      temp = callback;
      callback = options;
      options = temp;
    } else if (typeof extraHeaders === 'function') {
      temp = callback;
      callback = extraHeaders;
      extraHeaders = options;
      options = temp;
    }
    self._invoke(method, args, location, function(error, result, raw, soapHeader) {
      callback(error, result, raw, soapHeader);
    }, options, extraHeaders);
  };
};

Client.prototype._invoke = function(method, args, location, callback, options, extraHeaders) {
  var self = this,
    name = method.$name,
    input = method.input,
    output = method.output,
    style = method.style,
    defs = this.wsdl.definitions,
    envelopeKey = this.wsdl.options.envelopeKey,
    ns = defs.$targetNamespace,
    encoding = '',
    message = '',
    xml = null,
    req = null,
    soapAction,
    alias = findPrefix(defs.xmlns, ns),
    headers = {
      "Content-Type": "text/xml; charset=utf-8"
    },
    xmlnsSoap = "xmlns:" + envelopeKey + "=\"http://schemas.xmlsoap.org/soap/envelope/\"";

  if (this.wsdl.options.forceSoap12Headers) {
    headers["Content-Type"] = "application/soap+xml; charset=utf-8";
    xmlnsSoap = "xmlns:" + envelopeKey + "=\"http://www.w3.org/2003/05/soap-envelope\"";
  }

  if (this.SOAPAction) {
    soapAction = this.SOAPAction;
  } else if (method.soapAction !== undefined && method.soapAction !== null) {
    soapAction = method.soapAction;
  } else {
    soapAction = ((ns.lastIndexOf("/") !== ns.length - 1) ? ns + "/" : ns) + name;
  }

  if (!this.wsdl.options.forceSoap12Headers) {
    headers.SOAPAction = '"' + soapAction + '"';
  }

  options = options || {};

  //Add extra headers
  for (var header in this.httpHeaders ) { headers[header] = this.httpHeaders[header];  }
  for (var attr in extraHeaders) { headers[attr] = extraHeaders[attr]; }

  // Allow the security object to add headers
  if (self.security && self.security.addHeaders)
    self.security.addHeaders(headers);
  if (self.security && self.security.addOptions)
    self.security.addOptions(options);

    if ((style === 'rpc')&& ( ( input.parts || input.name==="element" ) || args === null) ) {
      assert.ok(!style || style === 'rpc', 'invalid message definition for document style binding');
      message = self.wsdl.objectToRpcXML(name, args, alias, ns,(input.name!=="element" ));
      (method.inputSoap === 'encoded') && (encoding = 'soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" ');
    } else if (typeof (args) === 'string') {
    message = args;
  } else {
    assert.ok(!style || style === 'document', 'invalid message definition for rpc style binding');
    // pass `input.$lookupType` if `input.$type` could not be found
    message = self.wsdl.objectToDocumentXML(input.$name, args, input.targetNSAlias, input.targetNamespace, (input.$type || input.$lookupType));
  }
  xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
    "<" + envelopeKey + ":Envelope " +
    xmlnsSoap + " " +
    "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
    encoding +
    this.wsdl.xmlnsInEnvelope + '>' +
    ((self.soapHeaders || self.security) ?
      (
        "<" + envelopeKey + ":Header>" +
        (self.soapHeaders ? self.soapHeaders.join("\n") : "") +
        (self.security && !self.security.postProcess ? self.security.toXML() : "") +
        "</" + envelopeKey + ":Header>"
      )
      :
        ''
      ) +
    "<" + envelopeKey + ":Body" +
    (self.bodyAttributes ? self.bodyAttributes.join(' ') : '') +
    (self.security && self.security.postProcess ? ' Id="_0"' : '') +
    ">" +
    message +
    "</" + envelopeKey + ":Body>" +
    "</" + envelopeKey + ":Envelope>";

  if(self.security && self.security.postProcess){
    xml = self.security.postProcess(xml);
  }

  self.lastMessage = message;
  self.lastRequest = xml;
  self.lastEndpoint = location;

  self.emit('message', message);
  self.emit('request', xml);

  var tryJSONparse = function(body) {
    try {
      return JSON.parse(body);
    }
    catch(err) {
      return undefined;
    }
  };

  req = self.httpClient.request(location, xml, function(err, response, body) {
    var result;
    var obj;
    self.lastResponse = body;
    self.lastResponseHeaders = response && response.headers;
    self.lastElapsedTime = response && response.elapsedTime;
    self.emit('response', body, response);

    if (err) {
      callback(err);
    } else {

      try {
        obj = self.wsdl.xmlToObject(body);
      } catch (error) {
        //  When the output element cannot be looked up in the wsdl and the body is JSON
        //  instead of sending the error, we pass the body in the response.
        if(!output || !output.$lookupTypes) {
          debug('Response element is not present. Unable to convert response xml to json.');
          //  If the response is JSON then return it as-is.
          var json = _.isObject(body) ? body : tryJSONparse(body);
          if (json) {
            return callback(null, response, json);
          }
        }
        error.response = response;
        error.body = body;
        self.emit('soapError', error);
        return callback(error, response, body);
      }

      if (!output){
        // one-way, no output expected
        return callback(null, null, body, obj.Header);
      }

      if( typeof obj.Body !== 'object' ) {
        var error = new Error('Cannot parse response');
        error.response = response;
        error.body = body;
        return callback(error, obj, body);
      }

      result = obj.Body[output.$name];
      // RPC/literal response body may contain elements with added suffixes I.E.
      // 'Response', or 'Output', or 'Out'
      // This doesn't necessarily equal the ouput message name. See WSDL 1.1 Section 2.4.5
      if(!result){
        result = obj.Body[output.$name.replace(/(?:Out(?:put)?|Response)$/, '')];
      }
      if (!result) {
        ['Response', 'Out', 'Output'].forEach(function (term) {
          if (obj.Body.hasOwnProperty(name + term)) {
            return result = obj.Body[name + term];
          }
        });
      }

      callback(null, result, body, obj.Header);
    }
  }, headers, options, self);

  // Added mostly for testability, but possibly useful for debugging
  if(req && req.headers) //fixes an issue when req or req.headers is indefined
    self.lastRequestHeaders = req.headers;
};

exports.Client = Client;
<|endoftext|>


<commit_before>import { document } from 'global';
import dedent from 'ts-dedent';

import { logger } from '@storybook/client-logger';

const rootEl = document.getElementById('root');
let activeComponent = null; // currently loaded marko component.
let activeTemplate = null; // template for the currently loaded component.

export default function renderMain({
  storyFn,
  kind,
  name,
  showMain,
  showError,
  parameters,
  // forceRender,
}) {
  const config = storyFn();

  if (!config || !(config.appendTo || config.component || parameters.component)) {
    showError({
      title: `Expecting an object with a component property to be returned from the story: "${name}" of "${kind}".`,
      description: dedent`
        Did you forget to return the component from the story?
        Use "() => ({ component: MyComponent, input: { hello: 'world' } })" when defining the story.
      `,
    });

    return;
  }
  if (config.appendTo) {
    logger.warn(
      '@storybook/marko: returning a rendered component for a story is deprecated, return an object with `{ component, input }` instead.'
    );

    // The deprecated API always destroys the previous component instance.
    if (activeComponent) {
      activeComponent.destroy();
    }

    activeComponent = config.appendTo(rootEl).getComponent();
  } else {
    const template = config.component || parameters.component;

    if (activeTemplate === template) {
      // When rendering the same template with new input, we reuse the same instance.
      activeComponent.input = config.input;
      activeComponent.update();
    } else {
      if (activeComponent) {
        activeComponent.destroy();
      }

      activeTemplate = template;
      activeComponent = activeTemplate.renderSync(config.input).appendTo(rootEl).getComponent();
    }
  }

  showMain();
}
<commit_msg>fix: always destroy old Marko component when switching stories<commit_after>import { document } from 'global';
import dedent from 'ts-dedent';

import { logger } from '@storybook/client-logger';

const rootEl = document.getElementById('root');
let activeComponent = null; // currently loaded marko component.
let activeTemplate = null; // template for the currently loaded component.
let activeStoryFn = null; // used to determine if we've switched stories.

export default function renderMain({
  storyFn,
  kind,
  name,
  showMain,
  showError,
  parameters,
  // forceRender,
}) {
  const isSameStory = activeStoryFn === storyFn;
  const config = storyFn();
  activeStoryFn = storyFn;

  if (!config || !(config.appendTo || config.component || parameters.component)) {
    showError({
      title: `Expecting an object with a component property to be returned from the story: "${name}" of "${kind}".`,
      description: dedent`
        Did you forget to return the component from the story?
        Use "() => ({ component: MyComponent, input: { hello: 'world' } })" when defining the story.
      `,
    });

    return;
  }
  if (config.appendTo) {
    logger.warn(
      '@storybook/marko: returning a rendered component for a story is deprecated, return an object with `{ component, input }` instead.'
    );

    // The deprecated API always destroys the previous component instance.
    if (activeComponent) {
      activeComponent.destroy();
    }

    activeComponent = config.appendTo(rootEl).getComponent();
  } else {
    const template = config.component || parameters.component;

    if (isSameStory && activeTemplate === template) {
      // When rendering the same template with new input, we reuse the same instance.
      activeComponent.input = config.input;
      activeComponent.update();
    } else {
      if (activeComponent) {
        activeComponent.destroy();
      }

      activeTemplate = template;
      activeComponent = activeTemplate.renderSync(config.input).appendTo(rootEl).getComponent();
    }
  }

  showMain();
}
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var request = require("request");
var querystring = require("querystring");
var url = require("url");
var Utils = require("./utils");

function Client(options){
  this.options = Utils.merge({}, this._options, options || {});

  return this.load(this.options);
}

Client.prototype._options = {
  type: "http"
}

Client.prototype.load = function(options){
  return new Object.hasOwnProperty.call(this.switch, options.type) && this.switch[options.type] || this.switch[this._options.type](options);
}

Client.prototype.switch = {
  http: require("./clients/http"),
  json: require("./clients/json")
}

module.exports = exports = Client;<commit_msg>better api<commit_after>/**
 * Module dependencies.
 */
var request = require("request");
var querystring = require("querystring");
var url = require("url");
var Utils = require("./utils");

function Client(options){
  this.options = Utils.merge({}, this._options, options || {});

}

Client.prototype._options = {

}

Client.prototype.get = function(path, callback){

}

Client.prototype.post = function(path, data, callback){

}<|endoftext|>


<commit_before>exports.inject = function(deps) {
  deps = deps || {};

  var _ = require('underscore'),
    events = require('events'),
    q = require('q'),
    request = deps.request || require('request'),
    util = require('util');

  function Client() {

    this.requestNumber = 0;

    events.EventEmitter.call(this);
    this.on('configure', _.bind(this.configure, this));
  }

  util.inherits(Client, events.EventEmitter);

  _.extend(Client.prototype, {

    configure: function(options) {
      _.extend(this, _.pick(options, 'baseUrl'));
    },

    request: function(options) {
      if (!_.isObject(options)) {
        throw new Error('Request options must be an object');
      } else if (!_.isString(options.method)) {
        throw new Error('"method" must be a string, got ' + options.method);
      } else if (!_.isString(options.url)) {
        throw new Error('"url" must be a string, got ' + options.url);
      }

      var deferred = q.defer(),
          startTime = new Date().getTime(),
          requestNumber = ++this.requestNumber;

      return this.buildRequestOptions(options).then(_.bind(this.sendRequest, this, requestNumber, startTime, options))
        .spread(_.bind(this.handleResponse, this, requestNumber, startTime), _.bind(this.handleError, this, requestNumber));
    },

    sendRequest: function(requestNumber, startTime, originalOptions, requestOptions) {
      this.emit('request', requestNumber, requestOptions, originalOptions);
      return q.nfcall(request, requestOptions);
    },

    handleError: function(requestNumber, err) {
      this.emit('error', requestNumber, err);
      return q.reject(err);
    },

    handleResponse: function(requestNumber, startTime, response) {
      this.emit('response', requestNumber, response, new Date().getTime() - startTime);
      return response;
    },

    buildUrl: function(url) {
      return this.baseUrl ? this.baseUrl + url : url;
    },

    buildRequestOptions: function(options) {

      var requestOptions = _.extend(_.omit(options, 'filters'), {
        method: options.method.toUpperCase(),
        url: this.buildUrl(options.url)
      });

      // make a promise for chaining
      var promise = q(requestOptions);

      if (options.filters) {

        // add each filter to the chain
        _.each(options.filters, function(filter, i) {

          // after each filter, ensure that the returned request options
          // are an object, or use
          promise = promise.then(filter).then(_.bind(this.ensureRequestOptions, this, i));
        }, this);
      }

      return promise;
    },

    ensureRequestOptions: function(filterIndex, options) {
      if (options === undefined) {
        throw new Error('Request filter at index ' + filterIndex + ' returned nothing; it must return the filtered request options');
      } else if (!_.isObject(options)) {
        throw new Error('Expected request filter at index ' + filterIndex + ' to return the request options as an object, got ' + typeof(options));
      }

      return options;
    }
  });

  return Client;
};
<commit_msg>Fixed comment.<commit_after>exports.inject = function(deps) {
  deps = deps || {};

  var _ = require('underscore'),
    events = require('events'),
    q = require('q'),
    request = deps.request || require('request'),
    util = require('util');

  function Client() {

    this.requestNumber = 0;

    events.EventEmitter.call(this);
    this.on('configure', _.bind(this.configure, this));
  }

  util.inherits(Client, events.EventEmitter);

  _.extend(Client.prototype, {

    configure: function(options) {
      _.extend(this, _.pick(options, 'baseUrl'));
    },

    request: function(options) {
      if (!_.isObject(options)) {
        throw new Error('Request options must be an object');
      } else if (!_.isString(options.method)) {
        throw new Error('"method" must be a string, got ' + options.method);
      } else if (!_.isString(options.url)) {
        throw new Error('"url" must be a string, got ' + options.url);
      }

      var deferred = q.defer(),
          startTime = new Date().getTime(),
          requestNumber = ++this.requestNumber;

      return this.buildRequestOptions(options).then(_.bind(this.sendRequest, this, requestNumber, startTime, options))
        .spread(_.bind(this.handleResponse, this, requestNumber, startTime), _.bind(this.handleError, this, requestNumber));
    },

    sendRequest: function(requestNumber, startTime, originalOptions, requestOptions) {
      this.emit('request', requestNumber, requestOptions, originalOptions);
      return q.nfcall(request, requestOptions);
    },

    handleError: function(requestNumber, err) {
      this.emit('error', requestNumber, err);
      return q.reject(err);
    },

    handleResponse: function(requestNumber, startTime, response) {
      this.emit('response', requestNumber, response, new Date().getTime() - startTime);
      return response;
    },

    buildUrl: function(url) {
      return this.baseUrl ? this.baseUrl + url : url;
    },

    buildRequestOptions: function(options) {

      var requestOptions = _.extend(_.omit(options, 'filters'), {
        method: options.method.toUpperCase(),
        url: this.buildUrl(options.url)
      });

      // make a promise for chaining
      var promise = q(requestOptions);

      if (options.filters) {

        // add each filter to the chain
        _.each(options.filters, function(filter, i) {

          // after each filter, ensure that the returned request options are an object
          promise = promise.then(filter).then(_.bind(this.ensureRequestOptions, this, i));
        }, this);
      }

      return promise;
    },

    ensureRequestOptions: function(filterIndex, options) {
      if (options === undefined) {
        throw new Error('Request filter at index ' + filterIndex + ' returned nothing; it must return the filtered request options');
      } else if (!_.isObject(options)) {
        throw new Error('Expected request filter at index ' + filterIndex + ' to return the request options as an object, got ' + typeof(options));
      }

      return options;
    }
  });

  return Client;
};
<|endoftext|>


<commit_before>'use babel'
const FS = require('fs')
const Path = require('path')
const View = require('./view')
import {exec} from './helper'

window.__sb_package_deps = window.__sb_package_deps || []

export function install(packageName, enablePackages = true) {
  if (!packageName) throw new Error('packageName is required')

  const packageDeps = atom.packages.getLoadedPackage(packageName).metadata['package-deps'] || []
  const packagesToInstall = []
  packageDeps.forEach(function(name) {
    if (__sb_package_deps.indexOf(name) === -1) {
      __sb_package_deps.push(name)
      if (!atom.packages.resolvePackagePath(name)) {
        packagesToInstall.push(name)
      } else if(!atom.packages.getActivePackage(name) && enablePackages) {
        atom.packages.enablePackage(name)
        atom.packages.activatePackage(name)
      }
    }
  })
  if (packagesToInstall.length) {
    return installPackage(packageName, packagesToInstall)
  } else return Promise.resolve()
}

export function installPackage(packageName, packageNames) {
  const APMPath = atom.packages.getApmPath()
  const promises = []
  const view = new View(packageName, packageNames)
  return view.createNotification().then(() => {
    packageNames.forEach(function(name) {
      promises.push(exec(APMPath, ['install', name, '--production']))
    })
    return Promise.all(promises)
  }).then(function(outputs){
    outputs.forEach(function(output, index) {
      const name = packageNames[index]
      if (output.indexOf('✓') === -1 && output.indexOf('[32mdone') === -1) {
        view.markErrored(name, output)
      } else {
        atom.packages.enablePackage(name)
        atom.packages.activatePackage(name)
        view.markFinished()
      }
    })
  })
}
<commit_msg>:art: Use the new installPackages function in main<commit_after>'use babel'
const FS = require('fs')
const Path = require('path')
const View = require('./view')
import {installPackages} from './helper'

window.__sb_package_deps = window.__sb_package_deps || []

export function install(packageName, enablePackages = true) {
  if (!packageName) throw new Error('packageName is required')

  const packageDeps = atom.packages.getLoadedPackage(packageName).metadata['package-deps'] || []
  const packagesToInstall = []
  packageDeps.forEach(function(name) {
    if (__sb_package_deps.indexOf(name) === -1) {
      __sb_package_deps.push(name)
      if (!atom.packages.resolvePackagePath(name)) {
        packagesToInstall.push(name)
      } else if(!atom.packages.getActivePackage(name) && enablePackages) {
        atom.packages.enablePackage(name)
        atom.packages.activatePackage(name)
      }
    }
  })
  if (packagesToInstall.length) {
    return installPackage(packageName, packagesToInstall)
  } else return Promise.resolve()
}

export function installPackage(packageName, packageNames) {
  const view = new View(packageName, packageNames)
  return view.createNotification().then(() =>
    installPackages(packageNames, (name, status) => {
      // output.indexOf('✓') === -1 && output.indexOf('[32mdone') === -1
      if (status) {
        view.markErrored('Some Package', 'Some Output')
        atom.packages.enablePackage(name)
        atom.packages.activatePackage(name)
      } else {
        view.markFinished()
      }
    })
  )
}
<|endoftext|>


<commit_before>// if node
var Ser = require('./serializer');
// end node

var Client = exports.Client = function (bridge, id) {
  this._bridge = bridge;
  this.clientId = id;
};

Client.prototype.getService = function (svc, cb) {
  this._bridge._connection
      .sendCommand('GETOPS',
		   {name: svc, client: this.clientId,
		    callback: Ser.serialize(this._bridge, cb)});
};
<commit_msg>break Client.js module exports into an uglify fence<commit_after>// if node
var Ser = require('./serializer');
// end node

var Client = function (bridge, id) {
  this._bridge = bridge;
  this.clientId = id;
};

Client.prototype.getService = function (svc, cb) {
  this._bridge._connection
      .sendCommand('GETOPS',
		   {name: svc, client: this.clientId,
		    callback: Ser.serialize(this._bridge, cb)});
};

// if node
module.exports = Reference;
// end node
<|endoftext|>


<commit_before>var Link = require('./components/link');
var Route = require('./components/route');
var Routes = require('./components/routes');
var routeStore = require('./stores/route-store');
var urlStore = require('./stores/url-store');

function transitionTo(routeName, params) {
  urlStore.push(Link.makeHref(routeName, params));
}

function replaceWith(routeName, params) {
  urlStore.replace(Link.makeHref(routeName, params));
}

function getCurrentInfo() {
  return {
    route: routeStore.getActiveRoute(),
    params: routeStore.getActiveParams()
  };
}

module.exports = {
  Link: Link,
  Route: Route,
  Routes: Routes,
  transitionTo: transitionTo,
  replaceWith: replaceWith,
  getCurrentInfo: getCurrentInfo
};

<commit_msg>Add query to getCurrentInfo<commit_after>var Link = require('./components/link');
var Route = require('./components/route');
var Routes = require('./components/routes');
var routeStore = require('./stores/route-store');
var urlStore = require('./stores/url-store');

function transitionTo(routeName, params) {
  urlStore.push(Link.makeHref(routeName, params));
}

function replaceWith(routeName, params) {
  urlStore.replace(Link.makeHref(routeName, params));
}

function getCurrentInfo() {
  return {
    route: routeStore.getActiveRoute(),
    params: routeStore.getActiveParams(),
    query: routeStore.getActiveQuery()
  };
}

module.exports = {
  Link: Link,
  Route: Route,
  Routes: Routes,
  transitionTo: transitionTo,
  replaceWith: replaceWith,
  getCurrentInfo: getCurrentInfo
};

<|endoftext|>


<commit_before>'use babel';

import levelsConfig     from './levels-config';
import levelsServices   from './levels-services';
import workspaceManager from './workspace-manager';

export default {
  activate() {
    workspaceManager.setUpWorkspace();
    workspaceManager.activateEventHandlers();
    workspaceManager.activateCommandHandlers();
  },

  deactivate() {
    workspaceManager.cleanUpWorkspace();
    workspaceManager.deactivateEventHandlers();
    workspaceManager.deactivateCommandHandlers();
  },

  config: levelsConfig,

  provideLevels() {
    return levelsServices;
  },

  consumeStatusBar(statusBar) {
    workspaceManager.consumeStatusBar(statusBar);
  }
};<commit_msg>Destroy language registry and workspace on package deactivation<commit_after>'use babel';

import languageRegistry from './language-registry';
import levelsConfig     from './levels-config';
import levelsServices   from './levels-services';
import workspace        from './workspace';
import workspaceManager from './workspace-manager';

export default {
  activate() {
    workspaceManager.setUpWorkspace();
    workspaceManager.activateEventHandlers();
    workspaceManager.activateCommandHandlers();
  },

  deactivate() {
    workspaceManager.cleanUpWorkspace();
    workspaceManager.deactivateEventHandlers();
    workspaceManager.deactivateCommandHandlers();
    workspace.destroy();
    languageRegistry.destroy();
  },

  config: levelsConfig,

  provideLevels() {
    return levelsServices;
  },

  consumeStatusBar(statusBar) {
    workspaceManager.consumeStatusBar(statusBar);
  }
};<|endoftext|>


<commit_before>"use strict";
var timestamp
try {
  timestamp = require('microtime').nowDouble
}
catch (e) {
  timestamp = function () { return Date.now() / 1000 >> 0 }
}

var LOG_LEVELS = ['emerg','alert','crit','error','warn','notice','info','debug']
var LOG_LEVEL_PRIORITIES = Object.create(null)
LOG_LEVELS.forEach(function (level, priority) { LOG_LEVEL_PRIORITIES[level] = priority })

var zlib = require('zlib')
var dgram = require('dgram')
var os = require('os')
var crypto = require('crypto')
var Stream = require('stream')

var GrayGelf = function (opts) {
  opts || (opts = {})
  this.graylogHost = opts.host || 'localhost'
  this.graylogPort = opts.port || 12201
  this.facility = opts.facility
  this.chunkSize = opts.chunkSize || GrayGelf.CHUNK_WAN
  this.compressType = (opts.compressType || '') === 'gzip' ? 'gzip' : 'deflate'
  this.hostname = os.hostname()

  if (!opts.mock) {
    this._udp = dgram.createSocket('udp4')
    this._udp.on('error', this._checkError.bind(this))
  }

  this.writable = true // writable stream
  this.stream = {}

  LOG_LEVELS.forEach(function (name, level) {
    this[name] = function () { this.log.apply(this, [level].concat(Array.prototype.slice.call(arguments))); return this }.bind(this)
  }, this)
  LOG_LEVELS.forEach(this._stream, this)
}
GrayGelf.prototype = Object.create(Stream.prototype)
GrayGelf.prototype.write = function (chunk) {
  if (!this._udp) return
  this._udp.send(chunk, 0, chunk.length, this.graylogPort, this.graylogHost)
}

GrayGelf.prototype._checkError = function (er) { if (er) this.emit('error', er) }

GrayGelf.prototype._stream = function (name) {
  var stream = new Stream()
  stream.writable = true
  stream.write = this[name].bind(this)
  stream.end = function(){} // 'end' event is noop, stream always stays open
  this.stream[name] = stream
}

GrayGelf.prototype.close = function () {
  if (!this._udp) return
  this._udp.close()
  this._udp = null
}

GrayGelf.prototype._prepJson = function ( /*level, short, full*/ ) {
  if (!arguments.length) return; // bail, nothing to log

  var level, short, full, args
  if (arguments.length <= 3) {
    level = arguments[0]
    short = arguments[1]
    full = arguments[2]
  } else {
    args = Array.prototype.slice.call(arguments)
    level = args.shift()
    full = args.pop()
    short = args.join(' ')
  }

  if (typeof level === 'string') {
    if (typeof LOG_LEVEL_PRIORITIES[level] === 'undefined') {
      throw new Error('invalid level ' + level)
    }

    level = LOG_LEVEL_PRIORITIES[level]
  }

  this.emit('message', LOG_LEVELS[level], short, full)

  var gelf = {
    version: '1.1',
    host: this.hostname,
    short_message: Buffer.isBuffer(short) ? short.toString() : short,
    timestamp: timestamp(),
    level: level
  }

  if (this.facility) gelf.facility = this.facility

  if (full) {
    gelf.full_message = Buffer.isBuffer(full) ? full.toString() : full

    if (typeof full == 'object' && !Array.isArray(full) && full !== null) {
      for (var key in full) {
        if (full.hasOwnProperty(key)) {
          // populate special _ fields, _id not allowed in GELF format
          if (key.charAt(0) == '_' && key != '_id') gelf[key] = full[key]
        }
      }
    }
  }
  return gelf
}

GrayGelf.prototype._compress = function (gelf, next) {
  var gelfbuf = new Buffer(JSON.stringify(gelf))
  zlib[this.compressType](gelfbuf, function (er, message) {
    if (er) return this.emit('error', er)

    if (message.length > this.chunkSize) {
      var total = Math.ceil(message.length / this.chunkSize)
      var offset = 0

      crypto.randomBytes(6, function (er, idBuf) {
        if (er) return this.emit('error', er)

        for (var i = 0; i < total; i++) {
          var bytesToSend = offset + this.chunkSize < message.length ? this.chunkSize : message.length - offset
          var chunk = new Buffer(bytesToSend + 12)
          chunk[0] = 0x1e
          chunk[1] = 0x0f
          idBuf.copy(chunk, 2, 0, 6)
          chunk[10] = i
          chunk[11] = total

          message.copy(chunk, 12, offset, offset+bytesToSend)
          offset += bytesToSend
          next.call(this, chunk)
        }
      }.bind(this))
    }
    else next.call(this, message)
  }.bind(this))
}

GrayGelf.prototype.log = function () {
  var gelf = this._prepJson.apply(this, arguments)
  this._compress(gelf, this.write)
  return this
}

GrayGelf.CHUNK_WAN = 1240
GrayGelf.CHUNK_LAN = 8154

module.exports = GrayGelf
<commit_msg>add; auto unref client<commit_after>"use strict";
var timestamp
try {
  timestamp = require('microtime').nowDouble
}
catch (e) {
  timestamp = function () { return Date.now() / 1000 >> 0 }
}

var LOG_LEVELS = ['emerg','alert','crit','error','warn','notice','info','debug']
var LOG_LEVEL_PRIORITIES = Object.create(null)
LOG_LEVELS.forEach(function (level, priority) { LOG_LEVEL_PRIORITIES[level] = priority })

var zlib = require('zlib')
var dgram = require('dgram')
var os = require('os')
var crypto = require('crypto')
var Stream = require('stream')

var GrayGelf = function (opts) {
  opts || (opts = {})
  this.graylogHost = opts.host || 'localhost'
  this.graylogPort = opts.port || 12201
  this.facility = opts.facility
  this.chunkSize = opts.chunkSize || GrayGelf.CHUNK_WAN
  this.compressType = (opts.compressType || '') === 'gzip' ? 'gzip' : 'deflate'
  this.hostname = os.hostname()

  if (!opts.mock) {
    this._udp = dgram.createSocket('udp4')
    this._udp.on('error', this._checkError.bind(this))
    this._udp.unref()
  }

  this.writable = true // writable stream
  this.stream = {}

  LOG_LEVELS.forEach(function (name, level) {
    this[name] = function () { this.log.apply(this, [level].concat(Array.prototype.slice.call(arguments))); return this }.bind(this)
  }, this)
  LOG_LEVELS.forEach(this._stream, this)
}
GrayGelf.prototype = Object.create(Stream.prototype)
GrayGelf.prototype.write = function (chunk) {
  if (!this._udp) return
  this._udp.send(chunk, 0, chunk.length, this.graylogPort, this.graylogHost)
}

GrayGelf.prototype._checkError = function (er) { if (er) this.emit('error', er) }

GrayGelf.prototype._stream = function (name) {
  var stream = new Stream()
  stream.writable = true
  stream.write = this[name].bind(this)
  stream.end = function(){} // 'end' event is noop, stream always stays open
  this.stream[name] = stream
}

GrayGelf.prototype.close = function () {
  if (!this._udp) return
  this._udp.close()
  this._udp = null
}

GrayGelf.prototype._prepJson = function ( /*level, short, full*/ ) {
  if (!arguments.length) return; // bail, nothing to log

  var level, short, full, args
  if (arguments.length <= 3) {
    level = arguments[0]
    short = arguments[1]
    full = arguments[2]
  } else {
    args = Array.prototype.slice.call(arguments)
    level = args.shift()
    full = args.pop()
    short = args.join(' ')
  }

  if (typeof level === 'string') {
    if (typeof LOG_LEVEL_PRIORITIES[level] === 'undefined') {
      throw new Error('invalid level ' + level)
    }

    level = LOG_LEVEL_PRIORITIES[level]
  }

  this.emit('message', LOG_LEVELS[level], short, full)

  var gelf = {
    version: '1.1',
    host: this.hostname,
    short_message: Buffer.isBuffer(short) ? short.toString() : short,
    timestamp: timestamp(),
    level: level
  }

  if (this.facility) gelf.facility = this.facility

  if (full) {
    gelf.full_message = Buffer.isBuffer(full) ? full.toString() : full

    if (typeof full == 'object' && !Array.isArray(full) && full !== null) {
      for (var key in full) {
        if (full.hasOwnProperty(key)) {
          // populate special _ fields, _id not allowed in GELF format
          if (key.charAt(0) == '_' && key != '_id') gelf[key] = full[key]
        }
      }
    }
  }
  return gelf
}

GrayGelf.prototype._compress = function (gelf, next) {
  var gelfbuf = new Buffer(JSON.stringify(gelf))
  zlib[this.compressType](gelfbuf, function (er, message) {
    if (er) return this.emit('error', er)

    if (message.length > this.chunkSize) {
      var total = Math.ceil(message.length / this.chunkSize)
      var offset = 0

      crypto.randomBytes(6, function (er, idBuf) {
        if (er) return this.emit('error', er)

        for (var i = 0; i < total; i++) {
          var bytesToSend = offset + this.chunkSize < message.length ? this.chunkSize : message.length - offset
          var chunk = new Buffer(bytesToSend + 12)
          chunk[0] = 0x1e
          chunk[1] = 0x0f
          idBuf.copy(chunk, 2, 0, 6)
          chunk[10] = i
          chunk[11] = total

          message.copy(chunk, 12, offset, offset+bytesToSend)
          offset += bytesToSend
          next.call(this, chunk)
        }
      }.bind(this))
    }
    else next.call(this, message)
  }.bind(this))
}

GrayGelf.prototype.log = function () {
  var gelf = this._prepJson.apply(this, arguments)
  this._compress(gelf, this.write)
  return this
}

GrayGelf.CHUNK_WAN = 1240
GrayGelf.CHUNK_LAN = 8154

module.exports = GrayGelf
<|endoftext|>


<commit_before>require("sdk/system/unload").when(function() {
	let prefService = require("sdk/preferences/service");
	prefService.reset("general.useragent.site_specific_overrides");
	prefService.reset("general.useragent.override.youtube.com");
});

let prefService = require("sdk/preferences/service");
prefService.set('general.useragent.site_specific_overrides', true);
prefService.set("general.useragent.override.youtube.com",
	"Mozilla/5.0 (Linux; Android 4.4; Nexus 7 Build/KRT16S) AppleWebkit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36"
);
<commit_msg>Bugfix for site changes<commit_after>require("sdk/system/unload").when(function() {
	let prefService = require("sdk/preferences/service");
	prefService.reset("general.useragent.site_specific_overrides");
	prefService.reset("general.useragent.override.youtube.com");
	prefService.set("media.mediasource.enabled");
});

let prefService = require("sdk/preferences/service");
prefService.set('general.useragent.site_specific_overrides', true);
prefService.set("general.useragent.override.youtube.com",
	"Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36"
);
prefService.set("media.mediasource.enabled", true);
<|endoftext|>