<commit_before>'use strict';

/**
 * @ngdoc function
 * @name wheretoliveApp.controller:AnalyticsCtrl
 * @description
 * # AnalyticsCtrl
 * Controller of the wheretoliveApp
 */
angular.module('wheretoliveApp')
    .controller('AnalyticsCtrl', ['$scope', 'Search',
        function ($scope, Search) {
            $scope.topCrime = "";
            $scope.toJournal = "";
            $scope.topCrimeAggregateNumber = '0';
            $scope.totalNewsCity = '0';
            $scope.topCrimesPerDay = [];
            $scope.showAnalytics = function (city) {
                $scope.totalCrimeCityS(city);
                $scope.histogramCrimesInCity(city);
                $scope.totalNewsInCity(city);
                //$scope.aggregateTopCrimesInCity(city);
                $scope.topJournalsInCity(city);
                $scope.topCrime(city);
                $scope.topJournal(city);
                $scope.topCrimesPerDay(city);

            };

            $scope.topJournals = [];
            $scope.newspapers = [
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    }
        ];

            /** TOP CRIME **/
            $scope.topCrime = {};

            $scope.topCrimeChartType = 'bar';
            $scope.topCrimeConfig = {
                tooltips: true,
                labels: false, // labels on data points
                // exposed events
                mouseover: function () {},
                mouseout: function () {},
                click: function () {},
                // legend config
                legend: {
                    display: true, // can be either 'left' or 'right'.
                    position: 'right',
                    // you can have html in series name
                    htmlEnabled: false
                },
                // override this array if you're not happy with default colors
                colors: [],
                innerRadius: 0, // Only on pie Charts
                lineLegend: 'lineEnd', // Only on line Charts
                lineCurveType: 'cardinal', // change this as per d3 guidelines to avoid smoothline
                isAnimate: true, // run animations while rendering chart
                yAxisTickFormat: 's' //refer tickFormats in d3 to edit this value
            };

            /** TOP DAY CRIME **/
            $scope.topCrymeDayFeatures = {
                legend: {
                    toggle: true,
                    highlight: true
                }
            };

            $scope.topDayCrimeChartType = 'line';
            $scope.topCrymeDayOptions = {
                renderer: 'area',
                stroke: true,
                preserve: true
            };
            $scope.topCrymeDaySeries = [{
                name: 'Series 1',
                color: 'steelblue',
                data: [{
                    x: 0,
                    y: 23
                }, {
                    x: 1,
                    y: 15
                }, {
                    x: 2,
                    y: 79
                }, {
                    x: 3,
                    y: 31
                }, {
                    x: 4,
                    y: 60
                }]
                    }, {
                name: 'Series 2',
                color: 'lightblue',
                data: [{
                    x: 0,
                    y: 30
                }, {
                    x: 1,
                    y: 20
                }, {
                    x: 2,
                    y: 64
                }, {
                    x: 3,
                    y: 50
                }, {
                    x: 4,
                    y: 15
                }]
                    }];
            /** TOP NEWSPAPER BY DAY  **/

            $scope.topNewspaperDaySeries = [{
                name: 'Series 1',
                color: 'steelblue',
                data: [{
                    x: 0,
                    y: 23
                }, {
                    x: 1,
                    y: 15
                }, {
                    x: 2,
                    y: 79
                }, {
                    x: 3,
                    y: 31
                }, {
                    x: 4,
                    y: 60
                }]
                    }, {
                name: 'Series 2',
                color: 'lightblue',
                data: [{
                    x: 0,
                    y: 30
                }, {
                    x: 1,
                    y: 20
                }, {
                    x: 2,
                    y: 64
                }, {
                    x: 3,
                    y: 50
                }, {
                    x: 4,
                    y: 15
                }]
                    }];
            $scope.topNewspaperDayFeatures = {};
            $scope.topDayNewspaperOptions = {
                renderer: 'area',
                stroke: true,
                preserve: true
            };

            $scope.totalCrimeCityS = function(city){
                Search.countCrimes(city).success(function(data){
                    var array = data.aggregations.crimes_count.buckets;
                    var result = 0;
                    var i = 0;
                    for (i = 0; i < array.length; i++){
                        result += array[i].doc_count;
                    }
                    $scope.topCrimeAggregateNumber = result;
                });
            };

            $scope.histogramCrimesInCity = function (city) {
                Search.histogramCrimesInCity(city).then(function (data) {
                    var res1 = data.data.aggregations.crimes_count.buckets; //jshint ignore:line
                    var i = 0;
                    var x = [];
                    var y = [];
                    for (i = 0; i < res1.length; i++) {
                        x.push(res1[i].key);
                        y.push(res1[i].doc_count); //jshint ignore:line
                    }
                    $scope.topCrime.series = x;
                    $scope.topCrime.data = [{
                        x: 'Top Crimini',
                        y: y
                    }];

                });
            };

            $scope.totalNewsInCity = function (city) {
                Search.totalNewsInCity(city).then(function (data) {
                    var res1 = data.data.hits.total;
                    $scope.totalNewsCity = res1;

                });
            };
            $scope.aggregateTopCrimesInCity = function (city) {
                Search.aggregateTopCrimesInCity(city).then(function (data) {
                    var res1 = data.data.hits.total;

                });
            };

            $scope.topJournalsInCity = function (city) {
                Search.topJournalsInCity(city).success(function (data) {
                    var result = data.aggregations.crimes.buckets;
                    $scope.topJournals = result.slice(1,result.length);
                });
            };

            $scope.topCrime = function (city) {
              Search.topCrime(city).success(function (data){
                  var result = data.aggregations.crime_histograms.buckets;
                  $scope.topCrime = result[1].key;
              });
            };

            $scope.topJournal = function (city) {
                Search.topJournal(city).success(function (data){
                    var result = data.aggregations.top_journal.buckets;
                    $scope.topJournal = result[1].key;
                });
            };

            $scope.topCrimesPerDay = function (city) {
                Search.topCrimePerDay(city).success(function (data){
                    var result = data.aggregations.top_journal.buckets;
                    $scope.topCrimePerDay = result
                });
            }

            $scope.init = function () {
                // $scope.aggregateTotalCrimesInCity("Bari");
                // $scope.aggregateTotalNewsInCity("Bari");
                //$scope.aggregateTopCrimesInCity("Bari");
                //$scope.aggregateTopJournalsInCity('Bari');
            };
    }]);
<commit_msg>add top crimes per day<commit_after>'use strict';

/**
 * @ngdoc function
 * @name wheretoliveApp.controller:AnalyticsCtrl
 * @description
 * # AnalyticsCtrl
 * Controller of the wheretoliveApp
 */
angular.module('wheretoliveApp')
    .controller('AnalyticsCtrl', ['$scope', 'Search',
        function ($scope, Search) {
            $scope.topCrime = "";
            $scope.toJournal = "";
            $scope.topCrimeAggregateNumber = '0';
            $scope.totalNewsCity = '0';
            $scope.topCrimesPerDay = [];
            $scope.showAnalytics = function (city) {
                $scope.totalCrimeCityS(city);
                $scope.histogramCrimesInCity(city);
                $scope.totalNewsInCity(city);
                //$scope.aggregateTopCrimesInCity(city);
                $scope.topJournalsInCity(city);
                $scope.topCrime(city);
                $scope.topJournal(city);
                $scope.topCrimesPerDay(city);

            };

            $scope.topJournals = [];
            $scope.newspapers = [
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    },
                {
                    titolo: 'Giornale 1'
                    }
        ];

            /** TOP CRIME **/
            $scope.topCrime = {};

            $scope.topCrimeChartType = 'bar';
            $scope.topCrimeConfig = {
                tooltips: true,
                labels: false, // labels on data points
                // exposed events
                mouseover: function () {},
                mouseout: function () {},
                click: function () {},
                // legend config
                legend: {
                    display: true, // can be either 'left' or 'right'.
                    position: 'right',
                    // you can have html in series name
                    htmlEnabled: false
                },
                // override this array if you're not happy with default colors
                colors: [],
                innerRadius: 0, // Only on pie Charts
                lineLegend: 'lineEnd', // Only on line Charts
                lineCurveType: 'cardinal', // change this as per d3 guidelines to avoid smoothline
                isAnimate: true, // run animations while rendering chart
                yAxisTickFormat: 's' //refer tickFormats in d3 to edit this value
            };

            /** TOP DAY CRIME **/
            $scope.topCrymeDayFeatures = {
                legend: {
                    toggle: true,
                    highlight: true
                }
            };

            $scope.topDayCrimeChartType = 'line';
            $scope.topCrymeDayOptions = {
                renderer: 'area',
                stroke: true,
                preserve: true
            };
            $scope.topCrymeDaySeries = [{
                name: 'Series 1',
                color: 'steelblue',
                data: [{
                    x: 0,
                    y: 23
                }, {
                    x: 1,
                    y: 15
                }, {
                    x: 2,
                    y: 79
                }, {
                    x: 3,
                    y: 31
                }, {
                    x: 4,
                    y: 60
                }]
                    }, {
                name: 'Series 2',
                color: 'lightblue',
                data: [{
                    x: 0,
                    y: 30
                }, {
                    x: 1,
                    y: 20
                }, {
                    x: 2,
                    y: 64
                }, {
                    x: 3,
                    y: 50
                }, {
                    x: 4,
                    y: 15
                }]
                    }];
            /** TOP NEWSPAPER BY DAY  **/

            $scope.topNewspaperDaySeries = [{
                name: 'Series 1',
                color: 'steelblue',
                data: [{
                    x: 0,
                    y: 23
                }, {
                    x: 1,
                    y: 15
                }, {
                    x: 2,
                    y: 79
                }, {
                    x: 3,
                    y: 31
                }, {
                    x: 4,
                    y: 60
                }]
                    }, {
                name: 'Series 2',
                color: 'lightblue',
                data: [{
                    x: 0,
                    y: 30
                }, {
                    x: 1,
                    y: 20
                }, {
                    x: 2,
                    y: 64
                }, {
                    x: 3,
                    y: 50
                }, {
                    x: 4,
                    y: 15
                }]
                    }];
            $scope.topNewspaperDayFeatures = {};
            $scope.topDayNewspaperOptions = {
                renderer: 'area',
                stroke: true,
                preserve: true
            };

            $scope.totalCrimeCityS = function(city){
                Search.countCrimes(city).success(function(data){
                    var array = data.aggregations.crimes_count.buckets;
                    var result = 0;
                    var i = 0;
                    for (i = 0; i < array.length; i++){
                        result += array[i].doc_count;
                    }
                    $scope.topCrimeAggregateNumber = result;
                });
            };

            $scope.histogramCrimesInCity = function (city) {
                Search.histogramCrimesInCity(city).then(function (data) {
                    var res1 = data.data.aggregations.crimes_count.buckets; //jshint ignore:line
                    var i = 0;
                    var x = [];
                    var y = [];
                    for (i = 0; i < res1.length; i++) {
                        x.push(res1[i].key);
                        y.push(res1[i].doc_count); //jshint ignore:line
                    }
                    $scope.topCrime.series = x;
                    $scope.topCrime.data = [{
                        x: 'Top Crimini',
                        y: y
                    }];

                });
            };

            $scope.totalNewsInCity = function (city) {
                Search.totalNewsInCity(city).then(function (data) {
                    var res1 = data.data.hits.total;
                    $scope.totalNewsCity = res1;

                });
            };
            $scope.aggregateTopCrimesInCity = function (city) {
                Search.aggregateTopCrimesInCity(city).then(function (data) {
                    var res1 = data.data.hits.total;

                });
            };

            $scope.topJournalsInCity = function (city) {
                Search.topJournalsInCity(city).success(function (data) {
                    var result = data.aggregations.crimes.buckets;
                    $scope.topJournals = result.slice(1,result.length);
                });
            };

            $scope.topCrime = function (city) {
              Search.topCrime(city).success(function (data){
                  var result = data.aggregations.crime_histograms.buckets;
                  $scope.topCrime = result[1].key;
              });
            };

            $scope.topJournal = function (city) {
                Search.topJournal(city).success(function (data){
                    var result = data.aggregations.top_journal.buckets;
                    $scope.topJournal = result[1].key;
                });
            };

            $scope.topCrimesPerDay = function (city) {
                Search.topCrimesPerDay(city).success(function (data){
                    var result = data.aggregations.crime_top.buckets;
                    var array = [];
                    var i = 0;
                    var j = 0;
                    for (i = 0; i < result.length; i++){
                        var crimeArray = result[i];
                        var crime = crimeArray.key;
                        var valuesArray = crimeArray.day_histogram.buckets;
                        var arrayXY = []
                        for (j = 0; j < valuesArray.length; j++){
                            arrayXY.push(
                                {
                                    x: valuesArray[j].key_as_string,
                                    y: valuesArray[j].doc_count
                                }
                            );
                        }
                        array.push({
                            name: crime,
                            data: arrayXY
                        });
                    }
                    console.log(array);
                    $scope.topCrimesPerDay = array;
                });
            }

            $scope.init = function () {
                // $scope.aggregateTotalCrimesInCity("Bari");
                // $scope.aggregateTotalNewsInCity("Bari");
                //$scope.aggregateTopCrimesInCity("Bari");
                //$scope.aggregateTopJournalsInCity('Bari');
            };
    }]);
