<commit_before>'use strict';

var DEFAULT_SETTINGS = {
        length: 20,
        repeat: 0,
        iteration: 8,
        lower: null,
        upper: null,
        number: null,
        dash: null,
        space: null,
        symbol: null,
        isVaultCompatible: true,
        useBrowserAction: false,

        autosend: false,
        servicename: 'prefix',
        defServicename: '',

        pwFieldList: [
            'pass', 'pass1', 'pass2', 'Pass', 'passwd', 'Passwd', 'password', 'Password', 'PASSWORD',
            'pw', 'PW', 'passwort', 'Passwort', 'ap_password', 'login_password', 'user_password',
            'user_pass', 'pwd', 'rpass', 'mypassword', 'myPassword', 'myregpassword'
        ],
        userFieldList: [
            'mail', 'Mail', 'email', 'Email', 'EMail', 'e-mail', 'E-Mail', 'eMail', 'login', 'Login',
            'user', 'User', 'username', 'Username', 'ap_email', 'userid', 'Userid', 'userId', 'UserId',
            'login_email', 'user_login', 'signin-email', 'j_username', 'session[username_or_email]'
        ],
        ccTldList: [
            'com', 'co', 'ar', 'net', 'org', 'jp', 'se', 'ae', 'me', 'plc', 'ac', 'ltd', 'gov', 'kids', 'us'
        ],

        serviceExceptions: {
            'alternate.de': {
                length: 15
            },
            'o2online.de': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.co.uk': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2online.ie': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.cz': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.sk': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'npmjs.org': {
                symbol: 0
            },
            'hosteurope.de': {
                length: 16,
                symbols: '!%&/()=*+#.,:;'
            },
            'wordpress.com': {
                symbols: '!%&()=*+#.,:;'
            },
            'zooplus.de': {
                length: 20,
                symbols: '!#$%&\'()*+,./=?[\\]^{}~'
            },
            'nodejitsu.com': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'check24.de': {
                length: 15
            },
            'kabeldeutschland.de': {
                space: 0
            },
            'unitymedia.de': {
                space: 0,
                symbols: '/+=]',
                dash: 0
            },
            'paket.de': {
                length: 13,
                space: 0,
                symbols: '!&/()=?*+'
            },
            'postpay.de': {
                length: 13,
                space: 0,
                symbols: '!&/()=?*+'
            },
            'adac.de': {
                space: 0,
                symbols: '#/*-+_'
            },
            'seedmatch.de': {
                space: 0
            }
        },

        imgUrl: 'images/close.png'
    },
    TYPES = 'lower upper number dash space symbol'.split(' '),
    UUID = '1e9632fa-e9b3-4a49-ab3b-e17256b83ff9';

var $ = function (selector) {
    var element = document.getElementById(selector);

    if (!element) {
        element = document.getElementsByName(selector)[0];
    }

    return element;
};

var on = function (element, event, listener) {
    if (!element) {
        return;
    }

    if ('string' === typeof event) {
        event = [event];
    }

    for (var i = 0, n = event.length; i < n; i++) {
        if (element.addEventListener) {
            element.addEventListener(event[i], listener, true);
        } else if (element.attachEvent) {
            element.attachEvent('on' + event[i], listener);
        } else {
            throw new Error('element not of type EventTarget');
        }
    }
};

/**
 * handles specific domain extensions
 */
var DomainService = {
    _domainName: '',
    _rules: null,
    _setPasswordRules: null,
    _setDomainname: null,
    getPasswordRules: null,
    getDomainname: null

};

DomainService._setDomainname = function _setDomainname(domain) {
    var domainname = domain || document.domain,
        domainparts = domainname.split('.');

    // if it's an IP we just skip the domain handling
    if (this._isIp4(domainparts)) {
console.log('this is an IP: ' + domainname);
        this._domainName = domainname;
        return;
    }

    if (2 < domainparts.length) {
        domainname = domainparts[domainparts.length - 2] + '.' + domainparts[domainparts.length - 1];

        if (Helper.isCcTld(domainparts[domainparts.length - 2])) {
            domainname = domainparts[domainparts.length - 3] + '.' + domainname;
        }
    }

    this._domainName = domainname;
};

DomainService._setPasswordRules = function _setPasswordRules(settings) {
    if (settings && settings[this._domainName]) {
        this._rules = settings[this._domainName];
    }
};

DomainService._isIp4 = function _isIp4(domainparts) {
    if (domainparts.length !== 4) {
        return false;
    }

    if (parseInt(domainparts[0]) <= 0 || parseInt(domainparts[3]) <= 0) {
        return false;
    }

    for (var i = 1, l = domainparts.length; i < l; i++) {
        if (parseInt(domainparts[i]) < 0 || parseInt(domainparts[i]) >= 255) {
            return false;
        }
    }
    return true;
};

DomainService.getDomainname = function getDomainname() {
    return this._domainName;
};

DomainService.getPasswordRules = function getPasswordRules() {
    return this._rules;
};

DomainService.init = function init(ruleSettings, domain) {
    this._setDomainname(domain);
    this._setPasswordRules(ruleSettings);

    return this;
};

/**
 * commonly used logic
 */
var Helper = {};

/**
 *
 * @param {Array} list
 *
 * @returns {*}
 */
Helper.getElementFromList = function (list) {
    var i, n, element;

    for (i = 0, n = list.length; i < n; i++) {
        element = $(list[i]);

        if (element) {
            return element;
        }
    }

    return null;
};

/**
 * checks if the given name is in the cctld list
 *
 * @param {String} name
 *
 * @returns {boolean}
 */
Helper.isCcTld = function (name) {
    var i, n;

    for (i = 0, n = DEFAULT_SETTINGS.ccTldList.length; i < n; i++) {
        if (name === DEFAULT_SETTINGS.ccTldList[i]) {
            return true;
        }
    }

    return false;
};

/**
 * fix problem if a password field id does exist more than once on a page
 *
 * @param {NodeList} nodeList
 */
Helper.fixDuplicateIds = function (nodeList) {
    var i, j, n = nodeList.length;

    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            if (nodeList[i].id === nodeList[j].id) {
                nodeList[j].id += '-' + Math.random().toString(16).substring(7);
            }
        }
    }
};

/**
 * check if given pwField is part of an overlay
 *
 * @param {Object} pwField
 *
 * @returns {Boolean}
 */
Helper.isOverlay = function (pwField) {
    // @todo this is easy password handler (overlay) only
    return pwField && pwField.id && pwField.id.match(/^easy-password-passphrase/);
};

/**
 * check if given pwField already has an overlay
 *
 * @param {Object} pwField
 *
 * @returns {Boolean}
 */
Helper.hasOverlay = function (pwField) {
    // @todo this is easy password handler (overlay) only
    return pwField && pwField.id && $(BASE_NAME + 'generator-overlay-' + pwField.id);
};

/**
 * cancel event bubbling and capturing
 *
 * @param {Object} event
 */
Helper.cancelEventPropagation = function (event) {
    if (event.stopImmediatePropagation) {
        // as long it is the first registered event: even captured events are stopped
        event.stopImmediatePropagation();
    }

    if (event.cancelBubble != null) {
        event.cancelBubble = true;
    }
};

/**
 * merges second object into first
 *
 * @param {Object} first
 * @param {Object} second
 *
 * @returns {Object}
 */
Helper.mergeObject = function (first, second) {
    var attrName;

    if (first && second) {
        for (attrName in second) {
            if (!second.hasOwnProperty(attrName)) {
                continue;
            }
            if ('object' === typeof first[attrName] && typeof second[attrName] === 'object') {
                first[attrName] = this.mergeObject(first[attrName], second[attrName]);
            } else {
                first[attrName] = second[attrName];
            }
        }
    }

    return first;
};

/**
 * gets the current password field's login form
 *
 * @param {Object} pwField
 *
 * @returns {Number|Boolean}
 */
Helper.getLoginForm = function (pwField) {
    for (var i = 0, n = document.forms.length; i < n; i++) {
        for (var o = 0, m = document.forms[i].length; o < m; o++) {
            if (pwField.id === document.forms[i][o].id) {
                return i;
            }
            if (pwField.name === document.forms[i][o].name) {
                return i;
            }
        }
    }

    return false;
};

/**
 * generates a (more or less) random servicename
 *
 * @returns {string}
 */
Helper.getRandomServicename = function () {
    return Math.random().toString(36).substring(7) + '@';
};

/**
 * get input type radio values
 *
 * @param {string} name
 * @returns {*}
 */
Helper.getRadio = function (name) {
    var inputs = document.getElementsByTagName('input'), input, i, n;

    for (i = 0, n = inputs.length; i < n; i++) {
        input = inputs[i];
        if (input.type === 'radio' && input.name === name && input.checked) {
            return input.value;
        }
    }

    return null;
};

/**
 * Set radio by name
 *
 * @param {String} name
 * @param {int} value
 */
Helper.setRadio = function (name, value) {
    var inputs = document.getElementsByTagName('input'), input, i, n;

    for (i = 0, n = inputs.length; i < n; i++) {
        input = inputs[i];
        if (input.type === 'radio' && input.name === name) {
            switch (input.value) {
                case 'required':
                    input.checked = (value && value > 0);
                    break;
                case 'allowed':
                    input.checked = (value === null);
                    break;
                case 'forbidden':
                    input.checked = (value === 0);
                    break;
            }
        }
    }
};

/**
 * Get current vault type settings
 *
 * @param {Object} settings
 * @param {int} requiredLength
 * @returns {Object}
 */
Helper.getTypeSettings = function (settings, requiredLength) {
    var i, n, value;

    for (i = 0, n = TYPES.length; i < n; i++) {
        value = this.getRadio(TYPES[i]);

        if (value === 'forbidden') {
            settings[TYPES[i]] = 0;
        } else if (value === 'required') {
            settings[TYPES[i]] = requiredLength;
        } else {
            settings[TYPES[i]] = null;
        }
    }

    return settings;
};

/**
 * set all vault radio types
 *
 * @param {Object} settings
 */
Helper.setTypeSettings = function (settings) {
    var i, n;

    for (i = 0, n = TYPES.length; i < n; i++) {
        Helper.setRadio(TYPES[i], settings[TYPES[i]]);
    }
};
<commit_msg>complete IP4 recognition<commit_after>'use strict';

