<commit_before>describe('su-modal', function () {
  let tag
  let spyOnShow = sinon.spy()
  let spyOnHide = sinon.spy()
  let mount = opts => {
    tag = riot.mount('su-modal', opts)[0]
    tag.on('show', spyOnShow)
      .on('hide', spyOnHide)
  }

  beforeEach(function () {
    this.clock = sinon.useFakeTimers()
  })

  afterEach(function () {
    spyOnShow.reset()
    spyOnHide.reset()
    this.clock.restore()
    tag.unmount()
  })

  it('is mounted', function () {
    $('body').append('<su-modal>modal</su-modal>')
    mount()
    tag.isMounted.should.be.true
  })

  it('opens/closes modal and triggers open/close event', function () {
    $('body').append('<su-modal>modal</su-modal>')
    mount({
      modal: {
        buttons: [{
          text: 'Ok',
        }]
      }
    })
    $('su-modal').is(':visible').should.equal(false)

    tag.show()
    spyOnShow.should.have.been.calledOnce
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    $('su-modal .ui.button:first').click()
    spyOnHide.should.have.been.calledOnce
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(false)
  })

  it('dimmer close', function () {
    $('body').append('<su-modal>modal</su-modal>')
    mount()
    $('su-modal').is(':visible').should.equal(false)

    tag.show()
    spyOnShow.should.have.been.calledOnce
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    $('su-modal').click()
    spyOnHide.should.have.been.calledOnce
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(false)
  })

  it('buttons', function () {
    $('body').append('<su-modal>modal</su-modal>')
    const modal = {
      buttons: [{
        text: 'Ok',
        type: 'primary',
        icon: 'checkmark'
      }, {
        text: 'Cancel'
      }]
    }
    mount({ modal: modal })
    tag.show()
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    const btn_ok = $('su-modal .ui.button:first')
    btn_ok.hasClass('labeled').should.equal(true)
    btn_ok.hasClass('icon').should.equal(true)
    btn_ok.find('.icon').length.should.equal(1)
    btn_ok.text().trim().should.equal(modal.buttons[0].text)
    btn_ok.hasClass(modal.buttons[0].type).should.equal(true)
    btn_ok.find(`.${modal.buttons[0].icon}`).length.should.equal(1)

    const btn_cancel = $('su-modal .ui.button:last')
    btn_cancel.hasClass('labeled').should.equal(false)
    btn_cancel.hasClass('icon').should.equal(false)
    btn_cancel.find('.icon').length.should.equal(0)
    btn_cancel.text().trim().should.equal(modal.buttons[1].text)
  })

  it('header', function () {
    $('body').append('<su-modal>modal</su-modal>')
    const modal = {
      heading: 'modal header'
    }
    mount({ modal: modal })
    tag.show()
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    const header = $('su-modal .ui.header')
    header.hasClass('icon').should.equal(false)
    header.text().trim(modal.heading)
  })

  it('icon header', function () {
    $('body').append('<su-modal>modal</su-modal>')
    const modal = {
      heading: {
        icon: 'archive',
        text: 'modal header'
      }
    }
    mount({ modal: modal })
    tag.show()
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    const header = $('su-modal .ui.header')
    header.hasClass('icon').should.equal(true)
    header.text().trim(modal.heading.text)
  })

  it('image content', function () {
    $('body').append(`
      <su-modal>

Default Profile Image

We've found the following gravatar image associated with
            your e-mail address.

Is it okay to use this photo?

      </su-modal>
    `)
    const modal = {
    }
    mount({ modal: modal })
    tag.show()
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    const content = $('su-modal .content')
    content.hasClass('image').should.equal(true)
  })

  it('full screen', function () {
    $('body').append('<su-modal>modal</su-modal>')
    mount({ class: 'fullscreen' })
    tag.show()
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    $('su-modal i.close.icon').length.should.equal(1)
  })
})
<commit_msg>Add test for su-modal<commit_after>describe('su-modal', function () {
  let tag
  let spyOnShow = sinon.spy()
  let spyOnHide = sinon.spy()
  let mount = opts => {
    tag = riot.mount('su-modal', opts)[0]
    tag.on('show', spyOnShow)
      .on('hide', spyOnHide)
  }

  beforeEach(function () {
    this.clock = sinon.useFakeTimers()
  })

  afterEach(function () {
    spyOnShow.reset()
    spyOnHide.reset()
    this.clock.restore()
    tag.unmount()
  })

  it('is mounted', function () {
    $('body').append('<su-modal>modal</su-modal>')
    mount()
    tag.isMounted.should.be.true
  })

  it('opens/closes modal and triggers open/close event', function () {
    $('body').append('<su-modal>modal</su-modal>')
    mount({
      modal: {
        buttons: [{
          text: 'Ok',
        }]
      }
    })
    $('su-modal').is(':visible').should.equal(false)

    tag.show()
    spyOnShow.should.have.been.calledOnce
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    $('su-modal .ui.button:first').click()
    spyOnHide.should.have.been.calledOnce
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(false)
  })

  it('dimmer close', function () {
    $('body').append('<su-modal>modal</su-modal>')
    mount()
    $('su-modal').is(':visible').should.equal(false)

    tag.show()
    spyOnShow.should.have.been.calledOnce
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    $('su-modal').click()
    spyOnHide.should.have.been.calledOnce
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(false)
  })

  it('buttons', function () {
    $('body').append('<su-modal>modal</su-modal>')
    const modal = {
      buttons: [{
        text: 'Ok',
        type: 'primary',
        icon: 'checkmark'
      }, {
        text: 'Cancel'
      }]
    }
    mount({ modal: modal })
    tag.show()
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    const btn_ok = $('su-modal .ui.button:first')
    btn_ok.hasClass('labeled').should.equal(true)
    btn_ok.hasClass('icon').should.equal(true)
    btn_ok.find('.icon').length.should.equal(1)
    btn_ok.text().trim().should.equal(modal.buttons[0].text)
    btn_ok.hasClass(modal.buttons[0].type).should.equal(true)
    btn_ok.find(`.${modal.buttons[0].icon}`).length.should.equal(1)

    const btn_cancel = $('su-modal .ui.button:last')
    btn_cancel.hasClass('labeled').should.equal(false)
    btn_cancel.hasClass('icon').should.equal(false)
    btn_cancel.find('.icon').length.should.equal(0)
    btn_cancel.text().trim().should.equal(modal.buttons[1].text)
  })

  it('header', function () {
    $('body').append('<su-modal>modal</su-modal>')
    const modal = {
      heading: 'modal header'
    }
    mount({ modal: modal })
    tag.show()
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    const header = $('su-modal .ui.header')
    header.hasClass('icon').should.equal(false)
    header.text().trim(modal.heading)
  })

  it('icon header', function () {
    $('body').append('<su-modal>modal</su-modal>')
    const modal = {
      heading: {
        icon: 'archive',
        text: 'modal header'
      }
    }
    mount({ modal: modal })
    tag.show()
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    const header = $('su-modal .ui.header')
    header.hasClass('icon').should.equal(true)
    header.text().trim(modal.heading.text)
  })

  it('image content', function () {
    $('body').append(`
      <su-modal>

Default Profile Image

We've found the following gravatar image associated with
            your e-mail address.

Is it okay to use this photo?

      </su-modal>
    `)
    const modal = {
    }
    mount({ modal: modal })
    tag.show()
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    const content = $('su-modal .content')
    content.hasClass('image').should.equal(true)
  })

  it('full screen', function () {
    $('body').append('<su-modal>modal</su-modal>')
    mount({ class: 'fullscreen' })
    tag.show()
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(true)

    $('su-modal i.close.icon').length.should.equal(1)

    $('su-modal i.close.icon').click()
    spyOnHide.should.have.been.calledOnce
    this.clock.tick(310)
    $('su-modal').is(':visible').should.equal(false)
  })
})
<|endoftext|>


<commit_before>const { getDavIdIconUrl } = require('../../server/lib/davIdIcon.js');
const { URL } = require('url');
const dummyDavId = '0xdfddfdfdfdfdfdfdfdfdfdfdfdfddfdfdfdfdfdd';

describe('getDavIdIconUrl()', () => {
  test('returns an absolute URL', () => {
    expect(
      checkIfAbsoluteURL(getDavIdIconUrl(dummyDavId))
    ).toBeTruthy();
  });

  const checkIfAbsoluteURL = (url) => {
    try {
      new URL(url);
      return true;
    } catch (err) {
      return false;
    }
  };
});
<commit_msg>Test the url getDavIdIconUrl(davId) returns contains the davId using the indexOf method (on the URL that is returned from the function). Issue #96<commit_after>const { getDavIdIconUrl } = require('../../server/lib/davIdIcon.js');
const { URL } = require('url');
const dummyDavId = '0xdfddfdfdfdfdfdfdfdfdfdfdfdfddfdfdfdfdfdd';

