<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var sprintf = require('util').format;
var restify = require('restify');
var errors = require('./errors');
var _ = require('underscore');
var getRequestHeaders = require('./get-request-headers');
var Promise = require('promise');

module.exports = {
    create: create,
    list: list,
    get: get,
    update: update,
    action: action,
    del: del,
    updateTags: updateTags,
    updateCustomerMetadata: updateCustomerMetadata,
    groupedByCustomer: groupedByCustomer
};

function create(req, res, next) {
    req.body.creator_uuid = req.session.data.user;
    req.body.origin = 'adminui';

    req.log.info(req.body, 'VMAPI Create Request');
    req.sdc[req.dc].vmapi.createVm(
        req.body,
        {headers: getRequestHeaders(req) },
        function (err, obj) {

        if (err) {
            return next(err);
        }

        res.send(obj);
        return next();
    });
}

var IPV4_REGEX =
    (/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/);

function list(req, res, next) {
    if (req.query.ip) {
        var ip = req.query.ip;
        if (false === IPV4_REGEX.test(ip)) {
            return next(
                new errors.InvalidParameterError('Invalid IP Address', [ {
                    field: 'ip',
                    code: 'invalid',
                    message: sprintf('IP address %s is not a valid IPv4 Address', ip)
                } ]));
        }
        return listVmsWithIP(ip);
    } else {
        return listVms();
    }

    function listVmsWithIP(ipAddr) {
        req.sdc[req.dc].napi.searchIPs(
            ipAddr,
            {},
            {headers: getRequestHeaders(req) },
            function (err, ips)
        {
            req.log.info(ips);
            var matches = _.where(ips, {
                belongs_to_type: 'zone',
                ip: ip
            });
            if (matches.length === 0) {
                res.send([]);
                return next();
            }
            var uuids = _.pluck(matches, 'belongs_to_uuid');
            var filter = uuids.map(function (u) {
                return sprintf('(uuid=%s)', u);
            });
            if (filter.length > 1) {
                filter = sprintf('(|%s)', filter);
            }

            req.log.debug('Listing VMs with IP addresses', {query: filter});

            req.sdc[req.dc].vmapi.listVms(
                {query: filter},
                {headers: getRequestHeaders(req) },
                function (lerr, vms) {
                if (lerr) {
                    return next(err);
                } else {
                    res.send(vms);
                    return next();
                }
            });
            return null;
        });
    }

    function listVms() {
        var params = req.params;
        var perPage = req.params.perPage || 1000;
        var page = req.params.page || 1;

        var query = [];

        if (params.uuid && params.uuid.length) {
            query.push(sprintf('(uuid=%s)', params.uuid));
        }

        if (params.server_uuid && params.server_uuid.length) {
            query.push(sprintf('(server_uuid=%s)', params.server_uuid));
            delete params.server_uuid;
        }

        if (params.alias && params.alias.length) {
            query.push(sprintf('(alias=*%s*)', params.alias));
            delete params.alias;
        }

        if (params.state && params.state.length) {
            if (params.state === 'active') {
                query.push(sprintf('(|(state=running)(state=stopped))'));
            } else {
                query.push(sprintf('(state=%s)', params.state));
            }
            delete params.state;
        }

        if (params.owner_uuid && params.owner_uuid.length) {
            query.push(sprintf('(owner_uuid=%s)', params.owner_uuid));
            delete params.owner_uuid;
        }

        if (params.billing_id && params.billing_id.length) {
            query.push(sprintf('(billing_id=%s)', params.billing_id));
            delete params.billing_id;
        }

        if (params.image_uuid && params.image_uuid.length) {
            query.push(sprintf('(image_uuid=%s)', params.image_uuid));
            delete params.image_uuid;
        }

        if (params.provisioned_from && params.provisioned_from.toString().match(/\d+/)) {
            query.push(sprintf('(create_timestamp>=%s)', params.provisioned_from));
            delete params.provisioned_from;
        }

        if (params.provisioned_to && params.provisioned_to.toString().match(/\d+/)) {
            query.push(sprintf('(create_timestamp<=%s)', params.provisioned_to));
            delete params.provisioned_to;
        }

        if (query.length) {
            params.query = '(&' + query.join('') + ')';
        }

        delete req.params.perPage;
        delete req.params.page;

        params.limit = perPage;
        params.offset = (page-1) * perPage;

        req.log.info(params, 'Listing VMS');
        req.sdc[req.dc].vmapi.listVms(
            params,
            {headers: getRequestHeaders(req) },
            function listMachinesCb(err, vms, _req, _res)
        {
            if (err) {
                req.log.error(err, 'Error retrieving Virtual Machines');
                return next(err);
            }
            var total = _res.headers['x-joyent-resource-count'];
            res.setHeader('x-object-count', total);
            vms = vms.map(function (vm) {
                delete vm.customer_metadata;
                delete vm.internal_metadata;
                return vm;
            });

            res.send(vms);
            return next();
        });
    }
}

function get(req, res, next) {
    req.sdc[req.dc].vmapi.getVm(
        {uuid: req.params.uuid},
        {headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            return next(err);
        }
        res.send(obj);
        return next();
    });
}

function del(req, res, next) {
    var params = {
        creator_uuid: req.session.data.user,
        origin: 'adminui',
        uuid: req.params.uuid
    };

    req.log.info(params, 'VMAPI Delete Request');

    req.sdc[req.dc].vmapi.deleteVm(
        params,
        {headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            return next(err);
        }

        res.send(obj);
        return next();
    });
}

function update(req, res, next) {
    var params = {};
    params.uuid = req.params.uuid;
    params.payload = req.body;

    if (req.body.firewall_enabled === 'true') {
        params.payload.firewall_enabled = true;
    } else if (req.body.firewall_enabled === 'false') {
        params.payload.firewall_enabled = false;
    }

    if (req.body.tags) {
        params.payload.tags = req.body.tags;
    }

    if (typeof (req.body.alias) === 'string')  {
        params.payload.alias = req.body.alias;
    }

    params.creator_uuid = req.session.data.user;
    params.origin = 'adminui';

    req.log.info(params, 'vm update request');

    req.sdc[req.dc].vmapi.updateVm(
        params,
        { headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            return next(err);
        }

        res.send(obj);
        return next();
    });
}

function updateTags(req, res, next) {
    var params = {};
    params.uuid = req.params.uuid;
    params.metadata = req.body;

    req.sdc[req.dc].vmapi.setMetadata(
        'tags',
        params,
        { headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            req.log.fatal(err);
            return next(err);
        }
        res.send(obj);
        return next();
    });
}

function updateCustomerMetadata(req, res, next) {
    var params = {};
    params.uuid = req.params.uuid;
    params.metadata = req.body;

    req.sdc[req.dc].vmapi.setMetadata(
        'customer_metadata',
        params,
        {headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            return next(err);
        }
        res.send(obj);
        return next();
    });
}

function updateNics(req, res, next) {
    var path = sprintf('/vms/%s?action=update_nics', req.params.uuid);
    req.sdc[req.dc].vmapi.post(
        {path: path, headers: getRequestHeaders(req) },
        { nics: req.body.nics },
        function (err, updateNicsRes) {
            if (err) {
                req.log.fatal('Error updating nics', {
                    error: err,
                    uuid: req.params.uuid,
                    nics: req.body.nics
                });
                return next(err);
            }

            return res.send(updateNicsRes);
        });
}

function action(req, res, next) {
    var actions = {
        start: req.sdc[req.dc].vmapi.startVm,
        stop: req.sdc[req.dc].vmapi.stopVm,
        reboot: req.sdc[req.dc].vmapi.rebootVm,
        create_snapshot: req.sdc[req.dc].vmapi.snapshotVm,
        rollback_snapshot: req.sdc[req.dc].vmapi.rollbackVm,
        add_nics: req.sdc[req.dc].vmapi.addNics,
        update_nics: req.sdc[req.dc].vmapi.updateNics,
        remove_nics: req.sdc[req.dc].vmapi.removeNics,
        reprovision: req.sdc[req.dc].vmapi.reprovisionVm,
        update: req.sdc[req.dc].vmapi.updateVm
    };

    if (req.query.action === 'update_nics') {
        return updateNics(req, res, next);
    }

    var fn = actions[req.params.action];
    var body;

    if (typeof (fn) === 'undefined') {
        return next(new restify.InvalidArgument('invalid action specified'));
    }
    if (req.params.action === 'update') {
        return update(req, res, next);
    }

    body = req.body || {};
    body.creator_uuid = req.session.data.user;
    body.origin = 'adminui';
    body.uuid = req.params.uuid;
    req.log.info(body, 'VMAPI Request ' + req.params.action);

    fn.call(
        req.sdc[req.dc].vmapi,
        body,
        {headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            return next(err);
        }
        res.send(obj);
        return next();
    });

    return null;
}

function groupedByCustomer(req, res, next) {
    var params = req.query;
    var _customers = {};
    var _vms;

    function _listVms() {
        return new Promise(function (resolve, reject) {
            req.sdc[req.dc].vmapi.listVms(params, function (err, vms) {
                _vms = vms.map(function (vm) {
                    delete vm.customer_metadata;
                    delete vm.internal_metadata;
                    return vm;
                });
                resolve(vms);
            });
        });
    }

    function _fetchOwners() {
        var allOwners = _.pluck(_vms, 'owner_uuid');
        var owners = _.uniq(allOwners);

        var getUserCalls = owners.map(function (uuid) {
            return new Promise(function (resolve, reject) {
                req.ufds.getUser(uuid, function (err, owner) {
                    if (err) {
                        req.log.fatal(err, 'error retrieving owner for vms summary', owner);
                        return next(err);
                    }

                    [
                        'controls',
                        'memberof',
                        'dn',
                        'pwdchangedtime',
                        'pwdendtime',
                        'registered_developer',
                        'approved_for_provisioning',
                        'memberof',
                        'objectclass'
                    ].forEach(function (k) {
                        delete owner[k];
                    });
                    owner.created_at = new Date(Number(owner.created_at));
                    owner.updated_at = new Date(Number(owner.updated_at));
                    _customers[uuid] = owner;
                    resolve(owner);
                    return null;
                });
            });
        });

        return Promise.all(getUserCalls);
    }

    function _mergeData() {
        var values = [];
        var vmsGroupedByCustomerUuid = _.groupBy(_vms, function (vm) {
            return vm.owner_uuid;
        });

        for (var customerUuid in _customers) {
            var row = _customers[customerUuid];
            row.vms = vmsGroupedByCustomerUuid[customerUuid];
            values.push(row);
        }
        return values;
    }

    _listVms().then(_fetchOwners).then(_mergeData).then(function (data) {
        res.send(data);
    });
}
<commit_msg>ADMINUI-2203 Search Virtual Machine works incorrectly when using 'IP ADDRESS' parameter<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var sprintf = require('util').format;
var restify = require('restify');
var errors = require('./errors');
var _ = require('underscore');
var getRequestHeaders = require('./get-request-headers');
var Promise = require('promise');