var DEFAULT_SETTINGS = {
        length: 20,
        repeat: 0,
        iteration: 8,
        lower: null,
        upper: null,
        number: null,
        dash: null,
        space: null,
        symbol: null,
        isVaultCompatible: true,
        useBrowserAction: false,

        autosend: false,
        servicename: 'prefix',
        defServicename: '',

        pwFieldList: [
            'pass', 'pass1', 'pass2', 'Pass', 'passwd', 'Passwd', 'password', 'Password', 'PASSWORD',
            'pw', 'PW', 'passwort', 'Passwort', 'ap_password', 'login_password', 'user_password',
            'user_pass', 'pwd', 'rpass', 'mypassword', 'myPassword', 'myregpassword'
        ],
        userFieldList: [
            'mail', 'Mail', 'email', 'Email', 'EMail', 'e-mail', 'E-Mail', 'eMail', 'login', 'Login',
            'user', 'User', 'username', 'Username', 'ap_email', 'userid', 'Userid', 'userId', 'UserId',
            'login_email', 'user_login', 'signin-email', 'j_username', 'session[username_or_email]'
        ],
        ccTldList: [
            'com', 'co', 'ar', 'net', 'org', 'jp', 'se', 'ae', 'me', 'plc', 'ac', 'ltd', 'gov', 'kids', 'us'
        ],

        serviceExceptions: {
            'alternate.de': {
                length: 15
            },
            'o2online.de': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.co.uk': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2online.ie': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.cz': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.sk': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'npmjs.org': {
                symbol: 0
            },
            'hosteurope.de': {
                length: 16,
                symbols: '!%&/()=*+#.,:;'
            },
            'wordpress.com': {
                symbols: '!%&()=*+#.,:;'
            },
            'zooplus.de': {
                length: 20,
                symbols: '!#$%&\'()*+,./=?[\\]^{}~'
            },
            'nodejitsu.com': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'check24.de': {
                length: 15
            },
            'kabeldeutschland.de': {
                space: 0
            },
            'unitymedia.de': {
                space: 0,
                symbols: '/+=]',
                dash: 0
            },
            'paket.de': {
                length: 13,
                space: 0,
                symbols: '!&/()=?*+'
            },
            'postpay.de': {
                length: 13,
                space: 0,
                symbols: '!&/()=?*+'
            },
            'adac.de': {
                space: 0,
                symbols: '#/*-+_'
            },
            'seedmatch.de': {
                space: 0
            }
        },

        imgUrl: 'images/close.png'
    },
    TYPES = 'lower upper number dash space symbol'.split(' '),
    UUID = '1e9632fa-e9b3-4a49-ab3b-e17256b83ff9';

var $ = function (selector) {
    var element = document.getElementById(selector);

    if (!element) {
        element = document.getElementsByName(selector)[0];
    }

    return element;
};

var on = function (element, event, listener) {
    if (!element) {
        return;
    }

    if ('string' === typeof event) {
        event = [event];
    }

    for (var i = 0, n = event.length; i < n; i++) {
        if (element.addEventListener) {
            element.addEventListener(event[i], listener, true);
        } else if (element.attachEvent) {
            element.attachEvent('on' + event[i], listener);
        } else {
            throw new Error('element not of type EventTarget');
        }
    }
};

/**
 * handles specific domain extensions
 */
var DomainService = {
    _domainName: '',
    _rules: null,
    _setPasswordRules: null,
    _setDomainname: null,
    getPasswordRules: null,
    getDomainname: null

};

DomainService._setDomainname = function _setDomainname(domain) {
    var domainname = domain || document.domain,
        domainparts = domainname.split('.');

    // if it's an IP we just skip the domain handling
    if (this._isIp4(domainparts)) {
        this._domainName = domainname;
        return;
    }

    if (2 < domainparts.length) {
        domainname = domainparts[domainparts.length - 2] + '.' + domainparts[domainparts.length - 1];

        if (Helper.isCcTld(domainparts[domainparts.length - 2])) {
            domainname = domainparts[domainparts.length - 3] + '.' + domainname;
        }
    }

    this._domainName = domainname;
};

DomainService._setPasswordRules = function _setPasswordRules(settings) {
    if (settings && settings[this._domainName]) {
        this._rules = settings[this._domainName];
    }
};

DomainService._isIp4 = function _isIp4(domainparts) {
    if (domainparts.length !== 4) {
        return false;
    }

    if (parseInt(domainparts[0]) <= 0 || parseInt(domainparts[3]) <= 0) {
        return false;
    }

    for (var i = 1, l = domainparts.length; i < l; i++) {
        if (parseInt(domainparts[i]) < 0 || parseInt(domainparts[i]) >= 255) {
            return false;
        }
    }
    return true;
};

DomainService.getDomainname = function getDomainname() {
    return this._domainName;
};

DomainService.getPasswordRules = function getPasswordRules() {
    return this._rules;
};

DomainService.init = function init(ruleSettings, domain) {
    this._setDomainname(domain);
    this._setPasswordRules(ruleSettings);

    return this;
};

/**
 * commonly used logic
 */
var Helper = {};

/**
 *
 * @param {Array} list
 *
 * @returns {*}
 */
Helper.getElementFromList = function (list) {
    var i, n, element;

    for (i = 0, n = list.length; i < n; i++) {
        element = $(list[i]);

        if (element) {
            return element;
        }
    }

    return null;
};

/**
 * checks if the given name is in the cctld list
 *
 * @param {String} name
 *
 * @returns {boolean}
 */
Helper.isCcTld = function (name) {
    var i, n;

    for (i = 0, n = DEFAULT_SETTINGS.ccTldList.length; i < n; i++) {
        if (name === DEFAULT_SETTINGS.ccTldList[i]) {
            return true;
        }
    }

    return false;
};

/**
 * fix problem if a password field id does exist more than once on a page
 *
 * @param {NodeList} nodeList
 */
Helper.fixDuplicateIds = function (nodeList) {
    var i, j, n = nodeList.length;

    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            if (nodeList[i].id === nodeList[j].id) {
                nodeList[j].id += '-' + Math.random().toString(16).substring(7);
            }
        }
    }
};

/**
 * check if given pwField is part of an overlay
 *
 * @param {Object} pwField
 *
 * @returns {Boolean}
 */
Helper.isOverlay = function (pwField) {
    // @todo this is easy password handler (overlay) only
    return pwField && pwField.id && pwField.id.match(/^easy-password-passphrase/);
};

/**
 * check if given pwField already has an overlay
 *
 * @param {Object} pwField
 *
 * @returns {Boolean}
 */
Helper.hasOverlay = function (pwField) {
    // @todo this is easy password handler (overlay) only
    return pwField && pwField.id && $(BASE_NAME + 'generator-overlay-' + pwField.id);
};

/**
 * cancel event bubbling and capturing
 *
 * @param {Object} event
 */
Helper.cancelEventPropagation = function (event) {
    if (event.stopImmediatePropagation) {
        // as long it is the first registered event: even captured events are stopped
        event.stopImmediatePropagation();
    }

    if (event.cancelBubble != null) {
        event.cancelBubble = true;
    }
};

/**
 * merges second object into first
 *
 * @param {Object} first
 * @param {Object} second
 *
 * @returns {Object}
 */
Helper.mergeObject = function (first, second) {
    var attrName;

    if (first && second) {
        for (attrName in second) {
            if (!second.hasOwnProperty(attrName)) {
                continue;
            }
            if ('object' === typeof first[attrName] && typeof second[attrName] === 'object') {
                first[attrName] = this.mergeObject(first[attrName], second[attrName]);
            } else {
                first[attrName] = second[attrName];
            }
        }
    }

    return first;
};

/**
 * gets the current password field's login form
 *
 * @param {Object} pwField
 *
 * @returns {Number|Boolean}
 */
Helper.getLoginForm = function (pwField) {
    for (var i = 0, n = document.forms.length; i < n; i++) {
        for (var o = 0, m = document.forms[i].length; o < m; o++) {
            if (pwField.id === document.forms[i][o].id) {
                return i;
            }
            if (pwField.name === document.forms[i][o].name) {
                return i;
            }
        }
    }

    return false;
};

/**
 * generates a (more or less) random servicename
 *
 * @returns {string}
 */
Helper.getRandomServicename = function () {
    return Math.random().toString(36).substring(7) + '@';
};

/**
 * get input type radio values
 *
 * @param {string} name
 * @returns {*}
 */
Helper.getRadio = function (name) {
    var inputs = document.getElementsByTagName('input'), input, i, n;

    for (i = 0, n = inputs.length; i < n; i++) {
        input = inputs[i];
        if (input.type === 'radio' && input.name === name && input.checked) {
            return input.value;
        }
    }

    return null;
};

/**
 * Set radio by name
 *
 * @param {String} name
 * @param {int} value
 */
Helper.setRadio = function (name, value) {
    var inputs = document.getElementsByTagName('input'), input, i, n;

    for (i = 0, n = inputs.length; i < n; i++) {
        input = inputs[i];
        if (input.type === 'radio' && input.name === name) {
            switch (input.value) {
                case 'required':
                    input.checked = (value && value > 0);
                    break;
                case 'allowed':
                    input.checked = (value === null);
                    break;
                case 'forbidden':
                    input.checked = (value === 0);
                    break;
            }
        }
    }
};

/**
 * Get current vault type settings
 *
 * @param {Object} settings
 * @param {int} requiredLength
 * @returns {Object}
 */
Helper.getTypeSettings = function (settings, requiredLength) {
    var i, n, value;

    for (i = 0, n = TYPES.length; i < n; i++) {
        value = this.getRadio(TYPES[i]);

        if (value === 'forbidden') {
            settings[TYPES[i]] = 0;
        } else if (value === 'required') {
            settings[TYPES[i]] = requiredLength;
        } else {
            settings[TYPES[i]] = null;
        }
    }

    return settings;
};

/**
 * set all vault radio types
 *
 * @param {Object} settings
 */
Helper.setTypeSettings = function (settings) {
    var i, n;

    for (i = 0, n = TYPES.length; i < n; i++) {
        Helper.setRadio(TYPES[i], settings[TYPES[i]]);
    }
};
<|endoftext|>


<commit_before>'use strict';

