<commit_before>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template, FeedbackService) {

    var qs = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));

    var is_empty = function(obj) {
        return Object.keys(obj).length === 0;
    }

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    var current_url = window.location.pathname;

    var insert_param = function(key, value) {

        var key = escape(key); value = escape(value);
        var kvp = document.location.search.substr(1).split('&');
        if (kvp == '') {
            document.location.search = '?' + key + '=' + value;
        } else {
            var i=kvp.length;
            var x;
            while(i--) {
                x = kvp[i].split('=');

                if (x[0]==key) {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
                }
            }

            if (i<0) {
                kvp[kvp.length] = [key,value].join('=');
            }

            //this will reload the page, it's likely better to store this until finished
            document.location.search = kvp.join('&');
        }
    }

    $scope.selected = [];
    var checkboxes = $(".feed-checkbox");
    $scope.status_select_value = 'none';

    $scope.date_filter     = (!is_empty(qs) && qs['date']) ? qs['date'] : 'none';
    $scope.priority_filter = (!is_empty(qs) && qs['priority']) ? qs['priority'] : 'none';
    $scope.status_filter   = (!is_empty(qs) && qs['status']) ? qs['status'] : 'none';
    $scope.rating_filter   = (!is_empty(qs) && qs['rating']) ? qs['rating'] : 'none';

    $scope.feedback_status = function($event) {

        var currentUrl = window.location.pathname;
        var target = $($event.target);
        var feed = $.parseJSON(target.attr('data-feed'));

        if(currentUrl.match(/filed/g)) {
            var current = {
                id: feed.id
              , catid: feed.catid
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        } else {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        }

        FeedbackSignal.current_state(current);
        feed.origin = Template.current_inbox_state;
        FeedbackControlService.change_status(feed, true);
    }

    $scope.flag_feedback = function($event) {
        var flag = $($event.target);
        var feed = $.parseJSON(flag.attr('data-feed'));

        var return_policy = flag.attr('return-policy') == true;

        var modfeed = {
            id: feed.id
          , catid: (current_url.match(/filed/g)) ? feed.catid : Template.default_category_id
          , status: (return_policy == true) ? feed.status : 'unflag'
          , origin: Template.current_inbox_state
        }

        FeedbackControlService.flag_feedback(modfeed);
    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            var currentUrl = window.location.pathname;
            var selected = [];
            var catids = [];
            var ids = $scope.selected;
            var mode = $scope.status_select_value;
            var feed = {};

            for(var i=0; i < ids.length; ++i) {
                var me = ids[i];

                var entity = $(".dashboard-feedback[feedback=" + me + "]");
                var entity_parent = entity.parents('.feedback-group');
                var score = entity.attr('score');
                var permission = entity.attr('permission');
                var catid = entity.attr('catid');

                if(
                      (score >= 3 && permission == 1)
                   || ((score >= 3 && permission == 0) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                   || ((score == 1 || score == 2) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                  )  {

                    entity.hide();

                    var child_count = entity_parent.children('.dashboard-feedback:visible');

                    if(child_count.length == 0) {
                        entity_parent.hide();
                    }

                    selected.push(me);
                    catids.push(catid);
                }
            }

            if(selected.length > 0) {

                if(currentUrl.match(/filed/g)) {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid:  catids
                      , origin: Template.current_inbox_state
                    }
                } else {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid: Template.default_category_id
                      , origin: Template.current_inbox_state
                    }
                }

                if(mode == "remove") {
                    FeedbackSignal.current_state(feed);
                    FeedbackControlService.change_status(feed, true);
                } else {
                    FeedbackSignal.current_state(feed);
                    FeedbackControlService.change_status(feed, true);
                    $(".checky-box-container").show();
                }

            } else {
                alert("Action is not allowed!");
            }

            selected = [];
            $scope.selected = [];
            $scope.status_select_value = 'none';
        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < checkboxes.length; i++) {

            var entity = $(checkboxes[i]);
            var myparent = entity.parents('.dashboard-feedback');

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!entity.is(":checked")) {
                    entity.click();
                }
            } else {
                entity.click();
            }

            update_selected(action, parseInt(entity.val(), 10));
        }
    }

    $scope.filter = function(filter_type) {
        if(filter_type == 'date') {
            if($scope.date_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('date', $scope.date_filter);
            }
        }

        if(filter_type == 'priority') {
            if($scope.priority_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('priority', $scope.priority_filter);
            }
        }

        if(filter_type == 'status') {
            if($scope.status_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('status', $scope.status_filter);
            }
        }

        if(filter_type == 'rating') {
            if($scope.rating_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('rating', $scope.rating_filter);
            }
        }
    }

    $scope.fast_forward = function(email, feedid) {
        FeedbackService.send_fastforward(email, feedid);
    }

    $scope.$on('expungeFeedId', function() {
        FeedbackSignal.data.id = [];
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection;

    $scope.undo = function() {
        FeedbackControlService.change_status(FeedbackSignal.data, false);
    }

    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.data.status;
    });
}
<commit_msg>I am glad<commit_after>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template, FeedbackService) {

    var qs = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));

    var is_empty = function(obj) {
        return Object.keys(obj).length === 0;
    }

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    var current_url = window.location.pathname;

    var insert_param = function(key, value) {

        var key = escape(key); value = escape(value);
        var kvp = document.location.search.substr(1).split('&');
        if (kvp == '') {
            document.location.search = '?' + key + '=' + value;
        } else {
            var i=kvp.length;
            var x;
            while(i--) {
                x = kvp[i].split('=');

                if (x[0]==key) {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
                }
            }

            if (i<0) {
                kvp[kvp.length] = [key,value].join('=');
            }

            //this will reload the page, it's likely better to store this until finished
            document.location.search = kvp.join('&');
        }
    }

    $scope.selected = [];
    var checkboxes = $(".feed-checkbox");
    $scope.status_select_value = 'none';

    $scope.date_filter     = (!is_empty(qs) && qs['date']) ? qs['date'] : 'none';
    $scope.priority_filter = (!is_empty(qs) && qs['priority']) ? qs['priority'] : 'none';
    $scope.status_filter   = (!is_empty(qs) && qs['status']) ? qs['status'] : 'none';
    $scope.rating_filter   = (!is_empty(qs) && qs['rating']) ? qs['rating'] : 'none';

    $scope.feedback_status = function($event) {

        var currentUrl = window.location.pathname;
        var target = $($event.target);
        var feed = $.parseJSON(target.attr('data-feed'));

        if(currentUrl.match(/filed/g)) {
            var current = {
                id: feed.id
              , catid: feed.catid
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        } else {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        }

        FeedbackSignal.current_state(current);
        feed.origin = Template.current_inbox_state;
        FeedbackControlService.change_status(feed, true);
    }

    $scope.flag_feedback = function($event) {
        var flag = $($event.target);
        var feed = $.parseJSON(flag.attr('data-feed'));

        var return_policy = flag.attr('return-policy') == true;

        var modfeed = {
            id: feed.id
          , catid: (current_url.match(/filed/g)) ? feed.catid : Template.default_category_id
          , status: (return_policy == true) ? feed.status : 'unflag'
          , origin: Template.current_inbox_state
        }

        FeedbackControlService.flag_feedback(modfeed);
    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            var currentUrl = window.location.pathname;
            var selected = [];
            var catids = [];
            var ids = $scope.selected;
            var mode = $scope.status_select_value;
            var feed = {};

            if(mode == "remove") {
                if(confirm("Are you sure you want to permanently remove this feedback? There is no undo."))      {
                    console.log("yes");
                }
            } else {
                console.log("yes");
            }
            /*
            for(var i=0; i < ids.length; ++i) {
                var me = ids[i];

                var entity = $(".dashboard-feedback[feedback=" + me + "]");
                var entity_parent = entity.parents('.feedback-group');
                var score = entity.attr('score');
                var permission = entity.attr('permission');
                var catid = entity.attr('catid');

                if(
                       (score >= 3 && permission == 1)
                   || ((score >= 3 && permission == 0) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                   || ((score == 1 || score == 2) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                  )  {
                    entity.hide();
                    var child_count = entity_parent.children('.dashboard-feedback:visible');

                    if(child_count.length == 0) {
                        entity_parent.hide();
                    }

                    selected.push(me);
                    catids.push(catid);
                }
            }

            if(selected.length > 0) {

                if(currentUrl.match(/filed/g)) {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid:  catids
                      , origin: Template.current_inbox_state
                    }
                } else {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid: Template.default_category_id
                      , origin: Template.current_inbox_state
                    }
                }

                if(mode == "remove") {
                    FeedbackSignal.current_state(feed);
                    FeedbackControlService.change_status(feed, true);
                } else {
                    FeedbackSignal.current_state(feed);
                    FeedbackControlService.change_status(feed, true);
                    $(".checky-box-container").show();
                }

            } else {
                alert("Action is not allowed!");
            }

            selected = [];
            $scope.selected = [];
            $scope.status_select_value = 'none';
            */
        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < checkboxes.length; i++) {

            var entity = $(checkboxes[i]);
            var myparent = entity.parents('.dashboard-feedback');

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!entity.is(":checked")) {
                    entity.click();
                }
            } else {
                entity.click();
            }

            update_selected(action, parseInt(entity.val(), 10));
        }
    }

    $scope.filter = function(filter_type) {
        if(filter_type == 'date') {
            if($scope.date_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('date', $scope.date_filter);
            }
        }

        if(filter_type == 'priority') {
            if($scope.priority_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('priority', $scope.priority_filter);
            }
        }

        if(filter_type == 'status') {
            if($scope.status_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('status', $scope.status_filter);
            }
        }

        if(filter_type == 'rating') {
            if($scope.rating_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('rating', $scope.rating_filter);
            }
        }
    }

    $scope.fast_forward = function(email, feedid) {
        FeedbackService.send_fastforward(email, feedid);
    }

    $scope.$on('expungeFeedId', function() {
        FeedbackSignal.data.id = [];
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection;

    $scope.undo = function() {
        FeedbackControlService.change_status(FeedbackSignal.data, false);
    }

    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.data.status;
    });
}
<|endoftext|>


