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

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

        self.fileName = ko.observable();

        self.placeholderName = ko.observable();
        self.placeholderDisplayName = ko.observable();
        self.placeholderDescription = ko.observable();

        self.profileName = ko.observable();
        self.profileDisplayName = ko.observable();
        self.profileDescription = ko.observable();
        self.profileAllowOverwrite = ko.observable(true);

        self.uploadElement = $("#settings-slic3r-import");
        self.uploadButton = $("#settings-slic3r-import-start");

        self.profiles = new ItemListHelper(
            "plugin_slic3r_profiles",
            {
                "id": function(a, b) {
                    if (a["key"].toLocaleLowerCase() < b["key"].toLocaleLowerCase()) return -1;
                    if (a["key"].toLocaleLowerCase() > b["key"].toLocaleLowerCase()) return 1;
                    return 0;
                },
                "name": function(a, b) {
                    // sorts ascending
                    var aName = a.name();
                    if (aName === undefined) {
                        aName = "";
                    }
                    var bName = b.name();
                    if (bName === undefined) {
                        bName = "";
                    }

                    if (aName.toLocaleLowerCase() < bName.toLocaleLowerCase()) return -1;
                    if (aName.toLocaleLowerCase() > bName.toLocaleLowerCase()) return 1;
                    return 0;
                }
            },
            {},
            "id",
            [],
            [],
            5
        );

        self._sanitize = function(name) {
            return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
        };

        self.uploadElement.fileupload({
            dataType: "json",
            maxNumberOfFiles: 1,
            autoUpload: false,
            add: function(e, data) {
                if (data.files.length == 0) {
                    return false;
                }

                self.fileName(data.files[0].name);

                var name = self.fileName().substr(0, self.fileName().lastIndexOf("."));
                self.placeholderName(self._sanitize(name).toLowerCase());
                self.placeholderDisplayName(name);
                self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));

                self.uploadButton.on("click", function() {
                    var form = {
                        allowOverwrite: self.profileAllowOverwrite()
                    };

                    if (self.profileName() !== undefined) {
                        form["name"] = self.profileName();
                    }
                    if (self.profileDisplayName() !== undefined) {
                        form["displayName"] = self.profileDisplayName();
                    }
                    if (self.profileDescription() !== undefined) {
                        form["description"] = self.profileDescription();
                    }

                    data.formData = form;
                    data.submit();
                });
            },
            done: function(e, data) {
                self.fileName(undefined);
                self.placeholderName(undefined);
                self.placeholderDisplayName(undefined);
                self.placeholderDescription(undefined);
                self.profileName(undefined);
                self.profileDisplayName(undefined);
                self.profileDescription(undefined);
                self.profileAllowOverwrite(true);

                $("#settings_plugin_slic3r_import").modal("hide");
                self.requestData();
                self.slicingViewModel.requestData();
            }
        });

        self.removeProfile = function(data) {
            if (!data.resource) {
                return;
            }

            self.profiles.removeItem(function(item) {
                return (item.key == data.key);
            });

            $.ajax({
                url: data.resource(),
                type: "DELETE",
                success: function() {
                    self.requestData();
                    self.slicingViewModel.requestData();
                }
            });
        };

        self.makeProfileDefault = function(data) {
            if (!data.resource) {
                return;
            }

            _.each(self.profiles.items(), function(item) {
                item.isdefault(false);
            });
            var item = self.profiles.getItem(function(item) {
                return item.key == data.key;
            });
            if (item !== undefined) {
                item.isdefault(true);
            }

            $.ajax({
                url: data.resource(),
                type: "PATCH",
                dataType: "json",
                data: JSON.stringify({default: true}),
                contentType: "application/json; charset=UTF-8",
                success: function() {
                    self.requestData();
                }
            });
        };

        self.showImportProfileDialog = function() {
            $("#settings_plugin_slic3r_import").modal("show");
        };

        self.requestData = function() {
            $.ajax({
                url: API_BASEURL + "slicing/slic3r/profiles",
                type: "GET",
                dataType: "json",
                success: self.fromResponse
            });
        };

        self.fromResponse = function(data) {
            var profiles = [];
            _.each(_.keys(data), function(key) {
                profiles.push({
                    key: key,
                    name: ko.observable(data[key].displayName),
                    description: ko.observable(data[key].description),
                    isdefault: ko.observable(data[key].default),
                    resource: ko.observable(data[key].resource)
                });
            });
            self.profiles.updateItems(profiles);
        };

        self.onBeforeBinding = function () {
            self.settings = self.settingsViewModel.settings;
            self.requestData();
        };

    }

    // view model class, parameters for constructor, container to bind to
    ADDITIONAL_VIEWMODELS.push([Slic3rViewModel, ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], document.getElementById("settings_plugin_slic3r_dialog")]);
});<commit_msg>Bind confirm just once and not once per upload.<commit_after>$(function() {
    function Slic3rViewModel(parameters) {
        var self = this;

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

        self.fileName = ko.observable();

        self.placeholderName = ko.observable();
        self.placeholderDisplayName = ko.observable();
        self.placeholderDescription = ko.observable();

        self.profileName = ko.observable();
        self.profileDisplayName = ko.observable();
        self.profileDescription = ko.observable();
        self.profileAllowOverwrite = ko.observable(true);

        self.uploadElement = $("#settings-slic3r-import");
        self.uploadButton = $("#settings-slic3r-import-start");
        var data_ = null;
        self.uploadButton.on("click", function() {
            if (data_) {
                data_.submit();
            }
        });

        self.profiles = new ItemListHelper(
            "plugin_slic3r_profiles",
            {
                "id": function(a, b) {
                    if (a["key"].toLocaleLowerCase() < b["key"].toLocaleLowerCase()) return -1;
                    if (a["key"].toLocaleLowerCase() > b["key"].toLocaleLowerCase()) return 1;
                    return 0;
                },
                "name": function(a, b) {
                    // sorts ascending
                    var aName = a.name();
                    if (aName === undefined) {
                        aName = "";
                    }
                    var bName = b.name();
                    if (bName === undefined) {
                        bName = "";
                    }

                    if (aName.toLocaleLowerCase() < bName.toLocaleLowerCase()) return -1;
                    if (aName.toLocaleLowerCase() > bName.toLocaleLowerCase()) return 1;
                    return 0;
                }
            },
            {},
            "id",
            [],
            [],
            5
        );

        self._sanitize = function(name) {
            return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
        };

        self.clearUpload = function() {
            self.fileName(undefined);
            self.placeholderName(undefined);
            self.placeholderDisplayName(undefined);
            self.placeholderDescription(undefined);
            self.profileName(undefined);
            self.profileDisplayName(undefined);
            self.profileDescription(undefined);
            self.profileAllowOverwrite(true);
            data_ = null;
        };

        self.uploadElement.fileupload({
            dataType: "json",
            maxNumberOfFiles: 1,
            autoUpload: false,
            headers: OctoPrint.getRequestHeaders(),
            add: function(e, data) {
                if (data.files.length == 0) {
                    return false;
                }

                self.fileName(data.files[0].name);

                var name = self.fileName().substr(0, self.fileName().lastIndexOf("."));
                self.placeholderName(self._sanitize(name).toLowerCase());
                self.placeholderDisplayName(name);
                self.placeholderDescription("Imported from " + self.fileName() + " on " + formatDate(new Date().getTime() / 1000));

                var form = {
                    allowOverwrite: self.profileAllowOverwrite()
                };
                if (self.profileName() !== undefined) {
                    form["name"] = self.profileName();
                }
                if (self.profileDisplayName() !== undefined) {
                    form["displayName"] = self.profileDisplayName();
                }
                if (self.profileDescription() !== undefined) {
                    form["description"] = self.profileDescription();
                }

                data.formData = form;
                data_ = data;
            },
            done: function(e, data) {
                self.clearUpload();

                $("#settings_plugin_slic3r_import").modal("hide");
                self.requestData();
                self.slicingViewModel.requestData();
            }
        });

        self.removeProfile = function(data) {
            if (!data.resource) {
                return;
            }

            self.profiles.removeItem(function(item) {
                return (item.key == data.key);
            });

            $.ajax({
                url: data.resource(),
                type: "DELETE",
                success: function() {
                    self.requestData();
                    self.slicingViewModel.requestData();
                }
            });
        };

        self.makeProfileDefault = function(data) {
            if (!data.resource) {
                return;
            }

            _.each(self.profiles.items(), function(item) {
                item.isdefault(false);
            });
            var item = self.profiles.getItem(function(item) {
                return item.key == data.key;
            });
            if (item !== undefined) {
                item.isdefault(true);
            }

            $.ajax({
                url: data.resource(),
                type: "PATCH",
                dataType: "json",
                data: JSON.stringify({default: true}),
                contentType: "application/json; charset=UTF-8",
                success: function() {
                    self.requestData();
                }
            });
        };

        self.showImportProfileDialog = function() {
            self.clearUpload();
            $("#settings_plugin_slic3r_import").modal("show");
        };

        self.requestData = function() {
            $.ajax({
                url: API_BASEURL + "slicing/slic3r/profiles",
                type: "GET",
                dataType: "json",
                success: self.fromResponse
            });
        };

        self.fromResponse = function(data) {
            var profiles = [];
            _.each(_.keys(data), function(key) {
                profiles.push({
                    key: key,
                    name: ko.observable(data[key].displayName),
                    description: ko.observable(data[key].description),
                    isdefault: ko.observable(data[key].default),
                    resource: ko.observable(data[key].resource)
                });
            });
            self.profiles.updateItems(profiles);
        };

        self.onBeforeBinding = function () {
            self.settings = self.settingsViewModel.settings;
            self.requestData();
        };

    }

    // view model class, parameters for constructor, container to bind to
    ADDITIONAL_VIEWMODELS.push([Slic3rViewModel, ["loginStateViewModel", "settingsViewModel", "slicingViewModel"], document.getElementById("settings_plugin_slic3r_dialog")]);
});
<|endoftext|>


<commit_before>
//PREPARE MODAL
 var modal='\

\

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>\

Import DB
\

\

\

Be carefull ! this action isn\'t cancelable
\

Please, provide a complete Conf RDF File
\

