<commit_before>/**
 * UX Rocket
 * jQuery based content rotator
 * @author Bilal Cinarli
 * @author Kursad Yildirmak (Version 0.2)
 */
;
(function($) {
    var uxrotator = "uxrotator", // global shorthand
        ux, // local shorthand

        defaults = {
            slides         : '.slide',
            current        : 'current',
            autoSlide      : true,
            slideDelay     : 7000,
            transition     : 'none',
            transitionSpeed: 750,
            bullets        : false
        };

    // constructor method
    var Rotator = function(el, options) {
        var opts = $.extend({}, defaults, options, $(el).data()),

        // cached jQuery Objects
            $slider = $(el),
            $slides = $slider.find(opts.slides),
            $next = $slider.find('.next'),
            $prev = $slider.find('.prev'),
            $currentOne,
            $nextOne,

        // cached Variables
            timer,
            currentSlide = 0,
            nextSlide = 0,
            totalSlides = 0,
            bulletIndex = 0,
            direction = 'next',
            animating = false,
            start = -100, // slides to left for 100%
            end = 0;

        $slides.addClass('rotator-slide').wrapAll('
').hide().first().show().addClass(opts.current);
        totalSlides = $slides.length;

        //create bullets
        if(opts.bullets == true && !$slider.find('.rotator-bullets').length) {
            var bullets = "";
            for(var i = 0; i < totalSlides; i++) {
                if(i == 0) {
                    bullets += '' + i + '';
                } else {
                    bullets += '' + i + '';
                }
            }
            $slider.append('
' + bullets + '
');
            var $bullet = $slider.find('.rotator-bullets').children('.bullet');
        }

        /**
         * Slide functions
         **/
        var animate = function(slideIndex) {
            if(totalSlides < 2) {
                return;
            }

            if(animating === false) {
                animating = true;

                //go to slide if bullets is activated
                if(typeof slideIndex != "undefined") {
                    nextSlide = slideIndex;
                    if(currentSlide > nextSlide) {
                        start = 100;
                    }
                } else {
                    if(direction === 'next') {
                        nextSlide = (nextSlide + 1 === totalSlides) ? 0 : nextSlide + 1;
                    }
                    if(direction === 'prev') {
                        nextSlide = (nextSlide - 1 < 0) ? totalSlides - 1 : nextSlide - 1;
                        start = 100; // slides to right for 100%
                    }
                }
                $currentOne = $slides.filter(':eq(' + currentSlide + ')');
                $nextOne = $slides.filter(':eq(' + nextSlide + ')');

                if(opts.transition === 'horizontal') {
                    $currentOne.animate({
                        left: start + '%'
                    }, opts.transitionSpeed, function() {
                        $(this).hide();
                    }).removeClass(opts.current);
                    $nextOne.addClass(opts.current).css('left', -start + '%').show().animate({
                        left: end
                    }, opts.transitionSpeed);
                } else if(opts.transition === 'vertical') {
                    $currentOne.animate({
                        top: start + '%'
                    }, opts.transitionSpeed, function() {
                        $(this).hide();
                    }).removeClass(opts.current);
                    $nextOne.addClass(opts.current).css('top', -start + '%').show().animate({
                        top: end
                    }, opts.transitionSpeed);
                } else if(opts.transition === 'fade') {
                    $currentOne.fadeOut(opts.transitionSpeed).removeClass(opts.current);
                    $nextOne.addClass(opts.current).fadeIn(opts.transitionSpeed);
                } else {
                    $currentOne.hide().removeClass(opts.current);
                    $nextOne.addClass(opts.current).show();
                }

                if(opts.bullets == true) {
                    $bullet.removeClass('current').eq($nextOne.index()).addClass('current');
                }
                // set the direction to default always for autoRun
                direction = 'next';

                // jump to next index
                currentSlide = nextSlide;
                start = -100;

                animating = false;
            }
        };

        var run = function() {
            // make sure forwarding
            direction = 'next';
            timer = setInterval(animate, opts.slideDelay);
        };

        var stop = function() {
            clearInterval(timer);
        };

        $next.on('click', function() {
            stop();
            direction = 'next';
            animate();
        });

        $prev.on('click', function() {
            stop();
            direction = 'prev';
            animate();
        });

        //bullet click event
        if(opts.bullets == true) {
            $bullet.on('click', function() {
                var activebullet = $(this).index();
                $bullet.removeClass('current');
                $(this).addClass('current');

                if(bulletIndex != activebullet) {
                    stop();
                    animate(activebullet);
                    bulletIndex = activebullet;
                }
            });
        }

        // Initialize  auto rotation
        if(opts.autoSlide && totalSlides > 1) {
            run();
            $slider.hover(function() {
                stop();
            }, function() {
                run();
            });
        }

        return this;
    };

    // jquery bindings
    ux = $.fn.rotator = $.uxrotator = function(options) {
        return this.each(function() {
            var $el = $(this),
                rotator;

            if($el.hasClass('uxitd-rotator-ready')) {
                return;
            }

            $el.addClass('uxitd-rotator-ready');

            rotator = new Rotator(this, options);
        });
    };

    // Version
    ux.version = "0.3.0";

    // settings
    ux.settings = defaults;
})(jQuery);<commit_msg>Update uxrocket.rotator.js<commit_after>/**
 * UX Rocket
 * jQuery based content rotator
 * @author Bilal Cinarli
 * @author Kursad Yildirmak (Version 0.2)
 */
;
(function($) {
    var uxrotator = "uxrotator", // global shorthand
        ux, // local shorthand

        defaults = {
            slides         : '.slide',
            current        : 'current',
            autoSlide      : true,
            slideDelay     : 7000,
            transition     : 'none',
            transitionSpeed: 750,
            bullets        : false
        };

    // constructor method
    var Rotator = function(el, options) {
        var opts = $.extend({}, defaults, options, $(el).data()),

        // cached jQuery Objects
            $slider = $(el),
            $slides = $slider.find(opts.slides),
            $next = $slider.find('.next'),
            $prev = $slider.find('.prev'),
            $currentOne,
            $nextOne,

        // cached Variables
            timer,
            currentSlide = 0,
            nextSlide = 0,
            totalSlides = 0,
            bulletIndex = 0,
            direction = 'next',
            animating = false,
            start = -100, // slides to left for 100%
            end = 0;

        $slides.addClass('rotator-slide').wrapAll('
').hide().first().show().addClass(opts.current);
        totalSlides = $slides.length;

        //create bullets
        if(opts.bullets == true && !$slider.find('.rotator-bullets').length) {
            var bullets = "";
            for(var i = 0; i < totalSlides; i++) {
                if(i == 0) {
                    bullets += '' + i + '';
                } else {
                    bullets += '' + i + '';
                }
            }
            $slider.append('
' + bullets + '
');
            var $bullet = $slider.find('.rotator-bullets').children('.bullet');
        }

        /**
         * Slide functions
         **/
        var animate = function(slideIndex) {
            if(totalSlides < 2) {
                return;
            }

            if(animating === false) {
                animating = true;

                //go to slide if bullets is activated
                if(typeof slideIndex != "undefined") {
                    nextSlide = slideIndex;
                    if(currentSlide > nextSlide) {
                        start = 100;
                    }
                } else {
                    if(direction === 'next') {
                        nextSlide = (nextSlide + 1 === totalSlides) ? 0 : nextSlide + 1;
                    }
                    if(direction === 'prev') {
                        nextSlide = (nextSlide - 1 < 0) ? totalSlides - 1 : nextSlide - 1;
                        start = 100; // slides to right for 100%
                    }
                }
                $currentOne = $slides.filter(':eq(' + currentSlide + ')');
                $nextOne = $slides.filter(':eq(' + nextSlide + ')');

                if(opts.transition === 'horizontal') {
                    $currentOne.animate({
                        left: start + '%'
                    }, opts.transitionSpeed, function() {
                        $(this).hide();
                    }).removeClass(opts.current);
                    $nextOne.addClass(opts.current).css('left', -start + '%').show().animate({
                        left: end
                    }, opts.transitionSpeed);
                } else if(opts.transition === 'vertical') {
                    $currentOne.animate({
                        top: start + '%'
                    }, opts.transitionSpeed, function() {
                        $(this).hide();
                    }).removeClass(opts.current);
                    $nextOne.addClass(opts.current).css('top', -start + '%').show().animate({
                        top: end
                    }, opts.transitionSpeed);
                } else if(opts.transition === 'fade') {
                    $currentOne.fadeOut(opts.transitionSpeed).removeClass(opts.current);
                    $nextOne.addClass(opts.current).fadeIn(opts.transitionSpeed);
                } else {
                    $currentOne.hide().removeClass(opts.current);
                    $nextOne.addClass(opts.current).show();
                }

                if(opts.bullets == true) {
                    $bullet.removeClass('current').eq($nextOne.index()).addClass('current');
                }
                // set the direction to default always for autoRun
                direction = 'next';

                // jump to next index
                currentSlide = nextSlide;
                start = -100;

                animating = false;
            }
        };

        var run = function() {
            // make sure forwarding
            direction = 'next';
            timer = setInterval(animate, opts.slideDelay);
        };

        var stop = function() {
            clearInterval(timer);
        };

        $next.on('click', function(e) {
            e.preventDefault();
            stop();
            direction = 'next';
            animate();
        });

        $prev.on('click', function(e) {
            e.preventDefault();
            stop();
            direction = 'prev';
            animate();
        });

        //bullet click event
        if(opts.bullets == true) {
            $bullet.on('click', function() {
                var activebullet = $(this).index();
                $bullet.removeClass('current');
                $(this).addClass('current');

                if(bulletIndex != activebullet) {
                    stop();
                    animate(activebullet);
                    bulletIndex = activebullet;
                }
            });
        }

        // Initialize  auto rotation
        if(opts.autoSlide && totalSlides > 1) {
            run();
            $slider.hover(function() {
                stop();
            }, function() {
                run();
            });
        }

        return this;
    };

    // jquery bindings
    ux = $.fn.rotator = $.uxrotator = function(options) {
        return this.each(function() {
            var $el = $(this),
                rotator;

            if($el.hasClass('uxitd-rotator-ready')) {
                return;
            }

            $el.addClass('uxitd-rotator-ready');

            rotator = new Rotator(this, options);
        });
    };

    // Version
    ux.version = "0.3.0";

    // settings
    ux.settings = defaults;
})(jQuery);
<|endoftext|>


<commit_before>var Emitter = require('events').EventEmitter ;
var util = require('util') ;
var assert = require('assert') ;
var only = require('only') ;
var noop = require('node-noop').noop;
var _ = require('lodash') ;
var async = require('async') ;
var debug = require('debug')('drachtio-fsmrf') ;

var State = {
  NOT_CREATED: 1,
  CREATED: 2,
  DESTROYED: 3
};

/**
 * an audio or video conference mixer.  Conferences may be created on the fly by simply joining an endpoint
 * to a named conference without explicitly creating a Conference object.  The main purpose of the Conference
 * object is to enable the ability to create a conference on the media server without having an inbound call
 * (e.g., to create a scheduled conference at a particular point in time).
 *
 * @constructor
 * @param {Endpoint} endpoint - endpoint that will provide the control connection to the conference
 * @param {String}   name  - conference name
 * @param {Conference~createOptions}  [opts] - conference-level configuration options
 * @param {Conference~createCallback} cb - callback invoked when conference is created
 */
function Conference( endpoint, name, opts, cb ) {
  Emitter.call(this);
  var self = this ;

  if( typeof opts === 'function') {
    cb = opts ;
    opts = {} ;
  }

  this._endpoint = endpoint ;

  /**
   * conference name
   * @type {string}
   */

  this.name = name ;

  /**
   * file that conference is currently being recorded to
   * @type {String}
   */
  this.recordFile = null ;

  /**
   * conference state
   * @type {Number}
   */
  this.state = State.NOT_CREATED ;

  /**
   * true if conference is locked
   * @type {Boolean}
   */
  this.locked = false ;

  /**
   * member ID of the conference control leg
   * @type {Number}
   */
  this.memberId = -1 ;

  /**
   * current participants in the conference, keyed by member ID
   * @type {Object}
   */
  this.participants = {} ;

  /**
   * max number of members allowed (-1 means no limit)
   * @type {Number}
   */
  this.maxMembers = -1 ;

  this._endpoint.conn.subscribe('all') ;

  this._endpoint.conn.on('esl::event::CUSTOM::*', this._onConferenceEvent.bind(this)) ;

  opts.flags = opts.flags || {} ;

  //set these because our leg is purely a control leg
  _.extend( opts.flags, {
    ghost: true,
    endconf: true,
    mute: true,
    vmute: true
  }) ;

  this._endpoint.joinConference(name, opts, function( err, connection) {
    self.confConn = connection ;
    debug('conference created: ', JSON.stringify(self)) ;

    if( opts.maxMembers ) {
      connection.api('conference', name + ' set max_members ' + opts.maxMembers ) ;
      self.maxMembers = opts.maxMembers ;
    }
    cb(err, self) ;
  }) ;
}

util.inherits(Conference, Emitter) ;

module.exports = exports = Conference ;

/**
 * destroy the conference, releasing all legs
 * @param  {Conference~destroyCallback} cb - callback invoked when conference has been destroyed
 */
Conference.prototype.destroy = function(cb) {
    this._endpoint.destroy(cb) ;
} ;
/**
 * This callback is invoked when a conference has been destroyed
 * @callback Conference~destroyCallback
 * @param {Error} error, if any
 */

//media operations
/**
 * adjust the automatic gain control for the conference
 * @param  {Number|String}   level - 'on', 'off', or a numeric level
 * @param  {Conference~mediaOperationCallback} [cb] - callback invoked when operation completes
 */
Conference.prototype.agc = function( level, cb ) {
  assert.ok( typeof level === 'number' || -1 !== ['on','off'].indexOf(level),
    '\'level\' must be \'on\', \'off\', or a numeric level to apply' );

  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' agc ' + level, cb) ;
} ;
/**
 * This callback is invoked whenever any media command has completed
 * @callback Conference~mediaOperationCallback
 * @param {Object} response - response to the command
 */

/**
 * check the status of the conference recording
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.chkRecord = function(cb) {
  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' chk-record', cb) ;
} ;
/**
 * deaf all the non-moderators in the conference
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.deafAll = function(cb) {
  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' deaf non_moderator', cb) ;
} ;
/**
 * mute all the non-moderators in the conference
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.muteAll = function(cb) {
  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' mute non_moderator', cb) ;
} ;
/**
 * lock the conference
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.lock = function(cb) {
  var self = this ;
  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' lock', function(res) {
    self.locked = true ;
    cb(res) ;
  }) ;
} ;
/**
 * unlock the conference
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.unlock = function(cb) {
  var self = this ;
  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' unlock', function(res) {
    self.locked = false ;
    cb(res) ;
  }) ;
} ;
/**
 * start recording the conference
 * @param  {String}   file - filepath to record to
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.startRecording = function( file, cb ) {
  assert.equals(typeof file === 'string', '\'file\' parameter must be provided') ;

  cb = cb || noop ;
  this.recordFile = file ;
  this._endpoint.api('record', this.name + ' recording start ' + file, cb) ;
} ;
/**
 * pause the recording
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.pauseRecording = function( file, cb ) {
  cb = cb || noop ;
  this.recordFile = file ;
  this._endpoint.api('record', this.name + ' recording pause ' + this.recordFile, cb) ;
} ;
/**
 * resume the recording
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.resumeRecording = function( file, cb ) {
  cb = cb || noop ;
  this.recordFile = file ;
  this._endpoint.api('record', this.name + ' recording resume ' + this.recordFile, cb) ;
} ;
/**
 * stop the conference recording
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.stopRecording = function( file, cb ) {
  cb = cb || noop ;
  this._endpoint.api('record', this.name + ' recording tops ' + this.recordFile, cb) ;
  this.recordFile = null ;
} ;
/**
 * play an audio file into the conference
 * @param  {string|Array}   file file (or array of files) to play
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.play = function( file, cb ) {
  assert.ok( 'string' === typeof file || _.isArray( file ), 'file param is required and must be a string or array') ;

  var self = this ;
  cb = cb || noop ;
  var files = typeof file === 'string' ? [file] : file ;

  // each call to conference play queues the file up; i.e. the callback returns immediately upon successful queueing,
  // not when the file has finished playing
  async.eachSeries( files, function( f, callback ) {
    self._endpoint.api('conference', self.name + ' play ' + f, function() {
      callback(null) ;
    }) ;
  }, function(){
    cb() ;
  }) ;
};

//conference event handlers
Conference.prototype.onAddMember = function( evt ) {
 debug('Conference#onAddMember: ', JSON.stringify(this)) ;
 if( !this.uuid ) {
    this.uuid = evt.getHeader('Conference-Unique-ID') ;
    this.memberId = evt.getHeader('Member-ID') ;

    this._endpoint.filter('Conference-Unique-ID', this.uuid, function(res) {
      debug('response to filter command: ', res) ;
    }) ;

    debug('created conference with Conference-Unique-ID: ', this.uuid) ;
  }
  else {
    //debug('Conference#onAddMember: another leg joined: ', evt) ;
    var size = parseInt( evt.getHeader('Conference-Size') );
    var newMemberId = evt.getHeader('Member-ID')  ;
    var memberType = evt.getHeader('Member-Type') ;
    var memberGhost = evt.getHeader('Member-Ghost') ;
    var channelUuid = evt.getHeader('Channel-Call-UUID') ;
    var obj = {
      memberId: newMemberId,
      type: memberType,
      ghost: memberGhost,
      channelUuid: channelUuid
    } ;
    this.participants[newMemberId] = obj ;

    debug('Adding member to conference, size is now %d: ', size, this.participants) ;
  }
} ;
Conference.prototype.onDelMember = function(evt) {
    var memberId = evt.getHeader('Member-ID') ;
    var size = parseInt( evt.getHeader('Conference-Size') );

    delete this.participants[memberId] ;
    debug('member with member-id %s left, size is now: %d, remaining participants: ', memberId, size, this.participants) ;
} ;
Conference.prototype.onStartTalking = function(evt) {
  debug('member started talking: ', evt) ;
} ;
Conference.prototype.onStopTalking = function(evt) {
  debug('member stopped talking: ', evt) ;
} ;
Conference.prototype.onMuteDetect = function(evt) {
  debug('a muted member is talking: ', evt) ;
} ;
Conference.prototype.onUnmuteMember = function(evt) {
  debug('a member has been unmuted: ', evt) ;
} ;
Conference.prototype.onMuteMember = function(evt) {
  debug('a member has been muted: ', evt) ;
} ;
Conference.prototype.onKickMember = function(evt) {
  debug('a member has been kicked: ', evt) ;
} ;
Conference.prototype.onDtmfMember = function(evt) {
  debug('a member has entered DTMF: ', evt) ;
} ;
Conference.prototype.onPlayFile = function(evt) {
  debug('conference-level play has started: ', evt) ;
} ;
Conference.prototype.onPlayFileMember = function(evt) {
  debug('member-level play has completed: ', evt) ;
} ;
Conference.prototype.onPlayFileDone = function(/* evt */) {
  debug('conference-level play has completed: ' /*, evt*/) ;
} ;
Conference.prototype.onLock = function(evt) {
  debug('conference has been locked: ', evt) ;
} ;
Conference.prototype.onUnlock = function(evt) {
  debug('conference has been unlocked: ', evt) ;
} ;
Conference.prototype.onTransfer = function(evt) {
  debug('member has been transferred to another conference: ', evt) ;
} ;
Conference.prototype.onRecord = function(evt) {
  debug('conference record has started or stopped: ', evt) ;
} ;

function unhandled(evt) {
  debug('Conference#_onConferenceEvent: unhandled event: %s', evt.getHeader('Action')) ;
}

// esl connection event handlers
Conference.prototype._onConferenceEvent = function( evt ) {
  var eventName = evt.getHeader('Event-Subclass') ;
  if( eventName === 'conference::maintenance') {
    var action = evt.getHeader('Action') ;
    debug('Conference#_onConferenceEvent: conference event action: %s ', action) ;

    //invoke a handler for this action, if we have defined one
    (Conference.prototype['on' + _.capitalize(_.camelCase(action))] || unhandled).bind( this, evt )() ;

  }
  else {
    debug('Conference#_onConferenceEvent: got unhandled custom event: ', eventName ) ;
  }
};

// representation
Conference.prototype.toJSON = function() {
  return( only( this, 'name state uuid memberId confConn endpoint maxMembers locked recordFile')) ;
} ;
Conference.prototype.toString = function() {
  return this.toJSON().toString() ;
} ;
<commit_msg>minor debugging add<commit_after>var Emitter = require('events').EventEmitter ;
var util = require('util') ;
var assert = require('assert') ;
var only = require('only') ;
var noop = require('node-noop').noop;
var _ = require('lodash') ;
var async = require('async') ;
var debug = require('debug')('drachtio-fsmrf') ;

var State = {
  NOT_CREATED: 1,
  CREATED: 2,
  DESTROYED: 3
};

/**
 * an audio or video conference mixer.  Conferences may be created on the fly by simply joining an endpoint
 * to a named conference without explicitly creating a Conference object.  The main purpose of the Conference
 * object is to enable the ability to create a conference on the media server without having an inbound call
 * (e.g., to create a scheduled conference at a particular point in time).
 *
 * @constructor
 * @param {Endpoint} endpoint - endpoint that will provide the control connection to the conference
 * @param {String}   name  - conference name
 * @param {Conference~createOptions}  [opts] - conference-level configuration options
 * @param {Conference~createCallback} cb - callback invoked when conference is created
 */
function Conference( endpoint, name, opts, cb ) {
  Emitter.call(this);
  var self = this ;

  if( typeof opts === 'function') {
    cb = opts ;
    opts = {} ;
  }

  this._endpoint = endpoint ;

  /**
   * conference name
   * @type {string}
   */

  this.name = name ;

  /**
   * file that conference is currently being recorded to
   * @type {String}
   */
  this.recordFile = null ;

  /**
   * conference state
   * @type {Number}
   */
  this.state = State.NOT_CREATED ;

  /**
   * true if conference is locked
   * @type {Boolean}
   */
  this.locked = false ;

  /**
   * member ID of the conference control leg
   * @type {Number}
   */
  this.memberId = -1 ;

  /**
   * current participants in the conference, keyed by member ID
   * @type {Object}
   */
  this.participants = {} ;

  /**
   * max number of members allowed (-1 means no limit)
   * @type {Number}
   */
  this.maxMembers = -1 ;

  this._endpoint.conn.subscribe('all') ;

  this._endpoint.conn.on('esl::event::CUSTOM::*', this._onConferenceEvent.bind(this)) ;

  opts.flags = opts.flags || {} ;

  //set these because our leg is purely a control leg
  _.extend( opts.flags, {
    ghost: true,
    endconf: true,
    mute: true,
    vmute: true
  }) ;

  this._endpoint.joinConference(name, opts, function( err, connection) {
    self.confConn = connection ;
    debug('conference created: ', JSON.stringify(self)) ;

    if( opts.maxMembers ) {
      connection.api('conference', name + ' set max_members ' + opts.maxMembers ) ;
      self.maxMembers = opts.maxMembers ;
    }
    cb(err, self) ;
  }) ;
}

util.inherits(Conference, Emitter) ;

module.exports = exports = Conference ;

/**
 * destroy the conference, releasing all legs
 * @param  {Conference~destroyCallback} cb - callback invoked when conference has been destroyed
 */
Conference.prototype.destroy = function(cb) {
    this._endpoint.destroy(cb) ;
} ;
/**
 * This callback is invoked when a conference has been destroyed
 * @callback Conference~destroyCallback
 * @param {Error} error, if any
 */

//media operations
/**
 * adjust the automatic gain control for the conference
 * @param  {Number|String}   level - 'on', 'off', or a numeric level
 * @param  {Conference~mediaOperationCallback} [cb] - callback invoked when operation completes
 */
Conference.prototype.agc = function( level, cb ) {
  assert.ok( typeof level === 'number' || -1 !== ['on','off'].indexOf(level),
    '\'level\' must be \'on\', \'off\', or a numeric level to apply' );

  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' agc ' + level, cb) ;
} ;
/**
 * This callback is invoked whenever any media command has completed
 * @callback Conference~mediaOperationCallback
 * @param {Object} response - response to the command
 */

/**
 * check the status of the conference recording
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.chkRecord = function(cb) {
  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' chk-record', cb) ;
} ;
/**
 * deaf all the non-moderators in the conference
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.deafAll = function(cb) {
  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' deaf non_moderator', cb) ;
} ;
/**
 * mute all the non-moderators in the conference
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.muteAll = function(cb) {
  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' mute non_moderator', cb) ;
} ;
/**
 * lock the conference
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.lock = function(cb) {
  var self = this ;
  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' lock', function(res) {
    self.locked = true ;
    cb(res) ;
  }) ;
} ;
/**
 * unlock the conference
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.unlock = function(cb) {
  var self = this ;
  cb = cb || noop ;
  this._endpoint.api('conference', this.name + ' unlock', function(res) {
    self.locked = false ;
    cb(res) ;
  }) ;
} ;
/**
 * start recording the conference
 * @param  {String}   file - filepath to record to
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.startRecording = function( file, cb ) {
  assert.equals(typeof file === 'string', '\'file\' parameter must be provided') ;

  cb = cb || noop ;
  this.recordFile = file ;
  this._endpoint.api('record', this.name + ' recording start ' + file, cb) ;
} ;
/**
 * pause the recording
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.pauseRecording = function( file, cb ) {
  cb = cb || noop ;
  this.recordFile = file ;
  this._endpoint.api('record', this.name + ' recording pause ' + this.recordFile, cb) ;
} ;
/**
 * resume the recording
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.resumeRecording = function( file, cb ) {
  cb = cb || noop ;
  this.recordFile = file ;
  this._endpoint.api('record', this.name + ' recording resume ' + this.recordFile, cb) ;
} ;
/**
 * stop the conference recording
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.stopRecording = function( file, cb ) {
  cb = cb || noop ;
  this._endpoint.api('record', this.name + ' recording tops ' + this.recordFile, cb) ;
  this.recordFile = null ;
} ;
/**
 * play an audio file into the conference
 * @param  {string|Array}   file file (or array of files) to play
 * @param  {Conference~mediaOperationsCallback} [cb] - callback invoked when media operations completes
 */
Conference.prototype.play = function( file, cb ) {
  assert.ok( 'string' === typeof file || _.isArray( file ), 'file param is required and must be a string or array') ;

  var self = this ;
  cb = cb || noop ;
  var files = typeof file === 'string' ? [file] : file ;

  // each call to conference play queues the file up; i.e. the callback returns immediately upon successful queueing,
  // not when the file has finished playing
  async.eachSeries( files, function( f, callback ) {
    self._endpoint.api('conference', self.name + ' play ' + f, function() {
      callback(null) ;
    }) ;
  }, function(){
    cb() ;
  }) ;
};

//conference event handlers
Conference.prototype.onAddMember = function( evt ) {
 debug('Conference#onAddMember: ', JSON.stringify(this)) ;
 if( !this.uuid ) {
    this.uuid = evt.getHeader('Conference-Unique-ID') ;
    this.memberId = evt.getHeader('Member-ID') ;

    this._endpoint.filter('Conference-Unique-ID', this.uuid, function(res) {
      debug('response to filter command: ', res) ;
    }) ;

    debug('created conference with Conference-Unique-ID: ', this.uuid) ;
  }
  else {
    //debug('Conference#onAddMember: another leg joined: ', evt) ;
    var size = parseInt( evt.getHeader('Conference-Size') );
    var newMemberId = evt.getHeader('Member-ID')  ;
    var memberType = evt.getHeader('Member-Type') ;
    var memberGhost = evt.getHeader('Member-Ghost') ;
    var channelUuid = evt.getHeader('Channel-Call-UUID') ;
    var obj = {
      memberId: newMemberId,
      type: memberType,
      ghost: memberGhost,
      channelUuid: channelUuid
    } ;
    this.participants[newMemberId] = obj ;

    debug('Adding member to conference, size is now %d: ', size, this.participants) ;
  }
} ;
Conference.prototype.onDelMember = function(evt) {
    var memberId = evt.getHeader('Member-ID') ;
    var size = parseInt( evt.getHeader('Conference-Size') );

    delete this.participants[memberId] ;
    debug('member with member-id %s left, size is now: %d, remaining participants: ', memberId, size, this.participants) ;
} ;
Conference.prototype.onStartTalking = function(evt) {
  debug('member started talking: ', evt.getHeader('Member-ID')) ;
} ;
Conference.prototype.onStopTalking = function(evt) {
  debug('member stopped talking: ', evt.getHeader('Member-ID')) ;
} ;
Conference.prototype.onMuteDetect = function(evt) {
  debug('a muted member is talking: ', evt) ;
} ;
Conference.prototype.onUnmuteMember = function(evt) {
  debug('a member has been unmuted: ', evt) ;
} ;
Conference.prototype.onMuteMember = function(evt) {
  debug('a member has been muted: ', evt) ;
} ;
Conference.prototype.onKickMember = function(evt) {
  debug('a member has been kicked: ', evt) ;
} ;
Conference.prototype.onDtmfMember = function(evt) {
  debug('a member has entered DTMF: ', evt) ;
} ;
Conference.prototype.onPlayFile = function(evt) {
  debug('conference-level play has started: ' , _.pick( evt.headers, ['File','Conference-Name']) ) ;
} ;
Conference.prototype.onPlayFileMember = function(evt) {
  debug('member-level play has completed: ', evt) ;
} ;
Conference.prototype.onPlayFileDone = function(evt) {
  debug('conference-level play has completed: ' , _.pick( evt.headers, ['seconds', 'milliseconds','samples','File','Conference-Name']) ) ;
} ;
Conference.prototype.onLock = function(evt) {
  debug('conference has been locked: ', evt) ;
} ;
Conference.prototype.onUnlock = function(evt) {
  debug('conference has been unlocked: ', evt) ;
} ;
Conference.prototype.onTransfer = function(evt) {
  debug('member has been transferred to another conference: ', evt) ;
} ;
Conference.prototype.onRecord = function(evt) {
  debug('conference record has started or stopped: ', evt) ;
} ;

function unhandled(evt) {
  debug('Conference#_onConferenceEvent: unhandled event: %s', evt.getHeader('Action')) ;
}

// esl connection event handlers
Conference.prototype._onConferenceEvent = function( evt ) {
  var eventName = evt.getHeader('Event-Subclass') ;
  if( eventName === 'conference::maintenance') {
    var action = evt.getHeader('Action') ;
    debug('Conference#_onConferenceEvent: conference event action: %s ', action) ;

    //invoke a handler for this action, if we have defined one
    (Conference.prototype['on' + _.capitalize(_.camelCase(action))] || unhandled).bind( this, evt )() ;

  }
  else {
    debug('Conference#_onConferenceEvent: got unhandled custom event: ', eventName ) ;
  }
};

// representation
Conference.prototype.toJSON = function() {
  return( only( this, 'name state uuid memberId confConn endpoint maxMembers locked recordFile')) ;
} ;
Conference.prototype.toString = function() {
  return this.toJSON().toString() ;
} ;
<|endoftext|>


<commit_before>/**
    导航栏
**/
(function(vc){
    var vm = new Vue({
        el:'#nav',
        data:{
            nav:{
                moreNoticeUrl:'/flow/noticeFlow',
                notices:[],
                total:0
            },
            userName:"",
            navCommunityInfo:{
                _currentCommunity:{

                },
                communityInfos:[]
            }
        },
        mounted:function(){
            this.getNavCommunity();
            this.getNavData();
            //this.getUserInfo();
        },
        methods:{
            getNavData:function(){

                var param = {
                    params:{
                        page:1,
                        row:3
                    }

                };

                //发送get请求
               vc.http.get('nav',
                            'getNavData',
                             param,
                             function(json){
                                var _noticeObj = JSON.parse(json);
                                vm.nav.notices = _noticeObj.notices;
                                vm.nav.total = _noticeObj.total;
                             },function(){
                                console.log('请求失败处理');
                             }
                           );

            },
            logout:function(){
                var param = {
                    msg:123
                };
                  //发送get请求
               vc.http.post('nav',
                            'logout',
                            JSON.stringify(param),
                           {
                               emulateJSON:true
                            },
                             function(json,res){
                               if(res.status == 200){
                                   vc.jumpToPage("/flow/login");
                                   return ;
                               }
                             },function(){
                                console.log('请求失败处理');
                             }
                           );
            },
            getUserInfo:function(){
//                var _userInfo = vc.getData("_userInfo");
//                //浏览器缓存中能获取到
//                if(_userInfo != null && _userInfo != undefined){
//                    vm.userName = _userInfo.name;
//                    return ;
//                }
                //获取用户名
                var param = {
                                    msg:'123',
                };

                //发送get请求
               vc.http.get('nav',
                            'getUserInfo',
                             param,
                             function(json,res){
                                if(res.status == 200){
                                    var tmpUserInfo = JSON.parse(json);
                                    console.log(vm,tmpUserInfo);
                                   vm.userName = tmpUserInfo.name;
//                                   vc.saveData("_userInfo",tmpUserInfo);
                               }
                             },function(){
                                console.log('请求失败处理');
                             }
                           );
            },
            getNavCommunity:function(){
                var _tmpCurrentCommunity = vc.getCurrentCommunity();
                //浏览器缓存中能获取到
                if(_tmpCurrentCommunity != null && _tmpCurrentCommunity != undefined){
                    this.navCommunityInfo._currentCommunity = _tmpCurrentCommunity;
                    this.navCommunityInfo.communityInfos = vc.getCommunitys();

                    return ;
                }

                //说明缓存中没有数据
                //发送get请求
                /**
                    [{community:"123123",name:"测试1小区"},{community:"223123",name:"测试2小区"}]
                **/
               vc.http.get('nav',
                            'getCommunitys',
                             '',
                             function(json,res){
                                if(res.status == 200){
                                    vm.navCommunityInfo.communityInfos = JSON.parse(json);

                                    if(vm.navCommunityInfo.communityInfos == null || vm.navCommunityInfo.communityInfos.length == 0){
                                          vm.navCommunityInfo._currentCommunity ={
                                                name:"还没有入驻小区"
                                          };
                                          return;
                                    }

                                    vm.navCommunityInfo._currentCommunity = vm.navCommunityInfo.communityInfos[0];
                                    vc.setCurrentCommunity(vm.navCommunityInfo._currentCommunity);
                                    vc.setCommunitys(vm.navCommunityInfo.communityInfos);

                                    //对首页做特殊处理，因为首页在加载数据时还没有小区信息 会报错
                                    if(vm.navCommunityInfo.communityInfos != null && vm.navCommunityInfo.communityInfos.length > 0){
                                        vc.emit("indexContext","_queryIndexContextData",{});
                                        vc.emit("indexArrears","_listArrearsData",{});
                                    }

                               }
                             },function(){
                                console.log('请求失败处理');
                             }
                           );

            },
            changeCommunity:function(_community){
                 vc.setCurrentCommunity(_community);
                 vc.component.navCommunityInfo._currentCommunity= _community;
            },
            _noticeDetail:function(_notice){
                //console.log(_notice.noticeId);
                vc.jumpToPage("/flow/noticeDetailFlow?noticeId="+_notice.noticeId);
            }
        }

    });

     vm.getUserInfo();

})(window.vc);<commit_msg>优化设置当前小区时的错误<commit_after>/**
    导航栏
**/
(function(vc){
    var vm = new Vue({
        el:'#nav',
        data:{
            nav:{
                moreNoticeUrl:'/flow/noticeFlow',
                notices:[],
                total:0
            },
            userName:"",
            navCommunityInfo:{
                _currentCommunity:{

                },
                communityInfos:[]
            }
        },
        mounted:function(){
            this.getNavCommunity();
            this.getNavData();
            //this.getUserInfo();
        },
        methods:{
            getNavData:function(){

                var param = {
                    params:{
                        page:1,
                        row:3
                    }

                };

                //发送get请求
               vc.http.get('nav',
                            'getNavData',
                             param,
                             function(json){
                                var _noticeObj = JSON.parse(json);
                                vm.nav.notices = _noticeObj.notices;
                                vm.nav.total = _noticeObj.total;
                             },function(){
                                console.log('请求失败处理');
                             }
                           );

            },
            logout:function(){
                var param = {
                    msg:123
                };
                  //发送get请求
               vc.http.post('nav',
                            'logout',
                            JSON.stringify(param),
                           {
                               emulateJSON:true
                            },
                             function(json,res){
                               if(res.status == 200){
                                   vc.jumpToPage("/flow/login");
                                   return ;
                               }
                             },function(){
                                console.log('请求失败处理');
                             }
                           );
            },
            getUserInfo:function(){
//                var _userInfo = vc.getData("_userInfo");
//                //浏览器缓存中能获取到
//                if(_userInfo != null && _userInfo != undefined){
//                    vm.userName = _userInfo.name;
//                    return ;
//                }
                //获取用户名
                var param = {
                                    msg:'123',
                };

                //发送get请求
               vc.http.get('nav',
                            'getUserInfo',
                             param,
                             function(json,res){
                                if(res.status == 200){
                                    var tmpUserInfo = JSON.parse(json);
                                    console.log(vm,tmpUserInfo);
                                   vm.userName = tmpUserInfo.name;
//                                   vc.saveData("_userInfo",tmpUserInfo);
                               }
                             },function(){
                                console.log('请求失败处理');
                             }
                           );
            },
            getNavCommunity:function(){
                var _tmpCurrentCommunity = vc.getCurrentCommunity();
                //浏览器缓存中能获取到
                if(_tmpCurrentCommunity != null && _tmpCurrentCommunity != undefined){
                    this.navCommunityInfo._currentCommunity = _tmpCurrentCommunity;
                    this.navCommunityInfo.communityInfos = vc.getCommunitys();

                    return ;
                }

                //说明缓存中没有数据
                //发送get请求
                /**
                    [{community:"123123",name:"测试1小区"},{community:"223123",name:"测试2小区"}]
                **/
               vc.http.get('nav',
                            'getCommunitys',
                             '',
                             function(json,res){
                                if(res.status == 200){
                                    vm.navCommunityInfo.communityInfos = JSON.parse(json);

                                    if(vm.navCommunityInfo.communityInfos == null || vm.navCommunityInfo.communityInfos.length == 0){
                                          vm.navCommunityInfo._currentCommunity ={
                                                name:"还没有入驻小区"
                                          };
                                          return;
                                    }

                                    vm.navCommunityInfo._currentCommunity = vm.navCommunityInfo.communityInfos[0];
                                    vc.setCurrentCommunity(vm.navCommunityInfo._currentCommunity);
                                    vc.setCommunitys(vm.navCommunityInfo.communityInfos);

                                    //对首页做特殊处理，因为首页在加载数据时还没有小区信息 会报错
                                    if(vm.navCommunityInfo.communityInfos != null && vm.navCommunityInfo.communityInfos.length > 0){
                                        vc.emit("indexContext","_queryIndexContextData",{});
                                        vc.emit("indexArrears","_listArrearsData",{});
                                    }

                               }
                             },function(){
                                console.log('请求失败处理');
                             }
                           );

            },
            changeCommunity:function(_community){
                 vc.setCurrentCommunity(_community);
                  vm.navCommunityInfo._currentCommunity= _community;
            },
            _noticeDetail:function(_notice){
                //console.log(_notice.noticeId);
                vc.jumpToPage("/flow/noticeDetailFlow?noticeId="+_notice.noticeId);
            }
        }

    });

     vm.getUserInfo();

})(window.vc);<|endoftext|>


<commit_before>/*
 * This file defines the base webpack configuration that is shared across both
 * build and testing environments. If you need to add anything to the general
 * webpack config, like adding loaders for different asset types, different
 * preLoaders or Plugins - they should be done here. If you are looking to add
 * dev specific features, please do so in webpack.config.dev.js - if you wish
 * to add test specific features, these can be done in the karma.conf.js.
 *
 * Note:
 *  This file is not called directly by webpack.
 *  It copied once for each plugin by parse_bundle_plugin.js
 *  and used as a template, with additional plugin-specific
 *  modifications made on top.
 */
var path = require('path');

/*
 * This is a filthy hack. Do as I say, not as I do.
 * Taken from: https://gist.github.com/branneman/8048520#6-the-hack
 * This forces the NODE_PATH environment variable to include the main
 * kolibri node_modules folder, so that even plugins being built outside
 * of the kolibri folder will have access to all installed loaders, etc.
 * Doing it here, rather than at command invocation, allows us to do this
 * in a cross platform way, and also to avoid having to prepend it to all
 * our commands that end up invoking webpack.
 */

process.env.NODE_PATH = path.resolve(path.join(__dirname, '..', '..', 'node_modules'));
require('module').Module._initPaths();

var fs = require('fs');
var webpack = require('webpack');
var jeet = require('jeet');
var autoprefixer = require('autoprefixer');

require('./htmlhint_custom'); // adds custom rules

var config = {
  module: {
    preLoaders: [
      {
        test: /\.(vue|js)$/,
        loader: 'eslint',
        exclude: /node_modules/
      },
      {
        test: /\.(vue|html)/,
        loader: 'htmlhint',
        exclude: /node_modules/
      }
    ],
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      },
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          // Babel loader ignores Webpack config options
          // So we pass a module reference rather than a path here
          // to ensure that they get properly resolved when building happens
          // outside of the kolibri base path.
          presets: [require.resolve('babel-preset-es2015-ie')],
          plugins: [require.resolve('babel-plugin-transform-runtime')]
        },
      },
      {
        test: /\.json$/,
        loader: 'json',
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader!postcss-loader'
      },
      {
        test: /\.styl$/,
        loader: 'style-loader!css-loader?sourceMap!postcss-loader!stylus-loader!stylint'
      },
      // moved from parse_bundle_plugin.js
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: '[name].[ext]?[hash]'
        }
      },
      // Usage of file loader allows referencing a local vtt file without in-lining it.
      // Can be removed once the local en.vtt test file is removed.
      {
        test: /\.(vtt|eot|woff|ttf|woff2)$/,
        loader: 'file',
        query: {
          name: '[name].[ext]?[hash]'
        }
      },
      // Hack to make the onloadCSS node module properly export-able.
      // Not currently used - we may be able to delete this if we
      // deprecate our custom KolibriModule async css loading functionality.
      {
        test: /fg-loadcss\/src\/onloadCSS/,
        loader: 'exports?onloadCSS'
      }
    ]
  },
  plugins: [
  ],
  resolve: {
    alias: {
      'kolibri_module': path.resolve('kolibri/core/assets/src/kolibri_module'),
      'core-constants': path.resolve('kolibri/core/assets/src/constants'),
      'core-actions': path.resolve('kolibri/core/assets/src/core-actions'),
      'nav-bar-item': path.resolve('kolibri/core/assets/src/vue/nav-bar/nav-bar-item'),
      'nav-bar-item.styl': path.resolve('kolibri/core/assets/src/vue/nav-bar/nav-bar-item.styl'),
      'icon-button': path.resolve('kolibri/core/assets/src/vue/icon-button'),
      'core-theme.styl': path.resolve('kolibri/core/assets/src/styles/core-theme.styl'),
      'content_renderer_module': path.resolve('kolibri/core/assets/src/content_renderer_module'),
      'logging': path.resolve('kolibri/core/assets/src/logging'),
      'router': path.resolve('kolibri/core/assets/src/router'),
      'core-store': path.resolve('kolibri/core/assets/src/core-store'),
    },
    extensions: ["", ".vue", ".js"],
  },
  eslint: {
    failOnError: true
  },
  htmlhint: {
    failOnError: true,
    emitAs: "error"
  },
  vue: {
    loaders: {
      stylus: 'vue-style-loader!css-loader?sourceMap!stylus-loader!stylint',
      html: 'vue-html-loader!svg-inline', // inlines SVGs
    }
  },
  stylus: {
    use: [jeet()]
  },
  postcss: function () {
    return [autoprefixer];
  },
  node: {
    __filename: true
  }
};