<commit_before>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template, FeedbackService) {

    var qs = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));

    var is_empty = function(obj) {
        return Object.keys(obj).length === 0;
    }

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    var current_url = window.location.pathname;

    var insert_param = function(key, value) {

        var key = escape(key); value = escape(value);
        var kvp = document.location.search.substr(1).split('&');
        if (kvp == '') {
            document.location.search = '?' + key + '=' + value;
        } else {
            var i=kvp.length;
            var x;
            while(i--) {
                x = kvp[i].split('=');

                if (x[0]==key) {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
                }
            }

            if (i<0) {
                kvp[kvp.length] = [key,value].join('=');
            }

            //this will reload the page, it's likely better to store this until finished
            document.location.search = kvp.join('&');
        }
    }

    $scope.selected = [];
    var checkboxes = $(".feed-checkbox");
    $scope.status_select_value = 'none';

    $scope.date_filter     = (!is_empty(qs) && qs['date']) ? qs['date'] : 'none';
    $scope.priority_filter = (!is_empty(qs) && qs['priority']) ? qs['priority'] : 'none';
    $scope.status_filter   = (!is_empty(qs) && qs['status']) ? qs['status'] : 'none';
    $scope.rating_filter   = (!is_empty(qs) && qs['rating']) ? qs['rating'] : 'none';

    $scope.feedback_status = function($event) {

        var currentUrl = window.location.pathname;
        var target = $($event.target);
        var feed = $.parseJSON(target.attr('data-feed'));

        if(currentUrl.match(/filed/g)) {
            var current = {
                id: feed.id
              , catid: feed.catid
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        } else {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        }

        FeedbackSignal.current_state(current);
        feed.origin = Template.current_inbox_state;
        FeedbackControlService.change_status(feed, true);
    }

    $scope.flag_feedback = function($event) {
        var flag = $($event.target);
        var feed = $.parseJSON(flag.attr('data-feed'));

        var return_policy = flag.attr('return-policy') == true;

        var modfeed = {
            id: feed.id
          , catid: (current_url.match(/filed/g)) ? feed.catId : Template.default_category_id
          , status: (return_policy == true) ? feed.status : 'unflag'
          , origin: Template.current_inbox_state
        }

        FeedbackControlService.flag_feedback(modfeed);
    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            var currentUrl = window.location.pathname;
            var selected = [];
            var catids = [];
            var ids = $scope.selected;
            var mode = $scope.status_select_value;

            for(var i=0; i < ids.length; ++i) {
                var me = ids[i];

                var entity = $(".dashboard-feedback[feedback=" + me + "]");
                var entity_parent = entity.parents('.feedback-group');
                var score = entity.attr('score');
                var permission = entity.attr('permission');
                var catid = entity.attr('catid');

                if(
                      (score >= 3 && permission == 1)
                   || ((score >= 3 && permission == 0) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                   || ((score == 1 || score == 2) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                  )  {

                    entity.hide();

                    var child_count = entity_parent.children('.dashboard-feedback:visible');

                    if(child_count.length == 0) {
                        entity_parent.hide();
                    }

                    selected.push(me);
                    catids.push(catid);
                }
            }

            if(selected.length > 0) {

                if(currentUrl.match(/filed/g)) {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid:  catids
                      , origin: Template.current_inbox_state
                    }
                } else {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid: Template.default_category_id
                      , origin: Template.current_inbox_state
                    }
                }
                FeedbackSignal.current_state(feed);
                FeedbackControlService.change_status(feed, true);
                $(".checky-box-container").show();
            } else {
                alert("Action is not allowed!");
            }

            selected = [];
            $scope.selected = [];
            $scope.status_select_value = 'none';
        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < checkboxes.length; i++) {

            var entity = $(checkboxes[i]);
            var myparent = entity.parents('.dashboard-feedback');

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!entity.is(":checked")) {
                    entity.click();
                }
            } else {
                entity.click();
            }

            update_selected(action, parseInt(entity.val(), 10));
        }
    }

    $scope.filter = function(filter_type) {
        if(filter_type == 'date') {
            if($scope.date_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('date', $scope.date_filter);
            }
        }

        if(filter_type == 'priority') {
            if($scope.priority_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('priority', $scope.priority_filter);
            }
        }

        if(filter_type == 'status') {
            if($scope.status_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('status', $scope.status_filter);
            }
        }

        if(filter_type == 'rating') {
            if($scope.rating_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('rating', $scope.rating_filter);
            }
        }
    }

    $scope.fast_forward = function(email, feedid) {
        FeedbackService.send_fastforward(email, feedid);
    }

    $scope.$on('expungeFeedId', function() {
        //console.log("expunged");
        FeedbackSignal.data.id = [];
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection;

    $scope.undo = function() {
        FeedbackControlService.change_status(FeedbackSignal.data, false);
    }

    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.data.status;
    });
}
<commit_msg>putang<commit_after>function FeedbackControl($scope, FeedbackControlService, FeedbackSignal, Template, FeedbackService) {

    var qs = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p=a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'));

    var is_empty = function(obj) {
        return Object.keys(obj).length === 0;
    }

    var update_selected = function(action, id) {
        if (action == 'add' && $scope.selected.indexOf(id) == -1) {
            $scope.selected.push(id);
        }

        if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
            $scope.selected.splice($scope.selected.indexOf(id), 1);
        }
    }

    var current_url = window.location.pathname;

    var insert_param = function(key, value) {

        var key = escape(key); value = escape(value);
        var kvp = document.location.search.substr(1).split('&');
        if (kvp == '') {
            document.location.search = '?' + key + '=' + value;
        } else {
            var i=kvp.length;
            var x;
            while(i--) {
                x = kvp[i].split('=');

                if (x[0]==key) {
                    x[1] = value;
                    kvp[i] = x.join('=');
                    break;
                }
            }

            if (i<0) {
                kvp[kvp.length] = [key,value].join('=');
            }

            //this will reload the page, it's likely better to store this until finished
            document.location.search = kvp.join('&');
        }
    }

    $scope.selected = [];
    var checkboxes = $(".feed-checkbox");
    $scope.status_select_value = 'none';

    $scope.date_filter     = (!is_empty(qs) && qs['date']) ? qs['date'] : 'none';
    $scope.priority_filter = (!is_empty(qs) && qs['priority']) ? qs['priority'] : 'none';
    $scope.status_filter   = (!is_empty(qs) && qs['status']) ? qs['status'] : 'none';
    $scope.rating_filter   = (!is_empty(qs) && qs['rating']) ? qs['rating'] : 'none';

    $scope.feedback_status = function($event) {

        var currentUrl = window.location.pathname;
        var target = $($event.target);
        var feed = $.parseJSON(target.attr('data-feed'));

        if(currentUrl.match(/filed/g)) {
            var current = {
                id: feed.id
              , catid: feed.catid
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        } else {
            var current = {
                id: feed.id
              , catid: Template.default_category_id
              , status: feed.status
              , origin: Template.current_inbox_state
            }
        }

        FeedbackSignal.current_state(current);
        feed.origin = Template.current_inbox_state;
        FeedbackControlService.change_status(feed, true);
    }

    $scope.flag_feedback = function($event) {
        var flag = $($event.target);
        var feed = $.parseJSON(flag.attr('data-feed'));

        var return_policy = flag.attr('return-policy') == true;

        var modfeed = {
            id: feed.id
          , catid: (current_url.match(/filed/g)) ? feed.catid : Template.default_category_id
          , status: (return_policy == true) ? feed.status : 'unflag'
          , origin: Template.current_inbox_state
        }

        FeedbackControlService.flag_feedback(modfeed);
    }

    $scope.update_selection = function($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        update_selected(action, id);
    }

    $scope.change_value_status = function() {
        if( $('input[type=checkbox].feed-checkbox:checked').length > 0 ) {

            var currentUrl = window.location.pathname;
            var selected = [];
            var catids = [];
            var ids = $scope.selected;
            var mode = $scope.status_select_value;

            for(var i=0; i < ids.length; ++i) {
                var me = ids[i];

                var entity = $(".dashboard-feedback[feedback=" + me + "]");
                var entity_parent = entity.parents('.feedback-group');
                var score = entity.attr('score');
                var permission = entity.attr('permission');
                var catid = entity.attr('catid');

                if(
                      (score >= 3 && permission == 1)
                   || ((score >= 3 && permission == 0) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                   || ((score == 1 || score == 2) && (mode == 'delete' || mode == 'restore' || mode == 'remove'))
                  )  {

                    entity.hide();

                    var child_count = entity_parent.children('.dashboard-feedback:visible');

                    if(child_count.length == 0) {
                        entity_parent.hide();
                    }

                    selected.push(me);
                    catids.push(catid);
                }
            }

            if(selected.length > 0) {

                if(currentUrl.match(/filed/g)) {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid:  catids
                      , origin: Template.current_inbox_state
                    }
                } else {
                    var feed = {
                        id: selected
                      , status: $scope.status_select_value
                      , catid: Template.default_category_id
                      , origin: Template.current_inbox_state
                    }
                }
                FeedbackSignal.current_state(feed);
                FeedbackControlService.change_status(feed, true);
                $(".checky-box-container").show();
            } else {
                alert("Action is not allowed!");
            }

            selected = [];
            $scope.selected = [];
            $scope.status_select_value = 'none';
        }
    }

    $scope.select_all = function($event) {

        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');

        for(var i=0; i < checkboxes.length; i++) {

            var entity = $(checkboxes[i]);
            var myparent = entity.parents('.dashboard-feedback');

            //if action is add then click on checkboxes if not click again to deselect
            if(action == "add") {
                if(!entity.is(":checked")) {
                    entity.click();
                }
            } else {
                entity.click();
            }

            update_selected(action, parseInt(entity.val(), 10));
        }
    }

    $scope.filter = function(filter_type) {
        if(filter_type == 'date') {
            if($scope.date_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('date', $scope.date_filter);
            }
        }

        if(filter_type == 'priority') {
            if($scope.priority_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('priority', $scope.priority_filter);
            }
        }

        if(filter_type == 'status') {
            if($scope.status_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('status', $scope.status_filter);
            }
        }

        if(filter_type == 'rating') {
            if($scope.rating_filter == 'none') {
                window.location = window.location.pathname;
            } else {
                insert_param('rating', $scope.rating_filter);
            }
        }
    }

    $scope.fast_forward = function(email, feedid) {
        FeedbackService.send_fastforward(email, feedid);
    }

    $scope.$on('expungeFeedId', function() {
        //console.log("expunged");
        FeedbackSignal.data.id = [];
        $scope.selected = [];
    })
}