(such as : http://data.semanticweb.org/conference/www/2012/complete)
\

\
          <input type="text" id="DBURL" placeholder="Complete Conf rdf File"></input>\
          <button  id="DBURLBtn" data-dismiss="modal" class="btn">\
             \
            import\
          </button>\

\

\

\
          <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>\

\

';
 $('body').append($(modal).hide());
 function run(dbimportpath){
    $('#myModal').modal();
    $('#DBURLBtn').off('click').click({dbimportpath:dbimportpath},function(event){
        /*
        if( $('#DBURL').val()=="")return;
        var completeConfRdfURL =  $('#DBURL').val();

        var completeConfRdf=getRdfFromUrl(completeConfRdfURL) ;
        */
        var completeConfRdf=getRdfFromUrl('../../../complete4.rdf');

        // run www2012 conf sample with ../../../complete4.rdf

        if(completeConfRdf==undefined){alert('wrong URL');return;}
        if(!confirm("Are you sure you want to import "+$('#DBURL').val()+" file ? "))return;

        var events= [];
        var locations= [];
        var xproperties= [];
        var relations= [];
        var categories= [];

        //call stack for parent inheritance
        var defaultDate='1980-01-01T00:00:00+00:00'
        //////////////////////////////////////////////////////////////////////////
        ///////////////////////  first round for locations  //////////////////////
        //////////////////////////////////////////////////////////////////////////

        $(completeConfRdf).children().children().each(function(index){
          if(this.nodeName=="swc:MeetingRoomPlace"){
              /////////////////////         LOCATION NODE         //////////////////

                var location={setDescription:""};

                $(this).children().each(function(){

                    if(this.nodeName=="rdfs:comment"){

                      location['setDescription']= location.setDescription+$(this).text()+", ";

                    }else if(this.nodeName=="rdfs:label"){

                      location['setName']=$(this).text();

                    }

                });

                //temporary attribute / flag
                location['uri']=$(this).attr('rdf:about');

                locations.push(location);
          }
        });
        //console.log('-------locations--------');
        //console.log(locations);

        //////////////////////////////////////////////////////////////////////////
        ///////////////////  second round for events  ////////////////////////////
        //////////////////////////////////////////////////////////////////////////

        $(completeConfRdf).children().children().each(function(index){
        /*
        /////////////////////         ROOT NODE         //////////////////
            if(this.nodeName=="swc:ConferenceEvent"){
                doEvent(this);
                addRelation(this);
                //console.log(events[events.length-1]);
                //console.log(xproperties[xproperties.length-1]);
            }else */if( this.nodeName.indexOf("Event")!== -1) {
        /////////////////////         EVENT NODE         //////////////////

              doEvent(this);
              addRelation(this);

              //console.log(events);
              //console.log(relations);
            }
        });

        //////////////////////////////////////////////////////////////////////////
        ///////////////////  third round for publication title  //////////////////
        //////////////////////////////////////////////////////////////////////////

        $(completeConfRdf).children().children().each(function(index){

            if(this.nodeName=="swrc:InProceedings"){
                //for each proceeding
                var uri = $(this).attr('rdf:about');
                for (var i=0;i<xproperties.length;i++){

                    if(xproperties[i]['setXValue']==uri){
                    // if we find the corresponding xproperty
                        $(this).children().each(function(){
                            //we look for the title
                            if(this.nodeName=="dce:title"){
                              //to finally store it in the setXKey !
                              xproperties[i]['setXKey']=$(this).text();
                            }
                        });
                    }
                }
            }
        });

        //////////////////////////////////////////////////////////////////////////
        ////////////////////////  INHERIT PARENT DATE  ///////////////////////////
        //////////////////////////////////////////////////////////////////////////
        var maxCllStck=20;
        var ctn;
        for(var i=0;i<events.length;i++){
            if(events[i]['setStartAt']==undefined){
                ctn=0;
                var parentStartAt= getParentProp(i,'setStartAt');
                if(parentStartAt!=undefined){
                    events[i]['setStartAt']=parentStartAt;
                    events[i]['setEndAt']=getParentProp(i,'setEndAt');
                }else{
                    events[i]['setStartAt']=events[0]['setStartAt'];
                    events[i]['setEndAt']=events[0]['setEndAt'];
                }
            }
        }

        send(event.data.dbimportpath);
        return 1;
        //////////////////////////////////////////////////////////////////////////
        ////////////////////////  run() workflow end  ////////////////////////////
        //////////////////////////////////////////////////////////////////////////

        //EVENT PARSE : CATCH START, END AT, LOCATION
        // THEN ADD 2 XPROPERTIES RELATED TO ITS EVENT AND PUBLICATION
        function doEvent(event){
            var rtnArray={};
            $(event).children().each(function(){
                if(this.nodeName=="rdfs:label"){   // LABEL
                    // replace & caractere,  f*** JSON.stringify() ...
                    rtnArray['setSummary']=this.textContent.split(/\x26/).join("%26").split(/\x3D/).join("%3D");;
                }else if(this.nodeName=="icaltzd:dtstart"){ // START AT

                    rtnArray['setStartAt']=$(this).text();

                }else if(this.nodeName=="dce:description"){ // DESCRIPTION

                    rtnArray['setDescription']=this.textContent.split(/\x26/).join("%26").split(/\x3D/).join("%3D");

                }else if(this.nodeName=="swrc:abstract"){ // ABSTRACT

                    rtnArray['setComment']=this.textContent.split(/\x26/).join("%26").split(/\x3D/).join("%3D");;

                }else if(this.nodeName=="icaltzd:dtend"){   // END AT

                    rtnArray['setEndAt']=$(this).text();

                }else if(this.nodeName=="swc:hasRelatedDocument"){ // RELATED PUBLICATION XPROP

                    var xproperty= {};
                    xproperty['setCalendarEntity']=events.length;
                    xproperty['setXNamespace']="publication_uri";
                    xproperty['setXValue']=$(this).attr('rdf:resource');
                    xproperties.push(xproperty);

                }else if(this.nodeName=="icaltzd:location"){   // LOCATION XPROP

                    var xproperty= {};
                    xproperty['setCalendarEntity']=events.length;
                    xproperty['setXNamespace']="location_uri";
                    xproperty['setXValue']=$(this).attr('rdf:resource');
                    xproperties.push(xproperty);

                    var locationId = getLocationIdFromUri($(this).attr('rdf:resource'));
                    rtnArray['setLocation']=locationId;

                }

                /*else if(this.nodeName="event:time" && rtnArray['setStartAt']==undefined){
                    var interval=$(this).attr("rdf:resource").split("/");
                    interval=interval[interval.length-1].split("_");

                    rtnArray['setStartAt']=interval[0];
                    rtnArray['setEndAt']=interval[0];

                }else if(this.nodeName=="dce:description"){
                    rtnArray['setDescription']=$(this).text();
                }*/

            });

              // EVENT CAT
            var catName = event.nodeName.split("swc:").join("").split("event:").join("");
            var tmp=catName;
            if(tmp.split("Event").join("")!="")catName=tmp;
            var catId = getCategoryIdFromName(catName);
            if(catId==undefined){
              var category= {};
              category['setName']=catName;
              categories.push(category);
              catId = categories.length-1;
            }
            rtnArray['addCategorie']=catId;

            events.push( rtnArray );

              // EVENT XPROP
            var xproperty= {};
            xproperty['setCalendarEntity']=events.length-1;
            xproperty['setXNamespace']="event_uri";
            xproperty['setXValue']=$(event).attr('rdf:about');
            xproperties.push(xproperty);

         }

        //EVENT ADD BOTH PARENT AND CHILD RELATION BETWEEN 2 EVENTS
        function addRelation(event){
            var currentEventId = events.length-1;
            $(event).children().each(function(){
                if(this.nodeName=="swc:isSubEventOf"||this.nodeName=="swc:isSuperEventOf"){//
                    var relatedToEventId=getEventIdFromURI($(this).attr('rdf:resource'));
                    if(relatedToEventId!=undefined && events[relatedToEventId]!=undefined ){
                        var relationType = this.nodeName.indexOf("swc:isSubEventOf")!== -1?"PARENT":"CHILD";
                        var relation= {};
                        relation['setCalendarEntity']=parseInt(relatedToEventId);
                        relation['setRelationType']=relationType;
                        relation['setRelatedTo']=parseInt(currentEventId);
                        relations.push(relation);
                        var relationType = this.nodeName=="swc:isSubEventOf"?"CHILD":"PARENT";
                        var relation= {};
                        relation['setCalendarEntity']=parseInt(currentEventId);
                        relation['setRelationType']=relationType;
                        relation['setRelatedTo']=parseInt(relatedToEventId);
                        relations.push(relation);
                        return true;
                    }else{
                      //alert( event['setSummary']+", "+$(this).attr('rdf:resource'));
                      //console.log("Unknown parent");

                    }
                }
            });
            return false;
        }

        // GET THE INDEX OF A CATEGORY GIVEN ITS NAME
        function getCategoryIdFromName(name){

            for (var i=0;i<categories.length;i++){
                //alert(url+"\n"+xproperties[i]['setXValue']+"\n"+(xproperties[i]['setXValue']==url)+"\n"+i);
                if(categories[i]['setName']==name){
                    return i;
                }
            }
            return undefined;
        }

        // GET THE INDEX OF A LOCATION GIVEN ITS URI
        function getLocationIdFromUri(uri){

            for (var i=0;i<locations.length;i++){
                //alert(url+"\n"+xproperties[i]['setXValue']+"\n"+(xproperties[i]['setXValue']==url)+"\n"+i);
                if(locations[i]['uri']==uri){
                    return i;
                }
            }
            return undefined;
        }

        // GET THE INDEX OF AN EVENT GIVEN ITS URI
        function getEventIdFromURI(uri){

            for (var i=0;i<xproperties.length;i++){
                //alert(url+"\n"+xproperties[i]['setXValue']+"\n"+(xproperties[i]['setXValue']==url)+"\n"+i);
                if(xproperties[i]['setXValue']==uri){
                    return xproperties[i]['setCalendarEntity'];
                }
            }
            return undefined;
        }

        // GET THE INDEX OF AN EVENT GIVEN ITS CHILD INDEX
        function getParentIndex(eventIndex){
            for(var i=0;i<relations.length;i++){
                 if(relations[i]['setRelatedTo'] == eventIndex  && relations[i]['setRelationType'].indexOf("PARENT") ){
                    return relations[i]['setCalendarEntity'];
                 }
            }
            return undefined;
        }

        // GET RECURSIVELY PARENT DATETIME

        function getParentProp(eventIndex,parentProp){
            ctn++;
            if(ctn>maxCllStck)return defaultDate;
            var parentIndex=getParentIndex(eventIndex);
            if( parentIndex==undefined || events[parentIndex]==undefined)return defaultDate;
            if( events[parentIndex][parentProp]!=undefined)return events[parentIndex][parentProp];
            return getParentProp(getParentIndex(eventIndex),parentProp);
        }

        // SEND TO IMPORT PHP SCRIPT
        function send(dbimportpath){

          for (var i=0;i<locations.length;i++){
            delete locations[i]["uri"];
          }
          var dataArray={};
          dataArray['categories']=categories;
          dataArray['events']=events;
          dataArray['xproperties']=xproperties;
          dataArray['relations']=relations;
          dataArray['locations']=locations;

          if(events.length<1 && xproperties.length<1 && relations.length<1 && locations.length<1){
            alert('nothing imported');
            return;
          }
          console.log('---------sending---------' );
          console.log(dataArray );

          $.ajax({
            type: "POST",
            url: dbimportpath,
            data: "dataArray=" + JSON.stringify(dataArray, null),
            success:function(a,b,c){console.log(a,b,c)},
            error:function(a,b,c){console.log(a,b,c)},
          });

       }
     });
}

function getRdfFromUrl(completeConfRdfURL){
    var returnVar;
        $.ajax({
          url: completeConfRdfURL ,
          async:false,
          cache:false,
          success:function(data){
            returnVar=data;
          }
        });
    return returnVar;
}
<commit_msg>default behavior restored for the import button<commit_after>
//PREPARE MODAL
 var modal='\

\

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>\

Import DB
\

\

\

Be carefull ! this action isn\'t cancelable
\

Please, provide a complete Conf RDF File
\

(such as : http://data.semanticweb.org/conference/www/2012/complete)
\

\
          <input type="text" id="DBURL" placeholder="Complete Conf rdf File"></input>\
          <button  id="DBURLBtn" data-dismiss="modal" class="btn">\
             \
            import\
          </button>\

\

\

\
          <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>\

\

';
 $('body').append($(modal).hide());
 function run(dbimportpath){
    $('#myModal').modal();
    $('#DBURLBtn').off('click').click({dbimportpath:dbimportpath},function(event){

        if( $('#DBURL').val()=="")return;
        var completeConfRdfURL =  $('#DBURL').val();

        var completeConfRdf=getRdfFromUrl(completeConfRdfURL) ;

        // run www2012 conf sample with ../../../complete4.rdf

        if(completeConfRdf==undefined){alert('wrong URL');return;}
        if(!confirm("Are you sure you want to import "+$('#DBURL').val()+" file ? "))return;

        var events= [];
        var locations= [];
        var xproperties= [];
        var relations= [];
        var categories= [];

        //call stack for parent inheritance
        var defaultDate='1980-01-01T00:00:00+00:00'
        //////////////////////////////////////////////////////////////////////////
        ///////////////////////  first round for locations  //////////////////////
        //////////////////////////////////////////////////////////////////////////

        $(completeConfRdf).children().children().each(function(index){
          if(this.nodeName=="swc:MeetingRoomPlace"){
              /////////////////////         LOCATION NODE         //////////////////

                var location={setDescription:""};

                $(this).children().each(function(){

                    if(this.nodeName=="rdfs:comment"){

                      location['setDescription']= location.setDescription+$(this).text()+", ";

                    }else if(this.nodeName=="rdfs:label"){

                      location['setName']=$(this).text();

                    }

                });

                //temporary attribute / flag
                location['uri']=$(this).attr('rdf:about');

                locations.push(location);
          }
        });
        //console.log('-------locations--------');
        //console.log(locations);

        //////////////////////////////////////////////////////////////////////////
        ///////////////////  second round for events  ////////////////////////////
        //////////////////////////////////////////////////////////////////////////

        $(completeConfRdf).children().children().each(function(index){
        /*
        /////////////////////         ROOT NODE         //////////////////
            if(this.nodeName=="swc:ConferenceEvent"){
                doEvent(this);
                addRelation(this);
                //console.log(events[events.length-1]);
                //console.log(xproperties[xproperties.length-1]);
            }else */if( this.nodeName.indexOf("Event")!== -1) {
        /////////////////////         EVENT NODE         //////////////////

              doEvent(this);
              addRelation(this);

              //console.log(events);
              //console.log(relations);
            }
        });

        //////////////////////////////////////////////////////////////////////////
        ///////////////////  third round for publication title  //////////////////
        //////////////////////////////////////////////////////////////////////////

        $(completeConfRdf).children().children().each(function(index){

            if(this.nodeName=="swrc:InProceedings"){
                //for each proceeding
                var uri = $(this).attr('rdf:about');
                for (var i=0;i<xproperties.length;i++){

                    if(xproperties[i]['setXValue']==uri){
                    // if we find the corresponding xproperty
                        $(this).children().each(function(){
                            //we look for the title
                            if(this.nodeName=="dce:title"){
                              //to finally store it in the setXKey !
                              xproperties[i]['setXKey']=$(this).text();
                            }
                        });
                    }
                }
            }
        });

        //////////////////////////////////////////////////////////////////////////
        ////////////////////////  INHERIT PARENT DATE  ///////////////////////////
        //////////////////////////////////////////////////////////////////////////
        var maxCllStck=20;
        var ctn;
        for(var i=0;i<events.length;i++){
            if(events[i]['setStartAt']==undefined){
                ctn=0;
                var parentStartAt= getParentProp(i,'setStartAt');
                if(parentStartAt!=undefined){
                    events[i]['setStartAt']=parentStartAt;
                    events[i]['setEndAt']=getParentProp(i,'setEndAt');
                }else{
                    events[i]['setStartAt']=events[0]['setStartAt'];
                    events[i]['setEndAt']=events[0]['setEndAt'];
                }
            }
        }

        send(event.data.dbimportpath);
        return 1;
        //////////////////////////////////////////////////////////////////////////
        ////////////////////////  run() workflow end  ////////////////////////////
        //////////////////////////////////////////////////////////////////////////

        //EVENT PARSE : CATCH START, END AT, LOCATION
        // THEN ADD 2 XPROPERTIES RELATED TO ITS EVENT AND PUBLICATION
        function doEvent(event){
            var rtnArray={};
            $(event).children().each(function(){
                if(this.nodeName=="rdfs:label"){   // LABEL
                    // replace & caractere,  f*** JSON.stringify() ...
                    rtnArray['setSummary']=this.textContent.split(/\x26/).join("%26").split(/\x3D/).join("%3D");;
                }else if(this.nodeName=="icaltzd:dtstart"){ // START AT

                    rtnArray['setStartAt']=$(this).text();

                }else if(this.nodeName=="dce:description"){ // DESCRIPTION

                    rtnArray['setDescription']=this.textContent.split(/\x26/).join("%26").split(/\x3D/).join("%3D");

                }else if(this.nodeName=="swrc:abstract"){ // ABSTRACT

                    rtnArray['setComment']=this.textContent.split(/\x26/).join("%26").split(/\x3D/).join("%3D");;

                }else if(this.nodeName=="icaltzd:dtend"){   // END AT

                    rtnArray['setEndAt']=$(this).text();

                }else if(this.nodeName=="swc:hasRelatedDocument"){ // RELATED PUBLICATION XPROP

                    var xproperty= {};
                    xproperty['setCalendarEntity']=events.length;
                    xproperty['setXNamespace']="publication_uri";
                    xproperty['setXValue']=$(this).attr('rdf:resource');
                    xproperties.push(xproperty);

                }else if(this.nodeName=="icaltzd:location"){   // LOCATION XPROP

                    var xproperty= {};
                    xproperty['setCalendarEntity']=events.length;
                    xproperty['setXNamespace']="location_uri";
                    xproperty['setXValue']=$(this).attr('rdf:resource');
                    xproperties.push(xproperty);

                    var locationId = getLocationIdFromUri($(this).attr('rdf:resource'));
                    rtnArray['setLocation']=locationId;

                }

                /*else if(this.nodeName="event:time" && rtnArray['setStartAt']==undefined){
                    var interval=$(this).attr("rdf:resource").split("/");
                    interval=interval[interval.length-1].split("_");

                    rtnArray['setStartAt']=interval[0];
                    rtnArray['setEndAt']=interval[0];

                }else if(this.nodeName=="dce:description"){
                    rtnArray['setDescription']=$(this).text();
                }*/

            });

              // EVENT CAT
            var catName = event.nodeName.split("swc:").join("").split("event:").join("");
            var tmp=catName;
            if(tmp.split("Event").join("")!="")catName=tmp;
            var catId = getCategoryIdFromName(catName);
            if(catId==undefined){
              var category= {};
              category['setName']=catName;
              categories.push(category);
              catId = categories.length-1;
            }
            rtnArray['addCategorie']=catId;

            events.push( rtnArray );

              // EVENT XPROP
            var xproperty= {};
            xproperty['setCalendarEntity']=events.length-1;
            xproperty['setXNamespace']="event_uri";
            xproperty['setXValue']=$(event).attr('rdf:about');
            xproperties.push(xproperty);

         }

        //EVENT ADD BOTH PARENT AND CHILD RELATION BETWEEN 2 EVENTS
        function addRelation(event){
            var currentEventId = events.length-1;
            $(event).children().each(function(){
                if(this.nodeName=="swc:isSubEventOf"||this.nodeName=="swc:isSuperEventOf"){//
                    var relatedToEventId=getEventIdFromURI($(this).attr('rdf:resource'));
                    if(relatedToEventId!=undefined && events[relatedToEventId]!=undefined ){
                        var relationType = this.nodeName.indexOf("swc:isSubEventOf")!== -1?"PARENT":"CHILD";
                        var relation= {};
                        relation['setCalendarEntity']=parseInt(relatedToEventId);
                        relation['setRelationType']=relationType;
                        relation['setRelatedTo']=parseInt(currentEventId);
                        relations.push(relation);
                        var relationType = this.nodeName=="swc:isSubEventOf"?"CHILD":"PARENT";
                        var relation= {};
                        relation['setCalendarEntity']=parseInt(currentEventId);
                        relation['setRelationType']=relationType;
                        relation['setRelatedTo']=parseInt(relatedToEventId);
                        relations.push(relation);
                        return true;
                    }else{
                      //alert( event['setSummary']+", "+$(this).attr('rdf:resource'));
                      //console.log("Unknown parent");

                    }
                }
            });
            return false;
        }

        // GET THE INDEX OF A CATEGORY GIVEN ITS NAME
        function getCategoryIdFromName(name){

            for (var i=0;i<categories.length;i++){
                //alert(url+"\n"+xproperties[i]['setXValue']+"\n"+(xproperties[i]['setXValue']==url)+"\n"+i);
                if(categories[i]['setName']==name){
                    return i;
                }
            }
            return undefined;
        }

        // GET THE INDEX OF A LOCATION GIVEN ITS URI
        function getLocationIdFromUri(uri){

            for (var i=0;i<locations.length;i++){
                //alert(url+"\n"+xproperties[i]['setXValue']+"\n"+(xproperties[i]['setXValue']==url)+"\n"+i);
                if(locations[i]['uri']==uri){
                    return i;
                }
            }
            return undefined;
        }

        // GET THE INDEX OF AN EVENT GIVEN ITS URI
        function getEventIdFromURI(uri){

            for (var i=0;i<xproperties.length;i++){
                //alert(url+"\n"+xproperties[i]['setXValue']+"\n"+(xproperties[i]['setXValue']==url)+"\n"+i);
                if(xproperties[i]['setXValue']==uri){
                    return xproperties[i]['setCalendarEntity'];
                }
            }
            return undefined;
        }

        // GET THE INDEX OF AN EVENT GIVEN ITS CHILD INDEX
        function getParentIndex(eventIndex){
            for(var i=0;i<relations.length;i++){
                 if(relations[i]['setRelatedTo'] == eventIndex  && relations[i]['setRelationType'].indexOf("PARENT") ){
                    return relations[i]['setCalendarEntity'];
                 }
            }
            return undefined;
        }

        // GET RECURSIVELY PARENT DATETIME

        function getParentProp(eventIndex,parentProp){
            ctn++;
            if(ctn>maxCllStck)return defaultDate;
            var parentIndex=getParentIndex(eventIndex);
            if( parentIndex==undefined || events[parentIndex]==undefined)return defaultDate;
            if( events[parentIndex][parentProp]!=undefined)return events[parentIndex][parentProp];
            return getParentProp(getParentIndex(eventIndex),parentProp);
        }

        // SEND TO IMPORT PHP SCRIPT
        function send(dbimportpath){

          for (var i=0;i<locations.length;i++){
            delete locations[i]["uri"];
          }
          var dataArray={};
          dataArray['categories']=categories;
          dataArray['events']=events;
          dataArray['xproperties']=xproperties;
          dataArray['relations']=relations;
          dataArray['locations']=locations;

          if(events.length<1 && xproperties.length<1 && relations.length<1 && locations.length<1){
            alert('nothing imported');
            return;
          }
          console.log('---------sending---------' );
          console.log(dataArray );

          $.ajax({
            type: "POST",
            url: dbimportpath,
            data: "dataArray=" + JSON.stringify(dataArray, null),
            success:function(a,b,c){console.log(a,b,c)},
            error:function(a,b,c){console.log(a,b,c)},
          });

       }
     });
}

function getRdfFromUrl(completeConfRdfURL){
    var returnVar;
        $.ajax({
          url: completeConfRdfURL ,
          async:false,
          cache:false,
          success:function(data){
            returnVar=data;
          }
        });
    return returnVar;
}
<|endoftext|>


<commit_before>NGApp.factory('TicketViewService', function($rootScope, $resource, $routeParams, $timeout, NotificationService, AccountService, SocketService, MainNavigationService, TicketService) {
	var service = {
		isTyping: false,
		id_support: false,
		messages: [],
		socket: SocketService.socket
	};

	service.sideInfo = { id_support: null };

	service.sideInfo.setTicket = function( id_support ){
		service.sideInfo.id_support = id_support;
		service.sideInfo.reset();
	}

	service.sideInfo.reset = function(){
		service.sideInfo.data = { id_support: service.sideInfo.id_support, messages: [], page: 0, loaded: 0, total: null, has_more: false };
		service._private = { first_load: true, current_scroll: 0, could_load: true };
		service.sideInfo.update_controller();
		setTimeout( function(){
			service.sideInfo.update_controller();
		} )
	};

	service.sideInfo.force_first_page = function(){
		service.sideInfo.reset();
		service.sideInfo.load();
	}

	service.sideInfo.scroll = function( action ){
		var container = $('.support-chat-contents-scroll');
		switch( action ){
			case 'begin':
				$timeout( function(){
					container.stop( true, false ).animate( { scrollTop: container[0].scrollHeight }, 0 );
					service.sideInfo.release();
				}, 300 );
				break;
			case 'current':
				service._private.current_scroll = container[0].scrollHeight;
				break;
			default:
				var position = action;
				setTimeout(function() {
					var finalScroll = container[0].scrollHeight;
					var goToScroll = finalScroll - service._private.current_scroll;
					container[0].scrollTop = goToScroll;
					service.sideInfo.release();
				}, 100 );
				break;
		}
	}

	service.sideInfo.release = function(){
		setTimeout(function() { service._private.could_load = true }, 500 );
	}

	service.sideInfo.add_message = function( message ){
		service.sideInfo.data.messages.push( message );
		service.sideInfo.data.total++;
		service.sideInfo.data.loaded++;
		service.sideInfo.update_controller();
		service.sideInfo.scroll( 'begin' );
	}

	service.sideInfo.load_ticket_page = function(){
		if( service.sideInfo.id_support ){
			MainNavigationService.link( '/ticket/' + service.sideInfo.id_support );
		}
	}

	service.sideInfo.update_controller = function(){
		$rootScope.$broadcast( 'triggerTicketInfoUpdated', service.sideInfo.data );
	}

	service.sideInfo.load = function(){

		if( service.sideInfo.id_support ){
			if( !service._private.could_load ){
				return false;
			}
			if( service.sideInfo.data.total !== null && service.sideInfo.data.loaded >= service.sideInfo.data.total ){
				return;
			}
			service._private.could_load = false;

			service.sideInfo.data.page++;

			var params = { id_support: service.sideInfo.id_support, page: service.sideInfo.data.page };

			TicketService.side_info( params, function( data ){
				service.sideInfo.scroll( 'current' );
				service.sideInfo.data.pexcard = data.pexcard;
				service.sideInfo.data.restaurant = data.restaurant;
				service.sideInfo.data.order = data.order;
				service.sideInfo.data.total = data.messages.total;
				var messages = [];
				for( x in data.messages.list ){
					if( data.messages.list[ x ].id_support_message ){
						messages.push( data.messages.list[ x ] );
					}
				}
				for( x in service.sideInfo.data.messages ){
					if( service.sideInfo.data.messages[ x ].id_support_message ){
						messages.push( service.sideInfo.data.messages[ x ] );
					}
				}
				service.sideInfo.data.messages = messages;
				service.sideInfo.data.loaded = service.sideInfo.data.messages.length;
				service.sideInfo.data.has_more = ( service.sideInfo.data.loaded >= service.sideInfo.data.total ) ? false : true;
				service.sideInfo.update_controller();
				if( service._private.first_load ){
					service.sideInfo.scroll( 'begin' );
					service._private.first_load = false;
					service.sideInfo.load_ticket_page();
					$rootScope.$broadcast( 'triggerSideViewTicket', {} );
				} else {
					service.sideInfo.scroll();
				}
			} );
			return true;
		}
		return false;
	};

	service.setViewTicket = function(id) {
		service.scope.viewTicket = id;
		service.sideInfo.setTicket( id );
	};

	$rootScope.$on('triggerViewTicket', function(e, ticket) {

		if( service.scope.viewTicket && service.scope.ticket &&
				service.scope.viewTicket.id_support == ticket.id_support &&
				service.scope.ticket.id_support == ticket.id_support ){
			service.sideInfo.force_first_page();
			return;
		}

		NotificationService.check();

		service.scope.viewTicket = ticket;
		service.scope.ticket = ticket;

		if (service.scope.viewTicket) {
			if( typeof service.scope.viewTicket == 'object' ){
				var id_support = service.scope.viewTicket.id_support
			} else {
				var id_support = service.scope.viewTicket;
			}
			service.socket.emit('event.subscribe', 'ticket.' + id_support);
		}
	});

	var notified  = new Array();

	$rootScope.$on('userAuthUpdated', function(e, data) {

		if (AccountService.user && AccountService.user.id_admin) {

			service.socket.emit('event.subscribe', 'user.preference.' + AccountService.user.id_admin );

			SocketService.listen( 'user.preference.' + AccountService.user.id_admin, $rootScope).on( 'user.preference', function( payload ){
				if( AccountService.user.prefs['notification-desktop-support-all'] ){
					console.debug('Subscribing to all tickets: socket event');
					service.socket.emit('event.subscribe', 'ticket.all');
					service.socket.emit('event.subscribe', 'tickets');
				} else {
					console.debug('Unsubscribing to all tickets: socket event');
					service.socket.emit('event.unsubscribe', 'ticket.all');
					service.socket.emit('event.unsubscribe', 'tickets');
				}
			} );

			if (AccountService.isSupport) {

				if( AccountService.user && AccountService.user.prefs && AccountService.user.prefs[ 'notification-desktop-support-all' ] === true ){
					console.debug('Subscribing to all tickets: auth event');
					service.socket.emit('event.subscribe', 'ticket.all');
					service.socket.emit('event.subscribe', 'tickets');
				} else {
					console.debug('Unsubscribing to all tickets: auth event');
					service.socket.emit('event.unsubscribe', 'ticket.all');
					service.socket.emit('event.unsubscribe', 'tickets');
				}

				service.socket.emit('event.subscribe', 'ticket.update');

				SocketService.listen('ticket.update', $rootScope).on( 'change_ticket_status', function(){
					$rootScope.$broadcast( 'updateSideTickets' );
					$rootScope.$broadcast( 'updateHeartbeat' );
				} )

				SocketService.listen('tickets', $rootScope)
					.on('message', function(d) {

						if( AccountService.user && AccountService.user.prefs && AccountService.user.prefs[ 'notification-desktop-support-all' ] === false ){
console.log('ignore messages');
							return;
						}
console.log('receive messages');
						console.debug('Recieved chat message: ', d);

						if (notified.indexOf(d.id_support_message) > -1) {
							console.log('already notified ', d.id_support_message);
							return;
						}

						notified.push(d.id_support_message);

						// update the chat room
						console.log('service.sideInfo.id_support',service.sideInfo.id_support);
						console.log('d.id_support',d.id_support);
						if( service.sideInfo.id_support && d.id_support && parseInt( service.sideInfo.id_support ) != parseInt( d.id_support ) ){
							console.log('force_first_page??');
							// service.sideInfo.force_first_page();
						}
console.log('d.from',d.from);
						// https://github.com/crunchbutton/crunchbutton/issues/7579#issuecomment-172934677
						if (d.from == 'rep' ) {
							return;
						}
console.log('d.id_support',d.id_support);
console.log('service.scope.viewTicket',service.scope.viewTicket);
						if (d.id_support == service.scope.viewTicket) {
							//App.playAudio('support-message-recieved');
						} else {
							//App.playAudio('support-message-new');
						}
console.log('d.name',d.name);
console.log('d.body',d.body);
						NotificationService.notify(d.name, d.body, null, function() {
							try{
								if( document.getElementById('support-chat-box') ){
									document.getElementById('support-chat-box').focus();
								}
							}catch(e){}

						});

					})
					.on( 'sms_status', function( d ){

						console.debug('Recieved sms status update: ', d);

						updateSmsStatus( d );
					} )

			}

		} else {
			//service.socket.close();
			//service.socket = null;
		}
	});

	var updateSmsStatus = function( d ){
		var id_support_message = d.id_support_message;
		var status = d.status;
		var element = $( '#support-message-status-' + id_support_message );
		if( element && element.length ){
			element.attr( 'title', 'Status: ' + status );
		}
	}

	service.send = function(message, add_as_note, callback) {
		var add_as_note = ( add_as_note ? true : false );
		var guid = App.guid();
		console.log('guid',guid);
		if( !service.sideInfo.id_support ){
			return;
		}
		TicketService.message( {
			id_support: service.sideInfo.id_support,
			body: message,
			guid: guid,
			note: add_as_note
		},
		// callback
		function(d) {
			if(!d.status){
				d.status = 'queued';
			}

			for ( var x in service.sideInfo.data.messages ) {
				if ( service.sideInfo.data.messages[x].guid == guid ) {
					d.guid = guid;
					service.sideInfo.data.messages[x] = d;
					notified.push( d.id_support_message );
					break;
				}
			}
		});
		if( callback ){
			callback()
		} else {
			service.scope.$apply(function() {
				console.log('no callback');
				service.sideInfo.add_message( { body: message, name: AccountService.user.firstName, timestamp: new Date().getTime(), sending: true, guid: guid, status: 'queued' } );
			});
		}
		$rootScope.$broadcast( 'replyFinished' );
	};

	service.scroll = function(instant) {
		setTimeout(function() {
			if( $('.support-chat-contents-scroll').length ){
				$('.support-chat-contents-scroll').stop(true,false).animate({
					scrollTop: $('.support-chat-contents-scroll')[0].scrollHeight
				}, instant ? 0 : 800);
			}
		}, 100);
	};

	/*
	var typingTimer;

	service.typing = function(val) {
		return;
		if (!service.isTyping) {
			service.isTyping = true;
			service.websocket.send({
				type: 'ticket.typing.start'
			});

		} else {
			if (!val) {
				service.isTyping = false;
				service.websocket.send({
					type: 'ticket.typing.stop'
				});
			}
		}

		if (typingTimer) {
			clearTimeout(typingTimer);
		}
		typingTimer = setTimeout(function() {
			if (service.isTyping) {
				service.isTyping = false;
				service.websocket.send({
					type: 'ticket.typing.stop'
				});
			}
		}, 5000);
	};
	*/

	return service;
});
<commit_msg>Notify on all support tickets still notifiesa me when it is off #7651<commit_after>NGApp.factory('TicketViewService', function($rootScope, $resource, $routeParams, $timeout, NotificationService, AccountService, SocketService, MainNavigationService, TicketService) {
	var service = {
		isTyping: false,
		id_support: false,
		messages: [],
		socket: SocketService.socket
	};

	service.sideInfo = { id_support: null };

	service.sideInfo.setTicket = function( id_support ){
		service.sideInfo.id_support = id_support;
		service.sideInfo.reset();
	}

	service.sideInfo.reset = function(){
		service.sideInfo.data = { id_support: service.sideInfo.id_support, messages: [], page: 0, loaded: 0, total: null, has_more: false };
		service._private = { first_load: true, current_scroll: 0, could_load: true };
		service.sideInfo.update_controller();
		setTimeout( function(){
			service.sideInfo.update_controller();
		} )
	};

	service.sideInfo.force_first_page = function(){
		service.sideInfo.reset();
		service.sideInfo.load();
	}

	service.sideInfo.scroll = function( action ){
		var container = $('.support-chat-contents-scroll');
		switch( action ){
			case 'begin':
				$timeout( function(){
					container.stop( true, false ).animate( { scrollTop: container[0].scrollHeight }, 0 );
					service.sideInfo.release();
				}, 300 );
				break;
			case 'current':
				service._private.current_scroll = container[0].scrollHeight;
				break;
			default:
				var position = action;
				setTimeout(function() {
					var finalScroll = container[0].scrollHeight;
					var goToScroll = finalScroll - service._private.current_scroll;
					container[0].scrollTop = goToScroll;
					service.sideInfo.release();
				}, 100 );
				break;
		}
	}

	service.sideInfo.release = function(){
		setTimeout(function() { service._private.could_load = true }, 500 );
	}

	service.sideInfo.add_message = function( message ){
		service.sideInfo.data.messages.push( message );
		service.sideInfo.data.total++;
		service.sideInfo.data.loaded++;
		service.sideInfo.update_controller();
		service.sideInfo.scroll( 'begin' );
	}

	service.sideInfo.load_ticket_page = function(){
		if( service.sideInfo.id_support ){
			MainNavigationService.link( '/ticket/' + service.sideInfo.id_support );
		}
	}

	service.sideInfo.update_controller = function(){
		$rootScope.$broadcast( 'triggerTicketInfoUpdated', service.sideInfo.data );
	}

	service.sideInfo.load = function(){

		if( service.sideInfo.id_support ){
			if( !service._private.could_load ){
				return false;
			}
			if( service.sideInfo.data.total !== null && service.sideInfo.data.loaded >= service.sideInfo.data.total ){
				return;
			}
			service._private.could_load = false;

			service.sideInfo.data.page++;

			var params = { id_support: service.sideInfo.id_support, page: service.sideInfo.data.page };

			TicketService.side_info( params, function( data ){
				service.sideInfo.scroll( 'current' );
				service.sideInfo.data.pexcard = data.pexcard;
				service.sideInfo.data.restaurant = data.restaurant;
				service.sideInfo.data.order = data.order;
				service.sideInfo.data.total = data.messages.total;
				var messages = [];
				for( x in data.messages.list ){
					if( data.messages.list[ x ].id_support_message ){
						messages.push( data.messages.list[ x ] );
					}
				}
				for( x in service.sideInfo.data.messages ){
					if( service.sideInfo.data.messages[ x ].id_support_message ){
						messages.push( service.sideInfo.data.messages[ x ] );
					}
				}
				service.sideInfo.data.messages = messages;
				service.sideInfo.data.loaded = service.sideInfo.data.messages.length;
				service.sideInfo.data.has_more = ( service.sideInfo.data.loaded >= service.sideInfo.data.total ) ? false : true;
				service.sideInfo.update_controller();
				if( service._private.first_load ){
					service.sideInfo.scroll( 'begin' );
					service._private.first_load = false;
					service.sideInfo.load_ticket_page();
					$rootScope.$broadcast( 'triggerSideViewTicket', {} );
				} else {
					service.sideInfo.scroll();
				}
			} );
			return true;
		}
		return false;
	};

	service.setViewTicket = function(id) {
		service.scope.viewTicket = id;
		service.sideInfo.setTicket( id );
	};

	$rootScope.$on('triggerViewTicket', function(e, ticket) {

		if( service.scope.viewTicket && service.scope.ticket &&
				service.scope.viewTicket.id_support == ticket.id_support &&
				service.scope.ticket.id_support == ticket.id_support ){
			service.sideInfo.force_first_page();
			return;
		}

		NotificationService.check();

		service.scope.viewTicket = ticket;
		service.scope.ticket = ticket;

		if (service.scope.viewTicket) {
			if( typeof service.scope.viewTicket == 'object' ){
				var id_support = service.scope.viewTicket.id_support
			} else {
				var id_support = service.scope.viewTicket;
			}
			service.socket.emit('event.subscribe', 'ticket.' + id_support);
		}
	});

	var notified  = new Array();

	$rootScope.$on('userAuthUpdated', function(e, data) {

		if (AccountService.user && AccountService.user.id_admin) {

			service.socket.emit('event.subscribe', 'user.preference.' + AccountService.user.id_admin );

			SocketService.listen( 'user.preference.' + AccountService.user.id_admin, $rootScope).on( 'user.preference', function( payload ){
				console.log('payload',payload);
				console.log('payload',payload);
				console.log('payload',payload);
				console.log('payload',payload);
				console.log('payload',payload);
				// AccountService.user.prefs['notification-desktop-support-all'] = payload;
			} );

			if (AccountService.isSupport) {

				// if( AccountService.user && AccountService.user.prefs && AccountService.user.prefs[ 'notification-desktop-support-all' ] === true ){
				// 	console.debug('Subscribing to all tickets: auth event');
				// 	service.socket.emit('event.subscribe', 'ticket.all');
				// 	service.socket.emit('event.subscribe', 'tickets');
				// } else {
				// 	console.debug('Unsubscribing to all tickets: auth event');
				// 	service.socket.emit('event.unsubscribe', 'ticket.all');
				// 	service.socket.emit('event.unsubscribe', 'tickets');
				// }

				service.socket.emit('event.subscribe', 'ticket.update');

				SocketService.listen('ticket.update', $rootScope).on( 'change_ticket_status', function(){
					$rootScope.$broadcast( 'updateSideTickets' );
					$rootScope.$broadcast( 'updateHeartbeat' );
				} )

				SocketService.listen('tickets', $rootScope)
					.on('message', function(d) {

						if( AccountService.user && AccountService.user.prefs && AccountService.user.prefs[ 'notification-desktop-support-all' ] === false ){
							return;
						}

						console.debug('Recieved chat message: ', d);

						if (notified.indexOf(d.id_support_message) > -1) {
							console.log('already notified ', d.id_support_message);
							return;
						}

						notified.push(d.id_support_message);

						// update the chat room
						console.log('service.sideInfo.id_support',service.sideInfo.id_support);
						console.log('d.id_support',d.id_support);
						if( service.sideInfo.id_support && d.id_support && parseInt( service.sideInfo.id_support ) != parseInt( d.id_support ) ){
							console.log('force_first_page??');
							// service.sideInfo.force_first_page();
						}
console.log('d.from',d.from);
						// https://github.com/crunchbutton/crunchbutton/issues/7579#issuecomment-172934677
						if (d.from == 'rep' ) {
							return;
						}
console.log('d.id_support',d.id_support);
console.log('service.scope.viewTicket',service.scope.viewTicket);
						if (d.id_support == service.scope.viewTicket) {
							//App.playAudio('support-message-recieved');
						} else {
							//App.playAudio('support-message-new');
						}
console.log('d.name',d.name);
console.log('d.body',d.body);
						NotificationService.notify(d.name, d.body, null, function() {
							try{
								if( document.getElementById('support-chat-box') ){
									document.getElementById('support-chat-box').focus();
								}
							}catch(e){}

						});

					})
					.on( 'sms_status', function( d ){

						console.debug('Recieved sms status update: ', d);

						updateSmsStatus( d );
					} )

			}

		} else {
			//service.socket.close();
			//service.socket = null;
		}
	});

	var updateSmsStatus = function( d ){
		var id_support_message = d.id_support_message;
		var status = d.status;
		var element = $( '#support-message-status-' + id_support_message );
		if( element && element.length ){
			element.attr( 'title', 'Status: ' + status );
		}
	}

	service.send = function(message, add_as_note, callback) {
		var add_as_note = ( add_as_note ? true : false );
		var guid = App.guid();
		console.log('guid',guid);
		if( !service.sideInfo.id_support ){
			return;
		}
		TicketService.message( {
			id_support: service.sideInfo.id_support,
			body: message,
			guid: guid,
			note: add_as_note
		},
		// callback
		function(d) {
			if(!d.status){
				d.status = 'queued';
			}

			for ( var x in service.sideInfo.data.messages ) {
				if ( service.sideInfo.data.messages[x].guid == guid ) {
					d.guid = guid;
					service.sideInfo.data.messages[x] = d;
					notified.push( d.id_support_message );
					break;
				}
			}
		});
		if( callback ){
			callback()
		} else {
			service.scope.$apply(function() {
				console.log('no callback');
				service.sideInfo.add_message( { body: message, name: AccountService.user.firstName, timestamp: new Date().getTime(), sending: true, guid: guid, status: 'queued' } );
			});
		}
		$rootScope.$broadcast( 'replyFinished' );
	};

	service.scroll = function(instant) {
		setTimeout(function() {
			if( $('.support-chat-contents-scroll').length ){
				$('.support-chat-contents-scroll').stop(true,false).animate({
					scrollTop: $('.support-chat-contents-scroll')[0].scrollHeight
				}, instant ? 0 : 800);
			}
		}, 100);
	};

	/*
	var typingTimer;

	service.typing = function(val) {
		return;
		if (!service.isTyping) {
			service.isTyping = true;
			service.websocket.send({
				type: 'ticket.typing.start'
			});

		} else {
			if (!val) {
				service.isTyping = false;
				service.websocket.send({
					type: 'ticket.typing.stop'
				});
			}
		}

		if (typingTimer) {
			clearTimeout(typingTimer);
		}
		typingTimer = setTimeout(function() {
			if (service.isTyping) {
				service.isTyping = false;
				service.websocket.send({
					type: 'ticket.typing.stop'
				});
			}
		}, 5000);
	};
	*/

	return service;
});
<|endoftext|>