<|endoftext|>


<commit_before>module.exports = class TwitterHelper {
	constructor(logger, google, twitter) {
		this.logger  = logger;
		this.google  = google;
		this.twitter = twitter;
	}

	tweetNextShow() {
		let self = this;

		return new Promise(function(resolve, reject) {
			self.google.calendar.getNextShow()
				.then(function(response) {
					let nextShow = response;
					let tweet    = '';

					if (nextShow !== undefined) {
						tweet += nextShow.summary;
					}
					else {
						tweet += 'Eine Sendung';
					}

					if (tweet.startsWith('@')) {
						tweet = '.' + tweet;
					}

					if (message.length <= 118) {
						tweet += ' – jetzt live im #BRG!';
					}
					else if (message.length <= 103) {
						tweet += ' – jetzt live im Brony Radio Germany!';
					}

					if (message.length < 133) {
						tweet += ' #Brony';
					}

					if (message.length <  135) {
						tweet += ' #MLP';
					}

					self.twitter.post('statuses/update', {status: tweet}, (error, tweet, response) => {
						if (error) {
							self.logger.error(error);
							reject(Error(error));
						}

						resolve(response);
					});
				})
				.catch(function(error) {
					self.logger.error(error);
					reject(Error(error));
				});
		});
	}
}
<commit_msg>Fixed tweetNextShow function<commit_after>module.exports = class TwitterHelper {
	constructor(logger, google, twitter) {
		this.logger  = logger;
		this.google  = google;
		this.twitter = twitter;
	}

	tweetNextShow() {
		let self = this;

		return new Promise(function(resolve, reject) {
			self.google.calendar.getNextShow()
				.then(function(response) {
					let nextShow = response;
					let tweet    = '';

					if (nextShow !== undefined) {
						tweet += nextShow.summary;
					}
					else {
						tweet += 'Eine Sendung';
					}

					if (tweet.startsWith('@')) {
						tweet = '.' + tweet;
					}

					if (tweet.length <= 118) {
						tweet += ' – jetzt live im #BRG!';
					}
					else if (tweet.length <= 103) {
						tweet += ' – jetzt live im Brony Radio Germany!';
					}

					if (tweet.length < 133) {
						tweet += ' #Brony';
					}

					if (tweet.length <  135) {
						tweet += ' #MLP';
					}

					self.twitter.post('statuses/update', {status: tweet}, (error, tweet, response) => {
						if (error) {
							self.logger.error(error);
							reject(Error(error));
						}

						resolve(response);
					});
				})
				.catch(function(error) {
					self.logger.error(error);
					reject(Error(error));
				});
		});
	}
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.Object}
 * @param {WebInspector.ResourceTreeModel} resourceTreeModel
 */
WebInspector.RuntimeModel = function(resourceTreeModel)
{
    resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, this._frameAdded, this);
    resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._frameNavigated, this);
    resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this._frameDetached, this);
    resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded, this._didLoadCachedResources, this);
    this._frameIdToContextList = {};
}

WebInspector.RuntimeModel.Events = {
    FrameExecutionContextListAdded: "FrameExecutionContextListAdded",
    FrameExecutionContextListRemoved: "FrameExecutionContextListRemoved",
}

