<commit_before>/*
Copyright (c) 2015 Twitter, Inc. and other contributors

Component to add Velocity animations around React transitions. Delegates to the React TransitionGroup
addon.

Properties
  enter: Animation to run on a child component being added
  leave: Animation to run on a child component leaving
  runOnMount: if true, runs the "enter" animation on the elements that exist as children when this
    component is mounted.

Any additional properties (e.g. "className", "component") will be passed to the internal
TransitionGroup.

"enter" and "leave" should either be a string naming an animation, or a hash with an
"animation" key that can either be a string itself, or a hash of style attributes to animate (this
value is passed to Velocity its the first arg).

If "enter" or "leave" is a hash, it can additionally have a "style" value that is applied the tick
before the Velocity animation starts. Use this for non-animating properties (like "position") that
are prerequisites for correct animation. The style value is applied using Velocity's JS -> CSS
routines, which may differ from React's.

Any hash entries beyond "animation" and "style" are passed in an options hash to Velocity. Use this
for options like "stagger", "reverse", &tc.

Statics
  disabledForTest: Set this to true globally to turn off all custom animation logic. Instead, this
    component will behave like a vanilla TransitionGroup.

Inspired by https://gist.github.com/tkafka/0d94c6ec94297bb67091
*/

var _ = {
  each: require('lodash/collection/each'),
  extend: require('lodash/object/extend'),
  keys: require('lodash/object/keys'),
  omit: require('lodash/object/omit'),
  pluck: require('lodash/collection/pluck'),
};
var React = require('react');
var ReactDOM = require('react-dom');
var ReactTransitionGroup = require('react-addons-transition-group');
var Velocity = require('./lib/velocity-animate-shim');

// Internal wrapper for the transitioned elements. Delegates all child lifecycle events to the
// parent VelocityTransitionGroup so that it can co-ordinate animating all of the elements at once.
var VelocityTransitionGroupChild = React.createClass({
  displayName: 'VelocityTransitionGroupChild',

  propTypes: {
    children: React.PropTypes.element.isRequired,
    willAppearFunc: React.PropTypes.func.isRequired,
    willEnterFunc: React.PropTypes.func.isRequired,
    willLeaveFunc: React.PropTypes.func.isRequired,
  },

  componentWillAppear: function (doneFn) {
    this.props.willAppearFunc(ReactDOM.findDOMNode(this), doneFn);
  },

  componentWillEnter: function (doneFn) {
    this.props.willEnterFunc(ReactDOM.findDOMNode(this), doneFn);
  },

  componentWillLeave: function (doneFn) {
    this.props.willLeaveFunc(ReactDOM.findDOMNode(this), doneFn);
  },

  render: function () {
    return React.Children.only(this.props.children);
  },
});

var VelocityTransitionGroup = React.createClass({
  displayName: 'VelocityTransitionGroup',

  statics: {
    disabledForTest: false, // global, mutable, for disabling animations during test
  },

  propTypes: {
    runOnMount: React.PropTypes.bool,
    enter: React.PropTypes.any,
    leave: React.PropTypes.any,
    children: React.PropTypes.any,
  },

  getDefaultProps: function() {
    return {
      runOnMount: false,
      enter: null,
      leave: null,
    };
  },

  componentWillMount: function () {
    this._scheduled = false;
    this._entering = [];
    this._leaving = [];
  },

  componentWillUnmount: function () {
    this._entering = [];
    this._leaving = [];
  },

  render: function () {
    // Pass any props that are not our own on into the TransitionGroup delegate.
    var transitionGroupProps = _.omit(this.props, _.keys(this.constructor.propTypes));

    // Without our custom childFactory, we just get a default TransitionGroup that doesn't do
    // anything special at all.
    if (!this.constructor.disabledForTest && !Velocity.velocityReactServerShim) {
      transitionGroupProps.childFactory = this._wrapChild;
    }

    return React.createElement(ReactTransitionGroup, transitionGroupProps, this.props.children);
  },

  childWillAppear: function (node, doneFn) {
    if (this.props.runOnMount) {
      this.childWillEnter(node, doneFn);
    } else {
      this._finishAnimation(node, this.props.enter);

      // Important to tick over so that any callbacks due to finishing the animation complete first.
      // isMounted check necessary to avoid exception in tests, which can mount and unmount a
      // component before this runs over, as the "doneFn" callback does a ref lookup rather than
      // closing over the component.
      //
      // Using setTimeout so that doneFn gets called even when the tab is hidden.
      var self = this;
      window.setTimeout(function () {
        if (self.isMounted()) {
          doneFn();
        }
      }, 0);
    }
  },

  childWillEnter: function (node, doneFn) {
    if (this._shortCircuitAnimation(this.props.enter, doneFn)) return;

    // By finishing a "leave" on the element, we put it in the right state to be animated in. Useful
    // if "leave" includes a rotation or something that we'd like to have as our starting point, for
    // symmetry.
    this._finishAnimation(node, this.props.leave);

    // We're not going to start the animation for a tick, so set the node's display to none so that
    // it doesn't flash in.
    Velocity.CSS.setPropertyValue(node, 'display', 'none');

    this._entering.push({
      node: node,
      doneFn: doneFn,
    });

    this._schedule();
  },

  childWillLeave: function (node, doneFn) {
    if (this._shortCircuitAnimation(this.props.leave, doneFn)) return;

    this._leaving.push({
      node: node,
      doneFn: doneFn,
    });

    this._schedule();
  },

  // document.hidden check is there because animation completion callbacks won't fire (due to
  // chaining off of rAF), which would prevent entering / leaving DOM nodes from being cleaned up
  // while the tab is hidden.
  //
  // Returns true if this did short circuit, false if lifecycle methods should continue with
  // their animations.
  _shortCircuitAnimation: function (animationProp, doneFn) {
    if (document.hidden || (this._parseAnimationProp(animationProp).animation == null)) {
      if (this.isMounted()) {
        doneFn();
      }

      return true;
    } else {
      return false;
    }
  },

  _schedule: function () {
    if (this._scheduled) {
      return;
    }

    this._scheduled = true;

    // Need rAF to make sure we're in the same event queue as Velocity from here out. Important
    // for avoiding getting wrong interleaving with Velocity callbacks.
    window.requestAnimationFrame(this._runAnimations);
  },

  _runAnimations: function () {
    this._scheduled = false;

    this._runAnimation(true, this._entering, this.props.enter);
    this._runAnimation(false, this._leaving, this.props.leave);

    this._entering = [];
    this._leaving = [];
  },

  // Used to parse out the 'enter' and 'leave' properties. Handles cases where they are omitted
  // as well as when they are just strings and not hashes of animation and options.
  _parseAnimationProp: function (animationProp) {
    var animation, opts, style;

    if (typeof animationProp === 'string') {
      animation = animationProp;
      style = null;
      opts = {};
    } else {
      animation = (animationProp != null) ? animationProp.animation : null;
      style = (animationProp != null) ? animationProp.style : null;
      opts = _.omit(animationProp, 'animation', 'style');
    }

    return {
      animation: animation,
      style: style,
      opts: opts,
    };
  },

  _runAnimation: function (entering, queue, animationProp) {
    if (!this.isMounted() || queue.length === 0) {
      return;
    }

    var nodes = _.pluck(queue, 'node');
    var doneFns = _.pluck(queue, 'doneFn');

    var parsedAnimation = this._parseAnimationProp(animationProp);
    var animation = parsedAnimation.animation;
    var style = parsedAnimation.style;
    var opts = parsedAnimation.opts;

    // Clearing display reverses the behavior from childWillAppear where all elements are added with
    // display: none to prevent them from flashing in before the animation starts. We don't do this
    // for the fade/slide animations or any animation that ends in "In," since Velocity will handle
    // it for us.
    if (entering && !(/^(fade|slide)/.test(animation) || /In$/.test(animation))) {
      style = _.extend({
        display: ''
      }, style);
    }

    // Because Safari can synchronously repaint when CSS "display" is reset, we set styles for all
    // browsers before the rAF tick below that starts the animation. This way you know in all
    // cases that you need to support your static styles being visible on the element before
    // the animation begins.
    if (style != null) {
      _.each(style, function (value, key) {
        Velocity.hook(nodes, key, value);
      });
    }

    var self = this;
    var completeFn = function () {
      if (!self.isMounted()) {
        return;
      }

      doneFns.map(function (doneFn) { doneFn(); });
    };

    // For nodes that are entering, we tell the TransitionGroup that we're done with them
    // immediately. That way, they can be removed later before their entering animations complete.
    // If we're leaving, we stop current animations (which may be partially-completed enter
    // animations) so that we can then animate out. Velocity typically makes these transitions
    // very smooth, correctly animating from whatever state the element is currently in.
    if (entering) {
      completeFn();
      completeFn = null;
    } else {
      Velocity(nodes, 'stop');
    }

    // Bit of a hack. Without this rAF, sometimes an enter animation doesn't start running, or is
    // stopped before getting anywhere. This should get us on the other side of both completeFn and
    // any _finishAnimation that's happening.
    window.requestAnimationFrame(function () {
      Velocity(nodes, animation, _.extend({}, opts, {
        complete: completeFn
      }));
    });
  },

  _finishAnimation: function (node, animationProp) {
    var parsedAnimation = this._parseAnimationProp(animationProp);
    var animation = parsedAnimation.animation;
    var style = parsedAnimation.style;
    var opts = parsedAnimation.opts;

    if (style != null) {
      _.each(style, function (value, key) {
        Velocity.hook(node, key, value);
      });
    }

    if (animation != null) {
      // Opts are relevant even though we're immediately finishing, since things like "display"
      // can affect the animation outcome.

      Velocity(node, animation, opts);
      Velocity(node, 'finishAll', true);
    }
  },

  _wrapChild: function (child) {
    return React.createElement(VelocityTransitionGroupChild, {
      willAppearFunc: this.childWillAppear,
      willEnterFunc: this.childWillEnter,
      willLeaveFunc: this.childWillLeave,
    }, child);
  },
});