module.exports = config;
<commit_msg>Use aliases generated by the core API Spec rather than hand coded ones (bar two!).<commit_after>/*
 * This file defines the base webpack configuration that is shared across both
 * build and testing environments. If you need to add anything to the general
 * webpack config, like adding loaders for different asset types, different
 * preLoaders or Plugins - they should be done here. If you are looking to add
 * dev specific features, please do so in webpack.config.dev.js - if you wish
 * to add test specific features, these can be done in the karma.conf.js.
 *
 * Note:
 *  This file is not called directly by webpack.
 *  It copied once for each plugin by parse_bundle_plugin.js
 *  and used as a template, with additional plugin-specific
 *  modifications made on top.
 */
var path = require('path');

/*
 * This is a filthy hack. Do as I say, not as I do.
 * Taken from: https://gist.github.com/branneman/8048520#6-the-hack
 * This forces the NODE_PATH environment variable to include the main
 * kolibri node_modules folder, so that even plugins being built outside
 * of the kolibri folder will have access to all installed loaders, etc.
 * Doing it here, rather than at command invocation, allows us to do this
 * in a cross platform way, and also to avoid having to prepend it to all
 * our commands that end up invoking webpack.
 */

process.env.NODE_PATH = path.resolve(path.join(__dirname, '..', '..', 'node_modules'));
require('module').Module._initPaths();