WebInspector.RuntimeModel.prototype = {
    /**
     * @param {WebInspector.ExecutionContext} executionContext
     */
    setCurrentExecutionContext: function(executionContext)
    {
        this._currentExecutionContext = executionContext;
    },

    /**
     * @return {WebInspector.ExecutionContext}
     */
    currentExecutionContext: function()
    {
        return this._currentExecutionContext;
    },

    /**
     * @return {!Array.<!WebInspector.FrameExecutionContextList>}
     */
    contextLists: function()
    {
        return Object.values(this._frameIdToContextList);
    },

    /**
     * @param {WebInspector.ResourceTreeFrame} frame
     * @return {WebInspector.FrameExecutionContextList}
     */
    contextListByFrame: function(frame)
    {
        return this._frameIdToContextList[frame.id];
    },

    _frameAdded: function(event)
    {
        var frame = event.data;
        var context = new WebInspector.FrameExecutionContextList(frame);
        this._frameIdToContextList[frame.id] = context;
        this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.FrameExecutionContextListAdded, context);
    },

    _frameNavigated: function(event)
    {
        var frame = event.data;
        var context = this._frameIdToContextList[frame.id];
        if (context)
            context._frameNavigated(frame);
    },

    _frameDetached: function(event)
    {
        var frame = event.data;
        var context = this._frameIdToContextList[frame.id];
        if (!context)
            return;
        this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.FrameExecutionContextListRemoved, context);
        delete this._frameIdToContextList[frame.id];
    },

    _didLoadCachedResources: function()
    {
        InspectorBackend.registerRuntimeDispatcher(new WebInspector.RuntimeDispatcher(this));
        RuntimeAgent.enable();
    },

    _executionContextCreated: function(context)
    {
        var contextList = this._frameIdToContextList[context.frameId];
        // FIXME(85708): this should never happen
        if (!contextList)
            return;
        contextList._addExecutionContext(new WebInspector.ExecutionContext(context.id, context.name, context.isPageContext));
    },

    /**
     * @param {string} expression
     * @param {string} objectGroup
     * @param {boolean} includeCommandLineAPI
     * @param {boolean} doNotPauseOnExceptionsAndMuteConsole
     * @param {boolean} returnByValue
     * @param {boolean} generatePreview
     * @param {function(?WebInspector.RemoteObject, boolean, ?RuntimeAgent.RemoteObject=)} callback
     */
    evaluate: function(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback)
    {
        if (WebInspector.debuggerModel.selectedCallFrame()) {
            WebInspector.debuggerModel.evaluateOnSelectedCallFrame(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback);
            return;
        }

        if (!expression) {
            // There is no expression, so the completion should happen against global properties.
            expression = "this";
        }

        /**
         * @param {?Protocol.Error} error
         * @param {RuntimeAgent.RemoteObject} result
         * @param {boolean=} wasThrown
         */
        function evalCallback(error, result, wasThrown)
        {
            if (error) {
                callback(null, false);
                return;
            }

            if (returnByValue)
                callback(null, !!wasThrown, wasThrown ? null : result);
            else
                callback(WebInspector.RemoteObject.fromPayload(result), !!wasThrown);
        }
        RuntimeAgent.evaluate(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, this._currentExecutionContext ? this._currentExecutionContext.id : undefined, returnByValue, generatePreview, evalCallback);
    },

    /**
     * @param {Element} proxyElement
     * @param {Range} wordRange
     * @param {boolean} force
     * @param {function(!Array.<string>, number=)} completionsReadyCallback
     */
    completionsForTextPrompt: function(proxyElement, wordRange, force, completionsReadyCallback)
    {
        // Pass less stop characters to rangeOfWord so the range will be a more complete expression.
        var expressionRange = wordRange.startContainer.rangeOfWord(wordRange.startOffset, " =:[({;,!+-*/&|^<>", proxyElement, "backward");
        var expressionString = expressionRange.toString();
        var prefix = wordRange.toString();
        this._completionsForExpression(expressionString, prefix, force, completionsReadyCallback);
    },

    /**
     * @param {string} expressionString
     * @param {string} prefix
     * @param {boolean} force
     * @param {function(!Array.<string>, number=)} completionsReadyCallback
     */
    _completionsForExpression: function(expressionString, prefix, force, completionsReadyCallback)
    {
        var lastIndex = expressionString.length - 1;

        var dotNotation = (expressionString[lastIndex] === ".");
        var bracketNotation = (expressionString[lastIndex] === "[");

        if (dotNotation || bracketNotation)
            expressionString = expressionString.substr(0, lastIndex);

        if (expressionString && parseInt(expressionString, 10) == expressionString) {
            // User is entering float value, do not suggest anything.
            completionsReadyCallback([]);
            return;
        }

        if (!prefix && !expressionString && !force) {
            completionsReadyCallback([]);
            return;
        }

        if (!expressionString && WebInspector.debuggerModel.selectedCallFrame())
            WebInspector.debuggerModel.getSelectedCallFrameVariables(receivedPropertyNames.bind(this));
        else
            this.evaluate(expressionString, "completion", true, true, false, false, evaluated.bind(this));

        function evaluated(result, wasThrown)
        {
            if (!result || wasThrown) {
                completionsReadyCallback([]);
                return;
            }

            function getCompletions(primitiveType)
            {
                var object;
                if (primitiveType === "string")
                    object = new String("");
                else if (primitiveType === "number")
                    object = new Number(0);
                else if (primitiveType === "boolean")
                    object = new Boolean(false);
                else
                    object = this;

                var resultSet = {};
                for (var o = object; o; o = o.__proto__) {
                    try {
                        var names = Object.getOwnPropertyNames(o);
                        for (var i = 0; i < names.length; ++i)
                            resultSet[names[i]] = true;
                    } catch (e) {
                    }
                }
                return resultSet;
            }

            if (result.type === "object" || result.type === "function")
                result.callFunctionJSON(getCompletions, undefined, receivedPropertyNames.bind(this));
            else if (result.type === "string" || result.type === "number" || result.type === "boolean")
                this.evaluate("(" + getCompletions + ")(\"" + result.type + "\")", "completion", false, true, true, false, receivedPropertyNamesFromEval.bind(this));
        }

        function receivedPropertyNamesFromEval(notRelevant, wasThrown, result)
        {
            if (result && !wasThrown)
                receivedPropertyNames.call(this, result.value);
            else
                completionsReadyCallback([]);
        }

        function receivedPropertyNames(propertyNames)
        {
            RuntimeAgent.releaseObjectGroup("completion");
            if (!propertyNames) {
                completionsReadyCallback([]);
                return;
            }
            var includeCommandLineAPI = (!dotNotation && !bracketNotation);
            if (includeCommandLineAPI) {
                const commandLineAPI = ["dir", "dirxml", "keys", "values", "profile", "profileEnd", "monitorEvents", "unmonitorEvents", "inspect", "copy", "clear",
                    "getEventListeners", "debug", "undebug", "monitor", "unmonitor", "table", "$", "$$", "$x"];
                for (var i = 0; i < commandLineAPI.length; ++i)
                    propertyNames[commandLineAPI[i]] = true;
            }
            this._reportCompletions(completionsReadyCallback, dotNotation, bracketNotation, expressionString, prefix, Object.keys(propertyNames));
        }
    },

    /**
     * @param {function(!Array.<string>, number=)} completionsReadyCallback
     * @param {boolean} dotNotation
     * @param {boolean} bracketNotation
     * @param {string} expressionString
     * @param {string} prefix
     * @param {!Array.<string>} properties
     */
    _reportCompletions: function(completionsReadyCallback, dotNotation, bracketNotation, expressionString, prefix, properties) {
        if (bracketNotation) {
            if (prefix.length && prefix[0] === "'")
                var quoteUsed = "'";
            else
                var quoteUsed = "\"";
        }

        var results = [];

        if (!expressionString) {
            const keywords = ["break", "case", "catch", "continue", "default", "delete", "do", "else", "finally", "for", "function", "if", "in",
                              "instanceof", "new", "return", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with"];
            properties = properties.concat(keywords);
        }

        properties.sort();

        for (var i = 0; i < properties.length; ++i) {
            var property = properties[i];

            if (dotNotation && !/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(property))
                continue;

            if (bracketNotation) {
                if (!/^[0-9]+$/.test(property))
                    property = quoteUsed + property.escapeCharacters(quoteUsed + "\\") + quoteUsed;
                property += "]";
            }

            if (property.length < prefix.length)
                continue;
            if (prefix.length && !property.startsWith(prefix))
                continue;

            results.push(property);
        }
        completionsReadyCallback(results);
    },

    __proto__: WebInspector.Object.prototype
}

/**
 * @type {WebInspector.RuntimeModel}
 */
WebInspector.runtimeModel = null;

/**
 * @constructor
 * @implements {RuntimeAgent.Dispatcher}
 * @param {WebInspector.RuntimeModel} runtimeModel
 */
WebInspector.RuntimeDispatcher = function(runtimeModel)
{
    this._runtimeModel = runtimeModel;
}

WebInspector.RuntimeDispatcher.prototype = {
    executionContextCreated: function(context)
    {
        this._runtimeModel._executionContextCreated(context);
    }
}

/**
 * @constructor
 * @extends {WebInspector.Object}
 */
WebInspector.ExecutionContext = function(id, name, isPageContext)
{
    this.id = id;
    this.name = (isPageContext && !name) ? "<page context>" : name;
    this.isMainWorldContext = isPageContext;
}

/**
 * @param {!WebInspector.ExecutionContext} a
 * @param {!WebInspector.ExecutionContext} b
 * @return {number}
 */
WebInspector.ExecutionContext.comparator = function(a, b)
{
    // Main world context should always go first.
    if (a.isMainWorldContext)
        return -1;
    if (b.isMainWorldContext)
        return +1;
    return a.name.localeCompare(b.name);
}

/**
 * @constructor
 * @extends {WebInspector.Object}
 */
WebInspector.FrameExecutionContextList = function(frame)
{
    this._frame = frame;
    this._executionContexts = [];
}

WebInspector.FrameExecutionContextList.EventTypes = {
    ContextsUpdated: "ContextsUpdated",
    ContextAdded: "ContextAdded"
}

WebInspector.FrameExecutionContextList.prototype =
{
    _frameNavigated: function(frame)
    {
        this._frame = frame;
        this._executionContexts = [];
        this.dispatchEventToListeners(WebInspector.FrameExecutionContextList.EventTypes.ContextsUpdated, this);
    },

    /**
     * @param {!WebInspector.ExecutionContext} context
     */
    _addExecutionContext: function(context)
    {
        var insertAt = insertionIndexForObjectInListSortedByFunction(context, this._executionContexts, WebInspector.ExecutionContext.comparator);
        this._executionContexts.splice(insertAt, 0, context);
        this.dispatchEventToListeners(WebInspector.FrameExecutionContextList.EventTypes.ContextAdded, this);
    },

    executionContexts: function()
    {
        return this._executionContexts;
    },

    mainWorldContext: function()
    {
        return this._executionContexts[0];
    },

    /**
     * @param {string} securityOrigin
     */
    contextBySecurityOrigin: function(securityOrigin)
    {
        for (var i = 0; i < this._executionContexts.length; ++i) {
            var context = this._executionContexts[i];
            if (!context.isMainWorldContext && context.name === securityOrigin)
                return context;
        }
    },

    get frameId()
    {
        return this._frame.id;
    },

    get url()
    {
        return this._frame.url;
    },

    get displayName()
    {
        if (!this._frame.parentFrame)
            return "<top frame>";
        var name = this._frame.name || "";
        var subtitle = new WebInspector.ParsedURL(this._frame.url).displayName;
        if (subtitle) {
            if (!name)
                return subtitle;
            return name + "( " + subtitle + " )";
        }
        return "<iframe>";
    },

    __proto__: WebInspector.Object.prototype
}
<commit_msg>[DevTools] Tuned console completion filter to allow non-ascii properties auto-completion.<commit_after>/*
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.Object}
 * @param {WebInspector.ResourceTreeModel} resourceTreeModel
 */
WebInspector.RuntimeModel = function(resourceTreeModel)
{
    resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameAdded, this._frameAdded, this);
    resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameNavigated, this._frameNavigated, this);
    resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached, this._frameDetached, this);
    resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.CachedResourcesLoaded, this._didLoadCachedResources, this);
    this._frameIdToContextList = {};
}

WebInspector.RuntimeModel.Events = {
    FrameExecutionContextListAdded: "FrameExecutionContextListAdded",
    FrameExecutionContextListRemoved: "FrameExecutionContextListRemoved",
}

