<commit_before>'use strict';

var module = require('../../lib/index');
var messages = require('../../lib/messages');
var ansiTrim = require('cli-color/lib/trim');

describe("Messages module", function () {
    it("can be loaded", function () {
        expect(messages).toBeDefined();
    });
});

describe("Server Output", function () {
    var expected = "\nOK, Server running at http://0.0.0.0:8000";
    expected    += "\nServing files from: /users/shakyshane/app/files";
    expected    += "\n\nLoad a browser & check back here. If you set up everything correctly, you'll see a 'Browser Connected' message\n";
    var actual = ansiTrim(messages.initServer("0.0.0.0", 8000, "/users/shakyshane/app/files"));
    expect(actual).toBe(expected);
});

describe("Proxy Output", function () {

    var ports, host;

    beforeEach(function () {
        ports = [3000, 3001, 3002];
        host = "192.168.0.3";
    });

    it("can output a message about proxy (1)", function () {
        var expected = "Proxy running. Use this URL: http://192.168.0.3:3002";
        expect(ansiTrim(messages.initProxy(host, ports[2]))).toBe(expected);
    });
    it("can output a message about proxy (2)", function () {
        var expected = "Proxy running. Use this URL: http://192.168.0.3:3001";
        expect(ansiTrim(messages.initProxy(host, ports[1]))).toBe(expected);
    });
});

describe("Creating URLS", function () {
    it("can return a full URL with ports", function () {
        expect(messages._makeUrl("192.168.0.4", 3001)).toBe("http://192.168.0.4:3001");
    });
});

describe("Outputting script tags", function () {
    it("can output correctly", function () {

        var expected = "<script src='http://192.168.0.4:3000/socket.io/socket.io.js'></script>" +
                "\n<script src='http://192.168.0.4:3001/browser-sync-client.min.js'></script>\n\n";

        var actual = messages.scriptTags("192.168.0.4", "3000", "3001");

        expect(actual).toBe(expected);
    });
});

describe("Outputting generic messages", function () {

    it("should output browser connected correctly", function () {

        var expected = "Browser Connected! (Chrome, version: 21.222)";
        var actual = ansiTrim(messages.browser.connection({name: "Chrome", version: "21.222"}));

        expect(actual).toBe(expected);
    });
    it("should output invalid base dir message", function () {

        var expected = "Invalid Base Directory path for server. Should be like this ( baseDir: 'path/to/app' )";
        var actual = ansiTrim(messages.invalidBaseDir());

        expect(actual).toBe(expected);
    });
});

describe("Outputting file watching messages", function () {

    it("should output warning if no files watched", function () {

        var expected = "Not watching any files...";
        var actual = ansiTrim(messages.files.watching([]));
        expect(actual).toBe(expected);
    });
    it("should output a single pattern", function () {

        var expected = "Watching the following:\n";
        expected += "**/*.css\n";

        var actual = ansiTrim(messages.files.watching(["**/*.css"]));
        expect(actual).toBe(expected);
    });
    it("should output multiple patterns", function () {

        var patterns = [
            "**/*.css",
            "**/*.js",
            "**/*.html",
            "**/*.erb"
        ];

        var expected = "Watching the following:\n";
        expected += "**/*.css\n";
        expected += "**/*.js\n";
        expected += "**/*.html\n";
        expected += "**/*.erb\n";

        var actual = ansiTrim(messages.files.watching(patterns));
        expect(actual).toBe(expected);
    });
    it("should output multiple patterns with a limit", function () {

        var patterns = [
            "**/*.css",
            "**/*.js",
            "**/*.html",
            "**/*.erb"
        ];

        var expected = "Watching the following:\n";
        expected += "**/*.css\n";
        expected += "**/*.js\n";
        expected += "Plus more...\n";

        var actual = ansiTrim(messages.files.watching(patterns, 2));
        expect(actual).toBe(expected);
    });
    it("should notify when a file is changed", function () {
        var expected = "File Changed: /users/shane/file.js";
        var actual   = ansiTrim(messages.files.changed("/users/shane/file.js"));
        expect(actual).toBe(expected);
    });
    it("should notify when a file is changed & should be reloaded", function () {
        var expected = "Reloading all connected browsers...";
        var actual   = ansiTrim(messages.browser.reload());
        expect(actual).toBe(expected);
    });
    it("should notify when a file is changed & should be injected", function () {
        var expected = "Injecting file into all connected browsers...";
        var actual   = ansiTrim(messages.browser.inject());
        expect(actual).toBe(expected);
    });
    it("should notify when changing location", function () {
        var expected = "Link clicked! Redirecting all browsers to http://local.dev/forms.html";
        var actual   = ansiTrim(messages.location("http://local.dev/forms.html"));
        expect(actual).toBe(expected);
    });
    it("should output the socket connector", function () {
        var expected = "var ___socket___ = io.connect('http://0.0.0.0:3001');";
        var actual   = messages.socketConnector("0.0.0.0", 3001);
        expect(actual).toBe(expected);
    });
});
<commit_msg>Add spec for control panel script<commit_after>'use strict';

var module = require('../../lib/index');
var messages = require('../../lib/messages');
var ansiTrim = require('cli-color/lib/trim');

describe("Messages module", function () {
    it("can be loaded", function () {
        expect(messages).toBeDefined();
    });
});

describe("Server Output", function () {
    var expected = "\nOK, Server running at http://0.0.0.0:8000";
    expected    += "\nServing files from: /users/shakyshane/app/files";
    expected    += "\n\nLoad a browser & check back here. If you set up everything correctly, you'll see a 'Browser Connected' message\n";
    var actual = ansiTrim(messages.initServer("0.0.0.0", 8000, "/users/shakyshane/app/files"));
    expect(actual).toBe(expected);
});

describe("Proxy Output", function () {

    var ports, host;

    beforeEach(function () {
        ports = [3000, 3001, 3002];
        host = "192.168.0.3";
    });

    it("can output a message about proxy (1)", function () {
        var expected = "Proxy running. Use this URL: http://192.168.0.3:3002";
        expect(ansiTrim(messages.initProxy(host, ports[2]))).toBe(expected);
    });
    it("can output a message about proxy (2)", function () {
        var expected = "Proxy running. Use this URL: http://192.168.0.3:3001";
        expect(ansiTrim(messages.initProxy(host, ports[1]))).toBe(expected);
    });
});

describe("Creating URLS", function () {
    it("can return a full URL with ports", function () {
        expect(messages.utils.makeUrl("192.168.0.4", 3001)).toBe("http://192.168.0.4:3001");
    });
});

describe("Outputting script tags", function () {
    it("can output correctly for client", function () {

        var expected = "<script src='http://192.168.0.4:3000/socket.io/socket.io.js'></script>" +
                "\n<script src='http://192.168.0.4:3001/browser-sync-client.min.js'></script>\n\n";

        var actual = messages.snippets.client("192.168.0.4", "3000", "3001");

        expect(actual).toBe(expected);
    });
    it("can output correctly for Control Panel", function () {

        var expected = "<script src='http://192.168.0.4:3000/socket.io/socket.io.js'></script>" +
                "\n<script src='http://192.168.0.4:3003/js/app.js'></script>\n\n";

        var actual = messages.snippets.controlPanel("192.168.0.4", "3000", "3003");

        expect(actual).toBe(expected);
    });
});

describe("Outputting generic messages", function () {

    it("should output browser connected correctly", function () {

        var expected = "Browser Connected! (Chrome, version: 21.222)";
        var actual = ansiTrim(messages.browser.connection({name: "Chrome", version: "21.222"}));

        expect(actual).toBe(expected);
    });
    it("should output invalid base dir message", function () {

        var expected = "Invalid Base Directory path for server. Should be like this ( baseDir: 'path/to/app' )";
        var actual = ansiTrim(messages.invalidBaseDir());

        expect(actual).toBe(expected);
    });
});

describe("Outputting file watching messages", function () {

    it("should output warning if no files watched", function () {

        var expected = "Not watching any files...";
        var actual = ansiTrim(messages.files.watching([]));
        expect(actual).toBe(expected);
    });
    it("should output a single pattern", function () {

        var expected = "Watching the following:\n";
        expected += "**/*.css\n";

        var actual = ansiTrim(messages.files.watching(["**/*.css"]));
        expect(actual).toBe(expected);
    });
    it("should output multiple patterns", function () {

        var patterns = [
            "**/*.css",
            "**/*.js",
            "**/*.html",
            "**/*.erb"
        ];

        var expected = "Watching the following:\n";
        expected += "**/*.css\n";
        expected += "**/*.js\n";
        expected += "**/*.html\n";
        expected += "**/*.erb\n";

        var actual = ansiTrim(messages.files.watching(patterns));
        expect(actual).toBe(expected);
    });
    it("should output multiple patterns with a limit", function () {

        var patterns = [
            "**/*.css",
            "**/*.js",
            "**/*.html",
            "**/*.erb"
        ];

        var expected = "Watching the following:\n";
        expected += "**/*.css\n";
        expected += "**/*.js\n";
        expected += "Plus more...\n";

        var actual = ansiTrim(messages.files.watching(patterns, 2));
        expect(actual).toBe(expected);
    });
    it("should notify when a file is changed", function () {
        var expected = "File Changed: /users/shane/file.js";
        var actual   = ansiTrim(messages.files.changed("/users/shane/file.js"));
        expect(actual).toBe(expected);
    });
    it("should notify when a file is changed & should be reloaded", function () {
        var expected = "Reloading all connected browsers...";
        var actual   = ansiTrim(messages.browser.reload());
        expect(actual).toBe(expected);
    });
    it("should notify when a file is changed & should be injected", function () {
        var expected = "Injecting file into all connected browsers...";
        var actual   = ansiTrim(messages.browser.inject());
        expect(actual).toBe(expected);
    });
    it("should notify when changing location", function () {
        var expected = "Link clicked! Redirecting all browsers to http://local.dev/forms.html";
        var actual   = ansiTrim(messages.location("http://local.dev/forms.html"));
        expect(actual).toBe(expected);
    });
    it("should output the socket connector", function () {
        var expected = "var ___socket___ = io.connect('http://0.0.0.0:3001');";
        var actual   = messages.socketConnector("0.0.0.0", 3001);
        expect(actual).toBe(expected);
    });
});
<|endoftext|>


