<commit_before>var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var LegendColorView = require('./color/legend-color-view');
var LegendSizeView = require('./size/legend-size-view');
var createTextLabelsTabPane = require('../../../../components/tab-pane/create-text-labels-tab-pane');
var TabPaneTemplate = require('../../../tab-pane-submenu.tpl');
var sqlErrorTemplate = require('./legend-content-sql-error.tpl');
var actionErrorTemplate = require('../../sql-error-action.tpl');
var loadingTemplate = require('../../panel-loading-template.tpl');
var legendNoGeometryTemplate = require('./legend-no-geometry-template.tpl');
var QuerySanity = require('../../query-sanity-check');
var georeferencePlaceholderTemplate = require('./georeference-placeholder.tpl');
var checkAndBuildOpts = require('../../../../helpers/required-opts');
var Infobox = require('../../../../components/infobox/infobox-factory');
var InfoboxModel = require('../../../../components/infobox/infobox-model');
var InfoboxCollection = require('../../../../components/infobox/infobox-collection');
var PanelWithOptionsView = require('../../../../components/view-options/panel-with-options-view');
var ViewFactory = require('../../../../components/view-factory');
var panelTemplate = require('./panel-with-options.tpl');
var OverlayView = require('../../../components/overlay/overlay-view');
var fetchAllQueryObjectsIfNecessary = require('../../../../helpers/fetch-all-query-objects');

var STATES = {
  ready: 'ready',
  loading: 'loading',
  fetched: 'fetched',
  error: 'error'
};

var REQUIRED_OPTS = [
  'mapDefinitionModel',
  'userActions',
  'layerDefinitionModel',
  'queryGeometryModel',
  'querySchemaModel',
  'queryRowsCollection',
  'legendDefinitionsCollection',
  'editorModel',
  'userModel',
  'configModel',
  'modals'
];

module.exports = CoreView.extend({

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    this._layerInfowindowModel = this._layerDefinitionModel.infowindowModel;
    this._layerTooltipModel = this._layerDefinitionModel.tooltipModel;

    this._initModels();
    this._initBinds();

    this._fetchAllQueryObjectsIfNecessary();

    // In order to handle sql errors
    QuerySanity.track(this, this._onQueryChanged.bind(this));
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();

    if (this._queryGeometryModel.isFetching()) {
      this._renderLoading();
    } else if (this._hasError()) {
      this._renderError();
    } else if (this._queryGeometryModel.hasValue()) {
      this._initViews();
    } else {
      if (this._layerDefinitionModel.canBeGeoreferenced()) {
        this._renderGeoreferencePlaceholder();
      } else {
        this._renderEmptyGeometry();
      }
    }

    this._renderOverlay();
    return this;
  },

  _renderOverlay: function () {
    var view = new OverlayView({
      overlayModel: this._overlayModel
    });
    this.addView(view);
    this.$('.js-content').append(view.render().el);
  },

  _initModels: function () {
    this._infoboxModel = new InfoboxModel({
      state: this._isLayerHidden() ? 'layer-hidden' : ''
    });

    this._overlayModel = new Backbone.Model({
      visible: this._isLayerHidden()
    });

    this.modelView = new Backbone.Model({
      state: this._getInitialState()
    });
  },

  _isLayerHidden: function () {
    return this._layerDefinitionModel.get('visible') === false;
  },

  _initBinds: function () {
    this.listenTo(this._querySchemaModel, 'change:status', this._onStatusChanged);
    this.listenTo(this._queryGeometryModel, 'change:status', this._onStatusChanged);
    this.listenTo(this._queryRowsCollection.statusModel, 'change:status', this._onStatusChanged);
    this.listenTo(this._editorModel, 'change:edition', this._changeStyle);

    // If there is a change in the node query (we check queryGeometryModel because is the last query element set)
    // we should fetch all objects (necessary in this case)
    this.listenTo(this._queryGeometryModel, 'change:query', function () {
      this._queryGeometryModel.set('status', 'unfetched');
      this._fetchAllQueryObjectsIfNecessary();
    });
    this.listenTo(this._queryGeometryModel, 'change:status', this._onGeometryChanged);
    this.listenTo(this._editorModel, 'change:edition', this._changeStyle);
  },

  _fetchAllQueryObjectsIfNecessary: function () {
    fetchAllQueryObjectsIfNecessary({
      queryRowsCollection: this._queryRowsCollection,
      queryGeometryModel: this._queryGeometryModel,
      querySchemaModel: this._querySchemaModel
    });
  },

  _onStatusChanged: function () {
    if (this._querySchemaModel.isFetched() &&
        this._queryGeometryModel.isFetched() &&
        this._queryRowsCollection.isFetched()) {
      this.render();
    }
  },

  _onQueryChanged: function () {
    if (this._hasError()) {
      this.render();
    }
  },

  _getInitialState: function () {
    return STATES.ready;
  },

  _hasError: function () {
    return this.modelView.get('state') === STATES.error;
  },

  _renderError: function () {
    this.$el.append(
      sqlErrorTemplate({
        body: _t('editor.error-query.body', {
          action: actionErrorTemplate({
            label: _t('editor.error-query.label')
          })
        })
      })
    );
  },

  _renderGeoreferencePlaceholder: function () {
    var self = this;

    var infoboxSstates = [
      {
        state: 'layer-hidden',
        createContentView: function () {
          return Infobox.createWithAction({
            type: 'alert',
            title: _t('editor.infowindow.messages.layer-hidden.title'),
            body: _t('editor.infowindow.messages.layer-hidden.body'),
            mainAction: {
              label: _t('editor.infowindow.messages.layer-hidden.show')
            }
          });
        },
        mainAction: self._showHiddenLayer.bind(self)
      }
    ];

    var infoboxCollection = new InfoboxCollection(infoboxSstates);

    var panelWithOptionsView = new PanelWithOptionsView({
      template: panelTemplate,
      className: 'Editor-content',
      editorModel: self._editorModel,
      infoboxModel: self._infoboxModel,
      infoboxCollection: infoboxCollection,
      createContentView: function () {
        return ViewFactory.createByHTML(georeferencePlaceholderTemplate());
      }
    });

    this.$el.append(panelWithOptionsView.render().el);
    this.addView(panelWithOptionsView);
  },

  _renderEmptyGeometry: function () {
    this.$el.append(legendNoGeometryTemplate());
  },

  _renderLoading: function () {
    this.$el.append(loadingTemplate());
  },

  _initViews: function () {
    var self = this;

    var tabPaneTabs = [{
      name: 'color',
      label: _t('editor.legend.menu-tab-pane-labels.color'),
      createContentView: function () {
        return new LegendColorView({
          className: 'Editor-content',
          mapDefinitionModel: self._mapDefinitionModel,
          editorModel: self._editorModel,
          userActions: self._userActions,
          modelView: self.modelView,
          layerDefinitionModel: self._layerDefinitionModel,
          legendDefinitionsCollection: self._legendDefinitionsCollection,
          type: 'color',
          userModel: self._userModel,
          configModel: self._configModel,
          modals: self._modals
        });
      }
    }, {
      name: 'size',
      label: _t('editor.legend.menu-tab-pane-labels.size'),
      createContentView: function () {
        return new LegendSizeView({
          className: 'Editor-content',
          mapDefinitionModel: self._mapDefinitionModel,
          editorModel: self._editorModel,
          userActions: self._userActions,
          userModel: self._userModel,
          configModel: self._configModel,
          modals: self._modals,
          modelView: self.modelView,
          layerDefinitionModel: self._layerDefinitionModel,
          legendDefinitionsCollection: self._legendDefinitionsCollection,
          type: 'size'
        });
      }
    }];

    var tabPaneOptions = {
      tabPaneOptions: {
        template: TabPaneTemplate,
        tabPaneItemOptions: {
          tagName: 'li',
          className: 'CDB-NavSubmenu-item'
        }
      },
      tabPaneItemLabelOptions: {
        tagName: 'button',
        className: 'CDB-NavSubmenu-link u-upperCase'
      }
    };

    this._layerTabPaneView = createTextLabelsTabPane(tabPaneTabs, tabPaneOptions);
    this.$el.append(this._layerTabPaneView.render().$el);
    this.addView(this._layerTabPaneView);
    this._changeStyle(this._editorModel);
  },

  _changeStyle: function (m) {
    this._layerTabPaneView.changeStyleMenu(m);
  },

  _showHiddenLayer: function () {
    var savingOptions = {
      shouldPreserveAutoStyle: true
    };
    this._layerDefinitionModel.toggleVisible();
    this._userActions.saveLayer(this._layerDefinitionModel, savingOptions);
  }
});
<commit_msg>Fix #11825<commit_after>var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var LegendColorView = require('./color/legend-color-view');
var LegendSizeView = require('./size/legend-size-view');
var createTextLabelsTabPane = require('../../../../components/tab-pane/create-text-labels-tab-pane');
var TabPaneTemplate = require('../../../tab-pane-submenu.tpl');
var sqlErrorTemplate = require('./legend-content-sql-error.tpl');
var actionErrorTemplate = require('../../sql-error-action.tpl');
var loadingTemplate = require('../../panel-loading-template.tpl');
var legendNoGeometryTemplate = require('./legend-no-geometry-template.tpl');
var QuerySanity = require('../../query-sanity-check');
var georeferencePlaceholderTemplate = require('./georeference-placeholder.tpl');
var checkAndBuildOpts = require('../../../../helpers/required-opts');
var Infobox = require('../../../../components/infobox/infobox-factory');
var InfoboxModel = require('../../../../components/infobox/infobox-model');
var InfoboxCollection = require('../../../../components/infobox/infobox-collection');
var PanelWithOptionsView = require('../../../../components/view-options/panel-with-options-view');
var ViewFactory = require('../../../../components/view-factory');
var panelTemplate = require('./panel-with-options.tpl');
var OverlayView = require('../../../components/overlay/overlay-view');
var fetchAllQueryObjectsIfNecessary = require('../../../../helpers/fetch-all-query-objects');

