<commit_before>/*global window */
import d3 from 'd3';
import fc from 'd3fc';
import chart from './chart/chart';
import model from './model/model';
import menu from './menu/menu';
import util from './util/util';
import event from './event';
import dataInterface from './data/dataInterface';
import coinbaseProducts from './data/coinbase/getProducts';
import coinbaseAdaptor from './data/coinbase/historic/feedAdaptor';
import coinbaseHistoricErrorResponseFormatter from './data/coinbase/historic/errorResponseFormatter';
import dataGeneratorAdaptor from './data/generator/historic/feedAdaptor';
import quandlAdaptor from './data/quandl/historic/feedAdaptor';
import quandlHistoricErrorResponseFormatter from './data/quandl/historic/errorResponseFormatter';
import coinbaseWebSocket from './data/coinbase/streaming/webSocket';
import coinbaseStreamingErrorResponseFormatter from './data/coinbase/streaming/errorResponseFormatter';
import formatProducts from './data/coinbase/formatProducts';
import notification from './notification/notification';

export default function() {

    var app = {};

    var appContainer = d3.select('#app-container');
    var chartsContainer = appContainer.select('#charts-container');
    var overlay = appContainer.select('#overlay');
    var containers = {
        app: appContainer,
        charts: chartsContainer,
        primary: chartsContainer.select('#primary-container'),
        secondaries: chartsContainer.selectAll('.secondary-container'),
        xAxis: chartsContainer.select('#x-axis-container'),
        navbar: chartsContainer.select('#navbar-container'),
        overlay: overlay,
        overlaySecondaries: overlay. selectAll('.overlay-secondary-container'),
        legend: appContainer.select('#legend'),
        suspendLayout: function(value) {
            var self = this;
            Object.keys(self).forEach(function(key) {
                if (typeof self[key] !== 'function') {
                    self[key].layoutSuspended(value);
                }
            });
        }
    };

    var week1 = model.data.period({
        display: 'Weekly',
        seconds: 60 * 60 * 24 * 7,
        d3TimeInterval: {unit: d3.time.week, value: 1},
        timeFormat: '%b %d'});
    var day1 = model.data.period({
        display: 'Daily',
        seconds: 60 * 60 * 24,
        d3TimeInterval: {unit: d3.time.day, value: 1},
        timeFormat: '%b %d'});
    var hour1 = model.data.period({
        display: '1 Hr',
        seconds: 60 * 60,
        d3TimeInterval: {unit: d3.time.hour, value: 1},
        timeFormat: '%b %d %Hh'});
    var minute5 = model.data.period({
        display: '5 Min',
        seconds: 60 * 5,
        d3TimeInterval: {unit: d3.time.minute, value: 5},
        timeFormat: '%H:%M'});
    var minute1 = model.data.period({
        display: '1 Min',
        seconds: 60,
        d3TimeInterval: {unit: d3.time.minute, value: 1},
        timeFormat: '%H:%M'});

    var generatedSource = model.data.source(dataGeneratorAdaptor(), null, null);
    var bitcoinSource = model.data.source(coinbaseAdaptor(), coinbaseHistoricErrorResponseFormatter, coinbaseWebSocket(), coinbaseStreamingErrorResponseFormatter);
    var quandlSource = model.data.source(quandlAdaptor(), quandlHistoricErrorResponseFormatter, null, null);

    var generated = model.data.product({
        id: null,
        display: 'Data Generator',
        volumeFormat: '.3s',
        periods: [day1],
        source: generatedSource
    });
    var quandl = model.data.product({
        id: 'GOOG',
        display: 'GOOG',
        volumeFormat: '.3s',
        periods: [day1, week1],
        source: quandlSource
    });

    var primaryChartModel = model.chart.primary(generated);
    var secondaryChartModel = model.chart.secondary(generated);
    var selectorsModel = model.menu.selectors();
    var xAxisModel = model.chart.xAxis(day1);
    var navModel = model.chart.nav();
    var navResetModel = model.chart.navigationReset();
    var headMenuModel = model.menu.head([generated, quandl], generated, day1);
    var legendModel = model.chart.legend(generated, day1);
    var overlayModel = model.menu.overlay();
    var notificationMessagesModel = model.notification.messages();

    var charts = {
        primary: undefined,
        secondaries: [],
        xAxis: chart.xAxis(),
        navbar: undefined,
        legend: chart.legend()
    };

    var headMenu;
    var navReset;
    var selectors;
    var toastNotifications;

    function renderInternal() {
        if (layoutRedrawnInNextRender) {
            containers.suspendLayout(false);
        }

        containers.primary.datum(primaryChartModel)
            .call(charts.primary);

        containers.legend.datum(legendModel)
            .call(charts.legend);

        containers.secondaries.datum(secondaryChartModel)
            // TODO: Add component: group of secondary charts.
            // Then also move method layout.getSecondaryContainer into the group.
            .filter(function(d, i) { return i < charts.secondaries.length; })
            .each(function(d, i) {
                d3.select(this)
                    .attr('class', 'secondary-container ' + charts.secondaries[i].valueString)
                    .call(charts.secondaries[i].option);
            });

        containers.xAxis.datum(xAxisModel)
            .call(charts.xAxis);

        containers.navbar.datum(navModel)
            .call(charts.navbar);

        containers.app.select('#navbar-reset')
            .datum(navResetModel)
            .call(navReset);

        containers.app.select('.head-menu')
            .datum(headMenuModel)
            .call(headMenu);

        containers.app.select('#selectors')
            .datum(selectorsModel)
            .call(selectors);

        containers.app.select('#notifications')
            .datum(notificationMessagesModel)
            .call(toastNotifications);

        containers.overlay.datum(overlayModel)
            .call(overlay);

        if (layoutRedrawnInNextRender) {
            containers.suspendLayout(true);
            layoutRedrawnInNextRender = false;
        }
    }

    var render = fc.util.render(renderInternal);

    var layoutRedrawnInNextRender = true;

    function updateLayout() {
        layoutRedrawnInNextRender = true;
        util.layout(containers, charts);
    }

    function initialiseResize() {
        d3.select(window).on('resize', function() {
            updateLayout();
            render();
        });
    }

    function addNotification(message) {
        notificationMessagesModel.messages.unshift(model.notification.message(message));
    }

    function onViewChange(domain) {
        var viewDomain = [domain[0], domain[1]];
        primaryChartModel.viewDomain = viewDomain;
        secondaryChartModel.viewDomain = viewDomain;
        xAxisModel.viewDomain = viewDomain;
        navModel.viewDomain = viewDomain;

        var trackingLatest = util.domain.trackingLatestData(
            primaryChartModel.viewDomain,
            primaryChartModel.data);
        primaryChartModel.trackingLatest = trackingLatest;
        secondaryChartModel.trackingLatest = trackingLatest;
        navModel.trackingLatest = trackingLatest;
        navResetModel.trackingLatest = trackingLatest;
        render();
    }

    function onPrimaryIndicatorChange(indicator) {
        indicator.isSelected = !indicator.isSelected;
        updatePrimaryChartIndicators();
        render();
    }

    function onSecondaryChartChange(_chart) {
        _chart.isSelected = !_chart.isSelected;
        updateSecondaryCharts();
        render();
    }

    function onCrosshairChange(dataPoint) {
        legendModel.data = dataPoint;
        render();
    }

    function onStreamingFeedCloseOrError(streamingEvent, source) {
        var message = source.streamingNotificationFormatter(streamingEvent);
        if (message) {
            addNotification(message);
            render();
        }
    }

    function resetToLatest() {
        var data = primaryChartModel.data;
        var dataDomain = fc.util.extent()
            .fields('date')(data);
        var navTimeDomain = util.domain.moveToLatest(dataDomain, data, 0.2);
        onViewChange(navTimeDomain);
    }

    function loading(isLoading, error) {
        appContainer.select('#loading-status-message')
            .classed('hidden', !(isLoading || error))
            .select('.content')
            .text(error ? error : 'Loading...');
        appContainer.select('#charts')
            .classed('hidden', isLoading || error);
    }

    function updateModelData(data) {
        primaryChartModel.data = data;
        secondaryChartModel.data = data;
        navModel.data = data;
    }

    function updateModelSelectedProduct(product) {
        headMenuModel.selectedProduct = product;
        primaryChartModel.product = product;
        secondaryChartModel.product = product;
        legendModel.product = product;
    }

    function updateModelSelectedPeriod(period) {
        headMenuModel.selectedPeriod = period;
        xAxisModel.period = period;
        legendModel.period = period;
    }

    function initialisePrimaryChart() {
        return chart.primary()
            .on(event.crosshairChange, onCrosshairChange)
            .on(event.viewChange, onViewChange);
    }

    function initialiseNav() {
        return chart.nav()
            .on(event.viewChange, onViewChange);
    }

    function initialiseNavReset() {
        return menu.navigationReset()
            .on(event.resetToLatest, resetToLatest);
    }

    function initialiseDataInterface() {
        return dataInterface()
            .on(event.newTrade, function(data, source) {
                updateModelData(data);
                if (primaryChartModel.trackingLatest) {
                    var newDomain = util.domain.moveToLatest(
                        primaryChartModel.viewDomain,
                        primaryChartModel.data);
                    onViewChange(newDomain);
                }
            })
            .on(event.historicDataLoaded, function(data, source) {
                loading(false);
                updateModelData(data);
                legendModel.data = null;
                resetToLatest();
                updateLayout();
            })
            .on(event.historicFeedError, function(err, source) {
                loading(false, 'Error loading data. Please make your selection again, or refresh the page.');
                var responseText = '';
                try {
                    var responseObject = JSON.parse(err.responseText);
                    var formattedMessage = source.historicNotificationFormatter(responseObject);
                    if (formattedMessage) {
                        responseText = '. ' + formattedMessage;
                    }
                } catch (e) {
                    responseText = '';
                }
                var statusText = err.statusText || 'Unkown reason.';
                var message = 'Error getting historic data: ' + statusText + responseText;

                addNotification(message);
                render();
            })
            .on(event.streamingFeedError, onStreamingFeedCloseOrError)
            .on(event.streamingFeedClose, onStreamingFeedCloseOrError);
    }

    function initialiseHeadMenu(_dataInterface) {
        return menu.head()
            .on(event.dataProductChange, function(product) {
                loading(true);
                updateModelSelectedProduct(product.option);
                updateModelSelectedPeriod(product.option.periods[0]);
                _dataInterface(product.option.periods[0].seconds, product.option);
                render();
            })
            .on(event.dataPeriodChange, function(period) {
                loading(true);
                updateModelSelectedPeriod(period.option);
                _dataInterface(period.option.seconds);
                render();
            })
            .on(event.clearAllPrimaryChartIndicatorsAndSecondaryCharts, function() {
                primaryChartModel.indicators.forEach(deselectOption);
                charts.secondaries.forEach(deselectOption);

                updatePrimaryChartIndicators();
                updateSecondaryCharts();
                render();
            });
    }

    function selectOption(option, options) {
        options.forEach(function(_option) {
            _option.isSelected = false;
        });
        option.isSelected = true;
    }

    function deselectOption(option) { option.isSelected = false; }

    function fetchCoinbaseProducts() {
        coinbaseProducts(insertProductsIntoHeadMenuModel);
    }

    function insertProductsIntoHeadMenuModel(error, bitcoinProducts) {
        if (error) {
            var statusText = error.statusText || 'Unkown reason.';
            var message = 'Error retrieving Coinbase products: ' + statusText;
            addNotification(message);
        } else {
            var defaultPeriods = [hour1, day1];
            var productPeriodOverrides = d3.map();
            productPeriodOverrides.set('BTC-USD', [minute1, minute5, hour1, day1]);
            var formattedProducts = formatProducts(bitcoinProducts, bitcoinSource, defaultPeriods, productPeriodOverrides);
            headMenuModel.products = headMenuModel.products.concat(formattedProducts);
        }
        render();
    }

    function initialiseSelectors() {
        return menu.selectors()
            .on(event.primaryChartSeriesChange, function(series) {
                primaryChartModel.series = series;
                selectOption(series, selectorsModel.seriesSelector.options);
                render();
            })
            .on(event.primaryChartIndicatorChange, onPrimaryIndicatorChange)
            .on(event.secondaryChartChange, onSecondaryChartChange);
    }

    function updatePrimaryChartIndicators() {
        primaryChartModel.indicators =
            selectorsModel.indicatorSelector.indicatorOptions.filter(function(option) {
                return option.isSelected;
            });

        overlayModel.primaryIndicators = primaryChartModel.indicators;
    }

    function updateSecondaryCharts() {
        charts.secondaries =
            selectorsModel.indicatorSelector.secondaryChartOptions.filter(function(option) {
                return option.isSelected;
            });
        // TODO: This doesn't seem to be a concern of menu.
        charts.secondaries.forEach(function(chartOption) {
            chartOption.option.on(event.viewChange, onViewChange);
        });

        overlayModel.secondaryIndicators = charts.secondaries;
        // TODO: Remove .remove! (could a secondary chart group component manage this?).
        containers.secondaries.selectAll('*').remove();
        updateLayout();
    }

    function initialiseOverlay() {
        return menu.overlay()
            .on(event.primaryChartIndicatorChange, onPrimaryIndicatorChange)
            .on(event.secondaryChartChange, onSecondaryChartChange);
    }

    function onNotificationClose(id) {
        notificationMessagesModel.messages = notificationMessagesModel.messages.filter(function(message) { return message.id !== id; });
        render();
    }

    function initialiseNotifications() {
        return notification.toast()
            .on(event.notificationClose, onNotificationClose);
    }

    app.run = function() {
        charts.primary = initialisePrimaryChart();
        charts.navbar = initialiseNav();

        var _dataInterface = initialiseDataInterface();
        headMenu = initialiseHeadMenu(_dataInterface);
        navReset = initialiseNavReset();
        selectors = initialiseSelectors();
        overlay = initialiseOverlay();
        toastNotifications = initialiseNotifications();

        updateLayout();
        initialiseResize();

        _dataInterface(generated.periods[0].seconds, generated);
        fetchCoinbaseProducts();
    };

    return app;
}
<commit_msg>Small style update to loading function<commit_after>/*global window */
import d3 from 'd3';
import fc from 'd3fc';
import chart from './chart/chart';
import model from './model/model';
import menu from './menu/menu';
import util from './util/util';
import event from './event';
import dataInterface from './data/dataInterface';
import coinbaseProducts from './data/coinbase/getProducts';
import coinbaseAdaptor from './data/coinbase/historic/feedAdaptor';
import coinbaseHistoricErrorResponseFormatter from './data/coinbase/historic/errorResponseFormatter';
import dataGeneratorAdaptor from './data/generator/historic/feedAdaptor';
import quandlAdaptor from './data/quandl/historic/feedAdaptor';
import quandlHistoricErrorResponseFormatter from './data/quandl/historic/errorResponseFormatter';
import coinbaseWebSocket from './data/coinbase/streaming/webSocket';
import coinbaseStreamingErrorResponseFormatter from './data/coinbase/streaming/errorResponseFormatter';
import formatProducts from './data/coinbase/formatProducts';
import notification from './notification/notification';

