<commit_before>// --------------------------------------------------------------------------------------------------------------------
//
// dynamodb.js - class for AWS DynamoDB
//
// Copyright (c) 2012 AppsAttic Ltd - http://www.appsattic.com/
// Written by Andrew Chilton <chilts@appsattic.com>
//
// License: http://opensource.org/licenses/MIT
//
// --------------------------------------------------------------------------------------------------------------------
// requires

// built-ins
var util = require('util');
var crypto = require('crypto');
var https = require('https');
var http = require('http');

// dependencies
var _ = require('underscore');
var dateFormat = require('dateformat');

// our own
var awssum = require('../awssum');
var amazon = awssum.load('amazon/amazon');
var stsService = awssum.load('amazon/sts');
var operations = require('./dynamodb-config');

// --------------------------------------------------------------------------------------------------------------------
// package variables

var MARK = 'dynamodb: ';

// From: http://docs.amazonwebservices.com/general/latest/gr/rande.html
var endPoint = {};
endPoint[amazon.US_EAST_1]      = "dynamodb.us-east-1.amazonaws.com";
endPoint[amazon.EU_WEST_1]      = "dynamodb.eu-west-1.amazonaws.com";
endPoint[amazon.AP_NORTHEAST_1] = "dynamodb.ap-northeast-1.amazonaws.com";
// no other endpoints exist (yet) for this service

var version = '20111205';

// --------------------------------------------------------------------------------------------------------------------
// constructor

var DynamoDB = function(accessKeyId, secretAccessKey, awsAccountId, region) {
    var self = this;

    // call the superclass for initialisation
    DynamoDB.super_.call(this, accessKeyId, secretAccessKey, awsAccountId, region);

    // check the region is valid
    if ( ! endPoint[region] ) {
        throw MARK + "invalid region '" + region + "'";
    }

    // create an STS client to use for getting the session tokens
    self._sts = new stsService(accessKeyId, secretAccessKey, awsAccountId, amazon.US_EAST_1);

    return self;
};

// inherit from Amazon
util.inherits(DynamoDB, amazon.Amazon);

// --------------------------------------------------------------------------------------------------------------------
// methods we need to implement from amazon.js

DynamoDB.prototype.method = function() {
    return 'POST';
}

DynamoDB.prototype.host = function(args) {
    return endPoint[this.region()];
};

DynamoDB.prototype.version = function() {
    return version;
};

DynamoDB.prototype.extractBody = function() {
    // DynamoDB always returns JSON
    return 'json';
};

// From: http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/HMACAuth.html
//
// Returns a strToSign for this request.
DynamoDB.prototype.strToSign = function(options, args) {
    var self = this;

    // firstly, get the following headers
    var headers = {};
    headers.host = self.host();
    if ( !_.isUndefined( options.headers['x-amz-security-token'] ) ) {
        headers['x-amz-security-token'] = options.headers['x-amz-security-token'];
    }
    headers['x-amz-target'] = options.headers['x-amz-target'];

    // create the canonicalizedHeaders
    var canonicalizedHeaders = '';
    var headerNames = _.keys(headers).sort();
    _.each(headerNames, function(hdrName, i) {
        canonicalizedHeaders += hdrName + ':' + headers[hdrName] + '\n';
    });

    var canonicalHeaders = headerNames.map(function(key) {
        return util.format("%s:%s\n", key.trim().toLowerCase(), headers[key].trim());
    }).sort().join('');

    // create the string we need to sign
    var strToSign = '';

    if ( false ) {
        strToSign += options.method + "\n";
        strToSign += "/\n";
        strToSign += "\n"; // querystring, but DynamoDB doesn't use them
        strToSign += canonicalizedHeaders + "\n";
        strToSign += options.body;

        console.log('===============================================================================');
        console.log('1) StrToSign :', strToSign + '(Ends)');
        console.log('===============================================================================');

        var strToSign = [options.method, '/', '', canonicalHeaders, options.body].join("\n");

        console.log('===============================================================================');
        console.log('2) StrToSign :', strToSign + '(Ends)');
        console.log('===============================================================================');

        // console.log('options :', options);
    }

    // From: https://forums.aws.amazon.com/thread.jspa?threadID=85891
    var strToSign = '';
    strToSign += options.method + "\n";
    strToSign += "/\n";
    strToSign += "\n";
    strToSign += 'host:' + headers.host + "\n";
    strToSign += 'x-amz-date:' + options.headers.Date + "\n";
    strToSign += 'x-amz-security-token:' + options.headers['x-amz-security-token'] + "\n";
    strToSign += 'x-amz-target:' + options.headers['x-amz-target'] + "\n";
    strToSign += "\n";
    strToSign += options.body;

    // console.log('===============================================================================');
    // console.log('3) StrToSign :', strToSign + '(Ends)');
    // console.log('===============================================================================');

    return strToSign;
};

// From: http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/HMACAuth.html
//
// Creates the signature for this request.
DynamoDB.prototype.signature = function(strToSign) {
    var self = this;

    // console.log('AccessKeyId = ' + self.accessKeyId());
    // console.log('SecretAccessKey = ' + self.secretAccessKey());
    // console.log('SessionToken = ' + self._sessionToken);

    // firstly, get the SHA256 has of the strToSign
    var sha256 = crypto.createHash("sha256")
    var hash = sha256.update(strToSign).digest();
    // console.log('*** HASH = ' + hash);

    // secondly, make the SHA256_HMAC of the hash from above
    var signature = crypto
        .createHmac('sha256', self.secretAccessKey())
        .update(hash)
        .digest('base64');

    return signature;
}

// From: http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/HMACAuth.html
//
// Adds the signature to the request.
DynamoDB.prototype.addSignature = function(options, signature) {
    var self = this;
    // console.log('addSignature(): signatureMethod = ' + self.signatureMethod());
    options.headers['x-amzn-authorization'] = 'AWS3 AWSAccessKeyId=' + self.accessKeyId()
        + ',Algorithm=' + self.signatureMethod()
        + ',SignedHeaders=host;x-amz-date;x-amz-security-token;x-amz-target'
        + ',Signature=' + signature;

    // console.log('Auth=' + options.headers['x-amzn-authorization']);
};

// From: http://docs.amazonwebservices.com/DynamoDB/latest/APIReference/Headers.html
//
// Adds the common headers to this request.
DynamoDB.prototype.addCommonOptions = function(options, args) {
    var self = this;

    // add in the target
    options.headers['x-amz-target'] = 'DynamoDB_' + self.version() + '.' + args.Target;

    // add the content-type
    options.headers['content-type'] = 'application/x-amz-json-1.0';

    // add the security token
    options.headers['x-amz-security-token'] = self._sessionToken;

    // add in the date
    var date = dateFormat(new Date(), "UTC:ddd, dd mmm yyyy HH:MM:ss Z");
    options.headers.Date = date;
    options.headers['x-amz-date'] = options.headers.Date;

    // make the strToSign, create the signature and sign it
    var strToSign = self.strToSign(options, args);
    var signature = self.signature(strToSign);
    self.addSignature(options, signature);
};

// --------------------------------------------------------------------------------------------------------------------
// operations on the service

_.each(operations, function(operation, operationName) {
    // firstly, make the operation function so we can call it
    var mainOperation = awssum.makeOperation(operation);

    // console.log('Making the operation for ' + operationName);

    var doRequest = function(args, callback) {
        var self = this;
        // console.log('doRequest(): we already have a session token, so call the mainOperation');
        // console.log('self:', self);
        // console.log('args:', args);
        // console.log('callback:', callback);

        // do the request but check the return to see if we need a new session token
        mainOperation.apply(self, [ args, function(err, data) {
            if ( err ) {
                if ( err.StatusCode === 400 ) {
                    // this error wasn't a session token problem, so pass it back to the callback
                    callback(err, null);
                    return;
                }

                self._sts.GetSessionToken(function(err, data) {
                    if ( err ) {
                        // just pass this error back
                        callback(err, null);
                        return;
                    }

                    // set the new access key id, secret access key and session token
                    var credentials = data.Body.GetSessionTokenResponse.GetSessionTokenResult.Credentials;
                    self.setAccessKeyId(credentials.AccessKeyId);
                    self.setSecretAccessKey(credentials.SecretAccessKey);
                    self._sessionToken = credentials.SessionToken;

                    // finally, do the operation again (no fallback this time)
                    mainOperation.apply(self, [args, callback]);
                });
                return;
            }

            // console.log('no error when calling the mainOperation, doing callback(null, data)');

            // no error, so just call the callback ok
            callback(null, data);
        }]);
    }

    // now create a function which calls the STS service and wraps the above mainOperation
    var wrapper = function(args, callback) {
        var self = this;

        // if args hasn't been given
        var self = this;
        if ( callback == null ) {
            callback = args;
            args = {};
        }
        args = args || {};

        // console.log('Called ' + operationName);
        // console.log('args:', args);
        // console.log('callback:', callback);

        // if we have a session token already, just do the request
        if ( !_.isUndefined(self._sessionToken) ) {
            // console.log('wrapper(): we already have a session token, just do the request');
            doRequest.apply(self, [args, callback]);
            return;
        }

        // console.log('No session token, calling sts.GetSessionToken() first');

        // no session token, get one first, then call the request
        self._sts.GetSessionToken(function(err, data) {
            if ( err ) {
                // console.log('GetSessionToken(): got an error');
                // just pass this error back
                callback(err, null);
                return;
            }

            // console.log('GetSessionToken(): got a session token');

            // set the new access key id, secret access key and session token
            var credentials = data.Body.GetSessionTokenResponse.GetSessionTokenResult.Credentials;
            // console.log('GetSessionToken() callback - credentials:', credentials);
            self.setAccessKeyId(credentials.AccessKeyId);
            self.setSecretAccessKey(credentials.SecretAccessKey);
            self._sessionToken = credentials.SessionToken;

            // do the request
            doRequest.apply(self, [args, callback]);
        });
    };

    DynamoDB.prototype[operationName] = wrapper;
});

// --------------------------------------------------------------------------------------------------------------------
// exports

module.exports = DynamoDB;

