<commit_before>(function () {
    "use strict";

    // Setup dimensions.
    var levelWidth = 600;
    var levelHeight = 400;

    // Setup pixi.
    var stage = new PIXI.Stage(0x141c22);
    var renderer = PIXI.autoDetectRenderer(levelWidth, levelHeight);
    document.body.appendChild(renderer.view);

    // Setup world.
    var world = new hitagi.World();

    // Setup controls.
    var controls = new hitagi.Controls();
    controls.bind(38, 'up');
    controls.bind(40, 'down');

    // Define and register systems.
    var renderSystem = new hitagi.systems.PixiRenderSystem(stage);
    world.register(renderSystem);

    world.register(new hitagi.systems.VelocitySystem());

    var collisionSystem = new hitagi.systems.CollisionSystem();
    world.register(collisionSystem);

    var PaddleSystem = function () {
        this.update = function (entity, dt) {
            if (entity.has('paddle')) {
                // Slow down from friction.
                entity.c.velocity.yspeed *= entity.c.paddle.friction;
                if (Math.abs(entity.c.velocity.yspeed) < 0.01) {
                    entity.c.velocity.yspeed = 0;
                }

                // Stop from leaving screen.
                var projectedY = entity.c.position.y + entity.c.velocity.yspeed;
                if (projectedY - entity.c.paddle.height/2 < 0) {
                    entity.c.velocity.yspeed *= -1.4;
                }
                if (projectedY + entity.c.paddle.height/2 > levelHeight) {
                    entity.c.velocity.yspeed *= -1.4;
                }
            }
        };
    };
    world.register(new PaddleSystem());

    var PlayerSystem = function () {
        this.update = function (entity, dt) {
            if (entity.has('player') && entity.has('paddle')) {
                // Handle player input.
                if (controls.check('up')) {
                    entity.c.velocity.yspeed -= entity.c.paddle.speed;
                }
                if (controls.check('down')) {
                    entity.c.velocity.yspeed += entity.c.paddle.speed;
                }
            }
        };
    };
    world.register(new PlayerSystem());

    var AISystem = function () {
        var ai = null;

        this.build = function (entity) {
            if (entity.has('ai')) {
                ai = entity;
            }
        }

        this.update = function (entity) {
            if (entity.has('ai')) {
                if (Math.random() > 0.8) {
                    if (entity.c.position.y < entity.c.ai.lastKnownY) {
                        entity.c.velocity.yspeed += entity.c.paddle.speed;
                    } else {
                        entity.c.velocity.yspeed -= entity.c.paddle.speed;
                    }
                }
            }
            if (entity.has('ball')) {
                ai.c.ai.lastKnownY = entity.c.position.y;
            }
        };
    };
    world.register(new AISystem());

    var BallSystem = function (collisionSystem) {
        this.update = function (entity, dt) {
            if (entity.has('ball')) {
                var x = entity.c.position.x;
                var y = entity.c.position.y;

                var test = collisionSystem.collide(entity, 'paddle', x, y);
                if (test.hit) {
                    entity.c.velocity.xspeed *= -1.01;

                    if (entity.c.position.y < test.entity.c.position.y) {
                        entity.c.velocity.yspeed +=
                            (entity.c.position.y - test.entity.c.position.y) / 50;
                    }
                    if (entity.c.position.y > test.entity.c.position.y) {
                        entity.c.velocity.yspeed -=
                            (entity.c.position.y - test.entity.c.position.y) / 50;
                    }
                }

                if ((entity.c.position.y < 0) || (entity.c.position.y > levelHeight)) {
                    entity.c.velocity.yspeed *= -1;
                }
            }
        };

        this.resetBall = function (ball) {
            ball.c.position.x = levelWidth/2;
            ball.c.position.y = levelHeight/2;
            ball.c.velocity.yspeed *= -0.95;
            ball.c.velocity.xspeed *= -0.95;
        };
    };
    var ballSystem = world.register(new BallSystem(collisionSystem));

    var ScoreSystem = function (ballSystem, renderSystem) {
        var scores = null;

        this.build = function (entity) {
            if (entity.has('scorecard')) {
                scores = entity;
            }
        }

        this.update = function (entity, dt) {
            if (entity.has('ball')) {
                if (entity.c.position.x < 0) {
                    ballSystem.resetBall(entity);
                    scores.c.scorecard.score2++;
                }

                if (entity.c.position.x > levelWidth) {
                    ballSystem.resetBall(entity);
                    scores.c.scorecard.score1++;
                }
            }

            if (entity.has('scorecard')) {
                renderSystem.setText(
                    entity,
                    entity.c.scorecard.score1 + ' - ' + entity.c.scorecard.score2
                );
            }
        };
    };
    world.register(new ScoreSystem(ballSystem, renderSystem));

    // Define prefabs.

    // Params: color, friction, height, width, speed, x, y
    var Paddle = function (params) {
        return new hitagi.Entity()
            .attach(new hitagi.components.Position({
                x: params.x,
                y: params.y
            }))
            .attach(new hitagi.components.Velocity({
                xspeed: 0,
                yspeed: 0
            }))
            .attach(new hitagi.components.Rectangle({
                color: params.color,
                x1: 0,
                y1: 0,
                x2: params.width,
                y2: params.height,
                offsetX: -params.width/2,
                offsetY: -params.height/2
            }))
            .attach({
                id: 'paddle',
                deps: ['velocity'],
                friction: params.friction,
                height: params.height,
                speed: params.speed,
                width: params.width
            })
            .attach(new hitagi.components.Collision({
                height: params.height,
                width: params.width
            }));
    };

    // Params: color, height, width, x, y, xspeed, yspeed
    var Ball = function (params) {
        return new hitagi.Entity()
            .attach(new hitagi.components.Position({
                x: params.x,
                y: params.y
            }))
            .attach(new hitagi.components.Velocity({
                xspeed: params.xspeed,
                yspeed: params.yspeed
            }))
            .attach(new hitagi.components.Rectangle({
                color: params.color,
                x1: 0,
                y1: 0,
                x2: params.width/2,
                y2: params.height/2,
                offsetX: -params.width/2,
                offsetY: -params.height/2
            }))
            .attach(new hitagi.components.Collision({
                height: params.width,
                width: params.height
            }))
            .attach({'id': 'ball'})
    };

    // Params: color, font, score1, score2, x, y
    var Score = function (params) {
        return new hitagi.Entity()
            .attach(new hitagi.components.Position({
                x: params.x,
                y: params.y
            }))
            .attach(new hitagi.components.Text({
                txt: '',
                options: {
                    font: params.font,
                    fill: params.color
                }
            }))
            .attach({
                id: 'scorecard',
                score1: params.score1,
                score2: params.score2
            })
    };

    // Add entities.
    var player = world.add(
        new Paddle({
            color:  0xFFFF00,
            friction: 0.9,
            height: 96,
            width: 4,
            speed: 1,
            x: 32,
            y: levelHeight/2
        })
        .attach({
            id: 'player',
            deps: ['paddle']
        })
    );

    var opponent = world.add(
        new Paddle({
            color:  0xFFFF00,
            friction: 0.9,
            height: 96,
            width: 4,
            speed: 1,
            x: levelWidth - 24,
            y: levelHeight/2
        })
        .attach({
            id: 'ai',
            deps: ['paddle'],
            lastKnownY: levelHeight/2
        })
    );

    var ball = world.add(
        new Ball({
            color: 0xFFFFFF,
            height: 16,
            width: 16,
            x: levelWidth/2,
            y: levelHeight/2,
            xspeed: -5,
            yspeed: 0
        })
    );

    var score = world.add(
        new Score({
            color: 'white',
            font: '16px monospace',
            score1: 0,
            score2: 0,
            x: levelWidth/2 - 16/2,
            y: 16
        })
    );

    // Setup game loop.
    requestAnimationFrame(animate);

    function animate() {
        // Update the world, using a fixed delta time.
        world.tick(1000);

        // Render the world.
        renderer.render(stage);

        // Next frame.
        requestAnimationFrame(animate);
    }

} ());
<commit_msg>Pong example: Created a unified paddle input system and improved AI<commit_after>(function () {
    "use strict";

    // Setup dimensions.
    var levelWidth = 600;
    var levelHeight = 400;

    // Setup pixi.
    var stage = new PIXI.Stage(0x141c22);
    var renderer = PIXI.autoDetectRenderer(levelWidth, levelHeight);
    document.body.appendChild(renderer.view);

    // Setup world.
    var world = new hitagi.World();

    // Setup controls.
    var controls = new hitagi.Controls();
    controls.bind(38, 'up');
    controls.bind(40, 'down');

    // Define and register systems.
    var renderSystem = new hitagi.systems.PixiRenderSystem(stage);
    world.register(renderSystem);

    world.register(new hitagi.systems.VelocitySystem());

    var collisionSystem = new hitagi.systems.CollisionSystem();
    world.register(collisionSystem);

    var PaddleSystem = function () {
        this.update = function (entity, dt) {
            if (entity.has('paddle')) {
                // Slow down from friction.
                entity.c.velocity.yspeed *= entity.c.paddle.friction;
                if (Math.abs(entity.c.velocity.yspeed) < 0.01) {
                    entity.c.velocity.yspeed = 0;
                }

                // Stop from leaving screen.
                var projectedY = entity.c.position.y + entity.c.velocity.yspeed;
                if (projectedY - entity.c.paddle.height/2 < 0) {
                    entity.c.velocity.yspeed *= -1.4;
                }
                if (projectedY + entity.c.paddle.height/2 > levelHeight) {
                    entity.c.velocity.yspeed *= -1.4;
                }
            }
        };

        this.input = function (entity, input) {
            if (entity.has('paddle')) {
                switch (input) {
                    case 'down':
                        entity.c.velocity.yspeed += entity.c.paddle.speed;
                        break;
                    case 'up':
                        entity.c.velocity.yspeed -= entity.c.paddle.speed;
                        break;
                    default:
                        throw new Error('UnknownInput');
                        break;
                }
            }
        };
    };
    var paddleSystem = world.register(new PaddleSystem());

    var PlayerSystem = function (paddleSystem) {
        this.update = function (entity, dt) {
            if (entity.has('player') && entity.has('paddle')) {
                // Handle player input.
                if (controls.check('up')) {
                    paddleSystem.input(entity, 'up');
                }
                if (controls.check('down')) {
                    paddleSystem.input(entity, 'down');
                }
            }
        };
    };
    world.register(new PlayerSystem(paddleSystem));

    var AISystem = function () {
        var ai = null;

        this.build = function (entity) {
            if (entity.has('ai')) {
                ai = entity;
            }
        }

        this.update = function (entity) {
            if (!ai) {
                return;
            }

            if (entity.has('ai')) {
                var distance = Math.abs(entity.c.position.y - entity.c.ai.lastKnownY);

                if (distance > entity.c.ai.sensitivity + (Math.random()*20 - 10)) {
                    if (entity.c.position.y > entity.c.ai.lastKnownY) {
                        paddleSystem.input(entity, 'up');
                    } else {
                        paddleSystem.input(entity, 'down');
                    }
                }
            }
            if (entity.has('ball')) {
                ai.c.ai.lastKnownY = entity.c.position.y;
            }
        };
    };
    world.register(new AISystem());

    var BallSystem = function (collisionSystem) {
        this.update = function (entity, dt) {
            if (entity.has('ball')) {
                var x = entity.c.position.x;
                var y = entity.c.position.y;

                var test = collisionSystem.collide(entity, 'paddle', x, y);
                if (test.hit) {
                    entity.c.velocity.xspeed *= -1.01;

                    if (entity.c.position.y < test.entity.c.position.y) {
                        entity.c.velocity.yspeed +=
                            (entity.c.position.y - test.entity.c.position.y) / 50;
                    }
                    if (entity.c.position.y > test.entity.c.position.y) {
                        entity.c.velocity.yspeed -=
                            (entity.c.position.y - test.entity.c.position.y) / 50;
                    }
                }

                if ((entity.c.position.y < 0) || (entity.c.position.y > levelHeight)) {
                    entity.c.velocity.yspeed *= -1;
                }
            }
        };

        this.resetBall = function (ball) {
            ball.c.position.x = levelWidth/2;
            ball.c.position.y = levelHeight/2;
            ball.c.velocity.yspeed *= -0.95;
            ball.c.velocity.xspeed *= -0.95;
        };
    };
    var ballSystem = world.register(new BallSystem(collisionSystem));

    var ScoreSystem = function (ballSystem, renderSystem) {
        var scores = null;

        this.build = function (entity) {
            if (entity.has('scorecard')) {
                scores = entity;
            }
        }

        this.update = function (entity, dt) {
            if (!ball) {
                return;
            }

            if (entity.has('ball')) {
                if (entity.c.position.x < 0) {
                    ballSystem.resetBall(entity);
                    scores.c.scorecard.score2++;
                }

                if (entity.c.position.x > levelWidth) {
                    ballSystem.resetBall(entity);
                    scores.c.scorecard.score1++;
                }
            }

            if (entity.has('scorecard')) {
                renderSystem.setText(
                    entity,
                    entity.c.scorecard.score1 + ' - ' + entity.c.scorecard.score2
                );
            }
        };
    };
    world.register(new ScoreSystem(ballSystem, renderSystem));

    // Define prefabs.

    // Params: color, friction, height, width, speed, x, y
    var Paddle = function (params) {
        return new hitagi.Entity()
            .attach(new hitagi.components.Position({
                x: params.x,
                y: params.y
            }))
            .attach(new hitagi.components.Velocity({
                xspeed: 0,
                yspeed: 0
            }))
            .attach(new hitagi.components.Rectangle({
                color: params.color,
                x1: 0,
                y1: 0,
                x2: params.width,
                y2: params.height,
                offsetX: -params.width/2,
                offsetY: -params.height/2
            }))
            .attach({
                id: 'paddle',
                deps: ['velocity'],
                friction: params.friction,
                height: params.height,
                speed: params.speed,
                width: params.width
            })
            .attach(new hitagi.components.Collision({
                height: params.height,
                width: params.width
            }));
    };

    // Params: color, height, width, x, y, xspeed, yspeed
    var Ball = function (params) {
        return new hitagi.Entity()
            .attach(new hitagi.components.Position({
                x: params.x,
                y: params.y
            }))
            .attach(new hitagi.components.Velocity({
                xspeed: params.xspeed,
                yspeed: params.yspeed
            }))
            .attach(new hitagi.components.Rectangle({
                color: params.color,
                x1: 0,
                y1: 0,
                x2: params.width/2,
                y2: params.height/2,
                offsetX: -params.width/2,
                offsetY: -params.height/2
            }))
            .attach(new hitagi.components.Collision({
                height: params.width,
                width: params.height
            }))
            .attach({'id': 'ball'})
    };

    // Params: color, font, score1, score2, x, y
    var Score = function (params) {
        return new hitagi.Entity()
            .attach(new hitagi.components.Position({
                x: params.x,
                y: params.y
            }))
            .attach(new hitagi.components.Text({
                txt: '',
                options: {
                    font: params.font,
                    fill: params.color
                }
            }))
            .attach({
                id: 'scorecard',
                score1: params.score1,
                score2: params.score2
            })
    };

    // Add entities.
    var player = world.add(
        new Paddle({
            color:  0xFFFF00,
            friction: 0.9,
            height: 96,
            width: 4,
            speed: 1,
            x: 32,
            y: levelHeight/2
        })
        .attach({
            id: 'player',
            deps: ['paddle']
        })
    );

    var opponent = world.add(
        new Paddle({
            color:  0xFFFF00,
            friction: 0.9,
            height: 96,
            width: 4,
            speed: 1,
            x: levelWidth - 24,
            y: levelHeight/2
        })
        .attach({
            id: 'ai',
            deps: ['paddle'],
            lastKnownY: levelHeight/2,
            sensitivity: 60
        })
    );

    var ball = world.add(
        new Ball({
            color: 0xFFFFFF,
            height: 16,
            width: 16,
            x: levelWidth/2,
            y: levelHeight/2,
            xspeed: -5,
            yspeed: Math.random()*4 - 2
        })
    );

    var score = world.add(
        new Score({
            color: 'white',
            font: '16px monospace',
            score1: 0,
            score2: 0,
            x: levelWidth/2 - 16/2,
            y: 16
        })
    );

    // Setup game loop.
    requestAnimationFrame(animate);

    function animate() {
        // Update the world, using a fixed delta time.
        world.tick(1000);

        // Render the world.
        renderer.render(stage);

        // Next frame.
        requestAnimationFrame(animate);
    }

} ());
<|endoftext|>