module.exports = {
    create: create,
    list: list,
    get: get,
    update: update,
    action: action,
    del: del,
    updateTags: updateTags,
    updateCustomerMetadata: updateCustomerMetadata,
    groupedByCustomer: groupedByCustomer
};

function create(req, res, next) {
    req.body.creator_uuid = req.session.data.user;
    req.body.origin = 'adminui';

    req.log.info(req.body, 'VMAPI Create Request');
    req.sdc[req.dc].vmapi.createVm(
        req.body,
        {headers: getRequestHeaders(req) },
        function (err, obj) {

        if (err) {
            return next(err);
        }

        res.send(obj);
        return next();
    });
}

var IPV4_REGEX =
    (/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/);

function list(req, res, next) {
    var params = req.params;
    var ip = params.ip;
    if (ip) {
        if (false === IPV4_REGEX.test(ip)) {
            return next(
                new errors.InvalidParameterError('Invalid IP Address', [ {
                    field: 'ip',
                    code: 'invalid',
                    message: sprintf('IP address %s is not a valid IPv4 Address', ip)
                } ]));
        }
        return listVmsWithIP(ip);
    } else {
        return listVms();
    }

    function listVmsWithIP(ipAddr) {
        req.sdc[req.dc].napi.searchIPs(
            ipAddr,
            {},
            {headers: getRequestHeaders(req) },
            function (err, ips)
        {
            req.log.info(ips);
            var matches = _.where(ips, {
                belongs_to_type: 'zone',
                ip: ip
            });
            if (matches.length === 0) {
                res.send([]);
                return next();
            }
            var uuids = _.pluck(matches, 'belongs_to_uuid');

            if (params.uuid) {
                var isUuidPresent = uuids.some(function (uuid) {
                    return uuid === params.uuid;
                });
                if (isUuidPresent && uuids.length === 1) {
                    delete params.uuid;
                } else {
                    res.send([]);
                    return next();
                }
            }

            var filter = uuids.map(function (uuid) {
                return sprintf('(uuid=%s)', uuid);
            });

            var query = filter.length > 1 ? [sprintf('(|%s)', filter)] : filter;
            req.log.debug('Listing VMs with IP addresses', {query: filter});

            params.query = query;
            delete params.ip;
            return listVms();
        });
    }

    function listVms() {
        var perPage = req.params.perPage || 1000;
        var page = req.params.page || 1;
        var query = params.query || [];

        if (params.uuid && params.uuid.length) {
            query.push(sprintf('(uuid=%s)', params.uuid));
        }

        if (params.server_uuid && params.server_uuid.length) {
            query.push(sprintf('(server_uuid=%s)', params.server_uuid));
            delete params.server_uuid;
        }

        if (params.alias && params.alias.length) {
            query.push(sprintf('(alias=*%s*)', params.alias));
            delete params.alias;
        }

        if (params.state && params.state.length) {
            if (params.state === 'active') {
                query.push(sprintf('(|(state=running)(state=stopped))'));
            } else {
                query.push(sprintf('(state=%s)', params.state));
            }
            delete params.state;
        }

        if (params.owner_uuid && params.owner_uuid.length) {
            query.push(sprintf('(owner_uuid=%s)', params.owner_uuid));
            delete params.owner_uuid;
        }

        if (params.billing_id && params.billing_id.length) {
            query.push(sprintf('(billing_id=%s)', params.billing_id));
            delete params.billing_id;
        }

        if (params.image_uuid && params.image_uuid.length) {
            query.push(sprintf('(image_uuid=%s)', params.image_uuid));
            delete params.image_uuid;
        }

        if (params.provisioned_from && params.provisioned_from.toString().match(/\d+/)) {
            query.push(sprintf('(create_timestamp>=%s)', params.provisioned_from));
            delete params.provisioned_from;
        }

        if (params.provisioned_to && params.provisioned_to.toString().match(/\d+/)) {
            query.push(sprintf('(create_timestamp<=%s)', params.provisioned_to));
            delete params.provisioned_to;
        }

        if (query.length) {
            params.query = '(&' + query.join('') + ')';
        }

        delete req.params.perPage;
        delete req.params.page;

        params.limit = perPage;
        params.offset = (page-1) * perPage;

        req.log.info(params, 'Listing VMS');
        req.sdc[req.dc].vmapi.listVms(
            params,
            {headers: getRequestHeaders(req) },
            function listMachinesCb(err, vms, _req, _res)
        {
            if (err) {
                req.log.error(err, 'Error retrieving Virtual Machines');
                return next(err);
            }
            var total = _res.headers['x-joyent-resource-count'];
            res.setHeader('x-object-count', total);
            vms = vms.map(function (vm) {
                delete vm.customer_metadata;
                delete vm.internal_metadata;
                return vm;
            });

            res.send(vms);
            return next();
        });
    }
}

function get(req, res, next) {
    req.sdc[req.dc].vmapi.getVm(
        {uuid: req.params.uuid},
        {headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            return next(err);
        }
        res.send(obj);
        return next();
    });
}

function del(req, res, next) {
    var params = {
        creator_uuid: req.session.data.user,
        origin: 'adminui',
        uuid: req.params.uuid
    };

    req.log.info(params, 'VMAPI Delete Request');

    req.sdc[req.dc].vmapi.deleteVm(
        params,
        {headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            return next(err);
        }

        res.send(obj);
        return next();
    });
}

function update(req, res, next) {
    var params = {};
    params.uuid = req.params.uuid;
    params.payload = req.body;

    if (req.body.firewall_enabled === 'true') {
        params.payload.firewall_enabled = true;
    } else if (req.body.firewall_enabled === 'false') {
        params.payload.firewall_enabled = false;
    }

    if (req.body.tags) {
        params.payload.tags = req.body.tags;
    }

    if (typeof (req.body.alias) === 'string')  {
        params.payload.alias = req.body.alias;
    }

    params.creator_uuid = req.session.data.user;
    params.origin = 'adminui';

    req.log.info(params, 'vm update request');

    req.sdc[req.dc].vmapi.updateVm(
        params,
        { headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            return next(err);
        }

        res.send(obj);
        return next();
    });
}

function updateTags(req, res, next) {
    var params = {};
    params.uuid = req.params.uuid;
    params.metadata = req.body;

    req.sdc[req.dc].vmapi.setMetadata(
        'tags',
        params,
        { headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            req.log.fatal(err);
            return next(err);
        }
        res.send(obj);
        return next();
    });
}

function updateCustomerMetadata(req, res, next) {
    var params = {};
    params.uuid = req.params.uuid;
    params.metadata = req.body;

    req.sdc[req.dc].vmapi.setMetadata(
        'customer_metadata',
        params,
        {headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            return next(err);
        }
        res.send(obj);
        return next();
    });
}

function updateNics(req, res, next) {
    var path = sprintf('/vms/%s?action=update_nics', req.params.uuid);
    req.sdc[req.dc].vmapi.post(
        {path: path, headers: getRequestHeaders(req) },
        { nics: req.body.nics },
        function (err, updateNicsRes) {
            if (err) {
                req.log.fatal('Error updating nics', {
                    error: err,
                    uuid: req.params.uuid,
                    nics: req.body.nics
                });
                return next(err);
            }

            return res.send(updateNicsRes);
        });
}

function action(req, res, next) {
    var actions = {
        start: req.sdc[req.dc].vmapi.startVm,
        stop: req.sdc[req.dc].vmapi.stopVm,
        reboot: req.sdc[req.dc].vmapi.rebootVm,
        create_snapshot: req.sdc[req.dc].vmapi.snapshotVm,
        rollback_snapshot: req.sdc[req.dc].vmapi.rollbackVm,
        add_nics: req.sdc[req.dc].vmapi.addNics,
        update_nics: req.sdc[req.dc].vmapi.updateNics,
        remove_nics: req.sdc[req.dc].vmapi.removeNics,
        reprovision: req.sdc[req.dc].vmapi.reprovisionVm,
        update: req.sdc[req.dc].vmapi.updateVm
    };

    if (req.query.action === 'update_nics') {
        return updateNics(req, res, next);
    }

    var fn = actions[req.params.action];
    var body;

    if (typeof (fn) === 'undefined') {
        return next(new restify.InvalidArgument('invalid action specified'));
    }
    if (req.params.action === 'update') {
        return update(req, res, next);
    }

    body = req.body || {};
    body.creator_uuid = req.session.data.user;
    body.origin = 'adminui';
    body.uuid = req.params.uuid;
    req.log.info(body, 'VMAPI Request ' + req.params.action);

    fn.call(
        req.sdc[req.dc].vmapi,
        body,
        {headers: getRequestHeaders(req) },
        function (err, obj)
    {
        if (err) {
            return next(err);
        }
        res.send(obj);
        return next();
    });

    return null;
}

function groupedByCustomer(req, res, next) {
    var params = req.query;
    var _customers = {};
    var _vms;

    function _listVms() {
        return new Promise(function (resolve, reject) {
            req.sdc[req.dc].vmapi.listVms(params, function (err, vms) {
                _vms = vms.map(function (vm) {
                    delete vm.customer_metadata;
                    delete vm.internal_metadata;
                    return vm;
                });
                resolve(vms);
            });
        });
    }

    function _fetchOwners() {
        var allOwners = _.pluck(_vms, 'owner_uuid');
        var owners = _.uniq(allOwners);

        var getUserCalls = owners.map(function (uuid) {
            return new Promise(function (resolve, reject) {
                req.ufds.getUser(uuid, function (err, owner) {
                    if (err) {
                        req.log.fatal(err, 'error retrieving owner for vms summary', owner);
                        return next(err);
                    }

                    [
                        'controls',
                        'memberof',
                        'dn',
                        'pwdchangedtime',
                        'pwdendtime',
                        'registered_developer',
                        'approved_for_provisioning',
                        'memberof',
                        'objectclass'
                    ].forEach(function (k) {
                        delete owner[k];
                    });
                    owner.created_at = new Date(Number(owner.created_at));
                    owner.updated_at = new Date(Number(owner.updated_at));
                    _customers[uuid] = owner;
                    resolve(owner);
                    return null;
                });
            });
        });

        return Promise.all(getUserCalls);
    }

    function _mergeData() {
        var values = [];
        var vmsGroupedByCustomerUuid = _.groupBy(_vms, function (vm) {
            return vm.owner_uuid;
        });

        for (var customerUuid in _customers) {
            var row = _customers[customerUuid];
            row.vms = vmsGroupedByCustomerUuid[customerUuid];
            values.push(row);
        }
        return values;
    }

    _listVms().then(_fetchOwners).then(_mergeData).then(function (data) {
        res.send(data);
    });
}
<|endoftext|>