// --------------------------------------------------------------------------------------------------------------------
<commit_msg>Get a new token if it has less than a minute left to live<commit_after>// --------------------------------------------------------------------------------------------------------------------
//
// dynamodb.js - class for AWS DynamoDB
//
// Copyright (c) 2012 AppsAttic Ltd - http://www.appsattic.com/
// Written by Andrew Chilton <chilts@appsattic.com>
//
// License: http://opensource.org/licenses/MIT
//
// --------------------------------------------------------------------------------------------------------------------
// requires

// built-ins
var util = require('util');
var crypto = require('crypto');
var https = require('https');
var http = require('http');

// dependencies
var _ = require('underscore');
var dateFormat = require('dateformat');

// our own
var awssum = require('../awssum');
var amazon = awssum.load('amazon/amazon');
var stsService = awssum.load('amazon/sts');
var operations = require('./dynamodb-config');

// --------------------------------------------------------------------------------------------------------------------
// package variables

var MARK = 'dynamodb: ';

// From: http://docs.amazonwebservices.com/general/latest/gr/rande.html
var endPoint = {};
endPoint[amazon.US_EAST_1]      = "dynamodb.us-east-1.amazonaws.com";
endPoint[amazon.EU_WEST_1]      = "dynamodb.eu-west-1.amazonaws.com";
endPoint[amazon.AP_NORTHEAST_1] = "dynamodb.ap-northeast-1.amazonaws.com";
// no other endpoints exist (yet) for this service

var version = '20111205';

// --------------------------------------------------------------------------------------------------------------------
// constructor

var DynamoDB = function(accessKeyId, secretAccessKey, awsAccountId, region) {
    var self = this;

    // call the superclass for initialisation
    DynamoDB.super_.call(this, accessKeyId, secretAccessKey, awsAccountId, region);

    // check the region is valid
    if ( ! endPoint[region] ) {
        throw MARK + "invalid region '" + region + "'";
    }

    // create an STS client to use for getting the session tokens
    self._sts = new stsService(accessKeyId, secretAccessKey, awsAccountId, amazon.US_EAST_1);

    return self;
};

// inherit from Amazon
util.inherits(DynamoDB, amazon.Amazon);

// --------------------------------------------------------------------------------------------------------------------
// methods we need to implement from amazon.js

DynamoDB.prototype.method = function() {
    return 'POST';
}

DynamoDB.prototype.host = function(args) {
    return endPoint[this.region()];
};

DynamoDB.prototype.version = function() {
    return version;
};

DynamoDB.prototype.extractBody = function() {
    // DynamoDB always returns JSON
    return 'json';
};

// From: http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/HMACAuth.html
//
// Returns a strToSign for this request.
DynamoDB.prototype.strToSign = function(options, args) {
    var self = this;

    // firstly, get the following headers
    var headers = {};
    headers.host = self.host();
    if ( !_.isUndefined( options.headers['x-amz-security-token'] ) ) {
        headers['x-amz-security-token'] = options.headers['x-amz-security-token'];
    }
    headers['x-amz-target'] = options.headers['x-amz-target'];

    // create the canonicalizedHeaders
    var canonicalizedHeaders = '';
    var headerNames = _.keys(headers).sort();
    _.each(headerNames, function(hdrName, i) {
        canonicalizedHeaders += hdrName + ':' + headers[hdrName] + '\n';
    });

    var canonicalHeaders = headerNames.map(function(key) {
        return util.format("%s:%s\n", key.trim().toLowerCase(), headers[key].trim());
    }).sort().join('');

    // create the string we need to sign
    var strToSign = '';

    if ( false ) {
        strToSign += options.method + "\n";
        strToSign += "/\n";
        strToSign += "\n"; // querystring, but DynamoDB doesn't use them
        strToSign += canonicalizedHeaders + "\n";
        strToSign += options.body;

        console.log('===============================================================================');
        console.log('1) StrToSign :', strToSign + '(Ends)');
        console.log('===============================================================================');

        var strToSign = [options.method, '/', '', canonicalHeaders, options.body].join("\n");

        console.log('===============================================================================');
        console.log('2) StrToSign :', strToSign + '(Ends)');
        console.log('===============================================================================');

        // console.log('options :', options);
    }

    // From: https://forums.aws.amazon.com/thread.jspa?threadID=85891
    var strToSign = '';
    strToSign += options.method + "\n";
    strToSign += "/\n";
    strToSign += "\n";
    strToSign += 'host:' + headers.host + "\n";
    strToSign += 'x-amz-date:' + options.headers.Date + "\n";
    strToSign += 'x-amz-security-token:' + options.headers['x-amz-security-token'] + "\n";
    strToSign += 'x-amz-target:' + options.headers['x-amz-target'] + "\n";
    strToSign += "\n";
    strToSign += options.body;

    // console.log('===============================================================================');
    // console.log('3) StrToSign :', strToSign + '(Ends)');
    // console.log('===============================================================================');

    return strToSign;
};

// From: http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/HMACAuth.html
//
// Creates the signature for this request.
DynamoDB.prototype.signature = function(strToSign) {
    var self = this;

    // console.log('AccessKeyId = ' + self.accessKeyId());
    // console.log('SecretAccessKey = ' + self.secretAccessKey());
    // console.log('SessionToken = ' + self._sessionToken);
    // console.log('SessionTokenExpiration = ' + self._sessionTokenExpiration);

    // firstly, get the SHA256 has of the strToSign
    var sha256 = crypto.createHash("sha256")
    var hash = sha256.update(strToSign).digest();
    // console.log('*** HASH = ' + hash);

    // secondly, make the SHA256_HMAC of the hash from above
    var signature = crypto
        .createHmac('sha256', self.secretAccessKey())
        .update(hash)
        .digest('base64');

    return signature;
}

// From: http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/HMACAuth.html
//
// Adds the signature to the request.
DynamoDB.prototype.addSignature = function(options, signature) {
    var self = this;
    // console.log('addSignature(): signatureMethod = ' + self.signatureMethod());
    options.headers['x-amzn-authorization'] = 'AWS3 AWSAccessKeyId=' + self.accessKeyId()
        + ',Algorithm=' + self.signatureMethod()
        + ',SignedHeaders=host;x-amz-date;x-amz-security-token;x-amz-target'
        + ',Signature=' + signature;

    // console.log('Auth=' + options.headers['x-amzn-authorization']);
};

// From: http://docs.amazonwebservices.com/DynamoDB/latest/APIReference/Headers.html
//
// Adds the common headers to this request.
DynamoDB.prototype.addCommonOptions = function(options, args) {
    var self = this;

    // add in the target
    options.headers['x-amz-target'] = 'DynamoDB_' + self.version() + '.' + args.Target;

    // add the content-type
    options.headers['content-type'] = 'application/x-amz-json-1.0';

    // add the security token
    options.headers['x-amz-security-token'] = self._sessionToken;

    // add in the date
    var date = dateFormat(new Date(), "UTC:ddd, dd mmm yyyy HH:MM:ss Z");
    options.headers.Date = date;
    options.headers['x-amz-date'] = options.headers.Date;

    // make the strToSign, create the signature and sign it
    var strToSign = self.strToSign(options, args);
    var signature = self.signature(strToSign);
    self.addSignature(options, signature);
};

// --------------------------------------------------------------------------------------------------------------------
// operations on the service

_.each(operations, function(operation, operationName) {
    // firstly, make the operation function so we can call it
    var mainOperation = awssum.makeOperation(operation);

    // console.log('Making the operation for ' + operationName);

    var doRequest = function(args, callback) {
        var self = this;
        // console.log('doRequest(): we already have a session token, so call the mainOperation');
        // console.log('self:', self);
        // console.log('args:', args);
        // console.log('callback:', callback);

        // do the request but check the return to see if we need a new session token
        mainOperation.apply(self, [ args, function(err, data) {
            if ( err ) {
                if ( err.StatusCode === 400 ) {
                    // this error wasn't a session token problem, so pass it back to the callback
                    callback(err, null);
                    return;
                }

                self._sts.GetSessionToken(function(err, data) {
                    if ( err ) {
                        // just pass this error back
                        callback(err, null);
                        return;
                    }

                    // set the new access key id, secret access key and session token
                    var credentials = data.Body.GetSessionTokenResponse.GetSessionTokenResult.Credentials;
                    self.setAccessKeyId(credentials.AccessKeyId);
                    self.setSecretAccessKey(credentials.SecretAccessKey);
                    self._sessionToken = credentials.SessionToken;
                    self._sessionTokenExpiration = new Date(credentials.Expiration);

                    // console.log('expiration=' + self._sessionTokenExpiration.toISOString());

                    // finally, do the operation again (no fallback this time)
                    mainOperation.apply(self, [args, callback]);
                });
                return;
            }

            // console.log('no error when calling the mainOperation, doing callback(null, data)');

            // no error, so just call the callback ok
            callback(null, data);
        }]);
    }

    // now create a function which calls the STS service and wraps the above mainOperation
    var wrapper = function(args, callback) {
        var self = this;

        // if args hasn't been given
        var self = this;
        if ( callback == null ) {
            callback = args;
            args = {};
        }
        args = args || {};

        // console.log('Called ' + operationName);
        // console.log('args:', args);
        // console.log('callback:', callback);

        // if we have a session token already and it has more than a minute left, just do the request
        var currentDate = new Date();

        if ( !_.isUndefined(self._sessionToken) && self._sessionTokenExpiration.valueOf() < currentDate - 60 ) {
            // console.log('wrapper(): we already have a non-expired session token, so just do the request');
            doRequest.apply(self, [args, callback]);
            return;
        }

        // console.log('No session token, calling sts.GetSessionToken() first');

        // no session token, get one first, then call the request
        self._sts.GetSessionToken(function(err, data) {
            if ( err ) {
                // console.log('GetSessionToken(): got an error');
                // just pass this error back
                callback(err, null);
                return;
            }

            // set the new access key id, secret access key and session token
            var credentials = data.Body.GetSessionTokenResponse.GetSessionTokenResult.Credentials;
            // console.log('GetSessionToken() callback - credentials:', credentials);
            self.setAccessKeyId(credentials.AccessKeyId);
            self.setSecretAccessKey(credentials.SecretAccessKey);
            self._sessionToken = credentials.SessionToken;
            self._sessionTokenExpiration = new Date(credentials.Expiration);

            // console.log('expiration=' + self._sessionTokenExpiration.toISOString());

            // do the request
            doRequest.apply(self, [args, callback]);
        });
    };

    DynamoDB.prototype[operationName] = wrapper;
});

