<commit_before>import Schema from './schema';
import OCSource from 'orbit-common/source';

/**
 @module ember-orbit
 */

var get = Ember.get,
    set = Ember.set;

var Source = Ember.Object.extend({
  orbitSourceClass: null,
  orbitSourceOptions: null,
  schema: null,

  /**
   @method init
   @private
   */
  init: function() {
    this._super.apply(this, arguments);

    var OrbitSourceClass = get(this, 'orbitSourceClass');
    // If `orbitSourceClass` is obtained through the _super chain, dereference
    // its wrapped function, which will be the constructor.
    //
    // Note: This is only necessary when retrieving a *constructor* from an Ember
    //       class hierarchy. Otherwise, `superWrapper` "just works".
    if (OrbitSourceClass && OrbitSourceClass.wrappedFunction) {
     OrbitSourceClass = OrbitSourceClass.wrappedFunction;
    }

    Ember.assert("Source.orbitSourceClass must be initialized with an instance of an `OC.Source`",
      OrbitSourceClass); // TODO: verify OrbitSourceClass instanceof OCSource - need to resolve an inheritance problem in Orbit first

    var schema = get(this, 'schema');
    if (!schema) {
      var container = get(this, 'container');
      schema = container.lookup('schema:main');
      set(this, 'schema', schema);
    }

    var orbitSourceSchema = get(schema, '_schema');
    var orbitSourceOptions = get(this, 'orbitSourceOptions');
    this.orbitSource = new OrbitSourceClass(orbitSourceSchema, orbitSourceOptions);
  }
});

export default Source;<commit_msg>Resolved inheritance problem in Orbit 0.4.<commit_after>import Schema from './schema';
import OCSource from 'orbit-common/source';

/**
 @module ember-orbit
 */

var get = Ember.get,
    set = Ember.set;

var Source = Ember.Object.extend({
  orbitSourceClass: null,
  orbitSourceOptions: null,
  schema: null,

  /**
   @method init
   @private
   */
  init: function() {
    this._super.apply(this, arguments);

    var OrbitSourceClass = get(this, 'orbitSourceClass');

    // If `orbitSourceClass` is obtained through the _super chain, dereference
    // its wrapped function, which will be the constructor.
    //
    // Note: This is only necessary when retrieving a *constructor* from an Ember
    //       class hierarchy. Otherwise, `superWrapper` "just works".
    if (OrbitSourceClass && OrbitSourceClass.wrappedFunction) {
      OrbitSourceClass = OrbitSourceClass.wrappedFunction;
    }

    var schema = get(this, 'schema');
    if (!schema) {
      var container = get(this, 'container');
      schema = container.lookup('schema:main');
      set(this, 'schema', schema);
    }

    var orbitSourceSchema = get(schema, '_schema');
    var orbitSourceOptions = get(this, 'orbitSourceOptions');
    this.orbitSource = new OrbitSourceClass(orbitSourceSchema, orbitSourceOptions);

    Ember.assert("orbitSource must be an instance of an `OC.Source`",
      this.orbitSource instanceof OCSource);
  }
});

export default Source;<|endoftext|>


<commit_before>const generateEndpoints = require('./endpoints-utils');

const categoryName = 'Products';

const apiVersion = '2011-10-01';

const endpointList = [
    'ListMatchingProducts',
    'GetMatchingProduct',
    'GetMatchingProductForId',
    'GetCompetitivePricingForSKU',
    'GetCompetitivePricingForASIN',
    'GetLowestOfferListingsForSKU',
    'GetLowestOfferListingsForASIN',
    'GetLowestPricedOffersForSKU',
    'GetLowestPricedOffersForASIN',
    'GetMyFeesEstimate',
    'GetMyPriceForSKU',
    'GetMyPriceForASIN',
    'GetProductCategoriesForSKU',
    'GetProductCategoriesForASIN',
    'GetServiceStatus',
];

const newEndpointList = {
    GetMatchingProduct: {
        throttle: {
            maxInFlight: 1,
            restoreRate: 1,
        },
        params: {
            // this will cause an error to throw if you attempt to use this function.
            // The official documentation says to use GetMatchingProductForId instead, so we'll
            // just enforce that.
            DEPRECATED_USE_GetMatchingProductForId_INSTEAD: {
                type: 'xs:string',
                required: true,
            },
        },
    },
    GetMatchingProductForId: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 300,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: doc says "MarketplaceType" -- should we validate as that? https://docs.developer.amazonservices.com/en_UK/products/Products_Datatypes.html#MarketplaceType
                required: true,
            },
            IdType: {
                type: 'xs:string',
                required: true,
                values: ['ASIN', 'GCID', 'SellerSKU', 'UPC', 'EAN', 'ISBN', 'JAN'],
            },
            IdList: {
                type: 'xs:string',
                required: true,
                list: 'IdList.Id',
            },
        },
        returns: {
            Product: {
                type: '', // TODO: ?
                required: false,
            },
            Identifiers: {
                type: '', // TODO: ?
                required: false,
            },
            Relationships: {
                type: '', // TODO: ?
                required: false,
            },
            SalesRankings: {
                type: '', // TODO: ?
                required: false,
            },
        },
    },
    GetLowestOfferListingsForASIN: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: marketplaceId verification
                required: true,
            },
            ASINList: {
                type: 'xs:string',
                required: true,
                list: 'ASINList.ASIN',
            },
        },
        returns: {
            AllOfferListingsConsidered: {
                type: '', // TODO: ??? Documentation is really not clear
                required: false,
            },
            Product: {
                type: 'Product', // TODO: contains product subelements Product.Identifiers and Product.LowestOfferListings
                required: true,
            },
            Identifiers: {
                type: '', // TODO: ??? Documnetation also not clear
                required: false,
            },
            LowestOfferListings: {
                type: '', // TODO: ??????
                required: true,
            },
        },
    },
    GetLowestOfferListingsForSKU: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: marketplaceId verification
                required: true,
            },
            SellerSKUList: {
                type: 'xs:string',
                required: true,
                list: 'SellerSKUList.SellerSKU',
            },
        },
        returns: {
            AllOfferListingsConsidered: {
                type: '', // TODO: ??? Documentation is really not clear
                required: false,
            },
            Product: {
                type: 'Product', // TODO: contains product subelements Product.Identifiers and Product.LowestOfferListings
                required: true,
            },
            Identifiers: {
                type: '', // TODO: ??? Documnetation also not clear
                required: false,
            },
            LowestOfferListings: {
                type: '', // TODO: ??????
                required: true,
            },
        },
    },
    GetLowestPricedOffersForASIN: {
        throttle: {
            maxInFlight: 10,
            restoreRate: 300,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: doc says 'MarketplaceType'
                required: true,
            },
            ASIN: {
                type: 'xs:string',
                required: true,
            },
            ItemCondition: {
                type: 'xs:string',
                required: true,
                values: ['New', 'Used', 'Collectible', 'Refurbished', 'Club'],
            },
        },
        returns: {
            Identifier: {
                type: 'Identifier',
                required: true,
            },
            Summary: {
                type: 'Summary',
                required: true,
            },
            Offers: {
                type: 'Offers',
                required: false,
            },
        },
    },
    GetLowestPricedOffersForSKU: {
        throttle: {
            maxInFlight: 10,
            restoreRate: 300,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: doc says 'MarketplaceType'
                required: true,
            },
            SellerSKU: {
                type: 'xs:string',
                required: true,
            },
            ItemCondition: {
                type: 'xs:string',
                required: true,
                values: ['New', 'Used', 'Collectible', 'Refurbished', 'Club'],
            },
        },
        returns: {
            Identifier: {
                type: 'Identifier',
                required: true,
            },
            Summary: {
                type: 'Summary',
                required: true,
            },
            Offers: {
                type: 'Offers',
                required: false,
            },
        },
    },
    GetCompetitivePricingForASIN: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string',
                required: true,
            },
            ASINList: {
                type: 'xs:string',
                required: true, // TODO: maximum 20 values
                list: 'ASINList.ASIN',
            },
        },
        returns: {
            Product: {
                type: 'Product',
                required: true,
            },
            Identifiers: {
                type: 'Identifier',
                required: true,
            },
            CompetitivePricing: {
                type: 'CompetitivePrice',
                required: true,
            },
            SalesRankings: {
                type: 'SalesRanking',
                required: true,
            },
        },
    },
    GetCompetitivePricingForSKU: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string',
                required: true,
            },
            SellerSKUList: {
                type: 'xs:string',
                required: true, // TODO: maximum 20 values
                list: 'SellerSKUList.SellerSKU',
            },
        },
        returns: {
            Product: {
                type: 'Product',
                required: true,
            },
            Identifiers: {
                type: 'Identifier',
                required: true,
            },
            CompetitivePricing: {
                type: 'CompetitivePrice',
                required: true,
            },
            SalesRankings: {
                type: 'SalesRanking',
                required: true,
            },
        },
    },
    GetMyPriceForASIN: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string',
                required: true,
            },
            ASINList: {
                type: 'xs:string',
                required: true,
                list: 'ASINList.ASIN',
            },
            ItemCondition: {
                type: 'xs:string',
                values: ['New', 'Used', 'Collectible', 'Refurbished', 'Club'],
            },
        },
        returns: {
            Identifiers: {
                type: 'Identifier',
                required: true,
            },
            BuyingPrice: {
                type: 'BuyingPrice',
                required: true,
            },
            RegularPrice: {
                type: 'RegularPrice',
                required: true,
            },
            FulfillmentChannel: {
                type: 'FulfillmentChannel',
                required: true,
            },
            ItemCondition: {
                type: 'ItemCondition',
                required: true,
            },
            ItemSubCondition: {
                type: 'ItemSubCondition',
                required: true,
            },
            SellerId: {
                type: 'SellerId',
                required: true,
            },
            SellerSKU: {
                type: 'SellerSKU',
                required: true,
            },
        },
    },
    GetMyPriceForSKU: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string',
                required: true,
            },
            SellerSKUList: {
                type: 'xs:string',
                required: true,
                list: 'SellerSKUList.SellerSKU',
            },
            ItemCondition: {
                type: 'xs:string',
                values: ['New', 'Used', 'Collectible', 'Refurbished', 'Club'],
            },
        },
        returns: {
            Identifiers: {
                type: 'Identifier',
                required: true,
            },
            BuyingPrice: {
                type: 'BuyingPrice',
                required: true,
            },
            RegularPrice: {
                type: 'RegularPrice',
                required: true,
            },
            FulfillmentChannel: {
                type: 'FulfillmentChannel',
                required: true,
            },
            ItemCondition: {
                type: 'ItemCondition',
                required: true,
            },
            ItemSubCondition: {
                type: 'ItemSubCondition',
                required: true,
            },
            SellerId: {
                type: 'SellerId',
                required: true,
            },
            SellerSKU: {
                type: 'SellerSKU',
                required: true,
            },
        },
    },
    GetProductCategoriesForASIN: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 12,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: validate marketplaceId
                required: true,
            },
            ASIN: {
                type: 'xs:string',
                required: true,
            },
        },
        returns: {
            // TODO: fill this in
        },
    },
    GetProductCategoriesForSKU: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 12,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: validate marketplaceId
                required: true,
            },
            SellerSKU: {
                type: 'xs:string',
                required: true,
            },
        },
        returns: {
            // TODO: fill this in
        },
    },
    GetServiceStatus: {
        throttle: {
            maxInFlight: 2,
            restoreRate: 0.20,
        },
    },
    // GetMyFeesEstimate: {
    //     throttle: {
    //         maxInFlight: 20,
    //         restoreRate: 600,
    //     },
    //     params: {
    //         FeesEstimateRequestList: {
    //             // https://docs.developer.amazonservices.com/en_UK/products/Products_Datatypes.html#FeesEstimateRequest
    //             // TODO: we don't support custom objects.
    //             // This looks like
    //             // FeesEstimateRequestList.FeesEstimateRequest.1=
    //             // {
    //             //     IdType: 'ASIN', // type: 'MarketplaceType', values: ['ASIN', 'SellerSKU'],
    //             //     IdValue: 'B002KT3XQM', // type: 'xs:string'
    //             //     IsAmazonFulled: true, // type: 'xs:boolean',
    //             //     Identifier: 'request1', // type: 'xs:string'
    //             //     PriceToEstimateFees: {
    //             //         ListingPrice: {
    //             //             CurrencyCode: 'USD',
    //             //             Amount: '30.00',
    //             //         },
    //             //         Shipping: {
    //             //             CurrencyCode: 'USD',
    //             //             Amount: '3.99',
    //             //         },
    //             //         Points: {
    //             //             PointsNumber: 0,
    //             //         },
    //             //     },
    //             // }
    //             type: 'FeesEstimateRequest',
    //             required: true,
    //         },
    //     },
    //     returns: {

    //     },
    // }
};