<commit_before>'use strict';

const { NotAuthorizedError, UnsupportedMediaTypeError } = require('restify-errors'),
  config = require('config'),
  apicache = require('apicache'),
  got = require('got');

const addCache = function addCache (duration, group) {
  // configure the apicache, set the group and only cache response code 200 responses
  const apicacheMiddlewareFunction = function apicacheMiddlewareFunction (req, res) {
    req.apicacheGroup = group;

    return res.statusCode === 200;
  };

  return apicache.middleware(duration, apicacheMiddlewareFunction);
};

const clearCache = function clearCache (identifiers) {
  if (Array.isArray(identifiers)) {
    for (const identifier of identifiers) {
      apicache.clear(identifier);
    }
  } else {
    apicache.clear(identifiers);
  }
};

/**
 * @apiDefine ContentTypeJSON
 *
 * @apiHeader {String="application/json","application/json; charset=utf-8"} content-type
 * @apiError {Object} 415 the request has invalid or missing content type.
 * @apiErrorExample {json} Error-Response:
 *     HTTP/1.1 415 Unsupported Media Type
 *     {"code":"NotAuthorized","message":"Unsupported content-type. Try application/json"}
 */
const checkContentType = function (req, res, next) {
  if (!req.is('json')) {
    return next(new UnsupportedMediaTypeError('Unsupported content-type. Try application/json'));
  }

  return next();
};