// --------------------------------------------------------------------------------------------------------------------
// exports

module.exports = DynamoDB;

// --------------------------------------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>/**
 * FoodCoopShop - The open source software for your foodcoop
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @since         FoodCoopShop 3.1.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 * @author        Mario Rothauer <office@foodcoopshop.com>
 * @copyright     Copyright (c) Mario Rothauer, https://www.rothauer-it.com
 * @link          https://www.foodcoopshop.com
 */
foodcoopshop.ModalInstantOrderAdd = {

    init : function(button) {

        var modalSelector = '#instant-order-add';

        foodcoopshop.Modal.appendModalToDom(
            modalSelector,
            '',
            foodcoopshop.ModalInstantOrderAdd.getHtml(),
            []
        );

        foodcoopshop.Modal.bindSuccessButton(modalSelector, function() {
            foodcoopshop.ModalInstantOrderAdd.getSuccessHandler(modalSelector);
        });

        $(modalSelector).on('hidden.bs.modal', function (e) {
            foodcoopshop.ModalInstantOrderAdd.getCloseHandler($(this));
        });

        $(button).on('click', function() {
            foodcoopshop.ModalInstantOrderAdd.getOpenHandler(button, modalSelector);
        });

    },

    getHtml : function() {
         return '';
    },

    getCloseHandler : function(modal) {
        modal.find('.modal-title').text('');
        modal.find('.modal-body').text('');
        foodcoopshop.Helper.ajaxCall(
            '/carts/ajaxDeleteInstantOrderCustomer',
            {},
            {
                onOk: function (data) {},
                onError: function (data) {}
            }
        );
    },

    getSuccessHandler : function(modalSelector) {
        //??
    },

    getOpenHandler : function(button, modalSelector) {

        $(modalSelector).modal();

        // START DROPDOWN
        var customerDropdownId = 'customerDropdown';
        var header = $('
' + foodcoopshop.LocalizedJs.admin.PlaceInstantOrderFor + ': <select id="' + customerDropdownId + '"><option value="0">' + foodcoopshop.LocalizedJs.admin.PleaseSelect + '</option></select>
');
        $(modalSelector + ' .modal-title').append(header);

        var customerDropdownSelector = '#' + customerDropdownId;

        $(customerDropdownSelector).selectpicker({
            liveSearch: true,
            size: 7,
            title: foodcoopshop.LocalizedJs.admin.PleaseSelectMember
        });

        // always preselect user if there is a dropdown called #customerId (for call from order detail)
        var customerId = $('#customerid').val();
        foodcoopshop.Admin.initCustomerDropdown(customerId, false, customerDropdownSelector, function () {
            var newSrc = foodcoopshop.Helper.cakeServerName + '/admin/order-details/initInstantOrder/' + $(customerDropdownSelector).val();
            $(modalSelector + ' iframe').attr('src', newSrc);
        });

        $(customerDropdownSelector).show();
        $(customerDropdownSelector).removeClass('hide');

        // START IFRAME
        var iframe = $('');
        iframe.attr('src', foodcoopshop.Helper.cakeServerName + '/admin/order-details/iframeStartPage');
        iframe.css('width', '100%');
        iframe.css('height', '100%');
        iframe.css('border', 'none');
        $(modalSelector + ' .modal-body').append(iframe);

        $(modalSelector + ' iframe').on('load', function () {
            // called after each url change in iframe!
            var currentUrl = $(this).get(0).contentWindow.document.URL;
            var cartFinishedRegExp = new RegExp(foodcoopshop.LocalizedJs.admin.routeCartFinished);
            if (currentUrl.match(cartFinishedRegExp)) {
                var message = $(this).contents().find('#flashMessage').html().replace(/<(a|i)[^>]*>/g,'');
                document.location.href = foodcoopshop.Admin.addParameterToURL(
                    foodcoopshop.Admin.getParentLocation(),
                    'message=' + encodeURIComponent(message)
                );
            }
        });

    }

};<commit_msg>remove unneeded handlers<commit_after>/**
 * FoodCoopShop - The open source software for your foodcoop
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @since         FoodCoopShop 3.1.0
 * @license       https://opensource.org/licenses/mit-license.php MIT License
 * @author        Mario Rothauer <office@foodcoopshop.com>
 * @copyright     Copyright (c) Mario Rothauer, https://www.rothauer-it.com
 * @link          https://www.foodcoopshop.com
 */
foodcoopshop.ModalInstantOrderAdd = {

    init : function(button) {

        var modalSelector = '#instant-order-add';

        foodcoopshop.Modal.appendModalToDom(
            modalSelector,
            '',
            '',
            []
        );

        $(button).on('click', function() {
            foodcoopshop.ModalInstantOrderAdd.getOpenHandler(button, modalSelector);
        });

    },

    getCloseHandler : function(modal) {
        modal.find('.modal-title').text('');
        modal.find('.modal-body').text('');
        foodcoopshop.Helper.ajaxCall(
            '/carts/ajaxDeleteInstantOrderCustomer',
            {},
            {
                onOk: function (data) {},
                onError: function (data) {}
            }
        );
    },

    getOpenHandler : function(button, modalSelector) {

        $(modalSelector).modal();

        // START DROPDOWN
        var customerDropdownId = 'customerDropdown';
        var header = $('
' + foodcoopshop.LocalizedJs.admin.PlaceInstantOrderFor + ': <select id="' + customerDropdownId + '"><option value="0">' + foodcoopshop.LocalizedJs.admin.PleaseSelect + '</option></select>
');
        $(modalSelector + ' .modal-title').append(header);

        var customerDropdownSelector = '#' + customerDropdownId;

        $(customerDropdownSelector).selectpicker({
            liveSearch: true,
            size: 7,
            title: foodcoopshop.LocalizedJs.admin.PleaseSelectMember
        });

        // always preselect user if there is a dropdown called #customerId (for call from order detail)
        var customerId = $('#customerid').val();
        foodcoopshop.Admin.initCustomerDropdown(customerId, false, customerDropdownSelector, function () {
            var newSrc = foodcoopshop.Helper.cakeServerName + '/admin/order-details/initInstantOrder/' + $(customerDropdownSelector).val();
            $(modalSelector + ' iframe').attr('src', newSrc);
        });

        $(customerDropdownSelector).show();
        $(customerDropdownSelector).removeClass('hide');

        // START IFRAME
        var iframe = $('');
        iframe.attr('src', foodcoopshop.Helper.cakeServerName + '/admin/order-details/iframeStartPage');
        iframe.css('width', '100%');
        iframe.css('height', '100%');
        iframe.css('border', 'none');
        $(modalSelector + ' .modal-body').append(iframe);

        $(modalSelector + ' iframe').on('load', function () {
            // called after each url change in iframe!
            var currentUrl = $(this).get(0).contentWindow.document.URL;
            var cartFinishedRegExp = new RegExp(foodcoopshop.LocalizedJs.admin.routeCartFinished);
            if (currentUrl.match(cartFinishedRegExp)) {
                var message = $(this).contents().find('#flashMessage').html().replace(/<(a|i)[^>]*>/g,'');
                document.location.href = foodcoopshop.Admin.addParameterToURL(
                    foodcoopshop.Admin.getParentLocation(),
                    'message=' + encodeURIComponent(message)
                );
            }
        });

    }

};<|endoftext|>


<commit_before>//Attachments.js: Client for the zendesk API.

var util        = require('util'),
    Client      = require('./client').Client,
    defaultgroups = require('./helpers').defaultgroups;

var Attachments = exports.Attachments = function (options) {
  Client.call(this, options);
};

// Inherit from Client base object
util.inherits(Attachments, Client);

// ====================================== Creating Attachments
Attachments.prototype.upload = function (file, fileToken, cb) { //TODO
  this.uppload(['uploads'], file, fileToken, cb);
};

<commit_msg>[fix] wrong name for refrencing function<commit_after>//Attachments.js: Client for the zendesk API.

var util        = require('util'),
    Client      = require('./client').Client,
    defaultgroups = require('./helpers').defaultgroups;

var Attachments = exports.Attachments = function (options) {
  Client.call(this, options);
};

// Inherit from Client base object
util.inherits(Attachments, Client);

// ====================================== Creating Attachments
Attachments.prototype.upload = function (file, fileToken, cb) { //TODO
  this.upload(['uploads'], file, fileToken, cb);
};

<|endoftext|>


<commit_before>/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var BADNUM = require('../../constants/numerical').BADNUM;

module.exports = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) {
    var colLen = trace._length;
    var col1 = ax1.makeCalcdata(trace, var1Name);
    var col2 = ax2.makeCalcdata(trace, var2Name);
    var textCol = trace.text;
    var hasColumnText = (textCol !== undefined && Lib.isArray1D(textCol));
    var hoverTextCol = trace.hovertext;
    var hasColumnHoverText = (hoverTextCol !== undefined && Lib.isArray1D(hoverTextCol));
    var i, j;

    var col1dv = Lib.distinctVals(col1);
    var col1vals = col1dv.vals;
    var col2dv = Lib.distinctVals(col2);
    var col2vals = col2dv.vals;
    var newArrays = [];
    var text;
    var hovertext;

    for(i = 0; i < arrayVarNames.length; i++) {
        newArrays[i] = Lib.init2dArray(col2vals.length, col1vals.length);
    }

    if(hasColumnText) {
        text = Lib.init2dArray(col2vals.length, col1vals.length);
    }
    if(hasColumnHoverText) {
        hovertext = Lib.init2dArray(col2vals.length, col1vals.length);
    }

    var after2before = Lib.init2dArray(col2vals.length, col1vals.length);

    for(i = 0; i < colLen; i++) {
        if(col1[i] !== BADNUM && col2[i] !== BADNUM) {
            var i1 = Lib.findBin(col1[i] + col1dv.minDiff / 2, col1vals);
            var i2 = Lib.findBin(col2[i] + col2dv.minDiff / 2, col2vals);

            for(j = 0; j < arrayVarNames.length; j++) {
                var arrayVarName = arrayVarNames[j];
                var arrayVar = trace[arrayVarName];
                var newArray = newArrays[j];
                newArray[i2][i1] = arrayVar[i];
                after2before[i2][i1] = i;
            }

            if(hasColumnText) text[i2][i1] = textCol[i];
            if(hasColumnHoverText) hovertext[i2][i1] = hoverTextCol[i];
        }
    }

    trace['_' + var1Name] = col1vals;
    trace['_' + var2Name] = col2vals;
    for(j = 0; j < arrayVarNames.length; j++) {
        trace['_' + arrayVarNames[j]] = newArrays[j];
    }
    if(hasColumnText) trace._text = text;
    if(hasColumnHoverText) trace._hovertext = hovertext;

    if(ax1 && ax1.type === 'category') {
        trace['_' + var1Name + 'CategoryMap'] = col1vals.map(function(v) { return ax1._categories[v];});
    }

    if(ax2 && ax2.type === 'category') {
        trace['_' + var2Name + 'CategoryMap'] = col2vals.map(function(v) { return ax2._categories[v];});
    }

    trace._after2before = after2before;
};
<commit_msg>refactor heatmap convertColumnData<commit_after>/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var BADNUM = require('../../constants/numerical').BADNUM;

module.exports = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) {
    var colLen = trace._length;
    var col1 = ax1.makeCalcdata(trace, var1Name);
    var col2 = ax2.makeCalcdata(trace, var2Name);
    var textCol = trace.text;
    var hasColumnText = (textCol !== undefined && Lib.isArray1D(textCol));
    var hoverTextCol = trace.hovertext;
    var hasColumnHoverText = (hoverTextCol !== undefined && Lib.isArray1D(hoverTextCol));
    var i, j;

    var col1dv = Lib.distinctVals(col1);
    var col1vals = col1dv.vals;
    var col2dv = Lib.distinctVals(col2);
    var col2vals = col2dv.vals;
    var newArrays = [];
    var text;
    var hovertext;

    var nI = col2vals.length;
    var nJ = col1vals.length;

    for(i = 0; i < arrayVarNames.length; i++) {
        newArrays[i] = Lib.init2dArray(nI, nJ);
    }

    if(hasColumnText) {
        text = Lib.init2dArray(nI, nJ);
    }
    if(hasColumnHoverText) {
        hovertext = Lib.init2dArray(nI, nJ);
    }

    var after2before = Lib.init2dArray(nI, nJ);

    for(i = 0; i < colLen; i++) {
        if(col1[i] !== BADNUM && col2[i] !== BADNUM) {
            var i1 = Lib.findBin(col1[i] + col1dv.minDiff / 2, col1vals);
            var i2 = Lib.findBin(col2[i] + col2dv.minDiff / 2, col2vals);

            for(j = 0; j < arrayVarNames.length; j++) {
                var arrayVarName = arrayVarNames[j];
                var arrayVar = trace[arrayVarName];
                var newArray = newArrays[j];
                newArray[i2][i1] = arrayVar[i];
                after2before[i2][i1] = i;
            }

            if(hasColumnText) text[i2][i1] = textCol[i];
            if(hasColumnHoverText) hovertext[i2][i1] = hoverTextCol[i];
        }
    }

    trace['_' + var1Name] = col1vals;
    trace['_' + var2Name] = col2vals;
    for(j = 0; j < arrayVarNames.length; j++) {
        trace['_' + arrayVarNames[j]] = newArrays[j];
    }
    if(hasColumnText) trace._text = text;
    if(hasColumnHoverText) trace._hovertext = hovertext;

    if(ax1 && ax1.type === 'category') {
        trace['_' + var1Name + 'CategoryMap'] = col1vals.map(function(v) { return ax1._categories[v];});
    }

    if(ax2 && ax2.type === 'category') {
        trace['_' + var2Name + 'CategoryMap'] = col2vals.map(function(v) { return ax2._categories[v];});
    }

    trace._after2before = after2before;
};
<|endoftext|>