export default function() {

    var app = {};

    var appContainer = d3.select('#app-container');
    var chartsContainer = appContainer.select('#charts-container');
    var overlay = appContainer.select('#overlay');
    var containers = {
        app: appContainer,
        charts: chartsContainer,
        primary: chartsContainer.select('#primary-container'),
        secondaries: chartsContainer.selectAll('.secondary-container'),
        xAxis: chartsContainer.select('#x-axis-container'),
        navbar: chartsContainer.select('#navbar-container'),
        overlay: overlay,
        overlaySecondaries: overlay. selectAll('.overlay-secondary-container'),
        legend: appContainer.select('#legend'),
        suspendLayout: function(value) {
            var self = this;
            Object.keys(self).forEach(function(key) {
                if (typeof self[key] !== 'function') {
                    self[key].layoutSuspended(value);
                }
            });
        }
    };

    var week1 = model.data.period({
        display: 'Weekly',
        seconds: 60 * 60 * 24 * 7,
        d3TimeInterval: {unit: d3.time.week, value: 1},
        timeFormat: '%b %d'});
    var day1 = model.data.period({
        display: 'Daily',
        seconds: 60 * 60 * 24,
        d3TimeInterval: {unit: d3.time.day, value: 1},
        timeFormat: '%b %d'});
    var hour1 = model.data.period({
        display: '1 Hr',
        seconds: 60 * 60,
        d3TimeInterval: {unit: d3.time.hour, value: 1},
        timeFormat: '%b %d %Hh'});
    var minute5 = model.data.period({
        display: '5 Min',
        seconds: 60 * 5,
        d3TimeInterval: {unit: d3.time.minute, value: 5},
        timeFormat: '%H:%M'});
    var minute1 = model.data.period({
        display: '1 Min',
        seconds: 60,
        d3TimeInterval: {unit: d3.time.minute, value: 1},
        timeFormat: '%H:%M'});

    var generatedSource = model.data.source(dataGeneratorAdaptor(), null, null);
    var bitcoinSource = model.data.source(coinbaseAdaptor(), coinbaseHistoricErrorResponseFormatter, coinbaseWebSocket(), coinbaseStreamingErrorResponseFormatter);
    var quandlSource = model.data.source(quandlAdaptor(), quandlHistoricErrorResponseFormatter, null, null);

    var generated = model.data.product({
        id: null,
        display: 'Data Generator',
        volumeFormat: '.3s',
        periods: [day1],
        source: generatedSource
    });
    var quandl = model.data.product({
        id: 'GOOG',
        display: 'GOOG',
        volumeFormat: '.3s',
        periods: [day1, week1],
        source: quandlSource
    });

    var primaryChartModel = model.chart.primary(generated);
    var secondaryChartModel = model.chart.secondary(generated);
    var selectorsModel = model.menu.selectors();
    var xAxisModel = model.chart.xAxis(day1);
    var navModel = model.chart.nav();
    var navResetModel = model.chart.navigationReset();
    var headMenuModel = model.menu.head([generated, quandl], generated, day1);
    var legendModel = model.chart.legend(generated, day1);
    var overlayModel = model.menu.overlay();
    var notificationMessagesModel = model.notification.messages();

    var charts = {
        primary: undefined,
        secondaries: [],
        xAxis: chart.xAxis(),
        navbar: undefined,
        legend: chart.legend()
    };

    var headMenu;
    var navReset;
    var selectors;
    var toastNotifications;

    function renderInternal() {
        if (layoutRedrawnInNextRender) {
            containers.suspendLayout(false);
        }

        containers.primary.datum(primaryChartModel)
            .call(charts.primary);

        containers.legend.datum(legendModel)
            .call(charts.legend);

        containers.secondaries.datum(secondaryChartModel)
            // TODO: Add component: group of secondary charts.
            // Then also move method layout.getSecondaryContainer into the group.
            .filter(function(d, i) { return i < charts.secondaries.length; })
            .each(function(d, i) {
                d3.select(this)
                    .attr('class', 'secondary-container ' + charts.secondaries[i].valueString)
                    .call(charts.secondaries[i].option);
            });

        containers.xAxis.datum(xAxisModel)
            .call(charts.xAxis);

        containers.navbar.datum(navModel)
            .call(charts.navbar);

        containers.app.select('#navbar-reset')
            .datum(navResetModel)
            .call(navReset);

        containers.app.select('.head-menu')
            .datum(headMenuModel)
            .call(headMenu);

        containers.app.select('#selectors')
            .datum(selectorsModel)
            .call(selectors);

        containers.app.select('#notifications')
            .datum(notificationMessagesModel)
            .call(toastNotifications);

        containers.overlay.datum(overlayModel)
            .call(overlay);

        if (layoutRedrawnInNextRender) {
            containers.suspendLayout(true);
            layoutRedrawnInNextRender = false;
        }
    }

    var render = fc.util.render(renderInternal);

    var layoutRedrawnInNextRender = true;

    function updateLayout() {
        layoutRedrawnInNextRender = true;
        util.layout(containers, charts);
    }

    function initialiseResize() {
        d3.select(window).on('resize', function() {
            updateLayout();
            render();
        });
    }

    function addNotification(message) {
        notificationMessagesModel.messages.unshift(model.notification.message(message));
    }

    function onViewChange(domain) {
        var viewDomain = [domain[0], domain[1]];
        primaryChartModel.viewDomain = viewDomain;
        secondaryChartModel.viewDomain = viewDomain;
        xAxisModel.viewDomain = viewDomain;
        navModel.viewDomain = viewDomain;

        var trackingLatest = util.domain.trackingLatestData(
            primaryChartModel.viewDomain,
            primaryChartModel.data);
        primaryChartModel.trackingLatest = trackingLatest;
        secondaryChartModel.trackingLatest = trackingLatest;
        navModel.trackingLatest = trackingLatest;
        navResetModel.trackingLatest = trackingLatest;
        render();
    }

    function onPrimaryIndicatorChange(indicator) {
        indicator.isSelected = !indicator.isSelected;
        updatePrimaryChartIndicators();
        render();
    }

    function onSecondaryChartChange(_chart) {
        _chart.isSelected = !_chart.isSelected;
        updateSecondaryCharts();
        render();
    }

    function onCrosshairChange(dataPoint) {
        legendModel.data = dataPoint;
        render();
    }

    function onStreamingFeedCloseOrError(streamingEvent, source) {
        var message = source.streamingNotificationFormatter(streamingEvent);
        if (message) {
            addNotification(message);
            render();
        }
    }

    function resetToLatest() {
        var data = primaryChartModel.data;
        var dataDomain = fc.util.extent()
            .fields('date')(data);
        var navTimeDomain = util.domain.moveToLatest(dataDomain, data, 0.2);
        onViewChange(navTimeDomain);
    }

    function loading(isLoading, error) {
        appContainer.select('#loading-status-message')
            .classed('hidden', !(isLoading || error))
            .select('.content')
            .text(error || 'Loading...');
        appContainer.select('#charts')
            .classed('hidden', isLoading || error);
    }

    function updateModelData(data) {
        primaryChartModel.data = data;
        secondaryChartModel.data = data;
        navModel.data = data;
    }

    function updateModelSelectedProduct(product) {
        headMenuModel.selectedProduct = product;
        primaryChartModel.product = product;
        secondaryChartModel.product = product;
        legendModel.product = product;
    }

    function updateModelSelectedPeriod(period) {
        headMenuModel.selectedPeriod = period;
        xAxisModel.period = period;
        legendModel.period = period;
    }

    function initialisePrimaryChart() {
        return chart.primary()
            .on(event.crosshairChange, onCrosshairChange)
            .on(event.viewChange, onViewChange);
    }

    function initialiseNav() {
        return chart.nav()
            .on(event.viewChange, onViewChange);
    }

    function initialiseNavReset() {
        return menu.navigationReset()
            .on(event.resetToLatest, resetToLatest);
    }

    function initialiseDataInterface() {
        return dataInterface()
            .on(event.newTrade, function(data, source) {
                updateModelData(data);
                if (primaryChartModel.trackingLatest) {
                    var newDomain = util.domain.moveToLatest(
                        primaryChartModel.viewDomain,
                        primaryChartModel.data);
                    onViewChange(newDomain);
                }
            })
            .on(event.historicDataLoaded, function(data, source) {
                loading(false);
                updateModelData(data);
                legendModel.data = null;
                resetToLatest();
                updateLayout();
            })
            .on(event.historicFeedError, function(err, source) {
                loading(false, 'Error loading data. Please make your selection again, or refresh the page.');
                var responseText = '';
                try {
                    var responseObject = JSON.parse(err.responseText);
                    var formattedMessage = source.historicNotificationFormatter(responseObject);
                    if (formattedMessage) {
                        responseText = '. ' + formattedMessage;
                    }
                } catch (e) {
                    responseText = '';
                }
                var statusText = err.statusText || 'Unkown reason.';
                var message = 'Error getting historic data: ' + statusText + responseText;

                addNotification(message);
                render();
            })
            .on(event.streamingFeedError, onStreamingFeedCloseOrError)
            .on(event.streamingFeedClose, onStreamingFeedCloseOrError);
    }

    function initialiseHeadMenu(_dataInterface) {
        return menu.head()
            .on(event.dataProductChange, function(product) {
                loading(true);
                updateModelSelectedProduct(product.option);
                updateModelSelectedPeriod(product.option.periods[0]);
                _dataInterface(product.option.periods[0].seconds, product.option);
                render();
            })
            .on(event.dataPeriodChange, function(period) {
                loading(true);
                updateModelSelectedPeriod(period.option);
                _dataInterface(period.option.seconds);
                render();
            })
            .on(event.clearAllPrimaryChartIndicatorsAndSecondaryCharts, function() {
                primaryChartModel.indicators.forEach(deselectOption);
                charts.secondaries.forEach(deselectOption);

                updatePrimaryChartIndicators();
                updateSecondaryCharts();
                render();
            });
    }

    function selectOption(option, options) {
        options.forEach(function(_option) {
            _option.isSelected = false;
        });
        option.isSelected = true;
    }

    function deselectOption(option) { option.isSelected = false; }

    function fetchCoinbaseProducts() {
        coinbaseProducts(insertProductsIntoHeadMenuModel);
    }

    function insertProductsIntoHeadMenuModel(error, bitcoinProducts) {
        if (error) {
            var statusText = error.statusText || 'Unkown reason.';
            var message = 'Error retrieving Coinbase products: ' + statusText;
            addNotification(message);
        } else {
            var defaultPeriods = [hour1, day1];
            var productPeriodOverrides = d3.map();
            productPeriodOverrides.set('BTC-USD', [minute1, minute5, hour1, day1]);
            var formattedProducts = formatProducts(bitcoinProducts, bitcoinSource, defaultPeriods, productPeriodOverrides);
            headMenuModel.products = headMenuModel.products.concat(formattedProducts);
        }
        render();
    }

    function initialiseSelectors() {
        return menu.selectors()
            .on(event.primaryChartSeriesChange, function(series) {
                primaryChartModel.series = series;
                selectOption(series, selectorsModel.seriesSelector.options);
                render();
            })
            .on(event.primaryChartIndicatorChange, onPrimaryIndicatorChange)
            .on(event.secondaryChartChange, onSecondaryChartChange);
    }

    function updatePrimaryChartIndicators() {
        primaryChartModel.indicators =
            selectorsModel.indicatorSelector.indicatorOptions.filter(function(option) {
                return option.isSelected;
            });

        overlayModel.primaryIndicators = primaryChartModel.indicators;
    }

    function updateSecondaryCharts() {
        charts.secondaries =
            selectorsModel.indicatorSelector.secondaryChartOptions.filter(function(option) {
                return option.isSelected;
            });
        // TODO: This doesn't seem to be a concern of menu.
        charts.secondaries.forEach(function(chartOption) {
            chartOption.option.on(event.viewChange, onViewChange);
        });

        overlayModel.secondaryIndicators = charts.secondaries;
        // TODO: Remove .remove! (could a secondary chart group component manage this?).
        containers.secondaries.selectAll('*').remove();
        updateLayout();
    }

    function initialiseOverlay() {
        return menu.overlay()
            .on(event.primaryChartIndicatorChange, onPrimaryIndicatorChange)
            .on(event.secondaryChartChange, onSecondaryChartChange);
    }

    function onNotificationClose(id) {
        notificationMessagesModel.messages = notificationMessagesModel.messages.filter(function(message) { return message.id !== id; });
        render();
    }

    function initialiseNotifications() {
        return notification.toast()
            .on(event.notificationClose, onNotificationClose);
    }

    app.run = function() {
        charts.primary = initialisePrimaryChart();
        charts.navbar = initialiseNav();

        var _dataInterface = initialiseDataInterface();
        headMenu = initialiseHeadMenu(_dataInterface);
        navReset = initialiseNavReset();
        selectors = initialiseSelectors();
        overlay = initialiseOverlay();
        toastNotifications = initialiseNotifications();

        updateLayout();
        initialiseResize();

        _dataInterface(generated.periods[0].seconds, generated);
        fetchCoinbaseProducts();
    };

    return app;
}
<|endoftext|>