module.exports = VelocityTransitionGroup;
<commit_msg>Allows for an alternate enter hide/show strategy<commit_after>/*
Copyright (c) 2015 Twitter, Inc. and other contributors

Component to add Velocity animations around React transitions. Delegates to the React TransitionGroup
addon.

Properties
  enter: Animation to run on a child component being added
  leave: Animation to run on a child component leaving
  runOnMount: if true, runs the "enter" animation on the elements that exist as children when this
    component is mounted.
  enterHideStyle/enterShowStyle: see below.

Any additional properties (e.g. "className", "component") will be passed to the internal
TransitionGroup.

"enter" and "leave" should either be a string naming an animation, or a hash with an
"animation" key that can either be a string itself, or a hash of style attributes to animate (this
value is passed to Velocity its the first arg).

If "enter" or "leave" is a hash, it can additionally have a "style" value that is applied the tick
before the Velocity animation starts. Use this for non-animating properties (like "position") that
are prerequisites for correct animation. The style value is applied using Velocity's JS -> CSS
routines, which may differ from React's.

Any hash entries beyond "animation" and "style" are passed in an options hash to Velocity. Use this
for options like "stagger", "reverse", &tc.

By default, this component will immediately hide all entering children with display: 'none', and
unhide them one tick later with display: ''. This is done so that we can coalesce multiple enters
into a single animation, and we want to avoid any popping of elements in while they're collected. If
you prefer a different way of hiding these elements so that e.g. geometry can be immediately
calculated, use the enterHideStyle and enterShowStyle props to provide alternate style hashes for
hiding and revealing entering elements.

Statics
  disabledForTest: Set this to true globally to turn off all custom animation logic. Instead, this
    component will behave like a vanilla TransitionGroup.

Inspired by https://gist.github.com/tkafka/0d94c6ec94297bb67091
*/

var _ = {
  each: require('lodash/collection/each'),
  extend: require('lodash/object/extend'),
  forEach: require('lodash/collection/forEach'),
  isEqual: require('lodash/lang/isEqual'),
  keys: require('lodash/object/keys'),
  omit: require('lodash/object/omit'),
  pluck: require('lodash/collection/pluck'),
};
var React = require('react');
var ReactDOM = require('react-dom');
var ReactTransitionGroup = require('react-addons-transition-group');
var Velocity = require('./lib/velocity-animate-shim');

// Internal wrapper for the transitioned elements. Delegates all child lifecycle events to the
// parent VelocityTransitionGroup so that it can co-ordinate animating all of the elements at once.
var VelocityTransitionGroupChild = React.createClass({
  displayName: 'VelocityTransitionGroupChild',

  propTypes: {
    children: React.PropTypes.element.isRequired,
    willAppearFunc: React.PropTypes.func.isRequired,
    willEnterFunc: React.PropTypes.func.isRequired,
    willLeaveFunc: React.PropTypes.func.isRequired,
  },

  componentWillAppear: function (doneFn) {
    this.props.willAppearFunc(ReactDOM.findDOMNode(this), doneFn);
  },

  componentWillEnter: function (doneFn) {
    this.props.willEnterFunc(ReactDOM.findDOMNode(this), doneFn);
  },

  componentWillLeave: function (doneFn) {
    this.props.willLeaveFunc(ReactDOM.findDOMNode(this), doneFn);
  },

  render: function () {
    return React.Children.only(this.props.children);
  },
});

var VelocityTransitionGroup = React.createClass({
  displayName: 'VelocityTransitionGroup',

  statics: {
    disabledForTest: false, // global, mutable, for disabling animations during test
  },

  propTypes: {
    runOnMount: React.PropTypes.bool,
    enter: React.PropTypes.any,
    leave: React.PropTypes.any,
    children: React.PropTypes.any,
    enterHideStyle: React.PropTypes.object,
    enterShowStyle: React.PropTypes.object,
  },

  getDefaultProps: function() {
    return {
      runOnMount: false,
      enter: null,
      leave: null,
      enterHideStyle: {
        display: 'none',
      },
      enterShowStyle: {
        display: '',
      },
    };
  },

  componentWillMount: function () {
    this._scheduled = false;
    this._entering = [];
    this._leaving = [];
  },

  componentWillUnmount: function () {
    this._entering = [];
    this._leaving = [];
  },

  render: function () {
    // Pass any props that are not our own on into the TransitionGroup delegate.
    var transitionGroupProps = _.omit(this.props, _.keys(this.constructor.propTypes));

    // Without our custom childFactory, we just get a default TransitionGroup that doesn't do
    // anything special at all.
    if (!this.constructor.disabledForTest && !Velocity.velocityReactServerShim) {
      transitionGroupProps.childFactory = this._wrapChild;
    }

    return React.createElement(ReactTransitionGroup, transitionGroupProps, this.props.children);
  },

  childWillAppear: function (node, doneFn) {
    if (this.props.runOnMount) {
      this.childWillEnter(node, doneFn);
    } else {
      this._finishAnimation(node, this.props.enter);

      // Important to tick over so that any callbacks due to finishing the animation complete first.
      // isMounted check necessary to avoid exception in tests, which can mount and unmount a
      // component before this runs over, as the "doneFn" callback does a ref lookup rather than
      // closing over the component.
      //
      // Using setTimeout so that doneFn gets called even when the tab is hidden.
      var self = this;
      window.setTimeout(function () {
        if (self.isMounted()) {
          doneFn();
        }
      }, 0);
    }
  },

  childWillEnter: function (node, doneFn) {
    if (this._shortCircuitAnimation(this.props.enter, doneFn)) return;

    // By finishing a "leave" on the element, we put it in the right state to be animated in. Useful
    // if "leave" includes a rotation or something that we'd like to have as our starting point, for
    // symmetry.
    this._finishAnimation(node, this.props.leave);

    // We're not going to start the animation for a tick, so set the node's display to none (or any
    // custom "hide" style provided) so that it doesn't flash in.
    _.forEach(this.props.enterHideStyle, function (val, key) {
      Velocity.CSS.setPropertyValue(node, key, val);
    });

    this._entering.push({
      node: node,
      doneFn: doneFn,
    });

    this._schedule();
  },

  childWillLeave: function (node, doneFn) {
    if (this._shortCircuitAnimation(this.props.leave, doneFn)) return;

    this._leaving.push({
      node: node,
      doneFn: doneFn,
    });

    this._schedule();
  },

  // document.hidden check is there because animation completion callbacks won't fire (due to
  // chaining off of rAF), which would prevent entering / leaving DOM nodes from being cleaned up
  // while the tab is hidden.
  //
  // Returns true if this did short circuit, false if lifecycle methods should continue with
  // their animations.
  _shortCircuitAnimation: function (animationProp, doneFn) {
    if (document.hidden || (this._parseAnimationProp(animationProp).animation == null)) {
      if (this.isMounted()) {
        doneFn();
      }

      return true;
    } else {
      return false;
    }
  },

  _schedule: function () {
    if (this._scheduled) {
      return;
    }

    this._scheduled = true;

    // Need rAF to make sure we're in the same event queue as Velocity from here out. Important
    // for avoiding getting wrong interleaving with Velocity callbacks.
    window.requestAnimationFrame(this._runAnimations);
  },

  _runAnimations: function () {
    this._scheduled = false;

    this._runAnimation(true, this._entering, this.props.enter);
    this._runAnimation(false, this._leaving, this.props.leave);

    this._entering = [];
    this._leaving = [];
  },

  // Used to parse out the 'enter' and 'leave' properties. Handles cases where they are omitted
  // as well as when they are just strings and not hashes of animation and options.
  _parseAnimationProp: function (animationProp) {
    var animation, opts, style;

    if (typeof animationProp === 'string') {
      animation = animationProp;
      style = null;
      opts = {};
    } else {
      animation = (animationProp != null) ? animationProp.animation : null;
      style = (animationProp != null) ? animationProp.style : null;
      opts = _.omit(animationProp, 'animation', 'style');
    }

    return {
      animation: animation,
      style: style,
      opts: opts,
    };
  },

  _runAnimation: function (entering, queue, animationProp) {
    if (!this.isMounted() || queue.length === 0) {
      return;
    }

    var nodes = _.pluck(queue, 'node');
    var doneFns = _.pluck(queue, 'doneFn');

    var parsedAnimation = this._parseAnimationProp(animationProp);
    var animation = parsedAnimation.animation;
    var style = parsedAnimation.style;
    var opts = parsedAnimation.opts;

    // Clearing display reverses the behavior from childWillAppear where all elements are added with
    // display: none to prevent them from flashing in before the animation starts. We don't do this
    // for the fade/slide animations or any animation that ends in "In," since Velocity will handle
    // it for us.
    //
    // If a custom "enterShowStyle" prop is passed, (i.e. not one that just reverses display: none)
    // we always run it, regardless of the animation, since it's probably doing something around
    // opacity or positioning that Velocity will not necessarily reset.
    if (entering) {
      if (!_.isEqual(this.props.enterShowStyle, {display: ''})
        || !(/^(fade|slide)/.test(animation) || /In$/.test(animation))) {
        style = _.extend({}, this.props.enterShowStyle, style);
      }
    }

    // Because Safari can synchronously repaint when CSS "display" is reset, we set styles for all
    // browsers before the rAF tick below that starts the animation. This way you know in all
    // cases that you need to support your static styles being visible on the element before
    // the animation begins.
    if (style != null) {
      _.each(style, function (value, key) {
        Velocity.hook(nodes, key, value);
      });
    }

    var self = this;
    var completeFn = function () {
      if (!self.isMounted()) {
        return;
      }

      doneFns.map(function (doneFn) { doneFn(); });
    };

    // For nodes that are entering, we tell the TransitionGroup that we're done with them
    // immediately. That way, they can be removed later before their entering animations complete.
    // If we're leaving, we stop current animations (which may be partially-completed enter
    // animations) so that we can then animate out. Velocity typically makes these transitions
    // very smooth, correctly animating from whatever state the element is currently in.
    if (entering) {
      completeFn();
      completeFn = null;
    } else {
      Velocity(nodes, 'stop');
    }

    // Bit of a hack. Without this rAF, sometimes an enter animation doesn't start running, or is
    // stopped before getting anywhere. This should get us on the other side of both completeFn and
    // any _finishAnimation that's happening.
    window.requestAnimationFrame(function () {
      Velocity(nodes, animation, _.extend({}, opts, {
        complete: completeFn
      }));
    });
  },

  _finishAnimation: function (node, animationProp) {
    var parsedAnimation = this._parseAnimationProp(animationProp);
    var animation = parsedAnimation.animation;
    var style = parsedAnimation.style;
    var opts = parsedAnimation.opts;

    if (style != null) {
      _.each(style, function (value, key) {
        Velocity.hook(node, key, value);
      });
    }

    if (animation != null) {
      // Opts are relevant even though we're immediately finishing, since things like "display"
      // can affect the animation outcome.

      Velocity(node, animation, opts);
      Velocity(node, 'finishAll', true);
    }
  },

  _wrapChild: function (child) {
    return React.createElement(VelocityTransitionGroupChild, {
      willAppearFunc: this.childWillAppear,
      willEnterFunc: this.childWillEnter,
      willLeaveFunc: this.childWillLeave,
    }, child);
  },
});