describe('getDavIdIconUrl()', () => {
  test('returns an absolute URL', () => {
    expect(
      checkIfAbsoluteURL(getDavIdIconUrl(dummyDavId))
    ).toBeTruthy();
  });

  const checkIfAbsoluteURL = (url) => {
    try {
      new URL(url);
      return true;
    } catch (err) {
      return false;
    }
  };

  test('Return contains the davID within it options',() => {
    expect(
      checkIfReturnDavId(getDavIdIconUrl(dummyDavId))
    ).toBeTruthy();
  });

  const checkIfReturnDavId = (url) => {
    if (url.toLowerCase().indexOf(dummyDavId) >= 0) {
      return true;
    } else {
      return false;
    }
  }
});
<|endoftext|>


<commit_before>angular.module('anol.featureinfo')
/**
 * @ngdoc directive
 * @name anol.featureinfo.directive:anolFeatureInfo
 *
 * @restrict A
 * @requires $compile
 * @requires $http
 * @required $window
 * @requires anol.map.MapService
 * @requires anol.map.LayersService
 * @requires anol.map.ControlsService
 *
 * @description
 * Makes GetFeatureInfo request on all non vector layers with 'featureinfo' property
 * and show result if not empty depending on 'target' specified in 'featureinfo'
 *
 * @param {function} customTargetFilled Callback called after featureinfo result added to custom element
 * @param {string} templateUrl Url to template to use instead of default one
 *
 * Layer property **featureinfo** - {Object} - Contains properties:
 * - **target** - {string} - Target for featureinfo result. ('_blank', '_popup', [element-id])
 */
.directive('anolFeatureInfo', [
    '$compile', '$http', '$window', 'MapService', 'LayersService', 'ControlsService',
    function($compile, $http, $window, MapService, LayersService, ControlsService) {
    return {
        restrict: 'A',
        require: '?^anolMap',
        replace: true,
        scope: {
            customTargetFilled: '&'
        },
        templateUrl: function(tElement, tAttrs) {
            var defaultUrl = 'src/modules/featureinfo/templates/popup.html';
            return tAttrs.templateUrl || defaultUrl;
        },
        link: {
            pre: function(scope, element) {
                $compile(element.contents())(scope);

                scope.map = MapService.getMap();
                // get callback from wrapper function
                scope.customTargetCallback = scope.customTargetFilled();
                var view = scope.map.getView();
                var popupContent = element.find('.anol-popup-content');
                var popupOverlay = new ol.Overlay({
                    element: element.context,
                    autoPan: true,
                    autoPanAnimation: {
                        duration: 250
                    }
                });

                scope.map.addOverlay(popupOverlay);

                scope.close = function() {
                    element.css('display', 'none');
                };

                scope.handleClick = function(evt) {
                    var viewResolution = view.getResolution();
                    var coordinate = evt.coordinate;
                    var divTargetCleared = false;

                    element.css('display', 'none');
                    popupContent.empty();

                    angular.forEach(LayersService.layers, function(layer) {
                        var layers = [layer];
                        if(layer instanceof anol.layer.Group) {
                            layers = layer.layers;
                        }
                        angular.forEach(layers, function(layer) {
                            if(!layer.getVisible()) {
                                return;
                            }
                            if(layer.olLayer instanceof ol.layer.Vector) {
                                return;
                            }
                            if(!layer.featureinfo) {
                                return;
                            }

                            var params = layer.olLayer.getSource().getParams();
                            var queryLayers = params.layers || params.LAYERS;
                            queryLayers = queryLayers.split(',');

                            angular.forEach(queryLayers, function(queryLayer) {
                                var url = layer.olLayer.getSource().getGetFeatureInfoUrl(
                                    coordinate, viewResolution, view.getProjection(),
                                    {
                                        'INFO_FORMAT': 'text/html',
                                        'QUERY_LAYERS': queryLayer

                                    }
                                );
                                if(angular.isDefined(url)) {
                                    $http.get(url).success(function(response) {
                                        if(angular.isString(response) && response !== '' && !response.startsWith('<?xml')) {
                                            var iframe;
                                            if(layer.featureinfo.target !== '_blank') {
                                                iframe = $('');
                                            }
                                            switch(layer.featureinfo.target) {
                                                case '_blank':
                                                    $window.open(url, '_blank');
                                                break;
                                                case '_popup':
                                                    popupContent.append(iframe);
                                                    if(element.css('display') === 'none') {
                                                        element.css('display', '');
                                                        popupOverlay.setPosition(coordinate);
                                                    }
                                                break;
                                                default:
                                                    var target = $(layer.featureinfo.target);
                                                    if(divTargetCleared === false) {
                                                        target.empty();
                                                        divTargetCleared = true;
                                                    }
                                                    target.append(iframe);
                                                    if(angular.isFunction(scope.customTargetCallback)) {
                                                        scope.customTargetCallback();
                                                    }
                                                break;
                                            }
                                        }
                                    });
                                }
                            });
                        });
                    });
                };
            },
            post: function(scope) {
                var handlerKey;
                var control = new anol.control.Control({
                    subordinate: true,
                    olControl: null
                });
                control.onDeactivate(function() {
                    scope.map.unByKey(handlerKey);
                });
                control.onActivate(function() {
                    handlerKey = scope.map.on('singleclick', scope.handleClick, this);
                });

                control.activate();

                ControlsService.addControl(control);
            }
        }
    };
}]);
<commit_msg>Only create iframes when showing featureinfo result in popup<commit_after>angular.module('anol.featureinfo')
/**
 * @ngdoc directive
 * @name anol.featureinfo.directive:anolFeatureInfo
 *
 * @restrict A
 * @requires $compile
 * @requires $http
 * @required $window
 * @requires anol.map.MapService
 * @requires anol.map.LayersService
 * @requires anol.map.ControlsService
 *
 * @description
 * Makes GetFeatureInfo request on all non vector layers with 'featureinfo' property
 * and show result if not empty depending on 'target' specified in 'featureinfo'
 *
 * @param {function} customTargetFilled Callback called after featureinfo result added to custom element
 * @param {string} templateUrl Url to template to use instead of default one
 *
 * Layer property **featureinfo** - {Object} - Contains properties:
 * - **target** - {string} - Target for featureinfo result. ('_blank', '_popup', [element-id])
 */
.directive('anolFeatureInfo', [
    '$compile', '$http', '$window', 'MapService', 'LayersService', 'ControlsService',
    function($compile, $http, $window, MapService, LayersService, ControlsService) {
    return {
        restrict: 'A',
        require: '?^anolMap',
        replace: true,
        scope: {
            customTargetFilled: '&'
        },
        templateUrl: function(tElement, tAttrs) {
            var defaultUrl = 'src/modules/featureinfo/templates/popup.html';
            return tAttrs.templateUrl || defaultUrl;
        },
        link: {
            pre: function(scope, element) {
                $compile(element.contents())(scope);

                scope.map = MapService.getMap();
                // get callback from wrapper function
                scope.customTargetCallback = scope.customTargetFilled();
                var view = scope.map.getView();
                var popupContent = element.find('.anol-popup-content');
                var popupOverlay = new ol.Overlay({
                    element: element.context,
                    autoPan: true,
                    autoPanAnimation: {
                        duration: 250
                    }
                });

                scope.map.addOverlay(popupOverlay);

                scope.close = function() {
                    element.css('display', 'none');
                };

                scope.handleClick = function(evt) {
                    var viewResolution = view.getResolution();
                    var coordinate = evt.coordinate;
                    var divTargetCleared = false;

                    element.css('display', 'none');
                    popupContent.empty();

                    angular.forEach(LayersService.layers, function(layer) {
                        var layers = [layer];
                        if(layer instanceof anol.layer.Group) {
                            layers = layer.layers;
                        }
                        angular.forEach(layers, function(layer) {
                            if(!layer.getVisible()) {
                                return;
                            }
                            if(layer.olLayer instanceof ol.layer.Vector) {
                                return;
                            }
                            if(!layer.featureinfo) {
                                return;
                            }

                            var params = layer.olLayer.getSource().getParams();
                            var queryLayers = params.layers || params.LAYERS;
                            queryLayers = queryLayers.split(',');

                            angular.forEach(queryLayers, function(queryLayer) {
                                var url = layer.olLayer.getSource().getGetFeatureInfoUrl(
                                    coordinate, viewResolution, view.getProjection(),
                                    {
                                        'INFO_FORMAT': 'text/html',
                                        'QUERY_LAYERS': queryLayer

                                    }
                                );
                                if(angular.isDefined(url)) {
                                    $http.get(url).success(function(response) {
                                        if(angular.isString(response) && response !== '' && !response.startsWith('<?xml')) {
                                            var iframe;
                                            if(layer.featureinfo.target === '_popup') {
                                                iframe = $('');
                                            }
                                            switch(layer.featureinfo.target) {
                                                case '_blank':
                                                    $window.open(url, '_blank');
                                                break;
                                                case '_popup':
                                                    popupContent.append(iframe);
                                                    if(element.css('display') === 'none') {
                                                        element.css('display', '');
                                                        popupOverlay.setPosition(coordinate);
                                                    }
                                                break;
                                                default:
                                                    var target = $(layer.featureinfo.target);
                                                    if(divTargetCleared === false) {
                                                        target.empty();
                                                        divTargetCleared = true;
                                                    }
                                                    target.append(iframe);
                                                    if(angular.isFunction(scope.customTargetCallback)) {
                                                        scope.customTargetCallback();
                                                    }
                                                break;
                                            }
                                        }
                                    });
                                }
                            });
                        });
                    });
                };
            },
            post: function(scope) {
                var handlerKey;
                var control = new anol.control.Control({
                    subordinate: true,
                    olControl: null
                });
                control.onDeactivate(function() {
                    scope.map.unByKey(handlerKey);
                });
                control.onActivate(function() {
                    handlerKey = scope.map.on('singleclick', scope.handleClick, this);
                });

                control.activate();

                ControlsService.addControl(control);
            }
        }
    };
}]);
<|endoftext|>