<commit_before>var logger = require('mino-logger');
var ConfigServer = require('./config_server/ConfigServer');
var Path = require('../../common_classes/Path');

function MinoDbPermissions(options) {
	var plugin = this;

    plugin.path = options.path;
    if (!plugin.path) {
        throw "Plugin requires path to be specified in options";
    }

    plugin.username = options.username;
    if (!plugin.username) {
        throw "Plugin requires username to be specified in options";
    }

    plugin.name = options.name || "minodb_permissions";
    plugin.display_name = options.display_name || plugin.name;

    plugin.permission_path = plugin.path + "permissions/";
    plugin.group_path = plugin.path + "groups/";

    plugin.config_server = new ConfigServer();
}

MinoDbPermissions.prototype.get_config_server = function(){
    var plugin = this;
    return plugin.config_server.express_server;
};

MinoDbPermissions.prototype.info = function(){
    var plugin = this;

    return {
        name: plugin.name,
        display_name: plugin.display_name
    };
};

MinoDbPermissions.prototype.init = function(minodb, callback){
    var plugin = this;
    plugin.minodb = minodb;
    plugin.sdk = minodb.with_user(plugin.username);

    var waiting_for = 2;
    var finished_one = function() {
        waiting_for--;
        if (waiting_for === 0) {
            callback();
        }
    };

    plugin.create_folders(finished_one);
    plugin.create_types(finished_one);
};