<commit_before>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    var customFieldName = 'All';
    var customColumnName = 'all';
    var ajaxSaveStateUrl = null;
    var selectAllRecords = false;
    var totalRecords = 0;
    var totalCurrentPageRecords = 0;
    var ajaxExportUrl = null;
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the ajax URL for selected rows of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSaveStateUrl = function (source) {
        ajaxSaveStateUrl = source;

    }
    /**
     * Set the ajax URL to save export request in db.
     * @param {string} source
     *
     */
    this.setAjaxExportUrl = function (source) {
        ajaxExportUrl = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
//			$('#container').removeClass('container');
//			$('#container').css('margin', '20px');
            var selected = [];
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);
                                selfObj.totalRecords = json.iTotalDisplayRecords;
                                selfObj.totalCurrentPageRecords = json.iTotalRecords;
                            });
                        },
                        "createdRow": function (row, data, index) {
                            var input = $(row).find("td:first").html();
                            row.id = "row-" + $(input).attr('value');
                        },
//                        "ajax": ajaxSaveStateUrl,
                        "rowCallback": function (row, data) {
                            if ($(data[0]).attr("checked") == "checked") {
                                $(row).addClass("selected");
                            }
                        }
                    });
            $('#records tbody').on('click', 'tr', function () {
                var id = this.id;
                var index = $.inArray(id, selected);
                if (index === -1) {
                    selected.push(id);
                } else {
                    selected.splice(index, 1);
                }
                $(this).toggleClass('selected', function () {
                    var input = $("#" + id + " td:first").html();
                    if ($(this).hasClass('selected') === true) {
                        $("#" + $(input).attr('id')).attr("checked", "checked");
                        $("#" + $(input).attr('id')).prop("checked", true);
                    } else {
                        $("#" + $(input).attr('id')).removeAttr("checked");
                        $("#" + $(input).attr('id')).prop("checked", false);
                        $(this).removeClass('selected');
                    }
                    selfObj.saveState($(input).attr('value'));
                });

            });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        selfObj.isAnySearch();
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).prop("checked"));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).prop('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).prop('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).prop('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).prop('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).prop('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).prop('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).prop('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).prop('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).prop('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).prop('checked'));
        });
        initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });
        $('#reset_all').click(function () {
            selfObj.resetAll();
        });

        selfObj.addCustomToken();
        $('#addKeyword').click(function () {
            selfObj.addKeyword();
        });
        $('#keywordSearch').keypress(function (e) {
            if (e.which == 13) {
                selfObj.addKeyword();
            }
        });

        selfObj.removeFilter();
        selfObj.removeKeywordFilter();
        selfObj.selectCurrentPageRecords();
        selfObj.selectAllRecords();
        selfObj.clearSelection();
        selfObj.exportRecords();
        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked)
            totalChecked++;
        else
            totalChecked--;
        if (totalChecked < 0)
            totalChecked = 0;
        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.blockUI({
            message: 'Please wait...',
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff',
                zIndex: 999999
            }
        });
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                var source = $('#metro-js').attr('src');
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = source;
                script.id = "metro-js";
                $("#recordsContainer").append(script);
                selfObj.initDataTable();
                selfObj.bindEvents();
                $('body').scrollTop(0);
                $.unblockUI();
            }

        });
    }

    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        if ($('#keywordSearch').val() != '') {
            if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                Filters = JSON.parse($('#facet_keyword_search').val());
            }
            else {
                Filters = new Array();
            }
            for (x in Filters) {
                if (Filters[x].value == $('#keywordSearch').val()) {
                    alert($('#keywordSearch').val() + " filter is already applied.");
                    return false;
                }
            }
            var temp = {};
            temp.value = $('#keywordSearch').val();
            temp.type = customColumnName;
            Filters.push(temp);

            $('#facet_keyword_search').val(JSON.stringify(Filters));
            customFieldName = 'All';
            customColumnName = 'all';
            filterRecords();
        }
    }

    this.removeFilter = function () {
        $('.delFilter').click(function () {
            elementID = $(this).attr('data-elementId');
            type = $(this).attr('data-type');
            $('#' + elementID).prop('checked', false);
            checkParentFacet(type);
        });
    }
    this.removeKeywordFilter = function () {
        $('.deleteKeyword').click(function () {
            var index = $.trim($(this).data().index);
            Filters = JSON.parse($('#facet_keyword_search').val());
            delete (Filters[index]);
            Filters.splice(index, 1);
            $('#facet_keyword_search').val(JSON.stringify(Filters));
            filterRecords();
        });

    }
    this.resetAll = function () {
        $('#formSearch').find('input:hidden, input:text, select').val('');
        $('#formSearch').find('input:radio, input:checkbox')
                .removeAttr('checked').removeAttr('selected');
        filterRecords();
    }
    this.isAnySearch = function () {
        if ($('.search_keys').length > 0) {
            $('#reset_all').show();
        }
        else {
            $('#reset_all').hide();

        }

    }

    this.selectCurrentPageRecords = function () {
        $('#selectAll').click(function () {
            if ($(this).prop('checked') == true) {
                selfObj.selectAllRecords = true;
                $('input[name=record_checkbox]').attr('checked', 'checked');
                $('input[name=record_checkbox]').prop('checked', true);
                if (selfObj.totalRecords > 0 && selfObj.totalRecords > selfObj.totalCurrentPageRecords) {
                    var html = '';
                    html += 'All ' + selfObj.totalCurrentPageRecords + ' records on this page selected.';
                    html += ' Select all ' + selfObj.totalRecords + ' records. Clear selection';
                    $("#div-select-all-records").html(html);
                    $('#div-select-all-records').fadeIn('slow');
                }
                $('#records tbody tr').addClass("selected");
                selfObj.saveState(0, 'check_current', 1);
            } else if ($(this).prop('checked') == false) {
                selfObj.selectAllRecords = false;
                $('input[name=record_checkbox]').removeAttr('checked');
                $('input[name=record_checkbox]').prop('checked', false);
                $("#div-select-all-records").html('');
                $('#records tbody tr').removeClass("selected");
                selfObj.saveState(0, 'check_current', 0);
            }
        });
    }

    this.selectAllRecords = function () {
        $(document).on('click', '#select-all-records', function () {
            selfObj.selectAllRecords = true;
            $(this).hide();
            $('input[name=record_checkbox]').attr('checked', 'checked');
            $('input[name=record_checkbox]').prop('checked', true);
            $('#records tbody tr').addClass("selected");
            selfObj.saveState(0, 'all', 1);
            $('#div-select-all-records').html('All ' + selfObj.totalRecords + ' records selected. Clear selection');
        });
    }

    this.clearSelection = function () {
        $(document).on('click', '#clear-selection', function () {
            selfObj.selectAllRecords = false;
            $('#selectAll').removeAttr('checked');
            $('input[name=record_checkbox]').removeAttr('checked');
            $('input[name=record_checkbox]').prop('checked', false);
            $('#div-select-all-records').fadeOut('slow');
            $('#records tbody tr').removeClass("selected");
            $(this).hide();
            selfObj.saveState(0, 'all', 0);
        });
    }

    this.saveState = function (elementID, select, isChecked) {
        var id = '';
        var checked = 0;
        var isAll = 0;
        var selectedrecords = '';
        if (select) {
            if (select == 'all') {
                checked = isChecked;
                isAll = 1;
                selectedrecords = 'all';
            }
            else {
                checked = isChecked;
                if ($('input[name=record_checkbox]').attr("checked") == "checked") {
                    $('input[name=record_checkbox]').each(function () {
                        id += $(this).val() + ',';
                    });
                    selectedrecords = id;
                }
            }
        }
        else {
            id = elementID;
            if ($('#row_' + elementID).attr('checked')) {
                checked = 1;
                selectedrecords = id;
            }
        }
        $("#selectedrecords").val(selectedrecords);
        $.ajax({
            type: 'POST',
            url: ajaxSaveStateUrl,
            data: {id: id, checked: checked, is_all: isAll, },
            dataType: 'json',
            success: function (response)
            {

            }
        });
    }

    this.exportRecords = function () {
        $('.export').click(function (e) {
            var checked = $('input[name=record_checkbox]').attr("checked");
            console.log(checked);
            if (checked == "checked") {
                var exportType = $(this).attr('data-type');
                var selectedrecords = $("#selectedrecords").val();
                $.Dialog({
                    overlay: true,
                    shadow: true,
                    flat: true,
                    title: 'Export Records',
                    content: 'Are you sure you want to export the record(s)?',
                    closeButton: true,
                    width: 400,
                    height: 150,
                    padding: 10,
                    'buttons': {
                        'Ok': {
                            'action': function () {
                            }
                        },
                        'Cancel': {
                            'action': function () {
                            }
                        }
                    }
                });
//                $.ajax({
//                    type: 'POST',
//                    url: ajaxExportUrl,
//                    data: {type: exportType, records: selectedrecords},
//                    dataType: 'json',
//                    success: function (response)
//                    {
//
//                    }
//                });
            } else {
                $.Dialog({
                    'title': 'Error',
                    'content': 'Please select any record.',
                    'draggable': true,
                    'overlay': true,
                    'closeButton': false,
                    'buttonsAlign': 'right',
                    shadow: true,
                    flat: true,
                    width: 400,
                    height: 150,
                    padding: 10,
                    'position': {
                        'zone': 'right'
                    },
                });
            }
        });
    }
}

<commit_msg>export records<commit_after>/**
 * Class of managing Filtering and displaying of records.
 *
 * @returns {Records}
 */