var fs = require('fs');
var webpack = require('webpack');
var jeet = require('jeet');
var autoprefixer = require('autoprefixer');

var aliases = require('./apiSpecExportTools').coreAliases();

Object.assign(aliases, {
  'kolibri_module': path.resolve('kolibri/core/assets/src/kolibri_module'),
  'content_renderer_module': path.resolve('kolibri/core/assets/src/content_renderer_module'),
});

require('./htmlhint_custom'); // adds custom rules

var config = {
  module: {
    preLoaders: [
      {
        test: /\.(vue|js)$/,
        loader: 'eslint',
        exclude: /node_modules/
      },
      {
        test: /\.(vue|html)/,
        loader: 'htmlhint',
        exclude: /node_modules/
      }
    ],
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      },
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/,
        query: {
          // Babel loader ignores Webpack config options
          // So we pass a module reference rather than a path here
          // to ensure that they get properly resolved when building happens
          // outside of the kolibri base path.
          presets: [require.resolve('babel-preset-es2015-ie')],
          plugins: [require.resolve('babel-plugin-transform-runtime')]
        },
      },
      {
        test: /\.json$/,
        loader: 'json',
        exclude: /node_modules/
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader!postcss-loader'
      },
      {
        test: /\.styl$/,
        loader: 'style-loader!css-loader?sourceMap!postcss-loader!stylus-loader!stylint'
      },
      // moved from parse_bundle_plugin.js
      {
        test: /\.(png|jpe?g|gif|svg)$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: '[name].[ext]?[hash]'
        }
      },
      // Usage of file loader allows referencing a local vtt file without in-lining it.
      // Can be removed once the local en.vtt test file is removed.
      {
        test: /\.(vtt|eot|woff|ttf|woff2)$/,
        loader: 'file',
        query: {
          name: '[name].[ext]?[hash]'
        }
      },
      // Hack to make the onloadCSS node module properly export-able.
      // Not currently used - we may be able to delete this if we
      // deprecate our custom KolibriModule async css loading functionality.
      {
        test: /fg-loadcss\/src\/onloadCSS/,
        loader: 'exports?onloadCSS'
      }
    ]
  },
  plugins: [
  ],
  resolve: {
    alias: aliases,
    extensions: ["", ".vue", ".js"],
  },
  eslint: {
    failOnError: true
  },
  htmlhint: {
    failOnError: true,
    emitAs: "error"
  },
  vue: {
    loaders: {
      stylus: 'vue-style-loader!css-loader?sourceMap!stylus-loader!stylint',
      html: 'vue-html-loader!svg-inline', // inlines SVGs
    }
  },
  stylus: {
    use: [jeet()]
  },
  postcss: function () {
    return [autoprefixer];
  },
  node: {
    __filename: true
  }
};