<commit_before>import path from 'path'
import glob from 'glob'
import env from '../utils/env'
import config from '../utils/config'

import Endpoint from '.'

// require built-in endpoints
glob.sync(path.join(__dirname, '*/*.js'))
  .forEach((endpoint) => {
    Endpoint.register(require(endpoint).default)
  })
// require plugins
config.plugins
.filter((plugin) => plugin.enable)
.forEach((plugin) => {
  try {
    let plugin = require(plugin.id)
    if (plugin.default) {
      plugin = plugin.default
    }
    plugin({Endpoint, env, config: conf})
  } catch (err) {
    console.error(`Failed to load plugin: ${plugin.id}`, err)
  }
})
<commit_msg>fix plugin load<commit_after>import path from 'path'
import glob from 'glob'
import env from '../utils/env'
import config from '../utils/config'

import Endpoint from '.'

// require built-in endpoints
glob.sync(path.join(__dirname, '*/*.js'))
  .forEach((endpoint) => {
    Endpoint.register(require(endpoint).default)
  })
// require plugins
config.plugins
.filter((plugin) => plugin.enable)
.forEach((plugin) => {
  try {
    let pluginInstance = require(plugin.id)
    if (pluginInstance.default) {
      pluginInstance = pluginInstance.default
    }
    pluginInstance({Endpoint, env, config: conf})
  } catch (err) {
    console.error(`Failed to load plugin: ${plugin.id}`, err)
  }
})
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')
const _h = require('../_helpers')

exports.handler = async (event, context) => {
  if (event.source === 'aws.events') { return _h.json({ message: 'OK' }) }

  if (!event.Records && event.Records.length === 0) { return }

  for (var i = 0; i < event.Records.length; i++) {
    const data = JSON.parse(event.Records[i].body)
    const entityId = _h.strToId(data.entity)
    const db = await _h.db(data.account)

    if (data.dt) {
      const e = await db.collection('entity').findOne({ _id: entityId, aggregated: { $gte: new Date(data.dt) } }, { projection: { _id: true } })
      if (!e) {
        console.log('Entity', entityId, 'already aggregated at', data.dt)
        continue
      }
    }

    const properties = await db.collection('property').find({ entity: entityId, deleted: { $exists: false } }).toArray()

    if (properties.find(x => x.type === '_deleted')) {
      const deleteResponse = await db.collection('entity').deleteOne({ _id: entityId })
      console.log('Entity', entityId, 'deleted')
      continue
    }

    let entity = {
      aggregated: data.dt ? new Date(data.dt) : new Date()
    }

    for (var n = 0; n < properties.length; n++) {
      const prop = properties[n]
      let cleanProp = _.omit(prop, ['entity', 'type', 'created', 'search', 'public'])

      if (prop.reference && ['_viewer', '_expander', '_editor', '_owner'].includes(prop.type)) {
        if (!_.has(entity, 'access')) {
          _.set(entity, 'access', [])
        }
        entity.access.push(prop.reference)
      }

      if (!_.has(entity, ['private', prop.type])) {
        _.set(entity, ['private', prop.type], [])
      }

      if (prop.reference) {
        const referenceEntities = await db.collection('entity').findOne({ _id: prop.reference }, { projection: { 'private.name': true }})

        if (_.has(referenceEntities, 'private.name')) {
          cleanProp = referenceEntities.private.name.map(x => {
            return { ...cleanProp, ...x }
          })
        }
      }

      if (!Array.isArray(cleanProp)) {
        cleanProp = [cleanProp]
      }
      entity.private[prop.type] = [...entity.private[prop.type], ...cleanProp]

      if (prop.public) {
        if (!_.has(entity, ['public', prop.type])) {
          _.set(entity, ['public', prop.type], [])
        }

        entity.public[prop.type] = [...entity.public[prop.type], ...cleanProp]
      }
    }

    const replaceResponse = await db.collection('entity').replaceOne({ _id: entityId }, entity)

    const referrers = await db.collection('property').aggregate([
      { $match: { reference: entityId, deleted: { $exists: false } } },
      { $group: { _id: '$entity' } }
    ]).toArray()

    for (var i = 0; i < referrers.length; i++) {
      await _h.addEntityAggregateSqs(context, data.account, referrers[i]._id.toString(), entity.aggregated)
    }

    console.log('Entity', entityId, 'updated and added', referrers.length, 'entities to sqs')
  }
}
<commit_msg>Set reference as string if no entity with this _id<commit_after>'use strict'

const _ = require('lodash')
const _h = require('../_helpers')

exports.handler = async (event, context) => {
  if (event.source === 'aws.events') { return _h.json({ message: 'OK' }) }

  if (!event.Records && event.Records.length === 0) { return }

  for (var i = 0; i < event.Records.length; i++) {
    const data = JSON.parse(event.Records[i].body)
    const entityId = _h.strToId(data.entity)
    const db = await _h.db(data.account)

    if (data.dt) {
      const e = await db.collection('entity').findOne({ _id: entityId, aggregated: { $gte: new Date(data.dt) } }, { projection: { _id: true } })
      if (!e) {
        console.log('Entity', entityId, 'already aggregated at', data.dt)
        continue
      }
    }

    const properties = await db.collection('property').find({ entity: entityId, deleted: { $exists: false } }).toArray()

    if (properties.find(x => x.type === '_deleted')) {
      const deleteResponse = await db.collection('entity').deleteOne({ _id: entityId })
      console.log('Entity', entityId, 'deleted')
      continue
    }

    let entity = {
      aggregated: data.dt ? new Date(data.dt) : new Date()
    }

    for (var n = 0; n < properties.length; n++) {
      const prop = properties[n]
      let cleanProp = _.omit(prop, ['entity', 'type', 'created', 'search', 'public'])

      if (prop.reference && ['_viewer', '_expander', '_editor', '_owner'].includes(prop.type)) {
        if (!_.has(entity, 'access')) {
          _.set(entity, 'access', [])
        }
        entity.access.push(prop.reference)
      }

      if (!_.has(entity, ['private', prop.type])) {
        _.set(entity, ['private', prop.type], [])
      }

      if (prop.reference) {
        const referenceEntities = await db.collection('entity').findOne({ _id: prop.reference }, { projection: { 'private.name': true }})

        if (_.has(referenceEntities, 'private.name')) {
          cleanProp = referenceEntities.private.name.map(x => {
            return { ...cleanProp, ...x }
          })
        } else {
          cleanProp = { ...cleanProp, string: prop.reference }
        }
      }

      if (!Array.isArray(cleanProp)) {
        cleanProp = [cleanProp]
      }
      entity.private[prop.type] = [...entity.private[prop.type], ...cleanProp]

      if (prop.public) {
        if (!_.has(entity, ['public', prop.type])) {
          _.set(entity, ['public', prop.type], [])
        }

        entity.public[prop.type] = [...entity.public[prop.type], ...cleanProp]
      }
    }

    const replaceResponse = await db.collection('entity').replaceOne({ _id: entityId }, entity)

    const referrers = await db.collection('property').aggregate([
      { $match: { reference: entityId, deleted: { $exists: false } } },
      { $group: { _id: '$entity' } }
    ]).toArray()

    for (var i = 0; i < referrers.length; i++) {
      await _h.addEntityAggregateSqs(context, data.account, referrers[i]._id.toString(), entity.aggregated)
    }

    console.log('Entity', entityId, 'updated and added', referrers.length, 'entities to sqs')
  }
}
<|endoftext|>