module.exports = VelocityTransitionGroup;
<|endoftext|>


<commit_before><commit_msg>add maincontroller.js (assigns controller to app)<commit_after><|endoftext|>


<commit_before>
/*
 * www-authenticate
 * https://github.com/randymized/www-authenticate
 *
 * Copyright (c) 2013 Randy McLaughlin
 * Licensed under the MIT license.
 */

'use strict';

var crypto= require('crypto')
  , md5sum = crypto.createHash('md5')
  , parsers= require('./parsers')
  ;

function md5(s) {
  return crypto.createHash('md5').update(s).digest('hex');
}

function hex8(num)
{
  return ("00000000" + num.toString(16)).slice(-8);
}

module.exports = function(username,password,options)
{
  var cnonce;
  if (options) {
    if (toString.call(options.cnonce) == '[object String]')
      cnonce= options.cnonce;
  }
  if (cnonce === void 0) cnonce= crypto.pseudoRandomBytes(8).toString('hex');
  return function parse_header(www_authenticate)
  {
    function Authenticator()
    {
      function note_error(err)
      {
        this.err= err
      }
      var nc= 0;

      var parsed= new parsers.WWW_Authenticate(www_authenticate);
      if (parsed.err) return note_error(parsed.err);
      var auth_parms= this.parms= parsed.parms;
      this.cnonce= cnonce;

      switch(parsed.scheme) {
        case 'Basic':
          var auth_string=
            password !== '' && !password && options.password_optional?
              'Basic '+new Buffer(username, "ascii").toString("base64")
            :
              'Basic '+new Buffer(username+':'+password, "ascii").toString("base64")
          this.authorize= function() {
            return auth_string;
          };
          return;
        case 'Digest':
          var realm= auth_parms.realm;
          if (!realm) {
            return note_error("Realm not found in www-authenticate header.");
          }

          var ha1=
            password !== '' && !password && options.password_optional?
              md5(username+':'+realm)
              :
              md5(username+':'+realm+':'+password)
          var nonce= auth_parms.nonce;
          if (!nonce) {
            return note_error("Nonce not found in www-authenticate header.");
          }

          var fixed= 'Digest username="'+username+'",'+
              ' realm="'+realm+'",'+
              ' nonce="'+nonce+'",';
          var qop= auth_parms.qop;
          if (!qop) {
              this.authorize= function(method,digestURI) {
                var ha2= md5(method+':'+digestURI);
                return fixed+
                  ' uri="'+digestURI+'",'+
                  ' response="'+md5(ha1+':'+nonce+':'+ha2)+'",';
              };
              return;
          }
          else {
            var qopa= qop.split(',');
            var q, x, _i, _len;
            for (_i = 0, _len = qopa.length; _i < _len; _i++) {
              if ('auth' === qopa[_i]) {
                var opaque= auth_parms.opaque;
                var algorithm= auth_parms.algorithm;
                if (algorithm) {
                  fixed+= ', algorithm="'+algorithm+'"';
                }
                else {
                  algorithm= 'MD5';
                }
                var a1= 'MD5-sess' == algorithm ?
                  md5(ha1+':'+nonce+':'+cnonce)
                  :
                  ha1;
                this.authorize= function(method,digestURI) {
                  var ha2= md5(method+':'+digestURI);
                  nc= nc+1;
                  var hexed_nc= hex8(nc);
                  var s= fixed+
                    ' uri="'+digestURI+'",'+
                    ' qop=auth,'+
                    ' nc='+hexed_nc+','+
                    ' cnonce="'+cnonce+'",'+
                    ' response="'+md5(a1+':'+nonce+':'+hexed_nc+':'+cnonce+':auth:'+ha2)+'"';
                  if (opaque) {
                    s+= ', opaque="'+opaque+'"';
                  }
                  return s;
                };
                return;
              }
              return note_error('Server does not accept any supported quality of protection techniques.');
            }
          }
          break;
        default:
          return note_error("Unknown scheme");
      }
    }

    return new Authenticator();
  };
};

module.exports.parsers= parsers;<commit_msg>Fix misplaced comma in authorization header string if algorithm specified.<commit_after>
/*
 * www-authenticate
 * https://github.com/randymized/www-authenticate
 *
 * Copyright (c) 2013 Randy McLaughlin
 * Licensed under the MIT license.
 */

'use strict';

var crypto= require('crypto')
  , md5sum = crypto.createHash('md5')
  , parsers= require('./parsers')
  ;

function md5(s) {
  return crypto.createHash('md5').update(s).digest('hex');
}

function hex8(num)
{
  return ("00000000" + num.toString(16)).slice(-8);
}

module.exports = function(username,password,options)
{
  var cnonce;
  if (options) {
    if (toString.call(options.cnonce) == '[object String]')
      cnonce= options.cnonce;
  }
  if (cnonce === void 0) cnonce= crypto.pseudoRandomBytes(8).toString('hex');
  return function parse_header(www_authenticate)
  {
    function Authenticator()
    {
      function note_error(err)
      {
        this.err= err
      }
      var nc= 0;

      var parsed= new parsers.WWW_Authenticate(www_authenticate);
      if (parsed.err) return note_error(parsed.err);
      var auth_parms= this.parms= parsed.parms;
      this.cnonce= cnonce;

      switch(parsed.scheme) {
        case 'Basic':
          var auth_string=
            password !== '' && !password && options.password_optional?
              'Basic '+new Buffer(username, "ascii").toString("base64")
            :
              'Basic '+new Buffer(username+':'+password, "ascii").toString("base64")
          this.authorize= function() {
            return auth_string;
          };
          return;
        case 'Digest':
          var realm= auth_parms.realm;
          if (!realm) {
            return note_error("Realm not found in www-authenticate header.");
          }

          var ha1=
            password !== '' && !password && options.password_optional?
              md5(username+':'+realm)
              :
              md5(username+':'+realm+':'+password)
          var nonce= auth_parms.nonce;
          if (!nonce) {
            return note_error("Nonce not found in www-authenticate header.");
          }

          var fixed= 'Digest username="'+username+'",'+
              ' realm="'+realm+'",'+
              ' nonce="'+nonce+'",';
          var qop= auth_parms.qop;
          if (!qop) {
              this.authorize= function(method,digestURI) {
                var ha2= md5(method+':'+digestURI);
                return fixed+
                  ' uri="'+digestURI+'",'+
                  ' response="'+md5(ha1+':'+nonce+':'+ha2)+'",';
              };
              return;
          }
          else {
            var qopa= qop.split(',');
            var q, x, _i, _len;
            for (_i = 0, _len = qopa.length; _i < _len; _i++) {
              if ('auth' === qopa[_i]) {
                var opaque= auth_parms.opaque;
                var algorithm= auth_parms.algorithm;
                if (algorithm) {
                  fixed+= ' algorithm="'+algorithm+'",';
                }
                else {
                  algorithm= 'MD5';
                }
                var a1= 'MD5-sess' == algorithm ?
                  md5(ha1+':'+nonce+':'+cnonce)
                  :
                  ha1;
                this.authorize= function(method,digestURI) {
                  var ha2= md5(method+':'+digestURI);
                  nc= nc+1;
                  var hexed_nc= hex8(nc);
                  var s= fixed+
                    ' uri="'+digestURI+'",'+
                    ' qop=auth,'+
                    ' nc='+hexed_nc+','+
                    ' cnonce="'+cnonce+'",'+
                    ' response="'+md5(a1+':'+nonce+':'+hexed_nc+':'+cnonce+':auth:'+ha2)+'"';
                  if (opaque) {
                    s+= ', opaque="'+opaque+'"';
                  }
                  return s;
                };
                return;
              }
              return note_error('Server does not accept any supported quality of protection techniques.');
            }
          }
          break;
        default:
          return note_error("Unknown scheme");
      }
    }

    return new Authenticator();
  };
};

module.exports.parsers= parsers;<|endoftext|>


<commit_before>// ensure that a button's class is correct
// based on its action
function update_button_content( element ) {
  $.ajax({
    type: 'GET',
    url: '/api/' + $(element).data('route') + '/',
    success: function( data ) {
      if ( data === 'true' ) {
        // it's running
        // class: btn-success
        // action: stop
        $(element)
          .removeClass('btn-danger')
          .addClass('btn-success')
          .data('action', 'stop');
      } else {
        // it's not running
        // class: btn-success
        // action: stop
        $(element)
          .removeClass('btn-success')
          .addClass('btn-danger')
          .data('action', 'start');
      }
    }
  })
}

function update_all_buttons() {
  var buttons = $('.service-button');

  buttons.each(function(i, button) {
    update_button_content( button );
  });

  buttons
    .click(function() {
      var route = $(this).data('route'),
          action = $(this).data('action'),
          element = $(this);

      $.ajax({
        type: 'POST',
        url: [ '/api', route, action ].join('/'),
        data: '',
        success: function() {
          update_button_content( element );
        },
        error: function() {
          alert('ERROR');
        }
      });

      return false;
    });
}

$(function() {
  update_all_buttons();

  $('#refresh-button').click(update_all_buttons);
});