MinoDbPermissions.prototype.create_folders = function(callback) {
    var plugin = this;

    var path = new Path();
    path.init(plugin.path);

    var parent_path = path.parent_path();

    plugin.sdk.save([{
        name: path.object_names[path.length-1],
        path: parent_path.toString(),
        folder: true
    }], function(err, res) {

        logger.debug(JSON.stringify(err, null, 4),res);
        plugin.sdk.save([{
            name: 'permissions',
            path: plugin.path,
            folder: true
        },{
            name: 'groups',
            path: plugin.path,
            folder: true
        }], function(err, res) {
            logger.debug(err,res);
            callback(err,res);
        });

    });
};

MinoDbPermissions.prototype.create_types = function(callback) {
    var plugin = this;

    plugin.minodb.save_type({
        "name": "minodb_group_permission",
        "display_name": "MinoDB Group Permission",
        "type": "object",
        "any": false,
        "fields": [
            {
                "name": "group",
                "display_name": "Group",
                "type": "text"
            },
            {
                "name": "permission",
                "display_name": "Permission",
                "type": "text"
            }
        ]
    }, function(err, res) {
        logger.debug(err, res);

        if (err) {
            callback(err);
            return;
        }

        plugin.minodb.save_type({
            "name": "minodb_identifier_permission",
            "display_name": "MinoDB Identifier Permission",
            "type": "object",
            "any": false,
            "fields": [
                {
                    "name": "identifier",
                    "display_name": "Identifier",
                    "type": "text"
                },
                {
                    "name": "permission",
                    "display_name": "Permission",
                    "type": "text"
                }
            ]
        }, function(err, res) {
            logger.debug(err, res);

            if (err) {
                callback(err);
                return;
            }

            plugin.minodb.save_type({
                "name": "minodb_identifier_group",
                "display_name": "MinoDB Identifier Group",
                "type": "object",
                "any": false,
                "fields": [
                    {
                        "name": "identifier",
                        "display_name": "Identifier",
                        "type": "text"
                    },
                    {
                        "name": "group",
                        "display_name": "Group",
                        "type": "text"
                    }
                ]
            }, function(err, res) {
                logger.debug(err, res);

                if (err) {
                    callback(err);
                    return;
                }

                callback();
            });
        });
    });
};

MinoDbPermissions.prototype.assign_permission_to_id = function(permission, id, callback) {
    var plugin = this;

    var escaped_id = plugin.encode_text(id);
    var escaped_permission = plugin.encode_text(permission);

    plugin.sdk.save([{
        name: escaped_permission,
        path: plugin.permission_path,
        folder: true
    }], function(err, res) {
        logger.debug(err, res);

        plugin.sdk.save([{
            name: "id:"+escaped_id,
            path: plugin.permission_path + escaped_permission + '/',
            minodb_identifier_permission: {
                permission: permission,
                identifier: id
            }
        }], function(err, res) {
            logger.debug(err,res);
            if (err) {
                callback(err);
            } else {
                callback(null, res.objects[0]);
            }
        });
    });
};

MinoDbPermissions.prototype.remove_permission_from_id = function(permission, id, callback) {
    var plugin = this;

    var escaped_id = plugin.encode_text(id);
    var escaped_permission = plugin.encode_text(permission);
    var path = plugin.permission_path + escaped_permission + '/id:'+escaped_id;

    plugin.sdk.delete([path], function(err, res) {
        if (err) {
            callback(err);
        } else {
            callback(null, res.objects[0]);
        }
    });
};

MinoDbPermissions.prototype.has_permission = function(permission, id, callback) {
    var plugin = this;

    plugin.has_permissions([permission], id, function(err, has_permissions) {
        logger.debug(err, has_permissions);
        if (err) {
            callback(err);
        } else {
            callback(null, has_permissions[0]);
        }
    });
};