<commit_before>/**
 * Vow
 *
 * Copyright (c) 2012 Filatov Dmitry (dfilatov@yandex-team.ru)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @version 0.1.8
 */

(function(global) {

var undef,
    nextTick = typeof process === 'object'? // nodejs
        process.nextTick :
        global.setImmediate? // ie10
            global.setImmediate :
            global.postMessage? // modern browsers
                (function() {
                    var fns = [],
                        msg = '__promise' + +new Date,
                        onMessage = function(e) {
                            if(e.data === msg) {
                                e.stopPropagation && e.stopPropagation();

                                var callFns = fns, i = 0, len = fns.length;
                                fns = [];
                                while(i < len) {
                                    callFns[i++]();
                                }
                            }
                        };

                    global.addEventListener?
                        global.addEventListener('message', onMessage, true) :
                        global.attachEvent('onmessage', onMessage);

                    return function(fn) {
                        fns.push(fn) === 1 && global.postMessage(msg, '*');
                    };
                })() :
                function(fn) { // old browsers
                    setTimeout(fn, 0);
                },
    throwException = function(e) {
        nextTick(function() {
            throw e;
        });
    },
    isFunction = function(obj) {
        return typeof obj === 'function';
    };

var Promise = function(val) {
    this._res = val;

    this._isFulfilled = typeof val !== 'undefined';
    this._isRejected = false;

    this._fulfilledCallbacks = [];
    this._rejectedCallbacks = [];
};

Promise.prototype = {
    valueOf : function() {
        return this._res;
    },

    isFulfilled : function() {
        return this._isFulfilled;
    },

    isRejected : function() {
        return this._isRejected;
    },

    isResolved : function() {
        return this._isFulfilled || this._isRejected;
    },

    fulfill : function(val) {
        if(this.isResolved()) {
            return;
        }

        this._isFulfilled = true;
        this._res = val;

        this._callCallbacks(this._fulfilledCallbacks);
        this._fulfilledCallbacks = this._rejectedCallbacks = undef;
    },

    reject : function(error) {
        if(this.isResolved()) {
            return;
        }

        this._isRejected = true;
        this._res = error;

        this._callCallbacks(this._rejectedCallbacks);
        this._fulfilledCallbacks = this._rejectedCallbacks = undef;
    },

    then : function(onFulfilled, onRejected) {
        var promise = new Promise(),
            cb;

        if(!this._isRejected) {
            cb = { promise : promise, fn : onFulfilled };
            this._isFulfilled?
                this._callCallbacks([cb]) :
                this._fulfilledCallbacks.push(cb);
        }

        if(!this._isFulfilled) {
            cb = { promise : promise, fn : onRejected };
            this._isRejected?
                this._callCallbacks([cb]) :
                this._rejectedCallbacks.push(cb);
        }

        return promise;
    },

    fail : function(onRejected) {
        return this.then(undef, onRejected);
    },

    spread : function(onFulfilled, onRejected) {
        return this.then(
            function(val) {
                return onFulfilled.apply(this, val);
            },
            onRejected);
    },

    done : function() {
        this.fail(throwException);
    },

    timeout : function(timeout) {
        var promise = new Promise(),
            timer = setTimeout(
                function() {
                    promise.reject(Error('timed out'));
                },
                timeout);

        this.then(
            function(res) {
                clearTimeout(timer);
                promise.fulfill(res);
            },
            function(error) {
                clearTimeout(timer);
                promise.reject(error);
            });

        return promise;
    },

    _callCallbacks : function(callbacks) {
        var len = callbacks.length;
        if(!len) {
            return;
        }

        var arg = this._res,
            isFulfilled = this.isFulfilled();

        nextTick(function() {
            var i = 0, cb, promise, fn;
            while(i < len) {
                cb = callbacks[i++];
                promise = cb.promise;
                fn = cb.fn;

                if(isFunction(fn)) {
                    var res;
                    try {
                        res = fn(arg);
                    }
                    catch(e) {
                        promise.reject(e);
                        continue;
                    }

                    Vow.isPromise(res)?
                        (function(promise) {
                            res.then(
                                function(val) {
                                    promise.fulfill(val);
                                },
                                function(error) {
                                    promise.reject(error);
                                })
                        })(promise) :
                        promise.fulfill(res);
                }
                else {
                    isFulfilled?
                        promise.fulfill(arg) :
                        promise.reject(arg);
                }
            }
        });
    }
};

var Vow = {
    promise : function(val) {
        return this.isPromise(val)? val : new Promise(val);
    },

    when : function(obj, onFulfilled, onRejected) {
        return this.promise(obj).then(onFulfilled, onRejected);
    },

    fail : function(obj, onRejected) {
        return this.when(obj, undef, onRejected);
    },

    spread : function(obj, onFulfilled, onRejected) {
        return this.promise(obj).spread(onFulfilled, onRejected);
    },

    done : function(obj) {
        this.isPromise(obj) && obj.done();
    },

    isPromise : function(obj) {
        return obj && isFunction(obj.then);
    },

    isFulfilled : function(obj) {
        return this.isPromise(obj)? obj.isFulfilled() : true;
    },

    isRejected : function(obj) {
        return this.isPromise(obj)? obj.isRejected() : false;
    },

    isResolved : function(obj) {
        return this.isPromise(obj)? obj.isResolved() : true;
    },

    fulfill : function(val) {
        return this.when(val, undef, function(error) {
            return error;
        });
    },

    reject : function(error) {
        return this.when(error, function(val) {
            var promise = new Promise();
            promise.reject(val);
            return promise;
        });
    },

    resolve : function(val) {
        return this.isPromise(val)? val : this.when(val);
    },

    forEach : function(promises, onFulfilled, onRejected) {
        var i = 0, len = promises.length;
        while(i < len) {
            this.when(promises[i++], onFulfilled, onRejected);
        }
    },

    all : function(promises) {
        var i = promises.length;
        if(!i) {
            return new Promise([]);
        }

        var resPromise = new Promise(),
            onFulfilled = function() {
                if(!--i) {
                    var res = [],
                        promise;
                    while(promise = promises[i++]) {
                        res.push(promise.valueOf());
                    }
                    resPromise.fulfill(res);
                }
            },
            onRejected = function(error) {
                resPromise.reject(error);
            };

        this.forEach(promises, onFulfilled, onRejected);

        return resPromise;
    },

    allResolved : function(promises) {
        var i = promises.length;
        if(!i) {
            return new Promise([]);
        }

        var resPromise = new Promise(),
            onProgress = function() {
                if(!--i) {
                    resPromise.fulfill(promises);
                }
            };

        this.forEach(promises, onProgress, onProgress);

        return resPromise;
    },

    any : function(promises) {
        var len = promises.length,
            resPromise = new Promise();

        if(!len) {
            resPromise.reject(Error());
            return resPromise;
        }

        var i = 0, error,
            onFulfilled = function(val) {
                resPromise.fulfill(val);
            },
            onRejected = function(_error) {
                i || (error = _error);
                if(++i === len) {
                    resPromise.reject(error);
                }
            };

        this.forEach(promises, onFulfilled, onRejected);

        return resPromise;
    },

    timeout : function(val, timeout) {
        return this.promise(val).timeout(timeout);
    }
};

if(typeof exports === 'object') {
    module.exports = Vow;
}
else if(typeof define === 'function') {
    define(function(require, exports, module) {
        module.exports = Vow;
    });
}
else {
    global.Vow = Vow;
}

})(this);<commit_msg>script readystatechanged trick for real setTimeout 0<commit_after>/**
 * Vow
 *
 * Copyright (c) 2012 Filatov Dmitry (dfilatov@yandex-team.ru)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @version 0.1.8
 */