/**
 * @private
 */

const endpoints = generateEndpoints(
    categoryName,
    apiVersion,
    endpointList,
    newEndpointList,
);

module.exports = endpoints;
<commit_msg>add ListMatchingProducts parameter validation<commit_after>const generateEndpoints = require('./endpoints-utils');

const categoryName = 'Products';

const apiVersion = '2011-10-01';

const endpointList = [
    'ListMatchingProducts',
    'GetMatchingProduct',
    'GetMatchingProductForId',
    'GetCompetitivePricingForSKU',
    'GetCompetitivePricingForASIN',
    'GetLowestOfferListingsForSKU',
    'GetLowestOfferListingsForASIN',
    'GetLowestPricedOffersForSKU',
    'GetLowestPricedOffersForASIN',
    'GetMyFeesEstimate',
    'GetMyPriceForSKU',
    'GetMyPriceForASIN',
    'GetProductCategoriesForSKU',
    'GetProductCategoriesForASIN',
    'GetServiceStatus',
];

const newEndpointList = {
    GetMatchingProduct: {
        throttle: {
            maxInFlight: 1,
            restoreRate: 1,
        },
        params: {
            // this will cause an error to throw if you attempt to use this function.
            // The official documentation says to use GetMatchingProductForId instead, so we'll
            // just enforce that.
            DEPRECATED_USE_GetMatchingProductForId_INSTEAD: {
                type: 'xs:string',
                required: true,
            },
        },
    },
    GetMatchingProductForId: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 300,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: doc says "MarketplaceType" -- should we validate as that? https://docs.developer.amazonservices.com/en_UK/products/Products_Datatypes.html#MarketplaceType
                required: true,
            },
            IdType: {
                type: 'xs:string',
                required: true,
                values: ['ASIN', 'GCID', 'SellerSKU', 'UPC', 'EAN', 'ISBN', 'JAN'],
            },
            IdList: {
                type: 'xs:string',
                required: true,
                list: 'IdList.Id',
            },
        },
        returns: {
            Product: {
                type: '', // TODO: ?
                required: false,
            },
            Identifiers: {
                type: '', // TODO: ?
                required: false,
            },
            Relationships: {
                type: '', // TODO: ?
                required: false,
            },
            SalesRankings: {
                type: '', // TODO: ?
                required: false,
            },
        },
    },
    GetLowestOfferListingsForASIN: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: marketplaceId verification
                required: true,
            },
            ASINList: {
                type: 'xs:string',
                required: true,
                list: 'ASINList.ASIN',
            },
        },
        returns: {
            AllOfferListingsConsidered: {
                type: '', // TODO: ??? Documentation is really not clear
                required: false,
            },
            Product: {
                type: 'Product', // TODO: contains product subelements Product.Identifiers and Product.LowestOfferListings
                required: true,
            },
            Identifiers: {
                type: '', // TODO: ??? Documnetation also not clear
                required: false,
            },
            LowestOfferListings: {
                type: '', // TODO: ??????
                required: true,
            },
        },
    },
    GetLowestOfferListingsForSKU: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: marketplaceId verification
                required: true,
            },
            SellerSKUList: {
                type: 'xs:string',
                required: true,
                list: 'SellerSKUList.SellerSKU',
            },
        },
        returns: {
            AllOfferListingsConsidered: {
                type: '', // TODO: ??? Documentation is really not clear
                required: false,
            },
            Product: {
                type: 'Product', // TODO: contains product subelements Product.Identifiers and Product.LowestOfferListings
                required: true,
            },
            Identifiers: {
                type: '', // TODO: ??? Documnetation also not clear
                required: false,
            },
            LowestOfferListings: {
                type: '', // TODO: ??????
                required: true,
            },
        },
    },
    GetLowestPricedOffersForASIN: {
        throttle: {
            maxInFlight: 10,
            restoreRate: 300,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: doc says 'MarketplaceType'
                required: true,
            },
            ASIN: {
                type: 'xs:string',
                required: true,
            },
            ItemCondition: {
                type: 'xs:string',
                required: true,
                values: ['New', 'Used', 'Collectible', 'Refurbished', 'Club'],
            },
        },
        returns: {
            Identifier: {
                type: 'Identifier',
                required: true,
            },
            Summary: {
                type: 'Summary',
                required: true,
            },
            Offers: {
                type: 'Offers',
                required: false,
            },
        },
    },
    GetLowestPricedOffersForSKU: {
        throttle: {
            maxInFlight: 10,
            restoreRate: 300,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: doc says 'MarketplaceType'
                required: true,
            },
            SellerSKU: {
                type: 'xs:string',
                required: true,
            },
            ItemCondition: {
                type: 'xs:string',
                required: true,
                values: ['New', 'Used', 'Collectible', 'Refurbished', 'Club'],
            },
        },
        returns: {
            Identifier: {
                type: 'Identifier',
                required: true,
            },
            Summary: {
                type: 'Summary',
                required: true,
            },
            Offers: {
                type: 'Offers',
                required: false,
            },
        },
    },
    GetCompetitivePricingForASIN: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string',
                required: true,
            },
            ASINList: {
                type: 'xs:string',
                required: true, // TODO: maximum 20 values
                list: 'ASINList.ASIN',
            },
        },
        returns: {
            Product: {
                type: 'Product',
                required: true,
            },
            Identifiers: {
                type: 'Identifier',
                required: true,
            },
            CompetitivePricing: {
                type: 'CompetitivePrice',
                required: true,
            },
            SalesRankings: {
                type: 'SalesRanking',
                required: true,
            },
        },
    },
    GetCompetitivePricingForSKU: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string',
                required: true,
            },
            SellerSKUList: {
                type: 'xs:string',
                required: true, // TODO: maximum 20 values
                list: 'SellerSKUList.SellerSKU',
            },
        },
        returns: {
            Product: {
                type: 'Product',
                required: true,
            },
            Identifiers: {
                type: 'Identifier',
                required: true,
            },
            CompetitivePricing: {
                type: 'CompetitivePrice',
                required: true,
            },
            SalesRankings: {
                type: 'SalesRanking',
                required: true,
            },
        },
    },
    GetMyPriceForASIN: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string',
                required: true,
            },
            ASINList: {
                type: 'xs:string',
                required: true,
                list: 'ASINList.ASIN',
            },
            ItemCondition: {
                type: 'xs:string',
                values: ['New', 'Used', 'Collectible', 'Refurbished', 'Club'],
            },
        },
        returns: {
            Identifiers: {
                type: 'Identifier',
                required: true,
            },
            BuyingPrice: {
                type: 'BuyingPrice',
                required: true,
            },
            RegularPrice: {
                type: 'RegularPrice',
                required: true,
            },
            FulfillmentChannel: {
                type: 'FulfillmentChannel',
                required: true,
            },
            ItemCondition: {
                type: 'ItemCondition',
                required: true,
            },
            ItemSubCondition: {
                type: 'ItemSubCondition',
                required: true,
            },
            SellerId: {
                type: 'SellerId',
                required: true,
            },
            SellerSKU: {
                type: 'SellerSKU',
                required: true,
            },
        },
    },
    GetMyPriceForSKU: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 600,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string',
                required: true,
            },
            SellerSKUList: {
                type: 'xs:string',
                required: true,
                list: 'SellerSKUList.SellerSKU',
            },
            ItemCondition: {
                type: 'xs:string',
                values: ['New', 'Used', 'Collectible', 'Refurbished', 'Club'],
            },
        },
        returns: {
            Identifiers: {
                type: 'Identifier',
                required: true,
            },
            BuyingPrice: {
                type: 'BuyingPrice',
                required: true,
            },
            RegularPrice: {
                type: 'RegularPrice',
                required: true,
            },
            FulfillmentChannel: {
                type: 'FulfillmentChannel',
                required: true,
            },
            ItemCondition: {
                type: 'ItemCondition',
                required: true,
            },
            ItemSubCondition: {
                type: 'ItemSubCondition',
                required: true,
            },
            SellerId: {
                type: 'SellerId',
                required: true,
            },
            SellerSKU: {
                type: 'SellerSKU',
                required: true,
            },
        },
    },
    GetProductCategoriesForASIN: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 12,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: validate marketplaceId
                required: true,
            },
            ASIN: {
                type: 'xs:string',
                required: true,
            },
        },
        returns: {
            // TODO: fill this in
        },
    },
    GetProductCategoriesForSKU: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 12,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: validate marketplaceId
                required: true,
            },
            SellerSKU: {
                type: 'xs:string',
                required: true,
            },
        },
        returns: {
            // TODO: fill this in
        },
    },
    GetServiceStatus: {
        throttle: {
            maxInFlight: 2,
            restoreRate: 0.20,
        },
    },
    ListMatchingProducts: {
        throttle: {
            maxInFlight: 20,
            restoreRate: 12,
        },
        params: {
            MarketplaceId: {
                type: 'xs:string', // TODO: validate marketplaceId
                required: true,
            },
            Query: {
                type: 'xs:string',
                required: true,
            },
            QueryContextId: {
                type: 'xs:string',
                required: true,
            },
        },
        returns: {
            /*
            Product,
            Identifiers,
            AttributeSets,
            Relationships,
            SalesRankings,
            */
        },
    },
    // GetMyFeesEstimate: {
    //     throttle: {
    //         maxInFlight: 20,
    //         restoreRate: 600,
    //     },
    //     params: {
    //         FeesEstimateRequestList: {
    //             // https://docs.developer.amazonservices.com/en_UK/products/Products_Datatypes.html#FeesEstimateRequest
    //             // TODO: we don't support custom objects.
    //             // This looks like
    //             // FeesEstimateRequestList.FeesEstimateRequest.1=
    //             // {
    //             //     IdType: 'ASIN', // type: 'MarketplaceType', values: ['ASIN', 'SellerSKU'],
    //             //     IdValue: 'B002KT3XQM', // type: 'xs:string'
    //             //     IsAmazonFulled: true, // type: 'xs:boolean',
    //             //     Identifier: 'request1', // type: 'xs:string'
    //             //     PriceToEstimateFees: {
    //             //         ListingPrice: {
    //             //             CurrencyCode: 'USD',
    //             //             Amount: '30.00',
    //             //         },
    //             //         Shipping: {
    //             //             CurrencyCode: 'USD',
    //             //             Amount: '3.99',
    //             //         },
    //             //         Points: {
    //             //             PointsNumber: 0,
    //             //         },
    //             //     },
    //             // }
    //             type: 'FeesEstimateRequest',
    //             required: true,
    //         },
    //     },
    //     returns: {

    //     },
    // }
};

