<commit_before>var idtarget="";
var code = "";

  function allowDrop(ev)
{
ev.preventDefault();
idtarget=ev.target.id;
//ev.dataTransfer.setData("id",idtarget);
console.log(idtarget);
}
//Funzione per definire cosa fare in caso di drag(non funziona)
  function drag(ev,source)
  {
      getAttributeTags(ev.target.id, function (ret) {

          stampMyObj(ret);

          ev.dataTransfer.setData("source", source);
          ev.dataTransfer.setData("id", ev.target.id);
          var j = JSON.stringify(ret);//pass my object in JSON format because dataTransfer support only string
          ev.dataTransfer.setData("foo", j);

      });
  }

//Funzione per definire cosa fare in caso di drop(non funziona)
  function drop(ev)
  {

      if (ev.dataTransfer) {
          ev.preventDefault();

          var id = ev.dataTransfer.getData("id");
          var ret = JSON.parse(ev.dataTransfer.getData("foo"));
          var source = ev.dataTransfer.getData("source");

          stampMyObj(ret);
          if (ret.type === "iapi") {
              console.log("generate iapi");
          } else if (ret.type === "json") {
              console.log("generate json");
          } else if (ret.type === "rss") {
              console.log("generate rss");
          }
      }
      else {
          alert("Your browser does not support the dataTransfer object.");
      }
}