<commit_before>'use strict';

const test = require('tape');
const sinon = require('sinon');
const oddcast = require('oddcast');
const awsTransport = require('../lib/oddcast-aws-transport');

const ACCESS_KEY_ID = process.env.ACCESS_KEY_ID;
const SECRET_ACCESS_KEY = process.env.SECRET_ACCESS_KEY;
const REGION = process.env.REGION;
const TOPIC_ARN = process.env.TOPIC_ARN;
const QUEUE_URL = process.env.QUEUE_URL;

if (!ACCESS_KEY_ID) {
	console.error('ACCESS_KEY_ID env variable is required.');
	process.exit(1);
}
if (!SECRET_ACCESS_KEY) {
	console.error('SECRET_ACCESS_KEY env variable is required.');
	process.exit(1);
}
if (!REGION) {
	console.error('REGION env variable is required.');
	process.exit(1);
}
if (!TOPIC_ARN) {
	console.error('TOPIC_ARN env variable is required.');
	process.exit(1);
}
if (!QUEUE_URL) {
	console.error('QUEUE_URL env variable is required.');
	process.exit(1);
}

(function commandOriginatedMessage() {
	const paylaod = {
		id: 'command_success'
	};

	const readTransport = awsTransport.sqsCommandListener({
		queueUrl: QUEUE_URL,
		region: REGION,
		accessKeyId: ACCESS_KEY_ID,
		secretAccessKey: SECRET_ACCESS_KEY
	});

	const writeTransport = awsTransport.sqsCommandEmitter({
		queueUrl: QUEUE_URL,
		region: REGION,
		accessKeyId: ACCESS_KEY_ID,
		secretAccessKey: SECRET_ACCESS_KEY
	});

	const receiveChannel = oddcast.commandChannel();
	const sendChannel = oddcast.commandChannel();

	const readErrorHandler = sinon.spy();
	const writeErrorHandler = sinon.spy();

	const messageHandler = sinon.spy();
	const messageDeletedHandler = sinon.spy();

	test('before all commandOriginatedMessage', function (t) {
		readTransport.on('error', readErrorHandler);
		writeTransport.on('error', writeErrorHandler);

		readTransport.on('error', function () {
			t.end();
		});
		writeTransport.on('error', function () {
			t.end();
		});

		readTransport.on('message:deleted', messageDeletedHandler);
		readTransport.on('message:deleted', function () {
			readTransport.close();
		});

		receiveChannel.use({role: 'test'}, readTransport);
		sendChannel.use({role: 'test'}, writeTransport);

		// Setup the receive handler.
		receiveChannel.receive({role: 'test', cmd: 'command:message'}, messageHandler);

		readTransport.on('close', function () {
			t.end();
		});

		// Send the command.
		sendChannel.send({role: 'test', cmd: 'command:message'}, paylaod);
	});

	test('read error handler is not called', function (t) {
		t.plan(1);
		t.equal(readErrorHandler.callCount, 0);
	});

	test('write error handler is not called', function (t) {
		t.plan(1);
		t.equal(writeErrorHandler.callCount, 0);
	});

	test('got message paylaod', function (t) {
		t.plan(2);
		const args = messageHandler.args[0][0];
		t.ok(typeof paylaod.id !== 'undefined', 'paylaod is present');
		t.equal(args.id, paylaod.id);
	});

	test('message:deleted is called only once', function (t) {
		t.plan(1);
		t.equal(messageDeletedHandler.callCount, 1);
	});

	test('after all commandOriginatedMessage', function (t) {
		readTransport.close();
		t.end();
	});
})();

(function messageHandlersReject() {
	const paylaod = {
		id: 'command_failures'
	};

	const readTransport = awsTransport.sqsCommandListener({
		queueUrl: QUEUE_URL,
		region: REGION,
		accessKeyId: ACCESS_KEY_ID,
		secretAccessKey: SECRET_ACCESS_KEY
	});

	const writeTransport = awsTransport.sqsCommandEmitter({
		queueUrl: QUEUE_URL,
		region: REGION,
		accessKeyId: ACCESS_KEY_ID,
		secretAccessKey: SECRET_ACCESS_KEY
	});

	const receiveChannel = oddcast.commandChannel();
	const sendChannel = oddcast.commandChannel();

	const receiveChannelErrorHandler = sinon.spy();
	const sendChannelErrorHandler = sinon.spy();

	const readErrorHandler = sinon.spy();
	const writeErrorHandler = sinon.spy();

	const messageDeletedHandler = sinon.spy();

	const successErrorHandler = sinon.spy(function () {
		return Promise.resolve(null);
	});

	const refuseErrorHandler = sinon.spy(function () {
		receiveChannel.remove({role: 'test'}, refuseErrorHandler);
		receiveChannel.receive({role: 'test'}, successErrorHandler);
		return Promise.resolve(false);
	});

	const rejectErrorHandler = sinon.spy(function () {
		receiveChannel.remove({role: 'test'}, rejectErrorHandler);
		receiveChannel.receive({role: 'test'}, refuseErrorHandler);
		return Promise.reject(Error('reject error'));
	});

	const throwErrorHandler = sinon.spy(function () {
		receiveChannel.remove({role: 'test'}, throwErrorHandler);
		receiveChannel.receive({role: 'test'}, rejectErrorHandler);
		throw new Error('thrown error');
	});

	test('before all messageHandlersReject', function (t) {
		// Setup transport error event tests
		readTransport.on('error', readErrorHandler);
		writeTransport.on('error', writeErrorHandler);

		// Setup channel error event tests
		receiveChannel.on('error', receiveChannelErrorHandler);
		sendChannel.on('error', sendChannelErrorHandler);

		// End the tests when the message is finally deleted from the queue.
		readTransport.on('message:deleted', messageDeletedHandler);
		readTransport.on('message:deleted', function () {
			readTransport.close();
		});

		// Bind the transports to the channels.
		receiveChannel.use({role: 'test'}, readTransport);
		sendChannel.use({role: 'test'}, writeTransport);

		// Setup the receive handler chain.
		receiveChannel.receive({role: 'test'}, throwErrorHandler);

		readTransport.on('close', function () {
			t.end();
		});

		// Send the command.
		sendChannel.send({role: 'test', cmd: 'command:message'}, paylaod);
	});

	test('transport error events are not fired', function (t) {
		t.plan(2);
		t.equal(readErrorHandler.callCount, 0);
		t.equal(writeErrorHandler.callCount, 0);
	});

	test('send channel error events are not fired', function (t) {
		t.plan(1);
		t.equal(sendChannelErrorHandler.callCount, 0);
	});

	test('receive channel error events are fired', function (t) {
		t.plan(2);
		const args = receiveChannelErrorHandler.args.map(function (args) {
			return args[0];
		});
		t.equal(args[0].message, 'thrown error');
		t.equal(args[1].message, 'reject error');
	});

	test('message:deleted is called only once', function (t) {
		t.plan(1);
		t.equal(messageDeletedHandler.callCount, 1);
	});

	test('after all commandOriginatedMessage', function (t) {
		readTransport.close();
		t.end();
	});
})();
<commit_msg>Broadcast events into queued commands!!!<commit_after>'use strict';