/**
 * @private
 */

const endpoints = generateEndpoints(
    categoryName,
    apiVersion,
    endpointList,
    newEndpointList,
);

module.exports = endpoints;
<|endoftext|>


<commit_before>tinyMCE.init({

		// General options
		mode : "exact",
		elements : ${idlist},
		theme : "advanced",
		skin : "o2k7",
		plugins : "brix,safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups",

		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,

		// Example content CSS (should be your site CSS)
		content_css : "css/content.css",

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",

		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});<commit_msg>minimize buttons noise<commit_after>tinyMCE.init({

		// General options
		mode : "exact",
		elements : ${idlist},
		theme : "advanced",
		skin : "o2k7",
		plugins : "brix,safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,inlinepopups",

		// Theme options
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image",
		theme_advanced_buttons3 : "",
		theme_advanced_buttons4 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,

		// Example content CSS (should be your site CSS)
		content_css : "css/content.css",

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",

		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});<|endoftext|>


<commit_before>(function(window, document, $) {
    "use strict";
    var site = window.SITE,
        viewName = "index.photography",
        ui = {
            el: "#photography",
            backstretchEl: ".backstretch-wrap",
        },
        $backstretchEl = $(ui.el).find(ui.backstretchEl),
        partialImagesPath = "images/photos/",
        initBackstretch = function(){
            if ($.fn.backstretch){
                var imagesArr = [
                        {
                            url: "stuck-in-traffic.jpg",
                        },
                        {
                            url: "hana.jpg",
                        },
                        {
                            url: "big-ben.jpg",
                            alignY: 0.7,
                        },
                        {
                            url: "cat.jpg",
                            alignY: 0,
                        },
                        {
                            url: "double-rainbow-in-paris.jpg",
                        },
                        {
                            url: "autumn-in-zrinjevac.jpg",
                        },
                        {
                            url: "paris-sunset.jpg",
                        },
                        {
                            url: "flowers.jpg",
                        },
                        {
                            url: "tower-bridge.jpg",
                        },
                        {
                            url: "adriatic-sea.jpg",
                        },
                        {
                            url: "dijana.jpg",
                            alignY: 1,
                        },
                    ],
                    options = {
                        duration: 5000,
                        fade: 750,
                        preload: 1,
                    };

                // "http://farm8.staticflickr.com/7035/6464821765_36a618a812_o.jpg", /* Paris opera */

                $backstretchEl.backstretch(addImagePath(imagesArr), options);

                $(ui.el).on("click", function(){
                    var $el = $(this),
                        pausedClass = "paused",
                        playingClass = "playing",
                        isPaused = $el.is("."+pausedClass);

                    $el.toggleClass(pausedClass, !isPaused);
                    $el.toggleClass(playingClass, isPaused);

                    $backstretchEl.backstretch(isPaused ? "resume" : "pause");
                });
            }
            else {
                console.warn("Backstretch init failed");
            }
        },
        addImagePath = function(imagesArr){
            var fullImagesPath = site.settings.assetsUrl.local + partialImagesPath;

            imagesArr.forEach(function(el, i, arr){
                el.url = fullImagesPath + el.url;
            });

            return imagesArr;
        },
        exports = {
            init: function(){
                $(window).on("load."+viewName, function(){
                    initBackstretch();
                });
            },
        };

    site.views.register(viewName, exports);

})(this, this.document, jQuery);
<commit_msg>Added photography webp support<commit_after>(function(window, document, $) {
    "use strict";
    var site = window.SITE,
        viewName = "index.photography",
        ui = {
            el: "#photography",
            backstretchEl: ".backstretch-wrap",
        },
        $backstretchEl = $(ui.el).find(ui.backstretchEl),
        partialImagesPath = "images/photos/",
        initBackstretch = function(){
            if ($.fn.backstretch){
                var imagesArr = [
                        {
                            url: "stuck-in-traffic",
                        },
                        {
                            url: "hana",
                        },
                        {
                            url: "big-ben",
                            alignY: 0.7,
                        },
                        {
                            url: "cat",
                            alignY: 0,
                        },
                        {
                            url: "double-rainbow-in-paris",
                        },
                        {
                            url: "autumn-in-zrinjevac",
                        },
                        {
                            url: "paris-sunset",
                        },
                        {
                            url: "flowers",
                        },
                        {
                            url: "tower-bridge",
                        },
                        {
                            url: "adriatic-sea",
                        },
                        {
                            url: "dijana",
                            alignY: 1,
                        },
                    ],
                    options = {
                        duration: 5000,
                        fade: 750,
                        preload: 1,
                    };

                // "http://farm8.staticflickr.com/7035/6464821765_36a618a812_o.jpg", /* Paris opera */

                $backstretchEl.backstretch(prepareImages(imagesArr), options);

                $(ui.el).on("click", function(){
                    var $el = $(this),
                        pausedClass = "paused",
                        playingClass = "playing",
                        isPaused = $el.is("."+pausedClass);

                    $el.toggleClass(pausedClass, !isPaused);
                    $el.toggleClass(playingClass, isPaused);

                    $backstretchEl.backstretch(isPaused ? "resume" : "pause");
                });
            }
            else {
                console.warn("Backstretch init failed");
            }
        },
        prepareImages = function(imagesArr){
            var fullImagesPath = site.settings.assetsUrl.local + partialImagesPath,
                isWebPSupported = $("html").hasClass("webp");

            imagesArr.forEach(function(el, i, arr){
                el.url = fullImagesPath + el.url + "." + (isWebPSupported ? "webp" : "jpg");
            });

            return imagesArr;
        },
        exports = {
            init: function(){
                $(window).on("load."+viewName, function(){
                    initBackstretch();
                });
            },
        };

    site.views.register(viewName, exports);

})(this, this.document, jQuery);
<|endoftext|>