<commit_before>/**
 * A JavaScript project for accessing the accelerometer and gyro from various devices
 *
 * @author Tom Gallacher <tom.gallacher23@gmail.com>
 * @copyright Tom Gallacher <http://www.tomg.co>
 * @version 0.0.1a
 * @license MIT License
 * @options frequency, callback
 */
(function (root, factory) {
		if (typeof define === 'function' && define.amd) {
				// AMD. Register as an anonymous module.
				define(factory);
		} else if (typeof exports === 'object') {
				// Node. Does not work with strict CommonJS, but
				// only CommonJS-like enviroments that support module.exports,
				// like Node.
				module.exports = factory();
		} else {
				// Browser globals (root is window)
				root.gyro = factory();
	}
}(this, function () {
	var measurements = {
				x: null,
				y: null,
				z: null,
				alpha: null,
				beta: null,
				gamma: null
			},
			calibration = {
				x: 0,
				y: 0,
				z: 0,
				alpha: 0,
				beta: 0,
				gamma: 0,
				rawAlpha: 0,
				rawBeta: 0,
				rawGamma: 0
			},
			interval = null,
			features = [];

	var gyro = {};

	/**
	 * @public
	 */
	gyro.frequency = 500; //ms

	gyro.calibrate = function() {
		for (var i in measurements) {
			calibration[i] = (typeof measurements[i] === 'number') ? measurements[i] : 0;
		}
	};

	gyro.getOrientation = function() {
		return measurements;
	};

	gyro.startTracking = function(callback) {
		interval = setInterval(function() {
			callback(measurements);
		}, gyro.frequency);
	};

	gyro.stopTracking = function() {
		clearInterval(interval);
	};

	/**
	 * Current available features are:
	 * MozOrientation
	 * devicemotion
	 * deviceorientation
	 */
	gyro.hasFeature = function(feature) {
		for (var i in features) {
			if (feature == features[i]) {
				return true;
			}
		}
		return false;
	};

	gyro.getFeatures = function() {
		return features;
	};

	/**
	 * @private
	 */
	function eulerToQuaternion(e) {
		var s = Math.PI / 180;
		var x = e.beta * s, y = e.gamma * s; z = e.alpha * s;
		var cX = Math.cos(x / 2);
		var cY = Math.cos(y / 2);
		var cZ = Math.cos(z / 2);
		var sX = Math.sin(x / 2);
		var sY = Math.sin(y / 2);
		var sZ = Math.sin(z / 2);
		var w = cX * cY * cZ - sX * sY * sZ;
		x = sX * cY * cZ - cX * sY * sZ;
		y = cX * sY * cZ + sX * cY * sZ;
		z = cX * cY * sZ + sX * sY * cZ;
		return {x:x, y:y, z:z, w:w};
	}
	gyro.eulerToQuaternion=eulerToQuaternion;

	/**
	 * @private
	 */
	function quaternionMultiply(a, b) {
		return {
			w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
			x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
			y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
			z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w
		};
	}

	/**
	 * @private
	 */
	function quaternionApply(v, a) {
		v = quaternionMultiply(a, {x:v.x,y:v.y,z:v.z,w:0});
		v = quaternionMultiply(v, {w:a.w, x:-a.x, y:-a.y, z:-a.z});
		return {x:v.x, y:v.y, z:v.z};
	}

	/**
	 * @private
	 */
	function vectorDot(a, b) {
		return a.x * b.x + a.y * b.y + a.z * b.z;
	}

	/**
	 * @private
	 */
	function quaternionToEuler(q) {
		var s = 180 / Math.PI;
		var front = quaternionApply({x:0,y:1,z:0}, q);
		// console.log(front);
		var alpha = (front.x == 0 && front.y == 0) ?
			0 : -Math.atan2(front.x, front.y);
		var beta = Math.atan2(front.z,Math.sqrt(front.x*front.x+front.y*front.y));
		var zgSide = {
			x: Math.cos(alpha),
			y: Math.sin(alpha),
			z: 0
		};
		var zgUp = {
			x: Math.sin(alpha) * Math.sin(beta),
			y: -Math.cos(alpha) * Math.sin(beta),
			z: Math.cos(beta)
		};
		var up = quaternionApply({x:0,y:0,z:1}, q);
		var gamma = Math.atan2(vectorDot(up, zgSide), vectorDot(up, zgUp));

		// wrap-around the value according to DeviceOrientation
		// Event Specification
		if (alpha < 0) alpha += 2 * Math.PI;
		if (gamma >= Math.PI * 0.5) {
			gamma -= Math.PI; alpha += Math.PI;
			if (beta > 0) beta = Math.PI - beta;
			else beta = -Math.PI - beta;
		} else if (gamma < Math.PI * -0.5) {
			gamma += Math.PI; alpha += Math.PI;
			if (beta > 0) beta = Math.PI - beta;
			else beta = -Math.PI - beta;
		}
		if (alpha >= 2 * Math.PI) alpha -= 2 * Math.PI;
		return {alpha: alpha * s, beta: beta * s, gamma: gamma * s};
	}

	/**
	 * @private
	 */
	// it doesn't make sense to depend on a "window" module
	// since deviceorientation & devicemotion make just sense in the browser
	// so old school test used.
	if (window && window.addEventListener) {
		function setupListeners() {
			function MozOrientationInitListener (e) {
				features.push('MozOrientation');
				e.target.removeEventListener('MozOrientation', MozOrientationInitListener, true);

				e.target.addEventListener('MozOrientation', function(e) {
					measurements.x = e.x - calibration.x;
					measurements.y = e.y - calibration.y;
					measurements.z = e.z - calibration.z;
				}, true);
			}
			function deviceMotionListener (e) {
				features.push('devicemotion');
				e.target.removeEventListener('devicemotion', deviceMotionListener, true);

				e.target.addEventListener('devicemotion', function(e) {
					// console.log(e);
					measurements.x = e.acceleration.x - calibration.x;
					measurements.y = e.acceleration.y - calibration.y;
					measurements.z = e.acceleration.z - calibration.z;
				}, true);
			}
			function deviceOrientationListener (e) {
				features.push('deviceorientation');
				e.target.removeEventListener('deviceorientation', deviceOrientationListener, true);

				e.target.addEventListener('deviceorientation', function(e) {
					var calib = eulerToQuaternion({
						alpha: calibration.rawAlpha,
						beta: calibration.rawBeta,
						gamma: calibration.rawGamma
					});
					calib.x *= -1; calib.y *= -1; calib.z *= -1;

					var raw = eulerToQuaternion({
						alpha: e.alpha, beta: e.beta, gamma: e.gamma
					});
					var calibrated = quaternionMultiply(calib, raw);
					var calibEuler = quaternionToEuler(calibrated);

					measurements.alpha = calibEuler.alpha;
					measurements.beta = calibEuler.beta;
					measurements.gamma = calibEuler.gamma;

					measurements.rawAlpha = e.alpha;
					measurements.rawBeta = e.beta;
					measurements.rawGamma = e.gamma;
				}, true);
			}

			window.addEventListener('MozOrientation', MozOrientationInitListener, true);
			window.addEventListener('devicemotion', deviceMotionListener, true);
			window.addEventListener('deviceorientation', deviceOrientationListener, true);
		}
		setupListeners();
	}

	return gyro;
}));
<commit_msg>added original code back as comments for reference<commit_after>/**
 * A JavaScript project for accessing the accelerometer and gyro from various devices
 *
 * @author Tom Gallacher <tom.gallacher23@gmail.com>
 * @copyright Tom Gallacher <http://www.tomg.co>
 * @version 0.0.1a
 * @license MIT License
 * @options frequency, callback
 */