function Records() {
    /**
     * Object of datatable.
     */
//	this.oTable = null;
    /**
     * URL for managing calls of datatable
     * @type {string}
     */
    var ajaxSource = null;
    var pageUrl = null;
    var selfObj = this;
    var Filters = new Object();
    var customFieldName = 'All';
    var customColumnName = 'all';
    var ajaxSaveStateUrl = null;
    var selectAllRecords = false;
    var totalRecords = 0;
    var totalCurrentPageRecords = 0;
    var ajaxExportUrl = null;
    /**
     * Set the ajax URL of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSource = function (source) {
        ajaxSource = source;

    }
    /**
     * Set the ajax URL for selected rows of datatable.
     * @param {string} source
     *
     */
    this.setAjaxSaveStateUrl = function (source) {
        ajaxSaveStateUrl = source;

    }
    /**
     * Set the ajax URL to save export request in db.
     * @param {string} source
     *
     */
    this.setAjaxExportUrl = function (source) {
        ajaxExportUrl = source;

    }
    /**
     * Set the page url.
     * @param {string} url
     *
     */
    this.setPageUrl = function (url) {
        pageUrl = url;

    }
    /**
     * Initialize the datatable.
     *
     */
    this.initDataTable = function () {
        // check the existence of table on which we are going to apply datatable.
        if ($('#records').length > 0)
        {
            // Modify css for managing view.
//			$('#container').removeClass('container');
//			$('#container').css('margin', '20px');
            var selected = [];
            oTable =
                    $('#records').dataTable(
                    {
                        "dom": '<"top"p><"clear">tir<"bottom"p>',
                        "bProcessing": true,
                        "bServerSide": true,
                        retrieve: true,
                        destroy: true,
                        "language": {
                            "info": "Showing _START_ - _END_ of _MAX_",
                            "infoFiltered": ''
                        },
                        "aoColumnDefs": [
                            {"bSortable": false, "aTargets": [0]}
                        ],
                        "aaSorting": [],
                        "sAjaxSource": ajaxSource,
                        "bStateSave": true,
//				"fnInitComplete": function () {
//					this.oTable.fnAdjustColumnSizing();
//				},
                        "fnServerData": function (sSource, aoData, fnCallback) {
                            jQuery.getJSON(sSource, aoData, function (json) {
                                fnCallback(json);
                                selfObj.totalRecords = json.iTotalDisplayRecords;
                                selfObj.totalCurrentPageRecords = json.iTotalRecords;
                            });
                        },
                        "createdRow": function (row, data, index) {
                            var input = $(row).find("td:first").html();
                            row.id = "row-" + $(input).attr('value');
                        },
//                        "ajax": ajaxSaveStateUrl,
                        "rowCallback": function (row, data) {
                            if ($(data[0]).attr("checked") == "checked") {
                                $(row).addClass("selected");
                            }
                        }
                    });
            $('#records tbody').on('click', 'tr', function () {
                var id = this.id;
                var index = $.inArray(id, selected);
                if (index === -1) {
                    selected.push(id);
                } else {
                    selected.splice(index, 1);
                }
                $(this).toggleClass('selected', function () {
                    var input = $("#" + id + " td:first").html();
                    if ($(this).hasClass('selected') === true) {
                        $("#" + $(input).attr('id')).attr("checked", "checked");
                        $("#" + $(input).attr('id')).prop("checked", true);
                    } else {
                        $("#" + $(input).attr('id')).removeAttr("checked");
                        $("#" + $(input).attr('id')).prop("checked", false);
                        $(this).removeClass('selected');
                    }
                    selfObj.saveState($(input).attr('value'));
                });

            });
        }

    }
    /**
     *
     * @returns {Boolean}
     */
    this.bindEvents = function () {
        selfObj.isAnySearch();
        $('input[name="mediaType[]"]').click(function () {
            checkParentFacet('media_type', $(this).prop("checked"));
        });
        $('input[name="commercial[]"]').click(function () {
            checkParentFacet('commercial', $(this).prop('checked'));
        });
        $('input[name="format[]"]').click(function () {
            checkParentFacet('format', $(this).prop('checked'));
        });
        $('input[name="base[]"]').click(function () {
            checkParentFacet('base', $(this).prop('checked'));
        });
        $('input[name="recordingStandard[]"]').click(function () {
            checkParentFacet('recordingStandard', $(this).prop('checked'));
        });
        $('input[name="printType[]"]').click(function () {
            checkParentFacet('printType', $(this).prop('checked'));
        });
        $('input[name="project[]"]').click(function () {
            checkParentFacet('project', $(this).prop('checked'));
        });
        $('input[name="reelDiameter[]"]').click(function () {
            checkParentFacet('reelDiameter', $(this).prop('checked'));
        });
        $('input[name="discDiameter[]"]').click(function () {
            checkParentFacet('discDiameter', $(this).prop('checked'));
        });
        $('input[name="acidDetection[]"]').click(function () {
            checkParentFacet('acidDetection', $(this).prop('checked'));
        });
        $('input[name="collectionName[]"]').click(function () {
            checkParentFacet('collectionName', $(this).prop('checked'));
        });
        initTriStateCheckBox('is_review_check', 'is_review_check_state', true);
        $('#is_review_check').click(function () {
            var totalChecked = $('#total_checked').val();
            var containerId = $(this).attr('id');
            var currentVal = $('#' + containerId + '_state').val();
            if (currentVal > 0 && totalChecked == 0)
            {
                totalChecked++;
                $('#parent_facet').val(containerId);
                $('#total_checked').val(totalChecked);
            }
            if (currentVal == 0 && $('#parent_facet').val() == containerId) {
                totalChecked--;
                $('#parent_facet').val('');
                $('#total_checked').val(totalChecked);
            }
            filterRecords();
        });
        $('#reset_all').click(function () {
            selfObj.resetAll();
        });

        selfObj.addCustomToken();
        $('#addKeyword').click(function () {
            selfObj.addKeyword();
        });
        $('#keywordSearch').keypress(function (e) {
            if (e.which == 13) {
                selfObj.addKeyword();
            }
        });

        selfObj.removeFilter();
        selfObj.removeKeywordFilter();
        selfObj.selectCurrentPageRecords();
        selfObj.selectAllRecords();
        selfObj.clearSelection();
        selfObj.exportRecords();
        return true;
    }
    /**
     *
     * @param {type} type
     * @param {type} isChecked
     * @returns {undefined}
     */
    var checkParentFacet = function (type, isChecked) {
        //todo need to update function
        var totalChecked = $('#total_checked').val();
        var total = $('#facet_sidebar input:checked').length;
        if (total == 0)
            totalChecked = 0;
        if (isChecked)
            totalChecked++;
        else
            totalChecked--;
        if (totalChecked < 0)
            totalChecked = 0;
        $('#total_checked').val(totalChecked);

        if ($('#parent_facet').val() == '' && totalChecked == 1)
            $('#parent_facet').val(type);
        else if (totalChecked == 0)
            $('#parent_facet').val('');
        filterRecords();
    }
    /**
     *
     * @returns {undefined}
     */
    var filterRecords = function () {
        $.blockUI({
            message: 'Please wait...',
            css: {
                border: 'none',
                padding: '15px',
                backgroundColor: '#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                opacity: .5,
                color: '#fff',
                zIndex: 999999
            }
        });
        $.ajax({
            type: 'GET',
            url: pageUrl,
            data: $('#formSearch').serialize(),
            dataType: 'json',
            success: function (response)
            {
                $("#recordsContainer").html(response.html);
                var source = $('#metro-js').attr('src');
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = source;
                script.id = "metro-js";
                $("#recordsContainer").append(script);
                selfObj.initDataTable();
                selfObj.bindEvents();
                $('body').scrollTop(0);
                $.unblockUI();
            }

        });
    }

    /**
     *
     * @returns {undefined}
     */
    this.addCustomToken = function () {
        $('.customToken').click(function () {
            customFieldName = $(this).attr('data-fieldName');
            customColumnName = $(this).attr('data-columnName');
            $('#limit_field_text').html(customFieldName);
        });
    }

    this.addKeyword = function () {
        if ($('#keywordSearch').val() != '') {
            if ($('#facet_keyword_search').val() != '' && $('#facet_keyword_search').val() != '""') {
                Filters = JSON.parse($('#facet_keyword_search').val());
            }
            else {
                Filters = new Array();
            }
            for (x in Filters) {
                if (Filters[x].value == $('#keywordSearch').val()) {
                    alert($('#keywordSearch').val() + " filter is already applied.");
                    return false;
                }
            }
            var temp = {};
            temp.value = $('#keywordSearch').val();
            temp.type = customColumnName;
            Filters.push(temp);

            $('#facet_keyword_search').val(JSON.stringify(Filters));
            customFieldName = 'All';
            customColumnName = 'all';
            filterRecords();
        }
    }

    this.removeFilter = function () {
        $('.delFilter').click(function () {
            elementID = $(this).attr('data-elementId');
            type = $(this).attr('data-type');
            $('#' + elementID).prop('checked', false);
            checkParentFacet(type);
        });
    }
    this.removeKeywordFilter = function () {
        $('.deleteKeyword').click(function () {
            var index = $.trim($(this).data().index);
            Filters = JSON.parse($('#facet_keyword_search').val());
            delete (Filters[index]);
            Filters.splice(index, 1);
            $('#facet_keyword_search').val(JSON.stringify(Filters));
            filterRecords();
        });

    }
    this.resetAll = function () {
        $('#formSearch').find('input:hidden, input:text, select').val('');
        $('#formSearch').find('input:radio, input:checkbox')
                .removeAttr('checked').removeAttr('selected');
        filterRecords();
    }
    this.isAnySearch = function () {
        if ($('.search_keys').length > 0) {
            $('#reset_all').show();
        }
        else {
            $('#reset_all').hide();

        }

    }

    this.selectCurrentPageRecords = function () {
        $('#selectAll').click(function () {
            if ($(this).prop('checked') == true) {
                selfObj.selectAllRecords = true;
                $('input[name=record_checkbox]').attr('checked', 'checked');
                $('input[name=record_checkbox]').prop('checked', true);
                if (selfObj.totalRecords > 0 && selfObj.totalRecords > selfObj.totalCurrentPageRecords) {
                    var html = '';
                    html += 'All ' + selfObj.totalCurrentPageRecords + ' records on this page selected.';
                    html += ' Select all ' + selfObj.totalRecords + ' records. Clear selection';
                    $("#div-select-all-records").html(html);
                    $('#div-select-all-records').fadeIn('slow');
                }
                $('#records tbody tr').addClass("selected");
                selfObj.saveState(0, 'check_current', 1);
            } else if ($(this).prop('checked') == false) {
                selfObj.selectAllRecords = false;
                $('input[name=record_checkbox]').removeAttr('checked');
                $('input[name=record_checkbox]').prop('checked', false);
                $("#div-select-all-records").html('');
                $('#records tbody tr').removeClass("selected");
                selfObj.saveState(0, 'check_current', 0);
            }
        });
    }

    this.selectAllRecords = function () {
        $(document).on('click', '#select-all-records', function () {
            selfObj.selectAllRecords = true;
            $(this).hide();
            $('input[name=record_checkbox]').attr('checked', 'checked');
            $('input[name=record_checkbox]').prop('checked', true);
            $('#records tbody tr').addClass("selected");
            selfObj.saveState(0, 'all', 1);
            $('#div-select-all-records').html('All ' + selfObj.totalRecords + ' records selected. Clear selection');
        });
    }

    this.clearSelection = function () {
        $(document).on('click', '#clear-selection', function () {
            selfObj.selectAllRecords = false;
            $('#selectAll').removeAttr('checked');
            $('input[name=record_checkbox]').removeAttr('checked');
            $('input[name=record_checkbox]').prop('checked', false);
            $('#div-select-all-records').fadeOut('slow');
            $('#records tbody tr').removeClass("selected");
            $(this).hide();
            selfObj.saveState(0, 'all', 0);
        });
    }

    this.saveState = function (elementID, select, isChecked) {
        var id = '';
        var checked = 0;
        var isAll = 0;
        var selectedrecords = '';
        if (select) {
            if (select == 'all') {
                checked = isChecked;
                isAll = 1;
                selectedrecords = 'all';
            }
            else {
                checked = isChecked;
                if ($('input[name=record_checkbox]').attr("checked") == "checked") {
                    $('input[name=record_checkbox]').each(function () {
                        id += $(this).val() + ',';
                    });
                    selectedrecords = id;
                }
            }
        }
        else {
            id = elementID;
            if ($('#row_' + elementID).attr('checked')) {
                checked = 1;
                selectedrecords = id;
            }
        }
        $("#selectedrecords").val(selectedrecords);
        $.ajax({
            type: 'POST',
            url: ajaxSaveStateUrl,
            data: {id: id, checked: checked, is_all: isAll, },
            dataType: 'json',
            success: function (response)
            {

            }
        });
    }

    this.exportRecords = function () {
        $('.export').click(function (e) {
            var checked = $('input[name=record_checkbox]').prop("checked");
            console.log(checked);
            if (checked == "checked") {
                var exportType = $(this).attr('data-type');
                var selectedrecords = $("#selectedrecords").val();
                $.Dialog({
                    overlay: true,
                    shadow: true,
                    flat: true,
                    title: 'Export Records',
                    content: 'Are you sure you want to export the record(s)?',
                    closeButton: true,
                    width: 400,
                    height: 150,
                    padding: 10,
                    'buttons': {
                        'Ok': {
                            'action': function () {
                            }
                        },
                        'Cancel': {
                            'action': function () {
                            }
                        }
                    }
                });
//                $.ajax({
//                    type: 'POST',
//                    url: ajaxExportUrl,
//                    data: {type: exportType, records: selectedrecords},
//                    dataType: 'json',
//                    success: function (response)
//                    {
//
//                    }
//                });
            } else {
                $.Dialog({
                    'title': 'Error',
                    'content': 'Please select any record.',
                    'draggable': true,
                    'overlay': true,
                    'closeButton': false,
                    'buttonsAlign': 'right',
                    shadow: true,
                    flat: true,
                    width: 400,
                    height: 150,
                    padding: 10,
                    'position': {
                        'zone': 'right'
                    },
                });
            }
        });
    }
}