WebInspector.RuntimeModel.prototype = {
    /**
     * @param {WebInspector.ExecutionContext} executionContext
     */
    setCurrentExecutionContext: function(executionContext)
    {
        this._currentExecutionContext = executionContext;
    },

    /**
     * @return {WebInspector.ExecutionContext}
     */
    currentExecutionContext: function()
    {
        return this._currentExecutionContext;
    },

    /**
     * @return {!Array.<!WebInspector.FrameExecutionContextList>}
     */
    contextLists: function()
    {
        return Object.values(this._frameIdToContextList);
    },

    /**
     * @param {WebInspector.ResourceTreeFrame} frame
     * @return {WebInspector.FrameExecutionContextList}
     */
    contextListByFrame: function(frame)
    {
        return this._frameIdToContextList[frame.id];
    },

    _frameAdded: function(event)
    {
        var frame = event.data;
        var context = new WebInspector.FrameExecutionContextList(frame);
        this._frameIdToContextList[frame.id] = context;
        this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.FrameExecutionContextListAdded, context);
    },

    _frameNavigated: function(event)
    {
        var frame = event.data;
        var context = this._frameIdToContextList[frame.id];
        if (context)
            context._frameNavigated(frame);
    },

    _frameDetached: function(event)
    {
        var frame = event.data;
        var context = this._frameIdToContextList[frame.id];
        if (!context)
            return;
        this.dispatchEventToListeners(WebInspector.RuntimeModel.Events.FrameExecutionContextListRemoved, context);
        delete this._frameIdToContextList[frame.id];
    },

    _didLoadCachedResources: function()
    {
        InspectorBackend.registerRuntimeDispatcher(new WebInspector.RuntimeDispatcher(this));
        RuntimeAgent.enable();
    },

    _executionContextCreated: function(context)
    {
        var contextList = this._frameIdToContextList[context.frameId];
        // FIXME(85708): this should never happen
        if (!contextList)
            return;
        contextList._addExecutionContext(new WebInspector.ExecutionContext(context.id, context.name, context.isPageContext));
    },

    /**
     * @param {string} expression
     * @param {string} objectGroup
     * @param {boolean} includeCommandLineAPI
     * @param {boolean} doNotPauseOnExceptionsAndMuteConsole
     * @param {boolean} returnByValue
     * @param {boolean} generatePreview
     * @param {function(?WebInspector.RemoteObject, boolean, ?RuntimeAgent.RemoteObject=)} callback
     */
    evaluate: function(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback)
    {
        if (WebInspector.debuggerModel.selectedCallFrame()) {
            WebInspector.debuggerModel.evaluateOnSelectedCallFrame(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, returnByValue, generatePreview, callback);
            return;
        }

        if (!expression) {
            // There is no expression, so the completion should happen against global properties.
            expression = "this";
        }

        /**
         * @param {?Protocol.Error} error
         * @param {RuntimeAgent.RemoteObject} result
         * @param {boolean=} wasThrown
         */
        function evalCallback(error, result, wasThrown)
        {
            if (error) {
                callback(null, false);
                return;
            }

            if (returnByValue)
                callback(null, !!wasThrown, wasThrown ? null : result);
            else
                callback(WebInspector.RemoteObject.fromPayload(result), !!wasThrown);
        }
        RuntimeAgent.evaluate(expression, objectGroup, includeCommandLineAPI, doNotPauseOnExceptionsAndMuteConsole, this._currentExecutionContext ? this._currentExecutionContext.id : undefined, returnByValue, generatePreview, evalCallback);
    },

    /**
     * @param {Element} proxyElement
     * @param {Range} wordRange
     * @param {boolean} force
     * @param {function(!Array.<string>, number=)} completionsReadyCallback
     */
    completionsForTextPrompt: function(proxyElement, wordRange, force, completionsReadyCallback)
    {
        // Pass less stop characters to rangeOfWord so the range will be a more complete expression.
        var expressionRange = wordRange.startContainer.rangeOfWord(wordRange.startOffset, " =:[({;,!+-*/&|^<>", proxyElement, "backward");
        var expressionString = expressionRange.toString();
        var prefix = wordRange.toString();
        this._completionsForExpression(expressionString, prefix, force, completionsReadyCallback);
    },

    /**
     * @param {string} expressionString
     * @param {string} prefix
     * @param {boolean} force
     * @param {function(!Array.<string>, number=)} completionsReadyCallback
     */
    _completionsForExpression: function(expressionString, prefix, force, completionsReadyCallback)
    {
        var lastIndex = expressionString.length - 1;

        var dotNotation = (expressionString[lastIndex] === ".");
        var bracketNotation = (expressionString[lastIndex] === "[");

        if (dotNotation || bracketNotation)
            expressionString = expressionString.substr(0, lastIndex);

        if (expressionString && parseInt(expressionString, 10) == expressionString) {
            // User is entering float value, do not suggest anything.
            completionsReadyCallback([]);
            return;
        }

        if (!prefix && !expressionString && !force) {
            completionsReadyCallback([]);
            return;
        }

        if (!expressionString && WebInspector.debuggerModel.selectedCallFrame())
            WebInspector.debuggerModel.getSelectedCallFrameVariables(receivedPropertyNames.bind(this));
        else
            this.evaluate(expressionString, "completion", true, true, false, false, evaluated.bind(this));

        function evaluated(result, wasThrown)
        {
            if (!result || wasThrown) {
                completionsReadyCallback([]);
                return;
            }

            function getCompletions(primitiveType)
            {
                var object;
                if (primitiveType === "string")
                    object = new String("");
                else if (primitiveType === "number")
                    object = new Number(0);
                else if (primitiveType === "boolean")
                    object = new Boolean(false);
                else
                    object = this;

                var resultSet = {};
                for (var o = object; o; o = o.__proto__) {
                    try {
                        var names = Object.getOwnPropertyNames(o);
                        for (var i = 0; i < names.length; ++i)
                            resultSet[names[i]] = true;
                    } catch (e) {
                    }
                }
                return resultSet;
            }

            if (result.type === "object" || result.type === "function")
                result.callFunctionJSON(getCompletions, undefined, receivedPropertyNames.bind(this));
            else if (result.type === "string" || result.type === "number" || result.type === "boolean")
                this.evaluate("(" + getCompletions + ")(\"" + result.type + "\")", "completion", false, true, true, false, receivedPropertyNamesFromEval.bind(this));
        }

        function receivedPropertyNamesFromEval(notRelevant, wasThrown, result)
        {
            if (result && !wasThrown)
                receivedPropertyNames.call(this, result.value);
            else
                completionsReadyCallback([]);
        }

        function receivedPropertyNames(propertyNames)
        {
            RuntimeAgent.releaseObjectGroup("completion");
            if (!propertyNames) {
                completionsReadyCallback([]);
                return;
            }
            var includeCommandLineAPI = (!dotNotation && !bracketNotation);
            if (includeCommandLineAPI) {
                const commandLineAPI = ["dir", "dirxml", "keys", "values", "profile", "profileEnd", "monitorEvents", "unmonitorEvents", "inspect", "copy", "clear",
                    "getEventListeners", "debug", "undebug", "monitor", "unmonitor", "table", "$", "$$", "$x"];
                for (var i = 0; i < commandLineAPI.length; ++i)
                    propertyNames[commandLineAPI[i]] = true;
            }
            this._reportCompletions(completionsReadyCallback, dotNotation, bracketNotation, expressionString, prefix, Object.keys(propertyNames));
        }
    },

    /**
     * @param {function(!Array.<string>, number=)} completionsReadyCallback
     * @param {boolean} dotNotation
     * @param {boolean} bracketNotation
     * @param {string} expressionString
     * @param {string} prefix
     * @param {!Array.<string>} properties
     */
    _reportCompletions: function(completionsReadyCallback, dotNotation, bracketNotation, expressionString, prefix, properties) {
        if (bracketNotation) {
            if (prefix.length && prefix[0] === "'")
                var quoteUsed = "'";
            else
                var quoteUsed = "\"";
        }

        var results = [];

        if (!expressionString) {
            const keywords = ["break", "case", "catch", "continue", "default", "delete", "do", "else", "finally", "for", "function", "if", "in",
                              "instanceof", "new", "return", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with"];
            properties = properties.concat(keywords);
        }

        properties.sort();

        for (var i = 0; i < properties.length; ++i) {
            var property = properties[i];

            // Assume that all non-ASCII characters are letters and thus can be used as part of identifier.
            if (dotNotation && !/^[a-zA-Z_$\u008F-\uFFFF][a-zA-Z0-9_$\u008F-\uFFFF]*$/.test(property))
                continue;

            if (bracketNotation) {
                if (!/^[0-9]+$/.test(property))
                    property = quoteUsed + property.escapeCharacters(quoteUsed + "\\") + quoteUsed;
                property += "]";
            }

            if (property.length < prefix.length)
                continue;
            if (prefix.length && !property.startsWith(prefix))
                continue;

            results.push(property);
        }
        completionsReadyCallback(results);
    },

    __proto__: WebInspector.Object.prototype
}

/**
 * @type {WebInspector.RuntimeModel}
 */
WebInspector.runtimeModel = null;

/**
 * @constructor
 * @implements {RuntimeAgent.Dispatcher}
 * @param {WebInspector.RuntimeModel} runtimeModel
 */
WebInspector.RuntimeDispatcher = function(runtimeModel)
{
    this._runtimeModel = runtimeModel;
}

WebInspector.RuntimeDispatcher.prototype = {
    executionContextCreated: function(context)
    {
        this._runtimeModel._executionContextCreated(context);
    }
}

/**
 * @constructor
 * @extends {WebInspector.Object}
 */
WebInspector.ExecutionContext = function(id, name, isPageContext)
{
    this.id = id;
    this.name = (isPageContext && !name) ? "<page context>" : name;
    this.isMainWorldContext = isPageContext;
}

/**
 * @param {!WebInspector.ExecutionContext} a
 * @param {!WebInspector.ExecutionContext} b
 * @return {number}
 */
WebInspector.ExecutionContext.comparator = function(a, b)
{
    // Main world context should always go first.
    if (a.isMainWorldContext)
        return -1;
    if (b.isMainWorldContext)
        return +1;
    return a.name.localeCompare(b.name);
}

/**
 * @constructor
 * @extends {WebInspector.Object}
 */
WebInspector.FrameExecutionContextList = function(frame)
{
    this._frame = frame;
    this._executionContexts = [];
}

WebInspector.FrameExecutionContextList.EventTypes = {
    ContextsUpdated: "ContextsUpdated",
    ContextAdded: "ContextAdded"
}

WebInspector.FrameExecutionContextList.prototype =
{
    _frameNavigated: function(frame)
    {
        this._frame = frame;
        this._executionContexts = [];
        this.dispatchEventToListeners(WebInspector.FrameExecutionContextList.EventTypes.ContextsUpdated, this);
    },

    /**
     * @param {!WebInspector.ExecutionContext} context
     */
    _addExecutionContext: function(context)
    {
        var insertAt = insertionIndexForObjectInListSortedByFunction(context, this._executionContexts, WebInspector.ExecutionContext.comparator);
        this._executionContexts.splice(insertAt, 0, context);
        this.dispatchEventToListeners(WebInspector.FrameExecutionContextList.EventTypes.ContextAdded, this);
    },

    executionContexts: function()
    {
        return this._executionContexts;
    },

    mainWorldContext: function()
    {
        return this._executionContexts[0];
    },

    /**
     * @param {string} securityOrigin
     */
    contextBySecurityOrigin: function(securityOrigin)
    {
        for (var i = 0; i < this._executionContexts.length; ++i) {
            var context = this._executionContexts[i];
            if (!context.isMainWorldContext && context.name === securityOrigin)
                return context;
        }
    },

    get frameId()
    {
        return this._frame.id;
    },

    get url()
    {
        return this._frame.url;
    },

    get displayName()
    {
        if (!this._frame.parentFrame)
            return "<top frame>";
        var name = this._frame.name || "";
        var subtitle = new WebInspector.ParsedURL(this._frame.url).displayName;
        if (subtitle) {
            if (!name)
                return subtitle;
            return name + "( " + subtitle + " )";
        }
        return "<iframe>";
    },

    __proto__: WebInspector.Object.prototype
}
<|endoftext|>