(function (root, factory) {
		if (typeof define === 'function' && define.amd) {
				// AMD. Register as an anonymous module.
				define(factory);
		} else if (typeof exports === 'object') {
				// Node. Does not work with strict CommonJS, but
				// only CommonJS-like enviroments that support module.exports,
				// like Node.
				module.exports = factory();
		} else {
				// Browser globals (root is window)
				root.gyro = factory();
	}
}(this, function () {
	var measurements = {
				x: null,
				y: null,
				z: null,
				alpha: null,
				beta: null,
				gamma: null,
				alphaR: null,
				betaR: null,
				gammaR: null
			},
			calibration = {
				x: 0,
				y: 0,
				z: 0,
				alpha: 0,
				beta: 0,
				gamma: 0,
				rawAlpha: 0,
				rawBeta: 0,
				rawGamma: 0
			},
			interval = null,
			features = [];

	var gyro = {};

	/**
	 * @public
	 */
	gyro.frequency = 500; //ms

	gyro.calibrate = function() {
		for (var i in measurements) {
			calibration[i] = (typeof measurements[i] === 'number') ? measurements[i] : 0;
		}
	};

	gyro.getOrientation = function() {
		return measurements;
	};

	gyro.startTracking = function(callback) {
		interval = setInterval(function() {
			callback(measurements);
		}, gyro.frequency);
	};

	gyro.stopTracking = function() {
		clearInterval(interval);
	};

	/**
	 * Current available features are:
	 * MozOrientation
	 * devicemotion
	 * deviceorientation
	 */
	gyro.hasFeature = function(feature) {
		for (var i in features) {
			if (feature == features[i]) {
				return true;
			}
		}
		return false;
	};

	gyro.getFeatures = function() {
		return features;
	};

	/**
	 * @private
	 */
	function eulerToQuaternion(e) {
		var s = Math.PI / 180;
		var x = e.beta * s, y = e.gamma * s; z = e.alpha * s;
		var cX = Math.cos(x / 2);
		var cY = Math.cos(y / 2);
		var cZ = Math.cos(z / 2);
		var sX = Math.sin(x / 2);
		var sY = Math.sin(y / 2);
		var sZ = Math.sin(z / 2);
		var w = cX * cY * cZ - sX * sY * sZ;
		x = sX * cY * cZ - cX * sY * sZ;
		y = cX * sY * cZ + sX * cY * sZ;
		z = cX * cY * sZ + sX * sY * cZ;
		return {x:x, y:y, z:z, w:w};
	}
	gyro.eulerToQuaternion=eulerToQuaternion;

	/**
	 * @private
	 */
	function quaternionMultiply(a, b) {
		return {
			w: a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z,
			x: a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y,
			y: a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x,
			z: a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w
		};
	}

	/**
	 * @private
	 */
	function quaternionApply(v, a) {
		v = quaternionMultiply(a, {x:v.x,y:v.y,z:v.z,w:0});
		v = quaternionMultiply(v, {w:a.w, x:-a.x, y:-a.y, z:-a.z});
		return {x:v.x, y:v.y, z:v.z};
	}

	/**
	 * @private
	 */
	function vectorDot(a, b) {
		return a.x * b.x + a.y * b.y + a.z * b.z;
	}

	/**
	 * @private
	 */
	function quaternionToEuler(q) {
		var s = 180 / Math.PI;
		var front = quaternionApply({x:0,y:1,z:0}, q);
		// console.log(front);
		var alpha = (front.x == 0 && front.y == 0) ?
			0 : -Math.atan2(front.x, front.y);
		var beta = Math.atan2(front.z,Math.sqrt(front.x*front.x+front.y*front.y));
		var zgSide = {
			x: Math.cos(alpha),
			y: Math.sin(alpha),
			z: 0
		};
		var zgUp = {
			x: Math.sin(alpha) * Math.sin(beta),
			y: -Math.cos(alpha) * Math.sin(beta),
			z: Math.cos(beta)
		};
		var up = quaternionApply({x:0,y:0,z:1}, q);
		var gamma = Math.atan2(vectorDot(up, zgSide), vectorDot(up, zgUp));

		// wrap-around the value according to DeviceOrientation
		// Event Specification
		if (alpha < 0) alpha += 2 * Math.PI;
		if (gamma >= Math.PI * 0.5) {
			gamma -= Math.PI; alpha += Math.PI;
			if (beta > 0) beta = Math.PI - beta;
			else beta = -Math.PI - beta;
		} else if (gamma < Math.PI * -0.5) {
			gamma += Math.PI; alpha += Math.PI;
			if (beta > 0) beta = Math.PI - beta;
			else beta = -Math.PI - beta;
		}
		if (alpha >= 2 * Math.PI) alpha -= 2 * Math.PI;
		return {alpha: alpha * s, beta: beta * s, gamma: gamma * s};
	}

	/**
	 * @private
	 */
	// it doesn't make sense to depend on a "window" module
	// since deviceorientation & devicemotion make just sense in the browser
	// so old school test used.
	if (window && window.addEventListener) {
		function setupListeners() {
			function MozOrientationInitListener (e) {
				features.push('MozOrientation');
				e.target.removeEventListener('MozOrientation', MozOrientationInitListener, true);

				e.target.addEventListener('MozOrientation', function(e) {
					measurements.x = e.x - calibration.x;
					measurements.y = e.y - calibration.y;
					measurements.z = e.z - calibration.z;
				}, true);
			}
			function deviceMotionListener (e) {
				features.push('devicemotion');
				e.target.removeEventListener('devicemotion', deviceMotionListener, true);

				e.target.addEventListener('devicemotion', function(e) {
					// console.log(e);
					// measurements.x = e.accelerationIncludingGravity.x - calibration.x;
					// measurements.y = e.accelerationIncludingGravity.y - calibration.y;
					// measurements.z = e.accelerationIncludingGravity.z - calibration.z;
					measurements.x = e.acceleration.x - calibration.x;
					measurements.y = e.acceleration.y - calibration.y;
					measurements.z = e.acceleration.z - calibration.z;
				}, true);
			}
			function deviceOrientationListener (e) {
				features.push('deviceorientation');
				e.target.removeEventListener('deviceorientation', deviceOrientationListener, true);

				e.target.addEventListener('deviceorientation', function(e) {
					var calib = eulerToQuaternion({
						alpha: calibration.rawAlpha,
						beta: calibration.rawBeta,
						gamma: calibration.rawGamma
					});
					calib.x *= -1; calib.y *= -1; calib.z *= -1;

					var raw = eulerToQuaternion({
						alpha: e.alpha, beta: e.beta, gamma: e.gamma
					});
					var calibrated = quaternionMultiply(calib, raw);
					var calibEuler = quaternionToEuler(calibrated);

					measurements.alpha = calibEuler.alpha;
					measurements.beta = calibEuler.beta;
					measurements.gamma = calibEuler.gamma;

					measurements.rawAlpha = e.alpha;
					measurements.rawBeta = e.beta;
					measurements.rawGamma = e.gamma;
				}, true);
			}

			window.addEventListener('MozOrientation', MozOrientationInitListener, true);
			window.addEventListener('devicemotion', deviceMotionListener, true);
			window.addEventListener('deviceorientation', deviceOrientationListener, true);
		}
		setupListeners();
	}

	return gyro;
}));
<|endoftext|>


<commit_before>'use strict'

function ElementFocuser() {
	let currentlySelectedElement

	//
	// Public API
	//

	// Set focus on the selected landmark element.
	//
	// This function requires an actual DOM element, as returned by various
	// functions of the LandmarksFinder.
	//
	// Note: this should only be called if landmarks were found. The check
	//       for this is done in the main content script, as it involves UI
	//       activity, and couples finding and focusing.
	this.focusElement = function(element) {
		browser.storage.sync.get({
			borderType: 'momentary'
		}, function(items) {
			removeBorderOnCurrentlySelectedElement()

			const borderTypePref = items.borderType

			// Ensure that the element is focusable
			const originalTabindex = element.getAttribute('tabindex')
			if (originalTabindex === null || originalTabindex === '0') {
				element.setAttribute('tabindex', '-1')
			}

			element.focus()

			// Add the border and set a timer to remove it (if required by user)
			if (borderTypePref === 'persistent' || borderTypePref === 'momentary') {
				addBorder(element)

				if (borderTypePref === 'momentary') {
					setTimeout(function() {
						removeBorder(element)
					}, 2000)
				}
			}

			// Restore tabindex value
			if (originalTabindex === null) {
				element.removeAttribute('tabindex')
			} else if (originalTabindex === '0') {
				element.setAttribute('tabindex', '0')
			}

			currentlySelectedElement = element
		})
	}

	function removeBorderOnCurrentlySelectedElement() {
		if (currentlySelectedElement) {
			removeBorder(currentlySelectedElement)
		}
	}

	// Also needs to be available publicly
	this.removeBorderOnCurrentlySelectedElement =
		removeBorderOnCurrentlySelectedElement

	//
	// Private API
	//

	function addBorder(element) {
		element.style.outline = 'medium solid red'
		element.style.outlineOffset = '-3px'
	}

	function removeBorder(element) {
		element.style.outline = null
	}
}
<commit_msg>Tweak outline style for greater visibility<commit_after>'use strict'

