<commit_before>/*******************************************************************************
 * Copyright (c) 2015 SAP and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * Contributors:
 * SAP - initial API and implementation
 *******************************************************************************/

/* globals $ java org */
/* eslint-env node, dirigible */

var streams = require("io/streams");

/**
 * Create a collection by the given path e.g. /myRoot/myCollection
 */
exports.createCollection = function(path) {
	$.getRepository().createCollection(path);
};

/**
 * Create a resource by the given path e.g. /myRoot/myCollection/myResource.txt,
 * content (a javascript bytes array object), isBinary - a flag indicating the type of the content and
 * the exact contentType following the corresponding RFC
 */
exports.createResource = function(path, content, isBinary, contentType) {
	$.getRepository().createResource(path, streams.toJavaBytes(content), isBinary ? isBinary : false, contentType ? contentType : "plain/text");
};

/**
 * Create a text resource by the given path e.g. /myRoot/myCollection/myResource and text.
 * Optionally you can provide the exact contentType of the provided text
 */
exports.createTextResource = function(path, text, contentType) {
    var content = new java.lang.String(text).getBytes();
	$.getRepository().createResource(path, content, false, contentType ? contentType : "plain/text");
};

/**
 * Get a Collection by the given path e.g. /myRoot/myCollection
 */
exports.getCollection = function(path) {
	var internalCollection = $.getRepository().getCollection(path);
	return new Collection(internalCollection);
};

/**
 * Gets a Resource by the given path e.g. /myRoot/myCollection/myResource.txt
 */
exports.getResource = function(path) {
	var internalResource = $.getRepository().getResource(path);
	return new Resource(internalResource);
};

/**
 * Gets the root Collection
 */
exports.getRoot = function(path) {
	var internalCollection = $.getRepository().getRoot();
	return new Collection(internalCollection);
};

/**
 * Check the existence of a Collection by the given path e.g. /myRoot/myCollection
 */
exports.hasCollection = function(path) {
	return $.getRepository().hasCollection(path);
};

/**
 * Check the existence of a Resource by the given path e.g. /myRoot/myCollection/myResource.txt
 */
exports.hasResource = function(path) {
	return $.getRepository().hasResource(path);
};

/**Removes a Collection by the given path e.g. /myRoot/myCollection
 */
exports.removeCollection = function(path) {
	return $.getRepository().removeCollection(path);
};

/**
 * Remove a Resource by the given path e.g. /myRoot/myCollection/myResource.txt
 */
exports.removeResource = function(path) {
	return $.getRepository().removeResource(path);
};

/**
 * Collection object
 */
function Collection(internalCollection) {
	this.internalCollection = internalCollection;

	this.getInternalObject = function() {
		return this.internalCollection;
	};

	this.create = function() {
		this.internalCollection.create();
	};

	this.delete = function() {
		this.internalCollection.delete();
	};

	this.exists = function() {
		return this.internalCollection.exists();
	};

	this.getName = function() {
		return this.internalCollection.getName();
	};

	this.getParent = function() {
		var internalParent = this.internalCollection.getParent();
		return new Collection(internalParent);
	};

	this.getPath = function() {
		return this.internalCollection.getPath();
	};

	this.createCollection = function(name) {
		return new Collection(this.internalCollection.createCollection(name));
	};

	this.createResource = function(name, content, isBinary, contentType) {
		return new Resource(this.internalCollection.createResource(name, streams.toJavaBytes(content), isBinary ? isBinary : false, contentType ? contentType : "plain/text"));
	};

//	this.getChildren = collectionGetChildren
//function collectionGetChildren() {
//	return this.internalCollection.getChildren();
//}

	this.getCollection = function(name) {
		return new Collection(this.internalCollection.getCollection(name));
	};

	this.getCollections = function() {
		var collections = [];
		var internalCollections = this.internalCollection.getCollections();
		for (var i = 0; i< internalCollections.size(); i++) {
			collections.push(new Collection(internalCollections.get(i)));
		}
		return collections;
	};

	this.getCollectionNames = function() {
		var collectionNames = [];
		var internalCollectionNames = this.internalCollection.getCollectionNames();
		for (var i = 0; i< internalCollectionNames.size(); i++) {
			collectionNames.push(internalCollectionNames.get(i));
		}
		return collectionNames;
	};

	this.getResource = function(name) {
		return new Collection(this.internalCollection.getResource(name));
	};

	this.getResources = function() {
		var resources = [];
		var internalResources = this.internalCollection.getResources();
		for (var i = 0; i< internalResources.size(); i++) {
			resources.push(new Collection(internalResources.get(i)));
		}
		return resources;
	};

	this.getResourceNames = function() {
		var resourceNames = [];
		var internalResourceNames = this.internalResource.getResourceNames();
		for (var i = 0; i< internalResourceNames.size(); i++) {
			resourceNames.push(internalResourceNames.get(i));
		}
		return resourceNames;
	};

	this.isEmpty = function() {
		return this.internalCollection.isEmpty();
	};

	this.removeCollection = function(name) {
		return this.internalCollection.removeCollection(name);
	};

	this.removeResource = function(name) {
		return this.internalCollection.removeResoruce(name);
	};

	this.renameTo = function(name) {
		return this.internalCollection.renameTo(name);
	};

	this.moveTo = function(path) {
		return this.internalCollection.moveTo(path);
	};

	this.copyTo = function(path) {
		return this.internalCollection.copyTo(path);
	};
}

/**
 * Resource object
 */
function Resource(internalResource) {
	this.internalResource = internalResource;

	this.getInternalObject = function() {
		return this.internalResource;
	};

	this.create = function() {
		this.internalResource.create();
	};

	this.delete = function() {
		this.internalResource.delete();
	};

	this.exists = function() {
		return this.internalResource.exists();
	};

	this.getName = function() {
		return this.internalResource.getName();
	};

	this.getParent = function() {
		return new Collection(this.internalResource.getParent());
	};

	this.getPath = function() {
		return this.internalResource.getPath();
	};

	this.getContent = function() {
		return streams.toJavaScriptBytes(this.internalResource.getContent());
	};

	this.getTextContent = function() {
		return new java.lang.String(this.internalResource.getContent()) + "";
	};

	this.getContentType = function() {
		return this.internalResource.getContentType();
	};

	this.isBinary = function() {
		return this.internalResource.isBinary();
	};

	this.isEmpty = function() {
		return this.internalResource.isEmpty();
	};

	this.renameTo = function(name) {
		return this.internalResource.renameTo(name);
	};

	this.moveTo = function(path) {
		return this.internalResource.moveTo(path);
	};

	this.copyTo = function(path) {
		return this.internalResource.copyTo(path);
	};

	this.setContent = function(content) {
		this.internalResource.setContent(streams.toJavaBytes(content));
	};

	this.setTextContent = function(text) {
		var content = new java.lang.String(text).getBytes();
		this.internalResource.setTextContent(streams.toJavaBytes(content));
	};
}<commit_msg>Fixes Repository API<commit_after>/*******************************************************************************
 * Copyright (c) 2015 SAP and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * Contributors:
 * SAP - initial API and implementation
 *******************************************************************************/

/* globals $ java org */
/* eslint-env node, dirigible */

var streams = require("io/streams");

/**
 * Create a collection by the given path e.g. /myRoot/myCollection
 */
exports.createCollection = function(path) {
	$.getRepository().createCollection(path);
};

/**
 * Create a resource by the given path e.g. /myRoot/myCollection/myResource.txt,
 * content (a javascript bytes array object), isBinary - a flag indicating the type of the content and
 * the exact contentType following the corresponding RFC
 */
exports.createResource = function(path, content, isBinary, contentType) {
	$.getRepository().createResource(path, streams.toJavaBytes(content), isBinary ? isBinary : false, contentType ? contentType : "plain/text");
};

/**
 * Create a text resource by the given path e.g. /myRoot/myCollection/myResource and text.
 * Optionally you can provide the exact contentType of the provided text
 */
exports.createTextResource = function(path, text, contentType) {
    var content = new java.lang.String(text).getBytes();
	$.getRepository().createResource(path, content, false, contentType ? contentType : "plain/text");
};

/**
 * Get a Collection by the given path e.g. /myRoot/myCollection
 */
exports.getCollection = function(path) {
	var internalCollection = $.getRepository().getCollection(path);
	return new Collection(internalCollection);
};

/**
 * Gets a Resource by the given path e.g. /myRoot/myCollection/myResource.txt
 */
exports.getResource = function(path) {
	var internalResource = $.getRepository().getResource(path);
	return new Resource(internalResource);
};

/**
 * Gets the root Collection
 */
exports.getRoot = function(path) {
	var internalCollection = $.getRepository().getRoot();
	return new Collection(internalCollection);
};

/**
 * Check the existence of a Collection by the given path e.g. /myRoot/myCollection
 */
exports.hasCollection = function(path) {
	return $.getRepository().hasCollection(path);
};

/**
 * Check the existence of a Resource by the given path e.g. /myRoot/myCollection/myResource.txt
 */
exports.hasResource = function(path) {
	return $.getRepository().hasResource(path);
};

/**Removes a Collection by the given path e.g. /myRoot/myCollection
 */
exports.removeCollection = function(path) {
	return $.getRepository().removeCollection(path);
};

/**
 * Remove a Resource by the given path e.g. /myRoot/myCollection/myResource.txt
 */
exports.removeResource = function(path) {
	return $.getRepository().removeResource(path);
};

/**
 * Collection object
 */
function Collection(internalCollection) {
	this.internalCollection = internalCollection;

	this.getInternalObject = function() {
		return this.internalCollection;
	};

	this.create = function() {
		this.internalCollection.create();
	};

	this.delete = function() {
		this.internalCollection.delete();
	};

	this.exists = function() {
		return this.internalCollection.exists();
	};

	this.getName = function() {
		return this.internalCollection.getName();
	};

	this.getParent = function() {
		var internalParent = this.internalCollection.getParent();
		return new Collection(internalParent);
	};

	this.getPath = function() {
		return this.internalCollection.getPath();
	};

	this.createCollection = function(name) {
		return new Collection(this.internalCollection.createCollection(name));
	};

	this.createResource = function(name, content, isBinary, contentType) {
		return new Resource(this.internalCollection.createResource(name, streams.toJavaBytes(content), isBinary ? isBinary : false, contentType ? contentType : "plain/text"));
	};

//	this.getChildren = collectionGetChildren
//function collectionGetChildren() {
//	return this.internalCollection.getChildren();
//}

	this.getCollection = function(name) {
		return new Collection(this.internalCollection.getCollection(name));
	};

	this.getCollections = function() {
		var collections = [];
		var internalCollections = this.internalCollection.getCollections();
		for (var i = 0; i< internalCollections.size(); i++) {
			collections.push(new Collection(internalCollections.get(i)));
		}
		return collections;
	};

	this.getCollectionNames = function() {
		var collectionNames = [];
		var internalCollectionNames = this.internalCollection.getCollectionsNames();
		for (var i = 0; i< internalCollectionNames.size(); i++) {
			collectionNames.push(internalCollectionNames.get(i));
		}
		return collectionNames;
	};

	this.getResource = function(name) {
		return new Collection(this.internalCollection.getResource(name));
	};

	this.getResources = function() {
		var resources = [];
		var internalResources = this.internalCollection.getResources();
		for (var i = 0; i< internalResources.size(); i++) {
			resources.push(new Collection(internalResources.get(i)));
		}
		return resources;
	};

	this.getResourceNames = function() {
		var resourceNames = [];
		var internalResourceNames = this.internalCollection.getResourcesNames();
		for (var i = 0; i< internalResourceNames.size(); i++) {
			resourceNames.push(internalResourceNames.get(i));
		}
		return resourceNames;
	};

	this.isEmpty = function() {
		return this.internalCollection.isEmpty();
	};

	this.removeCollection = function(name) {
		return this.internalCollection.removeCollection(name);
	};

	this.removeResource = function(name) {
		return this.internalCollection.removeResoruce(name);
	};

	this.renameTo = function(name) {
		return this.internalCollection.renameTo(name);
	};

	this.moveTo = function(path) {
		return this.internalCollection.moveTo(path);
	};

	this.copyTo = function(path) {
		return this.internalCollection.copyTo(path);
	};
}