<commit_before>/**
 * (This file was autogenerated by hob)
 *
 * @fileoverview
 * fixme: add fileoverview
 */

window.cls || ( window.cls = {} );

/**
  * @constructor
  */

window.cls.TestFramework = function()
{

  /* interface */

  this.get_bound_click_handler = function(){};
  this.get_bound_change_handler = function(){};
  /**
    * to clear the log entries
    */
  this.clear_log = function(){};

  /* privat */

  this._selected_service = "";
  this._status_map = cls.ServiceBase.get_status_map();
  this._event_map = cls.ServiceBase.get_event_map();

  const INDENT = "  ", RESPONSE = 2;

  this._get_indent = function(count)
  {
    var ret = "";
    while(count && count-- > 0)
    {
      ret += INDENT;
    }
    return ret;
  }

  this._pretty_print_payload_item = function(indent, name, definition, item)
  {
    return (
      this._get_indent(indent) +
      name + ': ' + (
        "message" in definition && "\n" +
            this._pretty_print_payload(item, definition["message"], indent + 1) ||
        !item && item !== 0 && "null" ||
        typeof item == "string" && "\"" + item + "\"" ||
        item));
  }

  this._pretty_print_payload = function(payload, definitions, indent)
  {
    var
    ret = [],
    item = null,
    i = 0,
    definition = null,
    j = 0;

    //# TODO message: self
    if (definitions)
    {
      for (; i < payload.length; i++)
      {
        item = payload[i];
        definition = definitions[i];
        if (definition["q"] == "repeated")
        {
          ret.push(this._get_indent(indent) + definition['name'] + ':');
          for( j = 0; j < item.length; j++)
          {
            ret.push(this._pretty_print_payload_item(
              indent + 1,
              definition['name'].replace("List", ""),
              definition,
              item[j]));
          }
        }
        else
        {
          ret.push(this._pretty_print_payload_item(
            indent,
            definition['name'],
            definition,
            item))
        }
      }
      return ret.join("\n")
    }
    return "";
  }

  // handle a command response
  this._handle_response = function(status, message, service, command)
  {
    this._last_message = Array.prototype.slice.call(arguments, 0);
    var response = document.getElementById('message-response');
    if(response)
    {
      response.parentNode.removeChild(response);
    }
    response =
      document.getElementById('message-container').
      appendChild(document.createElement('pre'));
    response.id = 'message-response';
    service = this._dashed_name(service);
    var command_id = this._event_map[service].indexOf('handle' + command);
    var definitions = window.command_map[service][command_id][RESPONSE];
    if (status != 0) // Use the error structure if we received an error response
        definitions = window.package_map["com.opera.stp"]["Error"];
    response.textContent =
      "response:\n  status: " +
      this._status_map[status] + "\n" +
      "  payload: \n" +
      (cookies.get('pretty-print-message') == 'true' ?
        this._pretty_print_payload(message, definitions, 2) :
        JSON.stringify(message));
  }

  // to highlight the selected element in a list
  this._update_selected = function(container, target)
  {
    var selected = container && container.getElementsByClassName('selected')[0];
    if(selected)
    {
      selected.className = selected.className.replace(/ ?selected/, '');
    }
    if(target)
    {
      target.className += (target.className ? ' ' : '') + 'selected';
    }
  }

  // to upadte the Command and Evenet List
  this._update_list = function(name, list, target)
  {
    var list_ele = document.getElementById(name.toLowerCase() + '-list-container');
    list_ele.innerHTML =
        "
" + name + " List

" +
          list.map(this._list_item).join("") +
        "
";
  }

  // callback to display a message definition
  this._show_def = function(xhr, context)
  {
    context.pre.innerHTML = xhr.responseText;
  }

  // to re-select entries of the Service or Command List
  this._reselect_element = function(/* list of names */)
  {
    var
    name = '',
    i = 0,
    j = 0,
    last_selected = '',
    lis = null,
    li = null;

    for( ; name = arguments[i]; i++)
    {
      if(last_selected = cookies.get(name))
      {
        lis = document.getElementById(name).getElementsByTagName('li');
        for( j = 0; ( li = lis[j] ) && li.textContent != last_selected; j++);
        if(li)
        {
          this._click_handler({target: li});
        }
      }
    }
  }

  // to re-select the last selected service and command or event
  // and display the according message definitions
  this._rebuild_last_state = function()
  {
    this._reselect_element('service-list', 'command-list');
  }

  // basic helpers
  // map argument
  this._list_item = function(name)
  {
    return "
" + name + "
";
  }

  this._dashed_name = function(name)
  {
    for ( var cur = '', i = 0, ret = ''; cur = name[i]; i++)
    {
      ret += /[A-Z]/.test(cur) && ( i ? '-' : '' ) + cur.toLowerCase() || cur;
    }
    return ret;
  }

  // generic click event handler
  this._click_handler = function(event)
  {
    var target = event.target;
    while (target && !target.id && (target = target.parentNode));
    if (target)
    {
      switch (target.id.replace(/-\d+$/, ''))
      {
        case 'window-id':
        {
          this._update_selected(target.parentNode, event.target);
          windows.set_debug_context(parseInt(event.target.id.slice(10)));
          break;
        }
        case 'service-list':
        {
          this._update_selected(target, event.target);
          document.getElementById('message-container').innerHTML = "";
          this._selected_service = event.target.textContent
          this._update_list('Command', service_descriptions.commands[this._selected_service], target);
          this._update_list('Event', service_descriptions.events[this._selected_service], target);
          cookies.set('service-list', this._selected_service, 2*60*60*1000);
          break;
        }
        case 'command-list':
        {
          this._update_selected(target, event.target);
          this._update_selected(document.getElementById('event-list'));
          var message_container = document.getElementById('message-container');
          message_container.innerHTML =
            "
Command " + event.target.textContent + "
" +
            "
command

" +
            "<textarea rows='10' id='proto-message'>[]</textarea>" +
            "
<input type='button' value='send' data-service='" + this._selected_service + "'" +
            " data-command='" + event.target.textContent +
            "' id = 'test-send-command' >
" +
            "
response

" +
              "
pretty print message " +
                "<input type='checkbox'" +
                  (cookies.get('pretty-print-message') == 'true' ? " checked='checked' " : "" ) +
                  " id='pretty-print-message'>" +
                "
";
          var pres = message_container.getElementsByTagName('pre');
          new XMLHttpRequest().loadResource(
              './defs/' + this._selected_service + '.commands.' + event.target.textContent + '.def',
              this._show_def,
              {'pre': pres[0]}
            )
          new XMLHttpRequest().loadResource(
              './defs/' + this._selected_service + '.responses.' + event.target.textContent + '.def',
              this._show_def,
              {'pre': pres[1]}
            )
          cookies.set('command-list', event.target.textContent, 2*60*60*1000);
          break;
        }
        case 'event-list':
        {
          this._update_selected(target, event.target);
          this._update_selected(document.getElementById('command-list'));
          var message_container = document.getElementById('message-container');
          message_container.innerHTML =
            "
Event " + event.target.textContent + "
" +
            "

";
          var pres = message_container.getElementsByTagName('pre');
          new XMLHttpRequest().loadResource(
              './defs/' + this._selected_service + '.events.' + event.target.textContent + '.def',
              this._show_def,
              {'pre': pres[0]}
            );
          break;
        }
        case 'test-send-command':
        {
          this._send_command(target);
          break;
        }
        case 'clear-log':
        {
          document.getElementById('log-container').firstElementChild.textContent = "";
          break;
        }
      }
    }
  }

  this._change_handler = function(event)
  {
    switch(event.target.id)
    {
      case 'pretty-print-message':
      {
        cookies.set('pretty-print-message', event.target.checked && 'true' || 'false');
        if(this._last_message)
        {
          this._handle_response.apply(this, this._last_message);
        }
        break;
      }
    }
  }

  /* implementation */
  this._send_command = function(target)
  {
    var service = target.getAttribute('data-service');
    var command = target.getAttribute('data-command');
    var response = document.getElementById('message-response');
    if(response)
    {
      response.parentNode.removeChild(response);
    }
    try
    {
      var message = eval('(' + document.getElementById('proto-message').value + ')');
      var tag = tagManager.set_callback(this, this._handle_response, [service, command]);
      services[this._dashed_name(service)]['request' + command](tag, message);
    }
    catch(e)
    {
      alert('not a valid message');
    };
  }

  this.get_bound_click_handler = function()
  {
    var self = this;
    return function(event)
    {
      self._click_handler(event);
    }
  }

  this.get_bound_change_handler = function()
  {
    var self = this;
    return function(event)
    {
      self._change_handler(event);
    }
  }

}<commit_msg>updated test_framework.js from hob<commit_after>/**
 * (This file was autogenerated by hob)
 *
 * @fileoverview
 * fixme: add fileoverview
 */

window.cls || ( window.cls = {} );

/**
  * @constructor
  */

