<commit_before>'use strict';

angular.module('sbAdminApp', ['toastr', 'ngDialog'])
  .controller('EventCtrl', ['$scope', '$window', '$http', 'EventsService', '$stateParams', 'toastr', 'ngDialog', '$rootScope',
    function($scope, $window, $http, EventsService, $stateParams, toastr, ngDialog, $rootScope) {

      var eventsType = $stateParams.type;
      var keyword = $stateParams.search;
      var pastEvents = [];
      var latestEvents = [];
      $scope.eventsList = {};
      $rootScope.filteredEvents = {};
      $scope.dialogShown = true;
      var epoch, isEventsPresentinSession;
      $scope.hideSearchBar = true;

      $scope.ConfirmDelete = function(event) {
        $rootScope.EventtobeDeleted = event;
        ngDialog.open({
          template: 'views/template.html',
          controller: 'DialogCtrl',
          className: 'ngdialog-theme-default ngdialog-theme-custom'
        });
      };

      function LoadEventsFromSession() {
        $scope.eventsList = JSON.parse(isEventsPresentinSession);
      }

      function CheckLastSession() {
        isEventsPresentinSession = sessionStorage.getItem('allEvents');
      }

      function LoadEvents(Type) {
        CheckLastSession();
        Date.prototype.today = function() {
            return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
          }
          // For the time now
        Date.prototype.timeNow = function() {
          return ((this.getHours() < 10) ? "0" : "") + this.getHours() + ":" + ((this.getMinutes() < 10) ? "0" : "") + this.getMinutes() + ":" + ((this.getSeconds() < 10) ? "0" : "") + this.getSeconds();
        }

        function ProcessEvents() {
          var today = new Date();
          epoch = moment(today.today() + " " + today.timeNow(), "D/M/YYYY H:mm").unix();
          angular.forEach($scope.eventsList, function(event) {
            if (Type === 'past') {
              console.log("evluating past");
              $scope.Heading = "All Past Events: before " + today.today() + " " + today.timeNow();
              if (parseInt(event.start_time) < epoch) {
                var GMTTime = moment.unix(event.start_time);
                event.start_time = moment(GMTTime).subtract({
                  'hours': '5',
                  'minutes': '30'
                }).format('ll HH:mm');
                pastEvents.push(event);
              }
            } else {
              console.log("evluating latest");
              $scope.Heading = "All Latest Events: after " + today.today() + " " + today.timeNow();
              if (parseInt(event.start_time) >= epoch) {
                var GMTTime = moment.unix(event.start_time).format('ll HH:mm');
                event.start_time = moment(GMTTime).subtract({
                  'hours': '5',
                  'minutes': '30'
                }).format('ll HH:mm');
                latestEvents.push(event);
              }
            }
          });
        }
        if (isEventsPresentinSession !== 'undefined' && isEventsPresentinSession != null && isEventsPresentinSession != '') {
          LoadEventsFromSession();
          ProcessEvents();
        } else {
          EventsService.GetEvents(function() {})
            .then(function(response) {
              $scope.eventsList = response.data.events;
              sessionStorage.setItem('allEvents', JSON.stringify(response.data.events));
              ProcessEvents();
              ProcessEvents();

            });
        }
        // For todays date;

        console.log("Type =" + Type);
        if (Type === 'past') {
          $rootScope.filteredEvents = pastEvents;

        } else {
          $rootScope.filteredEvents = latestEvents;

        }

        /*   console.log(pastEvents);
           console.log(latestEvents);*/

        //need to make sessionStorage.clear
        //  console.log($scope.eventsList.length);
      };

      if (eventsType !== "" && eventsType !== null && eventsType !== undefined) {
        LoadEvents(eventsType);
      }

      $scope.SearchEvent = function(keyword) {
        $scope.hideSearchBar = false;
        var pastEvents = [];
        var latestEvents = [];
        CheckLastSession();
        if (isEventsPresentinSession !== "undefined" && isEventsPresentinSession != null && isEventsPresentinSession != '') {
          LoadEventsFromSession();
        }
        angular.forEach($scope.eventsList, function(event) {
          if (event.name.toLowerCase().indexOf(keyword) != -1) {
            if (parseInt(event.start_time) < epoch) {
              pastEvents.push(event);
            } else {
              latestEvents.push(event);
            }
          }
        });
        console.log(pastEvents);
        console.log(latestEvents);
        $rootScope.filteredEvents = null;
        if (pastEvents.length > 0) {
          latestEvents.push(pastEvents);
        }
        //$scope.filteredEvents.push(latestEvents);
        debugger;
        $rootScope.filteredEvents = latestEvents;
        console.log("result of search");
        console.log($rootScope.filteredEvents);

      }
      if (keyword !== "" && keyword !== null && keyword !== undefined) {
        $scope.SearchEvent(keyword.toLowerCase());
      } else {
        if (eventsType === 'past') {
          $window.location.href = '/#/dashboard/events?type=past';
        } else {
          $window.location.href = '/#/dashboard/events?type=latest';
        }
      }
      /*
            $scope.DeleteEvent = function(event) {
              console.log('deleting event' + event.key + '  ' + event.name);
              EventsService.DeleteEvent(event.key).then(function(response) {
                toastr.success('Event deleted successfully', 'Success!');
                sessionStorage.removeItem('allEvents');
                var afterDeleteEvents = [];
                angular.forEach($rootScope.filteredEvents, function(currentEvent) {
                  if (currentEvent.key !== event.key && currentEvent.key !== undefined && currentEvent.key !== null && currentEvent.key !== '') {
                    afterDeleteEvents.push(currentEvent);
                  }
                });

                $rootScope.filteredEvents = afterDeleteEvents;
                // var eventString =  JSON.stringify(afterDeleteEvents);
                //sessionStorage.setItem('allEvents', eventString);
                console.log($rootScope.filteredEvents);
                console.log('event getting deleted');
                console.log(afterDeleteEvents);
              }, function() {
                toastr.success('Event deleting failed', 'Error!');
              });
            }*/

      $scope.ShowEventDetails = function(event) {
        var stringevent = JSON.stringify(event);
        sessionStorage.setItem('currentEvent', stringevent);
        $window.location.href = '/#/dashboard/e/' + eventsType + '/' + event.key;
      }
    }
  ])
  .controller('DialogCtrl', ['EventsService', 'toastr', '$scope', 'ngDialog', '$rootScope', function(EventsService, toastr, $scope, ngDialog, $rootScope) {

    $scope.closeDialog = function() {
      ngDialog.close('ngdialog1');
    }

    $scope.DeleteEvent = function() {
      ngDialog.close('ngdialog1');
      EventsService.DeleteEvent($rootScope.EventtobeDeleted.key).then(function(response) {
        toastr.success('Event deleted successfully', 'Success!');
        sessionStorage.removeItem('allEvents');
        var afterDeleteEvents = [];
        angular.forEach($rootScope.filteredEvents, function(currentEvent) {
          if (currentEvent.key !== $rootScope.EventtobeDeleted.key && currentEvent.key !== undefined && currentEvent.key !== null && currentEvent.key !== '') {
            afterDeleteEvents.push(currentEvent);
          }
        });
        $rootScope.filteredEvents = afterDeleteEvents;
      }, function() {
        toastr.success('Event deleting failed', 'Error!');
      });
    }

  }]);<commit_msg>Refractored code<commit_after>'use strict';