/**
 * Resource object
 */
function Resource(internalResource) {
	this.internalResource = internalResource;

	this.getInternalObject = function() {
		return this.internalResource;
	};

	this.create = function() {
		this.internalResource.create();
	};

	this.delete = function() {
		this.internalResource.delete();
	};

	this.exists = function() {
		return this.internalResource.exists();
	};

	this.getName = function() {
		return this.internalResource.getName();
	};

	this.getParent = function() {
		return new Collection(this.internalResource.getParent());
	};

	this.getPath = function() {
		return this.internalResource.getPath();
	};

	this.getContent = function() {
		return streams.toJavaScriptBytes(this.internalResource.getContent());
	};

	this.getTextContent = function() {
		return new java.lang.String(this.internalResource.getContent()) + "";
	};

	this.getContentType = function() {
		return this.internalResource.getContentType();
	};

	this.isBinary = function() {
		return this.internalResource.isBinary();
	};

	this.isEmpty = function() {
		return this.internalResource.isEmpty();
	};

	this.renameTo = function(name) {
		return this.internalResource.renameTo(name);
	};

	this.moveTo = function(path) {
		return this.internalResource.moveTo(path);
	};

	this.copyTo = function(path) {
		return this.internalResource.copyTo(path);
	};

	this.setContent = function(content) {
		this.internalResource.setContent(streams.toJavaBytes(content));
	};

	this.setTextContent = function(text) {
		var content = new java.lang.String(text).getBytes();
		this.internalResource.setTextContent(streams.toJavaBytes(content));
	};
}
<|endoftext|>


<commit_before>var COMMCAREHQ_URLS = {};
hqDefine('hqwebapp/js/urllib.js', function () {
    // http://stackoverflow.com/a/21903119/240553
    var getUrlParameter = function (param) {
        return getUrlParameterFromString(param, window.location.search);
    };
    var getUrlParameterFromString = function (param, search) {
        var pageUrl = search.substring(1),
            urlVariables = pageUrl.split('&');

        for (var i = 0; i < urlVariables.length; i++) {
            var keyValue = urlVariables[i].split('=');
            var key = decodeURIComponent(keyValue[0]);
            var value = decodeURIComponent(keyValue[1]);

            if (key === param) {
                return value === undefined ? true : value;
            }
        }
    };
    var registerUrl = function(name, url) {
        COMMCAREHQ_URLS[name] = url;
    };
    var reverse = function (name) {
        var args = arguments;
        var index = 1;
        return COMMCAREHQ_URLS[name].replace(/---/g, function () {
            return args[index++];
        });
    };
    return {
        getUrlParameter: getUrlParameter,
        getUrlParameterFromString: getUrlParameterFromString,
        registerUrl: registerUrl,
        reverse: reverse,
    };
});
<commit_msg>urllib.js: add url name to errors<commit_after>var COMMCAREHQ_URLS = {};
hqDefine('hqwebapp/js/urllib.js', function () {
    // http://stackoverflow.com/a/21903119/240553
    var getUrlParameter = function (param) {
        return getUrlParameterFromString(param, window.location.search);
    };
    var getUrlParameterFromString = function (param, search) {
        var pageUrl = search.substring(1),
            urlVariables = pageUrl.split('&');

        for (var i = 0; i < urlVariables.length; i++) {
            var keyValue = urlVariables[i].split('=');
            var key = decodeURIComponent(keyValue[0]);
            var value = decodeURIComponent(keyValue[1]);

            if (key === param) {
                return value === undefined ? true : value;
            }
        }
    };
    var registerUrl = function(name, url) {
        COMMCAREHQ_URLS[name] = url;
    };
    var reverse = function (name) {
        var args = arguments;
        var index = 1;
        if (!COMMCAREHQ_URLS[name]) {
            throw new Error("URL '" + name + "' not found in registry");
        }
        return COMMCAREHQ_URLS[name].replace(/---/g, function () {
            return args[index++];
        });
    };
    return {
        getUrlParameter: getUrlParameter,
        getUrlParameterFromString: getUrlParameterFromString,
        registerUrl: registerUrl,
        reverse: reverse,
    };
});
<|endoftext|>