window.cls.TestFramework = function()
{
  /**
    * class to inspect and test the scope interface
    *
    * the class expects the following markup:
    *
    *

 optional
    *
    *

    *
Scope

    *
WindowManager

    *
EcmascriptDebugger

    *
HttpLogger

    *     etc
    *

    *
    *

    *
    *

    *
    *

    *
    *  the two methods `get_bound_click_handler`
    *  and `get_bound_change_handler` must be set to
    *  an appropriated event listeners
    *
    */

  /* interface */

  this.get_bound_click_handler = function(){};
  this.get_bound_change_handler = function(){};
  /**
    * to clear the log entries
    */
  this.clear_log = function(){};

  /* privat */

  this._selected_service = "";
  this._status_map = cls.ServiceBase.get_status_map();
  this._event_map = cls.ServiceBase.get_event_map();

  const INDENT = "  ", RESPONSE = 2;

  this._get_indent = function(count)
  {
    var ret = "";
    while(count && count-- > 0)
    {
      ret += INDENT;
    }
    return ret;
  }

  this._pretty_print_payload_item = function(indent, name, definition, item)
  {
    return (
      this._get_indent(indent) +
      name + ': ' + (
        "message" in definition && "\n" +
            this._pretty_print_payload(item, definition["message"], indent + 1) ||
        !item && item === null &&  "null" ||
        typeof item == "string" && "\"" + item + "\"" ||
        item));
  }

  this._pretty_print_payload = function(payload, definitions, indent)
  {
    var
    ret = [],
    item = null,
    i = 0,
    definition = null,
    j = 0;

    //# TODO message: self
    if (definitions)
    {
      for (; i < payload.length; i++)
      {
        item = payload[i];
        definition = definitions[i];
        if (definition["q"] == "repeated")
        {
          ret.push(this._get_indent(indent) + definition['name'] + ':');
          for( j = 0; j < item.length; j++)
          {
            ret.push(this._pretty_print_payload_item(
              indent + 1,
              definition['name'].replace("List", ""),
              definition,
              item[j]));
          }
        }
        else
        {
          ret.push(this._pretty_print_payload_item(
            indent,
            definition['name'],
            definition,
            item))
        }
      }
      return ret.join("\n")
    }
    return "";
  }

  // handle a command response
  this._handle_response = function(status, message, service, command)
  {
    this._last_message = Array.prototype.slice.call(arguments, 0);
    var response = document.getElementById('message-response');
    if(response)
    {
      response.parentNode.removeChild(response);
    }
    response =
      document.getElementById('message-container').
      appendChild(document.createElement('pre'));
    response.id = 'message-response';
    service = this._dashed_name(service);
    var command_id = this._event_map[service].indexOf('handle' + command);
    var definitions = window.command_map[service][command_id][RESPONSE];
    if (status != 0) // Use the error structure if we received an error response
        definitions = window.package_map["com.opera.stp"]["Error"];
    response.textContent =
      "response:\n  status: " +
      this._status_map[status] + "\n" +
      "  payload: \n" +
      (cookies.get('pretty-print-message') == 'true' ?
        this._pretty_print_payload(message, definitions, 2) :
        JSON.stringify(message));
  }

  // to highlight the selected element in a list
  this._update_selected = function(container, target)
  {
    var selected = container && container.getElementsByClassName('selected')[0];
    if(selected)
    {
      selected.className = selected.className.replace(/ ?selected/, '');
    }
    if(target)
    {
      target.className += (target.className ? ' ' : '') + 'selected';
    }
  }

  // to upadte the Command and Evenet List
  this._update_list = function(name, list, target)
  {
    var list_ele = document.getElementById(name.toLowerCase() + '-list-container');
    list_ele.innerHTML =
        "
" + name + " List

" +
          list.map(this._list_item).join("") +
        "
";
  }

  // callback to display a message definition
  this._show_def = function(xhr, context)
  {
    context.pre.innerHTML = xhr.responseText;
  }

  // to re-select entries of the Service or Command List
  this._reselect_element = function(/* list of names */)
  {
    var
    name = '',
    i = 0,
    j = 0,
    last_selected = '',
    lis = null,
    li = null;

    for( ; name = arguments[i]; i++)
    {
      if(last_selected = cookies.get(name))
      {
        lis = document.getElementById(name).getElementsByTagName('li');
        for( j = 0; ( li = lis[j] ) && li.textContent != last_selected; j++);
        if(li)
        {
          this._click_handler({target: li});
        }
      }
    }
  }

  // to re-select the last selected service and command or event
  // and display the according message definitions
  this._rebuild_last_state = function()
  {
    this._reselect_element('service-list', 'command-list');
  }

  // basic helpers
  // map argument
  this._list_item = function(name)
  {
    return "
" + name + "
";
  }

  this._dashed_name = function(name)
  {
    for ( var cur = '', i = 0, ret = ''; cur = name[i]; i++)
    {
      ret += /[A-Z]/.test(cur) && ( i ? '-' : '' ) + cur.toLowerCase() || cur;
    }
    return ret;
  }

  // generic click event handler
  this._click_handler = function(event)
  {
    var target = event.target;
    while (target && !target.id && (target = target.parentNode));
    if (target)
    {
      switch (target.id)
      {
        case 'window-list':
        {
          this._update_selected(target.parentNode, event.target);
          windows.set_debug_context(parseInt(event.target.getAttribute('data-window-id')));
          break;
        }
        case 'service-list':
        {
          this._update_selected(target, event.target);
          document.getElementById('message-container').innerHTML = "";
          this._selected_service = event.target.textContent
          this._update_list('Command', service_descriptions.commands[this._selected_service], target);
          this._update_list('Event', service_descriptions.events[this._selected_service], target);
          cookies.set('service-list', this._selected_service, 2*60*60*1000);
          break;
        }
        case 'command-list':
        {
          this._update_selected(target, event.target);
          this._update_selected(document.getElementById('event-list'));
          var message_container = document.getElementById('message-container');
          message_container.innerHTML =
            "
Command " + event.target.textContent + "
" +
            "
command

" +
            "<textarea rows='10' id='proto-message'>[]</textarea>" +
            "
<input type='button' value='send' data-service='" + this._selected_service + "'" +
            " data-command='" + event.target.textContent +
            "' id = 'test-send-command' >
" +
            "
response

" +
              "
pretty print message " +
                "<input type='checkbox'" +
                  (cookies.get('pretty-print-message') == 'true' ? " checked='checked' " : "" ) +
                  " id='pretty-print-message'>" +
                "
";
          var pres = message_container.getElementsByTagName('pre');
          new XMLHttpRequest().loadResource(
              './defs/' + this._selected_service + '.commands.' + event.target.textContent + '.def',
              this._show_def,
              {'pre': pres[0]}
            )
          new XMLHttpRequest().loadResource(
              './defs/' + this._selected_service + '.responses.' + event.target.textContent + '.def',
              this._show_def,
              {'pre': pres[1]}
            )
          cookies.set('command-list', event.target.textContent, 2*60*60*1000);
          break;
        }
        case 'event-list':
        {
          this._update_selected(target, event.target);
          this._update_selected(document.getElementById('command-list'));
          var message_container = document.getElementById('message-container');
          message_container.innerHTML =
            "
Event " + event.target.textContent + "
" +
            "

";
          var pres = message_container.getElementsByTagName('pre');
          new XMLHttpRequest().loadResource(
              './defs/' + this._selected_service + '.events.' + event.target.textContent + '.def',
              this._show_def,
              {'pre': pres[0]}
            );
          break;
        }
        case 'test-send-command':
        {
          this._send_command(target);
          break;
        }
        case 'clear-log':
        {
          document.getElementById('log-container').firstElementChild.textContent = "";
          break;
        }
      }
    }
  }

  this._change_handler = function(event)
  {
    switch(event.target.id)
    {
      case 'pretty-print-message':
      {
        cookies.set('pretty-print-message', event.target.checked && 'true' || 'false');
        if(this._last_message)
        {
          this._handle_response.apply(this, this._last_message);
        }
        break;
      }
    }
  }

  /* implementation */
  this._send_command = function(target)
  {
    var service = target.getAttribute('data-service');
    var command = target.getAttribute('data-command');
    var response = document.getElementById('message-response');
    if(response)
    {
      response.parentNode.removeChild(response);
    }
    try
    {
      var message = eval('(' + document.getElementById('proto-message').value + ')');
      var tag = tagManager.set_callback(this, this._handle_response, [service, command]);
      services[this._dashed_name(service)]['request' + command](tag, message);
    }
    catch(e)
    {
      alert('not a valid message');
    };
  }

  this.get_bound_click_handler = function()
  {
    var self = this;
    return function(event)
    {
      self._click_handler(event);
    }
  }

  this.get_bound_change_handler = function()
  {
    var self = this;
    return function(event)
    {
      self._change_handler(event);
    }
  }

}<|endoftext|>


<commit_before>'use strict';
const echo = require('./modules/echo');
const error = require('./modules/error');

module.exports = class FunctionController {

  constructor(){
    this.moduleList = [new echo];
    this.error = new error;
    this.botName = 'KadseBot'
  }

  getCommand(inputData) {
    let command = inputData.toLowerCase();
    if (contains(inputData, ' ')) {
      command = command.split(' ')[0];
    }
    if (contains(command, '@'.concat(this.botName.toLowerCase()))) {
      return command.replace('@'.concat(this.botName.toLowerCase()), '');
    } else if (contains(command, ' @'.concat(this.botName.toLowerCase()))) {
      return command.replace(' @'.concat(this.botName.toLowerCase()), '');
    }
    return command;
  }

  getParams(inputData) {
    const params = inputData.split(' ');
    if (contains(inputData, ' @'.concat(this.botName))) {
      return params.slice(2);
    } else {
      return params.slice(1);
    }
  }

   executeCommand(commandSource,JsonData) {
    //   incrementUsage(JsonData);
    let command;
    if (typeof JsonData.message.text === 'undefined') {
      command = 'undefined';
    } else {
      command = getCommand(JsonData.message.text);
    }
    console.log('after getCommand'.concat(command));

    const payload= {};
    payload.original = JsonData;
    payload.parameters = getParams(JsonData);

    for(const module in this.moduleList) {
      if(`/${module.getCommand()}` === command) {
        return module.executeCommand(commandSource,payload);
      }
    }
    return this.error.executeCommand(commandSource,payload);
  }
};<commit_msg>fix functionController<commit_after>'use strict';
const echo = require('./modules/echo');
const error = require('./modules/error');

module.exports = class FunctionController {

  constructor(){
    this.moduleList = [new echo];
    this.error = new error;
    this.botName = 'KadseBot'
  }

  getCommand(inputData) {
    let command = inputData.toLowerCase();
    if (contains(inputData, ' ')) {
      command = command.split(' ')[0];
    }
    if (contains(command, '@'.concat(this.botName.toLowerCase()))) {
      return command.replace('@'.concat(this.botName.toLowerCase()), '');
    } else if (contains(command, ' @'.concat(this.botName.toLowerCase()))) {
      return command.replace(' @'.concat(this.botName.toLowerCase()), '');
    }
    return command;
  }

  getParams(inputData) {
    const params = inputData.split(' ');
    if (contains(inputData, ' @'.concat(this.botName))) {
      return params.slice(2);
    } else {
      return params.slice(1);
    }
  }

   executeCommand(commandSource,JsonData) {
    //   incrementUsage(JsonData);
    let command;
    if (typeof JsonData.message.text === 'undefined') {
      command = 'undefined';
    } else {
      command = this.getCommand(JsonData.message.text);
    }
    console.log('after getCommand'.concat(command));

    const payload= {};
    payload.original = JsonData;
    payload.parameters = this.getParams(JsonData);

    for(const module in this.moduleList) {
      if(`/${module.getCommand()}` === command) {
        return module.executeCommand(commandSource,payload);
      }
    }
    return this.error.executeCommand(commandSource,payload);
  }
};<|endoftext|>


<commit_before>/**
 * @fileoverview Creates a YouTube player in a modal.
 */

var classes = require('../utils/classes');
var dom = require('../utils/dom');
var events = require('../utils/events');
var objects = require('../utils/objects');
var useragent = require('../utils/useragent');

var player = null;
var singleton = null;
var defaultConfig = {
  useHandlerOnMobile: true,
  history: false,
  historyNamePrefix: 'video:',
  transitionDuration: 300,
  className: 'ak-youtubemodal',
  parentSelector: 'body',
  onModalOpen: null,
  onModalClose: null,
  playerVars: {
    'autohide': 1,
    'autoplay': 1,
    'fs': 1,
    'modestbranding': 1,
    'rel': 0,
    'showinfo': 0,
    'iv_load_policy': 3
  }
};

/**
 * Plays a YouTube video in a modal dialog.
 * @constructor
 */