function ElementFocuser() {
	let currentlySelectedElement

	//
	// Public API
	//

	// Set focus on the selected landmark element.
	//
	// This function requires an actual DOM element, as returned by various
	// functions of the LandmarksFinder.
	//
	// Note: this should only be called if landmarks were found. The check
	//       for this is done in the main content script, as it involves UI
	//       activity, and couples finding and focusing.
	this.focusElement = function(element) {
		browser.storage.sync.get({
			borderType: 'momentary'
		}, function(items) {
			removeBorderOnCurrentlySelectedElement()

			const borderTypePref = items.borderType

			// Ensure that the element is focusable
			const originalTabindex = element.getAttribute('tabindex')
			if (originalTabindex === null || originalTabindex === '0') {
				element.setAttribute('tabindex', '-1')
			}

			element.focus()

			// Add the border and set a timer to remove it (if required by user)
			if (borderTypePref === 'persistent' || borderTypePref === 'momentary') {
				addBorder(element)

				if (borderTypePref === 'momentary') {
					setTimeout(function() {
						removeBorder(element)
					}, 2000)
				}
			}

			// Restore tabindex value
			if (originalTabindex === null) {
				element.removeAttribute('tabindex')
			} else if (originalTabindex === '0') {
				element.setAttribute('tabindex', '0')
			}

			currentlySelectedElement = element
		})
	}

	function removeBorderOnCurrentlySelectedElement() {
		if (currentlySelectedElement) {
			removeBorder(currentlySelectedElement)
		}
	}

	// Also needs to be available publicly
	this.removeBorderOnCurrentlySelectedElement =
		removeBorderOnCurrentlySelectedElement

	//
	// Private API
	//

	function addBorder(element) {
		element.style.outline = '5px solid red'
		element.style.outlineOffset = '-3px'
	}

	function removeBorder(element) {
		element.style.outline = null
	}
}
<|endoftext|>


<commit_before>var config = require('../config');
var request = require('request');
var fs = require('fs');

var telegramAPI = {};

telegramAPI.setupWebhook = function(token, url, callback){
  var requestUrl = config.TELEGRAM_BASE_URL + token + config.TELEGRAM_SETUP_WEBHOOK.replace(":url", url);
  request(requestUrl, {}, function (err, res, body) {
    if (err) {
      return callback(err);
    } else if (res.statusCode == 200) {
      return callback(null);
    } else {
      return callback(new Error("Unable to setup webhook. Code " + res.statusCode));
    }
  });
};

telegramAPI.postMessage = function(token, chatId, message, callback) {
  var requestUrl = config.TELEGRAM_BASE_URL + token + config.TELEGRAM_POST_MESSAGE;
  var formData = {
    chat_id: chatId,
    text: message
  };
  request.post({url:requestUrl, formData: formData}, function(err, res, body) {
    if (err) {
      return callback(err);
    } else if (res.statusCode == 200) {
      return callback(null, res, body);
    } else {
      return callback(new Error("Unable to post message. Code " + res.statusCode));
    }
  });
};

telegramAPI.postImage = function(token, imagePath, chatId, callback) {
  fs.access(imagePath, fs.F_OK, function(err) {
    if (err) {
      callback(err);
    } else {
      var requestUrl = config.TELEGRAM_BASE_URL + token + config.TELEGRAM_POST_IMAGE;
      var formData = {
        chat_id: chatId,
        photo: fs.createReadStream(imagePath)
      };
      request.post({url:requestUrl, formData: formData}, function(err, res, body) {
        fs.unlink(imagePath, function(error) {
          if (error)
            return callback(error);
        });
        if (err) {
          return callback(err);
        } else if (res.statusCode == 200) {
          return callback(null, res, body);
        } else {
          return callback(new Error("Unable to post image. Code " + res.statusCode));
        }
      });
    }
  });
};

telegramAPI.postDocument = function(token, documentPath, chatId, callback) {
  fs.access(documentPath, fs.F_OK, function(err) {
    if (err) {
      callback(err);
    } else {
      var requestUrl = config.TELEGRAM_BASE_URL + token + config.TELEGRAM_POST_DOCUMENT;
      var formData = {
        chat_id: chatId,
        document: fs.createReadStream(documentPath)
      };
      request.post({url:requestUrl, formData: formData}, function(err, res, body) {
        fs.unlink(documentPath, function(error) {
          if (error)
            throw error;
        });
        if (err) {
          return callback(err);
        } else if (res.statusCode == 200) {
          return callback(null, res, body);
        } else {
          return callback(new Error("Unable to post document. Code " + res.statusCode));
        }
      });
    }
  });
};

telegramAPI.answerQueryWithMedia = function(token, queryId, mediaURLs, callback) {
  var requestUrl = config.TELEGRAM_BASE_URL + token + config.TELEGRAM_ANSWER_QUERY;
  var results = mediaURLs.map(function(url) {
    var fileExtension = url.split('.').pop();
    var fileName = url.split('/').pop().split('.')[0];
    var thumbnailUrl = url.replace('.' + fileExtension, 's.jpg');
    var result = {};
    switch (fileExtension) {
      // case 'webm':
      // result.type = 'video';
      // result.mime_type = 'video/mp4';
      // result.video_url = url;
      // result.caption = fileName;
      // break;
      case 'gif':
      result.type = 'gif';
      result.gif_url = url;
      break;
      case 'jpeg':
      result.type = 'photo';
      result.photo_url = url;
      break;
      default:
      result.type = 'article';
      result.url = url;
      result.input_message_content = {message_text: url};
    }
    // Common properties
    result.id = fileName;
    result.title = fileName;
    result.thumb_url = thumbnailUrl;
    return result;
  });
  request.post(requestUrl, {form:{inline_query_id:queryId, cache_time:10, results: JSON.stringify(results)}}, function(err, res, body) {
    if (err) {
      return callback(err);
    } else if (res.statusCode == 200) {
      return callback(null, res, body);
    } else {
      return callback(new Error(body.error_code));
    }
  });
};

module.exports = telegramAPI;
<commit_msg>Forward error to callback to avoid crashing.<commit_after>var config = require('../config');
var request = require('request');
var fs = require('fs');

var telegramAPI = {};

telegramAPI.setupWebhook = function(token, url, callback){
  var requestUrl = config.TELEGRAM_BASE_URL + token + config.TELEGRAM_SETUP_WEBHOOK.replace(":url", url);
  request(requestUrl, {}, function (err, res, body) {
    if (err) {
      return callback(err);
    } else if (res.statusCode == 200) {
      return callback(null);
    } else {
      return callback(new Error("Unable to setup webhook. Code " + res.statusCode));
    }
  });
};

telegramAPI.postMessage = function(token, chatId, message, callback) {
  var requestUrl = config.TELEGRAM_BASE_URL + token + config.TELEGRAM_POST_MESSAGE;
  var formData = {
    chat_id: chatId,
    text: message
  };
  request.post({url:requestUrl, formData: formData}, function(err, res, body) {
    if (err) {
      return callback(err);
    } else if (res.statusCode == 200) {
      return callback(null, res, body);
    } else {
      return callback(new Error("Unable to post message. Code " + res.statusCode));
    }
  });
};

telegramAPI.postImage = function(token, imagePath, chatId, callback) {
  fs.access(imagePath, fs.F_OK, function(err) {
    if (err) {
      callback(err);
    } else {
      var requestUrl = config.TELEGRAM_BASE_URL + token + config.TELEGRAM_POST_IMAGE;
      var formData = {
        chat_id: chatId,
        photo: fs.createReadStream(imagePath)
      };
      request.post({url:requestUrl, formData: formData}, function(err, res, body) {
        fs.unlink(imagePath, function(error) {
          if (error)
            return callback(error);
        });
        if (err) {
          return callback(err);
        } else if (res.statusCode == 200) {
          return callback(null, res, body);
        } else {
          return callback(new Error("Unable to post image. Code " + res.statusCode));
        }
      });
    }
  });
};

telegramAPI.postDocument = function(token, documentPath, chatId, callback) {
  fs.access(documentPath, fs.F_OK, function(err) {
    if (err) {
      callback(err);
    } else {
      var requestUrl = config.TELEGRAM_BASE_URL + token + config.TELEGRAM_POST_DOCUMENT;
      var formData = {
        chat_id: chatId,
        document: fs.createReadStream(documentPath)
      };
      request.post({url:requestUrl, formData: formData}, function(err, res, body) {
        fs.unlink(documentPath, function(error) {
          if (error)
            return callback(error);
        });
        if (err) {
          return callback(err);
        } else if (res.statusCode == 200) {
          return callback(null, res, body);
        } else {
          return callback(new Error("Unable to post document. Code " + res.statusCode));
        }
      });
    }
  });
};

telegramAPI.answerQueryWithMedia = function(token, queryId, mediaURLs, callback) {
  var requestUrl = config.TELEGRAM_BASE_URL + token + config.TELEGRAM_ANSWER_QUERY;
  var results = mediaURLs.map(function(url) {
    var fileExtension = url.split('.').pop();
    var fileName = url.split('/').pop().split('.')[0];
    var thumbnailUrl = url.replace('.' + fileExtension, 's.jpg');
    var result = {};
    switch (fileExtension) {
      // case 'webm':
      // result.type = 'video';
      // result.mime_type = 'video/mp4';
      // result.video_url = url;
      // result.caption = fileName;
      // break;
      case 'gif':
      result.type = 'gif';
      result.gif_url = url;
      break;
      case 'jpeg':
      result.type = 'photo';
      result.photo_url = url;
      break;
      default:
      result.type = 'article';
      result.url = url;
      result.input_message_content = {message_text: url};
    }
    // Common properties
    result.id = fileName;
    result.title = fileName;
    result.thumb_url = thumbnailUrl;
    return result;
  });
  request.post(requestUrl, {form:{inline_query_id:queryId, cache_time:10, results: JSON.stringify(results)}}, function(err, res, body) {
    if (err) {
      return callback(err);
    } else if (res.statusCode == 200) {
      return callback(null, res, body);
    } else {
      return callback(new Error(body.error_code));
    }
  });
};