var STATES = {
  ready: 'ready',
  loading: 'loading',
  fetched: 'fetched',
  error: 'error'
};

var REQUIRED_OPTS = [
  'mapDefinitionModel',
  'userActions',
  'layerDefinitionModel',
  'queryGeometryModel',
  'querySchemaModel',
  'queryRowsCollection',
  'legendDefinitionsCollection',
  'editorModel',
  'userModel',
  'configModel',
  'modals'
];

module.exports = CoreView.extend({

  initialize: function (opts) {
    checkAndBuildOpts(opts, REQUIRED_OPTS, this);

    this._layerInfowindowModel = this._layerDefinitionModel.infowindowModel;
    this._layerTooltipModel = this._layerDefinitionModel.tooltipModel;

    this._initModels();
    this._initBinds();

    this._fetchAllQueryObjectsIfNecessary();

    // In order to handle sql errors
    QuerySanity.track(this, this._onQueryChanged.bind(this));
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();

    if (this._queryGeometryModel.isFetching()) {
      this._renderLoading();
    } else if (this._hasError()) {
      this._renderError();
    } else if (this._queryGeometryModel.hasValue()) {
      this._initViews();
    } else {
      if (this._layerDefinitionModel.canBeGeoreferenced()) {
        this._renderGeoreferencePlaceholder();
      } else {
        this._renderEmptyGeometry();
      }
    }

    this._renderOverlay();
    return this;
  },

  _renderOverlay: function () {
    var view = new OverlayView({
      overlayModel: this._overlayModel
    });
    this.addView(view);
    this.$el.append(view.render().el);
  },

  _initModels: function () {
    this._infoboxModel = new InfoboxModel({
      state: this._isLayerHidden() ? 'layer-hidden' : ''
    });

    this._overlayModel = new Backbone.Model({
      visible: this._isLayerHidden()
    });

    this.modelView = new Backbone.Model({
      state: this._getInitialState()
    });
  },

  _isLayerHidden: function () {
    return this._layerDefinitionModel.get('visible') === false;
  },

  _initBinds: function () {
    this.listenTo(this._querySchemaModel, 'change:status', this._onStatusChanged);
    this.listenTo(this._queryGeometryModel, 'change:status', this._onStatusChanged);
    this.listenTo(this._queryRowsCollection.statusModel, 'change:status', this._onStatusChanged);
    this.listenTo(this._editorModel, 'change:edition', this._changeStyle);

    // If there is a change in the node query (we check queryGeometryModel because is the last query element set)
    // we should fetch all objects (necessary in this case)
    this.listenTo(this._queryGeometryModel, 'change:query', function () {
      this._queryGeometryModel.set('status', 'unfetched');
      this._fetchAllQueryObjectsIfNecessary();
    });
    this.listenTo(this._queryGeometryModel, 'change:status', this._onGeometryChanged);
    this.listenTo(this._editorModel, 'change:edition', this._changeStyle);
  },

  _fetchAllQueryObjectsIfNecessary: function () {
    fetchAllQueryObjectsIfNecessary({
      queryRowsCollection: this._queryRowsCollection,
      queryGeometryModel: this._queryGeometryModel,
      querySchemaModel: this._querySchemaModel
    });
  },

  _onStatusChanged: function () {
    if (this._querySchemaModel.isFetched() &&
        this._queryGeometryModel.isFetched() &&
        this._queryRowsCollection.isFetched()) {
      this.render();
    }
  },

  _onQueryChanged: function () {
    if (this._hasError()) {
      this.render();
    }
  },

  _getInitialState: function () {
    return STATES.ready;
  },

  _hasError: function () {
    return this.modelView.get('state') === STATES.error;
  },

  _renderError: function () {
    this.$el.append(
      sqlErrorTemplate({
        body: _t('editor.error-query.body', {
          action: actionErrorTemplate({
            label: _t('editor.error-query.label')
          })
        })
      })
    );
  },

  _renderGeoreferencePlaceholder: function () {
    var self = this;

    var infoboxSstates = [
      {
        state: 'layer-hidden',
        createContentView: function () {
          return Infobox.createWithAction({
            type: 'alert',
            title: _t('editor.infowindow.messages.layer-hidden.title'),
            body: _t('editor.infowindow.messages.layer-hidden.body'),
            mainAction: {
              label: _t('editor.infowindow.messages.layer-hidden.show')
            }
          });
        },
        mainAction: self._showHiddenLayer.bind(self)
      }
    ];

    var infoboxCollection = new InfoboxCollection(infoboxSstates);

    var panelWithOptionsView = new PanelWithOptionsView({
      template: panelTemplate,
      className: 'Editor-content',
      editorModel: self._editorModel,
      infoboxModel: self._infoboxModel,
      infoboxCollection: infoboxCollection,
      createContentView: function () {
        return ViewFactory.createByHTML(georeferencePlaceholderTemplate());
      }
    });

    this.$el.append(panelWithOptionsView.render().el);
    this.addView(panelWithOptionsView);
  },

  _renderEmptyGeometry: function () {
    this.$el.append(legendNoGeometryTemplate());
  },

  _renderLoading: function () {
    this.$el.append(loadingTemplate());
  },

  _initViews: function () {
    var self = this;

    var tabPaneTabs = [{
      name: 'color',
      label: _t('editor.legend.menu-tab-pane-labels.color'),
      createContentView: function () {
        return new LegendColorView({
          className: 'Editor-content',
          mapDefinitionModel: self._mapDefinitionModel,
          editorModel: self._editorModel,
          userActions: self._userActions,
          modelView: self.modelView,
          layerDefinitionModel: self._layerDefinitionModel,
          legendDefinitionsCollection: self._legendDefinitionsCollection,
          type: 'color',
          userModel: self._userModel,
          configModel: self._configModel,
          modals: self._modals
        });
      }
    }, {
      name: 'size',
      label: _t('editor.legend.menu-tab-pane-labels.size'),
      createContentView: function () {
        return new LegendSizeView({
          className: 'Editor-content',
          mapDefinitionModel: self._mapDefinitionModel,
          editorModel: self._editorModel,
          userActions: self._userActions,
          userModel: self._userModel,
          configModel: self._configModel,
          modals: self._modals,
          modelView: self.modelView,
          layerDefinitionModel: self._layerDefinitionModel,
          legendDefinitionsCollection: self._legendDefinitionsCollection,
          type: 'size'
        });
      }
    }];

    var tabPaneOptions = {
      tabPaneOptions: {
        template: TabPaneTemplate,
        tabPaneItemOptions: {
          tagName: 'li',
          className: 'CDB-NavSubmenu-item'
        }
      },
      tabPaneItemLabelOptions: {
        tagName: 'button',
        className: 'CDB-NavSubmenu-link u-upperCase'
      }
    };

    this._layerTabPaneView = createTextLabelsTabPane(tabPaneTabs, tabPaneOptions);
    this.$el.append(this._layerTabPaneView.render().$el);
    this.addView(this._layerTabPaneView);
    this._changeStyle(this._editorModel);
  },

  _changeStyle: function (m) {
    this._layerTabPaneView.changeStyleMenu(m);
  },

  _showHiddenLayer: function () {
    var savingOptions = {
      shouldPreserveAutoStyle: true
    };
    this._layerDefinitionModel.toggleVisible();
    this._userActions.saveLayer(this._layerDefinitionModel, savingOptions);
  }
});
<|endoftext|>