function CheckyBox($scope, FeedbackSignal, FeedbackControlService) {

    $scope.status_selection;

    $scope.undo = function() {
        FeedbackControlService.change_status(FeedbackSignal.data, false);
    }

    $scope.$on('checkFeedbackStatus', function() {
        $scope.status_selection = FeedbackSignal.data.status;
    });
}
<|endoftext|>


<commit_before>'use strict';

angular.module('publicApp')
  .controller('RippleTransactionsCtrl', ['$scope', '$http', '$location', '$route', '$routeParams', 'UserService', 'GatewayService',function ($scope, $http, $location, $route, $routeParams, $user, $gateway) {
    if (!$user.isLogged) { $location.path('/login') };

    $scope.user = $user;
    $scope.rippleWithdrawal = {};
    console.log($gateway);
    $scope.hotWallet = $gateway.hotWallet;

    $scope.createRippleWithdrawal = function() {
      var opts  = {};
      opts.from_currency = $scope.rippleWithdrawal.currency;
      opts.from_amount = parseFloat($scope.rippleWithdrawal.amount);
      opts.from_issuer = 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk';
      opts.from_address = 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk';

      opts.to_currency = $scope.rippleWithdrawal.currency;
      opts.to_amount = parseFloat($scope.rippleWithdrawal.amount);
      opts.to_issuer = 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk';
      opts.to_address = 'r4EwBWxrx5HxYRyisfGzMto3AT8FZiYdWk';
      opts.issuance = true;

      opts.to_address = $scope.rippleWithdrawal.ripple_address;
      opts.from_address = $scope.rippleWithdrawal.ripple_address;

      opts.ripple_address_id = 3;

      $http.post('/api/v1/users/'+$user.id+'/ripple_transactions', opts).success(function(err, transaction) {
        console.log(err);
        console.log(transaction);
      });
      $location.path('/users/'+$user.id);
    }
  }]);
<commit_msg>[FEATURE] Get ripple address before creating ripple transaction.<commit_after>'use strict';

angular.module('publicApp')
  .controller('RippleTransactionsCtrl', ['$scope', '$http', '$location', '$route', '$routeParams', 'UserService', 'GatewayService',function ($scope, $http, $location, $route, $routeParams, $user, $gateway) {
    if (!$user.isLogged) { $location.path('/login') };

    $scope.user = $user;
    $scope.rippleWithdrawal = {};
    console.log($gateway);
    $scope.hotWallet = $gateway.hotWallet;

    $scope.createRippleWithdrawal = function() {
      var opts  = {};
      opts.from_currency = $scope.rippleWithdrawal.currency;
      opts.from_amount = parseFloat($scope.rippleWithdrawal.amount);
      opts.from_issuer = $gateway.hotWallet;
      opts.from_address = $gateway.hotWallet;

      opts.to_currency = $scope.rippleWithdrawal.currency;
      opts.to_amount = parseFloat($scope.rippleWithdrawal.amount);
      opts.to_issuer = $gateway.hotWallet;
      opts.issuance = true;

      opts.to_address = $scope.rippleWithdrawal.ripple_address;

      $http.get('/api/v1/users/'+$user.id+'/ripple_addresses').success(function(res){
        opts.ripple_address_id = res.ripple_addresses[0].id;
        $http.post('/api/v1/users/'+$user.id+'/ripple_transactions', opts).success(function(err, transaction) {
          $location.path('/users/'+$user.id);
        });

      });
    }
  }]);
<|endoftext|>


<commit_before>// TODO: Remove the complexity in this file by breaking out testing and storing of variables into discrete functions, then update .eslintrc

(function () {
	'use strict';

	mare.views.GallerySearchForm = Backbone.View.extend({
		// This view controls everything inside the element with class 'gallery-search-form'
		el: '.gallery-search-form',

		events: {

			'click .gallery-search-form__search-button' : 'updateGallery'

		},

		updateGallery: function updateGallery() {

			this.getFormFields();
			this.processFormFields();
			this.removeUneededFilters();
			this.updateChildren();
		},

		getFormFields: function getFormFields() {

			this.formFields = {
				genders							: $( '.select-gender:checked' ),
				minimumSiblings					: $( '#minimum-number-of-siblings' ).val(),
				maximumSiblings					: $( '#maximum-number-of-siblings' ).val(),
				youngestAge						: $( '#youngest-age' ).val(),
				oldestAge						: $( '#oldest-age' ).val(),
				races							: $( '.select-race:checked' ),
				primaryLanguages				: $( '.select-primary-language:checked' ),
				contactWithBiologicalSiblings	: $( '.select-contact-with-biological-siblings:checked' ).val(),
				contactWithBiologicalParents	: $( '.select-contact-with-biological-parents:checked' ).val(),
				videoOnly						: $( '.select-video-only:checked' ).length > 0,
				legallyFreeOnly					: $( '.select-legally-free-only:checked' ).length > 0,
				updatedWithin					: $( '#updated-within' ).val(),
				maximumPhysicalNeeds			: $( '.select-maximum-physical-needs:checked' ).val(),
				maximumEmotionalNeeds			: $( '.select-maximum-emotional-needs:checked' ).val(),
				maximumIntellectualNeeds		: $( '.select-maximum-intellectual-needs:checked' ).val(),
				disabilities					: $( '.select-disabilities:checked' ),
				otherConsiderations				: $( '.select-other-considerations:checked' ),
				familyConstellation				: $( '.select-family-constellation:checked' ).val(),
				numberOfChildrenInHome			: $( '.select-number-of-children-in-home' ).val(),
				gendersOfChildrenInHome			: $( '.select-genders-of-children-in-home:checked' ),
				youngestChildAgeInHome			: $( '#youngest-child-age-in-home' ).val(),
				oldestChildAgeInHome			: $( '#oldest-child-age-in-home' ).val(),
				petsInHome						: $( '.select-pets-in-home:checked' ).length > 0
			};
		},

		processFormFields: function processFormFields() {

			var gendersArray					= [],
				raceArray						= [],
				primaryLanguagesArray			= [],
				disabilityArray					= [],
				otherConsiderationsArray		= [],
				gendersOfChildrenInHomeArray	= [],
				formFields						= this.formFields;

			_.each(  formFields.genders, function( gender ) {
				gendersArray.push( gender.getAttribute( 'value' ) );
			});

			_.each( formFields.races, function( race ) {
				raceArray.push( race.getAttribute( 'value' ) );
			});

			_.each( formFields.primaryLanguages, function( language ) {
				primaryLanguagesArray.push( language.getAttribute( 'value' ) );
			});

			_.each( formFields.disabilities, function( disability ) {
				disabilityArray.push( disability.getAttribute( 'value' ) );
			});

			_.each( formFields.otherConsiderations, function( consideration ) {
				otherConsiderationsArray.push( consideration.getAttribute( 'value' ) );
			});

			_.each( formFields.gendersOfChildrenInHome, function( gender ) {
				gendersOfChildrenInHomeArray.push( gender.getAttribute( 'value' ) );
			});

			formFields.genders					= gendersArray;
			formFields.races					= raceArray;
			formFields.primaryLanguages			= primaryLanguagesArray;
			formFields.disabilities				= disabilityArray;
			formFields.otherConsiderations		= otherConsiderationsArray;
			formFields.gendersOfChildrenInHome	= gendersOfChildrenInHomeArray;

			formFields.minimumSiblings			= parseInt( formFields.minimumSiblings, 10 );
			formFields.maximumSiblings			= parseInt( formFields.maximumSiblings, 10 );
			formFields.youngestAge				= parseInt( formFields.youngestAge, 10 );
			formFields.oldestAge				= parseInt( formFields.oldestAge, 10 );
			formFields.maximumPhysicalNeeds		= formFields.maximumPhysicalNeeds !== undefined ? parseInt( formFields.maximumPhysicalNeeds, 10 ) : 3;
			formFields.maximumEmotionalNeeds	= formFields.maximumEmotionalNeeds !== undefined ? parseInt( formFields.maximumEmotionalNeeds, 10 ) : 3;
			formFields.maximumIntellectualNeeds	= formFields.maximumIntellectualNeeds !== undefined ? parseInt( formFields.maximumIntellectualNeeds, 10 ) : 3;
			formFields.numberOfChildrenInHome	= parseInt( formFields.numberOfChildrenInHome, 10 );
			formFields.youngestChildAgeInHome	= parseInt( formFields.youngestChildAgeInHome, 10 );
			formFields.oldestChildAgeInHome		= parseInt( formFields.oldestChildAgeInHome, 10 );

			formFields.contactWithBiologicalSiblings = formFields.contactWithBiologicalSiblings === 'no' ? false : true; // false : true order is needed, do not change
			formFields.contactWithBiologicalParents = formFields.contactWithBiologicalParents === 'no' ? false : true; // false : true order is needed, do not change
		},

		removeUneededFilters: function removeUneededFilters() {

			var formFields = this.formFields;

			if( formFields.genders.length === 0 )						{ delete formFields.genders; }
			if( formFields.races.length === 0 )							{ delete formFields.races; }
			if( formFields.primaryLanguages.length === 0 )				{ delete formFields.primaryLanguages }
			if( formFields.contactWithBiologicalSiblings !== false )	{ delete formFields.contactWithBiologicalSiblings; }
			if( formFields.contactWithBiologicalParents !== false )		{ delete formFields.contactWithBiologicalParents; }
			if( !formFields.videoOnly )									{ delete formFields.videoOnly; }
			if( !formFields.legallyFreeOnly )							{ delete formFields.legallyFreeOnly; }
			if( formFields.updatedWithin === '' )						{ delete formFields.updatedWithin; }
			if( formFields.maximumPhysicalNeeds === 3 )					{ delete formFields.maximumPhysicalNeeds; }
			if( formFields.maximumEmotionalNeeds === 3 )				{ delete formFields.maximumEmotionalNeeds; }
			if( formFields.maximumIntellectualNeeds === 3 )				{ delete formFields.maximumIntellectualNeeds; }
			if( formFields.disabilities.length === 0 )					{ delete formFields.disabilities; }
			if( formFields.otherConsiderations.length === 0 )			{ delete formFields.otherConsiderations; }
			if( !formFields.familyConstellation )						{ delete formFields.familyConstellation; }
			if( formFields.gendersOfChildrenInHome.length === 0 )		{ delete formFields.gendersOfChildrenInHome; }
			if( !formFields.petsInHome )								{ delete formFields.petsInHome; }

		},

		updateChildren: function updateChildren() {

			var formFields = this.formFields;

			// clear out all contents of the current gallery collection
			mare.collections.galleryChildren.reset();

			mare.collections.allChildren.each( function( child ) {

				// break out of the current loop if the child's gender wasn't selected ( return is needed for this in _.each )
				if( formFields.genders && formFields.genders.indexOf( child.get( 'gender' ) ) === -1 ) { return; }

				// break out of the current loop if the child has less than the min or more then the max specified ( return is needed for this in _.each )
				if( formFields.minimumSiblings > child.get( 'siblingContactsCount' ) ||
				   formFields.maximumSiblings < child.get( 'siblingContactsCount' ) ) { return; }

				// break out of the current loop if the child's age is less than the youngest or more than the oldest specified ( return is needed for this in _.each )
				if( formFields.youngestAge > child.get( 'age' ) ||
				   formFields.oldestAge < child.get( 'age' ) ) { return; }

				// break out of the current loop only if none of the child's races match a selected race ( return is needed for this in _.each )
				// <3 Underscore.js for this one
				if( formFields.races && _.intersection( formFields.races, child.get( 'race' )).length === 0 ) { return; }

				// break out of the current loop only if none of the child's languages match a selected primary language ( return is needed for this in _.each )
				// <3 Underscore.js for this one
				if( formFields.primaryLanguages && _.intersection( formFields.primaryLanguages, child.get( 'language' )).length === 0 ) { return; }

				// break out of the current loop only if the child having contact with their biological siblings/parents doesn't match the user's selection ( return is needed for this in _.each )
				if( formFields.contactWithBiologicalSiblings === false &&
				   child.get( 'hasContactWithBiologicalSiblings' ) !== false ) { return; }

				if( formFields.contactWithBiologicalParents === false &&
				   child.get( 'hasContactWithBiologicalParents' ) !== false ) { return; }

				// break out of the current loop if the child doesn't have a video and the user specifies that they should ( return is needed for this in _.each )
				if( formFields.videoOnly && child.get( 'hasVideo' ) === false ) { return; }

				// break out of the current loop if the child isn't legally free and the user specifies that they should be ( return is needed for this in _.each )
				if( formFields.legallyFreeOnly && child.get( 'legalStatus' ) !== 'free' ) { return; }

				// only consider when the child was updated if a selection was made in the search criteria
				if( formFields.updatedWithin ) {
					var lastUpdated			= new Date( child.get( 'updatedAt' ) ),
						restriction			= new Date( formFields.updatedWithin ),
						currentMilliseconds	= new Date().getTime(),
						cutoffMilliseconds	= parseInt( formFields.updatedWithin, 10 ),
						cutoffDate			= new Date( currentMilliseconds - cutoffMilliseconds ),
						isIncluded			= lastUpdated >= cutoffDate;

					// break out of the current loop if the child wasn't updated within the timeframe specified by the user ( return is needed for this in _.each )
					if( !isIncluded ) { return; }
				}
				// TODO: are these !== undefined checks necessary?
				// break out of the loop if any of the child's needs exceed the maximum specified by the user ( return is needed for this in _.each )
				if( formFields.maximumPhysicalNeeds !== undefined && child.get( 'physicalNeeds' ) > formFields.maximumPhysicalNeeds ) { return; }
				if( formFields.maximumEmotionalNeeds !== undefined && child.get( 'emotionalNeeds' ) > formFields.maximumEmotionalNeeds ) { return; }
				if( formFields.maximumIntellectualNeeds !== undefined && child.get( 'intellectualNeeds' ) > formFields.maximumIntellectualNeeds ) { return; }

				// break out of the current loop only if the child has disabilities and none match a selected disability ( return is needed for this in _.each )
				if( formFields.disabilities &&
					child.get( 'disabilities' ).length > 0 &&
				   _.intersection( formFields.disabilities, child.get( 'disabilities' ) ).length === 0 ) { return; }

				// break out of the current loop only if none of the child's other considerations match a selected consideration ( return is needed for this in _.each )
				if( formFields.otherConsiderations &&
					child.get( 'otherConsiderations' ).length > 0 &&
				   _.intersection( formFields.otherConsiderations, child.get( 'otherConsiderations' ) ).length === 0 ) { return; }

				// break out of the loop if the recommended family constellation for the child does not contain the one selected by the user ( return is needed for this in _.each )
				if( formFields.familyConstellation !== undefined &&
				   child.get( 'recommendedFamilyConstellation' ).indexOf( formFields.familyConstellation ) === -1 ) { return; }

				// break out of the loop if any of the other considerations selected don't match the child ( return is needed for this in _.each )
				if( child.get( 'requiresSiblings' ) && formFields.numberOfChildrenInHome === 0 ) { return; }
				if( child.get( 'requiresNoSiblings' ) && formFields.numberOfChildrenInHome > 0 ) { return; }
				if( child.get( 'requiresOlderSibling' ) && formFields.oldestChildAgeInHome <= child.get( 'age' ) ) { return; }
				if( child.get( 'requiresYoungerSibling' ) && formFields.youngestChildAgeInHome >= child.get( 'age' ) ) { return; }
				if( child.get( 'noPets' ) && formFields.petsInHome ) { return; }

				// if the child passes all checks, add them to the collection to display on the gallery
				mare.collections.galleryChildren.add( child );

			});

			// emit an event to allow the gallery to update it's display now that we have all matching models
			mare.collections.galleryChildren.trigger( 'updateComplete' );

		}
	});
}() );
<commit_msg>#122 | update search logic to handle family constellation as a multi-select<commit_after>// TODO: Remove the complexity in this file by breaking out testing and storing of variables into discrete functions, then update .eslintrc

