<commit_before>define
([
    'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap',
    'tmpl!auth',
],
function($, superdesk, dust, jsSHA)
{
<<<<<<< HEAD
    var AuthLogin = function(username, password, logintoken){
=======
    var AuthDetails = function(username){
		var authDetails = new $.rest('Superdesk/User');
		authDetails.resetData().xfilter('Name,Id,EMail').select({ name: username }).done(function(users){
			var user = users.UserList[0];
			localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.Name);
			localStorage.setItem('superdesk.login.email', user.EMail);
		});
		return $(authDetails);
	},
	AuthLogin = function(username, password, logintoken){
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
		var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"),
			authLogin = new $.rest('Authentication');
			authLogin.resetData().insert({
			UserName: username,
			LoginToken: logintoken,
			HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX")
		}).done(function(user){
			localStorage.setItem('superdesk.login.session', user.Session);
<<<<<<< HEAD
			localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.UserName);
			localStorage.setItem('superdesk.login.email', user.EMail);
			$(authLogin).trigger('success');
=======
			//localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.UserName);
			localStorage.setItem('superdesk.login.email', user.EMail);
			$(authLogin).trigger('success');
/*			authDetails = AuthDetails(username);
			$(authDetails).on('failed', function(){
				$(authLogin).trigger('failed', 'authDetails');
			});
*/
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
		});
		return $(authLogin);
	},
	AuthToken = function(username, password) {
		var authToken = new $.rest('Authentication');
		authToken.resetData().select({ userName: username }).done(
			function(data){
				authLogin = AuthLogin(username, password, data.Token);
				authLogin.on('failed', function(){
					$(authToken).trigger('failed', 'authToken');
				}).on('success', function(){
					$(authToken).trigger('success');
				});
			}
		);
		return $(authToken);
	},
	AuthApp =
    {
        success: $.noop,
        require: function()
        {
			if(this.showed) return;
            var self = this; // rest
			self.showed = true;
            $.tmpl('auth', null, function(e, o)
            {
                var dialog = $(o).eq(0).dialog
                ({
                    draggable: false,
                    resizable: false,
                    modal: true,
                    width: "40.1709%",
                    buttons:
                    [
                         { text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"},
                         { text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"}
                    ]
                }),
                    form = dialog.find('form');
                form.off('submit.superdesk')//
                .on('submit.superdesk', function(event)
                {
                    var username = $(this).find('#username'), password=$(this).find('#password');
					AuthToken(username.val(), password.val()).on('failed',function(evt, type){
						username.val('');
						password.val('')
					}).on('success', function(){
                        AuthApp.success && AuthApp.success.apply();
						$(dialog).dialog('close');
						self.showed = false;
					});
                    event.preventDefault();

                });
            });
        }
    };
    return AuthApp;
});<commit_msg>NR-226: Create login functionality in Ally framework<commit_after>define
([
    'jquery', 'jquery/superdesk', 'dust/core', 'utils/sha512', 'jquery/tmpl', 'jquery/rest', 'bootstrap',
    'tmpl!auth',
],
function($, superdesk, dust, jsSHA)
{
<<<<<<< HEAD
    var AuthLogin = function(username, password, logintoken){
=======
    var AuthDetails = function(username){
		var authDetails = new $.rest('Superdesk/User');
		authDetails.resetData().xfilter('Name,Id,EMail').select({ name: username }).done(function(users){
			var user = users.UserList[0];
			localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.Name);
			localStorage.setItem('superdesk.login.email', user.EMail);
		});
		return $(authDetails);
	},
	AuthLogin = function(username, password, logintoken){
>>>>>>> 718d8c014dc7f1c47606de731769286a6bcebb81
		var shaObj = new jsSHA(logintoken, "ASCII"),shaPassword = new jsSHA(password, "ASCII"),
			authLogin = new $.rest('Authentication');
			authLogin.resetData().insert({
			UserName: username,
			LoginToken: logintoken,
			HashedLoginToken: shaObj.getHMAC(username+shaPassword.getHash("SHA-512", "HEX"), "ASCII", "SHA-512", "HEX")
		}).done(function(user){
			localStorage.setItem('superdesk.login.session', user.Session);
			localStorage.setItem('superdesk.login.id', user.Id);
			localStorage.setItem('superdesk.login.name', user.UserName);
			localStorage.setItem('superdesk.login.email', user.EMail);
			$(authLogin).trigger('success');
		});
		return $(authLogin);
	},
	AuthToken = function(username, password) {
		var authToken = new $.rest('Authentication');
		authToken.resetData().select({ userName: username }).done(
			function(data){
				authLogin = AuthLogin(username, password, data.Token);
				authLogin.on('failed', function(){
					$(authToken).trigger('failed', 'authToken');
				}).on('success', function(){
					$(authToken).trigger('success');
				});
			}
		);
		return $(authToken);
	},
	AuthApp =
    {
        success: $.noop,
        require: function()
        {
			if(this.showed) return;
            var self = this; // rest
			self.showed = true;
            $.tmpl('auth', null, function(e, o)
            {
                var dialog = $(o).eq(0).dialog
                ({
                    draggable: false,
                    resizable: false,
                    modal: true,
                    width: "40.1709%",
                    buttons:
                    [
                         { text: "Login", click: function(){ $(form).trigger('submit'); }, class: "btn btn-primary"},
                         { text: "Close", click: function(){ $(this).dialog('close'); }, class: "btn"}
                    ]
                }),
                    form = dialog.find('form');
                form.off('submit.superdesk')//
                .on('submit.superdesk', function(event)
                {
                    var username = $(this).find('#username'), password=$(this).find('#password');
					AuthToken(username.val(), password.val()).on('failed',function(evt, type){
						username.val('');
						password.val('')
					}).on('success', function(){
                        AuthApp.success && AuthApp.success.apply();
						$(dialog).dialog('close');
						self.showed = false;
					});
                    event.preventDefault();

                });
            });
        }
    };
    return AuthApp;
});<|endoftext|>


<commit_before>/*
---
script: expectation.js
description: expectation class
license: MIT-style license
authors:
- Mark Obcena
provides: [Expectation]
...
*/

(function(){

var utils = require('./utils'),
	typeOf = utils.typeOf,
	instanceOf = utils.instanceOf;

var prepareNot = function(exp){
	exp.not = {};
	for (var matcher in Expectation.Matchers) (function(matcher){
		exp.not[matcher] = function(expected){
			var Matchers = Expectation.Matchers;
			var result = !Matchers[matcher].call(Matchers, exp.$received, expected);
			exp.$callback.call(exp.$bound, result, exp.$received, expected, 'not.' + matcher);
			return result;
		};
	})(matcher);
};

var Expectation = function(value, callback, bound){
	this.$received = value;
	this.$callback = callback || function(){};
	this.$bound = bound || this;
	prepareNot(this);
};

Expectation.setMatcher = function(name, func){
	if (func === undefined || !(func instanceof Function))
		throw new TypeError('Expectation.setMatcher requires a function as its second argument.');
	Expectation.prototype[name] = function(expected){
		var Matchers = Expectation.Matchers;
		var result = func.call(Matchers, this.$received, expected);
		this.$callback.call(this.$bound, result, this.$received, expected, name);
		return result;
	};
};

Expectation.Matchers = {

	toBe: function(received, expected){
		return expected === received;
	},

	toEqual: function(received, expected){
		return expected == received;
	},

	toBeType: function(received, expected){
		return expected == typeOf(received);
	},

	toBeAnInstanceOf: function(received, expected){
		return instanceOf(received, expected);
	},

	toBeNull: function(received){
		return received === null;
	},

	toBeUndefined: function(received){
		return received === undefined;
	},

	toBeTrue: function(received){
		return received === true;
	},

	toBeTruthy: function(received){
		return (!!received) === true;
	},

	toBeFalse: function(received){
		return received === false;
	},

	toBeFalsy: function(received){
		return (!!received) === false;
	},

	toHaveMember: function(received, expected){
		try {
			return (expected in received);
		} catch(e){
			return false;
		}
	},

	toHaveProperty: function(received, expected){
		try {
			return (expected in received) && received[expected] !== undefined && !(received[expected] instanceof Function);
		} catch(e){
			return false;
		}
	},

	toHaveMethod: function(received, expected){
		try {
			return (expected in received) && received[expected] !== undefined && (received[expected] instanceof Function);
		} catch(e){
			return false;
		}
	},

	toBeLike: function(received, expected){
		var type = typeOf(expected);
		if (type !== typeOf(received)) return null;
		if (type == 'object'){
			for (var key in expected){
				if (received[key] === undefined || !this.toBeLike(received[key], expected[key])) return false;
			}
		} else if (type == 'array'){
			var len = expected.length;
			while (len--){
				if (!this.toBeLike(received[len], expected[len])) return false;
			}
		} else {
			return expected === received;
		}
		return true;
	},

	toBeSimilar: function(received, expected){
		return JSON.stringify(received) === JSON.stringify(expected);
	},

	toMatch: function(received, expected){
		return expected.test(received);
	}

};

for (var matcher in Expectation.Matchers) Expectation.setMatcher(matcher, Expectation.Matchers[matcher]);

exports.Expectation = Expectation;

})();
<commit_msg>* Make setMatcher add matcher directly to Expectation.Matchers.<commit_after>/*
---
script: expectation.js
description: expectation class
license: MIT-style license
authors:
- Mark Obcena
provides: [Expectation]
...
*/

(function(){

var utils = require('./utils'),
	typeOf = utils.typeOf,
	instanceOf = utils.instanceOf;

var prepareNot = function(exp){
	exp.not = {};
	for (var matcher in Expectation.Matchers) (function(matcher){
		exp.not[matcher] = function(expected){
			var Matchers = Expectation.Matchers;
			var result = !Matchers[matcher].call(Matchers, exp.$received, expected);
			exp.$callback.call(exp.$bound, result, exp.$received, expected, 'not.' + matcher);
			return result;
		};
	})(matcher);
};

var Expectation = function(value, callback, bound){
	this.$received = value;
	this.$callback = callback || function(){};
	this.$bound = bound || this;
	prepareNot(this);
};

Expectation.setMatcher = function(name, func){
	if (func === undefined || !(func instanceof Function))
		throw new TypeError('Expectation.setMatcher requires a function as its second argument.');
	Expectation.prototype[name] = function(expected){
		var Matchers = Expectation.Matchers;
		var result = func.call(Matchers, this.$received, expected);
		this.$callback.call(this.$bound, result, this.$received, expected, name);
		return result;
	};
	Expectation.Matchers[name] = func;
};

Expectation.Matchers = {

	toBe: function(received, expected){
		return expected === received;
	},

	toEqual: function(received, expected){
		return expected == received;
	},

	toBeType: function(received, expected){
		return expected == typeOf(received);
	},

	toBeAnInstanceOf: function(received, expected){
		return instanceOf(received, expected);
	},

	toBeNull: function(received){
		return received === null;
	},

	toBeUndefined: function(received){
		return received === undefined;
	},

	toBeTrue: function(received){
		return received === true;
	},

	toBeTruthy: function(received){
		return (!!received) === true;
	},

	toBeFalse: function(received){
		return received === false;
	},

	toBeFalsy: function(received){
		return (!!received) === false;
	},

	toHaveMember: function(received, expected){
		try {
			return (expected in received);
		} catch(e){
			return false;
		}
	},

	toHaveProperty: function(received, expected){
		try {
			return (expected in received) && received[expected] !== undefined && !(received[expected] instanceof Function);
		} catch(e){
			return false;
		}
	},

	toHaveMethod: function(received, expected){
		try {
			return (expected in received) && received[expected] !== undefined && (received[expected] instanceof Function);
		} catch(e){
			return false;
		}
	},

	toBeLike: function(received, expected){
		var type = typeOf(expected);
		if (type !== typeOf(received)) return null;
		if (type == 'object'){
			for (var key in expected){
				if (received[key] === undefined || !this.toBeLike(received[key], expected[key])) return false;
			}
		} else if (type == 'array'){
			var len = expected.length;
			while (len--){
				if (!this.toBeLike(received[len], expected[len])) return false;
			}
		} else {
			return expected === received;
		}
		return true;
	},

	toBeSimilar: function(received, expected){
		return JSON.stringify(received) === JSON.stringify(expected);
	},

	toMatch: function(received, expected){
		return expected.test(received);
	}

};

for (var matcher in Expectation.Matchers) Expectation.setMatcher(matcher, Expectation.Matchers[matcher]);

exports.Expectation = Expectation;

})();
<|endoftext|>


<commit_before>angular.module('apolloApp').controller('adminCRQueueCtrl', ['$scope','$modal','$location','$http','nodeAttributeDictionary','ngIdentity',
	function($scope,$modal,$location, $http,nodeAttributeDictionary,ngIdentity) {

    var checkcounter=0;
    var cacheRenew=new Date().getTime();
    $http.get('/apollo/api/node/all'+'?'+cacheRenew).then(function(res) {
      $scope.nodeNameallArray=res.data;
      //console.log($scope.nodeNameallArray);
      checkcounter++;
      if(checkcounter==2)
      {
        getSimilarities();
      }
    });

    $scope.open = function (docid) {

        var modalInstance = $modal.open({
          templateUrl: 'myModalContent.html',
          controller: 'ModalInstanceCtrl',
          size: 'sm',
          resolve: {
            doc_id: function () {
              return docid;
            }
          }
        });

        modalInstance.result.then(function (docid) {
            $scope.deleteCR(docid);
        }, function () {
          //$log.info('Modal dismissed at: ' + new Date());
          //console.log('Modal dismissed at: ' + new Date(),$scope.selected);
        });
    };

    $scope.crStatusModel='PENDING';
    //console.log("test");
    $scope.userFilter="";
    $scope.usersu=false;

    // var location = $location.path();
    // console.log(location);

     $scope.isActive = function(route) {
        return route === $location.path();
    }

    $scope.init=function()
    {

        if($scope.identity.currentUser.roles.levelTwo)
        {
            $scope.usersu=true;
            //$scope.userFilter="";
        }
        else
        {
            $scope.usersu=false;
            //$scope.userFilter=$scope.identity.currentUser.displayName;
        }

        $scope.mongoDocumentsAll=[];
        $scope.crtSelect="";
        $scope.crtOpen=false;
        $scope.crFilterModel='';

        $scope.sortval="CR_DATE_CREATED";

        $scope.crAddCount=0;
        $scope.crDeleteCount=0;
        $scope.crUpdateCount=0;
        $scope.hover=false;
        $scope.reverse = true;
        var cacheRenew=new Date().getTime();
        $http.get('/apollo/api/mongo/all'+'?'+cacheRenew).then(function(res) {
            $scope.mongoDocumentsAll=res.data;
            //console.log($scope.mongoDocumentsAll);

            for (var i=0;i<$scope.mongoDocumentsAll.length;i++)
            {
                //console.log($scope.mongoDocumentsAll[i].CR_REQUEST_TYPE);
                if($scope.mongoDocumentsAll[i].CR_REQUEST_TYPE=="ADD" && $scope.mongoDocumentsAll[i].CR_STATUS=="PENDING")
                {
                    $scope.crAddCount++;
                }
                else if($scope.mongoDocumentsAll[i].CR_REQUEST_TYPE=="DELETE" && $scope.mongoDocumentsAll[i].CR_STATUS=="PENDING")
                {
                    $scope.crDeleteCount++;
                }
                else if($scope.mongoDocumentsAll[i].CR_REQUEST_TYPE=="UPDATE" && $scope.mongoDocumentsAll[i].CR_STATUS=="PENDING")
                {
                    $scope.crUpdateCount++;
                }
            }

            // if(!$scope.$$phase) {
            //   $scope.$apply();
            // }
            checkcounter++;
            if(checkcounter==2)
            {
              getSimilarities();
            }

        });

        //$scope.crAddCount
    }

    $scope.init();

   var getSimilarities = function()
   {

      for(cr in $scope.mongoDocumentsAll)
      {

        var crnodename=$scope.mongoDocumentsAll[cr].name;
        console.log('CR NODE NAME',crnodename);
        var crnodeid=$scope.mongoDocumentsAll[cr].id;
        if(crnodeid==undefined || crnodeid==null || crnodeid=="")
        {
          crnodeid="TBD";
        }
        //console.log("******************",crnodename,"*******************");

        var similarNodes=[];
        //console.log($scope.nodeNameallArray);
        for(n in $scope.nodeNameallArray)
        {
          var neonodename=$scope.nodeNameallArray[n].name;

          var neonodeid=$scope.nodeNameallArray[n].id;
          console.log('NEO NODE NAME', neonodename);
          console.log('NEO NODE ID', neonodeid);
          if(neonodeid==crnodeid)
          {

          }
          else
          {
            if(neonodename != null){
              if(crnodename.toLowerCase()==neonodename.toLowerCase())
              {
                similarNodes.push({neonodename:neonodename,neonodeid:neonodeid,level:1});
              }
              var crnodename1=crnodename.replace(/the|\sa\s|\s/gi, function myFunction(x){return "";});
              var neonodename1=neonodename.replace(/the|\sa\s|\s/gi, function myFunction(x){return "";});
              //if(crnodename1.match(/biosense/))
              //console.log("*************",crnodename1,"**************",neonodename1);
              if(crnodename1.toLowerCase()==neonodename1.toLowerCase())
              {
                var found = false;
                for(i=0;i<similarNodes.length;i++)
                {
                  if(similarNodes[i].neonodeid==neonodeid)
                  {
                    found = true;
                  }
                }
                if(!found)
                {
                  similarNodes.push({neonodename:neonodename,neonodeid:neonodeid,level:2});
                }
                else
                {
                  //console.log("skipped");
                }

              }

              var crnodename2=crnodename1.replace(/system|program|registry|survey|tool|data|dataset|standard|collaborative|element/gi, function myFunction(x){return "";});
              var neonodename2=neonodename1.replace(/system|program|registry|survey|tool|data|dataset|standard|collaborative|element/gi, function myFunction(x){return "";});
              //if(crnodename2.match(/biosense/))
              //console.log("***",crnodename2,"***",neonodename2);
              if(crnodename2.toLowerCase()==neonodename2.toLowerCase())
              {
                //console.log(crnodename2,neonodename2);
                var found = false;
                for(i=0;i<similarNodes.length;i++)
                {
                  if(similarNodes[i].neonodeid==neonodeid)
                  {
                    found = true;
                  }
                }
                if(!found)
                {
                  similarNodes.push({neonodename:neonodename,neonodeid:neonodeid,level:2});
                }
                else
                {
                  //console.log("skipped");
                }

              }
            }

          }

        }

        var similarNodesString="Similar to: ";
        for(i=0;i<similarNodes.length;i++)
        {
          similarNodesString=similarNodesString+", "+similarNodes[i].neonodename+" ("+similarNodes[i].neonodeid+")";
        }
        if(similarNodesString=="Similar to: ")
        {
          similarNodesString="Similar to none";
        }
        //console.log(similarNodesString);
        similarNodesString=similarNodesString.replace("Similar to: , ","Similar to: ");
        $scope.mongoDocumentsAll[cr].similarities=similarNodesString;
      }
   }

    $scope.deleteCR = function(id){
        //console.log(id);
        mongoid={mongoid:id};
        mongoid.adminUserId = $scope.identity.currentUser._id;
        mongoid.adminUserDisplayName = $scope.identity.currentUser.displayName;

        $http.post('/apollo/api/mongo/deletecr', mongoid).
        //$http({method: 'Post', url: '/apollo/api/mongo/postcr', data: {greeting: 'hi'}}).
          success(function(data, status, headers, config) {
              if(checkcounter==2)
              {
                checkcounter--;
              }
                $scope.init();
          }).error(function(data, status) {

        });

    };

}]);

angular.module('apolloApp').controller('ModalInstanceCtrl', function ($scope, $modalInstance,doc_id) {

  // $scope.items = items;
  // $scope.selected = {
  //   item: $scope.items[0]
  // };
  //console.log(doc_id);
  $scope.ok = function () {
    //$modalInstance.close('ok');
    $scope.$close(doc_id);
  };

  $scope.cancel = function () {
    //$modalInstance.dismiss('cancel');
    $scope.$dismiss();
  };
});

<commit_msg>remove console logs<commit_after>angular.module('apolloApp').controller('adminCRQueueCtrl', ['$scope','$modal','$location','$http','nodeAttributeDictionary','ngIdentity',
	function($scope,$modal,$location, $http,nodeAttributeDictionary,ngIdentity) {

    var checkcounter=0;
    var cacheRenew=new Date().getTime();
    $http.get('/apollo/api/node/all'+'?'+cacheRenew).then(function(res) {
      $scope.nodeNameallArray=res.data;
      //console.log($scope.nodeNameallArray);
      checkcounter++;
      if(checkcounter==2)
      {
        getSimilarities();
      }
    });

    $scope.open = function (docid) {

        var modalInstance = $modal.open({
          templateUrl: 'myModalContent.html',
          controller: 'ModalInstanceCtrl',
          size: 'sm',
          resolve: {
            doc_id: function () {
              return docid;
            }
          }
        });

        modalInstance.result.then(function (docid) {
            $scope.deleteCR(docid);
        }, function () {
          //$log.info('Modal dismissed at: ' + new Date());
          //console.log('Modal dismissed at: ' + new Date(),$scope.selected);
        });
    };

    $scope.crStatusModel='PENDING';
    //console.log("test");
    $scope.userFilter="";
    $scope.usersu=false;

    // var location = $location.path();
    // console.log(location);

     $scope.isActive = function(route) {
        return route === $location.path();
    }

    $scope.init=function()
    {

        if($scope.identity.currentUser.roles.levelTwo)
        {
            $scope.usersu=true;
            //$scope.userFilter="";
        }
        else
        {
            $scope.usersu=false;
            //$scope.userFilter=$scope.identity.currentUser.displayName;
        }

        $scope.mongoDocumentsAll=[];
        $scope.crtSelect="";
        $scope.crtOpen=false;
        $scope.crFilterModel='';

        $scope.sortval="CR_DATE_CREATED";

        $scope.crAddCount=0;
        $scope.crDeleteCount=0;
        $scope.crUpdateCount=0;
        $scope.hover=false;
        $scope.reverse = true;
        var cacheRenew=new Date().getTime();
        $http.get('/apollo/api/mongo/all'+'?'+cacheRenew).then(function(res) {
            $scope.mongoDocumentsAll=res.data;
            //console.log($scope.mongoDocumentsAll);

            for (var i=0;i<$scope.mongoDocumentsAll.length;i++)
            {
                //console.log($scope.mongoDocumentsAll[i].CR_REQUEST_TYPE);
                if($scope.mongoDocumentsAll[i].CR_REQUEST_TYPE=="ADD" && $scope.mongoDocumentsAll[i].CR_STATUS=="PENDING")
                {
                    $scope.crAddCount++;
                }
                else if($scope.mongoDocumentsAll[i].CR_REQUEST_TYPE=="DELETE" && $scope.mongoDocumentsAll[i].CR_STATUS=="PENDING")
                {
                    $scope.crDeleteCount++;
                }
                else if($scope.mongoDocumentsAll[i].CR_REQUEST_TYPE=="UPDATE" && $scope.mongoDocumentsAll[i].CR_STATUS=="PENDING")
                {
                    $scope.crUpdateCount++;
                }
            }

            // if(!$scope.$$phase) {
            //   $scope.$apply();
            // }
            checkcounter++;
            if(checkcounter==2)
            {
              getSimilarities();
            }

        });

        //$scope.crAddCount
    }

    $scope.init();

   var getSimilarities = function()
   {

      for(cr in $scope.mongoDocumentsAll)
      {

        var crnodename=$scope.mongoDocumentsAll[cr].name;
        var crnodeid=$scope.mongoDocumentsAll[cr].id;
        if(crnodeid==undefined || crnodeid==null || crnodeid=="")
        {
          crnodeid="TBD";
        }
        //console.log("******************",crnodename,"*******************");

        var similarNodes=[];
        //console.log($scope.nodeNameallArray);
        for(n in $scope.nodeNameallArray)
        {
          var neonodename=$scope.nodeNameallArray[n].name;

          var neonodeid=$scope.nodeNameallArray[n].id;
          if(neonodeid==crnodeid)
          {

          }
          else
          {
            if(neonodename != null){
              if(crnodename.toLowerCase()==neonodename.toLowerCase())
              {
                similarNodes.push({neonodename:neonodename,neonodeid:neonodeid,level:1});
              }
              var crnodename1=crnodename.replace(/the|\sa\s|\s/gi, function myFunction(x){return "";});
              var neonodename1=neonodename.replace(/the|\sa\s|\s/gi, function myFunction(x){return "";});
              //if(crnodename1.match(/biosense/))
              //console.log("*************",crnodename1,"**************",neonodename1);
              if(crnodename1.toLowerCase()==neonodename1.toLowerCase())
              {
                var found = false;
                for(i=0;i<similarNodes.length;i++)
                {
                  if(similarNodes[i].neonodeid==neonodeid)
                  {
                    found = true;
                  }
                }
                if(!found)
                {
                  similarNodes.push({neonodename:neonodename,neonodeid:neonodeid,level:2});
                }
                else
                {
                  //console.log("skipped");
                }

              }

              var crnodename2=crnodename1.replace(/system|program|registry|survey|tool|data|dataset|standard|collaborative|element/gi, function myFunction(x){return "";});
              var neonodename2=neonodename1.replace(/system|program|registry|survey|tool|data|dataset|standard|collaborative|element/gi, function myFunction(x){return "";});
              //if(crnodename2.match(/biosense/))
              //console.log("***",crnodename2,"***",neonodename2);
              if(crnodename2.toLowerCase()==neonodename2.toLowerCase())
              {
                //console.log(crnodename2,neonodename2);
                var found = false;
                for(i=0;i<similarNodes.length;i++)
                {
                  if(similarNodes[i].neonodeid==neonodeid)
                  {
                    found = true;
                  }
                }
                if(!found)
                {
                  similarNodes.push({neonodename:neonodename,neonodeid:neonodeid,level:2});
                }
                else
                {
                  //console.log("skipped");
                }

              }
            }

          }

        }

        var similarNodesString="Similar to: ";
        for(i=0;i<similarNodes.length;i++)
        {
          similarNodesString=similarNodesString+", "+similarNodes[i].neonodename+" ("+similarNodes[i].neonodeid+")";
        }
        if(similarNodesString=="Similar to: ")
        {
          similarNodesString="Similar to none";
        }
        //console.log(similarNodesString);
        similarNodesString=similarNodesString.replace("Similar to: , ","Similar to: ");
        $scope.mongoDocumentsAll[cr].similarities=similarNodesString;
      }
   }

    $scope.deleteCR = function(id){
        //console.log(id);
        mongoid={mongoid:id};
        mongoid.adminUserId = $scope.identity.currentUser._id;
        mongoid.adminUserDisplayName = $scope.identity.currentUser.displayName;

        $http.post('/apollo/api/mongo/deletecr', mongoid).
        //$http({method: 'Post', url: '/apollo/api/mongo/postcr', data: {greeting: 'hi'}}).
          success(function(data, status, headers, config) {
              if(checkcounter==2)
              {
                checkcounter--;
              }
                $scope.init();
          }).error(function(data, status) {

        });

    };

}]);

angular.module('apolloApp').controller('ModalInstanceCtrl', function ($scope, $modalInstance,doc_id) {

  // $scope.items = items;
  // $scope.selected = {
  //   item: $scope.items[0]
  // };
  //console.log(doc_id);
  $scope.ok = function () {
    //$modalInstance.close('ok');
    $scope.$close(doc_id);
  };

  $scope.cancel = function () {
    //$modalInstance.dismiss('cancel');
    $scope.$dismiss();
  };
});

<|endoftext|>


<commit_before>var commHandler = require('./../../DisplayPeerCommunicationHandler.js');
var abstractState = require('./AbstractState.js');
var wallBuilder2Player = require('./../2PlayerField.js');

var state = function (game) {
  abstractState.call(this, game);
  this.init = function () {
    console.log("InitializeNewGame");
  };
  this.preload = function () {
    // Don't pause game if the form looses focus
    this.game.stage.disableVisibilityChange = true;

    this.cleanup();
    this.game.properties.gameId = commHandler.init();
  };
  this.create = function () {
    this.game.state.start("Initial", false, false, wallBuilder2Player);
  };
  this.cleanup = function () {
    this.game.properties.ball = undefined;
    this.game.properties.players = new Map();
  };
};

state.prototype = Object.create(abstractState.prototype);
state.prototype.constructor = state;

module.exports = state;
<commit_msg>hotfix, avoid DisplayCommunicationHandler bug<commit_after>var commHandler = require('./../../DisplayPeerCommunicationHandler.js');
var abstractState = require('./AbstractState.js');
var wallBuilder2Player = require('./../2PlayerField.js');

var state = function (game) {
  abstractState.call(this, game);
  this.init = function () {
    console.log("InitializeNewGame");
  };
  this.preload = function () {
    // Don't pause game if the form looses focus
    this.game.stage.disableVisibilityChange = true;

    this.cleanup();
    //@TODO: GameId should be regenerated each game. The if(!this.game.properties.gameId) is just a hotfix, to avoid a bug.
    if(!this.game.properties.gameId){
      this.game.properties.gameId = commHandler.init();
    }
  };
  this.create = function () {
    this.game.state.start("Initial", false, false, wallBuilder2Player);
  };
  this.cleanup = function () {
    this.game.properties.ball = undefined;
    this.game.properties.players = new Map();
  };
};

state.prototype = Object.create(abstractState.prototype);
state.prototype.constructor = state;

module.exports = state;
<|endoftext|>


<commit_before>/* Custom filtering function which will search data in column four between two values */
$.fn.dataTable.ext.search.push(
    function( settings, searchData, index, rowData, counter ) {
        let table = $(settings.nTable).DataTable();
        let row = table.rows(index);
        let node = row.nodes().to$().first();
        return TableHelper.checkDataForNode(node);
    }
);

const TableHelper = {
    tables: {},
    checkedFilters: {},
    updateCheckedFilters: function(){
        this.checkedFilters = TableHelper.getCheckedFilters();
    },
    getBazarListeContainer: function (table){
        let tableNode = table.tables().nodes().to$();
        return $(tableNode).closest('.bazar-list');
    },
    findBazarListFiltersContainer: function (table){
        let bazarlistContainer = this.getBazarListeContainer(table);
        if (!$(bazarlistContainer).parent().hasClass('results-col')){
            return {length:0};
        } else {
            return $(bazarlistContainer).parent().siblings('.filters-col').find('.filters');
        }
    },
    updateNBResults: function (table){
        let filterContainer = this.findBazarListFiltersContainer(table);
        if (filterContainer.length > 0){
            let bazarlistContainer = this.getBazarListeContainer(table);
            let nbResults = bazarlistContainer.find('.bazar-entry:visible').length;
            let nbResultInfoNode = $(filterContainer).find('.nb-results');
            if (nbResultInfoNode.length > 0){
                $(nbResultInfoNode).html(nbResults);
                if (nbResults > 1) {
                    $(filterContainer).find('.result-label').hide();
                    $(filterContainer).find('.results-label').show();
                } else {
                    $(filterContainer).find('.result-label').show();
                    $(filterContainer).find('.results-label').hide();
                }
            }
        }
    },
    updateTables: function(){
        TableHelper.updateCheckedFilters();
        Object.keys(TableHelper.tables).forEach(key => {
            let table = TableHelper.tables[key];
            table.draw();
        });
    },
    sanitizeValue: function (val){
        return (isNaN(val)) ? 1 : Number(val) ;
    },
    updateFooter: function(index){
        let table = TableHelper.tables[index];
        if (typeof table !== "undefined"){
            let activatedRows = [];
            table.rows({search:'applied'}).every(function(){
                    activatedRows.push(this.index());
                });
            let activatedCols = [];
            table.columns( '.sum-activated' ).every( function () {
                activatedCols.push(this.index());
            });
            activatedCols.forEach(function(indexCol){
                var sum = 0;
                activatedRows.forEach(function(indexRow){
                    let value = table.row(indexRow).data()[indexCol];
                    sum = sum + TableHelper.sanitizeValue(value);
                });
                $(table.columns(indexCol).footer()).html(sum );
            });
        }
    },
    initTables: function (){
        TableHelper.updateCheckedFilters();
        $('.table.prevent-auto-init.in-tableau-template').each(function(){
            var index = Object.keys(TableHelper.tables).length;
            let buttons = [];
            DATATABLE_OPTIONS.buttons.forEach(function(option){
                buttons.push({
                    ...option,
                    ...{
                        footer:true
                    }
                });
            });
            let table = $(this).DataTable({
                ...DATATABLE_OPTIONS,
                ...{
                        "footerCallback": function ( row, data, start, end, display ) {
                            TableHelper.updateFooter(index);
                        },
                        buttons: buttons,
                    }
                }
            );
            TableHelper.tables[index] = table;
            table.on( 'draw', function () {
                TableHelper.updateNBResults(table);
            } );
            table.draw();
        });
    },
    init: function(){
        let helper = this;
        $('.filter-checkbox').on('click', function(){
            helper.updateTables();
        });
        this.initTables();
    },
    getCheckedFilters: function(){
        let inputs = $('.filter-checkbox:checked');
        if (inputs.length == 0){
            return {};
        } else {
            let res = {};
            for (let index = 0; index < inputs.length; index++) {
                let input = inputs[index];
                let name = $(input).attr('name');
                let value = $(input).attr('value');
                if (res.hasOwnProperty(name)){
                    res[name].push(value);
                } else {
                    res[name] = [value];
                }
            }
            return res;
        }
    },
    checkDataForNode: function(node){
        if(Object.keys(this.checkedFilters).length == 0){
            return true;
        } else {
            for (const name in this.checkedFilters) {
                if (this.checkedFilters[name].length == 0){
                    return true;
                } else {
                    let nodeValue = $(node).attr('data-'+name);
                    if (typeof nodeValue === "undefined" || nodeValue.length == 0) {
                        return false;
                    } else {
                        let values = nodeValue.split(",");

                        for (let index = 0; index < this.checkedFilters[name].length; index++) {
                            if (values.indexOf(this.checkedFilters[name][index]) > -1){
                                return true;
                            }
                        }
                        return false;
                    }
                }
            }
        }
    }
};
$(document).ready(function () {
    TableHelper.init();
});<commit_msg>feat(tableau.twig): allosw multiple tables in same page<commit_after>/* Custom filtering function which will search data in column four between two values */
$.fn.dataTable.ext.search.push(
    function( settings, searchData, index, rowData, counter ) {
        let table = $(settings.nTable).DataTable();
        let row = table.rows(index);
        let node = row.nodes().to$().first();
        return TableHelper.checkDataForNode(table,node);
    }
);

const TableHelper = {
    tables: {},
    tablesByIds: {},
    checkedFilters: {},
    updateCheckedFilters: function(){
        this.checkedFilters = TableHelper.getCheckedFilters();
    },
    getBazarListeContainer: function (table){
        let tableNode = table.tables().nodes().to$();
        return $(tableNode).closest('.bazar-list');
    },
    findBazarListFiltersContainer: function (table){
        let bazarlistContainer = this.getBazarListeContainer(table);
        if (!$(bazarlistContainer).parent().hasClass('results-col')){
            return {length:0};
        } else {
            return $(bazarlistContainer).parent().siblings('.filters-col').find('.filters');
        }
    },
    updateNBResults: function (table){
        let filterContainer = this.findBazarListFiltersContainer(table);
        if (filterContainer.length > 0){
            let bazarlistContainer = this.getBazarListeContainer(table);
            let nbResults = bazarlistContainer.find('.bazar-entry:visible').length;
            let nbResultInfoNode = $(filterContainer).find('.nb-results');
            if (nbResultInfoNode.length > 0){
                $(nbResultInfoNode).html(nbResults);
                if (nbResults > 1) {
                    $(filterContainer).find('.result-label').hide();
                    $(filterContainer).find('.results-label').show();
                } else {
                    $(filterContainer).find('.result-label').show();
                    $(filterContainer).find('.results-label').hide();
                }
            }
        }
    },
    updateTables: function(){
        TableHelper.updateCheckedFilters();
        Object.keys(TableHelper.tables).forEach(key => {
            let table = TableHelper.tables[key];
            table.draw();
        });
    },
    sanitizeValue: function (val){
        return (isNaN(val)) ? 1 : Number(val) ;
    },
    updateFooter: function(index){
        let table = TableHelper.tables[index];
        if (typeof table !== "undefined"){
            let activatedRows = [];
            table.rows({search:'applied'}).every(function(){
                    activatedRows.push(this.index());
                });
            let activatedCols = [];
            table.columns( '.sum-activated' ).every( function () {
                activatedCols.push(this.index());
            });
            activatedCols.forEach(function(indexCol){
                var sum = 0;
                activatedRows.forEach(function(indexRow){
                    let value = table.row(indexRow).data()[indexCol];
                    sum = sum + TableHelper.sanitizeValue(value);
                });
                $(table.columns(indexCol).footer()).html(sum );
            });
        }
    },
    initTables: function (){
        TableHelper.updateCheckedFilters();
        $('.table.prevent-auto-init.in-tableau-template').each(function(){
            var index = Object.keys(TableHelper.tables).length;
            let buttons = [];
            DATATABLE_OPTIONS.buttons.forEach(function(option){
                buttons.push({
                    ...option,
                    ...{
                        footer:true
                    }
                });
            });
            let table = $(this).DataTable({
                ...DATATABLE_OPTIONS,
                ...{
                        "footerCallback": function ( row, data, start, end, display ) {
                            TableHelper.updateFooter(index);
                        },
                        buttons: buttons,
                    }
                }
            );
            TableHelper.tables[index] = table;
            TableHelper.tablesByIds[$(table.table(0).node()).prop('id')] = index;
            table.on( 'draw', function () {
                TableHelper.updateNBResults(table);
            } );
            table.draw();
        });
    },
    init: function(){
        let helper = this;
        $('.filter-checkbox').on('click', function(){
            helper.updateTables();
        });
        this.initTables();
    },
    getCheckedFilters: function(){
        let res = {};
        Object.keys(TableHelper.tables).forEach(function(key){
            let table = TableHelper.tables[key];
            let filterContainer = TableHelper.findBazarListFiltersContainer(table);
            if (filterContainer.length == 0){
                res[key] = {};
            } else {
                let inputs = $(filterContainer).find('.filter-checkbox:checked');
                if (inputs.length == 0){
                    res[key] = {};
                } else {
                    let tableRes = {};
                    for (let index = 0; index < inputs.length; index++) {
                        let input = inputs[index];
                        let name = $(input).attr('name');
                        let value = $(input).attr('value');
                        if (tableRes.hasOwnProperty(name)){
                            tableRes[name].push(value);
                        } else {
                            tableRes[name] = [value];
                        }
                    }
                    res[key] = tableRes;
                }
            }
        });
        return res;
    },
    checkDataForNode: function(table,node){
        if(Object.keys(this.checkedFilters).length == 0){
            return true;
        } else {
            let tableId = $(table.table(0).node()).prop('id');
            if (tableId.length == 0 || !TableHelper.tablesByIds.hasOwnProperty(tableId)){
                return true;
            } else {
                let indexTable = TableHelper.tablesByIds[tableId];
                if (!TableHelper.checkedFilters.hasOwnProperty(indexTable)){
                    return true;
                } else {
                    let checkedFilters = TableHelper.checkedFilters[indexTable];
                    if(Object.keys(checkedFilters).length == 0){
                        return true;
                    } else {
                        for (const name in checkedFilters) {
                            if (checkedFilters[name].length == 0){
                                return true;
                            } else {
                                let nodeValue = $(node).attr('data-'+name);
                                if (typeof nodeValue === "undefined" || nodeValue.length == 0) {
                                    return false;
                                } else {
                                    let values = nodeValue.split(",");

                                    for (let index = 0; index < checkedFilters[name].length; index++) {
                                        if (values.indexOf(checkedFilters[name][index]) > -1){
                                            return true;
                                        }
                                    }
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
};
$(document).ready(function () {
    TableHelper.init();
});<|endoftext|>


<commit_before>'use strict'

const { join, resolve } = require('path')
const { app, ipcMain: ipc, powerSaveBlocker } = require('electron')
const { createWindow } = require('electron-window')
const { errors, helpers, ONE_AND_DONES } = require('./mocha')
const run = require('mocha/lib/cli/run')
const ansi = require('ansi-colors')
const symbols = require('log-symbols')

const whenReady = app.isReady()
  ? Promise.resove()
  : new Promise(resolve => { app.once('ready', () => resolve()) })

exports.command = run.command
exports.describe = 'Run tests with Electron-Mocha'

exports.builder = yargs => {
  run.builder(new Proxy(yargs, {
    get (obj, prop, proxy) {
      const original = obj[prop]

      return (typeof original !== 'function')
        ? original : (...args) => {
          let result

          switch (prop) {
            case 'check':
              result = obj
              break
            default:
              result = original.apply(obj, args)
          }

          return (result === obj) ? proxy : result
        }
    }
  }))

  return yargs
    .default('exit', true)
    .default('extension', [])
    .default('file', [])
    .default('ignore', [])
    .default('spec', ['test'])
    .options({
      renderer: {
        describe: 'Run tests in renderer process',
        group: 'Electron'
      },
      'require-main': {
        alias: 'main',
        describe: 'Require module in main process',
        group: 'Electron',
        requiresArg: true
      },
      script: {
        alias: 'preload',
        describe: 'Load module in renderer via script tag',
        group: 'Electron',
        implies: 'renderer',
        requiresArg: true
      },
      interactive: {
        describe: 'Show renderer tests in persistent window',
        group: 'Electron',
        implies: 'renderer'
      },
      inspect: {
        alias: ['inspect-brk', 'inspect-port', 'debug'],
        defaultDescription: '5858',
        describe: 'Enable debugger on [port]',
        group: 'Electron',
        hidden: true
      }
    })
    .check(argv => {
      // Mocha Checks
      // See: mocha/lib/cli/run.js

      // "one-and-dones"; let yargs handle help and version
      Object.keys(ONE_AND_DONES).forEach(opt => {
        if (argv[opt]) {
          ONE_AND_DONES[opt].call(null, yargs)
          app.exit()
        }
      })

      // yargs.implies() isn't flexible enough to handle this
      if (argv.invert && !('fgrep' in argv || 'grep' in argv)) {
        throw errors.createMissingArgumentError(
          '"--invert" requires one of "--fgrep <str>" or "--grep <regexp>"',
          '--fgrep|--grep',
          'string|regexp'
        )
      }

      if (argv.compilers) {
        throw errors.createUnsupportedError(
          `--compilers is DEPRECATED and no longer supported.
          Use --require instead.`
        )
      }

      // Additional Electron-Mocha Checks
      if (argv._[0] === 'debug' || argv.interactive) {
        argv.inspect = true
      }

      if (argv.script) {
        argv.script = argv.script.map(script => resolve(script))
      }

      helpers.handleRequires(argv['require-main'])

      return true
    })
}

exports.handler = argv => {
  whenReady
    .then(() => {
      powerSaveBlocker.start('prevent-app-suspension')

      if (process.platform === 'darwin') {
        if (!(argv.inspect && argv.renderer)) {
          app.dock.hide()
        }
      }

      let code = 0

      process.on('SIGINT', () => app.exit(code))
      process.on('SIGTERM', () => app.exit(code))

      if (!argv.renderer) {
        helpers.runMocha(argv, count => {
          code = Math.min(count, 255)
          if (!argv.watch) {
            app.exit(code)
          }
        })
      } else {
        const win = createWindow({
          height: 700,
          width: 1200,
          focusable: argv.inspect,
          webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            webSecurity: false
          }
        })

        win.webContents.on('destroyed', () => app.exit(code))

        ipc.on('mocha-done', (event, count) => {
          code = Math.min(count, 255)
          if (!(argv.interactive || argv.watch)) {
            win.close()
          }
        })

        ipc.on('mocha-error', (_, error) => fail(error, argv['full-trace']))
        ipc.on('mocha-warn', (_, warning) => warn(warning))

        // Undocumented call in electron-window
        win._loadURLWithArgs(
          join(__dirname, '../renderer/index.html'),
          argv,
          () => {
            if (argv.inspect) {
              win.show()
              win.webContents.openDevTools()
              win.webContents.on('devtools-opened', () => {
                // Debugger is not immediately ready!
                setTimeout(() => {
                  win.webContents.send('mocha-start')
                }, 250)
              })

              // Called on reload in --interactive mode
              ipc.on('mocha-ready-to-run', () => {
                win.webContents.send('mocha-start')
              })
            } else {
              win.webContents.send('mocha-start')
            }
          })
      }
    })
    .catch(fail)
}

const fail = (error, trace) => {
  console.error(`\n${symbols.error} ${ansi.red('ERROR:')} ${error.message}`)
  if (trace && error.stack) console.error(error.stack)
  app.exit(1)
}

const warn = warning => {
  console.warn(ansi.yellow(`Warning: ${warning.message}`))
}
<commit_msg>Fix double exit on error<commit_after>'use strict'

const { join, resolve } = require('path')
const { app, ipcMain: ipc, powerSaveBlocker } = require('electron')
const { createWindow } = require('electron-window')
const { errors, helpers, ONE_AND_DONES } = require('./mocha')
const run = require('mocha/lib/cli/run')
const ansi = require('ansi-colors')
const symbols = require('log-symbols')

const whenReady = app.isReady()
  ? Promise.resove()
  : new Promise(resolve => { app.once('ready', () => resolve()) })

exports.command = run.command
exports.describe = 'Run tests with Electron-Mocha'

exports.builder = yargs => {
  run.builder(new Proxy(yargs, {
    get (obj, prop, proxy) {
      const original = obj[prop]

      return (typeof original !== 'function')
        ? original : (...args) => {
          let result

          switch (prop) {
            case 'check':
              result = obj
              break
            default:
              result = original.apply(obj, args)
          }

          return (result === obj) ? proxy : result
        }
    }
  }))

  return yargs
    .default('exit', true)
    .default('extension', [])
    .default('file', [])
    .default('ignore', [])
    .default('spec', ['test'])
    .options({
      renderer: {
        describe: 'Run tests in renderer process',
        group: 'Electron'
      },
      'require-main': {
        alias: 'main',
        describe: 'Require module in main process',
        group: 'Electron',
        requiresArg: true
      },
      script: {
        alias: 'preload',
        describe: 'Load module in renderer via script tag',
        group: 'Electron',
        implies: 'renderer',
        requiresArg: true
      },
      interactive: {
        describe: 'Show renderer tests in persistent window',
        group: 'Electron',
        implies: 'renderer'
      },
      inspect: {
        alias: ['inspect-brk', 'inspect-port', 'debug'],
        defaultDescription: '5858',
        describe: 'Enable debugger on [port]',
        group: 'Electron',
        hidden: true
      }
    })
    .check(argv => {
      // Mocha Checks
      // See: mocha/lib/cli/run.js

      // "one-and-dones"; let yargs handle help and version
      Object.keys(ONE_AND_DONES).forEach(opt => {
        if (argv[opt]) {
          ONE_AND_DONES[opt].call(null, yargs)
          app.exit()
        }
      })

      // yargs.implies() isn't flexible enough to handle this
      if (argv.invert && !('fgrep' in argv || 'grep' in argv)) {
        throw errors.createMissingArgumentError(
          '"--invert" requires one of "--fgrep <str>" or "--grep <regexp>"',
          '--fgrep|--grep',
          'string|regexp'
        )
      }

      if (argv.compilers) {
        throw errors.createUnsupportedError(
          `--compilers is DEPRECATED and no longer supported.
          Use --require instead.`
        )
      }

      // Additional Electron-Mocha Checks
      if (argv._[0] === 'debug' || argv.interactive) {
        argv.inspect = true
      }

      if (argv.script) {
        argv.script = argv.script.map(script => resolve(script))
      }

      helpers.handleRequires(argv['require-main'])

      return true
    })
}

exports.handler = argv => {
  whenReady
    .then(() => {
      powerSaveBlocker.start('prevent-app-suspension')

      if (process.platform === 'darwin') {
        if (!(argv.inspect && argv.renderer)) {
          app.dock.hide()
        }
      }

      let code = 0

      process.on('SIGINT', () => app.exit(code))
      process.on('SIGTERM', () => app.exit(code))

      if (!argv.renderer) {
        helpers.runMocha(argv, count => {
          code = Math.min(count, 255)
          if (!argv.watch) {
            app.exit(code)
          }
        })
      } else {
        const win = createWindow({
          height: 700,
          width: 1200,
          focusable: argv.inspect,
          webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            webSecurity: false
          }
        })

        win.webContents.on('destroyed', () => app.exit(code))

        ipc.on('mocha-done', (event, count) => {
          code = Math.min(count, 255)
          if (!(argv.interactive || argv.watch)) {
            win.close()
          }
        })

        ipc.on('mocha-error', (_, error) => {
          win.webContents.removeAllListeners('destroyed')
          fail(error, argv['full-trace'])
        })
        ipc.on('mocha-warn', (_, warning) => warn(warning))

        // Undocumented call in electron-window
        win._loadURLWithArgs(
          join(__dirname, '../renderer/index.html'),
          argv,
          () => {
            if (argv.inspect) {
              win.show()
              win.webContents.openDevTools()
              win.webContents.on('devtools-opened', () => {
                // Debugger is not immediately ready!
                setTimeout(() => {
                  win.webContents.send('mocha-start')
                }, 250)
              })

              // Called on reload in --interactive mode
              ipc.on('mocha-ready-to-run', () => {
                win.webContents.send('mocha-start')
              })
            } else {
              win.webContents.send('mocha-start')
            }
          })
      }
    })
    .catch(fail)
}

const fail = (error, trace) => {
  console.error(`\n${symbols.error} ${ansi.red('ERROR:')} ${error.message}`)
  if (trace && error.stack) console.error(error.stack)
  app.exit(1)
}

const warn = warning => {
  console.warn(ansi.yellow(`Warning: ${warning.message}`))
}
<|endoftext|>


<commit_before>'use strict'

const EE = require('events').EventEmitter
const URL = require('url')
const Histogram = require('native-hdr-histogram')
const timestring = require('timestring')
const Client = require('./httpClient')
const xtend = require('xtend')
const histUtil = require('hdr-histogram-percentiles-obj')
const histAsObj = histUtil.histAsObj
const addPercentiles = histUtil.addPercentiles

const defaultOptions = {
  headers: {},
  body: new Buffer(0),
  method: 'GET',
  duration: 10,
  connections: 10,
  pipelining: 1,
  timeout: 10,
  maxConnectionRequests: 0,
  maxOverallRequests: 0,
  connectionRate: 0,
  overallRate: 0,
  amount: 0,
  reconnectRate: 0,
  requests: [{}]
}

function run (opts, cb) {
  cb = cb || noop

  const tracker = new EE()

  const latencies = new Histogram(1, 10000, 5)
  const requests = new Histogram(1, 1000000, 3)
  const throughput = new Histogram(1, 1000000000, 1)
  const statusCodes = [
    0, // 1xx
    0, // 2xx
    0, // 3xx
    0, // 4xx
    0  // 5xx
  ]

  opts = xtend(defaultOptions, opts)

  // do error checking, if error, return
  if (checkOptsForErrors()) return

  // set tracker.opts here, so throwing over invalid opts and setting defaults etc.
  // is done
  tracker.opts = opts

  if (opts.url.indexOf('http') !== 0) opts.url = 'http://' + opts.url
  const url = URL.parse(opts.url)

  let counter = 0
  let bytes = 0
  let errors = 0
  let timeouts = 0
  let totalBytes = 0
  let totalRequests = 0
  let totalCompletedRequests = 0
  let amount = opts.amount
  let stop = false
  let numRunning = opts.connections
  let startTime = Date.now()

  // copy over fields so that the client
  // performs the right HTTP requests
  url.pipelining = opts.pipelining
  url.method = opts.method
  url.body = opts.body
  url.headers = opts.headers
  url.setupClient = opts.setupClient
  url.timeout = opts.timeout
  url.requests = opts.requests
  url.reconnectRate = opts.reconnectRate
  url.responseMax = amount || opts.maxConnectionRequests || opts.maxOverallRequests
  url.rate = opts.connectionRate || opts.overallRate

  let clients = []
  for (let i = 0; i < opts.connections; i++) {
    if (!amount && !opts.maxConnectionRequests && opts.maxOverallRequests) {
      url.responseMax = distributeNums(opts.maxOverallRequests, i)
    }
    if (amount) {
      url.responseMax = distributeNums(amount, i)
    }
    if (!opts.connectionRate && opts.overallRate) {
      url.rate = distributeNums(opts.overallRate, i)
    }

    let client = new Client(url)
    client.on('response', onResponse)
    client.on('connError', onError)
    client.on('timeout', onTimeout)
    client.on('request', () => { totalRequests++ })
    client.on('done', onDone)
    clients.push(client)

    // we will miss the initial request emits because the client emits request on construction
    totalRequests += url.pipelining < url.rate ? url.rate : url.pipelining
  }

  function distributeNums (x, i) {
    return (Math.floor(x / opts.connections) + (((i + 1) <= (x % opts.connections)) ? 1 : 0))
  }

  function onResponse (statusCode, resBytes, responseTime) {
    tracker.emit('response', this, statusCode, resBytes, responseTime)
    const codeIndex = Math.floor(parseInt(statusCode) / 100) - 1
    statusCodes[codeIndex] += 1
    // only record 2xx latencies
    if (codeIndex === 1) latencies.record(responseTime)
    bytes += resBytes
    counter++
  }

  function onError () {
    for (let i = 0; i < opts.pipelining; i++) tracker.emit('reqError')
    errors++
    if (opts.bailout && errors >= opts.bailout) tracker.stop()
  }

  // treat a timeout as a special type of error
  function onTimeout () {
    for (let i = 0; i < opts.pipelining; i++) tracker.emit('reqError')
    errors++
    timeouts++
    if (opts.bailout && errors >= opts.bailout) tracker.stop()
  }

  function onDone () {
    if (!--numRunning) {
      tracker.stop()
    }
  }

  if (!amount) {
    var stopTimer = setTimeout(() => {
      stop = true
    }, opts.duration * 1000)
  }

  tracker.stop = () => {
    if (stopTimer) clearTimeout(stopTimer)
    stop = true
  }

  const interval = setInterval(() => {
    totalBytes += bytes
    totalCompletedRequests += counter
    requests.record(counter)
    throughput.record(bytes)
    counter = 0
    bytes = 0
    tracker.emit('tick')

    if (stop) {
      clearInterval(interval)
      clients.forEach((client) => client.destroy())
      let result = {
        title: opts.title,
        url: opts.url,
        requests: histAsObj(requests, totalCompletedRequests),
        latency: addPercentiles(latencies, histAsObj(latencies)),
        throughput: histAsObj(throughput, totalBytes),
        errors: errors,
        timeouts: timeouts,
        duration: Math.round((Date.now() - startTime) / 1000),
        start: new Date(startTime),
        finish: new Date(),
        connections: opts.connections,
        pipelining: opts.pipelining,
        'non2xx': statusCodes[0] + statusCodes[2] + statusCodes[3] + statusCodes[4]
      }
      result.requests.sent = totalRequests
      statusCodes.forEach((code, index) => { result[(index + 1) + 'xx'] = code })
      tracker.emit('done', result)

      cb(null, result)
    }
  }, 1000)

  // will return true if error with opts entered
  function checkOptsForErrors () {
    if (!opts.url) {
      cb(new Error('url option required'))
      return true
    }

    if (typeof opts.duration !== 'number') {
      if (/[a-zA-Z]/.exec(opts.duration)) opts.duration = timestring(opts.duration)
      else opts.duration = Number(opts.duration.trim())
    }

    if (typeof opts.duration === 'number') {
      if (lessThanZeroError(opts.duration, 'duration')) return true
    } else {
      cb(new Error('duration entered was in an invalid format'))
      return true
    }

    if (lessThanOneError(opts.connections, 'connections')) return true
    if (lessThanOneError(opts.pipelining, 'pipelining factor')) return true
    if (greaterThanZeroError(opts.timeout, 'timeout')) return true
    if (opts.bailout && lessThanOneError(opts.bailout, 'bailout threshold')) return true
    if (opts.connectionRate && lessThanOneError(opts.connectionRate, 'connectionRate')) return true
    if (opts.overallRate && lessThanOneError(opts.overallRate, 'bailout overallRate')) return true
    if (opts.amount && lessThanOneError(opts.amount, 'amount')) return true
    if (opts.maxConnectionRequests && lessThanOneError(opts.maxConnectionRequests, 'maxConnectionRequests')) return true
    if (opts.maxOverallRequests && lessThanOneError(opts.maxOverallRequests, 'maxOverallRequests')) return true

    function lessThanZeroError (x, label) {
      if (x < 0) {
        cb(new Error(`${label} can not be less than 0`))
        return true
      }
      return false
    }

    function lessThanOneError (x, label) {
      if (x < 1) {
        cb(new Error(`${label} can not be less than 1`))
        return true
      }
      return false
    }

    function greaterThanZeroError (x, label) {
      if (x <= 0) {
        cb(new Error(`${label} must be greater than 0`))
        return true
      }
      return false
    }

    return false
  } // checkOptsForErrors

  return tracker
} // run

function noop () {}

module.exports = run
<commit_msg>Correctly handle duration if it is a boolean.<commit_after>'use strict'

const EE = require('events').EventEmitter
const URL = require('url')
const Histogram = require('native-hdr-histogram')
const timestring = require('timestring')
const Client = require('./httpClient')
const xtend = require('xtend')
const histUtil = require('hdr-histogram-percentiles-obj')
const histAsObj = histUtil.histAsObj
const addPercentiles = histUtil.addPercentiles

const defaultOptions = {
  headers: {},
  body: new Buffer(0),
  method: 'GET',
  duration: 10,
  connections: 10,
  pipelining: 1,
  timeout: 10,
  maxConnectionRequests: 0,
  maxOverallRequests: 0,
  connectionRate: 0,
  overallRate: 0,
  amount: 0,
  reconnectRate: 0,
  requests: [{}]
}

function run (opts, cb) {
  cb = cb || noop

  const tracker = new EE()

  const latencies = new Histogram(1, 10000, 5)
  const requests = new Histogram(1, 1000000, 3)
  const throughput = new Histogram(1, 1000000000, 1)
  const statusCodes = [
    0, // 1xx
    0, // 2xx
    0, // 3xx
    0, // 4xx
    0  // 5xx
  ]

  opts = xtend(defaultOptions, opts)

  // do error checking, if error, return
  if (checkOptsForErrors()) return

  // set tracker.opts here, so throwing over invalid opts and setting defaults etc.
  // is done
  tracker.opts = opts

  if (opts.url.indexOf('http') !== 0) opts.url = 'http://' + opts.url
  const url = URL.parse(opts.url)

  let counter = 0
  let bytes = 0
  let errors = 0
  let timeouts = 0
  let totalBytes = 0
  let totalRequests = 0
  let totalCompletedRequests = 0
  let amount = opts.amount
  let stop = false
  let numRunning = opts.connections
  let startTime = Date.now()

  // copy over fields so that the client
  // performs the right HTTP requests
  url.pipelining = opts.pipelining
  url.method = opts.method
  url.body = opts.body
  url.headers = opts.headers
  url.setupClient = opts.setupClient
  url.timeout = opts.timeout
  url.requests = opts.requests
  url.reconnectRate = opts.reconnectRate
  url.responseMax = amount || opts.maxConnectionRequests || opts.maxOverallRequests
  url.rate = opts.connectionRate || opts.overallRate

  let clients = []
  for (let i = 0; i < opts.connections; i++) {
    if (!amount && !opts.maxConnectionRequests && opts.maxOverallRequests) {
      url.responseMax = distributeNums(opts.maxOverallRequests, i)
    }
    if (amount) {
      url.responseMax = distributeNums(amount, i)
    }
    if (!opts.connectionRate && opts.overallRate) {
      url.rate = distributeNums(opts.overallRate, i)
    }

    let client = new Client(url)
    client.on('response', onResponse)
    client.on('connError', onError)
    client.on('timeout', onTimeout)
    client.on('request', () => { totalRequests++ })
    client.on('done', onDone)
    clients.push(client)

    // we will miss the initial request emits because the client emits request on construction
    totalRequests += url.pipelining < url.rate ? url.rate : url.pipelining
  }

  function distributeNums (x, i) {
    return (Math.floor(x / opts.connections) + (((i + 1) <= (x % opts.connections)) ? 1 : 0))
  }

  function onResponse (statusCode, resBytes, responseTime) {
    tracker.emit('response', this, statusCode, resBytes, responseTime)
    const codeIndex = Math.floor(parseInt(statusCode) / 100) - 1
    statusCodes[codeIndex] += 1
    // only record 2xx latencies
    if (codeIndex === 1) latencies.record(responseTime)
    bytes += resBytes
    counter++
  }

  function onError () {
    for (let i = 0; i < opts.pipelining; i++) tracker.emit('reqError')
    errors++
    if (opts.bailout && errors >= opts.bailout) tracker.stop()
  }

  // treat a timeout as a special type of error
  function onTimeout () {
    for (let i = 0; i < opts.pipelining; i++) tracker.emit('reqError')
    errors++
    timeouts++
    if (opts.bailout && errors >= opts.bailout) tracker.stop()
  }

  function onDone () {
    if (!--numRunning) {
      tracker.stop()
    }
  }

  if (!amount) {
    var stopTimer = setTimeout(() => {
      stop = true
    }, opts.duration * 1000)
  }

  tracker.stop = () => {
    if (stopTimer) clearTimeout(stopTimer)
    stop = true
  }

  const interval = setInterval(() => {
    totalBytes += bytes
    totalCompletedRequests += counter
    requests.record(counter)
    throughput.record(bytes)
    counter = 0
    bytes = 0
    tracker.emit('tick')

    if (stop) {
      clearInterval(interval)
      clients.forEach((client) => client.destroy())
      let result = {
        title: opts.title,
        url: opts.url,
        requests: histAsObj(requests, totalCompletedRequests),
        latency: addPercentiles(latencies, histAsObj(latencies)),
        throughput: histAsObj(throughput, totalBytes),
        errors: errors,
        timeouts: timeouts,
        duration: Math.round((Date.now() - startTime) / 1000),
        start: new Date(startTime),
        finish: new Date(),
        connections: opts.connections,
        pipelining: opts.pipelining,
        'non2xx': statusCodes[0] + statusCodes[2] + statusCodes[3] + statusCodes[4]
      }
      result.requests.sent = totalRequests
      statusCodes.forEach((code, index) => { result[(index + 1) + 'xx'] = code })
      tracker.emit('done', result)

      cb(null, result)
    }
  }, 1000)

  // will return true if error with opts entered
  function checkOptsForErrors () {
    if (!opts.url) {
      cb(new Error('url option required'))
      return true
    }

    if (typeof opts.duration === 'string') {
      if (/[a-zA-Z]/.exec(opts.duration)) opts.duration = timestring(opts.duration)
      else opts.duration = Number(opts.duration.trim())
    }

    if (typeof opts.duration === 'number') {
      if (lessThanZeroError(opts.duration, 'duration')) return true
    } else {
      cb(new Error('duration entered was in an invalid format'))
      return true
    }

    if (lessThanOneError(opts.connections, 'connections')) return true
    if (lessThanOneError(opts.pipelining, 'pipelining factor')) return true
    if (greaterThanZeroError(opts.timeout, 'timeout')) return true
    if (opts.bailout && lessThanOneError(opts.bailout, 'bailout threshold')) return true
    if (opts.connectionRate && lessThanOneError(opts.connectionRate, 'connectionRate')) return true
    if (opts.overallRate && lessThanOneError(opts.overallRate, 'bailout overallRate')) return true
    if (opts.amount && lessThanOneError(opts.amount, 'amount')) return true
    if (opts.maxConnectionRequests && lessThanOneError(opts.maxConnectionRequests, 'maxConnectionRequests')) return true
    if (opts.maxOverallRequests && lessThanOneError(opts.maxOverallRequests, 'maxOverallRequests')) return true

    function lessThanZeroError (x, label) {
      if (x < 0) {
        cb(new Error(`${label} can not be less than 0`))
        return true
      }
      return false
    }

    function lessThanOneError (x, label) {
      if (x < 1) {
        cb(new Error(`${label} can not be less than 1`))
        return true
      }
      return false
    }

    function greaterThanZeroError (x, label) {
      if (x <= 0) {
        cb(new Error(`${label} must be greater than 0`))
        return true
      }
      return false
    }

    return false
  } // checkOptsForErrors

  return tracker
} // run

function noop () {}

module.exports = run
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2020 3D Repo Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

const path = require('path');
const logger = require('../lib/logger');
const { config, configPath } = require('../lib/config');
const run = require('../lib/runCommand');
const { BOUNCER_SOFT_FAILS } = require('../constants/errorCodes');

const bouncerClientPath = path.normalize(config.bouncer.path);

const setBouncerEnvars = (logDir) => {
	if (config.bouncer.envars) {
		Object.keys(config.bouncer.envars).forEach((key) => {
			process.env[key] = config.bouncer.envars[key];
		});
	}

	if (logDir) {
		process.env.REPO_LOG_DIR = logDir;
	}

	if (config.repoLicense) {
		process.env.REPO_LICENSE = config.repoLicense;
		process.env.REPO_INSTANCE_ID = config.instanceId;
	}
};

const BouncerHandler = {};

BouncerHandler.testClient = async () => {
	const logLabel = { label: 'INIT' };
	logger.info('Checking status of client...', logLabel);

	setBouncerEnvars();

	const cmdParams = [
		configPath,
		'test',
	];

	try {
		await run(bouncerClientPath, cmdParams, { logLabel });
		logger.info('Bouncer call passed', logLabel);
	} catch (code) {
		logger.error(`Bouncer call errored (Error code: ${code})`, logLabel);
		throw code;
	}
};

BouncerHandler.runBouncerCommand = async (
	logDir,
	cmdParams,
	processInformation,
) => {
	setBouncerEnvars(logDir);
	return run(bouncerClientPath, cmdParams, { codesAsSuccess: BOUNCER_SOFT_FAILS, logLabel: { label: 'BOUNCER' } }, processInformation);
};

BouncerHandler.generateTreeStash = async (logDir, database, modelId, stashType, rev = 'all') => {
	const cmd = [configPath, 'genStash', database, modelId, stashType, rev];
	return BouncerHandler.runBouncerCommand(logDir, cmd);
};

module.exports = BouncerHandler;
<commit_msg>ISSUE #519 log out machine id<commit_after>/**
 * Copyright (C) 2020 3D Repo Ltd
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

const path = require('path');
const logger = require('../lib/logger');
const { config, configPath } = require('../lib/config');
const run = require('../lib/runCommand');
const { BOUNCER_SOFT_FAILS } = require('../constants/errorCodes');

const bouncerClientPath = path.normalize(config.bouncer.path);

const setBouncerEnvars = (logDir) => {
	if (config.bouncer.envars) {
		Object.keys(config.bouncer.envars).forEach((key) => {
			process.env[key] = config.bouncer.envars[key];
		});
	}

	if (logDir) {
		process.env.REPO_LOG_DIR = logDir;
	}

	if (config.repoLicense) {
		process.env.REPO_LICENSE = config.repoLicense;
		process.env.REPO_INSTANCE_ID = config.instanceId;
	}
};

const BouncerHandler = {};

BouncerHandler.testClient = async () => {
	const logLabel = { label: 'INIT' };
	logger.info('Checking status of client...', logLabel);
	if (config.repoLicense) {
		logger.info(`Machine Instance ID is set to ${config.instanceId}`);
	}

	setBouncerEnvars();

	const cmdParams = [
		configPath,
		'test',
	];

	try {
		await run(bouncerClientPath, cmdParams, { logLabel });
		logger.info('Bouncer call passed', logLabel);
	} catch (code) {
		logger.error(`Bouncer call errored (Error code: ${code})`, logLabel);
		throw code;
	}
};

BouncerHandler.runBouncerCommand = async (
	logDir,
	cmdParams,
	processInformation,
) => {
	setBouncerEnvars(logDir);
	return run(bouncerClientPath, cmdParams, { codesAsSuccess: BOUNCER_SOFT_FAILS, logLabel: { label: 'BOUNCER' } }, processInformation);
};

BouncerHandler.generateTreeStash = async (logDir, database, modelId, stashType, rev = 'all') => {
	const cmd = [configPath, 'genStash', database, modelId, stashType, rev];
	return BouncerHandler.runBouncerCommand(logDir, cmd);
};

module.exports = BouncerHandler;
<|endoftext|>


<commit_before>// Runs tests

"use strict";

var isError      = require("es5-ext/error/is-error")
  , isFunction   = require("es5-ext/function/is-function")
  , noop         = require("es5-ext/function/noop")
  , toArray      = require("es5-ext/object/to-array")
  , hforEach     = require("es5-ext/object/for-each")
  , isValue      = require("es5-ext/object/is-value")
  , deferred     = require("deferred")
  , createLogger = require("./logger")
  , createAssert = require("./assert");

var nextTick = process.nextTick
  , pattern = /^\s*function\s*\(\s*([tad])(?:\s*,\s*([tad]))?\s*\)/
  , run;

run = function self(testee, tests, assert, logger) {
	if (isFunction(tests)) {
		tests = { "": tests };
	}

	hforEach(tests, function (t) {
		var conf, match;
		if (isFunction(t)) {
			conf = t.conf = { t: true, a: true, d: false };
			if (t.length > 2) {
				conf.d = true;
			} else if ((match = t.toString().match(pattern))) {
				conf.t = conf.a = false;
				conf[match[1]] = true;
				if (match[2]) {
					conf[match[2]] = true;
				}
			}
		}
	});

	return deferred.reduce(
		toArray(tests),
		// eslint-disable-next-line max-statements
		function (ignore, data) {
			var testResult, d, finish, done, name, testFunction;
			name = data[0];
			testFunction = data[1];
			d = deferred();
			finish = function () {
				logger.out(true);
				d.resolve();
			};
			logger.in(name, true);
			if (isFunction(testFunction)) {
				try {
					if (testFunction.conf.d) {
						done = function (asyncTestResult) {
							if (asyncTestResult) {
								if (isError(asyncTestResult)) {
									assert.fail(asyncTestResult);
									finish();
								} else {
									self(testee, asyncTestResult, assert, logger)(finish).done();
								}
							} else {
								finish();
							}
						};
						if (testFunction.conf.t) {
							// eslint-disable-next-line max-depth
							if (testFunction.conf.a) {
								testFunction(testee, assert, done);
							} else {
								testFunction(testee, done);
							}
						} else if (testFunction.conf.a) {
							testFunction(assert, done);
						} else {
							testFunction(done);
						}
					} else {
						if (testFunction.conf.t) {
							testResult = testFunction(testee, assert);
						} else {
							testResult = testFunction(assert);
						}
						if (testResult) {
							self(testee, testResult, assert, logger)(finish).done();
						} else {
							finish();
						}
					}
				} catch (e) {
					logger.error(e);
					finish();
				}
			} else if (isValue(testFunction)) {
				self(testee, testFunction, assert, logger)(finish).done();
			} else {
				assert.fail(new Error("No tests found at '" + name + "' property"));
				finish();
			}
			return d.promise;
		},
		null
	)(noop);
};

module.exports = function (testee, test, assert, logger) {
	var runResult;
	logger = logger || createLogger();
	assert = assert || createAssert(logger);
	nextTick(function () {
		runResult = run(testee, test, assert, logger);
		if (logger.end) {
			runResult = runResult(logger.end.bind(logger));
		}
		runResult.done();
	});
	return logger;
};
<commit_msg>style: Do not apply max-lines to old code<commit_after>/* eslint max-lines: "off" */

// Runs tests

"use strict";

var isError      = require("es5-ext/error/is-error")
  , isFunction   = require("es5-ext/function/is-function")
  , noop         = require("es5-ext/function/noop")
  , toArray      = require("es5-ext/object/to-array")
  , hforEach     = require("es5-ext/object/for-each")
  , isValue      = require("es5-ext/object/is-value")
  , deferred     = require("deferred")
  , createLogger = require("./logger")
  , createAssert = require("./assert");

var nextTick = process.nextTick
  , pattern = /^\s*function\s*\(\s*([tad])(?:\s*,\s*([tad]))?\s*\)/
  , run;

run = function self(testee, tests, assert, logger) {
	if (isFunction(tests)) {
		tests = { "": tests };
	}

	hforEach(tests, function (t) {
		var conf, match;
		if (isFunction(t)) {
			conf = t.conf = { t: true, a: true, d: false };
			if (t.length > 2) {
				conf.d = true;
			} else if ((match = t.toString().match(pattern))) {
				conf.t = conf.a = false;
				conf[match[1]] = true;
				if (match[2]) {
					conf[match[2]] = true;
				}
			}
		}
	});

	return deferred.reduce(
		toArray(tests),
		// eslint-disable-next-line max-statements
		function (ignore, data) {
			var testResult, d, finish, done, name, testFunction;
			name = data[0];
			testFunction = data[1];
			d = deferred();
			finish = function () {
				logger.out(true);
				d.resolve();
			};
			logger.in(name, true);
			if (isFunction(testFunction)) {
				try {
					if (testFunction.conf.d) {
						done = function (asyncTestResult) {
							if (asyncTestResult) {
								if (isError(asyncTestResult)) {
									assert.fail(asyncTestResult);
									finish();
								} else {
									self(testee, asyncTestResult, assert, logger)(finish).done();
								}
							} else {
								finish();
							}
						};
						if (testFunction.conf.t) {
							// eslint-disable-next-line max-depth
							if (testFunction.conf.a) {
								testFunction(testee, assert, done);
							} else {
								testFunction(testee, done);
							}
						} else if (testFunction.conf.a) {
							testFunction(assert, done);
						} else {
							testFunction(done);
						}
					} else {
						if (testFunction.conf.t) {
							testResult = testFunction(testee, assert);
						} else {
							testResult = testFunction(assert);
						}
						if (testResult) {
							self(testee, testResult, assert, logger)(finish).done();
						} else {
							finish();
						}
					}
				} catch (e) {
					logger.error(e);
					finish();
				}
			} else if (isValue(testFunction)) {
				self(testee, testFunction, assert, logger)(finish).done();
			} else {
				assert.fail(new Error("No tests found at '" + name + "' property"));
				finish();
			}
			return d.promise;
		},
		null
	)(noop);
};

module.exports = function (testee, test, assert, logger) {
	var runResult;
	logger = logger || createLogger();
	assert = assert || createAssert(logger);
	nextTick(function () {
		runResult = run(testee, test, assert, logger);
		if (logger.end) {
			runResult = runResult(logger.end.bind(logger));
		}
		runResult.done();
	});
	return logger;
};
<|endoftext|>


<commit_before>var fs       = require('fs');
var path     = require('path');
var url      = require('url');
var util     = require('./util');
var crequest = require('./crequest');
var JStream  = require('jstream');

/**
 * Gets signature for formats.
 *
 * @param {String} link
 * @param {Object} info
 * @param {Boolean} debug
 * @param {Function(Error, String)} callback
 */
exports.get = function(link, info, debug, callback) {
  if (info.formats[0] && info.formats[0].s) {
    crequest(link, function(err, body) {
      if (err) return callback(err);

      var jsonStr = util.between(body, 'ytplayer.config = ', '</script>');
      if (!jsonStr) {
        return callback(new Error('could not find `ytplayer.config`'));
      }

      var jstream = new JStream();
      var ended = false;
      jstream.on('data', function(config) {
        ended = true;
        jstream.pause();

        var newFormats = util.parseFormats(config.args);
        var html5playerfile = 'http:' + config.assets.js;
        crequest(html5playerfile, function(err, body) {
          if (err) return callback(err);

          var tokens = exports.extractActions(body);
          if (!tokens) {
            if (debug) {
              var filename = path.basename(config.assets.js);
              var filepath = path.resolve(
                __dirname, '../tests/files/html5player/' + filename);
              fs.writeFile(filepath, body);
              var name = path.basename(filename, '.js');
              var html5player = require('../test/html5player.json');
              html5player[name] = [];
              fs.writeFile(
                path.resolve(__dirname, '../test/html5player.json'),
                JSON.stringify(html5player, null, 2));
            }
            callback(
              new Error('could not extract signature deciphering actions'));
            return;
          }

          info.formats = info.formats.map(function(format) {
            var newFormat = newFormats
              .filter(function(f) { return f.itag === format.itag; })[0];
            if (newFormat && newFormat.s) {
              format = newFormat;
            }
            var sig = exports.decipher(tokens, format.s);
            format.url = exports.getDownloadURL(format, sig, debug);
            return format;
          });

          callback(null, info);
        });
      });
      jstream.on('error', function(err) {
        if (ended) { return; }
        callback(
          new Error('could not parse `ytplayer.config`: ' + err.message));
      });
      jstream.end(jsonStr);
    });

  } else {
    info.formats.forEach(function(format) {
      var sig = format.sig || '';
      format.url = exports.getDownloadURL(format, sig, debug);
    });
    callback(null, info);
  }
};

/**
 * @param {Object} format
 * @param {Array.<String>} tokens
 * @param {Boolean} debug
 * @return {!String}
 */
exports.getDownloadURL = function(format, sig, debug) {
  var decodedUrl;
  if (format.url) {
    decodedUrl = format.url;
  } else if (format.stream) {
    if (format.conn) {
      decodedUrl = format.conn;
      if (decodedUrl[decodedUrl.length - 1] !== '/') {
        decodedUrl += '/';
      }
      decodedUrl += format.stream;
    } else {
      decodedUrl = format.stream;
    }
  } else {
    if (debug) {
      console.warn('download url not found for itag ' + format.itag);
    }
    return null;
  }

  try {
    decodedUrl = decodeURIComponent(decodedUrl);
  } catch (err) {
    if (debug) {
      console.warn('could not decode url: ' + err.message);
    }
    return null;
  }

  // Make some adjustments to the final url.
  var parsedUrl = url.parse(decodedUrl, true);

  // Deleting the `search` part is necessary otherwise changes to
  // `query` won't reflect when running `url.format()`
  delete parsedUrl.search;

  var query = parsedUrl.query;
  query.ratebypass = 'yes';
  if (sig) {
    query.signature = sig;
  }

  return url.format(parsedUrl);
};

/**
 * Decipher a signature based on action tokens.
 *
 * @param {Array.<String>} tokens
 * @param {String} sig
 * @return {String}
 */
exports.decipher = function(tokens, sig) {
  sig = sig.split('');
  var pos;
  for (var i = 0, len = tokens.length; i < len; i++) {
    var token = tokens[i];
    switch (token[0]) {
    case 'r':
      sig = sig.reverse();
      break;
    case 'w':
      pos = ~~token.slice(1);
      sig = swapHeadAndPosition(sig, pos);
      break;
    case 's':
      pos = ~~token.slice(1);
      sig = sig.slice(pos);
      break;
    case 'p':
      pos = ~~token.slice(1);
      sig.splice(0, pos);
      break;
    }
  }
  return sig.join('');
};

/**
 * Swaps the first element of an array with one of given position.
 *
 * @param {Array.<Object>} arr
 * @param {Number} position
 * @return {Array.<Object>}
 */
function swapHeadAndPosition(arr, position) {
  var first = arr[0];
  arr[0] = arr[position % arr.length];
  arr[position] = first;
  return arr;
}

var jsvarStr = '[a-zA-Z_\\$][a-zA-Z_0-9]*';
var reverseStr = ':function\\(a\\)\\{' +
  '(?:return )?a\\.reverse\\(\\)' +
'\\}';
var sliceStr = ':function\\(a,b\\)\\{' +
  'return a\\.slice\\(b\\)' +
'\\}';
var spliceStr = ':function\\(a,b\\)\\{' +
  'a\\.splice\\(0,b\\)' +
'\\}';
var swapStr = ':function\\(a,b\\)\\{' +
  'var c=a\\[0\\];a\\[0\\]=a\\[b%a\\.length\\];a\\[b\\]=c(?:;return a)?' +
'\\}';
var actionsRegexp = new RegExp(
  'var (' + jsvarStr + ')=\\{((?:(?:' +
    jsvarStr + reverseStr + '|' +
    jsvarStr + sliceStr   + '|' +
    jsvarStr + spliceStr  + '|' +
    jsvarStr + swapStr +
  '),?)+)\\};' +
  'function ' + jsvarStr + '\\(a\\)\\{' +
    'a=a\\.split\\(""\\);' +
    '((?:(?:a=)?\\1\\.' + jsvarStr + '\\(a,\\d+\\);)+)' +
    'return a\\.join\\(""\\)' +
  '\\}'
);
var reverseRegexp = new RegExp('(?:^|,)(' + jsvarStr + ')' + reverseStr);
var sliceRegexp   = new RegExp('(?:^|,)(' + jsvarStr + ')' + sliceStr);
var spliceRegexp  = new RegExp('(?:^|,)(' + jsvarStr + ')' + spliceStr);
var swapRegexp    = new RegExp('(?:^|,)(' + jsvarStr + ')' + swapStr);

/**
 * Extracts the actions that should be taken to decypher a signature.
 *
 *
 * @param {String} body
 * @return {Array.<String>}
 */
exports.extractActions = function(body) {
  var result = actionsRegexp.exec(body);
  if (!result) { return null; }

  var obj      = result[1];
  var objBody  = result[2];
  var funcbody = result[3];

  result = reverseRegexp.exec(objBody);
  var reverseKey = result && result[1];
  result = sliceRegexp.exec(objBody);
  var sliceKey = result && result[1];
  result = spliceRegexp.exec(objBody);
  var spliceKey = result && result[1];
  result = swapRegexp.exec(objBody);
  var swapKey = result && result[1];

  var myreg = '(?:a=)?' + obj + '\\.(' +
    [reverseKey, sliceKey, spliceKey, swapKey].join('|') + ')\\(a,(\\d+)\\)';
  var tokenizeRegexp = new RegExp(myreg, 'g');
  var tokens = [];
  while ((result = tokenizeRegexp.exec(funcbody)) !== null) {
    switch (result[1]) {
      case swapKey:
        tokens.push('w' + result[2]);
        break;
      case reverseKey:
        tokens.push('r');
        break;
      case sliceKey:
        tokens.push('s' + result[2]);
        break;
      case spliceKey:
        tokens.push('p' + result[2]);
        break;
    }
  }
  return tokens;
};
<commit_msg>fix path for saving html5player files<commit_after>var fs       = require('fs');
var path     = require('path');
var url      = require('url');
var util     = require('./util');
var crequest = require('./crequest');
var JStream  = require('jstream');

/**
 * Gets signature for formats.
 *
 * @param {String} link
 * @param {Object} info
 * @param {Boolean} debug
 * @param {Function(Error, String)} callback
 */
exports.get = function(link, info, debug, callback) {
  if (info.formats[0] && info.formats[0].s) {
    crequest(link, function(err, body) {
      if (err) return callback(err);

      var jsonStr = util.between(body, 'ytplayer.config = ', '</script>');
      if (!jsonStr) {
        return callback(new Error('could not find `ytplayer.config`'));
      }

      var jstream = new JStream();
      var ended = false;
      jstream.on('data', function(config) {
        ended = true;
        jstream.pause();

        var newFormats = util.parseFormats(config.args);
        var html5playerfile = 'http:' + config.assets.js;
        crequest(html5playerfile, function(err, body) {
          if (err) return callback(err);

          var tokens = exports.extractActions(body);
          if (!tokens) {
            if (debug) {
              var filename = path.basename(config.assets.js);
              var filepath = path.resolve(
                __dirname, '../test/files/html5player/' + filename);
              fs.writeFile(filepath, body);
              var name = path.basename(filename, '.js');
              var html5player = require('../test/html5player.json');
              html5player[name] = [];
              fs.writeFile(
                path.resolve(__dirname, '../test/html5player.json'),
                JSON.stringify(html5player, null, 2));
            }
            callback(
              new Error('could not extract signature deciphering actions'));
            return;
          }

          info.formats = info.formats.map(function(format) {
            var newFormat = newFormats
              .filter(function(f) { return f.itag === format.itag; })[0];
            if (newFormat && newFormat.s) {
              format = newFormat;
            }
            var sig = exports.decipher(tokens, format.s);
            format.url = exports.getDownloadURL(format, sig, debug);
            return format;
          });

          callback(null, info);
        });
      });
      jstream.on('error', function(err) {
        if (ended) { return; }
        callback(
          new Error('could not parse `ytplayer.config`: ' + err.message));
      });
      jstream.end(jsonStr);
    });

  } else {
    info.formats.forEach(function(format) {
      var sig = format.sig || '';
      format.url = exports.getDownloadURL(format, sig, debug);
    });
    callback(null, info);
  }
};

/**
 * @param {Object} format
 * @param {Array.<String>} tokens
 * @param {Boolean} debug
 * @return {!String}
 */
exports.getDownloadURL = function(format, sig, debug) {
  var decodedUrl;
  if (format.url) {
    decodedUrl = format.url;
  } else if (format.stream) {
    if (format.conn) {
      decodedUrl = format.conn;
      if (decodedUrl[decodedUrl.length - 1] !== '/') {
        decodedUrl += '/';
      }
      decodedUrl += format.stream;
    } else {
      decodedUrl = format.stream;
    }
  } else {
    if (debug) {
      console.warn('download url not found for itag ' + format.itag);
    }
    return null;
  }

  try {
    decodedUrl = decodeURIComponent(decodedUrl);
  } catch (err) {
    if (debug) {
      console.warn('could not decode url: ' + err.message);
    }
    return null;
  }

  // Make some adjustments to the final url.
  var parsedUrl = url.parse(decodedUrl, true);

  // Deleting the `search` part is necessary otherwise changes to
  // `query` won't reflect when running `url.format()`
  delete parsedUrl.search;

  var query = parsedUrl.query;
  query.ratebypass = 'yes';
  if (sig) {
    query.signature = sig;
  }

  return url.format(parsedUrl);
};

/**
 * Decipher a signature based on action tokens.
 *
 * @param {Array.<String>} tokens
 * @param {String} sig
 * @return {String}
 */
exports.decipher = function(tokens, sig) {
  sig = sig.split('');
  var pos;
  for (var i = 0, len = tokens.length; i < len; i++) {
    var token = tokens[i];
    switch (token[0]) {
    case 'r':
      sig = sig.reverse();
      break;
    case 'w':
      pos = ~~token.slice(1);
      sig = swapHeadAndPosition(sig, pos);
      break;
    case 's':
      pos = ~~token.slice(1);
      sig = sig.slice(pos);
      break;
    case 'p':
      pos = ~~token.slice(1);
      sig.splice(0, pos);
      break;
    }
  }
  return sig.join('');
};

/**
 * Swaps the first element of an array with one of given position.
 *
 * @param {Array.<Object>} arr
 * @param {Number} position
 * @return {Array.<Object>}
 */
function swapHeadAndPosition(arr, position) {
  var first = arr[0];
  arr[0] = arr[position % arr.length];
  arr[position] = first;
  return arr;
}

var jsvarStr = '[a-zA-Z_\\$][a-zA-Z_0-9]*';
var reverseStr = ':function\\(a\\)\\{' +
  '(?:return )?a\\.reverse\\(\\)' +
'\\}';
var sliceStr = ':function\\(a,b\\)\\{' +
  'return a\\.slice\\(b\\)' +
'\\}';
var spliceStr = ':function\\(a,b\\)\\{' +
  'a\\.splice\\(0,b\\)' +
'\\}';
var swapStr = ':function\\(a,b\\)\\{' +
  'var c=a\\[0\\];a\\[0\\]=a\\[b%a\\.length\\];a\\[b\\]=c(?:;return a)?' +
'\\}';
var actionsRegexp = new RegExp(
  'var (' + jsvarStr + ')=\\{((?:(?:' +
    jsvarStr + reverseStr + '|' +
    jsvarStr + sliceStr   + '|' +
    jsvarStr + spliceStr  + '|' +
    jsvarStr + swapStr +
  '),?)+)\\};' +
  'function ' + jsvarStr + '\\(a\\)\\{' +
    'a=a\\.split\\(""\\);' +
    '((?:(?:a=)?\\1\\.' + jsvarStr + '\\(a,\\d+\\);)+)' +
    'return a\\.join\\(""\\)' +
  '\\}'
);
var reverseRegexp = new RegExp('(?:^|,)(' + jsvarStr + ')' + reverseStr);
var sliceRegexp   = new RegExp('(?:^|,)(' + jsvarStr + ')' + sliceStr);
var spliceRegexp  = new RegExp('(?:^|,)(' + jsvarStr + ')' + spliceStr);
var swapRegexp    = new RegExp('(?:^|,)(' + jsvarStr + ')' + swapStr);

/**
 * Extracts the actions that should be taken to decypher a signature.
 *
 *
 * @param {String} body
 * @return {Array.<String>}
 */
exports.extractActions = function(body) {
  var result = actionsRegexp.exec(body);
  if (!result) { return null; }

  var obj      = result[1];
  var objBody  = result[2];
  var funcbody = result[3];

  result = reverseRegexp.exec(objBody);
  var reverseKey = result && result[1];
  result = sliceRegexp.exec(objBody);
  var sliceKey = result && result[1];
  result = spliceRegexp.exec(objBody);
  var spliceKey = result && result[1];
  result = swapRegexp.exec(objBody);
  var swapKey = result && result[1];

  var myreg = '(?:a=)?' + obj + '\\.(' +
    [reverseKey, sliceKey, spliceKey, swapKey].join('|') + ')\\(a,(\\d+)\\)';
  var tokenizeRegexp = new RegExp(myreg, 'g');
  var tokens = [];
  while ((result = tokenizeRegexp.exec(funcbody)) !== null) {
    switch (result[1]) {
      case swapKey:
        tokens.push('w' + result[2]);
        break;
      case reverseKey:
        tokens.push('r');
        break;
      case sliceKey:
        tokens.push('s' + result[2]);
        break;
      case spliceKey:
        tokens.push('p' + result[2]);
        break;
    }
  }
  return tokens;
};
<|endoftext|>