function YouTubeModal(config) {
  this.config = config;
  this.parentElement = document.querySelector(this.config.parentSelector);
  this.closeEventListener_ = this.setActive_.bind(this, false);
  this.popstateListener_ = this.onHistoryChange_.bind(this);
  this.initDom_();
  this.lastActiveVideoId_ = null;
  this.scrollY = 0;

  var func = function(targetEl) {
    var data = 'data-' + this.config.className + '-video-id';
    var videoId = targetEl.getAttribute(data);
    var startDataAttribute = 'data-' + this.config.className + '-video-start-seconds';
    var startTime = +targetEl.getAttribute(startDataAttribute);
    if (videoId) {
      this.play(videoId, true /* opt_updateState */, startTime);
    }
  }.bind(this);

  // Loads YouTube iframe API.
  events.addDelegatedListener(document, 'click', func);
  var tag = document.createElement('script');
  tag.setAttribute('src', 'https://www.youtube.com/iframe_api');
  this.parentElement.appendChild(tag);
}

/**
 * Creates the DOM for the YouTube modal.
 * @private
 */
YouTubeModal.prototype.initDom_ = function() {
  var createDom = dom.createDom;
  var el = createDom('div', this.config.className);
  var closeEl = createDom('div', this.config.className + '-x');
  closeEl.setAttribute('aria-label', 'Close video player');
  closeEl.setAttribute('role', 'button');
  closeEl.setAttribute('tabindex', '0');
  el.appendChild(closeEl);
  el.appendChild(createDom('div', this.config.className + '-player'));
  el.appendChild(createDom('div', this.config.className + '-mask'));
  this.parentElement.appendChild(el);
  closeEl.addEventListener('click', this.closeEventListener_);

  if (this.config.history) {
    window.addEventListener('popstate', this.popstateListener_);
  }
};

YouTubeModal.prototype.dispose = function() {
  var el = document.querySelector('.' + this.config.className);
  var closeEl = document.querySelector('.' + this.config.className + '-x');
  closeEl.removeEventListener('click', this.closeEventListener_);
  this.parentElement.removeChild(el);
  if (this.config.history) {
    window.removeEventListener('popstate', this.popstateListener_);
  }
};

/**
 * Sets the modal's visibility.
 * @param {boolean} enabled Whether the modal should be visible.
 */
YouTubeModal.prototype.setVisible = function(enabled) {
  // Plays or pauses depending on visibility.
  if (player) {
    // Delay call to give player time to load.
    window.setTimeout(function() {
      if (enabled) {
        player.playVideo();
      } else {
        player.pauseVideo();
      }
    }, 100);
  }

  var _keyToggle = function(e) {
    if (e.keyCode == 27) {
      this.setActive_(false);
      document.body.removeEventListener('keydown', _keyToggle);
    }
  }.bind(this);

  if (enabled) {
    document.body.addEventListener('keydown', _keyToggle);
  } else {
    document.body.removeEventListener('keydown', _keyToggle);
  }

  var lightboxEl = document.querySelector('.' + this.config.className);
  window.setTimeout(function() {
    classes.enable(lightboxEl, this.config.className + '--enabled', enabled);
  }.bind(this), enabled ? 0 : this.config.transitionDuration);
  window.setTimeout(function() {
    classes.enable(lightboxEl, this.config.className + '--visible', enabled);
  }.bind(this), enabled ? this.config.transitionDuration : 0);
};

/**
 * Sets whether the modal is active (and thus visible and playing). Handles history state if applicable.
 * @param {boolean} active Whether the modal is active.
 * @param {string=} opt_videoId Video ID to use in the history hash.
 * @param {boolean=} opt_updateState Whether to update the history state.
 * @private
 */
YouTubeModal.prototype.setActive_ = function(active, opt_videoId, opt_updateState) {
  if (opt_videoId) {
    this.lastActiveVideoId_ = opt_videoId;
  }

  if (active) {
    this.config.onModalOpen && this.config.onModalOpen(this.lastActiveVideoId_);
    this.scrollY = window.pageYOffset;
  } else {
    this.config.onModalClose && this.config.onModalClose(this.lastActiveVideoId_);
    window.scrollTo(0, this.scrollY);
  }
  if (!this.config.history) {
    this.setVisible(active);
    return;
  }

  this.setVisible(active);
  if (opt_updateState === false) {
    return;
  }
  var videoId = opt_videoId || this.activeVideoId_;
  if (active) {
    // Avoid pushing two equal items onto the state.
    var stateId = window.history.state && window.history.state['videoId'];
    if (stateId == videoId) {
      return;
    }
    window.history.pushState(
        {'videoId': videoId}, '',
        '#' + this.config.historyNamePrefix + videoId);
  } else {
    window.history.pushState(
        {'videoId': null}, '', window.location.pathname);
  }
};

/**
 * Callback for changes to the history state.
 * @param {Event} e Pop state event.
 * @private
 */
YouTubeModal.prototype.onHistoryChange_ = function(e) {
  if (e.state && e.state['videoId']) {
    this.play(e.state['videoId'], false);
  } else {
    this.setVisible(false);
  }
};

/**
 * Plays a YouTube video.
 * @param {string} videoId Video ID to play.
 * @param {boolean=} opt_updateState Whether to update the history state.
 * @param {number=} opt_startTime A specific time in the video to start at.
 */
YouTubeModal.prototype.play = function(videoId, opt_updateState, opt_startTime) {
  var useHandler = (
      this.config.useHandlerOnMobile
      && (useragent.isIOS() || useragent.isAndroid()));

  if (useHandler) {
    var url = 'https://m.youtube.com/watch?v=' + videoId;
    if (opt_startTime) {
      url += '&t=' + opt_startTime + 's';
    }
    window.location.href = url;
    return;
  }

  this.setActive_(true, videoId, opt_updateState);
  if (player && videoId == this.activeVideoId_) {
    return;
  } else if (player && videoId != this.activeVideoId_) {
    player.loadVideoById(videoId, 0, 'large');
    this.activeVideoId_ = videoId;
    return;
  }
  var playerEl = document.querySelector('.' + this.config.className + '-player');
  let playerVars = objects.clone(this.config.playerVars);
  if (opt_startTime) {
    playerVars['start'] = opt_startTime;
  }

  var options = {
    'videoId': videoId,
    'playerVars': playerVars
  };
  player = new YT.Player(playerEl, options);
  this.activeVideoId_ = videoId;
}

/**
 * Initializes a YouTube modal dialog singleton.
 * @param {Object=} opt_config Config options.
 */
function init(opt_config) {
  if (singleton) {
    return;
  }
  var config = objects.clone(defaultConfig);
  if (opt_config) {
    objects.merge(config, opt_config);
  }

  singleton = new YouTubeModal(config);
}

function dispose() {
  if (!singleton) {
    return;
  }
  singleton.dispose();
  singleton = null;
  player = null;
}

/**
 * Plays a YouTube video in a modal, without requiring a click on an element.
 * @param {string} videoId YouTube video ID.
 */
function play(videoId) {
  if (!singleton) {
    throw 'youtubemodal.init must be run first.';
  }
  return singleton.play(videoId);
}

module.exports = {
  dispose: dispose,
  init: init,
  play: play
};
<commit_msg>destroy() YT player in youtubemodal dispose<commit_after>/**
 * @fileoverview Creates a YouTube player in a modal.
 */

var classes = require('../utils/classes');
var dom = require('../utils/dom');
var events = require('../utils/events');
var objects = require('../utils/objects');
var useragent = require('../utils/useragent');

var player = null;
var singleton = null;
var defaultConfig = {
  useHandlerOnMobile: true,
  history: false,
  historyNamePrefix: 'video:',
  transitionDuration: 300,
  className: 'ak-youtubemodal',
  parentSelector: 'body',
  onModalOpen: null,
  onModalClose: null,
  playerVars: {
    'autohide': 1,
    'autoplay': 1,
    'fs': 1,
    'modestbranding': 1,
    'rel': 0,
    'showinfo': 0,
    'iv_load_policy': 3
  }
};

/**
 * Plays a YouTube video in a modal dialog.
 * @constructor
 */
function YouTubeModal(config) {
  this.config = config;
  this.parentElement = document.querySelector(this.config.parentSelector);
  this.closeEventListener_ = this.setActive_.bind(this, false);
  this.popstateListener_ = this.onHistoryChange_.bind(this);
  this.initDom_();
  this.lastActiveVideoId_ = null;
  this.scrollY = 0;

  var func = function(targetEl) {
    var data = 'data-' + this.config.className + '-video-id';
    var videoId = targetEl.getAttribute(data);
    var startDataAttribute = 'data-' + this.config.className + '-video-start-seconds';
    var startTime = +targetEl.getAttribute(startDataAttribute);
    if (videoId) {
      this.play(videoId, true /* opt_updateState */, startTime);
    }
  }.bind(this);

  // Loads YouTube iframe API.
  events.addDelegatedListener(document, 'click', func);
  var tag = document.createElement('script');
  tag.setAttribute('src', 'https://www.youtube.com/iframe_api');
  this.parentElement.appendChild(tag);
}

/**
 * Creates the DOM for the YouTube modal.
 * @private
 */
YouTubeModal.prototype.initDom_ = function() {
  var createDom = dom.createDom;
  var el = createDom('div', this.config.className);
  var closeEl = createDom('div', this.config.className + '-x');
  closeEl.setAttribute('aria-label', 'Close video player');
  closeEl.setAttribute('role', 'button');
  closeEl.setAttribute('tabindex', '0');
  el.appendChild(closeEl);
  el.appendChild(createDom('div', this.config.className + '-player'));
  el.appendChild(createDom('div', this.config.className + '-mask'));
  this.parentElement.appendChild(el);
  closeEl.addEventListener('click', this.closeEventListener_);

  if (this.config.history) {
    window.addEventListener('popstate', this.popstateListener_);
  }
};

YouTubeModal.prototype.dispose = function() {
  var el = document.querySelector('.' + this.config.className);
  var closeEl = document.querySelector('.' + this.config.className + '-x');
  closeEl.removeEventListener('click', this.closeEventListener_);
  this.parentElement.removeChild(el);
  if (this.config.history) {
    window.removeEventListener('popstate', this.popstateListener_);
  }
};

/**
 * Sets the modal's visibility.
 * @param {boolean} enabled Whether the modal should be visible.
 */
YouTubeModal.prototype.setVisible = function(enabled) {
  // Plays or pauses depending on visibility.
  if (player) {
    // Delay call to give player time to load.
    window.setTimeout(function() {
      if (enabled) {
        player.playVideo();
      } else {
        player.pauseVideo();
      }
    }, 100);
  }

  var _keyToggle = function(e) {
    if (e.keyCode == 27) {
      this.setActive_(false);
      document.body.removeEventListener('keydown', _keyToggle);
    }
  }.bind(this);

  if (enabled) {
    document.body.addEventListener('keydown', _keyToggle);
  } else {
    document.body.removeEventListener('keydown', _keyToggle);
  }

  var lightboxEl = document.querySelector('.' + this.config.className);
  window.setTimeout(function() {
    classes.enable(lightboxEl, this.config.className + '--enabled', enabled);
  }.bind(this), enabled ? 0 : this.config.transitionDuration);
  window.setTimeout(function() {
    classes.enable(lightboxEl, this.config.className + '--visible', enabled);
  }.bind(this), enabled ? this.config.transitionDuration : 0);
};

/**
 * Sets whether the modal is active (and thus visible and playing). Handles history state if applicable.
 * @param {boolean} active Whether the modal is active.
 * @param {string=} opt_videoId Video ID to use in the history hash.
 * @param {boolean=} opt_updateState Whether to update the history state.
 * @private
 */