module.exports = config;
<|endoftext|>


<commit_before>
/*!
 * CSS - Compiler
 * Copyright(c) 2010 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var Visitor = require('./')
  , nodes = require('../nodes');

/**
 * Initialize a new `Compiler` with the given `root` Node
 * and the following `options`.
 *
 * Options:
 *
 *   - `compress`  Compress the css output, defaults to false
 *
 * @param {Node} root
 * @api public
 */

var Compiler = module.exports = function Compiler(root, options) {
  options = options || {};
  this.compress = options.compress;
  this.indents = 1;
  Visitor.call(this, root);
};

/**
 * Inherit from `Visitor.prototype`.
 */

Compiler.prototype.__proto__ = Visitor.prototype;

/**
 * Compile to css, and callback `fn(err, css)`.
 *
 * @param {Function} fn
 * @api public
 */

Compiler.prototype.compile = function(fn){
  this.callback = fn;
  this.css = this.visit(this.root);
  fn(null, this.css);
};

/**
 * Return indentation string.
 *
 * @return {String}
 * @api private
 */

Compiler.prototype.__defineGetter__('indent', function(){
  return this.compress
     ? ''
     : new Array(this.indents).join('  ');
});

/**
 * Visit Root.
 */

Compiler.prototype.visitRoot = function(block){
  this.buf = '';
  for (var i = 0, len = block.nodes.length; i < len; ++i) {
    var node = block.nodes[i];
    if (node instanceof nodes.Null
      || node instanceof nodes.Expression
      || node instanceof nodes.Function) continue;
    var ret = this.visit(node);
    if (ret) this.buf += ret + '\n';
  }
  return this.buf;
};