<commit_msg>rewrote javascript<commit_after>(function( document, window, $ ) {

  var ButtonController = function( timeout ) {
    this.timeout = timeout; // how often to update the ui

    this.autoUpdateThread = null; // store the setTimeout
  }

  // ensure that a button's class is correct
  // based on its action
  ButtonController.prototype.updateButtonContent = function( element ) {
    $.ajax({
      type: 'GET',
      url: '/api/' + $(element).data('route') + '/',
      success: function( data ) {
        if ( data === 'true' ) {
          // it's running
          // class: btn-success
          // action: stop
          $(element)
            .removeClass('btn-danger')
            .addClass('btn-success')
            .data('action', 'stop');
        } else {
          // it's not running
          // class: btn-success
          // action: stop
          $(element)
            .removeClass('btn-success')
            .addClass('btn-danger')
            .data('action', 'start');
        }
      }
    });
  }

  ButtonController.prototype.updateAllButtons = function() {
    var buttons = $('.service-button');

    // update each individual button
    buttons.each(function(i, button) {
      this.updateButtonContent( button );
    }.bind(this));
  }

  // configure each button so when clicked, it'll perform the appropriate action
  ButtonController.prototype.attachActionToButtons = function( buttons ) {
    var bc = this;

    buttons.click(function() {
      var route = $(this).data('route'),
          action = $(this).data('action'),
          element = $(this);

      $.ajax({
        type: 'POST',
        url: [ '/api', route, action ].join('/'),
        data: '',
        success: function() {
          this.updateButtonContent( element );

          console.log('slipping interval');
          clearInterval( bc.autoUpdateThread );
          bc.autoUpdateThread = null;
          bc.timedUpdateAllButtons();
        }.bind(bc),
        error: function() {
          alert('ERROR');
        }
      });

      return false;
    });
  }

  ButtonController.prototype.timedUpdateAllButtons = function() {
    // skip the fist run if there's a current thread configured...
    if ( this.autoUpdateThread !== null ) {
      console.log('updating by timed...')
      this.updateAllButtons();
    } else {
      console.log('skipping...');
    }

    this.autoUpdateThread = setTimeout( this.timedUpdateAllButtons.bind(this), this.timeout );
  }

  $(function() {
    var bc = new ButtonController( 5000 );

    bc.updateAllButtons();
    bc.attachActionToButtons( $('.service-button') );
    bc.timedUpdateAllButtons();

    $('#refresh-button').click(bc.updateAllButtons.bind(bc));
  });

})( document, window, jQuery );

<|endoftext|>


<commit_before>var ASTRAL = {}

// sets up the Astral flash streaming module and instructs it to upload to and
function previewStream(streamSlug) {
    $.ajax({
        url: "http://localhost:8000/settings",
        success: function(data) {
            ASTRAL.astral_streaming_module.setupAndStream(ASTRAL.userRole,
                streamSlug,
                "rtmp://localhost:" + data.rtmp_port + "/"
                    + data.rtmp_resource);
        },
        dataType: 'jsonp'
    });
}

function changeStreamStatus(streamSlug, streamingStatus) {
    $.ajax({
        url: "http://localhost:8000/stream/" + streamSlug + "?streaming="
                + streamingStatus,
        dataType: 'jsonp'
    });
}

function stopStream() {
    ASTRAL.astral_streaming_module.stopStreaming();
    $.ajax({
        url: "http://localhost:8000/settings",
        success: function(data) {
            ASTRAL.astral_streaming_module.setupAndStream(ASTRAL.userRole,
                streamSlug,
                "rtmp://localhost:" + data.rtmp_port + "/"
                    + data.rtmp_resource);
        },
        dataType: 'jsonp'
    });

    $.ajax({
        type: "DELETE",
        url: "http://localhost:8000/stream/" + streamSlug,
        dataType: 'jsonp'
    });
}

// sets up the Astral flash streaming module and instructs it to connect to a
// specific port on localhost, an HTTP tunnel to a remote RTMP server
function startConsuming(streamSlug) {
    $.ajax({
        type: "POST",
        url: "http://localhost:8000/stream/" + streamSlug + "/tickets",
        success: function(data) {
            $.ajax({
                url: "http://localhost:8000/settings",
                success: function(data) {
                    ASTRAL.astral_streaming_module.setupAndStream(
                        ASTRAL.userRole,
                        streamSlug, "", "",
                        "rtmp://localhost:" + data.rtmp_tunnel_port + "/"
                            + data.rtmp_resource);
                },
                dataType: 'jsonp'
            });
        }
    });
}

function stopConsuming(streamSlug) {
    $.ajax({
        type: "DELETE",
        url: "http://localhost:8000/stream/" + streamSlug + "/ticket",
        dataType: 'jsonp'
    });
}

// used by flash to display error messages
function displayFromFlash(msg) {
    $("div#streaming_flash_error").text(msg);
}

$(document).ready(function() {
    WebFont.load({
        custom: {
            families: ['star-lit-night'],
            urls: ['/css/font.css']
        }
    });

    ASTRAL.astral_streaming_module = document.getElementById("astral");
    // Either publisher or consumer
    ASTRAL.userRole = "publisher";

    if (ASTRAL.astral_streaming_module) {
        // get the stream's unique identifier on the network
        streamSlug = $("div#slug").text();
        if(streamSlug) {
            previewStream(streamSlug);
            $("#streaming_notice").text("This is a preview - the video " +
                "will not be streaming until you being publishing.");
        }

        $("#consume_start").removeClass("hidden");
        $("#publish_start").removeClass("hidden");
        $("#publish_stop").removeClass("hidden");

        $("#publish_start").click(function(e) {
            $("#publish_pause").removeClass("hidden");
            $("#publish_start").addClass("hidden");
            $("#streaming_notice").text("Video is streaming to the network.");

            changeStreamStatus(streamSlug, true);
            return false;
        });

        $("#publish_pause").click(function(e) {
            $("#publish_start").removeClass("hidden");
            $("#publish_pause").addClass("hidden");
            $("#streaming_notice").text("Streaming is now paused.");
            changeStreamStatus(streamSlug, false);
            return false;
        });

        $("#publish_stop").click(function(e) {
            $("#consume_start").removeClass("hidden");
            $("#publish_stop").addClass("hidden");
            $("#publish_pause").addClass("hidden");
            $("#publish_start").addClass("hidden");
            $("#streaming_notice").text(
                    "Stopped publishing. Please reload page.");
            stopStream();
            return false;
        });

        $("#consume_stop").click(function(e) {
            $("#consume_start").removeClass("hidden");
            $("#consume_stop").addClass("hidden");
            $("#streaming_notice").text("Stopped streaming.");
            stopConsuming(streamSlug);
            return false;
        });

        $("#consume_start").click(function(e) {
            $("#streaming_notice").text("Streaming from network.");
            $("#consume_start").addClass("hidden");
            $("#consume_stop").removeClass("hidden");
            startConsuming(streamSlug);
            return false;
        });
    }
});
<commit_msg>Only load the preview if on the publish page.<commit_after>var ASTRAL = {}

// sets up the Astral flash streaming module and instructs it to upload to and
function previewStream(streamSlug) {
    $.ajax({
        url: "http://localhost:8000/settings",
        success: function(data) {
            ASTRAL.astral_streaming_module.setupAndStream(ASTRAL.userRole,
                streamSlug,
                "rtmp://localhost:" + data.rtmp_port + "/"
                    + data.rtmp_resource);
        },
        dataType: 'jsonp'
    });
}

function changeStreamStatus(streamSlug, streamingStatus) {
    $.ajax({
        url: "http://localhost:8000/stream/" + streamSlug + "?streaming="
                + streamingStatus,
        dataType: 'jsonp'
    });
}

function stopStream() {
    ASTRAL.astral_streaming_module.stopStreaming();
    $.ajax({
        url: "http://localhost:8000/settings",
        success: function(data) {
            ASTRAL.astral_streaming_module.setupAndStream(ASTRAL.userRole,
                streamSlug,
                "rtmp://localhost:" + data.rtmp_port + "/"
                    + data.rtmp_resource);
        },
        dataType: 'jsonp'
    });

    $.ajax({
        type: "DELETE",
        url: "http://localhost:8000/stream/" + streamSlug,
        dataType: 'jsonp'
    });
}

// sets up the Astral flash streaming module and instructs it to connect to a
// specific port on localhost, an HTTP tunnel to a remote RTMP server
function startConsuming(streamSlug) {
    $.ajax({
        type: "POST",
        url: "http://localhost:8000/stream/" + streamSlug + "/tickets",
        success: function(data) {
            $.ajax({
                url: "http://localhost:8000/settings",
                success: function(data) {
                    ASTRAL.astral_streaming_module.setupAndStream(
                        ASTRAL.userRole,
                        streamSlug, "", "",
                        "rtmp://localhost:" + data.rtmp_tunnel_port + "/"
                            + data.rtmp_resource);
                },
                dataType: 'jsonp'
            });
        }
    });
}

function stopConsuming(streamSlug) {
    $.ajax({
        type: "DELETE",
        url: "http://localhost:8000/stream/" + streamSlug + "/ticket",
        dataType: 'jsonp'
    });
}

// used by flash to display error messages
function displayFromFlash(msg) {
    $("div#streaming_flash_error").text(msg);
}

$(document).ready(function() {
    WebFont.load({
        custom: {
            families: ['star-lit-night'],
            urls: ['/css/font.css']
        }
    });

    ASTRAL.astral_streaming_module = document.getElementById("astral");
    // Either publisher or consumer
    ASTRAL.userRole = "publisher";

    if (ASTRAL.astral_streaming_module) {
        // get the stream's unique identifier on the network
        var streamSlug = $("div#slug").text();
        if(streamSlug && $("#publish_start").length != 0) {
            previewStream(streamSlug);
            $("#streaming_notice").text("This is a preview - the video " +
                "will not be streaming until you being publishing.");
        }

        $("#consume_start").removeClass("hidden");
        $("#publish_start").removeClass("hidden");
        $("#publish_stop").removeClass("hidden");

        $("#publish_start").click(function(e) {
            $("#publish_pause").removeClass("hidden");
            $("#publish_start").addClass("hidden");
            $("#streaming_notice").text("Video is streaming to the network.");

            changeStreamStatus(streamSlug, true);
            return false;
        });

        $("#publish_pause").click(function(e) {
            $("#publish_start").removeClass("hidden");
            $("#publish_pause").addClass("hidden");
            $("#streaming_notice").text("Streaming is now paused.");
            changeStreamStatus(streamSlug, false);
            return false;
        });

        $("#publish_stop").click(function(e) {
            $("#consume_start").removeClass("hidden");
            $("#publish_stop").addClass("hidden");
            $("#publish_pause").addClass("hidden");
            $("#publish_start").addClass("hidden");
            $("#streaming_notice").text(
                    "Stopped publishing. Please reload page.");
            stopStream();
            return false;
        });

        $("#consume_stop").click(function(e) {
            $("#consume_start").removeClass("hidden");
            $("#consume_stop").addClass("hidden");
            $("#streaming_notice").text("Stopped streaming.");
            stopConsuming(streamSlug);
            return false;
        });

        $("#consume_start").click(function(e) {
            $("#streaming_notice").text("Streaming from network.");
            $("#consume_start").addClass("hidden");
            $("#consume_stop").removeClass("hidden");
            startConsuming(streamSlug);
            return false;
        });
    }
});
<|endoftext|>