var DEFAULT_SETTINGS = {
        length: 20,
        repeat: 0,
        iteration: 8,
        lower: null,
        upper: null,
        number: null,
        dash: null,
        space: null,
        symbol: null,
        isVaultCompatible: true,
        useBrowserAction: false,

        autosend: false,
        servicename: 'prefix',
        defServicename: '',

        pwFieldList: [
            'pass', 'pass1', 'pass2', 'Pass', 'passwd', 'Passwd', 'password', 'Password', 'PASSWORD',
            'pw', 'PW', 'passwort', 'Passwort', 'ap_password', 'login_password', 'user_password',
            'user_pass', 'pwd', 'rpass', 'mypassword', 'myPassword', 'myregpassword'
        ],
        userFieldList: [
            'mail', 'Mail', 'email', 'Email', 'EMail', 'e-mail', 'E-Mail', 'eMail', 'login', 'Login',
            'user', 'User', 'username', 'Username', 'ap_email', 'userid', 'Userid', 'userId', 'UserId',
            'login_email', 'user_login', 'signin-email', 'j_username', 'session[username_or_email]'
        ],
        ccTldList: [
            'com', 'co', 'ar', 'net', 'org', 'jp', 'se', 'ae', 'me', 'plc', 'ac', 'ltd', 'gov', 'kids', 'us'
        ],

        serviceExceptions: {
            'alternate.de': {
                length: 15
            },
            'o2online.de': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.co.uk': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2online.ie': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.cz': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.sk': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'npmjs.org': {
                symbol: 0
            },
            'hosteurope.de': {
                length: 16,
                symbols: '!%&/()=*+#.,:;'
            },
            'wordpress.com': {
                symbols: '!%&()=*+#.,:;'
            },
            'zooplus.de': {
                length: 20,
                symbols: '!#$%&\'()*+,./=?[\\]^{}~'
            },
            'nodejitsu.com': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'check24.de': {
                length: 15
            },
            'kabeldeutschland.de': {
                space: 0
            },
            'unitymedia.de': {
                space: 0,
                symbols: '/+=]',
                dash: 0
            },
            'paket.de': {
                length: 13,
                space: 0,
                symbols: '!&/()=?*+'
            },
            'postpay.de': {
                length: 13,
                space: 0,
                symbols: '!&/()=?*+'
            },
            'adac.de': {
                space: 0,
                symbols: '#/*-+_'
            },
            'seedmatch.de': {
                space: 0
            }
        },

        imgUrl: 'images/close.png'
    },
    TYPES = 'lower upper number dash space symbol'.split(' '),
    UUID = '1e9632fa-e9b3-4a49-ab3b-e17256b83ff9';

var $ = function (selector) {
    var element = document.getElementById(selector);

    if (!element) {
        element = document.getElementsByName(selector)[0];
    }

    return element;
};

var on = function (element, event, listener) {
    if (!element) {
        return;
    }

    if ('string' === typeof event) {
        event = [event];
    }

    for (var i = 0, n = event.length; i < n; i++) {
        if (element.addEventListener) {
            element.addEventListener(event[i], listener, true);
        } else if (element.attachEvent) {
            element.attachEvent('on' + event[i], listener);
        } else {
            throw new Error('element not of type EventTarget');
        }
    }
};

/**
 * handles specific domain extensions
 */
var DomainService = {
    _domainName: '',
    _rules: null,
    _setPasswordRules: null,
    _setDomainname: null,
    getPasswordRules: null,
    getDomainname: null

};

DomainService._setDomainname = function (domain) {
    var domainname = domain || document.domain,
        domainparts = domainname.split('.');

    if (2 < domainparts.length) {
        domainname = domainparts[domainparts.length - 2] + '.' + domainparts[domainparts.length - 1];

        if (Helper.isCcTld(domainparts[domainparts.length - 2])) {
            domainname = domainparts[domainparts.length - 3] + '.' + domainname;
        }
    }

    this._domainName = domainname;
};

DomainService._setPasswordRules = function (settings) {
    if (settings && settings[this._domainName]) {
        this._rules = settings[this._domainName];
    }
};

DomainService.getDomainname = function () {
    return this._domainName;
};

DomainService.getPasswordRules = function () {
    return this._rules;
};

DomainService.init = function (ruleSettings, domain) {
    this._setDomainname(domain);
    this._setPasswordRules(ruleSettings);

    return this;
};

/**
 * commonly used logic
 */
var Helper = {};

/**
 *
 * @param {Array} list
 *
 * @returns {*}
 */
Helper.getElementFromList = function (list) {
    var i, n, element;

    for (i = 0, n = list.length; i < n; i++) {
        element = $(list[i]);

        if (element) {
            return element;
        }
    }

    return null;
};

/**
 * checks if the given name is in the cctld list
 *
 * @param {String} name
 *
 * @returns {boolean}
 */
Helper.isCcTld = function (name) {
    var i, n;

    for (i = 0, n = DEFAULT_SETTINGS.ccTldList.length; i < n; i++) {
        if (name === DEFAULT_SETTINGS.ccTldList[i]) {
            return true;
        }
    }

    return false;
};

/**
 * fix problem if a password field id does exist more than once on a page
 *
 * @param {NodeList} nodeList
 */
Helper.fixDuplicateIds = function (nodeList) {
    var i, j, n = nodeList.length;

    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            if (nodeList[i].id === nodeList[j].id) {
                nodeList[j].id += '-' + Math.random().toString(16).substring(7);
            }
        }
    }
};

/**
 * check if given pwField is part of an overlay
 *
 * @param {Object} pwField
 *
 * @returns {Boolean}
 */
Helper.isOverlay = function (pwField) {
    // @todo this is easy password handler (overlay) only
    return pwField && pwField.id && pwField.id.match(/^easy-password-passphrase/);
};

/**
 * check if given pwField already has an overlay
 *
 * @param {Object} pwField
 *
 * @returns {Boolean}
 */
Helper.hasOverlay = function (pwField) {
    // @todo this is easy password handler (overlay) only
    return pwField && pwField.id && $(BASE_NAME + 'generator-overlay-' + pwField.id);
};

/**
 * cancel event bubbling and capturing
 *
 * @param {Object} event
 */
Helper.cancelEventPropagation = function (event) {
    if (event.stopImmediatePropagation) {
        // as long it is the first registered event: even captured events are stopped
        event.stopImmediatePropagation();
    }

    if (event.cancelBubble != null) {
        event.cancelBubble = true;
    }
};

/**
 * merges second object into first
 *
 * @param {Object} first
 * @param {Object} second
 *
 * @returns {Object}
 */
Helper.mergeObject = function (first, second) {
    var attrName;

    if (first && second) {
        for (attrName in second) {
            if (!second.hasOwnProperty(attrName)) {
                continue;
            }
            if ('object' === typeof first[attrName] && typeof second[attrName] === 'object') {
                first[attrName] = this.mergeObject(first[attrName], second[attrName]);
            } else {
                first[attrName] = second[attrName];
            }
        }
    }

    return first;
};

/**
 * gets the current password field's login form
 *
 * @param {Object} pwField
 *
 * @returns {Number|Boolean}
 */
Helper.getLoginForm = function (pwField) {
    for (var i = 0, n = document.forms.length; i < n; i++) {
        for (var o = 0, m = document.forms[i].length; o < m; o++) {
            if (pwField.id === document.forms[i][o].id) {
                return i;
            }
            if (pwField.name === document.forms[i][o].name) {
                return i;
            }
        }
    }

    return false;
};

/**
 * generates a (more or less) random servicename
 *
 * @returns {string}
 */
Helper.getRandomServicename = function () {
    return Math.random().toString(36).substring(7) + '@';
};

/**
 * get input type radio values
 *
 * @param {string} name
 * @returns {*}
 */
Helper.getRadio = function (name) {
    var inputs = document.getElementsByTagName('input'), input, i, n;

    for (i = 0, n = inputs.length; i < n; i++) {
        input = inputs[i];
        if (input.type === 'radio' && input.name === name && input.checked) {
            return input.value;
        }
    }

    return null;
};

/**
 * Set radio by name
 *
 * @param {String} name
 * @param {int} value
 */
Helper.setRadio = function (name, value) {
    var inputs = document.getElementsByTagName('input'), input, i, n;

    for (i = 0, n = inputs.length; i < n; i++) {
        input = inputs[i];
        if (input.type === 'radio' && input.name === name) {
            switch (input.value) {
                case 'required':
                    input.checked = (value && value > 0);
                    break;
                case 'allowed':
                    input.checked = (value === null);
                    break;
                case 'forbidden':
                    input.checked = (value === 0);
                    break;
            }
        }
    }
};

/**
 * Get current vault type settings
 *
 * @param {Object} settings
 * @param {int} requiredLength
 * @returns {Object}
 */
Helper.getTypeSettings = function (settings, requiredLength) {
    var i, n, value;

    for (i = 0, n = TYPES.length; i < n; i++) {
        value = this.getRadio(TYPES[i]);

        if (value === 'forbidden') {
            settings[TYPES[i]] = 0;
        } else if (value === 'required') {
            settings[TYPES[i]] = requiredLength;
        } else {
            settings[TYPES[i]] = null;
        }
    }

    return settings;
};

/**
 * set all vault radio types
 *
 * @param {Object} settings
 */
Helper.setTypeSettings = function (settings) {
    var i, n;

    for (i = 0, n = TYPES.length; i < n; i++) {
        Helper.setRadio(TYPES[i], settings[TYPES[i]]);
    }
};
<commit_msg>#28 add ip checking<commit_after>'use strict';