angular.module('sbAdminApp', ['toastr', 'ngDialog'])
  .controller('EventCtrl', ['$scope', '$window', '$http', 'EventsService', '$stateParams', 'toastr', 'ngDialog', '$rootScope',
    function($scope, $window, $http, EventsService, $stateParams, toastr, ngDialog, $rootScope) {

      var eventsType = $stateParams.type,
        keyword, pastEvents = [],
        latestEvents = [],
        epoch, isEventsPresentinSession;

      function DisplayEvents(eventsType) {
        console.log("Type =" + eventsType);
        if (eventsType === 'past') {
          $rootScope.filteredEvents = pastEvents;
        } else {
          $rootScope.filteredEvents = latestEvents;
        }
      }

      function _initilize() {
        $scope.eventsList = {};
        $rootScope.filteredEvents = {};
        $scope.dialogShown = true;
        $scope.hideSearchBar = true;
        keyword = $stateParams.search;

        if (eventsType !== "" && eventsType !== null && eventsType !== undefined) {
          LoadEvents(eventsType);
        }
        DisplayEvents(eventsType);

        if (keyword !== "" && keyword !== null && keyword !== undefined) {
          $scope.SearchEvent(keyword.toLowerCase());
        } else {
          if (eventsType === 'past') {
            $window.location.href = '/#/dashboard/events?type=past';
          } else {
            $window.location.href = '/#/dashboard/events?type=latest';
          }
        }
      }

      $scope.ConfirmDelete = function(event) {
        $rootScope.EventtobeDeleted = event;
        ngDialog.open({
          template: 'views/template.html',
          controller: 'DialogCtrl',
          className: 'ngdialog-theme-default ngdialog-theme-custom'
        });
      };

      $scope.ShowEventDetails = function(event) {
        var stringevent = JSON.stringify(event);
        sessionStorage.setItem('currentEvent', stringevent);
        $window.location.href = '/#/dashboard/e/' + eventsType + '/' + event.key;
      }

      $scope.SearchEvent = function(keyword) {
        $scope.hideSearchBar = false;
        var pastEvents = [];
        var latestEvents = [];
        CheckLastSession();
        if (isEventsPresentinSession !== "undefined" && isEventsPresentinSession != null && isEventsPresentinSession != '') {
          LoadEventsFromSession();
        }
        angular.forEach($scope.eventsList, function(event) {
          if (event.name.toLowerCase().indexOf(keyword) != -1) {
            if (parseInt(event.start_time) < epoch) {
              pastEvents.push(event);
            } else {
              latestEvents.push(event);
            }
          }
        });
        $rootScope.filteredEvents = null;
        if (pastEvents.length > 0) {
          latestEvents.push(pastEvents);
        }
        //$scope.filteredEvents.push(latestEvents);
        debugger;
        $rootScope.filteredEvents = latestEvents;
        console.log("result of search");
        console.log($rootScope.filteredEvents);
      }

      function LoadEventsFromSession() {
        $scope.eventsList = JSON.parse(isEventsPresentinSession);
      }

      function CheckLastSession() {
        isEventsPresentinSession = sessionStorage.getItem('allEvents');
      }

      function LoadDateTimeFunction() {
        Date.prototype.today = function() {
          return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
        }
        Date.prototype.timeNow = function() {
          return ((this.getHours() < 10) ? "0" : "") + this.getHours() + ":" + ((this.getMinutes() < 10) ? "0" : "") + this.getMinutes() + ":" + ((this.getSeconds() < 10) ? "0" : "") + this.getSeconds();
        }
      }

      function ProcessEvents(Type) {
        var today = new Date();
        epoch = moment(today.today() + " " + today.timeNow(), "D/M/YYYY H:mm").unix();

        angular.forEach($scope.eventsList, function(event) {
          if (Type === 'past') {
            console.log("evluating past");
            $scope.Heading = "All Past Events: before " + today.today() + " " + today.timeNow();
            if (parseInt(event.start_time) < epoch) {
              var GMTTime = moment.unix(event.start_time);
              event.start_time = moment(GMTTime).subtract({
                'hours': '5',
                'minutes': '30'
              }).format('ll HH:mm');
              pastEvents.push(event);
            }
          } else {
            console.log("evluating latest");
            $scope.Heading = "All Latest Events: after " + today.today() + " " + today.timeNow();
            if (parseInt(event.start_time) >= epoch) {
              var GMTTime = moment.unix(event.start_time).format('ll HH:mm');
              event.start_time = moment(GMTTime).subtract({
                'hours': '5',
                'minutes': '30'
              }).format('ll HH:mm');
              latestEvents.push(event);
            }
          }
        });
      }

      function LoadEventfromEventService() {
        EventsService.GetEvents(function() {})
          .then(function(response) {
            $scope.eventsList = response.data.events;
            sessionStorage.setItem('allEvents', JSON.stringify(response.data.events));
            ProcessEvents(eventsType);
          });
      }

      function LoadEvents(Type) {
        CheckLastSession();
        LoadDateTimeFunction();

        if (isEventsPresentinSession !== 'undefined' && isEventsPresentinSession != null && isEventsPresentinSession != '') {
          LoadEventsFromSession();
          ProcessEvents(eventsType);
        } else {
          LoadEventfromEventService();
        }
      };

      _initilize();
    }
  ])
  .controller('DialogCtrl', ['EventsService', 'toastr', '$scope', 'ngDialog', '$rootScope', function(EventsService, toastr, $scope, ngDialog, $rootScope) {

    $scope.closeDialog = function() {
      ngDialog.close('ngdialog1');
    }

    $scope.DeleteEvent = function() {
      ngDialog.close('ngdialog1');
      EventsService.DeleteEvent($rootScope.EventtobeDeleted.key).then(function(response) {
        toastr.success('Event deleted successfully', 'Success!');
        sessionStorage.removeItem('allEvents');
        var afterDeleteEvents = [];
        angular.forEach($rootScope.filteredEvents, function(currentEvent) {
          if (currentEvent.key !== $rootScope.EventtobeDeleted.key && currentEvent.key !== undefined && currentEvent.key !== null && currentEvent.key !== '') {
            afterDeleteEvents.push(currentEvent);
          }
        });
        $rootScope.filteredEvents = afterDeleteEvents;
      }, function() {
        toastr.success('Event deleting failed', 'Error!');
      });
    }

  }]);<|endoftext|>


<commit_before>(function() {
  angular.module('ncsaas')
    .controller('KeyAddController', ['baseControllerAddClass', 'keysService', '$state', KeyAddController]);

  function KeyAddController(baseControllerAddClass, keysService, $state) {
    var controllerScope = this;
    var Controller = baseControllerAddClass.extend({
      init: function() {
        this.service = keysService;
        this.controllerScope = controllerScope;
        this._super();
        this.listState = 'profile.details';
      },
      successRedirect: function() {
        $state.go('profile.details', {tab: 'keys'});
      },
      save: function() {
        if (this.instance.name) {
          this._super();
        } else {
          if (this.instance.public_key) {
            var key = this.instance.public_key.split('==');
            if (key[1]) {
              this.instance.name = key[1];
              this._super();
            } else {
              this.errors = {name: ['This field may not be blank.']};
            }
          } else {
            this.errors = {public_key: ['This field may not be blank.']};
          }
        }
      }
    });

    controllerScope.__proto__ = new Controller();
  }
})();<commit_msg>Change getting key method (SAAS-612)<commit_after>(function() {
  angular.module('ncsaas')
    .controller('KeyAddController', ['baseControllerAddClass', 'keysService', '$state', KeyAddController]);

  function KeyAddController(baseControllerAddClass, keysService, $state) {
    var controllerScope = this;
    var Controller = baseControllerAddClass.extend({
      init: function() {
        this.service = keysService;
        this.controllerScope = controllerScope;
        this._super();
        this.listState = 'profile.details';
      },
      successRedirect: function() {
        $state.go('profile.details', {tab: 'keys'});
      },
      save: function() {
        if (this.instance.name) {
          this._super();
        } else {
          if (this.instance.public_key) {
            var key = this.instance.public_key.split(' ');
            if (key[2]) {
              this.instance.name = key[2].trim();
              this._super();
            } else {
              this.errors = {name: ['This field may not be blank.']};
            }
          } else {
            this.errors = {public_key: ['This field may not be blank.']};
          }
        }
      }
    });

    controllerScope.__proto__ = new Controller();
  }
})();<|endoftext|>