<commit_before>import { createStore, applyMiddleware } from "redux";
import createLogger from "redux-logger";
import thunk from "redux-thunk";

import reducer from "./reducers";

export default function configureStore() {
  const middlewares = [thunk];

  if (process.env.NODE_ENV !== 'production') { //eslint-disable-line
    middlewares.push(createLogger());
  }

  const store = createStore(
    reducer,
    /* persistedStateIfYouUseIt, */
    applyMiddleware(...middlewares)
  );

  return store;
}

<commit_msg>Add devtools Chrome extension<commit_after>import { createStore, applyMiddleware, compose } from "redux";
import createLogger from "redux-logger";
import thunk from "redux-thunk";

import reducer from "./reducers";

export default function configureStore() {
  const middlewares = [thunk];

  if (process.env.NODE_ENV !== 'production') { //eslint-disable-line
    middlewares.push(createLogger());
  }

  const devTools = window.devToolsExtension
    ? window.devToolsExtension()
    : (f => f);

  const enhancers = compose(
    applyMiddleware(...middlewares),
    devTools
  );

  const store = createStore(
    reducer,
    /* persistedStateIfYouUseIt, */
    enhancers
  );

  return store;
}

<|endoftext|>


<commit_before>/**
 * Room Controller
 *
 * @param {Object} $scope
 * @param {RoomRepository} RoomRepository
 */
function RoomConfigController($scope, repository)
{
    AbstractController.call(this, $scope);

    this.repository = repository;
    this.config     = null;

    // Binding:
    this.onJoined     = this.onJoined.bind(this);
    this.toggleBonus  = this.toggleBonus.bind(this);
    this.togglePreset = this.togglePreset.bind(this);
    this.setOpen      = this.setOpen.bind(this);
    this.setMaxScore  = this.setMaxScore.bind(this);
    this.setVariable  = this.setVariable.bind(this);

    // Hydrating scope
    this.$scope.toggleBonus  = this.toggleBonus;
    this.$scope.togglePreset = this.togglePreset;
    this.$scope.setOpen      = this.setOpen;
    this.$scope.setMaxScore  = this.setMaxScore;
    this.$scope.setVariable  = this.setVariable;

    this.repository.on('config:open', this.digestScope);
    this.repository.on('config:max-score', this.digestScope);
    this.repository.on('config:variable', this.digestScope);
    this.repository.on('config:bonus', this.digestScope);

    this.$scope.$parent.$watch('room', this.onJoined);
}

RoomConfigController.prototype = Object.create(AbstractController.prototype);
RoomConfigController.prototype.constructor = RoomConfigController;
var disabledit = false;
/**
 * On room joined
 */
RoomConfigController.prototype.onJoined = function()
{
    if (this.$scope.$parent.room) {
        this.config = this.$scope.$parent.room.config;
        this.$scope.config = this.config;
    }
};

/**
 * Toggle bonus
 *
 * @param {String} bonus
 */
RoomConfigController.prototype.toggleBonus = function(bonus)
{
    if (this.config.bonusExists(bonus) && this.repository.amIMaster()) {
        var config = this.config;

        this.repository.setConfigBonus(bonus, function (result) {
            config.setBonus(bonus, result.enabled);
        });
    } else {
        console.error('Unknown bonus: %s', bonus.type);
    }
};

/**
 * Toggle preset
 *
 * @param {String} bonus
 */
RoomConfigController.prototype.togglePreset = function(preset)
{
    if (this.config.preset === preset) {
        if (preset === this.config.getDefaultPreset()) {
            return;
        }

        return this.applyPreset(this.config.getDefaultPreset());
    }
	console.log(preset);
	for (var bonus in this.config.bonuses) {
		if (preset.hasName('Speed of light')) {
			console.log('YES ACTIVATED YES YES');
			sp1();
			disabledit = true;
			setTimeout(enableStuff, 3000);
			BaseAvatar.prototype.speed = true;
		}else {
			console.log('different one.');
			sp2();
			disabledit = true;
			setTimeout(enableStuff, 3000);
			BaseAvatar.prototype.speed = false;
		}
	}
    this.applyPreset(preset);

};
function enableStuff(){
	disabledit = false;
}
/**
 * Apply the given preset
 *
 * @param {Preset} preset
 */
RoomConfigController.prototype.applyPreset = function(preset)
{
    if (this.repository.amIMaster()) {
        for (var bonus in this.config.bonuses) {
            if (this.config.bonuses[bonus] !== preset.hasBonus(bonus)) {
                this.toggleBonus(bonus);
            }
        }
        this.config.preset = preset;
    }
	for (var bonus in this.config.bonuses) {
		if (preset.hasName('Speed of light')) {
			console.log('YES ACTIVATED YES YES');
			sp1();
		}else {
			console.log('different one.');
			sp2();
		}
	}
};

/**
 * Set open
 */
RoomConfigController.prototype.setOpen = function(open)
{
    if (this.repository.amIMaster()) {
        var config = this.config;

        this.repository.setConfigOpen(open, function (result) {
            config.setOpen(result.open);
            config.setPassword(result.password);
        });
    }
};

/**
 * Set max score
 */
RoomConfigController.prototype.setMaxScore = function(maxScore)
{
    if (this.repository.amIMaster()) {
        var config = this.config;

        this.repository.setConfigMaxScore(maxScore, function (result) {
            config.setMaxScore(result.maxScore);
        });
    }
};

/**
 * Set variable
 */
RoomConfigController.prototype.setVariable = function(variable)
{
    if (this.config.variableExists(variable) && this.repository.amIMaster()) {
        var config = this.config;

        this.repository.setConfigVariable(variable, this.config.getVariable(variable), function (result) {
            config.setVariable(result.variable, result.value);
        });
    }
};
<commit_msg>afasfasfsaf<commit_after>/**
 * Room Controller
 *
 * @param {Object} $scope
 * @param {RoomRepository} RoomRepository
 */
function RoomConfigController($scope, repository)
{
    AbstractController.call(this, $scope);

    this.repository = repository;
    this.config     = null;

    // Binding:
    this.onJoined     = this.onJoined.bind(this);
    this.toggleBonus  = this.toggleBonus.bind(this);
    this.togglePreset = this.togglePreset.bind(this);
    this.setOpen      = this.setOpen.bind(this);
    this.setMaxScore  = this.setMaxScore.bind(this);
    this.setVariable  = this.setVariable.bind(this);

    // Hydrating scope
    this.$scope.toggleBonus  = this.toggleBonus;
    this.$scope.togglePreset = this.togglePreset;
    this.$scope.setOpen      = this.setOpen;
    this.$scope.setMaxScore  = this.setMaxScore;
    this.$scope.setVariable  = this.setVariable;

    this.repository.on('config:open', this.digestScope);
    this.repository.on('config:max-score', this.digestScope);
    this.repository.on('config:variable', this.digestScope);
    this.repository.on('config:bonus', this.digestScope);

    this.$scope.$parent.$watch('room', this.onJoined);
}

RoomConfigController.prototype = Object.create(AbstractController.prototype);
RoomConfigController.prototype.constructor = RoomConfigController;
var disabledit = false;
/**
 * On room joined
 */
RoomConfigController.prototype.onJoined = function()
{
    if (this.$scope.$parent.room) {
        this.config = this.$scope.$parent.room.config;
        this.$scope.config = this.config;
    }
};

/**
 * Toggle bonus
 *
 * @param {String} bonus
 */
RoomConfigController.prototype.toggleBonus = function(bonus)
{
    if (this.config.bonusExists(bonus) && this.repository.amIMaster()) {
        var config = this.config;

        this.repository.setConfigBonus(bonus, function (result) {
            config.setBonus(bonus, result.enabled);
        });
    } else {
        console.error('Unknown bonus: %s', bonus.type);
    }
};

/**
 * Toggle preset
 *
 * @param {String} bonus
 */
RoomConfigController.prototype.togglePreset = function(preset)
{
    if (this.config.preset === preset) {
        if (preset === this.config.getDefaultPreset()) {
            return;
        }

        return this.applyPreset(this.config.getDefaultPreset());
    }
	console.log(preset);
	for (var bonus in this.config.bonuses) {
		if (preset.hasName('Speed of light')) {
			console.log('YES ACTIVATED YES YES');
			sp1();
			disabledit = true;
			setTimeout(enableStuff, 3000);
			BaseAvatar.prototype.speed = true;
		}else {
			console.log('different one.');
			disabledit = true;
			setTimeout(enableStuff, 3000);
		}
	}
    this.applyPreset(preset);

};
function enableStuff(){
	disabledit = false;
}
/**
 * Apply the given preset
 *
 * @param {Preset} preset
 */
RoomConfigController.prototype.applyPreset = function(preset)
{
    if (this.repository.amIMaster()) {
        for (var bonus in this.config.bonuses) {
            if (this.config.bonuses[bonus] !== preset.hasBonus(bonus)) {
                this.toggleBonus(bonus);
            }
        }
        this.config.preset = preset;
    }
	for (var bonus in this.config.bonuses) {
		if (preset.hasName('Speed of light')) {
			console.log('YES ACTIVATED YES YES');
			sp1();
		}else {
			console.log('different one.');
			sp2();
		}
	}
};