<|endoftext|>


<commit_before>var cv = require('opencv');
var configLot = require("../../lib/config/config");

// camera properties
var camWidth = 320;
var camHeight = 240;
var camFps = 10;
var camInterval = 1000 / camFps;

// face detection properties
var rectColor = [0, 255, 0];
var rectColorRed = [0,0,255];
var rectThickness = 2;

//Thresh values and area from movement detection
var lowThresh = 0;
var highThresh = 50;
var nIters = 2;
var minArea = 600;

// initialize camera
var camera = new cv.VideoCapture(0);

camera.setWidth(camWidth);
camera.setHeight(camHeight);

//Initialize the frame
var firstFrame = null;

module.exports = function (socket) {
  setInterval(function() {
    camera.read(function(err, im) {
      if (err) throw err;

      // obtain the frame
      var gray = im.copy();

      // if the fisrt frame is None, initialize it
      if(firstFrame == null){
      	firstFrame = gray;
        gray.save('firstFrame.png');
      }

      //convert the frame into grayscale and blur it
      gray.convertGrayscale();
      gray.gaussianBlur([21,21]);

      //Compute the absolute difference between the current frame and first frame
      var frameDelta = new cv.Matrix(im.width(), im.height());
      frameDelta.absDiff(firstFrame,gray);

      // dilate the thereshold image to fill un holes
      // then find contours on threasholder image
      frameDelta.canny(lowThresh, highThresh);
  	  frameDelta.dilate(nIters);
  	  contours = frameDelta.findContours();

      for (i = 0; i < contours.size(); i++) {
  	  //loop over the contours
  	  	 //if te contour is too small, ignore it
    	   if (contours.area(i) < minArea) continue;

         configLot.forEach(function (data) {

           var imRoi = im.roi(data.position.x,
             data.position.y,
             data.position.width,
             data.position.height);

             if(data.occupied){
               im.rectangle([data.position.x,
                             data.position.y],
                             [data.position.width,
                             data.position.height], rectColorRed, rectThickness);
             }else{
               im.rectangle([data.position.x,
                             data.position.y],
                             [data.position.width,
                             data.position.height], rectColor, rectThickness);
             }

           imRoi.detectObject('./node_modules/opencv/data/haarcascade_frontalface_alt2.xml', {}, function(err, cars) {
         	    if (!err){
                if(cars.length==0){
                    //TODO
                    data.occupied = false;
                    console.log('NO detectObject');
                }else{
                    //TODO
                    data.occupied = true;

                    if(data.occupied_time == ""){
                        data.occupied_time = new Date();
                    }else{
                      var diffMs = (data.occupied_time - new Date());
                      var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000);

                      if(diffMins >1){
                          console.log('DetectObject');
                      }
                    }
                }
              }

              socket.emit('frame', { buffer: im.toBuffer() });
       	   });
         })
      }

    });
  }, camInterval);
};

/**
 * You first need to create a formatting function to pad numbers to two digits…
 **/
function twoDigits(d) {
    if(0 <= d && d < 10) return "0" + d.toString();
    if(-10 < d && d < 0) return "-0" + (-1*d).toString();
    return d.toString();
}

/**
 * …and then create the method to output the date string as desired.
 * Some people hate using prototypes this way, but if you are going
 * to apply this to more than one Date object, having it as a prototype
 * makes sense.
 **/
Date.prototype.toMysqlFormat = function() {
    return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};
<commit_msg>pequeños cambios<commit_after>var cv = require('opencv');
var configLot = require("../../lib/config/config");

// camera properties
var camWidth = 320;
var camHeight = 240;
var camFps = 10;
var camInterval = 1000 / camFps;

// face detection properties
var rectColor = [0, 255, 0];
var rectColorRed = [0,0,255];
var rectThickness = 2;

//Thresh values and area from movement detection
var lowThresh = 0;
var highThresh = 50;
var nIters = 2;
var minArea = 600;

// initialize camera
var camera = new cv.VideoCapture(0);

camera.setWidth(camWidth);
camera.setHeight(camHeight);

//Initialize the frame
var firstFrame = null;

module.exports = function (socket) {
  setInterval(function() {
    camera.read(function(err, im) {
      if (err) throw err;

      var gray = im.copy();

      // if the fisrt frame is None, initialize it
      if(firstFrame == null){
      	firstFrame = gray;
        gray.save('firstFrame.png');
      }

      //convert the frame into grayscale and blur it
      gray.convertGrayscale();
      gray.gaussianBlur([21,21]);

      //Compute the absolute difference between the current frame and first frame
      var frameDelta = new cv.Matrix(im.width(), im.height());
      frameDelta.absDiff(firstFrame,gray);

      // dilate the thereshold image to fill un holes
      // obtain the frame
      // then find contours on threasholder image
      frameDelta.canny(lowThresh, highThresh);
  	  frameDelta.dilate(nIters);
  	  contours = frameDelta.findContours();

      for (i = 0; i < contours.size(); i++) {
  	  //loop over the contours
  	  	 //if te contour is too small, ignore it
    	   if (contours.area(i) < minArea) continue;

         configLot.forEach(function (data) {

           var imRoi = im.roi(data.position.x,
             data.position.y,
             data.position.width,
             data.position.height);

             if(data.occupied){
               im.rectangle([data.position.x,
                             data.position.y],
                             [data.position.width,
                             data.position.height], rectColorRed, rectThickness);
             }else{
               im.rectangle([data.position.x,
                             data.position.y],
                             [data.position.width,
                             data.position.height], rectColor, rectThickness);
             }

           imRoi.detectObject('../data/hogcascade_cars_sideview.xml', {}, function(err, cars) {
         	    if (!err){
                if(cars.length==0){
                    //TODO
                    data.occupied = false;
                    console.log('NO detectObject');
                }else{
                    //TODO
                    data.occupied = true;

                    if(data.occupied_time == ""){
                        data.occupied_time = new Date();
                    }else{
                      var diffMs = (data.occupied_time - new Date());
                      var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000);

                      if(diffMins >1){
                          console.log('DetectObject');
                      }
                    }
                }
              }

              socket.emit('frame', { buffer: im.toBuffer() });
       	   });
         })
      }

    });
  }, camInterval);
};

/**
 * You first need to create a formatting function to pad numbers to two digits…
 **/
function twoDigits(d) {
    if(0 <= d && d < 10) return "0" + d.toString();
    if(-10 < d && d < 0) return "-0" + (-1*d).toString();
    return d.toString();
}

/**
 * …and then create the method to output the date string as desired.
 * Some people hate using prototypes this way, but if you are going
 * to apply this to more than one Date object, having it as a prototype
 * makes sense.
 **/
Date.prototype.toMysqlFormat = function() {
    return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};
<|endoftext|>


<commit_before>window.urb = window.urb || {}
window.urb.appl = window.urb.appl || null

window.urb.init = function(onload){ // XX proper class?
  onload = onload || function(){}
  var $init = this.init
  if($init.loaded) return onload()
  if($init.loading) return $init.loading.push(onload)
  $init.loading = [onload]
  var s = document.createElement('script')
  s.src = "/~/at/~/auth.js" // XX nop.js? auth.json?
  s.onload = function(){
    $init.loading.map(function(f){f()})
    delete $init.loading
    $init.loaded = true
  }
  document.body.appendChild(s)
}
window.urb.init.loaded = window.urb.oryx