/**
 * Visit Function.
 */

Compiler.prototype.visitFunction = function(fn){
  return '';
};

/**
 * Visit Variable.
 */

Compiler.prototype.visitVariable = function(variable){
  return '';
};

/**
 * Visit Charset.
 */

Compiler.prototype.visitCharset = function(charset){
  return '@charset ' + this.visit(charset.val);
};

/**
 * Visit Literal.
 */

Compiler.prototype.visitLiteral = function(lit){
  return lit.val.trim().replace(/^  /gm, '');
};

/**
 * Visit Boolean.
 */

Compiler.prototype.visitBoolean = function(bool){
  return bool.toString();
};

/**
 * Visit Color.
 */

Compiler.prototype.visitColor = function(color){
  return color.toString();
};

/**
 * Visit HSLA.
 */

Compiler.prototype.visitHSLA = function(hsla){
  return hsla.rgba.toString();
};

/**
 * Visit Unit.
 */

Compiler.prototype.visitUnit = function(unit){
  var type = unit.type || ''
    , n = unit.val;

  // Int
  if ('px' == type) n = n.toFixed(0);

  // Compress
  if (this.compress) {
    // Zero is always '0'
    if (0 == unit.val) return '0';
    // Omit leading '0'
    if (unit.val < 1) {
      return n.toString().substr(1) + type;
    }
  }

  return n.toString() + type;
};

/**
 * Visit Group.
 */

Compiler.prototype.visitGroup = function(group){
  var selector = this.selector;

  // Map nested selector names
  var names = group.nodes.map(function(node){
    return selector
      ? selector + ' ' + node.val
      : node.val;
  });

  // Stash for next visitGroup
  this.selector = names;

  // Join selector names
  if (group.block.hasProperties) {
    this.buf += names.join(this.compress ? ',' : ',\n');
  }

  // Output blocks
  this.visit(group.block);
  this.selector = '';
};

/**
 * Visit Block.
 */

Compiler.prototype.visitBlock = function(block){
  if (block.hasProperties) {
    var arr = [this.compress ? '{' : ' {'];
    ++this.indents;
    for (var i = 0, len = block.nodes.length; i < len; ++i) {
      this.last = len - 1 == i;
      var node = block.nodes[i];
      if (node instanceof nodes.Null
        || node instanceof nodes.Expression
        || node instanceof nodes.Function
        || node instanceof nodes.Group) continue;
      arr.push(this.visit(node));
    }
    --this.indents;
    arr.push('}');
    this.buf += arr.join(this.compress ? '' : '\n');
    this.buf += '\n';
  }
  for (var i = 0, len = block.nodes.length; i < len; ++i) {
    var node = block.nodes[i];
    if (node instanceof nodes.Group) {
      this.visit(node);
    }
  }
};

/**
 * Visit Ident.
 */

Compiler.prototype.visitIdent = function(id){
  return id.name;
};

/**
 * Visit String.
 */

Compiler.prototype.visitString = function(string){
  return string.toString();
};

/**
 * Visit Null.
 */

Compiler.prototype.visitNull = function(node){
  return '';
};

/**
 * Visit Call.
 */

Compiler.prototype.visitCall = function(call){
  return call.name + '(' + this.visit(call.args) + ')';
};