var DEFAULT_SETTINGS = {
        length: 20,
        repeat: 0,
        iteration: 8,
        lower: null,
        upper: null,
        number: null,
        dash: null,
        space: null,
        symbol: null,
        isVaultCompatible: true,
        useBrowserAction: false,

        autosend: false,
        servicename: 'prefix',
        defServicename: '',

        pwFieldList: [
            'pass', 'pass1', 'pass2', 'Pass', 'passwd', 'Passwd', 'password', 'Password', 'PASSWORD',
            'pw', 'PW', 'passwort', 'Passwort', 'ap_password', 'login_password', 'user_password',
            'user_pass', 'pwd', 'rpass', 'mypassword', 'myPassword', 'myregpassword'
        ],
        userFieldList: [
            'mail', 'Mail', 'email', 'Email', 'EMail', 'e-mail', 'E-Mail', 'eMail', 'login', 'Login',
            'user', 'User', 'username', 'Username', 'ap_email', 'userid', 'Userid', 'userId', 'UserId',
            'login_email', 'user_login', 'signin-email', 'j_username', 'session[username_or_email]'
        ],
        ccTldList: [
            'com', 'co', 'ar', 'net', 'org', 'jp', 'se', 'ae', 'me', 'plc', 'ac', 'ltd', 'gov', 'kids', 'us'
        ],

        serviceExceptions: {
            'alternate.de': {
                length: 15
            },
            'o2online.de': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.co.uk': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2online.ie': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.cz': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'o2.sk': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'npmjs.org': {
                symbol: 0
            },
            'hosteurope.de': {
                length: 16,
                symbols: '!%&/()=*+#.,:;'
            },
            'wordpress.com': {
                symbols: '!%&()=*+#.,:;'
            },
            'zooplus.de': {
                length: 20,
                symbols: '!#$%&\'()*+,./=?[\\]^{}~'
            },
            'nodejitsu.com': {
                space: 0,
                dash: 0,
                symbol: 0
            },
            'check24.de': {
                length: 15
            },
            'kabeldeutschland.de': {
                space: 0
            },
            'unitymedia.de': {
                space: 0,
                symbols: '/+=]',
                dash: 0
            },
            'paket.de': {
                length: 13,
                space: 0,
                symbols: '!&/()=?*+'
            },
            'postpay.de': {
                length: 13,
                space: 0,
                symbols: '!&/()=?*+'
            },
            'adac.de': {
                space: 0,
                symbols: '#/*-+_'
            },
            'seedmatch.de': {
                space: 0
            }
        },

        imgUrl: 'images/close.png'
    },
    TYPES = 'lower upper number dash space symbol'.split(' '),
    UUID = '1e9632fa-e9b3-4a49-ab3b-e17256b83ff9';

var $ = function (selector) {
    var element = document.getElementById(selector);

    if (!element) {
        element = document.getElementsByName(selector)[0];
    }

    return element;
};

var on = function (element, event, listener) {
    if (!element) {
        return;
    }

    if ('string' === typeof event) {
        event = [event];
    }

    for (var i = 0, n = event.length; i < n; i++) {
        if (element.addEventListener) {
            element.addEventListener(event[i], listener, true);
        } else if (element.attachEvent) {
            element.attachEvent('on' + event[i], listener);
        } else {
            throw new Error('element not of type EventTarget');
        }
    }
};

/**
 * handles specific domain extensions
 */
var DomainService = {
    _domainName: '',
    _rules: null,
    _setPasswordRules: null,
    _setDomainname: null,
    getPasswordRules: null,
    getDomainname: null

};

DomainService._setDomainname = function (domain) {
    var domainname = domain || document.domain,
        domainparts = domainname.split('.');

    // if it's an IP we just skip the domain handling
    if (this._isIp(domainparts)) {
        this._domainName = domainname;
console.log('this is an IP: ' + domainname);
        return;
    }

    if (2 < domainparts.length) {
        domainname = domainparts[domainparts.length - 2] + '.' + domainparts[domainparts.length - 1];

        if (Helper.isCcTld(domainparts[domainparts.length - 2])) {
            domainname = domainparts[domainparts.length - 3] + '.' + domainname;
        }
    }

    this._domainName = domainname;
};

DomainService._setPasswordRules = function _setPasswordRules(settings) {
    if (settings && settings[this._domainName]) {
        this._rules = settings[this._domainName];
    }
};

DomainService._isIp = function _isIp(domainparts) {
    if (domainparts.length !== 4) {
        return false;
    }

    for (var i = 0, l = domainparts.length; i < l; i++) {
        if (domainparts[i] <= 0 || domainparts[i] >= 255) {
            return false;
        }
    }
    return true;
};

DomainService.getDomainname = function () {
    return this._domainName;
};

DomainService.getPasswordRules = function () {
    return this._rules;
};

DomainService.init = function (ruleSettings, domain) {
    this._setDomainname(domain);
    this._setPasswordRules(ruleSettings);

    return this;
};

/**
 * commonly used logic
 */
var Helper = {};

/**
 *
 * @param {Array} list
 *
 * @returns {*}
 */
Helper.getElementFromList = function (list) {
    var i, n, element;

    for (i = 0, n = list.length; i < n; i++) {
        element = $(list[i]);

        if (element) {
            return element;
        }
    }

    return null;
};

/**
 * checks if the given name is in the cctld list
 *
 * @param {String} name
 *
 * @returns {boolean}
 */
Helper.isCcTld = function (name) {
    var i, n;

    for (i = 0, n = DEFAULT_SETTINGS.ccTldList.length; i < n; i++) {
        if (name === DEFAULT_SETTINGS.ccTldList[i]) {
            return true;
        }
    }

    return false;
};

/**
 * fix problem if a password field id does exist more than once on a page
 *
 * @param {NodeList} nodeList
 */
Helper.fixDuplicateIds = function (nodeList) {
    var i, j, n = nodeList.length;

    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            if (nodeList[i].id === nodeList[j].id) {
                nodeList[j].id += '-' + Math.random().toString(16).substring(7);
            }
        }
    }
};

/**
 * check if given pwField is part of an overlay
 *
 * @param {Object} pwField
 *
 * @returns {Boolean}
 */
Helper.isOverlay = function (pwField) {
    // @todo this is easy password handler (overlay) only
    return pwField && pwField.id && pwField.id.match(/^easy-password-passphrase/);
};

/**
 * check if given pwField already has an overlay
 *
 * @param {Object} pwField
 *
 * @returns {Boolean}
 */
Helper.hasOverlay = function (pwField) {
    // @todo this is easy password handler (overlay) only
    return pwField && pwField.id && $(BASE_NAME + 'generator-overlay-' + pwField.id);
};

/**
 * cancel event bubbling and capturing
 *
 * @param {Object} event
 */
Helper.cancelEventPropagation = function (event) {
    if (event.stopImmediatePropagation) {
        // as long it is the first registered event: even captured events are stopped
        event.stopImmediatePropagation();
    }

    if (event.cancelBubble != null) {
        event.cancelBubble = true;
    }
};

/**
 * merges second object into first
 *
 * @param {Object} first
 * @param {Object} second
 *
 * @returns {Object}
 */
Helper.mergeObject = function (first, second) {
    var attrName;

    if (first && second) {
        for (attrName in second) {
            if (!second.hasOwnProperty(attrName)) {
                continue;
            }
            if ('object' === typeof first[attrName] && typeof second[attrName] === 'object') {
                first[attrName] = this.mergeObject(first[attrName], second[attrName]);
            } else {
                first[attrName] = second[attrName];
            }
        }
    }

    return first;
};

/**
 * gets the current password field's login form
 *
 * @param {Object} pwField
 *
 * @returns {Number|Boolean}
 */
Helper.getLoginForm = function (pwField) {
    for (var i = 0, n = document.forms.length; i < n; i++) {
        for (var o = 0, m = document.forms[i].length; o < m; o++) {
            if (pwField.id === document.forms[i][o].id) {
                return i;
            }
            if (pwField.name === document.forms[i][o].name) {
                return i;
            }
        }
    }

    return false;
};

/**
 * generates a (more or less) random servicename
 *
 * @returns {string}
 */
Helper.getRandomServicename = function () {
    return Math.random().toString(36).substring(7) + '@';
};

/**
 * get input type radio values
 *
 * @param {string} name
 * @returns {*}
 */
Helper.getRadio = function (name) {
    var inputs = document.getElementsByTagName('input'), input, i, n;

    for (i = 0, n = inputs.length; i < n; i++) {
        input = inputs[i];
        if (input.type === 'radio' && input.name === name && input.checked) {
            return input.value;
        }
    }

    return null;
};

/**
 * Set radio by name
 *
 * @param {String} name
 * @param {int} value
 */
Helper.setRadio = function (name, value) {
    var inputs = document.getElementsByTagName('input'), input, i, n;

    for (i = 0, n = inputs.length; i < n; i++) {
        input = inputs[i];
        if (input.type === 'radio' && input.name === name) {
            switch (input.value) {
                case 'required':
                    input.checked = (value && value > 0);
                    break;
                case 'allowed':
                    input.checked = (value === null);
                    break;
                case 'forbidden':
                    input.checked = (value === 0);
                    break;
            }
        }
    }
};

/**
 * Get current vault type settings
 *
 * @param {Object} settings
 * @param {int} requiredLength
 * @returns {Object}
 */
Helper.getTypeSettings = function (settings, requiredLength) {
    var i, n, value;

    for (i = 0, n = TYPES.length; i < n; i++) {
        value = this.getRadio(TYPES[i]);

        if (value === 'forbidden') {
            settings[TYPES[i]] = 0;
        } else if (value === 'required') {
            settings[TYPES[i]] = requiredLength;
        } else {
            settings[TYPES[i]] = null;
        }
    }

    return settings;
};

/**
 * set all vault radio types
 *
 * @param {Object} settings
 */
Helper.setTypeSettings = function (settings) {
    var i, n;

    for (i = 0, n = TYPES.length; i < n; i++) {
        Helper.setRadio(TYPES[i], settings[TYPES[i]]);
    }
};
<|endoftext|>


<commit_before>var config = require('./config'),
    geogoose = require('./geogoose'),
    console = require('./ext-console'),
    mongoose = require('mongoose'),
    mongooseTypes = require("mongoose-types"),
    _ = require('cloneextend'),
    util = require('util');

var useTimestamps = function (schema, options) {
    schema.add({
        createdAt: Date
      , updatedAt: Date
    });
    schema.pre('save', function (next) {
      if (!this.createdAt) {
        this.createdAt = this.updatedAt = new Date;
      } else {
        this.updatedAt = new Date;
      }
      next();
    });
};

mongooseTypes.loadTypes(mongoose);
//useTimestamps = mongooseTypes.useTimestamps;

var User = mongoose.model('User', new mongoose.Schema({
    name: String,
    email: {type: mongoose.SchemaTypes.Email, required: true}
}));

User.schema.plugin(useTimestamps);

var Job = mongoose.model('Job', new mongoose.Schema({
    createdAt: Date,
    updatedAt: Date,
    type: {type: String, enum: [config.JobType.IMPORT, config.JobType.REDUCE], required: true},
    status: {type: String, enum: [config.JobStatus.ACTIVE, config.JobStatus.IDLE], required: true},
}));

Job.schema.plugin(useTimestamps);

var colorMatch = /^#([a-fA-F0-9]{2}){3}$/;