<commit_before>// Dependencies
var request = require('request');
var moment = require('moment');

// Local libraries
var utils = require('../lib/utils.js');
var datalib = require('../lib/datalib.js');

var DataSource = require('../models/data_source').DataSource;
var Project = require('../models/project');
var Signal = require('../models/data_source').Signal;
var Model = require('../models/model');
var ShareToken = require('../models/datashare_token');
var signalAPIService = require('../services/SignalAPIService');
var mongoose = require('mongoose');
var asyncR = require('async');

var hat = require('hat');

var validator = require('validator');

exports.getAllDataSourcesForUser = function(req, res) {
  var authenticatedUser = req.user;

  var sort = req.query.sort;
	sort = (typeof req.query.sort === 'undefined') ? "desc" : sort;
	var sortInt = (sort === 'desc') ? -1 : 1;

  var criteria = {
    'user': authenticatedUser,
  };

  DataSource.find(criteria)
    .sort({name: sort})
    .populate('projects', 'name')
    .exec(function(err_datasource, datasources) {
    if (err_datasource || !datasources.length) {
      res.json({
        status: 0,
        message: "No datasources found for user.",
        datasources: []
      });
    } else {
      var userDataSources = datasources;
      /* lets get shared datasources */
      ShareToken.find({
          sharedWithUser: authenticatedUser.local.email
        })
        .populate('datasource').lean().populate('sharedByUser').exec(function(err_sharedDatasource, sharedDatasources) {
          sharedDatasources.forEach(function(dataSource) {
            dataSource.sharedByUser = utils.santizeUserObject(dataSource.sharedByUser);
          })
					res.set('X-Total-Count', datasources.length.toString());
          res.json({
            status: 1,
            datasources: userDataSources,
            shared_datasources: sharedDatasources
          });
        });
    }
  });
}

exports.addDataSource = function(req, res) {
  var datasourceName = req.body.datasource_name;
  var datasourceDescription = req.body.datasource_description;
  var authenticatedUser = req.user;

  datasourceName = validator.escape(datasourceName);
  datasourceDescription = validator.escape(datasourceDescription);

  var newDataSource = DataSource({
    name: datasourceName,
    description: datasourceDescription,
    user: authenticatedUser
  });

  newDataSource.save(function(err, newDataSource) {
    if (err)
      res.json({
        status: 0,
        message: 'Datasource not saved'
      });
    else
      res.json({
        status: 1,
        message: 'Datasource saved successfully',
        links: {
          href: '/datasources/' + newDataSource._id
        },
        datasource: {
          name: newDataSource.name,
          description: newDataSource.description,
        }
      });
  });
};

exports.getDataSourceById = function(req, res) {
  var datasource_id = req.params.datasource_id;
  var authenticatedUser = req.user;

  DataSource.findOne({
    '_id': datasource_id,
    'user': authenticatedUser
  }).populate('signals', '-measurements').exec(function(err, datasource) {
    if (err)
      res.json({
        status: 0,
        message: 'Data source not found'
      });
    else
      res.json({
        status: 1,
        datasource: datasource,
      });
  });
}

exports.editDataSource = function(req, res) {
  var datasource_id = req.params.datasource_id;
  var name = req.body.datasourcename;
  var description = req.body.datasourcedescription;
  var authenticatedUser = req.user;

  if (datasource_id === "")
    res.json({
      staus: -1,
      message: "Could not find datasource with ID " + datasource_id
    });

  DataSource.findOne({
    _id: datasource_id,
    'user': authenticatedUser
  }, function(err, datasource) {
    if (err) {
      res.send(err);
    }

    datasource.name = name;
    datasource.description = description;

    datasource.save(function(err, datasource) {
      if (err) {
        res.send(err);
      }
      res.json(datasource);
    });

  })

}

exports.deleteDataSource = function(req, res) {
  var datasource_id = req.params.datasource_id;
  var authenticatedUser = req.user;

  if (datasource_id === "")
    res.json({
      staus: -1,
      message: "Could not find datasource with ID " + datasource_id
    });

  DataSource.findOne({
    _id: datasource_id,
    'user': authenticatedUser
  }).remove(function(err, datasource) {
    if (err) {
      res.send(err);
    }

    Project.findOne({
        'datasources.oid': datasource_id
      }, {
        'datasources.$': 1
      },
      function(err, project) {

        if (project) {

        } else {

        }
      }
    )

    res.json(datasource);

  })

}

exports.getAllDataSourcesForProject = function(req, res) {
  var project_id = req.params.project_id
  var authenticatedUser = req.user;

  var criteria = {};
  criteria = {
    'project_id': project_id,
  };

  DataSource.find(criteria, function(err, datasources) {

    if (err || !datasources.length) {
      res.json({
        status: 0,
        datasources: [{
          id: 0,
          name: 'No datasources found for project'
        }]
      });
    } else {
      var returnedDataSources = datasources;
      res.json({
        status: 1,
        datasources: returnedDataSources
      });
    }
  });
}

exports.getAllSignalsFromDataSource = function(req, res) {
  var datasource_id = req.params.datasource_id;
  // Get the authenticated user
  var authenticatedUser = req.user;

  var depth = req.query.depth;
  var populateSelector = "";
  if (depth === undefined)
    populateSelector = '';
  else
    populateSelector = depth.replace(',', ' ');

  var criteria = {};
  criteria = {
    '_id': datasource_id,
    'user': authenticatedUser,
  };

  DataSource.findOne(criteria).populate('signals', populateSelector).exec(function(err, datasource) {

    if (err || !datasource) {

      res.json({
        status: 0,
        message: "No signals defined",
        signals: []
      });
    } else {
			console.log(datasource.signals);
      var signals = datasource.signals;
      res.json({
        status: 1,
        signals: signals
      });
    }
  });
}

var constructSignal = function(form_data) {
  var signal = new Signal({});
	signal.name = form_data.signal_name;
  signal.description = form_data.signal_description;

	if (form_data.signal_type === "timestamp") {
		signal.data_type = "Timestamp";
	}
  else if (form_data.signal_type === "generated_signal") {

    var linear_gradient = parseFloat(form_data.signal_linear_gradient);
    var linear_delay = parseInt(form_data.signal_linear_delay);
    var periodic_delay = parseInt(form_data.signal_periodic_delay);
    var periodic_mag = parseInt(form_data.signal_periodic_mag);
    var periodic_period = parseInt(form_data.signal_periodic_period);

		signal.data_type = "RG";
		signal.linear_gradient = linear_gradient;
		signal.periodic_mag = form_data.signal_periodic_mag;
		signal.periodic_period = form_data.signal_periodic_period;

    var today = moment();
    var date = moment(form_data.start_date);

    var dt_minutes = form_data.signal_dt;

    var measurements = [];

    var counter = 0;
    var linear_counter = 0;
    var periodic_counter = 0;
    for (var m = date; m.diff(today, 'minutes') <= 0; m.add(dt_minutes, 'minutes')) {
      var linearDelayFlag = (counter >= linear_delay) ? 1 : 0;
      var periodicDelayFlag = (counter >= periodic_delay) ? 1 : 0;
      var periodicComponent = 0; //periodic_period%periodic_counter;
      var newValue = datalib.generateInitialData(0, 2) + linear_counter * linear_gradient + periodic_counter * periodicComponent;
      var value = {
        datetime: m.format("YYYY-MM-DD hh:mm:ss"),
        value: newValue
      };

      measurements.push(value);
      linear_counter = linear_counter + linearDelayFlag;
      periodic_counter = periodic_counter + periodicDelayFlag;
      counter++;
    }

    signal = signalAPIService.processNewMeasurements(signal, measurements);
    signal.measurements = measurements;
    signal.data_count = measurements.length;
  } else if (form_data.signal_type === "general_signal") {
      signal.data_type = "General";
  } else if (form_data.signal_type === "sensor_signal") {
      signal.data_type = "Sensor data",
      signal.sensor_location = form_data.sensor_location;
      signal.sensor_type = form_data.sensor_type;
      signal.file_uri = form_data.file_uri;
      signal.sensor_data_source = form_data.sensor_data_source;
  }
  return signal;
}

exports.addSignalToDataSource = function(req, res) {
  var datasource_id = req.params.datasource_id
  var user = req.user;
  var criteria = {};
  criteria = {
    '_id': datasource_id,
    'user': user,
  };

  DataSource.findOne(criteria).exec(function(err_find, datasource) {

    if (err_find) {

      res.json({
        status: 0,
        message: "No signals defined"
      });
    } else {

      //Validate and sanitize
      var signal = constructSignal(req.body);
      signal.user = user;

      signal.save(function(err_signal) {
        datasource.signals.push(signal);
        datasource.save(function(err_save) {
          if (!err_save && !err_signal) {
            res.json({
              status: 1,
              datasource: datasource,
              signal: signal
            });
          }
        });

      });
    }
  });
}

exports.deleteSignalFromDataSource = function(req, res) {
  var datasource_id = req.params.datasource_id;
  var signal_id = req.params.signal_id;
  var authenticatedUser = req.user;

  var criteria = {};
  criteria = {
    '_id': datasource_id,
    'user': authenticatedUser,
  };
  DataSource.findOne(criteria).exec(function(err_find, datasource) {
    if (err_find) {
      res.json({
        status: 0,
        message: "No signals defined"
      });
    } else {
      datasource.signals.pull(mongoose.Types.ObjectId(signal_id));
      datasource.save(function(err_save) {

        Signal.findOne({
          '_id': signal_id
        }).remove(function(err_remove, signal) {

          //Find model and re-do the states
          Model.find({
            'datasource': datasource_id,
            'user': authenticatedUser,
          }).exec(function(err_models, models) {

            models.forEach(function(model) {
              model.states = [];
              datasource.signals.forEach(function(signal) {
                model.states.push({
                  "name": signal.name,
                  "type": "from signal"
                });
              });

            });

            if (!err_save) {
              res.json({
                status: 1,
                datasource: datasource,
              });
            }

          });

        });

      });
    }
  });
}