/**
 * Visit Import.
 */

Compiler.prototype.visitImport = function(import){
  return '@import "' + import.path + '"';
};

/**
 * Visit Expression.
 */

Compiler.prototype.visitExpression = function(expr){
  return expr.nodes.map(function(node){
    return this.visit(node);
  }, this).join(expr.isList
      ? (this.compress ? ',' : ', ')
      : ' ');
};

/**
 * Visit Property.
 */

Compiler.prototype.visitProperty = function(prop){
  var self = this
    , val = this.visit(prop.expr);
  return this.indent + prop.name
    + (this.compress ? ':' + val : ': ' + val)
    + (this.compress
        ? (this.last ? '' : ';')
        : ';');
};
<commit_msg>Started fixing nested selectors<commit_after>
/*!
 * CSS - Compiler
 * Copyright(c) 2010 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var Visitor = require('./')
  , nodes = require('../nodes');

/**
 * Initialize a new `Compiler` with the given `root` Node
 * and the following `options`.
 *
 * Options:
 *
 *   - `compress`  Compress the css output, defaults to false
 *
 * @param {Node} root
 * @api public
 */

var Compiler = module.exports = function Compiler(root, options) {
  options = options || {};
  this.compress = options.compress;
  this.indents = 1;
  Visitor.call(this, root);
};

/**
 * Inherit from `Visitor.prototype`.
 */

Compiler.prototype.__proto__ = Visitor.prototype;

/**
 * Compile to css, and callback `fn(err, css)`.
 *
 * @param {Function} fn
 * @api public
 */

Compiler.prototype.compile = function(fn){
  this.callback = fn;
  this.css = this.visit(this.root);
  fn(null, this.css);
};

/**
 * Return indentation string.
 *
 * @return {String}
 * @api private
 */

Compiler.prototype.__defineGetter__('indent', function(){
  return this.compress
     ? ''
     : new Array(this.indents).join('  ');
});

/**
 * Visit Root.
 */

Compiler.prototype.visitRoot = function(block){
  this.buf = '';
  for (var i = 0, len = block.nodes.length; i < len; ++i) {
    var node = block.nodes[i];
    if (node instanceof nodes.Null
      || node instanceof nodes.Expression
      || node instanceof nodes.Function) continue;
    var ret = this.visit(node);
    if (ret) this.buf += ret + '\n';
  }
  return this.buf;
};

/**
 * Visit Function.
 */

Compiler.prototype.visitFunction = function(fn){
  return '';
};

/**
 * Visit Variable.
 */

Compiler.prototype.visitVariable = function(variable){
  return '';
};

/**
 * Visit Charset.
 */

Compiler.prototype.visitCharset = function(charset){
  return '@charset ' + this.visit(charset.val);
};

/**
 * Visit Literal.
 */

Compiler.prototype.visitLiteral = function(lit){
  return lit.val.trim().replace(/^  /gm, '');
};

/**
 * Visit Boolean.
 */

Compiler.prototype.visitBoolean = function(bool){
  return bool.toString();
};

/**
 * Visit Color.
 */

Compiler.prototype.visitColor = function(color){
  return color.toString();
};

/**
 * Visit HSLA.
 */

Compiler.prototype.visitHSLA = function(hsla){
  return hsla.rgba.toString();
};

/**
 * Visit Unit.
 */

Compiler.prototype.visitUnit = function(unit){
  var type = unit.type || ''
    , n = unit.val;

  // Int
  if ('px' == type) n = n.toFixed(0);

  // Compress
  if (this.compress) {
    // Zero is always '0'
    if (0 == unit.val) return '0';
    // Omit leading '0'
    if (unit.val < 1) {
      return n.toString().substr(1) + type;
    }
  }

  return n.toString() + type;
};

/**
 * Visit Group.
 */

Compiler.prototype.visitGroup = function(group){
  var prev = this.selector;

  // Map nested selector names
  var names = group.nodes.map(function(node){
    return prev
      ? prev.map(function(str){
        return str + ' ' + node.val;
      }).join(',\n')
      : node.val;
  });

  // Stash for next visitGroup
  this.selector = names;

  // Join selector names
  if (group.block.hasProperties) {
    this.buf += names.join(this.compress ? ',' : ',\n');
  }

  // Output blocks
  this.visit(group.block);
  this.selector = null;
};

/**
 * Visit Block.
 */

Compiler.prototype.visitBlock = function(block){
  if (block.hasProperties) {
    var arr = [this.compress ? '{' : ' {'];
    ++this.indents;
    for (var i = 0, len = block.nodes.length; i < len; ++i) {
      this.last = len - 1 == i;
      var node = block.nodes[i];
      if (node instanceof nodes.Null
        || node instanceof nodes.Expression
        || node instanceof nodes.Function
        || node instanceof nodes.Group) continue;
      arr.push(this.visit(node));
    }
    --this.indents;
    arr.push('}');
    this.buf += arr.join(this.compress ? '' : '\n');
    this.buf += '\n';
  }
  for (var i = 0, len = block.nodes.length; i < len; ++i) {
    var node = block.nodes[i];
    if (node instanceof nodes.Group) {
      this.visit(node);
    }
  }
};

/**
 * Visit Ident.
 */

Compiler.prototype.visitIdent = function(id){
  return id.name;
};

/**
 * Visit String.
 */

Compiler.prototype.visitString = function(string){
  return string.toString();
};

/**
 * Visit Null.
 */

Compiler.prototype.visitNull = function(node){
  return '';
};

/**
 * Visit Call.
 */

Compiler.prototype.visitCall = function(call){
  return call.name + '(' + this.visit(call.args) + ')';
};

/**
 * Visit Import.
 */

Compiler.prototype.visitImport = function(import){
  return '@import "' + import.path + '"';
};

/**
 * Visit Expression.
 */

Compiler.prototype.visitExpression = function(expr){
  return expr.nodes.map(function(node){
    return this.visit(node);
  }, this).join(expr.isList
      ? (this.compress ? ',' : ', ')
      : ' ');
};

/**
 * Visit Property.
 */

Compiler.prototype.visitProperty = function(prop){
  var self = this
    , val = this.visit(prop.expr);
  return this.indent + prop.name
    + (this.compress ? ':' + val : ': ' + val)
    + (this.compress
        ? (this.last ? '' : ';')
        : ';');
};
<|endoftext|>


<commit_before>'use strict';

const EventEmitter = require('events').EventEmitter;

const debug = require('debug')('sequelize-msnodesqlv8');
const mssql = require('msnodesqlv8');
const uuid = require('uuid');

const Request = require('./request.js');

function detectDriver() {
	const drivers = [
		'SQL Server Native Client 12.0',
		'SQL Server Native Client 11.0',
		'SQL Server Native Client 10.0',
		'SQL Native Client',
		'SQL Server'
	];
	let detectedDriver = null;
	return drivers.reduce((prev, driver) => {
		return prev.then(() => {
			if (detectedDriver !== null) {
				return;
			}
			return new Promise((resolve) => {
				mssql.open(`Driver=${ driver };`, (err, conn) => {
					if (err) {
						if (err.message.indexOf('Neither DSN nor SERVER keyword supplied') !== -1 && detectedDriver === null) {
							detectedDriver = driver;
						}
					} else {
						// Should not be possible because nothing but driver is specified.
						conn.close(() => {});
					}
					resolve();
				});
			});
		});
	}, Promise.resolve()).then(() => {
		if (detectedDriver) {
			return detectedDriver;
		}
		throw new Error('driver was not specified and no driver was detected');
	});
}

class Connection extends EventEmitter {
	constructor(config) {
		super();

		config = Object.assign({}, config, config.options);
		delete config.options;

		if (!config.connectionString) {
			if (typeof config.instanceName !== 'string' || config.instanceName.match(/^MSSQLSERVER$/i)) {
				config.instanceName = '';
			}
			config.connectionString = (config.driver ? `Driver={${ config.driver }};` : '') +
				`Server=${ config.server ? config.server : 'localhost' }\\${ config.instanceName };` +
				(config.database ? `Database=${ config.database };` : '') +
				(config.trustedConnection ? 'Trusted_Connection=yes;' : `Uid=${ config.userName || '' };Pwd=${ config.password || '' };`);
		}

		this.uuid = uuid.v4();
		this.config = config;
		this.connection = null;
		this.connectionCloseFunc = null;
		this.timer = null;
		this.requests = [];

		Promise.resolve().then(() => {
			let match = this.config.connectionString.match(/(?:^\s*Driver\s*=)|(?:;\s*Driver\s*=)/i);
			if (!match) {
				return detectDriver().then((driver) => {
					this.config.driver = driver;
					this.config.connectionString = `Driver={${ driver }};${ this.config.connectionString }`;
				});
			}
		}).then(() => {
			this.connect();
		}).catch((err) => {
			this.emit('connect', err);
		});
	}

	get closed() {
		return this.connection === null || this.connection.close !== this.connectionCloseFunc;
	}

	get loggedIn() {
		return !this.closed;
	}

	connect() {
		mssql.open(this.config.connectionString, (err, conn) => {
			if (!err) {
				debug(`connection (${ this.uuid }): opened`);
				this.connection = conn;
				this.connectionCloseFunc = conn.close;
				// Poll connection to make sure it is still open.
				this.timer = setInterval(() => {
					if (this.closed) {
						this.reset();
					}
				}, 5000);
			}
			this.emit('connect', err);
		});
	}

	reset() {
		debug(`connection (${ this.uuid }): reset by peer`);
		let error = new Error('connection reset by peer');
		error.code = 'ECONNRESET';
		this.emit('error', error);
	}

	close() {
		clearInterval(this.timer);
		this.timer = null;
		if (this.connection !== null) {
			this.connection.close((err) => {
				this.connection = null;
				this.emit('end', err);
			});
		} else {
			this.emit('end', new Error('connection already closed'));
		}
		this.requests.slice().forEach((request) => this.removeRequest(request, new Error('connection closed')));
		debug(`connection (${ this.uuid }): closed`);
	}

	beginTransaction(callback, name) {
		name = name || '';
		let request = new Request(`BEGIN TRANSACTION ${ name };`, (err) => {
			if (typeof callback === 'function') {
				callback(err);
			}
		});
		request.execute(this);
	}

	commitTransaction(callback, name) {
		name = name || '';
		let request = new Request(`COMMIT TRANSACTION ${ name };`, (err) => {
			if (typeof callback === 'function') {
				callback(err);
			}
		});
		request.execute(this);
	}

	rollbackTransaction(callback, name) {
		name = name || '';
		let request = new Request(`ROLLBACK TRANSACTION ${ name };`, (err) => {
			if (typeof callback === 'function') {
				callback(err);
			}
		});
		request.execute(this);
	}