(function(global) {

var undef,
    nextTick = typeof process === 'object'? // nodejs
        process.nextTick :
        global.setImmediate? // ie10
            global.setImmediate :
            global.postMessage? // modern browsers
                (function() {
                    var fns = [],
                        msg = '__promise' + +new Date,
                        onMessage = function(e) {
                            if(e.data === msg) {
                                e.stopPropagation && e.stopPropagation();

                                var callFns = fns, i = 0, len = fns.length;
                                fns = [];
                                while(i < len) {
                                    callFns[i++]();
                                }
                            }
                        };

                    global.addEventListener?
                        global.addEventListener('message', onMessage, true) :
                        global.attachEvent('onmessage', onMessage);

                    return function(fn) {
                        fns.push(fn) === 1 && global.postMessage(msg, '*');
                    };
                })() :
                function(fn) { // old browsers
                    var script = document.createElement('script');
                    script.onreadystatechange = function() {
                        script.parentNode.removeChild(script);
                        script = script.onreadystatechange = null;
                        fn();
                    };
                    (document.documentElement || document.body).appendChild(script);
                },
    throwException = function(e) {
        nextTick(function() {
            throw e;
        });
    },
    isFunction = function(obj) {
        return typeof obj === 'function';
    };

var Promise = function(val) {
    this._res = val;

    this._isFulfilled = typeof val !== 'undefined';
    this._isRejected = false;

    this._fulfilledCallbacks = [];
    this._rejectedCallbacks = [];
};

Promise.prototype = {
    valueOf : function() {
        return this._res;
    },

    isFulfilled : function() {
        return this._isFulfilled;
    },

    isRejected : function() {
        return this._isRejected;
    },

    isResolved : function() {
        return this._isFulfilled || this._isRejected;
    },

    fulfill : function(val) {
        if(this.isResolved()) {
            return;
        }

        this._isFulfilled = true;
        this._res = val;

        this._callCallbacks(this._fulfilledCallbacks);
        this._fulfilledCallbacks = this._rejectedCallbacks = undef;
    },

    reject : function(error) {
        if(this.isResolved()) {
            return;
        }

        this._isRejected = true;
        this._res = error;

        this._callCallbacks(this._rejectedCallbacks);
        this._fulfilledCallbacks = this._rejectedCallbacks = undef;
    },

    then : function(onFulfilled, onRejected) {
        var promise = new Promise(),
            cb;

        if(!this._isRejected) {
            cb = { promise : promise, fn : onFulfilled };
            this._isFulfilled?
                this._callCallbacks([cb]) :
                this._fulfilledCallbacks.push(cb);
        }

        if(!this._isFulfilled) {
            cb = { promise : promise, fn : onRejected };
            this._isRejected?
                this._callCallbacks([cb]) :
                this._rejectedCallbacks.push(cb);
        }

        return promise;
    },

    fail : function(onRejected) {
        return this.then(undef, onRejected);
    },

    spread : function(onFulfilled, onRejected) {
        return this.then(
            function(val) {
                return onFulfilled.apply(this, val);
            },
            onRejected);
    },

    done : function() {
        this.fail(throwException);
    },

    timeout : function(timeout) {
        var promise = new Promise(),
            timer = setTimeout(
                function() {
                    promise.reject(Error('timed out'));
                },
                timeout);

        this.then(
            function(res) {
                clearTimeout(timer);
                promise.fulfill(res);
            },
            function(error) {
                clearTimeout(timer);
                promise.reject(error);
            });

        return promise;
    },

    _callCallbacks : function(callbacks) {
        var len = callbacks.length;
        if(!len) {
            return;
        }

        var arg = this._res,
            isFulfilled = this.isFulfilled();

        nextTick(function() {
            var i = 0, cb, promise, fn;
            while(i < len) {
                cb = callbacks[i++];
                promise = cb.promise;
                fn = cb.fn;

                if(isFunction(fn)) {
                    var res;
                    try {
                        res = fn(arg);
                    }
                    catch(e) {
                        promise.reject(e);
                        continue;
                    }

                    Vow.isPromise(res)?
                        (function(promise) {
                            res.then(
                                function(val) {
                                    promise.fulfill(val);
                                },
                                function(error) {
                                    promise.reject(error);
                                })
                        })(promise) :
                        promise.fulfill(res);
                }
                else {
                    isFulfilled?
                        promise.fulfill(arg) :
                        promise.reject(arg);
                }
            }
        });
    }
};

var Vow = {
    promise : function(val) {
        return this.isPromise(val)? val : new Promise(val);
    },

    when : function(obj, onFulfilled, onRejected) {
        return this.promise(obj).then(onFulfilled, onRejected);
    },

    fail : function(obj, onRejected) {
        return this.when(obj, undef, onRejected);
    },

    spread : function(obj, onFulfilled, onRejected) {
        return this.promise(obj).spread(onFulfilled, onRejected);
    },

    done : function(obj) {
        this.isPromise(obj) && obj.done();
    },

    isPromise : function(obj) {
        return obj && isFunction(obj.then);
    },

    isFulfilled : function(obj) {
        return this.isPromise(obj)? obj.isFulfilled() : true;
    },

    isRejected : function(obj) {
        return this.isPromise(obj)? obj.isRejected() : false;
    },

    isResolved : function(obj) {
        return this.isPromise(obj)? obj.isResolved() : true;
    },

    fulfill : function(val) {
        return this.when(val, undef, function(error) {
            return error;
        });
    },

    reject : function(error) {
        return this.when(error, function(val) {
            var promise = new Promise();
            promise.reject(val);
            return promise;
        });
    },

    resolve : function(val) {
        return this.isPromise(val)? val : this.when(val);
    },

    forEach : function(promises, onFulfilled, onRejected) {
        var i = 0, len = promises.length;
        while(i < len) {
            this.when(promises[i++], onFulfilled, onRejected);
        }
    },

    all : function(promises) {
        var i = promises.length;
        if(!i) {
            return new Promise([]);
        }

        var resPromise = new Promise(),
            onFulfilled = function() {
                if(!--i) {
                    var res = [],
                        promise;
                    while(promise = promises[i++]) {
                        res.push(promise.valueOf());
                    }
                    resPromise.fulfill(res);
                }
            },
            onRejected = function(error) {
                resPromise.reject(error);
            };

        this.forEach(promises, onFulfilled, onRejected);

        return resPromise;
    },

    allResolved : function(promises) {
        var i = promises.length;
        if(!i) {
            return new Promise([]);
        }

        var resPromise = new Promise(),
            onProgress = function() {
                if(!--i) {
                    resPromise.fulfill(promises);
                }
            };

        this.forEach(promises, onProgress, onProgress);

        return resPromise;
    },

    any : function(promises) {
        var len = promises.length,
            resPromise = new Promise();

        if(!len) {
            resPromise.reject(Error());
            return resPromise;
        }

        var i = 0, error,
            onFulfilled = function(val) {
                resPromise.fulfill(val);
            },
            onRejected = function(_error) {
                i || (error = _error);
                if(++i === len) {
                    resPromise.reject(error);
                }
            };

        this.forEach(promises, onFulfilled, onRejected);

        return resPromise;
    },

    timeout : function(val, timeout) {
        return this.promise(val).timeout(timeout);
    }
};

if(typeof exports === 'object') {
    module.exports = Vow;
}
else if(typeof define === 'function') {
    define(function(require, exports, module) {
        module.exports = Vow;
    });
}
else {
    global.Vow = Vow;
}

})(this);<|endoftext|>


<commit_before>const debug = require('debug')('weh')
const trough = require('trough')
const read = require('./read')
const write = require('./write')
const { generateConfig } = require('./config')

async function siteUse (fn, opts = {}) {
  const plugin = await fn(opts)
  this.hooks.use(plugin)
}

function siteConfig (conf = {}) {
  this._config = generateConfig(conf)
}

function _runMiddleware (hooks, files) {
  return new Promise((resolve, reject) => {
    hooks.run(files, (err, res) => {
      if (err) reject(err)
      resolve(res)
    })
  })
}

async function buildSite (site) {
  site.files = []

  debug('starting read...')
  try {
    site.files = site._config.dry_run
      ? site._config.files
      : await read(site._config.source)
  } catch (errs) {
    debug('one or more errors occured while reading:')
    errs.forEach(err => { throw err })
  }

  debug('running plugins...')
  site.files = await _runMiddleware(site.hooks, site.files)

  debug('got %d files', site.files.length)
  if (site._config.dry_run) {
    debug('skipping write...')
  } else {
    debug('starting write...')
    site = await write(site)
  }

  debug('all done!')
  return site
}

async function wehCore (site, fn) {
  site.config = siteConfig.bind(site)
  site.use = siteUse.bind(site)

  debug('weh is ready to go!!!')

  const resSite = await fn(site)
  if (Object.keys(site._config).length === 0) {
    site._config = generateConfig({})
  }
  return buildSite(resSite)
}

async function weh (fn) {
  const site = {}
  site._config = {}
  site.hooks = trough()
  return wehCore(site, fn)
}

async function wehIntegration (fn, files) {
  const site = {}
  site._config = {
    dry_run: true,
    files
  }
  site.hooks = trough()
  return wehCore(site, fn)
}

module.exports = weh
module.exports.integration = wehIntegration
<commit_msg>split dry_run into no_read and no_write<commit_after>const debug = require('debug')('weh')
const trough = require('trough')
const read = require('./read')
const write = require('./write')
const { generateConfig } = require('./config')

async function siteUse (fn, opts = {}) {
  const plugin = await fn(opts)
  this.hooks.use(plugin)
}

function siteConfig (conf = {}) {
  this._config = generateConfig(conf)
}

function _runMiddleware (hooks, files) {
  return new Promise((resolve, reject) => {
    hooks.run(files, (err, res) => {
      if (err) reject(err)
      resolve(res)
    })
  })
}

async function buildSite (site) {
  site.files = []

  debug('starting read...')
  try {
    site.files = site._config.no_read
      ? site._config.files
      : await read(site._config.source)
  } catch (errs) {
    debug('one or more errors occured while reading:')
    errs.forEach(err => { throw err })
  }

  debug('running plugins...')
  site.files = await _runMiddleware(site.hooks, site.files)

  debug('got %d files', site.files.length)
  if (site._config.no_write) {
    debug('skipping write...')
  } else {
    debug('starting write...')
    site = await write(site)
  }

  debug('all done!')
  return site
}

async function wehCore (site, fn) {
  site.config = siteConfig.bind(site)
  site.use = siteUse.bind(site)

  debug('weh is ready to go!!!')

  const resSite = await fn(site)
  if (Object.keys(site._config).length === 0) {
    site._config = generateConfig({})
  }
  return buildSite(resSite)
}

async function weh (fn) {
  const site = {}
  site._config = {}
  site.hooks = trough()
  return wehCore(site, fn)
}

async function wehIntegration (fn, files) {
  const site = {}
  site._config = {
    no_read: true,
    no_write: true,
    files
  }
  site.hooks = trough()
  return wehCore(site, fn)
}

module.exports = weh
module.exports.integration = wehIntegration
<|endoftext|>


