<commit_before>define([
    'require',
    'jquery',
    'base/js/namespace',
    'base/js/dialog',
    'notebook/js/celltoolbar',
    'base/js/events',
], function (require,
             $,
             Jupyter,
             dialog,
             notebook_celltoolbar,
             events)
       {

    var preset_name = 'Cell Testing';

    var CellToolbar = notebook_celltoolbar.CellToolbar;

    var prepare_data = function(cell) {
        if (cell.nbcelltesting_data === undefined) {
            cell.nbcelltesting_data = {};
        }
        if (cell.nbcelltesting_data.pending === undefined) {
            cell.nbcelltesting_data.pending = false;
        }
    };

    events.on('execute.CodeCell', function(event, data) {
        cell = data.cell;
        prepare_data(cell);
        cell.nbcelltesting_data.pending = true;
        delete cell.nbcelltesting_data.result_test;
        cell.celltoolbar.rebuild();
        update_global_result();
    });

    events.on('finished_execute.CodeCell', function(event, data) {
        cell = data.cell;
        prepare_data(cell);
        cell.nbcelltesting_data.pending = false;
        test_output(cell);
        cell.celltoolbar.rebuild();
        update_global_result();
    });

    var prepare_metadata = function(cell) {
        if (cell.metadata.nbcelltesting === undefined) {
            cell.metadata.nbcelltesting = {};
        }
    };

    var cleanup_metadata = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            Object.keys(cell.metadata.nbcelltesting).length === 0) {
            delete cell.metadata.nbcelltesting
        }
    };

    var cell_output = function(cell) {
        pre = cell.output_area.element.find('div.output_subarea').last().find('pre');
        return pre.text();
    };

    var save_desired_output = function(cell) {
        prepare_metadata(cell);
        cell.metadata.nbcelltesting.desired_output = cell_output(cell);
    };

    var desired_output = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            cell.metadata.nbcelltesting.desired_output !== undefined) {
            return cell.metadata.nbcelltesting.desired_output;
        }
        return null;
    };

    var reset_desired_output = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            cell.metadata.nbcelltesting.hasOwnProperty("desired_output")) {
            delete cell.metadata.nbcelltesting.desired_output;
            cleanup_metadata(cell);
        }
    };

    var edit_nbcelltesting_metadata = function(cell, celltoolbar=null) {
        if (cell.metadata.nbcelltesting === undefined) {
            metadata = {};
        } else {
            metadata = cell.metadata.nbcelltesting;
        }

        notebook = Jupyter.notebook
        dialog.edit_metadata({
            md: metadata,
            callback: function (md) {
                prepare_metadata(cell);
                cell.metadata.nbcelltesting = md;
                test_output(cell);
                if (celltoolbar !== null) {
                    celltoolbar.rebuild();
                }
            },
            name: 'Cell Testing',
            notebook: notebook,
            keyboard_manager: notebook.keyboard_manager});
    };

    var compare_output = function(cell) {
        dout = desired_output(cell);
        if (dout === null) {
            return null;
        }
        cout = cell_output(cell);
        return cout === dout;
    };

    var status = {'pending': {'text': '',
                              'style': 'info',
                              'cls': 'label-info',
                              'count': 0},
                  'not_available': {'text': 'no output saved',
                                    'style': 'info',
                                    'cls': 'label-info',
                                    'count': 0},
                  'failed': {'text': 'wrong output',
                             'style': 'danger',
                             'cls': 'label-danger',
                             'count': 0},
                  'passed': {'text': 'correct output',
                             'style': 'success',
                             'cls': 'label-success',
                             'count': 0},
                 };

    var test_output = function(cell) {
        prepare_data(cell);
        var result;
        var cls;
        if (cell.nbcelltesting_data.pending === true) {
            result = 'pending';
        } else {
            comparison_result = compare_output(cell);
            if (comparison_result === null) {
                result = 'not_available';
            } else if (comparison_result === false) {
                result = 'failed';
            } else if (comparison_result === true) {
                result = 'passed';
            }
        }

        if (cell.nbcelltesting_data.result_test !== undefined) {
            if (cell.nbcelltesting_data.result_test != result) {
                status[cell.nbcelltesting_data.result_test].count--;
                cell.nbcelltesting_data.result_test = result;
                status[result].count++;
            }
        } else {
            cell.nbcelltesting_data.result_test = result;
            status[result].count++;
        }
    };

    var result_test = function(cell) {
        if (cell.nbcelltesting_data === undefined ||
            cell.nbcelltesting_data.result_test === undefined) {
            test_output(cell);
        }
        return cell.nbcelltesting_data.result_test;
    };

    var create_result_test = function(div, cell, celltoolbar) {
        var cell_status = result_test(cell);

        var result = status[cell_status].text;
        var cls = status[cell_status].cls;

        var element = $('').addClass('label result-label').addClass(cls);
        element.append(result);
        element.on('click', function() { on_test_output(cell, celltoolbar); });

        $(div).addClass('ctb-thing result-test')
            .append(element);
    };

    var create_button = function(name, value, callback) {
        return function(div, cell, celltoolbar) {
            var button = $('<button/>').addClass('btn btn-default btn-xs')
                .addClass('button-' + name)
                .prop('type', 'button')
                .html(value);
            button.name = name;
            button.on('click', function() { callback(cell, celltoolbar) });
            $(div).addClass('ctb-thing').append(button);
        };
    };

    var on_save_desired_output = function(cell, celltoolbar) {
        save_desired_output(cell);
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var create_button_save = create_button('save', 'Save Output',
                                           on_save_desired_output);

    var on_reset_desired_output = function(cell, celltoolbar) {
        reset_desired_output(cell);
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var on_edit_nbcelltesting_metadata = edit_nbcelltesting_metadata;

    var on_test_output = function(cell, celltoolbar) {
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var actions = [{name: 'Reset Output', callback: on_reset_desired_output},
                   {name: 'Edit Output', callback: on_edit_nbcelltesting_metadata},
                   {name: 'Test Output', callback: on_test_output}];

    var action_callback = function(action, cell, celltoolbar) {
	return function() { action.callback(cell, celltoolbar); }
    }

    var dropdown_factory = function(div, cell, celltoolbar) {
        var dropdownButton = $('<button/>').addClass('btn btn-default btn-xs dropdown-toggle')
            .prop('type', 'button').attr('data-toggle', 'dropdown')
            .html('');

        var options = $('
').addClass('dropdown-menu');

        for (var action of actions) {
            var action_link = $('').prop('href', '#').html(action.name);
            action_link.on('click', action_callback(action, cell, celltoolbar));
            options.append($('
').append(action_link));
        }

        $(div).addClass('ctb-thing dropdown').append(dropdownButton).append(options);
    };

    var global_status = ['passed', 'pending', 'failed', 'not_available'];

    var update_global_result = function() {
        var n = 0;
        for (var s of global_status) {
            n += status[s].count;
        }
        for (var s of global_status) {
            $('#nbcelltesting-global-result-' + s)
                .attr('style', 'width: ' + status[s].count / n * 100 + '%');
        }
    };

    events.on('preset_activated.CellToolbar', function(event, preset) {
        var element = $('#nbcelltesting-global-result');
        if (preset.name === preset_name) {
            if (element.length == 0) {
                var progress = $('
')
                    .attr('id', 'nbcelltesting-global-result')
                    .addClass('progress')
                for (var s of global_status) {
                    progress.append(
                        $('
')
                            .attr('id', 'nbcelltesting-global-result-' + s)
                            .addClass('progress-bar progress-bar-' + status[s].style)
                            .attr('role', 'progressbar'));
                }
                $("#maintoolbar-container").append(progress);
            }
            update_global_result();
            element = progress;
            element.show();
        } else {
            element.hide();
        }
    });

    var load_css = function () {
        var link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.href = require.toUrl('./nbcelltesting.css');
        document.getElementsByTagName('head')[0].appendChild(link);
    };

    function load_extension(){
        load_css();

        CellToolbar.register_callback('nbcelltesting.result_test',
                                      create_result_test,
                                      ['code']);
        CellToolbar.register_callback('nbcelltesting.button_save',
                                      create_button_save,
                                      ['code']);
        CellToolbar.register_callback('nbcelltesting.dropdown_menu',
                                      dropdown_factory,
                                      ['code']);

         var preset = [
            'nbcelltesting.result_test',
            'nbcelltesting.button_save',
            'nbcelltesting.dropdown_menu',
        ];
        CellToolbar.register_preset(preset_name, preset, Jupyter.notebook);
        console.log('nbcelltesting extension loaded.');
    }

    return {
        load_ipython_extension: load_extension
    };
});
<commit_msg>dialog for editing output<commit_after>define([
    'require',
    'jquery',
    'base/js/namespace',
    'base/js/dialog',
    'notebook/js/celltoolbar',
    'base/js/events',
], function (require,
             $,
             Jupyter,
             dialog,
             notebook_celltoolbar,
             events) {

    var preset_name = 'Cell Testing';

    var CellToolbar = notebook_celltoolbar.CellToolbar;

    var prepare_data = function(cell) {
        if (cell.nbcelltesting_data === undefined) {
            cell.nbcelltesting_data = {};
        }
        if (cell.nbcelltesting_data.pending === undefined) {
            cell.nbcelltesting_data.pending = false;
        }
    };

    events.on('execute.CodeCell', function(event, data) {
        cell = data.cell;
        prepare_data(cell);
        cell.nbcelltesting_data.pending = true;
        delete cell.nbcelltesting_data.result_test;
        cell.celltoolbar.rebuild();
        update_global_result();
    });

    events.on('finished_execute.CodeCell', function(event, data) {
        cell = data.cell;
        prepare_data(cell);
        cell.nbcelltesting_data.pending = false;
        test_output(cell);
        cell.celltoolbar.rebuild();
        update_global_result();
    });

    var prepare_metadata = function(cell) {
        if (cell.metadata.nbcelltesting === undefined) {
            cell.metadata.nbcelltesting = {};
        }
    };

    var cleanup_metadata = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            Object.keys(cell.metadata.nbcelltesting).length === 0) {
            delete cell.metadata.nbcelltesting
        }
    };

    var cell_output = function(cell) {
        pre = cell.output_area.element.find('div.output_subarea').last().find('pre');
        return pre.text();
    };

    var _save_desired_output_ = function(cell, output) {
        prepare_metadata(cell);
        cell.metadata.nbcelltesting.desired_output = output;
    };

    var save_desired_output = function(cell) {
        return _save_desired_output_(cell, cell_output(cell));
    };

    var desired_output = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            cell.metadata.nbcelltesting.desired_output !== undefined) {
            return cell.metadata.nbcelltesting.desired_output;
        }
        return null;
    };

    var reset_desired_output = function(cell) {
        if (cell.metadata.nbcelltesting !== undefined &&
            cell.metadata.nbcelltesting.hasOwnProperty("desired_output")) {
            delete cell.metadata.nbcelltesting.desired_output;
            cleanup_metadata(cell);
        }
    };

    var edit_nbcelltesting_metadata = function(cell, celltoolbar=null) {
        if (cell.metadata.nbcelltesting === undefined) {
            metadata = {};
        } else {
            metadata = cell.metadata.nbcelltesting;
        }

        notebook = Jupyter.notebook
        dialog.edit_metadata({
            md: metadata,
            callback: function (md) {
                prepare_metadata(cell);
                cell.metadata.nbcelltesting = md;
                test_output(cell);
                if (celltoolbar !== null) {
                    celltoolbar.rebuild();
                }
            },
            name: 'Cell Testing',
            notebook: notebook,
            keyboard_manager: notebook.keyboard_manager});
    };

    var edit_desired_output = function(cell, celltoolbar=null) {
        var output = desired_output(cell);
        var notebook = Jupyter.notebook
        var error_div = $('
').css('color', 'red');
        var message = 'desired output';

        var textarea = $('<textarea/>')
            .attr('rows', '13')
            .attr('cols', '80')
            .attr('name', 'desired-output')
            .text(output);

        var dialogform = $('
').attr('title', 'Edit Desired Output')
            .append(
                $('<form/>').append(
                    $('<fieldset/>').append(
                        $('')
                        .attr('for','desired-output')
                        .text(message)
                        )
                        .append(error_div)
                        .append($('
'))
                        .append(textarea)
                    )
            );

        var editor = CodeMirror.fromTextArea(textarea[0], {
            lineNumbers: true,
            matchBrackets: true,
            indentUnit: 2,
            autoIndent: true,
            mode: 'text/plain',
        });

        var modal_obj = dialog.modal({
            title: 'Edit Desired Output',
            body: dialogform,
            buttons: {
                OK: { class : "btn-primary",
                    click: function() {
                        var new_output = editor.getValue();
                        _save_desired_output_(cell, new_output);
                    }
                },
                Cancel: {}
            },
            notebook: notebook,
            keyboard_manager: notebook.keyboard_manager,
        });

        modal_obj.on('shown.bs.modal', function(){ editor.refresh(); });
    };

    var compare_output = function(cell) {
        dout = desired_output(cell);
        if (dout === null) {
            return null;
        }
        cout = cell_output(cell);
        return cout === dout;
    };

    var status = {'pending': {'text': '',
                              'style': 'info',
                              'cls': 'label-info',
                              'count': 0},
                  'not_available': {'text': 'no output saved',
                                    'style': 'info',
                                    'cls': 'label-info',
                                    'count': 0},
                  'failed': {'text': 'wrong output',
                             'style': 'danger',
                             'cls': 'label-danger',
                             'count': 0},
                  'passed': {'text': 'correct output',
                             'style': 'success',
                             'cls': 'label-success',
                             'count': 0},
                 };

    var test_output = function(cell) {
        prepare_data(cell);
        var result;
        var cls;
        if (cell.nbcelltesting_data.pending === true) {
            result = 'pending';
        } else {
            comparison_result = compare_output(cell);
            if (comparison_result === null) {
                result = 'not_available';
            } else if (comparison_result === false) {
                result = 'failed';
            } else if (comparison_result === true) {
                result = 'passed';
            }
        }

        if (cell.nbcelltesting_data.result_test !== undefined) {
            if (cell.nbcelltesting_data.result_test != result) {
                status[cell.nbcelltesting_data.result_test].count--;
                cell.nbcelltesting_data.result_test = result;
                status[result].count++;
            }
        } else {
            cell.nbcelltesting_data.result_test = result;
            status[result].count++;
        }
    };

    var result_test = function(cell) {
        if (cell.nbcelltesting_data === undefined ||
            cell.nbcelltesting_data.result_test === undefined) {
            test_output(cell);
        }
        return cell.nbcelltesting_data.result_test;
    };

    var create_result_test = function(div, cell, celltoolbar) {
        var cell_status = result_test(cell);

        var result = status[cell_status].text;
        var cls = status[cell_status].cls;

        var element = $('').addClass('label result-label').addClass(cls);
        element.append(result);
        element.on('click', function() { on_test_output(cell, celltoolbar); });

        $(div).addClass('ctb-thing result-test')
            .append(element);
    };

    var create_button = function(name, value, callback) {
        return function(div, cell, celltoolbar) {
            var button = $('<button/>').addClass('btn btn-default btn-xs')
                .addClass('button-' + name)
                .prop('type', 'button')
                .html(value);
            button.name = name;
            button.on('click', function() { callback(cell, celltoolbar) });
            $(div).addClass('ctb-thing').append(button);
        };
    };

    var on_save_desired_output = function(cell, celltoolbar) {
        save_desired_output(cell);
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var create_button_save = create_button('save', 'Save Output',
                                           on_save_desired_output);

    var on_reset_desired_output = function(cell, celltoolbar) {
        reset_desired_output(cell);
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var on_edit_nbcelltesting_metadata = edit_nbcelltesting_metadata;

    var on_edit_desired_output = edit_desired_output;

    var on_test_output = function(cell, celltoolbar) {
        test_output(cell);
        celltoolbar.rebuild();
        update_global_result();
    };

    var actions = [{name: 'Reset Output', callback: on_reset_desired_output},
                   {name: 'Edit Output', callback: on_edit_desired_output},
                   {name: 'Edit Metadata', callback: on_edit_nbcelltesting_metadata},
                   {name: 'Test Output', callback: on_test_output}];

    var action_callback = function(action, cell, celltoolbar) {
	return function() { action.callback(cell, celltoolbar); }
    }

    var dropdown_factory = function(div, cell, celltoolbar) {
        var dropdownButton = $('<button/>').addClass('btn btn-default btn-xs dropdown-toggle')
            .prop('type', 'button').attr('data-toggle', 'dropdown')
            .html('');

        var options = $('
').addClass('dropdown-menu');

        for (var action of actions) {
            var action_link = $('').prop('href', '#').html(action.name);
            action_link.on('click', action_callback(action, cell, celltoolbar));
            options.append($('
').append(action_link));
        }

        $(div).addClass('ctb-thing dropdown').append(dropdownButton).append(options);
    };

    var global_status = ['passed', 'pending', 'failed', 'not_available'];

    var update_global_result = function() {
        var n = 0;
        for (var s of global_status) {
            n += status[s].count;
        }
        for (var s of global_status) {
            $('#nbcelltesting-global-result-' + s)
                .attr('style', 'width: ' + status[s].count / n * 100 + '%');
        }
    };

    events.on('preset_activated.CellToolbar', function(event, preset) {
        var element = $('#nbcelltesting-global-result');
        if (preset.name === preset_name) {
            if (element.length == 0) {
                var progress = $('
')
                    .attr('id', 'nbcelltesting-global-result')
                    .addClass('progress')
                for (var s of global_status) {
                    progress.append(
                        $('
')
                            .attr('id', 'nbcelltesting-global-result-' + s)
                            .addClass('progress-bar progress-bar-' + status[s].style)
                            .attr('role', 'progressbar'));
                }
                $("#maintoolbar-container").append(progress);
            }
            update_global_result();
            element = progress;
            element.show();
        } else {
            element.hide();
        }
    });

    var load_css = function () {
        var link = document.createElement('link');
        link.type = 'text/css';
        link.rel = 'stylesheet';
        link.href = require.toUrl('./nbcelltesting.css');
        document.getElementsByTagName('head')[0].appendChild(link);
    };

    function load_extension(){
        load_css();

        CellToolbar.register_callback('nbcelltesting.result_test',
                                      create_result_test,
                                      ['code']);
        CellToolbar.register_callback('nbcelltesting.button_save',
                                      create_button_save,
                                      ['code']);
        CellToolbar.register_callback('nbcelltesting.dropdown_menu',
                                      dropdown_factory,
                                      ['code']);

         var preset = [
            'nbcelltesting.result_test',
            'nbcelltesting.button_save',
            'nbcelltesting.dropdown_menu',
        ];
        CellToolbar.register_preset(preset_name, preset, Jupyter.notebook);
        console.log('nbcelltesting extension loaded.');
    }

    return {
        load_ipython_extension: load_extension
    };
});
<|endoftext|>


<commit_before>var exec = require('cordova/exec'),
    channel = require('cordova/channel'),
    utils = require('cordova/utils');

channel.createSticky('onCordovaXGPushReady');
channel.waitForInitialization('onCordovaXGPushReady');

function XGPush() {

    var me = this;

    this.channels = {
        'click': channel.create('click'),
        'message': channel.create('message'),
        'register': channel.create('register'),
        'unRegister': channel.create('unRegister'),
        'show': channel.create('show'),
        'deleteTag': channel.create('deleteTag'),
        'setTag': channel.create('setTag'),
    };

    this.on = function (type, func) {
        if (type in me.channels) {
            me.channels[type].subscribe(func);
        }
    };

    this.un = function (type, func) {
        if (type in this.channels) {
            me.channels[type].unsubscribe(func);
        }
    };

    this.registerPush = function (account, successCallback, errorCallback) {
        exec(successCallback, errorCallback, "XGPush", "registerPush", [account]);
    };

    this.unRegisterPush = function (successCallback, errorCallback) {
        exec(successCallback, errorCallback, "XGPush", "unRegisterPush", []);
    };

    this.setTag = function (tagName) {
        exec(null,null, "XGPush", "setTag", [tagName]);
    };

    this.deleteTag = function (tagName) {
        exec(null, null, "XGPush", "deleteTag", [tagName]);
    };

    this.addLocalNotification = function (type, title, content, successCallback, errorCallback) {
        exec(successCallback, errorCallback, "XGPush", "addLocalNotification", [type, title, content]);
    };

    this.enableDebug = function (debugMode, successCallback, errorCallback) {
        exec(successCallback, errorCallback, "XGPush", "enableDebug", [debugMode]);
    };

    this.getLaunchInfo = function (successCallback) {
        exec(successCallback, null, "XGPush", "getLaunchInfo", []);
    };

    this.getToken = function (successCallback) {
        exec(successCallback, null, "XGPush", "getToken", []);
    };

    this.setAccessInfo = function (accessId, accessKey, successCallback, errorCallback) {
        exec(successCallback, errorCallback, "XGPush", "setAccessInfo", [accessId, accessKey]);
    };

    channel.onCordovaReady.subscribe(function () {
        exec(
            function (event) {
                console.log("[XGPush] Event = " + event.type + ": ", event);
                if (event && (event.type in me.channels)) {
                    me.channels[event.type].fire(event);
                }
            },
            null, "XGPush", "addListener", []
            );

        me.registerPush(null, function (info) {
            console.log("[XGPush] RegisterPush: ", info);
            channel.onCordovaXGPushReady.fire();
        }, function (e) {
            console.log("[ERROR] RegisterPush: ", e);
            channel.onCordovaXGPushReady.fire();
        });
    });
}

module.exports = new XGPush();<commit_msg>添加 stopNification<commit_after>var exec = require('cordova/exec'),
    channel = require('cordova/channel'),
    utils = require('cordova/utils');

channel.createSticky('onCordovaXGPushReady');
channel.waitForInitialization('onCordovaXGPushReady');

function XGPush() {

    var me = this;

    this.channels = {
        'click': channel.create('click'),
        'message': channel.create('message'),
        'register': channel.create('register'),
        'unRegister': channel.create('unRegister'),
        'show': channel.create('show'),
        'deleteTag': channel.create('deleteTag'),
        'setTag': channel.create('setTag'),
    };

    this.on = function (type, func) {
        if (type in me.channels) {
            me.channels[type].subscribe(func);
        }
    };

    this.un = function (type, func) {
        if (type in this.channels) {
            me.channels[type].unsubscribe(func);
        }
    };

    this.registerPush = function (account, successCallback, errorCallback) {
        exec(successCallback, errorCallback, "XGPush", "registerPush", [account]);
    };

    this.unRegisterPush = function (successCallback, errorCallback) {
        exec(successCallback, errorCallback, "XGPush", "unRegisterPush", []);
    };

    this.setTag = function (tagName) {
        exec(null,null, "XGPush", "setTag", [tagName]);
    };

    this.deleteTag = function (tagName) {
        exec(null, null, "XGPush", "deleteTag", [tagName]);
    };

    this.addLocalNotification = function (type, title, content, successCallback, errorCallback) {
        exec(successCallback, errorCallback, "XGPush", "addLocalNotification", [type, title, content]);
    };

    this.enableDebug = function (debugMode, successCallback, errorCallback) {
        exec(successCallback, errorCallback, "XGPush", "enableDebug", [debugMode]);
    };

    this.getLaunchInfo = function (successCallback) {
        exec(successCallback, null, "XGPush", "getLaunchInfo", []);
    };

    this.getToken = function (successCallback) {
        exec(successCallback, null, "XGPush", "getToken", []);
    };

    this.setAccessInfo = function (accessId, accessKey, successCallback, errorCallback) {
        exec(successCallback, errorCallback, "XGPush", "setAccessInfo", [accessId, accessKey]);
    };

    this.stopNotification = function () {
        exec(null, null, "XGPush", "stopNotification", []);
    };

    channel.onCordovaReady.subscribe(function () {
        exec(
            function (event) {
                console.log("[XGPush] Event = " + event.type + ": ", event);
                if (event && (event.type in me.channels)) {
                    me.channels[event.type].fire(event);
                }
            },
            null, "XGPush", "addListener", []
            );

        me.registerPush(null, function (info) {
            console.log("[XGPush] RegisterPush: ", info);
            channel.onCordovaXGPushReady.fire();
        }, function (e) {
            console.log("[ERROR] RegisterPush: ", e);
            channel.onCordovaXGPushReady.fire();
        });
    });
}

module.exports = new XGPush();<|endoftext|>


<commit_before>const fs = require('fs');
const exts = '(.beard$)';
const traversy = require('traversy');
const normalize = require('path').normalize;

function hash(str) {
  let hash = 5381;
  let i = str.length;
  while (i) hash = (hash * 33) ^ str.charCodeAt(--i);
  return hash >>> 0;
}

const _cleanWhitespace = str => str.replace(/\s+/g, ' ').trim();
const _getDir = path => path.replace(/\/[^\/]+$/, '');

module.exports = function(opts = {}) {
  // have defaults that we merge the opts passed into with
  if (!opts.hasOwnProperty('cache')) opts.cache = true;
  if (!opts.hasOwnProperty('asset')) opts.asset = (path) => false;
  opts.templates = opts.templates || {};

  let fnCache = {};
  let pathMap = {};
  let iterator = 0;
  let tags = [
    'include', 'block', 'blockEnd',
    'asset', 'put', 'encode', 'comment',
    'if', 'exists', 'elseIf', 'else',
    'for', 'each', 'end'
  ];

  const Beard = function() {
    if (opts.root) {
      const regex = new RegExp(`(^${opts.root}|.beard$)`, 'g');
      traversy(opts.root, exts, (path) => {
        const key = path.replace(regex, '');
        const body = fs.readFileSync(path, 'utf8');
        opts.templates[key] = opts.cache ? _cleanWhitespace(body) : body;
        pathMap[key] = path;
      });
    }
  }

  Beard.prototype = {
    render: (path, data = {}) => {
      iterator = 0;
      return compiled(path, '/')({
        globals: {},
        locals: [data],
        path: null
      });
    }
  };

  function _resolvePath(path, parentPath) {
    return path.startsWith('/')
      ? path
      : normalize(`${_getDir(parentPath)}/${path}`);
  }

  function _asset(p, path) {
    const absolutePath = _resolvePath(p, path);
    return opts.asset(absolutePath) || absolutePath;
  }

  const exps = {
    extends:    (/\{{extends\s\'([^}}]+?)\'\}}/g),
    include:    (/^include\s\'([^\(]*?)\'(\s*,\s+([\s\S]+))?$/m),
    asset:      (/^asset\s+\'(.+)\'$/),
    put:        (/^put\s+(.+)$/),
    exists:     (/^exists\s+(.+)$/),
    block:      (/^block\s+(.[^}]*)/),
    blockEnd:   (/^endblock$/),
    encode:     (/^\:(.*)/),
    comment:    (/^\*.*\*$/),
    statement:  (/{{\s*([\S\s(?!}})]+?)\s*}}(?!\})/g),
    if:         (/^if\s+([^]*)$/),
    elseIf:     (/^else\s+if\s+([^]*)$/),
    else:       (/^else$/),
    for:        (/^for\s+([$A-Za-z_][0-9A-Za-z_]*)(?:\s*,\s*([$A-Za-z_][0-9A-Za-z_]*))?\s+in\s+(.*)$/),
    each:       (/^each\s+([$A-Za-z_][0-9A-Za-z_]*)(?:\s*,\s*([$A-Za-z_][0-9A-Za-z_]*))?\s+in\s(.*)$/),
    end:        (/^end$/)
  };

  const parse = {
    block:      (_, blockname) => `_blockName = "${blockname}"; _blockCapture = "";`,
    blockEnd:   () => 'eval(`var ${_blockName} = _blockCapture`); _context.globals[_blockName] = _blockCapture; _blockName = null;',
    asset:      (_, path) => `_capture(_asset("${path}", path));`,
    put:        (_, varname) => `_capture(typeof ${varname} !== "undefined" ? ${varname} : "");`,
    exists:     (_, varname) => `if (typeof ${varname} !== "undefined") {`,
    encode:     (_, statement) => `_encode(${statement});`,
    comment:    () => '',
    if:         (_, statement) => `if (${statement}) {`,
    elseIf:     (_, statement) => `} else if (${statement}) {`,
    else:       () => '} else {',
    end:        () => '}',
    include:    (_, includePath, __, data) => {
      data = data || '{}';
      return `
        _context.locals.push(Object.assign(_context.locals[_context.locals.length - 1], ${data}));
        _capture(compiled("${includePath}", path)(_context));
        _context.locals.pop();
      `;
    },
    for: (_, key, value, object) => {
      if (!value) key = (value = key, 'iterator' + iterator++);
      return `for (var ${key} in ${object}){ var ${value} = ${object}[${key}];`;
    },
    each: (_, iter, value, array) => {
      if (!value) iter = (value = iter, 'iterator' + iterator++);
      const length = 'length' + iterator++;
      return `for (var ${iter} = 0, ${length} = ${array}.length; ${iter} < ${length}; ${iter}++) { var ${value} = ${array}[${(iter)}];`;
    }
  };

  function parser(match, inner) {
    const prev = inner;
    const reducer = (inner, tag) => inner.replace(exps[tag], parse[tag]);
    inner = tags.reduce(reducer, inner);

    const middle = inner === prev && !/^:/.test(inner)
      ? `_capture(${inner});`
      : inner.replace(/\t|\n|\r|^:/, '');

    return `"); ${middle} _capture("`;
  }

  function compiled(path, parentPath) {
    const fullPath = _resolvePath(path, parentPath);
    if (opts.cache) {
      const str = opts.templates[fullPath];
      const key = hash(fullPath);
      if (!fnCache[key]) fnCache[key] = compile(str, fullPath);
      return fnCache[key];
    } else {
      const str = fs.readFileSync(pathMap[fullPath], 'utf8');
      return compile(str, fullPath);
    }
  }

  function compile(str, path) {
    let layout = '';

    str = str
      .replace(exps.extends, (_, path) => {
        layout = `
          _context.globals.view = _buffer;
          _buffer = compiled('${path}', path)(_context);
        `;
        return '';
      })
      .replace(new RegExp('\\\\', 'g'), '\\\\').replace(/"/g, '\\"')
      .replace(exps.statement, parser);

    const fn = `
      function _compiledFn(_context){
        var _buffer = '';
        var _blockName;
        var _blockCapture;

        function _capture(str) {
          if (_blockName) {
            _blockCapture += str;
          } else {
            _buffer += str;
          }
        }

        function _encode(str) {
          _capture(str
            .replace(/&(?!\\w+;)/g, '&')
            .replace(/\</g, '<')
            .replace(/\>/g, '>')
            .replace(/\"/g, '"')
            .replace(/\'/g, ''')
            .replace(/\\//g, '/'));
        }

        for (var prop in _context.globals) {
          if (_context.globals.hasOwnProperty(prop)) {
            eval('var ' + prop + ' = _context.globals[prop]');
          }
        }

        var _locals = _context.locals[_context.locals.length - 1];
        for (var prop in _locals) {
          if (_locals.hasOwnProperty(prop)) {
            eval('var ' + prop + ' = _locals[prop]');
          }
        }

        _capture("${str}");
        ${layout}
        return _buffer;
      }
    `.replace(/_capture\(""\);(\s+)?/g, '');

    try {
      eval(_cleanWhitespace(fn));
      return _compiledFn;
    } catch (e) {
      throw new Error(`Compilation error: ${fn}`);
    }
  }

  return new Beard();
};
<commit_msg>Use new Function instead of eval<commit_after>const fs = require('fs');
const exts = '(.beard$)';
const traversy = require('traversy');
const normalize = require('path').normalize;

function hash(str) {
  let hash = 5381;
  let i = str.length;
  while (i) hash = (hash * 33) ^ str.charCodeAt(--i);
  return hash >>> 0;
}

const cleanWhitespace = str => str.replace(/\s+/g, ' ').trim();
const getDir = path => path.replace(/\/[^\/]+$/, '');

module.exports = function(opts = {}) {
  // have defaults that we merge the opts passed into with
  if (!opts.hasOwnProperty('cache')) opts.cache = true;
  if (!opts.hasOwnProperty('asset')) opts.asset = (path) => false;
  opts.templates = opts.templates || {};

  let fnCache = {};
  let pathMap = {};
  let iterator = 0;
  let tags = [
    'include', 'block', 'blockEnd',
    'asset', 'put', 'encode', 'comment',
    'if', 'exists', 'elseIf', 'else',
    'for', 'each', 'end'
  ];

  const Beard = function() {
    if (opts.root) {
      const regex = new RegExp(`(^${opts.root}|.beard$)`, 'g');
      traversy(opts.root, exts, (path) => {
        const key = path.replace(regex, '');
        const body = fs.readFileSync(path, 'utf8');
        opts.templates[key] = opts.cache ? cleanWhitespace(body) : body;
        pathMap[key] = path;
      });
    }
  }

  Beard.prototype = {
    render: (path, data = {}) => {
      iterator = 0;
      return compiled(path, '/')({
        globals: {},
        locals: [data],
        path: null,
        compiled,
        asset
      });
    }
  };

  function resolvePath(path, parentPath) {
    return path.startsWith('/')
      ? path
      : normalize(`${getDir(parentPath)}/${path}`);
  }

  function asset(p, path) {
    const absolutePath = resolvePath(p, path);
    return opts.asset(absolutePath) || absolutePath;
  }

  const exps = {
    extends:    (/\{{extends\s\'([^}}]+?)\'\}}/g),
    include:    (/^include\s\'([^\(]*?)\'(\s*,\s+([\s\S]+))?$/m),
    asset:      (/^asset\s+\'(.+)\'$/),
    put:        (/^put\s+(.+)$/),
    exists:     (/^exists\s+(.+)$/),
    block:      (/^block\s+(.[^}]*)/),
    blockEnd:   (/^endblock$/),
    encode:     (/^\:(.*)/),
    comment:    (/^\*.*\*$/),
    statement:  (/{{\s*([\S\s(?!}})]+?)\s*}}(?!\})/g),
    if:         (/^if\s+([^]*)$/),
    elseIf:     (/^else\s+if\s+([^]*)$/),
    else:       (/^else$/),
    for:        (/^for\s+([$A-Za-z_][0-9A-Za-z_]*)(?:\s*,\s*([$A-Za-z_][0-9A-Za-z_]*))?\s+in\s+(.*)$/),
    each:       (/^each\s+([$A-Za-z_][0-9A-Za-z_]*)(?:\s*,\s*([$A-Za-z_][0-9A-Za-z_]*))?\s+in\s(.*)$/),
    end:        (/^end$/)
  };

  const parse = {
    block:      (_, blockname) => `_blockName = "${blockname}"; _blockCapture = "";`,
    blockEnd:   () => 'eval(`var ${_blockName} = _blockCapture`); _context.globals[_blockName] = _blockCapture; _blockName = null;',
    asset:      (_, path) => `_capture(_context.asset("${path}", _context.path));`,
    put:        (_, varname) => `_capture(typeof ${varname} !== "undefined" ? ${varname} : "");`,
    exists:     (_, varname) => `if (typeof ${varname} !== "undefined") {`,
    encode:     (_, statement) => `_encode(${statement});`,
    comment:    () => '',
    if:         (_, statement) => `if (${statement}) {`,
    elseIf:     (_, statement) => `} else if (${statement}) {`,
    else:       () => '} else {',
    end:        () => '}',
    include:    (_, includePath, __, data) => {
      data = data || '{}';
      return `
        _context.locals.push(Object.assign(_context.locals[_context.locals.length - 1], ${data}));
        _capture(_context.compiled("${includePath}", _context.path)(_context));
        _context.locals.pop();
      `;
    },
    for: (_, key, value, object) => {
      if (!value) key = (value = key, 'iterator' + iterator++);
      return `for (var ${key} in ${object}){ var ${value} = ${object}[${key}];`;
    },
    each: (_, iter, value, array) => {
      if (!value) iter = (value = iter, 'iterator' + iterator++);
      const length = 'length' + iterator++;
      return `for (var ${iter} = 0, ${length} = ${array}.length; ${iter} < ${length}; ${iter}++) { var ${value} = ${array}[${(iter)}];`;
    }
  };

  function parser(match, inner) {
    const prev = inner;
    const reducer = (inner, tag) => inner.replace(exps[tag], parse[tag]);
    inner = tags.reduce(reducer, inner);

    const middle = inner === prev && !/^:/.test(inner)
      ? `_capture(${inner});`
      : inner.replace(/\t|\n|\r|^:/, '');

    return `"); ${middle} _capture("`;
  }

  function compiled(path, parentPath) {
    const fullPath = resolvePath(path, parentPath);
    if (opts.cache) {
      const str = opts.templates[fullPath];
      const key = hash(fullPath);
      if (!fnCache[key]) fnCache[key] = compile(str, fullPath);
      return fnCache[key];
    } else {
      const str = fs.readFileSync(pathMap[fullPath], 'utf8');
      return compile(str, fullPath);
    }
  }

  function compile(str, currentPath) {
    let layout = '';

    str = str
      .replace(exps.extends, (_, path) => {
        layout = `
          _context.globals.view = _buffer;
          _buffer = _context.compiled('${path}', '${currentPath}')(_context);
        `;
        return '';
      })
      .replace(new RegExp('\\\\', 'g'), '\\\\').replace(/"/g, '\\"')
      .replace(exps.statement, parser);

    const fn = `
        var _buffer = '';
        var _blockName;
        var _blockCapture;

        function _capture(str) {
          if (_blockName) {
            _blockCapture += str;
          } else {
            _buffer += str;
          }
        }

        function _encode(str) {
          _capture(str
            .replace(/&(?!\\w+;)/g, '&')
            .replace(/\</g, '<')
            .replace(/\>/g, '>')
            .replace(/\"/g, '"')
            .replace(/\'/g, ''')
            .replace(/\\//g, '/'));
        }

        for (var prop in _context.globals) {
          if (_context.globals.hasOwnProperty(prop)) {
            eval('var ' + prop + ' = _context.globals[prop]');
          }
        }

        var _locals = _context.locals[_context.locals.length - 1];
        for (var prop in _locals) {
          if (_locals.hasOwnProperty(prop)) {
            eval('var ' + prop + ' = _locals[prop]');
          }
        }

        _context.path = '${currentPath}';

        _capture("${str}");
        ${layout}
        return _buffer;
    `.replace(/_capture\(""\);(\s+)?/g, '');

    try {
      return new Function('_context', cleanWhitespace(fn));
    } catch (e) {
      throw new Error(`Compilation error: ${fn}`);
    }
  }

  return new Beard();
};
<|endoftext|>


<commit_before>var searchService = require('../services/SearchService');
var MatchCriteria = require('../models/MatchCriteria');

var express = require('express');
var router = express.Router();

/* Edit scherm tonen. */
router.get('/', function (req, res) {
    // Zijn we wel ingelogd?
    if (!req.session.user) {
        res.redirect('/login');
    }

    // Haal de eerste search order op voor dit account die momenteel nog aangemaakt wordt.
    searchService.getPendingSearchOrderByFaceBookId(req.session.user.fbid).then(function(existing_order) {
            if (existing_order) {
                // Params uit de search order uit de record halen.

                 res.render('filters', {searchorder_id: existing_order._id,
                    gender: existing_order.MatchCriteria.Gender ? existing_order.MatchCriteria.Gender : null,
                    age_min: existing_order.MatchCriteria.Age ? (existing_order.MatchCriteria.Age.min ? existing_order.MatchCriteria.Age.min : null) : null,
                    age_max: existing_order.MatchCriteria.Age ? (existing_order.MatchCriteria.Age.max ? existing_order.MatchCriteria.Age.max : null) : null,
                    location_lat: existing_order.MatchCriteria.Location ? (existing_order.MatchCriteria.Location.lat ? existing_order.MatchCriteria.Location.lat : null) : null,
                    location_lng: existing_order.MatchCriteria.Location ? (existing_order.MatchCriteria.Location.long ? existing_order.MatchCriteria.Location.long : null) : null,
                    range: existing_order.MatchCriteria.Range ? existing_order.MatchCriteria.Range : null,
                    session: req.session} );
            } else {
                // Geen openstaande order, gewoon leeg scherm laten zien.
                res.render('filters', {session: req.session});
            }
        }
    );
});

/* Opslaan ingevulde waarden. */
router.post('/', function(req, res) {
    // Zijn we wel ingelogd?
    if (!req.session.user) {
        res.redirect('/login');
    }

    // Checken parameters en validatiefouten verzamelen.
    var gender = req.param('gender');
    var age_min = parseInt(req.param('age_min', 0), 10);
    var age_max = parseInt(req.param('age_max', 0), 10);
    var location_lat = parseFloat(req.param('location_lat', 0.0));
    var location_long = parseFloat(req.param('location_lng', 0.0));
    var range = parseInt(req.param('range',0), 10);
    var searchorder_id = req.param('searchorder_id', '');

    var validation_errors = [];
    if (!gender || (gender != 'm' && gender != 'v' && gender != 'b') ) {
        validation_errors.push("
Het opgegeven geslacht is ongeldig.
");
    }
    if (isNaN(age_min) || age_min < 0) {
        validation_errors.push("
De opgegeven minimum leeftijd is ongeldig.
");
    }
    if (isNaN(age_max) || age_max <= 0) {
        validation_errors.push("
De opgegeven maximum leeftijd is ongeldig.
");
    }
    if (age_min >= age_max) {
        validation_errors.push("
De minimum leeftijd moet lager liggen dan de maximum leeftijd.
");
    }
    if (isNaN(location_lat)) {
        validation_errors.push("
De opgegeven location_lat is ongeldig.
");
    }
    if (isNaN(location_long)) {
        validation_errors.push("
De opgegeven location_lng is ongeldig.
");
    }
    if (isNaN(range) || range <= 0) {
        validation_errors.push("
Het opgegeven bereik is ongeldig.
");
    }

    // Nu ophalen eventuele meegegeven searchorder.
    searchService.getSearchOrderById(searchorder_id).then(function (searchorder) {
            if (searchorder_id && !searchorder) {
                validation_errors.push("
De bestaande searchorder is ongeldig.
");
            }

            if (validation_errors.length > 0 ) {
                req.session.last_error = 'Er zijn fouten opgetreden in de invoer:
' + validation_errors.join('') + '
';
                res.render('filters', {
                    searchorder_id: searchorder ? searchorder.searchorder_id : null,
                    gender: gender,
                    age_min: age_min,
                    age_max: age_max,
                    location_lat: location_lat,
                    location_lng: location_long,
                    range: range,
                    session: req.session});
                res.end();
                return;
            }

            if (searchorder) {
                // Bestaande searchorder aanpassen.
                var match_crit = new MatchCriteria(gender, age_min, age_max, location_lat, location_long, range, searchorder.MatchCriteria.Complete);

                searchService.updateSearchOrder( searchorder._id, {
                    facebookAccountId: req.session.user.fbid,
                    matchCriteria: match_crit,
                    pickupLines: searchorder.PickupLines,
                    sampleSize: searchorder.SampleSize
                }).then(function (result) {
                    // Updaten succesvol, doorverwijzen naar de volgende pagina.
                    req.session.last_error = '';
                    res.redirect('/pickuplines');
                }).fail(function (error) {
                    // Fout melden.
                    req.session.last_error = 'Er is een fout opgetreden bij het opslaan van de invoer: ' + error.message;
                    res.render('filters', {
                        searchorder_id: searchorder._id,
                        gender: gender,
                        age_min: age_min,
                        age_max: age_max,
                        location_lat: location_lat,
                        location_lng: location_long,
                        range: range,
                        session: req.session});
                    res.end();
                });
            } else {
                // Nieuwe searchorder aanmaken.
                var match_crit = new MatchCriteria(gender, age_min, age_max, location_lat, location_long, range, 0);

                 searchService.createSearchOrder( {
                    facebookAccountId: req.session.user.fbid,
                    matchCriteria: match_crit,
                    pickupLines: null,
                    sampleSize: 0
                }).then(function (order) {
                     // Opslaan succesvol, doorverwijzen naar de volgende pagina.
                     req.session.last_error = '';
                     res.redirect('/pickuplines');
                 }).fail( function (error) {
                     req.session.last_error = 'Er is een fout opgetreden bij het opslaan van de invoer: ' + error.message;
                     res.render('filters', {
                             gender: gender,
                             age_min: age_min,
                             age_max: age_max,
                             location_lat: location_lat,
                             location_lng: location_long,
                             range: range,
                             session: req.session});
                 });
            }
        }
    );
});

/* Verwijderen openstaande search order. */
router.get('/delete', function(req, res) {
    // Als search order pending is, dan verwijderen.
    // Daarna doorverwijzen naar status scherm.
    // TODO.
})

module.exports = router;
<commit_msg>Verbeteren routing logica in filters scherm<commit_after>var searchService = require('../services/SearchService');
var MatchCriteria = require('../models/MatchCriteria');

var express = require('express');
var router = express.Router();

/* Edit scherm tonen. */
router.get('/', function (req, res) {
    // Zijn we wel ingelogd?
    if (!req.session.user) {
        res.redirect('/login');
    }

    // Heeft deze account orders?
    searchService.getAllSearchOrdersByFaceBookId(req.session.user.fbid).then(function(orders) {
        if (orders && orders.length > 0) {
            // Er zijn orders, zoek de eerste openstaande order.
            var order_openstaand = null;
            orders.every(function(el) {
                if (el.MatchCriteria.Complete == 0) {
                    order_openstaand = el; return false;
                } else {
                    return true;
                }
            });

            if (order_openstaand) {
                // Er is een openstaande order, we geven de params aan de front-end.
                res.render('filters', {searchorder_id: order_openstaand._id,
                    gender: order_openstaand.MatchCriteria.Gender ? order_openstaand.MatchCriteria.Gender : null,
                    age_min: order_openstaand.MatchCriteria.Age ? (order_openstaand.MatchCriteria.Age.min ? order_openstaand.MatchCriteria.Age.min : null) : null,
                    age_max: order_openstaand.MatchCriteria.Age ? (order_openstaand.MatchCriteria.Age.max ? order_openstaand.MatchCriteria.Age.max : null) : null,
                    location_lat: order_openstaand.MatchCriteria.Location ? (order_openstaand.MatchCriteria.Location.lat ? order_openstaand.MatchCriteria.Location.lat : null) : null,
                    location_lng: order_openstaand.MatchCriteria.Location ? (order_openstaand.MatchCriteria.Location.long ? order_openstaand.MatchCriteria.Location.long : null) : null,
                    range: order_openstaand.MatchCriteria.Range ? order_openstaand.MatchCriteria.Range : null,
                    session: req.session} );
            } else {
                // Wel orders, maar geen openstaande, dus we verwijzen door naar het status scherm.
                res.redirect('/status');
            }
        } else {
            // Geen orders, we laten een leeg scherm zien.
            res.render('filters', {session: req.session});
        }
    }).fail(function(error) {
        // TODO
        res.render('filters', {session: req.session});
    });
});

/* Opslaan ingevulde waarden. */
router.post('/', function(req, res) {
    // Zijn we wel ingelogd?
    if (!req.session.user) {
        res.redirect('/login');
    }

    // Checken parameters en validatiefouten verzamelen.
    var gender = req.param('gender');
    var age_min = parseInt(req.param('age_min', 0), 10);
    var age_max = parseInt(req.param('age_max', 0), 10);
    var location_lat = parseFloat(req.param('location_lat', 0.0));
    var location_long = parseFloat(req.param('location_lng', 0.0));
    var range = parseInt(req.param('range',0), 10);
    var searchorder_id = req.param('searchorder_id', '');

    var validation_errors = [];
    if (!gender || (gender != 'm' && gender != 'v' && gender != 'b') ) {
        validation_errors.push("
Het opgegeven geslacht is ongeldig.
");
    }
    if (isNaN(age_min) || age_min < 0) {
        validation_errors.push("
De opgegeven minimum leeftijd is ongeldig.
");
    }
    if (isNaN(age_max) || age_max <= 0) {
        validation_errors.push("
De opgegeven maximum leeftijd is ongeldig.
");
    }
    if (age_min >= age_max) {
        validation_errors.push("
De minimum leeftijd moet lager liggen dan de maximum leeftijd.
");
    }
    if (isNaN(location_lat)) {
        validation_errors.push("
De opgegeven location_lat is ongeldig.
");
    }
    if (isNaN(location_long)) {
        validation_errors.push("
De opgegeven location_lng is ongeldig.
");
    }
    if (isNaN(range) || range <= 0) {
        validation_errors.push("
Het opgegeven bereik is ongeldig.
");
    }

    // Nu ophalen eventuele meegegeven searchorder.
    searchService.getSearchOrderById(searchorder_id).then(function (searchorder) {
            if (searchorder_id && !searchorder) {
                validation_errors.push("
De bestaande searchorder is ongeldig.
");
            }

            if (validation_errors.length > 0 ) {
                req.session.last_error = 'Er zijn fouten opgetreden in de invoer:
' + validation_errors.join('') + '
';
                res.render('filters', {
                    searchorder_id: searchorder ? searchorder.searchorder_id : null,
                    gender: gender,
                    age_min: age_min,
                    age_max: age_max,
                    location_lat: location_lat,
                    location_lng: location_long,
                    range: range,
                    session: req.session});
                res.end();
                return;
            }

            if (searchorder) {
                // Bestaande searchorder aanpassen.
                var match_crit = new MatchCriteria(gender, age_min, age_max, location_lat, location_long, range, searchorder.MatchCriteria.Complete);

                searchService.updateSearchOrder( searchorder._id, {
                    facebookAccountId: req.session.user.fbid,
                    matchCriteria: match_crit,
                    pickupLines: searchorder.PickupLines,
                    sampleSize: searchorder.SampleSize
                }).then(function (result) {
                    // Updaten succesvol, doorverwijzen naar de volgende pagina.
                    req.session.last_error = '';
                    res.redirect('/pickuplines');
                }).fail(function (error) {
                    // Fout melden.
                    req.session.last_error = 'Er is een fout opgetreden bij het opslaan van de invoer: ' + error.message;
                    res.render('filters', {
                        searchorder_id: searchorder._id,
                        gender: gender,
                        age_min: age_min,
                        age_max: age_max,
                        location_lat: location_lat,
                        location_lng: location_long,
                        range: range,
                        session: req.session});
                    res.end();
                });
            } else {
                // Nieuwe searchorder aanmaken.
                var match_crit = new MatchCriteria(gender, age_min, age_max, location_lat, location_long, range, 0);

                 searchService.createSearchOrder( {
                    facebookAccountId: req.session.user.fbid,
                    matchCriteria: match_crit,
                    pickupLines: null,
                    sampleSize: 0
                }).then(function (order) {
                     // Opslaan succesvol, doorverwijzen naar de volgende pagina.
                     req.session.last_error = '';
                     res.redirect('/pickuplines');
                 }).fail( function (error) {
                     req.session.last_error = 'Er is een fout opgetreden bij het opslaan van de invoer: ' + error.message;
                     res.render('filters', {
                             gender: gender,
                             age_min: age_min,
                             age_max: age_max,
                             location_lat: location_lat,
                             location_lng: location_long,
                             range: range,
                             session: req.session});
                 });
            }
        }
    );
});

/* Verwijderen openstaande search order. */
router.get('/delete', function(req, res) {
    // Als search order pending is, dan verwijderen.
    // Daarna doorverwijzen naar status scherm.
    // TODO.
})

module.exports = router;
<|endoftext|>


<commit_before>var crypto = require("crypto");
var exec = require('child_process').exec;
var fs = require('fs');

helpers = {

  boxFromParam: function (param, res) {
    var box = null
    if(param == null) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "No box param given. Should be in format: '+
        '?box=253723.176600653,6660500.4670516,267723.176600653,6646500.4670516"}');
      return;
    } else {
      param = param.split("|")[0];
      box = param.split(',');
    }
    if (box[0] > box[2]) {
      p = box[2]
      box[2] = box[0]
      box[0] = p
    }
    if (box[1] < box[3]) {
      p = box[3]
      box[3] = box[1]
      box[1] = p
    }
    return box;
  },

  outsizeFromParam: function(param, res) {
    var outsize = null;
    if(param == null) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "No outsize param given. ' +
        'Should be in format: ?outsize=1000,1000  (x,y)"}');
      return false;
    } else {
      outsize = param.split(",");
      if(outsize.length == 1) {
        outsize = [outsize,outsize];
      }
    }
    return outsize;
  },
  numericParams: function(params, res) {
  	var non_number = false;
  	params.forEach(function(i) {
  	      if(!(typeof Number(i) === 'number' &&
              isFinite(Number(i)))) {
  	        non_number = i;
  	        return;
  	      }
  	    }
  	  );
    if(non_number) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "box or outsize param contains non-numerics"}');
    }
    return !non_number;
  },
  fileHash: function(filename, extension) {
    return crypto.createHash('sha1').update(filename).digest('hex')+"."+extension;
  },
  isLoggedIn: function(session) {
    if (!session.oauth_access_token) {
      return false;
    }
    return true;
  },
  generate: function(filename, box, callback) {
    var output = "";
    var generator = exec("node "+__dirname+"/../generate.js "+filename+" \""+box.join(',')+"\"", function(err, stdout, stderr) {
      if (err) {
        output += err;
      };
      if (stdout) {
        console.log("generator: ", stdout.toString())
        output += stdout.toString();
      };
      if (stderr) {
        console.log("generator: ", stderr.toString())
        output += stderr.toString();
      }
    });
    generator.on('exit', function(code, signal) {
      if (code != 0) {
        callback("Generator failed with code "+code+"\n <!-- "+output+" -->", null);
      } else {
        callback(null, filename);
      }
    });
  }
};
module.exports = helpers;
<commit_msg>More logging<commit_after>var crypto = require("crypto");
var exec = require('child_process').exec;
var fs = require('fs');

helpers = {

  boxFromParam: function (param, res) {
    var box = null
    if(param == null) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "No box param given. Should be in format: '+
        '?box=253723.176600653,6660500.4670516,267723.176600653,6646500.4670516"}');
      return;
    } else {
      param = param.split("|")[0];
      box = param.split(',');
    }
    if (box[0] > box[2]) {
      p = box[2]
      box[2] = box[0]
      box[0] = p
      console.log("Swapped box 0 <-> 2")
    }
    if (box[1] < box[3]) {
      p = box[3]
      box[3] = box[1]
      box[1] = p
      console.log("Swapped box 1 <-> 3")
    }
    return box;
  },

  outsizeFromParam: function(param, res) {
    var outsize = null;
    if(param == null) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "No outsize param given. ' +
        'Should be in format: ?outsize=1000,1000  (x,y)"}');
      return false;
    } else {
      outsize = param.split(",");
      if(outsize.length == 1) {
        outsize = [outsize,outsize];
      }
    }
    return outsize;
  },
  numericParams: function(params, res) {
  	var non_number = false;
  	params.forEach(function(i) {
  	      if(!(typeof Number(i) === 'number' &&
              isFinite(Number(i)))) {
  	        non_number = i;
  	        return;
  	      }
  	    }
  	  );
    if(non_number) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "box or outsize param contains non-numerics"}');
    }
    return !non_number;
  },
  fileHash: function(filename, extension) {
    return crypto.createHash('sha1').update(filename).digest('hex')+"."+extension;
  },
  isLoggedIn: function(session) {
    if (!session.oauth_access_token) {
      return false;
    }
    return true;
  },
  generate: function(filename, box, callback) {
    var output = "";
    var generator = exec("node "+__dirname+"/../generate.js "+filename+" \""+box.join(',')+"\"", function(err, stdout, stderr) {
      if (err) {
        output += err;
      };
      if (stdout) {
        console.log("generator: ", stdout.toString())
        output += stdout.toString();
      };
      if (stderr) {
        console.log("generator: ", stderr.toString())
        output += stderr.toString();
      }
    });
    generator.on('exit', function(code, signal) {
      if (code != 0) {
        callback("Generator failed with code "+code+"\n <!-- "+output+" -->", null);
      } else {
        callback(null, filename);
      }
    });
  }
};
module.exports = helpers;
<|endoftext|>


<commit_before>var crypto = require("crypto");
var exec = require('child_process').exec;
var fs = require('fs');

helpers = {

  boxFromParam: function (param, res) {
    var box = null
    if(param == null) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "No box param given. Should be in format: '+
        '?box=253723.176600653,6660500.4670516,267723.176600653,6646500.4670516"}');
      return;
    } else {
      param = param.split("|")[0];
      box = param.split(',');
    }
    if (box[0] > box[2]) {
      p = box[2]
      box[2] = box[0]
      box[0] = p
      console.log("Swapped box 0 <-> 2")
    }
    if (box[1] < box[3]) {
      p = box[3]
      box[3] = box[1]
      box[1] = p
      console.log("Swapped box 1 <-> 3")
    }
    return box;
  },

  outsizeFromParam: function(param, res) {
    var outsize = null;
    if(param == null) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "No outsize param given. ' +
        'Should be in format: ?outsize=1000,1000  (x,y)"}');
      return false;
    } else {
      outsize = param.split(",");
      if(outsize.length == 1) {
        outsize = [outsize,outsize];
      }
    }
    return outsize;
  },
  numericParams: function(params, res) {
  	var non_number = false;
  	params.forEach(function(i) {
  	      if(!(typeof Number(i) === 'number' &&
              isFinite(Number(i)))) {
  	        non_number = i;
  	        return;
  	      }
  	    }
  	  );
    if(non_number) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "box or outsize param contains non-numerics"}');
    }
    return !non_number;
  },
  fileHash: function(filename, extension) {
    return crypto.createHash('sha1').update(filename).digest('hex')+"."+extension;
  },
  isLoggedIn: function(session) {
    if (!session.oauth_access_token) {
      return false;
    }
    return true;
  },
  generate: function(filename, box, callback) {
    var output = "";
    var generator = exec("node "+__dirname+"/../generate.js "+filename+" \""+box.join(',')+"\"", function(err, stdout, stderr) {
      if (err) {
        output += err;
      };
      if (stdout) {
        console.log("generator: ", stdout.toString())
        output += stdout.toString();
      };
      if (stderr) {
        console.log("generator: ", stderr.toString())
        output += stderr.toString();
      }
    });
    generator.on('exit', function(code, signal) {
      if (code != 0) {
        callback("Generator failed with code "+code+"\n <!-- "+output+" -->", null);
      } else {
        callback(null, filename);
      }
    });
  }
};
module.exports = helpers;
<commit_msg>Tweak to prevent mirroring trouble<commit_after>var crypto = require("crypto");
var exec = require('child_process').exec;
var fs = require('fs');

helpers = {

  boxFromParam: function (param, res) {
    var box = null
    if(param == null) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "No box param given. Should be in format: '+
        '?box=253723.176600653,6660500.4670516,267723.176600653,6646500.4670516"}');
      return;
    } else {
      param = param.split("|")[0];
      box = param.split(',');
    }
    if (Math.abs(box[0]) > Math.abs(box[2])) {
      p = box[2]
      box[2] = box[0]
      box[0] = p
      console.log("Swapped box 0 <-> 2")
    }
    if (box[1] < box[3]) {
      p = box[3]
      box[3] = box[1]
      box[1] = p
      console.log("Swapped box 1 <-> 3")
    }
    return box;
  },

  outsizeFromParam: function(param, res) {
    var outsize = null;
    if(param == null) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "No outsize param given. ' +
        'Should be in format: ?outsize=1000,1000  (x,y)"}');
      return false;
    } else {
      outsize = param.split(",");
      if(outsize.length == 1) {
        outsize = [outsize,outsize];
      }
    }
    return outsize;
  },
  numericParams: function(params, res) {
  	var non_number = false;
  	params.forEach(function(i) {
  	      if(!(typeof Number(i) === 'number' &&
              isFinite(Number(i)))) {
  	        non_number = i;
  	        return;
  	      }
  	    }
  	  );
    if(non_number) {
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end('{"error": "box or outsize param contains non-numerics"}');
    }
    return !non_number;
  },
  fileHash: function(filename, extension) {
    return crypto.createHash('sha1').update(filename).digest('hex')+"."+extension;
  },
  isLoggedIn: function(session) {
    if (!session.oauth_access_token) {
      return false;
    }
    return true;
  },
  generate: function(filename, box, callback) {
    var output = "";
    var generator = exec("node "+__dirname+"/../generate.js "+filename+" \""+box.join(',')+"\"", function(err, stdout, stderr) {
      if (err) {
        output += err;
      };
      if (stdout) {
        console.log("generator: ", stdout.toString())
        output += stdout.toString();
      };
      if (stderr) {
        console.log("generator: ", stderr.toString())
        output += stderr.toString();
      }
    });
    generator.on('exit', function(code, signal) {
      if (code != 0) {
        callback("Generator failed with code "+code+"\n <!-- "+output+" -->", null);
      } else {
        callback(null, filename);
      }
    });
  }
};
module.exports = helpers;
<|endoftext|>


<commit_before>var express      = require('express');
var router       = express.Router();
var jsonwebtoken = require('jsonwebtoken');
const Mailer     = require('../helpers/mailer');
const TokenMaker = require('../helpers/tokenMaker');

var secretKey = process.env.TEAM_MANAGER_SECRET_KEY;

var tokenMaker = new TokenMaker(secretKey);
var mailer     = new Mailer();

var Member = require('../schema/member');
var User = require('../schema/user');
var Team = require('../schema/team');

router.post('/add', function(req, res, next) {

    var member = new Member({
        team: req.body.team,
        user: req.body.user,

    });

    member.save(function(err) {
        if(err) {
            console.log("member save error: " + err);
            res.send(err);
            return;
        }
        console.log("member created");
    });

    res.json({ success: true, message: 'member created !', member: member});
});

//-----------------------------------------------------
//   Get Members
//-----------------------------------------------------
router.get('/all', function(req, res) {

    var user_id = req.decoded._id;
    console.log("get all members for user: " + user_id);

    Member.find( {manager: user_id})
        .populate('manager', ['_id', 'first_name', 'last_name', 'username'])
        .exec(function(err, members) {

            if(err) {
                res.send(err);
                return;
            }
            res.json(members);
        });
});

//-----------------------------------------------------
//   VERIFY
//-----------------------------------------------------
router.get('/verify/:token', function(req, res) {
    var token = req.params.token;

    console.log("Got verification token: " + token);

    if(!token) {
        res.send("No token found!");
        return;
    }

    jsonwebtoken.verify(token, secretKey, function(err, decoded){

        if(err) {
            res.send("Token verification failed!");
            return;
        }

        // approving user
        Member.update({user: decoded._id}, {is_accepted: true}, function(err, numberAffected, rawResponse) {

            console.log("-- saved: " + err);
            if(err) res.send("Token verification failed!");
            else {

                //res.send("User verification Successfully!");

                var parentDir  = __dirname.substring(0, __dirname.lastIndexOf('/'));

                res.sendFile(parentDir + '/public/views/general/verification_done.html') ;
            }
        })

    });//jsonwebtoken

    //res.send("ok");
});

function sendInvitationEmail(req, email, token) {
    const subject = "Welcome to team manager";
    var html = "Hi
,
 Welcome !!!
 Team Manager is a perfect solution for managing your project and teams !!!
";

    html += "
 Click on following link to verify your email.";

    // origin will tell localhost or server domain url's prefix
    var origin = req.get('origin');

    html += "
VERIFY ME";

    html += "

 Thanks
 Team Manager Team";

    mailer.sendMail(email, subject, html);
}

//-----------------------------------------------------
//   INVITE USER TO TEAM
//-----------------------------------------------------
router.post('/invite_team_member', function(req, res) {
    var email = req.body.email;

    // console.log("[INFO] :: sending invitation to : " + email);

    // if user is not registered - check for email
    // send back error, user not found
    // ensure that user is not already registered

    User.findOne({
        email: req.body.email
            //}).select('password').exec(function(err, user) { // this will only select _id and password in user obj
        }).exec(function(err, user) {   //// this will select all fields in user obj

        if(err) throw err;

        if(!user) {
            res.send({ success: false, message: 'User does not exist !'});
            //res.status(403).send( {success: false, message: 'User does not exist !'});
        } else if(user) {

            //----------------------------------------------
            // before logging, ensure that user is verified
            //----------------------------------------------
            if(!user.is_verified) {

                console.log("------------ user not verified ----");

                res.send(JSON.stringify( { success: false, message: 'User is not verified, please check you email for verification. '} )  );
                //res.status(403).send( JSON.stringify( { success: false, message: 'User is not verified !'} )  );
                return;
            }

            else {

                console.log("User  exists");

                //-------------------------
                // user exists , create token
                //-------------------------
                var token = tokenMaker.createUserToken(user);
                //req.session.user = user;

                // res.json({
                //     success: true,
                //     message: "User Exists",
                //     role: user.role,
                //     user_id: user._id,
                //     email: user.email,
                //     first_name: user.first_name,
                //     last_name: user.last_name,
                //     });

                res.json({ success: true, message: 'Invitation sent to ' + email});
                sendInvitationEmail(req, email, tokenMaker.createVerificationToken(user));

            }
        }
    });

});
module.exports = router;
<commit_msg>modified member routes<commit_after>var express      = require('express');
var router       = express.Router();
var jsonwebtoken = require('jsonwebtoken');
const Mailer     = require('../helpers/mailer');
const TokenMaker = require('../helpers/tokenMaker');

var secretKey = process.env.TEAM_MANAGER_SECRET_KEY;

var tokenMaker = new TokenMaker(secretKey);
var mailer     = new Mailer();

var Member = require('../schema/member');
var User = require('../schema/user');
var Team = require('../schema/team');

//-----------------------------------------------------
//   Get Members
//-----------------------------------------------------
router.get('/all', function(req, res) {

    var user_id = req.decoded._id;
    console.log("get all members for user: " + user_id);

    Member.find( {manager: user_id})
        .populate('manager', ['_id', 'first_name', 'last_name', 'username'])
        .exec(function(err, members) {

            if(err) {
                res.send(err);
                return;
            }
            res.json(members);
        });
});

//-----------------------------------------------------
//   VERIFY
//-----------------------------------------------------
router.get('/verify/:token', function(req, res) {
    var token = req.params.token;

    console.log("Got verification token: " + token);

    if(!token) {
        res.send("No token found!");
        return;
    }

    jsonwebtoken.verify(token, secretKey, function(err, decoded){

        if(err) {
            res.send("Token verification failed!");
            return;
        }

        // approving user
        Member.update({user: decoded._id}, {is_accepted: true}, function(err, numberAffected, rawResponse) {

            console.log("-- saved: " + err);
            if(err) res.send("Token verification failed!");
            else {

                //res.send("User verification Successfully!");

                var parentDir  = __dirname.substring(0, __dirname.lastIndexOf('/'));

                res.sendFile(parentDir + '/public/views/general/verification_done.html') ;
            }
        })

    });//jsonwebtoken

    //res.send("ok");
});

function sendInvitationEmail(req, email, token) {
    const subject = "Welcome to team manager";
    var html = "Hi
,
 Welcome !!!
 Team Manager is a perfect solution for managing your project and teams !!!
";

    html += "
 Click on following link to verify your email.";

    // origin will tell localhost or server domain url's prefix
    var origin = req.get('origin');

    html += "
VERIFY ME";

    html += "

 Thanks
 Team Manager Team";

    mailer.sendMail(email, subject, html);
}

//-----------------------------------------------------
//   INVITE USER TO TEAM
//-----------------------------------------------------
router.post('/invite_team_member', function(req, res) {

    var team_id;
    var manager_id = req.decoded._id;
    var email = req.body.email;

    Team.findOne( {manager:manager_id })

    .exec(function(err, team) {

        if(err) {
            res.send({ success: false, message: 'Team not found'});
            return;
        }

        team_id=team._id;

        var member = new Member({
            team: team_id,
            user: manager_id,

        });

        member.save(function(err) {
            if(err) {
                console.log("member save error: " + err);
                res.send(err);
                return;
            }
            console.log("member created");
        });

        res.json({ success: true, message: 'member created !', member: member});

        }); // Team

    User.findOne({
        email: req.body.email

        }).exec(function(err, user) {

        if(err) throw err;

        if(!user) {
            res.send({ success: false, message: 'User does not exist !'});

        } else if(user) {

            //----------------------------------------------
            // before logging, ensure that user is verified
            //----------------------------------------------
            if(!user.is_verified) {

                console.log("------------ user not verified ----");

                res.send(JSON.stringify( { success: false, message: 'User is not verified, please check you email for verification. '} )  );
                //res.status(403).send( JSON.stringify( { success: false, message: 'User is not verified !'} )  );
                return;
            }

            else {

                console.log("User  exists");

                //-------------------------
                // user exists , create token
                //-------------------------
                var token = tokenMaker.createUserToken(user);

                // res.json({ success: true, message: 'Invitation sent to ' + email});
                sendInvitationEmail(req, email, tokenMaker.createVerificationToken(user));

             }
        }
    });

});
module.exports = router;
<|endoftext|>


<commit_before>'use strict';

var action = require('../actions')(),
    agentDb = require('../schemata/agent')(),
    extend = require('extend'),
    multiparty = require('connect-multiparty'),
    nconf = require('nconf'),
    passport = require('passport'),
    q = require('q'),
    sc = require('../lib/sc'),
    utils = require('../lib/utils'),
    winston = require('winston');

module.exports = function(testing) {

    var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ colorize: true }) ] });

    // Get this agent's email. Put into
    // test mode, if specified
    var agentEmail = nconf.get('email');
    if (testing) {
      agentEmail = nconf.get('testEmail');
    }

    /**
     * Handle incoming attempts to perform
     * actions on the data specified in the message
     */
    var _handler = function(req, res, done) {

        var message = req.body,
            agent = req.user;

        logger.info('message', JSON.stringify(message, null, 2));
        logger.info('req.files', JSON.stringify(req.files, null, 2));

        // A message's receiver used to be specified in the
        // message body. Since the vanilla gebo no longer mediates
        // between external agents, the vanilla gebo is always
        // the receiver.
        message.receiver = agentEmail;

        // Form a social commitment
        sc.form(agent, 'perform', message).
            then(function(socialCommitment) {
                _verify(agent, message).
                    then(function(verified) {

                        // There might be files attached to the message.
                        // They are included here, because it seems
                        // silly to attach them to the social commitment.
                        extend(true, message, req.files);

                        logger.info('verified', verified);

                        /**
                         * Actions may be specified in dot notation. This was written
                         * in the heat of the moment, so an agent can currently only
                         * have an action burried one layer deep. Ideally, this should
                         * handle actions burried any arbitrary depth, but at the moment
                         * I can't see why it would ever go deeper than one. So screw it.
                         */
                        var actionPtr = action;
                        var actionParts = message.action.split('.');
                        if (actionParts.length === 2) {
                            actionPtr = actionPtr[actionParts[0]];
                        }

                        /**
                         * Make sure this agent knows how to
                         * perform the requested action
                         */
                        if(!actionPtr[actionParts[actionParts.length - 1]]) {
                          res.send(501, 'I don\'t know how to ' + message.action);
                          done();
                        }
                        else {
                          actionPtr[actionParts[actionParts.length - 1]](verified, message).
                              then(function(data) {
                                 sc.fulfil(message.receiver, socialCommitment._id).
                                      then(function(sc) {
                                          logger.info('data', data);
                                          // If you don't set this as a string,
                                          // the status code will be set to the
                                          // numeric value contained in data
                                          if (typeof data === 'number') {
                                            res.send(200, '' + data);
                                          }
                                          else {
                                            res.status(200).send(data);
                                          }
                                          done();
                                        }).
                                      catch(function(err) {
                                          logger.error('Social commitment fulfil', err);
                                          res.send(401, err);
                                          done(err);
                                        });
                                }).
                              catch(function(err) {
                                      logger.error('Action', err);
                                      res.send(401, err);
                                      done(err);
                                });
                        }
                      }).
                    catch(function(err) {
                        logger.error('Verification', err);
                        res.send(401, err);
                        done(err);
                      });
              }).
            catch(function(err) {
                logger.error('Cannot commit', err);
                res.send(401, err);
                done(err);
              });
       };
    exports.handler = _handler;

    /**
     * Authenticate, if necessary
     */
    function _authenticate(req, res, next) {
        if (req.user) {
          return next();
        }

        passport.authenticate(['bearer'], { session: false })(req, res, next);
      };
    exports.authenticate = _authenticate;

    /**
     * Receive a perform attempt for consideration
     */
    var multipartyMiddleware = multiparty();
    exports.perform = [
        multipartyMiddleware,
        _authenticate,
        // _handler takes a callback for unit testing purposes.
        // passport.authenticate's next() callback screws everything up
        // when the server runs for real. This step, though goofy looking,
        // circumvents that issue.
        function(req, res, next) {
            _handler(req, res, function(){});
        }
      ];

    /**
     * Determine what permissions an agent has on a
     * given object
     *
     * @param Object
     * @param Object
     *
     * @return promise
     */
    function _verify(agent, message) {
        var deferred = q.defer();

        // A message's contents may be received as a string.
        if (typeof message.content === 'string') {
          message.content = JSON.parse(message.content);
        }

        /**
         * A resource may be a DB collection or an action
         * performed by the gebo. If no collection is specified
         * then the relevant resource must be an action
         */
        var resource = message.action;
        if (message.content && message.content.resource) {
          resource = utils.getMongoCollectionName(message.content.resource);
        }

        var verified = {
                resource: resource,
                admin: agent.admin,
                read: false,
                write: false,
                execute: false,
            };

//        if (!verified.dbName) {
//          verified.dbName = utils.getMongoDbName(agent.email);
//        }

        if (agent.admin) {
          verified.read = true;
          verified.write = true;
          verified.execute = true;
          deferred.resolve(verified);
        }
        else {
          agentDb.friendoModel.findOne({ email: agent.email }, function(err, friendo) {
                logger.info('friendo:', agent.email, JSON.stringify(friendo, null, 2));
                if (err) {
                  deferred.reject(err);
                }
                if (!friendo) {
                  deferred.resolve(verified);
                }
                else {
                  // Search the array for relevant resource
                  var index = utils.getIndexOfObject(friendo.permissions, 'resource', verified.resource);

                  if (index > -1) {
                    verified.read = friendo.permissions[index].read;
                    verified.write = friendo.permissions[index].write;
                    verified.execute = friendo.permissions[index].execute;
                  }

                  deferred.resolve(verified);
                }
              });
        }

        return deferred.promise;
      };
    exports.verify = _verify;

    return exports;
  };

<commit_msg>Update deprecated express res.send calls to res.status.send<commit_after>'use strict';

var action = require('../actions')(),
    agentDb = require('../schemata/agent')(),
    extend = require('extend'),
    multiparty = require('connect-multiparty'),
    nconf = require('nconf'),
    passport = require('passport'),
    q = require('q'),
    sc = require('../lib/sc'),
    utils = require('../lib/utils'),
    winston = require('winston');

module.exports = function(testing) {

    var logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ colorize: true }) ] });

    // Get this agent's email. Put into
    // test mode, if specified
    var agentEmail = nconf.get('email');
    if (testing) {
      agentEmail = nconf.get('testEmail');
    }

    /**
     * Handle incoming attempts to perform
     * actions on the data specified in the message
     */
    var _handler = function(req, res, done) {

        var message = req.body,
            agent = req.user;

        logger.info('message', JSON.stringify(message, null, 2));
        logger.info('req.files', JSON.stringify(req.files, null, 2));

        // A message's receiver used to be specified in the
        // message body. Since the vanilla gebo no longer mediates
        // between external agents, the vanilla gebo is always
        // the receiver.
        message.receiver = agentEmail;

        // Form a social commitment
        sc.form(agent, 'perform', message).
            then(function(socialCommitment) {
                _verify(agent, message).
                    then(function(verified) {

                        // There might be files attached to the message.
                        // They are included here, because it seems
                        // silly to attach them to the social commitment.
                        extend(true, message, req.files);

                        logger.info('verified', verified);

                        /**
                         * Actions may be specified in dot notation. This was written
                         * in the heat of the moment, so an agent can currently only
                         * have an action burried one layer deep. Ideally, this should
                         * handle actions burried any arbitrary depth, but at the moment
                         * I can't see why it would ever go deeper than one. So screw it.
                         */
                        var actionPtr = action;
                        var actionParts = message.action.split('.');
                        if (actionParts.length === 2) {
                            actionPtr = actionPtr[actionParts[0]];
                        }

                        /**
                         * Make sure this agent knows how to
                         * perform the requested action
                         */
                        if(!actionPtr[actionParts[actionParts.length - 1]]) {
                          res.status(501).send({ error: 501, message: 'I don\'t know how to ' + message.action });
                          done();
                        }
                        else {
                          actionPtr[actionParts[actionParts.length - 1]](verified, message).
                              then(function(data) {
                                 sc.fulfil(message.receiver, socialCommitment._id).
                                      then(function(sc) {
                                          logger.info('data', data);
                                          // If you don't set this as a string,
                                          // the status code will be set to the
                                          // numeric value contained in data
                                          if (typeof data === 'number') {
                                            //res.send(200, '' + data);
                                            res.status(200).send('' + data);
                                          }
                                          else {
                                            res.status(200).send(data);
                                          }
                                          done();
                                        }).
                                      catch(function(err) {
                                          logger.error('Social commitment fulfil', err);
                                          //res.send(401, err);
                                          res.status(401).send({ code: '401', message: err });
                                          done(err);
                                        });
                                }).
                              catch(function(err) {
                                      logger.error('Action', err);
                                      //res.send(401, err);
                                      res.status(401).send({ code: '401', message: 'You are not allowed access to that resource' });
                                      done(err);
                                });
                        }
                      }).
                    catch(function(err) {
                        logger.error('Verification', err);
                        //res.send(401, err);
                        res.status(401).send({ code: '401', message: err });
                        done(err);
                      });
              }).
            catch(function(err) {
                logger.error('Bad request', err);
                res.status(400).send({ code: '400', message: 'The request could not be understood by the server' });
                done(err);
              });
       };
    exports.handler = _handler;

    /**
     * Authenticate, if necessary
     */
    function _authenticate(req, res, next) {
        if (req.user) {
          return next();
        }

        passport.authenticate(['bearer'], { session: false })(req, res, next);
      };
    exports.authenticate = _authenticate;

    /**
     * Receive a perform attempt for consideration
     */
    var multipartyMiddleware = multiparty();
    exports.perform = [
        multipartyMiddleware,
        _authenticate,
        // _handler takes a callback for unit testing purposes.
        // passport.authenticate's next() callback screws everything up
        // when the server runs for real. This step, though goofy looking,
        // circumvents that issue.
        function(req, res, next) {
            _handler(req, res, function(){});
        }
      ];

    /**
     * Determine what permissions an agent has on a
     * given object
     *
     * @param Object
     * @param Object
     *
     * @return promise
     */
    function _verify(agent, message) {
        var deferred = q.defer();

        // A message's contents may be received as a string.
        if (typeof message.content === 'string') {
          message.content = JSON.parse(message.content);
        }

        /**
         * A resource may be a DB collection or an action
         * performed by the gebo. If no collection is specified
         * then the relevant resource must be an action
         */
        var resource = message.action;
        if (message.content && message.content.resource) {
          resource = utils.getMongoCollectionName(message.content.resource);
        }

        var verified = {
                resource: resource,
                admin: agent.admin,
                read: false,
                write: false,
                execute: false,
            };

//        if (!verified.dbName) {
//          verified.dbName = utils.getMongoDbName(agent.email);
//        }

        if (agent.admin) {
          verified.read = true;
          verified.write = true;
          verified.execute = true;
          deferred.resolve(verified);
        }
        else {
          agentDb.friendoModel.findOne({ email: agent.email }, function(err, friendo) {
                logger.info('friendo:', agent.email, JSON.stringify(friendo, null, 2));
                if (err) {
                  deferred.reject(err);
                }
                if (!friendo) {
                  deferred.resolve(verified);
                }
                else {
                  // Search the array for relevant resource
                  var index = utils.getIndexOfObject(friendo.permissions, 'resource', verified.resource);

                  if (index > -1) {
                    verified.read = friendo.permissions[index].read;
                    verified.write = friendo.permissions[index].write;
                    verified.execute = friendo.permissions[index].execute;
                  }

                  deferred.resolve(verified);
                }
              });
        }

        return deferred.promise;
      };
    exports.verify = _verify;

    return exports;
  };

<|endoftext|>


<commit_before>/**
 * Created by оо on 21.11.13.
 */

(function(){

    console.log("Artem".match(/\d(Artem)|Igor/g)); //null
    console.log("2Artem".match(/\d(Artem)|Igor/g)); //2Artem

})()<commit_msg>вернуть с помощью () отдельный результат из правила<commit_after>/**
 * Created by оо on 21.11.13.
 */

(function(){
    console.log("23px, aaa".match(/\d+px/)); //23px
    console.log("23px, aaa".match(/(\d+)px/)); //23

})()<|endoftext|>