	saveTransaction(callback, name) {
		if (!name) {
			callback(new Error('name required for transaction savepoint'));
			return;
		}
		let request = new Request(`SAVE TRANSACTION ${ name };`, (err) => {
			if (typeof callback === 'function') {
				callback(err);
			}
		});
		request.execute(this);
	}

	execSql(request) {
		request.execute(this);
	}

	removeRequest(request, error) {
		debug(`connection (${ this.uuid }): removing request (${ request.uuid })`);
		let index = this.requests.indexOf(request);
		if (index !== -1) {
			this.requests.splice(index, 1);
			if (error && typeof request.callback === 'function') {
				request.callback(error);
			}
		}
	}
}

module.exports = Connection;
<commit_msg>lib.connection: modify transaction commands to add delimiters<commit_after>'use strict';

const EventEmitter = require('events').EventEmitter;

const debug = require('debug')('sequelize-msnodesqlv8');
const mssql = require('msnodesqlv8');
const uuid = require('uuid');

const Request = require('./request.js');

function detectDriver() {
	const drivers = [
		'SQL Server Native Client 12.0',
		'SQL Server Native Client 11.0',
		'SQL Server Native Client 10.0',
		'SQL Native Client',
		'SQL Server'
	];
	let detectedDriver = null;
	return drivers.reduce((prev, driver) => {
		return prev.then(() => {
			if (detectedDriver !== null) {
				return;
			}
			return new Promise((resolve) => {
				mssql.open(`Driver=${ driver };`, (err, conn) => {
					if (err) {
						if (err.message.indexOf('Neither DSN nor SERVER keyword supplied') !== -1 && detectedDriver === null) {
							detectedDriver = driver;
						}
					} else {
						// Should not be possible because nothing but driver is specified.
						conn.close(() => {});
					}
					resolve();
				});
			});
		});
	}, Promise.resolve()).then(() => {
		if (detectedDriver) {
			return detectedDriver;
		}
		throw new Error('driver was not specified and no driver was detected');
	});
}

class Connection extends EventEmitter {
	constructor(config) {
		super();

		config = Object.assign({}, config, config.options);
		delete config.options;

		if (!config.connectionString) {
			if (typeof config.instanceName !== 'string' || config.instanceName.match(/^MSSQLSERVER$/i)) {
				config.instanceName = '';
			}
			config.connectionString = (config.driver ? `Driver={${ config.driver }};` : '') +
				`Server=${ config.server ? config.server : 'localhost' }\\${ config.instanceName };` +
				(config.database ? `Database=${ config.database };` : '') +
				(config.trustedConnection ? 'Trusted_Connection=yes;' : `Uid=${ config.userName || '' };Pwd=${ config.password || '' };`);
		}

		this.uuid = uuid.v4();
		this.config = config;
		this.connection = null;
		this.connectionCloseFunc = null;
		this.timer = null;
		this.requests = [];

		Promise.resolve().then(() => {
			let match = this.config.connectionString.match(/(?:^\s*Driver\s*=)|(?:;\s*Driver\s*=)/i);
			if (!match) {
				return detectDriver().then((driver) => {
					this.config.driver = driver;
					this.config.connectionString = `Driver={${ driver }};${ this.config.connectionString }`;
				});
			}
		}).then(() => {
			this.connect();
		}).catch((err) => {
			this.emit('connect', err);
		});
	}

	get closed() {
		return this.connection === null || this.connection.close !== this.connectionCloseFunc;
	}

	get loggedIn() {
		return !this.closed;
	}

	connect() {
		mssql.open(this.config.connectionString, (err, conn) => {
			if (!err) {
				debug(`connection (${ this.uuid }): opened`);
				this.connection = conn;
				this.connectionCloseFunc = conn.close;
				// Poll connection to make sure it is still open.
				this.timer = setInterval(() => {
					if (this.closed) {
						this.reset();
					}
				}, 5000);
			}
			this.emit('connect', err);
		});
	}

	reset() {
		debug(`connection (${ this.uuid }): reset by peer`);
		let error = new Error('connection reset by peer');
		error.code = 'ECONNRESET';
		this.emit('error', error);
	}

	close() {
		clearInterval(this.timer);
		this.timer = null;
		if (this.connection !== null) {
			this.connection.close((err) => {
				this.connection = null;
				this.emit('end', err);
			});
		} else {
			this.emit('end', new Error('connection already closed'));
		}
		this.requests.slice().forEach((request) => this.removeRequest(request, new Error('connection closed')));
		debug(`connection (${ this.uuid }): closed`);
	}

	beginTransaction(callback, name) {
		name = name ? `[${ name }]` : '';
		let request = new Request(`BEGIN TRANSACTION ${ name };`, (err) => {
			if (typeof callback === 'function') {
				callback(err);
			}
		});
		request.execute(this);
	}

	commitTransaction(callback, name) {
		name = name ? `[${ name }]` : '';
		let request = new Request(`COMMIT TRANSACTION ${ name };`, (err) => {
			if (typeof callback === 'function') {
				callback(err);
			}
		});
		request.execute(this);
	}

	rollbackTransaction(callback, name) {
		name = name ? `[${ name }]` : '';
		let request = new Request(`ROLLBACK TRANSACTION ${ name };`, (err) => {
			if (typeof callback === 'function') {
				callback(err);
			}
		});
		request.execute(this);
	}

	saveTransaction(callback, name) {
		if (!name) {
			callback(new Error('name required for transaction savepoint'));
			return;
		}
		name = `[${ name }]`;
		let request = new Request(`SAVE TRANSACTION ${ name };`, (err) => {
			if (typeof callback === 'function') {
				callback(err);
			}
		});
		request.execute(this);
	}

	execSql(request) {
		request.execute(this);
	}

	removeRequest(request, error) {
		debug(`connection (${ this.uuid }): removing request (${ request.uuid })`);
		let index = this.requests.indexOf(request);
		if (index !== -1) {
			this.requests.splice(index, 1);
			if (error && typeof request.callback === 'function') {
				request.callback(error);
			}
		}
	}
}

module.exports = Connection;
<|endoftext|>


<commit_before>/* @flow */
'use strict';
const _ = require('lodash');
const utils = require('./utils');
const {validate} = utils.common;
import type {Submit} from './types.js';

function isImmediateRejection(engineResult: string): boolean {
  // note: "tel" errors mean the local server refused to process the
  // transaction *at that time*, but it could potentially buffer the
  // transaction and then process it at a later time, for example
  // if the required fee changes (this does not occur at the time of
  // this writing, but it could change in the future)
  // all other error classes can potentially result in transcation validation
  return _.startsWith(engineResult, 'tem') || _.startsWith(engineResult, 'tej');
}

function formatSubmitResponse(response) {
  const data = {
    resultCode: response.engine_result,
    resultMessage: response.engine_result_message
  };
  if (isImmediateRejection(response.engine_result)) {
    throw new utils.common.errors.RippledError('Submit failed', data);
  }
  return data;
}

function submit(signedTransaction: string): Promise<Submit> {
  validate.submit({signedTransaction});

  const request = {
    command: 'submit',
    tx_blob: signedTransaction
  };
  return this.connection.request(request).then(formatSubmitResponse);
}

module.exports = submit;
<commit_msg>[FIX] remove check for `tej` class of errors.<commit_after>/* @flow */
'use strict'; // eslint-disable-line
const _ = require('lodash');
const utils = require('./utils');
const {validate} = utils.common;
import type {Submit} from './types.js';

function isImmediateRejection(engineResult: string): boolean {
  // note: "tel" errors mean the local server refused to process the
  // transaction *at that time*, but it could potentially buffer the
  // transaction and then process it at a later time, for example
  // if the required fee changes (this does not occur at the time of
  // this writing, but it could change in the future)
  // all other error classes can potentially result in transcation validation
  return _.startsWith(engineResult, 'tem');
}

function formatSubmitResponse(response) {
  const data = {
    resultCode: response.engine_result,
    resultMessage: response.engine_result_message
  };
  if (isImmediateRejection(response.engine_result)) {
    throw new utils.common.errors.RippledError('Submit failed', data);
  }
  return data;
}

function submit(signedTransaction: string): Promise<Submit> {
  validate.submit({signedTransaction});

  const request = {
    command: 'submit',
    tx_blob: signedTransaction
  };
  return this.connection.request(request).then(formatSubmitResponse);
}

module.exports = submit;
<|endoftext|>


<commit_before>'use strict';

var angular = require('angular');
var tartan = require('tartan');
var ngTartan = require('../../module');

function makeDraggable(window, canvas, getOffset, repaint) {
  var document = window.document;
  var drag = null;
  var dragTarget = document.releaseCapture ? canvas : window;

  function onMouseDown(event) {
    event = event || window.event;
    if (event.target !== canvas) {
      return;
    }
    if (event.buttons == 1) {
      event.preventDefault();
      drag = {
        x: event.clientX,
        y: event.clientY
      };
      if (event.target && event.target.setCapture) {
        // Only IE and FF
        event.target.setCapture();
      }
    }
  }
  function onMouseMove(event) {
    event = event || window.event;
    if (drag) {
      if (event.buttons != 1) {
        drag = null;
        if (document.releaseCapture) {
          // Only IE and FF
          document.releaseCapture();
        }
      } else {
        var offset = getOffset();
        offset.x += event.clientX - drag.x;
        offset.y += event.clientY - drag.y;

        drag.x = event.clientX;
        drag.y = event.clientY;

        event.preventDefault();
      }

      repaint();
    }
  }
  function onMouseUp(event) {
    event = event || window.event;
    if (event.buttons == 1) {
      drag = null;
      if (document.releaseCapture) {
        // Only IE and FF
        document.releaseCapture();
      }
    }
    repaint();
  }
  function onLoseCapture() {
    // Only IE and FF
    drag = null;
  }

  dragTarget.addEventListener('mousedown', onMouseDown);
  dragTarget.addEventListener('mousemove', onMouseMove);
  dragTarget.addEventListener('mouseup', onMouseUp);
  canvas.addEventListener('losecapture', onLoseCapture);

  return function() {
    dragTarget.removeEventListener('mousedown', onMouseDown);
    dragTarget.removeEventListener('mousemove', onMouseMove);
    dragTarget.removeEventListener('mouseup', onMouseUp);
    canvas.removeEventListener('losecapture', onLoseCapture);
  };
}

function makeResizable(window, update) {
  function onResize() {
    if (angular.isFunction(update)) {
      update();
    }
  }

  window.addEventListener('resize', onResize);
  return function() {
    window.removeEventListener('mousedown', onResize);
  };
}