<commit_before>(function (win, events) {
    var DEFAULT_ORIGIN = '*';
    var xde, eventListeners;
    var onlyStrings;

    function onMessage(evt) {
        var parsedData;

        if (xde.targetOrigin != DEFAULT_ORIGIN && evt.origin !== xde.targetOrigin) {
            return;
        }

        parsedData = evt.data;
        if (typeof evt.data == 'string') {
            try {
                parsedData = JSON.parse(evt.data);
            } catch (e) {}
        }

        if (!parsedData || parsedData.__xde !== true) {
            return;
        }

        parsedData.origin = evt.origin;
        parsedData.source = evt.source;

        var listeners = eventListeners[parsedData.name];
        if (listeners && listeners.length > 0) {
            listeners.forEach(function(fn){
                fn(parsedData);
            });
        }
    }

    function validateName (name) {
        if (!name || typeof name != 'string') { throw new Error('Event name has to be a string'); };
    }

    function validateNameAndFn (name, fn) {
        validateName(name);
        if (typeof fn != "function" ) { throw new Error('Callback function has to be given'); }
    }

    xde = {
        on: function (name, fn) {
            validateNameAndFn(name, fn);

            if (typeof eventListeners[name] == 'undefined') {
                eventListeners[name] = [];
            }
            eventListeners[name].push(fn);
        },

        off: function (name, fn) {
            validateNameAndFn(name, fn);
            var listeners = eventListeners[name];
            if (!listeners) {
                return;
            }
            eventListeners[name] = listeners.filter(function (listener) {
                return listener !== fn;
            });
        },

        sendTo: function (otherWindow, name, data) {
            validateName(name);
            if (otherWindow && otherWindow.contentWindow) {
                otherWindow = otherWindow.contentWindow;
            }
            if ( !otherWindow || !otherWindow.postMessage ) {
                throw new TypeError('otherWindow does not support postMessage');
            }

            var msg = {
                name : name,
                data : data,
                __xde : true
            };
            if (onlyStrings) {
                msg = JSON.stringify(msg);
            }
            otherWindow.postMessage(msg, this.targetOrigin); // TODO fix security issue
        },

        targetOrigin: DEFAULT_ORIGIN,

        _reset: function (forceStringify) {
            eventListeners = {};
            this.targetOrigin = DEFAULT_ORIGIN;
            onlyStrings = forceStringify || false;
            try{win.postMessage({toString:function(){onlyStrings=true;}},"*");}catch(e){}
        }
    };

    xde._reset();
    events.add(window, 'message', onMessage, false);

    if(typeof exports === 'object') {
        module.exports = xde;
    } else {
        win.xde = xde;
    }
})(this, this.eventListener || require('eventlistener'));
<commit_msg>Avoid security exception<commit_after>(function (win, events) {
    var DEFAULT_ORIGIN = '*';
    var xde, eventListeners;
    var onlyStrings;

    function onMessage(evt) {
        var parsedData;

        if (xde.targetOrigin != DEFAULT_ORIGIN && evt.origin !== xde.targetOrigin) {
            return;
        }

        parsedData = evt.data;
        if (typeof evt.data == 'string') {
            try {
                parsedData = JSON.parse(evt.data);
            } catch (e) {}
        }

        if (!parsedData || parsedData.__xde !== true) {
            return;
        }

        parsedData.origin = evt.origin;
        parsedData.source = evt.source;

        var listeners = eventListeners[parsedData.name];
        if (listeners && listeners.length > 0) {
            listeners.forEach(function(fn){
                fn(parsedData);
            });
        }
    }

    function validateName (name) {
        if (!name || typeof name != 'string') { throw new Error('Event name has to be a string'); };
    }

    function validateNameAndFn (name, fn) {
        validateName(name);
        if (typeof fn != "function" ) { throw new Error('Callback function has to be given'); }
    }

    xde = {
        on: function (name, fn) {
            validateNameAndFn(name, fn);

            if (typeof eventListeners[name] == 'undefined') {
                eventListeners[name] = [];
            }
            eventListeners[name].push(fn);
        },

        off: function (name, fn) {
            validateNameAndFn(name, fn);
            var listeners = eventListeners[name];
            if (!listeners) {
                return;
            }
            eventListeners[name] = listeners.filter(function (listener) {
                return listener !== fn;
            });
        },

        sendTo: function (otherWindow, name, data) {
            validateName(name);
            try {
                if (otherWindow && otherWindow.contentWindow) {
                    otherWindow = otherWindow.contentWindow;
                }
            } catch(e) {}
            if ( !otherWindow || !otherWindow.postMessage ) {
                throw new TypeError('otherWindow does not support postMessage');
            }

            var msg = {
                name : name,
                data : data,
                __xde : true
            };
            if (onlyStrings) {
                msg = JSON.stringify(msg);
            }
            otherWindow.postMessage(msg, this.targetOrigin); // TODO fix security issue
        },

        targetOrigin: DEFAULT_ORIGIN,

        _reset: function (forceStringify) {
            eventListeners = {};
            this.targetOrigin = DEFAULT_ORIGIN;
            onlyStrings = forceStringify || false;
            try{win.postMessage({toString:function(){onlyStrings=true;}},"*");}catch(e){}
        }
    };

    xde._reset();
    events.add(window, 'message', onMessage, false);

    if(typeof exports === 'object') {
        module.exports = xde;
    } else {
        win.xde = xde;
    }
})(this, this.eventListener || require('eventlistener'));
<|endoftext|>


<commit_before>module.exports = {
    search: function(series, options, callback) {
        var params = fixParameters(options, callback);
        var values = search.queryObject(series);
        makeApiCall(params.options, search, values, params.callback);
    },
    getEpisodeList: function(seriesId, options, callback) {
        var params = fixParameters(options, callback);
        var values = eplist.queryObject(seriesId);
        makeApiCall(params.options, eplist, values, params.callback);
    },
    getSeriesDetails: function(seriesId, options, callback) {
        var params = fixParameters(options, callback);
        var values = eplist.queryObject(seriesId);
        makeApiCall(params.options, seriesinfo, values, params.callback);
    },
    getEpisode: function(query, options, callback) {
        var params = fixParameters(options, callback);
        getEpisodeDetails(query, params.options, params.callback);
    }
};

function fixParameters(options, callback) {
    var onlyHaveCallback = (typeof(options) === "function" && callback === undefined);

    return {
        options: onlyHaveCallback ? {} : options,
        callback: onlyHaveCallback ? options : callback
    };
}

var querystring = require("querystring"),
    defaultify = require("defaultify"),

    search = require("./search"),
    eplist = require("./eplist"),
    seriesinfo = require("./seriesinfo");

const API_ROOT_URL = "http://services.tvrage.com/feeds/";

function getEpisodeDetails(query, options, callback) {
    module.exports.search(query.series, options, function(err, series) {
        if (err) {
            callback(err);
        } else {
            module.exports.getEpisodeList(series[0].id, options, function(err, list) {
                if (err) {
                    callback(err);
                } else {
                    var season = findMatchingSeason(list, query);
                    var eps = findMatchingEps(season, query);

                    callback(null, {
                        series: series,
                        matched: {
                            series: series[0].name,
                            season: season.number,
                            episodes: eps
                        }
                    });
                }
            });
        }
    });
}

function findMatchingSeason(list, query) {
    for (var i = 0; i < list.length; ++i) {
        if (list[i].number == query.season) {
            return list[i];
        }
    }
    return {number:null, list:[]};
}

function findMatchingEps(eps, query) {
    var result = [];
    if (eps && eps.list) {
        for (var i = 0; i < eps.list.length; ++i) {
            for (var x = 0; x < query.episodes.length; ++x) {
                if (eps.list[i].index.season == query.episodes[x]) {
                    result.push(eps.list[i]);
                }
            }
        }
    }
    return result;
}

function makeApiCall(userOptions, apiCall, values, callback) {
    var qs = querystring.stringify(values);
    var url = API_ROOT_URL + apiCall.apiName + ".php?" + qs;

    buildOptions(userOptions, function(err, options) {
        if (err) {
            callback(err);
        } else {
            var cacheKey = apiCall.apiName + ":" + qs;
            options.cache(cacheKey, function(cachedValue) {
                if (cachedValue) {
                    callback(null, cachedValue);
                } else {
                    // cache miss
                    if (options.get === serviceClientWrapper) {
                        serviceClientWrapper(apiCall, url, callback);
                    } else {
                        options.get(url, function(err, xml) {
                            if (err) {
                                process.nextTick(function() {
                                    callback(err);
                                });
                            } else {
                                process.nextTick(function() {
                                    apiCall.parse(xml, function(err, data) {
                                        if (err) {
                                            callback(err);
                                        } else {
                                            options.save(cacheKey, data);
                                            callback(null, data);
                                        }
                                    });
                                });
                            }
                        });
                    }
                }
            });
        }
    });
}

function buildOptions(user, callback) {
    const DEFAULT = {
        get: serviceClientWrapper,
        cache: redisWrapper.cache,
        save: redisWrapper.save
    };

    try {
        var result = defaultify(user, DEFAULT, true);
        process.nextTick(function() {
            callback(null, result.value);
        });
    } catch (e) {
        process.nextTick(function() {
            callback(e);
        });
    }
}

function serviceClientWrapper(apiCall, url, callback) {
    try {
        var sc = require("service-client");
        sc.get(url, { parse: apiCall.parse }, callback);
    } catch (e) {
        callback(e);
    }
}

function RedisWrapper() {
    var self = this;
    var redis = null;

    self.cache = function(key, callback) {
        if (redis) {
            redis.get(key, function(err, value) {
                callback(JSON.parse(value));
            });
        } else {
            // always cache miss
            callback(null);
        }
    }
    self.save = function(key, value) {
        if (redis) {
            redis.set(key, JSON.stringify(value));
        } // else: no-op
    }

    function createRedis() {
        try {
            var r = require("redis").createClient();
            r.on("ready", function() {
                redis = r;
            });
        } catch (e) { /* ignored */ }
    }

    process.nextTick(createRedis);
}

var redisWrapper = new RedisWrapper();

<commit_msg>also save cache when using service wrapper extract save/callback into creator function, save cache values<commit_after>module.exports = {
    search: function(series, options, callback) {
        var params = fixParameters(options, callback);
        var values = search.queryObject(series);
        makeApiCall(params.options, search, values, params.callback);
    },
    getEpisodeList: function(seriesId, options, callback) {
        var params = fixParameters(options, callback);
        var values = eplist.queryObject(seriesId);
        makeApiCall(params.options, eplist, values, params.callback);
    },
    getSeriesDetails: function(seriesId, options, callback) {
        var params = fixParameters(options, callback);
        var values = eplist.queryObject(seriesId);
        makeApiCall(params.options, seriesinfo, values, params.callback);
    },
    getEpisode: function(query, options, callback) {
        var params = fixParameters(options, callback);
        getEpisodeDetails(query, params.options, params.callback);
    }
};

function fixParameters(options, callback) {
    var onlyHaveCallback = (typeof(options) === "function" && callback === undefined);

    return {
        options: onlyHaveCallback ? {} : options,
        callback: onlyHaveCallback ? options : callback
    };
}

var querystring = require("querystring"),
    defaultify = require("defaultify"),

    search = require("./search"),
    eplist = require("./eplist"),
    seriesinfo = require("./seriesinfo");

const API_ROOT_URL = "http://services.tvrage.com/feeds/";

function getEpisodeDetails(query, options, callback) {
    module.exports.search(query.series, options, function(err, series) {
        if (err) {
            callback(err);
        } else {
            module.exports.getEpisodeList(series[0].id, options, function(err, list) {
                if (err) {
                    callback(err);
                } else {
                    var season = findMatchingSeason(list, query);
                    var eps = findMatchingEps(season, query);

                    callback(null, {
                        series: series,
                        matched: {
                            series: series[0].name,
                            season: season.number,
                            episodes: eps
                        }
                    });
                }
            });
        }
    });
}

function findMatchingSeason(list, query) {
    for (var i = 0; i < list.length; ++i) {
        if (list[i].number == query.season) {
            return list[i];
        }
    }
    return {number:null, list:[]};
}

function findMatchingEps(eps, query) {
    var result = [];
    if (eps && eps.list) {
        for (var i = 0; i < eps.list.length; ++i) {
            for (var x = 0; x < query.episodes.length; ++x) {
                if (eps.list[i].index.season == query.episodes[x]) {
                    result.push(eps.list[i]);
                }
            }
        }
    }
    return result;
}