const validUnsecuredPathRegex = new RegExp(`^\\${config.get('routes.boxes')}/[a-f\\d]{24}/((data)|([a-f\\d]{24}))/?$`, 'i');
const preRequest = function preRequest (request, response, next) {
  response.charSet('utf-8');
  request.log.info({ req: request });

  if (process.env.NODE_ENV === 'production'
    && (!request.headers['x-forwarded-proto'] || request.headers['x-forwarded-proto'] !== 'https')) {
    if (request.method !== 'POST' || !validUnsecuredPathRegex.test(request.url)) {
      return next(new NotAuthorizedError('Access through http is not allowed'));
    }
  }

  return next();
};

// sends out CORS headers
const preCors = function preCors (request, response, next) {
  if (!response.getHeader('access-control-allow-origin')) {
    response.header('access-control-allow-origin', '*');
  }

  if (!response.getHeader('access-control-allow-methods')) {
    const allowedMethods = new Set(['OPTIONS']);
    if (request.header('access-control-request-method')) {
      allowedMethods.add(request.header('access-control-request-method').toUpperCase());
    }
    allowedMethods.add(request.method.toUpperCase());

    response.header('access-control-allow-methods', Array.from(allowedMethods)
      .reverse()
      .join(', '));
  }

  if (!response.getHeader('access-control-allow-headers')) {
    const allowedHeaders = new Set(['authorization']);
    if (request.header('access-control-request-headers')) {
      allowedHeaders.add(request.header('access-control-request-headers').toLowerCase());
    }

    response.header('access-control-allow-headers', Array.from(allowedHeaders).join(', '));
  }

  if (!response.getHeader('access-control-max-age')) {
    response.header('access-control-max-age', 600);
  }

  if (request.method === 'OPTIONS') {
    return response.send(204);
  }

  return next();
};