MinoDbPermissions.prototype.has_permissions = function(permissions, id, callback) {
    var plugin = this;

    var permission_results = {};
    for (var i=0; i<permissions.length; i++) {
        var permission = permissions[i];
        permission_results[permission] = false;
    }

    var check_individual_permissions = function(callback) {
        plugin.sdk.call({
            "function": "search",
            "parameters": {
                "paths": [plugin.permission_path],
                "query": {
                    "minodb_identifier_permission.identifier": id,
                    "minodb_identifier_permission.permission": {
                        "$in": permissions
                    }
                },
                "include_subfolders": true
            }
        }, function(err, res) {
            logger.debug(err, res);
            if (res.objects) {
                for (var i=0; i<res.objects.length; i++) {
                    var permission = res.objects[i].minodb_identifier_permission.permission;
                    permission_results[permission] = true;
                }
            }
            callback();
        });
    };

    var check_group_permissions = function(callback) {
        plugin.sdk.call({
            "function": "search",
            "parameters": {
                "paths": [plugin.permission_path],
                "query": {
                    "minodb_group_permission.permission": {
                        "$in" : permissions
                    }
                },
                "include_subfolders": true
            }
        }, function(err, res) {

            if (err || !res.objects) {
                callback();
                return;
            }

            var groups = [];
            var group_permissions = {};
            for (var i=0; i< res.objects.length; i++) {
                var group = res.objects[i].minodb_group_permission.group;
                groups.push(group);
                if (!group_permissions[group]) {
                    group_permissions[group] = [];
                }
                group_permissions[group].push(res.objects[i].minodb_group_permission.permission);
            }
            logger.debug(groups);

            plugin.sdk.call({
                "function": "search",
                "parameters": {
                    "paths": [plugin.group_path],
                    "query": {
                        "minodb_identifier_group.identifier": id,
                        "minodb_identifier_group.group": {
                            "$in": groups
                        }
                    },
                    "include_subfolders": true
                }
            }, function(err, res) {
                logger.debug(res);
                if (err || !res.objects) {
                    callback();
                    return;
                }

                for (var i=0; i<res.objects.length; i++) {
                    var group = res.objects[i].minodb_identifier_group.group;
                    for (var j=0; j<group_permissions[group].length; j++) {
                        var permission  = group_permissions[group][j];
                        if (permission_results[permission] === false) {
                            permission_results[permission] = true;
                        }
                    }
                }

                callback();
            });

        });
    };

    check_individual_permissions(function() {
        check_group_permissions(function() {
            var result = [];
            for (var i=0; i<permissions.length; i++) {
                var permission = permissions[i];
                result.push(permission_results[permission]);
            }
            callback(null, result);
        });
    });
};

MinoDbPermissions.prototype.assign_group_to_id = function(group, id, callback) {
    var plugin = this;

    var escaped_id = plugin.encode_text(id);
    var escaped_group = plugin.encode_text(group);

    plugin.sdk.save([{
        name: escaped_group,
        path: plugin.group_path,
        folder: true
    }], function(err, res) {
        logger.debug(err, res);

        plugin.sdk.save([{
            name: "id:"+escaped_id,
            path: plugin.group_path + escaped_group + '/',
            minodb_identifier_group: {
                group: group,
                identifier: id
            }
        }], function(err, res) {
            logger.debug(err,res);
            if (err) {
                callback(err);
            } else {
                callback(null, res.objects[0]);
            }
        });
    });
};

MinoDbPermissions.prototype.remove_group_from_id = function(group, id, callback) {
    var plugin = this;

    var escaped_id = plugin.encode_text(id);
    var escaped_group = plugin.encode_text(group);
    var path = plugin.group_path + escaped_group + '/id:'+escaped_id;

    plugin.sdk.delete([path], function(err, res) {
        if (err) {
            callback(err);
        } else {
            callback(null, res.objects[0]);
        }
    });
};

MinoDbPermissions.prototype.assign_permission_to_group = function(permission, group, callback) {
    var plugin = this;

    var escaped_group = plugin.encode_text(group);
    var escaped_permission = plugin.encode_text(permission);

    plugin.sdk.save([{
        name: escaped_permission,
        path: plugin.permission_path,
        folder: true
    }], function(err, res) {
        logger.debug(err, res);

        plugin.sdk.save([{
            name: "group:"+escaped_group,
            path: plugin.permission_path + escaped_permission + '/',
            minodb_group_permission: {
                permission: permission,
                group: group
            }
        }], function(err, res) {
            logger.debug(err,res);
            if (err) {
                callback(err);
            } else {
                callback(null, res.objects[0]);
            }
        });
    });
};

MinoDbPermissions.prototype.remove_permission_from_group = function(permission, group, callback) {
    var plugin = this;

    var escaped_permission = plugin.encode_text(permission);
    var escaped_group = plugin.encode_text(group);
    var path = plugin.permission_path + escaped_permission + '/group:'+escaped_group;

    plugin.sdk.delete([path], function(err, res) {
        if (err) {
            callback(err);
        } else {
            callback(null, res.objects[0]);
        }
    });
};

MinoDbPermissions.prototype.encode_text = function(text) {
    return encodeURIComponent(text);
};

MinoDbPermissions.prototype.decode_text = function(text) {
    return decodeURIComponent(text);
};

MinoDbPermissions.prototype.get_available_groups = function(callback) {
    var plugin = this;
    plugin.sdk.call({
        "function": "search",
        "parameters": {
            "paths": [plugin.permission_path],
            "include_subfolders": true,
            "query": {
                "minodb_group_permission": {
                    "$exists": true
                }
            }
        }
    }, function(err, res) {
        logger.debug(err, res);
        var result = [];
        for (var i=0; i<res.objects.length; i++) {
            var group = res.objects[i].minodb_group_permission.group;
            result.push(group);
        }

        callback(null, result);

    });
};

MinoDbPermissions.prototype.get_ids_from_group = function(group, callback) {
    var plugin = this;
    plugin.get_ids_from_groups([group], callback);
};

MinoDbPermissions.prototype.get_ids_from_groups = function(groups, callback) {
    var plugin = this;
    plugin.sdk.call({
        "function": "search",
        "parameters": {
            "paths": [plugin.group_path],
            "include_subfolders": true,
            "query": {
                "minodb_identifier_group.group": {
                    "$in": groups
                }
            }
        }
    }, function(err, res) {
        logger.debug(err, res);
        var result = [];
        for (var i=0; i<res.objects.length; i++) {
            var id = res.objects[i].minodb_identifier_group.identifier;
            if (result.indexOf(id) === -1) {
                result.push(id);
            }
        }

        callback(null, result);

    });
};

MinoDbPermissions.prototype.get_groups_from_perm = function(perm, callback) {
    var plugin = this;
    plugin.sdk.call({
        "function": "search",
        "parameters": {
            "paths": [plugin.permission_path + perm + "/"],
            "query": {
                "minodb_group_permission": {
                    "$exists": true
                }
            }
        }
    }, function(err, res) {
        logger.debug(err, res);

        var result = [];
        for (var i=0; i<res.objects.length; i++) {
            var group = res.objects[i].minodb_group_permission.group;
            result.push(group);
        }

        callback(null, result);

    });
};

MinoDbPermissions.prototype.get_ids_from_perm = function(perm, callback) {
    var plugin = this;
    plugin.sdk.call({
        "function": "search",
        "parameters": {
            "paths": [plugin.permission_path + perm + "/"],
            "query": {
                "minodb_identifier_permission": {
                    "$exists": true
                }
            }
        }
    }, function(err, res) {
        logger.debug(err, res);
        var result = [];
        for (var i=0; i<res.objects.length; i++) {
            var id = res.objects[i].minodb_identifier_permission.identifier;
            result.push(id);
        }

        plugin.get_groups_from_perm(perm, function(err, groups) {
            logger.debug(err, groups);
            plugin.get_ids_from_groups(groups, function(err, ids) {
                logger.debug(err, ids);
                for (var i=0; i<ids.length; i++) {
                    if (result.indexOf(ids[i]) === -1) {
                        result.push(ids[i]);
                    }
                }

                callback(null, result);

            });
        });
    });
};