function makeApiCall(userOptions, apiCall, values, callback) {
    var qs = querystring.stringify(values);
    var url = API_ROOT_URL + apiCall.apiName + ".php?" + qs;

    function createSaveCacheAndCallback(cacheKey, options) {
        return function(err, data) {
            process.nextTick(function() {
                if (err) {
                    callback(err);
                } else {
                    options.save(cacheKey, data);
                    callback(null, data);
                }
            });
        };
    }

    buildOptions(userOptions, function(err, options) {
        if (err) {
            callback(err);
        } else {
            var cacheKey = apiCall.apiName + ":" + qs;
            var newCallback = createSaveCacheAndCallback(cacheKey, options);
            options.cache(cacheKey, function(cachedValue) {
                if (cachedValue) {
                    callback(null, cachedValue);
                } else {
                    // cache miss
                    if (options.get === serviceClientWrapper) {
                        serviceClientWrapper(apiCall, url, newCallback);
                    } else {
                        options.get(url, function(err, xml) {
                            if (err) {
                                process.nextTick(function() {
                                    callback(err);
                                });
                            } else {
                                process.nextTick(function() {
                                    apiCall.parse(xml, newCallback);
                                });
                            }
                        });
                    }
                }
            });
        }
    });
}

function buildOptions(user, callback) {
    const DEFAULT = {
        get: serviceClientWrapper,
        cache: redisWrapper.cache,
        save: redisWrapper.save
    };

    try {
        var result = defaultify(user, DEFAULT, true);
        process.nextTick(function() {
            callback(null, result.value);
        });
    } catch (e) {
        process.nextTick(function() {
            callback(e);
        });
    }
}

function serviceClientWrapper(apiCall, url, callback) {
    try {
        var sc = require("service-client");
        sc.get(url, { parse: apiCall.parse }, callback);
    } catch (e) {
        callback(e);
    }
}

function RedisWrapper() {
    var self = this;
    var redis = null;

    self.cache = function(key, callback) {
        if (redis) {
            redis.get(key, function(err, value) {
                callback(JSON.parse(value));
            });
        } else {
            // always cache miss
            callback(null);
        }
    }
    self.save = function(key, value) {
        if (redis) {
            redis.set(key, JSON.stringify(value));
        } // else: no-op
    }

    function createRedis() {
        try {
            var r = require("redis").createClient();
            r.on("ready", function() {
                redis = r;
            });
        } catch (e) { /* ignored */ }
    }

    process.nextTick(createRedis);
}

var redisWrapper = new RedisWrapper();

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';

import Keypad from './keypad';
import Step from './step';
import MathRenderer from './math-renderer';
import store from './../store';
import Parser from '../parser';
import params from '../params';

const parser = new Parser();

class AuxApp extends Component {
    static defaultProps = {
        goal: params.end ? parser.parse(params.end) : parser.parse('x = 5/2')
    };

    select = step => {
        store.dispatch({
            type: 'SELECT_STEP',
            step: step
        });
    };

    componentDidMount() {
        const {offsetHeight, scrollHeight} = this.refs.container;

        if (scrollHeight > offsetHeight) {
            this.refs.container.scrollTop = scrollHeight - offsetHeight;
        }
    }

    render() {
        const style = {
            display: 'flex',
            flexDirection: 'column',
            height: '100vh',
        };

        const containerStyle = {
            flexGrow: 1,
            overflow: 'scroll',
            background: '#EEE',
            display: 'flex',
            flexDirection: 'column-reverse'
        };

        const lineStyle = {
            fontFamily: 'Helvetica-Light',
            fontSize: 26,
        };

        const goalStyle = {
            ...lineStyle,
            display: 'flex',
            flexDirection: 'row',
            paddingLeft: 20,
            paddingRight: 20,
            marginTop: 10,
            marginBottom: 10,
            flexShrink: 0,
        };

        const goal =

Goal:

                <MathRenderer
                    fontSize={26}
                    math={this.props.goal}
                />

;

        const length = this.props.steps.length;

        return

                {this.props.steps.map((line, i) =>
                    <Step
                        {...line}
                        key={i === 0 ? 0 : length - i}
                        onClick={e => this.select(i)}
                        active={this.props.activeStep === i}
                    />)
                }

            {goal}
            <Keypad />

;
    }
}

module.exports = connect(state => state)(AuxApp);
<commit_msg>make the goal smaller so it doesn't take up so much space<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';

import Keypad from './keypad';
import Step from './step';
import MathRenderer from './math-renderer';
import store from './../store';
import Parser from '../parser';
import params from '../params';

const parser = new Parser();

class AuxApp extends Component {
    static defaultProps = {
        goal: params.end ? parser.parse(params.end) : parser.parse('x = 5/2')
    };

    select = step => {
        store.dispatch({
            type: 'SELECT_STEP',
            step: step
        });
    };

    componentDidMount() {
        const {offsetHeight, scrollHeight} = this.refs.container;

        if (scrollHeight > offsetHeight) {
            this.refs.container.scrollTop = scrollHeight - offsetHeight;
        }
    }

    render() {
        const style = {
            display: 'flex',
            flexDirection: 'column',
            height: '100vh',
        };

        const containerStyle = {
            flexGrow: 1,
            overflow: 'scroll',
            background: '#EEE',
            display: 'flex',
            flexDirection: 'column-reverse'
        };

        const lineStyle = {
            fontFamily: 'Helvetica-Light',
            fontSize: 26,
        };

        const goalStyle = {
            ...lineStyle,
            display: 'flex',
            flexDirection: 'row',
            paddingLeft: 20,
            paddingRight: 20,
            marginTop: 5,
            marginBottom: 5,
            flexShrink: 0,
            fontSize: 20,
        };

        const goal =

Goal:

                <MathRenderer
                    fontSize={20}
                    math={this.props.goal}
                />

;

        const length = this.props.steps.length;

        return

                {this.props.steps.map((line, i) =>
                    <Step
                        {...line}
                        key={i === 0 ? 0 : length - i}
                        onClick={e => this.select(i)}
                        active={this.props.activeStep === i}
                    />)
                }

            {goal}
            <Keypad />

;
    }
}

module.exports = connect(state => state)(AuxApp);
<|endoftext|>