YouTubeModal.prototype.setActive_ = function(active, opt_videoId, opt_updateState) {
  if (opt_videoId) {
    this.lastActiveVideoId_ = opt_videoId;
  }

  if (active) {
    this.config.onModalOpen && this.config.onModalOpen(this.lastActiveVideoId_);
    this.scrollY = window.pageYOffset;
  } else {
    this.config.onModalClose && this.config.onModalClose(this.lastActiveVideoId_);
    window.scrollTo(0, this.scrollY);
  }
  if (!this.config.history) {
    this.setVisible(active);
    return;
  }

  this.setVisible(active);
  if (opt_updateState === false) {
    return;
  }
  var videoId = opt_videoId || this.activeVideoId_;
  if (active) {
    // Avoid pushing two equal items onto the state.
    var stateId = window.history.state && window.history.state['videoId'];
    if (stateId == videoId) {
      return;
    }
    window.history.pushState(
        {'videoId': videoId}, '',
        '#' + this.config.historyNamePrefix + videoId);
  } else {
    window.history.pushState(
        {'videoId': null}, '', window.location.pathname);
  }
};

/**
 * Callback for changes to the history state.
 * @param {Event} e Pop state event.
 * @private
 */
YouTubeModal.prototype.onHistoryChange_ = function(e) {
  if (e.state && e.state['videoId']) {
    this.play(e.state['videoId'], false);
  } else {
    this.setVisible(false);
  }
};

/**
 * Plays a YouTube video.
 * @param {string} videoId Video ID to play.
 * @param {boolean=} opt_updateState Whether to update the history state.
 * @param {number=} opt_startTime A specific time in the video to start at.
 */
YouTubeModal.prototype.play = function(videoId, opt_updateState, opt_startTime) {
  var useHandler = (
      this.config.useHandlerOnMobile
      && (useragent.isIOS() || useragent.isAndroid()));

  if (useHandler) {
    var url = 'https://m.youtube.com/watch?v=' + videoId;
    if (opt_startTime) {
      url += '&t=' + opt_startTime + 's';
    }
    window.location.href = url;
    return;
  }

  this.setActive_(true, videoId, opt_updateState);
  if (player && videoId == this.activeVideoId_) {
    return;
  } else if (player && videoId != this.activeVideoId_) {
    player.loadVideoById(videoId, 0, 'large');
    this.activeVideoId_ = videoId;
    return;
  }
  var playerEl = document.querySelector('.' + this.config.className + '-player');
  let playerVars = objects.clone(this.config.playerVars);
  if (opt_startTime) {
    playerVars['start'] = opt_startTime;
  }

  var options = {
    'videoId': videoId,
    'playerVars': playerVars
  };
  player = new YT.Player(playerEl, options);
  this.activeVideoId_ = videoId;
}

/**
 * Initializes a YouTube modal dialog singleton.
 * @param {Object=} opt_config Config options.
 */
function init(opt_config) {
  if (singleton) {
    return;
  }
  var config = objects.clone(defaultConfig);
  if (opt_config) {
    objects.merge(config, opt_config);
  }

  singleton = new YouTubeModal(config);
}

function dispose() {
  if (!singleton) {
    return;
  }
  singleton.dispose();
  singleton = null;
  if (player) {
    player.destroy();
    player = null;
  }
}

/**
 * Plays a YouTube video in a modal, without requiring a click on an element.
 * @param {string} videoId YouTube video ID.
 */
function play(videoId) {
  if (!singleton) {
    throw 'youtubemodal.init must be run first.';
  }
  return singleton.play(videoId);
}

module.exports = {
  dispose: dispose,
  init: init,
  play: play
};
<|endoftext|>


<commit_before>var render = require('../application/render');
var Backbone = require('backbone');
var ArgumentNullException = require('../exception/ArgumentNullException');
var message = require('../message');
var userHelper = require('../user');
var dispatcher = require('../dispatcher');

/**
 * Function call before each route.
 */
function beforeRouting(){
  console.log('Routing: before');
  //Clear header
  dispatcher.handleViewAction({
    data: {
      cartridgeComponent: React.DOM.div,
      summaryComponent: React.DOM.div,
      actions: {primary: [], secondary: []}
    },
    type: 'update'
  });
  //Clear errors

  //Render stack errors

}
module.exports = Backbone.Router.extend({
  noRoleRoute: 'home',
  route : function (urlRoute, name, callback) {
    var router = this;
    if (!callback){
      callback = this[name];
    }
    if(callback === undefined || callback === null){
      console.warn(`
        The callback is not defined for your route, you should check these two points in the routes property of your router:
        - You directly have a callback associated to your route: 'routeName': function handleRoute(){ //do what you want}
        - You have a string property, your router should have a function in its declaration with the same name as your property
        For more informations please see http://backbonejs.org/#Router-route
      `);
      throw new ArgumentNullException(`The route callback seems to be undefined, please check your router file for your route: ${name}`);
    }
    var customWrapperAroundCallback = ()=>{
      var currentRoute = urlRoute;
      console.log(`Route change: ${urlRoute}`);
      //The default route is the noRoleRoute by default
      if(currentRoute === ''){
        currentRoute = router.noRoleRoute;
      }
      var routeName = '';//siteDescriptionBuilder.findRouteName(currentRoute);
      var routeDescciption = {roles: ['DEFAULT_ROLE']};//siteDescriptionBuilder.getRoute(routeName);
      if((routeDescciption === undefined && currentRoute !== '') || !userHelper.hasRole(routeDescciption.roles)){
        message.addErrorMessage('application.noRights');
        return Backbone.history.navigate('', true);
      }else {

        //Rendre all the errors notifications in the stack.
        //backboneNotification.renderNotifications();
        beforeRouting();
      }
      //console.log('routeObject', siteDescriptionBuilder.getRoute(n));
      callback.apply(router, arguments);

  };
    return Backbone.Router.prototype.route.call(this, urlRoute, name, customWrapperAroundCallback);
  },
  /**
   * Render the compoennt into the page content.
   */
  _pageContent(component, options){
    return render(component, '[data-focus="page-content"]', options);
  }
});
<commit_msg>[router] Add empty div<commit_after>var render = require('../application/render');
var Backbone = require('backbone');
var ArgumentNullException = require('../exception/ArgumentNullException');
var message = require('../message');
var userHelper = require('../user');
var dispatcher = require('../dispatcher');

/**
 * Function call before each route.
 */
function beforeRouting(){
  console.log('Routing: before');
  //Clear header
  dispatcher.handleViewAction({
    data: {
      cartridgeComponent: {component: React.DOM.div},
      summaryComponent: {component: React.DOM.div},
      actions: {primary: [], secondary: []}
    },
    type: 'update'
  });
  //Clear errors

  //Render stack errors

}
module.exports = Backbone.Router.extend({
  noRoleRoute: 'home',
  route : function (urlRoute, name, callback) {
    var router = this;
    if (!callback){
      callback = this[name];
    }
    if(callback === undefined || callback === null){
      console.warn(`
        The callback is not defined for your route, you should check these two points in the routes property of your router:
        - You directly have a callback associated to your route: 'routeName': function handleRoute(){ //do what you want}
        - You have a string property, your router should have a function in its declaration with the same name as your property
        For more informations please see http://backbonejs.org/#Router-route
      `);
      throw new ArgumentNullException(`The route callback seems to be undefined, please check your router file for your route: ${name}`);
    }
    var customWrapperAroundCallback = ()=>{
      var currentRoute = urlRoute;
      console.log(`Route change: ${urlRoute}`);
      //The default route is the noRoleRoute by default
      if(currentRoute === ''){
        currentRoute = router.noRoleRoute;
      }
      var routeName = '';//siteDescriptionBuilder.findRouteName(currentRoute);
      var routeDescciption = {roles: ['DEFAULT_ROLE']};//siteDescriptionBuilder.getRoute(routeName);
      if((routeDescciption === undefined && currentRoute !== '') || !userHelper.hasRole(routeDescciption.roles)){
        message.addErrorMessage('application.noRights');
        return Backbone.history.navigate('', true);
      }else {

        //Rendre all the errors notifications in the stack.
        //backboneNotification.renderNotifications();
        beforeRouting();
      }
      //console.log('routeObject', siteDescriptionBuilder.getRoute(n));
      callback.apply(router, arguments);

  };
    return Backbone.Router.prototype.route.call(this, urlRoute, name, customWrapperAroundCallback);
  },
  /**
   * Render the compoennt into the page content.
   */
  _pageContent(component, options){
    return render(component, '[data-focus="page-content"]', options);
  }
});
<|endoftext|>


<commit_before>const { Structures } = require('discord.js');
const Command = require('../commands/base');
const GuildSettingsHelper = require('../providers/helper');

module.exports = Structures.extend('Guild', Guild => {
	/**
	 * A fancier Guild for fancier people.
	 * @extends Guild
	 */
	class CommandoGuild extends Guild {
		constructor(client, data) {
			super(client, data);

			/**
			 * Shortcut to use setting provider methods for this guild
			 * @type {GuildSettingsHelper}
			 */
			this.settings = new GuildSettingsHelper(this.client, this);

			/**
			 * Internal command prefix for the guild, controlled by the {@link CommandoGuild#commandPrefix}
			 * getter/setter
			 * @name CommandoGuild#_commandPrefix
			 * @type {?string}
			 * @private
			 */
			this._commandPrefix = null;
		}

		/**
		 * Command prefix in the guild. An empty string indicates that there is no prefix, and only mentions will be used.
		 * Setting to `null` means that the prefix from {@link CommandoClient#commandPrefix} will be used instead.
		 * @type {string}
		 * @emits {@link CommandoClient#commandPrefixChange}
		 */
		get commandPrefix() {
			if(this._commandPrefix === null) return this.client.commandPrefix;
			return this._commandPrefix;
		}

		set commandPrefix(prefix) {
			this._commandPrefix = prefix;
			/**
			 * Emitted whenever a guild's command prefix is changed
			 * @event CommandoClient#commandPrefixChange
			 * @param {?Guild} guild - Guild that the prefix was changed in (null for global)
			 * @param {?string} prefix - New command prefix (null for default)
			 */
			this.client.emit('commandPrefixChange', this, this._commandPrefix);
		}

		/**
		 * Sets whether a command is enabled in the guild
		 * @param {CommandResolvable} command - Command to set status of
		 * @param {boolean} enabled - Whether the command should be enabled
		 */
		setCommandEnabled(command, enabled) {
			command = this.client.registry.resolveCommand(command);
			if(command.guarded) throw new Error('The command is guarded.');
			if(typeof enabled === 'undefined') throw new TypeError('Enabled must not be undefined.');
			enabled = Boolean(enabled);
			if(!this._commandsEnabled) {
				/**
				 * Map object of internal command statuses, mapped by command name
				 * @type {Object}
				 * @private
				 */
				this._commandsEnabled = {};
			}
			this._commandsEnabled[command.name] = enabled;
			/**
			 * Emitted whenever a command is enabled/disabled in a guild
			 * @event CommandoClient#commandStatusChange
			 * @param {?Guild} guild - Guild that the command was enabled/disabled in (null for global)
			 * @param {Command} command - Command that was enabled/disabled
			 * @param {boolean} enabled - Whether the command is enabled
			 */
			this.client.emit('commandStatusChange', this, command, enabled);
		}

		/**
		 * Checks whether a command is enabled in the guild (does not take the command's group status into account)
		 * @param {CommandResolvable} command - Command to check status of
		 * @return {boolean}
		 */
		isCommandEnabled(command) {
			command = this.client.registry.resolveCommand(command);
			if(command.guarded) return true;
			if(!this._commandsEnabled || typeof this._commandsEnabled[command.name] === 'undefined') {
				return command._globalEnabled;
			}
			return this._commandsEnabled[command.name];
		}

		/**
		 * Sets whether a command group is enabled in the guild
		 * @param {CommandGroupResolvable} group - Command to set status of
		 * @param {boolean} enabled - Whether the group should be enabled
		 */
		setGroupEnabled(group, enabled) {
			group = this.client.registry.resolveGroup(group);
			if(group.guarded) throw new Error('The group is guarded.');
			if(typeof enabled === 'undefined') throw new TypeError('Enabled must not be undefined.');
			enabled = Boolean(enabled);
			if(!this._groupsEnabled) {
				/**
				 * Internal map object of group statuses, mapped by group ID
				 * @type {Object}
				 * @private
				 */
				this._groupsEnabled = {};
			}
			this._groupsEnabled[group.id] = enabled;
			/**
			 * Emitted whenever a command group is enabled/disabled in a guild
			 * @event CommandoClient#groupStatusChange
			 * @param {?Guild} guild - Guild that the group was enabled/disabled in (null for global)
			 * @param {CommandGroup} group - Group that was enabled/disabled
			 * @param {boolean} enabled - Whether the group is enabled
			 */
			this.client.emit('groupStatusChange', this, group, enabled);
		}

		/**
		 * Checks whether a command group is enabled in the guild
		 * @param {CommandGroupResolvable} group - Group to check status of
		 * @return {boolean}
		 */
		isGroupEnabled(group) {
			group = this.client.registry.resolveGroup(group);
			if(group.guarded) return true;
			if(!this._groupsEnabled || typeof this._groupsEnabled[group.id] === 'undefined') return group._globalEnabled;
			return this._groupsEnabled[group.id];
		}

		/**
		 * Creates a command usage string using the guild's prefix
		 * @param {string} [command] - A command + arg string
		 * @param {User} [user=this.client.user] - User to use for the mention command format
		 * @return {string}
		 */
		commandUsage(command, user = this.client.user) {
			return Command.usage(command, this.commandPrefix, user);
		}
	}

	return CommandoGuild;
});
<commit_msg>Use spread operator for Guild constructor<commit_after>const { Structures } = require('discord.js');
const Command = require('../commands/base');
const GuildSettingsHelper = require('../providers/helper');