<commit_before>angular.module("yds").directive("ydsDashboardUpdater", ["Data", "DashboardService", "$timeout", "$location",
    function (Data, DashboardService, $timeout, $location) {
        return {
            restrict: "E",
            scope: {
                type: "@",                  // What type of component to show (grid, info etc.)
                projectId: "@",             // Project ID
                viewType: "@",              // Type to give to component
                lang: "@",                  // Language of component
                dashboardId: "@",           // ID used for getting selected year range from DashboardService
                dynamicDashboard: "@",      // Set to true if you are using this in a Dashboard with dynamic filters

                aggregateSetOnInit: "@",    // If the component shown is an aggregate, this indicates if it"s the first
                aggregateIconSize: "@",     // Aggregate icon size (used only if component shown is aggregate)
                aggregateShowButton: "@",   // If true, the aggregate will show the "View details" button
                aggregateValueObj: "=",     // If set, the aggregate should save its value in this object

                addToBasket: "@",           // If true, will show basket button in the components that support it
                selectionId: "@",           // ID for saving the selection for the specified dashboardId (used for grid)
                selectionType: "@",         // Selection type for grid (single or multiple)
                ignoreOwnSelection: "@",    // Ignore own selection (for some grids)
                enableAdvSearch: "@",       // Enable/disable advanced search in Search Tabs component (default: true)
                groupedData: "@",           // Used for grid, set to true if the data from the API will be grouped
                numberOfItems: "@",         // Number of items for the grid, if needed
                baseUrl: "@",               // Base URL to send to API
                aggregateType: "@",         // Type of aggregation that the displayed chart should make (count/amount)
                normaliseType: "@",         // Type of normalisation that the displayed chart should make (gdp/per capita)

                embeddable: "@",            // Set to true to enable the embed functionality
                disableExplanation: "@",    // Set to true to disable the explanation button
                exporting: "@",             // Set to true to enable exporting of charts
                barVertical: "@",           // Set to true to enable vertical bar chart

                quickFiltering: "@",        // Enable or disable quick filtering in selection grid
                enableGridViewBtn: "@",     // Enable or disable the view button in grid-paging
                enableSelection: "@",       // Enable or disable day selection in traffic-observation component
                minHeight: "@",             // Minimum height of this component's container
                enableRating: "@"           // Enable rating buttons (not supported for all components)
            },
            templateUrl: Data.templatePath + "templates/dashboard/dashboard-updater.html",
            link: function (scope) {
                var dashboardId = scope.dashboardId;
                var baseUrl = scope.baseUrl;
                var minHeight = parseInt(scope.minHeight);
                var originalType = scope.type;
                var filterSubscriptions = [];
                scope.showInfo = false;

                // Variables needed in case Search Tabs are shown
                var initialized = false;
                var requestType = "";
                var searchParams = {};

                // Keep previous parameter values, to check if the component needs to be re-rendered
                var prevParams = null;
                var prevAggregateType = "amount";
                var prevNormaliseType = "no";

                // If projectId is undefined, set default value (none)
                if (_.isUndefined(scope.projectId) || scope.projectId.trim() === "")
                    scope.projectId = "none";

                // If type is undefined, set default value
                if (_.isUndefined(scope.type) || scope.type.trim() === "")
                    scope.type = "info";

                // If viewType is undefined, set default value
                if (_.isUndefined(scope.viewType) || scope.viewType.trim() === "")
                    scope.viewType = "default";

                // If lang is undefined, set default value
                if (_.isUndefined(scope.lang) || scope.lang.trim() === "")
                    scope.lang = "en";

                // If addToBasket is undefined, set default value
                if (_.isUndefined(scope.addToBasket) || scope.addToBasket.trim() === "")
                    scope.addToBasket = "false";

                // If aggregateShowButton is undefined, set default value
                if (_.isUndefined(scope.aggregateShowButton) || (scope.aggregateShowButton !== "true" && scope.aggregateShowButton !== "false"))
                    scope.aggregateShowButton = "true";

                // If enableAdvSearch is undefined, set default value
                if (_.isUndefined(scope.enableAdvSearch) || (scope.enableAdvSearch !== "true" && scope.enableAdvSearch !== "false"))
                    scope.enableAdvSearch = "true";

                // If dynamicDashboard is undefined, set default value
                if (_.isUndefined(scope.dynamicDashboard) || (scope.dynamicDashboard !== "true" && scope.dynamicDashboard !== "false"))
                    scope.dynamicDashboard = "false";

                // If enableGridViewBtn is undefined, set default value
                if (_.isUndefined(scope.enableGridViewBtn) || (scope.enableGridViewBtn !== "true" && scope.enableGridViewBtn !== "false"))
                    scope.enableGridViewBtn = "false";

                // If enableSelection is undefined, set default value
                if (_.isUndefined(scope.enableSelection) || (scope.enableSelection !== "true" && scope.enableSelection !== "false"))
                    scope.enableSelection = "true";

                // If embeddable is undefined, set default value
                if (_.isUndefined(scope.embeddable) || (scope.embeddable !== "true" && scope.embeddable !== "false"))
                    scope.embeddable = "true";

                // If dashboardId is undefined, set default value
                if (_.isUndefined(dashboardId) || dashboardId.trim() === "") {
                    dashboardId = "default";
                }

                // If minHeight is undefined, set default value
                if (_.isUndefined(minHeight) || _.isNaN(minHeight)) {
                    minHeight = 0;
                }

                // Set Y position of buttons
                scope.yBtnPosition = minHeight + 5;

                // Set minimum height of container so when component is being refreshed, the container's
                // height does not become 0 which causes the page to scroll up
                scope.containerStyle = {
                    "min-height": minHeight + "px"
                };

                // Create list of Dashboard IDs that contain grid selection
                var gridDashboards = [
                    "comparison",
                    "comparison1",
                    "comparison2",
                    "comparison_details_1",
                    "comparison_details_2",
                    "country_page",
                    "public_project"
                ];

                // Create list of Dashboard IDs that contain object selection
                var objDashboards = [
                    "traffic_observation",
                    "country_producing_heatmap",
                    "traffic_observation_line1",
                    "traffic_observation_line2",
                    "comparison",
                    "comparison1",
                    "comparison2",
                    "comparison_details_1",
                    "comparison_details_2"
                ];

                /**
                 * Cause a refresh of the component by setting the type to an empty string and then back to the original
                 */
                var rerenderComponent = function () {
                    scope.type = "";                // Make type empty to hide component

                    $timeout(function () {
                        scope.type = originalType;  // At end of digest show component again
                    });
                };

                var updateExtraParams = function () {
                    // Keep old parameters for comparison and get new parameters from DashboardService
                    var newParams;
                    if (scope.dynamicDashboard === "true") {
                        // Get options for the enabled filters
                        newParams = DashboardService.getApiOptionsDynamic(dashboardId);
                    } else {
                        newParams = DashboardService.getApiOptions(dashboardId);
                    }

                    // If something changed in the parameters, update component
                    var differentAggregateType = !_.isUndefined(scope.aggregateType) && !_.isEqual(prevAggregateType, scope.aggregateType);
                    var differentNormaliseType = !_.isUndefined(scope.normaliseType) && !_.isEqual(prevNormaliseType, scope.normaliseType);
                    var differentParams = !_.isEqual(prevParams, newParams);

                    if (differentParams || differentAggregateType || differentNormaliseType) {
                        prevParams = _.clone(newParams);    // Keep current parameters to check equality later
                        scope.extraParams = newParams;      // Add new parameters to scope

                        // Add base URL to the extra params
                        if (!_.isUndefined(baseUrl) && baseUrl.length > 0) {
                            scope.extraParams = _.extend({
                                baseurl: baseUrl
                            }, scope.extraParams);
                        }

                        // If the aggregateType attribute is defined (and valid), add it to the extra parameters
                        var aggregateType = scope.aggregateType;
                        if (!_.isUndefined(aggregateType) &&
                            (aggregateType === "amount" || aggregateType === "count" || aggregateType === "budget")) {
                            scope.extraParams = _.extend({
                                aggregate: aggregateType
                            }, scope.extraParams);

                            prevAggregateType = scope.aggregateType;
                        }

                        // If the normaliseType attribute is defined (and valid), add it to the extra parameters
                        var normaliseType = scope.normaliseType;
                        if (!_.isUndefined(normaliseType) &&
                            (normaliseType === "no" || normaliseType === "gdp" || normaliseType === "percapita")) {
                            scope.extraParams = _.extend({
                                normalise: normaliseType
                            }, scope.extraParams);

                            prevNormaliseType = scope.normaliseType;
                        }

                        //noinspection FallThroughInSwitchStatementJS
                        switch (scope.type) {
                            case "selection-grid":
                            case "selection-paging-grid":
                            case "aggregate":
                                // Aggregates and selection grids watch their extra params for changes, so do nothing
                                break;
                            case "search":
                                if (!initialized) {
                                    // Get parameters for search component and keep requestType for later
                                    searchParams = DashboardService.getSearchParams(dashboardId);
                                    requestType = searchParams.requestType;

                                    // Add parameters for the search-tabs component to scope (requestType not needed)
                                    _.extend(scope, _.omit(searchParams, "requestType"));

                                    initialized = true;
                                }

                                // Make request to get rules for QueryBuilder
                                if (scope.enableAdvSearch === "true") {
                                    Data.getQueryBuilderRules(requestType, scope.extraParams).then(function (response) {
                                        var paramPrefix = searchParams.urlParamPrefix;
                                        var newRules = JSURL.stringify(response.data);

                                        // Set rules URL parameter with the new rules so QueryBuilder can update itself
                                        $location.search(paramPrefix + "rules", newRules);
                                    });
                                }

                                break;
                            case "bar":
                                if (!_.isUndefined(scope.barVertical)) {
                                    scope.extraParams.chart = (scope.barVertical === "true") ? "bar" : "column";
                                }

                                rerenderComponent();
                                break;
                            case "grid":
                            case "grid-paging":
                                if (!initialized) {
                                    // Get concept from DashboardService so "view" button will work correctly
                                    scope.concept = DashboardService.getSearchParams(dashboardId).concept;

                                    initialized = true;
                                }
                            // Continue to re-render grid
                            default:
                                // Re-render component
                                rerenderComponent();
                        }
                    }
                };

                if (scope.dynamicDashboard !== "true") {
                    // Subscribe to be notified of changes in selected countries and year range
                    DashboardService.subscribeSelectionChanges(scope, updateExtraParams);
                    DashboardService.subscribeYearChanges(scope, updateExtraParams);

                    // Check if we should also subscribe to the grid selection changes
                    if (scope.type === "selection-grid" || _.contains(gridDashboards, dashboardId)) {
                        DashboardService.subscribeGridSelectionChanges(scope, updateExtraParams);
                    }

                    // Check if we should subscribe to object changes
                    if (_.contains(objDashboards, dashboardId)) {
                        DashboardService.subscribeObjectChanges(scope, updateExtraParams);
                    }
                } else {
                    // Subscribe to changes in filters (when filters change, will subscribe only to the required filter
                    // types to watch for changes)
                    DashboardService.subscribeObjectChanges(scope, function () {
                        DashboardService.updateFilterSubscriptions(dashboardId, filterSubscriptions, scope, updateExtraParams);

                        // Check if we should update the extra parameters in case a filter type was removed
                        var newParams = DashboardService.getApiOptionsDynamic(dashboardId);

                        if (!_.isEqual(newParams, prevParams)) {
                            updateExtraParams();
                        }
                    });

                    DashboardService.updateFilterSubscriptions(dashboardId, filterSubscriptions, scope, updateExtraParams);
                }

                // If the aggregateType attribute is defined, watch it for changes and update the chart
                if (!_.isUndefined(scope.aggregateType) && _.contains(["amount", "count", "budget"], scope.aggregateType)) {
                    scope.$watch("aggregateType", updateExtraParams);
                }

                // If the normaliseType attribute is defined, watch it for changes and update the chart
                if (!_.isUndefined(scope.normaliseType) && _.contains(["no", "gdp", "percapita"], scope.normaliseType)) {
                    scope.$watch("normaliseType", updateExtraParams);
                }

                // Get initial info
                updateExtraParams();
            }
        };
    }
]);
<commit_msg>Add all parameters to the extraParams before adding it to scope<commit_after>angular.module("yds").directive("ydsDashboardUpdater", ["Data", "DashboardService", "$timeout", "$location",
    function (Data, DashboardService, $timeout, $location) {
        return {
            restrict: "E",
            scope: {
                type: "@",                  // What type of component to show (grid, info etc.)
                projectId: "@",             // Project ID
                viewType: "@",              // Type to give to component
                lang: "@",                  // Language of component
                dashboardId: "@",           // ID used for getting selected year range from DashboardService
                dynamicDashboard: "@",      // Set to true if you are using this in a Dashboard with dynamic filters

                aggregateSetOnInit: "@",    // If the component shown is an aggregate, this indicates if it"s the first
                aggregateIconSize: "@",     // Aggregate icon size (used only if component shown is aggregate)
                aggregateShowButton: "@",   // If true, the aggregate will show the "View details" button
                aggregateValueObj: "=",     // If set, the aggregate should save its value in this object

                addToBasket: "@",           // If true, will show basket button in the components that support it
                selectionId: "@",           // ID for saving the selection for the specified dashboardId (used for grid)
                selectionType: "@",         // Selection type for grid (single or multiple)
                ignoreOwnSelection: "@",    // Ignore own selection (for some grids)
                enableAdvSearch: "@",       // Enable/disable advanced search in Search Tabs component (default: true)
                groupedData: "@",           // Used for grid, set to true if the data from the API will be grouped
                numberOfItems: "@",         // Number of items for the grid, if needed
                baseUrl: "@",               // Base URL to send to API
                aggregateType: "@",         // Type of aggregation that the displayed chart should make (count/amount)
                normaliseType: "@",         // Type of normalisation that the displayed chart should make (gdp/per capita)

                embeddable: "@",            // Set to true to enable the embed functionality
                disableExplanation: "@",    // Set to true to disable the explanation button
                exporting: "@",             // Set to true to enable exporting of charts
                barVertical: "@",           // Set to true to enable vertical bar chart

                quickFiltering: "@",        // Enable or disable quick filtering in selection grid
                enableGridViewBtn: "@",     // Enable or disable the view button in grid-paging
                enableSelection: "@",       // Enable or disable day selection in traffic-observation component
                minHeight: "@",             // Minimum height of this component's container
                enableRating: "@"           // Enable rating buttons (not supported for all components)
            },
            templateUrl: Data.templatePath + "templates/dashboard/dashboard-updater.html",
            link: function (scope) {
                var dashboardId = scope.dashboardId;
                var baseUrl = scope.baseUrl;
                var minHeight = parseInt(scope.minHeight);
                var originalType = scope.type;
                var filterSubscriptions = [];
                scope.showInfo = false;

                // Variables needed in case Search Tabs are shown
                var initialized = false;
                var requestType = "";
                var searchParams = {};

                // Keep previous parameter values, to check if the component needs to be re-rendered
                var prevParams = null;
                var prevAggregateType = "amount";
                var prevNormaliseType = "no";

                // If projectId is undefined, set default value (none)
                if (_.isUndefined(scope.projectId) || scope.projectId.trim() === "")
                    scope.projectId = "none";

                // If type is undefined, set default value
                if (_.isUndefined(scope.type) || scope.type.trim() === "")
                    scope.type = "info";

                // If viewType is undefined, set default value
                if (_.isUndefined(scope.viewType) || scope.viewType.trim() === "")
                    scope.viewType = "default";

                // If lang is undefined, set default value
                if (_.isUndefined(scope.lang) || scope.lang.trim() === "")
                    scope.lang = "en";

                // If addToBasket is undefined, set default value
                if (_.isUndefined(scope.addToBasket) || scope.addToBasket.trim() === "")
                    scope.addToBasket = "false";

                // If aggregateShowButton is undefined, set default value
                if (_.isUndefined(scope.aggregateShowButton) || (scope.aggregateShowButton !== "true" && scope.aggregateShowButton !== "false"))
                    scope.aggregateShowButton = "true";

                // If enableAdvSearch is undefined, set default value
                if (_.isUndefined(scope.enableAdvSearch) || (scope.enableAdvSearch !== "true" && scope.enableAdvSearch !== "false"))
                    scope.enableAdvSearch = "true";

                // If dynamicDashboard is undefined, set default value
                if (_.isUndefined(scope.dynamicDashboard) || (scope.dynamicDashboard !== "true" && scope.dynamicDashboard !== "false"))
                    scope.dynamicDashboard = "false";

                // If enableGridViewBtn is undefined, set default value
                if (_.isUndefined(scope.enableGridViewBtn) || (scope.enableGridViewBtn !== "true" && scope.enableGridViewBtn !== "false"))
                    scope.enableGridViewBtn = "false";

                // If enableSelection is undefined, set default value
                if (_.isUndefined(scope.enableSelection) || (scope.enableSelection !== "true" && scope.enableSelection !== "false"))
                    scope.enableSelection = "true";

                // If embeddable is undefined, set default value
                if (_.isUndefined(scope.embeddable) || (scope.embeddable !== "true" && scope.embeddable !== "false"))
                    scope.embeddable = "true";

                // If dashboardId is undefined, set default value
                if (_.isUndefined(dashboardId) || dashboardId.trim() === "") {
                    dashboardId = "default";
                }

                // If minHeight is undefined, set default value
                if (_.isUndefined(minHeight) || _.isNaN(minHeight)) {
                    minHeight = 0;
                }

                // Set Y position of buttons
                scope.yBtnPosition = minHeight + 5;

                // Set minimum height of container so when component is being refreshed, the container's
                // height does not become 0 which causes the page to scroll up
                scope.containerStyle = {
                    "min-height": minHeight + "px"
                };

                // Create list of Dashboard IDs that contain grid selection
                var gridDashboards = [
                    "comparison",
                    "comparison1",
                    "comparison2",
                    "comparison_details_1",
                    "comparison_details_2",
                    "country_page",
                    "public_project"
                ];

                // Create list of Dashboard IDs that contain object selection
                var objDashboards = [
                    "traffic_observation",
                    "country_producing_heatmap",
                    "traffic_observation_line1",
                    "traffic_observation_line2",
                    "comparison",
                    "comparison1",
                    "comparison2",
                    "comparison_details_1",
                    "comparison_details_2"
                ];

                /**
                 * Cause a refresh of the component by setting the type to an empty string and then back to the original
                 */
                var rerenderComponent = function () {
                    scope.type = "";                // Make type empty to hide component

                    $timeout(function () {
                        scope.type = originalType;  // At end of digest show component again
                    });
                };

                var updateExtraParams = function () {
                    // Keep old parameters for comparison and get new parameters from DashboardService
                    var newParams;
                    if (scope.dynamicDashboard === "true") {
                        // Get options for the enabled filters
                        newParams = DashboardService.getApiOptionsDynamic(dashboardId);
                    } else {
                        newParams = DashboardService.getApiOptions(dashboardId);
                    }

                    // If something changed in the parameters, update component
                    var differentAggregateType = !_.isUndefined(scope.aggregateType) && !_.isEqual(prevAggregateType, scope.aggregateType);
                    var differentNormaliseType = !_.isUndefined(scope.normaliseType) && !_.isEqual(prevNormaliseType, scope.normaliseType);
                    var differentParams = !_.isEqual(prevParams, newParams);

                    if (differentParams || differentAggregateType || differentNormaliseType) {
                        prevParams = _.clone(newParams);    // Keep current parameters to check equality later

                        // Add base URL to the extra params
                        if (!_.isUndefined(baseUrl) && baseUrl.length > 0) {
                            newParams = _.extend({
                                baseurl: baseUrl
                            }, newParams);
                        }

                        // If the aggregateType attribute is defined (and valid), add it to the extra parameters
                        var aggregateType = scope.aggregateType;
                        if (!_.isUndefined(aggregateType) &&
                            (aggregateType === "amount" || aggregateType === "count" || aggregateType === "budget")) {
                            newParams = _.extend({
                                aggregate: aggregateType
                            }, newParams);

                            prevAggregateType = scope.aggregateType;
                        }

                        // If the normaliseType attribute is defined (and valid), add it to the extra parameters
                        var normaliseType = scope.normaliseType;
                        if (!_.isUndefined(normaliseType) &&
                            (normaliseType === "no" || normaliseType === "gdp" || normaliseType === "percapita")) {
                            newParams = _.extend({
                                normalise: normaliseType
                            }, newParams);

                            prevNormaliseType = scope.normaliseType;
                        }

                        // If the barVertical parameter has been set, add it to the parameters
                        if (!_.isUndefined(scope.barVertical)) {
                            newParams = _.extend({
                                chart: (scope.barVertical === "true") ? "bar" : "column"
                            }, newParams);
                        }

                        // Add new parameters to scope
                        scope.extraParams = newParams;

                        switch (scope.type) {
                            case "selection-grid":
                            case "selection-paging-grid":
                            case "aggregate":
                                // Aggregates and selection grids watch their extra params for changes, so do nothing
                                break;
                            case "search":
                                if (!initialized) {
                                    // Get parameters for search component and keep requestType for later
                                    searchParams = DashboardService.getSearchParams(dashboardId);
                                    requestType = searchParams.requestType;

                                    // Add parameters for the search-tabs component to scope (requestType not needed)
                                    _.extend(scope, _.omit(searchParams, "requestType"));

                                    initialized = true;
                                }

                                // Make request to get rules for QueryBuilder
                                if (scope.enableAdvSearch === "true") {
                                    Data.getQueryBuilderRules(requestType, scope.extraParams).then(function (response) {
                                        var paramPrefix = searchParams.urlParamPrefix;
                                        var newRules = JSURL.stringify(response.data);

                                        // Set rules URL parameter with the new rules so QueryBuilder can update itself
                                        $location.search(paramPrefix + "rules", newRules);
                                    });
                                }

                                break;
                            case "grid":
                            case "grid-paging":
                                if (!initialized) {
                                    // Get concept from DashboardService so "view" button will work correctly
                                    scope.concept = DashboardService.getSearchParams(dashboardId).concept;

                                    initialized = true;
                                }
                            // Continue to re-render grid
                            // noinspection FallThroughInSwitchStatementJS
                            default:
                                // Re-render component
                                rerenderComponent();
                        }
                    }
                };

                if (scope.dynamicDashboard !== "true") {
                    // Subscribe to be notified of changes in selected countries and year range
                    DashboardService.subscribeSelectionChanges(scope, updateExtraParams);
                    DashboardService.subscribeYearChanges(scope, updateExtraParams);

                    // Check if we should also subscribe to the grid selection changes
                    if (scope.type === "selection-grid" || _.contains(gridDashboards, dashboardId)) {
                        DashboardService.subscribeGridSelectionChanges(scope, updateExtraParams);
                    }

                    // Check if we should subscribe to object changes
                    if (_.contains(objDashboards, dashboardId)) {
                        DashboardService.subscribeObjectChanges(scope, updateExtraParams);
                    }
                } else {
                    // Subscribe to changes in filters (when filters change, will subscribe only to the required filter
                    // types to watch for changes)
                    DashboardService.subscribeObjectChanges(scope, function () {
                        DashboardService.updateFilterSubscriptions(dashboardId, filterSubscriptions, scope, updateExtraParams);

                        // Check if we should update the extra parameters in case a filter type was removed
                        var newParams = DashboardService.getApiOptionsDynamic(dashboardId);

                        if (!_.isEqual(newParams, prevParams)) {
                            updateExtraParams();
                        }
                    });

                    DashboardService.updateFilterSubscriptions(dashboardId, filterSubscriptions, scope, updateExtraParams);
                }

                // If the aggregateType attribute is defined, watch it for changes and update the chart
                if (!_.isUndefined(scope.aggregateType) && _.contains(["amount", "count", "budget"], scope.aggregateType)) {
                    scope.$watch("aggregateType", updateExtraParams);
                }

                // If the normaliseType attribute is defined, watch it for changes and update the chart
                if (!_.isUndefined(scope.normaliseType) && _.contains(["no", "gdp", "percapita"], scope.normaliseType)) {
                    scope.$watch("normaliseType", updateExtraParams);
                }

                // Get initial info
                updateExtraParams();
            }
        };
    }
]);
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {connect} from 'react-redux';
import {
  addNotification as notify,
  updateNotification
} from '../../../../index';