let Honeybadger = {
  notify () { },
  resetContext () { }
};

/* eslint-disable global-require */
if (config.get('honeybadger_apikey')) {
  Honeybadger = require('honeybadger').configure({
    apiKey: config.get('honeybadger_apikey')
  });
}
/* eslint-enable global-require */

const postToSlack = function postToSlack (text) {
  if (config.get('slack_url')) {
    got(config.get('slack_url'), {
      json: true,
      body: { text },
      retries: 0
    })
      // swallow errors, we don't care
      .catch(() => { });
  }
};

const redactEmail = function redactEmail (email) {
  /* eslint-disable prefer-const */
  let [name = '', domain = ''] = email.split('@');
  /* eslint-enable prefer-const */

  let [hostname = '', tld = ''] = domain.split('.');

  tld = `${tld.slice(0, 1)}**`;
  hostname = `${hostname.slice(0, 3)}****`;
  name = `${name.slice(0, 3)}****`;

  return `${name}@${hostname}.${tld}`;
};

const getVersion = (function () {
  try {
    /* eslint-disable global-require */
    const version = require('../../../../version');
    /* eslint-enable global-require */

    console.log(version);

    return version;
  } catch (err) {
    return 'unknown version';
  }
})();

module.exports = {
  addCache,
  clearCache,
  checkContentType,
  preRequest,
  preCors,
  Honeybadger,
  postToSlack,
  getVersion,
  redactEmail
};
<commit_msg>(api) remove console.log from commit before<commit_after>'use strict';