const test = require('tape');
const sinon = require('sinon');
const oddcast = require('oddcast');
const awsTransport = require('../lib/oddcast-aws-transport');

const ACCESS_KEY_ID = process.env.ACCESS_KEY_ID;
const SECRET_ACCESS_KEY = process.env.SECRET_ACCESS_KEY;
const REGION = process.env.REGION;
const TOPIC_ARN = process.env.TOPIC_ARN;
const QUEUE_URL = process.env.QUEUE_URL;

if (!ACCESS_KEY_ID) {
	console.error('ACCESS_KEY_ID env variable is required.');
	process.exit(1);
}
if (!SECRET_ACCESS_KEY) {
	console.error('SECRET_ACCESS_KEY env variable is required.');
	process.exit(1);
}
if (!REGION) {
	console.error('REGION env variable is required.');
	process.exit(1);
}
if (!TOPIC_ARN) {
	console.error('TOPIC_ARN env variable is required.');
	process.exit(1);
}
if (!QUEUE_URL) {
	console.error('QUEUE_URL env variable is required.');
	process.exit(1);
}

(function commandOriginatedMessage() {
	const paylaod = {
		id: 'command_success'
	};

	const readTransport = awsTransport.sqsCommandListener({
		queueUrl: QUEUE_URL,
		region: REGION,
		accessKeyId: ACCESS_KEY_ID,
		secretAccessKey: SECRET_ACCESS_KEY
	});

	const writeTransport = awsTransport.sqsCommandEmitter({
		queueUrl: QUEUE_URL,
		region: REGION,
		accessKeyId: ACCESS_KEY_ID,
		secretAccessKey: SECRET_ACCESS_KEY
	});

	const receiveChannel = oddcast.commandChannel();
	const sendChannel = oddcast.commandChannel();

	const readErrorHandler = sinon.spy();
	const writeErrorHandler = sinon.spy();

	const messageHandler = sinon.spy();
	const messageDeletedHandler = sinon.spy();

	test('before all commandOriginatedMessage', function (t) {
		readTransport.on('error', readErrorHandler);
		writeTransport.on('error', writeErrorHandler);

		readTransport.on('error', function () {
			t.end();
		});
		writeTransport.on('error', function () {
			t.end();
		});

		readTransport.on('message:deleted', messageDeletedHandler);
		readTransport.on('message:deleted', function () {
			readTransport.close();
		});

		receiveChannel.use({role: 'test'}, readTransport);
		sendChannel.use({role: 'test'}, writeTransport);

		// Setup the receive handler.
		receiveChannel.receive({role: 'test', cmd: 'command:message'}, messageHandler);

		readTransport.on('close', function () {
			t.end();
		});

		// Send the command.
		sendChannel.send({role: 'test', cmd: 'command:message'}, paylaod);
	});

	test('read error handler is not called', function (t) {
		t.plan(1);
		t.equal(readErrorHandler.callCount, 0);
	});

	test('write error handler is not called', function (t) {
		t.plan(1);
		t.equal(writeErrorHandler.callCount, 0);
	});

	test('got message paylaod', function (t) {
		t.plan(2);
		const args = messageHandler.args[0][0];
		t.ok(typeof paylaod.id !== 'undefined', 'paylaod is present');
		t.equal(args.id, paylaod.id);
	});

	test('message:deleted is called only once', function (t) {
		t.plan(1);
		t.equal(messageDeletedHandler.callCount, 1);
	});
})();

(function eventOriginatedMessage() {
	const paylaod = {
		id: 'event_success'
	};

	const readTransport = awsTransport.sqsCommandListener({
		queueUrl: QUEUE_URL,
		region: REGION,
		accessKeyId: ACCESS_KEY_ID,
		secretAccessKey: SECRET_ACCESS_KEY
	});

	const writeTransport = awsTransport.snsBroadcastEmitter({
		topicArn: TOPIC_ARN,
		region: REGION,
		accessKeyId: ACCESS_KEY_ID,
		secretAccessKey: SECRET_ACCESS_KEY
	});

	const receiveChannel = oddcast.commandChannel();
	const broadcastChannel = oddcast.commandChannel();

	const readErrorHandler = sinon.spy();
	const writeErrorHandler = sinon.spy();

	const messageHandler = sinon.spy();
	const messageDeletedHandler = sinon.spy();

	test('before all eventOriginatedMessage', function (t) {
		readTransport.on('error', readErrorHandler);
		writeTransport.on('error', writeErrorHandler);

		readTransport.on('error', function () {
			t.end();
		});
		writeTransport.on('error', function () {
			t.end();
		});

		readTransport.on('message:deleted', messageDeletedHandler);
		readTransport.on('message:deleted', function () {
			readTransport.close();
		});

		receiveChannel.use({role: 'test'}, readTransport);
		broadcastChannel.use({role: 'test'}, writeTransport);

		// Setup the receive handler.
		receiveChannel.receive({role: 'test', cmd: 'command:message'}, messageHandler);

		readTransport.on('close', function () {
			t.end();
		});

		// Send the command.
		broadcastChannel.broadcast({role: 'test', cmd: 'command:message'}, paylaod);
	});

	test('read error handler is not called', function (t) {
		t.plan(1);
		t.equal(readErrorHandler.callCount, 0);
	});

	test('write error handler is not called', function (t) {
		t.plan(1);
		t.equal(writeErrorHandler.callCount, 0);
	});

	test('got message paylaod', function (t) {
		t.plan(2);
		const args = messageHandler.args[0][0];
		t.ok(typeof paylaod.id !== 'undefined', 'paylaod is present');
		t.equal(args.id, paylaod.id);
	});

	test('message:deleted is called only once', function (t) {
		t.plan(1);
		t.equal(messageDeletedHandler.callCount, 1);
	});
})();

(function messageHandlersReject() {
	const paylaod = {
		id: 'command_failures'
	};

	const readTransport = awsTransport.sqsCommandListener({
		queueUrl: QUEUE_URL,
		region: REGION,
		accessKeyId: ACCESS_KEY_ID,
		secretAccessKey: SECRET_ACCESS_KEY
	});

	const writeTransport = awsTransport.sqsCommandEmitter({
		queueUrl: QUEUE_URL,
		region: REGION,
		accessKeyId: ACCESS_KEY_ID,
		secretAccessKey: SECRET_ACCESS_KEY
	});

	const receiveChannel = oddcast.commandChannel();
	const sendChannel = oddcast.commandChannel();

	const receiveChannelErrorHandler = sinon.spy();
	const sendChannelErrorHandler = sinon.spy();

	const readErrorHandler = sinon.spy();
	const writeErrorHandler = sinon.spy();

	const messageDeletedHandler = sinon.spy();

	const successErrorHandler = sinon.spy(function () {
		return Promise.resolve(null);
	});

	const refuseErrorHandler = sinon.spy(function () {
		receiveChannel.remove({role: 'test'}, refuseErrorHandler);
		receiveChannel.receive({role: 'test'}, successErrorHandler);
		return Promise.resolve(false);
	});

	const rejectErrorHandler = sinon.spy(function () {
		receiveChannel.remove({role: 'test'}, rejectErrorHandler);
		receiveChannel.receive({role: 'test'}, refuseErrorHandler);
		return Promise.reject(Error('reject error'));
	});

	const throwErrorHandler = sinon.spy(function () {
		receiveChannel.remove({role: 'test'}, throwErrorHandler);
		receiveChannel.receive({role: 'test'}, rejectErrorHandler);
		throw new Error('thrown error');
	});

	test('before all messageHandlersReject', function (t) {
		// Setup transport error event tests
		readTransport.on('error', readErrorHandler);
		writeTransport.on('error', writeErrorHandler);

		// Setup channel error event tests
		receiveChannel.on('error', receiveChannelErrorHandler);
		sendChannel.on('error', sendChannelErrorHandler);

		// End the tests when the message is finally deleted from the queue.
		readTransport.on('message:deleted', messageDeletedHandler);
		readTransport.on('message:deleted', function () {
			readTransport.close();
		});

		// Bind the transports to the channels.
		receiveChannel.use({role: 'test'}, readTransport);
		sendChannel.use({role: 'test'}, writeTransport);

		// Setup the receive handler chain.
		receiveChannel.receive({role: 'test'}, throwErrorHandler);

		readTransport.on('close', function () {
			t.end();
		});

		// Send the command.
		sendChannel.send({role: 'test', cmd: 'command:message'}, paylaod);
	});

	test('transport error events are not fired', function (t) {
		t.plan(2);
		t.equal(readErrorHandler.callCount, 0);
		t.equal(writeErrorHandler.callCount, 0);
	});

	test('send channel error events are not fired', function (t) {
		t.plan(1);
		t.equal(sendChannelErrorHandler.callCount, 0);
	});

	test('receive channel error events are fired', function (t) {
		t.plan(2);
		const args = receiveChannelErrorHandler.args.map(function (args) {
			return args[0];
		});
		t.equal(args[0].message, 'thrown error');
		t.equal(args[1].message, 'reject error');
	});

	test('message:deleted is called only once', function (t) {
		t.plan(1);
		t.equal(messageDeletedHandler.callCount, 1);
	});
})();
<|endoftext|>