// --- Sharing

exports.addDataSourceShareToken = function(req, res) {
  var datasource_id = req.params.datasource_id
  var authenticatedUser = req.user;
  var sharedWithUser = req.body.sharewith;

  var criteria = {};
  criteria = {
    '_id': datasource_id,
    'user': authenticatedUser,
  };

  DataSource.findOne(criteria).exec(function(err_find, datasource) {

    if (err_find) {

      res.json({
        status: 0,
        message: "No signals defined"
      });
    } else {

      var token = hat();

      var sharetoken = new ShareToken({
        datasource: datasource,
        sharedByUser: authenticatedUser,
        sharedWithUser: sharedWithUser,
        token: token
      });

      sharetoken.save(function(err_save) {
        if (!err_save) {
          res.json({
            status: 1,
            sharetoken: sharetoken
          });
        }
      });
    }
  });
}

exports.getAllShareTokensForDataSource = function(req, res) {
  var datasource_id = req.params.datasource_id
  var authenticatedUser = req.user;

  var criteria = {};
  criteria = {
    'datasource': datasource_id,
    'sharedByUser': authenticatedUser,
  };

  ShareToken.find(
    criteria
  ).exec(function(err, sharetokens) {

    if (err || !sharetokens.length) {
      res.json({
        status: 0,
        sharetokens: [{
          id: 0,
          name: 'No sharetokens found for user'
        }]
      });
    } else {
      res.json({
        status: 1,
        sharetokens: sharetokens
      });
    }
  });
}

exports.deleteShareTokenFromDataSource = function(req, res) {
  var datasource_id = req.params.datasource_id;
  var share_id = req.params.share_id;
  var authenticatedUser = req.user;

  var criteria = {
    $and: [{
      '_id': share_id
    }, {
      $or: [{
        'sharedByUser': authenticatedUser
      }, {
        'sharedWithUser': authenticatedUser.local.email
      }]
    }]
  }

  ShareToken.findOne(criteria).remove(function(err, sharetoken) {
    if (err) {
      res.json({
        status: 0,
        message: "No sharetoken defined"
      });
    } else {
      if (!err) {
        res.json({
          status: 1,
          sharetoken: sharetoken,
        });
      }
    }
  });
}<commit_msg>cleaned up file<commit_after>// Dependencies
var request = require('request');
var moment = require('moment');

// Local libraries
var utils = require('../lib/utils.js');
var datalib = require('../lib/datalib.js');

var DataSource = require('../models/data_source').DataSource;
var Project = require('../models/project');
var Signal = require('../models/data_source').Signal;
var Model = require('../models/model');
var ShareToken = require('../models/datashare_token');
var signalAPIService = require('../services/SignalAPIService');
var mongoose = require('mongoose');
var asyncR = require('async');

var hat = require('hat');

var validator = require('validator');

exports.getAllDataSourcesForUser = function(req, res) {
	var authenticatedUser = req.user;

	var sort = req.query.sort;
	sort = (typeof req.query.sort === 'undefined') ? "desc" : sort;
	var sortInt = (sort === 'desc') ? -1 : 1;

	var criteria = {
		'user': authenticatedUser,
	};

	DataSource.find(criteria)
		.sort({
			name: sort
		})
		.populate('projects', 'name')
		.exec(function(err_datasource, datasources) {
			if (err_datasource || !datasources.length) {
				res.json({
					status: 0,
					message: "No datasources found for user.",
					datasources: []
				});
			} else {
				var userDataSources = datasources;
				/* lets get shared datasources */
				ShareToken.find({
						sharedWithUser: authenticatedUser.local.email
					})
					.populate('datasource').lean().populate('sharedByUser').exec(function(err_sharedDatasource, sharedDatasources) {
						sharedDatasources.forEach(function(dataSource) {
							dataSource.sharedByUser = utils.santizeUserObject(dataSource.sharedByUser);
						})
						res.set('X-Total-Count', datasources.length.toString());
						res.json({
							status: 1,
							datasources: userDataSources,
							shared_datasources: sharedDatasources
						});
					});
			}
		});
}

exports.addDataSource = function(req, res) {
	var datasourceName = req.body.datasource_name;
	var datasourceDescription = req.body.datasource_description;
	var authenticatedUser = req.user;

	var newDataSource = DataSource(
		req.body
	);
	// Set the user
	newDataSource.user = authenticatedUser;

	newDataSource.save(function(err, newDataSource) {
		if (err)
			res.json({
				status: 0,
				message: 'Datasource not saved'
			});
		else
		res.json({
			status: 1,
			message: 'Datasource saved successfully',
			links: {
				href: '/datasources/' + newDataSource._id
			},
			datasource: {
				name: newDataSource.name,
				description: newDataSource.description,
			}
		});
	});
};

exports.getDataSourceById = function(req, res) {
	var datasource_id = req.params.datasource_id;
	var authenticatedUser = req.user;

	DataSource.findOne({
		'_id': datasource_id,
		'user': authenticatedUser
	}).populate('signals', '-measurements').exec(function(err, datasource) {
		if (err)
			res.json({
				status: 0,
				message: 'Data source not found'
			});
		else
			res.json({
				status: 1,
				datasource: datasource,
			});
	});
}

exports.editDataSource = function(req, res) {
	var datasource_id = req.params.datasource_id;
	var name = req.body.datasourcename;
	var description = req.body.datasourcedescription;
	var authenticatedUser = req.user;

	if (datasource_id === "")
		res.json({
			staus: -1,
			message: "Could not find datasource with ID " + datasource_id
		});

	DataSource.findOne({
		_id: datasource_id,
		'user': authenticatedUser
	}, function(err, datasource) {
		if (err) {
			res.send(err);
		}

		datasource.name = name;
		datasource.description = description;

		datasource.save(function(err, datasource) {
			if (err) {
				res.send(err);
			}
			res.json(datasource);
		});

	})

}

exports.deleteDataSource = function(req, res) {
	var datasource_id = req.params.datasource_id;
	var authenticatedUser = req.user;

	if (datasource_id === "")
		res.json({
			staus: -1,
			message: "Could not find datasource with ID " + datasource_id
		});

	DataSource.findOne({
		_id: datasource_id,
		'user': authenticatedUser
	}).remove(function(err, datasource) {
		if (err) {
			res.send(err);
		}

		Project.findOne({
				'datasources.oid': datasource_id
			}, {
				'datasources.$': 1
			},
			function(err, project) {

				if (project) {

				} else {

				}
			}
		)

		res.json(datasource);

	})

}

exports.getAllDataSourcesForProject = function(req, res) {
	var project_id = req.params.project_id
	var authenticatedUser = req.user;

	var criteria = {};
	criteria = {
		'project_id': project_id,
	};

	DataSource.find(criteria, function(err, datasources) {

		if (err || !datasources.length) {
			res.json({
				status: 0,
				datasources: [{
					id: 0,
					name: 'No datasources found for project'
				}]
			});
		} else {
			var returnedDataSources = datasources;
			res.json({
				status: 1,
				datasources: returnedDataSources
			});
		}
	});
}

exports.getAllSignalsFromDataSource = function(req, res) {
	var datasource_id = req.params.datasource_id;
	// Get the authenticated user
	var authenticatedUser = req.user;

	var depth = req.query.depth;
	var populateSelector = "";
	if (depth === undefined)
		populateSelector = '';
	else
		populateSelector = depth.replace(',', ' ');

	var criteria = {};
	criteria = {
		'_id': datasource_id,
		'user': authenticatedUser,
	};

	DataSource.findOne(criteria).populate('signals', populateSelector).exec(function(err, datasource) {

		if (err || !datasource) {

			res.json({
				status: 0,
				message: "No signals defined",
				signals: []
			});
		} else {
			console.log(datasource.signals);
			var signals = datasource.signals;
			res.json({
				status: 1,
				signals: signals
			});
		}
	});
}

var constructSignal = function(form_data) {
	var signal = new Signal({});
	signal.name = form_data.signal_name;
	signal.description = form_data.signal_description;

	if (form_data.signal_type === "timestamp") {
		signal.data_type = "Timestamp";
	} else if (form_data.signal_type === "generated_signal") {

		var linear_gradient = parseFloat(form_data.signal_linear_gradient);
		var linear_delay = parseInt(form_data.signal_linear_delay);
		var periodic_delay = parseInt(form_data.signal_periodic_delay);
		var periodic_mag = parseInt(form_data.signal_periodic_mag);
		var periodic_period = parseInt(form_data.signal_periodic_period);

		signal.data_type = "RG";
		signal.linear_gradient = linear_gradient;
		signal.periodic_mag = form_data.signal_periodic_mag;
		signal.periodic_period = form_data.signal_periodic_period;

		var today = moment();
		var date = moment(form_data.start_date);

		var dt_minutes = form_data.signal_dt;

		var measurements = [];

		var counter = 0;
		var linear_counter = 0;
		var periodic_counter = 0;
		for (var m = date; m.diff(today, 'minutes') <= 0; m.add(dt_minutes, 'minutes')) {
			var linearDelayFlag = (counter >= linear_delay) ? 1 : 0;
			var periodicDelayFlag = (counter >= periodic_delay) ? 1 : 0;
			var periodicComponent = 0; //periodic_period%periodic_counter;
			var newValue = datalib.generateInitialData(0, 2) + linear_counter * linear_gradient + periodic_counter * periodicComponent;
			var value = {
				datetime: m.format("YYYY-MM-DD hh:mm:ss"),
				value: newValue
			};

			measurements.push(value);
			linear_counter = linear_counter + linearDelayFlag;
			periodic_counter = periodic_counter + periodicDelayFlag;
			counter++;
		}

		signal = signalAPIService.processNewMeasurements(signal, measurements);
		signal.measurements = measurements;
		signal.data_count = measurements.length;
	} else if (form_data.signal_type === "general_signal") {
		signal.data_type = "General";
	} else if (form_data.signal_type === "sensor_signal") {
		signal.data_type = "Sensor data",
			signal.sensor_location = form_data.sensor_location;
		signal.sensor_type = form_data.sensor_type;
		signal.file_uri = form_data.file_uri;
		signal.sensor_data_source = form_data.sensor_data_source;
	}
	return signal;
}