const { NotAuthorizedError, UnsupportedMediaTypeError } = require('restify-errors'),
  config = require('config'),
  apicache = require('apicache'),
  got = require('got');

const addCache = function addCache (duration, group) {
  // configure the apicache, set the group and only cache response code 200 responses
  const apicacheMiddlewareFunction = function apicacheMiddlewareFunction (req, res) {
    req.apicacheGroup = group;

    return res.statusCode === 200;
  };

  return apicache.middleware(duration, apicacheMiddlewareFunction);
};

const clearCache = function clearCache (identifiers) {
  if (Array.isArray(identifiers)) {
    for (const identifier of identifiers) {
      apicache.clear(identifier);
    }
  } else {
    apicache.clear(identifiers);
  }
};

/**
 * @apiDefine ContentTypeJSON
 *
 * @apiHeader {String="application/json","application/json; charset=utf-8"} content-type
 * @apiError {Object} 415 the request has invalid or missing content type.
 * @apiErrorExample {json} Error-Response:
 *     HTTP/1.1 415 Unsupported Media Type
 *     {"code":"NotAuthorized","message":"Unsupported content-type. Try application/json"}
 */
const checkContentType = function (req, res, next) {
  if (!req.is('json')) {
    return next(new UnsupportedMediaTypeError('Unsupported content-type. Try application/json'));
  }

  return next();
};

const validUnsecuredPathRegex = new RegExp(`^\\${config.get('routes.boxes')}/[a-f\\d]{24}/((data)|([a-f\\d]{24}))/?$`, 'i');
const preRequest = function preRequest (request, response, next) {
  response.charSet('utf-8');
  request.log.info({ req: request });

  if (process.env.NODE_ENV === 'production'
    && (!request.headers['x-forwarded-proto'] || request.headers['x-forwarded-proto'] !== 'https')) {
    if (request.method !== 'POST' || !validUnsecuredPathRegex.test(request.url)) {
      return next(new NotAuthorizedError('Access through http is not allowed'));
    }
  }

  return next();
};

// sends out CORS headers
const preCors = function preCors (request, response, next) {
  if (!response.getHeader('access-control-allow-origin')) {
    response.header('access-control-allow-origin', '*');
  }

  if (!response.getHeader('access-control-allow-methods')) {
    const allowedMethods = new Set(['OPTIONS']);
    if (request.header('access-control-request-method')) {
      allowedMethods.add(request.header('access-control-request-method').toUpperCase());
    }
    allowedMethods.add(request.method.toUpperCase());

    response.header('access-control-allow-methods', Array.from(allowedMethods)
      .reverse()
      .join(', '));
  }

  if (!response.getHeader('access-control-allow-headers')) {
    const allowedHeaders = new Set(['authorization']);
    if (request.header('access-control-request-headers')) {
      allowedHeaders.add(request.header('access-control-request-headers').toLowerCase());
    }

    response.header('access-control-allow-headers', Array.from(allowedHeaders).join(', '));
  }

  if (!response.getHeader('access-control-max-age')) {
    response.header('access-control-max-age', 600);
  }

  if (request.method === 'OPTIONS') {
    return response.send(204);
  }

  return next();
};

let Honeybadger = {
  notify () { },
  resetContext () { }
};

/* eslint-disable global-require */
if (config.get('honeybadger_apikey')) {
  Honeybadger = require('honeybadger').configure({
    apiKey: config.get('honeybadger_apikey')
  });
}
/* eslint-enable global-require */

const postToSlack = function postToSlack (text) {
  if (config.get('slack_url')) {
    got(config.get('slack_url'), {
      json: true,
      body: { text },
      retries: 0
    })
      // swallow errors, we don't care
      .catch(() => { });
  }
};

const redactEmail = function redactEmail (email) {
  /* eslint-disable prefer-const */
  let [name = '', domain = ''] = email.split('@');
  /* eslint-enable prefer-const */

  let [hostname = '', tld = ''] = domain.split('.');

  tld = `${tld.slice(0, 1)}**`;
  hostname = `${hostname.slice(0, 3)}****`;
  name = `${name.slice(0, 3)}****`;

  return `${name}@${hostname}.${tld}`;
};

const getVersion = (function () {
  try {
    /* eslint-disable global-require */
    const version = require('../../../../version');
    /* eslint-enable global-require */

    return version;
  } catch (err) {
    return 'unknown version';
  }
})();

module.exports = {
  addCache,
  clearCache,
  checkContentType,
  preRequest,
  preCors,
  Honeybadger,
  postToSlack,
  getVersion,
  redactEmail
};
<|endoftext|>


<commit_before>const { param } = require("jquery");