/**
 * Set open
 */
RoomConfigController.prototype.setOpen = function(open)
{
    if (this.repository.amIMaster()) {
        var config = this.config;

        this.repository.setConfigOpen(open, function (result) {
            config.setOpen(result.open);
            config.setPassword(result.password);
        });
    }
};

/**
 * Set max score
 */
RoomConfigController.prototype.setMaxScore = function(maxScore)
{
    if (this.repository.amIMaster()) {
        var config = this.config;

        this.repository.setConfigMaxScore(maxScore, function (result) {
            config.setMaxScore(result.maxScore);
        });
    }
};

/**
 * Set variable
 */
RoomConfigController.prototype.setVariable = function(variable)
{
    if (this.config.variableExists(variable) && this.repository.amIMaster()) {
        var config = this.config;

        this.repository.setConfigVariable(variable, this.config.getVariable(variable), function (result) {
            config.setVariable(result.variable, result.value);
        });
    }
};
<|endoftext|>


<commit_before>function GeographicCtrl($scope, GeographicRegion, $http, limitToFilter, FindSocieties) {
    $scope.model.searchParams.selectedRegions = [];

    $scope.removeRegion = function(region) {
        var index = $scope.model.searchParams.selectedRegions.indexOf(region)
        $scope.model.searchParams.selectedRegions.splice(index, 1);
    };

    // Discrepancy here. Region id is the tdwg code but the API expects the model pk id
    $scope.getSelectedGeographicRegions = function() {
        return $scope.model.searchParams.selectedRegions.map(function(region) {
            return region.id;
        });
    }

    $scope.doSearch = function() {
        var geographicRegions = $scope.getSelectedGeographicRegions();
        $scope.disableSearchButton();
        $scope.model.searchResults = FindSocieties.find({ geographic_regions: geographicRegions }, function() {
            $scope.enableSearchButton();
            $scope.switchToResults();
        });
    };
}
<commit_msg>Working search across multiple regions<commit_after>function GeographicCtrl($scope, GeographicRegion, $http, limitToFilter, FindSocieties) {
    $scope.model.searchParams.selectedRegions = [];
    $scope.model.geographic_regions = GeographicRegion.query();
    $scope.removeRegion = function(region) {
        var index = $scope.model.searchParams.selectedRegions.indexOf(region)
        $scope.model.searchParams.selectedRegions.splice(index, 1);
    };

    $scope.regionIdFromCode = function(code) {
        var regionId;
        $scope.model.geographic_regions.forEach(function (region) {
            if(region.tdwg_code == code) {
                regionId = region.id;
            }
        });
        return regionId;
    }

    $scope.getSelectedGeographicRegions = function() {
        var regionsWithoutIds = $scope.model.searchParams.selectedRegions;
        var regionIds = regionsWithoutIds.map(function(region) {
            return $scope.regionIdFromCode(Number(region.code));
        });
        return regionIds;
    }

    $scope.doSearch = function() {
        $scope.disableSearchButton();
        var geographicRegions = $scope.getSelectedGeographicRegions();
        $scope.model.searchResults = FindSocieties.find({ geographic_regions: geographicRegions }, function() {
            $scope.enableSearchButton();
            $scope.switchToResults();
        });
    };
}
<|endoftext|>


<commit_before>/*globals document,window,$,jQuery,Image */
/*jslint white: true, browser: true, onevar: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, strict: true, newcap: true, immed: true, indent: 2 */

"use strict";

/*
 * jQuery UI Lightbox
 *
 * Copyright (c) 2009 Benjamin Doherty
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Depends:
 *  ui.core.js
 *  ui.dialog.js
 *  jquery.mousewheel.js (optional)
 */