<commit_before>(function(Two) {

  var _ = Two.Utils;

  var Vector = Two.Vector = function(x, y) {

    this.x = x || 0;
    this.y = y || 0;

  };

  _.extend(Vector, {

    zero: new Two.Vector()

  });

  _.extend(Vector.prototype, Two.Utils.Events, {

    set: function(x, y) {
      this.x = x;
      this.y = y;
      return this;
    },

    copy: function(v) {
      this.x = v.x;
      this.y = v.y;
      return this;
    },

    clear: function() {
      this.x = 0;
      this.y = 0;
      return this;
    },

    clone: function() {
      return new Vector(this.x, this.y);
    },

    add: function(v1, v2) {
      this.x = v1.x + v2.x;
      this.y = v1.y + v2.y;
      return this;
    },

    addSelf: function(v) {
      this.x += v.x;
      this.y += v.y;
      return this;
    },

    sub: function(v1, v2) {
      this.x = v1.x - v2.x;
      this.y = v1.y - v2.y;
      return this;
    },

    subSelf: function(v) {
      this.x -= v.x;
      this.y -= v.y;
      return this;
    },

    multiplySelf: function(v) {
      this.x *= v.x;
      this.y *= v.y;
      return this;
    },

    multiplyScalar: function(s) {
      this.x *= s;
      this.y *= s;
      return this;
    },

    divideScalar: function(s) {
      if (s) {
        this.x /= s;
        this.y /= s;
      } else {
        this.set(0, 0);
      }
      return this;
    },

    negate: function() {
      return this.multiplyScalar(-1);
    },

    dot: function(v) {
      return this.x * v.x + this.y * v.y;
    },

    lengthSquared: function() {
      return this.x * this.x + this.y * this.y;
    },

    length: function() {
      return Math.sqrt(this.lengthSquared());
    },

    normalize: function() {
      return this.divideScalar(this.length());
    },

    distanceTo: function(v) {
      return Math.sqrt(this.distanceToSquared(v));
    },

    distanceToSquared: function(v) {
      var dx = this.x - v.x,
          dy = this.y - v.y;
      return dx * dx + dy * dy;
    },

    setLength: function(l) {
      return this.normalize().multiplyScalar(l);
    },

    equals: function(v, eps) {
      eps = (typeof eps === 'undefined') ?  0.0001 : eps;
      return (this.distanceTo(v) < eps);
    },

    lerp: function(v, t) {
      var x = (v.x - this.x) * t + this.x;
      var y = (v.y - this.y) * t + this.y;
      return this.set(x, y);
    },

    isZero: function(eps) {
      eps = (typeof eps === 'undefined') ?  0.0001 : eps;
      return (this.length() <  eps);
    },

    toString: function() {
      return this.x + ',' + this.y;
    },

    toObject: function() {
      return { x: this.x, y: this.y };
    },

    rotate: function (radians) {
      var newX = this.x * Math.cos(radians) - this.y * Math.sin(radians);
      var newY = this.x * Math.sin(radians) + this.y * Math.cos(radians);
      return this.set(newX, newY);;
    }

  });

  var BoundProto = {

    set: function(x, y) {
      this._x = x;
      this._y = y;
      return this.trigger(Two.Events.change);
    },

    copy: function(v) {
      this._x = v.x;
      this._y = v.y;
      return this.trigger(Two.Events.change);
    },

    clear: function() {
      this._x = 0;
      this._y = 0;
      return this.trigger(Two.Events.change);
    },

    clone: function() {
      return new Vector(this._x, this._y);
    },

    add: function(v1, v2) {
      this._x = v1.x + v2.x;
      this._y = v1.y + v2.y;
      return this.trigger(Two.Events.change);
    },

    addSelf: function(v) {
      this._x += v.x;
      this._y += v.y;
      return this.trigger(Two.Events.change);
    },

    sub: function(v1, v2) {
      this._x = v1.x - v2.x;
      this._y = v1.y - v2.y;
      return this.trigger(Two.Events.change);
    },

    subSelf: function(v) {
      this._x -= v.x;
      this._y -= v.y;
      return this.trigger(Two.Events.change);
    },

    multiplySelf: function(v) {
      this._x *= v.x;
      this._y *= v.y;
      return this.trigger(Two.Events.change);
    },

    multiplyScalar: function(s) {
      this._x *= s;
      this._y *= s;
      return this.trigger(Two.Events.change);
    },

    divideScalar: function(s) {
      if (s) {
        this._x /= s;
        this._y /= s;
        return this.trigger(Two.Events.change);
      }
      return this.clear();
    },

    negate: function() {
      return this.multiplyScalar(-1);
    },

    dot: function(v) {
      return this._x * v.x + this._y * v.y;
    },

    lengthSquared: function() {
      return this._x * this._x + this._y * this._y;
    },

    length: function() {
      return Math.sqrt(this.lengthSquared());
    },

    normalize: function() {
      return this.divideScalar(this.length());
    },

    distanceTo: function(v) {
      return Math.sqrt(this.distanceToSquared(v));
    },

    distanceToSquared: function(v) {
      var dx = this._x - v.x,
          dy = this._y - v.y;
      return dx * dx + dy * dy;
    },

    setLength: function(l) {
      return this.normalize().multiplyScalar(l);
    },

    equals: function(v, eps) {
      eps = (typeof eps === 'undefined') ?  0.0001 : eps;
      return (this.distanceTo(v) < eps);
    },

    lerp: function(v, t) {
      var x = (v.x - this._x) * t + this._x;
      var y = (v.y - this._y) * t + this._y;
      return this.set(x, y);
    },

    isZero: function(eps) {
      eps = (typeof eps === 'undefined') ?  0.0001 : eps;
      return (this.length() < eps);
    },

    toString: function() {
      return this._x + ',' + this._y;
    },

    toObject: function() {
      return { x: this._x, y: this._y };
    }

  };

  var xgs = {
    enumerable: true,
    get: function() {
      return this._x;
    },
    set: function(v) {
      this._x = v;
      this.trigger(Two.Events.change, 'x');
    }
  };

  var ygs = {
    enumerable: true,
    get: function() {
      return this._y;
    },
    set: function(v) {
      this._y = v;
      this.trigger(Two.Events.change, 'y');
    }
  };

  /**
   * Override Backbone bind / on in order to add properly broadcasting.
   * This allows Two.Vector to not broadcast events unless event listeners
   * are explicity bound to it.
   */

  Two.Vector.prototype.bind = Two.Vector.prototype.on = function() {

    if (!this._bound) {
      this._x = this.x;
      this._y = this.y;
      Object.defineProperty(this, 'x', xgs);
      Object.defineProperty(this, 'y', ygs);
      _.extend(this, BoundProto);
      this._bound = true; // Reserved for event initialization check
    }

    Two.Utils.Events.bind.apply(this, arguments);

    return this;

  };

})(this.Two);
<commit_msg>Update vector.js<commit_after>(function(Two) {

  var _ = Two.Utils;

  var Vector = Two.Vector = function(x, y) {

    this.x = x || 0;
    this.y = y || 0;

  };

  _.extend(Vector, {

    zero: new Two.Vector()

  });

  _.extend(Vector.prototype, Two.Utils.Events, {

    set: function(x, y) {
      this.x = x;
      this.y = y;
      return this;
    },

    copy: function(v) {
      this.x = v.x;
      this.y = v.y;
      return this;
    },

    clear: function() {
      this.x = 0;
      this.y = 0;
      return this;
    },

    clone: function() {
      return new Vector(this.x, this.y);
    },

    add: function(v1, v2) {
      this.x = v1.x + v2.x;
      this.y = v1.y + v2.y;
      return this;
    },

    addSelf: function(v) {
      this.x += v.x;
      this.y += v.y;
      return this;
    },

    sub: function(v1, v2) {
      this.x = v1.x - v2.x;
      this.y = v1.y - v2.y;
      return this;
    },

    subSelf: function(v) {
      this.x -= v.x;
      this.y -= v.y;
      return this;
    },

    multiplySelf: function(v) {
      this.x *= v.x;
      this.y *= v.y;
      return this;
    },

    multiplyScalar: function(s) {
      this.x *= s;
      this.y *= s;
      return this;
    },

    divideScalar: function(s) {
      if (s) {
        this.x /= s;
        this.y /= s;
      } else {
        this.set(0, 0);
      }
      return this;
    },

    negate: function() {
      return this.multiplyScalar(-1);
    },

    dot: function(v) {
      return this.x * v.x + this.y * v.y;
    },

    lengthSquared: function() {
      return this.x * this.x + this.y * this.y;
    },

    length: function() {
      return Math.sqrt(this.lengthSquared());
    },

    normalize: function() {
      return this.divideScalar(this.length());
    },

    distanceTo: function(v) {
      return Math.sqrt(this.distanceToSquared(v));
    },

    distanceToSquared: function(v) {
      var dx = this.x - v.x,
          dy = this.y - v.y;
      return dx * dx + dy * dy;
    },

    setLength: function(l) {
      return this.normalize().multiplyScalar(l);
    },

    equals: function(v, eps) {
      eps = (typeof eps === 'undefined') ?  0.0001 : eps;
      return (this.distanceTo(v) < eps);
    },

    lerp: function(v, t) {
      var x = (v.x - this.x) * t + this.x;
      var y = (v.y - this.y) * t + this.y;
      return this.set(x, y);
    },

    isZero: function(eps) {
      eps = (typeof eps === 'undefined') ?  0.0001 : eps;
      return (this.length() <  eps);
    },

    toString: function() {
      return this.x + ',' + this.y;
    },

    toObject: function() {
      return { x: this.x, y: this.y };
    },

    rotate: function (radians) {
      var newX = this.x * Math.cos(radians) - this.y * Math.sin(radians);
      var newY = this.x * Math.sin(radians) + this.y * Math.cos(radians);
      return this.set(newX, newY);
    }

  });

  var BoundProto = {

    set: function(x, y) {
      this._x = x;
      this._y = y;
      return this.trigger(Two.Events.change);
    },

    copy: function(v) {
      this._x = v.x;
      this._y = v.y;
      return this.trigger(Two.Events.change);
    },

    clear: function() {
      this._x = 0;
      this._y = 0;
      return this.trigger(Two.Events.change);
    },

    clone: function() {
      return new Vector(this._x, this._y);
    },

    add: function(v1, v2) {
      this._x = v1.x + v2.x;
      this._y = v1.y + v2.y;
      return this.trigger(Two.Events.change);
    },

    addSelf: function(v) {
      this._x += v.x;
      this._y += v.y;
      return this.trigger(Two.Events.change);
    },

    sub: function(v1, v2) {
      this._x = v1.x - v2.x;
      this._y = v1.y - v2.y;
      return this.trigger(Two.Events.change);
    },

    subSelf: function(v) {
      this._x -= v.x;
      this._y -= v.y;
      return this.trigger(Two.Events.change);
    },

    multiplySelf: function(v) {
      this._x *= v.x;
      this._y *= v.y;
      return this.trigger(Two.Events.change);
    },

    multiplyScalar: function(s) {
      this._x *= s;
      this._y *= s;
      return this.trigger(Two.Events.change);
    },

    divideScalar: function(s) {
      if (s) {
        this._x /= s;
        this._y /= s;
        return this.trigger(Two.Events.change);
      }
      return this.clear();
    },

    negate: function() {
      return this.multiplyScalar(-1);
    },

    dot: function(v) {
      return this._x * v.x + this._y * v.y;
    },

    lengthSquared: function() {
      return this._x * this._x + this._y * this._y;
    },

    length: function() {
      return Math.sqrt(this.lengthSquared());
    },

    normalize: function() {
      return this.divideScalar(this.length());
    },

    distanceTo: function(v) {
      return Math.sqrt(this.distanceToSquared(v));
    },

    distanceToSquared: function(v) {
      var dx = this._x - v.x,
          dy = this._y - v.y;
      return dx * dx + dy * dy;
    },

    setLength: function(l) {
      return this.normalize().multiplyScalar(l);
    },

    equals: function(v, eps) {
      eps = (typeof eps === 'undefined') ?  0.0001 : eps;
      return (this.distanceTo(v) < eps);
    },

    lerp: function(v, t) {
      var x = (v.x - this._x) * t + this._x;
      var y = (v.y - this._y) * t + this._y;
      return this.set(x, y);
    },

    isZero: function(eps) {
      eps = (typeof eps === 'undefined') ?  0.0001 : eps;
      return (this.length() < eps);
    },

    toString: function() {
      return this._x + ',' + this._y;
    },

    toObject: function() {
      return { x: this._x, y: this._y };
    }

  };

  var xgs = {
    enumerable: true,
    get: function() {
      return this._x;
    },
    set: function(v) {
      this._x = v;
      this.trigger(Two.Events.change, 'x');
    }
  };

  var ygs = {
    enumerable: true,
    get: function() {
      return this._y;
    },
    set: function(v) {
      this._y = v;
      this.trigger(Two.Events.change, 'y');
    }
  };

  /**
   * Override Backbone bind / on in order to add properly broadcasting.
   * This allows Two.Vector to not broadcast events unless event listeners
   * are explicity bound to it.
   */

  Two.Vector.prototype.bind = Two.Vector.prototype.on = function() {

    if (!this._bound) {
      this._x = this.x;
      this._y = this.y;
      Object.defineProperty(this, 'x', xgs);
      Object.defineProperty(this, 'y', ygs);
      _.extend(this, BoundProto);
      this._bound = true; // Reserved for event initialization check
    }

    Two.Utils.Events.bind.apply(this, arguments);

    return this;

  };

})(this.Two);
<|endoftext|>


<commit_before>import 'angular';
import 'angular-aria';
import 'angular-i18n/nl-nl';
import 'angular-sanitize';
import 'imports-loader?angulartics!angulartics-piwik/src/angulartics-piwik';
import 'leaflet.markercluster';
import 'leaflet-draw';
import 'leaflet-rotatedmarker';
import 'objectFitPolyfill';

import Marzipano from 'marzipano/marzipano';
import 'imports-loader?d3!bbga_visualisatie_d3/bbga';
import * as d3 from 'd3';
import * as Redux from 'redux';
import marked from 'marked';

window.Marzipano = Marzipano;
window.d3 = d3;
window.Redux = Redux;
window.marked = marked;
<commit_msg>Add babel polyfills<commit_after>import 'babel-polyfill';
import 'angular';
import 'angular-aria';
import 'angular-i18n/nl-nl';
import 'angular-sanitize';
import 'imports-loader?angulartics!angulartics-piwik/src/angulartics-piwik';
import 'leaflet.markercluster';
import 'leaflet-draw';
import 'leaflet-rotatedmarker';
import 'objectFitPolyfill';

import Marzipano from 'marzipano/marzipano';
import 'imports-loader?d3!bbga_visualisatie_d3/bbga';
import * as d3 from 'd3';
import * as Redux from 'redux';
import marked from 'marked';

window.Marzipano = Marzipano;
window.d3 = d3;
window.Redux = Redux;
window.marked = marked;
<|endoftext|>


<commit_before>'use strict';

var meta = module.parent.require('./meta');
var user = module.parent.require('./user');

var db   = module.parent.require('./database'); // NodeBB / src / database 참고.
var au   = module.parent.require('./controllers/authentication'); // NodeBB / src / controllers 참고.

var winston = require('winston');
var jwt = require('jsonwebtoken');

var plugin = {};

plugin.init = function (params, callback)	{
	var mw = params.middleware;
	console.log('init');
	// console.log(arguments)
	// console.log(params, callback);
	// winston.add(winston.transports.File, {
	// 	level: 'debug',
	// 	json: false,
	// 	filename: 'my.log'
	// });

	// winston.info('This is info');
	// winston.error('This is error');
	callback();
};