class NotificationExamples extends Component {
  static propTypes = {
    notify: React.PropTypes.func.isRequired,
    updateNotification: React.PropTypes.func.isRequired
  };

  /**
   * Bind methods
   * @param {Object} props
   * @returns {void}
   */
  constructor(props) {
    super(props);
    this._notificationUpdatedExample = this._notificationUpdatedExample.bind(this);
    this._notificationWithImage = this._notificationWithImage.bind(this);
  }

  /**
   * Example of a notification updated
   * @returns {void}
   * @private
   */
  _notificationUpdatedExample() {
    const {notify, updateNotification} = this.props;
    let notif = notify({
      title: 'Upload status',
      message: 'Your file is uploading...',
      status: 'info',
      dismissible: false,
      dismissAfter: 0,
      buttons: [{
        name: 'OK',
        primary: true,
        onClick: function() {
          alert('You clicked on OK button.');
        }
      }]

    });
    setTimeout(function() {
      notif.status = 'success';
      notif.message = 'Your file has been successfully uploaded';
      notif.dismissible = true;
      notif.dismissAfter = 5000;
      notif.buttons = [{
        name: 'OK',
        primary: true,
        onClick: function() {
          alert('You clicked on OK button.');
        }
      }, {
        name: 'Details',
        onClick: function() {
          alert('You clicked on Details button.');
        }

      }];
      updateNotification(notif);
    }, 3000);
  }

  /**
   * Example of a notification with an image
   * @returns {void}
   * @private
   */
  _notificationWithImage() {
    const {notify} = this.props;
    notify({
      title: 'Steve Frizeli added you',
      message: 'Do you want to accept him as friend?',
      image: '/static/images/image-2.png',
      dismissible: false,
      dismissAfter: 0,
      buttons: [{
        name: 'Yes',
        primary: true
      }, {
        name: 'No'
      }],
      allowHTML: true
    });
  }

  /**
   * Render form
   * @returns {XML}
   */
  render() {
    return (

        <button className='btn btn-primary btn-block' onClick={this._notificationUpdatedExample}>
          Notification updated example
        </button>
        <button className='btn btn-primary btn-block' onClick={this._notificationWithImage}>
          Notification with image
        </button>

    );
  }
}

export default connect(null, {notify, updateNotification})(NotificationExamples);
<commit_msg>fix bug in the demo - image was not appearing on Notification with image<commit_after>import React, {Component} from 'react';
import {connect} from 'react-redux';
import {
  addNotification as notify,
  updateNotification
} from '../../../../index';

class NotificationExamples extends Component {
  static propTypes = {
    notify: React.PropTypes.func.isRequired,
    updateNotification: React.PropTypes.func.isRequired
  };