(function () {
	'use strict';

	mare.views.GallerySearchForm = Backbone.View.extend({
		// This view controls everything inside the element with class 'gallery-search-form'
		el: '.gallery-search-form',

		events: {

			'click .gallery-search-form__search-button' : 'updateGallery'

		},

		updateGallery: function updateGallery() {

			this.getFormFields();
			this.processFormFields();
			this.removeUneededFilters();
			this.updateChildren();
		},

		getFormFields: function getFormFields() {

			this.formFields = {
				genders							: $( '.select-gender:checked' ),
				minimumSiblings					: $( '#minimum-number-of-siblings' ).val(),
				maximumSiblings					: $( '#maximum-number-of-siblings' ).val(),
				youngestAge						: $( '#youngest-age' ).val(),
				oldestAge						: $( '#oldest-age' ).val(),
				races							: $( '.select-race:checked' ),
				primaryLanguages				: $( '.select-primary-language:checked' ),
				contactWithBiologicalSiblings	: $( '.select-contact-with-biological-siblings:checked' ).val(),
				contactWithBiologicalParents	: $( '.select-contact-with-biological-parents:checked' ).val(),
				videoOnly						: $( '.select-video-only:checked' ).length > 0,
				legallyFreeOnly					: $( '.select-legally-free-only:checked' ).length > 0,
				updatedWithin					: $( '#updated-within' ).val(),
				maximumPhysicalNeeds			: $( '.select-maximum-physical-needs:checked' ).val(),
				maximumEmotionalNeeds			: $( '.select-maximum-emotional-needs:checked' ).val(),
				maximumIntellectualNeeds		: $( '.select-maximum-intellectual-needs:checked' ).val(),
				disabilities					: $( '.select-disabilities:checked' ),
				otherConsiderations				: $( '.select-other-considerations:checked' ),
				familyConstellation				: $( '.select-family-constellation:checked' ),
				numberOfChildrenInHome			: $( '.select-number-of-children-in-home' ).val(),
				gendersOfChildrenInHome			: $( '.select-genders-of-children-in-home:checked' ),
				youngestChildAgeInHome			: $( '#youngest-child-age-in-home' ).val(),
				oldestChildAgeInHome			: $( '#oldest-child-age-in-home' ).val(),
				petsInHome						: $( '.select-pets-in-home:checked' ).length > 0
			};
		},

		processFormFields: function processFormFields() {

			var gendersArray					= [],
				raceArray						= [],
				primaryLanguagesArray			= [],
				disabilityArray					= [],
				otherConsiderationsArray		= [],
				familyConstellationArray		= [],
				gendersOfChildrenInHomeArray	= [],
				formFields						= this.formFields;

			_.each(  formFields.genders, function( gender ) {
				gendersArray.push( gender.getAttribute( 'value' ) );
			});

			_.each( formFields.races, function( race ) {
				raceArray.push( race.getAttribute( 'value' ) );
			});

			_.each( formFields.primaryLanguages, function( language ) {
				primaryLanguagesArray.push( language.getAttribute( 'value' ) );
			});

			_.each( formFields.disabilities, function( disability ) {
				disabilityArray.push( disability.getAttribute( 'value' ) );
			});

			_.each( formFields.otherConsiderations, function( consideration ) {
				otherConsiderationsArray.push( consideration.getAttribute( 'value' ) );
			});

			_.each( formFields.familyConstellation, function( constellation ) {
				familyConstellationArray.push( constellation.getAttribute( 'value' ) );
			});

			_.each( formFields.gendersOfChildrenInHome, function( gender ) {
				gendersOfChildrenInHomeArray.push( gender.getAttribute( 'value' ) );
			});

			formFields.genders					= gendersArray;
			formFields.races					= raceArray;
			formFields.primaryLanguages			= primaryLanguagesArray;
			formFields.disabilities				= disabilityArray;
			formFields.otherConsiderations		= otherConsiderationsArray;
			formFields.familyConstellation		= familyConstellationArray;
			formFields.gendersOfChildrenInHome	= gendersOfChildrenInHomeArray;

			formFields.minimumSiblings			= parseInt( formFields.minimumSiblings, 10 );
			formFields.maximumSiblings			= parseInt( formFields.maximumSiblings, 10 );
			formFields.youngestAge				= parseInt( formFields.youngestAge, 10 );
			formFields.oldestAge				= parseInt( formFields.oldestAge, 10 );
			formFields.maximumPhysicalNeeds		= formFields.maximumPhysicalNeeds !== undefined ? parseInt( formFields.maximumPhysicalNeeds, 10 ) : 3;
			formFields.maximumEmotionalNeeds	= formFields.maximumEmotionalNeeds !== undefined ? parseInt( formFields.maximumEmotionalNeeds, 10 ) : 3;
			formFields.maximumIntellectualNeeds	= formFields.maximumIntellectualNeeds !== undefined ? parseInt( formFields.maximumIntellectualNeeds, 10 ) : 3;
			formFields.numberOfChildrenInHome	= parseInt( formFields.numberOfChildrenInHome, 10 );
			formFields.youngestChildAgeInHome	= parseInt( formFields.youngestChildAgeInHome, 10 );
			formFields.oldestChildAgeInHome		= parseInt( formFields.oldestChildAgeInHome, 10 );

			formFields.contactWithBiologicalSiblings = formFields.contactWithBiologicalSiblings === 'no' ? false : true; // false : true order is needed, do not change
			formFields.contactWithBiologicalParents = formFields.contactWithBiologicalParents === 'no' ? false : true; // false : true order is needed, do not change
		},

		removeUneededFilters: function removeUneededFilters() {

			var formFields = this.formFields;

			if( formFields.genders.length === 0 )						{ delete formFields.genders; }
			if( formFields.races.length === 0 )							{ delete formFields.races; }
			if( formFields.primaryLanguages.length === 0 )				{ delete formFields.primaryLanguages }
			if( formFields.contactWithBiologicalSiblings !== false )	{ delete formFields.contactWithBiologicalSiblings; }
			if( formFields.contactWithBiologicalParents !== false )		{ delete formFields.contactWithBiologicalParents; }
			if( !formFields.videoOnly )									{ delete formFields.videoOnly; }
			if( !formFields.legallyFreeOnly )							{ delete formFields.legallyFreeOnly; }
			if( formFields.updatedWithin === '' )						{ delete formFields.updatedWithin; }
			if( formFields.maximumPhysicalNeeds === 3 )					{ delete formFields.maximumPhysicalNeeds; }
			if( formFields.maximumEmotionalNeeds === 3 )				{ delete formFields.maximumEmotionalNeeds; }
			if( formFields.maximumIntellectualNeeds === 3 )				{ delete formFields.maximumIntellectualNeeds; }
			if( formFields.disabilities.length === 0 )					{ delete formFields.disabilities; }
			if( formFields.otherConsiderations.length === 0 )			{ delete formFields.otherConsiderations; }
			if( formFields.familyConstellation.length === 0 )			{ delete formFields.familyConstellation; }
			if( formFields.gendersOfChildrenInHome.length === 0 )		{ delete formFields.gendersOfChildrenInHome; }
			if( !formFields.petsInHome )								{ delete formFields.petsInHome; }

		},

		updateChildren: function updateChildren() {

			var formFields = this.formFields;

			// clear out all contents of the current gallery collection
			mare.collections.galleryChildren.reset();

			mare.collections.allChildren.each( function( child ) {

				// break out of the current loop if the child's gender wasn't selected ( return is needed for this in _.each )
				if( formFields.genders && formFields.genders.indexOf( child.get( 'gender' ) ) === -1 ) { return; }

				// break out of the current loop if the child has less than the min or more then the max specified ( return is needed for this in _.each )
				if( formFields.minimumSiblings > child.get( 'siblingContactsCount' ) ||
				   formFields.maximumSiblings < child.get( 'siblingContactsCount' ) ) { return; }

				// break out of the current loop if the child's age is less than the youngest or more than the oldest specified ( return is needed for this in _.each )
				if( formFields.youngestAge > child.get( 'age' ) ||
				   formFields.oldestAge < child.get( 'age' ) ) { return; }

				// break out of the current loop only if none of the child's races match a selected race ( return is needed for this in _.each )
				// <3 Underscore.js for this one
				if( formFields.races && _.intersection( formFields.races, child.get( 'race' )).length === 0 ) { return; }

				// break out of the current loop only if none of the child's languages match a selected primary language ( return is needed for this in _.each )
				// <3 Underscore.js for this one
				if( formFields.primaryLanguages && _.intersection( formFields.primaryLanguages, child.get( 'language' )).length === 0 ) { return; }

				// break out of the current loop only if the child having contact with their biological siblings/parents doesn't match the user's selection ( return is needed for this in _.each )
				if( formFields.contactWithBiologicalSiblings === false &&
				   child.get( 'hasContactWithBiologicalSiblings' ) !== false ) { return; }

				if( formFields.contactWithBiologicalParents === false &&
				   child.get( 'hasContactWithBiologicalParents' ) !== false ) { return; }

				// break out of the current loop if the child doesn't have a video and the user specifies that they should ( return is needed for this in _.each )
				if( formFields.videoOnly && child.get( 'hasVideo' ) === false ) { return; }

				// break out of the current loop if the child isn't legally free and the user specifies that they should be ( return is needed for this in _.each )
				if( formFields.legallyFreeOnly && child.get( 'legalStatus' ) !== 'free' ) { return; }

				// only consider when the child was updated if a selection was made in the search criteria
				if( formFields.updatedWithin ) {
					var lastUpdated			= new Date( child.get( 'updatedAt' ) ),
						restriction			= new Date( formFields.updatedWithin ),
						currentMilliseconds	= new Date().getTime(),
						cutoffMilliseconds	= parseInt( formFields.updatedWithin, 10 ),
						cutoffDate			= new Date( currentMilliseconds - cutoffMilliseconds ),
						isIncluded			= lastUpdated >= cutoffDate;

					// break out of the current loop if the child wasn't updated within the timeframe specified by the user ( return is needed for this in _.each )
					if( !isIncluded ) { return; }
				}
				// TODO: are these !== undefined checks necessary?
				// break out of the loop if any of the child's needs exceed the maximum specified by the user ( return is needed for this in _.each )
				if( formFields.maximumPhysicalNeeds !== undefined && child.get( 'physicalNeeds' ) > formFields.maximumPhysicalNeeds ) { return; }
				if( formFields.maximumEmotionalNeeds !== undefined && child.get( 'emotionalNeeds' ) > formFields.maximumEmotionalNeeds ) { return; }
				if( formFields.maximumIntellectualNeeds !== undefined && child.get( 'intellectualNeeds' ) > formFields.maximumIntellectualNeeds ) { return; }

				// break out of the current loop only if the child has disabilities and none match a selected disability ( return is needed for this in _.each )
				if( formFields.disabilities &&
					child.get( 'disabilities' ).length > 0 &&
				   _.intersection( formFields.disabilities, child.get( 'disabilities' ) ).length === 0 ) { return; }

				// break out of the current loop only if none of the child's other considerations match a selected consideration ( return is needed for this in _.each )
				if( formFields.otherConsiderations &&
					child.get( 'otherConsiderations' ).length > 0 &&
				   _.intersection( formFields.otherConsiderations, child.get( 'otherConsiderations' ) ).length === 0 ) { return; }

				// break out of the loop if the recommended family constellation for the child does not contain the one selected by the user ( return is needed for this in _.each )
				if( formFields.familyConstellation &&
				   child.get( 'recommendedFamilyConstellation' ).length > 0 &&
				_.intersection( formFields.familyConstellation, child.get( 'recommendedFamilyConstellation' ) ).length === 0 ) { return; }

				// break out of the loop if any of the other considerations selected don't match the child ( return is needed for this in _.each )
				if( child.get( 'requiresSiblings' ) && formFields.numberOfChildrenInHome === 0 ) { return; }
				if( child.get( 'requiresNoSiblings' ) && formFields.numberOfChildrenInHome > 0 ) { return; }
				if( child.get( 'requiresOlderSibling' ) && formFields.oldestChildAgeInHome <= child.get( 'age' ) ) { return; }
				if( child.get( 'requiresYoungerSibling' ) && formFields.youngestChildAgeInHome >= child.get( 'age' ) ) { return; }
				if( child.get( 'noPets' ) && formFields.petsInHome ) { return; }

				// if the child passes all checks, add them to the collection to display on the gallery
				mare.collections.galleryChildren.add( child );

			});

			// emit an event to allow the gallery to update it's display now that we have all matching models
			mare.collections.galleryChildren.trigger( 'updateComplete' );

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


<commit_before>/*
 * Copyright (c) 2016, Regents of the University of California
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * IOTAUTH_COPYRIGHT_VERSION_1
 */

 /**
 * Generator for entity configuration files.
 * @author Hokeun Kim
 */

"use strict";

var fs = require('fs');
var JSON2 = require('JSON2');

var entityList = [
    { name: 'client' },
    { name: 'ptClient' },
    { name: 'rcClient' },
    { name: 'udpClient' },
    { name: 'safetyCriticalClient' },
    { name: 'rcUdpClient' },
    { name: 'server', port: 100 },
    { name: 'ptServer', port: 200 },
    { name: 'rcServer', port: 300 },
    { name: 'udpServer', port: 400 },
    { name: 'safetyCriticalServer', port: 500 },
    { name: 'rcUdpServer', port: 600 },
    { name: 'ptPublisher' },
    { name: 'ptSubscriber' }
];

var tcpServerInfoList = [];
var udpServerInfoList = [];
var safetyCriticalServerInfoList = [];

function capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

function getNetName(netId) {
    return 'net' + netId;
}

function getKeyPath(netId, entityName, keySuffix) {
    return '../../credentials/keys/' + getNetName(netId) + '/'
        + capitalizeFirstLetter(getNetName(netId)) + '.'
        + capitalizeFirstLetter(entityName) + keySuffix;
}

function getEntityInfo(netId, entityName) {
    var entityInfo = {};
    entityInfo.name = getNetName(netId) + '.' + entityName;
    if (entityName.toLowerCase().includes('ptclient')) {
        entityInfo.group = 'PtClients';
    }
    else if (entityName.toLowerCase().includes('ptserver')) {
        entityInfo.group = 'PtServers';
    }
    else if (entityName.toLowerCase().includes('ptpublisher')) {
        entityInfo.group = 'PtPublishers';
    }
    else if (entityName.toLowerCase().includes('ptsubscriber')) {
        entityInfo.group = 'PtSubscribers';
    }
    else if (entityName.toLowerCase().includes('client')) {
        entityInfo.group = 'Clients';
    }
    else if (entityName.toLowerCase().includes('server')) {
        entityInfo.group = 'Servers';
    }
    if (entityName.toLowerCase().includes('udp')) {
        entityInfo.distProtocol = 'UDP';
    }
    else {
        entityInfo.distProtocol = 'TCP';
    }
    if (entityName.toLowerCase().includes('rc')) {
        entityInfo.usePermanentDistKey = true;
        entityInfo.permanentDistKey = {
            'cipherKey': getKeyPath(netId, entityName, 'CipherKey.key'),
            'macKey': getKeyPath(netId, entityName, 'MacKey.key'),
            'validity': '365*day'
        }
    }
    else {
        entityInfo.usePermanentDistKey = false;
    }
    entityInfo.privateKey = getKeyPath(netId, entityName, 'Key.pem');
    return entityInfo;
}

function getNetPortBase(netId) {
    return 20000 + netId * 1000;
}

function getAuthInfo(netId, entityName) {
    var authInfo = {};
    authInfo.id = 100 + netId;
    authInfo.host = 'localhost';
    authInfo.port = getNetPortBase(netId) + 900;
    if (entityName.toLowerCase().includes('udp')) {
        authInfo.port += 2;
    }
    if (!entityName.toLowerCase().includes('rc')) {
        authInfo.publicKey = '../../auth_certs/Auth' + authInfo.id + 'EntityCert.pem';
    }
    return authInfo;
}

function getCryptoInfo(entityName) {
    var cryptoInfo = {};
    if (entityName.toLowerCase().includes('safetycritical')) {
        cryptoInfo.publicKeyCryptoSpec = {
            "sign": "RSA-SHA256",
            "diffieHellman": "secp128r2"
        };
    }
    else if (!entityName.toLowerCase().includes('rc')) {
        cryptoInfo.publicKeyCryptoSpec = {
            "sign": "RSA-SHA256"
        };
    }
    cryptoInfo.distCryptoSpec = {
        "cipher": "AES-128-CBC",
        "mac": "SHA256"
    };
    cryptoInfo.sessionCryptoSpec = {
        "cipher": "AES-128-CBC",
        "mac": "SHA256"
    };
    if (entityName.toLowerCase().includes('safetycritical')) {
        cryptoInfo.sessionCryptoSpec.diffieHellman = "secp128r2";
    }
    return cryptoInfo;
}

function getTargetServerInfoList(netId, entityName) {
    var targetServerInfoList = [];
    for (var i = 0; i < entityList.length; i++) {
        if (!entityList[i].name.toLowerCase().includes('server')) {
            continue;
        }
        var serverInfo = {};
        serverInfo.name = getNetName(netId) + '.' + entityList[i].name;
        serverInfo.port = getNetPortBase(netId) + entityList[i].port;
        serverInfo.host = 'localhost';
        if (entityList[i].name.toLowerCase().includes('udp')) {
            if (entityName.toLowerCase().includes('udp')) {
                targetServerInfoList.push(serverInfo);
            }
        }
        else if (entityList[i].name.toLowerCase().includes('safetycritical')) {
            if (entityName.toLowerCase().includes('safetycritical')) {
                targetServerInfoList.push(serverInfo);
            }
        }
        else {
            if (!entityName.toLowerCase().includes('udp') &&
                !entityName.toLowerCase().includes('safetycritical')) {
                    targetServerInfoList.push(serverInfo);
            }

        }
    }
    return targetServerInfoList;
}

function getListeningServerInfo(netId, server) {
    var listeningServerInfo = {};
    listeningServerInfo.host = 'localhost';
    listeningServerInfo.port = getNetPortBase(netId) + server.port;
    return listeningServerInfo;
}

function getEntityConfig(netId, entity) {
    var entityConfig = {};
    entityConfig.entityInfo = getEntityInfo(netId, entity.name);
    entityConfig.authInfo = getAuthInfo(netId, entity.name);
    entityConfig.cryptoInfo = getCryptoInfo(entity.name);
    if (entity.name.toLowerCase().includes('client')) {
        var targetServerInfoList = getTargetServerInfoList(1, entity.name);
        targetServerInfoList = targetServerInfoList.concat(getTargetServerInfoList(2, entity.name));
        entityConfig.targetServerInfoList = targetServerInfoList;
    }
    if (entity.name.toLowerCase().includes('server')) {
        entityConfig.listeningServerInfo = getListeningServerInfo(netId, entity);
    }
    return entityConfig;
}

function writeEntityConfigToFile(entityConfig) {
    var entityFullName = entityConfig.entityInfo.name;
    var separatorIndex = entityFullName.indexOf('.');
    var configFilePath = entityFullName.substring(0, separatorIndex)
        + '/' + entityFullName.substring(separatorIndex + 1) + '.config';
    console.log('Writing entityConfig to ' + configFilePath + ' ...');
    fs.writeFileSync(configFilePath,
        JSON2.stringify(entityConfig, null, '\t'),
        'utf8'
    );
}

function getEntityConfigs(numNets) {
    var netConfigList = [];
    for (var netId = 1; netId <= numNets; netId++) {
        var netConfig = {
            'netId': netId,
            'entityConfigList': []
        };
        var dirName = getNetName(netId);
        if (!fs.existsSync(dirName)){
            fs.mkdirSync(dirName);
        }
        for (var i = 0; i < entityList.length; i++) {
            netConfig.entityConfigList.push(getEntityConfig(netId, entityList[i]));
        }
        netConfigList.push(netConfig);
    }
    return netConfigList;
}

function generateEntityConfigs(netConfigList) {
    for (var i = 0; i < netConfigList.length; i++) {
            var netConfig = netConfigList[i];
        for (var j = 0; j < netConfig.entityConfigList.length; j++) {
            var entityConfig = netConfig.entityConfigList[j];
            if (entityConfig.entityInfo.name.includes('pt')) {
                continue;
            }
            writeEntityConfigToFile(entityConfig);
        }
    }
}

function convertToRegisteredEntity(entityConfig, backupTo) {
    var registeredEntity = {};
    registeredEntity.Name = entityConfig.entityInfo.name;
    registeredEntity.Group = entityConfig.entityInfo.group;
    registeredEntity.DistProtocol = entityConfig.entityInfo.distProtocol;
    // Resource-constrained entity
    if (entityConfig.entityInfo.usePermanentDistKey) {
        registeredEntity.UsePermanentDistKey = true;
        registeredEntity.MaxSessionKeysPerRequest = 30;
        var permanentDistKey = entityConfig.entityInfo.permanentDistKey;
        registeredEntity.DistKeyValidityPeriod = permanentDistKey.validity;
        // For resource-constrained only
        var separatorIndex = permanentDistKey.cipherKey.lastIndexOf('/');
        registeredEntity.DistCipherKeyFilePath = 'entity_keys'
            + permanentDistKey.cipherKey.substring(separatorIndex);
        separatorIndex = permanentDistKey.macKey.lastIndexOf('/');
        registeredEntity.DistMacKeyFilePath = 'entity_keys'
            + permanentDistKey.macKey.substring(separatorIndex);
    }
    // Not resource-constrained entity
    else {
        registeredEntity.UsePermanentDistKey = false;
        registeredEntity.PublicKeyCryptoSpec = entityConfig.cryptoInfo.publicKeyCryptoSpec.sign;
        // with additional Diffie-Hellman key exchange for key distribution
        if (entityConfig.cryptoInfo.publicKeyCryptoSpec.diffieHellman) {
            registeredEntity.PublicKeyCryptoSpec += (':DH-' + entityConfig.cryptoInfo.publicKeyCryptoSpec.diffieHellman);
        }
        // MaxSessionKeysPerRequest
        if (entityConfig.entityInfo.name.toLowerCase().includes('server')) {
            registeredEntity.MaxSessionKeysPerRequest = 1;
        }
        else {
            registeredEntity.MaxSessionKeysPerRequest = 5;
        }
        // DistKeyValidityPeriod
        if (entityConfig.entityInfo.name.toLowerCase().includes('pt')) {
            registeredEntity.DistKeyValidityPeriod = '3*sec';
        }
        else {
            registeredEntity.DistKeyValidityPeriod = '1*hour';
        }
        var separatorIndex = entityConfig.entityInfo.privateKey.lastIndexOf('/');
        // Public key setting
        registeredEntity.PublKeyFile = 'entity_certs'
            + entityConfig.entityInfo.privateKey.substring(separatorIndex).replace('Key.pem', 'Cert.pem');
    }

    registeredEntity.DistCryptoSpec = entityConfig.cryptoInfo.distCryptoSpec.cipher
        + ':' + entityConfig.cryptoInfo.distCryptoSpec.mac;

    registeredEntity.Active = true;
    registeredEntity.BackupToAuthID = backupTo;
    //registeredEntity.BackupFromAuthID = 5678;
    return registeredEntity;
}

function convertToRegisteredEntityTable(netConfigList) {
    var registeredEntityTableList = [];
    for (var i = 0; i < netConfigList.length; i++) {
        var netConfig = netConfigList[i];
        var registeredEntityTable = {
            'authId': 100 + netConfig.netId,
            'registeredEntityList': []
        };
        var backupToAuthID = -1;
        if (netConfigList.length > 1) {
            backupToAuthID = 100 + (netConfig.netId % netConfigList.length + 1);
        }
        for (var j = 0; j < netConfig.entityConfigList.length; j++) {
            registeredEntityTable.registeredEntityList.push(
                convertToRegisteredEntity(netConfig.entityConfigList[j], backupToAuthID)
            );
        }
        registeredEntityTableList.push(registeredEntityTable);
    }
    return registeredEntityTableList;
}

function generateRegisteredEntityTables(registeredEntityTableList) {
    var dirName = 'Auth';
    if (!fs.existsSync(dirName)){
        fs.mkdirSync(dirName);
    }
    for (var i = 0; i < registeredEntityTableList.length; i++) {
        var registeredEntityTable = registeredEntityTableList[i];
        var fileName = 'Auth' + registeredEntityTable.authId + 'RegisteredEntityTable.config';
        var configFilePath = dirName + '/' + fileName;
        console.log('Writing entityConfig to ' + configFilePath + ' ...');
        fs.writeFileSync(configFilePath,
            JSON2.stringify(registeredEntityTable.registeredEntityList, null, '\t'),
            'utf8'
        );
    }
}

var totalNumberOfNets = 2;
var netConfigList = getEntityConfigs(totalNumberOfNets);
//console.log(JSON2.stringify(netConfigList[0].entityConfigList, null, '\t'));
generateEntityConfigs(netConfigList);
var registeredEntityTableList = convertToRegisteredEntityTable(netConfigList);
generateRegisteredEntityTables(registeredEntityTableList);
//console.log(JSON2.stringify(registeredEntityTableList, null, '\t'));
<commit_msg>small change<commit_after>/*
 * Copyright (c) 2016, Regents of the University of California
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * IOTAUTH_COPYRIGHT_VERSION_1
 */

 /**
 * Generator for entity configuration files.
 * @author Hokeun Kim
 */

"use strict";

var fs = require('fs');
var JSON2 = require('JSON2');

var entityList = [
    { name: 'client' },
    { name: 'ptClient' },
    { name: 'rcClient' },
    { name: 'udpClient' },
    { name: 'safetyCriticalClient' },
    { name: 'rcUdpClient' },
    { name: 'server', port: 100 },
    { name: 'ptServer', port: 200 },
    { name: 'rcServer', port: 300 },
    { name: 'udpServer', port: 400 },
    { name: 'safetyCriticalServer', port: 500 },
    { name: 'rcUdpServer', port: 600 },
    { name: 'ptPublisher' },
    { name: 'ptSubscriber' }
];

var tcpServerInfoList = [];
var udpServerInfoList = [];
var safetyCriticalServerInfoList = [];

function capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

function getNetName(netId) {
    return 'net' + netId;
}

function getKeyPath(netId, entityName, keySuffix) {
    return '../../credentials/keys/' + getNetName(netId) + '/'
        + capitalizeFirstLetter(getNetName(netId)) + '.'
        + capitalizeFirstLetter(entityName) + keySuffix;
}

function getEntityInfo(netId, entityName) {
    var entityInfo = {};
    entityInfo.name = getNetName(netId) + '.' + entityName;
    if (entityName.toLowerCase().includes('ptclient')) {
        entityInfo.group = 'PtClients';
    }
    else if (entityName.toLowerCase().includes('ptserver')) {
        entityInfo.group = 'PtServers';
    }
    else if (entityName.toLowerCase().includes('ptpublisher')) {
        entityInfo.group = 'PtPublishers';
    }
    else if (entityName.toLowerCase().includes('ptsubscriber')) {
        entityInfo.group = 'PtSubscribers';
    }
    else if (entityName.toLowerCase().includes('client')) {
        entityInfo.group = 'Clients';
    }
    else if (entityName.toLowerCase().includes('server')) {
        entityInfo.group = 'Servers';
    }
    if (entityName.toLowerCase().includes('udp')) {
        entityInfo.distProtocol = 'UDP';
    }
    else {
        entityInfo.distProtocol = 'TCP';
    }
    if (entityName.toLowerCase().includes('rc')) {
        entityInfo.usePermanentDistKey = true;
        entityInfo.permanentDistKey = {
            'cipherKey': getKeyPath(netId, entityName, 'CipherKey.key'),
            'macKey': getKeyPath(netId, entityName, 'MacKey.key'),
            'validity': '365*day'
        }
    }
    else {
        entityInfo.usePermanentDistKey = false;
    }
    entityInfo.privateKey = getKeyPath(netId, entityName, 'Key.pem');
    return entityInfo;
}

function getNetPortBase(netId) {
    return 20000 + netId * 1000;
}

function getAuthInfo(netId, entityName) {
    var authInfo = {};
    authInfo.id = 100 + netId;
    authInfo.host = 'localhost';
    authInfo.port = getNetPortBase(netId) + 900;
    if (entityName.toLowerCase().includes('udp')) {
        authInfo.port += 2;
    }
    if (!entityName.toLowerCase().includes('rc')) {
        authInfo.publicKey = '../../auth_certs/Auth' + authInfo.id + 'EntityCert.pem';
    }
    return authInfo;
}

function getCryptoInfo(entityName) {
    var cryptoInfo = {};
    if (entityName.toLowerCase().includes('safetycritical')) {
        cryptoInfo.publicKeyCryptoSpec = {
            "sign": "RSA-SHA256",
            "diffieHellman": "secp128r2"
        };
    }
    else if (!entityName.toLowerCase().includes('rc')) {
        cryptoInfo.publicKeyCryptoSpec = {
            "sign": "RSA-SHA256"
        };
    }
    cryptoInfo.distCryptoSpec = {
        "cipher": "AES-128-CBC",
        "mac": "SHA256"
    };
    cryptoInfo.sessionCryptoSpec = {
        "cipher": "AES-128-CBC",
        "mac": "SHA256"
    };
    if (entityName.toLowerCase().includes('safetycritical')) {
        cryptoInfo.sessionCryptoSpec.diffieHellman = "secp128r2";
    }
    return cryptoInfo;
}

function getTargetServerInfoList(netId, entityName) {
    var targetServerInfoList = [];
    for (var i = 0; i < entityList.length; i++) {
        if (!entityList[i].name.toLowerCase().includes('server')) {
            continue;
        }
        var serverInfo = {};
        serverInfo.name = getNetName(netId) + '.' + entityList[i].name;
        serverInfo.port = getNetPortBase(netId) + entityList[i].port;
        serverInfo.host = 'localhost';
        if (entityList[i].name.toLowerCase().includes('udp')) {
            if (entityName.toLowerCase().includes('udp')) {
                targetServerInfoList.push(serverInfo);
            }
        }
        else if (entityList[i].name.toLowerCase().includes('safetycritical')) {
            if (entityName.toLowerCase().includes('safetycritical')) {
                targetServerInfoList.push(serverInfo);
            }
        }
        else {
            if (!entityName.toLowerCase().includes('udp') &&
                !entityName.toLowerCase().includes('safetycritical')) {
                    targetServerInfoList.push(serverInfo);
            }

        }
    }
    return targetServerInfoList;
}

function getListeningServerInfo(netId, server) {
    var listeningServerInfo = {};
    listeningServerInfo.host = 'localhost';
    listeningServerInfo.port = getNetPortBase(netId) + server.port;
    return listeningServerInfo;
}

function getEntityConfig(netId, entity) {
    var entityConfig = {};
    entityConfig.entityInfo = getEntityInfo(netId, entity.name);
    entityConfig.authInfo = getAuthInfo(netId, entity.name);
    entityConfig.cryptoInfo = getCryptoInfo(entity.name);
    if (entity.name.toLowerCase().includes('client')) {
        var targetServerInfoList = getTargetServerInfoList(1, entity.name);
        targetServerInfoList = targetServerInfoList.concat(getTargetServerInfoList(2, entity.name));
        entityConfig.targetServerInfoList = targetServerInfoList;
    }
    if (entity.name.toLowerCase().includes('server')) {
        entityConfig.listeningServerInfo = getListeningServerInfo(netId, entity);
    }
    return entityConfig;
}

function writeEntityConfigToFile(entityConfig) {
    var entityFullName = entityConfig.entityInfo.name;
    var separatorIndex = entityFullName.indexOf('.');
    var configFilePath = entityFullName.substring(0, separatorIndex)
        + '/' + entityFullName.substring(separatorIndex + 1) + '.config';
    console.log('Writing entityConfig to ' + configFilePath + ' ...');
    fs.writeFileSync(configFilePath,
        JSON2.stringify(entityConfig, null, '\t'),
        'utf8'
    );
}

function getEntityConfigs(numNets) {
    var netConfigList = [];
    for (var netId = 1; netId <= numNets; netId++) {
        var netConfig = {
            'netId': netId,
            'entityConfigList': []
        };
        for (var i = 0; i < entityList.length; i++) {
            netConfig.entityConfigList.push(getEntityConfig(netId, entityList[i]));
        }
        netConfigList.push(netConfig);
    }
    return netConfigList;
}

function generateEntityConfigs(netConfigList) {
    for (var i = 0; i < netConfigList.length; i++) {
        var dirName = getNetName(netConfigList[i].netId);
        if (!fs.existsSync(dirName)){
            fs.mkdirSync(dirName);
        }
        var netConfig = netConfigList[i];
        for (var j = 0; j < netConfig.entityConfigList.length; j++) {
            var entityConfig = netConfig.entityConfigList[j];
            if (entityConfig.entityInfo.name.includes('pt')) {
                continue;
            }
            writeEntityConfigToFile(entityConfig);
        }
    }
}

function convertToRegisteredEntity(entityConfig, backupTo) {
    var registeredEntity = {};
    registeredEntity.Name = entityConfig.entityInfo.name;
    registeredEntity.Group = entityConfig.entityInfo.group;
    registeredEntity.DistProtocol = entityConfig.entityInfo.distProtocol;
    // Resource-constrained entity
    if (entityConfig.entityInfo.usePermanentDistKey) {
        registeredEntity.UsePermanentDistKey = true;
        registeredEntity.MaxSessionKeysPerRequest = 30;
        var permanentDistKey = entityConfig.entityInfo.permanentDistKey;
        registeredEntity.DistKeyValidityPeriod = permanentDistKey.validity;
        // For resource-constrained only
        var separatorIndex = permanentDistKey.cipherKey.lastIndexOf('/');
        registeredEntity.DistCipherKeyFilePath = 'entity_keys'
            + permanentDistKey.cipherKey.substring(separatorIndex);
        separatorIndex = permanentDistKey.macKey.lastIndexOf('/');
        registeredEntity.DistMacKeyFilePath = 'entity_keys'
            + permanentDistKey.macKey.substring(separatorIndex);
    }
    // Not resource-constrained entity
    else {
        registeredEntity.UsePermanentDistKey = false;
        registeredEntity.PublicKeyCryptoSpec = entityConfig.cryptoInfo.publicKeyCryptoSpec.sign;
        // with additional Diffie-Hellman key exchange for key distribution
        if (entityConfig.cryptoInfo.publicKeyCryptoSpec.diffieHellman) {
            registeredEntity.PublicKeyCryptoSpec += (':DH-' + entityConfig.cryptoInfo.publicKeyCryptoSpec.diffieHellman);
        }
        // MaxSessionKeysPerRequest
        if (entityConfig.entityInfo.name.toLowerCase().includes('server')) {
            registeredEntity.MaxSessionKeysPerRequest = 1;
        }
        else {
            registeredEntity.MaxSessionKeysPerRequest = 5;
        }
        // DistKeyValidityPeriod
        if (entityConfig.entityInfo.name.toLowerCase().includes('pt')) {
            registeredEntity.DistKeyValidityPeriod = '3*sec';
        }
        else {
            registeredEntity.DistKeyValidityPeriod = '1*hour';
        }
        var separatorIndex = entityConfig.entityInfo.privateKey.lastIndexOf('/');
        // Public key setting
        registeredEntity.PublKeyFile = 'entity_certs'
            + entityConfig.entityInfo.privateKey.substring(separatorIndex).replace('Key.pem', 'Cert.pem');
    }

    registeredEntity.DistCryptoSpec = entityConfig.cryptoInfo.distCryptoSpec.cipher
        + ':' + entityConfig.cryptoInfo.distCryptoSpec.mac;

    registeredEntity.Active = true;
    registeredEntity.BackupToAuthID = backupTo;
    //registeredEntity.BackupFromAuthID = 5678;
    return registeredEntity;
}

function convertToRegisteredEntityTable(netConfigList) {
    var registeredEntityTableList = [];
    for (var i = 0; i < netConfigList.length; i++) {
        var netConfig = netConfigList[i];
        var registeredEntityTable = {
            'authId': 100 + netConfig.netId,
            'registeredEntityList': []
        };
        var backupToAuthID = -1;
        if (netConfigList.length > 1) {
            backupToAuthID = 100 + (netConfig.netId % netConfigList.length + 1);
        }
        for (var j = 0; j < netConfig.entityConfigList.length; j++) {
            registeredEntityTable.registeredEntityList.push(
                convertToRegisteredEntity(netConfig.entityConfigList[j], backupToAuthID)
            );
        }
        registeredEntityTableList.push(registeredEntityTable);
    }
    return registeredEntityTableList;
}

function generateRegisteredEntityTables(registeredEntityTableList) {
    var dirName = 'Auth';
    if (!fs.existsSync(dirName)){
        fs.mkdirSync(dirName);
    }
    for (var i = 0; i < registeredEntityTableList.length; i++) {
        var registeredEntityTable = registeredEntityTableList[i];
        var fileName = 'Auth' + registeredEntityTable.authId + 'RegisteredEntityTable.config';
        var configFilePath = dirName + '/' + fileName;
        console.log('Writing entityConfig to ' + configFilePath + ' ...');
        fs.writeFileSync(configFilePath,
            JSON2.stringify(registeredEntityTable.registeredEntityList, null, '\t'),
            'utf8'
        );
    }
}

var totalNumberOfNets = 2;
var netConfigList = getEntityConfigs(totalNumberOfNets);
//console.log(JSON2.stringify(netConfigList[0].entityConfigList, null, '\t'));
generateEntityConfigs(netConfigList);
var registeredEntityTableList = convertToRegisteredEntityTable(netConfigList);
generateRegisteredEntityTables(registeredEntityTableList);
//console.log(JSON2.stringify(registeredEntityTableList, null, '\t'));
<|endoftext|>


<commit_before>'use strict';

document.addEventListener('DOMContentLoaded', function() {
  const regexp = /(?:ISBN|ASIN)=([0-9A-Z]+)/g;
  const COMMENT_NODE = 8;
  let bodies = document.querySelectorAll('div.body');
  bodies.forEach(function(body, index) {
    body.childNodes.forEach(function(node, index) {
      if (node.nodeType !== COMMENT_NODE)
        return;
      if (!node.textContent.match(regexp))
        return;
      let itemId = RegExp.$1;
      let url = '/amazon/' + itemId + '.json';
      let request = new XMLHttpRequest();
      request.responseType = 'json';
      let promise = new Promise(function(resolve, reject) {
        request.open('GET', url);
        request.onreadystatechange = function() {
          if (request.readyState != 4) {
            // リクエスト中
          } else if (request.status != 200) {
            // 失敗
            reject(request.response);
          } else {
            // 取得成功
            let formatter = new Formatter(request.response);
            let result = formatter.formatItem();
            resolve(result);
          }
        };
        request.send();
      });
      promise.then(function(result) {
        let previous = node.previousSibling;
        let parent = node.parentNode;
        let d = document.createElement('div');
        d.className = 'amazon';
        d.innerHTML = result;
        parent.insertBefore(d, previous.nextSibling);
      }).catch(function(error) {
        console.log(error);
      });
      return promise;
    });
  });
});

var Formatter = (function() {
  function Formatter(json) {
    this.json = json;
  }

  Formatter.prototype.formatItem = function() {
    let json = this.json;
    let item, attr, title, link, image, price, author, manufacturer, str;
    let errors = json['ItemLookupResponse']['Items']['Request']['Errors'];
    if (typeof errors !== 'undefined' && errors !== null) {
      console.error(errors);
      return;
    }
    item = json['ItemLookupResponse']['Items']['Item'];
    attr = item['ItemAttributes'];
    title = attr['Title'];
    link  = item['DetailPageURL'];
    image = item['MediumImage']['URL'].replace('http://ecx.images-amazon', 'https://images-na.ssl-images-amazon');
    try {
      price = item['OfferSummary']['LowestNewPrice']['FormattedPrice'];
    }
    catch(e) {
      price = '-';
    }

    let authors = [];
    if (typeof attr['Creator'] !== 'undefined' && attr['Creator'] !== null)
      authors .push(this.formatAuthors(attr['Creator']));
    if (typeof attr['Author'] !== 'undefined' && attr['Author'] !== null)
      authors .push(this.formatAuthors(attr['Author']));
    if (typeof attr['Director'] !== 'undefined' && attr['Director'] !== null)
      authors .push(this.formatAuthors(attr['Director']));
    if (typeof attr['Actor'] !== 'undefined' && attr['Actor'] !== null)
      authors .push(this.formatAuthors(attr['Actor']));
    if (typeof attr['Artist'] !== 'undefined' && attr['Artist'] !== null)
      authors .push(this.formatAuthors(attr['Artist']));

    if (typeof authors !== 'undefined' && authors !== null) {
      author = authors.join(', ');
    }
    manufacturer = attr['Manufacturer'];

    str = '
' +
            '' +
          '
' +
          '
' +
            '
' +
              '
' + title + '
' +
              '
' + author + '
' +
              '
' + manufacturer + '
' +
              '
' + price + '
' +
            '
' +
          '
';
    return str;
  };

  Formatter.prototype.formatAuthors = function(authors) {
    if (typeof authors === Array && authors.length > 1) {
      let _authors = [];
      authors.forEach(function(item, index) {
        _authors.push(item)
      });
      authors = _authors.join(', ');
    }
    return authors;
  };

  return Formatter;
})();
<commit_msg>Show author only when author is present<commit_after>'use strict';

document.addEventListener('DOMContentLoaded', function() {
  const regexp = /(?:ISBN|ASIN)=([0-9A-Z]+)/g;
  const COMMENT_NODE = 8;
  let bodies = document.querySelectorAll('div.body');
  bodies.forEach(function(body, index) {
    body.childNodes.forEach(function(node, index) {
      if (node.nodeType !== COMMENT_NODE)
        return;
      if (!node.textContent.match(regexp))
        return;
      let itemId = RegExp.$1;
      let url = '/amazon/' + itemId + '.json';
      let request = new XMLHttpRequest();
      request.responseType = 'json';
      let promise = new Promise(function(resolve, reject) {
        request.open('GET', url);
        request.onreadystatechange = function() {
          if (request.readyState != 4) {
            // リクエスト中
          } else if (request.status != 200) {
            // 失敗
            reject(request.response);
          } else {
            // 取得成功
            let formatter = new Formatter(request.response);
            let result = formatter.formatItem();
            resolve(result);
          }
        };
        request.send();
      });
      promise.then(function(result) {
        let previous = node.previousSibling;
        let parent = node.parentNode;
        let d = document.createElement('div');
        d.className = 'amazon';
        d.innerHTML = result;
        parent.insertBefore(d, previous.nextSibling);
      }).catch(function(error) {
        console.log(error);
      });
      return promise;
    });
  });
});

var Formatter = (function() {
  function Formatter(json) {
    this.json = json;
  }

  Formatter.prototype.formatItem = function() {
    let json = this.json;
    let item, attr, title, link, image, price, author, manufacturer, str;
    let errors = json['ItemLookupResponse']['Items']['Request']['Errors'];
    if (typeof errors !== 'undefined' && errors !== null) {
      console.error(errors);
      return;
    }
    item = json['ItemLookupResponse']['Items']['Item'];
    attr = item['ItemAttributes'];
    title = attr['Title'];
    link  = item['DetailPageURL'];
    image = item['MediumImage']['URL'].replace('http://ecx.images-amazon', 'https://images-na.ssl-images-amazon');
    try {
      price = item['OfferSummary']['LowestNewPrice']['FormattedPrice'];
    }
    catch(e) {
      price = '-';
    }

    let authors = [];
    if (typeof attr['Creator'] !== 'undefined' && attr['Creator'] !== null)
      authors .push(this.formatAuthors(attr['Creator']));
    if (typeof attr['Author'] !== 'undefined' && attr['Author'] !== null)
      authors .push(this.formatAuthors(attr['Author']));
    if (typeof attr['Director'] !== 'undefined' && attr['Director'] !== null)
      authors .push(this.formatAuthors(attr['Director']));
    if (typeof attr['Actor'] !== 'undefined' && attr['Actor'] !== null)
      authors .push(this.formatAuthors(attr['Actor']));
    if (typeof attr['Artist'] !== 'undefined' && attr['Artist'] !== null)
      authors .push(this.formatAuthors(attr['Artist']));

    if (typeof authors !== 'undefined' && authors !== null) {
      author = authors.join(', ');
    }
    manufacturer = attr['Manufacturer'];

    str = '
' +
      '' +
      '
' +
      '
' +
      '
' +
      '
' + title + '
';
    if (author !== '') {
      str += '
' + author + '
';
    }
    str += '
' + manufacturer + '
' +
      '
' + price + '
' +
      '
' +
      '
';
    return str;
  };

  Formatter.prototype.formatAuthors = function(authors) {
    if (typeof authors === Array && authors.length > 1) {
      let _authors = [];
      authors.forEach(function(item, index) {
        _authors.push(item)
      });
      authors = _authors.join(', ');
    }
    return authors;
  };

  return Formatter;
})();
<|endoftext|>