window.urb.req = function(method,url,params,json,cb) {
  var xhr = new XMLHttpRequest()
  method = method.toUpperCase()
  if(method == "PUT" || method == "DELETE")
    xhr.open("POST", url+"?"+method)
  else xhr.open(method, url)

  if(json)
    xhr.setRequestHeader("content-type", "text/json")

  if(!window.urb.oryx) throw "No CSRF token" // XX fetch auth.json
  _data = {oryx: window.urb.oryx}
  if(params.xyro) { _data.xyro = params.xyro; }
  if(params.ship) { _data.ship = params.ship; }
  if(params.path) { _data.path = params.path; }
  if(params.appl) { _data.appl = params.appl; }
  if(params.mark) { _data.mark = params.mark; }
  if(params.wire) { _data.wire = params.wire; }
  if(cb) {
    xhr.onload = function() {
      var err,res
      try {
        err = null
        res = {
          status:this.status,
          data: JSON.parse(this.responseText)
        }
        if(res.data.reload)
          res.reload = res.data.reload
      } catch(e) {
        // if(urb.wall !== false) document.write(this.responseText) // XX
        err = {
          message:"Failed to parse JSON",
          raw:this.responseText
        }
        res = null
      }
      finally {
       cb(err,res)
      }
    }
    xhr.onerror = function() {
      cb({
        status:this.status,
        data:this.responseText
      })
    }
  }
  xhr.send(JSON.stringify(_data))
}

// window.urb.getJSON = function(url,cb){ window.urb.reqJSON("GET",url, null, cb)}
// window.urb.reqJSON = function(method, url, data, cb){
//   var xhr = new XMLHttpRequest()
//   xhr.open(method, url)
//   xhr.onload = function(){
//     urb.fetchTag.call(xhr)
//     if(cb) cb(JSON.parse(xhr.responseText))
//   }
//   xhr.send(data === null ? null : JSON.stringify(data))
// }

window.urb.reqq = []
window.urb.qreq = function(method,url,params,json,cb) {
  walk = function() {
    qobj = {}
    qobj.oargs = window.urb.reqq[0]
    qobj.nargs = [].slice.call(qobj.oargs,0,4)
    qobj.nargs.push(function(){
      if(this.oargs[4])
        this.oargs[4].apply(window.urb,arguments)
      window.urb.reqq.shift()
      if(window.urb.reqq.length > 0)
        walk()
    }.bind(qobj))
    window.urb.req.apply(this,qobj.nargs)
  }
  l = window.urb.reqq.length
  window.urb.reqq.push(arguments);
  if(l == 0) { walk() }
}