<commit_before>var priorityMap = { 2 : 'critical', 4: 'warning', 6: 'info' };

jsonLogs = jQuery.parseJSON($('div#jsonLogs').html());

initLogs();
$('#selectAllCheckbox').click(function() {
  $('input.logSelect').prop("checked", this.checked);
  });

function initLogs()
{
  $('table#listLogs').hide();
  $('.logsLoading').show();
  $('table#listLogs tr.logSum').remove();
  $('table#listLogs tr.logDetail').remove();
  var i = 1;
  $.each(jsonLogs, function(index, value) {
    var stripeClass = i % 2 ? 'odd' : 'even';
    i++;
    var html='';
    html+='
';
    html+=' <input class="logSelect" type="checkbox" id="logSelect'+value.errorlog_id+'" />	';
    html+=' '+value.datetime+'	';
    html+=' '+priorityMap[value.priority]+'	';
    html+=' '+value.module+'	';
    html+=' '+value.shortMessage+'

'+value.message+'

	';
    html+='
';
    html+='
';
    html+='
'+value.message+'
	';
    html+='
';
    $('table#listLogs').append(html);
    });
  $('table#listLogs').show();
  $('.logsLoading').hide();

  $('table#listLogs tr.logSum td.logMessage').click(function() {
    showBigDialogWithContent('Log', $(this).find('div').html(), true);
    });
  $('input.logSelect').enableCheckboxRangeSelection();
}

var dates = $("#startlog, #endlog").datepicker({
  defaultDate: "-1w",
  changeMonth: true,
  numberOfMonths: 1,
  onSelect: function(selectedDate) {
    var option = this.id == "startlog" ? "minDate" : "maxDate";
    var instance = $(this).data("datepicker");
    var date = $.datepicker.parseDate(
      instance.settings.dateFormat || $.datepicker._defaults.dateFormat,
      selectedDate, instance.settings);
    dates.not( this ).datepicker("option", option, date);
    },
  dayNamesMin: ["S", "M", "T", "W", "T", "F", "S"]
  });

$('#logSelector').ajaxForm( {beforeSubmit: validateShowlog, success: successShowlog} );

function validateShowlog(formData, jqForm, options)
{
  $('table#listLogs').hide();
  $('.logsLoading').show();
}

function successShowlog(responseText, statusText, xhr, form)
{
  try
    {
    var resp = jQuery.parseJSON(responseText);
    jsonLogs = resp.logs;
    $('#currentFilterStart').html(resp.currentFilter.start);
    $('#currentFilterEnd').html(resp.currentFilter.end);
    $('#currentFilterModule').html(resp.currentFilter.module);
    $('#currentFilterPriority').html(priorityMap[resp.currentFilter.priority]);
    }
  catch(e)
    {
    console.log(e);
    alert("An error occured.");
    return false;
    }
  initLogs();
}
<commit_msg>ENH: refs #0325. Enable both sorting and range selection on log table<commit_after>var priorityMap = { 2 : 'critical', 4: 'warning', 6: 'info' };

jsonLogs = jQuery.parseJSON($('div#jsonLogs').html());

initLogs();

var dates = $("#startlog, #endlog").datepicker({
  defaultDate: "-1w",
  changeMonth: true,
  numberOfMonths: 1,
  onSelect: function(selectedDate) {
    var option = this.id == "startlog" ? "minDate" : "maxDate";
    var instance = $(this).data("datepicker");
    var date = $.datepicker.parseDate(
      instance.settings.dateFormat || $.datepicker._defaults.dateFormat,
      selectedDate, instance.settings);
    dates.not( this ).datepicker("option", option, date);
    },
  dayNamesMin: ["S", "M", "T", "W", "T", "F", "S"]
  });

$('#logSelector').ajaxForm( {beforeSubmit: validateShowlog, success: successShowlog} );

$('table#listLogs').tablesorter({
  headers: {
    0: {sorter: false}, //checkbox column
    4: {sorter: false}  //log message column
    }
  }).bind('sortEnd', function() {
    $('input.logSelect').enableCheckboxRangeSelection();
  }).bind('update', function() {
    $('input.logSelect').enableCheckboxRangeSelection();
  });

$('#selectAllCheckbox').click(function() {
  $('input.logSelect').prop("checked", this.checked);
  });

function initLogs()
{
  $('table#listLogs').hide();
  $('.logsLoading').show();
  $('table#listLogs tr.logSum').remove();
  $('table#listLogs tr.logDetail').remove();
  var i = 1;
  $.each(jsonLogs, function(index, value) {
    var stripeClass = i % 2 ? 'odd' : 'even';
    i++;
    var html='';
    html+='
';
    html+=' <input class="logSelect" type="checkbox" id="logSelect'+value.errorlog_id+'" />	';
    html+=' '+value.datetime+'	';
    html+=' '+priorityMap[value.priority]+'	';
    html+=' '+value.module+'	';
    html+=' '+value.shortMessage+'

'+value.message+'

	';
    html+='
';
    html+='
';
    html+='
'+value.message+'
	';
    html+='
';
    $('table#listLogs').append(html);
    });
  $('table#listLogs').show();
  $('.logsLoading').hide();
  $('table#listLogs').trigger('update');

  $('table#listLogs tr.logSum td.logMessage').click(function() {
    showBigDialogWithContent('Log', $(this).find('div').html(), true);
    });
}

function validateShowlog(formData, jqForm, options)
{
  $('table#listLogs').hide();
  $('.logsLoading').show();
}

function successShowlog(responseText, statusText, xhr, form)
{
  try
    {
    var resp = jQuery.parseJSON(responseText);
    jsonLogs = resp.logs;
    $('#currentFilterStart').html(resp.currentFilter.start);
    $('#currentFilterEnd').html(resp.currentFilter.end);
    $('#currentFilterModule').html(resp.currentFilter.module);
    $('#currentFilterPriority').html(priorityMap[resp.currentFilter.priority]);
    }
  catch(e)
    {
    console.log(e);
    alert("An error occured.");
    return false;
    }
  initLogs();
}
<|endoftext|>


<commit_before>/**
 * @name mainApp
 * @description Main module of the application
 */
var mainApp = angular.module('mainApp',[
    'ngRoute',
    'mainAppCtrls',
    'mgcrea.ngStrap',
    'ui.router',
    'angular-jwt',
    'restSvcs',
    'angular-storage',
    'pascalprecht.translate',
    'textAngular',
    'prntSvcs'
]);
/**
 * @name mainAppCtrls
 * @type {angular.Module}
 * @description Module containg all controller of the application
 */
var mainAppCtrls = angular.module('mainAppCtrls',["pascalprecht.translate"]);