define([
    'arches',
    'jquery',
    'underscore',
    'knockout',
    'knockout-mapping',
    'viewmodels/alert',
    'viewmodels/workflow-step'
], function(arches, $, _, ko, koMapping, AlertViewModel, Step) {
    var Workflow = function(config) {
        var self = this;

        this.steps = config.steps || [];
        this.activeStep = ko.observable();
        this.previousStep = ko.observable();
        this.hoverStep = ko.observable();
        this.ready = ko.observable(false);
        this.tabbedWorkflow = ko.observable(ko.unwrap(config.tabbedWorkflow));
        this.loading = config.loading || ko.observable(false);
        this.alert = config.alert || ko.observable(null);
        this.state = {steps:[]};
        this.quitUrl = arches.urls.home;
        this.wastebinWarning = function(val){
            return [[arches.translations.workflowWastbinWarning.replace("${val}", val)],[arches.translations.workflowWastbinWarning2]];
        };
        this.warning = '';

        this.workflowName = ko.observable();
        this.getJSON = function(pluginJsonFileName) {
            $.ajax({
                type: "GET",
                url: arches.urls.plugin(pluginJsonFileName),
                data: { "json":true },
                context: self,
                success: function(workflowJson){ self.workflowName(workflowJson.name); }
            });
        };

        this.restoreStateFromURL = function(){
            var urlparams = new window.URLSearchParams(window.location.search);
            var res = {};
            var pathArray = window.location.pathname.split('/');
            res.workflowid = pathArray[2];
            urlparams.forEach(function(v, k){res[k] = v;});
            res.steps = res.steps ? JSON.parse(res.steps) : [];
            this.state = res;
        };
        this.canFinish = ko.observable(false);

        this.checkCanFinish = function(){
            var required = false, canFinish = true, complete = null;
            for(var i = 0; i < self.steps.length; i++) {
                required = ko.unwrap(self.steps[i].required);
                complete = ko.unwrap(self.steps[i].complete);
                if(!complete && required) {
                    canFinish = false;
                    break;
                }
            }
            self.canFinish(canFinish);
        };
        this.activeStep.subscribe(function() {
            self.checkCanFinish();
        });

        this.finishWorkflow = function() {
            if(self.canFinish()){ self.activeStep(self.steps[self.steps.length-1]); }
        };

        this.quitWorkflow = function(){
            var resourcesToDelete = [];
            var tilesToDelete = [];
            var warnings = []
            self.state.steps.forEach(function(step) {
                if (step.wastebin && step.wastebin.resourceid) {
                    warnings.push(step.wastebin.description);
                    resourcesToDelete.push(step.wastebin);
                } else if (step.wastebin && step.wastebin.tile) {
                    warnings.push(step.wastebin.description);
                    tilesToDelete.push(step.wastebin);
                }
            });
            self.warning = self.wastebinWarning(warnings.join());
            var deleteObject = function(type, obj){
                if (type === 'resource') {
                    $.ajax({
                        url: arches.urls.api_resources(obj),
                        type: 'DELETE',
                        success: function(result) {
                            console.log('result', result);
                        }
                    });
                } else if (type === 'tile') {
                    $.ajax({
                        type: "DELETE",
                        url: arches.urls.tile,
                        data: JSON.stringify(obj)
                    }).done(function(response) {
                        console.log('deleted', obj.tileid);
                    }).fail(function(response) {
                        if (typeof onFail === 'function') {
                            console.log(response);
                        }
                    });
                }
            };

            self.alert(
                new AlertViewModel(
                    'ep-alert-red',
                    self.warning[0],
                    self.warning[1],
                    null,
                    function(){
                        resourcesToDelete.forEach(function(resource){deleteObject('resource', resource.resourceid);});
                        tilesToDelete.forEach(function(tile){deleteObject('tile', tile.tile);});
                        window.location.href = self.quitUrl;
                    }
                )
            );
        };

        this.restoreStateFromURL();

        this.ready.subscribe(function() {
            var components = _.unique(self.steps.map(function(step) {return step.component;}));
            require(components, function() {
                // var modules = arguments;
                var stateStepCount = self.state.steps.length;
                self.steps.forEach(function(step, i) {
                    if (!(self.steps[i] instanceof Step)) {
                        step.workflow = self;
                        step.loading = self.loading;
                        step.alert = self.alert;
                        self.steps[i] = new Step(step);
                        if (stateStepCount !== 0 && i <= stateStepCount) {
                            if(self.state.steps[i]) {
                                self.steps[i].complete(self.state.steps[i].complete);
                            }
                        }
                        self.steps[i].complete.subscribe(function(complete) {
                            if (complete && self.steps[i].autoAdvance()) self.next();
                        });
                    }
                    self.steps[i]._index = i;
                });
                if (self.state.activestep) {
                    self.activeStep(self.steps[self.state.activestep]);
                }
                else if(self.steps.length > 0) {
                    self.activeStep(self.steps[0]);
                }
            });
        });

        this.updateUrl = function() {
            //Updates the url with the parameters needed for the next step
            var urlparams = JSON.parse(JSON.stringify(self.state)); //deep copy
            urlparams.steps = JSON.stringify(self.state.steps);
            history.pushState(null, '', window.location.pathname + '?' + $.param(urlparams));
        };

        this.updateState = function(val) {
            //Collects information from the previous step and sets it to the URL
            var activeStep = val;
            var previousStep = self.previousStep();
            var resourceId;
            if (previousStep && previousStep.hasOwnProperty('defineStateProperties')) {
                self.state.steps[previousStep._index] = previousStep.defineStateProperties();
                self.state.steps[previousStep._index].complete = ko.unwrap(previousStep.complete);
                self.state.activestep = val._index;
                self.state.previousstep = previousStep._index;
                if (!self.state.resourceid) {
                    resourceId = !!previousStep.resourceid ? ko.unwrap(previousStep.resourceid) : null;
                    self.state.resourceid = resourceId;
                }
                self.updateUrl();
            }
            self.previousStep(activeStep);
        };

        this.canStepBecomeActive = function(step) {
            var canStepBecomeActive = false;

            if (step && !step.active()) {  /* prevents refresh if clicking on active tab */
                var previousStep = self.steps[step._index - 1];

                if (
                    step.complete()
                    || ( previousStep && previousStep.complete() )
                    || self.canFinish() === true
                ) {
                    canStepBecomeActive = true;
                }
            }

            return canStepBecomeActive;
        };

        this.next = function(){
            var activeStep = self.activeStep();

            if (activeStep && (activeStep.complete() || !activeStep.required()) && activeStep._index < self.steps.length - 1) {
                self.activeStep(self.steps[activeStep._index+1]);
            }
        };

        this.back = function(){
            var activeStep = self.activeStep();
            if (activeStep && activeStep._index > 0) {
                self.activeStep(self.steps[activeStep._index - 1]);
            }
        };
    };
    return Workflow;
});
<commit_msg>nit #6972<commit_after>define([
    'arches',
    'jquery',
    'underscore',
    'knockout',
    'knockout-mapping',
    'viewmodels/alert',
    'viewmodels/workflow-step'
], function(arches, $, _, ko, koMapping, AlertViewModel, Step) {
    var Workflow = function(config) {
        var self = this;

        this.steps = config.steps || [];
        this.activeStep = ko.observable();
        this.previousStep = ko.observable();
        this.hoverStep = ko.observable();
        this.ready = ko.observable(false);
        this.tabbedWorkflow = ko.observable(ko.unwrap(config.tabbedWorkflow));
        this.loading = config.loading || ko.observable(false);
        this.alert = config.alert || ko.observable(null);
        this.state = {steps:[]};
        this.quitUrl = arches.urls.home;
        this.wastebinWarning = function(val){
            return [[arches.translations.workflowWastbinWarning.replace("${val}", val)],[arches.translations.workflowWastbinWarning2]];
        };
        this.warning = '';

        this.workflowName = ko.observable();
        this.getJSON = function(pluginJsonFileName) {
            $.ajax({
                type: "GET",
                url: arches.urls.plugin(pluginJsonFileName),
                data: { "json":true },
                context: self,
                success: function(workflowJson){ self.workflowName(workflowJson.name); }
            });
        };

        this.restoreStateFromURL = function(){
            var urlparams = new window.URLSearchParams(window.location.search);
            var res = {};
            var pathArray = window.location.pathname.split('/');
            res.workflowid = pathArray[2];
            urlparams.forEach(function(v, k){res[k] = v;});
            res.steps = res.steps ? JSON.parse(res.steps) : [];
            this.state = res;
        };
        this.canFinish = ko.observable(false);

        this.checkCanFinish = function(){
            var required = false, canFinish = true, complete = null;
            for(var i = 0; i < self.steps.length; i++) {
                required = ko.unwrap(self.steps[i].required);
                complete = ko.unwrap(self.steps[i].complete);
                if(!complete && required) {
                    canFinish = false;
                    break;
                }
            }
            self.canFinish(canFinish);
        };
        this.activeStep.subscribe(function() {
            self.checkCanFinish();
        });

        this.finishWorkflow = function() {
            if(self.canFinish()){ self.activeStep(self.steps[self.steps.length-1]); }
        };

        this.quitWorkflow = function(){
            var resourcesToDelete = [];
            var tilesToDelete = [];
            var warnings = []
            self.state.steps.forEach(function(step) {
                if (step.wastebin && step.wastebin.resourceid) {
                    warnings.push(step.wastebin.description);
                    resourcesToDelete.push(step.wastebin);
                } else if (step.wastebin && step.wastebin.tile) {
                    warnings.push(step.wastebin.description);
                    tilesToDelete.push(step.wastebin);
                }
            });
            self.warning = self.wastebinWarning(warnings.join());
            var deleteObject = function(type, obj){
                if (type === 'resource') {
                    $.ajax({
                        url: arches.urls.api_resources(obj),
                        type: 'DELETE',
                        success: function(result) {
                            console.log('result', result);
                        }
                    });
                } else if (type === 'tile') {
                    $.ajax({
                        type: "DELETE",
                        url: arches.urls.tile,
                        data: JSON.stringify(obj)
                    }).done(function(response) {
                        console.log('deleted', obj.tileid);
                    }).fail(function(response) {
                        if (typeof onFail === 'function') {
                            console.log(response);
                        }
                    });
                }
            };

            self.alert(
                new AlertViewModel(
                    'ep-alert-red',
                    self.warning[0],
                    self.warning[1],
                    null,
                    function(){
                        resourcesToDelete.forEach(function(resource){deleteObject('resource', resource.resourceid);});
                        tilesToDelete.forEach(function(tile){deleteObject('tile', tile.tile);});
                        window.location.href = self.quitUrl;
                    }
                )
            );
        };

        this.restoreStateFromURL();

        this.ready.subscribe(function() {
            var components = _.unique(self.steps.map(function(step) {return step.component;}));
            require(components, function() {
                // var modules = arguments;
                var stateStepCount = self.state.steps.length;
                self.steps.forEach(function(step, i) {
                    if (!(self.steps[i] instanceof Step)) {
                        step.workflow = self;
                        step.loading = self.loading;
                        step.alert = self.alert;
                        self.steps[i] = new Step(step);
                        if (stateStepCount !== 0 && i <= stateStepCount) {
                            if(self.state.steps[i]) {
                                self.steps[i].complete(self.state.steps[i].complete);
                            }
                        }
                        self.steps[i].complete.subscribe(function(complete) {
                            if (complete && self.steps[i].autoAdvance()) self.next();
                        });
                    }
                    self.steps[i]._index = i;
                });
                if (self.state.activestep) {
                    self.activeStep(self.steps[self.state.activestep]);
                }
                else if(self.steps.length > 0) {
                    self.activeStep(self.steps[0]);
                }
            });
        });

        this.updateUrl = function() {
            //Updates the url with the parameters needed for the next step
            var urlparams = JSON.parse(JSON.stringify(self.state)); //deep copy
            urlparams.steps = JSON.stringify(self.state.steps);
            history.pushState(null, '', window.location.pathname + '?' + $.param(urlparams));
        };

        this.updateState = function(val) {
            //Collects information from the previous step and sets it to the URL
            var activeStep = val;
            var previousStep = self.previousStep();
            var resourceId;
            if (previousStep && previousStep.hasOwnProperty('defineStateProperties')) {
                self.state.steps[previousStep._index] = previousStep.defineStateProperties();
                self.state.steps[previousStep._index].complete = ko.unwrap(previousStep.complete);
                self.state.activestep = val._index;
                self.state.previousstep = previousStep._index;
                if (!self.state.resourceid) {
                    resourceId = !!previousStep.resourceid ? ko.unwrap(previousStep.resourceid) : null;
                    self.state.resourceid = resourceId;
                }
                self.updateUrl();
            }
            self.previousStep(activeStep);
        };

        this.canStepBecomeActive = function(step) {
            var canStepBecomeActive = false;

            if (step && !step.active()) {  /* prevents refresh if clicking on active tab */
                var previousStep = self.steps[step._index - 1];

                if (
                    step.complete()
                    || ( previousStep && previousStep.complete() )
                    || self.canFinish() === true
                ) {
                    canStepBecomeActive = true;
                }
            }

            return canStepBecomeActive;
        };

        this.next = function(){
            var activeStep = self.activeStep();

            if (activeStep && (activeStep.complete() || !activeStep.required()) && activeStep._index < self.steps.length - 1) {
                self.activeStep(self.steps[activeStep._index+1]);
            }
        };

        this.back = function(){
            var activeStep = self.activeStep();
            if (activeStep && activeStep._index > 0) {
                self.activeStep(self.steps[activeStep._index - 1]);
            }
        };
    };
    return Workflow;
});
<|endoftext|>