plugin.loggedin = function (params, callback)	{
	console.log('normal console');

	// winston.info('winston logged in');
};

plugin.addMiddleware = function (req, res, next)	{
	jwt.verify(req.query.t, 'secret', function (err, result)	{
		if (err)	{
			return console.log('JWT Verify error: ', err);
		}
		console.log('JWT Verify result: ', result);
		var user_info = result,
			user_exist = db.getObjectField(user_info.institute_short + ':uid', user_info.id, function (data)	{
				console.log('User exist: ', data);
				return null;
			});

		if (user_exist)	{
			console.log('Already exist user');
		} else {
			user.create({
			username: user_info.name,
			id: user_info.id,
			email: user_info.id,
			institude_short: user_info.institute_short
			}, function (err, uid)	{
				if (err)	{
					return console.error('Create user error: ', err);
				}

				console.log('Create uid: ', uid);

				// db.setObjectField(user_info.institute_short + ':uid', 'id', uid);
			});
		}

		next();
	});

	// req.uid = 14;
	// au.doLogin(req, 14, next);
	// });

	// if (!isExist)	{
	// 	db.setObjectField(decoded.username, 'username', )
	// }

};

plugin.loggedOut = function (data, callback)	{
	// console.log(data);
	console.log('logged Out');
};

module.exports = plugin;<commit_msg>20170113094612<commit_after>'use strict';

var meta = module.parent.require('./meta');
var user = module.parent.require('./user');

var db   = module.parent.require('./database'); // NodeBB / src / database 참고.
var au   = module.parent.require('./controllers/authentication'); // NodeBB / src / controllers 참고.

var winston = require('winston');
var jwt = require('jsonwebtoken');

var plugin = {};

plugin.init = function (params, callback)	{
	var mw = params.middleware;
	console.log('init');
	// console.log(arguments)
	// console.log(params, callback);
	// winston.add(winston.transports.File, {
	// 	level: 'debug',
	// 	json: false,
	// 	filename: 'my.log'
	// });

	// winston.info('This is info');
	// winston.error('This is error');
	callback();
};

plugin.loggedin = function (params, callback)	{
	console.log('normal console');

	// winston.info('winston logged in');
};

plugin.addMiddleware = function (req, res, next)	{
	jwt.verify(req.query.t, 'secret', function (err, result)	{
		if (err)	{
			return console.log('JWT Verify error: ', err);
		}
		console.log('JWT Verify result: ', result);
		var user_info = result,
			user_exist = db.getObjectField(user_info.institute_short + ':uid', user_info.id, function (data)	{
				console.log('User exist: ', data);
				return data;
			});

		if (user_exist)	{
			console.log('Already exist user');
		} else {
			var test = user_info.id.replace('test', 'test101');

			user.create({
			username: user_info.name,
			id: test,
			email: test,
			institude_short: user_info.institute_short
			}, function (err, uid)	{
				if (err)	{
					return console.log('Create user error: ', err);
				}

				console.log('Create uid: ', uid);

				// db.setObjectField(user_info.institute_short + ':uid', 'id', uid);
			});
		}

		next();
	});

	// req.uid = 14;
	// au.doLogin(req, 14, next);
	// });

	// if (!isExist)	{
	// 	db.setObjectField(decoded.username, 'username', )
	// }

};

plugin.loggedOut = function (data, callback)	{
	// console.log(data);
	console.log('logged Out');
};

module.exports = plugin;<|endoftext|>


<commit_before>'use strict';

var NodeBB = module.parent;
var Settings = NodeBB.require("./settings");
var SocketAdmin = NodeBB.require('./socket.io/admin');

var controllers = require('./lib/controller');

var plugin = {};

var settings;
var camoUrl;
var loader;
var regex;

var defaultSettings = {
  host: "",
  key: "",
  type: "path",
  https: 0,
  useCamoProxy: 0,
  port: 8082
};

// Kill worker when nodebb closes/crashes. I have no idea if this is right.
process.on("uncaughtException", killWorker);
process.on("SIGINT", killWorker);
process.on("SIGHUP", killWorker);
process.on("SIGUSR2", killWorker);
process.on("SIGTERM", killWorker);

plugin.init = function(params, callback) {
  var router = params.router;
  var hostMiddleware = params.middleware;
  var hostControllers = params.controllers;

  settings = new Settings('camo', '1.0.0', defaultSettings, sync);

  router.get('/admin/plugins/camo', hostMiddleware.admin.buildHeader, controllers.renderAdminPage);
  router.get('/api/admin/plugins/camo', controllers.renderAdminPage);

  SocketAdmin.settings.syncCamo = function () {

    // Only reset the key if it was previously standalone.
    var wasStandalone = !settings.get('useCamoProxy');

    settings.sync(function(){
      if ((settings.get('useCamoProxy') && wasStandalone) || !settings.get('key')) {
        require('crypto').randomBytes(48, function(err, buf) {
          settings.set('key', buf.toString('base64').replace(/\//g, '='));
          settings.persist();
          sync();
        });
      }else{
        sync();
      }
    });
    console.log("Settings saved for Camo.");
  };

  function sync() {
    if (settings.get('https')) {
      regex = /<img[^>]+src=['"](http[^'"]+)['"][^>]*>/gi;
    } else {
      regex = /<img[^>]+src=['"](http[^s][^'"]+)['"][^>]*>/gi;
    }

    camoUrl = require('camo-url')({
      host: settings.get('host'),
      key: settings.get('key'),
      type: settings.get('type')
    });

    // Kill any previously started camo worker.
    killWorker();

    if (settings.get('useCamoProxy')) {
      console.log("Starting Camo worker...");
      var options = {silent: true, env: {
        'CAMO_KEY': settings.get('key'),
        'PORT': settings.get('port') || '8082'
      }};

      loader = require("child_process").fork(__dirname + '/server', [], options);
      loader.stdout.on('data', function (data) { console.log('CAMO PROXY SAYS: ' + data); });
      loader.stderr.on('data', function (data) {});
    }
  }

  callback();
};

plugin.addAdminNavigation = function(header, callback) {
  header.plugins.push({
    route: '/plugins/camo',
    icon: 'fa-image',
    name: 'Camo'
  });

  callback(null, header);
};

plugin.parseRaw = function(content, callback) {
  content = content.replace(regex, function (match, url) {
    return match.replace(url, camoUrl(url));
  });
  callback(null, content);
};

plugin.parsePost = function(data, callback) {
  plugin.parseRaw(data.postData.content, function(err, content){
    data.postData.content = content;
    callback(null, data);
  });
};

plugin.parseSignature = function(data, callback) {
  plugin.parseRaw(data.userData.signature, function(err, content){
    data.userData.signature = content;
    callback(null, data);
  });
};

plugin.reload = function (data, next) {
  killWorker();
  next();
};

function killWorker() {
  try {
    if (loader) {
      loader.kill('SIGHUP');
      console.log("Closed Camo worker.");
    }
  }catch(e){
  }
}

module.exports = plugin;
<commit_msg>I think this will work.<commit_after>'use strict';

var NodeBB = module.parent;
var Settings = NodeBB.require("./settings");
var SocketAdmin = NodeBB.require('./socket.io/admin');

var winston = require.main.require('winston');

var controllers = require('./lib/controller');

var plugin = {};

var settings;
var camoUrl;
var loader;
var regex;

var defaultSettings = {
  host: "",
  key: "",
  type: "path",
  https: 0,
  useCamoProxy: 0,
  port: 8082
};

var C = "[Camo]: ";
var CP = "[CamoProxy]: ";

// Kill worker when nodebb closes/crashes. I have no idea if this is right.
// TODO: Find an adult.
process.on("uncaughtException", killWorker);
process.on("SIGINT", killWorker);
process.on("SIGHUP", killWorker);
process.on("SIGUSR2", killWorker);
process.on("SIGTERM", killWorker);

plugin.init = function(params, callback) {
  var router = params.router;
  var hostMiddleware = params.middleware;
  var hostControllers = params.controllers;

  settings = new Settings('camo', '1.0.0', defaultSettings, sync);

  router.get('/admin/plugins/camo', hostMiddleware.admin.buildHeader, controllers.renderAdminPage);
  router.get('/api/admin/plugins/camo', controllers.renderAdminPage);

  SocketAdmin.settings.syncCamo = function () {

    // Only reset the key if it was previously standalone.
    var wasStandalone = !settings.get('useCamoProxy');

    settings.sync(function(){
      if ((settings.get('useCamoProxy') && wasStandalone) || !settings.get('key')) {
        require('crypto').randomBytes(48, function(err, buf) {
          settings.set('key', buf.toString('base64').replace(/\//g, '='));
          settings.persist();
          sync();
        });
      }else{
        sync();
      }
    });
    winston.info(C + "Settings saved.");
  };

  function sync() {
    if (settings.get('https')) {
      regex = /<img[^>]+src=['"](http[^'"]+)['"][^>]*>/gi;
    } else {
      regex = /<img[^>]+src=['"](http[^s][^'"]+)['"][^>]*>/gi;
    }

    camoUrl = require('camo-url')({
      host: settings.get('host'),
      key: settings.get('key'),
      type: settings.get('type')
    });

    // Kill any previously started camo worker.
    killWorker();

    if (settings.get('useCamoProxy')) {
      winston.info(C + "Starting Camo worker...");
      var options = {silent: true, env: {
        'CAMO_KEY': settings.get('key'),
        'PORT': settings.get('port') || '8082'
      }};

      loader = require("child_process").fork(__dirname + '/server', [], options);
      loader.stdout.on('data', function (data) { winston.info(CP + data); });
      loader.stderr.on('data', function (data) { winston.error(CP + data); });
    }
  }

  callback();
};

plugin.addAdminNavigation = function(header, callback) {
  header.plugins.push({
    route: '/plugins/camo',
    icon: 'fa-image',
    name: 'Camo'
  });

  callback(null, header);
};

plugin.parseRaw = function(content, callback) {
  content = content.replace(regex, function (match, url) {
    return match.replace(url, camoUrl(url));
  });
  callback(null, content);
};

plugin.parsePost = function(data, callback) {
  plugin.parseRaw(data.postData.content, function(err, content){
    data.postData.content = content;
    callback(null, data);
  });
};

plugin.parseSignature = function(data, callback) {
  plugin.parseRaw(data.userData.signature, function(err, content){
    data.userData.signature = content;
    callback(null, data);
  });
};

plugin.reload = function (data, next) {
  killWorker();
  next();
};

function killWorker() {
  try {
    if (loader) {
      loader.kill('SIGHUP');
      winston.info(C + "Closed Camo worker.");
    }
  }catch(e){
  }
}

module.exports = plugin;
<|endoftext|>