  /**
   * Bind methods
   * @param {Object} props
   * @returns {void}
   */
  constructor(props) {
    super(props);
    this._notificationUpdatedExample = this._notificationUpdatedExample.bind(this);
    this._notificationWithImage = this._notificationWithImage.bind(this);
  }

  /**
   * Example of a notification updated
   * @returns {void}
   * @private
   */
  _notificationUpdatedExample() {
    const {notify, updateNotification} = this.props;
    let notif = notify({
      title: 'Upload status',
      message: 'Your file is uploading...',
      status: 'info',
      dismissible: false,
      dismissAfter: 0,
      buttons: [{
        name: 'OK',
        primary: true,
        onClick: function() {
          alert('You clicked on OK button.');
        }
      }]

    });
    setTimeout(function() {
      notif.status = 'success';
      notif.message = 'Your file has been successfully uploaded';
      notif.dismissible = true;
      notif.dismissAfter = 5000;
      notif.buttons = [{
        name: 'OK',
        primary: true,
        onClick: function() {
          alert('You clicked on OK button.');
        }
      }, {
        name: 'Details',
        onClick: function() {
          alert('You clicked on Details button.');
        }

      }];
      updateNotification(notif);
    }, 3000);
  }

  /**
   * Example of a notification with an image
   * @returns {void}
   * @private
   */
  _notificationWithImage() {
    const {notify} = this.props;
    let path = window.location.href;
    path = path.replace(/index\.html/, '');

    notify({
      title: 'Steve Frizeli added you',
      message: 'Do you want to accept him as friend?',
      image: `${path}static/images/image-2.png`,
      dismissible: false,
      dismissAfter: 0,
      buttons: [{
        name: 'Yes',
        primary: true
      }, {
        name: 'No'
      }],
      allowHTML: true
    });
  }

  /**
   * Render form
   * @returns {XML}
   */
  render() {
    return (

        <button className='btn btn-primary btn-block' onClick={this._notificationUpdatedExample}>
          Notification updated example
        </button>
        <button className='btn btn-primary btn-block' onClick={this._notificationWithImage}>
          Notification with image
        </button>

    );
  }
}

export default connect(null, {notify, updateNotification})(NotificationExamples);
<|endoftext|>


<commit_before>riot.tag2('su-validation-error', '

{message}

 <virtual each="{errors in opts.errors}">
{message}
 </virtual>
', 'su-validation-error.ui.error.message,[data-is="su-validation-error"].ui.error.message{ display: block; }', 'class="{getClass()}"', function(opts) {
    this.getClass = () => {
      return opts.name ? '' : 'ui error message'
    }
});<commit_msg>Add su-validation-error<commit_after>riot.tag2('su-validation-error', '

{message}

 <virtual each="{errors in opts.errors}">
{message}
 </virtual>
', 'su-validation-error.ui.error.message,[data-is="su-validation-error"].ui.error.message{ display: block !important; }', 'class="{getClass()}"', function(opts) {
    this.getClass = () => {
      if (opts.name || this.isEmptyErrors()) {
        return ''
      }
      return 'ui error message'
    }

    this.isEmptyErrors = () => {
      return !opts.errors || Object.keys(opts.errors).length == 0
    }
});<|endoftext|>