ngTartan.directive('tartanPreviewControl', [
  '$window', '$timeout',
  function($window, $timeout) {
    return {
      restrict: 'E',
      require: '^^tartan',
      template:
        '
' +
          '<canvas></canvas>' +
        '
',
      replace: true,
      scope: {
        weave: '=?',
        repeat: '=?',
        offset: '=?',
        metrics: '=?',
        interactive: '=?',
        zoom: '=?',
        renderer: '=?'
      },
      link: function($scope, element, attr, controller) {
        element.css({
          position: 'relative'
        });

        var target = element.find('canvas');
        var canvas = target.get(0);
        var parent = target.parent().get(0);
        var render = null;
        var currentState = null;
        var offset = {x: 0, y: 0};

        $scope.interactiveOptions = {
          resize: false,
          drag: false
        };

        function updateOffset() {
          $scope.offset = angular.extend({}, offset);
        }

        var repaint = tartan.utils.repaint(function() {
          if (!$scope.interactive) {
            offset = {x: 0, y: 0};
          }
          offset = render(canvas, offset, !!$scope.repeat);
          $timeout(updateOffset);
        });

        function update() {
          var options = {
            zoom: $scope.zoom,
            weave: $scope.weave,
            defaultColors: currentState.colors,
            transformSyntaxTree: tartan.transform.flatten()
          };

          var renderer = tartan.render[$scope.renderer];
          if (!angular.isFunction(renderer)) {
            renderer = tartan.render.canvas;
            if (angular.isString($scope.renderer)) {
              for (var key in tartan.render) {
                if (
                  angular.isFunction(tartan.render[key]) &&
                  angular.isString(tartan.render[key].id) &&
                  (tartan.render[key].id == $scope.renderer)
                ) {
                  renderer = tartan.render[key];
                  break;
                }
              }
            }
          }

          render = renderer(currentState.sett, options);
          $scope.metrics = render.metrics;
          updateCanvasSize();
        }

        function tartanChanged(state) {
          currentState = state;
          update();
          $scope.$applyAsync();
        }

        controller.on('tartan.changed', tartanChanged);

        controller.requestUpdate(tartanChanged);

        ['weave', 'repeat', 'zoom', 'renderer'].forEach(function(name) {
          $scope.$watch(name, function(newValue, oldValue) {
            if (newValue !== oldValue) {
              update();
            }
          }, true);
        });

        $scope.$watch('offset', function(newValue, oldValue) {
          if (newValue !== oldValue) {
            var temp = angular.extend({}, offset, newValue);
            if ((temp.x != offset.x) || (temp.y != offset.y)) {
              offset = temp;
              repaint();
            }
          }
        }, true);

        var disableResize = null;
        var disableDrag = null;

        $scope.$watch('interactive', function() {
          var interactive = angular.extend({
            resize: false,
            drag: false
          }, $scope.interactive === true ? {
            resize: true,
            drag: true
          } : $scope.interactive);
          $scope.interactiveOptions = interactive;

          var disable = [];
          if (interactive.resize) {
            if (!disableResize) {
              disableResize = makeResizable($window, updateCanvasSize);
            }
          } else if (disableResize) {
            // Disable it later, but NULL it now
            disable.push(disableResize);
            disableResize = null;
          }

          if (interactive.drag) {
            if (!disableDrag) {
              disableDrag = makeDraggable($window, canvas, function() {
                return offset;
              }, repaint);
            }
          } else if (disableDrag) {
            // Disable it later, but NULL it now
            disable.push(disableDrag);
            disableDrag = null;
          }
          repaint();

          // Safely run each callback - even if one of them will
          // crash - it doesn't matter at the moment
          disable.forEach(function(disable) {
            disable();
          });
        });

        function updateCanvasSize() {
          var w = Math.ceil(parent.offsetWidth);
          var h = Math.ceil(parent.offsetHeight);
          target.css({
            position: 'absolute',
            left: '0px',
            top: '0px',
            width: w + 'px',
            height: h + 'px'
          });
          if (canvas.width != w) {
            canvas.width = w;
          }
          if (canvas.height != h) {
            canvas.height = h;
          }
          repaint();
        }

        $scope.$on('$destroy', function() {
          controller.off('tartan.changed', tartanChanged);
          if (disableDrag) {
            disableDrag();
          }
          if (disableResize) {
            disableResize();
          }
        });
      }
    };
  }
]);
<commit_msg>Unsubscribe from proper event<commit_after>'use strict';

var angular = require('angular');
var tartan = require('tartan');
var ngTartan = require('../../module');

function makeDraggable(window, canvas, getOffset, repaint) {
  var document = window.document;
  var drag = null;
  var dragTarget = document.releaseCapture ? canvas : window;

  function onMouseDown(event) {
    event = event || window.event;
    if (event.target !== canvas) {
      return;
    }
    if (event.buttons == 1) {
      event.preventDefault();
      drag = {
        x: event.clientX,
        y: event.clientY
      };
      if (event.target && event.target.setCapture) {
        // Only IE and FF
        event.target.setCapture();
      }
    }
  }
  function onMouseMove(event) {
    event = event || window.event;
    if (drag) {
      if (event.buttons != 1) {
        drag = null;
        if (document.releaseCapture) {
          // Only IE and FF
          document.releaseCapture();
        }
      } else {
        var offset = getOffset();
        offset.x += event.clientX - drag.x;
        offset.y += event.clientY - drag.y;

        drag.x = event.clientX;
        drag.y = event.clientY;

        event.preventDefault();
      }

      repaint();
    }
  }
  function onMouseUp(event) {
    event = event || window.event;
    if (event.buttons == 1) {
      drag = null;
      if (document.releaseCapture) {
        // Only IE and FF
        document.releaseCapture();
      }
    }
    repaint();
  }
  function onLoseCapture() {
    // Only IE and FF
    drag = null;
  }

  dragTarget.addEventListener('mousedown', onMouseDown);
  dragTarget.addEventListener('mousemove', onMouseMove);
  dragTarget.addEventListener('mouseup', onMouseUp);
  canvas.addEventListener('losecapture', onLoseCapture);

  return function() {
    dragTarget.removeEventListener('mousedown', onMouseDown);
    dragTarget.removeEventListener('mousemove', onMouseMove);
    dragTarget.removeEventListener('mouseup', onMouseUp);
    canvas.removeEventListener('losecapture', onLoseCapture);
  };
}

function makeResizable(window, update) {
  function onResize() {
    if (angular.isFunction(update)) {
      update();
    }
  }

  window.addEventListener('resize', onResize);
  return function() {
    window.removeEventListener('resize', onResize);
  };
}

ngTartan.directive('tartanPreviewControl', [
  '$window', '$timeout',
  function($window, $timeout) {
    return {
      restrict: 'E',
      require: '^^tartan',
      template:
        '
' +
          '<canvas></canvas>' +
        '
',
      replace: true,
      scope: {
        weave: '=?',
        repeat: '=?',
        offset: '=?',
        metrics: '=?',
        interactive: '=?',
        zoom: '=?',
        renderer: '=?'
      },
      link: function($scope, element, attr, controller) {
        element.css({
          position: 'relative'
        });

        var target = element.find('canvas');
        var canvas = target.get(0);
        var parent = target.parent().get(0);
        var render = null;
        var currentState = null;
        var offset = {x: 0, y: 0};

        $scope.interactiveOptions = {
          resize: false,
          drag: false
        };

        function updateOffset() {
          $scope.offset = angular.extend({}, offset);
        }

        var repaint = tartan.utils.repaint(function() {
          if (!$scope.interactive) {
            offset = {x: 0, y: 0};
          }
          offset = render(canvas, offset, !!$scope.repeat);
          $timeout(updateOffset);
        });

        function update() {
          var options = {
            zoom: $scope.zoom,
            weave: $scope.weave,
            defaultColors: currentState.colors,
            transformSyntaxTree: tartan.transform.flatten()
          };

          var renderer = tartan.render[$scope.renderer];
          if (!angular.isFunction(renderer)) {
            renderer = tartan.render.canvas;
            if (angular.isString($scope.renderer)) {
              for (var key in tartan.render) {
                if (
                  angular.isFunction(tartan.render[key]) &&
                  angular.isString(tartan.render[key].id) &&
                  (tartan.render[key].id == $scope.renderer)
                ) {
                  renderer = tartan.render[key];
                  break;
                }
              }
            }
          }

          render = renderer(currentState.sett, options);
          $scope.metrics = render.metrics;
          updateCanvasSize();
        }

        function tartanChanged(state) {
          currentState = state;
          update();
          $scope.$applyAsync();
        }

        controller.on('tartan.changed', tartanChanged);

        controller.requestUpdate(tartanChanged);

        ['weave', 'repeat', 'zoom', 'renderer'].forEach(function(name) {
          $scope.$watch(name, function(newValue, oldValue) {
            if (newValue !== oldValue) {
              update();
            }
          }, true);
        });

        $scope.$watch('offset', function(newValue, oldValue) {
          if (newValue !== oldValue) {
            var temp = angular.extend({}, offset, newValue);
            if ((temp.x != offset.x) || (temp.y != offset.y)) {
              offset = temp;
              repaint();
            }
          }
        }, true);

        var disableResize = null;
        var disableDrag = null;

        $scope.$watch('interactive', function() {
          var interactive = angular.extend({
            resize: false,
            drag: false
          }, $scope.interactive === true ? {
            resize: true,
            drag: true
          } : $scope.interactive);
          $scope.interactiveOptions = interactive;

          var disable = [];
          if (interactive.resize) {
            if (!disableResize) {
              disableResize = makeResizable($window, updateCanvasSize);
            }
          } else if (disableResize) {
            // Disable it later, but NULL it now
            disable.push(disableResize);
            disableResize = null;
          }

          if (interactive.drag) {
            if (!disableDrag) {
              disableDrag = makeDraggable($window, canvas, function() {
                return offset;
              }, repaint);
            }
          } else if (disableDrag) {
            // Disable it later, but NULL it now
            disable.push(disableDrag);
            disableDrag = null;
          }
          repaint();

          // Safely run each callback - even if one of them will
          // crash - it doesn't matter at the moment
          disable.forEach(function(disable) {
            disable();
          });
        });

        function updateCanvasSize() {
          var w = Math.ceil(parent.offsetWidth);
          var h = Math.ceil(parent.offsetHeight);
          target.css({
            position: 'absolute',
            left: '0px',
            top: '0px',
            width: w + 'px',
            height: h + 'px'
          });
          if (canvas.width != w) {
            canvas.width = w;
          }
          if (canvas.height != h) {
            canvas.height = h;
          }
          repaint();
        }

        $scope.$on('$destroy', function() {
          controller.off('tartan.changed', tartanChanged);
          if (disableDrag) {
            disableDrag();
          }
          if (disableResize) {
            disableResize();
          }
        });
      }
    };
  }
]);
<|endoftext|>