module.exports = MinoDbPermissions;<commit_msg>Refactored MinoDbPermission assign and remove calls<commit_after>var logger = require('mino-logger');
var ConfigServer = require('./config_server/ConfigServer');
var Path = require('../../common_classes/Path');

var GROUP_PERMISSION_TYPE = 'minodb_group_permission';
var IDENTIFIER_GROUP_TYPE = 'minodb_identifier_group';
var IDENTIFIER_PERMISSION_TYPE = 'minodb_identifier_permission';

function MinoDbPermissions(options) {
	var plugin = this;

    plugin.path = options.path;
    if (!plugin.path) {
        throw "Plugin requires path to be specified in options";
    }

    plugin.username = options.username;
    if (!plugin.username) {
        throw "Plugin requires username to be specified in options";
    }

    plugin.name = options.name || "minodb_permissions";
    plugin.display_name = options.display_name || plugin.name;

    plugin.permission_path = plugin.path + "permissions/";
    plugin.group_path = plugin.path + "groups/";

    plugin.config_server = new ConfigServer();
}

MinoDbPermissions.prototype.get_config_server = function(){
    var plugin = this;
    return plugin.config_server.express_server;
};

MinoDbPermissions.prototype.info = function(){
    var plugin = this;

    return {
        name: plugin.name,
        display_name: plugin.display_name
    };
};

MinoDbPermissions.prototype.init = function(minodb, callback){
    var plugin = this;
    plugin.minodb = minodb;
    plugin.sdk = minodb.with_user(plugin.username);

    var waiting_for = 2;
    var finished_one = function() {
        waiting_for--;
        if (waiting_for === 0) {
            callback();
        }
    };

    plugin.create_folders(finished_one);
    plugin.create_types(finished_one);
};

MinoDbPermissions.prototype.create_folders = function(callback) {
    var plugin = this;

    var path = new Path();
    path.init(plugin.path);

    var parent_path = path.parent_path();

    plugin.sdk.save([{
        name: path.object_names[path.length-1],
        path: parent_path.toString(),
        folder: true
    }], function(err, res) {

        logger.debug(JSON.stringify(err, null, 4),res);
        plugin.sdk.save([{
            name: 'permissions',
            path: plugin.path,
            folder: true
        },{
            name: 'groups',
            path: plugin.path,
            folder: true
        }], function(err, res) {
            logger.debug(err,res);
            callback(err,res);
        });

    });
};

MinoDbPermissions.prototype.create_types = function(callback) {
    var plugin = this;

    plugin.minodb.save_type({
        "name": GROUP_PERMISSION_TYPE,
        "display_name": "MinoDB Group Permission",
        "type": "object",
        "any": false,
        "fields": [
            {
                "name": "group",
                "display_name": "Group",
                "type": "text"
            },
            {
                "name": "permission",
                "display_name": "Permission",
                "type": "text"
            }
        ]
    }, function(err, res) {
        logger.debug(err, res);

        if (err) {
            callback(err);
            return;
        }

        plugin.minodb.save_type({
            "name": IDENTIFIER_PERMISSION_TYPE,
            "display_name": "MinoDB Identifier Permission",
            "type": "object",
            "any": false,
            "fields": [
                {
                    "name": "identifier",
                    "display_name": "Identifier",
                    "type": "text"
                },
                {
                    "name": "permission",
                    "display_name": "Permission",
                    "type": "text"
                }
            ]
        }, function(err, res) {
            logger.debug(err, res);

            if (err) {
                callback(err);
                return;
            }

            plugin.minodb.save_type({
                "name": IDENTIFIER_GROUP_TYPE,
                "display_name": "MinoDB Identifier Group",
                "type": "object",
                "any": false,
                "fields": [
                    {
                        "name": "identifier",
                        "display_name": "Identifier",
                        "type": "text"
                    },
                    {
                        "name": "group",
                        "display_name": "Group",
                        "type": "text"
                    }
                ]
            }, function(err, res) {
                logger.debug(err, res);

                if (err) {
                    callback(err);
                    return;
                }

                callback();
            });
        });
    });
};

MinoDbPermissions.prototype.assign_item = function(name, parent, type, callback) {
    var plugin = this;

    var escaped_name = plugin.get_item_name_from_type(type, name);
    var escaped_parent = plugin.encode_text(parent);
    var root_path = plugin.get_root_path_from_type(type);

    var save_object = {
        name: escaped_name,
        path: root_path + escaped_parent + '/'
    };

    if (type === GROUP_PERMISSION_TYPE) {
        save_object[type] = {
            group: name,
            permission: parent
        };
    } else if (type === IDENTIFIER_GROUP_TYPE) {
        save_object[type] = {
            identifier: name,
            group: parent
        };
    } else if (type === IDENTIFIER_PERMISSION_TYPE) {
        save_object[type] = {
            identifier: name,
            permission: parent
        };
    }

    logger.debug(save_object);

    plugin.sdk.save([{
        name: escaped_parent,
        path: root_path,
        folder: true
    }], function(err, res) {
        logger.debug(err, res);

        plugin.sdk.save([save_object], function(err, res) {
            logger.debug(err,res);
            if (err) {
                callback(err);
            } else {
                callback(null, res.objects[0]);
            }
        });
    });
};

MinoDbPermissions.prototype.remove_item = function(name, parent, type, callback) {
    var plugin = this;

    var escaped_name = plugin.get_item_name_from_type(type, name);
    var escaped_parent = plugin.encode_text(parent);
    var root_path = plugin.get_root_path_from_type(type);

    var path = root_path + escaped_parent + '/' + escaped_name;
    logger.debug(path);
    plugin.sdk.delete([path], function(err, res) {
        if (err) {
            callback(err);
        } else {
            callback(null, res.objects[0]);
        }
    });
};

MinoDbPermissions.prototype.assign_permission_to_id = function(permission, id, callback) {
    var plugin = this;
    plugin.assign_item(id, permission, IDENTIFIER_PERMISSION_TYPE, callback);
};

MinoDbPermissions.prototype.remove_permission_from_id = function(permission, id, callback) {
    var plugin = this;
    plugin.remove_item(id, permission, IDENTIFIER_PERMISSION_TYPE, callback);
};

MinoDbPermissions.prototype.assign_group_to_id = function(group, id, callback) {
    var plugin = this;
    plugin.assign_item(id, group, IDENTIFIER_GROUP_TYPE, callback);
};

MinoDbPermissions.prototype.remove_group_from_id = function(group, id, callback) {
    var plugin = this;
    plugin.remove_item(id, group, IDENTIFIER_GROUP_TYPE, callback);
};

MinoDbPermissions.prototype.assign_permission_to_group = function(permission, group, callback) {
    var plugin = this;
    plugin.assign_item(group, permission, GROUP_PERMISSION_TYPE, callback);
};

MinoDbPermissions.prototype.remove_permission_from_group = function(permission, group, callback) {
    var plugin = this;
    plugin.remove_item(group, permission, GROUP_PERMISSION_TYPE, callback);
};