<commit_before>(function() {
    $(document).ready(function() {

        /**
         * Status Message
         */
        var Status = function() {
            this.set = function(msg, done) {
                $('#status').show(200);
                $('#status').html(msg);
                if (done === 'fadeout') {
                    setTimeout(function() {
                        $('#status').hide(500);
                    }, 5000);
                }
            };
        };
        var status = new Status();

        /**
         * Loads List of TV-Shows from RSS
         *
         */
        var loadRssTV = function(type) {
            var div, rssTV = document.getElementById('rss_TV');
            $.getJSON('/tv', function(json) {
                for (var i in json) {
                    div = document.createElement('div');
                    div.className   = 'hyperlinkParse';
                    div.textContent = json[i].title;
                    div.onclick     = (function(link){
                        return function(){
                            parseData(link);
                        };
                    })(json[i].link);
                    rssTV.appendChild(div);
                }
            });
        };

        /**
         * Loads list of Movies as Thumbnails from db
         *
         */
        var loadRssMovies = function() {
            $.getJSON('/movies', function(json) {
                var div, i, poster;
                json.sort(function(a, b) {
                    a = new Date(a.lastUpdate);
                    b = new Date(b.lastUpdate);
                    return a > b ? -1 : a < b ? 1 : 0;
                });
                // Start creating Movie-Thumbs
                for (i = 0; i < json.length; i++) {
                    poster = json[i].info.posters !== undefined ? json[i].info.posters.thumbnail : '';
                    div = thumbPoster(poster, json[i].title);
                    div.style.float = 'left';
                    div.style.cursor = 'pointer';
                    div.onclick = (function(_id, title, info, image, sites) {
                        return function() {
                            $('#content').tabs({
                                active: 1
                            }); // Jump to tab 1 > links; tabs start with 0 = first tab
                            $('#linksDetails').empty();
                            $('#linksDetails').append(divMovieInfo(
                                _id,
                                title,
                                image,
                                info.runtime ? info.runtime : '?',
                                info.year,
                                'imdb-Rating',
                                info.synopsis === '' ? 'no synopsis' : info.synopsis,
                                'actors'
                            ));
                            // Site-Links for ripping links
                            // Link to Rip all links at the same time
                            var divAll = document.createElement('div');
                            divAll.className = 'hyperlinkParse';
                            divAll.textContent = '>- rip All Sites -<';
                            divAll.onclick = (function(sites){
                                return function() {
                                    status.set('parsing all sites...');
                                    $.post('/site/links', {sites: sites}, function(ids){
                                        parseIDs(ids);
                                    }, 'json');
                                };
                            })(sites);
                            $('#linksDetails').append(divAll);
                            // Single Links
                            var divLink;
                            for (var key in sites) {
                                divLink = document.createElement('div');
                                divLink.className = 'hyperlinkParse';
                                divLink.textContent = sites[key].title;
                                divLink.onclick = (function(site){
                                    return function() {
                                        status.set('parsing site...');
                                        $.post('/site/links', {sites: [site]}, function(ids){
                                            parseIDs(ids);
                                        }, 'json');
                                    };
                                })(sites[key]);
                                $('#linksDetails').append(divLink);
                            }
                        };
                    })(json[i]._id, json[i].title, json[i].info, poster, json[i].sites);
                    $('#rss_Movies').append(div);
                }
            });
        };

        /**
         * Loads the list of Downloaded files that are on the server
         */
        var loadFiles = function() {
            $.getJSON('/file', function(files) {
                $('#rss_files tbody').empty();
                // Sort files by Filename
                files.sort(function(a, b) {
                    a = a.filename.toLowerCase();
                    b = b.filename.toLowerCase();
                    return a > b ? 1 : a < b ? -1 : 0;
                });
                for (var i in files) {
                    $('#rss_files tbody').append('
' +
                    files[i].filename + '	' + '' + bytesToSize(files[i].size) + '	' +
                    '

	');
                }
            });
        };

        loadRssTV();
        loadRssMovies();
        loadFiles();

        /**
         * Takes the input string and decides if
         *    - String is URL but not uploaded-link > rip site
         *    - String is ul.to Id > check ul-File
         *    - String contains ul.to links
         *
         * It then takes the Ids to the Id-Parser which checks the links
         *
         * @param {string} data A string that contains URLs, an Id or plain text
         */
        var parseData = function(data) {
            status.set('start looking for links...');
            $('#content').tabs({active: 1}); // Jump to tab 1 > links

            // is link to page that may contain uploaded.net links > rip Site
            if (validateURL(data) && !isUploaded(data)) {
                status.set('parsing site...');
                $.post('/site/links', {sites: [{links:[data]}]}).done(function(ids){
                    parseIDs(ids);
                }, 'json');
            }
            else if (/^[a-zA-Z0-9-]{8}/i.test(data) && data !== 'uploaded') { // is ul.to ID
                parseIDs({data: data.substr(0, 8)});
            }
            else { // is string that may contain ul.to links
                parseIDs(getLinksFromString(data));
            }
        };

        /**
         *
         */
        var parseIDs = function(ids) {
            var links = '';
            var files = [];
            var filescount = 0;
            var curfile = 0;

            for (var key in ids) {
                if (ids.hasOwnProperty(key)) {
                    links += "\n" + "http://ul.to/" + ids[key];
                    filescount++;
                }
            }
            $('#data').val(links);
            $('#content').append('

');
            var defs = [];
            var addFile = function(info) {
                if (info !== false) {
                    files.push(info);
                }
                curfile++;
                status.set((filescount - curfile) + ' files left to check...');
                makeTableChecked(files);
            };
            status.set('start checking ' + filescount + ' files...');
            $.each(ids, function(key, value) {
                defs.push($.getJSON('/ul/' + value + '/check', function(info) {
                    addFile(info);
                }));
            });
            $.when.apply(null, defs).done(function() {
                status.set(filescount + ' files checked!', 'fadeout');
                makeTableChecked(files);
            });
        };

        /**
         * Table with ul.to links that have been checked for availability
         *
         * @param {array} files an Array containing all checked ul.to links
         */
        var makeTableChecked = function(files) {
            var extensions = {mp4:0, mkv:0, avi:0, rar:0, default:0};
            var rowcols    = ['link', 'size', 'extension', 'jd', 'cloud'];
            var target     = '#tabs-links-';
            var links      = '';
            for (var i in extensions)
                $(target + i + ' tbody').empty();

            var cols = function() {
                var tds = [];
                for (var i in rowcols)
                    tds.push(document.createElement('td'));
                return tds;
            };
            files.sort(function(a, b) {
                return a.extension  b.extension ? -1 : 0;
            }); // sort files by extension

            // Loop through all uploaded-files
            for (i in files) {
                var t = (extensions[files[i].extension] !== undefined) ? files[i].extension : 'default';
                extensions[t]++;
                var t = target + t;
                var tr = document.createElement('tr');
                var tds = new cols();

                // Link/Name Col
                var link = document.createElement('a');
                link.href = files[i].link;
                link.textContent = files[i].filename;
                tds[0].appendChild(link);

                // Size Col
                tds[1].textContent = bytesToSize(files[i].size);

                // Extension Col
                var extension = document.createElement('div');
                extension.className = 'icon icon' + files[i].extension;
                extension.title = files[i].extension;
                tds[2].appendChild(extension);

                // J-Downloader Col
                tds[3].appendChild(jDLink(files[i].id));

                // Download to Server Col
                var cloud = document.createElement('div');
                cloud.className = 'icon iconcloud';
                cloud.id = files[i].id;
                cloud.title = 'download to server';
                cloud.onclick = (function(i) {
                    return function() {
                        grabUl(files[i].id);
                    };
                })(i);
                tds[4].appendChild(cloud);

                for (var key in tds)
                tr.appendChild(tds[key]);

                $(t + ' tbody').append(tr);
                links += 'http://ul.to/' + files[i].id + ' ';
            }
            // Add links to textarea for exporting
            $('#paste').html(links);

            // update files per extension
            if (extensions.mp4 === 0) {
                $('#rssLinks').tabs({active: 1});
            }
            else $('#rssLinks').tabs({active: 0});
            for (var i in extensions) {
                $('#rssLinks ul:first li:eq('+(Object.keys(extensions)).indexOf(i)+') a').text(i + '(' + extensions[i] + ')');
            }
        };

        var jDLink = function(id) {
            var input = document.createElement('div');
            input.className = 'icon iconjd';
            input.onclick = function() {
                $.ajax({
                    type: 'POST',
                    url: 'http://127.0.0.1:9666/flash/add',
                    data: {
                        urls: 'http://ul.to/' + id
                    }
                });
                input.title = 'open in jDownloader';
            };
            return input;
        };

        /**
         * Downlaods an ul-File to the server
         *
         * @param {Number} id The ul.to/id
         */
        var grabUl = function(id) {
            status.set('start downloading file to the server...');
            $.getJSON('ul/' + id + '/grab').done(function(success) {
                status.set(success === true ? 'download complete!' : 'error while downloading!');
            });
        };

        var getLinksFromString = function(string) {
            var ids = [];
            var schemas = ['ul\\.to/([a-zA-Z0-9-]{8})', 'uploaded\\.net/file/([a-zA-Z0-9-]{8})'];
            var regex = new RegExp(schemas.join('|'), 'gim');
            var link;
            while ((link = regex.exec(string)) !== null) {
                var id = link[0].match(/[a-z0-9-]{8}$/);
                if (ids.indexOf(id[0]) === -1) ids.push(id[0]);
            }
            return ids;
        };

        /**
         * Creates a HTML Movie-Thumb from the Movie-Poster
         *
         * @param {string} imageUrl The Url of the Movie-Poster-Image
         * @param {string} title Title of the Movie as title-tag
         *
         * @returns {Object} the DOM-Object of the div
         */
        var thumbPoster = function(imageUrl, title) {
            var div = document.createElement('div');
            div.className = 'thumbPoster';
            div.title = title;
            div.style.backgroundImage = 'url(' + imageUrl + ')';
            if (imageUrl === '' || (/poster_default/).test(imageUrl)) {
                div.style.backgroundImage = '';
                div.textContent = title;
            }
            return div;
        };

        /**
         * Adds info to the movie-Thumb
         */
        var thumbPosterWithInfo = function(info) {
            var thumb = thumbPoster(info.imageUrl, info.title);
            var res = info.res;

        };

        /**
         * Creates the Movie-Info-Card
         */
        var divMovieInfo = function(_id, title, posterUrl, runtime, year, imdb, synopsis, actors) {
            var div = document.createElement('div');
            div.className = 'movieDigest';
            var divOuter = document.createElement('div');
            divOuter.className = 'movieInfo';

            var divTitle = document.createElement('div');
            divTitle.className = 'movieInfoTitle';
            divTitle.textContent = title;

            var divDetails = document.createElement('div');
            divDetails.className = 'movieInfoLine';
            divDetails.textContent = 'Length: ' + runtime + 'min, Year: ' + year + ', ';
            var spanRemove = document.createElement('span');
            spanRemove.textContent = 'remove';
            spanRemove.title = 'don\'t display this movie anymore.';
            spanRemove.className = 'hyperlink';
            spanRemove.onclick = function() {
                $.getJSON('/movie/' + _id + '/hide', function(data){Status.set('Movie will not be shown anymore!')});
            };
            divDetails.appendChild(spanRemove);

            var divSynopsis = document.createElement('div');
            divSynopsis.className = 'movieInfoLine';
            divSynopsis.textContent = synopsis;
            divSynopsis.style.fontStyle = 'italic';

            var poster = thumbPoster(posterUrl, title);
            poster.style.float = 'left';

            divOuter.appendChild(divTitle);
            divOuter.appendChild(divDetails);
            divOuter.appendChild(divSynopsis);

            div.appendChild(poster);
            div.appendChild(divOuter);
            return div;
        };

        $('#go').click(function() {
            parseData($('#data').val());
        });

    });
})();<commit_msg>error in TV Ripping $.get/post<commit_after>(function() {
    $(document).ready(function() {

        /**
         * Status Message
         */
        var Status = function() {
            this.set = function(msg, done) {
                $('#status').show(200);
                $('#status').html(msg);
                if (done === 'fadeout') {
                    setTimeout(function() {
                        $('#status').hide(500);
                    }, 5000);
                }
            };
        };
        var status = new Status();

        /**
         * Loads List of TV-Shows from RSS
         *
         */
        var loadRssTV = function(type) {
            var div, rssTV = document.getElementById('rss_TV');
            $.getJSON('/tv', function(json) {
                for (var i in json) {
                    div = document.createElement('div');
                    div.className   = 'hyperlinkParse';
                    div.textContent = json[i].title;
                    div.onclick     = (function(link){
                        return function(){
                            parseData(link);
                        };
                    })(json[i].link);
                    rssTV.appendChild(div);
                }
            });
        };

        /**
         * Loads list of Movies as Thumbnails from db
         *
         */
        var loadRssMovies = function() {
            $.getJSON('/movies', function(json) {
                var div, i, poster;
                json.sort(function(a, b) {
                    a = new Date(a.lastUpdate);
                    b = new Date(b.lastUpdate);
                    return a > b ? -1 : a < b ? 1 : 0;
                });
                // Start creating Movie-Thumbs
                for (i = 0; i < json.length; i++) {
                    poster = json[i].info.posters !== undefined ? json[i].info.posters.thumbnail : '';
                    div = thumbPoster(poster, json[i].title);
                    div.style.float = 'left';
                    div.style.cursor = 'pointer';
                    div.onclick = (function(_id, title, info, image, sites) {
                        return function() {
                            $('#content').tabs({
                                active: 1
                            }); // Jump to tab 1 > links; tabs start with 0 = first tab
                            $('#linksDetails').empty();
                            $('#linksDetails').append(divMovieInfo(
                                _id,
                                title,
                                image,
                                info.runtime ? info.runtime : '?',
                                info.year,
                                'imdb-Rating',
                                info.synopsis === '' ? 'no synopsis' : info.synopsis,
                                'actors'
                            ));
                            // Site-Links for ripping links
                            // Link to Rip all links at the same time
                            var divAll = document.createElement('div');
                            divAll.className = 'hyperlinkParse';
                            divAll.textContent = '>- rip All Sites -<';
                            divAll.onclick = (function(sites){
                                return function() {
                                    status.set('parsing all sites...');
                                    $.post('/site/links', {sites: sites}, function(ids){
                                        parseIDs(ids);
                                    }, 'json');
                                };
                            })(sites);
                            $('#linksDetails').append(divAll);
                            // Single Links
                            var divLink;
                            for (var key in sites) {
                                divLink = document.createElement('div');
                                divLink.className = 'hyperlinkParse';
                                divLink.textContent = sites[key].title;
                                divLink.onclick = (function(site){
                                    return function() {
                                        status.set('parsing site...');
                                        $.post('/site/links', {sites: [site]}, function(ids){
                                            parseIDs(ids);
                                        }, 'json');
                                    };
                                })(sites[key]);
                                $('#linksDetails').append(divLink);
                            }
                        };
                    })(json[i]._id, json[i].title, json[i].info, poster, json[i].sites);
                    $('#rss_Movies').append(div);
                }
            });
        };

        /**
         * Loads the list of Downloaded files that are on the server
         */
        var loadFiles = function() {
            $.getJSON('/file', function(files) {
                $('#rss_files tbody').empty();
                // Sort files by Filename
                files.sort(function(a, b) {
                    a = a.filename.toLowerCase();
                    b = b.filename.toLowerCase();
                    return a > b ? 1 : a < b ? -1 : 0;
                });
                for (var i in files) {
                    $('#rss_files tbody').append('
' +
                    files[i].filename + '	' + '' + bytesToSize(files[i].size) + '	' +
                    '

	');
                }
            });
        };

        loadRssTV();
        loadRssMovies();
        loadFiles();

        /**
         * Takes the input string and decides if
         *    - String is URL but not uploaded-link > rip site
         *    - String is ul.to Id > check ul-File
         *    - String contains ul.to links
         *
         * It then takes the Ids to the Id-Parser which checks the links
         *
         * @param {string} data A string that contains URLs, an Id or plain text
         */
        var parseData = function(data) {
            status.set('start looking for links...');
            $('#content').tabs({active: 1}); // Jump to tab 1 > links

            // is link to page that may contain uploaded.net links > rip Site
            if (validateURL(data) && !isUploaded(data)) {
                status.set('parsing site...');
                $.post('/site/links', {sites: [{link:data}]}).done(function(ids){
                    parseIDs(ids);
                }, 'json');
            }
            else if (/^[a-zA-Z0-9-]{8}/i.test(data) && data !== 'uploaded') { // is ul.to ID
                parseIDs({data: data.substr(0, 8)});
            }
            else { // is string that may contain ul.to links
                parseIDs(getLinksFromString(data));
            }
        };

        /**
         *
         */
        var parseIDs = function(ids) {
            var links = '';
            var files = [];
            var filescount = 0;
            var curfile = 0;

            for (var key in ids) {
                if (ids.hasOwnProperty(key)) {
                    links += "\n" + "http://ul.to/" + ids[key];
                    filescount++;
                }
            }
            $('#data').val(links);
            $('#content').append('

');
            var defs = [];
            var addFile = function(info) {
                if (info !== false) {
                    files.push(info);
                }
                curfile++;
                status.set((filescount - curfile) + ' files left to check...');
                makeTableChecked(files);
            };
            status.set('start checking ' + filescount + ' files...');
            $.each(ids, function(key, value) {
                defs.push($.getJSON('/ul/' + value + '/check', function(info) {
                    addFile(info);
                }));
            });
            $.when.apply(null, defs).done(function() {
                status.set(filescount + ' files checked!', 'fadeout');
                makeTableChecked(files);
            });
        };

        /**
         * Table with ul.to links that have been checked for availability
         *
         * @param {array} files an Array containing all checked ul.to links
         */
        var makeTableChecked = function(files) {
            var extensions = {mp4:0, mkv:0, avi:0, rar:0, default:0};
            var rowcols    = ['link', 'size', 'extension', 'jd', 'cloud'];
            var target     = '#tabs-links-';
            var links      = '';
            for (var i in extensions)
                $(target + i + ' tbody').empty();

            var cols = function() {
                var tds = [];
                for (var i in rowcols)
                    tds.push(document.createElement('td'));
                return tds;
            };
            files.sort(function(a, b) {
                return a.extension  b.extension ? -1 : 0;
            }); // sort files by extension

            // Loop through all uploaded-files
            for (i in files) {
                var t = (extensions[files[i].extension] !== undefined) ? files[i].extension : 'default';
                extensions[t]++;
                var t = target + t;
                var tr = document.createElement('tr');
                var tds = new cols();

                // Link/Name Col
                var link = document.createElement('a');
                link.href = files[i].link;
                link.textContent = files[i].filename;
                tds[0].appendChild(link);

                // Size Col
                tds[1].textContent = bytesToSize(files[i].size);

                // Extension Col
                var extension = document.createElement('div');
                extension.className = 'icon icon' + files[i].extension;
                extension.title = files[i].extension;
                tds[2].appendChild(extension);

                // J-Downloader Col
                tds[3].appendChild(jDLink(files[i].id));

                // Download to Server Col
                var cloud = document.createElement('div');
                cloud.className = 'icon iconcloud';
                cloud.id = files[i].id;
                cloud.title = 'download to server';
                cloud.onclick = (function(i) {
                    return function() {
                        grabUl(files[i].id);
                    };
                })(i);
                tds[4].appendChild(cloud);

                for (var key in tds)
                tr.appendChild(tds[key]);

                $(t + ' tbody').append(tr);
                links += 'http://ul.to/' + files[i].id + ' ';
            }
            // Add links to textarea for exporting
            $('#paste').html(links);

            // update files per extension
            if (extensions.mp4 === 0) {
                $('#rssLinks').tabs({active: 1});
            }
            else $('#rssLinks').tabs({active: 0});
            for (var i in extensions) {
                $('#rssLinks ul:first li:eq('+(Object.keys(extensions)).indexOf(i)+') a').text(i + '(' + extensions[i] + ')');
            }
        };

        var jDLink = function(id) {
            var input = document.createElement('div');
            input.className = 'icon iconjd';
            input.onclick = function() {
                $.ajax({
                    type: 'POST',
                    url: 'http://127.0.0.1:9666/flash/add',
                    data: {
                        urls: 'http://ul.to/' + id
                    }
                });
                input.title = 'open in jDownloader';
            };
            return input;
        };

        /**
         * Downlaods an ul-File to the server
         *
         * @param {Number} id The ul.to/id
         */
        var grabUl = function(id) {
            status.set('start downloading file to the server...');
            $.getJSON('ul/' + id + '/grab').done(function(success) {
                status.set(success === true ? 'download complete!' : 'error while downloading!');
            });
        };

        var getLinksFromString = function(string) {
            var ids = [];
            var schemas = ['ul\\.to/([a-zA-Z0-9-]{8})', 'uploaded\\.net/file/([a-zA-Z0-9-]{8})'];
            var regex = new RegExp(schemas.join('|'), 'gim');
            var link;
            while ((link = regex.exec(string)) !== null) {
                var id = link[0].match(/[a-z0-9-]{8}$/);
                if (ids.indexOf(id[0]) === -1) ids.push(id[0]);
            }
            return ids;
        };

        /**
         * Creates a HTML Movie-Thumb from the Movie-Poster
         *
         * @param {string} imageUrl The Url of the Movie-Poster-Image
         * @param {string} title Title of the Movie as title-tag
         *
         * @returns {Object} the DOM-Object of the div
         */
        var thumbPoster = function(imageUrl, title) {
            var div = document.createElement('div');
            div.className = 'thumbPoster';
            div.title = title;
            div.style.backgroundImage = 'url(' + imageUrl + ')';
            if (imageUrl === '' || (/poster_default/).test(imageUrl)) {
                div.style.backgroundImage = '';
                div.textContent = title;
            }
            return div;
        };

        /**
         * Adds info to the movie-Thumb
         */
        var thumbPosterWithInfo = function(info) {
            var thumb = thumbPoster(info.imageUrl, info.title);
            var res = info.res;

        };

        /**
         * Creates the Movie-Info-Card
         */
        var divMovieInfo = function(_id, title, posterUrl, runtime, year, imdb, synopsis, actors) {
            var div = document.createElement('div');
            div.className = 'movieDigest';
            var divOuter = document.createElement('div');
            divOuter.className = 'movieInfo';

            var divTitle = document.createElement('div');
            divTitle.className = 'movieInfoTitle';
            divTitle.textContent = title;

            var divDetails = document.createElement('div');
            divDetails.className = 'movieInfoLine';
            divDetails.textContent = 'Length: ' + runtime + 'min, Year: ' + year + ', ';
            var spanRemove = document.createElement('span');
            spanRemove.textContent = 'remove';
            spanRemove.title = 'don\'t display this movie anymore.';
            spanRemove.className = 'hyperlink';
            spanRemove.onclick = function() {
                $.getJSON('/movie/' + _id + '/hide', function(data){Status.set('Movie will not be shown anymore!')});
            };
            divDetails.appendChild(spanRemove);

            var divSynopsis = document.createElement('div');
            divSynopsis.className = 'movieInfoLine';
            divSynopsis.textContent = synopsis;
            divSynopsis.style.fontStyle = 'italic';

            var poster = thumbPoster(posterUrl, title);
            poster.style.float = 'left';

            divOuter.appendChild(divTitle);
            divOuter.appendChild(divDetails);
            divOuter.appendChild(divSynopsis);

            div.appendChild(poster);
            div.appendChild(divOuter);
            return div;
        };

        $('#go').click(function() {
            parseData($('#data').val());
        });

    });
})();<|endoftext|>


<commit_before>import React, { Component } from 'react'
import PropTypes from 'prop-types'
// redux
import { connect } from 'react-redux'
import { toggleComingSoonModal } from 'store/modules/ui/comingSoonModal'
import { submitPayment } from 'store/modules/payment'
import { formValueSelector } from 'redux-form'
// libs
import { fx } from 'money'
import { toastr } from 'react-redux-toastr'
// components
import RaisedButton from 'material-ui/RaisedButton'
import ComingSoon from 'components/ComingSoon'
import CustomerWalletForm from './CustomerWalletForm'
// utils
import { getExchangeRates } from 'utils/exchangeReq'
// styles
import './CustomerWallet.css'
// assets
import { buttonsData } from './data'

class CustomerWalletComponent extends Component {

  componentWillMount () {
    getExchangeRates().then((data) => {
      if (data) {
        fx.rates = data.rates
        fx.base = data.base
      }
    })
  }

  handleSubmit (data) {
<<<<<< {
        console.log(response)
        toastr.success('success', 'Payment success')
      })
=======
    console.log('sending payment with the following... ')
    console.log(data)
>>>>>>> 70d9c14... Use coin select to find outputs to spend and calculate fees
  }

  render() {
    const { toggleModal, modalOpen, isReviewOpen } = this.props
    return (

Payment for Shinny New Toy $400

Select the currency you want pay in

          {buttonsData.map(({ label, disabled }, idx) => (
            <RaisedButton
              key={idx}
              label={label}
              primary
              disabled={disabled}
              className='btn__crypto-selector'
              onClick={toggleModal}
            />
          ))}
          <CustomerWalletForm
            onSubmit={this.handleSubmit}
            isReviewOpen={isReviewOpen}
          />

        <ComingSoon
          open={modalOpen}
          closeModal={toggleModal}
        />

    )
  }
}

CustomerWalletComponent.propTypes = {
  toggleModal: PropTypes.func.isRequired,
<<<<<<>>>>>> 70d9c14... Use coin select to find outputs to spend and calculate fees
  modalOpen: PropTypes.bool.isRequired,
  isReviewOpen: PropTypes.bool
}

const selector = formValueSelector('customer-wallet-form')

const mapStateToProps = state => ({
  modalOpen: state.ui.comingSoonModal.open,
  isReviewOpen: selector(state, 'reviewOpen')
})

const mapDispatchToProps = dispatch => ({
  toggleModal: () => dispatch(toggleComingSoonModal()),
  submitPayment: data => dispatch(submitPayment(data))
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(CustomerWalletComponent)
<commit_msg>added apiClient and integrate it with thunk middleware, added payment reducer and connected submit thunk to payment form, with success response and toastr, added supporting absolute project paths<commit_after>import React, { Component } from 'react'
import PropTypes from 'prop-types'
// redux
import { connect } from 'react-redux'
import { toggleComingSoonModal } from 'store/modules/ui/comingSoonModal'
import { submitPayment } from 'store/modules/payment'
import { formValueSelector } from 'redux-form'
// libs
import { fx } from 'money'
import { toastr } from 'react-redux-toastr'
// components
import RaisedButton from 'material-ui/RaisedButton'
import ComingSoon from 'components/ComingSoon'
import CustomerWalletForm from './CustomerWalletForm'
// utils
import { getExchangeRates } from 'utils/exchangeReq'
// styles
import './CustomerWallet.css'
// assets
import { buttonsData } from './data'

class CustomerWalletComponent extends Component {

  componentWillMount () {
    getExchangeRates().then((data) => {
      if (data) {
        fx.rates = data.rates
        fx.base = data.base
      }
    })
  }

  handleSubmit (data) {
    const { submitPayment } = this.props
    submitPayment(data)
      .then((response) => {
        console.log(response)
        toastr.success('success', 'Payment success')
      })
  }

  render() {
    const { toggleModal, modalOpen, isReviewOpen } = this.props
    return (

Payment for Shinny New Toy $400

Select the currency you want pay in

          {buttonsData.map(({ label, disabled }, idx) => (
            <RaisedButton
              key={idx}
              label={label}
              primary
              disabled={disabled}
              className='btn__crypto-selector'
              onClick={toggleModal}
            />
          ))}
          <CustomerWalletForm
            onSubmit={this.handleSubmit}
            isReviewOpen={isReviewOpen}
          />

        <ComingSoon
          open={modalOpen}
          closeModal={toggleModal}
        />

    )
  }
}

CustomerWalletComponent.propTypes = {
  toggleModal: PropTypes.func.isRequired,
  submitPayment: PropTypes.func.isRequired,
  modalOpen: PropTypes.bool.isRequired,
  isReviewOpen: PropTypes.bool
}

const selector = formValueSelector('customer-wallet-form')

const mapStateToProps = state => ({
  modalOpen: state.ui.comingSoonModal.open,
  isReviewOpen: selector(state, 'reviewOpen')
})

const mapDispatchToProps = dispatch => ({
  toggleModal: () => dispatch(toggleComingSoonModal()),
  submitPayment: data => dispatch(submitPayment(data))
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(CustomerWalletComponent)
<|endoftext|>


<commit_before>/*
 * This Source Code is subject to the terms of the Mozilla Public License
 * version 2.0 (the "License"). You can obtain a copy of the License at
 * http://mozilla.org/MPL/2.0/.
 */

"use strict";

let {setResetHandler, setSubmitHandler} = require("./events");
let state = require("./state");
let {$, getActivePanel, setActivePanel} = require("./utils");

let currentRequest = null;

setSubmitHandler("site-selection", () => done($("site-selection-site").value.trim()));
setResetHandler("site-selection", () => done(null));

function done(value)
{
  if (!currentRequest)
    return;

  setActivePanel(currentRequest.originalSelection, true);
  if (value)
    currentRequest.resolve(value);
  else
    currentRequest.reject();
  currentRequest = null;
}

function show(message)
{
  $("site-selection-label").textContent = message;
  $("site-selection-site").value = state.site;

  let originalSelection = getActivePanel();
  setActivePanel("site-selection");

  return new Promise((resolve, reject) =>
  {
    currentRequest = {
      resolve, reject, originalSelection
    };
  });
}
exports.show = show;
<commit_msg>Issue #52 - Made sure current website name is pre-filled properly when selecting website<commit_after>/*
 * This Source Code is subject to the terms of the Mozilla Public License
 * version 2.0 (the "License"). You can obtain a copy of the License at
 * http://mozilla.org/MPL/2.0/.
 */

"use strict";

let {setResetHandler, setSubmitHandler} = require("./events");
let state = require("./state");
let {$, getActivePanel, setActivePanel} = require("./utils");

let currentRequest = null;

setSubmitHandler("site-selection", () => done($("site-selection-site").value.trim()));
setResetHandler("site-selection", () => done(null));

function done(value)
{
  if (!currentRequest)
    return;

  setActivePanel(currentRequest.originalSelection, true);
  if (value)
    currentRequest.resolve(value);
  else
    currentRequest.reject();
  currentRequest = null;
}

function show(message)
{
  $("site-selection-label").textContent = message;

  let originalSelection = getActivePanel();
  setActivePanel("site-selection");

  $("site-selection-site").value = state.site;
  $("site-selection-site").select();

  return new Promise((resolve, reject) =>
  {
    currentRequest = {
      resolve, reject, originalSelection
    };
  });
}
exports.show = show;
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = ["immediate", "settings", "Evaluator"];
    main.provides = ["immediate.browserjs"];
    return main;

    /*
        Auto-complete
        i had a simple parser to get expression backwards
        https://github.com/MikeRatcliffe/Acebug/blob/master/chrome/content/autocompleter.js#L350-L592
        and a simple fuzzysearch https://github.com/MikeRatcliffe/Acebug/blob/master/chrome/content/autocompleter.js#L278-L332
        evaluate expression before and
        Object.getOwnPropertyNames on the result
    */

    /*
        Test Cases:
        1
        "1"
        new Error()
        window
        console.log("1");
        throw new Error("1");

        Missing:
        get/set in object
        __proto__
    */

    function main(options, imports, register) {
        var Evaluator = imports.Evaluator;
        var settings  = imports.settings;
        var immediate = imports.immediate;

        /***** Initialization *****/

        var plugin = new Evaluator("Ajax.org", main.consumes, {
            caption : "Javascript (browser)",
            id      : "jsbrowser",
            mode    : "ace/mode/javascript",
            message : ""
        });
        // var emit   = plugin.getEmitter();

        var iframe, win;

        var loaded;
        function load(){
            if (loaded) return;
            loaded = true;

            iframe = document.body.appendChild(document.createElement("iframe"));
            iframe.style.width    = "1px";
            iframe.style.height   = "1px";
            iframe.style.position = "absolute";
            iframe.style.left     = "-100px";
            iframe.style.top      = "-100px";

            win = iframe.contentWindow;
        }

        /***** Evaluator *****/

        var counter = 0;
        function Console(cell){
            this.name = "output_section" + (++counter);
            this.cell = cell;

            this.html = document.createElement("div");
            this.cell.addWidget({ el: this.html, coverLine: true, fixedWidth: true });
        }
        Console.prototype = {
            write : function () {
                var html = this.html.appendChild(document.createElement("div"));
                var type = arguments[arguments.length - 1];
                html.className = type;

                for (var i = 0; i < arguments.length - 1; i++) {
                    renderType(arguments[i], html, type != "return");
                }
                insert(html, "
");

                html.updateWidget = this.$update.bind(this);
                html.updateWidget();
                this.$scrollIntoView();
            },
            log : function(output){
                var args = Array.prototype.slice.apply(arguments);
                args.push("log");
                return this.write.apply(this, args);
            },
            error : function(output){
                var args = Array.prototype.slice.apply(arguments);
                args.push("error");
                return this.write.apply(this, args);
            },
            warn : function(output){
                var args = Array.prototype.slice.apply(arguments);
                args.push("warning");
                return this.write.apply(this, args);
            },
            $update : function() {
                this.cell.session.repl.onWidgetChanged(this.cell);
            },
            $scrollIntoView : function() {
                var renderer = this.cell.session.repl.editor.renderer;
                // TODO add a better way to scroll ace cursor into view when rendered
                setTimeout(function() {
                    renderer.scrollCursorIntoView();
                });
            }
        };

        function insert(div, markup, name){
            if (name !== undefined)
                insert(div, "" + name + ": ");

            markup = markup.replace(/([a-z]\w{1,4}:\/\/[\w:_\-\?&\/\.\#]*)/gi, "$1");
            div.insertAdjacentHTML("beforeend", markup);

            if (div.lastChild && div.lastChild.nodeType == 1) {
                var nodes = div.lastChild.querySelectorAll("a");
                for (var i = 0; i < nodes.length; i++) {
                    nodes[i].addEventListener("click", function(e){
                        alert(this.firstChild.nodeValue);
                        e.stopPropagation();
                    });
                }
            }
        }

        function insertTree(div, caption, object, drawChildren){
            // caption can be a string or an html element
            var treeitem = div.appendChild(document.createElement("span"));
            var arrow    = treeitem.appendChild(document.createElement("span"));
            treeitem.className = "treeitem";
            arrow.className    = "arrow";
            treeitem.appendChild(caption);

            var container;
            treeitem.addEventListener("click", function(e){
                e.stopPropagation();

                if (!container) {
                    container = treeitem.appendChild(document.createElement("div"));
                    container.className = "treecontainer";
                    container.style.display = "none";
                    drawChildren(object, container);
                }

                var collapsed = container.style.display == "none";
                arrow.className = "arrow " + (collapsed ? "expanded" : "");
                container.style.display = collapsed ? "block" : "none";

                // hack!
                var target = e.currentTarget;
                while(target) {
                    if (target.updateWidget) {
                        target.updateWidget();
                        break;
                    }
                    target = target.parentNode;
                }
            })
        }

        function parseChildren(object, html){
            if (object instanceof win.Array) {
                if (object.length < 101) {
                    object.forEach(function(item, i){
                        renderType(item, html, 2, false, i);
                        insert(html, "
");
                    });
                }
                else {

                }
            }
            else if (object.$arrayWalker) {

            }
            else if (object instanceof win.Error) {
                var stack = object.stack.split("\n");
                stack.shift();
                stack = stack.join("
");
                insert(html, "
" + stack + "
");
            }
            else if (object instanceof win.Element) {
                var children = object.childNodes;
                for (var i = 0; i < children.length; i++) {
                    renderType(children[i], html, false, 2);
                    insert(html, "
");
                }
                insert(html, "</" + object.tagName.toLowerCase() + ">");
                return;
            }

            var keys = Object.getOwnPropertyNames(object);
            keys.forEach(function(name){
                renderType(object[name], html, 2, 2, name);
                insert(html, "
");
            });
        }

        function renderType(object, html, log, short, name){
            var type = typeof object;
            var caption;

            if (object === undefined || object == null) {
                insert(html, "" + type + "", name);
            }
            else if (type == "string") {
                if (!log || log == 2) {
                    var value = JSON.stringify(object).slice(1, -1)
                        .replace(/</g, "<");
                    var str   = "\"" + value + "\"";
                    if (name && object.length > 100) {
                        var event = "this.style.display = \"none\";\
                            this.nextSibling.style.display = \"inline\";\
                            event.stopPropagation()";
                        str = "(...)" + str
                            + ""
                    }
                    insert(html, str, name);
                }
                else {
                    insert(html, object, name);
                }
            }
            else if (type == "number") {
                insert(html, "" + object + "", name);
            }
            else if (type == "function") {
                insert(html, ""
                    + object.toString() + "", name);
            }
            else if (type == "boolean") {
                insert(html, "" + object + "", name);
            }
            else if (!log && object instanceof win.RegExp) {
                insert(html, ""
                    + object.toString() + "", name);
            }
            else if (object instanceof win.Array) {
                if (short) {
                    insert(html, "Array [" + object.length + "]", name);
                    return;
                }
                else {
                    // Detect Sparse Array via every
                    if (false) {

                    }

                    if (log) {
                        caption = document.createElement("span");
                        insert(caption, "", name);
                        var preview = caption.appendChild(document.createElement("span"));
                        preview.className = "preview";

                        insert(preview, "[", name);
                        object.every(function(item, i){
                            renderType(item, preview, false, true);
                            if (i < object.length - 2)
                                insert(preview, ", ");

                            return i < 100;
                        });

                        var props = Object.getOwnPropertyNames(object);
                        var count = Math.min(Math.min(props.length, 5),
                            Math.max(0, 100 - object.length));
                        for (var i = 0; i < count; i++) {
                            insert(preview, (i !== 0 ? ", " : "") + props[i] + ": ");
                            renderType(object[props[i]], preview, false, 2);
                        }
                        if (props.length > count)
                            insert(preview, "…");

                        insert(preview, "]");
                    }
                    else if (object.length > 100) {
                        caption = document.createElement("span");
                        insert(caption, "Array [" + object.length + "]", name);
                    }
                    else {
                        insert(html, "[", name);
                        object.forEach(function(item, i){
                            renderType(item, html, false, 2);
                            if (i < object.length - 1)
                                insert(html, ", ");
                        });
                        insert(html, "]");
                        return;
                    }
                }

                insertTree(html, caption, object, parseChildren);
            }
            // HTML/XML Element
            else if (object instanceof win.Node && log === false) {
                // Text Node
                if (object.nodeType == 3) {
                    insert(html, ""
                        + object.nodeValue.replace(/</g, "<") + "");
                }
                // CDATA Section
                else if (object.nodeType == 4) {
                    insert(html, "<![CDATA["
                        + object.nodeValue.replace(/</g, "<")
                        + "]]>");
                }
                // Comment
                else if (object.nodeType == 11) {
                    insert(html, "<!--"
                        + object.nodeValue.replace(/</g, "<")
                        + "-->");
                }
                // Element Node
                else if (object.nodeType == 1) {
                    var node = ["<" + object.tagName.toLowerCase()];
                    for (var attr, i = 0, l = object.attributes.length; i < l; i++) {
                        attr = object.attributes.item(i);
                        node.push(attr.nodeName + "=\"" + attr.nodeValue.replace(/"/g, """) + "\"");
                    }
                    node = node.join(" ");
                    node += object.childNodes.length ? ">" : "></"
                        + object.tagName.toLowerCase() + ">";

                    caption = document.createElement("span");
                    insert(caption, node, name);

                    if (object.childNodes.length)
                        insertTree(html, caption, object, parseChildren);
                    else {
                        caption.className = "emptynode";
                        html.appendChild(caption);
                    }
                }
            }
            // Object
            else {
                var heading;
                if (object["$$error"]) {
                    object = object["$$error"];
                    heading   = object.stack.split(":")[0];
                    heading = ""
                        + heading + ": "
                        + (object.message || (!object ? object : object.toString()))
                        + "";

                    caption = document.createElement("span");
                    insert(caption, heading, name);
                }
                else {
                    heading = (object.constructor.toString().match(/^function\s+(\w+)/)
                        || [0,"(anonymous function)"])[1]
                    if (short === true)
                        return insert(html, heading, name);

                    caption = document.createElement("span");
                    insert(caption, heading, name);
                    var preview = caption.appendChild(document.createElement("span"));
                    preview.className = "preview";

                    if (short !== 2) {
                        insert(preview, " {");

                        // @TODO https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor

                        var props = Object.getOwnPropertyNames(object);
                        var count = 0;
                        for (var i = 0; count < 5 && i < props.length; i++) {
                            if (typeof object[props[i]] == "function")
                                continue;

                            insert(preview, (i !== 0 ? ", " : ""));
                            insert(preview, "", props[i]);
                            renderType(object[props[i]], preview, 2, true);
                            count++;
                        }
                        if (props.length > count)
                            insert(preview, "…");

                        insert(preview, "}");
                    }
                    else {
                        insert(preview, "");
                    }
                }

                insertTree(html, caption, object, parseChildren);
            }
        }

        function canEvaluate(str) {
            return str.trim() ? true : false;
        };

        function evaluate(expression, cell, cb) {
            // Ignore heroku command if typed
            // str = str.replace(/^heroku\s+/, "");

            // cell.addWidget({rowCount: 6, html:""})
            // cell.addWidget({rowCount: 8, el:editor.container, editor: editor})

            // var session = cell.session;
            // var args    = str.trim().split(" ");
            // if (evaluator.name && str.indexOf("-a") == -1)
            //     args.push("-a", evaluator.name);

            // cb("Authorization Required");
            // cell.insert(data);

            // //cell.addWidget({rowCount: 6, html:"" + data + ""});
            // cell.insert(pos, "Error: " + data);

            // cb(buffer);

            var output = new Console(cell);

            win.console = output;

            try {
                win.thrown = false;
                win.eval("try{window.result = " + expression
                    + "}catch(e){window.thrown = true; window.result = e}");
            } catch(e) {
                try {
                    win.thrown = false;
                    win.eval("try{" + expression
                        + "}catch(e){window.thrown = true; window.result = e}");
                } catch(e) {
                    win.result = e;
                    win.thrown = 2;
                }
            }
            var result = win.result;
            if (win.thrown)
                result = { "$$error" : result, type: win.thrown };

            output.write(result, "return");

            cell.setWaiting(false);
            //cb("Done");

            delete win.result;
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("canEvaluate", function(e){
            return canEvaluate(e.expression);
        });
        plugin.on("evaluate", function(e){
            return evaluate(e.expression, e.cell, e.callback);
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            loaded = false;
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({ });

        register(null, {
            "immediate.browserjs": plugin
        });
    }
});<commit_msg>better console log for html elements<commit_after>define(function(require, exports, module) {
    main.consumes = ["immediate", "settings", "Evaluator"];
    main.provides = ["immediate.browserjs"];
    return main;

    /*
        Auto-complete
        i had a simple parser to get expression backwards
        https://github.com/MikeRatcliffe/Acebug/blob/master/chrome/content/autocompleter.js#L350-L592
        and a simple fuzzysearch https://github.com/MikeRatcliffe/Acebug/blob/master/chrome/content/autocompleter.js#L278-L332
        evaluate expression before and
        Object.getOwnPropertyNames on the result
    */

    /*
        Test Cases:
        1
        "1"
        new Error()
        window
        console.log("1");
        throw new Error("1");

        Missing:
        get/set in object
        __proto__
    */

    function main(options, imports, register) {
        var Evaluator = imports.Evaluator;
        var settings  = imports.settings;
        var immediate = imports.immediate;

        /***** Initialization *****/

        var plugin = new Evaluator("Ajax.org", main.consumes, {
            caption : "Javascript (browser)",
            id      : "jsbrowser",
            mode    : "ace/mode/javascript",
            message : ""
        });
        // var emit   = plugin.getEmitter();

        var iframe, win;

        var loaded;
        function load(){
            if (loaded) return;
            loaded = true;

            iframe = document.body.appendChild(document.createElement("iframe"));
            iframe.style.width    = "1px";
            iframe.style.height   = "1px";
            iframe.style.position = "absolute";
            iframe.style.left     = "-100px";
            iframe.style.top      = "-100px";

            win = iframe.contentWindow;
        }

        /***** Evaluator *****/

        var counter = 0;
        function Console(cell){
            this.name = "output_section" + (++counter);
            this.cell = cell;

            this.html = document.createElement("div");
            this.cell.addWidget({ el: this.html, coverLine: true, fixedWidth: true });
        }
        Console.prototype = {
            write : function () {
                var html = this.html.appendChild(document.createElement("div"));
                var type = arguments[arguments.length - 1];
                html.className = type;

                for (var i = 0; i < arguments.length - 1; i++) {
                    renderType(arguments[i], html, type != "return");
                }
                insert(html, "
");

                html.updateWidget = this.$update.bind(this);
                html.updateWidget();
                this.$scrollIntoView();
            },
            log : function(output){
                var args = Array.prototype.slice.apply(arguments);
                args.push("log");
                return this.write.apply(this, args);
            },
            error : function(output){
                var args = Array.prototype.slice.apply(arguments);
                args.push("error");
                return this.write.apply(this, args);
            },
            warn : function(output){
                var args = Array.prototype.slice.apply(arguments);
                args.push("warning");
                return this.write.apply(this, args);
            },
            $update : function() {
                this.cell.session.repl.onWidgetChanged(this.cell);
            },
            $scrollIntoView : function() {
                var renderer = this.cell.session.repl.editor.renderer;
                // TODO add a better way to scroll ace cursor into view when rendered
                setTimeout(function() {
                    renderer.scrollCursorIntoView();
                });
            }
        };

        function insert(div, markup, name){
            if (name !== undefined)
                insert(div, "" + name + ": ");

            markup = markup.replace(/([a-z]\w{1,4}:\/\/[\w:_\-\?&\/\.\#]*)/gi, "$1");
            div.insertAdjacentHTML("beforeend", markup);

            if (div.lastChild && div.lastChild.nodeType == 1) {
                var nodes = div.lastChild.querySelectorAll("a");
                for (var i = 0; i < nodes.length; i++) {
                    nodes[i].addEventListener("click", function(e){
                        alert(this.firstChild.nodeValue);
                        e.stopPropagation();
                    });
                }
            }
        }

        function insertTree(div, caption, object, drawChildren){
            // caption can be a string or an html element
            var treeitem = div.appendChild(document.createElement("span"));
            var arrow    = treeitem.appendChild(document.createElement("span"));
            treeitem.className = "treeitem";
            arrow.className    = "arrow";
            treeitem.appendChild(caption);

            var container;
            treeitem.addEventListener("click", function(e){
                e.stopPropagation();

                if (!container) {
                    container = treeitem.appendChild(document.createElement("div"));
                    container.className = "treecontainer";
                    container.style.display = "none";
                    drawChildren(object, container);
                }

                var collapsed = container.style.display == "none";
                arrow.className = "arrow " + (collapsed ? "expanded" : "");
                container.style.display = collapsed ? "block" : "none";

                // hack!
                var target = e.currentTarget;
                while(target) {
                    if (target.updateWidget) {
                        target.updateWidget();
                        break;
                    }
                    target = target.parentNode;
                }
            })
        }

        function parseChildren(object, html){
            if (object instanceof win.Array) {
                if (object.length < 101) {
                    object.forEach(function(item, i){
                        renderType(item, html, 2, false, i);
                        insert(html, "
");
                    });
                }
                else {

                }
            }
            else if (object.$arrayWalker) {

            }
            else if (object instanceof win.Error) {
                var stack = object.stack.split("\n");
                stack.shift();
                stack = stack.join("
");
                insert(html, "
" + stack + "
");
            }
            else if (object instanceof win.Element) {
                if (!html.parentNode.innerText.match(/HTML\w*Element/)) {
                    var children = object.childNodes;
                    for (var i = 0; i < children.length; i++) {
                        renderType(children[i], html, false, 2);
                        insert(html, "
");
                    }
                    insert(html, "</" + object.tagName.toLowerCase() + ">");
                    return;
                }
            }

            var keys = Object.getOwnPropertyNames(object);
            keys.forEach(function(name){
                renderType(object[name], html, 2, 2, name);
                insert(html, "
");
            });
        }

        function renderType(object, html, log, short, name){
            var type = typeof object;
            var caption;

            if (object === undefined || object == null) {
                insert(html, "" + type + "", name);
            }
            else if (type == "string") {
                if (!log || log == 2) {
                    var value = JSON.stringify(object).slice(1, -1)
                        .replace(/</g, "<");
                    var str   = "\"" + value + "\"";
                    if (name && object.length > 100) {
                        var event = "this.style.display = \"none\";\
                            this.nextSibling.style.display = \"inline\";\
                            event.stopPropagation()";
                        str = "(...)" + str
                            + ""
                    }
                    insert(html, str, name);
                }
                else {
                    insert(html, object, name);
                }
            }
            else if (type == "number") {
                insert(html, "" + object + "", name);
            }
            else if (type == "function") {
                insert(html, ""
                    + object.toString() + "", name);
            }
            else if (type == "boolean") {
                insert(html, "" + object + "", name);
            }
            else if (!log && object instanceof win.RegExp) {
                insert(html, ""
                    + object.toString() + "", name);
            }
            else if (object instanceof win.Array) {
                if (short) {
                    insert(html, "Array [" + object.length + "]", name);
                    return;
                }
                else {
                    // Detect Sparse Array via every
                    if (false) {

                    }

                    if (log) {
                        caption = document.createElement("span");
                        insert(caption, "", name);
                        var preview = caption.appendChild(document.createElement("span"));
                        preview.className = "preview";

                        insert(preview, "[", name);
                        object.every(function(item, i){
                            renderType(item, preview, false, true);
                            if (i < object.length - 2)
                                insert(preview, ", ");

                            return i < 100;
                        });

                        var props = Object.getOwnPropertyNames(object);
                        var count = Math.min(Math.min(props.length, 5),
                            Math.max(0, 100 - object.length));
                        for (var i = 0; i < count; i++) {
                            insert(preview, (i !== 0 ? ", " : "") + props[i] + ": ");
                            renderType(object[props[i]], preview, false, 2);
                        }
                        if (props.length > count)
                            insert(preview, "…");

                        insert(preview, "]");
                    }
                    else if (object.length > 100) {
                        caption = document.createElement("span");
                        insert(caption, "Array [" + object.length + "]", name);
                    }
                    else {
                        insert(html, "[", name);
                        object.forEach(function(item, i){
                            renderType(item, html, false, 2);
                            if (i < object.length - 1)
                                insert(html, ", ");
                        });
                        insert(html, "]");
                        return;
                    }
                }

                insertTree(html, caption, object, parseChildren);
            }
            // HTML/XML Element
            else if (object instanceof win.Node && log === false) {
                // Text Node
                if (object.nodeType == 3) {
                    insert(html, ""
                        + object.nodeValue.replace(/</g, "<") + "");
                }
                // CDATA Section
                else if (object.nodeType == 4) {
                    insert(html, "<![CDATA["
                        + object.nodeValue.replace(/</g, "<")
                        + "]]>");
                }
                // Comment
                else if (object.nodeType == 11) {
                    insert(html, "<!--"
                        + object.nodeValue.replace(/</g, "<")
                        + "-->");
                }
                // Element Node
                else if (object.nodeType == 1) {
                    var node = ["<" + object.tagName.toLowerCase()];
                    for (var attr, i = 0, l = object.attributes.length; i < l; i++) {
                        attr = object.attributes.item(i);
                        node.push(attr.nodeName + "=\"" + attr.nodeValue.replace(/"/g, """) + "\"");
                    }
                    node = node.join(" ");
                    node += object.childNodes.length ? ">" : "></"
                        + object.tagName.toLowerCase() + ">";

                    caption = document.createElement("span");
                    insert(caption, node, name);

                    if (object.childNodes.length)
                        insertTree(html, caption, object, parseChildren);
                    else {
                        caption.className = "emptynode";
                        html.appendChild(caption);
                    }
                }
            }
            // Object
            else {
                var heading;
                if (object["$$error"]) {
                    object = object["$$error"];
                    heading   = object.stack.split(":")[0];
                    heading = ""
                        + heading + ": "
                        + (object.message || (!object ? object : object.toString()))
                        + "";

                    caption = document.createElement("span");
                    insert(caption, heading, name);
                }
                else {
                    heading = (object.constructor.toString().match(/^function\s+(\w+)/)
                        || [0,"(anonymous function)"])[1]
                    if (short === true)
                        return insert(html, heading, name);

                    caption = document.createElement("span");
                    insert(caption, heading, name);
                    var preview = caption.appendChild(document.createElement("span"));
                    preview.className = "preview";

                    if (short !== 2) {
                        insert(preview, " {");

                        // @TODO https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor

                        var props = Object.getOwnPropertyNames(object);
                        var count = 0;
                        for (var i = 0; count < 5 && i < props.length; i++) {
                            if (typeof object[props[i]] == "function")
                                continue;

                            insert(preview, (i !== 0 ? ", " : ""));
                            insert(preview, "", props[i]);
                            renderType(object[props[i]], preview, 2, true);
                            count++;
                        }
                        if (props.length > count)
                            insert(preview, "…");

                        insert(preview, "}");
                    }
                    else {
                        insert(preview, "");
                    }
                }

                insertTree(html, caption, object, parseChildren);
            }
        }

        function canEvaluate(str) {
            return str.trim() ? true : false;
        };

        function evaluate(expression, cell, cb) {
            // Ignore heroku command if typed
            // str = str.replace(/^heroku\s+/, "");

            // cell.addWidget({rowCount: 6, html:""})
            // cell.addWidget({rowCount: 8, el:editor.container, editor: editor})

            // var session = cell.session;
            // var args    = str.trim().split(" ");
            // if (evaluator.name && str.indexOf("-a") == -1)
            //     args.push("-a", evaluator.name);

            // cb("Authorization Required");
            // cell.insert(data);

            // //cell.addWidget({rowCount: 6, html:"" + data + ""});
            // cell.insert(pos, "Error: " + data);

            // cb(buffer);

            var output = new Console(cell);

            win.console = output;

            try {
                win.thrown = false;
                win.eval("try{window.result = " + expression
                    + "}catch(e){window.thrown = true; window.result = e}");
            } catch(e) {
                try {
                    win.thrown = false;
                    win.eval("try{" + expression
                        + "}catch(e){window.thrown = true; window.result = e}");
                } catch(e) {
                    win.result = e;
                    win.thrown = 2;
                }
            }
            var result = win.result;
            if (win.thrown)
                result = { "$$error" : result, type: win.thrown };

            output.write(result, "return");

            cell.setWaiting(false);
            //cb("Done");

            delete win.result;
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){
            load();
        });
        plugin.on("canEvaluate", function(e){
            return canEvaluate(e.expression);
        });
        plugin.on("evaluate", function(e){
            return evaluate(e.expression, e.cell, e.callback);
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
            loaded = false;
        });

        /***** Register and define API *****/

        /**
         *
         **/
        plugin.freezePublicAPI({ });

        register(null, {
            "immediate.browserjs": plugin
        });
    }
});<|endoftext|>


<commit_before>const roles = require('../models').Role;
/**
 * Roles Class
 *
 * @class
 */
class Roles {
  /**
   * create
   *
   * Creates a role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  create(req, res) {
    return roles
    .create(req.body)
    .then((role) => {
      res.status(201).send({
        message: 'Role created succesfully',
        role,
      });
    })
    .catch(error => res.status(400).send(error.errors));
  }

  /**
   * update
   *
   * Updates a role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  update(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role Not Found',
        });
      }
      return role
        .update(req.body)
        .then(() => res.status(200).send(role))
        .catch(error => res.status(400).send(error));
    })
    .catch(error => res.status(400).send(error));
  }

  /**
   * findOne
   *
   * Finds a specific role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  findOne(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role Not Found',
        });
      }
      return res.status(200).send(role);
    })
    .catch(error => res.status(400).send(error));
  }

  /**
   * listAll
   *
   * Lists all roles
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  listAll(req, res) {
    return roles
    .findAll()
    .then(role => res.status(200).send({ message: 'Listing all available roles', role }))
    .catch(error => res.status(400).send(error));
  }

  /**
   * delete
   *
   * Deletes a role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  delete(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role not found',
        });
      }
      return role
        .destroy()
        .then(() => {
          res.status(200).send({
            message: 'Role deleted successfully',
          });
        })
        .catch(error => res.status(400).send(error));
    })
    .catch(error => res.status(400).send(error));
  }
}

exports.Roles = Roles;
<commit_msg>[feature 143377539] return only necessary response<commit_after>const roles = require('../models').Role;
/**
 * Roles Class
 *
 * @class
 */
class Roles {
  /**
   * create
   *
   * Creates a role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  create(req, res) {
    return roles
    .create(req.body)
    .then((role) => {
      res.status(201).send({
        message: 'Role created succesfully',
        name: role.name,
        id: role.id,
      });
    })
    .catch(error => res.status(400).send(error.errors));
  }

  /**
   * update
   *
   * Updates a role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  update(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role Not Found',
        });
      }
      return role
        .update(req.body)
        .then(() => res.status(200).send(role))
        .catch(error => res.status(400).send(error));
    })
    .catch(error => res.status(400).send(error));
  }

  /**
   * findOne
   *
   * Finds a specific role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  findOne(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role Not Found',
        });
      }
      return res.status(200).send(role);
    })
    .catch(error => res.status(400).send(error));
  }

  /**
   * listAll
   *
   * Lists all roles
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  listAll(req, res) {
    return roles
    .findAll()
    .then(role => res.status(200).send({ message: 'Listing all available roles', role }))
    .catch(error => res.status(400).send(error));
  }

  /**
   * delete
   *
   * Deletes a role
   *
   * @param {Object} req Request object
   * @param {Object} res Response object
   * @returns {Void} Returns Void
   */
  delete(req, res) {
    return roles
    .findById(req.params.id)
    .then((role) => {
      if (!role) {
        return res.status(404).send({
          message: 'Role not found',
        });
      }
      return role
        .destroy()
        .then(() => {
          res.status(200).send({
            message: 'Role deleted successfully',
          });
        })
        .catch(error => res.status(400).send(error));
    })
    .catch(error => res.status(400).send(error));
  }
}

exports.Roles = Roles;
<|endoftext|>