module.exports = telegramAPI;
<|endoftext|>


<commit_before>(function(){
  angular.module('ftFloater', [])
    .directive('floater', ['$parse', function($parse) {
      return {
        link: function(scope, el, attrs) {
          var options = $parse(attrs.floater)() || {};

          if(options.stopElement) {
            options.stopElement = $(options.stopElement);
          }

          $(el).floater(options).on('floatStart', function() {
            scope.$apply(attrs.floatStart);
          })
          .on('floatStop', function() {
            scope.$apply(attrs.floatStop);
          });
        }
      };
    }]);
}());<commit_msg>got float-begin and float-end directives working<commit_after>(function(){
  angular.module('ftFloater', [])
    .directive('floater', ['$parse', function($parse) {
      return {
        scope: {
          floatStart: '&floatBegin',
          floatStop: '&floatEnd'
        },
        link: function(scope, el, attrs) {
          var options = $parse(attrs.floater)() || {};

          if(options.stopElement) {
            options.stopElement = $(options.stopElement);
          }

          $(el)
            .floater(options)
            .on('floatStart', function() {
              scope.$apply(function() {
                scope.floatStart();
              });
            })
            .on('floatStop', function() {
              scope.$apply(function() {
                scope.floatStop();
              });
            });
        }
      };
    }]);
}());
<|endoftext|>


<commit_before>'use strict';

const Events = require('events');
const colors = require('ansi-colors');
const keypress = require('./keypress');
const timer = require('./timer');
const State = require('./state');
const theme = require('./theme');
const utils = require('./utils');
const ansi = require('./ansi');

/**
 * Base class for creating a new Prompt.
 * @param {Object} `options` Question object.
 */

class Prompt extends Events {
  constructor(options = {}) {
    super();
    this.name = options.name;
    this.type = options.type;
    this.options = options;
    theme(this);
    timer(this);
    this.state = new State(this);
    this.option('format');
    this.option('validate', () => true);
    this.option('result', val => val);
    this.option('stdout', process.stdout);
    this.option('stdin', process.stdin);
    this.option('initial');
    this.option('scale', 1);
    this.setMaxListeners(0);
  }

  async keypress(ch, event = {}) {
    let key = this.state.keypress = keypress.action(ch, keypress(ch, event));
    this.emit('keypress', ch, { ...key });
    let fn = this.options[key.action] || this[key.action] || this.dispatch;
    if (typeof fn === 'function') {
      return fn.call(this, ch, { ...key });
    }
    this.alert();
  }

  alert() {
    if (this.options.show === false) {
      this.emit('alert');
    } else {
      this.stdout.write(ansi.code.beep);
    }
  }

  cursorHide() {
    this.stdout.write(ansi.cursor.hide());
    utils.onExit(() => this.cursorShow());
  }

  cursorShow() {
    this.stdout.write(ansi.cursor.show());
  }

  write(str) {
    if (!str) return;
    if (this.stdout && this.state.show !== false) {
      this.stdout.write(str);
    }
    this.state.buffer += str;
  }

  clear(lines = 0) {
    let buffer = this.state.buffer;
    this.state.buffer = '';
    if ((!buffer && !lines) || this.options.show === false) return;
    this.stdout.write(ansi.cursor.down(lines) + ansi.clear(buffer));
  }

  restore() {
    if (this.state.closed || this.options.show === false) return;

    let { prompt, after, rest } = this.sections();
    let { cursor, initial = '', input = '', value = '' } = this;

    let size = this.state.size = rest.length;
    let state = { after, cursor, initial, input, prompt, size, value };
    let codes = ansi.cursor.restore(state);
    if (codes) {
      this.stdout.write(codes);
    }
  }

  sections() {
    let { buffer, input, prompt } = this.state;
    prompt = colors.unstyle(prompt);
    let buf = colors.unstyle(buffer);
    let idx = buf.indexOf(prompt);
    let header = buf.slice(0, idx);
    let rest = buf.slice(idx);
    let lines = rest.split('\n');
    let first = lines[0];
    let last = lines[lines.length - 1];
    let promptLine = prompt + (input ? ' ' + input : '');
    let len = promptLine.length;
    let after = len < first.length ? first.slice(len + 1) : '';
    return { header, prompt: first, after, rest: lines.slice(1), last };
  }

  async submit() {
    this.state.submitted = true;
    this.value = this.result(this.value);

    let valid = await this.validate(this.value);
    if (valid !== true) {
      this.state.submitted = false;
      this.state.error = '\n' + this.styles.danger(this.symbols.pointer + ' ' + valid.trim());
      this.render();
      return this.alert();
    }

    await this.render();
    await this.close();
    this.emit('submit', this.value);
  }

  async cancel() {
    this.state.cancelled = this.state.submitted = true;
    await this.render();
    await this.close();
    this.emit('cancel', await this.error());
  }

  async close() {
    this.state.closed = true;

    try {
      let sections = this.sections();
      let lines = Math.ceil(sections.prompt.length / this.width);
      if (sections.rest) {
        this.write(ansi.cursor.down(sections.rest.length));
      }
      this.write('\n'.repeat(lines));
    } catch (err) { /* do nothing */ }

    this.emit('close');
  }

  start() {
    if (this.stop || this.options.show === false) return;
    this.stop = keypress.listen(this.stdin, this.keypress.bind(this));
    this.on('close', this.stop);
  }

  async initialize() {
    await this.start();
    await this.render();
  }

  render() {
    throw new Error('expected prompt to have a custom render method');
  }

  run() {
    return new Promise(async(resolve, reject) => {
      this.once('cancel', reject);
      this.once('submit', resolve);
      await this.initialize();
      this.emit('run');
    });
  }

  async element(name, choice, i) {
    let timer = this.timers && this.timers[name];
    let state = this.state;
    state.timer = timer;
    let value = this.options[name] || state[name] || this.symbols[name];
    let item = choice && choice[name] ? choice[name] : value;
    let res = await utils.resolve(state, item, state, choice, i);
    if (!res && choice && choice[name]) {
      return utils.resolve(state, value, state, choice, i);
    }
    return res;
  }

  async prefix() {
    let element = await this.element('prefix') || this.symbols;
    let timer = this.timers && this.timers.prefix;
    let state = this.state;
    state.timer = timer;
    if (utils.isObject(element)) element = element[state.status] || element.pending;
    if (!utils.hasColor(element)) {
      let style = this.styles[state.status] || this.styles.pending;
      return style(element);
    }
    return element;
  }

  async message() {
    let message = await this.element('message');
    if (!utils.hasColor(message)) {
      return this.styles.strong(message);
    }
    return message;
  }

  async separator() {
    let element = await this.element('separator') || this.symbols;
    let timer = this.timers && this.timers.separator;
    let state = this.state;
    state.timer = timer;
    let value = element[state.status] || element.pending || state.separator;
    let ele = await utils.resolve(state, value, state);
    if (utils.isObject(ele)) ele = ele[state.status] || ele.pending;
    if (!utils.hasColor(ele)) {
      return this.styles.muted(ele);
    }
    return ele;
  }

  async pointer(choice, i) {
    let val = await this.element('pointer', choice, i);

    if (typeof val === 'string' && utils.hasColor(val)) {
      return val;
    }

    if (val) {
      let styles = this.styles;
      let enabled = this.index === i;
      let style = enabled ? styles.primary : val => val;
      let ele = await this.resolve(val[enabled ? 'on' : 'off'] || val, this.state);
      let styled = !utils.hasColor(ele) ? style(ele) : ele;
      return enabled ? styled : ' '.repeat(ele.length);
    }
  }

  async indicator(choice, i) {
    let val = await this.element('indicator', choice, i);

    if (typeof val === 'string' && utils.hasColor(val)) {
      return val;
    }

    if (val) {
      let styles = this.styles;
      let enabled = choice.enabled === true;
      let style = enabled ? styles.success : styles.dark;
      let ele = val[enabled ? 'on' : 'off'] || val;
      return !utils.hasColor(ele) ? style(ele) : ele;
    }
  }

  async footer() {
    if (this.state.status === 'pending') {
      return this.element('footer');
    }
  }

  async header() {
    if (this.state.status === 'pending') {
      return this.element('header');
    }
  }

  async hint() {
    if (this.state.status === 'pending' && !this.isValue(this.state.input)) {
      let hint = await this.element('hint');
      if (!utils.hasColor(hint)) {
        return this.styles.muted(hint);
      }
      return hint;
    }
  }

  error() {
    return !this.state.submitted ? this.state.error : '';
  }

  format(value) {
    return value;
  }

  isValue(value) {
    return !!value;
  }

  resolve(value, ...args) {
    return utils.resolve(this, value, ...args);
  }

  option(key, fallback) {
    let value = [this.options[key], this[key], fallback].find(v => v != null);
    if (typeof value === 'function') value = value.bind(this);
    this[key] = value;
    return this;
  }

  defaults(options = {}) {
    for (let key of Object.keys(options)) {
      if (this.options[key] == null) {
        this.state[key] = options[key];
      }
    }
  }

  get width() {
    return this.options.columns || utils.width(this.stdout, 80);
  }

  set cursor(value) {
    this.state.cursor = value;
  }
  get cursor() {
    return this.state.cursor;
  }

  set input(value) {
    this.state.input = value;
  }
  get input() {
    return this.state.input;
  }

  set value(value) {
    this.state.value = value;
  }
  get value() {
    return [this.state.value, this.input, this.initial].find(this.isValue.bind(this));
  }