window.urb.send = function(data,params,cb) { // or send(data, cb)
  if(!params || typeof params === "function")
    {cb = params; params = {}}

  var url, $send
  $send = this.send

  params.data = data
  params.ship = params.ship || this.ship
  params.appl = params.appl || this.appl
  params.mark = params.mark || $send.mark
  // params.seqn = params.seqn || $send.seqn
  params.wire = params.wire || "/"
  params.xyro = (typeof(params.data) === 'undefined') ? null : params.data

  if(!params.mark) throw new Error("You must specify a mark for urb.send.")
  if(!params.appl) throw new Error("You must specify an appl for urb.send.")

  url = ["to",params.appl,params.mark]
  url = "/~/"+url.join("/")

  // $send.seqn++

  this.qreq('post',url,params,true,function(err,data) {
    /* if(err) { $send.seqn--; }
    else */ if(data && data.data.fail && urb.wall !== false) {
      document.location = "#ERROR"
      document.write("
"+JSON.stringify(params.xyro)+"\n"
                            +data.data.mess+"
") // XX
    }
    if(cb) { cb.apply(this,arguments); }
  })
}
// window.urb.send.seqn = 0
window.urb.send.mark = "json"

window.urb.gsig = function(params) {
  var path = params.path
  if(!path) path = ""
  if(path[0] !== "/") path = "/"+path
  return  "~"+params.ship+"/"+
          params.appl+
          path.replace(/[^\x00-\x7F]/g, "")
}

window.urb.puls = false
window.urb.cabs = {}
window.urb.poll = function(params) {
  if(!params) throw new Error("You must supply params to urb.poll.")

  var url, $this

  seqn = this.poll.seqn
  if(params.seqn) seqn = params.seqn()

  url = "/~/of/"+this.ixor+"?poll="+seqn

  this.puls = true

  $this = this
  this.req("get",url,params,true,function(err,res) {
    $this.poll.dely = params.dely || $this.poll.dely
    if(res){
      if(res.data.beat)
        return $this.poll(params)
      switch(res.data.type){
          case "news":
        return document.location.reload()  // XX check autoreload
          case "rush":
          case "mean":
        var err2 = err
        if(res.data.type == "mean")
          err2 = res.data.data
        var fn = $this.gsig(res.data.from)
        if($this.cabs[fn])
          $this.cabs[fn].call(this,err2,
            {status: res.status, data: res.data.data.json}) // XX non-json
        break;
          default:
        throw new Error("Lost event %"+res.data.type)
      }
      if(params.incs)
        params.incs()
      else
        $this.poll.seqn++
      $this.poll.dely = 250
      return $this.poll(params)
    }

    else if(err){
      setTimeout(function() {
        $this.poll(params)
      }, $this.poll.dely)
      $this.poll.dely += Math.ceil($this.poll.dely*.2)
    }
    else throw "Neither error nor result on poll"
  })
}
window.urb.poll.seqn = 1
window.urb.poll.dely = 250

window.urb.bind = function(path, params, cb, nicecb){ // or bind(path, cb)
  if(!params || typeof params === "function")
    {cb = params; params = {}}

  params.path = path
  if(params.path[0] !== "/") params.path = "/"+params.path
  params.ship = params.ship || this.ship
  params.appl = params.appl || this.appl
  params.mark = params.mark || this.bind.mark
  params.wire = params.wire || params.path

  if(typeof path != "string")
    throw new Error("You must specify a string path for urb.bind.")
  if(!params.appl) throw new Error("You must specify an appl for urb.bind.")
  if(!cb) throw new Error("You must supply a callback to urb.bind.")

  var method, perm, url, $this

  if(params.mark !== "json")
    throw new Error("Non-json subscriptions unimplemented.")  //  XX
  url = "/~/is/"+this.gsig(params)+"."+params.mark

  params.path = params.wire
  this.cabs[this.gsig(params)] = cb

  $this = this
  this.qreq("put",url,params,true,function(err,res) {
    if(nicecb) { nicecb.apply(this,[err,{status: res.status, data: res.data}])}
    //  XX give raw data
    //
    if(!err && !$this.puls) $this.poll(params)
  })
}
urb.bind.mark = "json"

window.urb.drop = function(path, params, cb){  // or drop(path,cb)
  if(typeof params === "function")
    {cb = params; params = {}}

  params.path = path
  if(params.path[0] !== "/") params.path = "/"+params.path
  params.ship = params.ship || this.ship
  params.appl = params.appl || this.appl
  params.wire = params.wire || params.path

  if(typeof path != "string")
    throw new Error("You must specify a string path for urb.drop.")
  if(!params.appl) throw new Error("You must specify an appl for urb.drop.")

  url = "/~/is/"+this.gsig(params)+".json"
  method = "delete"
  this.req("delete",url,params,true,function(err,res) {
    if(cb) cb(err,res)
  })
}

window.urb.subscribe = function(params,cb) {   //  legacy interface
  if(!params) throw new Error("You must supply params to urb.subscribe")
  return window.urb.bind(params.path, params, cb, cb)
}

window.urb.unsubscribe = function(params,cb) { //  legacy intreface
  if(!params) throw new Error("You must supply params to urb.unsubscribe.")
  return window.urb.drop(params.path, params, cb)
}

window.urb.util = {
  isURL: function(s) {
     r = new RegExp('^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$', 'i');
     return s.length < 2083 && r.test(s);
  },
  numDot: function(n) {
    _n = String(n)
    fun = function(s){
      if(s.length <= 3)
        return s
      return fun(s.slice(0,-3))+"."+s.slice(-3)
    }
    return fun((_n))
  },
  toDate: function (dat){
    var mils = Math.floor((0x10000 * dat.getUTCMilliseconds()) / 1000).toString(16)
    function pad(num, str){
      return ((new Array(num + 1)).join('0') + str).substr(-num,num)
    }
    return  '~' + dat.getUTCFullYear() +
            '.' + (dat.getUTCMonth() + 1) +
            '.' + dat.getUTCDate() +
           '..' + pad(2, dat.getUTCHours()) +
            '.' + pad(2, dat.getUTCMinutes()) +
            '.' + pad(2, dat.getUTCSeconds()) +
           '..' + pad(4, mils)
  },
  basepath: function(spur, pathname){
    spur = spur || ''
    if(spur === '/') spur = ''
    pathname = pathname || window.location.pathname

    base = ""

    if(pathname.indexOf("/~~") == 0)
      base = "/~~"
    if(pathname.indexOf("/~/as/") == 0)
      base = "/~/as/"+pathname.split("/")[3]
    if(pathname.indexOf("/~/away") == 0)
      base = "/~/away"

    return base+spur
  }
}
<commit_msg>Set timeout for urb.req<commit_after>window.urb = window.urb || {}
window.urb.appl = window.urb.appl || null

window.urb.init = function(onload){ // XX proper class?
  onload = onload || function(){}
  var $init = this.init
  if($init.loaded) return onload()
  if($init.loading) return $init.loading.push(onload)
  $init.loading = [onload]
  var s = document.createElement('script')
  s.src = "/~/at/~/auth.js" // XX nop.js? auth.json?
  s.onload = function(){
    $init.loading.map(function(f){f()})
    delete $init.loading
    $init.loaded = true
  }
  document.body.appendChild(s)
}
window.urb.init.loaded = window.urb.oryx

window.urb.req = function(method,url,params,json,cb) {
  var xhr = new XMLHttpRequest()
  method = method.toUpperCase()
  if(method == "PUT" || method == "DELETE")
    xhr.open("POST", url+"?"+method)
  else xhr.open(method, url)

  if(json)
    xhr.setRequestHeader("content-type", "text/json")

  xhr.timeout = 60000

  if(!window.urb.oryx) throw "No CSRF token" // XX fetch auth.json
  _data = {oryx: window.urb.oryx}
  if(params.xyro) { _data.xyro = params.xyro; }
  if(params.ship) { _data.ship = params.ship; }
  if(params.path) { _data.path = params.path; }
  if(params.appl) { _data.appl = params.appl; }
  if(params.mark) { _data.mark = params.mark; }
  if(params.wire) { _data.wire = params.wire; }
  if(cb) {
    xhr.onload = function() {
      var err,res
      try {
        err = null
        res = {
          status:this.status,
          data: JSON.parse(this.responseText)
        }
        if(res.data.reload)
          res.reload = res.data.reload
      } catch(e) {
        // if(urb.wall !== false) document.write(this.responseText) // XX
        err = {
          message:"Failed to parse JSON",
          raw:this.responseText
        }
        res = null
      }
      finally {
       cb(err,res)
      }
    }
    xhr.ontimeout = function() {
      cb({
        status:408,
        data:null
      })
    }
    xhr.onerror = function() {
      cb({
        status:this.status,
        data:this.responseText
      })
    }
  }
  xhr.send(JSON.stringify(_data))
}

// window.urb.getJSON = function(url,cb){ window.urb.reqJSON("GET",url, null, cb)}
// window.urb.reqJSON = function(method, url, data, cb){
//   var xhr = new XMLHttpRequest()
//   xhr.open(method, url)
//   xhr.onload = function(){
//     urb.fetchTag.call(xhr)
//     if(cb) cb(JSON.parse(xhr.responseText))
//   }
//   xhr.send(data === null ? null : JSON.stringify(data))
// }

window.urb.reqq = []
window.urb.qreq = function(method,url,params,json,cb) {
  walk = function() {
    qobj = {}
    qobj.oargs = window.urb.reqq[0]
    qobj.nargs = [].slice.call(qobj.oargs,0,4)
    qobj.nargs.push(function(){
      if(this.oargs[4])
        this.oargs[4].apply(window.urb,arguments)
      window.urb.reqq.shift()
      if(window.urb.reqq.length > 0)
        walk()
    }.bind(qobj))
    window.urb.req.apply(this,qobj.nargs)
  }
  l = window.urb.reqq.length
  window.urb.reqq.push(arguments);
  if(l == 0) { walk() }
}

window.urb.send = function(data,params,cb) { // or send(data, cb)
  if(!params || typeof params === "function")
    {cb = params; params = {}}

  var url, $send
  $send = this.send

  params.data = data
  params.ship = params.ship || this.ship
  params.appl = params.appl || this.appl
  params.mark = params.mark || $send.mark
  // params.seqn = params.seqn || $send.seqn
  params.wire = params.wire || "/"
  params.xyro = (typeof(params.data) === 'undefined') ? null : params.data

  if(!params.mark) throw new Error("You must specify a mark for urb.send.")
  if(!params.appl) throw new Error("You must specify an appl for urb.send.")

  url = ["to",params.appl,params.mark]
  url = "/~/"+url.join("/")

  // $send.seqn++

  this.qreq('post',url,params,true,function(err,data) {
    /* if(err) { $send.seqn--; }
    else */ if(data && data.data.fail && urb.wall !== false) {
      document.location = "#ERROR"
      document.write("
"+JSON.stringify(params.xyro)+"\n"
                            +data.data.mess+"
") // XX
    }
    if(cb) { cb.apply(this,arguments); }
  })
}
// window.urb.send.seqn = 0
window.urb.send.mark = "json"

window.urb.gsig = function(params) {
  var path = params.path
  if(!path) path = ""
  if(path[0] !== "/") path = "/"+path
  return  "~"+params.ship+"/"+
          params.appl+
          path.replace(/[^\x00-\x7F]/g, "")
}

window.urb.puls = false
window.urb.cabs = {}
window.urb.poll = function(params) {
  if(!params) throw new Error("You must supply params to urb.poll.")

  var url, $this

  seqn = this.poll.seqn
  if(params.seqn) seqn = params.seqn()

  url = "/~/of/"+this.ixor+"?poll="+seqn

  this.puls = true

  $this = this
  this.req("get",url,params,true,function(err,res) {
    $this.poll.dely = params.dely || $this.poll.dely
    if(res){
      if(res.data.beat) {
        $this.poll.dely = params.dely || 250
        return $this.poll(params)
      }
      switch(res.data.type){
          case "news":
        return document.location.reload()  // XX check autoreload
          case "rush":
          case "mean":
        var err2 = err
        if(res.data.type == "mean")
          err2 = res.data.data
        var fn = $this.gsig(res.data.from)
        if($this.cabs[fn])
          $this.cabs[fn].call(this,err2,
            {status: res.status, data: res.data.data.json}) // XX non-json
        break;
          default:
        throw new Error("Lost event %"+res.data.type)
      }
      if(params.incs)
        params.incs()
      else
        $this.poll.seqn++
      $this.poll.dely = 250
      return $this.poll(params)
    }

    else if(err){
      setTimeout(function() {
        $this.poll(params)
      }, $this.poll.dely)
      $this.poll.dely += Math.ceil($this.poll.dely*.2)
    }
    else throw "Neither error nor result on poll"
  })
}
window.urb.poll.seqn = 1
window.urb.poll.dely = 250

window.urb.bind = function(path, params, cb, nicecb){ // or bind(path, cb)
  if(!params || typeof params === "function")
    {cb = params; params = {}}

  params.path = path
  if(params.path[0] !== "/") params.path = "/"+params.path
  params.ship = params.ship || this.ship
  params.appl = params.appl || this.appl
  params.mark = params.mark || this.bind.mark
  params.wire = params.wire || params.path

  if(typeof path != "string")
    throw new Error("You must specify a string path for urb.bind.")
  if(!params.appl) throw new Error("You must specify an appl for urb.bind.")
  if(!cb) throw new Error("You must supply a callback to urb.bind.")

  var method, perm, url, $this

  if(params.mark !== "json")
    throw new Error("Non-json subscriptions unimplemented.")  //  XX
  url = "/~/is/"+this.gsig(params)+"."+params.mark

  params.path = params.wire
  this.cabs[this.gsig(params)] = cb

  $this = this
  this.qreq("put",url,params,true,function(err,res) {
    if(nicecb) { nicecb.apply(this,[err,{status: res.status, data: res.data}])}
    //  XX give raw data
    //
    if(!err && !$this.puls) $this.poll(params)
  })
}
urb.bind.mark = "json"

window.urb.drop = function(path, params, cb){  // or drop(path,cb)
  if(typeof params === "function")
    {cb = params; params = {}}

  params.path = path
  if(params.path[0] !== "/") params.path = "/"+params.path
  params.ship = params.ship || this.ship
  params.appl = params.appl || this.appl
  params.wire = params.wire || params.path

  if(typeof path != "string")
    throw new Error("You must specify a string path for urb.drop.")
  if(!params.appl) throw new Error("You must specify an appl for urb.drop.")

  url = "/~/is/"+this.gsig(params)+".json"
  method = "delete"
  this.req("delete",url,params,true,function(err,res) {
    if(cb) cb(err,res)
  })
}

window.urb.subscribe = function(params,cb) {   //  legacy interface
  if(!params) throw new Error("You must supply params to urb.subscribe")
  return window.urb.bind(params.path, params, cb, cb)
}

window.urb.unsubscribe = function(params,cb) { //  legacy intreface
  if(!params) throw new Error("You must supply params to urb.unsubscribe.")
  return window.urb.drop(params.path, params, cb)
}

window.urb.util = {
  isURL: function(s) {
     r = new RegExp('^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$', 'i');
     return s.length < 2083 && r.test(s);
  },
  numDot: function(n) {
    _n = String(n)
    fun = function(s){
      if(s.length <= 3)
        return s
      return fun(s.slice(0,-3))+"."+s.slice(-3)
    }
    return fun((_n))
  },
  toDate: function (dat){
    var mils = Math.floor((0x10000 * dat.getUTCMilliseconds()) / 1000).toString(16)
    function pad(num, str){
      return ((new Array(num + 1)).join('0') + str).substr(-num,num)
    }
    return  '~' + dat.getUTCFullYear() +
            '.' + (dat.getUTCMonth() + 1) +
            '.' + dat.getUTCDate() +
           '..' + pad(2, dat.getUTCHours()) +
            '.' + pad(2, dat.getUTCMinutes()) +
            '.' + pad(2, dat.getUTCSeconds()) +
           '..' + pad(4, mils)
  },
  basepath: function(spur, pathname){
    spur = spur || ''
    if(spur === '/') spur = ''
    pathname = pathname || window.location.pathname

    base = ""

    if(pathname.indexOf("/~~") == 0)
      base = "/~~"
    if(pathname.indexOf("/~/as/") == 0)
      base = "/~/as/"+pathname.split("/")[3]
    if(pathname.indexOf("/~/away") == 0)
      base = "/~/away"

    return base+spur
  }
}
<|endoftext|>


<commit_before>import async from 'async';
import Field from '../Field';
import React from 'react';
import Select from 'react-select';
import xhr from 'xhr';
import { Button, FormInput } from 'elemental';

function compareValues(current, next) {
	let currentLength = current ? current.length : 0
	let nextLength = next ? next.length : 0
	if (currentLength !== nextLength) return false;
	for (let i = 0; i < currentLength; i++) {
		if (current[i] !== next[i]) return false;
	}
	return true;
}

module.exports = Field.create({

	displayName: 'RelationshipField',

	getInitialState () {
		return {
			value: null,
		};
	},

	componentDidMount () {
		this._itemsCache = {};
		this.loadValue(this.props.value);
	},

	componentWillReceiveProps (nextProps) {
		if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return;
		this.loadValue(nextProps.value);
	},

	shouldCollapse () {
		if (this.props.many) {
			// many:true relationships have an Array for a value
			return this.props.collapse && !this.props.value.length;
		}
		return this.props.collapse && !this.props.value;
	},

	buildFilters () {
		var filters = {};

		_.each(this.props.filters, function(value, key) {
			if(_.isString(value) && value[0] == ':') {//eslint-disable-line eqeqeq
				var fieldName = value.slice(1);

				var val = this.props.values[fieldName];
				if (val) {
					filters[key] = val;
					return;
				}

				// check if filtering by id and item was already saved
				if (fieldName === ':_id' && Keystone.item) {
					filters[key] = Keystone.item.id;
					return;
				}
			} else {
				filters[key] = value;
			}
		}, this);

		var parts = [];

		_.each(filters, function (val, key) {
			parts.push('filters[' + key + '][value]=' + encodeURIComponent(val));
		});

		return parts.join('&');
	},

	cacheItem (item) {
		item.href = Keystone.adminPath + '/' + this.props.refList.path + '/' + item.id;
		this._itemsCache[item.id] = item;
	},

	loadValue (values) {
		if (!values) {
			return this.setState({
				loading: false,
				value: null,
			});
		};
		values = Array.isArray(values) ? values : values.split(',');
		let cachedValues = values.map(i => this._itemsCache[i]).filter(i => i);
		if (cachedValues.length === values.length) {
			this.setState({
				loading: false,
				value: this.props.many ? cachedValues : cachedValues[0],
			});
			return;
		}
		this.setState({
			loading: true,
			value: null,
		});
		async.map(values, (value, done) => {
			xhr({
				url: Keystone.adminPath + '/api/' + this.props.refList.path + '/' + value + '?basic',
				responseType: 'json',
			}, (err, resp, data) => {
				if (err || !data) return done(err);
				this.cacheItem(data);
				done(err, data);
			});
		}, (err, expanded) => {
			if (!this.isMounted()) return;
			this.setState({
				loading: false,
				value: this.props.many ? expanded : expanded[0],
			});
		});
	},

	loadOptions (input, callback) {
		let filters = this.buildFilters();
		xhr({
			url: Keystone.adminPath + '/api/' + this.props.refList.path + '?basic&search=' + input + '&' + filters,
			responseType: 'json',
		}, (err, resp, data) => {
			if (err) {
				console.error('Error loading items:', err);
				return callback(null, []);
			}
			data.results.forEach(this.cacheItem);
			callback(null, {
				options: data.results,
				complete: data.results.length === data.count,
			});
		});
	},

	valueChanged (value) {
		this.props.onChange({
			path: this.props.path,
			value: value,
		});
	},

	renderSelect (noedit) {
		return (
			<Select.Async
				multi={this.props.many}
				disabled={noedit}
				loadOptions={this.loadOptions}
				labelKey="name"
				name={this.props.path}
				onChange={this.valueChanged}
				simpleValue
				value={this.state.value}
				valueKey="id"
			/>
		);
	},

	renderValue () {
		return this.renderSelect(true);
	},

	renderField () {
		return this.renderSelect();
	}

});
<commit_msg>Fixing linter issues with #2094<commit_after>import async from 'async';
import Field from '../Field';
import React from 'react';
import Select from 'react-select';
import xhr from 'xhr';
import { Button, FormInput } from 'elemental';

function compareValues(current, next) {
	let currentLength = current ? current.length : 0;
	let nextLength = next ? next.length : 0;
	if (currentLength !== nextLength) return false;
	for (let i = 0; i < currentLength; i++) {
		if (current[i] !== next[i]) return false;
	}
	return true;
}

module.exports = Field.create({

	displayName: 'RelationshipField',

	getInitialState () {
		return {
			value: null,
		};
	},

	componentDidMount () {
		this._itemsCache = {};
		this.loadValue(this.props.value);
	},

	componentWillReceiveProps (nextProps) {
		if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return;
		this.loadValue(nextProps.value);
	},

	shouldCollapse () {
		if (this.props.many) {
			// many:true relationships have an Array for a value
			return this.props.collapse && !this.props.value.length;
		}
		return this.props.collapse && !this.props.value;
	},

	buildFilters () {
		var filters = {};

		_.each(this.props.filters, function(value, key) {
			if(_.isString(value) && value[0] == ':') {//eslint-disable-line eqeqeq
				var fieldName = value.slice(1);

				var val = this.props.values[fieldName];
				if (val) {
					filters[key] = val;
					return;
				}

				// check if filtering by id and item was already saved
				if (fieldName === ':_id' && Keystone.item) {
					filters[key] = Keystone.item.id;
					return;
				}
			} else {
				filters[key] = value;
			}
		}, this);

		var parts = [];

		_.each(filters, function (val, key) {
			parts.push('filters[' + key + '][value]=' + encodeURIComponent(val));
		});

		return parts.join('&');
	},

	cacheItem (item) {
		item.href = Keystone.adminPath + '/' + this.props.refList.path + '/' + item.id;
		this._itemsCache[item.id] = item;
	},

	loadValue (values) {
		if (!values) {
			return this.setState({
				loading: false,
				value: null,
			});
		};
		values = Array.isArray(values) ? values : values.split(',');
		let cachedValues = values.map(i => this._itemsCache[i]).filter(i => i);
		if (cachedValues.length === values.length) {
			this.setState({
				loading: false,
				value: this.props.many ? cachedValues : cachedValues[0],
			});
			return;
		}
		this.setState({
			loading: true,
			value: null,
		});
		async.map(values, (value, done) => {
			xhr({
				url: Keystone.adminPath + '/api/' + this.props.refList.path + '/' + value + '?basic',
				responseType: 'json',
			}, (err, resp, data) => {
				if (err || !data) return done(err);
				this.cacheItem(data);
				done(err, data);
			});
		}, (err, expanded) => {
			if (!this.isMounted()) return;
			this.setState({
				loading: false,
				value: this.props.many ? expanded : expanded[0],
			});
		});
	},

	loadOptions (input, callback) {
		let filters = this.buildFilters();
		xhr({
			url: Keystone.adminPath + '/api/' + this.props.refList.path + '?basic&search=' + input + '&' + filters,
			responseType: 'json',
		}, (err, resp, data) => {
			if (err) {
				console.error('Error loading items:', err);
				return callback(null, []);
			}
			data.results.forEach(this.cacheItem);
			callback(null, {
				options: data.results,
				complete: data.results.length === data.count,
			});
		});
	},

	valueChanged (value) {
		this.props.onChange({
			path: this.props.path,
			value: value,
		});
	},

	renderSelect (noedit) {
		return (
			<Select.Async
				multi={this.props.many}
				disabled={noedit}
				loadOptions={this.loadOptions}
				labelKey="name"
				name={this.props.path}
				onChange={this.valueChanged}
				simpleValue
				value={this.state.value}
				valueKey="id"
			/>
		);
	},

	renderValue () {
		return this.renderSelect(true);
	},

	renderField () {
		return this.renderSelect();
	}

});
<|endoftext|>


<commit_before>var select = require('../lib/xpath.js').SelectNodes
  , dom = require('xmldom').DOMParser
  , SignedXml = require('../lib/signed-xml.js').SignedXml
  , fs = require('fs')

module.exports = {

  "verify signature": function (test) {
  	var xml = "<root><x xmlns=\"ns\"></x><y z_attr=\"value\" a_attr1=\"foo\"></y><z><ns:w ns:attr=\"value\" xmlns:ns=\"myns\"></ns:w></z></root>"
    verifySignature(test, xml, [
      "//*[local-name(.)='x']",
      "//*[local-name(.)='y']",
      "//*[local-name(.)='w']"])
  },

  "verify signature of complex element": function (test) {
    var xml = "<library>" +
                "<book>" +
                  "<name>Harry Potter</name>" +
                  "<author id=\"123456789\">" +
                    "<firstName>Joanne K</firstName>" +
                    "<lastName>Rowling</lastName>" +
                  "</author>" +
                "</book>"
              "</library>"

    verifySignature(test, xml, ["//*[local-name(.)='book']"])
  }

}

function verifySignature(test, xml, xpath) {
  var sig = new SignedXml()
  sig.signingKey = fs.readFileSync("./test/static/client.pem")
  sig.keyInfoCaluse = null

  xpath.map(function(n) { sig.addReference(n) })

  sig.computeSignature(xml)
  var signed = sig.getSignedXml()

  fs.writeFileSync("./test/validators/XmlCryptoUtilities/XmlCryptoUtilities/bin/Debug/signedExample.xml", signed)

  var spawn = require('child_process').spawn
  var proc = spawn('./test/validators/XmlCryptoUtilities/XmlCryptoUtilities/bin/Debug/XmlCryptoUtilities.exe', ['verify'])

  proc.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
  });

  proc.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
  });

  proc.on('exit', function (code) {
    test.equal(0, code, "signature validation failed")
    test.done()
  });

}<commit_msg>Skip Windows-specific test if not on Win32<commit_after>var select = require('../lib/xpath.js').SelectNodes
  , dom = require('xmldom').DOMParser
  , SignedXml = require('../lib/signed-xml.js').SignedXml
  , fs = require('fs')