var LayerOptions = mongoose.model('LayerOptions', new mongoose.Schema({
    htmlRenderer: {type: String, required: false, default: "", enum: ["", "Canvas", "SVG"]},
    enabled: {type: Boolean, required: true, default: true},
    public: {type: Boolean, required: true, default: true},
    featureType: {type: String, required: true, enum: [
        config.FeatureType.POINTS, config.FeatureType.SQUARE_TILES, config.FeatureType.BUBBLES, config.FeatureType.SHAPES]},
    featureTypeFallback: {type: Boolean, default: true},
    colorType: {type: String, required: true, default: config.ColorType.LINEAR_GRADIENT},
    //colorPalettes: {type: [ColorPalette.schema], index: 1},
    colorSchemes: [{
        name: {type: String, required: true},
        colors: [{
            color: {type: String, required: true, match: colorMatch},
            position: {type: String, match: /^[0-9]+(\.[0-9]+)?%?$/},
            interpolation: {type: String, enum: ['lerpRGB', 'threshold', ''], required: false},
            label: String,
            description: String
    }]}],
    colorSchemeIndex: {type: Number, required: true, default: 0},
    colorLabelColor: {type: String, match: colorMatch},
    strokeColor: {type: String, match: colorMatch},
    reduction: String,
    opacity: {type: Number, required: true, min: 0, max: 1},
    strokeOpacity: {type: Number, min: 0, max: 1},
    strokeWidth: {type: Number, min: config.MIN_STROKE_WIDTH, max: config.MAX_STROKE_WIDTH},
    strokeDashstyle: {type: String},
    strokeLinecap: {type: String},
    attrMap: {
        featureSize: {type: String, enum: ['', '$numeric.avg', '$numeric.max', '$numeric.min', 'count']},
        featureColor: {type: String},
        numeric: {type: String},
        datetime: {type: String},
        label: {type: String},
    },
    featureSize: {type: Number, min: config.MIN_FEATURE_SIZE, max: config.MAX_FEATURE_SIZE},
    minFeatureSize: {type: Number, min: config.MIN_FEATURE_SIZE, max: config.MAX_FEATURE_SIZE},
    datetimeFormat: String,
    valFormat: [{
        unit: {type: String, required: true},
        eq: {type: String, required: true},
        formatString: String
    }],
    filterQuery: mongoose.Schema.Types.Mixed,
    queryOptions: mongoose.Schema.Types.Mixed,
    title: String,
    unit: String,
    description: String,
    histogram: {type: Boolean, default: true},
    itemTitle: String,
    itemTitlePlural: String,
    cropDistribution: Boolean,
    feed: {
        url: String, // e.g. http://search.twitter.com/search.json?q=%(query)s&rpp=100&geocode=%(centerY)s,%(centerX)s,%(radius)s
        refreshInterval: Number,
        parser: String
    }
}));

LayerOptions.schema.path('colorSchemes').validate(function (value) {
    return value.length > 0 && value[0].colors && value[0].colors.length > 0;
}, 'At least one color scheme is required.');

var MapLayerSchema = new mongoose.Schema({
    featureCollection: { type: mongoose.Schema.ObjectId, ref: 'GeoFeatureCollection', index: 1 },
    layerOptions: { type: mongoose.Schema.ObjectId, ref: 'LayerOptions', index: 1 },
    position: Number
});

var Map = mongoose.model('Map', new mongoose.Schema({
    active: {type: Boolean, default: true},
    title: {type: String, required: true},
    description: String,
    author: String,
    linkURL: String,
    linkTitle: String,
    twitter: String,
    displayInfo: Boolean,
    adminslug: {type: String, required: true, index: {unique: true}},
    publicslug: {type: String, required: true, index: {unique: true}},
    host: {type: String, required: false, index: {unique: true, sparse: true}},
    featured: {type: Number, default: 0},
    initialArea: {
        center: [Number, Number],
        zoom: Number
    },
    viewOptions: {
        viewName: String,
        viewBase: String,
        viewStyle: String
    },
    // TODO: Enforce privacy (currently unused because no user login required)
    status: {type: String, enum: [config.MapStatus.PRIVATE, config.MapStatus.PUBLIC], required: true, default: config.MapStatus.PUBLIC},
    layers: [MapLayerSchema],
    createdBy: { type: mongoose.Schema.ObjectId, ref: 'User', index: 1 },
    modifiedBy: { type: mongoose.Schema.ObjectId, ref: 'User', index: 1 },
    createdAt: Date,
    updatedAt: Date,
    tour: {
        steps: [{
        layers: [Number],
        title: String,
        body: String
        }]
    }
}));

Map.schema.plugin(useTimestamps);

var GeoFeatureSchema = new geogoose.models.GeoFeatureSchema({
    geocoded: {type: Boolean, default: false, required: true},
    incrementor: mongoose.Schema.Types.Mixed,
    source: mongoose.Schema.Types.Mixed,
    count: Number
});

GeoFeatureSchema.plugin(useTimestamps);

GeoFeatureSchema.pre('save', function(next) {
    this.geocoded = this.bounds2d && this.bounds2d.length;
    next();
});

var GeoFeatureMapReducedSchema = new geogoose.models.GeoFeatureSchema({_id: String}, null, null, null, {
    value: geogoose.models.geoJSONFeatureDefinition
});

GeoFeatureMapReducedSchema.methods.toGeoJSON = function(extraAttrs)
{
    var obj = this.toJSON().value;
    obj._id = this.get('_id').toString();
    if (extraAttrs) obj = _.extend(obj, extraAttrs);
    return geogoose.util.toGeoJSON(obj);
};

var GeoFeatureCollectionSchema = new geogoose.models.GeoFeatureCollectionSchema({
    title: String,
    description: String,
    source: String,
    unit: String,
    sourceFieldNames: {type: Array, default: []},
    fields: {type: Array},
    extremes: { type: mongoose.Schema.Types.Mixed, index: 1, default: {} },
    importParams: mongoose.Schema.Types.Mixed,
    gridSize: Number,
    defaults: { type: mongoose.Schema.ObjectId, ref: 'LayerOptions', index: 1 },
    active: Boolean,
    status: String,
    progress: Number,
    numBusy: Number,
    tile: String,
    limitFeatures: {type: Boolean},
    maxReduceZoom: Number,
    sync: Boolean,
    cropDistribution: Boolean,
    createdBy: { type: mongoose.Schema.ObjectId, ref: 'User', index: 1 },
    modifiedBy: { type: mongoose.Schema.ObjectId, ref: 'User', index: 1 },
    createdAt: Date,
    updatedAt: Date,
    lastReducedAt: Date,
}, {FeatureSchema: GeoFeatureSchema});

GeoFeatureCollectionSchema.plugin(useTimestamps);

GeoFeatureCollectionSchema.methods.getMapReducedFeatureModel = function(opts) {
    var collectionName =
        'r_'
        + this.getFeatureModel().collection.name
        + (opts.tileSize != undefined ? '_tile_rect_' + opts.tileSize : '')
        + (opts.timeGrid != undefined ? '_' + opts.timeGrid : '');
    return this.getFeatureModel({collectionName: collectionName, schema: GeoFeatureMapReducedSchema});
};

cloneLayerOptionsDefaults = function(featureCollection, callback)
{
    if (!featureCollection || !featureCollection.defaults) {
        return new LayerOptions(config.LAYER_OPTIONS_DEFAULTS).save(callback);
    }
    LayerOptions.findById(featureCollection.defaults, function(err, defaults) {
        if (err) {
            callback(err);
            return;
        }
        clone = defaults.toObject();
        delete clone._id;
        return new LayerOptions(clone).save(callback);
    });
};

var GeoFeatureCollection = mongoose.model('GeoFeatureCollection', GeoFeatureCollectionSchema);

module.exports = {
    User: User,
    Job: Job,
    LayerOptions: LayerOptions,
    Map: Map,
    GeoFeatureCollection: GeoFeatureCollection,
    adHocModel: geogoose.util.adHocModel,
    cloneLayerOptionsDefaults: cloneLayerOptionsDefaults
};

<commit_msg>Added index for createdAt/updatedAt<commit_after>var config = require('./config'),
    geogoose = require('./geogoose'),
    console = require('./ext-console'),
    mongoose = require('mongoose'),
    mongooseTypes = require("mongoose-types"),
    _ = require('cloneextend'),
    util = require('util');

var useTimestamps = function (schema, options) {
    schema.add({
        createdAt: {type: Date, index: 1},
        updatedAt: {type: Date, index: 1}
    });
    schema.pre('save', function (next) {
      if (!this.createdAt) {
        this.createdAt = this.updatedAt = new Date;
      } else {
        this.updatedAt = new Date;
      }
      next();
    });
};

mongooseTypes.loadTypes(mongoose);
//useTimestamps = mongooseTypes.useTimestamps;

var User = mongoose.model('User', new mongoose.Schema({
    name: String,
    email: {type: mongoose.SchemaTypes.Email, required: true}
}));

User.schema.plugin(useTimestamps);

var Job = mongoose.model('Job', new mongoose.Schema({
    createdAt: Date,
    updatedAt: Date,
    type: {type: String, enum: [config.JobType.IMPORT, config.JobType.REDUCE], required: true},
    status: {type: String, enum: [config.JobStatus.ACTIVE, config.JobStatus.IDLE], required: true},
}));

Job.schema.plugin(useTimestamps);

var colorMatch = /^#([a-fA-F0-9]{2}){3}$/;