MinoDbPermissions.prototype.has_permission = function(permission, id, callback) {
    var plugin = this;

    plugin.has_permissions([permission], id, function(err, has_permissions) {
        logger.debug(err, has_permissions);
        if (err) {
            callback(err);
        } else {
            callback(null, has_permissions[0]);
        }
    });
};

MinoDbPermissions.prototype.has_permissions = function(permissions, id, callback) {
    var plugin = this;

    var permission_results = {};
    for (var i=0; i<permissions.length; i++) {
        var permission = permissions[i];
        permission_results[permission] = false;
    }

    var check_individual_permissions = function(callback) {
        plugin.sdk.call({
            "function": "search",
            "parameters": {
                "paths": [plugin.permission_path],
                "query": {
                    "minodb_identifier_permission.identifier": id,
                    "minodb_identifier_permission.permission": {
                        "$in": permissions
                    }
                },
                "include_subfolders": true
            }
        }, function(err, res) {
            logger.debug(err, res);
            if (res.objects) {
                for (var i=0; i<res.objects.length; i++) {
                    var permission = res.objects[i].minodb_identifier_permission.permission;
                    permission_results[permission] = true;
                }
            }
            callback();
        });
    };

    var check_group_permissions = function(callback) {
        plugin.sdk.call({
            "function": "search",
            "parameters": {
                "paths": [plugin.permission_path],
                "query": {
                    "minodb_group_permission.permission": {
                        "$in" : permissions
                    }
                },
                "include_subfolders": true
            }
        }, function(err, res) {

            if (err || !res.objects) {
                callback();
                return;
            }

            var groups = [];
            var group_permissions = {};
            for (var i=0; i< res.objects.length; i++) {
                var group = res.objects[i].minodb_group_permission.group;
                groups.push(group);
                if (!group_permissions[group]) {
                    group_permissions[group] = [];
                }
                group_permissions[group].push(res.objects[i].minodb_group_permission.permission);
            }
            logger.debug(groups);

            plugin.sdk.call({
                "function": "search",
                "parameters": {
                    "paths": [plugin.group_path],
                    "query": {
                        "minodb_identifier_group.identifier": id,
                        "minodb_identifier_group.group": {
                            "$in": groups
                        }
                    },
                    "include_subfolders": true
                }
            }, function(err, res) {
                logger.debug(res);
                if (err || !res.objects) {
                    callback();
                    return;
                }

                for (var i=0; i<res.objects.length; i++) {
                    var group = res.objects[i].minodb_identifier_group.group;
                    for (var j=0; j<group_permissions[group].length; j++) {
                        var permission  = group_permissions[group][j];
                        if (permission_results[permission] === false) {
                            permission_results[permission] = true;
                        }
                    }
                }

                callback();
            });

        });
    };

    check_individual_permissions(function() {
        check_group_permissions(function() {
            var result = [];
            for (var i=0; i<permissions.length; i++) {
                var permission = permissions[i];
                result.push(permission_results[permission]);
            }
            callback(null, result);
        });
    });
};

MinoDbPermissions.prototype.get_root_path_from_type = function(type) {
    var plugin = this;
    if (type === GROUP_PERMISSION_TYPE) {
        return plugin.permission_path;
    } else if (type === IDENTIFIER_GROUP_TYPE) {
        return plugin.group_path;
    } else if (type === IDENTIFIER_PERMISSION_TYPE) {
        return plugin.permission_path;
    }
};

MinoDbPermissions.prototype.get_item_name_from_type = function() {
    var plugin = this;
    var type = arguments[0];
    var name = plugin.encode_text(arguments[1]);

    if (type === GROUP_PERMISSION_TYPE) {
        return 'group:'+name;
    } else if (type === IDENTIFIER_GROUP_TYPE) {
        return 'id:'+name;
    } else if (type === IDENTIFIER_PERMISSION_TYPE) {
        return 'id:'+name;
    }
};

MinoDbPermissions.prototype.encode_text = function(text) {
    return encodeURIComponent(text);
};

MinoDbPermissions.prototype.decode_text = function(text) {
    return decodeURIComponent(text);
};

MinoDbPermissions.prototype.get_available_groups = function(callback) {
    var plugin = this;
    plugin.sdk.call({
        "function": "search",
        "parameters": {
            "paths": [plugin.permission_path],
            "include_subfolders": true,
            "query": {
                "minodb_group_permission": {
                    "$exists": true
                }
            }
        }
    }, function(err, res) {
        logger.debug(err, res);
        var result = [];
        for (var i=0; i<res.objects.length; i++) {
            var group = res.objects[i].minodb_group_permission.group;
            result.push(group);
        }

        callback(null, result);

    });
};

MinoDbPermissions.prototype.get_ids_from_group = function(group, callback) {
    var plugin = this;
    plugin.get_ids_from_groups([group], callback);
};

MinoDbPermissions.prototype.get_ids_from_groups = function(groups, callback) {
    var plugin = this;
    plugin.sdk.call({
        "function": "search",
        "parameters": {
            "paths": [plugin.group_path],
            "include_subfolders": true,
            "query": {
                "minodb_identifier_group.group": {
                    "$in": groups
                }
            }
        }
    }, function(err, res) {
        logger.debug(err, res);
        var result = [];
        for (var i=0; i<res.objects.length; i++) {
            var id = res.objects[i].minodb_identifier_group.identifier;
            if (result.indexOf(id) === -1) {
                result.push(id);
            }
        }

        callback(null, result);

    });
};

MinoDbPermissions.prototype.get_groups_from_perm = function(perm, callback) {
    var plugin = this;
    plugin.sdk.call({
        "function": "search",
        "parameters": {
            "paths": [plugin.permission_path + perm + "/"],
            "query": {
                "minodb_group_permission": {
                    "$exists": true
                }
            }
        }
    }, function(err, res) {
        logger.debug(err, res);

        var result = [];
        for (var i=0; i<res.objects.length; i++) {
            var group = res.objects[i].minodb_group_permission.group;
            result.push(group);
        }

        callback(null, result);

    });
};

MinoDbPermissions.prototype.get_ids_from_perm = function(perm, callback) {
    var plugin = this;
    plugin.sdk.call({
        "function": "search",
        "parameters": {
            "paths": [plugin.permission_path + perm + "/"],
            "query": {
                "minodb_identifier_permission": {
                    "$exists": true
                }
            }
        }
    }, function(err, res) {
        logger.debug(err, res);
        var result = [];
        for (var i=0; i<res.objects.length; i++) {
            var id = res.objects[i].minodb_identifier_permission.identifier;
            result.push(id);
        }

        plugin.get_groups_from_perm(perm, function(err, groups) {
            logger.debug(err, groups);
            plugin.get_ids_from_groups(groups, function(err, ids) {
                logger.debug(err, ids);
                for (var i=0; i<ids.length; i++) {
                    if (result.indexOf(ids[i]) === -1) {
                        result.push(ids[i]);
                    }
                }

                callback(null, result);

            });
        });
    });
};

module.exports = MinoDbPermissions;<|endoftext|>