<commit_before>import React from 'react';

class DinoScene extends React.Component {
  constructor(props) {
    super(props);
  }

  render () {
    return (
      <a-scene>
      <a-assets>
        <a-asset-item id="asstronautDae" src="/assets/John_glenn/model.dae" />
        <a-asset-item id="stall" src="/assets/Toilet_Stall.dae" />
      </a-assets>
      <a-sky src='/assets/prehistoric.jpg'/>
      <a-model src="/assets/dino.dae" position='10 0 10' rotation='0 90 0'>
      <a-animation
          attribute='rotation'
          dur='1000'
          from='10 0 10'
          to='0 10 100'
          repeat='indefinite'
        />
      </a-model>

      <a-plane id='ground' src='/assets/ground.jpg' position='0 0 0' rotation='-90 0 0' width='70' height='50' />
      <a-entity position='0 1.5 0'>
        <a-camera id='camera' wasd-controls-enabled='false'/>
      </a-entity>
      {/*<a-collada-model src='#asstronautDae' position='0 -0.5 0' rotation='0 180 0'/>*/}

      <a-entity position='0 10 -10'>
        <a-plane src='/assets/ptero.png' transparent='true' width='3' height='2' rotation='90 0 0'/>
        <a-animation
          attribute='position'
          dur='15000'
          from='0 10 -100'
          to='0 10 100'
          repeat='indefinite'
        />
      </a-entity>
      <a-collada-model scale="2.3 1.5 2" src='#stall' position='1.2 0 1' rotation='0 180 0'/>

      </a-scene>
    );
  }
};

module.exports = DinoScene;
<commit_msg>Move dino around view<commit_after>import React from 'react';

class DinoScene extends React.Component {
  constructor(props) {
    super(props);
  }

  render () {
    return (
      <a-scene>
      <a-assets>
        <a-asset-item id="asstronautDae" src="/assets/John_glenn/model.dae" />
        <a-asset-item id="stall" src="/assets/Toilet_Stall.dae" />
      </a-assets>
      <a-sky src='/assets/prehistoric.jpg'/>
      <a-entity>
        <a-model src="/assets/dino.dae" position='0 0 0' rotation='0 90 0'>

        </a-model>
        <a-animation attribute="rotation"
                     dur="10000"
                     fill="forwards"
                     to="0 360 0"
                     repeat="indefinite"/>
      </a-entity>

      <a-plane id='ground' src='/assets/ground.jpg' position='0 0 0' rotation='-90 0 0' width='70' height='50' />
      <a-entity position='0 1.5 0'>
        <a-camera id='camera' wasd-controls-enabled='false'/>
      </a-entity>
      {/*<a-collada-model src='#asstronautDae' position='0 -0.5 0' rotation='0 180 0'/>*/}

      <a-entity position='0 10 -10'>
        <a-plane src='/assets/ptero.png' transparent='true' width='3' height='2' rotation='90 0 0'/>
        <a-animation
          attribute='position'
          dur='15000'
          from='0 10 -100'
          to='0 10 100'
          repeat='indefinite'
        />
      </a-entity>
      <a-collada-model scale="2.3 1.5 2" src='#stall' position='1.2 0 1' rotation='0 180 0'/>

      </a-scene>
    );
  }
};

module.exports = DinoScene;
<|endoftext|>


<commit_before>var commonModal = require('client/components/modal_common/index');
var createSubnet = require('../../../subnet/pop/create_subnet/index');
var config = require('./config.json');
var request = require('../../request');
var __ = require('locale/client/dashboard.lang.json');

var copyObj = function(obj) {
  var newobj = obj.constructor === Array ? [] : {};
  if (typeof obj !== 'object') {
    return newobj;
  } else {
    newobj = JSON.parse(JSON.stringify(obj));
  }
  return newobj;
};

var getAvailableSubnets = function(data, refs) {
  var subnets = copyObj(data);
  var subnetGroup = [],
    hasAvailableSubnet = false;
  subnets.forEach((s) => {
    if (s.router.id) {
      s.disabled = true;
    } else if (s.gateway_ip === null) {
      s.disabled = true;
    } else {
      if(!s.network.shared) {
        hasAvailableSubnet = true;
      }
    }
  });

  subnets.forEach((subnet) => {
    if (!subnet.network.shared) {
      var hasGroup = subnetGroup.some((group) => {
        if (group.id === subnet.network_id) {
          group.data.push(subnet);
          return true;
        }
        return false;
      });
      if (!hasGroup) {
        subnetGroup.push({
          id: subnet.network_id,
          name: subnet.network.name || '(' + subnet.network.id.substr(0, 8) + ')',
          data: [subnet]
        });
      }
    }
  });

  if (hasAvailableSubnet) {
    if(hasAvailableSubnet) {
      refs.btn.setState({
        disabled: false
      });
    }
  }
  subnets.some((s) => {
    if (!s.disabled && !s.network.shared) {
      refs.subnet.setState({
        value: s.id
      });
      return true;
    }
    return false;
  });

  return subnetGroup;
};

function pop(obj, parent, callback) {
  config.fields[0].text = obj.name || '(' + obj.id.substr(0, 8) + ')';

  var props = {
    __: __,
    parent: parent,
    config: config,
    onInitialize: function(refs) {
      request.getSubnets(false).then(res => {
        var mySubnets = getAvailableSubnets(res, refs);
        refs.subnet.setState({
          data: mySubnets
        });
      });
    },
    onConfirm: function(refs, cb) {
      request.addInterface(obj.id, {
        subnet_id: refs.subnet.state.value
      }).then((res) => {
        callback && callback();
        cb(true);
      });
    },
    onAction: function(field, status, refs) {
      switch(field) {
        case 'subnet':
          if(status.clicked === true && refs.subnet.state.data.length === 0) {
            refs.subnet.setState({
              clicked: false
            });
            createSubnet(null, null, function() {
              request.getSubnets(true).then(res => {
                var mySubnets = getAvailableSubnets(res, refs);
                refs.subnet.setState({
                  data: mySubnets
                });
              });
            });
          }
          break;
        default:
          break;
      }
    }
  };

  commonModal(props);
}

module.exports = pop;
<commit_msg>filter subnet in join subnet in router<commit_after>var commonModal = require('client/components/modal_common/index');
var createSubnet = require('../../../subnet/pop/create_subnet/index');
var config = require('./config.json');
var request = require('../../request');
var __ = require('locale/client/dashboard.lang.json');

var getAvailableSubnets = function(data, refs) {
  var subnets = data.filter((ele) => !ele.network['router:external']);
  var subnetGroup = [],
    hasAvailableSubnet = false;
  subnets.forEach((s) => {
    if (s.router.id) {
      s.disabled = true;
    } else if (s.gateway_ip === null) {
      s.disabled = true;
    } else {
      if(!s.network.shared) {
        hasAvailableSubnet = true;
      }
    }
  });

  subnets.forEach((subnet) => {
    if (!subnet.network.shared) {
      var hasGroup = subnetGroup.some((group) => {
        if (group.id === subnet.network_id) {
          group.data.push(subnet);
          return true;
        }
        return false;
      });
      if (!hasGroup) {
        subnetGroup.push({
          id: subnet.network_id,
          name: subnet.network.name || '(' + subnet.network.id.substr(0, 8) + ')',
          data: [subnet]
        });
      }
    }
  });

  if (hasAvailableSubnet) {
    if(hasAvailableSubnet) {
      refs.btn.setState({
        disabled: false
      });
    }
  }
  subnets.some((s) => {
    if (!s.disabled && !s.network.shared) {
      refs.subnet.setState({
        value: s.id
      });
      return true;
    }
    return false;
  });

  return subnetGroup;
};

function pop(obj, parent, callback) {
  config.fields[0].text = obj.name || '(' + obj.id.substr(0, 8) + ')';

  var props = {
    __: __,
    parent: parent,
    config: config,
    onInitialize: function(refs) {
      request.getSubnets(false).then(res => {
        var mySubnets = getAvailableSubnets(res, refs);
        refs.subnet.setState({
          data: mySubnets
        });
      });
    },
    onConfirm: function(refs, cb) {
      request.addInterface(obj.id, {
        subnet_id: refs.subnet.state.value
      }).then((res) => {
        callback && callback();
        cb(true);
      });
    },
    onAction: function(field, status, refs) {
      switch(field) {
        case 'subnet':
          if(status.clicked === true && refs.subnet.state.data.length === 0) {
            refs.subnet.setState({
              clicked: false
            });
            createSubnet(null, null, function() {
              request.getSubnets(true).then(res => {
                var mySubnets = getAvailableSubnets(res, refs);
                refs.subnet.setState({
                  data: mySubnets
                });
              });
            });
          }
          break;
        default:
          break;
      }
    }
  };

  commonModal(props);
}

module.exports = pop;
<|endoftext|>