var LayerOptions = mongoose.model('LayerOptions', new mongoose.Schema({
    htmlRenderer: {type: String, required: false, default: "", enum: ["", "Canvas", "SVG"]},
    enabled: {type: Boolean, required: true, default: true},
    public: {type: Boolean, required: true, default: true},
    featureType: {type: String, required: true, enum: [
        config.FeatureType.POINTS, config.FeatureType.SQUARE_TILES, config.FeatureType.BUBBLES, config.FeatureType.SHAPES]},
    featureTypeFallback: {type: Boolean, default: true},
    colorType: {type: String, required: true, default: config.ColorType.LINEAR_GRADIENT},
    //colorPalettes: {type: [ColorPalette.schema], index: 1},
    colorSchemes: [{
        name: {type: String, required: true},
        colors: [{
            color: {type: String, required: true, match: colorMatch},
            position: {type: String, match: /^[0-9]+(\.[0-9]+)?%?$/},
            interpolation: {type: String, enum: ['lerpRGB', 'threshold', ''], required: false},
            label: String,
            description: String
    }]}],
    colorSchemeIndex: {type: Number, required: true, default: 0},
    colorLabelColor: {type: String, match: colorMatch},
    strokeColor: {type: String, match: colorMatch},
    reduction: String,
    opacity: {type: Number, required: true, min: 0, max: 1},
    strokeOpacity: {type: Number, min: 0, max: 1},
    strokeWidth: {type: Number, min: config.MIN_STROKE_WIDTH, max: config.MAX_STROKE_WIDTH},
    strokeDashstyle: {type: String},
    strokeLinecap: {type: String},
    attrMap: {
        featureSize: {type: String, enum: ['', '$numeric.avg', '$numeric.max', '$numeric.min', 'count']},
        featureColor: {type: String},
        numeric: {type: String},
        datetime: {type: String},
        label: {type: String},
    },
    featureSize: {type: Number, min: config.MIN_FEATURE_SIZE, max: config.MAX_FEATURE_SIZE},
    minFeatureSize: {type: Number, min: config.MIN_FEATURE_SIZE, max: config.MAX_FEATURE_SIZE},
    datetimeFormat: String,
    valFormat: [{
        unit: {type: String, required: true},
        eq: {type: String, required: true},
        formatString: String
    }],
    filterQuery: mongoose.Schema.Types.Mixed,
    queryOptions: mongoose.Schema.Types.Mixed,
    title: String,
    unit: String,
    description: String,
    histogram: {type: Boolean, default: true},
    itemTitle: String,
    itemTitlePlural: String,
    cropDistribution: Boolean,
    feed: {
        url: String, // e.g. http://search.twitter.com/search.json?q=%(query)s&rpp=100&geocode=%(centerY)s,%(centerX)s,%(radius)s
        refreshInterval: Number,
        parser: String
    }
}));

LayerOptions.schema.path('colorSchemes').validate(function (value) {
    return value.length > 0 && value[0].colors && value[0].colors.length > 0;
}, 'At least one color scheme is required.');

var MapLayerSchema = new mongoose.Schema({
    featureCollection: { type: mongoose.Schema.ObjectId, ref: 'GeoFeatureCollection', index: 1 },
    layerOptions: { type: mongoose.Schema.ObjectId, ref: 'LayerOptions', index: 1 },
    position: Number
});

var Map = mongoose.model('Map', new mongoose.Schema({
    active: {type: Boolean, default: true},
    title: {type: String, required: true},
    description: String,
    author: String,
    linkURL: String,
    linkTitle: String,
    twitter: String,
    displayInfo: Boolean,
    adminslug: {type: String, required: true, index: {unique: true}},
    publicslug: {type: String, required: true, index: {unique: true}},
    host: {type: String, required: false, index: {unique: true, sparse: true}},
    featured: {type: Number, default: 0},
    initialArea: {
        center: [Number, Number],
        zoom: Number
    },
    viewOptions: {
        viewName: String,
        viewBase: String,
        viewStyle: String
    },
    // TODO: Enforce privacy (currently unused because no user login required)
    status: {type: String, enum: [config.MapStatus.PRIVATE, config.MapStatus.PUBLIC], required: true, default: config.MapStatus.PUBLIC},
    layers: [MapLayerSchema],
    createdBy: { type: mongoose.Schema.ObjectId, ref: 'User', index: 1 },
    modifiedBy: { type: mongoose.Schema.ObjectId, ref: 'User', index: 1 },
    createdAt: Date,
    updatedAt: Date,
    tour: {
        steps: [{
        layers: [Number],
        title: String,
        body: String
        }]
    }
}));

Map.schema.plugin(useTimestamps);

var GeoFeatureSchema = new geogoose.models.GeoFeatureSchema({
    geocoded: {type: Boolean, default: false, required: true},
    incrementor: mongoose.Schema.Types.Mixed,
    source: mongoose.Schema.Types.Mixed,
    count: Number
});

GeoFeatureSchema.plugin(useTimestamps);

GeoFeatureSchema.pre('save', function(next) {
    this.geocoded = this.bounds2d && this.bounds2d.length;
    next();
});

var GeoFeatureMapReducedSchema = new geogoose.models.GeoFeatureSchema({_id: String}, null, null, null, {
    value: geogoose.models.geoJSONFeatureDefinition
});

GeoFeatureMapReducedSchema.methods.toGeoJSON = function(extraAttrs)
{
    var obj = this.toJSON().value;
    obj._id = this.get('_id').toString();
    if (extraAttrs) obj = _.extend(obj, extraAttrs);
    return geogoose.util.toGeoJSON(obj);
};

var GeoFeatureCollectionSchema = new geogoose.models.GeoFeatureCollectionSchema({
    title: String,
    description: String,
    source: String,
    unit: String,
    sourceFieldNames: {type: Array, default: []},
    fields: {type: Array},
    extremes: { type: mongoose.Schema.Types.Mixed, index: 1, default: {} },
    importParams: mongoose.Schema.Types.Mixed,
    gridSize: Number,
    defaults: { type: mongoose.Schema.ObjectId, ref: 'LayerOptions', index: 1 },
    active: Boolean,
    status: String,
    progress: Number,
    numBusy: Number,
    tile: String,
    limitFeatures: {type: Boolean},
    maxReduceZoom: Number,
    sync: Boolean,
    cropDistribution: Boolean,
    createdBy: { type: mongoose.Schema.ObjectId, ref: 'User', index: 1 },
    modifiedBy: { type: mongoose.Schema.ObjectId, ref: 'User', index: 1 },
    createdAt: Date,
    updatedAt: Date,
    lastReducedAt: Date,
}, {FeatureSchema: GeoFeatureSchema});

GeoFeatureCollectionSchema.plugin(useTimestamps);

GeoFeatureCollectionSchema.methods.getMapReducedFeatureModel = function(opts) {
    var collectionName =
        'r_'
        + this.getFeatureModel().collection.name
        + (opts.tileSize != undefined ? '_tile_rect_' + opts.tileSize : '')
        + (opts.timeGrid != undefined ? '_' + opts.timeGrid : '');
    return this.getFeatureModel({collectionName: collectionName, schema: GeoFeatureMapReducedSchema});
};

cloneLayerOptionsDefaults = function(featureCollection, callback)
{
    if (!featureCollection || !featureCollection.defaults) {
        return new LayerOptions(config.LAYER_OPTIONS_DEFAULTS).save(callback);
    }
    LayerOptions.findById(featureCollection.defaults, function(err, defaults) {
        if (err) {
            callback(err);
            return;
        }
        clone = defaults.toObject();
        delete clone._id;
        return new LayerOptions(clone).save(callback);
    });
};

var GeoFeatureCollection = mongoose.model('GeoFeatureCollection', GeoFeatureCollectionSchema);

module.exports = {
    User: User,
    Job: Job,
    LayerOptions: LayerOptions,
    Map: Map,
    GeoFeatureCollection: GeoFeatureCollection,
    adHocModel: geogoose.util.adHocModel,
    cloneLayerOptionsDefaults: cloneLayerOptionsDefaults
};

<|endoftext|>