  static get prompt() {
    return options => new this(options).run();
  }
}

module.exports = Prompt;
<commit_msg>emit state instead of keypress<commit_after>'use strict';

const Events = require('events');
const colors = require('ansi-colors');
const keypress = require('./keypress');
const timer = require('./timer');
const State = require('./state');
const theme = require('./theme');
const utils = require('./utils');
const ansi = require('./ansi');

/**
 * Base class for creating a new Prompt.
 * @param {Object} `options` Question object.
 */

class Prompt extends Events {
  constructor(options = {}) {
    super();
    this.name = options.name;
    this.type = options.type;
    this.options = options;
    theme(this);
    timer(this);
    this.state = new State(this);
    this.option('format');
    this.option('validate', () => true);
    this.option('result', val => val);
    this.option('stdout', process.stdout);
    this.option('stdin', process.stdin);
    this.option('initial');
    this.option('scale', 1);
    this.setMaxListeners(0);
  }

  async keypress(ch, event = {}) {
    let key = keypress.action(ch, keypress(ch, event), this.actions);
    this.state.keypress = key;
    this.emit('state', this.state.clone());
    let fn = this.options[key.action] || this[key.action] || this.dispatch;
    if (typeof fn === 'function') {
      return fn.call(this, ch, key);
    }
    this.alert();
  }

  alert() {
    if (this.options.show === false) {
      this.emit('alert');
    } else {
      this.stdout.write(ansi.code.beep);
    }
  }

  cursorHide() {
    this.stdout.write(ansi.cursor.hide());
    utils.onExit(() => this.cursorShow());
  }

  cursorShow() {
    this.stdout.write(ansi.cursor.show());
  }

  write(str) {
    if (!str) return;
    if (this.stdout && this.state.show !== false) {
      this.stdout.write(str);
    }
    this.state.buffer += str;
  }

  clear(lines = 0) {
    let buffer = this.state.buffer;
    this.state.buffer = '';
    if ((!buffer && !lines) || this.options.show === false) return;
    this.stdout.write(ansi.cursor.down(lines) + ansi.clear(buffer));
  }

  restore() {
    if (this.state.closed || this.options.show === false) return;

    let { prompt, after, rest } = this.sections();
    let { cursor, initial = '', input = '', value = '' } = this;

    let size = this.state.size = rest.length;
    let state = { after, cursor, initial, input, prompt, size, value };
    let codes = ansi.cursor.restore(state);
    if (codes) {
      this.stdout.write(codes);
    }
  }

  sections() {
    let { buffer, input, prompt } = this.state;
    prompt = colors.unstyle(prompt);
    let buf = colors.unstyle(buffer);
    let idx = buf.indexOf(prompt);
    let header = buf.slice(0, idx);
    let rest = buf.slice(idx);
    let lines = rest.split('\n');
    let first = lines[0];
    let last = lines[lines.length - 1];
    let promptLine = prompt + (input ? ' ' + input : '');
    let len = promptLine.length;
    let after = len < first.length ? first.slice(len + 1) : '';
    return { header, prompt: first, after, rest: lines.slice(1), last };
  }

  async submit() {
    this.state.submitted = true;
    this.value = this.result(this.value);

    let valid = await this.validate(this.value);
    if (valid !== true) {
      this.state.submitted = false;
      this.state.error = '\n' + this.styles.danger(this.symbols.pointer + ' ' + valid.trim());
      this.render();
      return this.alert();
    }

    await this.render();
    await this.close();
    this.emit('submit', this.value);
  }

  async cancel() {
    this.state.cancelled = this.state.submitted = true;
    await this.render();
    await this.close();
    this.emit('cancel', await this.error());
  }

  async close() {
    this.state.closed = true;

    try {
      let sections = this.sections();
      let lines = Math.ceil(sections.prompt.length / this.width);
      if (sections.rest) {
        this.write(ansi.cursor.down(sections.rest.length));
      }
      this.write('\n'.repeat(lines));
    } catch (err) { /* do nothing */ }

    this.emit('close');
  }

  start() {
    if (this.stop || this.options.show === false) return;
    this.stop = keypress.listen(this.stdin, this.keypress.bind(this));
    this.on('close', this.stop);
  }

  async initialize() {
    await this.start();
    await this.render();
  }

  render() {
    throw new Error('expected prompt to have a custom render method');
  }

  run() {
    return new Promise(async(resolve, reject) => {
      this.once('cancel', reject);
      this.once('submit', resolve);
      await this.initialize();
      this.emit('run');
    });
  }

  async element(name, choice, i) {
    let timer = this.timers && this.timers[name];
    let state = this.state;
    state.timer = timer;
    let value = this.options[name] || state[name] || this.symbols[name];
    let item = choice && choice[name] ? choice[name] : value;
    let res = await utils.resolve(state, item, state, choice, i);
    if (!res && choice && choice[name]) {
      return utils.resolve(state, value, state, choice, i);
    }
    return res;
  }

  async prefix() {
    let element = await this.element('prefix') || this.symbols;
    let timer = this.timers && this.timers.prefix;
    let state = this.state;
    state.timer = timer;
    if (utils.isObject(element)) element = element[state.status] || element.pending;
    if (!utils.hasColor(element)) {
      let style = this.styles[state.status] || this.styles.pending;
      return style(element);
    }
    return element;
  }

  async message() {
    let message = await this.element('message');
    if (!utils.hasColor(message)) {
      return this.styles.strong(message);
    }
    return message;
  }

  async separator() {
    let element = await this.element('separator') || this.symbols;
    let timer = this.timers && this.timers.separator;
    let state = this.state;
    state.timer = timer;
    let value = element[state.status] || element.pending || state.separator;
    let ele = await utils.resolve(state, value, state);
    if (utils.isObject(ele)) ele = ele[state.status] || ele.pending;
    if (!utils.hasColor(ele)) {
      return this.styles.muted(ele);
    }
    return ele;
  }

  async pointer(choice, i) {
    let val = await this.element('pointer', choice, i);

    if (typeof val === 'string' && utils.hasColor(val)) {
      return val;
    }

    if (val) {
      let styles = this.styles;
      let enabled = this.index === i;
      let style = enabled ? styles.primary : val => val;
      let ele = await this.resolve(val[enabled ? 'on' : 'off'] || val, this.state);
      let styled = !utils.hasColor(ele) ? style(ele) : ele;
      return enabled ? styled : ' '.repeat(ele.length);
    }
  }

  async indicator(choice, i) {
    let val = await this.element('indicator', choice, i);

    if (typeof val === 'string' && utils.hasColor(val)) {
      return val;
    }

    if (val) {
      let styles = this.styles;
      let enabled = choice.enabled === true;
      let style = enabled ? styles.success : styles.dark;
      let ele = val[enabled ? 'on' : 'off'] || val;
      return !utils.hasColor(ele) ? style(ele) : ele;
    }
  }

  async footer() {
    if (this.state.status === 'pending') {
      return this.element('footer');
    }
  }

  async header() {
    if (this.state.status === 'pending') {
      return this.element('header');
    }
  }

  async hint() {
    if (this.state.status === 'pending' && !this.isValue(this.state.input)) {
      let hint = await this.element('hint');
      if (!utils.hasColor(hint)) {
        return this.styles.muted(hint);
      }
      return hint;
    }
  }

  error() {
    return !this.state.submitted ? this.state.error : '';
  }

  format(value) {
    return value;
  }

  isValue(value) {
    return !!value;
  }

  resolve(value, ...args) {
    return utils.resolve(this, value, ...args);
  }

  option(key, fallback) {
    let value = [this.options[key], this[key], fallback].find(v => v != null);
    if (typeof value === 'function') value = value.bind(this);
    this[key] = value;
    return this;
  }

  defaults(options = {}) {
    for (let key of Object.keys(options)) {
      if (this.options[key] == null) {
        this.state[key] = options[key];
      }
    }
  }

  get width() {
    return this.options.columns || utils.width(this.stdout, 80);
  }

  set cursor(value) {
    this.state.cursor = value;
  }
  get cursor() {
    return this.state.cursor;
  }

  set input(value) {
    this.state.input = value;
  }
  get input() {
    return this.state.input;
  }

  set value(value) {
    this.state.value = value;
  }
  get value() {
    return [this.state.value, this.input, this.initial].find(this.isValue.bind(this));
  }

  static get prompt() {
    return options => new this(options).run();
  }
}

module.exports = Prompt;
<|endoftext|>


<commit_before>(function(env){
    'use strict';

    env.ddg_spice_dns = function(api_result) {

        var records = DDG.getProperty(api_result, 'response.records');
        if (!records.length) {
            return Spice.failed('dns');
        }

        api_result.response.records.sort(function(a, b) {
            if (a.type < b.type)
              return -1
            if (a.type > b.type)
              return 1
            return parseInt(a.priority) - parseInt(b.priority);
        });

        Spice.add({
            id: 'dns',
            name: api_result.query.domain,
            data: api_result.response,
            meta: {
                sourceUrl: 'http://www.viewdns.info/dnsrecord/?domain=' + api_result.query.domain,
                sourceName: 'ViewDNS'
            },
            templates: {
                group: 'base',
                options: {
                    content: Spice.dns.content,
                    moreAt: true
                }
            }
        });
    };
})(this);
<commit_msg>DNS: Change name value to "Answer". Add error checking of api_result.<commit_after>(function(env){
    'use strict';

    env.ddg_spice_dns = function(api_result) {

        if (!api_result || !DDG.getProperty(api_result, 'response.records').length) {
            return Spice.failed('dns');
        }

        api_result.response.records.sort(function(a, b) {
            if (a.type < b.type)
              return -1
            if (a.type > b.type)
              return 1
            return parseInt(a.priority) - parseInt(b.priority);
        });

        Spice.add({
            id: 'dns',
            name: "Answer",
            data: api_result.response,
            meta: {
                sourceUrl: 'http://www.viewdns.info/dnsrecord/?domain=' + api_result.query.domain,
                sourceName: 'ViewDNS'
            },
            templates: {
                group: 'base',
                options: {
                    content: Spice.dns.content,
                    moreAt: true
                }
            }
        });
    };
})(this);
<|endoftext|>