<commit_before>/**
 * @file xsdwebformparser.js
 * XSD Schema to HTML5 Web Form
 * @author George Bouris <gb@eworx.gr>
 * @copyright Copyright (C) 2017 Eworx, George Bouris. All rights reserved.
 */

'use strict';

import { XmlDocument } from 'xmldoc';
import tagParser from './xsdwebformparsertags.js';
import HtmlTagParser from './xsdwebformparserhtmltags.js';

/**
 * Class XSDWebFormParser
 * Parser for XSD Schema to HTML5
 */
class XSDWebFormParser
{

    /**
     * Class constructor
     */
    constructor()
    {

        this.ELEMENT_TYPES = {
            "xs:element": tagParser.parseElement,
            "xs:import": tagParser.parseImport,
            "xs:simpleType": tagParser.parseSimpleType,
            "xs:complexType": tagParser.parseComplexType,
            "xs:sequence": tagParser.parseSequence,
            "xs:restriction": tagParser.parseRestriction,
            "xs:annotation": tagParser.parseAnnotation,
            "xs:documentation": tagParser.parseDocumentation,
            "xs:enumeration": tagParser.parseEnumeration,
            "xs:minInclusive": tagParser.parseMinInclusive,
            "xs:maxInclusive": tagParser.parseMaxInclusive,
            "xs:union": tagParser.parseUnion,
            "xs:pattern": tagParser.parsePattern,
            "xs:whiteSpace": tagParser.parseWhiteSpace,
            "xs:minLength": tagParser.parseMinLength,
            "xs:maxLength": tagParser.parseMaxLength
        };

        this.htmlTagParser = new HtmlTagParser();

        this.showLog = true;
        this.verbose = true;

        this.htmlTagParser.setLog(this.showLog);
        this.htmlTagParser.setVerbose((this.showLog && this.verbose));
        tagParser.setLog((this.showLog && this.verbose));

    }

    /**
     * parse - Parse XML Document
     * @param xml
     */
    parse(xObject)
    {

        if (this.showLog) {
           this.logXSD(xObject);
        }

        // Create XML Document for XSD
        var xsdItem = new XmlDocument(xObject.xdata);
        xsdItem.level = 0;
        this.xsdParse(xsdItem);

        if (this.showLog) {
            this.logHTML(xObject);
        }

        // Create XML Document for FORM.XML
        var htmlItem = new XmlDocument(xObject.hdata);
        htmlItem.level = 0;
        this.htmlTagParser.htmlParse(htmlItem, xsdItem);

        if (this.showLog) {
            console.log("\x1b[0m\x1b[32mHTML OBJECTS: \x1b[0m\x1b[36m");
            process.stdout.write(this.htmlTagParser.HTMLObjects[0].itemObject.htmlXML.attr.element);
            if (this.verbose) {
                    console.log("\x1b[0m\x1b[2m");
                    console.log(this.htmlTagParser.HTMLObjects);
                }
            console.log("\x1b[0m");
        }

        if (this.showLog) {
            console.log("\n\x1b[2m\x1b[33m==================================================================================================================================================\n\x1b[0m");
        }
    }

    /**
     * xsdParse - Parse inner XML Document
     * @param xsdItem
     */
    xsdParse(xsdItem)
    {

        if (this.showLog)
            this.showItemLog(xsdItem);

        // Loop through Tag's childNodes
        if (xsdItem.children) {
            for (let i = 0, l = xsdItem.children.length; i < l; i++) {
                if (xsdItem.children[i].type === "element") {

                    // Parse Tag Tag
                    this.parseXSDItem(xsdItem.children[i].name);
                    xsdItem.children[i].xparent = xsdItem;
                    xsdItem.children[i].level = xsdItem.level + 1;

                    // Recursive call
                    this.xsdParse(xsdItem.children[i]);

                }
            };
        }

    }

    /**
     * parseXSDItem - Parse XML Tag
     * @param item
     */
    parseXSDItem(item)
    {

        if ((item in this.ELEMENT_TYPES)) {
            (this.ELEMENT_TYPES[item])(item);
        } else {
            console.log(`\n************* Unknown Tag {${item}} *************\n`);
            process.stdout.write('\x07');
        }

    }

    /**
     * showItemLog - ShowLog
     * @param xsdItem
     */
    showItemLog(xsdItem)
    {

        let xspace = "  ";
        for (let i = 0; i < xsdItem.level; i++) {
            xspace += "\t";
        }

        console.log(`${xspace}\x1b[0m\x1b[31m▓▓▓▓▓▓▓▓▓▓▓▓▓\x1b[0m`);
        process.stdout.write(`${xspace}\x1b[2m▓▓▓▓ \x1b[0m\x1b[2mL:${xsdItem.level} \x1b[2m▓▓▓▓\x1b[0m\x1b[31m⇢\x1b[0m `);

        if (xsdItem.children) {
            process.stdout.write(`\x1b[1m${xsdItem.name}`);

            if (xsdItem.attr.name) {
                process.stdout.write(` - ${xsdItem.attr.name}`);

                if (this.verbose) {
                    if (xsdItem.name === "xs:element") {

                        var txmlItem = xsdItem.toString();
                        txmlItem = txmlItem.split("\n").join("");
                        txmlItem = txmlItem.split("<").join(xspace + `\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓\t \x1b[2m<`);

                        let pos1 = txmlItem.indexOf("<xs:documentation>");
                        if (pos1 > 0 ){
                            var pos2 = txmlItem.indexOf("</xs:documentation>");
                            txmlItem = txmlItem.substring(0, pos1) + "<xs:documentation> ..." + txmlItem.substring(pos2);
                        }

                        process.stdout.write(`\x1b[2m${txmlItem}`);
                    }
                }
            }

            process.stdout.write(`\n\x1b[2m${xspace}▓▓▓▓▓▓▓▓▓▓▓▓▓`); // ${xsdItem.name} | ${xsdItem.type} | ${xsdItem.children.length} ]`);
            if (xsdItem.xparent) {
                console.log(`\x1b[32m  parent ::\x1b[1m ${xsdItem.xparent.name}\x1b[0m`);

                if (xsdItem.xparent.attr.name) {
                    console.log(`${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[0m\x1b[36m par.name ::\x1b[1m ${xsdItem.xparent.attr.name}\x1b[0m`);
                }
            }
        }

        if (xsdItem.level === 0) {
            console.log(" ");
        }

        // console.log(`${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓`);
        process.stdout.write(`\x1b[2m${xspace}         ▒▒`); //\n${xspace}         ▒▒\x1b[0m
        if (!tagParser.getLog()) {
            console.log(" ");
        }

    }