<commit_before>var models = module.exports = [
require('./models/tradle.APIBasedVerificationMethod_Wealth.json'),
require('./models/tradle.API_Wealth.json'),
require('./models/tradle.AboutYou.json'),
require('./models/tradle.ActivityLicense_Estonia.json'),
require('./models/tradle.AdditionalInfo.json'),
require('./models/tradle.AddressType_Rabo_wholesale.json'),
require('./models/tradle.Address_Wealth.json'),
require('./models/tradle.AllowanceAppForNonProfitOrg_Estonia.json'),
require('./models/tradle.AppState.json'),
require('./models/tradle.ApplicationForEResidency_Estonia.json'),
require('./models/tradle.ApplicationSubmitted.json'),
require('./models/tradle.ArtworkInfo.json'),
require('./models/tradle.Aspect.json'),
require('./models/tradle.BasicContactInfo.json'),
require('./models/tradle.BetaTesterContactInfo.json'),
require('./models/tradle.BusinessAccount.json'),
require('./models/tradle.BusinessInformation.json'),
require('./models/tradle.CVItem.json'),
require('./models/tradle.CancelAccount_Estonia.json'),
require('./models/tradle.Collateral_Obvion.json'),
require('./models/tradle.CollaterizedLoan_SG.json'),
require('./models/tradle.CommercialProduct_Obvion.json'),
require('./models/tradle.CompanyInformation_LM.json'),
require('./models/tradle.CompanyOwners_LM.json'),
require('./models/tradle.CompanyRegistration_Estonia.json'),
require('./models/tradle.ConfirmPackageRequest.json'),
require('./models/tradle.ContactInformation_Estonia.json'),
require('./models/tradle.ContractType_Obvion.json'),
require('./models/tradle.CorporateAccount_Rabo_Wholesale.json'),
require('./models/tradle.Country.json'),
require('./models/tradle.CoverholderApproval_LM.json'),
require('./models/tradle.CreditCards.json'),
require('./models/tradle.Currency.json'),
require('./models/tradle.CurrentAccount.json'),
require('./models/tradle.CustomerEntity_Rabo_Wholesale.json'),
require('./models/tradle.CustomerInfo_Rabo_Wholesale.json'),
require('./models/tradle.CustomerOwnership_Rabo_Wholesale.json'),
require('./models/tradle.CustomerProfile_Rabo_Wholesale.json'),
require('./models/tradle.CustomerWaiting.json'),
require('./models/tradle.DebtKind_Obvion.json'),
require('./models/tradle.Document.json'),
require('./models/tradle.DriverLicense.json'),
require('./models/tradle.EResidencyApplicationType_Estonia.json'),
require('./models/tradle.EResidency_Estonia.json'),
require('./models/tradle.E_ResidencyMotivation_Estonia.json'),
require('./models/tradle.EarthworkApplication_Estonia.json'),
require('./models/tradle.EducationNL.json'),
require('./models/tradle.EmployeeOnboarding.json'),
require('./models/tradle.EnergyLabel.json'),
require('./models/tradle.Enum.json'),
require('./models/tradle.Exchange_Rabo_wholesale.json'),
require('./models/tradle.ExemptStatus_Rabo_wholesale.json'),
require('./models/tradle.File.json'),
require('./models/tradle.FinancialProduct.json'),
require('./models/tradle.Financials_LM.json'),
require('./models/tradle.FineArtInsurance.json'),
require('./models/tradle.ForestNotice_Estonia.json'),
require('./models/tradle.ForgetMe.json'),
require('./models/tradle.ForgotYou.json'),
require('./models/tradle.Form.json'),
require('./models/tradle.FormError.json'),
require('./models/tradle.FormRequest.json'),
require('./models/tradle.FormationType_Rabo_wholesale.json'),
require('./models/tradle.GovernmentIdType_Rabo_wholesale.json'),
require('./models/tradle.GuestSessionProof.json'),
require('./models/tradle.HealthInsurance.json'),
require('./models/tradle.HomeImprovement.json'),
require('./models/tradle.HomeInsurance.json'),
require('./models/tradle.HowToFund.json'),
require('./models/tradle.IDType.json'),
require('./models/tradle.ISAs.json'),
require('./models/tradle.IdentificationDetail_Estonia.json'),
require('./models/tradle.Identity.json'),
require('./models/tradle.IdentityDocumentType_Estonia.json'),
require('./models/tradle.IdentityPublishRequest.json'),
require('./models/tradle.IncomeProtectionInsurance.json'),
require('./models/tradle.Income_Obvion.json'),
require('./models/tradle.IndividualOwners_LM.json'),
require('./models/tradle.InsuranceInfo_ObvionAchmea.json'),
require('./models/tradle.InterestType_Obvion.json'),
require('./models/tradle.InternalInfo_Rabo_Wholesale.json'),
require('./models/tradle.Introduction.json'),
require('./models/tradle.Item.json'),
require('./models/tradle.KeyStaff_LM.json'),
require('./models/tradle.KindOfConstruction.json'),
require('./models/tradle.KindOfEngagement.json'),
require('./models/tradle.KindOfHouse.json'),
require('./models/tradle.KindOfInsurance.json'),
require('./models/tradle.KindOfObligation.json'),
require('./models/tradle.Language.json'),
require('./models/tradle.Licences_LM.json'),
require('./models/tradle.LifeInsurance.json'),
require('./models/tradle.LifeInsurance_ORV_Achmea.json'),
require('./models/tradle.LoanDetail_SG.json'),
require('./models/tradle.LoanPart_Obvion.json'),
require('./models/tradle.LoanTypes_Obvion.json'),
require('./models/tradle.Location_Estonia.json'),
require('./models/tradle.MaritalStatus.json'),
require('./models/tradle.MediaSnippet.json'),
require('./models/tradle.MerkleLeaf.json'),
require('./models/tradle.MerkleNode.json'),
require('./models/tradle.Message.json'),
require('./models/tradle.Method.json'),
require('./models/tradle.Money.json'),
require('./models/tradle.Mortgage.json'),
require('./models/tradle.MortgageDetail_Obvion.json'),
require('./models/tradle.MortgageGuarantee_Obvion.json'),
require('./models/tradle.MortgageLoanDetail.json'),
require('./models/tradle.MortgageProduct.json'),
require('./models/tradle.MyCoverholderApproval.json'),
require('./models/tradle.MyEmployeePass.json'),
require('./models/tradle.MyFineArtInsurance.json'),
require('./models/tradle.MyIdentities.json'),
require('./models/tradle.MyLifeInsurance.json'),
require('./models/tradle.MyMortgage.json'),
require('./models/tradle.MyProduct.json'),
require('./models/tradle.MyTaxesFiledConfirmation.json'),
require('./models/tradle.MyWealthManagementAccount.json'),
require('./models/tradle.Nationality.json'),
require('./models/tradle.NewMessageModel.json'),
require('./models/tradle.NextFormRequest.json'),
require('./models/tradle.NotarizePowerOfAttorney_SG.json'),
require('./models/tradle.NotarizePropertyOwnership_SG.json'),
require('./models/tradle.ObligationsDebts_Obvion.json'),
require('./models/tradle.Organization.json'),
require('./models/tradle.OtherCollaterals_Obvion.json'),
require('./models/tradle.OwnershipStructure_Rabo_wholesale.json'),
require('./models/tradle.PairingData.json'),
require('./models/tradle.PairingRequest.json'),
require('./models/tradle.PairingResponse.json'),
require('./models/tradle.Partial.json'),
require('./models/tradle.Passport.json'),
require('./models/tradle.PassportVerification.json'),
require('./models/tradle.PaymentPeriod.json'),
require('./models/tradle.Pension.json'),
require('./models/tradle.PersonalInfo_ObvionAchmea.json'),
require('./models/tradle.Phone.json'),
require('./models/tradle.PhoneBill.json'),
require('./models/tradle.PhoneTypes.json'),
require('./models/tradle.Photo.json'),
require('./models/tradle.PhotoID.json'),
require('./models/tradle.Posessions_Obvion.json'),
require('./models/tradle.ProductApplication.json'),
require('./models/tradle.ProductList.json'),
require('./models/tradle.ProfessionalIndemnity_LM.json'),
require('./models/tradle.Profile.json'),
require('./models/tradle.ProjectApplication_Estonia.json'),
require('./models/tradle.PropertyInformation.json'),
require('./models/tradle.PropertyOwnership_SG.json'),
require('./models/tradle.PropertyType.json'),
require('./models/tradle.PropertyTypes.json'),
require('./models/tradle.PurposeOfMortgageLoan.json'),
require('./models/tradle.PurposeOfTheAccount.json'),
require('./models/tradle.ReasonForApplication_Estonia.json'),
require('./models/tradle.Refinancing.json'),
require('./models/tradle.Regulator_Rabo_wholesale.json'),
require('./models/tradle.Remediation.json'),
require('./models/tradle.RemediationSimpleMessage.json'),
require('./models/tradle.RepaymentType_Obvion.json'),
require('./models/tradle.ReportOfNonProfitOrgAllowanceUsage_Estonia.json'),
require('./models/tradle.RequestForRepresentative.json'),
require('./models/tradle.Residence.json'),
require('./models/tradle.ResidenceType.json'),
require('./models/tradle.ResidentialStatus.json'),
require('./models/tradle.SSN_Obvion.json'),
require('./models/tradle.SalaryVerification.json'),
require('./models/tradle.SalesData.json'),
require('./models/tradle.SecurityCode.json'),
require('./models/tradle.SelfIntroduction.json'),
require('./models/tradle.Selfie.json'),
require('./models/tradle.ServiceProvider.json'),
require('./models/tradle.Settings.json'),
require('./models/tradle.Sex_Estonia.json'),
require('./models/tradle.ShareContext.json'),
require('./models/tradle.SharedResource.json'),
require('./models/tradle.SimpleMessage.json'),
require('./models/tradle.SkillVerification.json'),
require('./models/tradle.SourceOfIncome.json'),
require('./models/tradle.StateOfInsurance.json'),
require('./models/tradle.TaxesFiledConfirmation.json'),
require('./models/tradle.TaxesFiledConfirmationForm.json'),
require('./models/tradle.TermInsurance.json'),
require('./models/tradle.TermsAndConditions.json'),
require('./models/tradle.Terms_Obvion.json'),
require('./models/tradle.TypeOfApplication_Estonia.json'),
require('./models/tradle.TypeOfCoverage_Achmea.json'),
require('./models/tradle.UtilityBillVerification.json'),
require('./models/tradle.Verifiable.json'),
require('./models/tradle.Verification.json'),
require('./models/tradle.VerifiedItem.json'),
require('./models/tradle.Visa.json'),
require('./models/tradle.VisualVerificationMethod_Wealth.json'),
require('./models/tradle.WMP.json'),
require('./models/tradle.WealthCV.json'),
require('./models/tradle.WealthItemType.json'),
require('./models/tradle.WealthManagementAccount.json'),
require('./models/tradle.WebSite.json'),
require('./models/tradle.WellDrilling_Estonia.json'),
require('./models/tradle.YourBalance.json'),
require('./models/tradle.YourMoney.json')]
models.forEach(function (m) {
  models[m.id] = m
})
<commit_msg>Wealth management project<commit_after>var models = module.exports = [
require('./models/tradle.APIBasedVerificationMethod_Wealth.json'),
require('./models/tradle.API_Wealth.json'),
require('./models/tradle.AboutYou.json'),
require('./models/tradle.ActivityLicense_Estonia.json'),
require('./models/tradle.AdditionalInfo.json'),
require('./models/tradle.AddressType_Rabo_wholesale.json'),
require('./models/tradle.Address_Wealth.json'),
require('./models/tradle.AllowanceAppForNonProfitOrg_Estonia.json'),
require('./models/tradle.AppState.json'),
require('./models/tradle.ApplicationForEResidency_Estonia.json'),
require('./models/tradle.ApplicationSubmitted.json'),
require('./models/tradle.ArtworkInfo.json'),
require('./models/tradle.Aspect.json'),
require('./models/tradle.BasicContactInfo.json'),
require('./models/tradle.BetaTesterContactInfo.json'),
require('./models/tradle.BusinessAccount.json'),
require('./models/tradle.BusinessInformation.json'),
require('./models/tradle.CVItem.json'),
require('./models/tradle.CancelAccount_Estonia.json'),
require('./models/tradle.Collateral_Obvion.json'),
require('./models/tradle.CollaterizedLoan_SG.json'),
require('./models/tradle.CommercialProduct_Obvion.json'),
require('./models/tradle.CompanyInformation_LM.json'),
require('./models/tradle.CompanyOwners_LM.json'),
require('./models/tradle.CompanyRegistration_Estonia.json'),
require('./models/tradle.ConfirmPackageRequest.json'),
require('./models/tradle.ContactInformation_Estonia.json'),
require('./models/tradle.ContractType_Obvion.json'),
require('./models/tradle.CorporateAccount_Rabo_Wholesale.json'),
require('./models/tradle.Country.json'),
require('./models/tradle.CoverholderApproval_LM.json'),
require('./models/tradle.CreditCards.json'),
require('./models/tradle.Currency.json'),
require('./models/tradle.CurrentAccount.json'),
require('./models/tradle.CustomerEntity_Rabo_Wholesale.json'),
require('./models/tradle.CustomerInfo_Rabo_Wholesale.json'),
require('./models/tradle.CustomerOwnership_Rabo_Wholesale.json'),
require('./models/tradle.CustomerProfile_Rabo_Wholesale.json'),
require('./models/tradle.CustomerWaiting.json'),
require('./models/tradle.DebtKind_Obvion.json'),
require('./models/tradle.Document.json'),
require('./models/tradle.DriverLicense.json'),
require('./models/tradle.EResidencyApplicationType_Estonia.json'),
require('./models/tradle.EResidency_Estonia.json'),
require('./models/tradle.E_ResidencyMotivation_Estonia.json'),
require('./models/tradle.EarthworkApplication_Estonia.json'),
require('./models/tradle.Education.json'),
require('./models/tradle.EducationDegree.json'),
require('./models/tradle.EducationNL.json'),
require('./models/tradle.EmployeeOnboarding.json'),
require('./models/tradle.EnergyLabel.json'),
require('./models/tradle.Enum.json'),
require('./models/tradle.Exchange_Rabo_wholesale.json'),
require('./models/tradle.ExemptStatus_Rabo_wholesale.json'),
require('./models/tradle.File.json'),
require('./models/tradle.FinancialProduct.json'),
require('./models/tradle.Financials_LM.json'),
require('./models/tradle.FineArtInsurance.json'),
require('./models/tradle.ForestNotice_Estonia.json'),
require('./models/tradle.ForgetMe.json'),
require('./models/tradle.ForgotYou.json'),
require('./models/tradle.Form.json'),
require('./models/tradle.FormError.json'),
require('./models/tradle.FormRequest.json'),
require('./models/tradle.FormationType_Rabo_wholesale.json'),
require('./models/tradle.Funds.json'),
require('./models/tradle.GovernmentIdType_Rabo_wholesale.json'),
require('./models/tradle.GuestSessionProof.json'),
require('./models/tradle.HealthInsurance.json'),
require('./models/tradle.HomeImprovement.json'),
require('./models/tradle.HomeInsurance.json'),
require('./models/tradle.HowToFund.json'),
require('./models/tradle.IDType.json'),
require('./models/tradle.ISAs.json'),
require('./models/tradle.IdentificationDetail_Estonia.json'),
require('./models/tradle.Identity.json'),
require('./models/tradle.IdentityDocumentType_Estonia.json'),
require('./models/tradle.IdentityPublishRequest.json'),
require('./models/tradle.IncomeProtectionInsurance.json'),
require('./models/tradle.Income_Obvion.json'),
require('./models/tradle.IndividualOwners_LM.json'),
require('./models/tradle.InsuranceInfo_ObvionAchmea.json'),
require('./models/tradle.InterestType_Obvion.json'),
require('./models/tradle.InternalInfo_Rabo_Wholesale.json'),
require('./models/tradle.Introduction.json'),
require('./models/tradle.InvestingExperience.json'),
require('./models/tradle.InvestingType.json'),
require('./models/tradle.Item.json'),
require('./models/tradle.KeyStaff_LM.json'),
require('./models/tradle.KindOfConstruction.json'),
require('./models/tradle.KindOfEngagement.json'),
require('./models/tradle.KindOfHouse.json'),
require('./models/tradle.KindOfInsurance.json'),
require('./models/tradle.KindOfObligation.json'),
require('./models/tradle.Language.json'),
require('./models/tradle.Licences_LM.json'),
require('./models/tradle.LifeInsurance.json'),
require('./models/tradle.LifeInsurance_ORV_Achmea.json'),
require('./models/tradle.LoanDetail_SG.json'),
require('./models/tradle.LoanPart_Obvion.json'),
require('./models/tradle.LoanTypes_Obvion.json'),
require('./models/tradle.Location_Estonia.json'),
require('./models/tradle.Major.json'),
require('./models/tradle.MaritalStatus.json'),
require('./models/tradle.MediaSnippet.json'),
require('./models/tradle.MerkleLeaf.json'),
require('./models/tradle.MerkleNode.json'),
require('./models/tradle.Message.json'),
require('./models/tradle.Method.json'),
require('./models/tradle.Money.json'),
require('./models/tradle.Mortgage.json'),
require('./models/tradle.MortgageDetail_Obvion.json'),
require('./models/tradle.MortgageGuarantee_Obvion.json'),
require('./models/tradle.MortgageLoanDetail.json'),
require('./models/tradle.MortgageProduct.json'),
require('./models/tradle.MyCoverholderApproval.json'),
require('./models/tradle.MyEmployeePass.json'),
require('./models/tradle.MyFineArtInsurance.json'),
require('./models/tradle.MyIdentities.json'),
require('./models/tradle.MyLifeInsurance.json'),
require('./models/tradle.MyMortgage.json'),
require('./models/tradle.MyProduct.json'),
require('./models/tradle.MyTaxesFiledConfirmation.json'),
require('./models/tradle.MyWealthManagementAccount.json'),
require('./models/tradle.Nationality.json'),
require('./models/tradle.NewMessageModel.json'),
require('./models/tradle.NextFormRequest.json'),
require('./models/tradle.NotarizePowerOfAttorney_SG.json'),
require('./models/tradle.NotarizePropertyOwnership_SG.json'),
require('./models/tradle.ObligationsDebts_Obvion.json'),
require('./models/tradle.Organization.json'),
require('./models/tradle.OtherCollaterals_Obvion.json'),
require('./models/tradle.OwnershipStructure_Rabo_wholesale.json'),
require('./models/tradle.PairingData.json'),
require('./models/tradle.PairingRequest.json'),
require('./models/tradle.PairingResponse.json'),
require('./models/tradle.Partial.json'),
require('./models/tradle.Passport.json'),
require('./models/tradle.PassportVerification.json'),
require('./models/tradle.PaymentPeriod.json'),
require('./models/tradle.Pension.json'),
require('./models/tradle.PersonalInfo_ObvionAchmea.json'),
require('./models/tradle.Phone.json'),
require('./models/tradle.PhoneBill.json'),
require('./models/tradle.PhoneTypes.json'),
require('./models/tradle.Photo.json'),
require('./models/tradle.PhotoID.json'),
require('./models/tradle.Posessions_Obvion.json'),
require('./models/tradle.ProductApplication.json'),
require('./models/tradle.ProductList.json'),
require('./models/tradle.ProfessionalIndemnity_LM.json'),
require('./models/tradle.Profile.json'),
require('./models/tradle.ProjectApplication_Estonia.json'),
require('./models/tradle.PropertyInformation.json'),
require('./models/tradle.PropertyOwnership_SG.json'),
require('./models/tradle.PropertyType.json'),
require('./models/tradle.PropertyTypes.json'),
require('./models/tradle.PurposeOfMortgageLoan.json'),
require('./models/tradle.PurposeOfTheAccount.json'),
require('./models/tradle.QualifiedInvestor.json'),
require('./models/tradle.ReasonForApplication_Estonia.json'),
require('./models/tradle.Refinancing.json'),
require('./models/tradle.Regulator_Rabo_wholesale.json'),
require('./models/tradle.Remediation.json'),
require('./models/tradle.RemediationSimpleMessage.json'),
require('./models/tradle.RepaymentType_Obvion.json'),
require('./models/tradle.ReportOfNonProfitOrgAllowanceUsage_Estonia.json'),
require('./models/tradle.RequestForRepresentative.json'),
require('./models/tradle.Residence.json'),
require('./models/tradle.ResidenceType.json'),
require('./models/tradle.ResidentialStatus.json'),
require('./models/tradle.SSN_Obvion.json'),
require('./models/tradle.SalaryVerification.json'),
require('./models/tradle.SalesData.json'),
require('./models/tradle.SecurityCode.json'),
require('./models/tradle.SelfIntroduction.json'),
require('./models/tradle.Selfie.json'),
require('./models/tradle.ServiceProvider.json'),
require('./models/tradle.Settings.json'),
require('./models/tradle.Sex_Estonia.json'),
require('./models/tradle.ShareContext.json'),
require('./models/tradle.SharedResource.json'),
require('./models/tradle.SimpleMessage.json'),
require('./models/tradle.SkillVerification.json'),
require('./models/tradle.SourceOfIncome.json'),
require('./models/tradle.StateOfInsurance.json'),
require('./models/tradle.TaxesFiledConfirmation.json'),
require('./models/tradle.TaxesFiledConfirmationForm.json'),
require('./models/tradle.TermInsurance.json'),
require('./models/tradle.TermsAndConditions.json'),
require('./models/tradle.Terms_Obvion.json'),
require('./models/tradle.TypeOfApplication_Estonia.json'),
require('./models/tradle.TypeOfCoverage_Achmea.json'),
require('./models/tradle.UtilityBillVerification.json'),
require('./models/tradle.Verifiable.json'),
require('./models/tradle.Verification.json'),
require('./models/tradle.VerifiedItem.json'),
require('./models/tradle.Visa.json'),
require('./models/tradle.VisualVerificationMethod_Wealth.json'),
require('./models/tradle.WMP.json'),
require('./models/tradle.WealthCV.json'),
require('./models/tradle.WealthItemType.json'),
require('./models/tradle.WealthManagementAccount.json'),
require('./models/tradle.WebSite.json'),
require('./models/tradle.WellDrilling_Estonia.json'),
require('./models/tradle.YourBalance.json'),
require('./models/tradle.YourMoney.json')]
models.forEach(function (m) {
  models[m.id] = m
})
<|endoftext|>