<commit_before>define('app/controllers/machine_edit', ['ember'],
    //
    //  Machine Edit Controller
    //
    //  @returns Class
    //
    function () {

        'use strict';

        return Ember.Object.extend(Ember.Evented, {

            //
            //
            //  Properties
            //
            //

            machine: null,
            newName: '',
            renamingMachine: false,

            //
            //
            //  Methods
            //
            //

            open: function (machine) {
                this.setProperties({
                    machine: machine,
                    newName: machine.name
                });
                this.view.open();
            },

            close: function () {
                this.view.close();
            },

            save: function () {
                var that = this;
                this.set('renamingMachine', true);
                Mist.ajax.POST('/backends/' + this.machine.backend.id + '/machines/' + this.machine.id, {
                    'action' : 'rename',
                    'name': this.newName
                }).success(function() {
                    that._renameMachine();
                    that.close();
                }).error(function() {
                    Mist.notificationController.notify('Failed to rename machine');
                }).complete(function(success) {
                    that.set('renamingMachine', false);
                });
            },

            _renameMachine: function (machine, name) {
                Ember.run(this, function () {
                    this.get('machine', this.get('newName'));
                    this.trigger('onMachineRename', {
                        object: this.get('machine')
                    });
                });
            }
        });
    }
);
<commit_msg>Fix renaming<commit_after>define('app/controllers/machine_edit', ['ember'],
    //
    //  Machine Edit Controller
    //
    //  @returns Class
    //
    function () {

        'use strict';

        return Ember.Object.extend(Ember.Evented, {

            //
            //
            //  Properties
            //
            //

            machine: null,
            newName: '',
            renamingMachine: false,

            //
            //
            //  Methods
            //
            //

            open: function (machine) {
                this.setProperties({
                    machine: machine,
                    newName: machine.name
                });
                this.view.open();
            },

            close: function () {
                this.view.close();
            },

            save: function () {
                var that = this;
                this.set('renamingMachine', true);
                Mist.ajax.POST('/backends/' + this.machine.backend.id + '/machines/' + this.machine.id, {
                    'action' : 'rename',
                    'name': this.newName
                }).success(function() {
                    that._renameMachine();
                    that.close();
                }).error(function() {
                    Mist.notificationController.notify('Failed to rename machine');
                }).complete(function(success) {
                    that.set('renamingMachine', false);
                });
            },

            _renameMachine: function (machine, name) {
                Ember.run(this, function () {
                    this.get('machine').set('name', this.get('newName'));
                    this.trigger('onMachineRename', {
                        object: this.get('machine')
                    });
                });
            }
        });
    }
);
<|endoftext|>


<commit_before>var expect       = require("chai").expect;
var Cloudevent   = require("../index.js");
var nock         = require("nock");

const type        = "com.github.pull.create";
const source      = "urn:event:from:myapi/resourse/123";
const webhook     = "https://cloudevents.io/webhook";
const contentType = "application/cloudevents+json; charset=utf-8";
const now         = new Date();
const schemaurl   = "http://cloudevents.io/schema.json"

const ceContentType = "application/json";

const data = {
  foo: "bar"
};

const Structured01 = Cloudevent.bindings["http-structured0.1"];
const Binary01     = Cloudevent.bindings["http-binary0.1"];

var cloudevent =
  new Cloudevent()
    .type(type)
    .source(source)
    .contenttype(ceContentType)
    .time(now)
    .schemaurl(schemaurl)
    .data(data);

cloudevent.eventTypeVersion("1.0.0");

var httpcfg = {
  method : "POST",
  url    : webhook + "/json"
};

var httpstructured01 = new Structured01(httpcfg);
var httpbinary01     = new Binary01(httpcfg);

describe("HTTP Transport Binding - Version 0.1", () => {
  beforeEach(() => {
    // Mocking the webhook
    nock(webhook)
      .post("/json")
      .reply(201, {status: "accepted"});
  });

  describe("Structured", () => {
    describe("JSON Format", () => {
      it("requires '" + contentType + "' Content-Type in the header", () => {
        return httpstructured01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers["Content-Type"])
              .to.equal(contentType);
          });
      });

      it("the request payload should be correct", () => {
        return httpstructured01.emit(cloudevent)
          .then((response) => {
            expect(JSON.parse(response.config.data))
              .to.deep.equal(cloudevent.format());
          });
      });
    });
  });

  describe("Binary", () => {
    describe("JSON Format", () => {
      it("requires '" + cloudevent.getContenttype() + "' Content-Type in the header", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers["Content-Type"])
              .to.equal(cloudevent.getContenttype());
          });
      });

      it("the request payload should be correct", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(JSON.parse(response.config.data))
              .to.deep.equal(cloudevent.getData());
          });
      });

      it("HTTP Header contains 'CE-EventType'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-EventType");
          });
      });
      it("HTTP Header contains 'CE-EventTypeVersion'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-EventTypeVersion");
          });
      });
      it("HTTP Header contains 'CE-CloudEventsVersion'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-CloudEventsVersion");
          });
      });
      it("HTTP Header contains 'CE-Source'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-Source");
          });
      });
      it("HTTP Header contains 'CE-EventID'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-EventID");
          });
      });
      it("HTTP Header contains 'CE-EventTime'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-EventTime");
          });
      });
      it("HTTP Header contains 'CE-SchemaURL'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-SchemaURL");
          });
      });
    });
  });
});
<commit_msg>Semicolon<commit_after>var expect       = require("chai").expect;
var Cloudevent   = require("../index.js");
var nock         = require("nock");

const type        = "com.github.pull.create";
const source      = "urn:event:from:myapi/resourse/123";
const webhook     = "https://cloudevents.io/webhook";
const contentType = "application/cloudevents+json; charset=utf-8";
const now         = new Date();
const schemaurl   = "http://cloudevents.io/schema.json";

const ceContentType = "application/json";

const data = {
  foo: "bar"
};

const Structured01 = Cloudevent.bindings["http-structured0.1"];
const Binary01     = Cloudevent.bindings["http-binary0.1"];

var cloudevent =
  new Cloudevent()
    .type(type)
    .source(source)
    .contenttype(ceContentType)
    .time(now)
    .schemaurl(schemaurl)
    .data(data);

cloudevent.eventTypeVersion("1.0.0");

var httpcfg = {
  method : "POST",
  url    : webhook + "/json"
};

var httpstructured01 = new Structured01(httpcfg);
var httpbinary01     = new Binary01(httpcfg);

describe("HTTP Transport Binding - Version 0.1", () => {
  beforeEach(() => {
    // Mocking the webhook
    nock(webhook)
      .post("/json")
      .reply(201, {status: "accepted"});
  });

  describe("Structured", () => {
    describe("JSON Format", () => {
      it("requires '" + contentType + "' Content-Type in the header", () => {
        return httpstructured01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers["Content-Type"])
              .to.equal(contentType);
          });
      });

      it("the request payload should be correct", () => {
        return httpstructured01.emit(cloudevent)
          .then((response) => {
            expect(JSON.parse(response.config.data))
              .to.deep.equal(cloudevent.format());
          });
      });
    });
  });

  describe("Binary", () => {
    describe("JSON Format", () => {
      it("requires '" + cloudevent.getContenttype() + "' Content-Type in the header", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers["Content-Type"])
              .to.equal(cloudevent.getContenttype());
          });
      });

      it("the request payload should be correct", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(JSON.parse(response.config.data))
              .to.deep.equal(cloudevent.getData());
          });
      });

      it("HTTP Header contains 'CE-EventType'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-EventType");
          });
      });
      it("HTTP Header contains 'CE-EventTypeVersion'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-EventTypeVersion");
          });
      });
      it("HTTP Header contains 'CE-CloudEventsVersion'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-CloudEventsVersion");
          });
      });
      it("HTTP Header contains 'CE-Source'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-Source");
          });
      });
      it("HTTP Header contains 'CE-EventID'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-EventID");
          });
      });
      it("HTTP Header contains 'CE-EventTime'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-EventTime");
          });
      });
      it("HTTP Header contains 'CE-SchemaURL'", () => {
        return httpbinary01.emit(cloudevent)
          .then((response) => {
            expect(response.config.headers)
              .to.have.property("CE-SchemaURL");
          });
      });
    });
  });
});
<|endoftext|>