<commit_before>(function () {
'use strict';

  angular
    .module('moi.services')
    .factory('ScreenshotService', ScreenshotService);

  function ScreenshotService(ENV, $q) {

    var service = {
      getImageBase64: getImageBase64,
      validBase64: validBase64,
      getFileImage: getFileImage
    };

    function getImageBase64(elm) {
      var deferred = $q.defer();
      var html2canvasOpts = {
        backgroundColor: null,
        allowTaint: false,
        proxy: ENV.imagesProxy,
        useCORS: true
      };
      html2canvas(elm, html2canvasOpts).then(function(canvas) { // jshint ignore:line
        deferred.resolve(canvas.toDataURL());
      });
      return deferred.promise;
    }

    function getFileImage(elm) {
      var deferred = $q.defer();
      var html2canvasOpts = {
        backgroundColor: null,
        allowTaint: false,
        proxy: ENV.imagesProxy,
        useCORS: true
      };
      html2canvas(elm, html2canvasOpts).then(function(canvas) { // jshint ignore:line
        canvas.toBlob(function (blob) {
          var timestamp = new Date().valueOf();
          var fileName = 'screenshot_' + timestamp + '.png';
          var file = new File([blob], fileName, { type: 'image/png' });// jshint ignore:line
          deferred.resolve(file);
        }, 'image/png');
      });
      return deferred.promise;
    }

    function validBase64(value){
      var reg = RegExp(/data:image\/([a-zA-Z]*);base64,([^\"]*)/g); // jshint ignore:line
      return reg.test(value);
    }

    return service;

  }
})();
<commit_msg>Update app/scripts/services/screenshot-service.js<commit_after>(function () {
'use strict';

  angular
    .module('moi.services')
    .factory('ScreenshotService', ScreenshotService);

  function ScreenshotService(ENV, $q) {

    var service = {
      getBase64Image: getBase64Image,
      validBase64: validBase64,
      getFileImage: getFileImage
    };

    function getImageBase64(elm) {
      var deferred = $q.defer();
      var html2canvasOpts = {
        backgroundColor: null,
        allowTaint: false,
        proxy: ENV.imagesProxy,
        useCORS: true
      };
      html2canvas(elm, html2canvasOpts).then(function(canvas) { // jshint ignore:line
        deferred.resolve(canvas.toDataURL());
      });
      return deferred.promise;
    }

    function getFileImage(elm) {
      var deferred = $q.defer();
      var html2canvasOpts = {
        backgroundColor: null,
        allowTaint: false,
        proxy: ENV.imagesProxy,
        useCORS: true
      };
      html2canvas(elm, html2canvasOpts).then(function(canvas) { // jshint ignore:line
        canvas.toBlob(function (blob) {
          var timestamp = new Date().valueOf();
          var fileName = 'screenshot_' + timestamp + '.png';
          var file = new File([blob], fileName, { type: 'image/png' });// jshint ignore:line
          deferred.resolve(file);
        }, 'image/png');
      });
      return deferred.promise;
    }

    function validBase64(value){
      var reg = RegExp(/data:image\/([a-zA-Z]*);base64,([^\"]*)/g); // jshint ignore:line
      return reg.test(value);
    }

    return service;

  }
})();
<|endoftext|>


<commit_before>/**
 * @param {Object} $    - Global jQuery object
 * @param {Object} bolt - The Bolt module
 */
(function ($, bolt) {
    'use strict';

    /**
     * Filelist field widget.
     *
     * @license http://opensource.org/licenses/mit-license.php MIT License
     * @author rarila
     *
     * @class fieldFilelist
     * @memberOf jQuery.widget.bolt
     */
    $.widget('bolt.fieldFilelist', /** @lends jQuery.widget.bolt.fieldFilelist.prototype */ {
        /**
         * The constructor of the filelist field widget.
         *
         * @private
         */
        _create: function () {
            var self = this,
                fieldset = this.element,
                isImage = this.options.isImage || false,
                lastClickIndex = 0;

            // Mark this widget as type of "FileList", if not already set.
            this.options.isImage = isImage;

            // Make the list sortable.
            $('div.list', fieldset).sortable({
                // Set a helper element to be used for dragging display.
                helper: function (event, item) {
                    // We select the item dragged, as it isn't selected on a single item drag.
                    item.addClass('selected');

                    return $('<div/>');
                },
                // Triggered when sorting starts.
                start: function (event, ui) {
                    var elements = $('.selected', fieldset).not('.ui-sortable-placeholder'),
                        itemCount = elements.length,
                        placeholder = ui.placeholder,
                        outerHeight = placeholder.outerHeight(true),
                        innerHeight = placeholder.height(),
                        margin = parseInt(placeholder.css('margin-top')) + parseInt(placeholder.css('margin-bottom'));

                    elements.hide();
                    placeholder.height(innerHeight + (itemCount - 1) * outerHeight - margin);
                    ui.item.data('items', elements);
                },
                // Triggered when sorting stops, but when the placeholder/helper is still available.
                beforeStop: function (event, ui) {
                    ui.item.before(ui.item.data('items'));
                },
                // Triggered when sorting has stopped.
                stop: function () {
                    $('.selected', fieldset).show();
                    self._serialize();
                },
                // Set on which axis items items can be dragged.
                axis: 'y',
                // Time in milliseconds to define when the sorting should start.
                delay: 100,
                // Tolerance, in pixels, for when sorting should start.
                distance: 5
            });

            // Bind list events.
            var list = $('div.list', fieldset);

            this._on(list, {
                'click.list-item': function (event) {
                    var item = $(event.target);

                    if (item.hasClass('list-item')) {
                        if (event.shiftKey) {
                            var begin = Math.min(lastClickIndex, item.index()),
                                end = Math.max(lastClickIndex, item.index());

                            // Select all items in range.
                            list.children().each(function (idx, listitem) {
                                $(listitem).toggleClass('selected', idx >= begin && idx <= end);
                            });
                        } else if (event.ctrlKey || event.metaKey) {
                            item.toggleClass('selected');
                            // Remember last clicked item.
                            lastClickIndex = item.index();
                        } else {
                            var otherSelectedItems = list.children('.selected').not(item);

                            // Unselect all other selected items.
                            otherSelectedItems.removeClass('selected');
                            // Select if others were selected, otherwise toogle.
                            item.toggleClass('selected', otherSelectedItems.length > 0 ? true : null);
                            // Remember last clicked item.
                            lastClickIndex = item.index();
                        }
                    }
                },
                'click.remove-button': function (event) {
                    var msg = isImage ? 'field.imagelist.message.remove' : 'field.filelist.message.remove';

                    event.preventDefault();
                    event.stopPropagation();

                    if (confirm(bolt.data(msg))) {
                        event.target.closest('.list-item').remove();
                        self._serialize();
                    }
                },
                'change input': function () {
                    self._serialize();
                }
            });

            // Bind "Remove selected" button event.
            this._on($('.remove-selected-button', fieldset), {
                'click': function () {
                    var msg = isImage ? 'field.imagelist.message.removeMulti' : 'field.filelist.message.removeMulti';

                    if (confirm(bolt.data(msg))) {
                        $('.selected', list).closest('.list-item').remove();
                        self._serialize();
                    }
                }
            });

            // Bind events.
            bolt.uploads.bindUpload(fieldset, true);
            bolt.uploads.bindSelectFromStack(fieldset);
        },

        /**
         * Serialize list data on change.
         */
        _serialize: function () {
            var listField = $('div.list', this.element),
                dataField = $('textarea', this.element),
                template = this.options.isImage ? 'field.imagelist.template.empty' : 'field.filelist.template.empty',
                data = [];

            $('.list-item', listField).each(function () {
                data.push({
                    filename: $(this).find('input.filename').val(),
                    title: $(this).find('input.title').val()
                });
            });
            dataField.val(JSON.stringify(data));

            // Display empty list message.
            if (data.length === 0) {
                listField.html(bolt.data(template));
            }
        }
    });
})(jQuery, Bolt);
<commit_msg>Use ui element references<commit_after>/**
 * @param {Object} $    - Global jQuery object
 * @param {Object} bolt - The Bolt module
 */
(function ($, bolt) {
    'use strict';

    /**
     * Filelist field widget.
     *
     * @license http://opensource.org/licenses/mit-license.php MIT License
     * @author rarila
     *
     * @class fieldFilelist
     * @memberOf jQuery.widget.bolt
     */
    $.widget('bolt.fieldFilelist', /** @lends jQuery.widget.bolt.fieldFilelist.prototype */ {
        /**
         * The constructor of the filelist field widget.
         *
         * @private
         */
        _create: function () {
            var self = this,
                fieldset = this.element,
                isImage = this.options.isImage || false,
                lastClickIndex = 0;

            /**
             * Refs to UI elements of this widget.
             *
             * @type {Object}
             * @name _ui
             * @memberOf jQuery.widget.bolt.fieldFilelist.prototype
             * @private
             *
             * @property {Object} data           - List data holder
             * @property {Object} list           - List container
             * @property {Object} removeSelected - Remove selected button
             */
            this._ui = {
                data:           fieldset.find('textarea'),
                list:           fieldset.find('.list'),
                removeSelected: fieldset.find('.remove-selected-button')
            };

            // Mark this widget as type of "FileList", if not already set.
            self.options.isImage = isImage;

            // Make the list sortable.
            self._ui.list.sortable({
                // Set a helper element to be used for dragging display.
                helper: function (event, item) {
                    // We select the item dragged, as it isn't selected on a single item drag.
                    item.addClass('selected');

                    return $('<div/>');
                },
                // Triggered when sorting starts.
                start: function (event, ui) {
                    var elements = $('.selected', fieldset).not('.ui-sortable-placeholder'),
                        itemCount = elements.length,
                        placeholder = ui.placeholder,
                        outerHeight = placeholder.outerHeight(true),
                        innerHeight = placeholder.height(),
                        margin = parseInt(placeholder.css('margin-top')) + parseInt(placeholder.css('margin-bottom'));

                    elements.hide();
                    placeholder.height(innerHeight + (itemCount - 1) * outerHeight - margin);
                    ui.item.data('items', elements);
                },
                // Triggered when sorting stops, but when the placeholder/helper is still available.
                beforeStop: function (event, ui) {
                    ui.item.before(ui.item.data('items'));
                },
                // Triggered when sorting has stopped.
                stop: function () {
                    $('.selected', fieldset).show();
                    self._serialize();
                },
                // Set on which axis items items can be dragged.
                axis: 'y',
                // Time in milliseconds to define when the sorting should start.
                delay: 100,
                // Tolerance, in pixels, for when sorting should start.
                distance: 5
            });

            // Bind list events.
            this._on(self._ui.list, {
                'click.list-item': function (event) {
                    var item = $(event.target);

                    if (item.hasClass('list-item')) {
                        if (event.shiftKey) {
                            var begin = Math.min(lastClickIndex, item.index()),
                                end = Math.max(lastClickIndex, item.index());

                            // Select all items in range.
                            self._ui.list.children().each(function (idx, listitem) {
                                $(listitem).toggleClass('selected', idx >= begin && idx <= end);
                            });
                        } else if (event.ctrlKey || event.metaKey) {
                            item.toggleClass('selected');
                            // Remember last clicked item.
                            lastClickIndex = item.index();
                        } else {
                            var otherSelectedItems = self._ui.list.children('.selected').not(item);

                            // Unselect all other selected items.
                            otherSelectedItems.removeClass('selected');
                            // Select if others were selected, otherwise toogle.
                            item.toggleClass('selected', otherSelectedItems.length > 0 ? true : null);
                            // Remember last clicked item.
                            lastClickIndex = item.index();
                        }
                    }
                },
                'click.remove-button': function (event) {
                    var msg = isImage ? 'field.imagelist.message.remove' : 'field.filelist.message.remove';

                    event.preventDefault();
                    event.stopPropagation();

                    if (confirm(bolt.data(msg))) {
                        event.target.closest('.list-item').remove();
                        self._serialize();
                    }
                },
                'change input': function () {
                    self._serialize();
                }
            });

            // Bind "Remove selected" button event.
            this._on(this._ui.removeSelected, {
                'click': function () {
                    var msg = isImage ? 'field.imagelist.message.removeMulti' : 'field.filelist.message.removeMulti';

                    if (confirm(bolt.data(msg))) {
                        $('.selected', self._ui.list).closest('.list-item').remove();
                        self._serialize();
                    }
                }
            });

            // Bind events.
            bolt.uploads.bindUpload(fieldset, true);
            bolt.uploads.bindSelectFromStack(fieldset);
        },

        /**
         * Serialize list data on change.
         */
        _serialize: function () {
            var template = this.options.isImage ? 'field.imagelist.template.empty' : 'field.filelist.template.empty',
                data = [];

            $('.list-item', this._ui.list).each(function () {
                data.push({
                    filename: $(this).find('input.filename').val(),
                    title: $(this).find('input.title').val()
                });
            });
            this._ui.data.val(JSON.stringify(data));

            // Display empty list message.
            if (data.length === 0) {
                this._ui.list.html(bolt.data(template));
            }
        }
    });
})(jQuery, Bolt);
<|endoftext|>


<commit_before>import koa_router from 'koa-router';
import koa_body from 'koa-body';
import models from 'db/models';
import config from 'config';
import {esc, escAttrs} from 'db/models';
import {getRemoteIp, rateLimitReq, checkCSRF} from '../utils';
import destinationBtcAddress from 'shared/icoAddress'
import coRequest from 'co-request'
import {getLogger} from '../../app/utils/Logger'
import Apis from 'shared/api_client/ApiInstances';

const cypherToken = config.blockcypher_token
const print = getLogger('API - ico').print

export default function useIcoApi(app) {
  const router = koa_router();
  app.use(router.routes());
  const koaBody = koa_body();

  router.get('/api/v1/get_golos_current_supply', function * () {
    try {
      const data = yield Apis.instance().db_api.exec( 'get_dynamic_global_properties', []);
      //this.body = JSON.stringify({status: 'ok', data: data});
      this.body = data.current_supply.split(' ')[0];
    } catch (error) {
        console.error('Error in /api/v1/get_current_supply', error);
        this.body = JSON.stringify({
            error: error.message
        });
        this.status = 500;
    }
  })

  router.get('/api/v1/get_gbg_current_supply', function * () {
    try {
      const data = yield Apis.instance().db_api.exec( 'get_dynamic_global_properties', []);
      //this.body = JSON.stringify({status: 'ok', data: data});
      this.body = data.current_sbd_supply.split(' ')[0];
    } catch (error) {
        console.error('Error in /api/v1/get_current_supply', error);
        this.body = JSON.stringify({
            error: error.message
        });
        this.status = 500;
    }
  })

  router.get('/api/v1/get_raised_amounts', function * () {
    let responce = this;
    try {
      const data = yield models.List.findAll({kk: {$like:"icoBalance_Nov"}});
      this.body = JSON.stringify({status: 'ok', data: data});
    } catch (error) {
        console.error('Error in /get_raised_amounts api call', this.session.uid, error.toString());
        this.body = JSON.stringify({
            error: error.message
        });
        this.status = 500;
    }

  });

  router.post('/api/v1/generate_ico_address', koaBody, function * () {
    console.log(destinationBtcAddress);
    if (rateLimitReq(this, this.req))
      return;

    const params = this.request.body;
    const {csrf} = typeof(params) === 'string'
    ? JSON.parse(params)
    : params;
    if (!checkCSRF(this, csrf))
      return;
    const cypher = yield coRequest(`https://api.blockcypher.com/v1/btc/main/payments?token=${cypherToken}`, {
      method: 'post',
      headers: {
        Accept: 'application/json',
        'Content-type': 'application/json'
      },
      body: JSON.stringify({"destination": destinationBtcAddress})
    });
    try {
      let cypherParsed = JSON.parse(cypher.body);
      print('blockcypher generated payment forwarding address', cypherParsed);
      const icoAddress = cypherParsed.input_address;
      this.body = JSON.stringify({status: 'ok', icoAddress: icoAddress});
    } catch (error) {
      console.error(error);
      this.body = JSON.stringify({status: "error", error: error.message});
      this.status = 500;
    }
  });
}
<commit_msg>ico.js error catch for get_gbg_current_supply actually fixed here<commit_after>import koa_router from 'koa-router';
import koa_body from 'koa-body';
import models from 'db/models';
import config from 'config';
import {esc, escAttrs} from 'db/models';
import {getRemoteIp, rateLimitReq, checkCSRF} from '../utils';
import destinationBtcAddress from 'shared/icoAddress'
import coRequest from 'co-request'
import {getLogger} from '../../app/utils/Logger'
import Apis from 'shared/api_client/ApiInstances';

const cypherToken = config.blockcypher_token
const print = getLogger('API - ico').print

export default function useIcoApi(app) {
  const router = koa_router();
  app.use(router.routes());
  const koaBody = koa_body();

  router.get('/api/v1/get_golos_current_supply', function * () {
    try {
      const data = yield Apis.instance().db_api.exec( 'get_dynamic_global_properties', []);
      //this.body = JSON.stringify({status: 'ok', data: data});
      this.body = data.current_supply.split(' ')[0];
    } catch (error) {
        console.error('Error in /api/v1/get_current_supply', error);
        this.body = JSON.stringify({
            error: error.message
        });
        this.status = 500;
    }
  })

  router.get('/api/v1/get_gbg_current_supply', function * () {
    try {
      const data = yield Apis.instance().db_api.exec( 'get_dynamic_global_properties', []);
      //this.body = JSON.stringify({status: 'ok', data: data});
      this.body = data.current_sbd_supply.split(' ')[0];
    } catch (error) {
        console.error('Error in /api/v1/get_gbg_current_supply', error);
        this.body = JSON.stringify({
            error: error.message
        });
        this.status = 500;
    }
  })

  router.get('/api/v1/get_raised_amounts', function * () {
    let responce = this;
    try {
      const data = yield models.List.findAll({kk: {$like:"icoBalance_Nov"}});
      this.body = JSON.stringify({status: 'ok', data: data});
    } catch (error) {
        console.error('Error in /get_raised_amounts api call', this.session.uid, error.toString());
        this.body = JSON.stringify({
            error: error.message
        });
        this.status = 500;
    }

  });

  router.post('/api/v1/generate_ico_address', koaBody, function * () {
    console.log(destinationBtcAddress);
    if (rateLimitReq(this, this.req))
      return;

    const params = this.request.body;
    const {csrf} = typeof(params) === 'string'
    ? JSON.parse(params)
    : params;
    if (!checkCSRF(this, csrf))
      return;
    const cypher = yield coRequest(`https://api.blockcypher.com/v1/btc/main/payments?token=${cypherToken}`, {
      method: 'post',
      headers: {
        Accept: 'application/json',
        'Content-type': 'application/json'
      },
      body: JSON.stringify({"destination": destinationBtcAddress})
    });
    try {
      let cypherParsed = JSON.parse(cypher.body);
      print('blockcypher generated payment forwarding address', cypherParsed);
      const icoAddress = cypherParsed.input_address;
      this.body = JSON.stringify({status: 'ok', icoAddress: icoAddress});
    } catch (error) {
      console.error(error);
      this.body = JSON.stringify({status: "error", error: error.message});
      this.status = 500;
    }
  });
}
<|endoftext|>


<commit_before>/*
Copyright [2016] [Relevance Lab]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var express = require("express");
var app = express();
var path = require("path");
var http = require("http");
var https = require("https");
var fs = require('fs');
var childProcess = require('child_process');
var socketIo = require('_pr/socket.io');
var logger = require('_pr/logger')(module);
var expressLogger = require('_pr/logger').ExpressLogger();
var passport = require('passport');
var passportLdapStrategy = require('./lib/ldapPassportStrategy.js');
var passportADStrategy = require('./lib/adPassportStrategy.js');
var Tail = require('tail').Tail;

// express middleware
var expressCompression = require('compression');
var expressFavicon = require('serve-favicon');
var expressCookieParser = require('cookie-parser');
var expressSession = require('express-session');
var expressBodyParser = require('body-parser');
var multipart = require('connect-multiparty');
var expressMultipartMiddleware = multipart();
var appConfig = require('_pr/config');
var mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(expressSession);
var mongoDbConnect = require('_pr/lib/mongodb');
var mongoose = require('mongoose');

logger.debug('Starting Catalyst');
logger.debug('Logger Initialized');
var LDAPUser = require('_pr/model/ldap-user/ldap-user.js');
LDAPUser.getLdapUser(function(err, ldapData) {
	if (err) {
		logger.error("Failed to get ldap-user: ", err);
		return;
	}
	if (ldapData.length) {
		// setting up up passport authentication strategy
		var ldapUser = ldapData[0];
		passport.use(new passportLdapStrategy({
			host: ldapUser.host,
			port: ldapUser.port,
			baseDn: ldapUser.baseDn,
			ou: ldapUser.ou,
			usernameField: 'username',
			passwordField: 'pass'
		}));
	} else {
		logger.debug("No Ldap User found.");
	}
});

passport.serializeUser(function(user, done) {
	done(null, user);
});

passport.deserializeUser(function(user, done) {
	done(null, user);
});

var dboptions = {
	host: appConfig.db.host,
	port: appConfig.db.port,
	dbName: appConfig.db.dbName
};
mongoDbConnect(dboptions, function(err) {
	if (err) {
		logger.error("Unable to connect to mongo db >>" + err);
		throw new Error(err);
	} else {
		logger.debug('connected to mongodb - host = %s, port = %s, database = %s', dboptions.host, dboptions.port, dboptions.dbName);
	}
});

var mongoStore = new MongoStore({
    mongooseConnection: mongoose.connection
}, function() {

});

app.set('port', process.env.PORT || appConfig.app_run_port);
app.set('sport', appConfig.app_run_secure_port);
app.use(expressCompression());
app.use(expressFavicon(__dirname + '/../../client/htmls/private/img/favicons/favicon.ico'));
app.use(expressCookieParser());
//Disabled the Tag
app.disable('etag');
logger.debug("Initializing Session store in mongo");

var sessionMiddleware = expressSession({
	secret: 'sessionSekret',
	store: mongoStore,
	resave: false,
	saveUninitialized: true
});
app.use(sessionMiddleware);

// parse application/x-www-form-urlencoded
app.use(expressBodyParser.urlencoded({
	limit: '50mb',
	extended: true
}))

// parse application/json
app.use(expressBodyParser.json({
	limit: '50mb'
}))
app.use(expressMultipartMiddleware);

//setting up passport
app.use(passport.initialize());
app.use(passport.session());

//app.use(app.router);

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

/*var options = {
    key: fs.readFileSync('rlcatalyst.key'),
    cert: fs.readFileSync('rlcatalyst.cert'),
    requestCert: true,
    rejectUnauthorized: false
}*/

var server = http.createServer(app);

//getting socket connection
var io = socketIo.getInstance(server, {
	log: false,
	authFunc: function(socket, next) {
  		sessionMiddleware(socket.request, socket.request.res, next);
	}
});

logger.debug('Setting up application routes');
var routes = require('./routes/routes.js');
routes.setRoutes(app);

app.use(function(req, res, next) {
	if (req.accepts('json')) {
		var errorResponse = {
			'status': 404,
			'message': 'Not found'
		};
		res.send(errorResponse);
		return;
	}
});

var socketIORoutes = require('./routes/socket.io/routes.js');
socketIORoutes.setRoutes(io);
io.set('log level', 1);
io.sockets.on('connection', function(socket) {
	var dt = new Date();
	var month = dt.getMonth() + 1;
	if (month < 10)
		month = '0' + month;
	logger.debug('file :' + './logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate());
	var tail;
	if (fs.existsSync('./logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate() + '.2'))
		tail = new Tail('./logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate() + '.2'); //catalyst.log.2015-06-19
	else if (fs.existsSync('./logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate() + '.1'))
		tail = new Tail('./logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate() + '.1'); //catalyst.log.2015-06-19
	else
		tail = new Tail('./logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate()); //catalyst.log.2015-06-19
	tail.on('line', function(line) {
		socket.emit('log', line);
	});
});

var cronTabManager = require('_pr/cronjobs');
cronTabManager.start();

server.listen(app.get('port'), function() {
	logger.debug('Express server listening on port ' + app.get('port'));
});
<commit_msg>Remove disable tag<commit_after>/*
Copyright [2016] [Relevance Lab]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var express = require("express");
var app = express();
var path = require("path");
var http = require("http");
var https = require("https");
var fs = require('fs');
var childProcess = require('child_process');
var socketIo = require('_pr/socket.io');
var logger = require('_pr/logger')(module);
var expressLogger = require('_pr/logger').ExpressLogger();
var passport = require('passport');
var passportLdapStrategy = require('./lib/ldapPassportStrategy.js');
var passportADStrategy = require('./lib/adPassportStrategy.js');
var Tail = require('tail').Tail;

// express middleware
var expressCompression = require('compression');
var expressFavicon = require('serve-favicon');
var expressCookieParser = require('cookie-parser');
var expressSession = require('express-session');
var expressBodyParser = require('body-parser');
var multipart = require('connect-multiparty');
var expressMultipartMiddleware = multipart();
var appConfig = require('_pr/config');
var mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(expressSession);
var mongoDbConnect = require('_pr/lib/mongodb');
var mongoose = require('mongoose');

logger.debug('Starting Catalyst');
logger.debug('Logger Initialized');
var LDAPUser = require('_pr/model/ldap-user/ldap-user.js');
LDAPUser.getLdapUser(function(err, ldapData) {
	if (err) {
		logger.error("Failed to get ldap-user: ", err);
		return;
	}
	if (ldapData.length) {
		// setting up up passport authentication strategy
		var ldapUser = ldapData[0];
		passport.use(new passportLdapStrategy({
			host: ldapUser.host,
			port: ldapUser.port,
			baseDn: ldapUser.baseDn,
			ou: ldapUser.ou,
			usernameField: 'username',
			passwordField: 'pass'
		}));
	} else {
		logger.debug("No Ldap User found.");
	}
});

passport.serializeUser(function(user, done) {
	done(null, user);
});

passport.deserializeUser(function(user, done) {
	done(null, user);
});

var dboptions = {
	host: appConfig.db.host,
	port: appConfig.db.port,
	dbName: appConfig.db.dbName
};
mongoDbConnect(dboptions, function(err) {
	if (err) {
		logger.error("Unable to connect to mongo db >>" + err);
		throw new Error(err);
	} else {
		logger.debug('connected to mongodb - host = %s, port = %s, database = %s', dboptions.host, dboptions.port, dboptions.dbName);
	}
});

var mongoStore = new MongoStore({
    mongooseConnection: mongoose.connection
}, function() {

});

app.set('port', process.env.PORT || appConfig.app_run_port);
app.set('sport', appConfig.app_run_secure_port);
app.use(expressCompression());
app.use(expressFavicon(__dirname + '/../../client/htmls/private/img/favicons/favicon.ico'));
app.use(expressCookieParser());

logger.debug("Initializing Session store in mongo");

var sessionMiddleware = expressSession({
	secret: 'sessionSekret',
	store: mongoStore,
	resave: false,
	saveUninitialized: true
});
app.use(sessionMiddleware);

// parse application/x-www-form-urlencoded
app.use(expressBodyParser.urlencoded({
	limit: '50mb',
	extended: true
}))

// parse application/json
app.use(expressBodyParser.json({
	limit: '50mb'
}))
app.use(expressMultipartMiddleware);

//setting up passport
app.use(passport.initialize());
app.use(passport.session());

//app.use(app.router);

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

/*var options = {
    key: fs.readFileSync('rlcatalyst.key'),
    cert: fs.readFileSync('rlcatalyst.cert'),
    requestCert: true,
    rejectUnauthorized: false
}*/

var server = http.createServer(app);

//getting socket connection
var io = socketIo.getInstance(server, {
	log: false,
	authFunc: function(socket, next) {
  		sessionMiddleware(socket.request, socket.request.res, next);
	}
});

logger.debug('Setting up application routes');
var routes = require('./routes/routes.js');
routes.setRoutes(app);

app.use(function(req, res, next) {
	if (req.accepts('json')) {
		var errorResponse = {
			'status': 404,
			'message': 'Not found'
		};
		res.send(errorResponse);
		return;
	}
});

var socketIORoutes = require('./routes/socket.io/routes.js');
socketIORoutes.setRoutes(io);
io.set('log level', 1);
io.sockets.on('connection', function(socket) {
	var dt = new Date();
	var month = dt.getMonth() + 1;
	if (month < 10)
		month = '0' + month;
	logger.debug('file :' + './logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate());
	var tail;
	if (fs.existsSync('./logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate() + '.2'))
		tail = new Tail('./logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate() + '.2'); //catalyst.log.2015-06-19
	else if (fs.existsSync('./logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate() + '.1'))
		tail = new Tail('./logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate() + '.1'); //catalyst.log.2015-06-19
	else
		tail = new Tail('./logs/catalyst.log.' + dt.getFullYear() + '-' + month + '-' + dt.getDate()); //catalyst.log.2015-06-19
	tail.on('line', function(line) {
		socket.emit('log', line);
	});
});

var cronTabManager = require('_pr/cronjobs');
cronTabManager.start();

server.listen(app.get('port'), function() {
	logger.debug('Express server listening on port ' + app.get('port'));
});
<|endoftext|>


<commit_before>angular.module('RadioBrowserApp').factory('audioplayer', ['$http', '$uibModal', function audioplayer($http, $uibModal) {
    var audioVolume = 1;
    var audio = null;
    var playerItem = null;
    var statusObject = {};
    var hlsObject = null;
    var video = null;

    function setVolume(volume) {
        if (audio) {
            audio.volume = volume;
            audioVolume = volume;
            updateStatus();
        }
        if (video) {
            video.volume = volume;
            audioVolume = volume;
            updateStatus();
        }
    }

    function stop() {
        console.log("stop();")
        if (audio) {
            playerItem = null;
            audio.pause();
            updateStatus();
        }
        if (hlsObject) {
            playerItem = null;
            hlsObject.destroy();
            hlsObject = null;
            updateStatus();
        }
    }

    function play(url, name, hls, video) {
        if (!video){
            playerItem = {
                'name': name,
                'hls': hls,
                'video': video
            };
        }
        console.log(JSON.stringify(playerItem));
        if (hls) {
            if (video){
                var clappr;
                console.log("open");
                var modalInstance = $uibModal.open({
                    animation: true,
                    templateUrl: 'templates/video.html',
                    controller: 'ModalVideoInstanceCtrl'
                });

                modalInstance.result.then(function () {
                    console.log("closed");
                    stop();
                    clappr.stop();
                    clappr.destroy();
                }, function () {
                    console.log("dismissed");
                    stop();
                    clappr.stop();
                    clappr.destroy();
                });
                modalInstance.rendered.then(function() {
                    clappr = new Clappr.Player({parentId: "#player_clappr", autoPlay: true, source: url});
                    clappr.resize({height: 500, width: 568});
                });
            }else if (Hls.isSupported()) {
                if (!hlsObject) {
                    video = document.getElementById('video');
                    hlsObject = new Hls();
                    // bind them together
                    hlsObject.attachMedia(video);
                    // MEDIA_ATTACHED event is fired by hls object once MediaSource is ready
                    hlsObject.on(Hls.Events.MEDIA_ATTACHED, function () {
                        console.log("video and hls.js are now bound together !");
                        hlsObject.loadSource(url);
                        hlsObject.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
                            console.log("manifest loaded, found " + data.levels.length + " quality level");
                            video.play();
                        });
                    });
                }else{
                    hlsObject.loadSource(url);
                }
            }
        } else {
            if (audio !== null) {
                audio.src = url;
                audio.play();
            } else {
                audio = new Audio(url);
                audio.volume = audioVolume;
                audio.onplay = function () {
                    console.log("play ok");
                };
                audio.onerror = function (err) {
                    console.log("error on play");
                    console.error(err);

                    if (!audio.src.endsWith(";")){
                        setTimeout(function(){
                            audio.pause();
                            audio.src = url + "/;";
                            audio.play();
                        },1);
                    }else{
                        setTimeout(function(){
                            stop();
                            alert("browser is not able to play station. please try with external player.");
                        },1);
                    }
                };
                audio.play();
            }
        }
        updateStatus();
    }

    function updateStatus() {
        statusObject.volume = audioVolume;
        statusObject.playerItem = playerItem;
    }

    function getStatusObject() {
        return statusObject;
    }

    function getIsActive() {
        return playerItem !== null;
    }

    return {
        'play': play,
        'setVolume': setVolume,
        'stop': stop,
        'getIsActive': getIsActive,
        'getStatusObject': getStatusObject
    };
}]);
<commit_msg>remove old hls stream<commit_after>angular.module('RadioBrowserApp').factory('audioplayer', ['$http', '$uibModal', function audioplayer($http, $uibModal) {
    var audioVolume = 1;
    var audio = null;
    var playerItem = null;
    var statusObject = {};
    var hlsObject = null;
    var video = null;

    function setVolume(volume) {
        if (audio) {
            audio.volume = volume;
            audioVolume = volume;
            updateStatus();
        }
        if (video) {
            video.volume = volume;
            audioVolume = volume;
            updateStatus();
        }
    }

    function stop() {
        console.log("stop();")
        if (audio) {
            playerItem = null;
            audio.pause();
            updateStatus();
        }
        if (hlsObject) {
            playerItem = null;
            hlsObject.destroy();
            hlsObject = null;
            updateStatus();
        }
    }

    function play(url, name, hls, video) {
        if (!video){
            playerItem = {
                'name': name,
                'hls': hls,
                'video': video
            };
        }
        console.log(JSON.stringify(playerItem));
        if (hls) {
            if (video){
                var clappr;
                console.log("open");
                var modalInstance = $uibModal.open({
                    animation: true,
                    templateUrl: 'templates/video.html',
                    controller: 'ModalVideoInstanceCtrl'
                });

                modalInstance.result.then(function () {
                    console.log("closed");
                    stop();
                    clappr.stop();
                    clappr.destroy();
                }, function () {
                    console.log("dismissed");
                    stop();
                    clappr.stop();
                    clappr.destroy();
                });
                modalInstance.rendered.then(function() {
                    clappr = new Clappr.Player({parentId: "#player_clappr", autoPlay: true, source: url});
                    clappr.resize({height: 500, width: 568});
                });
            }else if (Hls.isSupported()) {
                if (hlsObject){
                    hlsObject.destroy();
                    hlsObject = null;
                }
                if (!hlsObject) {
                    video = document.getElementById('video');
                    hlsObject = new Hls();
                    // bind them together
                    hlsObject.attachMedia(video);
                    // MEDIA_ATTACHED event is fired by hls object once MediaSource is ready
                    hlsObject.on(Hls.Events.MEDIA_ATTACHED, function () {
                        console.log("video and hls.js are now bound together !");
                        hlsObject.loadSource(url);
                        hlsObject.on(Hls.Events.MANIFEST_PARSED, function (event, data) {
                            console.log("manifest loaded, found " + data.levels.length + " quality level");
                            video.play();
                        });
                    });
                }
            }
        } else {
            if (audio !== null) {
                audio.src = url;
                audio.play();
            } else {
                audio = new Audio(url);
                audio.volume = audioVolume;
                audio.onplay = function () {
                    console.log("play ok");
                };
                audio.onerror = function (err) {
                    console.log("error on play");
                    console.error(err);

                    if (!audio.src.endsWith(";")){
                        setTimeout(function(){
                            audio.pause();
                            audio.src = url + "/;";
                            audio.play();
                        },1);
                    }else{
                        setTimeout(function(){
                            stop();
                            alert("browser is not able to play station. please try with external player.");
                        },1);
                    }
                };
                audio.play();
            }
        }
        updateStatus();
    }

    function updateStatus() {
        statusObject.volume = audioVolume;
        statusObject.playerItem = playerItem;
    }

    function getStatusObject() {
        return statusObject;
    }

    function getIsActive() {
        return playerItem !== null;
    }

    return {
        'play': play,
        'setVolume': setVolume,
        'stop': stop,
        'getIsActive': getIsActive,
        'getStatusObject': getStatusObject
    };
}]);
<|endoftext|>


<commit_before>'use strict';

const socketio = require('feathers-socketio');
const jwtDecode = require('jwt-decode');
const compress = require('compression');

module.exports = function () {
	const app = this;

	app.use(compress()).configure(socketio(io => {
		io.on('connection', (socket) => {
			let cookies = socket.handshake.headers.cookie.split(';');
			let jwt = '';
			cookies.map(cookie => {
				if (cookie.includes('jwt')) {
					jwt = cookie.split('=')[1];
				}
			});
			let jwtDecoded = jwtDecode(jwt);

			let releasePromise = app.service('releases').find({query: {$sort: '-createdAt'}});
			let userPromise = app.service('users').get(jwtDecoded.userId);

			return Promise.all([userPromise, releasePromise])
				.then((result) => {
					let user = result[0];
					let release = result[1].data[0];
					let prefs = user.preferences || {};

					if (Date.parse(prefs.releaseDate) < Date.parse(release.createdAt)) {
						socket.emit('newReleaseAvailable', {bool: true, createdAt: release.createdAt});
					} else if (typeof prefs.releaseDate == 'undefined')
						socket.emit('newReleaseAvailable', {bool: true, createdAt: release.createdAt});

					return Promise.resolve(true);
				});
			});
	}));
};
<commit_msg>some edge cases<commit_after>'use strict';

const socketio = require('feathers-socketio');
const jwtDecode = require('jwt-decode');
const compress = require('compression');

module.exports = function () {
	const app = this;

	app.use(compress()).configure(socketio(io => {
		io.on('connection', (socket) => {
			let cookies = [];
			try {
				cookies = socket.handshake.headers.cookie.split(';');
			}catch(e) {
				return;
			}
			let jwt = '';
			cookies.map(cookie => {
				if (cookie.includes('jwt')) {
					jwt = cookie.split('=')[1];
				}
			});
			let jwtDecoded = {};
			if (jwt)
				jwtDecoded = jwtDecode(jwt);
			else
				return;

			let releasePromise = app.service('releases').find({query: {$sort: '-createdAt'}});
			let userPromise = app.service('users').get(jwtDecoded.userId);

			return Promise.all([userPromise, releasePromise])
				.then((result) => {
					let user = result[0];
					let release = result[1].data[0];
					let prefs = user.preferences || {};

					if (Date.parse(prefs.releaseDate) < Date.parse(release.createdAt)) {
						socket.emit('newReleaseAvailable', {bool: true, createdAt: release.createdAt});
					} else if (typeof prefs.releaseDate == 'undefined')
						socket.emit('newReleaseAvailable', {bool: true, createdAt: release.createdAt});

					return Promise.resolve();
				});
			});
	}));
};
<|endoftext|>


<commit_before>/*
Copyright 2019 New Vector Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Generalized management class for dealing with watchers on a per-handler (per-level)
 * basis without duplicating code. Handlers are expected to push updates through this
 * class, which are then proxied outwards to any applicable watchers.
 */
export class WatchManager {
    _watchers = {}; // { settingName: { roomId: callbackFns[] } }

    // Proxy for handlers to delegate changes to this manager
    watchSetting(settingName, roomId, cb) {
        if (!this._watchers[settingName]) this._watchers[settingName] = {};
        if (!this._watchers[settingName][roomId]) this._watchers[settingName][roomId] = [];
        this._watchers[settingName][roomId].push(cb);
    }

    // Proxy for handlers to delegate changes to this manager
    unwatchSetting(cb) {
        for (const settingName of Object.keys(this._watchers)) {
            for (const roomId of Object.keys(this._watchers[settingName])) {
                let idx;
                while ((idx = this._watchers[settingName][roomId].indexOf(cb)) !== -1) {
                    this._watchers[settingName][roomId].splice(idx, 1);
                }
            }
        }
    }

    notifyUpdate(settingName, inRoomId, atLevel, newValueAtLevel) {
        // Dev note: We could avoid raising changes for ultimately inconsequential changes, but
        // we also don't have a reliable way to get the old value of a setting. Instead, we'll just
        // let it fall through regardless and let the receiver dedupe if they want to.

        if (!this._watchers[settingName]) return;

        const roomWatchers = this._watchers[settingName];
        const callbacks = [];

        if (inRoomId !== null && roomWatchers[inRoomId]) callbacks.push(...roomWatchers[inRoomId]);
        if (roomWatchers[null]) callbacks.push(...roomWatchers[null]);

        for (const callback of callbacks) {
            callback(inRoomId, atLevel, newValueAtLevel);
        }
    }
}
<commit_msg>Trigger room-specific watchers whenever a higher level change happens<commit_after>/*
Copyright 2019 New Vector Ltd.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
 * Generalized management class for dealing with watchers on a per-handler (per-level)
 * basis without duplicating code. Handlers are expected to push updates through this
 * class, which are then proxied outwards to any applicable watchers.
 */
export class WatchManager {
    _watchers = {}; // { settingName: { roomId: callbackFns[] } }

    // Proxy for handlers to delegate changes to this manager
    watchSetting(settingName, roomId, cb) {
        if (!this._watchers[settingName]) this._watchers[settingName] = {};
        if (!this._watchers[settingName][roomId]) this._watchers[settingName][roomId] = [];
        this._watchers[settingName][roomId].push(cb);
    }

    // Proxy for handlers to delegate changes to this manager
    unwatchSetting(cb) {
        for (const settingName of Object.keys(this._watchers)) {
            for (const roomId of Object.keys(this._watchers[settingName])) {
                let idx;
                while ((idx = this._watchers[settingName][roomId].indexOf(cb)) !== -1) {
                    this._watchers[settingName][roomId].splice(idx, 1);
                }
            }
        }
    }

    notifyUpdate(settingName, inRoomId, atLevel, newValueAtLevel) {
        // Dev note: We could avoid raising changes for ultimately inconsequential changes, but
        // we also don't have a reliable way to get the old value of a setting. Instead, we'll just
        // let it fall through regardless and let the receiver dedupe if they want to.

        if (!this._watchers[settingName]) return;

        const roomWatchers = this._watchers[settingName];
        const callbacks = [];

        if (inRoomId !== null && roomWatchers[inRoomId]) {
            callbacks.push(...roomWatchers[inRoomId]);
        }

        if (!inRoomId) {
            // Fire updates to all the individual room watchers too, as they probably
            // care about the change higher up.
            callbacks.push(...Object.values(roomWatchers).reduce((r, a) => [...r, ...a], []));
        } else if (roomWatchers[null]) {
            callbacks.push(...roomWatchers[null]);
        }

        for (const callback of callbacks) {
            callback(inRoomId, atLevel, newValueAtLevel);
        }
    }
}
<|endoftext|>


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

// middleware to take care of CSP. CSP headers are only sent in development
// mode, and are not sent if the user is running the unit tests.

'use strict';

var helmet = require('helmet');
var config = require('./configuration');

var cspMiddleware = helmet.csp({'default-src': ['\'self\''],
                    'connect-src': ['\'self\'',
                          config.get('fxaccount_url'),
                          config.get('oauth_url')
                    ],
                    'report-uri': '/_/csp-violation'
                   });

module.exports = function (req, res, next) {
  if (! requiresCsp(req)) {
    return next();
  }

  cspMiddleware(req, res, next);
};

function requiresCsp(req) {
  // is the user running tests? No CSP.
  return req.path !== '/tests/index.html';
}
<commit_msg>fix(csp): allow data uris for images<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// middleware to take care of CSP. CSP headers are only sent in development
// mode, and are not sent if the user is running the unit tests.

'use strict';

var helmet = require('helmet');
var config = require('./configuration');

var cspMiddleware = helmet.csp({
                    'default-src': ['\'self\''],
                    'connect-src': [
                          '\'self\'',
                          config.get('fxaccount_url'),
                          config.get('oauth_url')
                    ],
                    'img-src': ['\'self\'', 'data:'],
                    'report-uri': '/_/csp-violation'
                   });

module.exports = function (req, res, next) {
  if (! requiresCsp(req)) {
    return next();
  }

  cspMiddleware(req, res, next);
};

function requiresCsp(req) {
  // is the user running tests? No CSP.
  return req.path !== '/tests/index.html';
}
<|endoftext|>


<commit_before>Meteor.methods({
  createBet: function(bet) {
    Bets.insert({
      bettors: [ bet.user.username, bet.defender.username ],
      status: "open",
      title: bet.title,
      wager: bet.wager,
      image_id: bet.image_id,
      createdAt: new Date()
    });
  },

  createBetNotification: function(user, defender, type, bet_id) {
    BetNotifications.insert({
      toNotify: defender,
      betBy: user,
      type: type,
      bet_id: bet_id
    });
  },

  deleteBet: function(bet_id){
    Bets.remove(bet_id)
  },

  completeBet: function(bet_id, winner){
    Bets.update(
      { _id: bet_id },
      { $set:
        { status: "completed",
          winner: winner,
          paid: false }
    });
  },

  updateStatus: function(bet_id, status){
    Bets.update({ _id : bet_id }, { $set: { status: status }})
  },

  editBet: function(bet) {
    Bets.update({ _id: bet._id }, {
      bettors: [ bet.user.username, bet.defender.username ],
      status: "open",
      title: bet.title,
      wager: bet.wager
    });
  },

  createMessage: function(message, sender, bet_id){
    Messages.insert({
      message: message,
      sentBy: sender,
      bet: bet_id
    });
  },

  addFriend: function(user_id, friendsName) {
    Friends.insert({
      user: user_id,
      friend: friendsName
    });
  },

  deleteNotification: function(notification_id){
    BetNotifications.remove({ _id: notification_id })
  },

  deleteAllNotifications: function(username) {
    BetNotifications.remove({
      toNotify: username
    });
  }

  createPoints: function(score, user){
    Points.insert({
      score: 0,
      wonBy: user,
    });
  }
});
<commit_msg>adds Meteor method for point incrementing<commit_after>Meteor.methods({
  createBet: function(bet) {
    Bets.insert({
      bettors: [ bet.user.username, bet.defender.username ],
      status: "open",
      title: bet.title,
      wager: bet.wager,
      image_id: bet.image_id,
      createdAt: new Date()
    });
  },

  createBetNotification: function(user, defender, type, bet_id) {
    BetNotifications.insert({
      toNotify: defender,
      betBy: user,
      type: type,
      bet_id: bet_id
    });
  },

  deleteBet: function(bet_id){
    Bets.remove(bet_id)
  },

  completeBet: function(bet_id, winner){
    Bets.update(
      { _id: bet_id },
      { $set:
        { status: "completed",
          winner: winner,
          paid: false }
    });
  },

  updateStatus: function(bet_id, status){
    Bets.update({ _id : bet_id }, { $set: { status: status }})
  },

  editBet: function(bet) {
    Bets.update({ _id: bet._id }, {
      bettors: [ bet.user.username, bet.defender.username ],
      status: "open",
      title: bet.title,
      wager: bet.wager
    });
  },

  createMessage: function(message, sender, bet_id){
    Messages.insert({
      message: message,
      sentBy: sender,
      bet: bet_id
    });
  },

  addFriend: function(user_id, friendsName) {
    Friends.insert({
      user: user_id,
      friend: friendsName
    });
  },

  deleteNotification: function(notification_id){
    BetNotifications.remove({ _id: notification_id })
  },

  deleteAllNotifications: function(username) {
    BetNotifications.remove({
      toNotify: username
    });
  },

  createPoints: function(score, user) {
    Points.insert({
      score: 0,
      wonBy: user
    });
  },

  incrementPoints: function(scoreValue, user) {
    Points.update(
    { $inc: {score: 5}},
      {wonBy: user}
    });
  },

});
<|endoftext|>


<commit_before>Meteor.publish(null, function() {
    return Meteor.roles.find({});
});

Meteor.publish("myself", function() {
    if (this.userId) {
        return Meteor.users.find({
            _id: this.userId
        }, {
            fields: {
                'isBanned': 1,
                'createdAt': 1
            }
        });
    } else {
        return this.ready();
    }
});

Meteor.publish("users", function() {
    if (Roles.userIsInRole(this.userId, ['moderator'])) {
        return Meteor.users.find({});
    } else {
        return Meteor.users.find({}, {
            fields: {
                "emails" : false,
                "services" : false,
                "defaultEmail" : false //Exclude defaultEmail from the sent data
            }
        });
    }
});

Meteor.publish("post", function(id) {
    if (id == 'rootNode') {
        id = Post.findOne({
            isRoot: true
        })._id;
    }
    return [
        Post.find({
            _id: id
        }), Link.find({
            $or: [
                {
                    sourceId: id
                }, {
                    targetId: id
                }
            ]
        })
    ];
});
<commit_msg>Added postRange publication.<commit_after>Meteor.publish(null, function() {
    return Meteor.roles.find({});
});

Meteor.publish("myself", function() {
    if (this.userId) {
        return Meteor.users.find({
            _id: this.userId
        }, {
            fields: {
                'isBanned': 1,
                'createdAt': 1
            }
        });
    } else {
        return this.ready();
    }
});

Meteor.publish("users", function() {
    if (Roles.userIsInRole(this.userId, ['moderator'])) {
        return Meteor.users.find({});
    } else {
        return Meteor.users.find({}, {
            fields: {
                "emails" : false,
                "services" : false,
                "defaultEmail" : false //Exclude defaultEmail from the sent data
            }
        });
    }
});

Meteor.publish("post", function(id) {
    if (id == 'rootNode') {
        id = Post.findOne({
            isRoot: true
        })._id;
    }
    return [
        Post.find({
            _id: id
        }), Link.find({
            $or: [
                {
                    sourceId: id
                }, {
                    targetId: id
                }
            ]
        })
    ];
});

Meteor.publish("postRange", function(startDate, endDate) {
    return Post.find({
        "createdAt" : { $gte : startDate, $lte : endDate }
    }, {limit: 1000});
});
<|endoftext|>


<commit_before>var session = require('express-session');
var passport = require('passport');
var sop = require('simple-object-path');

function redisProtect(req, res, next) {
    res.header('Cache-Control', 'no-cache');
    const token = sop(req.session, 'passport/user/accessToken');
    const user_id = sop(req.session, 'passport/user/user_id');
    const id = sop(req.session, 'passport/user/id');
    //console.log(req.session);
    if (!token && !user_id && !id) {
        const redirectUrl = 'https://auth.crosshj.com/';
        const redirectTo = 'https://cents.crosshj.com' + req.originalUrl;
        if(req.session){
            req.session.redirectTo = redirectTo;
        }
        return res.redirect(redirectUrl);
    }
    res.locals.token = token;
    res.locals.user_id = user_id;
    res.locals.id = id;
    next();
}

function redisSession(settings) {
    const RedisStore = require('connect-redis')(session);
    return session({
        secret: settings.cookieSecret,
        name: 'gAuthSess',
        store: new RedisStore({
            host: 'redis',
            port: 6379
        }),
        resave: false,
        saveUninitialized: true,
        cookie: {
            path: '/',
            domain: '.crosshj.com'
        }
    });
}

function fileStoreSession(settings) {
    var store = ((sess) => {
        const FileStore = require('session-file-store')(sess);
        const fileStoreOptions = {
            path: settings.folderLocation
        };
        const store = new FileStore(fileStoreOptions);
        return store;
    })(session);
    return session({
        secret: settings.cookieSecret,
        store,
        resave: false,
        saveUninitialized: false
    });
}

function mongoSession(settings) {
    var store = ((sess) => {
        var MongoDBStore = require('connect-mongodb-session')(sess);
        const connectErrorCallback = (error) => {
            if (error) {
                console.log({ mongoConnectError: error });
            }
        };
        var store = new MongoDBStore({
            uri: 'mongodb://ubuntu:27017',
            databaseName: 'cents',
            collection: 'sessions'
        }, connectErrorCallback);
        store.on('error', connectErrorCallback);
        return store;

    })(session);
    session({
        secret: settings.cookieSecret,
        store,
        resave: false,
        saveUninitialized: false
    });
}

class AppSession {
    constructor(app, store, settings) {
        this.store = store;

        const whichSession = {
            mongo: mongoSession,
            redis: redisSession,
            file: fileStoreSession
        }[store] || fileStoreSession;

        this.express = whichSession(settings);
        app.use(this.express);
        app.use(passport.initialize());
        app.use(passport.session());

        if(store === 'mongo' || store === 'file'){
            var authentication = require('./authentication');
            authentication.init(app);
        }

        if(store === 'redis'){
            passport.serializeUser(function (user, done) {
                done(null, user);
              });

            passport.deserializeUser(function (user, done) {
            done(null, user);
            });
        }

        const passportProtect = passport.authenticationMiddleware
            ? passport.authenticationMiddleware()
            : (req, res, next) => next('error with passport authenticationMiddleware');
        const whichProtect = {
            mongo: passportProtect,
            redis: redisProtect,
            file: passportProtect
        }[store] || passportProtect;

        this.protect = whichProtect;
    }
}

module.exports = AppSession;
<commit_msg>try, try again - getting auth middleware to work<commit_after>var session = require('express-session');
var passport = require('passport');
var sop = require('simple-object-path');

const authenticationMiddleware = function (req, res, next) {
    if (req.isAuthenticated()) {
        if (!req.cookies.username) {
            res.cookie('username', req.user.username, { maxAge: 900000, httpOnly: true });
        }
        return next();
    }
    if (/json/.test(req.headers.accept)) {
        res.send({ error: 'not logged in' });
        return;
    }

    // redirect to URL if not logged in before request
    if (req.session) {
        req.session.returnTo = req.originalUrl || req.url;
    }
    res.redirect('./login');
};

function redisProtect(req, res, next) {
    res.header('Cache-Control', 'no-cache');
    const token = sop(req.session, 'passport/user/accessToken');
    const user_id = sop(req.session, 'passport/user/user_id');
    const id = sop(req.session, 'passport/user/id');
    //console.log(req.session);
    if (!token && !user_id && !id) {
        const redirectUrl = 'https://auth.crosshj.com/';
        const redirectTo = 'https://cents.crosshj.com' + req.originalUrl;
        if (req.session) {
            req.session.redirectTo = redirectTo;
        }
        return res.redirect(redirectUrl);
    }
    res.locals.token = token;
    res.locals.user_id = user_id;
    res.locals.id = id;
    next();
}

function redisSession(settings) {
    const RedisStore = require('connect-redis')(session);
    return session({
        secret: settings.cookieSecret,
        name: 'gAuthSess',
        store: new RedisStore({
            host: 'redis',
            port: 6379
        }),
        resave: false,
        saveUninitialized: true,
        cookie: {
            path: '/',
            domain: '.crosshj.com'
        }
    });
}

function fileStoreSession(settings) {
    var store = ((sess) => {
        const FileStore = require('session-file-store')(sess);
        const fileStoreOptions = {
            path: settings.folderLocation
        };
        const store = new FileStore(fileStoreOptions);
        return store;
    })(session);
    return session({
        secret: settings.cookieSecret,
        store,
        resave: false,
        saveUninitialized: false
    });
}

function mongoSession(settings) {
    var store = ((sess) => {
        var MongoDBStore = require('connect-mongodb-session')(sess);
        const connectErrorCallback = (error) => {
            if (error) {
                console.log({ mongoConnectError: error });
            }
        };
        var store = new MongoDBStore({
            uri: 'mongodb://ubuntu:27017',
            databaseName: 'cents',
            collection: 'sessions'
        }, connectErrorCallback);
        store.on('error', connectErrorCallback);
        return store;

    })(session);
    session({
        secret: settings.cookieSecret,
        store,
        resave: false,
        saveUninitialized: false
    });
}

class AppSession {
    constructor(app, store, settings) {
        this.store = store;

        const whichSession = {
            mongo: mongoSession,
            redis: redisSession,
            file: fileStoreSession
        }[store] || fileStoreSession;

        this.express = whichSession(settings);
        app.use(this.express);
        app.use(passport.initialize());
        app.use(passport.session());

        if (store === 'mongo' || store === 'file') {
            var authentication = require('./authentication');
            authentication.init(app);
        }

        if (store === 'redis') {
            passport.serializeUser(function (user, done) {
                done(null, user);
            });

            passport.deserializeUser(function (user, done) {
                done(null, user);
            });
        }

        const whichProtect = {
            mongo: authenticationMiddleware,
            redis: redisProtect,
            file: authenticationMiddleware
        }[store] || authenticationMiddleware;

        this.protect = whichProtect;
    }
}

module.exports = AppSession;
<|endoftext|>


<commit_before>'use strict'

var express = require('express')
let request = require('request')
var htmlProcess = require('./html_process')
var through = require('through2')
var elasticsearch = require('elasticsearch')

class API {
  constructor(conf) {
    this.conf = conf
    this.elasticsearch = new elasticsearch.Client({
      host: conf.resources.elasticsearch,
      log: 'debug'
    })
  }

  getDocFragments(docId, res) {
    res.writeHead(200, {
      'Content-Type': 'application/json'
    })

    console.log(`Processing ${docId}: ${this.conf.resources.htmlUrl(docId)}`)
    request(this.conf.resources.htmlUrl(docId))
      .pipe(htmlProcess())
      .pipe(toJsonArray())
      .pipe(res)
      .on('error', e => {
        console.log("Error:", e.stack || e)
        res.end()
      })
  }

  searchDocs(queryString, res) {
    let query = queryString ? {
      query_string: {
        default_operator: 'AND',
        analyze_wildcard: true,
        query: queryString
      }
    } : {
      match_all: {}
    }
    this.elasticsearch.search({
      index: 'ratsinfo',
      type: 'pdf',
      body: {
        query: query,
        sort: [
          "_score",
          "started_at"
        ]
      }
    }).then(result =>
      groupBySessionAndTemplate(result.hits.hits.map(hit => hit._source))
    ).then(body => {
      res.writeHead(200, {
        'Content-Type': 'application/json'
      })
      res.write(JSON.stringify(body))
      res.end()
    }, err => {
      console.log("ES searchDocs for", query, ":", err)
      res.writeHead(500, {
        'Content-Type': 'text/plain'
      })
      res.write(err.message.toString())
      res.end()
    })
  }
}

function groupBySessionAndTemplate(hits) {
  let sessions = []
  for(let hit of hits) {
    let session_id = hit.session_id
    let session
    for(let session1 of sessions) {
      if (session1.id === session_id) {
        session = session1
        break
      }
    }
    if (!session) {
      session = {
        id: hit.session_id,
        description: hit.session_description,
        started_at: hit.started_at,
        parts: []
      }
      sessions.push(session)
    }

    let template_id = hit.template_id
    let part
    for(let part1 of session.parts) {
      if (part1.template_id === template_id) {
        part = part1
        break
      }
    }
    if (!part) {
      part = {
        template_id: hit.template_id,
        description: hit.template_description,
        documents: []
      }
      session.parts.push(part)
    }

    part.documents.push({
      file_name: hit.file_name,
      description: hit.description
    })
  }

  return sessions
}

module.exports = function(conf) {
  let api = new API(conf)
  var app = express()

  app.get('/docs/search/', (req, res) => {
    api.searchDocs("", res)
  })
  app.get('/docs/search/:query*', (req, res) => {
    api.searchDocs(req.params.query, res)
  })
  app.get('/docs/:docid/fragments', (req, res) => {
    api.getDocFragments(req.params.docid, res)
  })

  return app
}

function toJsonArray() {
  let count = 0
  return through.obj(function(fragment, enc, cb) {
    count++

    if (count === 1) {
      this.push("[\n")
    } else {
      this.push(",\n")
    }
    this.push(JSON.stringify(fragment))

    cb()
  }, function(cb) {
    this.push("\n]")
    cb()
  })
}

// SHIM for Object.values()
function objectValues(obj) {
  return Object.keys(obj).map(k => obj[k])
}
<commit_msg>server api: searchDocs() should sort by started_at desc<commit_after>'use strict'

var express = require('express')
let request = require('request')
var htmlProcess = require('./html_process')
var through = require('through2')
var elasticsearch = require('elasticsearch')

class API {
  constructor(conf) {
    this.conf = conf
    this.elasticsearch = new elasticsearch.Client({
      host: conf.resources.elasticsearch,
      log: 'debug'
    })
  }

  getDocFragments(docId, res) {
    res.writeHead(200, {
      'Content-Type': 'application/json'
    })

    console.log(`Processing ${docId}: ${this.conf.resources.htmlUrl(docId)}`)
    request(this.conf.resources.htmlUrl(docId))
      .pipe(htmlProcess())
      .pipe(toJsonArray())
      .pipe(res)
      .on('error', e => {
        console.log("Error:", e.stack || e)
        res.end()
      })
  }

  searchDocs(queryString, res) {
    let query = queryString ? {
      query_string: {
        default_operator: 'AND',
        analyze_wildcard: true,
        query: queryString
      }
    } : {
      match_all: {}
    }
    this.elasticsearch.search({
      index: 'ratsinfo',
      type: 'pdf',
      body: {
        query: query,
        sort: [
          { _score: "desc" },
          { started_at: "desc" }
        ]
      }
    }).then(result =>
      groupBySessionAndTemplate(result.hits.hits.map(hit => hit._source))
    ).then(body => {
      res.writeHead(200, {
        'Content-Type': 'application/json'
      })
      res.write(JSON.stringify(body))
      res.end()
    }, err => {
      console.log("ES searchDocs for", query, ":", err)
      res.writeHead(500, {
        'Content-Type': 'text/plain'
      })
      res.write(err.message.toString())
      res.end()
    })
  }
}

function groupBySessionAndTemplate(hits) {
  let sessions = []
  for(let hit of hits) {
    let session_id = hit.session_id
    let session
    for(let session1 of sessions) {
      if (session1.id === session_id) {
        session = session1
        break
      }
    }
    if (!session) {
      session = {
        id: hit.session_id,
        description: hit.session_description,
        started_at: hit.started_at,
        parts: []
      }
      sessions.push(session)
    }

    let template_id = hit.template_id
    let part
    for(let part1 of session.parts) {
      if (part1.template_id === template_id) {
        part = part1
        break
      }
    }
    if (!part) {
      part = {
        template_id: hit.template_id,
        description: hit.template_description,
        documents: []
      }
      session.parts.push(part)
    }

    part.documents.push({
      file_name: hit.file_name,
      description: hit.description
    })
  }

  return sessions
}

module.exports = function(conf) {
  let api = new API(conf)
  var app = express()

  app.get('/docs/search/', (req, res) => {
    api.searchDocs("", res)
  })
  app.get('/docs/search/:query*', (req, res) => {
    api.searchDocs(req.params.query, res)
  })
  app.get('/docs/:docid/fragments', (req, res) => {
    api.getDocFragments(req.params.docid, res)
  })

  return app
}

function toJsonArray() {
  let count = 0
  return through.obj(function(fragment, enc, cb) {
    count++

    if (count === 1) {
      this.push("[\n")
    } else {
      this.push(",\n")
    }
    this.push(JSON.stringify(fragment))

    cb()
  }, function(cb) {
    this.push("\n]")
    cb()
  })
}

// SHIM for Object.values()
function objectValues(obj) {
  return Object.keys(obj).map(k => obj[k])
}
<|endoftext|>


<commit_before>Meteor.startup(function () {
  Singleton.update({}, {$set: { version: "v1.0.3-dev" }});
});
<commit_msg>bump version number to v1.1.0<commit_after>Meteor.startup(function () {
  Singleton.update({}, {$set: { version: "v1.1.0" }});
});
<|endoftext|>