<commit_before>module.exports = Ec2Platform;

function Ec2Platform(config) {
	var AWS = require('aws-sdk');
	if(config)
		AWS.config = config;

	this.ec2 = new AWS.EC2();
}

Ec2Platform.prototype.startInstance = function(params, callback) {
	// TODO: do something to params?
	this.ec2.runInstances(params, function(err, data) {
		if (err)
			callback(err, null);
		else {
			var instanceId = data.Instances[0].InstanceId;
			callback(null, instanceId);
		}
	}
};

Ec2Platform.prototype.stopInstance = function(instanceId) {
	var params = {
		InstanceIds: [instanceId],
		DryRun: false
	};

	this.ec2.terminateInstances(params, function(err, data) {
		if(err)
			callback(err, null);
		else {
			callback(null, true);
		}
	});
};
<commit_msg>Fixed error, missing )<commit_after>module.exports = Ec2Platform;

function Ec2Platform(config) {
	var AWS = require('aws-sdk');
	if(config)
		AWS.config = config;

	this.ec2 = new AWS.EC2();
}

Ec2Platform.prototype.startInstance = function(params, callback) {
	// TODO: do something to params?
	this.ec2.runInstances(params, function(err, data) {
		if (err)
			callback(err, null);
		else {
			var instanceId = data.Instances[0].InstanceId;
			callback(null, instanceId);
		}
	});
};

Ec2Platform.prototype.stopInstance = function(instanceId) {
	var params = {
		InstanceIds: [instanceId],
		DryRun: false
	};

	this.ec2.terminateInstances(params, function(err, data) {
		if(err)
			callback(err, null);
		else {
			callback(null, true);
		}
	});
};
<|endoftext|>