<commit_before>import React  from 'react'
import { Query } from "react-apollo"
import gql from "graphql-tag"
import Browse from '../components/Browse'

const GET_PHOTOS = gql`
  query Photos($filters: String) {
    allPhotos(multiFilter: $filters) {
      edges {
        node {
          id
          location
        }
      }
    }
  }
`

export default class BrowseContainer extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      expanded: true,
    }
  }

  onExpandCollapse = () => {
    this.setState({expanded: !this.state.expanded})
  }

  render = () => {
    const params = new URLSearchParams(this.props.search)
    const mode = params.get('mode') ? params.get('mode').toUpperCase() : 'TIMELINE'
    const filtersStr = this.props.selectedFilters.map((filter) => (
      filter.id
    )).join(',')

    return (
      <Query query={GET_PHOTOS} variables={{filters: filtersStr}}>
        {({ loading, error, data }) => {
          let photoSections = []
          let photos = []
          if (!loading && !error) {
            photos = data.allPhotos.edges.map((photo) => (
              {
                id: photo.node.id,
                thumbnail: `/thumbnails/256x256_cover_q50/${photo.node.id}/`,
                location: photo.node.location ? [photo.node.location.split(',')[0], photo.node.location.split(',')[1]] : null,
              }
            ))
          }

          let section = {
            id: 12345,
            title: null,
            segments: [
              {
                numPhotos: photos.length,
                photos: photos,
              }
            ]
          }
          photoSections.push(section)

          return <Browse
            selectedFilters={this.props.selectedFilters}
            mode={mode}
            loading={loading}
            error={error}
            photoSections={photoSections}
            onFilterToggle={this.props.onFilterToggle}
            onClearFilters={this.props.onClearFilters}
            onExpandCollapse={this.onExpandCollapse}
            expanded={this.state.expanded} />
        }}
      </Query>
    )
  }
}
<commit_msg>Fixes map view<commit_after>import React  from 'react'
import { Query } from "react-apollo"
import gql from "graphql-tag"
import Browse from '../components/Browse'

const GET_PHOTOS = gql`
  query Photos($filters: String) {
    allPhotos(multiFilter: $filters) {
      edges {
        node {
          id
          location
        }
      }
    }
  }
`

export default class BrowseContainer extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      expanded: true,
    }
  }

  onExpandCollapse = () => {
    this.setState({expanded: !this.state.expanded})
  }

  render = () => {
    const params = new URLSearchParams(window.location.search)
    const mode = params.get('mode') ? params.get('mode').toUpperCase() : 'TIMELINE'
    const filtersStr = this.props.selectedFilters.map((filter) => (
      filter.id
    )).join(',')

    return (
      <Query query={GET_PHOTOS} variables={{filters: filtersStr}}>
        {({ loading, error, data }) => {
          let photoSections = []
          let photos = []
          if (!loading && !error) {
            photos = data.allPhotos.edges.map((photo) => (
              {
                id: photo.node.id,
                thumbnail: `/thumbnails/256x256_cover_q50/${photo.node.id}/`,
                location: photo.node.location ? [photo.node.location.split(',')[0], photo.node.location.split(',')[1]] : null,
              }
            ))
          }

          let section = {
            id: 12345,
            title: null,
            segments: [
              {
                numPhotos: photos.length,
                photos: photos,
              }
            ]
          }
          photoSections.push(section)

          return <Browse
            selectedFilters={this.props.selectedFilters}
            mode={mode}
            loading={loading}
            error={error}
            photoSections={photoSections}
            onFilterToggle={this.props.onFilterToggle}
            onClearFilters={this.props.onClearFilters}
            onExpandCollapse={this.onExpandCollapse}
            expanded={this.state.expanded} />
        }}
      </Query>
    )
  }
}
<|endoftext|>


<commit_before>const Router = require('koa-router')

const router = new Router({
  prefix: '/auth'
})

router.get('/', async (ctx) => {
  ctx.body = 'Hello World'
})

exports.router = router
<commit_msg>register API<commit_after>const Router = require('koa-router')
const AuthUtil = require('../thulib/auth').AuthUtil

const router = new Router({
  prefix: '/students'
})

router.post('/register', async ctx => {
  const {username, password} = ctx.request.fields || {}
  if (!username || !password) {
    ctx.throw(400, 'Missing Arguments')
  }

  const result = await AuthUtil.auth(username, password)

  ctx.body = {
    username: username
  }

  if (result) {
    ctx.body.message = 'Success'
    ctx.body.information = await AuthUtil.getUserInfo(username, password)

    // TODO: save user
  } else {
    ctx.body.message = 'Failure'
  }
})

exports.router = router
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PTT from './PTT';
import HelpButtons from './HelpButtons';
import LoadingIcon from './LoadingIcon';
import Header from './Header';
import TimerDashboard from './Timer/TimerDashboard';
import DiscoverWpApi from './DiscoverWpApi';
import './css/App.css';

/**
 * Application loader.
 */
class App extends Component {
  constructor() {
    super();

    this.state = {
      view: <LoadingIcon
        message="Locating your info.."/>
    }
  }

  render() {
    return (

          {this.state.view}
          <HelpButtons onReset={this._showInit.bind(this)} />

    );
  }

  // before the component loads
  componentWillMount() {
    PTT._init();
  }

  // once the component has loaded
  componentDidMount() {
    this._showInit();
  }

  // show the initial view,
  // used by componentDidMount and
  // help buttons - on reset.
  _showInit() {
    // DiscoverWpApi will check if
    // user is authenticated
    const view = <DiscoverWpApi
      onDiscovered={this._showDashboard.bind(this)} />;

    this.setState({ view });
  }

  // show the dashboard.
  _showDashboard() {
    const view = <TimerDashboard />;

    this.setState({ view });
  }
}

export default App;
<commit_msg>remove help buttons from app.js<commit_after>import React, { Component } from 'react';
import PTT from './PTT';
import LoadingIcon from './LoadingIcon';
import Header from './Header';
import TimerDashboard from './Timer/TimerDashboard';
import DiscoverWpApi from './DiscoverWpApi';
import './css/App.css';

/**
 * Application loader.
 */
class App extends Component {
  constructor() {
    super();

    this.state = {
      view: <LoadingIcon
        message="Locating your info.."/>
    }
  }

  render() {
    return (

          {this.state.view}

    );
  }

  // before the component loads
  componentWillMount() {
    PTT._init();
  }

  // once the component has loaded
  componentDidMount() {
    this._showInit();
  }

  // show the initial view,
  // used by componentDidMount and
  // help buttons - on reset.
  _showInit() {
    // DiscoverWpApi will check if
    // user is authenticated
    const view = <DiscoverWpApi
      onDiscovered={this._showDashboard.bind(this)} />;

    this.setState({ view });
  }

  // show the dashboard.
  _showDashboard() {
    const view = <TimerDashboard />;

    this.setState({ view });
  }
}

export default App;
<|endoftext|>