mainApp.config(['$urlRouterProvider','$stateProvider',
    function($urlRouterProvider,$stateProvider)
    {
        var prefix = "resources/views/";

        $stateProvider
            .state('workshops',{
                url: '/workshops',
                controller: 'WorkshopListCtrl',
                templateUrl: prefix.concat('workshopList.html')
            })
            .state('workshopsdetails',{
                url: '/workshops/details/:id',
                controller: 'WorkshopDetailsCtrl',
                templateUrl: prefix.concat('workshopDetails.html')
            })

            .state('login',{
                url: '/login',
                controller: 'LoginCtrl',
                templateUrl: prefix.concat('login.html')
            })

            .state('enrollment_confirm',{
                url: '/enrollment/confirm/:workshopid/:userid/:token',
                templateUrl: prefix.concat('enrollmentConfirm.html'),
                controller: 'EnrollmentConfirmCtrl'
            })

            .state('unsubscribe',{
                url: '/unsubscribe/:id/:workshopid/:token',
                templateUrl: prefix.concat('unsubscribemessage.html'),
                controller: 'UnsubscribeController'
            })

            .state('password_reset',{
                url: '/password_reset/:token',
                templateUrl: prefix.concat('passwordReset.html'),
                controller: 'PasswordRestCtrl'
            })

            .state('dashboard',{
                url: '/dashboard',
                controller: 'DashboardCtrl',
                templateUrl: prefix.concat('adminDashboard.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('workshop_template',{
                url:'/workshop/template',
                controller:'WorkshopTemplateCtrl',
                templateUrl: prefix.concat('adminWorkshopTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('workshop_template_new', {
                url: '/workshop/template/new',
                controller: 'NewWorkshopTemplateCtrl',
                templateUrl: prefix.concat('adminNewWorkshopTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('workshop_template_edit', {
                url: '/workshop/template/edit/:id',
                controller: 'EditWorkshopTemplateCtrl',
                templateUrl: prefix.concat('adminNewWorkshopTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('email_template', {
                url: '/email/template',
                controller: 'EmailTemplateCtrl',
                templateUrl: prefix.concat('adminEmailTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('email_template_new', {
                url: '/email/template/new',
                controller: 'NewEmailTemplateCtrl',
                templateUrl: prefix.concat('adminNewEmailTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('email_template_edit', {
                url: '/email/template/edit/:id',
                controller: 'EditEmailTemplateCtrl',
                templateUrl: prefix.concat('adminEditEmailTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('blacklist',{
                url: '/blacklist',
                controller: 'BlacklistCtrl',
                templateUrl: prefix.concat('adminBlacklist.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('administrator_management', {
                    url: '/admins',
                    controller: 'AdministratorManagementCtrl',
                    templateUrl: prefix.concat('administratorManagement.html'),
                data: {
                    requiresLogin: true
                }
                })

            .state('administrator_workshop_details', {
                url: '/workshop/management/details/:id',
                controller: 'adminWorkshopDetailsCtrl',
                templateUrl: prefix.concat('adminWorkshopDetails.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('admin_workshop_management',{
                url: '/workshop/management',
                controller: 'adminWorkshopManagementCtrl',
                templateUrl: prefix.concat('adminWorkshopManagement.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('admin_workshop_new',{
                url: '/workshop/management/new',
                controller: 'WorkshopNewCtrl',
                templateUrl: prefix.concat('adminWorkshopNew.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('admin_workshop_edit',{
                url: '/workshop/managment/edit/:id',
                controller: 'WorkshopEditCtrl',
                templateUrl: prefix.concat('adminWorkshopEdit.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('settings', {
                url: '/settings',
                controller: 'SettingsCtrl',
                templateUrl: prefix.concat('adminSettings.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('admininvite',{
                url: '/admin/create/:token',
                controller: 'AdminCreateCtrl',
                templateUrl: prefix.concat('adminInvite.html')

            })
            .state('legalnotice',{
                url: '/legalnotice',
                controller: 'LegalNoticeCtrl',
                templateUrl: prefix.concat('legalNotice.html')
            })
            .state('contact',{
                url: '/contact',
                controller: 'ContactCtrl',
                templateUrl: prefix.concat('contact.html')
            });

        $urlRouterProvider.otherwise('/workshops');

    }
]);

mainApp.config(['jwtInterceptorProvider','$httpProvider','$urlRouterProvider',function(jwtInterceptorProvider,$httpProvider,$urlRouterProvider){
    jwtInterceptorProvider.tokenGetter = function(store) {
        return store.get('jwt');
    };

    $httpProvider.interceptors.push('jwtInterceptor');
}])
    .run(['$rootScope','$state','store','jwtHelper',function($rootScope, $state, store, jwtHelper) {
        $rootScope.$on('$stateChangeStart', function(e, to) {
            if (to.data && to.data.requiresLogin) {
                if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
                    e.preventDefault();
                    $state.go('login');
                }
            };
        });
    }]);

mainApp.config(['$translateProvider', function($translateProvider) {
    $translateProvider.useStaticFilesLoader({
        prefix: 'resources/local/lang-',
        suffix: '.json'
    });
    $translateProvider.preferredLanguage('en');
}]);

/**
 * @ngdoc controller
 * @name mainApp.controller:GloablCtrl
 * @description Controller applied to the body HTML-Tag to avoid pollution of the rootScope. Provides Information wether login or logout button are to be shown

 */
mainApp.controller('GlobalCtrl',['$scope','store','jwtHelper','$state',function($scope,store,jwtHelper,$state) {

    $scope.show_login = true;
    $scope.show_logout = false;
    //Function called on every state change. Takes care of the buttons to be shown correctly
    $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        var jwt = store.get('jwt');
        if(toState.name == 'login') {
            $scope.show_login = false;
            $scope.fromState = fromState;
            if(jwt != null && !jwtHelper.isTokenExpired(jwt)) {
                event.preventDefault();
                $state.go(fromState);
            }
        } else {
            if(jwt != null) {
                $scope.show_login = jwtHelper.isTokenExpired(jwt);
                $scope.show_logout = !jwtHelper.isTokenExpired(jwt);
            } else {
                $scope.show_login = true;
                $scope.show_logout = false;
            }
        }
    });
    /**
     * @ngdoc function
     * @name mainApp.controller:GlobalCtrl#logout
     * @methodOf mainApp.controller:GlobalCtrl
     * @description Function bound to the logout button. Deletets the stored JWT and redirectes to the workhops state, if the current state requieres to be logged in. Also sets the login/-out buttons to be shown accordingly
     */
    $scope.logout = function() {

      var jwt =   store.get('jwt');
      if(jwt != null) {
          store.remove('jwt');
          $scope.show_login = true;
          $scope.show_logout = false;
          if($state.current.data.requiresLogin)
              $state.go('workshops');
      } else {
          $scope.show_login = true;
          $scope.show_logout = false;
      }
    };
}
]);
/**
 * @ngdoc directive
 * @name mainApp.directive:compare-to
 * @description
 */
mainApp.directive('compareTo',[function(){
    return {
        require: "ngModel",
        scope: {
            otherModelValue: "=compareTo"
        },
        link: function(scope, element, attributes, ngModel) {

            ngModel.$validators.compareTo = function(modelValue) {
                return modelValue == scope.otherModelValue;
            };

            scope.$watch("otherModelValue", function() {
                ngModel.$validate();
            });
        }
        };
    }
]);
mainApp.directive("myNavscroll", function($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
            if (!scope.scrollPosition) {
                scope.scrollPosition = 0
            }

            if (this.pageYOffset > scope.scrollPosition) {
                scope.boolChangeClass = true;
            } else {
                scope.boolChangeClass = false;
            }
            scope.scrollPosition = this.pageYOffset;
            scope.$apply();
        });
    };
});
<commit_msg>fixed typo in route<commit_after>/**
 * @name mainApp
 * @description Main module of the application
 */
var mainApp = angular.module('mainApp',[
    'ngRoute',
    'mainAppCtrls',
    'mgcrea.ngStrap',
    'ui.router',
    'angular-jwt',
    'restSvcs',
    'angular-storage',
    'pascalprecht.translate',
    'textAngular',
    'prntSvcs'
]);
/**
 * @name mainAppCtrls
 * @type {angular.Module}
 * @description Module containg all controller of the application
 */
var mainAppCtrls = angular.module('mainAppCtrls',["pascalprecht.translate"]);

mainApp.config(['$urlRouterProvider','$stateProvider',
    function($urlRouterProvider,$stateProvider)
    {
        var prefix = "resources/views/";

        $stateProvider
            .state('workshops',{
                url: '/workshops',
                controller: 'WorkshopListCtrl',
                templateUrl: prefix.concat('workshopList.html')
            })
            .state('workshopsdetails',{
                url: '/workshops/details/:id',
                controller: 'WorkshopDetailsCtrl',
                templateUrl: prefix.concat('workshopDetails.html')
            })

            .state('login',{
                url: '/login',
                controller: 'LoginCtrl',
                templateUrl: prefix.concat('login.html')
            })

            .state('enrollment_confirm',{
                url: '/enrollment/confirm/:workshopid/:userid/:token',
                templateUrl: prefix.concat('enrollmentConfirm.html'),
                controller: 'EnrollmentConfirmCtrl'
            })

            .state('unsubscribe',{
                url: '/unsubscribe/:id/:workshopid/:token',
                templateUrl: prefix.concat('unsubscribemessage.html'),
                controller: 'UnsubscribeController'
            })

            .state('password_reset',{
                url: '/password/reset/:token',
                templateUrl: prefix.concat('passwordReset.html'),
                controller: 'PasswordRestCtrl'
            })

            .state('dashboard',{
                url: '/dashboard',
                controller: 'DashboardCtrl',
                templateUrl: prefix.concat('adminDashboard.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('workshop_template',{
                url:'/workshop/template',
                controller:'WorkshopTemplateCtrl',
                templateUrl: prefix.concat('adminWorkshopTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('workshop_template_new', {
                url: '/workshop/template/new',
                controller: 'NewWorkshopTemplateCtrl',
                templateUrl: prefix.concat('adminNewWorkshopTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('workshop_template_edit', {
                url: '/workshop/template/edit/:id',
                controller: 'EditWorkshopTemplateCtrl',
                templateUrl: prefix.concat('adminNewWorkshopTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('email_template', {
                url: '/email/template',
                controller: 'EmailTemplateCtrl',
                templateUrl: prefix.concat('adminEmailTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('email_template_new', {
                url: '/email/template/new',
                controller: 'NewEmailTemplateCtrl',
                templateUrl: prefix.concat('adminNewEmailTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('email_template_edit', {
                url: '/email/template/edit/:id',
                controller: 'EditEmailTemplateCtrl',
                templateUrl: prefix.concat('adminEditEmailTemplate.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('blacklist',{
                url: '/blacklist',
                controller: 'BlacklistCtrl',
                templateUrl: prefix.concat('adminBlacklist.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('administrator_management', {
                    url: '/admins',
                    controller: 'AdministratorManagementCtrl',
                    templateUrl: prefix.concat('administratorManagement.html'),
                data: {
                    requiresLogin: true
                }
                })

            .state('administrator_workshop_details', {
                url: '/workshop/management/details/:id',
                controller: 'adminWorkshopDetailsCtrl',
                templateUrl: prefix.concat('adminWorkshopDetails.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('admin_workshop_management',{
                url: '/workshop/management',
                controller: 'adminWorkshopManagementCtrl',
                templateUrl: prefix.concat('adminWorkshopManagement.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('admin_workshop_new',{
                url: '/workshop/management/new',
                controller: 'WorkshopNewCtrl',
                templateUrl: prefix.concat('adminWorkshopNew.html'),
                data: {
                    requiresLogin: true
                }
            })
            .state('admin_workshop_edit',{
                url: '/workshop/management/edit/:id',
                controller: 'WorkshopEditCtrl',
                templateUrl: prefix.concat('adminWorkshopEdit.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('settings', {
                url: '/settings',
                controller: 'SettingsCtrl',
                templateUrl: prefix.concat('adminSettings.html'),
                data: {
                    requiresLogin: true
                }
            })

            .state('admininvite',{
                url: '/admin/create/:token',
                controller: 'AdminCreateCtrl',
                templateUrl: prefix.concat('adminInvite.html')

            })
            .state('legalnotice',{
                url: '/legalnotice',
                controller: 'LegalNoticeCtrl',
                templateUrl: prefix.concat('legalNotice.html')
            })
            .state('contact',{
                url: '/contact',
                controller: 'ContactCtrl',
                templateUrl: prefix.concat('contact.html')
            });

        $urlRouterProvider.otherwise('/workshops');

    }
]);

mainApp.config(['jwtInterceptorProvider','$httpProvider','$urlRouterProvider',function(jwtInterceptorProvider,$httpProvider,$urlRouterProvider){
    jwtInterceptorProvider.tokenGetter = function(store) {
        return store.get('jwt');
    };

    $httpProvider.interceptors.push('jwtInterceptor');
}])
    .run(['$rootScope','$state','store','jwtHelper',function($rootScope, $state, store, jwtHelper) {
        $rootScope.$on('$stateChangeStart', function(e, to) {
            if (to.data && to.data.requiresLogin) {
                if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
                    e.preventDefault();
                    $state.go('login');
                }
            };
        });
    }]);

mainApp.config(['$translateProvider', function($translateProvider) {
    $translateProvider.useStaticFilesLoader({
        prefix: 'resources/local/lang-',
        suffix: '.json'
    });
    $translateProvider.preferredLanguage('en');
}]);

/**
 * @ngdoc controller
 * @name mainApp.controller:GloablCtrl
 * @description Controller applied to the body HTML-Tag to avoid pollution of the rootScope. Provides Information wether login or logout button are to be shown

 */
mainApp.controller('GlobalCtrl',['$scope','store','jwtHelper','$state',function($scope,store,jwtHelper,$state) {

    $scope.show_login = true;
    $scope.show_logout = false;
    //Function called on every state change. Takes care of the buttons to be shown correctly
    $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        var jwt = store.get('jwt');
        if(toState.name == 'login') {
            $scope.show_login = false;
            $scope.fromState = fromState;
            if(jwt != null && !jwtHelper.isTokenExpired(jwt)) {
                event.preventDefault();
                $state.go(fromState);
            }
        } else {
            if(jwt != null) {
                $scope.show_login = jwtHelper.isTokenExpired(jwt);
                $scope.show_logout = !jwtHelper.isTokenExpired(jwt);
            } else {
                $scope.show_login = true;
                $scope.show_logout = false;
            }
        }
    });
    /**
     * @ngdoc function
     * @name mainApp.controller:GlobalCtrl#logout
     * @methodOf mainApp.controller:GlobalCtrl
     * @description Function bound to the logout button. Deletets the stored JWT and redirectes to the workhops state, if the current state requieres to be logged in. Also sets the login/-out buttons to be shown accordingly
     */
    $scope.logout = function() {

      var jwt =   store.get('jwt');
      if(jwt != null) {
          store.remove('jwt');
          $scope.show_login = true;
          $scope.show_logout = false;
          if($state.current.data.requiresLogin)
              $state.go('workshops');
      } else {
          $scope.show_login = true;
          $scope.show_logout = false;
      }
    };
}
]);
/**
 * @ngdoc directive
 * @name mainApp.directive:compare-to
 * @description
 */
mainApp.directive('compareTo',[function(){
    return {
        require: "ngModel",
        scope: {
            otherModelValue: "=compareTo"
        },
        link: function(scope, element, attributes, ngModel) {

            ngModel.$validators.compareTo = function(modelValue) {
                return modelValue == scope.otherModelValue;
            };

            scope.$watch("otherModelValue", function() {
                ngModel.$validate();
            });
        }
        };
    }
]);
mainApp.directive("myNavscroll", function($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
            if (!scope.scrollPosition) {
                scope.scrollPosition = 0
            }

            if (this.pageYOffset > scope.scrollPosition) {
                scope.boolChangeClass = true;
            } else {
                scope.boolChangeClass = false;
            }
            scope.scrollPosition = this.pageYOffset;
            scope.$apply();
        });
    };
});
<|endoftext|>


<commit_before>$(function() {
    function WizardViewModel(parameters) {
        var self = this;

        self.loginState = parameters[0];

        self.wizardDialog = undefined;

        self.isDialogActive = function() {
            return self.wizardDialog.is(":visible");
        };

        self.showDialog = function() {
            if (!CONFIG_WIZARD || !(CONFIG_FIRST_RUN || self.loginState.isAdmin())) return;

            self.wizardDialog.modal({
                minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
            }).css({
                width: 'auto',
                'margin-left': function() { return -($(this).width() /2); }
            });
        };

        self.closeDialog = function() {
            self.wizardDialog.modal("hide");
        };

        self.onStartup = function() {
            self.wizardDialog = $("#wizard_dialog");
        };

        self.onUserLoggedIn = function() {
            self.showDialog();
        };

        self.onAllBound = function(allViewModels) {
            self.wizardDialog.bootstrapWizard({
                tabClass: "nav nav-list",
                nextSelector: ".button-next",
                previousSelector: ".button-previous",
                finishSelector: ".button-finish",
                onTabClick: function() {
                    // we don't allow clicking on the tabs
                    return false;
                },
                onTabShow: function(tab, navigation, index) {
                    if (index < 0 || tab.length == 0) {
                        return true;
                    }

                    var total = self.wizardDialog.bootstrapWizard("navigationLength");

                    if (index == total) {
                        self.wizardDialog.find(".button-next").hide();
                        self.wizardDialog.find(".button-finish").show().removeClass("disabled");
                    } else {
                        self.wizardDialog.find(".button-finish").hide();
                        self.wizardDialog.find(".button-next").show();
                    }

                    var active = tab[0].id;
                    if (active != undefined) {
                        _.each(allViewModels, function(viewModel) {
                            if (viewModel.hasOwnProperty("onAfterWizardTabChange")) {
                                viewModel.onAfterWizardTabChange(active);
                            }
                        });
                    }
                },
                onTabChange: function(tab, navigation, index, nextTabIndex, nextTab) {
                    var current, next;

                    if (index == undefined || index < 0 ||
                        nextTabIndex == undefined || nextTabIndex < 0 ||
                        index == nextTabIndex ||
                        tab.length == 0 || nextTab.length == 0) {
                        // let's ignore that nonsense
                        return;
                    }

                    current = tab[0].id;
                    next = nextTab[0].id;

                    if (current != undefined && next != undefined) {
                        var result = true;
                        _.each(allViewModels, function(viewModel) {
                            if (viewModel.hasOwnProperty("onWizardTabChange")) {
                                result = result && (viewModel.onWizardTabChange(current, next) !== false);
                            }
                        });
                        return result;
                    }
                },
                onFinish: function(tab, navigation, index) {
                    var closeDialog = true;
                    _.each(allViewModels, function(viewModel) {
                        if (viewModel.hasOwnProperty("onWizardFinish")) {
                            closeDialog = closeDialog && (viewModel.onWizardFinish() !== false);
                        }
                    });

                    if (closeDialog) {
                        self.closeDialog();
                    }
                }
            });
            self.showDialog();
        };
    }

    OCTOPRINT_VIEWMODELS.push([
        WizardViewModel,
        ["loginStateViewModel"],
        "#wizard_dialog"
    ]);
});
<commit_msg>Wizard fetches details and saves enqueued setting on finish<commit_after>$(function() {
    function WizardViewModel(parameters) {
        var self = this;

        self.loginState = parameters[0];
        self.settingsViewModel = parameters[1];

        self.wizardDialog = undefined;

        self.allViewModels = undefined;

        self.isDialogActive = function() {
            return self.wizardDialog.is(":visible");
        };

        self.showDialog = function() {
            if (!CONFIG_WIZARD || !(CONFIG_FIRST_RUN || self.loginState.isAdmin())) return;

            self.getWizardDetails(function(response) {
                _.each(self.allViewModels, function(viewModel) {
                    if (viewModel.hasOwnProperty("onWizardDetails")) {
                        viewModel.onWizardDetails(response);
                    }
                });

                self.wizardDialog.modal({
                    minHeight: function() { return Math.max($.fn.modal.defaults.maxHeight() - 80, 250); }
                }).css({
                    width: 'auto',
                    'margin-left': function() { return -($(this).width() /2); }
                });
            });
        };

        self.closeDialog = function() {
            self.wizardDialog.modal("hide");
        };

        self.onStartup = function() {
            self.wizardDialog = $("#wizard_dialog");
        };

        self.onUserLoggedIn = function() {
            self.showDialog();
        };

        self.onAllBound = function(allViewModels) {
            self.allViewModels = allViewModels;
            self.wizardDialog.bootstrapWizard({
                tabClass: "nav nav-list",
                nextSelector: ".button-next",
                previousSelector: ".button-previous",
                finishSelector: ".button-finish",
                onTabClick: function() {
                    // we don't allow clicking on the tabs
                    return false;
                },
                onTabShow: function(tab, navigation, index) {
                    if (index < 0 || tab.length == 0) {
                        return true;
                    }

                    var total = self.wizardDialog.bootstrapWizard("navigationLength");

                    if (index == total) {
                        self.wizardDialog.find(".button-next").hide();
                        self.wizardDialog.find(".button-finish").show().removeClass("disabled");
                    } else {
                        self.wizardDialog.find(".button-finish").hide();
                        self.wizardDialog.find(".button-next").show();
                    }

                    var active = tab[0].id;
                    if (active != undefined) {
                        _.each(allViewModels, function(viewModel) {
                            if (viewModel.hasOwnProperty("onAfterWizardTabChange")) {
                                viewModel.onAfterWizardTabChange(active);
                            }
                        });
                    }
                },
                onTabChange: function(tab, navigation, index, nextTabIndex, nextTab) {
                    var current, next;

                    if (index == undefined || index < 0 ||
                        nextTabIndex == undefined || nextTabIndex < 0 ||
                        index == nextTabIndex ||
                        tab.length == 0 || nextTab.length == 0) {
                        // let's ignore that nonsense
                        return;
                    }

                    current = tab[0].id;
                    next = nextTab[0].id;

                    if (current != undefined && next != undefined) {
                        var result = true;
                        _.each(allViewModels, function(viewModel) {
                            if (viewModel.hasOwnProperty("onWizardTabChange")) {
                                result = result && (viewModel.onWizardTabChange(current, next) !== false);
                            }
                        });
                        return result;
                    }
                },
                onFinish: function(tab, navigation, index) {
                    var closeDialog = true;
                    _.each(allViewModels, function(viewModel) {
                        if (viewModel.hasOwnProperty("onBeforeWizardFinish")) {
                            closeDialog = closeDialog && (viewModel.onBeforeWizardFinish() !== false);
                        }
                    });

                    if (closeDialog) {
                        _.each(allViewModels, function(viewModel) {
                            if (viewModel.hasOwnProperty("onWizardFinish")) {
                                viewModel.onWizardFinish();
                            }
                        });
                        self.settingsViewModel.saveEnqueued();
                        self.closeDialog();
                    }
                }
            });
            self.showDialog();
        };

        self.getWizardDetails = function(callback) {
            if (!callback) return;

            $.ajax({
                url: API_BASEURL + "setup/wizard",
                type: "GET",
                dataType: "json",
                success: callback
            });
        }
    }

    OCTOPRINT_VIEWMODELS.push([
        WizardViewModel,
        ["loginStateViewModel", "settingsViewModel"],
        "#wizard_dialog"
    ]);
});
<|endoftext|>


<commit_before>function ButterBar(popup, message, close) {
  this.popup = popup;
  this.message = message;
  this.close = close;
}
ButterBar.prototype.showMessage = function(text) {
  this.message.textContent = text;  // FF, Chrome
  this.message.innerText = text;    // IE
  if (! $(this.popup).hasClass("shown")) {
    $(this.popup).addClass("shown");
  }
  if (this.close != null) {
    this.close.onclick = cbHideMsg;
  }
  window.onscroll = ButterBar.keepInView;
};
ButterBar.prototype.hide = function() {
  if ($(this.popup).hasClass("shown")) {
    $(this.popup).removeClass("shown");
  }
};
ButterBar.prototype.setCloseButtonVisible = function(visible) {
  if (visible) {
    this.close.style.display = null;
  } else {
    this.close.style.display = 'none';
  }
}
ButterBar.getButterBar = function() {
  return new ButterBar(document.getElementById("gcb-butterbar-top"),
    document.getElementById("gcb-butterbar-message"),
    document.getElementById("gcb-butterbar-close"));
};
function cbShowMsg(text) {
  var butterBar = ButterBar.getButterBar();
  butterBar.setCloseButtonVisible(true);
  butterBar.showMessage(text);
}
function cbShowAlert(text) {
  // An alert should not be closed; hide the close button
  var butterBar = ButterBar.getButterBar();
  butterBar.setCloseButtonVisible(false);
  butterBar.showMessage(text);
}
function cbHideMsg() {
  ButterBar.getButterBar().hide();
}
ButterBar.keepInView = function() {
  var popup = ButterBar.getButterBar().popup;
  var container = popup.parentElement;

  container.style.top = null;
  $(container).removeClass('fixed');

  var offset = $(popup).offset().top;
  if (offset - $(document).scrollTop() <= 10) {
    $(container).addClass('fixed');
    container.style.top = (10 - popup.offsetTop) + "px";
  }
};
<commit_msg>Fixing ie8 problem for butterbar.js 	Change on 2013/08/06 by emichael <emichael@google.com> ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=50443021<commit_after>function ButterBar(popup, message, close) {
  this.popup = popup;
  this.message = message;
  this.close = close;
}
ButterBar.prototype.showMessage = function(text) {
  this.message.textContent = text;  // FF, Chrome
  this.message.innerText = text;    // IE
  if (! $(this.popup).hasClass("shown")) {
    $(this.popup).addClass("shown");
  }
  if (this.close != null) {
    this.close.onclick = cbHideMsg;
  }
  window.onscroll = ButterBar.keepInView;
};
ButterBar.prototype.hide = function() {
  if ($(this.popup).hasClass("shown")) {
    $(this.popup).removeClass("shown");
  }
};
ButterBar.prototype.setCloseButtonVisible = function(visible) {
  if (visible) {
    $(this.close).css('display', null);
  } else {
    $(this.close).css('display', 'none');
  }
}
ButterBar.getButterBar = function() {
  return new ButterBar(document.getElementById("gcb-butterbar-top"),
    document.getElementById("gcb-butterbar-message"),
    document.getElementById("gcb-butterbar-close"));
};
function cbShowMsg(text) {
  var butterBar = ButterBar.getButterBar();
  butterBar.setCloseButtonVisible(true);
  butterBar.showMessage(text);
}
function cbShowAlert(text) {
  // An alert should not be closed; hide the close button
  var butterBar = ButterBar.getButterBar();
  butterBar.setCloseButtonVisible(false);
  butterBar.showMessage(text);
}
function cbHideMsg() {
  ButterBar.getButterBar().hide();
}
ButterBar.keepInView = function() {
  var popup = ButterBar.getButterBar().popup;
  var container = popup.parentElement;

  container.style.top = null;
  $(container).removeClass('fixed');

  var offset = $(popup).offset().top;
  if (offset - $(document).scrollTop() <= 10) {
    $(container).addClass('fixed');
    container.style.top = (10 - popup.offsetTop) + "px";
  }
};
<|endoftext|>