exports.addSignalToDataSource = function(req, res) {
	var datasource_id = req.params.datasource_id
	var user = req.user;
	var criteria = {};
	criteria = {
		'_id': datasource_id,
		'user': user,
	};

	DataSource.findOne(criteria).exec(function(err_find, datasource) {

		if (err_find) {

			res.json({
				status: 0,
				message: "No signals defined"
			});
		} else {

			//Validate and sanitize
			var signal = constructSignal(req.body);
			signal.user = user;

			signal.save(function(err_signal) {
				datasource.signals.push(signal);
				datasource.save(function(err_save) {
					if (!err_save && !err_signal) {
						res.json({
							status: 1,
							datasource: datasource,
							signal: signal
						});
					}
				});

			});
		}
	});
}

exports.deleteSignalFromDataSource = function(req, res) {
	var datasource_id = req.params.datasource_id;
	var signal_id = req.params.signal_id;
	var authenticatedUser = req.user;

	var criteria = {};
	criteria = {
		'_id': datasource_id,
		'user': authenticatedUser,
	};
	DataSource.findOne(criteria).exec(function(err_find, datasource) {
		if (err_find) {
			res.json({
				status: 0,
				message: "No signals defined"
			});
		} else {
			datasource.signals.pull(mongoose.Types.ObjectId(signal_id));
			datasource.save(function(err_save) {

				Signal.findOne({
					'_id': signal_id
				}).remove(function(err_remove, signal) {

					//Find model and re-do the states
					Model.find({
						'datasource': datasource_id,
						'user': authenticatedUser,
					}).exec(function(err_models, models) {

						models.forEach(function(model) {
							model.states = [];
							datasource.signals.forEach(function(signal) {
								model.states.push({
									"name": signal.name,
									"type": "from signal"
								});
							});

						});

						if (!err_save) {
							res.json({
								status: 1,
								datasource: datasource,
							});
						}

					});

				});

			});
		}
	});
}

// --- Sharing

exports.addDataSourceShareToken = function(req, res) {
	var datasource_id = req.params.datasource_id
	var authenticatedUser = req.user;
	var sharedWithUser = req.body.sharewith;

	var criteria = {};
	criteria = {
		'_id': datasource_id,
		'user': authenticatedUser,
	};

	DataSource.findOne(criteria).exec(function(err_find, datasource) {

		if (err_find) {

			res.json({
				status: 0,
				message: "No signals defined"
			});
		} else {

			var token = hat();

			var sharetoken = new ShareToken({
				datasource: datasource,
				sharedByUser: authenticatedUser,
				sharedWithUser: sharedWithUser,
				token: token
			});

			sharetoken.save(function(err_save) {
				if (!err_save) {
					res.json({
						status: 1,
						sharetoken: sharetoken
					});
				}
			});
		}
	});
}

exports.getAllShareTokensForDataSource = function(req, res) {
	var datasource_id = req.params.datasource_id
	var authenticatedUser = req.user;

	var criteria = {};
	criteria = {
		'datasource': datasource_id,
		'sharedByUser': authenticatedUser,
	};

	ShareToken.find(
		criteria
	).exec(function(err, sharetokens) {

		if (err || !sharetokens.length) {
			res.json({
				status: 0,
				sharetokens: [{
					id: 0,
					name: 'No sharetokens found for user'
				}]
			});
		} else {
			res.json({
				status: 1,
				sharetokens: sharetokens
			});
		}
	});
}

exports.deleteShareTokenFromDataSource = function(req, res) {
	var datasource_id = req.params.datasource_id;
	var share_id = req.params.share_id;
	var authenticatedUser = req.user;

	var criteria = {
		$and: [{
			'_id': share_id
		}, {
			$or: [{
				'sharedByUser': authenticatedUser
			}, {
				'sharedWithUser': authenticatedUser.local.email
			}]
		}]
	}

	ShareToken.findOne(criteria).remove(function(err, sharetoken) {
		if (err) {
			res.json({
				status: 0,
				message: "No sharetoken defined"
			});
		} else {
			if (!err) {
				res.json({
					status: 1,
					sharetoken: sharetoken,
				});
			}
		}
	});
}<|endoftext|>


<commit_before>/* global Components, Services, $ */

EXPORTED_SYMBOLS = ['Ui', 'Headup'];

const {interfaces: Ci, utils: Cu, classes: Cc} = Components;

const NS_XUL = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';

const KEYSET_ID = 'wakatime-keyset';
const KEY_ID = 'wakatime-key';

// global imports
Cu.import('resource://gre/modules/Services.jsm');

let Css = {
    stylesheets: [
        'chrome://wakatime/skin/overlay.css'
    ],
    init: function() {
        let styleSheetService = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);

        for( let i=0; i<Css.stylesheets.length; i++ ) {
            let styleSheetURI = Services.io.newURI(Css.stylesheets[i], null, null);

            styleSheetService.loadAndRegisterSheet(styleSheetURI, styleSheetService.AUTHOR_SHEET);
            Log.info(styleSheetURI);
        }
    },
    destroy: function() {
        let styleSheetService = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);

        for( let i=0; i<Css.stylesheets.length; i++ ) {
            let styleSheetURI = Services.io.newURI(Css.stylesheets[i], null, null);

            if (styleSheetService.sheetRegistered(styleSheetURI, styleSheetService.AUTHOR_SHEET)) {
                styleSheetService.unregisterSheet(styleSheetURI, styleSheetService.AUTHOR_SHEET);
            }
        }
    }
};

let Menu = {
    load: function(win) {
        // TODO: ideally no additional menus
    }
};

let Toolbar = {
    load: function(win) {
        // TODO: ideally no additional toolbar buttons
    }
};

let Statusbar = {
    init: function() {
        function Observer() {
            this.register();
        }

        Observer.prototype = {
            observe: function(subject, topic, data) {
                Log.info('Statusbar - s: ' + subject + ' t: ' + topic + ' d: ' + data);
            },
            register: function() {
                var observerService = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
                //observerService.addObserver(this, '*', false); // NOTE: just for debugging, very verbose
                observerService.addObserver(this, 'wt-event', false);
            },
            unregister: function() {
                var observerService = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
                //observerService.removeObserver(this, '*');
                observerService.removeObserver(this, 'wt-event');
            }
        };

        this.observer = new Observer();
    },
    destroy: function() {
        // TODO: anything to be done here?
    },
    load: function(win) {
        if (!win) return;

        let doc = win.document;

        doc.loadOverlay('chrome://wakatime/content/statusbar.xul', this.observer);
    }
};

let Headup = {
    init: function() {
    },
    observer: {
        observe: function(subject, topic, data) {
            Log.info('Headup - s: ' + subject + ' t: ' + topic + ' d: ' + data);
        }
    },
    show: function() {
        // NOTE: this functions blocks until dialog is closed (modal)
        //Ui.win().openDialog('chrome://wakatime/content/' + name + '.xul', '', 'chrome,centerscreen', timeout);
        //Ui.win().openDialog('chrome://wakatime/content/' + name + '.xul', '', 'dialog,centerscreen', timeout);
        //let AlertService = Cc['@mozilla.org/alerts-service;1'].getService(Ci.nsIAlertsService);
        //AlertService.showAlertNotification('chrome://wakatime/skin/logo.png', 'Wakatime', 'This is a message from Wakatime', true, '', Headup.observer, '');
        try {
            Cc['@mozilla.org/alerts-service;1'].getService(Ci.nsIAlertsService).showAlertNotification(null, 'Wakatime', 'This is a message from Wakatime', false, '', Headup.observer);
        } catch(e) {
            // prevents runtime error on platforms that don't implement nsIAlertsService
            Log.info(e);
        }
    }
};

let Shortcut = {
    load: function(win) {
        Log.info('Shortcut....');
        if (!win) return;

        let doc = win.document;

        let keyset = doc.createElementNS(NS_XUL, 'keyset');
        keyset.setAttribute('id', KEYSET_ID);

        let key = doc.createElementNS(NS_XUL, 'key');
        key.setAttribute('id', KEY_ID);
        key.setAttribute('key', Prefs.getPref('shortcut_key'));
        key.setAttribute('modifiers', Prefs.getPref('shortcut_modifiers'));
        key.setAttribute('oncommand', 'void(0);');
        key.addEventListener('command', function() {
            //Headup.show('project', 1000);
            Headup.show();
            Log.info('Shortcut done.');
        }, true);

        let node = $(doc, Ui.app.baseKeyset);

        // http://code.metager.de/source/xref/mozilla/thunderbird/suite/mailnews/compose/messengercompose.xul
        if(!node) {
            node  = $(doc, 'tasksKeys');
        }

        if(node && node.parentNode) {
            Log.info('Shortcut append....');
            node.parentNode.appendChild(keyset).appendChild(key);
        } else {
            Log.info('Shortcut fail!');
        }
    }
};