    /**
     * logXSD
     * @param xObject
     */
    logXSD(xObject){

        console.log("\n\n\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
        console.log(`                                                             \x1b[1m\x1b[36mFILE : ${xObject.xfile} \x1b[0m\n`);
        console.log("\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");

    }

    /**
     * logHTML
     * @param xObject
     */
    logHTML(xObject){

        console.log("\n\n\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
        console.log(`                                                             \x1b[1m\x1b[33mFILE : ${xObject.hfile} \x1b[0m\n`);
        console.log("\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");

    }

}

module.exports = XSDWebFormParser;<commit_msg>Parsing html data<commit_after>/**
 * @file xsdwebformparser.js
 * XSD Schema to HTML5 Web Form
 * @author George Bouris <gb@eworx.gr>
 * @copyright Copyright (C) 2017 Eworx, George Bouris. All rights reserved.
 */

'use strict';

import { XmlDocument } from 'xmldoc';
import tagParser from './xsdwebformparsertags.js';
import HtmlTagParser from './xsdwebformparserhtmltags.js';

/**
 * Class XSDWebFormParser
 * Parser for XSD Schema to HTML5
 */
class XSDWebFormParser
{

    /**
     * Class constructor
     */
    constructor()
    {

        this.ELEMENT_TYPES = {
            "xs:element": tagParser.parseElement,
            "xs:import": tagParser.parseImport,
            "xs:simpleType": tagParser.parseSimpleType,
            "xs:complexType": tagParser.parseComplexType,
            "xs:sequence": tagParser.parseSequence,
            "xs:restriction": tagParser.parseRestriction,
            "xs:annotation": tagParser.parseAnnotation,
            "xs:documentation": tagParser.parseDocumentation,
            "xs:enumeration": tagParser.parseEnumeration,
            "xs:minInclusive": tagParser.parseMinInclusive,
            "xs:maxInclusive": tagParser.parseMaxInclusive,
            "xs:union": tagParser.parseUnion,
            "xs:pattern": tagParser.parsePattern,
            "xs:whiteSpace": tagParser.parseWhiteSpace,
            "xs:minLength": tagParser.parseMinLength,
            "xs:maxLength": tagParser.parseMaxLength
        };

        this.htmlTagParser = new HtmlTagParser();

        this.showLog = true;
        this.verbose = true;

        this.htmlTagParser.setLog(this.showLog);
        this.htmlTagParser.setVerbose((this.showLog && this.verbose));
        tagParser.setLog((this.showLog && this.verbose));

    }

    /**
     * parse - Parse XML Document
     * @param xml
     */
    parse(xObject)
    {

        if (this.showLog) {
           this.logXSD(xObject);
        }

        // Create XML Document for XSD
        var xsdItem = new XmlDocument(xObject.xdata);
        xsdItem.level = 0;
        this.xsdParse(xsdItem);

        if (this.showLog) {
            this.logHTML(xObject);
        }

        // Create XML Document for FORM.XML
        var htmlItem = new XmlDocument(xObject.hdata);
        htmlItem.level = 0;
        this.htmlTagParser.htmlParse(htmlItem, xsdItem);

        if (this.showLog) {
            console.log("\x1b[0m\x1b[32mHTML OBJECTS: \x1b[0m\x1b[36m");
            process.stdout.write(this.htmlTagParser.HTMLObjects[0].itemObject.htmlXML.attr.element);
            if (this.verbose) {
                    console.log("\x1b[0m\x1b[2m");
                    console.log(this.htmlTagParser.HTMLObjects);
                }
            console.log("\x1b[0m");
        }

        if (this.showLog) {
            console.log("\n\x1b[2m\x1b[33m==================================================================================================================================================\n\x1b[0m");
        }
    }

    /**
     * xsdParse - Parse inner XML Document
     * @param xsdItem
     */
    xsdParse(xsdItem)
    {

        if (this.showLog)
            this.showItemLog(xsdItem);

        // Loop through Tag's childNodes
        if (xsdItem.children) {
            for (let i = 0, l = xsdItem.children.length; i < l; i++) {
                if (xsdItem.children[i].type === "element") {

                    // Parse Tag Tag
                    this.parseXSDItem(xsdItem.children[i].name);
                    xsdItem.children[i].xparent = xsdItem;
                    xsdItem.children[i].level = xsdItem.level + 1;

                    // Recursive call
                    this.xsdParse(xsdItem.children[i]);

                }
            };
        }

    }

    /**
     * parseXSDItem - Parse XML Tag
     * @param item
     */
    parseXSDItem(item)
    {

        if ((item in this.ELEMENT_TYPES)) {
            (this.ELEMENT_TYPES[item])(item);
        } else {
            console.log(`\n************* Unknown Tag {${item}} *************\n`);
            process.stdout.write('\x07');
        }

    }

    /**
     * showItemLog - ShowLog
     * @param xsdItem
     */
    showItemLog(xsdItem)
    {

        let xspace = "  ";
        for (let i = 0; i < xsdItem.level; i++) {
            xspace += "\t";
        }

        console.log(`${xspace}\x1b[0m\x1b[31m▓▓▓▓▓▓▓▓▓▓▓▓▓\x1b[0m`);
        process.stdout.write(`${xspace}\x1b[2m▓▓▓▓ \x1b[0m\x1b[2mL:${xsdItem.level} \x1b[2m▓▓▓▓\x1b[0m\x1b[31m⇢\x1b[0m `);

        if (xsdItem.children) {
            process.stdout.write(`\x1b[1m${xsdItem.name}`);

            if (xsdItem.attr.name) {
                process.stdout.write(` - ${xsdItem.attr.name}`);

                if (this.verbose) {
                    if (xsdItem.name === "xs:element") {

                        var txmlItem = xsdItem.toString();
                        txmlItem = txmlItem.split("\n").join("");
                        txmlItem = txmlItem.split("<").join(xspace + `\n${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓\t \x1b[2m<`);

                        let pos1 = txmlItem.indexOf("<xs:documentation>");
                        if (pos1 > 0 ){
                            var pos2 = txmlItem.indexOf("</xs:documentation>");
                            txmlItem = txmlItem.substring(0, pos1) + "<xs:documentation> ..." + txmlItem.substring(pos2);
                        }

                        process.stdout.write(`\x1b[2m${txmlItem}`);
                    }
                }
            }

            process.stdout.write(`\n\x1b[2m${xspace}▓▓▓▓▓▓▓▓▓▓▓▓▓`); // ${xsdItem.name} | ${xsdItem.type} | ${xsdItem.children.length} ]`);
            if (xsdItem.xparent) {
                console.log(`\x1b[32m  parent ::\x1b[1m ${xsdItem.xparent.name}\x1b[0m`);

                if (xsdItem.xparent.attr.name) {
                    console.log(`${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓ \x1b[0m\x1b[36m par.name ::\x1b[1m ${xsdItem.xparent.attr.name}\x1b[0m`);
                }
            }
        }

        if (xsdItem.level === 0) {
            console.log(" ");
        }

        // console.log(`${xspace}\x1b[2m▓▓▓▓▓▓▓▓▓▓▓▓▓`);
        process.stdout.write(`\x1b[2m${xspace}         ▒▒`); //\n${xspace}         ▒▒\x1b[0m
        if (!tagParser.getLog()) {
            console.log(" ");
        }

    }

    /**
     * logXSD
     * @param xObject
     */
    logXSD(xObject){

        console.log("\n\n\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
        console.log(`                                                             \x1b[1m\x1b[36mFILE : ${xObject.xfile} \x1b[0m\n`);
        console.log("\x1b[2m\x1b[36m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");

    }

    /**
     * logHTML
     * @param xObject
     */
    logHTML(xObject){

        console.log("\n\n\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m");
        console.log(`                                                             \x1b[1m\x1b[33mFILE : ${xObject.hfile} \x1b[0m\n`);
        console.log("\x1b[2m\x1b[33m__________________________________________________________________________________________________________________________________________________\n\x1b[0m\n\n");

    }

}

module.exports = XSDWebFormParser;<|endoftext|>


<commit_before>'use strict';

var db                  = require('../db')
  , assign              = require('es5-ext/object/assign')
  , copy                = require('es5-ext/object/copy')
  , _                   = require('mano').i18n.bind('View: Statistics')
  , memoize             = require('memoizee')
  , location            = require('mano/lib/client/location')
  , setupQueryHandler   = require('../utils/setup-client-query-handler')
  , resolveFullStepPath = require('../utils/resolve-processing-step-full-path')
  , capitalize          = require('es5-ext/string/#/capitalize')
  , uncapitalize        = require('es5-ext/string/#/uncapitalize')
  , Duration            = require('duration')
  , getData             = require('mano/lib/client/xhr-driver').get
  , getQueryHandlerConf = require('../routes/utils/get-statistics-time-query-handler-conf')
  , ObjservableValue    = require('observable-value')
  , nextTick            = require('next-tick')
  , observableResult    = new ObjservableValue();

exports._servicesColors  = ["#673AB7", "#FFC107", "#FF4B4B", "#3366CC"];
exports._stepsColors     = ["#673AB7", "#FFC107", "#FF4B4B", "#3366CC"];
exports._customChartsDOM     = Function.prototype;
exports._customChartsGetData = Function.prototype;

exports._commonOptions = {
	colors: exports._servicesColors, // by default colors of the services
	animation: {
		startup: true,
		duration: 1200,
		easing: "in"
	},
	legend: { position: "bottom", maxLines: 3 },
	chartArea: { width: "100%", height: "75%" },
	height: 300,
	is3D: true,
	isStacked: true,
	titlePosition: "out",
	axisTitlesPosition: "in",
	vAxis: {
		textPosition: "in",
		viewWindow: { min: 0 },
		minValue: 0
	},
	width: "100%"
};

var queryServer = memoize(function (query) {
	return getData('/get-dashboard-data/', query);
}, {
	normalizer: function (args) { return JSON.stringify(args[0]); },
	max: 1000
});

var getServiceNames = function () {
	var services = {};

	db.BusinessProcess.extensions.forEach(function (BusinessProcessClass) {
		services[uncapitalize.call(BusinessProcessClass.__id__.slice('BusinessProcess'.length))] =
			{ label: BusinessProcessClass.prototype.label };
	});

	return services;
};

var dayRangeConfig = {
	31: 1,
	182: 7,
	365: 30,
	Infinity: 365
};

var getGroupByCount = function (dateFrom, dateTo) {
	var duration, groupBy;
	duration = new Duration(dateFrom, dateTo);

	Object.keys(dayRangeConfig).some(function (rangeKey) {
		if (duration.days <= rangeKey) {
			groupBy = dayRangeConfig[rangeKey];
			return true;
		}
	});

	return groupBy;
};

var getStepLabelByShortPath = function (processingStepsMeta) {
	return function (shortStepPath) {
		return db['BusinessProcess' +
			capitalize.call(processingStepsMeta[shortStepPath]._services[0])].prototype
			.processingSteps.map.getBySKeyPath(resolveFullStepPath(shortStepPath)).label;
	};
};

var getFilesCompletedPerDay = function (data) {
	var result = { handle: 'chart-files-completed-per-day' }, chart = {
		options: assign(copy(exports._commonOptions), {
			orientation: 'horizontal'
		}),
		data: [["Service"]]
	}, days = Object.keys(data.filesApprovedByDay),
		dateFrom, dateTo, dateFromStr, rowData, rangeKey, groupByCount,
		daysCount = 0, currentRange,
		setupRange, addAmountToRange, setupRowData;

	if (!days || !days.length) {
		result.data = null;
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	dateFrom = new Date(Date.parse(data.filesApprovedByDay.dateFrom));
	dateTo   = new Date(Date.parse(data.filesApprovedByDay.dateTo));
	groupByCount = getGroupByCount(dateFrom, dateTo);

	setupRange = function (currentRange) {
		Object.keys(services).forEach(function (serviceName) {
			currentRange.services[serviceName] = 0;
		});
	};

	addAmountToRange = function (currentRange, dateFromStr) {
		Object.keys(services).forEach(function (serviceName) {
			var amount;
			amount = data.filesApprovedByDay[dateFromStr][serviceName] || 0;
			currentRange.services[serviceName] += amount;
		});
	};

	setupRowData = function (currentRange, rowData) {
		Object.keys(currentRange.services).forEach(function (service) {
			rowData.push(currentRange.services[service] || 0);
		});
	};
	while (dateFrom <= dateTo) {
		daysCount++;
		dateFromStr = dateFrom.toISOString().slice(0, 10);
		if (!currentRange) {
			currentRange = { name: dateFrom.toLocaleDateString(db.locale), services: {} };
			setupRange(currentRange);
		}
		if (data.filesApprovedByDay[dateFromStr]) {
			addAmountToRange(currentRange, dateFromStr);
		}
		if ((daysCount % groupByCount === 0) || dateFrom.getTime() === dateTo.getTime()) {
			rangeKey = groupByCount === 1 ? currentRange.name : currentRange.name + ' - ' +
				dateFrom.toLocaleDateString(db.locale);
			rowData = [rangeKey];
			setupRowData(currentRange, rowData);
			chart.data.push(rowData);
			currentRange = null;
		}
		dateFrom.setUTCDate(dateFrom.getUTCDate() + 1);
	}

	return assign(result, chart);
};

var getFilesCompletedByStep = function (data) {
	var result = { handle: 'chart-files-completed-by-service' }, chart = {
		options: exports._commonOptions,
		data: [["Service"]]
	};
	if (!Object.keys(data.byStepAndService).length) {
		return result;
	}

	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	Object.keys(data.byStepAndService).forEach(function (shortPath) {
		var stepData = [getStepLabelByShortPath(shortPath)];
		Object.keys(services).forEach(function (serviceName) {
			if (!data.byStepAndService[shortPath][serviceName]) {
				stepData.push(0);
				return;
			}
			stepData.push(data.byStepAndService[shortPath][serviceName].processed);
		});
		chart.data.push(stepData);
	});

	return assign(result, chart);
};

var getPendingFiles = function (data) {
	var result = { handle: 'chart-pending-files' }, chart = {
		options: assign(copy(exports._commonOptions), {
			colors: exports._stepsColors
		}),
		drawMethod: 'PieChart',
		data: [["Role", "Count"]]
	};

	if (!data.pendingFiles || !Object.keys(data.pendingFiles).length) {
		return result;
	}

	Object.keys(data.pendingFiles).forEach(function (shortPath) {
		chart.data.push([getStepLabelByShortPath(shortPath), data.pendingFiles[shortPath] || 0]);
	});

	return assign(result, chart);
};

var getAverageTime = function (data) {
	var result = { handle: 'chart-by-step-and-service' }, chart = {
		options: assign(copy(exports._commonOptions), {
			isStacked: false
		}),
		data: [["Role"]]
	};

	if (!data.byStepAndService || !Object.keys(data.byStepAndService).length) {
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	Object.keys(data.byStepAndService).forEach(function (shortPath) {
		if (shortPath === 'frontDesk') return;
		var stepData = [getStepLabelByShortPath(shortPath)];
		Object.keys(services).forEach(function (serviceName) {
			if (!data.byStepAndService[shortPath][serviceName]) {
				stepData.push(0);
				return;
			}
			stepData.push(
				Math.round(data.byStepAndService[shortPath][serviceName].avgTime / 1000 / 60 / 60 / 24)
			);
		});
		chart.data.push(stepData);
	});

	return assign(result, chart);
};

var getAverageTimeByService = function (data) {
	var result = { handle: 'chart-by-service' }, chart = {
		options: assign(copy(exports._commonOptions), {
			legend: null
		}),
		data: [["Service", "Data", { role: "style" }]]
	};

	if (!data.byService || !Object.keys(data.byService).length) {
		return result;
	}

	var services = getServiceNames(), i = 0;

	Object.keys(services).forEach(function (serviceName) {
		var row = [];
		row.push(services[serviceName].label);
		row.push(Math.round(
			(data.byService[serviceName] ? data.byService[serviceName].avgTime : 0) / 1000 / 60 / 60 / 24
		));
		row.push(chart.options.colors[i]);
		i++;
		chart.data.push(row);
	});

	return assign(result, chart);
};

var getWithdrawalTime = function (data) {
	var result = { handle: 'chart-withdrawal-time' }, chart = {
		options: assign(copy(exports._commonOptions), {
			isStacked: false,
			legend: null,
			axisTitlesPosition: "none"
		}),
		data: [["Service", "Data", { role: "style" }]]
	}, i = 0;

	if (!data.byStepAndService.frontDesk) {
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		var row = [];
		row.push(services[serviceName].label);
		if (!data.byStepAndService.frontDesk[serviceName]) {
			row.push(0);
		} else {
			row.push(
				Math.round(data.byStepAndService.frontDesk[serviceName].avgTime / 1000 / 60 / 60 / 24)
			);
		}
		row.push(chart.options.colors[i]);
		i++;
		chart.data.push(row);
	});

	return assign(result, chart);
};

var updateChartsData = function (data) {
	var dataForCharts = [], customChartsData = [];
	if (!data) return;

	dataForCharts.push(getFilesCompletedPerDay(data));
	dataForCharts.push(getFilesCompletedByStep(data));
	dataForCharts.push(getPendingFiles(data));
	dataForCharts.push(getAverageTime(data));
	dataForCharts.push(getAverageTimeByService(data));
	dataForCharts.push(getWithdrawalTime(data));
	customChartsData = exports._customChartsGetData.call(this, data);
	if (customChartsData && customChartsData.length) {
		dataForCharts = dataForCharts.concat(customChartsData);
	}
	observableResult.value = dataForCharts;

	nextTick(function () {
		document.emit('statistics-chart-update');
	});
};

exports._parent = require('./statistics-base');

exports['dashboard-nav'] = { class: { 'pills-nav-active': true } };

exports['statistics-main'] = function () {
	var queryHandler;
	getStepLabelByShortPath = getStepLabelByShortPath(this.processingStepsMeta);

	queryHandler = setupQueryHandler(getQueryHandlerConf({
		db: db,
		processingStepsMeta: this.processingStepsMeta,
		queryConf: null
	}), location, '/');

	queryHandler.on('query', function (query) {
		if (query.dateFrom) {
			query.dateFrom = query.dateFrom.toJSON();
		}
		if (query.dateTo) {
			query.dateTo = query.dateTo.toJSON();
		}
		queryServer(query)(function (result) {
			updateChartsData(result);
		}).done();
	});

	section({ class: 'section-primary users-table-filter-bar' },
		form({ action: '/', autoSubmit: true },
			div(
				{ class: 'users-table-filter-bar-status' },
				label({ for: 'date-from-input' }, _("Date from"), ":"),
				input({ id: 'date-from-input', type: 'date',
					name: 'dateFrom', value: location.query.get('dateFrom') })
			),
			div(
				{ class: 'users-table-filter-bar-status' },
				label({ for: 'date-to-input' }, _("Date to"), ":"),
				input({ id: 'date-to-input', type: 'date',
					name: 'dateTo', value: location.query.get('dateTo') })
			),
			p({ class: 'submit' }, input({ type: 'submit' }))));

	section({ class: "section-primary" },
		h3(_("Files completed per day")),
		div({ id: "chart-files-completed-per-day" }));
	section({ class: "section-primary" },
		h3(_("Processed files")),
		div({ id: "chart-files-completed-by-service" }));
	section({ class: "section-primary" }, h3(_("Pending files at ${ date }", {
		date: location.query.get('dateTo').map(function (dateTo) {
			var date = dateTo ? new db.Date(dateTo) : new db.Date();
			return date.toLocaleDateString(db.locale);
		})
	})),
		div({ id: "chart-pending-files" }));
	section({ class: "section-primary" },
		h3(_("Average processing time")),
		div({ id: "chart-by-step-and-service" }));
	section({ class: "section-primary" },
		h3(_("Total average processing time per service")),
		div({ id: "chart-by-service" }));
	section({ class: "section-primary" },
		h3(_("Withdrawal time")), div({ id: "chart-withdrawal-time" }));
	exports._customChartsDOM.call(this);

	script(function () {
		google.charts.load('current', { packages: ['corechart'] });
	});
	script(function (chartsData) {
		var reloadCharts = function () {
			google.charts.setOnLoadCallback(function () {
				if (!chartsData) return;
				chartsData.forEach(function (chart) {
					if (!chart.data) {
						$(chart.handle).innerHtml = '';
						return;
					}
					var googleChart =
						new google.visualization[chart.drawMethod || 'BarChart']($(chart.handle));
					googleChart.draw(google.visualization.arrayToDataTable(chart.data), chart.options);
				});
			});
		};
		reloadCharts();
		// this will be invoked only in SPA
		if (document.on) document.on('statistics-chart-update', reloadCharts);
	}, observableResult);
};
<commit_msg>#1598 added more information to chart titles were needed<commit_after>'use strict';

var db                  = require('../db')
  , assign              = require('es5-ext/object/assign')
  , copy                = require('es5-ext/object/copy')
  , _                   = require('mano').i18n.bind('View: Statistics')
  , memoize             = require('memoizee')
  , location            = require('mano/lib/client/location')
  , setupQueryHandler   = require('../utils/setup-client-query-handler')
  , resolveFullStepPath = require('../utils/resolve-processing-step-full-path')
  , capitalize          = require('es5-ext/string/#/capitalize')
  , uncapitalize        = require('es5-ext/string/#/uncapitalize')
  , Duration            = require('duration')
  , getData             = require('mano/lib/client/xhr-driver').get
  , getQueryHandlerConf = require('../routes/utils/get-statistics-time-query-handler-conf')
  , ObjservableValue    = require('observable-value')
  , nextTick            = require('next-tick')
  , observableResult    = new ObjservableValue();

exports._servicesColors  = ["#673AB7", "#FFC107", "#FF4B4B", "#3366CC"];
exports._stepsColors     = ["#673AB7", "#FFC107", "#FF4B4B", "#3366CC"];
exports._customChartsDOM     = Function.prototype;
exports._customChartsGetData = Function.prototype;

exports._commonOptions = {
	colors: exports._servicesColors, // by default colors of the services
	animation: {
		startup: true,
		duration: 1200,
		easing: "in"
	},
	legend: { position: "bottom", maxLines: 3 },
	chartArea: { width: "100%", height: "75%" },
	height: 300,
	is3D: true,
	isStacked: true,
	titlePosition: "out",
	axisTitlesPosition: "in",
	vAxis: {
		textPosition: "in",
		viewWindow: { min: 0 },
		minValue: 0
	},
	width: "100%"
};

var queryServer = memoize(function (query) {
	return getData('/get-dashboard-data/', query);
}, {
	normalizer: function (args) { return JSON.stringify(args[0]); },
	max: 1000
});

var getServiceNames = function () {
	var services = {};

	db.BusinessProcess.extensions.forEach(function (BusinessProcessClass) {
		services[uncapitalize.call(BusinessProcessClass.__id__.slice('BusinessProcess'.length))] =
			{ label: BusinessProcessClass.prototype.label };
	});

	return services;
};

var dayRangeConfig = {
	31: 1,
	182: 7,
	365: 30,
	Infinity: 365
};

var getGroupByCount = function (dateFrom, dateTo) {
	var duration, groupBy;
	duration = new Duration(dateFrom, dateTo);

	Object.keys(dayRangeConfig).some(function (rangeKey) {
		if (duration.days <= rangeKey) {
			groupBy = dayRangeConfig[rangeKey];
			return true;
		}
	});

	return groupBy;
};

var getStepLabelByShortPath = function (processingStepsMeta) {
	return function (shortStepPath) {
		return db['BusinessProcess' +
			capitalize.call(processingStepsMeta[shortStepPath]._services[0])].prototype
			.processingSteps.map.getBySKeyPath(resolveFullStepPath(shortStepPath)).label;
	};
};

var getFilesCompletedPerDay = function (data) {
	var result = { handle: 'chart-files-completed-per-day' }, chart = {
		options: assign(copy(exports._commonOptions), {
			orientation: 'horizontal'
		}),
		data: [["Service"]]
	}, days = Object.keys(data.filesApprovedByDay),
		dateFrom, dateTo, dateFromStr, rowData, rangeKey, groupByCount,
		daysCount = 0, currentRange,
		setupRange, addAmountToRange, setupRowData;

	if (!days || !days.length) {
		result.data = null;
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	dateFrom = new Date(Date.parse(data.filesApprovedByDay.dateFrom));
	dateTo   = new Date(Date.parse(data.filesApprovedByDay.dateTo));
	groupByCount = getGroupByCount(dateFrom, dateTo);

	setupRange = function (currentRange) {
		Object.keys(services).forEach(function (serviceName) {
			currentRange.services[serviceName] = 0;
		});
	};

	addAmountToRange = function (currentRange, dateFromStr) {
		Object.keys(services).forEach(function (serviceName) {
			var amount;
			amount = data.filesApprovedByDay[dateFromStr][serviceName] || 0;
			currentRange.services[serviceName] += amount;
		});
	};

	setupRowData = function (currentRange, rowData) {
		Object.keys(currentRange.services).forEach(function (service) {
			rowData.push(currentRange.services[service] || 0);
		});
	};
	while (dateFrom <= dateTo) {
		daysCount++;
		dateFromStr = dateFrom.toISOString().slice(0, 10);
		if (!currentRange) {
			currentRange = { name: dateFrom.toLocaleDateString(db.locale), services: {} };
			setupRange(currentRange);
		}
		if (data.filesApprovedByDay[dateFromStr]) {
			addAmountToRange(currentRange, dateFromStr);
		}
		if ((daysCount % groupByCount === 0) || dateFrom.getTime() === dateTo.getTime()) {
			rangeKey = groupByCount === 1 ? currentRange.name : currentRange.name + ' - ' +
				dateFrom.toLocaleDateString(db.locale);
			rowData = [rangeKey];
			setupRowData(currentRange, rowData);
			chart.data.push(rowData);
			currentRange = null;
		}
		dateFrom.setUTCDate(dateFrom.getUTCDate() + 1);
	}

	return assign(result, chart);
};

var getFilesCompletedByStep = function (data) {
	var result = { handle: 'chart-files-completed-by-service' }, chart = {
		options: exports._commonOptions,
		data: [["Service"]]
	};
	if (!Object.keys(data.byStepAndService).length) {
		return result;
	}

	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	Object.keys(data.byStepAndService).forEach(function (shortPath) {
		var stepData = [getStepLabelByShortPath(shortPath)];
		Object.keys(services).forEach(function (serviceName) {
			if (!data.byStepAndService[shortPath][serviceName]) {
				stepData.push(0);
				return;
			}
			stepData.push(data.byStepAndService[shortPath][serviceName].processed);
		});
		chart.data.push(stepData);
	});

	return assign(result, chart);
};

var getPendingFiles = function (data) {
	var result = { handle: 'chart-pending-files' }, chart = {
		options: assign(copy(exports._commonOptions), {
			colors: exports._stepsColors
		}),
		drawMethod: 'PieChart',
		data: [["Role", "Count"]]
	};

	if (!data.pendingFiles || !Object.keys(data.pendingFiles).length) {
		return result;
	}

	Object.keys(data.pendingFiles).forEach(function (shortPath) {
		chart.data.push([getStepLabelByShortPath(shortPath), data.pendingFiles[shortPath] || 0]);
	});

	return assign(result, chart);
};

var getAverageTime = function (data) {
	var result = { handle: 'chart-by-step-and-service' }, chart = {
		options: assign(copy(exports._commonOptions), {
			isStacked: false
		}),
		data: [["Role"]]
	};

	if (!data.byStepAndService || !Object.keys(data.byStepAndService).length) {
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		chart.data[0].push(services[serviceName].label);
	});
	Object.keys(data.byStepAndService).forEach(function (shortPath) {
		if (shortPath === 'frontDesk') return;
		var stepData = [getStepLabelByShortPath(shortPath)];
		Object.keys(services).forEach(function (serviceName) {
			if (!data.byStepAndService[shortPath][serviceName]) {
				stepData.push(0);
				return;
			}
			stepData.push(
				Math.round(data.byStepAndService[shortPath][serviceName].avgTime / 1000 / 60 / 60 / 24)
			);
		});
		chart.data.push(stepData);
	});

	return assign(result, chart);
};

var getAverageTimeByService = function (data) {
	var result = { handle: 'chart-by-service' }, chart = {
		options: assign(copy(exports._commonOptions), {
			legend: null
		}),
		data: [["Service", "Data", { role: "style" }]]
	};

	if (!data.byService || !Object.keys(data.byService).length) {
		return result;
	}

	var services = getServiceNames(), i = 0;

	Object.keys(services).forEach(function (serviceName) {
		var row = [];
		row.push(services[serviceName].label);
		row.push(Math.round(
			(data.byService[serviceName] ? data.byService[serviceName].avgTime : 0) / 1000 / 60 / 60 / 24
		));
		row.push(chart.options.colors[i]);
		i++;
		chart.data.push(row);
	});

	return assign(result, chart);
};

var getWithdrawalTime = function (data) {
	var result = { handle: 'chart-withdrawal-time' }, chart = {
		options: assign(copy(exports._commonOptions), {
			isStacked: false,
			legend: null,
			axisTitlesPosition: "none"
		}),
		data: [["Service", "Data", { role: "style" }]]
	}, i = 0;

	if (!data.byStepAndService.frontDesk) {
		return result;
	}
	var services = getServiceNames();
	Object.keys(services).forEach(function (serviceName) {
		var row = [];
		row.push(services[serviceName].label);
		if (!data.byStepAndService.frontDesk[serviceName]) {
			row.push(0);
		} else {
			row.push(
				Math.round(data.byStepAndService.frontDesk[serviceName].avgTime / 1000 / 60 / 60 / 24)
			);
		}
		row.push(chart.options.colors[i]);
		i++;
		chart.data.push(row);
	});

	return assign(result, chart);
};

var updateChartsData = function (data) {
	var dataForCharts = [], customChartsData = [];
	if (!data) return;

	dataForCharts.push(getFilesCompletedPerDay(data));
	dataForCharts.push(getFilesCompletedByStep(data));
	dataForCharts.push(getPendingFiles(data));
	dataForCharts.push(getAverageTime(data));
	dataForCharts.push(getAverageTimeByService(data));
	dataForCharts.push(getWithdrawalTime(data));
	customChartsData = exports._customChartsGetData.call(this, data);
	if (customChartsData && customChartsData.length) {
		dataForCharts = dataForCharts.concat(customChartsData);
	}
	observableResult.value = dataForCharts;

	nextTick(function () {
		document.emit('statistics-chart-update');
	});
};

exports._parent = require('./statistics-base');

exports['dashboard-nav'] = { class: { 'pills-nav-active': true } };

exports['statistics-main'] = function () {
	var queryHandler;
	getStepLabelByShortPath = getStepLabelByShortPath(this.processingStepsMeta);

	queryHandler = setupQueryHandler(getQueryHandlerConf({
		db: db,
		processingStepsMeta: this.processingStepsMeta,
		queryConf: null
	}), location, '/');

	queryHandler.on('query', function (query) {
		if (query.dateFrom) {
			query.dateFrom = query.dateFrom.toJSON();
		}
		if (query.dateTo) {
			query.dateTo = query.dateTo.toJSON();
		}
		queryServer(query)(function (result) {
			updateChartsData(result);
		}).done();
	});

	section({ class: 'section-primary users-table-filter-bar' },
		form({ action: '/', autoSubmit: true },
			div(
				{ class: 'users-table-filter-bar-status' },
				label({ for: 'date-from-input' }, _("Date from"), ":"),
				input({ id: 'date-from-input', type: 'date',
					name: 'dateFrom', value: location.query.get('dateFrom') })
			),
			div(
				{ class: 'users-table-filter-bar-status' },
				label({ for: 'date-to-input' }, _("Date to"), ":"),
				input({ id: 'date-to-input', type: 'date',
					name: 'dateTo', value: location.query.get('dateTo') })
			),
			p({ class: 'submit' }, input({ type: 'submit' }))));

	section({ class: "section-primary" },
		h3(_("Files completed per time range")),
		div({ id: "chart-files-completed-per-day" }));
	section({ class: "section-primary" },
		h3(_("Processed files")),
		div({ id: "chart-files-completed-by-service" }));
	section({ class: "section-primary" }, h3(_("Pending files at ${ date }", {
		date: location.query.get('dateTo').map(function (dateTo) {
			var date = dateTo ? new db.Date(dateTo) : new db.Date();
			return date.toLocaleDateString(db.locale);
		})
	})),
		div({ id: "chart-pending-files" }));
	section({ class: "section-primary" },
		h3(_("Average processing time in days")),
		div({ id: "chart-by-step-and-service" }));
	section({ class: "section-primary" },
		h3(_("Total average processing time per service in days")),
		div({ id: "chart-by-service" }));
	section({ class: "section-primary" },
		h3(_("Withdrawal time in days")), div({ id: "chart-withdrawal-time" }));
	exports._customChartsDOM.call(this);

	script(function () {
		google.charts.load('current', { packages: ['corechart'] });
	});
	script(function (chartsData) {
		var reloadCharts = function () {
			google.charts.setOnLoadCallback(function () {
				if (!chartsData) return;
				chartsData.forEach(function (chart) {
					if (!chart.data) {
						$(chart.handle).innerHtml = '';
						return;
					}
					var googleChart =
						new google.visualization[chart.drawMethod || 'BarChart']($(chart.handle));
					googleChart.draw(google.visualization.arrayToDataTable(chart.data), chart.options);
				});
			});
		};
		reloadCharts();
		// this will be invoked only in SPA
		if (document.on) document.on('statistics-chart-update', reloadCharts);
	}, observableResult);
};
<|endoftext|>


<commit_before><commit_msg>limit movie results to top 5<commit_after><|endoftext|>