<commit_before>/* Spinner Class */
(function(t,e){if(typeof exports=="object")module.exports=e();else if(typeof define=="function"&&define.amd)define(e);else t.Spinner=e()})(this,function(){"use strict";var t=["webkit","Moz","ms","O"],e={},i;function o(t,e){var i=document.createElement(t||"div"),o;for(o in e)i[o]=e[o];return i}function n(t){for(var e=1,i=arguments.length;e<i;e++)t.appendChild(arguments[e]);return t}var r=function(){var t=o("style",{type:"text/css"});n(document.getElementsByTagName("head")[0],t);return t.sheet||t.styleSheet}();function s(t,o,n,s){var a=["opacity",o,~~(t*100),n,s].join("-"),f=.01+n/s*100,l=Math.max(1-(1-t)/o*(100-f),t),u=i.substring(0,i.indexOf("Animation")).toLowerCase(),d=u&&"-"+u+"-"||"";if(!e[a]){r.insertRule("@"+d+"keyframes "+a+"{"+"0%{opacity:"+l+"}"+f+"%{opacity:"+t+"}"+(f+.01)+"%{opacity:1}"+(f+o)%100+"%{opacity:"+t+"}"+"100%{opacity:"+l+"}"+"}",r.cssRules.length);e[a]=1}return a}function a(e,i){var o=e.style,n,r;i=i.charAt(0).toUpperCase()+i.slice(1);for(r=0;r<t.length;r++){n=t[r]+i;if(o[n]!==undefined)return n}if(o[i]!==undefined)return i}function f(t,e){for(var i in e)t.style[a(t,i)||i]=e[i];return t}function l(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var o in i)if(t[o]===undefined)t[o]=i[o]}return t}function u(t){var e={x:t.offsetLeft,y:t.offsetTop};while(t=t.offsetParent)e.x+=t.offsetLeft,e.y+=t.offsetTop;return e}function d(t,e){return typeof t=="string"?t:t[e%t.length]}var p={lines:12,length:7,width:5,radius:10,rotate:0,corners:1,color:"#000",direction:1,speed:1,trail:100,opacity:1/4,fps:20,zIndex:2e9,className:"spinner",top:"auto",left:"auto",position:"relative"};function c(t){if(typeof this=="undefined")return new c(t);this.opts=l(t||{},c.defaults,p)}c.defaults={};l(c.prototype,{spin:function(t){this.stop();var e=this,n=e.opts,r=e.el=f(o(0,{className:n.className}),{position:n.position,width:0,zIndex:n.zIndex}),s=n.radius+n.length+n.width,a,l;if(t){t.insertBefore(r,t.firstChild||null);l=u(t);a=u(r);f(r,{left:(n.left=="auto"?l.x-a.x+(t.offsetWidth>>1):parseInt(n.left,10)+s)+"px",top:(n.top=="auto"?l.y-a.y+(t.offsetHeight>>1):parseInt(n.top,10)+s)+"px"})}r.setAttribute("role","progressbar");e.lines(r,e.opts);if(!i){var d=0,p=(n.lines-1)*(1-n.direction)/2,c,h=n.fps,m=h/n.speed,y=(1-n.opacity)/(m*n.trail/100),g=m/n.lines;(function v(){d++;for(var t=0;t<n.lines;t++){c=Math.max(1-(d+(n.lines-t)*g)%m*y,n.opacity);e.opacity(r,t*n.direction+p,c,n)}e.timeout=e.el&&setTimeout(v,~~(1e3/h))})()}return e},stop:function(){var t=this.el;if(t){clearTimeout(this.timeout);if(t.parentNode)t.parentNode.removeChild(t);this.el=undefined}return this},lines:function(t,e){var r=0,a=(e.lines-1)*(1-e.direction)/2,l;function u(t,i){return f(o(),{position:"absolute",width:e.length+e.width+"px",height:e.width+"px",background:t,boxShadow:i,transformOrigin:"left",transform:"rotate("+~~(360/e.lines*r+e.rotate)+"deg) translate("+e.radius+"px"+",0)",borderRadius:(e.corners*e.width>>1)+"px"})}for(;r<e.lines;r++){l=f(o(),{position:"absolute",top:1+~(e.width/2)+"px",transform:e.hwaccel?"translate3d(0,0,0)":"",opacity:e.opacity,animation:i&&s(e.opacity,e.trail,a+r*e.direction,e.lines)+" "+1/e.speed+"s linear infinite"});if(e.shadow)n(l,f(u("#000","0 0 4px "+"#000"),{top:2+"px"}));n(t,n(l,u(d(e.color,r),"0 0 1px rgba(0,0,0,.1)")))}return t},opacity:function(t,e,i){if(e<t.childNodes.length)t.childNodes[e].style.opacity=i}});function h(){function t(t,e){return o("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">',e)}r.addRule(".spin-vml","behavior:url(#default#VML)");c.prototype.lines=function(e,i){var o=i.length+i.width,r=2*o;function s(){return f(t("group",{coordsize:r+" "+r,coordorigin:-o+" "+-o}),{width:r,height:r})}var a=-(i.width+i.length)*2+"px",l=f(s(),{position:"absolute",top:a,left:a}),u;function p(e,r,a){n(l,n(f(s(),{rotation:360/i.lines*e+"deg",left:~~r}),n(f(t("roundrect",{arcsize:i.corners}),{width:o,height:i.width,left:i.radius,top:-i.width>>1,filter:a}),t("fill",{color:d(i.color,e),opacity:i.opacity}),t("stroke",{opacity:0}))))}if(i.shadow)for(u=1;u<=i.lines;u++)p(u,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(u=1;u<=i.lines;u++)p(u);return n(e,l)};c.prototype.opacity=function(t,e,i,o){var n=t.firstChild;o=o.shadow&&o.lines||0;if(n&&e+o<n.childNodes.length){n=n.childNodes[e+o];n=n&&n.firstChild;n=n&&n.firstChild;if(n)n.opacity=i}}}var m=f(o("group"),{behavior:"url(#default#VML)"});if(!a(m,"transform")&&m.adj)h();else i=a(m,"animation");return c});
/* END Spinner Class */

/**
 * CoreLoader.js
 * -------------
 * fast responding SAPUI5 and OpenUI5 Core(-Library) Loader
 *
 * @author Danilo Vorpahl / Inwerken AG
 * @version 1.0
 *
 * @github https://github.com/InwerkenAG/ui5-CoreLoader.js
 */
var CoreLoader = (function () {

	var _spinnerOptions = [{ lines:16, length: 13, width: 1, radius: 12, speed: 1 },
	                       { lines:16, length: 13, width: 1, radius: 12, speed: 2 }];

	var _customCSS = 'html, body { height: 100%; width:100%; margin:0; }'
					+'#coreloader { display: block; box-sizing: border-box; z-index:16777270;top:0;bottom:0;left:0;right:0; min-height:100%;height:100%; text-align:center; background:#fff;'
					+'background-image: -moz-linear-gradient(top, rgba(255, 255, 255, 0.3) 0, rgba(0, 124, 192, 0.2) 100%); background-image: -ms-linear-gradient(top, rgba(255, 255, 255, 0.3) 0, rgba(0, 124, 192, 0.2) 100%);'
					+'background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.3) 0, rgba(0, 124, 192, 0.2) 100%); background-repeat: repeat; background-position: left top; background-size: auto; position: absolute;';

	// spinner object
	var _spinner = null;

	// function to execute when core is loaded
	var _fnReady = null;

	// self state (1: loading; 2: coreLoaded; 3: call _fnReady function; 4: done!)
	var loaderState = null;

	/**
	 * get all "data-sap" attributes from script-Tag
	 *
	 * @param   {Object} domElement coreLoader script-Tag
	 * @returns {Object} Object with Attributes for script-Tag
	 *
	 * @private
	 * @function
	 */
    function getConfig(domElement) {

		var oConfig = {};

		for(var attr in domElement.attributes) {
			var currentAttr = domElement.attributes[attr];
			if (currentAttr.name && currentAttr.name.lastIndexOf('data-sap')===0) {
				oConfig[currentAttr.name]=currentAttr.value;
			}
		}
		return oConfig;
    };

    /**
     * prepare the Document DOM, insert style
	 *
	 * @private
	 * @function
     */
    function prepareDocument() {

    	var head = document.head || document.getElementsByTagName('head')[0],
        	body = document.body || document.getElementsByTagName('body')[0];

        // style
        var styleTag = document.createElement('style');
    		styleTag.type = 'text/css';

		if (styleTag.styleSheet) { styleTag.styleSheet.cssText = _customCSS; }
		else { styleTag.appendChild(document.createTextNode(_customCSS)); }

		head.appendChild(styleTag);

		// spinner
    	var spinnerDiv = document.createElement('div');
    		spinnerDiv.id  = 'coreloader';

    	body.appendChild(spinnerDiv);

    	// attach the Spinner
		_spinner = new Spinner(_spinnerOptions[0]).spin(spinnerDiv);
		_spinner.elm = spinnerDiv;
    };

    /**
     * load the Core (only once!)
	 *
	 * @private
	 * @function
     */
    function loadCore() {

    	if(loaderState) return false;

    	prepareDocument();

		var coreLoaderScriptTag =  document.getElementById('util-coreloader');
		if(!coreLoaderScriptTag) throw "No Element with ID:'util-coreloader' found!";

		// get the original configuration
		var oConfig = getConfig(coreLoaderScriptTag);

		// loading begins
		loaderState = 1;
		var targetScriptTag = document.createElement('script');

		targetScriptTag.id   = 'sap-ui-bootstrap';
		targetScriptTag.type = 'text/javascript';
		targetScriptTag.src  = coreLoaderScriptTag.getAttribute('data-loader-src');

		targetScriptTag.onload =
		targetScriptTag.onreadystatechange = function() {

			if ( loaderState === 1 && (!this.readyState || this.readyState == 'complete') ){
				loaderState = 2;

				for(var i in _spinnerOptions[1]) _spinner.opts[i] = _spinnerOptions[1][i];
				_spinner.spin(_spinner.elm);

				if(_fnReady) {
					loaderState = 3;
					_fnReady();
				}
				else loaderState = 4;

				waitForDone();
			}
		};

		for(var attr in oConfig) {
			targetScriptTag.setAttribute(attr,oConfig[attr]);
		}

		setTimeout(function(){
			coreLoaderScriptTag.parentElement.insertBefore(targetScriptTag, coreLoaderScriptTag);
			coreLoaderScriptTag.parentNode.removeChild(coreLoaderScriptTag);
		}(this));

		return true;
    };

    /**
     * wait for .ready() loop
	 *
	 * @private
	 * @function
     */
    function waitForDone() {

    	if(loaderState !== 4) {
    		setTimeout(waitForDone,1000);
    	}
    	else {
    		setTimeout(function() {
    			$('#coreloader').fadeOut(300, function(){
    				$(this).delay(20).remove();
    			});
    		},500);
    	}
    };

    // attach event to run the CoreLoader
    document.onreadystatechange = function () {
    	var state = document.readyState;
    	if (state == 'interactive') {
    		// console.log('coreloader: waiting for Document readyState');

    	}
    	else if (state == 'complete') {
    		// console.log('coreloader: Document readyState complete');
    		loadCore();
    	}
    };

    return {

    	ready: function() {
    		// everything should be ready now
    		loaderState = 4;
    		return true;
    	},

    	onReadyState : function(fnExec) {
    		if(typeof(fnExec) == 'function') {
    			_fnReady = fnExec;
        		return true;
    		}
    		return false;
    	}
    };

})();
<commit_msg>Cache Buster considered<commit_after>/* Spinner Class */
(function(t,e){if(typeof exports=="object")module.exports=e();else if(typeof define=="function"&&define.amd)define(e);else t.Spinner=e()})(this,function(){"use strict";var t=["webkit","Moz","ms","O"],e={},i;function o(t,e){var i=document.createElement(t||"div"),o;for(o in e)i[o]=e[o];return i}function n(t){for(var e=1,i=arguments.length;e<i;e++)t.appendChild(arguments[e]);return t}var r=function(){var t=o("style",{type:"text/css"});n(document.getElementsByTagName("head")[0],t);return t.sheet||t.styleSheet}();function s(t,o,n,s){var a=["opacity",o,~~(t*100),n,s].join("-"),f=.01+n/s*100,l=Math.max(1-(1-t)/o*(100-f),t),u=i.substring(0,i.indexOf("Animation")).toLowerCase(),d=u&&"-"+u+"-"||"";if(!e[a]){r.insertRule("@"+d+"keyframes "+a+"{"+"0%{opacity:"+l+"}"+f+"%{opacity:"+t+"}"+(f+.01)+"%{opacity:1}"+(f+o)%100+"%{opacity:"+t+"}"+"100%{opacity:"+l+"}"+"}",r.cssRules.length);e[a]=1}return a}function a(e,i){var o=e.style,n,r;i=i.charAt(0).toUpperCase()+i.slice(1);for(r=0;r<t.length;r++){n=t[r]+i;if(o[n]!==undefined)return n}if(o[i]!==undefined)return i}function f(t,e){for(var i in e)t.style[a(t,i)||i]=e[i];return t}function l(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var o in i)if(t[o]===undefined)t[o]=i[o]}return t}function u(t){var e={x:t.offsetLeft,y:t.offsetTop};while(t=t.offsetParent)e.x+=t.offsetLeft,e.y+=t.offsetTop;return e}function d(t,e){return typeof t=="string"?t:t[e%t.length]}var p={lines:12,length:7,width:5,radius:10,rotate:0,corners:1,color:"#000",direction:1,speed:1,trail:100,opacity:1/4,fps:20,zIndex:2e9,className:"spinner",top:"auto",left:"auto",position:"relative"};function c(t){if(typeof this=="undefined")return new c(t);this.opts=l(t||{},c.defaults,p)}c.defaults={};l(c.prototype,{spin:function(t){this.stop();var e=this,n=e.opts,r=e.el=f(o(0,{className:n.className}),{position:n.position,width:0,zIndex:n.zIndex}),s=n.radius+n.length+n.width,a,l;if(t){t.insertBefore(r,t.firstChild||null);l=u(t);a=u(r);f(r,{left:(n.left=="auto"?l.x-a.x+(t.offsetWidth>>1):parseInt(n.left,10)+s)+"px",top:(n.top=="auto"?l.y-a.y+(t.offsetHeight>>1):parseInt(n.top,10)+s)+"px"})}r.setAttribute("role","progressbar");e.lines(r,e.opts);if(!i){var d=0,p=(n.lines-1)*(1-n.direction)/2,c,h=n.fps,m=h/n.speed,y=(1-n.opacity)/(m*n.trail/100),g=m/n.lines;(function v(){d++;for(var t=0;t<n.lines;t++){c=Math.max(1-(d+(n.lines-t)*g)%m*y,n.opacity);e.opacity(r,t*n.direction+p,c,n)}e.timeout=e.el&&setTimeout(v,~~(1e3/h))})()}return e},stop:function(){var t=this.el;if(t){clearTimeout(this.timeout);if(t.parentNode)t.parentNode.removeChild(t);this.el=undefined}return this},lines:function(t,e){var r=0,a=(e.lines-1)*(1-e.direction)/2,l;function u(t,i){return f(o(),{position:"absolute",width:e.length+e.width+"px",height:e.width+"px",background:t,boxShadow:i,transformOrigin:"left",transform:"rotate("+~~(360/e.lines*r+e.rotate)+"deg) translate("+e.radius+"px"+",0)",borderRadius:(e.corners*e.width>>1)+"px"})}for(;r<e.lines;r++){l=f(o(),{position:"absolute",top:1+~(e.width/2)+"px",transform:e.hwaccel?"translate3d(0,0,0)":"",opacity:e.opacity,animation:i&&s(e.opacity,e.trail,a+r*e.direction,e.lines)+" "+1/e.speed+"s linear infinite"});if(e.shadow)n(l,f(u("#000","0 0 4px "+"#000"),{top:2+"px"}));n(t,n(l,u(d(e.color,r),"0 0 1px rgba(0,0,0,.1)")))}return t},opacity:function(t,e,i){if(e<t.childNodes.length)t.childNodes[e].style.opacity=i}});function h(){function t(t,e){return o("<"+t+' xmlns="urn:schemas-microsoft.com:vml" class="spin-vml">',e)}r.addRule(".spin-vml","behavior:url(#default#VML)");c.prototype.lines=function(e,i){var o=i.length+i.width,r=2*o;function s(){return f(t("group",{coordsize:r+" "+r,coordorigin:-o+" "+-o}),{width:r,height:r})}var a=-(i.width+i.length)*2+"px",l=f(s(),{position:"absolute",top:a,left:a}),u;function p(e,r,a){n(l,n(f(s(),{rotation:360/i.lines*e+"deg",left:~~r}),n(f(t("roundrect",{arcsize:i.corners}),{width:o,height:i.width,left:i.radius,top:-i.width>>1,filter:a}),t("fill",{color:d(i.color,e),opacity:i.opacity}),t("stroke",{opacity:0}))))}if(i.shadow)for(u=1;u<=i.lines;u++)p(u,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(u=1;u<=i.lines;u++)p(u);return n(e,l)};c.prototype.opacity=function(t,e,i,o){var n=t.firstChild;o=o.shadow&&o.lines||0;if(n&&e+o<n.childNodes.length){n=n.childNodes[e+o];n=n&&n.firstChild;n=n&&n.firstChild;if(n)n.opacity=i}}}var m=f(o("group"),{behavior:"url(#default#VML)"});if(!a(m,"transform")&&m.adj)h();else i=a(m,"animation");return c});
/* END Spinner Class */

/**
 * CoreLoader.js
 * -------------
 * fast responding SAPUI5 and OpenUI5 Core(-Library) Loader
 *
 * @author Danilo Vorpahl / Inwerken AG
 * @version 1.0
 *
 * @github https://github.com/InwerkenAG/ui5-CoreLoader.js
 */
var CoreLoader = (function () {

	var _spinnerOptions = [{ lines:16, length: 13, width: 1, radius: 12, speed: 1 },
	                       { lines:16, length: 13, width: 1, radius: 12, speed: 2 }];

	var _customCSS = 'html, body { height: 100%; width:100%; margin:0; }'
					+'#coreloader { display: block; box-sizing: border-box; z-index:16777270;top:0;bottom:0;left:0;right:0; min-height:100%;height:100%; text-align:center; background:#fff;'
					+'background-image: -moz-linear-gradient(top, rgba(255, 255, 255, 0.3) 0, rgba(0, 124, 192, 0.2) 100%); background-image: -ms-linear-gradient(top, rgba(255, 255, 255, 0.3) 0, rgba(0, 124, 192, 0.2) 100%);'
					+'background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.3) 0, rgba(0, 124, 192, 0.2) 100%); background-repeat: repeat; background-position: left top; background-size: auto; position: absolute;';

	// spinner object
	var _spinner = null;

	// function to execute when core is loaded
	var _fnReady = null;

	// self state (1: loading; 2: coreLoaded; 3: call _fnReady function; 4: done!)
	var loaderState = null;

	/**
	 * get all "data-sap" attributes from script-Tag
	 *
	 * @param   {Object} domElement coreLoader script-Tag
	 * @returns {Object} Object with Attributes for script-Tag
	 *
	 * @private
	 * @function
	 */
    function getConfig(domElement) {

		var oConfig = {};

		for(var attr in domElement.attributes) {
			var currentAttr = domElement.attributes[attr];
			if (currentAttr.name && currentAttr.name.lastIndexOf('data-sap')===0) {
				oConfig[currentAttr.name]=currentAttr.value;
			}
		}
		return oConfig;
    };

    /**
     * prepare the Document DOM, insert style
	 *
	 * @private
	 * @function
     */
    function prepareDocument() {

    	var head = document.head || document.getElementsByTagName('head')[0],
        	body = document.body || document.getElementsByTagName('body')[0];

        // style
        var styleTag = document.createElement('style');
    		styleTag.type = 'text/css';

		if (styleTag.styleSheet) { styleTag.styleSheet.cssText = _customCSS; }
		else { styleTag.appendChild(document.createTextNode(_customCSS)); }

		head.appendChild(styleTag);

		// spinner
    	var spinnerDiv = document.createElement('div');
    		spinnerDiv.id  = 'coreloader';

    	body.appendChild(spinnerDiv);

    	// attach the Spinner
		_spinner = new Spinner(_spinnerOptions[0]).spin(spinnerDiv);
		_spinner.elm = spinnerDiv;
    };

    /**
     * load the Core (only once!)
	 *
	 * @private
	 * @function
     */
    function loadCore() {

    	if(loaderState) return false;

    	prepareDocument();

		var coreLoaderScriptTag =  document.getElementById('util-coreloader');
		if(!coreLoaderScriptTag) throw "No Element with ID:'util-coreloader' found!";

		// get the original configuration
		var oConfig = getConfig(coreLoaderScriptTag);

		// loading begins
		loaderState = 1;
		var targetScriptTag = document.createElement('script');

		targetScriptTag.id   = 'sap-ui-bootstrap';
		targetScriptTag.type = 'text/javascript';
		targetScriptTag.src  = coreLoaderScriptTag.getAttribute('data-loader-src');

		targetScriptTag.onload =
		targetScriptTag.onreadystatechange = function() {

			if ( loaderState === 1 && (!this.readyState || this.readyState == 'complete') ){
				loaderState = 2;

				for(var i in _spinnerOptions[1]) _spinner.opts[i] = _spinnerOptions[1][i];
				_spinner.spin(_spinner.elm);

				if(_fnReady) {
					var fnWaitForCore = function() {
						if(!window.sap || !window.sap.ui) {
							alert('Do you use CacheBuster? This will not work, yet.')
							setTimeout(fnWaitForCore, 3000);
						}
						else {
							loaderState = 3;
							_fnReady();
						}
					}
					fnWaitForCore();
				}
				else loaderState = 4;

				waitForDone();
			}
		};

		for(var attr in oConfig) {
			targetScriptTag.setAttribute(attr,oConfig[attr]);
		}

		setTimeout(function(){
			coreLoaderScriptTag.parentElement.insertBefore(targetScriptTag, coreLoaderScriptTag);
			coreLoaderScriptTag.parentNode.removeChild(coreLoaderScriptTag);
		}(this));

		return true;
    };

    /**
     * wait for .ready() loop
	 *
	 * @private
	 * @function
     */
    function waitForDone() {

    	if(loaderState !== 4) {
    		setTimeout(waitForDone,1000);
    	}
    	else {
    		setTimeout(function() {
    			$('#coreloader').fadeOut(300, function(){
    				$(this).delay(20).remove();
    			});
    		},500);
    	}
    };

    // attach event to run the CoreLoader
    document.onreadystatechange = function () {
    	var state = document.readyState;
    	if (state == 'interactive') {
    		// console.log('coreloader: waiting for Document readyState');

    	}
    	else if (state == 'complete') {
    		// console.log('coreloader: Document readyState complete');
    		loadCore();
    	}
    };

    return {

    	ready: function() {
    		// everything should be ready now
    		loaderState = 4;
    		return true;
    	},

    	onReadyState : function(fnExec) {
    		if(typeof(fnExec) == 'function') {
    			_fnReady = fnExec;
        		return true;
    		}
    		return false;
    	}
    };

})();
<|endoftext|>


<commit_before>/**
 * Created by julia on 18.07.2016.
 */
var i18nBean = require('../utility/i18nManager');
var t = i18nBean.getT();
var userModel = require('../DB/user');
var serverModel = require('../DB/server');
var config = require('../config/main.json');
var cleanMessage = function (message) {
    return message.replace("@", "");
};
var createUser = function (message, level, pms, cb) {
    var guild = getServerObj(message, level, pms);
    var freshUser = new userModel({
        id: message.author.id,
        name: message.author.username,
        servers: [guild],
        avatar: message.author.avatarURL,
        created: Date.now(),
        banned: false,
        verified: false,
        favorites: [],
        cookies: []
    });
    freshUser.save((err) => {
        // console.log('Created User!');
        if (err) return cb(err);
        cb();
    });
};
var calcXpNeeded = function (User) {
    return Math.floor(User.level * 2 * 3.14 * 15);
};
var updateXp = function (message, cb) {
    serverModel.findOne({id: message.guild.id}, function (err, Server) {
        if (err) return cb(err);
        if (Server) {
            if (typeof (Server.levelEnabled) === 'undefined' || Server.levelEnabled) {
                updateUserLevel(message, Server, err => {
                    if (err) return cb(err);
                    return cb();
                })
            } else {
                return cb();
            }
        } else {
            let server = new serverModel({
                id: message.guild.id,
                nsfwChannels: [],
                lastVoiceChannel: "",
                levelEnabled: true,
                pmNotifications: true,
                prefix: "!w."
            });
            server.save(err => {
                if (err) return cb(err);
                updateUserLevel(message, server, err => {
                    if (err) return cb(err);
                    cb();
                });
            });
        }
    });
    // console.log('Started update XP!');

};
var updateUserLevel = function (message, Server, cb) {
    let serverId = message.guild.id;
    userModel.findOne({id: message.author.id}, function (err, User) {
        if (err) return cb(err);
        if (User) {
            if (User.name !== message.author.username) {
                User.updateName(message.author.username, function (err) {
                    if (err) return console.log(err);
                });
            }
            if (hasGuild(message, User)) {
                var clientServer = loadServerFromUser(message, User);
                // console.log('User has Server');
                if (levelEnabled(message, User) && !cooldown(clientServer)) {
                    // console.log('User has Level enabled and has no Cooldown!');
                    User.updateXP(serverId, calcXpMessage(message.content), function (err) {
                        if (err) return cb(err);
                        // console.log('Updated Xp');
                        if (typeof (clientServer) !== 'undefined' && clientServer.xp + calcXpMessage(message.content) > calcXpNeeded(clientServer)) {
                            User.updateLevel(serverId, function (err) {
                                if (err) return cb(err);
                                if (pmNotifications(message, User) && typeof (Server.pmNotifications) === 'undefined' || Server.pmNotifications) {
                                    message.author.sendMessage(t('generic.level-update', {
                                        lngs: message.lang,
                                        level: clientServer.level + 1,
                                        server: message.guild.name
                                    }));
                                }
                            });
                        }
                    });
                }
            } else {
                // console.log('added Server!');
                User.addServer(getServerObj(message, true, true), function (err) {
                    if (err) return cb(err);
                    cb();
                });
            }
        } else {
            // console.log('Create User!');
            createUser(message, true, true, function (err) {
                if (err) return cb(err);
                cb();
            });
        }
    });
};
var calcXpMessage = function (content) {
    return 5 + calcBonus(content);
};
var calcBonus = function (content) {
    var bonus = Math.floor(content.length / 50);
    if (bonus > 10) {
        return 10;
    }
    return bonus;
};
var getUserLevel = function getUserLevel(message, cb) {
    if (message.guild) {
        userModel.findOne({id: message.author.id}, function (err, User) {
            if (err) return cb(err);
            if (User) {
                if (hasGuild(message, User) && levelEnabled(message, User)) {
                    var clientServer = loadServerFromUser(message, User);
                    cb(null, clientServer)
                } else {
                    cb('OH Nooooo');
                }
            } else {
                let clientServer = {level: 1, xp: 5, totalXp: 5};
                createUser(message, true, true, function (err) {
                    if (err) return cb(err);
                    cb(null, clientServer);
                });
            }
        });
    }
};
var hasWolkeBot = function (message, member) {
    if (typeof (member) === 'undefined' && message.author.id === config.owner_id) {
        return true;
    }
    if (typeof (member) === 'undefined') {
        return message.member.roles.exists('name', 'WolkeBot');
    } else {
        return member.roles.exists('name', 'WolkeBot');
    }

};
var isOwner = function (message) {
    return message.author.equals(message.guild.owner.user);
};
var levelEnabled = function (message, User) {
    for (var i = 0; i < User.servers.length; i++) {
        if (User.servers[i].serverId === message.guild.id && User.servers[i].levelEnabled === true) {
            return true;
        }
        if (User.servers[i].serverId === message.guild.id && User.servers[i].levelEnabled === false) {
            return false;
        }
    }
};
var pmNotifications = function (message, User) {
    for (var i = 0; i < User.servers.length; i++) {
        if (User.servers[i].serverId === message.guild.id && User.servers[i].pmNotifications === true) {
            return true;
        }
        if (User.servers[i].serverId === message.guild.id && User.servers[i].pmNotifications === false) {
            return false;
        }
    }
};
var cooldown = function (User) {
    if (User.cooldown > Date.now() - 7500) {

        return true;
    } else {
        return false;
    }
};
var hasGuild = function (message, User) {
    for (var i = 0; i < User.servers.length; i++) {
        if (User.servers[i].serverId === message.guild.id) {
            return true;
        }
    }
    return false;
};
var loadServerFromUser = function (message, User) {
    for (var i = 0; i < User.servers.length; i++) {
        if (User.servers[i].serverId === message.guild.id) {
            return User.servers[i];
        }
    }
    return null;
};
var getServerObj = function (message, level, pms) {
    return {
        serverId: message.guild.id,
        level: 1,
        xp: 5,
        totalXp: 5,
        cookies: 0,
        levelEnabled: level,
        pmNotifications: pms,
        cooldown: Date.now(),
        warned: [],
        kicked: [],
        banned: []
    };
};
var noSpam = function (message) {
    // if(message.mentions.users.length > 25) {
    //     console.log('good.');
    // }
    console.log(message.mentions.length);
};
var checkNsfwChannel = function (message, cb) {
    serverModel.findOne({id: message.guild.id}, function (err, Server) {
        if (err) return console.log(err);
        if (Server) {
            if (typeof (Server.nsfwChannels) !== 'undefined' && Server.nsfwChannels.length > 0) {
                for (var i = 0; i < Server.nsfwChannels.length; i++) {
                    if (Server.nsfwChannels[i] === message.channel.id) {
                        return cb();
                    }
                }
                return cb(false);
            } else {
                if (typeof (Server.nsfwChannel) !== 'undefined' && Server.nsfwChannel === message.channel.id) {
                    serverModel.update({id: message.guild.id}, {
                        $addToSet: {nsfwChannels: Server.nsfwChannel},
                        $set: {nsfwChannel: ""}
                    }, function (err) {
                        if (err) return console.log(err);
                    });
                    return cb();
                } else {
                    return cb(false);
                }
            }
        } else {
            return cb(false);
        }
    });
};
var checkCmdChannel = function (message, cb) {
    serverModel.findOne({id: message.guild.id}, function (err, Server) {
        if (err) return console.log(err);
        if (Server) {
            if (typeof (Server.cmdChannels) !== 'undefined' && Server.cmdChannels.length > 0) {
                for (var i = 0; i < Server.cmdChannels.length; i++) {
                    if (Server.cmdChannels[i] === message.channel.id) {
                        return cb();
                    }
                }
                return cb({ignore: true});
            } else {
                return cb();
            }

        } else {
            return cb();
        }
    });
};
module.exports = {
    cleanMessage: cleanMessage,
    createUser: createUser,
    updateXP: updateXp,
    getLevel: getUserLevel,
    levelEnabled: levelEnabled,
    hasWolkeBot: hasWolkeBot,
    isOwner: isOwner,
    loadServerFromUser: loadServerFromUser,
    hasGuild: hasGuild,
    getServerObj: getServerObj,
    noSpam: noSpam,
    checkNsfw: checkNsfwChannel,
    pmNotifications: pmNotifications,
    calcXpNeeded: calcXpNeeded
};<commit_msg>God damn i am stupid sometimes<commit_after>/**
 * Created by julia on 18.07.2016.
 */
var i18nBean = require('../utility/i18nManager');
var t = i18nBean.getT();
var userModel = require('../DB/user');
var serverModel = require('../DB/server');
var config = require('../config/main.json');
var cleanMessage = function (message) {
    return message.replace("@", "");
};
var createUser = function (message, level, pms, cb) {
    var guild = getServerObj(message, level, pms);
    var freshUser = new userModel({
        id: message.author.id,
        name: message.author.username,
        servers: [guild],
        avatar: message.author.avatarURL,
        created: Date.now(),
        banned: false,
        verified: false,
        favorites: [],
        cookies: []
    });
    freshUser.save((err) => {
        // console.log('Created User!');
        if (err) return cb(err);
        cb();
    });
};
var calcXpNeeded = function (User) {
    return Math.floor(User.level * 2 * 3.14 * 15);
};
var updateXp = function (message, cb) {
    serverModel.findOne({id: message.guild.id}, function (err, Server) {
        if (err) return cb(err);
        if (Server) {
            if (typeof (Server.levelEnabled) === 'undefined' || Server.levelEnabled) {
                updateUserLevel(message, Server, err => {
                    if (err) return cb(err);
                    return cb();
                })
            } else {
                return cb();
            }
        } else {
            let server = new serverModel({
                id: message.guild.id,
                nsfwChannels: [],
                lastVoiceChannel: "",
                levelEnabled: true,
                pmNotifications: true,
                prefix: "!w."
            });
            server.save(err => {
                if (err) return cb(err);
                updateUserLevel(message, server, err => {
                    if (err) return cb(err);
                    cb();
                });
            });
        }
    });
    // console.log('Started update XP!');

};
var updateUserLevel = function (message, Server, cb) {
    let serverId = message.guild.id;
    userModel.findOne({id: message.author.id}, function (err, User) {
        if (err) return cb(err);
        if (User) {
            if (User.name !== message.author.username) {
                User.updateName(message.author.username, function (err) {
                    if (err) return console.log(err);
                });
            }
            if (hasGuild(message, User)) {
                var clientServer = loadServerFromUser(message, User);
                // console.log('User has Server');
                if (levelEnabled(message, User) && !cooldown(clientServer)) {
                    // console.log('User has Level enabled and has no Cooldown!');
                    User.updateXP(serverId, calcXpMessage(message.content), function (err) {
                        if (err) return cb(err);
                        // console.log('Updated Xp');
                        if (typeof (clientServer) !== 'undefined' && clientServer.xp + calcXpMessage(message.content) > calcXpNeeded(clientServer)) {
                            User.updateLevel(serverId, function (err) {
                                if (err) return cb(err);
                                if (pmNotifications(message, User) && typeof (Server.pmNotifications) === 'undefined' || Server.pmNotifications) {
                                    message.author.sendMessage(t('generic.level-update', {
                                        lngs: message.lang,
                                        level: clientServer.level + 1,
                                        server: message.guild.name
                                    }));
                                }
                            });
                        }
                    });
                }
            } else {
                // console.log('added Server!');
                User.addServer(getServerObj(message, true, true), function (err) {
                    if (err) return cb(err);
                    cb();
                });
            }
        } else {
            // console.log('Create User!');
            createUser(message, true, true, function (err) {
                if (err) return cb(err);
                cb();
            });
        }
    });
};
var calcXpMessage = function (content) {
    return 5 + calcBonus(content);
};
var calcBonus = function (content) {
    var bonus = Math.floor(content.length / 50);
    if (bonus > 10) {
        return 10;
    }
    return bonus;
};
var getUserLevel = function getUserLevel(message, cb) {
    if (message.guild) {
        userModel.findOne({id: message.author.id}, function (err, User) {
            if (err) return cb(err);
            if (User) {
                if (hasGuild(message, User) && levelEnabled(message, User)) {
                    var clientServer = loadServerFromUser(message, User);
                    cb(null, clientServer)
                } else {
                    cb('OH Nooooo');
                }
            } else {
                let clientServer = {level: 1, xp: 5, totalXp: 5};
                createUser(message, true, true, function (err) {
                    if (err) return cb(err);
                    cb(null, clientServer);
                });
            }
        });
    }
};
var hasWolkeBot = function (message, member) {
    if (typeof (member) === 'undefined' && message.author.id === config.owner_id) {
        return true;
    }
    if (typeof (member) === 'undefined') {
        return message.member.roles.exists('name', 'WolkeBot');
    } else {
        return member.roles.exists('name', 'WolkeBot');
    }

};
var isOwner = function (message) {
    return message.author.equals(message.guild.owner.user);
};
var levelEnabled = function (message, User) {
    for (var i = 0; i < User.servers.length; i++) {
        if (User.servers[i].serverId === message.guild.id && User.servers[i].levelEnabled === true) {
            return true;
        }
        if (User.servers[i].serverId === message.guild.id && User.servers[i].levelEnabled === false) {
            return false;
        }
    }
};
var pmNotifications = function (message, User) {
    for (var i = 0; i < User.servers.length; i++) {
        if (User.servers[i].serverId === message.guild.id && User.servers[i].pmNotifications === true) {
            return true;
        }
        if (User.servers[i].serverId === message.guild.id && User.servers[i].pmNotifications === false) {
            return false;
        }
    }
};
var cooldown = function (User) {
    if (User.cooldown > Date.now() - 7500) {

        return true;
    } else {
        return false;
    }
};
var hasGuild = function (message, User) {
    for (var i = 0; i < User.servers.length; i++) {
        if (User.servers[i].serverId === message.guild.id) {
            return true;
        }
    }
    return false;
};
var loadServerFromUser = function (message, User) {
    for (var i = 0; i < User.servers.length; i++) {
        if (User.servers[i].serverId === message.guild.id) {
            return User.servers[i];
        }
    }
    return null;
};
var getServerObj = function (message, level, pms) {
    return {
        serverId: message.guild.id,
        level: 1,
        xp: 5,
        totalXp: 5,
        cookies: 0,
        levelEnabled: level,
        pmNotifications: pms,
        cooldown: Date.now(),
        warned: [],
        kicked: [],
        banned: []
    };
};
var noSpam = function (message) {
    // if(message.mentions.users.length > 25) {
    //     console.log('good.');
    // }
    console.log(message.mentions.length);
};
var checkNsfwChannel = function (message, cb) {
    serverModel.findOne({id: message.guild.id}, function (err, Server) {
        if (err) return console.log(err);
        if (Server) {
            if (typeof (Server.nsfwChannels) !== 'undefined' && Server.nsfwChannels.length > 0) {
                for (var i = 0; i < Server.nsfwChannels.length; i++) {
                    if (Server.nsfwChannels[i] === message.channel.id) {
                        return cb();
                    }
                }
                return cb('NEIN');
            } else {
                if (typeof (Server.nsfwChannel) !== 'undefined' && Server.nsfwChannel === message.channel.id) {
                    serverModel.update({id: message.guild.id}, {
                        $addToSet: {nsfwChannels: Server.nsfwChannel},
                        $set: {nsfwChannel: ""}
                    }, function (err) {
                        if (err) return console.log(err);
                    });
                    return cb();
                } else {
                    return cb('NEIN');
                }
            }
        } else {
            return cb('NEIN');
        }
    });
};
var checkCmdChannel = function (message, cb) {
    serverModel.findOne({id: message.guild.id}, function (err, Server) {
        if (err) return console.log(err);
        if (Server) {
            if (typeof (Server.cmdChannels) !== 'undefined' && Server.cmdChannels.length > 0) {
                for (var i = 0; i < Server.cmdChannels.length; i++) {
                    if (Server.cmdChannels[i] === message.channel.id) {
                        return cb();
                    }
                }
                return cb({ignore: true});
            } else {
                return cb();
            }

        } else {
            return cb();
        }
    });
};
module.exports = {
    cleanMessage: cleanMessage,
    createUser: createUser,
    updateXP: updateXp,
    getLevel: getUserLevel,
    levelEnabled: levelEnabled,
    hasWolkeBot: hasWolkeBot,
    isOwner: isOwner,
    loadServerFromUser: loadServerFromUser,
    hasGuild: hasGuild,
    getServerObj: getServerObj,
    noSpam: noSpam,
    checkNsfw: checkNsfwChannel,
    pmNotifications: pmNotifications,
    calcXpNeeded: calcXpNeeded
};<|endoftext|>