let Ui = {
    init: function() {
        // module imports
        Cu.import('resource://wakatime/modules/util.jsm');

        this.app = {};

        switch(Services.appinfo.name) {
            case 'Thunderbird':
                this.app.winType = 'mail:3pane';
                this.app.baseKeyset = 'mailKeys';
                break;
            case 'Fennec':
                // ignore
                break;
            default:
                //Firefox, SeaMonkey
                this.app.winType = 'navigator:browser';
                this.app.baseKeyset = 'mainKeyset';
        }

        // init
        //Css.init();
        Statusbar.init();

        Services.ww.registerNotification(this.windowWatcher);

        // add features to existing windows
        this.eachWindow(function(win) {
            Ui.load(win);
        });
    },
    destroy: function() {
        Statusbar.destroy();
        //Css.destroy();
        Services.ww.unregisterNotification(this.windowWatcher);
    },
    load: function(win) {
        // load into windows
        Shortcut.load(win);
        Statusbar.load(win);
    },
    eachWindow: function (callback) {
        let enumerator = Services.wm.getEnumerator(this.app.winType);
        while (enumerator.hasMoreElements()) {
            let win = enumerator.getNext();
            if (win.document.readyState === 'complete') {
                callback(win);
            } else {
                Ui.runOnLoad(win, callback);
            }
        }
    },
    runOnLoad: function (win, callback) {
        win.addEventListener('load', function __listener() {
            win.removeEventListener('load', __listener, false);

            let winType = win.document.documentElement.getAttribute("windowtype");

            if(winType === Ui.app.winType || winType === 'msgcompose') {
                callback(win);
            } else {
                Log.info('Win Type: ' + winType); // TODO: remove before release
            }
        }, false);
    },
    windowWatcher: function(subject, topic) {
        if(topic === 'domwindowopened') {
            Ui.runOnLoad(subject, Ui.load);
        } else {
            Log.info('Watcher - t: ' + topic);
        }
    },
    win: function() {
        var wm = Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
        return wm.getMostRecentWindow(null);
    },
    setTimeout: function(callback, timeout) {
        var timer = Cc['@mozilla.org/timer;1'].createInstance(Ci.nsITimer);
        timer.initWithCallback(callback, timeout, Ci.nsITimer.TYPE_ONE_SHOT);
    }
};
<commit_msg>Remove debug messages<commit_after>/* global Components, Services, $ */

EXPORTED_SYMBOLS = ['Ui', 'Headup'];

const {interfaces: Ci, utils: Cu, classes: Cc} = Components;

const NS_XUL = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';

const KEYSET_ID = 'wakatime-keyset';
const KEY_ID = 'wakatime-key';

// global imports
Cu.import('resource://gre/modules/Services.jsm');

let Css = {
    stylesheets: [
        'chrome://wakatime/skin/overlay.css'
    ],
    init: function() {
        let styleSheetService = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);

        for( let i=0; i<Css.stylesheets.length; i++ ) {
            let styleSheetURI = Services.io.newURI(Css.stylesheets[i], null, null);

            styleSheetService.loadAndRegisterSheet(styleSheetURI, styleSheetService.AUTHOR_SHEET);
            Log.info(styleSheetURI);
        }
    },
    destroy: function() {
        let styleSheetService = Cc["@mozilla.org/content/style-sheet-service;1"].getService(Ci.nsIStyleSheetService);

        for( let i=0; i<Css.stylesheets.length; i++ ) {
            let styleSheetURI = Services.io.newURI(Css.stylesheets[i], null, null);

            if (styleSheetService.sheetRegistered(styleSheetURI, styleSheetService.AUTHOR_SHEET)) {
                styleSheetService.unregisterSheet(styleSheetURI, styleSheetService.AUTHOR_SHEET);
            }
        }
    }
};

let Menu = {
    load: function(win) {
        // TODO: ideally no additional menus
    }
};

let Toolbar = {
    load: function(win) {
        // TODO: ideally no additional toolbar buttons
    }
};

let Statusbar = {
    init: function() {
        function Observer() {
            this.register();
        }

        Observer.prototype = {
            observe: function(subject, topic, data) {
                Log.info('Statusbar - s: ' + subject + ' t: ' + topic + ' d: ' + data);
            },
            register: function() {
                var observerService = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
                //observerService.addObserver(this, '*', false); // NOTE: just for debugging, very verbose
                observerService.addObserver(this, 'wt-event', false);
            },
            unregister: function() {
                var observerService = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
                //observerService.removeObserver(this, '*');
                observerService.removeObserver(this, 'wt-event');
            }
        };

        this.observer = new Observer();
    },
    destroy: function() {
        // TODO: anything to be done here?
    },
    load: function(win) {
        if (!win) return;

        let doc = win.document;

        doc.loadOverlay('chrome://wakatime/content/statusbar.xul', this.observer);
    }
};

let Headup = {
    init: function() {
    },
    observer: {
        observe: function(subject, topic, data) {
            Log.info('Headup - s: ' + subject + ' t: ' + topic + ' d: ' + data);
        }
    },
    show: function() {
        // NOTE: this functions blocks until dialog is closed (modal)
        //Ui.win().openDialog('chrome://wakatime/content/' + name + '.xul', '', 'chrome,centerscreen', timeout);
        //Ui.win().openDialog('chrome://wakatime/content/' + name + '.xul', '', 'dialog,centerscreen', timeout);
        //let AlertService = Cc['@mozilla.org/alerts-service;1'].getService(Ci.nsIAlertsService);
        //AlertService.showAlertNotification('chrome://wakatime/skin/logo.png', 'Wakatime', 'This is a message from Wakatime', true, '', Headup.observer, '');
        try {
            Cc['@mozilla.org/alerts-service;1'].getService(Ci.nsIAlertsService).showAlertNotification(null, 'Wakatime', 'This is a message from Wakatime', false, '', Headup.observer);
        } catch(e) {
            // prevents runtime error on platforms that don't implement nsIAlertsService
            Log.info(e);
        }
    }
};

let Shortcut = {
    load: function(win) {
        if (!win) return;

        let doc = win.document;

        let keyset = doc.createElementNS(NS_XUL, 'keyset');
        keyset.setAttribute('id', KEYSET_ID);

        let key = doc.createElementNS(NS_XUL, 'key');
        key.setAttribute('id', KEY_ID);
        key.setAttribute('key', Prefs.getPref('shortcut_key'));
        key.setAttribute('modifiers', Prefs.getPref('shortcut_modifiers'));
        key.setAttribute('oncommand', 'void(0);');
        key.addEventListener('command', function() {
            Headup.show();
        }, true);

        // NOTE: this is the best way to find the window elements
        // http://code.metager.de/source/xref/mozilla/thunderbird/suite/mailnews/compose/messengercompose.xul
        let node = $(doc, Ui.app.baseKeyset);

        // msgcompose window
        if(!node) {
            node  = $(doc, 'tasksKeys');
        }

        if(node && node.parentNode) {
            node.parentNode.appendChild(keyset).appendChild(key);
        }
    }
};

let Ui = {
    init: function() {
        // module imports
        Cu.import('resource://wakatime/modules/util.jsm');

        this.app = {};

        switch(Services.appinfo.name) {
            case 'Thunderbird':
                this.app.winType = 'mail:3pane';
                this.app.baseKeyset = 'mailKeys';
                break;
            case 'Fennec':
                // ignore
                break;
            default:
                //Firefox, SeaMonkey
                this.app.winType = 'navigator:browser';
                this.app.baseKeyset = 'mainKeyset';
        }

        // init
        //Css.init();
        Statusbar.init();

        Services.ww.registerNotification(this.windowWatcher);

        // add features to existing windows
        this.eachWindow(function(win) {
            Ui.load(win);
        });
    },
    destroy: function() {
        Statusbar.destroy();
        //Css.destroy();
        Services.ww.unregisterNotification(this.windowWatcher);
    },
    load: function(win) {
        // load into windows
        Shortcut.load(win);
        Statusbar.load(win);
    },
    eachWindow: function (callback) {
        let enumerator = Services.wm.getEnumerator(this.app.winType);
        while (enumerator.hasMoreElements()) {
            let win = enumerator.getNext();
            if (win.document.readyState === 'complete') {
                callback(win);
            } else {
                Ui.runOnLoad(win, callback);
            }
        }
    },
    runOnLoad: function (win, callback) {
        win.addEventListener('load', function __listener() {
            win.removeEventListener('load', __listener, false);

            let winType = win.document.documentElement.getAttribute("windowtype");

            if(winType === Ui.app.winType || winType === 'msgcompose') {
                callback(win);
            } else {
                Log.info('Win Type: ' + winType); // TODO: remove before release
            }
        }, false);
    },
    windowWatcher: function(subject, topic) {
        if(topic === 'domwindowopened') {
            Ui.runOnLoad(subject, Ui.load);
        } else {
            Log.info('Watcher - t: ' + topic);
        }
    },
    win: function() {
        var wm = Cc['@mozilla.org/appshell/window-mediator;1'].getService(Ci.nsIWindowMediator);
        return wm.getMostRecentWindow(null);
    },
    setTimeout: function(callback, timeout) {
        var timer = Cc['@mozilla.org/timer;1'].createInstance(Ci.nsITimer);
        timer.initWithCallback(callback, timeout, Ci.nsITimer.TYPE_ONE_SHOT);
    }
};
<|endoftext|>


<commit_before>'use strict';

angular.module('videogularQuizExample.simpleExample', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
	$routeProvider.when('/simple-example', {
		templateUrl: 'simple-example/simple-example.html',
		controller: 'SimpleExampleCtrl'
	});
}])

.controller('SimpleExampleCtrl', function($scope, $sce) {
	$scope.config = {
		autoHide: false,
		autoHideTime: 3000,
		sources: [
			{src: $sce.trustAsResourceUrl("video.ogg"), type: "video/ogg"}
		],
		theme: {
			url: "simple-example/videogular.css"
		},
		plugins: {
			questions: {
				theme: {
					url: "simple-example/videogular-questions.css"
				},
				data:{
					url: "simple-example/simple-test.json",
				}
			}
		}
	};
});
<commit_msg>Added the new video formats to the javascript<commit_after>'use strict';

angular.module('videogularQuizExample.simpleExample', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
	$routeProvider.when('/simple-example', {
		templateUrl: 'simple-example/simple-example.html',
		controller: 'SimpleExampleCtrl'
	});
}])

.controller('SimpleExampleCtrl', function($scope, $sce) {
	$scope.config = {
		autoHide: false,
		autoHideTime: 3000,
		sources: [
			{src: $sce.trustAsResourceUrl("video.ogg"), type: "video/ogg"},
			{src: $sce.trustAsResourceUrl("video.mov"), type: "video/mov"},
			{src: $sce.trustAsResourceUrl("video.avi"), type: "video/avi"},
			{src: $sce.trustAsResourceUrl("video.mp4"), type: "video/mp4"},
			{src: $sce.trustAsResourceUrl("video.m4v"), type: "video/m4v"}
		],
		theme: {
			url: "simple-example/videogular.css"
		},
		plugins: {
			questions: {
				theme: {
					url: "simple-example/videogular-questions.css"
				},
				data:{
					url: "simple-example/simple-test.json",
				}
			}
		}
	};
});
<|endoftext|>