module.exports = {

  "verify signature": function (test) {
  	var xml = "<root><x xmlns=\"ns\"></x><y z_attr=\"value\" a_attr1=\"foo\"></y><z><ns:w ns:attr=\"value\" xmlns:ns=\"myns\"></ns:w></z></root>"
    verifySignature(test, xml, [
      "//*[local-name(.)='x']",
      "//*[local-name(.)='y']",
      "//*[local-name(.)='w']"])
  },

  "verify signature of complex element": function (test) {
    var xml = "<library>" +
                "<book>" +
                  "<name>Harry Potter</name>" +
                  "<author id=\"123456789\">" +
                    "<firstName>Joanne K</firstName>" +
                    "<lastName>Rowling</lastName>" +
                  "</author>" +
                "</book>"
              "</library>"

    verifySignature(test, xml, ["//*[local-name(.)='book']"])
  }

}

function verifySignature(test, xml, xpath) {
  if (process.platform !== 'win32') {
    test.done();
    return;
  }
  var sig = new SignedXml()
  sig.signingKey = fs.readFileSync("./test/static/client.pem")
  sig.keyInfoCaluse = null

  xpath.map(function(n) { sig.addReference(n) })

  sig.computeSignature(xml)
  var signed = sig.getSignedXml()

  fs.writeFileSync("./test/validators/XmlCryptoUtilities/XmlCryptoUtilities/bin/Debug/signedExample.xml", signed)

  var spawn = require('child_process').spawn
  var proc = spawn('./test/validators/XmlCryptoUtilities/XmlCryptoUtilities/bin/Debug/XmlCryptoUtilities.exe', ['verify'])

  proc.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
  });

  proc.stderr.on('data', function (data) {
    console.log('stderr: ' + data);
  });

  proc.on('exit', function (code) {
    test.equal(0, code, "signature validation failed")
    test.done()
  });

}
<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    _ = require('lodash'),
    base = require('./baseContentModel');

var properties = _.extend({
    name: String,
    attribution: String,
    caption: String,
    encoding: String,
    mimetype: String,
    extension: String,
    size: String,
    truncated: Boolean,
    file: Buffer
}, base.properties);

var MediaSchema = new Schema(properties);