module.exports = Structures.extend('Guild', Guild => {
	/**
	 * A fancier Guild for fancier people.
	 * @extends Guild
	 */
	class CommandoGuild extends Guild {
		constructor(...args) {
			super(...args);

			/**
			 * Shortcut to use setting provider methods for this guild
			 * @type {GuildSettingsHelper}
			 */
			this.settings = new GuildSettingsHelper(this.client, this);

			/**
			 * Internal command prefix for the guild, controlled by the {@link CommandoGuild#commandPrefix}
			 * getter/setter
			 * @name CommandoGuild#_commandPrefix
			 * @type {?string}
			 * @private
			 */
			this._commandPrefix = null;
		}

		/**
		 * Command prefix in the guild. An empty string indicates that there is no prefix, and only mentions will be used.
		 * Setting to `null` means that the prefix from {@link CommandoClient#commandPrefix} will be used instead.
		 * @type {string}
		 * @emits {@link CommandoClient#commandPrefixChange}
		 */
		get commandPrefix() {
			if(this._commandPrefix === null) return this.client.commandPrefix;
			return this._commandPrefix;
		}

		set commandPrefix(prefix) {
			this._commandPrefix = prefix;
			/**
			 * Emitted whenever a guild's command prefix is changed
			 * @event CommandoClient#commandPrefixChange
			 * @param {?Guild} guild - Guild that the prefix was changed in (null for global)
			 * @param {?string} prefix - New command prefix (null for default)
			 */
			this.client.emit('commandPrefixChange', this, this._commandPrefix);
		}

		/**
		 * Sets whether a command is enabled in the guild
		 * @param {CommandResolvable} command - Command to set status of
		 * @param {boolean} enabled - Whether the command should be enabled
		 */
		setCommandEnabled(command, enabled) {
			command = this.client.registry.resolveCommand(command);
			if(command.guarded) throw new Error('The command is guarded.');
			if(typeof enabled === 'undefined') throw new TypeError('Enabled must not be undefined.');
			enabled = Boolean(enabled);
			if(!this._commandsEnabled) {
				/**
				 * Map object of internal command statuses, mapped by command name
				 * @type {Object}
				 * @private
				 */
				this._commandsEnabled = {};
			}
			this._commandsEnabled[command.name] = enabled;
			/**
			 * Emitted whenever a command is enabled/disabled in a guild
			 * @event CommandoClient#commandStatusChange
			 * @param {?Guild} guild - Guild that the command was enabled/disabled in (null for global)
			 * @param {Command} command - Command that was enabled/disabled
			 * @param {boolean} enabled - Whether the command is enabled
			 */
			this.client.emit('commandStatusChange', this, command, enabled);
		}

		/**
		 * Checks whether a command is enabled in the guild (does not take the command's group status into account)
		 * @param {CommandResolvable} command - Command to check status of
		 * @return {boolean}
		 */
		isCommandEnabled(command) {
			command = this.client.registry.resolveCommand(command);
			if(command.guarded) return true;
			if(!this._commandsEnabled || typeof this._commandsEnabled[command.name] === 'undefined') {
				return command._globalEnabled;
			}
			return this._commandsEnabled[command.name];
		}

		/**
		 * Sets whether a command group is enabled in the guild
		 * @param {CommandGroupResolvable} group - Command to set status of
		 * @param {boolean} enabled - Whether the group should be enabled
		 */
		setGroupEnabled(group, enabled) {
			group = this.client.registry.resolveGroup(group);
			if(group.guarded) throw new Error('The group is guarded.');
			if(typeof enabled === 'undefined') throw new TypeError('Enabled must not be undefined.');
			enabled = Boolean(enabled);
			if(!this._groupsEnabled) {
				/**
				 * Internal map object of group statuses, mapped by group ID
				 * @type {Object}
				 * @private
				 */
				this._groupsEnabled = {};
			}
			this._groupsEnabled[group.id] = enabled;
			/**
			 * Emitted whenever a command group is enabled/disabled in a guild
			 * @event CommandoClient#groupStatusChange
			 * @param {?Guild} guild - Guild that the group was enabled/disabled in (null for global)
			 * @param {CommandGroup} group - Group that was enabled/disabled
			 * @param {boolean} enabled - Whether the group is enabled
			 */
			this.client.emit('groupStatusChange', this, group, enabled);
		}

		/**
		 * Checks whether a command group is enabled in the guild
		 * @param {CommandGroupResolvable} group - Group to check status of
		 * @return {boolean}
		 */
		isGroupEnabled(group) {
			group = this.client.registry.resolveGroup(group);
			if(group.guarded) return true;
			if(!this._groupsEnabled || typeof this._groupsEnabled[group.id] === 'undefined') return group._globalEnabled;
			return this._groupsEnabled[group.id];
		}

		/**
		 * Creates a command usage string using the guild's prefix
		 * @param {string} [command] - A command + arg string
		 * @param {User} [user=this.client.user] - User to use for the mention command format
		 * @return {string}
		 */
		commandUsage(command, user = this.client.user) {
			return Command.usage(command, this.commandPrefix, user);
		}
	}

	return CommandoGuild;
});
<|endoftext|>


<commit_before>var express = require('express');
var booksRouter = express.Router();

var dbLayer = require('../models/DB_MYSQL.js');

booksRouter.route('/')
.get(function(req, res, next) {
    var data = {};
    data.filter = req.query.filter;
    data.limit = req.query.limit;
    data.offset = req.query.offset;
    data.search = req.query.search;

<<<<<<< a1727392eb0907e2976a16cbbbeba5ea3921e80e
    dbLayer.getBooksAlt(data, function(err, resp) {
=======
    console.log('data limit',data.limit);

    dbLayer.getBooks(data, function(err, resp) {
>>>>>>> add elements on scrolling
        if (err) {
            res.json({ success: false, msg: err });
        } else {
            console.log(resp);
            res.json({ success: true, data: resp});
        }
    });

});

booksRouter.route('/:book_id')
.get(function(req, res, next) {

    dbLayer.getBook(req.params.book_id, function(err, resp) {
        if (err) {
            res.json({ success: false, msg: err });
        } else {
            res.json({ success: true, data: resp});
        }
    });
});

booksRouter.route('/:book_id/order')
.get(function(req, res, next) {
    var data = {};
    data.book_id = req.params.book_id;
    data.email = req.query.email;
    dbLayer.addToQueue(data, function(err, resp) {
        if (err) {
            res.json({ success: false, msg: err });
        } else {
            res.json({ success: true});
        }
    });
});

module.exports = booksRouter;
<commit_msg>fix conflict in routes/books<commit_after>var express = require('express');
var booksRouter = express.Router();

var dbLayer = require('../models/DB_MYSQL.js');

booksRouter.route('/')
.get(function(req, res, next) {
    var data = {};
    data.filter = req.query.filter;
    data.limit = req.query.limit;
    data.offset = req.query.offset;
    data.search = req.query.search;

    dbLayer.getBooksAlt(data, function(err, resp) {
        if (err) {
            res.json({ success: false, msg: err });
        } else {
            res.json({ success: true, data: resp});
        }
    });
});

booksRouter.route('/:book_id')
.get(function(req, res, next) {

    dbLayer.getBook(req.params.book_id, function(err, resp) {
        if (err) {
            res.json({ success: false, msg: err });
        } else {
            res.json({ success: true, data: resp});
        }
    });
});

booksRouter.route('/:book_id/order')
.get(function(req, res, next) {
    var data = {};
    data.book_id = req.params.book_id;
    data.email = req.query.email;
    dbLayer.addToQueue(data, function(err, resp) {
        if (err) {
            res.json({ success: false, msg: err });
        } else {
            res.json({ success: true});
        }
    });
});

module.exports = booksRouter;
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.json({ success: true });
});

module.exports = router;
<commit_msg>apis: Adds rest end points for the job: post, get and delete.<commit_after>var express = require('express')
  , router = express.Router()
  , queue = require('./../lib/q');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.json({ success: true });
});

/* POST A JOB */

router.post('/v1/jobs/:jobType', function(req, res, next){
  console.log("Creating " + req.params.jobType + " job");
  queue.addJob(req.params.jobType, req.body, function(err, jobid){
    if(err){
      console.log("Error occurred:" + err);
      next(err);
    }
    res.json({message: "job created successfully", jobid : jobid});
  });
});

/* GET JOB INFO */

router.get('/v1/jobs/:jobid', function(req, res, next){
  console.log("Info for job with id:" + req.params.jobid);
  queue.jobState(req.params.jobid, function(err, job){
    log.info("JOb info : " + job);
    if(err) {
      console.log("Error occurred: " + err);
    }
    res.json({jobInfo: job});
  });
});

/* DELETE JOBS */

router.delete('/v1/jobs/:jobid', function(req, res, next){
  console.log("Deleting job with id:" + req.params.jobid);
  queue.removeJob(req.params.jobid, function(err){
    if(err) {
      console.log("Error occurred: " + err)
    }
    res.json({success: true, message: "job with id:" + req.params.jobid + " has been removed"});
  });
});

module.exports = router;
<|endoftext|>