(function ($) {

  $.widget('ui.lightbox', {
    _init: function () {
      var self = this;

      // consider event delegation to make this more dynamic
      $(this.options.selector, this.element).click(function (event) {
        event.preventDefault();
        self.open(this);
      });
      $(document).keydown(function (event) {
        if (!self.lightbox || !self.lightbox.dialog('isOpen')) {
          return;
        }
        switch (event.keyCode) {
        case $.ui.keyCode.ESCAPE:
          if (self.options.closeOnEscape) {
            self.close();
          }
          break;
        case $.ui.keyCode.LEFT:
          self.prev("left");
          event.preventDefault();
          break;
        case $.ui.keyCode.UP:
          self.prev("up");
          event.preventDefault();
          break;
        case $.ui.keyCode.RIGHT:
          self.next("right");
          event.preventDefault();
          break;
        case $.ui.keyCode.DOWN:
          self.next("down");
          event.preventDefault();
          break;
        }
      });
      if ($.fn.mousewheel) {
        $(document).mousewheel(function (event, delta) {
          if (!self.lightbox.dialog('isOpen')) {
            return;
          }
          event.preventDefault();
          if (self.lightbox.is(":animated")) {
            return;
          }
          if (delta < 0) {
            self.next("down");
          }
          if (delta > 0) {
            self.prev("up");
          }
        });
      }
    },

    _makeDialog: function () {
      return $('
').dialog({
        autoOpen: false,
        closeOnEscape: false,
        modal: false,
        show: null,
        hide: null,
        dialogClass: this.options.dialogClass,
        position: this.options.position,
        resizable: this.options.resizable,
        draggable: this.options.draggable,
        height: this.options.height,
        width: this.options.width,
        // TODO: Support overlay by implementing focus,dragstop,resizestop
        open: function (event, ui) {
          $('.ui-dialog-buttonpane button', $(this).parents('.ui-dialog'))
            .each(function (index, domElement) {
              $(domElement).addClass('button-' + index);
            });
        }
      });
    },

    _buttons: {
      'Previous': function (eventObject) {
        $(this).dialog('option', '_lightbox').prev("right");
      },
      'Next': function (eventObject) {
        $(this).dialog('option', '_lightbox').next("left");
      }
    },

    destroy: function () {
      (this.overlay && this.overlay.destroy());
      this.element
        .unbind('.lightbox')
        .removeData('lightbox');
    },

    open: function (anchor) {
      var viewer = (this.lightbox = this._makeDialog());

      this.overlay = this.options.modal ? new $.ui.lightbox.overlay(viewer.data('dialog')) : null;
      this.setCurrentAnchor(anchor);

      viewer.dialog('option', 'buttons', this._buttons)
        .bind('dialogclose.lightbox', this._dialogClose)
        .dialog('open');

      viewer.dialog('option', '_lightbox', this);
    },

    close: function () {
      var viewer = this.lightbox;

      (this.overlay && this.overlay.destroy());

      $.ui.lightbox.overlay.resize();

      // TODO: these need to be destroyed with the widget.
      viewer.dialog('destroy').remove();
    },

    next: function (direction) {
      this._rotate(":gt(", ":first", direction || "up");
    },

    prev: function (direction) {
      this._rotate(":lt(", ":last", direction || "down");
    },

    _anchors: function () {
      // if deemed necessary, cache selection here
      return this.element.find(this.options.selector);
    },

    _setData: function (key, value) {
      if (key === 'cursor') {
        this.options[key] = value;
        this.spinner = new $.ui.lightbox.spinner(this);
        this._display(this._loadContent(value));
        this.spinner.destroy();
      }

      $.widget.prototype._setData.apply(this, arguments);
    },

    _display: function (content) {
      var anchor = this.getCurrentAnchor(),
        viewer = this.lightbox,
        size = this._calculateSize(content),
        $el = $(content).css(size).appendTo(viewer);

      viewer.dialog('option', 'title', $(anchor).attr('title') + this.options.titleSuffix);
      viewer.dialog('option', this._resize($el, size.width, size.height));
    },

    _loadContent: function (anchor) {
      var self = this,
        content = 'BUG',
        type = this.options.type ? this.options.type : this._deriveType(anchor);

      switch (type) {
      case "image":
        content = new Image();
        content.src = anchor.href;
        break;
      case "flash":
      case "flashvideo":
      case "quicktime":
      case "realplayer":
      case "windowsmedia":
        $(anchor).media({
          width: this.options.width,
          height: this.options.height,
          src: anchor.href,
          autoplay: 1
        }, function (element, options) {
        }, function (element, data, options, playerName) {
          content = $(data).html();
          $(data).media('undo');
        });
        break;
      case "iframe":
        content = this._element('iframe').attr('src', anchor.href).attr('frameborder', 0).attr('border', 0).html();
        break;
      case "html":
      case "dom":
        content = $('
').append($(anchor.href).clone().show()).remove().html();
        break;
      case "ajax":
      case "script":
        $.ajax({
          url: anchor.href,
          type: (parseInt(self.options.post, 10) === 1) ? "POST" : "GET",
          cache: true,
          async: false,
          data: self.options.parameters,
          dataType: (type === "ajax") ? "html" : "script",
          success: function (data, textStatus) {
            content = data;
          }
        });
        break;
      }

      return content;
    },

    _deriveType: function (anchor) {
      var reference = anchor.href;
      if (reference.toLowerCase().match(/\.(gif|jpg|jpeg|png)(\?[0123456789]+)?$/)) {
        return "image";
      }
      if (reference.toLowerCase().match(/\.(swf)(\?[0123456789]+)?$/)) {
        return "flash";
      }
      if (reference.toLowerCase().match(/\.(flv)(\?[0123456789]+)?$/)) {
        return "flashvideo";
      }
      if (reference.toLowerCase().match(/\.(aif|aiff|aac|au|bmp|gsm|mov|mid|midi|mpg|mpeg|m4a|m4v|mp4|psd|qt|qtif|qif|qti|snd|tif|tiff|wav|3g2|3gp|wbmp)(\?[0123456789]+)?$/)) {
        return "quicktime";
      }
      if (reference.toLowerCase().match(/\.(ra|ram|rm|rpm|rv|smi|smil)(\?[0123456789]+)?$/)) {
        return "realplayer";
      }
      if (reference.toLowerCase().match(/\.(asf|avi|wma|wmv)(\?[0123456789]+)?$/)) {
        return "windowsmedia";
      }
      return "ajax";
    },

    _preloadNeighbours: function () {
      var anchors = this._anchors(),
        index = anchors.index(this.getCurrentAnchor());
      anchors.filter(this._neighbours(anchors.length, index)).each(function () {
        //new Image().src = this.href;
      });
    },

    _neighbours: function (index, length) {
      return ":eq(" + (index === 0 ? length - 1 : index - 1) + "), :eq(" + (index === length - 1 ? 0 : index + 1) + ")";
    },

    _position: function (img) {
    },

    _calculateSize: function (content) {
      var width, height;
      $.swap($(content).appendTo('
').appendTo(document.body)[0], {
        position: "absolute",
        visibility: "hidden",
        display: "block"
      }, function () {
        width = $(this).width();
        height = $(this).height();
        $(this).remove();
      });
      return { width: width, height: height };
    },

    _resize: function (elem, width, height) {
      var viewer = this.lightbox,
        dialog = viewer.data('dialog'),
        offset = 20,

        // difference
        deltaContentWidth = viewer.outerWidth() - viewer.width(),
        deltaContentHeight = viewer.outerHeight() - viewer.height(),

        dialogTitlebarHeight = dialog.uiDialogTitlebar.outerHeight(),

        // Window
        wWidth = $(window).width(),
        wHeight = $(window).height(),

        size = {width: width, height: height},

        // Desired width
        finalWidth = size.width + deltaContentWidth,
        finalHeight = size.height + deltaContentHeight + dialogTitlebarHeight,

        ratio = Math.min(
          Math.min(
            Math.min(wWidth - deltaContentWidth - offset, size.width) / size.width,
            Math.min(wHeight - deltaContentHeight - dialogTitlebarHeight - offset, size.height) / size.height, 1));

      $.extend(size, {
        width: Math.round(ratio * size.width),
        height: Math.round(ratio * size.height)
      });

      elem.css(size);

      if (ratio !== 1) {
        elem.attr('width', '').attr('height', '');
      }

      finalWidth = size.width + deltaContentWidth;
      finalHeight = size.height + deltaContentHeight + dialogTitlebarHeight;

      return { width: finalWidth, height: finalHeight };
    },

    setCurrentAnchor: function (anchor) {
      this._setData('cursor', anchor);
    },

    getCurrentAnchor: function () {
      return this._getData('cursor');
    },

    _rotate: function (selectorA, selectorB, direction) {
      var self = this,
        anchors = this._anchors(),
        current = this.getCurrentAnchor(),
        target = this.getCurrentAnchor(),
        viewer = this.lightbox,
        dialog = viewer.data('dialog').uiDialog,

        effectOut = {
          direction: direction
        },
        effectIn = {
          direction: {up: "down", down: "up", left: "right", right: "left" }[direction]
        };

      if (anchors.length === 1) {
        return;
      }

      target = anchors.filter(selectorA + anchors.index(current) + ")" + selectorB)[0];
      if (!target && this.options.loop && anchors.length > 1) {
        target = anchors.filter(selectorB)[0];
      }

      dialog.hide(this.options.rotateOut, effectOut, this.options.duration, function () {
        viewer
          .unbind('dialogclose.lightbox')
          .bind('dialogclose.lightbox', self._rotateClose).dialog('close');
        self.setCurrentAnchor(target);
        $(this).show(self.options.rotateIn, effectIn, self.options.duration, function () {
          viewer
            .dialog('open')
            .unbind('dialogclose.lightbox')
            .bind('dialogclose.lightbox', self._dialogClose);
        });
      });
    },

    // Swappable dialog event handlers.

    _rotateClose: function (event, ui) {
      $(this).empty();
    },

    _dialogClose: function (event, ui) {
      $(this).empty().dialog('option', '_lightbox').close();
    },

    _element: function (type, clazz) {
      return $("<" + type + "/>").addClass(clazz).hide();
    }
  });

  $.extend($.ui.lightbox, {
    defaults: {
      loop: true,
      modal: true,
      overlay: {},
      post: 0,
      dialogClass: 'ui-lightbox',
      closeOnEscape: true,
      resizable: false,
      draggable: false,
      selector: "a[href]:has(img[src])",
      titleSuffix: "",
      position: 'center',
      width: 'auto',
      height: 'auto',
      parameters: {},
      duration: 1000,
      rotateIn: 'drop',
      rotateOut: 'drop',
      show: '',
      hide: ''
    },
    uuid: 0,
    overlay: function (dialog) {
      this.$el = $.ui.lightbox.overlay.create(dialog);
    },
    spinner: function (lightbox) {
      this.$el = $.ui.lightbox.spinner.create(lightbox);
    }
  });

  $.extend($.ui.lightbox.overlay, $.ui.dialog.overlay, {});

  $.extend($.ui.lightbox.overlay.prototype, $.ui.dialog.overlay.prototype, {
    destroy: function () {
      $.ui.lightbox.overlay.destroy(this.$el);
    }
  });

  $.extend($.ui.lightbox.spinner, {
    instances: [],
    create: function (lightbox) {
      if (this.instances.length === 0) {
        var $el = $('

').appendTo(document.body)
          .addClass('ui-loading-indicator ui-corner-all').fadeIn("slow");

        this.instances.push($el);
        return $el;
      }
    },
    destroy: function ($el) {
      this.instances.splice($.inArray(this.instances, $el), 1);

      $el.remove();
    }
  });

  $.extend($.ui.lightbox.spinner.prototype, {
    destroy: function () {
      $.ui.lightbox.spinner.destroy(this.$el);
    }
  });

})(jQuery);
<commit_msg>fix key lateral rotation direction.<commit_after>/*globals document,window,$,jQuery,Image */
/*jslint white: true, browser: true, onevar: true, undef: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, strict: true, newcap: true, immed: true, indent: 2 */

"use strict";

/*
 * jQuery UI Lightbox
 *
 * Copyright (c) 2009 Benjamin Doherty
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Depends:
 *  ui.core.js
 *  ui.dialog.js
 *  jquery.mousewheel.js (optional)
 */
(function ($) {

  $.widget('ui.lightbox', {
    _init: function () {
      var self = this;

      // consider event delegation to make this more dynamic
      $(this.options.selector, this.element).click(function (event) {
        event.preventDefault();
        self.open(this);
      });
      $(document).keydown(function (event) {
        if (!self.lightbox || !self.lightbox.dialog('isOpen')) {
          return;
        }
        switch (event.keyCode) {
        case $.ui.keyCode.ESCAPE:
          if (self.options.closeOnEscape) {
            self.close();
          }
          break;
        case $.ui.keyCode.LEFT:
          self.prev("right");
          event.preventDefault();
          break;
        case $.ui.keyCode.UP:
          self.prev("up");
          event.preventDefault();
          break;
        case $.ui.keyCode.RIGHT:
          self.next("left");
          event.preventDefault();
          break;
        case $.ui.keyCode.DOWN:
          self.next("down");
          event.preventDefault();
          break;
        }
      });
      if ($.fn.mousewheel) {
        $(document).mousewheel(function (event, delta) {
          if (!self.lightbox.dialog('isOpen')) {
            return;
          }
          event.preventDefault();
          if (self.lightbox.is(":animated")) {
            return;
          }
          if (delta < 0) {
            self.next("down");
          }
          if (delta > 0) {
            self.prev("up");
          }
        });
      }
    },

    _makeDialog: function () {
      return $('
').dialog({
        autoOpen: false,
        closeOnEscape: false,
        modal: false,
        show: null,
        hide: null,
        dialogClass: this.options.dialogClass,
        position: this.options.position,
        resizable: this.options.resizable,
        draggable: this.options.draggable,
        height: this.options.height,
        width: this.options.width,
        // TODO: Support overlay by implementing focus,dragstop,resizestop
        open: function (event, ui) {
          $('.ui-dialog-buttonpane button', $(this).parents('.ui-dialog'))
            .each(function (index, domElement) {
              $(domElement).addClass('button-' + index);
            });
        }
      });
    },

    _buttons: {
      'Previous': function (eventObject) {
        $(this).dialog('option', '_lightbox').prev("right");
      },
      'Next': function (eventObject) {
        $(this).dialog('option', '_lightbox').next("left");
      }
    },

    destroy: function () {
      (this.overlay && this.overlay.destroy());
      this.element
        .unbind('.lightbox')
        .removeData('lightbox');
    },

    open: function (anchor) {
      var viewer = (this.lightbox = this._makeDialog());

      this.overlay = this.options.modal ? new $.ui.lightbox.overlay(viewer.data('dialog')) : null;
      this.setCurrentAnchor(anchor);

      viewer.dialog('option', 'buttons', this._buttons)
        .bind('dialogclose.lightbox', this._dialogClose)
        .dialog('open');

      viewer.dialog('option', '_lightbox', this);
    },

    close: function () {
      var viewer = this.lightbox;

      (this.overlay && this.overlay.destroy());

      $.ui.lightbox.overlay.resize();

      // TODO: these need to be destroyed with the widget.
      viewer.dialog('destroy').remove();
    },

    next: function (direction) {
      this._rotate(":gt(", ":first", direction || "up");
    },

    prev: function (direction) {
      this._rotate(":lt(", ":last", direction || "down");
    },

    _anchors: function () {
      // if deemed necessary, cache selection here
      return this.element.find(this.options.selector);
    },

    _setData: function (key, value) {
      if (key === 'cursor') {
        this.options[key] = value;
        this.spinner = new $.ui.lightbox.spinner(this);
        this._display(this._loadContent(value));
        this.spinner.destroy();
      }

      $.widget.prototype._setData.apply(this, arguments);
    },

    _display: function (content) {
      var anchor = this.getCurrentAnchor(),
        viewer = this.lightbox,
        size = this._calculateSize(content),
        $el = $(content).css(size).appendTo(viewer);

      viewer.dialog('option', 'title', $(anchor).attr('title') + this.options.titleSuffix);
      viewer.dialog('option', this._resize($el, size.width, size.height));
    },

    _loadContent: function (anchor) {
      var self = this,
        content = 'BUG',
        type = this.options.type ? this.options.type : this._deriveType(anchor);

      switch (type) {
      case "image":
        content = new Image();
        content.src = anchor.href;
        break;
      case "flash":
      case "flashvideo":
      case "quicktime":
      case "realplayer":
      case "windowsmedia":
        $(anchor).media({
          width: this.options.width,
          height: this.options.height,
          src: anchor.href,
          autoplay: 1
        }, function (element, options) {
        }, function (element, data, options, playerName) {
          content = $(data).html();
          $(data).media('undo');
        });
        break;
      case "iframe":
        content = this._element('iframe').attr('src', anchor.href).attr('frameborder', 0).attr('border', 0).html();
        break;
      case "html":
      case "dom":
        content = $('
').append($(anchor.href).clone().show()).remove().html();
        break;
      case "ajax":
      case "script":
        $.ajax({
          url: anchor.href,
          type: (parseInt(self.options.post, 10) === 1) ? "POST" : "GET",
          cache: true,
          async: false,
          data: self.options.parameters,
          dataType: (type === "ajax") ? "html" : "script",
          success: function (data, textStatus) {
            content = data;
          }
        });
        break;
      }

      return content;
    },

    _deriveType: function (anchor) {
      var reference = anchor.href;
      if (reference.toLowerCase().match(/\.(gif|jpg|jpeg|png)(\?[0123456789]+)?$/)) {
        return "image";
      }
      if (reference.toLowerCase().match(/\.(swf)(\?[0123456789]+)?$/)) {
        return "flash";
      }
      if (reference.toLowerCase().match(/\.(flv)(\?[0123456789]+)?$/)) {
        return "flashvideo";
      }
      if (reference.toLowerCase().match(/\.(aif|aiff|aac|au|bmp|gsm|mov|mid|midi|mpg|mpeg|m4a|m4v|mp4|psd|qt|qtif|qif|qti|snd|tif|tiff|wav|3g2|3gp|wbmp)(\?[0123456789]+)?$/)) {
        return "quicktime";
      }
      if (reference.toLowerCase().match(/\.(ra|ram|rm|rpm|rv|smi|smil)(\?[0123456789]+)?$/)) {
        return "realplayer";
      }
      if (reference.toLowerCase().match(/\.(asf|avi|wma|wmv)(\?[0123456789]+)?$/)) {
        return "windowsmedia";
      }
      return "ajax";
    },

    _preloadNeighbours: function () {
      var anchors = this._anchors(),
        index = anchors.index(this.getCurrentAnchor());
      anchors.filter(this._neighbours(anchors.length, index)).each(function () {
        //new Image().src = this.href;
      });
    },

    _neighbours: function (index, length) {
      return ":eq(" + (index === 0 ? length - 1 : index - 1) + "), :eq(" + (index === length - 1 ? 0 : index + 1) + ")";
    },

    _position: function (img) {
    },

    _calculateSize: function (content) {
      var width, height;
      $.swap($(content).appendTo('
').appendTo(document.body)[0], {
        position: "absolute",
        visibility: "hidden",
        display: "block"
      }, function () {
        width = $(this).width();
        height = $(this).height();
        $(this).remove();
      });
      return { width: width, height: height };
    },

    _resize: function (elem, width, height) {
      var viewer = this.lightbox,
        dialog = viewer.data('dialog'),
        offset = 20,

        // difference
        deltaContentWidth = viewer.outerWidth() - viewer.width(),
        deltaContentHeight = viewer.outerHeight() - viewer.height(),

        dialogTitlebarHeight = dialog.uiDialogTitlebar.outerHeight(),

        // Window
        wWidth = $(window).width(),
        wHeight = $(window).height(),

        size = {width: width, height: height},

        // Desired width
        finalWidth = size.width + deltaContentWidth,
        finalHeight = size.height + deltaContentHeight + dialogTitlebarHeight,

        ratio = Math.min(
          Math.min(
            Math.min(wWidth - deltaContentWidth - offset, size.width) / size.width,
            Math.min(wHeight - deltaContentHeight - dialogTitlebarHeight - offset, size.height) / size.height, 1));

      $.extend(size, {
        width: Math.round(ratio * size.width),
        height: Math.round(ratio * size.height)
      });

      elem.css(size);

      if (ratio !== 1) {
        elem.attr('width', '').attr('height', '');
      }

      finalWidth = size.width + deltaContentWidth;
      finalHeight = size.height + deltaContentHeight + dialogTitlebarHeight;

      return { width: finalWidth, height: finalHeight };
    },

    setCurrentAnchor: function (anchor) {
      this._setData('cursor', anchor);
    },

    getCurrentAnchor: function () {
      return this._getData('cursor');
    },

    _rotate: function (selectorA, selectorB, direction) {
      var self = this,
        anchors = this._anchors(),
        current = this.getCurrentAnchor(),
        target = this.getCurrentAnchor(),
        viewer = this.lightbox,
        dialog = viewer.data('dialog').uiDialog,

        effectOut = {
          direction: direction
        },
        effectIn = {
          direction: {up: "down", down: "up", left: "right", right: "left" }[direction]
        };

      if (anchors.length === 1) {
        return;
      }

      target = anchors.filter(selectorA + anchors.index(current) + ")" + selectorB)[0];
      if (!target && this.options.loop && anchors.length > 1) {
        target = anchors.filter(selectorB)[0];
      }

      dialog.hide(this.options.rotateOut, effectOut, this.options.duration, function () {
        viewer
          .unbind('dialogclose.lightbox')
          .bind('dialogclose.lightbox', self._rotateClose).dialog('close');
        self.setCurrentAnchor(target);
        $(this).show(self.options.rotateIn, effectIn, self.options.duration, function () {
          viewer
            .dialog('open')
            .unbind('dialogclose.lightbox')
            .bind('dialogclose.lightbox', self._dialogClose);
        });
      });
    },

    // Swappable dialog event handlers.

    _rotateClose: function (event, ui) {
      $(this).empty();
    },

    _dialogClose: function (event, ui) {
      $(this).empty().dialog('option', '_lightbox').close();
    },

    _element: function (type, clazz) {
      return $("<" + type + "/>").addClass(clazz).hide();
    }
  });

  $.extend($.ui.lightbox, {
    defaults: {
      loop: true,
      modal: true,
      overlay: {},
      post: 0,
      dialogClass: 'ui-lightbox',
      closeOnEscape: true,
      resizable: false,
      draggable: false,
      selector: "a[href]:has(img[src])",
      titleSuffix: "",
      position: 'center',
      width: 'auto',
      height: 'auto',
      parameters: {},
      duration: 1000,
      rotateIn: 'drop',
      rotateOut: 'drop',
      show: '',
      hide: ''
    },
    uuid: 0,
    overlay: function (dialog) {
      this.$el = $.ui.lightbox.overlay.create(dialog);
    },
    spinner: function (lightbox) {
      this.$el = $.ui.lightbox.spinner.create(lightbox);
    }
  });

  $.extend($.ui.lightbox.overlay, $.ui.dialog.overlay, {});

  $.extend($.ui.lightbox.overlay.prototype, $.ui.dialog.overlay.prototype, {
    destroy: function () {
      $.ui.lightbox.overlay.destroy(this.$el);
    }
  });

  $.extend($.ui.lightbox.spinner, {
    instances: [],
    create: function (lightbox) {
      if (this.instances.length === 0) {
        var $el = $('

').appendTo(document.body)
          .addClass('ui-loading-indicator ui-corner-all').fadeIn("slow");

        this.instances.push($el);
        return $el;
      }
    },
    destroy: function ($el) {
      this.instances.splice($.inArray(this.instances, $el), 1);

      $el.remove();
    }
  });

  $.extend($.ui.lightbox.spinner.prototype, {
    destroy: function () {
      $.ui.lightbox.spinner.destroy(this.$el);
    }
  });

})(jQuery);
<|endoftext|>


<commit_before>/*
The MIT License (MIT)
Copyright (c) 2014 Andrea Rocco Lotronto
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var wts = require("node-reverse-wstunnel");
var autobahn = require('autobahn');

var os = require('os');
var ifaces = os.networkInterfaces();

var url_wamp_router = "ws://212.189.207.109:8181/ws";
var url_reverse_server = "ws://212.189.207.109:8080";

var connection = new autobahn.Connection({
	url: url_wamp_router,
	realm: "s4t"
});

var linino = require('ideino-linino-lib');
var board = new linino.Board();

var topic_command = 'board.command';
var topic_connection = 'board.connection';

var getIP = require('./lib/getIP.js');
var IPLocal = '127.0.0.1';//getIP('eth0', 'IPv4');

//As first step we need to use the function 'connect' of the object 'linino.Board()''
board.connect( function(){
   //After the connection is ready we can use the ideino-linino-lib to controll the PIN
   //of the board

   connection.onopen = function (session, details) {

      //Define a RPC to Read Data from PIN
      function readDigital(args){
         if (args[0]==os.hostname()){
            value = board.digitalRead(args[2]);
            return value;
         }
         else{
            //DEBUG Message
            console.log("ERRORRR");
            return null;
         }
      }
      //Define a RPC to Read Data from PIN
      function readAnalog(args){
         if (args[0]==os.hostname()){
            value = board.analogRead(args[2]);
            return value;
         }
         else{
            //DEBUG Message
            console.log("ERRORRR");
            return null;
         }
      }
      //Register a RPC for remoting
      session.register('command.rpc.read.digital', readDigital);
      session.register('command.rpc.read.analog', readAnalog);

      // Publish, Subscribe, Call and Register
      console.log("Connected to WAMP router: "+url_wamp_router);

      //Registro la scheda pubblicando su un topic
      console.log("Send my ID on topic: "+topic_connection);

      session.publish(topic_connection, [os.hostname(), 'connection']);

      //Gestione chiusura comunicazione al server
      process.on('SIGINT', function(){
         session.publish(topic_connection, [os.hostname(), 'disconnect']);
         process.exit();
      });

      //Gestisco topic per i comandi
      var onCommandMessage = function (args){
         console.log('Receive:::'+args[0]);
         console.log('')

         if(args[0]==os.hostname()){
            switch(args[1]){
               case 'ssh':
                  //DEBUG
                  console.log("Start REVERSE for ssh");

                  var reverse_client_ssh = new wts.client_reverse;

                  //DEBUG
                  console.log(typeof(reverse_client_ssh));
                  console.log(args[2]+','+url_reverse_server+','+IPLocal+':22')

                  reverse_client_ssh.start(args[2], url_reverse_server, IPLocal+':22');
                  break;
               case 'ideino':
                  //DEBUG
                  console.log("Start REVERSE for ideino");

                  var reverse_client_ideino = new wts.client_reverse;
                  //DEBUG
                  console.log(typeof(reverse_client_ideino));
                  console.log(args[2]+','+url_reverse_server+','+IPLocal+':2424')

                  reverse_client_ideino.start(args[2], url_reverse_server, IPLocal+':2424');
                  break;
               case 'osjs':
                  //DEBUG
                  console.log("Start REVERSE for osjs");
                  var reverse_client_ideino = new wts.client_reverse;

                  //DEBUG
                  console.log(typeof(reverse_client_ideino));
                  console.log(args[2]+','+url_reverse_server+','+IPLocal+':8000')

                  reverse_client_ideino.start(args[2], url_reverse_server, IPLocal+':8000');
                  break;

               //-----------SET MODE------------------
               case 'mode':
                  //DEBUG Message
                  console.log('Set PIN MODE');
                  //console.log('message::::'+args);
                  //console.log('board.pinMode('+args[2]+','+args[3]+')');
                  board.pinMode(args[2],args[3]);
                  break;
               //------------PIN ANALOG READ---------------------
               case 'analog':

                  if(args[3]!= undefined){//WRITE
                     //console.log('message::::'+args);
                     //DEBUG Message
                     console.log('ANALOG WRITE');
                     //console.log('boardanaloglWrite('+args[2]+','+args[3]+')');
                     board.analogWrite(args[2],parseInt(args[3]));
                     break;
                  }
                  /*else{//READ
                     //DEBUG Message
                     //console.log('message::::'+args);
                     console.log('ANALOG READ');
                     //Implement quait for response
                     break;
                  }
                  */
               case 'digital':

                   if(args[3]!= undefined){
                     //DEBUG Message
                     //console.log('message::::'+args);
                     console.log('DIGITAL WRITE');
                     //console.log('board.digitalWrite('+args[2]+','+args[3]+')');
                     board.digitalWrite(args[2],parseInt(args[3]));
                     break;
                   }
                   /*else{//READ
                     //DEBUG Message
                     //console.log('message::::'+args);
                     console.log('DIGITAL READ');
                     //Implement quait for response
                     break;
                   }*/

            }
         }
      }

      session.subscribe(topic_command, onCommandMessage);
   };

   connection.onclose = function (reason, details) {
      // handle connection lost
   }

   connection.open();

});<commit_msg>adjustmentsfor demo<commit_after>/*
The MIT License (MIT)
Copyright (c) 2014 Andrea Rocco Lotronto
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var wts = require("node-reverse-wstunnel");
var autobahn = require('autobahn');

var os = require('os');
var ifaces = os.networkInterfaces();

var url_wamp_router = "ws://212.189.207.109:8181/ws";
var url_reverse_server = "ws://212.189.207.109:8080";

var connection = new autobahn.Connection({
	url: url_wamp_router,
	realm: "s4t"
});

var linino = require('ideino-linino-lib');
var board = new linino.Board();

var topic_command = 'board.command';
var topic_connection = 'board.connection';

var getIP = require('./lib/getIP.js');
var IPLocal = '127.0.0.1';//getIP('eth0', 'IPv4');

//As first step we need to use the function 'connect' of the object 'linino.Board()''
board.connect( function(){
   //After the connection is ready we can use the ideino-linino-lib to controll the PIN
   //of the board

   connection.onopen = function (session, details) {

      //Define a RPC to Read Data from PIN
      function readDigital(args){
         if (args[0]==os.hostname()){
            value = board.digitalRead(args[2]);
            return value;
         }
         else{
            //DEBUG Message
            console.log("ERRORRR");
            return null;
         }
      }
      //Define a RPC to Read Data from PIN
      function readAnalog(args){
         if (args[0]==os.hostname()){
            value = board.analogRead(args[2]);
            return value;
         }
         else{
            //DEBUG Message
            console.log("ERRORRR");
            return null;
         }
      }
      //Register a RPC for remoting
      session.register(os.hostname()+'.command.rpc.read.digital', readDigital);
      session.register(os.hostname()+'.command.rpc.read.analog', readAnalog);

      // Publish, Subscribe, Call and Register
      console.log("Connected to WAMP router: "+url_wamp_router);

      //Registro la scheda pubblicando su un topic
      console.log("Send my ID on topic: "+topic_connection);

      session.publish(topic_connection, [os.hostname(), 'connection']);

      //Gestione chiusura comunicazione al server
      process.on('SIGINT', function(){
         session.publish(topic_connection, [os.hostname(), 'disconnect']);
         process.exit();
      });

      //Gestisco topic per i comandi
      var onCommandMessage = function (args){
         console.log('Receive:::'+args[0]);
         console.log('')

         if(args[0]==os.hostname()){
            switch(args[1]){
               case 'ssh':
                  //DEBUG
                  console.log("Start REVERSE for ssh");

                  var reverse_client_ssh = new wts.client_reverse;

                  //DEBUG
                  console.log(typeof(reverse_client_ssh));
                  console.log(args[2]+','+url_reverse_server+','+IPLocal+':22')

                  reverse_client_ssh.start(args[2], url_reverse_server, IPLocal+':22');
                  break;
               case 'ideino':
                  //DEBUG
                  console.log("Start REVERSE for ideino");

                  var reverse_client_ideino = new wts.client_reverse;
                  //DEBUG
                  console.log(typeof(reverse_client_ideino));
                  console.log(args[2]+','+url_reverse_server+','+IPLocal+':2424')

                  reverse_client_ideino.start(args[2], url_reverse_server, IPLocal+':2424');
                  break;
               case 'osjs':
                  //DEBUG
                  console.log("Start REVERSE for osjs");
                  var reverse_client_ideino = new wts.client_reverse;

                  //DEBUG
                  console.log(typeof(reverse_client_ideino));
                  console.log(args[2]+','+url_reverse_server+','+IPLocal+':8000')

                  reverse_client_ideino.start(args[2], url_reverse_server, IPLocal+':8000');
                  break;

               //-----------SET MODE------------------
               case 'mode':
                  //DEBUG Message
                  console.log('Set PIN MODE');
                  //console.log('message::::'+args);
                  //console.log('board.pinMode('+args[2]+','+args[3]+')');
                  board.pinMode(args[2],args[3]);
                  break;
               //------------PIN ANALOG READ---------------------
               case 'analog':

                  if(args[3]!= undefined){//WRITE
                     //console.log('message::::'+args);
                     //DEBUG Message
                     console.log('ANALOG WRITE');
                     //console.log('boardanaloglWrite('+args[2]+','+args[3]+')');
                     board.analogWrite(args[2],parseInt(args[3]));
                     break;
                  }
                  /*else{//READ
                     //DEBUG Message
                     //console.log('message::::'+args);
                     console.log('ANALOG READ');
                     //Implement quait for response
                     break;
                  }
                  */
               case 'digital':

                   if(args[3]!= undefined){
                     //DEBUG Message
                     //console.log('message::::'+args);
                     console.log('DIGITAL WRITE');
                     //console.log('board.digitalWrite('+args[2]+','+args[3]+')');
                     board.digitalWrite(args[2],parseInt(args[3]));
                     break;
                   }
                   /*else{//READ
                     //DEBUG Message
                     //console.log('message::::'+args);
                     console.log('DIGITAL READ');
                     //Implement quait for response
                     break;
                   }*/

            }
         }
      }

      session.subscribe(topic_command, onCommandMessage);
   };

   connection.onclose = function (reason, details) {
      // handle connection lost
   }

   connection.open();

});<|endoftext|>