var MediaSchema = new Schema(properties, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

MediaSchema.pre('save', function(next) {
    base.preSave(this);
    next();
});

MediaSchema.virtual('permissions')
    .set(function(permissions) {
        this._permissions = permissions;
    })
    .get(function() {
        return this._permissions;
    });

MediaSchema.statics = base.permissions;

MediaSchema.statics.fieldPermissions = function(){
    return base.fieldPermissions(this);
};

MediaSchema.statics.permissionsGrantedOnCreation = function(){
    return base.permissionsGrantedOnCreation(this);
};

MediaSchema.statics.permissionsGrantedOnUserCreation = function(){
    return base.permissionsGrantedOnUserCreation(this);
};

mongoose.model('Media', MediaSchema);
<commit_msg>Media Model specifies permissions to grant to anonymous users<commit_after>'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    _ = require('lodash'),
    base = require('./baseContentModel');

var properties = _.extend({
    name: String,
    attribution: String,
    caption: String,
    encoding: String,
    mimetype: String,
    extension: String,
    size: String,
    truncated: Boolean,
    file: Buffer
}, base.properties);

var MediaSchema = new Schema(properties);

var MediaSchema = new Schema(properties, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

MediaSchema.pre('save', function(next) {
    base.preSave(this);
    next();
});

MediaSchema.virtual('permissions')
    .set(function(permissions) {
        this._permissions = permissions;
    })
    .get(function() {
        return this._permissions;
    });

MediaSchema.statics = base.permissions;

MediaSchema.statics.fieldPermissions = function(){
    return base.fieldPermissions(this);
};

MediaSchema.statics.permissionsGrantedOnCreation = function(){
    return base.permissionsGrantedOnCreation(this);
};

MediaSchema.statics.permissionsGrantedOnUserCreation = function(){
    return base.permissionsGrantedOnUserCreation(this);
};

MediaSchema.statics.permissionsGrantedToAnon = function(){
    var fieldPermissions = this.fieldPermissions();
    var readPermission = this.readPermission();

    return [
        readPermission,
        fieldPermissions['name'][readPermission],
        fieldPermissions['attribution'][readPermission],
        fieldPermissions['caption'][readPermission],

    ];
};

mongoose.model('Media', MediaSchema);
<|endoftext|>


<commit_before>"use strict";

describe("Case #2: abTable with <eviratec/schema/v1/product/price> schema", function () {

  const SCHEMA_URL = "/base/test/spec/productPriceTable/data/schema.json";
  const MODELS_URL = "/base/test/spec/productPriceTable/data/models.json";

  let JsonSchema;
  let $compile;
  let $rootScope;

  let table;

  beforeEach(module('AppBuilder3'));

  beforeEach(inject(function (_JsonSchema_, _$compile_, _$rootScope_) {

    JsonSchema = _JsonSchema_;
    $compile = _$compile_;
    $rootScope = _$rootScope_;

    table = newTable();

  }));

  describe("Table Header", function () {

    let schema;
    let models;

    beforeEach(function (done) {
      readJSON(SCHEMA_URL, function (err, res) {
        schema = new JsonSchema(res);
        readJSON(MODELS_URL, function (err, res) {
          models = res;
          done();
        });
      });
    });

    it("Adds the appropriate column header cells", function () {

      var element;
      var $scope = $rootScope.$new(true);

      $scope.table = table;
      $scope.schema = schema;
      $scope.models = models;

      element = $compile("

")($scope);

      $scope.$digest();

      expect(element.html()).toContain("table-header");
      expect(element.html()).toContain("Type");
      expect(element.html()).toContain("$ Price");
      expect(element.html()).toContain("Currency");
      expect(element.html()).toContain("Valid From");
      expect(element.html()).toContain("Valid Thru");
      expect(element.html()).toContain("Public");

    });

  });

  describe("Table Data", function () {

    let schema;
    let models;

    beforeEach(function (done) {
      readJSON(SCHEMA_URL, function (err, res) {
        schema = new JsonSchema(res);
        readJSON(MODELS_URL, function (err, res) {
          models = res;
          done();
        });
      });
    });

    it("Adds the appropriate content", function () {

      var element;
      var $scope = $rootScope.$new(true);

      $scope.table = table;
      $scope.schema = schema;
      $scope.models = models;

      element = $compile("

")($scope);

      $scope.$digest();

      expect(element.html()).toContain("2017-01-01");

    });

  });

});
<commit_msg>(test):Expected cell count for abTable directive<commit_after>"use strict";

describe("Case #2: abTable with <eviratec/schema/v1/product/price> schema", function () {

  const SCHEMA_URL = "/base/test/spec/productPriceTable/data/schema.json";
  const MODELS_URL = "/base/test/spec/productPriceTable/data/models.json";

  let JsonSchema;
  let $compile;
  let $rootScope;

  let table;

  beforeEach(module('AppBuilder3'));

  beforeEach(inject(function (_JsonSchema_, _$compile_, _$rootScope_) {

    JsonSchema = _JsonSchema_;
    $compile = _$compile_;
    $rootScope = _$rootScope_;

    table = newTable();

  }));

  describe("Table Header", function () {

    let schema;
    let models;

    beforeEach(function (done) {
      readJSON(SCHEMA_URL, function (err, res) {
        schema = new JsonSchema(res);
        readJSON(MODELS_URL, function (err, res) {
          models = res;
          done();
        });
      });
    });

    it("Adds the appropriate column header cells", function () {

      var element;
      var $scope = $rootScope.$new(true);

      $scope.table = table;
      $scope.schema = schema;
      $scope.models = models;

      element = $compile("

")($scope);

      $scope.$digest();

      expect(element.html()).toContain("table-header");
      expect(element.html()).toContain("Type");
      expect(element.html()).toContain("$ Price");
      expect(element.html()).toContain("Currency");
      expect(element.html()).toContain("Valid From");
      expect(element.html()).toContain("Valid Thru");
      expect(element.html()).toContain("Public");

    });

  });

  describe("Table Data", function () {

    let schema;
    let models;

    beforeEach(function (done) {
      readJSON(SCHEMA_URL, function (err, res) {
        schema = new JsonSchema(res);
        readJSON(MODELS_URL, function (err, res) {
          models = res;
          done();
        });
      });
    });

    it("Adds the appropriate content", function () {

      var element;
      var $scope = $rootScope.$new(true);

      $scope.table = table;
      $scope.schema = schema;
      $scope.models = models;

      element = $compile("

")($scope);

      $scope.$digest();

      expect(element.html()).toContain(">PROMO<");
      expect(element.html()).toContain(">LIST<");
      expect(element.html()).toContain(">PURCH<");
      expect(element.html()).toContain(">120<");
      expect(element.html()).toContain(">61<");
      expect(element.html()).toContain(">149<");
      expect(element.html()).toContain(">AUD<");
      expect(element.html()).toContain(">2016-01-01<");
      expect(element.html()).toContain(">2017-01-01<");
      expect(element.html()).toContain(">2017-07-01<");
      expect(element.html()).toContain(">true<");

    });

    it("Adds the correct number of cells", function () {

      let element;
      let $scope = $rootScope.$new(true);

      $scope.table = table;
      $scope.schema = schema;
      $scope.models = models;

      element = $compile("

")($scope);

      $scope.$digest();

      let cellCount = element.html().match(/\<ab\-table\-cell /g).length;

      expect(cellCount).toBe(30);

    });

  });

});
<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    _ = require('lodash'),
    base = require('./baseContentModel');

var properties = _.extend({
    name: String,
    attribution: String,
    caption: String,
    encoding: String,
    mimetype: String,
    extension: String,
    size: String,
    truncated: Boolean,
    file: Buffer
}, base.properties);

var MediaSchema = new Schema(properties);

var MediaSchema = new Schema(properties, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

MediaSchema.pre('save', function(next) {
    base.preSave(this);
    next();
});

MediaSchema.virtual('permissions')
    .set(function(permissions) {
        this._permissions = permissions;
    })
    .get(function() {
        return this._permissions;
    });

MediaSchema.statics = base.permissions;

MediaSchema.statics.fieldPermissions = function(){
    return base.fieldPermissions(this);
};

MediaSchema.statics.permissionsGrantedOnCreation = function(){
    return base.permissionsGrantedOnCreation(this);
};

MediaSchema.statics.permissionsGrantedOnUserCreation = function(){
    return base.permissionsGrantedOnUserCreation(this);
};

MediaSchema.statics.permissionsGrantedToAnon = function(){
    var fieldPermissions = this.fieldPermissions();
    var readPermission = this.readPermission();

    //TODO: base permissionsGrantedToAnon which returns slug
    return [
        readPermission,
        fieldPermissions['name'][readPermission],
        fieldPermissions['attribution'][readPermission],
        fieldPermissions['caption'][readPermission],
    ];
};

mongoose.model('Media', MediaSchema);
<commit_msg>Media instances now have a transient "url" property which is a shortcut to render the media<commit_after>'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    _ = require('lodash'),
    base = require('./baseContentModel');

var properties = _.extend({
    name: String,
    attribution: String,
    caption: String,
    encoding: String,
    mimetype: String,
    extension: String,
    size: String,
    truncated: Boolean,
    file: Buffer
}, base.properties);

var MediaSchema = new Schema(properties);

var MediaSchema = new Schema(properties, {
    toObject: { virtuals: true },
    toJSON: { virtuals: true }
});

MediaSchema.pre('save', function(next) {
    base.preSave(this);
    next();
});

MediaSchema.virtual('permissions')
    .set(function(permissions) {
        this._permissions = permissions;
    })
    .get(function() {
        return this._permissions;
    });

MediaSchema.virtual('url')
    .get(function(){
        // TODO: dont hardcode api url
        return '/api/v1/media/' + this.id;
    });

MediaSchema.statics = base.permissions;

MediaSchema.statics.fieldPermissions = function(){
    return base.fieldPermissions(this);
};

MediaSchema.statics.permissionsGrantedOnCreation = function(){
    return base.permissionsGrantedOnCreation(this);
};

MediaSchema.statics.permissionsGrantedOnUserCreation = function(){
    return base.permissionsGrantedOnUserCreation(this);
};

MediaSchema.statics.permissionsGrantedToAnon = function(){
    var fieldPermissions = this.fieldPermissions();
    var readPermission = this.readPermission();

    //TODO: base permissionsGrantedToAnon which returns slug
    return [
        readPermission,
        fieldPermissions['name'][readPermission],
        fieldPermissions['attribution'][readPermission],
        fieldPermissions['caption'][readPermission],
    ];
};

mongoose.model('Media', MediaSchema);
<|endoftext|>