function generate(urlsource,iapiid,feedtag,itemtag,attributetag,tagsource){

	$.get(urlsource, function(data){
      //  console.log(data);
        if (data=="[object Document]"){

generateRSS(urlsource,feedtag,itemtag,attributetag,tagsource);
}
else{
     		var YourFindElement = $("
" + data + "
").find('.iapi,#'+iapiid+' [class^=data]');
            //console.log(YourFindElement);

		$.each(YourFindElement , function (i, rowValue) {
			var classarg=$(this).attr("class").split(" ");
            console.log(classarg);
			for(i=0;i<classarg.length;i++){
			if (classarg[i].slice(0,9)==("datafeed:") && $(this).hasClass("iapi")){
				code=code.concat("<"+feedtag+" class=\"iapi "+classarg[i]+"\" id=\""+iapiid+"\">");
			}
			else if (classarg[i].slice(0,9)==("dataitem:")){
    	   			code=code.concat("</"+itemtag+"><"+itemtag+" class=\""+classarg[i]+"\"> \n");
          		}
			else if(classarg[i].slice(0,14)==("dataattribute:")){
				code=code.concat("<"+attributetag+" class=\""+classarg[i]+"\">"+$(this).html()+"</"+attributetag+"> \n");
			}
          		else{

            			//code for not data
          		}}

       		});
			code=code.concat("</"+feedtag+">");

	$(tagsource+"[class~='iapi'][id="+idtarget+"]").html(code);
		}
	});
}

function generate(urlsource,iapiid,feedtag,itemtag,attributetag,tagsource){

	$.get(urlsource, function(data){
      //  console.log(data);
        if (data=="[object Document]"){

generateRSS(urlsource,feedtag,itemtag,attributetag,tagsource);
}
else{
     		var YourFindElement = $("
" + data + "
").find('.iapi,#'+iapiid+' [class^=data]');
            //console.log(YourFindElement);

		$.each(YourFindElement , function (i, rowValue) {
			var classarg=$(this).attr("class").split(" ");
            console.log(classarg);
			for(i=0;i<classarg.length;i++){
			if (classarg[i].slice(0,9)==("datafeed:") && $(this).hasClass("iapi")){
				code=code.concat("<"+feedtag+" class=\"iapi "+classarg[i]+"\" id=\""+iapiid+"\">");
			}
			else if (classarg[i].slice(0,9)==("dataitem:")){
    	   			code=code.concat("</"+itemtag+"><"+itemtag+" class=\""+classarg[i]+"\"> \n");
          		}
			else if(classarg[i].slice(0,14)==("dataattribute:")){
				code=code.concat("<"+attributetag+" class=\""+classarg[i]+"\">"+$(this).html()+"</"+attributetag+"> \n");
			}
          		else{

            			//code for not data
          		}}

       		});
			code=code.concat("</"+feedtag+">");

	$(tagsource+"[class~='iapi'][id="+idtarget+"]").html(code);
		}
	});
}

//call parseSRC or parseTRG
function getAttributeTags(iapiid, call) {
    var YourFindElement = $(".iapi").filter("#" + iapiid).get();

    $.each(YourFindElement, function (i, rowValue) {
        var tagtarg = $(this).attr("class").split(" ");

        var presenceDataSource=false;
        var t;
        for (i = 0; i < tagtarg.length; i++) {
            if (tagtarg[i].slice(0, 11) == ("datasource:")) {
                presenceDataSource=true;
            }
        }
        if (presenceDataSource === true) {
            //console.log("\nYES (presence DataSource)\n");
            parseTRG(YourFindElement, iapiid,function (ret) {
                call(ret);
            });
        }
        else {
            //console.log("\nNO(no presence DataSource)\n");
            parseSRC(YourFindElement, iapiid,function (ret) {
                call( ret);
            });
        }
    });

}

//get datasource,iapiid,sourcetype
function parseSRC(YourFindElement,id, callback) {
    //console.log("PARSE_SRC");
    $.each(YourFindElement, function (i, rowValue) {
        var tagtarg = $(this).attr("class").split(" ");
        var id = $(this).attr('id');

        var urlsource;
        var iapiid;
        var sourcetype;
        var arrayHideElements = new Array();

        for (i = 0; i < tagtarg.length; i++) {
            if (tagtarg[i].slice(0, 5) == ("json:")) {
                sourcetype = tagtarg[i].substr(0, 4);
                urlsource = tagtarg[i].substr(5);
            }
            else if (tagtarg[i].slice(0, 4) == ("rss:")) {
                sourcetype = tagtarg[i].substr(0, 3);
                urlsource = tagtarg[i].substr(4);
            }
            else if (tagtarg[i].slice(0, 4) == ("xml:")) {
                sourcetype = tagtarg[i].substr(0, 3);
                urlsource = tagtarg[i].substr(4);
            }
            else if (tagtarg[i].slice(0, 5) == ("hide:")) {//hide:Author:Title:Where
                var hideElements = tagtarg[i].substr(5).split(":");//Author Title Where
                for (var j = 0; j < hideElements.length; j++) {
                    arrayHideElements.push(hideElements[j]);
                }
            }
        }
        if (sourcetype === undefined)
            sourcetype = "iapi";

        ///DEBUG
        //if (urlsource != undefined)
        //    console.log("url:" + urlsource);

        var retCommon = parseCommon(id, sourcetype);
        var ret = {"url":urlsource,"type":sourcetype,"iapiid":iapiid,"hide":arrayHideElements,"other":retCommon};

        callback(ret);
    });

}

//get datasource,iapiid,sourcetype
function parseTRG(YourFindElement, id, callback) {
    //console.log("PARSE_TRG");

    $.each(YourFindElement, function (i, rowValue) {
        var tagtarg = $(this).attr("class").split(" ");
        var id = $(this).attr('id');

        var urlsource;
        var sourcetype;
        var iapiid;
        var arrayHideElements = new Array();

        for (i = 0; i < tagtarg.length; i++) {
            if (tagtarg[i].slice(0, 11) == ("datasource:")) {
                urlsource = tagtarg[i].substr(11);
            }
            else if (tagtarg[i].slice(0, 7) == ("iapiid:")) {
                iapiid = tagtarg[i].substr(7);
            }
            else if (tagtarg[i].slice(0, 11) == ("sourcetype:")) {
                sourcetype = tagtarg[i].substr(11);
            }
            else if (tagtarg[i].slice(0, 5) == ("hide:")) {//hide:Author:Title:Where
                var hideElements = tagtarg[i].substr(5).split(":");//Author Title Where
                for (var j = 0; j < hideElements.length; j++) {
                    arrayHideElements.push(hideElements[j]);
                }
            }

        }
        if (sourcetype === "iapi" && iapiid === undefined) {
            console.log("ERROR: you must declare iapiid");
            console.log("TODO");
            //TODO
        }

        ///DEBUG
        //if (urlsource != undefined)
        //    console.log("url:" + urlsource);
        //if (iapiid != undefined)
        //    console.log("iapiid:" + iapiid);

        var retCommon = parseCommon(id, sourcetype);
        var ret = { "url": urlsource, "type": sourcetype, "iapiid": iapiid, "hide": arrayHideElements, "other": retCommon };

        callback(ret);
    });

}

//get iapitemplate (true/false),dataitems[labe][key] and dataattributes[labe][key]
function parseCommon(id,sourcetype) {

    var YourFindElement2 = $(".iapi").filter("#" + id);

    dataattribute = new Array();
    iapitemplate = false;
    var dataitem;
    var YourFindElement3 = YourFindElement2.find("[class*=dataitem]").attr("class").split(" ");//first().html();
    for (i = 0; i < YourFindElement3.length; i++) {
        if (YourFindElement3[i] === "iapitemplate") {
            iapitemplate = true;
        }
        else if (YourFindElement3[i].slice(0, 9) == "dataitem:") {
            var temp2 = YourFindElement3[i].substr(9);//Publication:pubs or //Publication
            if (sourcetype != "iapi") {
                var n = temp2.indexOf(":");//Publication:pubs
                if (n !== -1) {
                    var a = temp2.substr(0, n);//Publication
                    var b = temp2.substr(n + 1);//pubs

                    if (a === "" || b === "") {
                        console.log("ERROR");
                    }
                    dataitem = ({ "type": YourFindElement3[i].slice(0, 8), "label": a, "key": b });
                } else {//Publication
                    var a = temp2.substr(0);

                    if (a === "" ) {
                        console.log("ERROR");
                    }
                    dataitem = ({ "type": YourFindElement3[i].slice(0, 8), "label": a});
                }

            }
            else {//Publication
                dataitem = ({ "type": YourFindElement3[i].slice(0, 8), "label": temp2 });

            }
        }
    }
    var YourFindElement5 = YourFindElement2.find("[class*=dataitem]");
    var YourFindElement4 = YourFindElement5.first().children("[class*=dataattribute]");
    $.each(YourFindElement4, function (i, rowValue) {

        if ($(this).attr("class").slice(0, 14) == ("dataattribute:")) {

            var temp = $(this).attr("class").substr(14);//Author:auth or //Author

            if (sourcetype != "iapi") {
                var n = temp.indexOf(":");//Author:auth
                var a = temp.substr(0, n);//Author
                var b = temp.substr(n + 1);//auth

                if (a == "" || b == "") {
                    console.log("ERROR");
                }
                dataattribute.push({ "type": $(this).attr("class").substr(0, 13), "label": a, "key": b });
            }
            else {//Author
                dataattribute.push({ "type": $(this).attr("class").substr(0, 13), "label": temp });
            }
        }
        //console.log("elem ->:" + dataattribute[i].type);

    });
    return {"iapitemplate":iapitemplate,"dataitem":dataitem,"dataattribute":dataattribute};
}

//DEBUG stamp my object
//
//"url",
//"type",
//"iapiid",
//"other":
//       "iapitemplate",
//       "dataitem":"type","label","key"
//       "dataattribute":"type","label","key"
function stampMyObj(ret) {
    console.log("url->" + ret.url);
    console.log("type->" + ret.type);
    console.log("iapiid->" + ret.iapiid);
    if (ret.hide.length !== 0) {
        var txt = "";
        console.log("hide:");
        for (var i = 0; i < ret.hide.length; i++) {
            if (i === 0)
                txt+="\t" + ret.hide[i];
            else
                txt+=" - " + ret.hide[i];
        }
        console.log(txt);
    }
    console.log("other:");
    console.log("\t iapitemplate->" + ret.other.iapitemplate);
    console.log("\t " + ret.other.dataitem.type + " 'label'->" + ret.other.dataitem.label + " 'key'->" + ret.other.dataitem.key);
    for (var i = 0; i < ret.other.dataattribute.length; i++) {
        console.log("\t " + ret.other.dataattribute[i].type + " [" + i + "] 'label'->" + ret.other.dataattribute[i].label + " 'key'->" + ret.other.dataattribute[i].key);
    }
}<commit_msg>remove comments<commit_after>var idtarget="";
var code = "";

  function allowDrop(ev)
{
ev.preventDefault();
idtarget=ev.target.id;
//ev.dataTransfer.setData("id",idtarget);
console.log(idtarget);
}
//Funzione per definire cosa fare in caso di drag(non funziona)
  function drag(ev,source)
  {
      getAttributeTags(ev.target.id, function (ret) {

          //stampMyObj(ret);

          ev.dataTransfer.setData("source", source);
          ev.dataTransfer.setData("id", ev.target.id);
          var j = JSON.stringify(ret);//pass my object in JSON format because dataTransfer support only string
          ev.dataTransfer.setData("foo", j);

      });
  }

//Funzione per definire cosa fare in caso di drop(non funziona)
  function drop(ev)
  {

      if (ev.dataTransfer) {
          ev.preventDefault();

          var id = ev.dataTransfer.getData("id");
          var ret = JSON.parse(ev.dataTransfer.getData("foo"));
          var source = ev.dataTransfer.getData("source");

          //stampMyObj(ret);
          if (ret.type === "iapi") {
              console.log("generate iapi");
          } else if (ret.type === "json") {
              console.log("generate json");
          } else if (ret.type === "rss") {
              console.log("generate rss");
          }
      }
      else {
          alert("Your browser does not support the dataTransfer object.");
      }
}

function generate(urlsource,iapiid,feedtag,itemtag,attributetag,tagsource){

	$.get(urlsource, function(data){
      //  console.log(data);
        if (data=="[object Document]"){

generateRSS(urlsource,feedtag,itemtag,attributetag,tagsource);
}
else{
     		var YourFindElement = $("
" + data + "
").find('.iapi,#'+iapiid+' [class^=data]');
            //console.log(YourFindElement);

		$.each(YourFindElement , function (i, rowValue) {
			var classarg=$(this).attr("class").split(" ");
            console.log(classarg);
			for(i=0;i<classarg.length;i++){
			if (classarg[i].slice(0,9)==("datafeed:") && $(this).hasClass("iapi")){
				code=code.concat("<"+feedtag+" class=\"iapi "+classarg[i]+"\" id=\""+iapiid+"\">");
			}
			else if (classarg[i].slice(0,9)==("dataitem:")){
    	   			code=code.concat("</"+itemtag+"><"+itemtag+" class=\""+classarg[i]+"\"> \n");
          		}
			else if(classarg[i].slice(0,14)==("dataattribute:")){
				code=code.concat("<"+attributetag+" class=\""+classarg[i]+"\">"+$(this).html()+"</"+attributetag+"> \n");
			}
          		else{

            			//code for not data
          		}}

       		});
			code=code.concat("</"+feedtag+">");

	$(tagsource+"[class~='iapi'][id="+idtarget+"]").html(code);
		}
	});
}

function generate(urlsource,iapiid,feedtag,itemtag,attributetag,tagsource){

	$.get(urlsource, function(data){
      //  console.log(data);
        if (data=="[object Document]"){

generateRSS(urlsource,feedtag,itemtag,attributetag,tagsource);
}
else{
     		var YourFindElement = $("
" + data + "
").find('.iapi,#'+iapiid+' [class^=data]');
            //console.log(YourFindElement);

		$.each(YourFindElement , function (i, rowValue) {
			var classarg=$(this).attr("class").split(" ");
            console.log(classarg);
			for(i=0;i<classarg.length;i++){
			if (classarg[i].slice(0,9)==("datafeed:") && $(this).hasClass("iapi")){
				code=code.concat("<"+feedtag+" class=\"iapi "+classarg[i]+"\" id=\""+iapiid+"\">");
			}
			else if (classarg[i].slice(0,9)==("dataitem:")){
    	   			code=code.concat("</"+itemtag+"><"+itemtag+" class=\""+classarg[i]+"\"> \n");
          		}
			else if(classarg[i].slice(0,14)==("dataattribute:")){
				code=code.concat("<"+attributetag+" class=\""+classarg[i]+"\">"+$(this).html()+"</"+attributetag+"> \n");
			}
          		else{

            			//code for not data
          		}}

       		});
			code=code.concat("</"+feedtag+">");

	$(tagsource+"[class~='iapi'][id="+idtarget+"]").html(code);
		}
	});
}

//call parseSRC or parseTRG
function getAttributeTags(iapiid, call) {
    var YourFindElement = $(".iapi").filter("#" + iapiid).get();

    $.each(YourFindElement, function (i, rowValue) {
        var tagtarg = $(this).attr("class").split(" ");

        var presenceDataSource=false;
        var t;
        for (i = 0; i < tagtarg.length; i++) {
            if (tagtarg[i].slice(0, 11) == ("datasource:")) {
                presenceDataSource=true;
            }
        }
        if (presenceDataSource === true) {
            //console.log("\nYES (presence DataSource)\n");
            parseTRG(YourFindElement, iapiid,function (ret) {
                call(ret);
            });
        }
        else {
            //console.log("\nNO(no presence DataSource)\n");
            parseSRC(YourFindElement, iapiid,function (ret) {
                call( ret);
            });
        }
    });

}

//get datasource,iapiid,sourcetype
function parseSRC(YourFindElement,id, callback) {
    //console.log("PARSE_SRC");
    $.each(YourFindElement, function (i, rowValue) {
        var tagtarg = $(this).attr("class").split(" ");
        var id = $(this).attr('id');

        var urlsource;
        var iapiid;
        var sourcetype;
        var arrayHideElements = new Array();

        for (i = 0; i < tagtarg.length; i++) {
            if (tagtarg[i].slice(0, 5) == ("json:")) {
                sourcetype = tagtarg[i].substr(0, 4);
                urlsource = tagtarg[i].substr(5);
            }
            else if (tagtarg[i].slice(0, 4) == ("rss:")) {
                sourcetype = tagtarg[i].substr(0, 3);
                urlsource = tagtarg[i].substr(4);
            }
            else if (tagtarg[i].slice(0, 4) == ("xml:")) {
                sourcetype = tagtarg[i].substr(0, 3);
                urlsource = tagtarg[i].substr(4);
            }
            else if (tagtarg[i].slice(0, 5) == ("hide:")) {//hide:Author:Title:Where
                var hideElements = tagtarg[i].substr(5).split(":");//Author Title Where
                for (var j = 0; j < hideElements.length; j++) {
                    arrayHideElements.push(hideElements[j]);
                }
            }
        }
        if (sourcetype === undefined)
            sourcetype = "iapi";

        ///DEBUG
        //if (urlsource != undefined)
        //    console.log("url:" + urlsource);

        var retCommon = parseCommon(id, sourcetype);
        var ret = {"url":urlsource,"type":sourcetype,"iapiid":iapiid,"hide":arrayHideElements,"other":retCommon};

        callback(ret);
    });

}

//get datasource,iapiid,sourcetype
function parseTRG(YourFindElement, id, callback) {
    //console.log("PARSE_TRG");

    $.each(YourFindElement, function (i, rowValue) {
        var tagtarg = $(this).attr("class").split(" ");
        var id = $(this).attr('id');

        var urlsource;
        var sourcetype;
        var iapiid;
        var arrayHideElements = new Array();

        for (i = 0; i < tagtarg.length; i++) {
            if (tagtarg[i].slice(0, 11) == ("datasource:")) {
                urlsource = tagtarg[i].substr(11);
            }
            else if (tagtarg[i].slice(0, 7) == ("iapiid:")) {
                iapiid = tagtarg[i].substr(7);
            }
            else if (tagtarg[i].slice(0, 11) == ("sourcetype:")) {
                sourcetype = tagtarg[i].substr(11);
            }
            else if (tagtarg[i].slice(0, 5) == ("hide:")) {//hide:Author:Title:Where
                var hideElements = tagtarg[i].substr(5).split(":");//Author Title Where
                for (var j = 0; j < hideElements.length; j++) {
                    arrayHideElements.push(hideElements[j]);
                }
            }

        }
        if (sourcetype === "iapi" && iapiid === undefined) {
            console.log("ERROR: you must declare iapiid");
            console.log("TODO");
            //TODO
        }

        ///DEBUG
        //if (urlsource != undefined)
        //    console.log("url:" + urlsource);
        //if (iapiid != undefined)
        //    console.log("iapiid:" + iapiid);

        var retCommon = parseCommon(id, sourcetype);
        var ret = { "url": urlsource, "type": sourcetype, "iapiid": iapiid, "hide": arrayHideElements, "other": retCommon };

        callback(ret);
    });

}

//get iapitemplate (true/false),dataitems[labe][key] and dataattributes[labe][key]
function parseCommon(id,sourcetype) {

    var YourFindElement2 = $(".iapi").filter("#" + id);

    dataattribute = new Array();
    iapitemplate = false;
    var dataitem;
    var YourFindElement3 = YourFindElement2.find("[class*=dataitem]").attr("class").split(" ");//first().html();
    for (i = 0; i < YourFindElement3.length; i++) {
        if (YourFindElement3[i] === "iapitemplate") {
            iapitemplate = true;
        }
        else if (YourFindElement3[i].slice(0, 9) == "dataitem:") {
            var temp2 = YourFindElement3[i].substr(9);//Publication:pubs or //Publication
            if (sourcetype != "iapi") {
                var n = temp2.indexOf(":");//Publication:pubs
                if (n !== -1) {
                    var a = temp2.substr(0, n);//Publication
                    var b = temp2.substr(n + 1);//pubs

                    if (a === "" || b === "") {
                        console.log("ERROR");
                    }
                    dataitem = ({ "type": YourFindElement3[i].slice(0, 8), "label": a, "key": b });
                } else {//Publication
                    var a = temp2.substr(0);

                    if (a === "" ) {
                        console.log("ERROR");
                    }
                    dataitem = ({ "type": YourFindElement3[i].slice(0, 8), "label": a});
                }

            }
            else {//Publication
                dataitem = ({ "type": YourFindElement3[i].slice(0, 8), "label": temp2 });

            }
        }
    }
    var YourFindElement5 = YourFindElement2.find("[class*=dataitem]");
    var YourFindElement4 = YourFindElement5.first().children("[class*=dataattribute]");
    $.each(YourFindElement4, function (i, rowValue) {

        if ($(this).attr("class").slice(0, 14) == ("dataattribute:")) {

            var temp = $(this).attr("class").substr(14);//Author:auth or //Author

            if (sourcetype != "iapi") {
                var n = temp.indexOf(":");//Author:auth
                var a = temp.substr(0, n);//Author
                var b = temp.substr(n + 1);//auth

                if (a == "" || b == "") {
                    console.log("ERROR");
                }
                dataattribute.push({ "type": $(this).attr("class").substr(0, 13), "label": a, "key": b });
            }
            else {//Author
                dataattribute.push({ "type": $(this).attr("class").substr(0, 13), "label": temp });
            }
        }
        //console.log("elem ->:" + dataattribute[i].type);

    });
    return {"iapitemplate":iapitemplate,"dataitem":dataitem,"dataattribute":dataattribute};
}

//DEBUG stamp my object
//
//"url",
//"type",
//"iapiid",
//"other":
//       "iapitemplate",
//       "dataitem":"type","label","key"
//       "dataattribute":"type","label","key"
function stampMyObj(ret) {
    console.log("url->" + ret.url);
    console.log("type->" + ret.type);
    console.log("iapiid->" + ret.iapiid);
    if (ret.hide.length !== 0) {
        var txt = "";
        console.log("hide:");
        for (var i = 0; i < ret.hide.length; i++) {
            if (i === 0)
                txt+="\t" + ret.hide[i];
            else
                txt+=" - " + ret.hide[i];
        }
        console.log(txt);
    }
    console.log("other:");
    console.log("\t iapitemplate->" + ret.other.iapitemplate);
    console.log("\t " + ret.other.dataitem.type + " 'label'->" + ret.other.dataitem.label + " 'key'->" + ret.other.dataitem.key);
    for (var i = 0; i < ret.other.dataattribute.length; i++) {
        console.log("\t " + ret.other.dataattribute[i].type + " [" + i + "] 'label'->" + ret.other.dataattribute[i].label + " 'key'->" + ret.other.dataattribute[i].key);
    }
}<|endoftext|>


<commit_before>angular.module('tattva')
.controller('LoginCtrl', ['$scope', '$http', '$state','AuthService',
function($scope, $http, $state,AuthService) {
  $scope.signUp=function(){
    $scope.selectedIndex = 1;
  }

  $scope.signIn=function(){
    $scope.selectedIndex = 0;
  }
  $scope.success="true";
  $scope.login = function() {
    $scope.error = "";
    AuthService.signIn($scope.user).then(function(user) {
      if(user.role=="tattvaAdmin"){
        $state.go("adminHome");
      } else {
      $state.go("home");
      }
    }, function(err) {
      $scope.error = err.message;
    });
  }

  $scope.register=function() {
    AuthService.signUp($scope.user).then(function(user) {
      $state.go("home");
    }, function(err) {
      $scope.error = err.err;
    });
  }
}]);
<commit_msg>login controller admin role<commit_after>angular.module('tattva')
.controller('LoginCtrl', ['$scope', '$http', '$state','AuthService',
function($scope, $http, $state,AuthService) {
  $scope.signUp=function(){
    $scope.selectedIndex = 1;
  }

  $scope.signIn=function(){
    $scope.selectedIndex = 0;
  }
  $scope.success="true";
  $scope.login = function() {
    $scope.error = "";
    AuthService.signIn($scope.user).then(function(user) {
      if(user.role=="TATTVAADM"){
        $state.go("adminHome");
      } else {
      $state.go("home");
      }
    }, function(err) {
      $scope.error = err.message;
    });
  }

  $scope.register=function() {
    AuthService.signUp($scope.user).then(function(user) {
      $state.go("home");
    }, function(err) {
      $scope.error = err.err;
    });
  }
}]);
<|endoftext|>


<commit_before>var assert        = require("assert");
var util          = require("util");
var http          = require("http");
var https         = require("https");
var url           = require("url");
var addressparser = require("addressparser");
var pkg           = require("../package.json");

//
// Constants
//
var STATUS_OK = 200;

//
// Helper
//
function isString(v) {
    return typeof v === "string" || v instanceof String;
}

function checkOptions(options) {
    var apiKey = options.apiKey;
    var apiUrl = options.apiUrl;

    assert(apiKey && isString(apiKey), "apiKey: must be a non-empty string");
    assert(apiUrl && isString(apiUrl), "apiUrl: must be a non-empty string");
}

function addAddress(obj, address) {
    obj[address.address] = address.name || "";
    return obj;
}

function flattenGroups(addresses) {
    var flattened = [];

    function traverse(obj) {
        if (obj.group) {
            obj.group.forEach(traverse);
        } else {
            flattened.push(obj);
        }
    }

    addresses.forEach(traverse);

    return flattened;
}

function transformAddresses(addresses) {
    return flattenGroups(addressparser(addresses)).reduce(function (obj, address) {
        return addAddress(obj, address);
    }, {});
}

function transformFromAddresses(addresses) {
    var fromAddress = flattenGroups(addressparser(addresses))[0];

    return [fromAddress.address, fromAddress.name];
}

function isErrorResponse(response) {
    if (response.statusCode !== STATUS_OK) {
        return true;
    }

    return false;
}

function responseError(response, body) {
    return new Error(
        util.format("%s (%s, %d)",
            body.message || "server error",
            body.code || "-",
            response.statusCode));
}

function makeInfo(data) {
    return {
        messageId: data["message-id"] || ""
    };
}

//
// Transport class
//
function SendinBlueTransport(options) {
    checkOptions(options);

    this.name    = "SendinBlue";
    this.version = pkg.version;

    this.reqOptions = url.parse(options.apiUrl + "/email");
    this.reqOptions.method = "POST";
    this.reqOptions.headers = {
        "api-key": options.apiKey,
        "Content-Type": "application/json"
    };

    this.reqBuilder = this.reqOptions.protocol === "https:" ? https.request : http.request;
}

SendinBlueTransport.prototype.send = function (mail, callback) {
    var req = this.reqBuilder(this.reqOptions, function (res) {
        res.setEncoding("utf-8");

        var data = "";
        res.on("data", function (chunk) {
            data += chunk;
        });

        res.on("end", function () {
            var body = {};

            try {
                body = JSON.parse(data);
            } catch (err) { /* Ignore error */ }

            if (isErrorResponse(res)) {
                return callback(responseError(res, body));
            }

            callback(null, makeInfo(body.data));
        });
    });

    req.write(JSON.stringify(this.transformData(mail.data)));
    req.end();
};

SendinBlueTransport.prototype.transformData = function (data) {
    return {
        from:    transformFromAddresses(data.from),
        to:      transformAddresses(data.to),
        cc:      transformAddresses(data.cc),
        bcc:     transformAddresses(data.bcc),
        replyto: transformFromAddresses(data.replyTo),
        subject: data.subject,
        text:    data.text,
        html:    data.html
    };
};

module.exports = function (options) {
    return new SendinBlueTransport(options);
};
<commit_msg>Handle request errors and pass them back to the caller<commit_after>var assert        = require("assert");
var util          = require("util");
var http          = require("http");
var https         = require("https");
var url           = require("url");
var addressparser = require("addressparser");
var pkg           = require("../package.json");

//
// Constants
//
var STATUS_OK = 200;

//
// Helper
//
function isString(v) {
    return typeof v === "string" || v instanceof String;
}

function checkOptions(options) {
    var apiKey = options.apiKey;
    var apiUrl = options.apiUrl;

    assert(apiKey && isString(apiKey), "apiKey: must be a non-empty string");
    assert(apiUrl && isString(apiUrl), "apiUrl: must be a non-empty string");
}

function addAddress(obj, address) {
    obj[address.address] = address.name || "";
    return obj;
}

function flattenGroups(addresses) {
    var flattened = [];

    function traverse(obj) {
        if (obj.group) {
            obj.group.forEach(traverse);
        } else {
            flattened.push(obj);
        }
    }

    addresses.forEach(traverse);

    return flattened;
}

function transformAddresses(addresses) {
    return flattenGroups(addressparser(addresses)).reduce(function (obj, address) {
        return addAddress(obj, address);
    }, {});
}

function transformFromAddresses(addresses) {
    var fromAddress = flattenGroups(addressparser(addresses))[0];

    return [fromAddress.address, fromAddress.name];
}

function isErrorResponse(response) {
    if (response.statusCode !== STATUS_OK) {
        return true;
    }

    return false;
}

function responseError(response, body) {
    return new Error(
        util.format("%s (%s, %d)",
            body.message || "server error",
            body.code || "-",
            response.statusCode));
}

function makeInfo(data) {
    return {
        messageId: data["message-id"] || ""
    };
}

//
// Transport class
//
function SendinBlueTransport(options) {
    checkOptions(options);

    this.name    = "SendinBlue";
    this.version = pkg.version;

    this.reqOptions = url.parse(options.apiUrl + "/email");
    this.reqOptions.method = "POST";
    this.reqOptions.headers = {
        "api-key": options.apiKey,
        "Content-Type": "application/json"
    };

    this.reqBuilder = this.reqOptions.protocol === "https:" ? https.request : http.request;
}

SendinBlueTransport.prototype.send = function (mail, callback) {
    var req = this.reqBuilder(this.reqOptions, function (res) {
        res.setEncoding("utf-8");

        var data = "";
        res.on("data", function (chunk) {
            data += chunk;
        });

        res.on("end", function () {
            var body = {};

            try {
                body = JSON.parse(data);
            } catch (err) { /* Ignore error */ }

            if (isErrorResponse(res)) {
                return callback(responseError(res, body));
            }

            callback(null, makeInfo(body.data));
        });
    });

    req.on("error", function (err) {
        callback(new Error("error sending request: " + err.message));
    });

    req.write(JSON.stringify(this.transformData(mail.data)));
    req.end();
};

SendinBlueTransport.prototype.transformData = function (data) {
    return {
        from:    transformFromAddresses(data.from),
        to:      transformAddresses(data.to),
        cc:      transformAddresses(data.cc),
        bcc:     transformAddresses(data.bcc),
        replyto: transformFromAddresses(data.replyTo),
        subject: data.subject,
        text:    data.text,
        html:    data.html
    };
};

module.exports = function (options) {
    return new SendinBlueTransport(options);
};
<|endoftext|>


<commit_before>'use strict';
/**
 * @file Upload all contacts from all accounts modified since last call to upload.
 *
 */

var async = require('async');
var Cluestr = require('cluestr');

var config = require('../../../config/configuration.js');
var retrieve = require('../helpers/retrieve.js');

/**
 * Build a uuid for each DB file.
 *
 * @param {int} uid User ID (available on the tokens)
 * @param {path} path File path
 */
var _identifier = function(uid, path) {
  return 'https://dropbox.com/' + uid + path;
};

/**
 * Run the task of uploading a document to Dropbox.
 * This function will be used as a queue
 * @see https://github.com/caolan/async#queueworker-concurrency
 *
 * @param {Object} task Task param (keys: `dropboxTokens`, `path`, `cluestrClient`)
 * @param {Function} cb Callback once task has been processed.
 */
var uploadFile = function(task, cb) {
  // Build additional datas
  var filename = task.path.substr(task.path.lastIndexOf('/') + 1);

  var actions = {
    'show': 'https://www.dropbox.com/home' + encodeURIComponent(task.path)
  };

  var metadatas = {
    title: filename,
    path: task.path
  };

  // Object to send
  var datas = {
    identifier: _identifier(task.dropboxTokens.uid, task.path),
    metadatas: metadatas,
    actions: actions,
    user_access: [task.accessToken]
  };

  // Stream the file from DB servers
  var stream = retrieve.streamFile(task.dropboxTokens, task.path);

  // File to send
  var fileConfig = {
    file: stream,
    filename: filename
  };

  // Let's roll.
  console.log('UPPING', datas.identifier);
  task.cluestrClient.sendDocumentAndFile(datas, fileConfig, cb);
};

/**
 * Run the task of deleting a document on Cluestr.
 * This function will be used as a queue
 * @see https://github.com/caolan/async#queueworker-concurrency
 *
 * @param {Object} task Task param (keys: `dropboxTokens`, `path`, `cluestrClient`)
 * @param {Function} cb Callback once task has been processed.
 */
var deleteFile = function(task, cb) {
  var identifier = _identifier(task.dropboxTokens.uid, task.path);

  console.log("DELING", identifier);
  task.cluestrClient.deleteDocument(identifier, cb);
};

/**
 * Upload all datas from the specified account onto Cluestr.
 *
 * @param {model/Token} token Datas for the account to upload
 * @param {Function} cb Callback. First parameter is the error if any.
 */
module.exports = function(token, cb) {
  // Build our queue.
  // It will hold our creation tasks.
  var createQueue = async.queue(uploadFile, config.max_concurrency);

  // Build our removal queue.
  // It will hold our deletion tasks.
  var deleteQueue = async.queue(deleteFile, 20);

  // cluestrClient to use for this token.
  var cluestr = new Cluestr(config.cluestr_id, config.cluestr_secret);
  cluestr.setAccessToken(token.cluestrToken);

  // Warning: in some cases, delta can be very long to generate.
  retrieve.delta(token.dropboxTokens, token.cursor, function(err, files) {
    if(err) {
      return cb(err);
    }

    // Build an array of tasks to feed onto the queue.
    var createTasks = files.files.map(function(path) {
      return {
        path: path,
        dropboxTokens: token.dropboxTokens,
        cluestrClient: cluestr,
        accessToken: token.cluestrToken,
      };
    });
    createQueue.push(createTasks);

    var deleteTasks = files.deletedFiles.map(function(path) {
      return {
        path: path,
        dropboxTokens: token.dropboxTokens,
        cluestrClient: cluestr
      };
    });
    deleteQueue.push(deleteTasks);

    // Warning: we put the final callback on fileQueue, as deleteFileQueue is assumed to be faster to empty.
    // In some edge cases however, the final cb() will be called but deleteFileQueue will still be processing. This has no incidence whatsoever unless you're polling far too quickly.
    createQueue.drain = function() {
      //TODO: uncomment.
      //token.cursor = cursor;
      token.save(function(err) {
        if(err) {
          return cb(err);
        }

        cb();
      });
    };
  });
};
<commit_msg>TODOs<commit_after>'use strict';
/**
 * @file Upload all contacts from all accounts modified since last call to upload.
 *
 */

var async = require('async');
var Cluestr = require('cluestr');

var config = require('../../../config/configuration.js');
var retrieve = require('../helpers/retrieve.js');

/**
 * Build a uuid for each DB file.
 *
 * @param {int} uid User ID (available on the tokens)
 * @param {path} path File path
 */
var _identifier = function(uid, path) {
  return 'https://dropbox.com/' + uid + path;
};

/**
 * Run the task of uploading a document to Dropbox.
 * This function will be used as a queue
 * @see https://github.com/caolan/async#queueworker-concurrency
 *
 * @param {Object} task Task param (keys: `dropboxTokens`, `path`, `cluestrClient`)
 * @param {Function} cb Callback once task has been processed.
 */
var uploadFile = function(task, cb) {
  // Build additional datas
  var filename = task.path.substr(task.path.lastIndexOf('/') + 1);

  var actions = {
    'show': 'https://www.dropbox.com/home' + encodeURIComponent(task.path)
  };

  var metadatas = {
    title: filename,
    path: task.path
  };

  // Object to send
  var datas = {
    identifier: _identifier(task.dropboxTokens.uid, task.path),
    metadatas: metadatas,
    actions: actions,
    user_access: [task.accessToken]
  };

  // Stream the file from DB servers
  var stream = retrieve.streamFile(task.dropboxTokens, task.path);

  // File to send
  var fileConfig = {
    file: stream,
    filename: filename
  };

  // Let's roll.
  console.log('UPPING', datas.identifier);
  task.cluestrClient.sendDocumentAndFile(datas, fileConfig, cb);
};

/**
 * Run the task of deleting a document on Cluestr.
 * This function will be used as a queue
 * @see https://github.com/caolan/async#queueworker-concurrency
 *
 * @param {Object} task Task param (keys: `dropboxTokens`, `path`, `cluestrClient`)
 * @param {Function} cb Callback once task has been processed.
 */
var deleteFile = function(task, cb) {
  var identifier = _identifier(task.dropboxTokens.uid, task.path);

  console.log("DELING", identifier);
  task.cluestrClient.deleteDocument(identifier, cb);
};

/**
 * Upload all datas from the specified account onto Cluestr.
 *
 * @param {model/Token} token Datas for the account to upload
 * @param {Function} cb Callback. First parameter is the error if any.
 */
module.exports = function(token, cb) {
  // Build our queue.
  // It will hold our creation tasks.
  // TODO: move this queue onto the server, instead of creating one per user.
  var createQueue = async.queue(uploadFile, config.max_concurrency);

  // Build our removal queue.
  // It will hold our deletion tasks.
  // TODO: move this queue onto the server, instead of creating one per user.

  var deleteQueue = async.queue(deleteFile, 20);

  // cluestrClient to use for this token.
  var cluestr = new Cluestr(config.cluestr_id, config.cluestr_secret);
  cluestr.setAccessToken(token.cluestrToken);

  // Warning: in some cases, delta can be very long to generate.
  retrieve.delta(token.dropboxTokens, token.cursor, function(err, files) {
    if(err) {
      return cb(err);
    }

    // Build an array of tasks to feed onto the queue.
    var createTasks = files.files.map(function(path) {
      return {
        path: path,
        dropboxTokens: token.dropboxTokens,
        cluestrClient: cluestr,
        accessToken: token.cluestrToken,
      };
    });
    createQueue.push(createTasks);

    var deleteTasks = files.deletedFiles.map(function(path) {
      return {
        path: path,
        dropboxTokens: token.dropboxTokens,
        cluestrClient: cluestr
      };
    });
    deleteQueue.push(deleteTasks);

    // Warning: we put the final callback on fileQueue, as deleteFileQueue is assumed to be faster to empty.
    // In some edge cases however, the final cb() will be called but deleteFileQueue will still be processing. This has no incidence whatsoever unless you're polling far too quickly.
    createQueue.drain = function() {
      //TODO: uncomment.
      //token.cursor = cursor;
      token.save(function(err) {
        if(err) {
          return cb(err);
        }

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


<commit_before>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var utils = require('../../util/utils');
var sioClient = require('socket.io-client');
var Tracer = require('../../util/tracer');
var DEFAULT_INTERVAL = 50;

var MailBox = function(server, opts) {
  EventEmitter.call(this);
  this.id = server.id;
  this.host = server.host;
  this.port = server.port;
  this.requests = {};
  this.curId = 0;
  this.queue = [];
  this.bufferMsg = opts.bufferMsg;
  this.interval = opts.interval || DEFAULT_INTERVAL;
  this.connected = false;
  this.closed = false;
  this.opts = opts;
};
util.inherits(MailBox, EventEmitter);

var  pro = MailBox.prototype;

pro.connect = function(tracer, cb) {
  tracer.info('client', __filename, 'connect', 'ws-mailbox try to connect');
  if(this.connected) {
    tracer.error('client', __filename, 'connect', 'mailbox has already connected');
    utils.invokeCallback(cb, new Error('mailbox has already connected.'));
    return;
  }

  this.socket = sioClient.connect(this.host + ':' + this.port, {'force new connection': true, 'reconnect': false});

  var self = this;
  this.socket.on('message', function(pkg) {
    try {
      if(pkg instanceof Array) {
        processMsgs(self, pkg);
      } else {
        processMsg(self, pkg);
      }
    } catch(e) {
      // socket.io would broke if not catch the exception
    }
  });

  this.socket.on('connect', function() {
    if(self.connected) {
      //ignore reconnect
      return;
    }
    // success to connect
    self.connected = true;
    if(self.bufferMsg) {
      // start flush interval
      self._interval = setInterval(function() {
        flush(self);
      }, self.interval);
    }
    utils.invokeCallback(cb);
  });

  this.socket.on('error', function(err) {
    utils.invokeCallback(cb, err);
  });

  this.socket.on('disconnect', function(reason) {
    var reqs = self.requests, cb;
    for(var id in reqs) {
      cb = reqs[id];
      utils.invokeCallback(cb, new Error('disconnect with remote server.'));
    }
    self.emit('close', self.id);
  });
};

/**
 * close mailbox
 */
pro.close = function() {
  if(this.closed) {
    return;
  }
  this.closed = true;
  if(this._interval) {
    clearInterval(this._interval);
    this._interval = null;
  }
  this.socket.disconnect();
};

/**
 * send message to remote server
 *
 * @param msg {service:"", method:"", args:[]}
 * @param opts {} attach info to send method
 * @param cb declaration decided by remote interface
 */
pro.send = function(tracer, msg, opts, cb) {
  tracer.info('client', __filename, 'send', 'ws-mailbox try to send');
  if(!this.connected) {
    tracer.error('client', __filename, 'send', 'ws-mailbox not init');
    utils.invokeCallback(cb, tracer, new Error('not init.'));
    return;
  }

  if(this.closed) {
    tracer.error('client', __filename, 'send', 'mailbox alread closed');
    utils.invokeCallback(cb, tracer, new Error('mailbox alread closed.'));
    return;
  }

  var id = this.curId++;
  this.requests[id] = cb;

  var pkg;
  if(tracer.isEnabled) {
    pkg = {traceId: tracer.id, seqId: tracer.seq, source: tracer.source, remote: tracer.remote, id: id, msg: msg};
  }
  else {
    pkg = {id: id, msg: msg};
  }
  if(this.bufferMsg) {
    enqueue(this, pkg);
  } else {
    this.socket.emit('message', pkg);
  }
};

var enqueue = function(mailbox, msg) {
  mailbox.queue.push(msg);
};

var flush = function(mailbox) {
  if(mailbox.closed || !mailbox.queue.length) {
    return;
  }
  mailbox.socket.emit('message', mailbox.queue);
  mailbox.queue = [];
};

var processMsgs = function(mailbox, pkgs) {
  for(var i=0, l=pkgs.length; i<l; i++) {
    processMsg(mailbox, pkgs[i]);
  }
};

var processMsg = function(mailbox, pkg) {
  var cb = mailbox.requests[pkg.id];
  delete mailbox.requests[pkg.id];

  if(!cb) {
    return;
  }

  var tracer = new Tracer(mailbox.opts.rpcLogger, mailbox.opts.rpcDebugLog, mailbox.opts.clientId, pkg.source, pkg.resp, pkg.traceId, pkg.seqId);
  var args = [tracer, null];

  pkg.resp.forEach(function(arg){
    args.push(arg);
  });

  cb.apply(null, args);
};

/**
 * Factory method to create mailbox
 *
 * @param {Object} server remote server info {id:"", host:"", port:""}
 * @param {Object} opts construct parameters
 *                      opts.bufferMsg {Boolean} msg should be buffered or send immediately.
 *                      opts.interval {Boolean} msg queue flush interval if bufferMsg is true. default is 50 ms
 */
module.exports.create = function(server, opts) {
  return new MailBox(server, opts || {});
};
<commit_msg>add rpc log<commit_after>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var utils = require('../../util/utils');
var sioClient = require('socket.io-client');
var Tracer = require('../../util/tracer');
var DEFAULT_INTERVAL = 50;

var MailBox = function(server, opts) {
  EventEmitter.call(this);
  this.id = server.id;
  this.host = server.host;
  this.port = server.port;
  this.requests = {};
  this.curId = 0;
  this.queue = [];
  this.bufferMsg = opts.bufferMsg;
  this.interval = opts.interval || DEFAULT_INTERVAL;
  this.connected = false;
  this.closed = false;
  this.opts = opts;
};
util.inherits(MailBox, EventEmitter);

var  pro = MailBox.prototype;

pro.connect = function(tracer, cb) {
  tracer.info('client', __filename, 'connect', 'ws-mailbox try to connect');
  if(this.connected) {
    tracer.error('client', __filename, 'connect', 'mailbox has already connected');
    utils.invokeCallback(cb, new Error('mailbox has already connected.'));
    return;
  }

  this.socket = sioClient.connect(this.host + ':' + this.port, {'force new connection': true, 'reconnect': false});

  var self = this;
  this.socket.on('message', function(pkg) {
    try {
      if(pkg instanceof Array) {
        processMsgs(self, pkg);
      } else {
        processMsg(self, pkg);
      }
    } catch(e) {
      console.error('rpc client process message with error: %j', e.stack);
    }
  });

  this.socket.on('connect', function() {
    if(self.connected) {
      //ignore reconnect
      return;
    }
    // success to connect
    self.connected = true;
    if(self.bufferMsg) {
      // start flush interval
      self._interval = setInterval(function() {
        flush(self);
      }, self.interval);
    }
    utils.invokeCallback(cb);
  });

  this.socket.on('error', function(err) {
    utils.invokeCallback(cb, err);
  });

  this.socket.on('disconnect', function(reason) {
    var reqs = self.requests, cb;
    for(var id in reqs) {
      cb = reqs[id];
      utils.invokeCallback(cb, new Error('disconnect with remote server.'));
    }
    self.emit('close', self.id);
  });
};

/**
 * close mailbox
 */
pro.close = function() {
  if(this.closed) {
    return;
  }
  this.closed = true;
  if(this._interval) {
    clearInterval(this._interval);
    this._interval = null;
  }
  this.socket.disconnect();
};

/**
 * send message to remote server
 *
 * @param msg {service:"", method:"", args:[]}
 * @param opts {} attach info to send method
 * @param cb declaration decided by remote interface
 */
pro.send = function(tracer, msg, opts, cb) {
  tracer.info('client', __filename, 'send', 'ws-mailbox try to send');
  if(!this.connected) {
    tracer.error('client', __filename, 'send', 'ws-mailbox not init');
    utils.invokeCallback(cb, tracer, new Error('not init.'));
    return;
  }

  if(this.closed) {
    tracer.error('client', __filename, 'send', 'mailbox alread closed');
    utils.invokeCallback(cb, tracer, new Error('mailbox alread closed.'));
    return;
  }

  var id = this.curId++;
  this.requests[id] = cb;

  var pkg;
  if(tracer.isEnabled) {
    pkg = {traceId: tracer.id, seqId: tracer.seq, source: tracer.source, remote: tracer.remote, id: id, msg: msg};
  }
  else {
    pkg = {id: id, msg: msg};
  }
  if(this.bufferMsg) {
    enqueue(this, pkg);
  } else {
    this.socket.emit('message', pkg);
  }
};

var enqueue = function(mailbox, msg) {
  mailbox.queue.push(msg);
};

var flush = function(mailbox) {
  if(mailbox.closed || !mailbox.queue.length) {
    return;
  }
  mailbox.socket.emit('message', mailbox.queue);
  mailbox.queue = [];
};

var processMsgs = function(mailbox, pkgs) {
  for(var i=0, l=pkgs.length; i<l; i++) {
    processMsg(mailbox, pkgs[i]);
  }
};

var processMsg = function(mailbox, pkg) {
  var cb = mailbox.requests[pkg.id];
  delete mailbox.requests[pkg.id];

  if(!cb) {
    return;
  }

  var tracer = new Tracer(mailbox.opts.rpcLogger, mailbox.opts.rpcDebugLog, mailbox.opts.clientId, pkg.source, pkg.resp, pkg.traceId, pkg.seqId);
  var args = [tracer, null];

  pkg.resp.forEach(function(arg){
    args.push(arg);
  });

  cb.apply(null, args);
};

/**
 * Factory method to create mailbox
 *
 * @param {Object} server remote server info {id:"", host:"", port:""}
 * @param {Object} opts construct parameters
 *                      opts.bufferMsg {Boolean} msg should be buffered or send immediately.
 *                      opts.interval {Boolean} msg queue flush interval if bufferMsg is true. default is 50 ms
 */
module.exports.create = function(server, opts) {
  return new MailBox(server, opts || {});
};
<|endoftext|>


<commit_before>var _ = require('lodash'),
    uuid = require('uuid'),
    async = require('async'),

    util = require('../util'),
    sdk = require('postman-collection'),
    sandbox = require('postman-sandbox'),
    serialisedError = require('serialised-error'),

    ASSERTION_FAILURE = 'AssertionFailure',
    SAFE_CONTEXT_VARIABLES = ['environment', 'globals', 'cookies', 'data', 'request', 'response'],

    postProcessContext = function (execution, failures) { // function determines whether the event needs to abort
        var tests = execution && execution.tests,
            error;

        _.forOwn(tests, function (result, test) {
            !result && (failures || (failures = [])).push(test);
        });

        if (failures && failures.length) {
            error = new Error(failures.join(', '));
            error.name = ASSERTION_FAILURE;
        }
        return error ? serialisedError(error, true) : undefined;
    };

/**
 * Script execution extenion of the runner.
 * This module exposes processors for executing scripts before and after requests. Essentially, the processors are
 * itself not aware of other processors and simply allow running of a script and then queue a procesor as defined in
 * payload.
 *
 * Adds options
 * - suppressEventPropagation:Boolean [true]
 * - stopOnScriptError:Boolean [false]
 * - host:Object [undefined]
 */
module.exports = {
    init: function (done) {
        var run = this;

        // if this run object already has a host, we do not need to create one.
        if (run.host) {
            return done();
        }

        // @todo - remove this when chrome app and electron host creation is offloaded to runner
        // @todo - can this be removed now in runtime v4?
        if (run.options.host && run.options.host.external === true) {
            run.host = run.options.host.instance;
            return done();
        }

        sandbox.createContext(_.merge({
            // debug: true
        }, run.options.host), function (err, context) {
            if (err) { return done(err); }
            // store the host in run object for future use and move on
            run.host = context;

            context.on('console', function () {
                run.triggers.console.apply(run.triggers, arguments);
            });

            context.on('error', function () {
                run.triggers.error.apply(run.triggers, arguments);
            });

            context.on('execution.error', function () {
                run.triggers.exception.apply(run.triggers, arguments);
            });

            context.on('execution.assertion', function () {
                run.triggers.assertion.apply(run.triggers, arguments);
            });

            done();
        });
    },

    /**
     * This lists the name of the events that the script processors are likely to trigger
     *
     * @type {Array}
     */
    triggers: ['beforeScript', 'script', 'assertion', 'exception', 'console'],

    process: {
        /**
         * This processors job is to do the following:
         * - trigger event by its name
         * - execute all scripts that the event listens to and return execution results
         *
         * @param {Object} payload
         * @param {String} payload.name
         * @param {Item} payload.item
         * @param {Object} [payload.context]
         * @param {Cursor} [payload.coords]
         * @param {Array.<String>} [payload.trackContext]
         * @param {Boolean} [payload.stopOnScriptError] - if set to true, then a synchronous error encountered during
         * execution of a script will stop executing any further scripts
         * @param {Boolean} [payload.abortOnFailure]
         * @param {Boolean} [payload.stopOnFailure]
         * @param {Function} next
         *
         * @note - in order to raise trigger for the entire event, ensure your extension has registered the triggers
         */
        event: function (payload, next) {
            var suppressEventPropagation = _.has(this.options, 'suppressEventPropagation') ?
                    this.options.suppressEventPropagation : true,
                item = payload.item,
                eventName = payload.name,
                cursor = payload.coords,
                // the payload can have a list of variables to track from the context post execution, ensure that
                // those are accurately set
                track = _.isArray(payload.trackContext) && _.isObject(payload.context) &&
                    // ensure that only those variables that are defined in the context are synced
                    payload.trackContext.filter(function (variable) {
                        return _.isObject(payload.context[variable]);
                    }),
                stopOnScriptError = (_.has(payload, 'stopOnScriptError') ? payload.stopOnScriptError :
                    this.options.stopOnScriptError),
                abortOnError = (_.has(payload, 'abortOnError') ? payload.abortOnError : this.options.abortOnError),

                // @todo: find a better home for this option processing
                abortOnFailure = payload.abortOnFailure,
                stopOnFailure = payload.stopOnFailure,

                events;

            // @todo: find a better place to code this so that event is not aware of such options
            if (abortOnFailure) {
                abortOnError = true;
            }

            // validate the payload
            if (!eventName) {
                return next(new Error('runner.extension~events: event payload is missing the event name.'));
            }
            if (!item) {
                return next(new Error('runner.extension~events: event payload is missing the triggered item.'));
            }

            // get the list of events to be executed. note that based on the `suppressEventPropagation` option, use
            // all inherited events or own events only
            events = suppressEventPropagation ? item.events.listenersOwn(eventName) : item.events.listeners(eventName);

            // call the "before" event trigger by its event name.
            // at this point, the one who queued this event, must ensure that the trigger for it is defined in its
            // 'trigger' interface
            this.triggers[_.camelCase('before-' + eventName)](null, cursor, events, item);

            // with all the event listeners in place, we now iterate on them and execute its scripts. post execution,
            // we accumulate the results in order to be passed on to the event callback trigger.
            async.mapSeries(events, function (event, next) {
                // in case the event has no script we bail out early
                if (!event.script) {
                    return next(null, {event: event});
                }

                // get access to the script from the event.
                var script = event.script,
                    executionId = uuid(),
                    assertionFailed = [];

                // store the execution id in script
                script._lastExecutionId = executionId; // please don't use it anywhere else!

                // trigger the "beforeScript" callback
                this.triggers.beforeScript(null, cursor, script, event, item);

                // add event listener to trap all assertion events, but only if needed. to avoid needlessly accumulate
                // stuff in memory.
                (abortOnFailure || stopOnFailure) &&
                    this.host.on('execution.assertion.' + executionId, function (cursor, assertion) {
                        !assertion.passed && assertionFailed.push(assertion.name);
                    });

                this.host.on('execution.request.' + executionId, function (cursor, id, requestId, request) {
                    // clone cursor and add source
                    var cursorWithSource = _.clone(cursor),
                        tempItem = new sdk.Item({
                            request: request
                        });

                    tempItem.setParent(item);
                    cursorWithSource.source = 'script'; // @todo - get script type from the sandbox

                    this.immediate('request', {
                        item: tempItem,
                        globals: payload.context.globals,
                        environment: payload.context.environment,
                        data: payload.context.data,
                        coords: cursorWithSource,
                        // abortOnError is set to true to make sure
                        // request command bubbles errors so we can pass it on to the callback
                        abortOnError: true
                    }).done(function (result) {
                        this.host.dispatch('execution.response.' + id, requestId, null, result && result.response);
                    }).catch(function (err) {
                        this.host.dispatch('execution.response.' + id, requestId, err);
                    });
                }.bind(this));

                // finally execute the script
                this.host.execute(event, {
                    id: executionId,
                    // debug: true,
                    timeout: payload.scriptTimeout,
                    cursor: cursor,
                    context: _.pick(payload.context, SAFE_CONTEXT_VARIABLES),

                    // legacy options
                    legacy: {
                        _itemId: item.id,
                        _itemName: item.name
                    }
                }, function (err, result) {
                    this.host.removeAllListeners('execution.request.' + executionId);
                    this.host.removeAllListeners('execution.assertion.' + executionId);
                    this.host.removeAllListeners('execution.error.' + executionId);

                    // electron IPC does not bubble errors to the browser process, so we serialize it here.
                    err && (err = serialisedError(err, true));

                    // if it is defined that certain variables are to be synced back to result, we do the same
                    track && result && track.forEach(function (variable) {
                        if (!(_.isObject(result[variable]) && payload.context[variable])) { return; }

                        // ensure that variablescope is treated accordingly
                        // @todo find a better way to not sync entire scope, but receive changes and update the existing
                        // scope using that
                        if (_.isFunction(payload.context[variable].syncVariablesFrom)) {
                            payload.context[variable].clear();
                            _.forEach(result[variable].values, function (def) {
                                payload.context[variable].values.add(def);
                            });
                        }
                        else {
                            util.syncObject(payload.context[variable], result[variable]);
                        }
                    });

                    // Get the failures. If there was an error running the script itself, that takes precedence
                    if (!err && (abortOnFailure || stopOnFailure)) {
                        err = postProcessContext(result, assertionFailed); // also use async assertions
                    }

                    // Ensure that we have SDK instances, not serialized plain objects.
                    // @todo - should this be handled by the sandbox?
                    result && result.environment && (result.environment = new sdk.VariableScope(result.environment));
                    result && result.globals && (result.globals = new sdk.VariableScope(result.globals));
                    result && result.request && (result.request = new sdk.Request(result.request));
                    result && result.response && (result.response = new sdk.Response(result.response));

                    // now that this script is done executing, we trigger the event and move to the next script
                    this.triggers.script(err || null, cursor, result, script, event, item);

                    // move to next script and pass on the results for accumulation
                    next(((stopOnScriptError || abortOnError || stopOnFailure) && err) ? err : null, _.assign({
                        event: event,
                        script: script,
                        result: result
                    }, err && {error: err})); // we use assign here to avoid needless error property
                }.bind(this));

            }.bind(this), function (err, results) {
                // trigger the event completion callback
                this.triggers[eventName](null, cursor, results, item);
                next((abortOnError && err) ? err : null, results, err);
            }.bind(this));
        }
    }
};
<commit_msg>Move event names as constants to the top<commit_after>var _ = require('lodash'),
    uuid = require('uuid'),
    async = require('async'),

    util = require('../util'),
    sdk = require('postman-collection'),
    sandbox = require('postman-sandbox'),
    serialisedError = require('serialised-error'),

    ASSERTION_FAILURE = 'AssertionFailure',
    SAFE_CONTEXT_VARIABLES = ['environment', 'globals', 'cookies', 'data', 'request', 'response'],

    EXECUTION_REQUEST_EVENT_BASE = 'execution.request.',
    EXECUTION_RESPONSE_EVENT_BASE = 'execution.response.',
    EXECUTION_ASSERTION_EVENT_BASE = 'execution.assertion.',
    EXECUTION_ERROR_EVENT_BASE = 'execution.error.',

    postProcessContext = function (execution, failures) { // function determines whether the event needs to abort
        var tests = execution && execution.tests,
            error;

        _.forOwn(tests, function (result, test) {
            !result && (failures || (failures = [])).push(test);
        });

        if (failures && failures.length) {
            error = new Error(failures.join(', '));
            error.name = ASSERTION_FAILURE;
        }
        return error ? serialisedError(error, true) : undefined;
    };

/**
 * Script execution extenion of the runner.
 * This module exposes processors for executing scripts before and after requests. Essentially, the processors are
 * itself not aware of other processors and simply allow running of a script and then queue a procesor as defined in
 * payload.
 *
 * Adds options
 * - suppressEventPropagation:Boolean [true]
 * - stopOnScriptError:Boolean [false]
 * - host:Object [undefined]
 */
module.exports = {
    init: function (done) {
        var run = this;

        // if this run object already has a host, we do not need to create one.
        if (run.host) {
            return done();
        }

        // @todo - remove this when chrome app and electron host creation is offloaded to runner
        // @todo - can this be removed now in runtime v4?
        if (run.options.host && run.options.host.external === true) {
            run.host = run.options.host.instance;
            return done();
        }

        sandbox.createContext(_.merge({
            // debug: true
        }, run.options.host), function (err, context) {
            if (err) { return done(err); }
            // store the host in run object for future use and move on
            run.host = context;

            context.on('console', function () {
                run.triggers.console.apply(run.triggers, arguments);
            });

            context.on('error', function () {
                run.triggers.error.apply(run.triggers, arguments);
            });

            context.on('execution.error', function () {
                run.triggers.exception.apply(run.triggers, arguments);
            });

            context.on('execution.assertion', function () {
                run.triggers.assertion.apply(run.triggers, arguments);
            });

            done();
        });
    },

    /**
     * This lists the name of the events that the script processors are likely to trigger
     *
     * @type {Array}
     */
    triggers: ['beforeScript', 'script', 'assertion', 'exception', 'console'],

    process: {
        /**
         * This processors job is to do the following:
         * - trigger event by its name
         * - execute all scripts that the event listens to and return execution results
         *
         * @param {Object} payload
         * @param {String} payload.name
         * @param {Item} payload.item
         * @param {Object} [payload.context]
         * @param {Cursor} [payload.coords]
         * @param {Array.<String>} [payload.trackContext]
         * @param {Boolean} [payload.stopOnScriptError] - if set to true, then a synchronous error encountered during
         * execution of a script will stop executing any further scripts
         * @param {Boolean} [payload.abortOnFailure]
         * @param {Boolean} [payload.stopOnFailure]
         * @param {Function} next
         *
         * @note - in order to raise trigger for the entire event, ensure your extension has registered the triggers
         */
        event: function (payload, next) {
            var suppressEventPropagation = _.has(this.options, 'suppressEventPropagation') ?
                    this.options.suppressEventPropagation : true,
                item = payload.item,
                eventName = payload.name,
                cursor = payload.coords,
                // the payload can have a list of variables to track from the context post execution, ensure that
                // those are accurately set
                track = _.isArray(payload.trackContext) && _.isObject(payload.context) &&
                    // ensure that only those variables that are defined in the context are synced
                    payload.trackContext.filter(function (variable) {
                        return _.isObject(payload.context[variable]);
                    }),
                stopOnScriptError = (_.has(payload, 'stopOnScriptError') ? payload.stopOnScriptError :
                    this.options.stopOnScriptError),
                abortOnError = (_.has(payload, 'abortOnError') ? payload.abortOnError : this.options.abortOnError),

                // @todo: find a better home for this option processing
                abortOnFailure = payload.abortOnFailure,
                stopOnFailure = payload.stopOnFailure,

                events;

            // @todo: find a better place to code this so that event is not aware of such options
            if (abortOnFailure) {
                abortOnError = true;
            }

            // validate the payload
            if (!eventName) {
                return next(new Error('runner.extension~events: event payload is missing the event name.'));
            }
            if (!item) {
                return next(new Error('runner.extension~events: event payload is missing the triggered item.'));
            }

            // get the list of events to be executed. note that based on the `suppressEventPropagation` option, use
            // all inherited events or own events only
            events = suppressEventPropagation ? item.events.listenersOwn(eventName) : item.events.listeners(eventName);

            // call the "before" event trigger by its event name.
            // at this point, the one who queued this event, must ensure that the trigger for it is defined in its
            // 'trigger' interface
            this.triggers[_.camelCase('before-' + eventName)](null, cursor, events, item);

            // with all the event listeners in place, we now iterate on them and execute its scripts. post execution,
            // we accumulate the results in order to be passed on to the event callback trigger.
            async.mapSeries(events, function (event, next) {
                // in case the event has no script we bail out early
                if (!event.script) {
                    return next(null, {event: event});
                }

                // get access to the script from the event.
                var script = event.script,
                    executionId = uuid(),
                    assertionFailed = [];

                // store the execution id in script
                script._lastExecutionId = executionId; // please don't use it anywhere else!

                // trigger the "beforeScript" callback
                this.triggers.beforeScript(null, cursor, script, event, item);

                // add event listener to trap all assertion events, but only if needed. to avoid needlessly accumulate
                // stuff in memory.
                (abortOnFailure || stopOnFailure) &&
                    this.host.on(EXECUTION_ASSERTION_EVENT_BASE + executionId, function (cursor, assertion) {
                        !assertion.passed && assertionFailed.push(assertion.name);
                    });

                this.host.on(EXECUTION_REQUEST_EVENT_BASE + executionId, function (cursor, id, requestId, request) {
                    // clone cursor and add source
                    var cursorWithSource = _.clone(cursor),
                        tempItem = new sdk.Item({
                            request: request
                        });

                    tempItem.setParent(item);
                    cursorWithSource.source = 'script'; // @todo - get script type from the sandbox

                    this.immediate('request', {
                        item: tempItem,
                        globals: payload.context.globals,
                        environment: payload.context.environment,
                        data: payload.context.data,
                        coords: cursorWithSource,
                        // abortOnError is set to true to make sure
                        // request command bubbles errors so we can pass it on to the callback
                        abortOnError: true
                    }).done(function (result) {
                        this.host.dispatch(
                            EXECUTION_RESPONSE_EVENT_BASE + id,
                            requestId, null,
                            result && result.response
                        );
                    }).catch(function (err) {
                        this.host.dispatch(EXECUTION_RESPONSE_EVENT_BASE + id, requestId, err);
                    });
                }.bind(this));

                // finally execute the script
                this.host.execute(event, {
                    id: executionId,
                    // debug: true,
                    timeout: payload.scriptTimeout,
                    cursor: cursor,
                    context: _.pick(payload.context, SAFE_CONTEXT_VARIABLES),

                    // legacy options
                    legacy: {
                        _itemId: item.id,
                        _itemName: item.name
                    }
                }, function (err, result) {
                    this.host.removeAllListeners(EXECUTION_REQUEST_EVENT_BASE + executionId);
                    this.host.removeAllListeners(EXECUTION_ASSERTION_EVENT_BASE + executionId);
                    this.host.removeAllListeners(EXECUTION_ERROR_EVENT_BASE + executionId);

                    // electron IPC does not bubble errors to the browser process, so we serialize it here.
                    err && (err = serialisedError(err, true));

                    // if it is defined that certain variables are to be synced back to result, we do the same
                    track && result && track.forEach(function (variable) {
                        if (!(_.isObject(result[variable]) && payload.context[variable])) { return; }

                        // ensure that variablescope is treated accordingly
                        // @todo find a better way to not sync entire scope, but receive changes and update the existing
                        // scope using that
                        if (_.isFunction(payload.context[variable].syncVariablesFrom)) {
                            payload.context[variable].clear();
                            _.forEach(result[variable].values, function (def) {
                                payload.context[variable].values.add(def);
                            });
                        }
                        else {
                            util.syncObject(payload.context[variable], result[variable]);
                        }
                    });

                    // Get the failures. If there was an error running the script itself, that takes precedence
                    if (!err && (abortOnFailure || stopOnFailure)) {
                        err = postProcessContext(result, assertionFailed); // also use async assertions
                    }

                    // Ensure that we have SDK instances, not serialized plain objects.
                    // @todo - should this be handled by the sandbox?
                    result && result.environment && (result.environment = new sdk.VariableScope(result.environment));
                    result && result.globals && (result.globals = new sdk.VariableScope(result.globals));
                    result && result.request && (result.request = new sdk.Request(result.request));
                    result && result.response && (result.response = new sdk.Response(result.response));

                    // now that this script is done executing, we trigger the event and move to the next script
                    this.triggers.script(err || null, cursor, result, script, event, item);

                    // move to next script and pass on the results for accumulation
                    next(((stopOnScriptError || abortOnError || stopOnFailure) && err) ? err : null, _.assign({
                        event: event,
                        script: script,
                        result: result
                    }, err && {error: err})); // we use assign here to avoid needless error property
                }.bind(this));

            }.bind(this), function (err, results) {
                // trigger the event completion callback
                this.triggers[eventName](null, cursor, results, item);
                next((abortOnError && err) ? err : null, results, err);
            }.bind(this));
        }
    }
};
<|endoftext|>


<commit_before>function CrocCheckbox(root, tr, t, tl, l, r, bl, b, br, bkg, unchecked) {
	CrocBase.call(this, root);

	tr = tr || root.themer.getValue(arguments.callee, "tr");
	t = t || root.themer.getValue(arguments.callee, "t");
	tl = tl || root.themer.getValue(arguments.callee, "tl");
	l = l || root.themer.getValue(arguments.callee, "l");
	r = r || root.themer.getValue(arguments.callee, "r");
	bl = bl || root.themer.getValue(arguments.callee, "bl");
	b = b || root.themer.getValue(arguments.callee, "b");
	br = br || root.themer.getValue(arguments.callee, "br");
	bkg = bkg || root.themer.getValue(arguments.callee, "bkg");

	unchecked = unchecked || root.themer.getValue(arguments.callee, "unchecked");

	this.value = false;

	this.border = new CrocPanelBorder(root, tl, t, tr, l, r, bl, b, br, bkg);
	this.uncheckedImage = new CrocImageSimple(root, unchecked);

	this.addEventListener('pointermove', function(e){
		this.getRoot().setCursor("pointer");

		return false;
	});

	this.addEventListener('pointerleave', function(e) {

		if(!this.hasFocus()) {
			this.setMode('normal');
		}

		this.getRoot().setCursor("");

		return false;
	});

	this.addEventListener('pointerdown', function(e) {
		this.focus();

		this.setValue(!this.getValue());

		this.event('valuechanged', this.getValue());

		this.setMode('focus');
	});

	this.addEventListener('pointerup', function(e) {
		this.blur();
		this.setMode('hover');
	});

};

//We inherit everything from CrocBase
CrocCheckbox.prototype = Object.create(CrocBase.prototype);
CrocCheckbox.prototype.constructor = CrocCheckbox;

CrocCheckbox.prototype.getValue = function() {
	return this.value;
};

CrocCheckbox.prototype.setMode = function(mode) {
// 	this.mode = mode;
// 	this.getRoot().repaint();
};

CrocCheckbox.prototype.setValue = function(value) {
	this.value = (value == true);
	this.getRoot().repaint();
};

CrocCheckbox.prototype.getWidth = function () {
	return this.border.getWidth();
};

CrocCheckbox.prototype.getHeight = function() {
	return this.border.getHeight();
};

CrocCheckbox.prototype.paint = function(context, width, height) {
	CrocBase.prototype.paint.call(this, context, width, height);

	context.save();

	var currentBorder = this.border;

	var tlw = currentBorder.topLeftImage.getWidth();
	var tlh = currentBorder.topLeftImage.getHeight();
	var brw = currentBorder.bottomRightImage.getWidth();
	var brh = currentBorder.bottomLeftImage.getHeight();

	currentBorder.paint(context, tlw + brw + this.uncheckedImage.getWidth(),  brh + tlh + this.uncheckedImage.getHeight());

	if(!this.getValue()) {
		context.translate(tlw, tlh);
		this.uncheckedImage.paint(context);
	}

	context.restore();

	return;
}
<commit_msg>Making the CrocCheckbox obey the visible flag.<commit_after>function CrocCheckbox(root, tr, t, tl, l, r, bl, b, br, bkg, unchecked) {
	CrocBase.call(this, root);

	tr = tr || root.themer.getValue(arguments.callee, "tr");
	t = t || root.themer.getValue(arguments.callee, "t");
	tl = tl || root.themer.getValue(arguments.callee, "tl");
	l = l || root.themer.getValue(arguments.callee, "l");
	r = r || root.themer.getValue(arguments.callee, "r");
	bl = bl || root.themer.getValue(arguments.callee, "bl");
	b = b || root.themer.getValue(arguments.callee, "b");
	br = br || root.themer.getValue(arguments.callee, "br");
	bkg = bkg || root.themer.getValue(arguments.callee, "bkg");

	unchecked = unchecked || root.themer.getValue(arguments.callee, "unchecked");

	this.value = false;

	this.border = new CrocPanelBorder(root, tl, t, tr, l, r, bl, b, br, bkg);
	this.uncheckedImage = new CrocImageSimple(root, unchecked);

	this.addEventListener('pointermove', function(e){
		this.getRoot().setCursor("pointer");

		return false;
	});

	this.addEventListener('pointerleave', function(e) {

		if(!this.hasFocus()) {
			this.setMode('normal');
		}

		this.getRoot().setCursor("");

		return false;
	});

	this.addEventListener('pointerdown', function(e) {
		this.focus();

		this.setValue(!this.getValue());

		this.event('valuechanged', this.getValue());

		this.setMode('focus');
	});

	this.addEventListener('pointerup', function(e) {
		this.blur();
		this.setMode('hover');
	});

};

//We inherit everything from CrocBase
CrocCheckbox.prototype = Object.create(CrocBase.prototype);
CrocCheckbox.prototype.constructor = CrocCheckbox;

CrocCheckbox.prototype.getValue = function() {
	return this.value;
};

CrocCheckbox.prototype.setMode = function(mode) {
// 	this.mode = mode;
// 	this.getRoot().repaint();
};

CrocCheckbox.prototype.setValue = function(value) {
	this.value = (value == true);
	this.getRoot().repaint();
};

CrocCheckbox.prototype.getWidth = function () {
	return this.border.getWidth();
};

CrocCheckbox.prototype.getHeight = function() {
	return this.border.getHeight();
};

CrocCheckbox.prototype.paint = function(context, width, height) {
	CrocBase.prototype.paint.call(this, context, width, height);

	if(!this.visible) {
		return;
	}

	context.save();

	var currentBorder = this.border;

	var tlw = currentBorder.topLeftImage.getWidth();
	var tlh = currentBorder.topLeftImage.getHeight();
	var brw = currentBorder.bottomRightImage.getWidth();
	var brh = currentBorder.bottomLeftImage.getHeight();

	currentBorder.paint(context, tlw + brw + this.uncheckedImage.getWidth(),  brh + tlh + this.uncheckedImage.getHeight());

	if(!this.getValue()) {
		context.translate(tlw, tlh);
		this.uncheckedImage.paint(context);
	}

	context.restore();

	return;
}
<|endoftext|>


<commit_before>const { logger } = require('../../logger');
const { appName } = require('../../config/app-strings');

module.exports = {
  ensureMasterIssue,
};

function getListItem(branch, type, pr) {
  let item = ' - [ ] ';
  item += `<!-- ${type}-branch=${branch.branchName} -->`;
  if (pr) {
    item += `[${branch.prTitle}](../pull/${pr.number})`;
  } else {
    item += branch.prTitle;
  }
  const uniquePackages = [
    ...new Set(branch.upgrades.map(upgrade => '`' + upgrade.depName + '`')),
  ];
  if (uniquePackages.length < 2) {
    return item + '\n';
  }
  return item + ' (' + uniquePackages.join(', ') + ')\n';
}

async function ensureMasterIssue(config, branches) {
  if (
    !(
      config.masterIssue ||
      branches.some(
        branch => branch.masterIssueApproval || branch.masterIssuePrApproval
      )
    )
  ) {
    return;
  }
  logger.info('Ensuring master issue');
  if (
    !branches.length ||
    branches.every(branch => branch.res === 'automerged')
  ) {
    if (config.masterIssueAutoclose) {
      logger.debug('Closing master issue');
      if (config.dryRun) {
        logger.info(
          'DRY-RUN: Would close Master Issue ' + config.masterIssueTitle
        );
      } else {
        await platform.ensureIssueClosing(config.masterIssueTitle);
      }
      return;
    }
    if (config.dryRun) {
      logger.info(
        'DRY-RUN: Would ensure Master Issue ' + config.masterIssueTitle
      );
    } else {
      await platform.ensureIssue(
        config.masterIssueTitle,
        'This repository is up-to-date and has no outstanding updates open or pending.'
      );
    }
    return;
  }
  let issueBody = `This [master issue](https://renovatebot.com/blog/master-issue) contains a list of ${appName} updates and their statuses.\n\n`;
  const pendingApprovals = branches.filter(
    branch => branch.res === 'needs-approval'
  );
  if (pendingApprovals.length) {
    issueBody += '## Pending Approval\n\n';
    issueBody += `These branches will be created by ${appName} only once you click their checkbox below.\n\n`;
    for (const branch of pendingApprovals) {
      issueBody += getListItem(branch, 'approve');
    }
    issueBody += '\n';
  }
  const awaitingSchedule = branches.filter(
    branch => branch.res === 'not-scheduled'
  );
  if (awaitingSchedule.length) {
    issueBody += '## Awaiting Schedule\n\n';
    issueBody +=
      'These updates are awaiting their schedule. Click on a checkbox to ignore the schedule.\n';
    for (const branch of awaitingSchedule) {
      issueBody += getListItem(branch, 'unschedule');
    }
    issueBody += '\n';
  }
  const rateLimited = branches.filter(
    branch => branch.res && branch.res.endsWith('pr-hourly-limit-reached')
  );
  if (rateLimited.length) {
    issueBody += '## Rate Limited\n\n';
    issueBody +=
      'These updates are currently rate limited. Click on a checkbox below to force their creation now.\n\n';
    for (const branch of rateLimited) {
      issueBody += getListItem(branch, 'unlimit');
    }
    issueBody += '\n';
  }
  const errorList = branches.filter(
    branch => branch.res && branch.res.endsWith('error')
  );
  if (errorList.length) {
    issueBody += '## Errored\n\n';
    issueBody +=
      'These updates encountered an error and will be retried. Click a checkbox below to force a retry now.\n\n';
    for (const branch of errorList) {
      issueBody += getListItem(branch, 'retry');
    }
    issueBody += '\n';
  }
  const awaitingPr = branches.filter(
    branch => branch.res === 'needs-pr-approval'
  );
  if (awaitingPr.length) {
    issueBody += '## PR Creation Approval Required\n\n';
    issueBody +=
      "These branches exist but PRs won't be created until you approve by ticking the checkbox.\n\n";
    for (const branch of awaitingPr) {
      issueBody += getListItem(branch, 'approvePr');
    }
    issueBody += '\n';
  }
  const prEdited = branches.filter(branch => branch.res === 'pr-edited');
  if (prEdited.length) {
    issueBody += '## Edited/Blocked\n\n';
    issueBody += `These updates have been manually edited so ${appName} will no longer make changes. To discard all commits and start over, check the box below.\n\n`;
    for (const branch of prEdited) {
      const pr = await platform.getBranchPr(branch.branchName);
      issueBody += getListItem(branch, 'rebase', pr);
    }
    issueBody += '\n';
  }
  const otherRes = [
    'needs-approval',
    'needs-pr-approval',
    'not-scheduled',
    'pr-hourly-limit-reached',
    'already-existed',
    'error',
    'automerged',
    'pr-edited',
  ];
  const inProgress = branches.filter(branch => !otherRes.includes(branch.res));
  if (inProgress.length) {
    issueBody += '## Open\n\n';
    issueBody +=
      'These updates have all been created already. Click a checkbox below to force a retry/rebase of any.\n\n';
    for (const branch of inProgress) {
      const pr = await platform.getBranchPr(branch.branchName);
      issueBody += getListItem(branch, 'rebase', pr);
    }
    if (inProgress.length > 2) {
      issueBody += ' - [ ] ';
      issueBody += '';
      issueBody +=
        '**Check this option to rebase all the above open PRs at once**';
      issueBody += '\n';
    }
    issueBody += '\n';
  }
  const alreadyExisted = branches.filter(
    branch => branch.res && branch.res.endsWith('already-existed')
  );
  if (alreadyExisted.length) {
    issueBody += '## Closed/Ignored\n\n';
    issueBody +=
      'These updates were closed unmerged and will not be recreated unless you click a checkbox below.\n\n';
    for (const branch of alreadyExisted) {
      const pr = await platform.findPr(
        branch.branchName,
        branch.prTitle,
        '!open'
      );
      issueBody += getListItem(branch, 'recreate', pr);
    }
    issueBody += '\n';
  }

  // istanbul ignore if
  if (global.appMode) {
    issueBody +=
      '---\nAdvanced\n\n- [ ] Check this box to trigger a request for Renovate to run again on this repository\n\n\n';
  }

  if (config.dryRun) {
    logger.info(
      'DRY-RUN: Would ensure Master Issue ' + config.masterIssueTitle
    );
  } else {
    await platform.ensureIssue(config.masterIssueTitle, issueBody);
  }
}
<commit_msg>fix(master-issue): add pending section<commit_after>const { logger } = require('../../logger');
const { appName } = require('../../config/app-strings');

module.exports = {
  ensureMasterIssue,
};

function getListItem(branch, type, pr) {
  let item = ' - [ ] ';
  item += `<!-- ${type}-branch=${branch.branchName} -->`;
  if (pr) {
    item += `[${branch.prTitle}](../pull/${pr.number})`;
  } else {
    item += branch.prTitle;
  }
  const uniquePackages = [
    ...new Set(branch.upgrades.map(upgrade => '`' + upgrade.depName + '`')),
  ];
  if (uniquePackages.length < 2) {
    return item + '\n';
  }
  return item + ' (' + uniquePackages.join(', ') + ')\n';
}

async function ensureMasterIssue(config, branches) {
  if (
    !(
      config.masterIssue ||
      branches.some(
        branch => branch.masterIssueApproval || branch.masterIssuePrApproval
      )
    )
  ) {
    return;
  }
  logger.info('Ensuring master issue');
  if (
    !branches.length ||
    branches.every(branch => branch.res === 'automerged')
  ) {
    if (config.masterIssueAutoclose) {
      logger.debug('Closing master issue');
      if (config.dryRun) {
        logger.info(
          'DRY-RUN: Would close Master Issue ' + config.masterIssueTitle
        );
      } else {
        await platform.ensureIssueClosing(config.masterIssueTitle);
      }
      return;
    }
    if (config.dryRun) {
      logger.info(
        'DRY-RUN: Would ensure Master Issue ' + config.masterIssueTitle
      );
    } else {
      await platform.ensureIssue(
        config.masterIssueTitle,
        'This repository is up-to-date and has no outstanding updates open or pending.'
      );
    }
    return;
  }
  let issueBody = `This [master issue](https://renovatebot.com/blog/master-issue) contains a list of ${appName} updates and their statuses.\n\n`;
  const pendingApprovals = branches.filter(
    branch => branch.res === 'needs-approval'
  );
  if (pendingApprovals.length) {
    issueBody += '## Pending Approval\n\n';
    issueBody += `These branches will be created by ${appName} only once you click their checkbox below.\n\n`;
    for (const branch of pendingApprovals) {
      issueBody += getListItem(branch, 'approve');
    }
    issueBody += '\n';
  }
  const awaitingSchedule = branches.filter(
    branch => branch.res === 'not-scheduled'
  );
  if (awaitingSchedule.length) {
    issueBody += '## Awaiting Schedule\n\n';
    issueBody +=
      'These updates are awaiting their schedule. Click on a checkbox to ignore the schedule.\n';
    for (const branch of awaitingSchedule) {
      issueBody += getListItem(branch, 'unschedule');
    }
    issueBody += '\n';
  }
  const rateLimited = branches.filter(
    branch => branch.res && branch.res.endsWith('pr-hourly-limit-reached')
  );
  if (rateLimited.length) {
    issueBody += '## Rate Limited\n\n';
    issueBody +=
      'These updates are currently rate limited. Click on a checkbox below to force their creation now.\n\n';
    for (const branch of rateLimited) {
      issueBody += getListItem(branch, 'unlimit');
    }
    issueBody += '\n';
  }
  const errorList = branches.filter(
    branch => branch.res && branch.res.endsWith('error')
  );
  if (errorList.length) {
    issueBody += '## Errored\n\n';
    issueBody +=
      'These updates encountered an error and will be retried. Click a checkbox below to force a retry now.\n\n';
    for (const branch of errorList) {
      issueBody += getListItem(branch, 'retry');
    }
    issueBody += '\n';
  }
  const awaitingPr = branches.filter(
    branch => branch.res === 'needs-pr-approval'
  );
  if (awaitingPr.length) {
    issueBody += '## PR Creation Approval Required\n\n';
    issueBody +=
      "These branches exist but PRs won't be created until you approve by ticking the checkbox.\n\n";
    for (const branch of awaitingPr) {
      issueBody += getListItem(branch, 'approvePr');
    }
    issueBody += '\n';
  }
  const prEdited = branches.filter(branch => branch.res === 'pr-edited');
  if (prEdited.length) {
    issueBody += '## Edited/Blocked\n\n';
    issueBody += `These updates have been manually edited so ${appName} will no longer make changes. To discard all commits and start over, check the box below.\n\n`;
    for (const branch of prEdited) {
      const pr = await platform.getBranchPr(branch.branchName);
      issueBody += getListItem(branch, 'rebase', pr);
    }
    issueBody += '\n';
  }
  const prPending = branches.filter(branch => branch.res === 'pending');
  if (prPending.length) {
    issueBody += '## Pending Status Checks\n\n';
    issueBody += `These updates await pending status checks. To force their creation now, check the box below.\n\n`;
    for (const branch of prPending) {
      issueBody += getListItem(branch, 'approvePr');
    }
    issueBody += '\n';
  }
  const otherRes = [
    'pending',
    'needs-approval',
    'needs-pr-approval',
    'not-scheduled',
    'pr-hourly-limit-reached',
    'already-existed',
    'error',
    'automerged',
    'pr-edited',
  ];
  const inProgress = branches.filter(branch => !otherRes.includes(branch.res));
  if (inProgress.length) {
    issueBody += '## Open\n\n';
    issueBody +=
      'These updates have all been created already. Click a checkbox below to force a retry/rebase of any.\n\n';
    for (const branch of inProgress) {
      const pr = await platform.getBranchPr(branch.branchName);
      issueBody += getListItem(branch, 'rebase', pr);
    }
    if (inProgress.length > 2) {
      issueBody += ' - [ ] ';
      issueBody += '';
      issueBody +=
        '**Check this option to rebase all the above open PRs at once**';
      issueBody += '\n';
    }
    issueBody += '\n';
  }
  const alreadyExisted = branches.filter(
    branch => branch.res && branch.res.endsWith('already-existed')
  );
  if (alreadyExisted.length) {
    issueBody += '## Closed/Ignored\n\n';
    issueBody +=
      'These updates were closed unmerged and will not be recreated unless you click a checkbox below.\n\n';
    for (const branch of alreadyExisted) {
      const pr = await platform.findPr(
        branch.branchName,
        branch.prTitle,
        '!open'
      );
      issueBody += getListItem(branch, 'recreate', pr);
    }
    issueBody += '\n';
  }

  // istanbul ignore if
  if (global.appMode) {
    issueBody +=
      '---\nAdvanced\n\n- [ ] Check this box to trigger a request for Renovate to run again on this repository\n\n\n';
  }

  if (config.dryRun) {
    logger.info(
      'DRY-RUN: Would ensure Master Issue ' + config.masterIssueTitle
    );
  } else {
    await platform.ensureIssue(config.masterIssueTitle, issueBody);
  }
}
<|endoftext|>