<commit_before>TRAFFICSIM_APP.WorldController = function (gameplayScene) {
    var self = this;

    var gameplayScene = gameplayScene;
    var map;
    var scene;
    var camera;
    var keyboardButtonsPressedOnLastFrame = [];
    var math = TRAFFICSIM_APP.utils.math;

    var logger = TRAFFICSIM_APP.utils.logger;

    var roadController;
    var vehicleController;

    var currentCameraPositionId = 1;
    var cameraTarget = null;
    var lastAutomaticCameraPositionSwitch = 0;
    var switchCameraPositionAutomatically = false;

    function constructor() {
        map = new TRAFFICSIM_APP.game.Map();
        roadController = new TRAFFICSIM_APP.game.RoadController(self);
        vehicleController = new TRAFFICSIM_APP.game.VehicleController(self);
        keyboard = new THREEx.KeyboardState();

        initialize();
    }

    function initialize() {
        initializeScene();
        initializeCamera();
        initializeWorld();
    }

    function initializeScene() {
        scene = new THREE.Scene();
    }

    function initializeCamera() {
        camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
        adjustCameraPosition(1);
    }

    function resolveRoadType(lineIndex, columnIndex) {
        // Crossroads
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex - 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex + 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex + 1))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex - 1))) {
            return 'I';
        }

        // Vertical road
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex - 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex + 1, columnIndex))) {
            return 'Y';
        }

        // Horizontal road
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex - 1))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex + 1))) {
            return 'T';
        }

        // Up right
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex - 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex + 1))) {
            return 'E';
        }

        // Up left
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex - 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex - 1))) {
            return 'Q';
        }

        // Down right
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex + 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex + 1))) {
            return 'R';
        }

        // Down left
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex + 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex - 1))) {
            return 'W';
        }

        return '';
    }

    function initializeMap() {
        var mapLines = map.getMapAsArray();
        for (var lineIndex = 0; lineIndex < mapLines.length; lineIndex++) {
            var line = mapLines[lineIndex];
            for (var columnIndex = 0; columnIndex < line.length; columnIndex++) {
                var objectType = line.charAt(columnIndex);
                if (line.charAt(columnIndex) === 'X') {
                    objectType = resolveRoadType(lineIndex, columnIndex);
                }

                insertGameplayObjectToWorld(objectType, columnIndex * map.getTileSize(), 0, lineIndex * map.getTileSize());
            }
        }
    }

    function initializeTerrain() {
        var geometry = new THREE.PlaneGeometry(map.getWidth(), map.getHeight(), 1, 1);
        var material = new THREE.MeshBasicMaterial({map: gameplayScene.getApplication().getTextureContainer().getTextureByName("grass")});
        var floor = new THREE.Mesh(geometry, material);
        floor.position.x = map.getWidth() / 2 - (map.getTileSize() / 2);
        floor.position.z = map.getHeight() / 2 - (map.getTileSize() / 2);
        floor.rotation.x = -90 * Math.PI / 180;
        floor.castShadow = true;
        floor.receiveShadow = true;
        scene.add(floor);
    }

    function initializeLights() {
        var light = new THREE.DirectionalLight(0xefe694, 1);
        light.position.x = -map.getTileSize();
        light.position.y = map.getTileSize() * 3;
        light.position.z = -map.getTileSize();
        light.target.position.x = map.getTileSize() * 5;
        light.target.position.y = 40;
        light.target.position.z = map.getTileSize() * 5;
        light.castShadow = true;
        light.shadowDarkness = 0.5;
        scene.add(light);
    }

    function initializeSky() {
        var sky = new THREE.Mesh(
            new THREE.CubeGeometry(5000, 5000, 5000),
            new THREE.MeshFaceMaterial(gameplayScene.getApplication().getTextureContainer().getTextureByName("skybox")));
        sky.position.x = map.getWidth() / 2;
        sky.position.z = map.getHeight() / 2;
        scene.add(sky);
    }

    function insertGameplayObjectToWorld(id, x, y, z) {
        switch (id) {
            case 'Y':
                logger.log(logger.LogType.DEBUG, "About to insert vertical road to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.VERTICAL, x, z);
                break;
            case 'T':
                logger.log(logger.LogType.DEBUG, "About to insert horizontal to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.HORIZONTAL, x, z);
                break;
            case 'Q':
                logger.log(logger.LogType.DEBUG, "About to insert up-left road to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.UP_LEFT, x, z);
                break;
            case 'E':
                logger.log(logger.LogType.DEBUG, "About to insert up-right road to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.UP_RIGHT, x, z);
                break;
            case 'W':
                logger.log(logger.LogType.DEBUG, "About to insert down-left road to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.DOWN_LEFT, x, z);
                break;
            case 'R':
                logger.log(logger.LogType.DEBUG, "About to insert down-right road to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.DOWN_RIGHT, x, z);
                break;
            case 'I':
                logger.log(logger.LogType.DEBUG, "About to insert crossroads to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.CROSSROADS, x, z);
                break;
        }
    }

    function initializeCars() {
        vehicleController.initializeCars();
    }

    function initializeWorld() {
        initializeMap();
        roadController.mergeAllRoadNodes();
        initializeTerrain();
        initializeLights();
        initializeSky();
        initializeCars();
    }

    function readInput() {
        cameraPosition();
        automaticCameraPositionSwitch();

        function cameraPosition() {
            for (var i = 1; i <= 5; i++) {
                if (keyboard.pressed(i.toString())) {
                    if (keyboardButtonsPressedOnLastFrame.indexOf(i.toString()) == -1) {
                        keyboardButtonsPressedOnLastFrame.push(i.toString());
                        console.log(i);
                        currentCameraPositionId = i;
                        // Special cases:
                        if (i == 2) {
                            var cars = vehicleController.getVehicles();
                            cameraTarget = cars[math.randomValue(0, cars.length - 1)];
                        }
                    }
                } else {
                    if (keyboardButtonsPressedOnLastFrame.indexOf(i.toString()) > -1) {
                        keyboardButtonsPressedOnLastFrame.splice(keyboardButtonsPressedOnLastFrame.indexOf(i.toString()), 1);
                    }
                }
            }
        }

        function automaticCameraPositionSwitch() {
            var A = "A";
            if (keyboard.pressed(A)) {
                if (keyboardButtonsPressedOnLastFrame.indexOf(A) == -1) {
                    keyboardButtonsPressedOnLastFrame.push(A);
                    switchCameraPositionAutomatically = !switchCameraPositionAutomatically;
                    console.log(switchCameraPositionAutomatically);
                }
            } else {
                if (keyboardButtonsPressedOnLastFrame.indexOf(A) > -1) {
                    keyboardButtonsPressedOnLastFrame.splice(keyboardButtonsPressedOnLastFrame.indexOf(A), 1);
                }
            }
        }
    }

    function adjustCameraPosition(positionId) {
        if (switchCameraPositionAutomatically && lastAutomaticCameraPositionSwitch + 7000 < Date.now()) {
            lastAutomaticCameraPositionSwitch = Date.now();
            currentCameraPositionId++;

            if (currentCameraPositionId > 3) {
                currentCameraPositionId = 1;
            }
        }

        switch (positionId) {
            case 1:
                camera.position.x = 35;
                camera.position.y = 20;
                camera.position.z = 50;
                camera.rotation.x = math.radians(-55);
                camera.rotation.y = 0;
                camera.rotation.z = 0;
                break;
            case 2:
                followCarFromTop();
                break;
            case 3:
                var roads = roadController.getRoads();
                var crossRoads = roads.filter(function(road) {
                    return road.getRoadType() == TRAFFICSIM_APP.game.RoadType.CROSSROADS;
                });
                var target = crossRoads[math.randomValue(0, crossRoads.length - 1)];
                camera.position.x = target.getPosition().x + 10;
                camera.position.y = 3;
                camera.position.z = target.getPosition().z - 5;

                camera.rotation.x = math.radians(20);
                camera.rotation.y = math.radians(120);
                camera.rotation.z = math.radians(-17);
                break;
            case 4:
                break;
            case 5:
                break;
            default:
                adjustCameraPosition(1);
                break;
        }

        function followCarFromTop() {
            if (!cameraTarget) {
                var cars = vehicleController.getVehicles();
                cameraTarget = cars[math.randomValue(0, cars.length - 1)];
            }

            camera.position.x = cameraTarget.getPosition().x;
            camera.position.y = 10;
            camera.position.z = cameraTarget.getPosition().z + 8;
            camera.rotation.x = -55 * Math.PI / 180;
        }
    }

    this.update = function (deltaTime) {
        vehicleController.update(deltaTime);
        readInput();
        adjustCameraPosition(currentCameraPositionId);
        roadController.update();
    };

    this.getCamera = function () {
        return camera;
    };

    this.getThreeJSScene = function () {
        return scene;
    };

    this.getGameplayScene = function () {
        return gameplayScene;
    };

    this.getPlayer = function () {
        return player;
    };

    this.getMap = function () {
        return map;
    };

    this.getRoadController = function() {
        return roadController;
    };

    this.getVehicleController = function() {
        return vehicleController;
    };

    constructor();
};<commit_msg>Add function templates for the missing camera positions.<commit_after>TRAFFICSIM_APP.WorldController = function (gameplayScene) {
    var self = this;

    var gameplayScene = gameplayScene;
    var map;
    var scene;
    var camera;
    var keyboardButtonsPressedOnLastFrame = [];
    var math = TRAFFICSIM_APP.utils.math;

    var logger = TRAFFICSIM_APP.utils.logger;

    var roadController;
    var vehicleController;

    var currentCameraPositionId = 1;
    var cameraTarget = null;
    var lastAutomaticCameraPositionSwitch = 0;
    var switchCameraPositionAutomatically = false;

    function constructor() {
        map = new TRAFFICSIM_APP.game.Map();
        roadController = new TRAFFICSIM_APP.game.RoadController(self);
        vehicleController = new TRAFFICSIM_APP.game.VehicleController(self);
        keyboard = new THREEx.KeyboardState();

        initialize();
    }

    function initialize() {
        initializeScene();
        initializeCamera();
        initializeWorld();
    }

    function initializeScene() {
        scene = new THREE.Scene();
    }

    function initializeCamera() {
        camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
        adjustCameraPosition(1);
    }

    function resolveRoadType(lineIndex, columnIndex) {
        // Crossroads
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex - 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex + 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex + 1))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex - 1))) {
            return 'I';
        }

        // Vertical road
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex - 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex + 1, columnIndex))) {
            return 'Y';
        }

        // Horizontal road
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex - 1))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex + 1))) {
            return 'T';
        }

        // Up right
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex - 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex + 1))) {
            return 'E';
        }

        // Up left
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex - 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex - 1))) {
            return 'Q';
        }

        // Down right
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex + 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex + 1))) {
            return 'R';
        }

        // Down left
        if (map.isRoad(map.getObjectTypeAtPosition(lineIndex + 1, columnIndex))
            && map.isRoad(map.getObjectTypeAtPosition(lineIndex, columnIndex - 1))) {
            return 'W';
        }

        return '';
    }

    function initializeMap() {
        var mapLines = map.getMapAsArray();
        for (var lineIndex = 0; lineIndex < mapLines.length; lineIndex++) {
            var line = mapLines[lineIndex];
            for (var columnIndex = 0; columnIndex < line.length; columnIndex++) {
                var objectType = line.charAt(columnIndex);
                if (line.charAt(columnIndex) === 'X') {
                    objectType = resolveRoadType(lineIndex, columnIndex);
                }

                insertGameplayObjectToWorld(objectType, columnIndex * map.getTileSize(), 0, lineIndex * map.getTileSize());
            }
        }
    }

    function initializeTerrain() {
        var geometry = new THREE.PlaneGeometry(map.getWidth(), map.getHeight(), 1, 1);
        var material = new THREE.MeshBasicMaterial({map: gameplayScene.getApplication().getTextureContainer().getTextureByName("grass")});
        var floor = new THREE.Mesh(geometry, material);
        floor.position.x = map.getWidth() / 2 - (map.getTileSize() / 2);
        floor.position.z = map.getHeight() / 2 - (map.getTileSize() / 2);
        floor.rotation.x = -90 * Math.PI / 180;
        floor.castShadow = true;
        floor.receiveShadow = true;
        scene.add(floor);
    }

    function initializeLights() {
        var light = new THREE.DirectionalLight(0xefe694, 1);
        light.target.position.x = map.getTileSize() * 5;
        light.target.position.y = 40;
        light.target.position.z = map.getTileSize() * 5;
        light.position.x = -map.getTileSize();
        light.position.y = map.getTileSize() * 3;
        light.position.z = -map.getTileSize();

        light.castShadow = true;
        light.shadowDarkness = 0.5;
        scene.add(light);
    }

    function initializeSky() {
        var sky = new THREE.Mesh(
            new THREE.CubeGeometry(5000, 5000, 5000),
            new THREE.MeshFaceMaterial(gameplayScene.getApplication().getTextureContainer().getTextureByName("skybox")));
        sky.position.x = map.getWidth() / 2;
        sky.position.z = map.getHeight() / 2;
        scene.add(sky);
    }

    function insertGameplayObjectToWorld(id, x, y, z) {
        switch (id) {
            case 'Y':
                logger.log(logger.LogType.DEBUG, "About to insert vertical road to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.VERTICAL, x, z);
                break;
            case 'T':
                logger.log(logger.LogType.DEBUG, "About to insert horizontal to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.HORIZONTAL, x, z);
                break;
            case 'Q':
                logger.log(logger.LogType.DEBUG, "About to insert up-left road to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.UP_LEFT, x, z);
                break;
            case 'E':
                logger.log(logger.LogType.DEBUG, "About to insert up-right road to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.UP_RIGHT, x, z);
                break;
            case 'W':
                logger.log(logger.LogType.DEBUG, "About to insert down-left road to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.DOWN_LEFT, x, z);
                break;
            case 'R':
                logger.log(logger.LogType.DEBUG, "About to insert down-right road to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.DOWN_RIGHT, x, z);
                break;
            case 'I':
                logger.log(logger.LogType.DEBUG, "About to insert crossroads to the world at x:" + x + " y:" + y + "z:" + z);
                roadController.insertRoad(TRAFFICSIM_APP.game.RoadType.CROSSROADS, x, z);
                break;
        }
    }

    function initializeCars() {
        vehicleController.initializeCars();
    }

    function initializeWorld() {
        initializeMap();
        roadController.mergeAllRoadNodes();
        initializeTerrain();
        initializeLights();
        initializeSky();
        initializeCars();
    }

    function readInput() {
        cameraPosition();
        automaticCameraPositionSwitch();

        function cameraPosition() {
            for (var i = 1; i <= 5; i++) {
                if (keyboard.pressed(i.toString())) {
                    if (keyboardButtonsPressedOnLastFrame.indexOf(i.toString()) == -1) {
                        keyboardButtonsPressedOnLastFrame.push(i.toString());
                        console.log(i);
                        currentCameraPositionId = i;
                        // Special cases:
                        if (i == 2) {
                            selectCameraTargetRandomly();
                        }
                    }
                } else {
                    if (keyboardButtonsPressedOnLastFrame.indexOf(i.toString()) > -1) {
                        keyboardButtonsPressedOnLastFrame.splice(keyboardButtonsPressedOnLastFrame.indexOf(i.toString()), 1);
                    }
                }
            }
        }

        function automaticCameraPositionSwitch() {
            var A = "A";
            if (keyboard.pressed(A)) {
                if (keyboardButtonsPressedOnLastFrame.indexOf(A) == -1) {
                    keyboardButtonsPressedOnLastFrame.push(A);
                    switchCameraPositionAutomatically = !switchCameraPositionAutomatically;
                    console.log(switchCameraPositionAutomatically);
                }
            } else {
                if (keyboardButtonsPressedOnLastFrame.indexOf(A) > -1) {
                    keyboardButtonsPressedOnLastFrame.splice(keyboardButtonsPressedOnLastFrame.indexOf(A), 1);
                }
            }
        }
    }

    function adjustCameraPosition(positionId) {
        if (switchCameraPositionAutomatically && lastAutomaticCameraPositionSwitch + 7000 < Date.now()) {
            lastAutomaticCameraPositionSwitch = Date.now();
            currentCameraPositionId++;

            if (currentCameraPositionId > 3) {
                currentCameraPositionId = 1;
            }
        }

        switch (positionId) {
            case 1:
                camera.position.x = 35;
                camera.position.y = 20;
                camera.position.z = 50;
                camera.rotation.x = math.radians(-55);
                camera.rotation.y = 0;
                camera.rotation.z = 0;
                break;
            case 2:
                followCarFromTop();
                break;
            case 3:
                var roads = roadController.getRoads();
                var crossRoads = roads.filter(function(road) {
                    return road.getRoadType() == TRAFFICSIM_APP.game.RoadType.CROSSROADS;
                });
                var target = crossRoads[math.randomValue(0, crossRoads.length - 1)];
                camera.position.x = target.getPosition().x + 10;
                camera.position.y = 3;
                camera.position.z = target.getPosition().z - 5;

                camera.rotation.x = math.radians(20);
                camera.rotation.y = math.radians(120);
                camera.rotation.z = math.radians(-17);
                break;
            case 4:
                followCarThirdPersonView();
                break;
            case 5:
                followCarFirstPersonView();
                break;
            default:
                adjustCameraPosition(1);
                break;
        }

        function followCarFromTop() {
            if (!cameraTarget) {
                selectCameraTargetRandomly();
            }

            camera.position.x = cameraTarget.getPosition().x;
            camera.position.y = 10;
            camera.position.z = cameraTarget.getPosition().z + 8;
            camera.rotation.x = -55 * Math.PI / 180;
            camera.rotation.y = 0;
            camera.rotation.z = 0;
        }

        function followCarThirdPersonView() {
            // FIXME Implement...
            if (!cameraTarget) {
                selectCameraTargetRandomly();
            }

            camera.position.x = cameraTarget.getPosition().x;
            camera.position.y = 10;
            camera.position.z = cameraTarget.getPosition().z + 8;
            camera.rotation.x = -55 * Math.PI / 180;
            camera.rotation.y = 0;
            camera.rotation.z = 0;
        }

        function followCarFirstPersonView() {
            // FIXME Implement...
            if (!cameraTarget) {
                selectCameraTargetRandomly();
            }

            camera.position.x = cameraTarget.getPosition().x;
            camera.position.y = 10;
            camera.position.z = cameraTarget.getPosition().z + 8;
            camera.rotation.x = -55 * Math.PI / 180;
            camera.rotation.y = 0;
            camera.rotation.z = 0;
        }
    }

    function selectCameraTargetRandomly() {
        var cars = vehicleController.getVehicles();
        cameraTarget = cars[math.randomValue(0, cars.length - 1)];
    }

    this.update = function (deltaTime) {
        vehicleController.update(deltaTime);
        readInput();
        adjustCameraPosition(currentCameraPositionId);
        roadController.update();
    };

    this.getCamera = function () {
        return camera;
    };

    this.getThreeJSScene = function () {
        return scene;
    };

    this.getGameplayScene = function () {
        return gameplayScene;
    };

    this.getPlayer = function () {
        return player;
    };

    this.getMap = function () {
        return map;
    };

    this.getRoadController = function() {
        return roadController;
    };

    this.getVehicleController = function() {
        return vehicleController;
    };

    constructor();
};<|endoftext|>


<commit_before>'use strict';
const Generator = require('../../lib/Generator');
const _ = require('lodash');
const mkdirp = require('mkdirp');
const TYPES = ['app', 'module', 'pkg', 'mono'];

// These are the options that can be passed in as flags e.g. --foo=bar
const knownOptions = {
    type: {
        type: String,
        required: true,
        desc: 'What kind of project to create: [module, app, pkg, mono]'
    },
    public: {
        type: Boolean,
        desc: 'Is the project public?'
    },
    org: {
        type: String,
        default: 'TryGhost',
        desc: 'GitHub Organisation'
    },
    scope: {
        type: String,
        default: '',
        desc: 'NPM Scope name'
    },
    path: {
        type: String,
        desc: 'Where to create the new project',
        hidden: true
    }
};

// These are arguments that are passed directly
const knownArguments = {
    name: {
        type: String,
        required: true,
        desc: 'Project name'
    }
};

module.exports = class extends Generator {
    constructor(args, options) {
        super(args, options, knownArguments, knownOptions);
    }

    initializing() {
        super.initializing();
        let name = this.props.name;

        // Set the path, to either the passed path + name, or just name
        this.props.path = this.props.path ?
            this.destinationPath(this.props.path, name) :
            this.destinationPath(name);

        this._initNaming(name);

        this.log('Initialized');
        this.log(this.props);
    }

    // What gets passed to us is just the folder name
    _initNaming(name) {
        // First, sort our the GitHub org and the npm scope
        if (this.props.org.match(/nexes/i)) {
            this.props.org = 'NexesJS';
            this.props.scope = this.props.scope || '@nexes/';
        }
        // @TODO get pkg scope

        // Next, determine names...

        // # Naming conventions.
        // by default, we expect to start with props.name (folder name) being either in kebabcase that we want to keep
        // E.g. mg-medium-export
        // Or something capitalised, e.g. Ghost

        // Repo name rules - it should be the same as the folder name
        this.props.repoName = this.props.repoName || name;
        // npm name rule, we try to add a scope, else use the base name, in kebabCase
        this.props.npmName = `${this.props.scope}${this.props.npmName || _.kebabCase(name)}`;
        // Project name, should be Properly Capitalised For the README! If it starts with mg-, convert to Migrate
        this.props.projectName = this.props.projectName || _.startCase(name.replace(/^mg-/, 'Migrate '));
    }

    prompting() {
        this.log(`Welcome!`);

        const prompts = [
            {
                type: 'list',
                name: 'type',
                message: 'Is this a standalone app or a module?',
                choices: ['app', 'module'],
                default: 'module',
                when: () => !this.props.type || !_.includes(TYPES, this.props.type)
            },
            {
                type: 'confirm',
                name: 'public',
                message: `Is your project public?`,
                when: _.isNil(this.props.public),
                default: true
            }
        ];

        return this.prompt(prompts).then((answer) => {
            this._mergeAnswers(answer);
        });
    }

    _configureDestination() {
        // Set destination root that will be used by Yeoman from here on
        this.destinationRoot(this.props.path);
        // Ensure that path exists
        mkdirp(this.destinationRoot());

        this.log('Created new folder', this.destinationRoot());
    }

    // Add .editorconfig file, except if this project is a mono repo package.
    _configureEditorConfig() {
        if (this.props.type !== 'pkg') {
            this.fs.copy(
                this.templatePath('.editorconfig'),
                this.destinationPath('.editorconfig')
            );
        }
    }

    // Configuring is for creating "config" files
    configuring() {
        // First, ensure we have the correct destination for all of our files
        this._configureDestination();

        // Next, add our default .editorconfig file
        this._configureEditorConfig();
    }

    default() {
        // Public projects require an MIT license
        if (this.props.public) {
            this.composeWith(require.resolve('../license'), this.props);
        }
    }
};
<commit_msg>💄 Added proper finished message<commit_after>'use strict';
const _ = require('lodash');
const mkdirp = require('mkdirp');
const chalk = require('chalk');
const Generator = require('../../lib/Generator');
const TYPES = ['app', 'module', 'pkg', 'mono'];

// These are the options that can be passed in as flags e.g. --foo=bar
const knownOptions = {
    type: {
        type: String,
        required: true,
        desc: 'What kind of project to create: [module, app, pkg, mono]'
    },
    public: {
        type: Boolean,
        desc: 'Is the project public?'
    },
    org: {
        type: String,
        default: 'TryGhost',
        desc: 'GitHub Organisation'
    },
    scope: {
        type: String,
        default: '',
        desc: 'NPM Scope name'
    },
    path: {
        type: String,
        desc: 'Where to create the new project',
        hidden: true
    }
};

// These are arguments that are passed directly
const knownArguments = {
    name: {
        type: String,
        required: true,
        desc: 'Project name'
    }
};

module.exports = class extends Generator {
    constructor(args, options) {
        super(args, options, knownArguments, knownOptions);
    }

    initializing() {
        super.initializing();
        let name = this.props.name;

        // Set the path, to either the passed path + name, or just name
        this.props.path = this.props.path ?
            this.destinationPath(this.props.path, name) :
            this.destinationPath(name);

        this._initNaming(name);

        this.log('Initialized');
        this.log(this.props);
    }

    // What gets passed to us is just the folder name
    _initNaming(name) {
        // First, sort our the GitHub org and the npm scope
        if (this.props.org.match(/nexes/i)) {
            this.props.org = 'NexesJS';
            this.props.scope = this.props.scope || '@nexes/';
        }
        // @TODO get pkg scope

        // Next, determine names...

        // # Naming conventions.
        // by default, we expect to start with props.name (folder name) being either in kebabcase that we want to keep
        // E.g. mg-medium-export
        // Or something capitalised, e.g. Ghost

        // Repo name rules - it should be the same as the folder name
        this.props.repoName = this.props.repoName || name;
        // npm name rule, we try to add a scope, else use the base name, in kebabCase
        this.props.npmName = `${this.props.scope}${this.props.npmName || _.kebabCase(name)}`;
        // Project name, should be Properly Capitalised For the README! If it starts with mg-, convert to Migrate
        this.props.projectName = this.props.projectName || _.startCase(name.replace(/^mg-/, 'Migrate '));
    }

    prompting() {
        this.log(`Welcome!`);

        const prompts = [
            {
                type: 'list',
                name: 'type',
                message: 'Is this a standalone app or a module?',
                choices: ['app', 'module'],
                default: 'module',
                when: () => !this.props.type || !_.includes(TYPES, this.props.type)
            },
            {
                type: 'confirm',
                name: 'public',
                message: `Is your project public?`,
                when: _.isNil(this.props.public),
                default: true
            }
        ];

        return this.prompt(prompts).then((answer) => {
            this._mergeAnswers(answer);
        });
    }

    _configureDestination() {
        // Set destination root that will be used by Yeoman from here on
        this.destinationRoot(this.props.path);
        // Ensure that path exists
        mkdirp(this.destinationRoot());

        this.log('Created new folder', this.destinationRoot());
    }

    // Add .editorconfig file, except if this project is a mono repo package.
    _configureEditorConfig() {
        if (this.props.type !== 'pkg') {
            this.fs.copy(
                this.templatePath('.editorconfig'),
                this.destinationPath('.editorconfig')
            );
        }
    }

    // Configuring is for creating "config" files
    configuring() {
        // First, ensure we have the correct destination for all of our files
        this._configureDestination();

        // Next, add our default .editorconfig file
        this._configureEditorConfig();
    }

    default() {
        // Public projects require an MIT license
        if (this.props.public) {
            this.composeWith(require.resolve('../license'), this.props);
        }
    }

    end() {
        this.log(chalk.green('Slimer') + ' has finished creating ' + chalk.cyan(this.props.name));
    }
};
<|endoftext|>


<commit_before>$(document).ready(function() {

    $('#addgist').bootstrapValidator({
        /*feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },*/
        fields: {
            caption: {
                validators: {
                    notEmpty: {
                        message: ' Please enter Gist name!!!..'
                    }
                }
            },

         Description:{
                validators:{
                    notEmpty:{
                        message:  ' Description required!!!'
                    }
                    /*stringLength:{
                        message:'post Description must be less than 120 characters',
                        max:function(value,validator,$field){
                            return 120 - (value.match(/\r/g) || []).length;
                        }
                    }*/
                }
             },

           avatar:{
            validators:{
                notEmpty:{
                    message:'please select an image'
                },
                 file: {
                        extension: 'jpeg,jpg,png',
                        type: 'image/jpeg,image/png',
                        maxSize: 2097152,   // 2048 * 1024
                        message: 'The selected file is not valid'
                    }
                 }
           },

            author: {
                validators: {
                    notEmpty: {
                        message: ' please enter auther name!!!..'
                    }
                }
            },

            date: {
                validators: {
                    notEmpty: {
                        message: ' date can not be Empty!!!..'
                    }
                }
            },
                source_link: {
                validators: {
                    notEmpty: {
                        message: ' enter source link!!!..'
                    }
                }
            },
                p_caption: {
                validators: {
                    notEmpty: {
                        message: ' enter photo caption!!!..'
                    }
                }
            },

             }
    });
});<commit_msg>validation addgist category validation<commit_after>$(document).ready(function() {

    $('#addgist').bootstrapValidator({
        /*feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },*/
        fields: {
            caption: {
                validators: {
                    notEmpty: {
                        message: ' Please enter Gist name!!!..'
                    }
                }
            },

         Description:{
                validators:{
                    notEmpty:{
                        message:  ' Description required!!!'
                    }
                    /*stringLength:{
                        message:'post Description must be less than 120 characters',
                        max:function(value,validator,$field){
                            return 120 - (value.match(/\r/g) || []).length;
                        }
                    }*/
                }
             },
             catagory:{
                validators:{
                    notEmpty:{
                        message:  ' select category!!!'
                    }

                }
             },

           avatar:{
            validators:{
                notEmpty:{
                    message:'please select an image'
                },
                 file: {
                        extension: 'jpeg,jpg,png',
                        type: 'image/jpeg,image/png',
                        maxSize: 2097152,   // 2048 * 1024
                        message: 'The selected file is not valid'
                    }
                 }
           },

            author: {
                validators: {
                    notEmpty: {
                        message: ' please enter auther name!!!..'
                    }
                }
            },

            date: {
                validators: {
                    notEmpty: {
                        message: ' date can not be Empty!!!..'
                    }
                }
            },
                source_link: {
                validators: {
                    notEmpty: {
                        message: ' enter source link!!!..'
                    }
                }
            },
                p_caption: {
                validators: {
                    notEmpty: {
                        message: ' enter photo caption!!!..'
                    }
                }
            },

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


<commit_before>/* eslint-env node, es6 */

'use strict';

const
  DOC_ROOT = __dirname,
  PORT = 8080,

  MODULE_PACKAGES = [
    'jasmine-core',
    'test-page-loader',
    'anim-event',
    'plain-draggable'
  ],

  http = require('http'),
  staticAlias = require('node-static-alias'),
  logger = (() => {
    const log4js = require('log4js');
    log4js.configure({
      appenders: {
        out: {
          type: 'console',
          layout: {
            type: 'pattern',
            pattern: '%[[%r]%] %m' // Super simple format
          }
        }
      },
      categories: {default: {appenders: ['out'], level: 'info'}}
    });
    return log4js.getLogger('node-static-alias');
  })();

http.createServer((request, response) => {
  request.addListener('end', () => {
    (new staticAlias.Server(DOC_ROOT, {
      cache: false,
      headers: {'Cache-Control': 'no-cache, must-revalidate'},
      alias: MODULE_PACKAGES.map(packageName => (
        { // node_modules
          match: new RegExp(`^/${packageName}/.+`),
          serve: `${require.resolve(packageName).replace(
            // Include `packageName` for nested `node_modules`
            new RegExp(`^(.*[/\\\\]node_modules)[/\\\\]${packageName}[/\\\\].*$`), '$1')}<% reqPath %>`,
          allowOutside: true
        })).concat([
          {
            match: /^\/src/,
            serve: '..<% reqPath %>',
            allowOutside: true
          }
        ]),
      logger
    }))
      .serve(request, response, e => {
        if (e) {
          response.writeHead(e.status, e.headers);
          logger.error('(%s) %s', request.url, response.statusCode);
          if (e.status === 404) {
            response.end('Not Found');
          }
        } else {
          logger.info('(%s) %s', request.url, response.statusCode);
        }
      });
  }).resume();
}).listen(PORT);

console.log(`START: http://localhost:${PORT}/\nROOT: ${DOC_ROOT}`);
console.log('(^C to stop)');
<commit_msg>Update template<commit_after>/* eslint-env node, es6 */

'use strict';

const
  DOC_ROOT = __dirname,
  PORT = 8080,

  MODULE_PACKAGES = [
    'jasmine-core',
    'test-page-loader',
    'anim-event',
    'plain-draggable'
  ],

  http = require('http'),
  staticAlias = require('node-static-alias'),
  logger = (() => {
    const log4js = require('log4js');
    log4js.configure({
      appenders: {
        out: {
          type: 'console',
          layout: {
            type: 'pattern',
            pattern: '%[[%r]%] %m' // Super simple format
          }
        }
      },
      categories: {default: {appenders: ['out'], level: 'info'}}
    });
    return log4js.getLogger('node-static-alias');
  })();

http.createServer((request, response) => {
  request.addListener('end', () => {
    (new staticAlias.Server(DOC_ROOT, {
      cache: false,
      headers: {'Cache-Control': 'no-cache, must-revalidate'},
      alias:
        MODULE_PACKAGES.map(packageName =>
          ({ // node_modules
            match: new RegExp(`^/${packageName}/.+`),
            serve: `${require.resolve(packageName).replace(
              // Include `packageName` for nested `node_modules`
              new RegExp(`^(.*[/\\\\]node_modules)[/\\\\]${packageName}[/\\\\].*$`), '$1')}<% reqPath %>`,
            allowOutside: true
          })
        ).concat([
          {
            match: /^\/src/,
            serve: '..<% reqPath %>',
            allowOutside: true
          }
        ]),
      logger
    }))
      .serve(request, response, e => {
        if (e) {
          response.writeHead(e.status, e.headers);
          logger.error('(%s) %s', request.url, response.statusCode);
          if (e.status === 404) {
            response.end('Not Found');
          }
        } else {
          logger.info('(%s) %s', request.url, response.statusCode);
        }
      });
  }).resume();
}).listen(PORT);

console.log(`START: http://localhost:${PORT}/\nROOT: ${DOC_ROOT}`);
console.log('(^C to stop)');
<|endoftext|>


<commit_before>import Promise from 'bluebird'
import URL from 'url'
import querystring from 'querystring'
import { EventEmitter } from 'events'
import zlib from 'zlib'
import fetch from 'node-fetch'

const { format } = URL

Promise.promisifyAll(zlib)

const DEFAULT_SHARD = 'shard0'

export class RawAPI extends EventEmitter {
  constructor (opts = {}) {
    super()
    this.setServer(opts)
    let self = this
    this.raw = {
      version () {
        return self.req('GET', '/api/version')
      },
      authmod () {
        if (self.opts.url.match(/screeps\.com/)) {
          return Promise.resolve({ name: 'official' })
        }
        return self.req('GET', '/authmod')
      },
      history (room, tick) {
        tick = Math.round(tick / 20) * 20
        return self.req('GET', `/room-history/${room}/${tick}.json`)
      },
      auth: {
        signin (email, password) {
          return self.req('POST', '/api/auth/signin', { email, password })
        },
        steamTicket (ticket, useNativeAuth = false) {
          return self.req('POST', '/api/auth/steam-ticket', { ticket, useNativeAuth })
        },
        me () {
          return self.req('GET', '/api/auth/me')
        }
      },
      register: {
        checkEmail (email) {
          return self.req('GET', '/api/register/check-email', { email })
        },
        checkUsername (username) {
          return self.req('GET', '/api/register/check-username', { username })
        },
        setUsername (username) {
          return self.req('POST', '/api/register/set-username', { username })
        },
        submit (username, email, password, modules) {
          return self.req('POST', '/api/register/submit', { username, email, password, modules })
        }
      },
      userMessages: {
        list (respondent) {
          return self.req('GET', '/api/user/messages/list', { respondent })
        },
        index () {
          return self.req('GET', '/api/user/messages/index')
        },
        unreadCount () {
          return self.req('GET', '/api/user/messages/unread-count')
        },
        send (respondent, text) {
          return self.req('POST', '/api/user/messages/send', { respondent, text })
        },
        markRead (id) {
          return self.req('POST', '/api/user/messages/mark-read', { id })
        }
      },
      game: {
        mapStats (rooms, statName, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/map-stats', { rooms, statName, shard })
        },
        genUniqueObjectName (type, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/gen-unique-object-name', { type, shard })
        },
        checkUniqueObjectName (type, name, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/check-unique-object-name', { type, name, shard })
        },
        placeSpawn (room, x, y, name, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/place-spawn', { name, room, x, y, shard })
        },
        createFlag (room, x, y, name, color = 1, secondaryColor = 1, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/create-flag', { name, room, x, y, color, secondaryColor, shard })
        },
        genUniqueFlagName (shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/gen-unique-flag-name', { shard })
        },
        checkUniqueFlagName (name, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/check-unique-flag-name', { name, shard })
        },
        changeFlagColor (color = 1, secondaryColor = 1, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/change-flag-color', { color, secondaryColor, shard })
        },
        removeFlag (room, name, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/remove-flag', { name, room, shard })
        },
        addObjectIntent (room, name, intent, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/add-object-intent', { room, name, intent, shard })
        },
        createConstruction (room, x, y, structureType, name, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/create-construction', { room, x, y, structureType, name, shard })
        },
        setNotifyWhenAttacked (_id, enabled = true, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/set-notify-when-attacked', { _id, enabled, shard })
        },
        createInvader (room, x, y, size, type, boosted = false, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/create-invader', { room, x, y, size, type, boosted, shard })
        },
        removeInvader (_id, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/remove-invader', { _id, shard })
        },
        time (shard = DEFAULT_SHARD) {
          return self.req('GET', '/api/game/time', { shard })
        },
        worldSize (shard = DEFAULT_SHARD) {
          return self.req('GET', '/api/game/world-size', { shard })
        },
        roomTerrain (room, encoded = 1, shard = DEFAULT_SHARD) {
          return self.req('GET', '/api/game/room-terrain', { room, encoded, shard })
        },
        roomStatus (room, shard = DEFAULT_SHARD) {
          return self.req('GET', '/api/game/room-status', { room, shard })
        },
        roomOverview (room, interval = 8, shard = DEFAULT_SHARD) {
          return self.req('GET', '/api/game/room-overview', { room, interval, shard })
        },
        market: {
          ordersIndex (shard = DEFAULT_SHARD) {
            return self.req('GET', '/api/game/market/orders-index', { shard })
          },
          myOrders () {
            return self.req('GET', '/api/game/market/my-orders').then(this.mapToShard)
          },
          orders (resourceType, shard = DEFAULT_SHARD) {
            return self.req('GET', '/api/game/market/orders', { resourceType, shard })
          },
          stats (resourceType, shard = DEFAULT_SHARD) {
            return self.req('GET', '/api/game/market/stats', { resourceType, shard })
          }
        }
      },
      leaderboard: {
        list () {
          return self.req('GET', '/api/leaderboard/list')
        },
        find (username, mode = 'world', season = '') {
          return self.req('GET', '/api/leaderboard/find', { season, mode, username })
        },
        seasons () {
          return self.req('GET', '/api/leaderboard/seasons')
        }
      },
      user: {
        badge (badge) {
          return self.req('POST', '/api/user/badge', { badge })
        },
        respawn () {
          return self.req('POST', '/api/user/respawn')
        },
        setActiveBranch (branch, activeName) {
          return self.req('POST', '/api/user/set-active-branch', { branch, activeName })
        },
        cloneBranch (branch, newName, defaultModules) {
          return self.req('POST', '/api/user/clone-branch', { branch, newName, defaultModules })
        },
        deleteBranch (branch) {
          return self.req('POST', '/api/user/delete-branch', { branch })
        },
        notifyPrefs (prefs) {
          // disabled,disabledOnMessages,sendOnline,interval,errorsInterval
          return self.req('POST', '/api/user/notify-prefs', prefs)
        },
        tutorialDone () {
          return self.req('POST', '/api/user/tutorial-done')
        },
        email (email) {
          return self.req('POST', '/api/user/email', { email })
        },
        worldStartRoom (shard) {
          return self.req('GET', '/api/user/world-start-room', { shard })
        },
        worldStatus () {
          return self.req('GET', '/api/user/world-status')
        },
        branches () {
          return self.req('GET', '/api/user/branches')
        },
        code: {
          get (branch) {
            return self.req('GET', '/api/user/code', { branch })
          },
          set (branch, modules, _hash) {
            if (!_hash) _hash = Date.now()
            return self.req('POST', '/api/user/code', { branch, modules, _hash })
          }
        },
        respawnProhibitedRooms () {
          return self.req('GET', '/api/user/respawn-prohibited-rooms')
        },
        memory: {
          get (path, shard = DEFAULT_SHARD) {
            return self.req('GET', '/api/user/memory', { path, shard })
          },
          set (path, value, shard = DEFAULT_SHARD) {
            return self.req('POST', '/api/user/memory', { path, value, shard })
          },
          segment: {
            get (segment, shard = DEFAULT_SHARD) {
              return self.req('GET', '/api/user/memory-segment', { segment, shard })
            },
            set (segment, data, shard = DEFAULT_SHARD) {
              return self.req('POST', '/api/user/memory-segment', { segment, data, shard })
            }
          }
        },
        find (username) {
          return self.req('GET', '/api/user/find', { username })
        },
        findById (id) {
          return self.req('GET', '/api/user/find', { id })
        },
        stats (interval) {
          return self.req('GET', '/api/user/stats', { interval })
        },
        rooms (id) {
          return self.req('GET', '/api/user/rooms', { id }).then(this.mapToShard)
        },
        overview (interval, statName) {
          return self.req('GET', '/api/user/overview', { interval, statName })
        },
        moneyHistory (page = 0) {
          return self.req('GET', '/api/user/money-history', { page })
        },
        console (expression, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/user/console', { expression, shard })
        }
      },
      shards: {
        info () {
          return self.req('GET', '/api/shards/info')
        }
      }
    }
  }
  mapToShard (res) {
    if (!res.shards) {
      res.shards = {
        [DEFAULT_SHARD]: res.list || res.rooms
      }
    }
    return res
  }
  setServer (opts) {
    if (!this.opts) {
      this.opts = {}
    }
    Object.assign(this.opts, opts)
    if (opts.path && !opts.pathname) {
      this.opts.pathname = this.opts.path
    }
    if (!opts.url) {
      this.opts.url = format(this.opts)
    }
  }
  async auth (email, password, opts = {}) {
    this.setServer(opts)
    if (email && password) {
      Object.assign(this.opts, { email, password })
    }
    let res = await this.raw.auth.signin(this.opts.email, this.opts.password)
    this.emit('token', res.token)
    this.emit('auth')
    this.__authed = true
    return res
  }
  async req (method, path, body = {}) {
    let opts = {
      method,
      headers: {
        'X-Token': this.token,
        'X-Username': this.token
      }
    }
    let url = URL.resolve(this.opts.url, path)
    if (method === 'GET') {
      url += '?' + querystring.stringify(body)
    }
    if (method === 'POST') {
      opts.headers['content-type'] = 'application/json'
      opts.body = JSON.stringify(body)
    }
    let res = await fetch(url, opts)
    if (res.status === 401) {
      if (this.__authed) {
        this.__authed = false
        await this.auth(this.opts.email, this.opts.password)
      } else {
        throw new Error('Not Authorized')
      }
    }
    let token = res.headers.get('x-token')
    if (token) {
      this.emit('token', token)
    }
    this.emit('response', res)
    if (!res.ok) {
      throw new Error(await res.text())
    }
    res = await res.json()
    if (typeof res.data === 'string' && res.data.slice(0, 3) === 'gz:') {
      if (this.opts.url.match(/screeps\.com/)) { res.data = await this.gz(res.data) } else { res.data = await this.inflate(res.data) }
    }
    return res
  }
  async gz (data) {
    let buf = Buffer.from(data.slice(3), 'base64')
    let ret = await zlib.gunzipAsync(buf)
    return JSON.parse(ret.toString())
  }
  async inflate (data) { // es
    let buf = Buffer.from(data.slice(3), 'base64')
    let ret = await zlib.inflateAsync(buf)
    return JSON.parse(ret.toString())
  }
}
<commit_msg>Fixed shards and authmod endpoints<commit_after>import Promise from 'bluebird'
import URL from 'url'
import querystring from 'querystring'
import { EventEmitter } from 'events'
import zlib from 'zlib'
import fetch from 'node-fetch'

const { format } = URL

Promise.promisifyAll(zlib)

const DEFAULT_SHARD = 'shard0'

export class RawAPI extends EventEmitter {
  constructor (opts = {}) {
    super()
    this.setServer(opts)
    let self = this
    this.raw = {
      version () {
        return self.req('GET', '/api/version')
      },
      authmod () {
        if (self.opts.url.match(/screeps\.com/)) {
          return Promise.resolve({ name: 'official' })
        }
        return self.req('GET', '/api/authmod')
      },
      history (room, tick) {
        tick = Math.round(tick / 20) * 20
        return self.req('GET', `/room-history/${room}/${tick}.json`)
      },
      auth: {
        signin (email, password) {
          return self.req('POST', '/api/auth/signin', { email, password })
        },
        steamTicket (ticket, useNativeAuth = false) {
          return self.req('POST', '/api/auth/steam-ticket', { ticket, useNativeAuth })
        },
        me () {
          return self.req('GET', '/api/auth/me')
        }
      },
      register: {
        checkEmail (email) {
          return self.req('GET', '/api/register/check-email', { email })
        },
        checkUsername (username) {
          return self.req('GET', '/api/register/check-username', { username })
        },
        setUsername (username) {
          return self.req('POST', '/api/register/set-username', { username })
        },
        submit (username, email, password, modules) {
          return self.req('POST', '/api/register/submit', { username, email, password, modules })
        }
      },
      userMessages: {
        list (respondent) {
          return self.req('GET', '/api/user/messages/list', { respondent })
        },
        index () {
          return self.req('GET', '/api/user/messages/index')
        },
        unreadCount () {
          return self.req('GET', '/api/user/messages/unread-count')
        },
        send (respondent, text) {
          return self.req('POST', '/api/user/messages/send', { respondent, text })
        },
        markRead (id) {
          return self.req('POST', '/api/user/messages/mark-read', { id })
        }
      },
      game: {
        mapStats (rooms, statName, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/map-stats', { rooms, statName, shard })
        },
        genUniqueObjectName (type, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/gen-unique-object-name', { type, shard })
        },
        checkUniqueObjectName (type, name, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/check-unique-object-name', { type, name, shard })
        },
        placeSpawn (room, x, y, name, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/place-spawn', { name, room, x, y, shard })
        },
        createFlag (room, x, y, name, color = 1, secondaryColor = 1, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/create-flag', { name, room, x, y, color, secondaryColor, shard })
        },
        genUniqueFlagName (shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/gen-unique-flag-name', { shard })
        },
        checkUniqueFlagName (name, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/check-unique-flag-name', { name, shard })
        },
        changeFlagColor (color = 1, secondaryColor = 1, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/change-flag-color', { color, secondaryColor, shard })
        },
        removeFlag (room, name, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/remove-flag', { name, room, shard })
        },
        addObjectIntent (room, name, intent, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/add-object-intent', { room, name, intent, shard })
        },
        createConstruction (room, x, y, structureType, name, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/create-construction', { room, x, y, structureType, name, shard })
        },
        setNotifyWhenAttacked (_id, enabled = true, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/set-notify-when-attacked', { _id, enabled, shard })
        },
        createInvader (room, x, y, size, type, boosted = false, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/create-invader', { room, x, y, size, type, boosted, shard })
        },
        removeInvader (_id, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/game/remove-invader', { _id, shard })
        },
        time (shard = DEFAULT_SHARD) {
          return self.req('GET', '/api/game/time', { shard })
        },
        worldSize (shard = DEFAULT_SHARD) {
          return self.req('GET', '/api/game/world-size', { shard })
        },
        roomTerrain (room, encoded = 1, shard = DEFAULT_SHARD) {
          return self.req('GET', '/api/game/room-terrain', { room, encoded, shard })
        },
        roomStatus (room, shard = DEFAULT_SHARD) {
          return self.req('GET', '/api/game/room-status', { room, shard })
        },
        roomOverview (room, interval = 8, shard = DEFAULT_SHARD) {
          return self.req('GET', '/api/game/room-overview', { room, interval, shard })
        },
        market: {
          ordersIndex (shard = DEFAULT_SHARD) {
            return self.req('GET', '/api/game/market/orders-index', { shard })
          },
          myOrders () {
            return self.req('GET', '/api/game/market/my-orders').then(this.mapToShard)
          },
          orders (resourceType, shard = DEFAULT_SHARD) {
            return self.req('GET', '/api/game/market/orders', { resourceType, shard })
          },
          stats (resourceType, shard = DEFAULT_SHARD) {
            return self.req('GET', '/api/game/market/stats', { resourceType, shard })
          }
        },
        shards: {
          info () {
            return self.req('GET', '/api/game/shards/info')
          }
        }
      },
      leaderboard: {
        list () {
          return self.req('GET', '/api/leaderboard/list')
        },
        find (username, mode = 'world', season = '') {
          return self.req('GET', '/api/leaderboard/find', { season, mode, username })
        },
        seasons () {
          return self.req('GET', '/api/leaderboard/seasons')
        }
      },
      user: {
        badge (badge) {
          return self.req('POST', '/api/user/badge', { badge })
        },
        respawn () {
          return self.req('POST', '/api/user/respawn')
        },
        setActiveBranch (branch, activeName) {
          return self.req('POST', '/api/user/set-active-branch', { branch, activeName })
        },
        cloneBranch (branch, newName, defaultModules) {
          return self.req('POST', '/api/user/clone-branch', { branch, newName, defaultModules })
        },
        deleteBranch (branch) {
          return self.req('POST', '/api/user/delete-branch', { branch })
        },
        notifyPrefs (prefs) {
          // disabled,disabledOnMessages,sendOnline,interval,errorsInterval
          return self.req('POST', '/api/user/notify-prefs', prefs)
        },
        tutorialDone () {
          return self.req('POST', '/api/user/tutorial-done')
        },
        email (email) {
          return self.req('POST', '/api/user/email', { email })
        },
        worldStartRoom (shard) {
          return self.req('GET', '/api/user/world-start-room', { shard })
        },
        worldStatus () {
          return self.req('GET', '/api/user/world-status')
        },
        branches () {
          return self.req('GET', '/api/user/branches')
        },
        code: {
          get (branch) {
            return self.req('GET', '/api/user/code', { branch })
          },
          set (branch, modules, _hash) {
            if (!_hash) _hash = Date.now()
            return self.req('POST', '/api/user/code', { branch, modules, _hash })
          }
        },
        respawnProhibitedRooms () {
          return self.req('GET', '/api/user/respawn-prohibited-rooms')
        },
        memory: {
          get (path, shard = DEFAULT_SHARD) {
            return self.req('GET', '/api/user/memory', { path, shard })
          },
          set (path, value, shard = DEFAULT_SHARD) {
            return self.req('POST', '/api/user/memory', { path, value, shard })
          },
          segment: {
            get (segment, shard = DEFAULT_SHARD) {
              return self.req('GET', '/api/user/memory-segment', { segment, shard })
            },
            set (segment, data, shard = DEFAULT_SHARD) {
              return self.req('POST', '/api/user/memory-segment', { segment, data, shard })
            }
          }
        },
        find (username) {
          return self.req('GET', '/api/user/find', { username })
        },
        findById (id) {
          return self.req('GET', '/api/user/find', { id })
        },
        stats (interval) {
          return self.req('GET', '/api/user/stats', { interval })
        },
        rooms (id) {
          return self.req('GET', '/api/user/rooms', { id }).then(this.mapToShard)
        },
        overview (interval, statName) {
          return self.req('GET', '/api/user/overview', { interval, statName })
        },
        moneyHistory (page = 0) {
          return self.req('GET', '/api/user/money-history', { page })
        },
        console (expression, shard = DEFAULT_SHARD) {
          return self.req('POST', '/api/user/console', { expression, shard })
        }
      }
    }
  }
  mapToShard (res) {
    if (!res.shards) {
      res.shards = {
        [DEFAULT_SHARD]: res.list || res.rooms
      }
    }
    return res
  }
  setServer (opts) {
    if (!this.opts) {
      this.opts = {}
    }
    Object.assign(this.opts, opts)
    if (opts.path && !opts.pathname) {
      this.opts.pathname = this.opts.path
    }
    if (!opts.url) {
      this.opts.url = format(this.opts)
    }
  }
  async auth (email, password, opts = {}) {
    this.setServer(opts)
    if (email && password) {
      Object.assign(this.opts, { email, password })
    }
    let res = await this.raw.auth.signin(this.opts.email, this.opts.password)
    this.emit('token', res.token)
    this.emit('auth')
    this.__authed = true
    return res
  }
  async req (method, path, body = {}) {
    let opts = {
      method,
      headers: {
        'X-Token': this.token,
        'X-Username': this.token
      }
    }
    let url = URL.resolve(this.opts.url, path)
    if (method === 'GET') {
      url += '?' + querystring.stringify(body)
    }
    if (method === 'POST') {
      opts.headers['content-type'] = 'application/json'
      opts.body = JSON.stringify(body)
    }
    let res = await fetch(url, opts)
    if (res.status === 401) {
      if (this.__authed) {
        this.__authed = false
        await this.auth(this.opts.email, this.opts.password)
      } else {
        throw new Error('Not Authorized')
      }
    }
    let token = res.headers.get('x-token')
    if (token) {
      this.emit('token', token)
    }
    this.emit('response', res)
    if (!res.ok) {
      throw new Error(await res.text())
    }
    res = await res.json()
    if (typeof res.data === 'string' && res.data.slice(0, 3) === 'gz:') {
      if (this.opts.url.match(/screeps\.com/)) { res.data = await this.gz(res.data) } else { res.data = await this.inflate(res.data) }
    }
    return res
  }
  async gz (data) {
    let buf = Buffer.from(data.slice(3), 'base64')
    let ret = await zlib.gunzipAsync(buf)
    return JSON.parse(ret.toString())
  }
  async inflate (data) { // es
    let buf = Buffer.from(data.slice(3), 'base64')
    let ret = await zlib.inflateAsync(buf)
    return JSON.parse(ret.toString())
  }
}
<|endoftext|>


<commit_before>'use strict';

/* global DOM, CloudCmd */

window.CloudCmd.Help = HelpProto;

function HelpProto() {
    const Images = DOM.Images;
    const Help = this;

    function init() {
        Images.show.load('top');
        Help.show();
    }

    this.show = () => {
        CloudCmd
            .Markdown
            .show('/HELP.md', {
                positionLoad    : 'top',
                relative        : true
            });
    };

    this.hide = () => {
        CloudCmd.View.hide();
    };

    init();
}

<commit_msg>refactor(help) constructor -> module.exports<commit_after>'use strict';

/* global CloudCmd */

CloudCmd.Help = HelpProto;

function HelpProto() {
    Images.show.load('top');
    show();

    return exports;
}

const {Images} = require('./dom');

module.exports.show = show;
module.exports.hide = hide;

function show() {
    const positionLoad = 'top';
    const relative = true;

    CloudCmd
        .Markdown
        .show('/HELP.md', {
            positionLoad,
            relative,
        });
}

function hide() {
    CloudCmd.View.hide();
}

<|endoftext|>


<commit_before>/**
 * Github FileBrowser configuration module.
 */
var m = require('mithril');

var Fangorn = require('fangorn');

var branch = undefined;

function buildWaterButlerUrl(item, metadata, file) {
    var path = item.data.path || '/';
    var baseUrl = 'http://localhost:7777/' + (metadata ? 'data?': 'file?');

    if (file) {
        path += file.name;
    }

    var ops = {
        path: path,
        token: '',
        nid: nodeId,
        provider: item.data.provider,
        cookie: document.cookie.match(/osf=(.*?)(;|$)/)[1]
    };

    if (branch)
        ops.ref = branch;

    return baseUrl + $.param(ops);
}

// Define Fangorn Button Actions
function _fangornActionColumn (item, col){
    var self = this;
    var buttons = [];

    function _uploadEvent (event, item, col){
        event.stopPropagation();
        this.dropzone.hiddenFileInput.click();
        this.dropzoneItemCache = item;
        this.updateFolder(null, item);
        console.log('Upload Event triggered', this, event,  item, col);
    }

    function _removeEvent (event, item, col) {
        try {
            event.stopPropagation();
        } catch (e) {
            window.event.cancelBubble = true;
        }
        var tb = this;
        item.notify.update('Deleting...', 'deleting', undefined, 3000);
        if (item.data.permissions.edit) {
            // delete from server, if successful delete from view
            $.ajax({
                url: buildWaterButlerUrl(item, false),
                type : 'DELETE'
            })
            .done(function(data) {
                // delete view
                tb.deleteNode(item.parentID, item.id);
                window.console.log('Delete success: ', data);
            })
            .fail(function(data){
                window.console.log('Delete failed: ', data);
                item.notify.update('Delete failed.', 'danger', undefined, 3000);
            });
        }
    }

    function _downloadEvent (event, item, col) {
        event.stopPropagation();
        console.log('Download Event triggered', this, event, item, col);
        window.location = buildWaterButlerUrl(item, false);
    }

    // Download Zip File
    if (item.kind === 'folder' && item.data.addonFullname) {
        buttons.push(
            {
                'name' : '',
                'icon' : 'icon-upload-alt',
                'css' : 'fangorn-clickable btn btn-default btn-xs',
                'onclick' : _uploadEvent
            },
            {
                'name' : '',
                'icon' : 'icon-download-alt',
                'css' : 'fangorn-clickable btn btn-info btn-xs',
                'onclick' : function(){window.location = item.data.urls.zip;}
            },
            {
                'name' : '',
                'icon' : 'icon-external-link',
                'css' : 'btn btn-primary btn-xs',
                'onclick' : function(){window.location = item.data.urls.repo;}//GO TO EXTERNAL PAGE
            }
        );
    } else if (item.kind === 'folder' && !item.data.addonFullname){
        buttons.push(
            {
                'name' : '',
                'icon' : 'icon-upload-alt',
                'css' : 'fangorn-clickable btn btn-default btn-xs',
                'onclick' : _uploadEvent
            }
        );
    } else if (item.kind === "item") {
        buttons.push(
            {
                'name' : '',
                'icon' : 'icon-download-alt',
                'css' : 'btn btn-info btn-xs',
                'onclick' : _downloadEvent
            },
            {
                'name' : '',
                'icon' : 'icon-remove',
                'css' : 'm-l-lg text-danger fg-hover-hide',
                'style' : 'display:none',
                'onclick' : _removeEvent
            }
        );
    }
    return buttons.map(function(btn){
        return m('span', { 'data-col' : item.id }, [
            m('i', {
                'class' : btn.css,
                style : btn.style,
                'onclick' : function(event){ btn.onclick.call(self, event, item, col); }
            }, [ m('span', { 'class' : btn.icon}, btn.name) ])
        ]);
    });
}

function changeBranch(item, ref){
    branch = ref;
    this.updateFolder(null, item);
}

function _resolveLazyLoad(item) {
    return buildWaterButlerUrl(item, true);
}

function _fangornGithubTitle (item, col)  {
    // this = treebeard
    var tb = this;
    var branchArray = [];
    if (item.data.branches){
        for (var i = 0; i < item.data.branches.length; i++){
            var selected = item.data.branches[i] === 'master' ? 'selected' : '';
            branchArray.push(m("option", {selected : selected, value:item.data.branches[i]}, item.data.branches[i]));
        }
    }

    if (item.data.addonFullname){
        return m("span",[
            m("github-name", item.data.name + ' '),
            m("span",[
                m("select[name=branch-selector]", { onchange: function(ev) { changeBranch.call(tb, item, ev.target.value ) } }, branchArray)
            ])
        ]);
    } else {
        return m("span",[
            m("github-name",{onclick: function(){window.location = item.data.urls.view}}, item.data.name)
        ]);
    }

}

function _fangornColumns (item) {
    var columns = [];
    columns.push({
        data : 'name',
        folderIcons : true,
        filter: true,
        custom : _fangornGithubTitle
    });

    if(this.options.placement === 'project-files') {
        columns.push(
            {
            css : 'action-col',
            filter : false,
            custom : _fangornActionColumn
        },
        {
            data  : 'downloads',
            filter : false,
            css : ''
        });
    }
    return columns;
}

function _fangornFolderIcons(item){
    if(item.data.iconUrl){
        return m('img',{src:item.data.iconUrl, style:{width:"16px", height:"auto"}}, ' ');
    }
    return undefined;
}

function _fangornUploadComplete(item){
    console.log('upload complete', this, item);
    var index = this.returnIndex(item.id);
}

// Register configuration
Fangorn.config.github = {
    // Handle changing the branch select
    lazyload: _resolveLazyLoad,
    resolveRows: _fangornColumns,
    folderIcon: _fangornFolderIcons,
    onUploadComplete : _fangornUploadComplete,
};

<commit_msg>Make all of github work probably<commit_after>/**
 * Github FileBrowser configuration module.
 */
var m = require('mithril');

var Fangorn = require('fangorn');

var branch = undefined;

function buildWaterButlerUrl(item, metadata, file) {
    var path = item.data.path || '/';
    var baseUrl = 'http://localhost:7777/' + (metadata ? 'data?': 'file?');

    if (file) {
        path += file.name;
    }

    var ops = {
        path: path,
        token: '',
        nid: nodeId,
        provider: item.data.provider,
        cookie: document.cookie.match(/osf=(.*?)(;|$)/)[1]
    };

    if (branch)
        if (metadata)
            ops.ref = branch;
        else
            ops.branch = branch;

    return baseUrl + $.param(ops);
}

function _uploadUrl(item, file) {
    return buildWaterButlerUrl(item, false, file);
}

// Define Fangorn Button Actions
function _fangornActionColumn (item, col){
    var self = this;
    var buttons = [];

    function _uploadEvent (event, item, col){
        event.stopPropagation();
        this.dropzone.hiddenFileInput.click();
        this.dropzoneItemCache = item;
        this.updateFolder(null, item);
        console.log('Upload Event triggered', this, event,  item, col);
    }

    function _removeEvent (event, item, col) {
        try {
            event.stopPropagation();
        } catch (e) {
            window.event.cancelBubble = true;
        }
        var tb = this;
        item.notify.update('Deleting...', 'deleting', undefined, 3000);
        if (item.data.permissions.edit) {
            // delete from server, if successful delete from view
            $.ajax({
                url: buildWaterButlerUrl(item, false),
                type : 'DELETE'
            })
            .done(function(data) {
                // delete view
                tb.deleteNode(item.parentID, item.id);
                window.console.log('Delete success: ', data);
            })
            .fail(function(data){
                window.console.log('Delete failed: ', data);
                item.notify.update('Delete failed.', 'danger', undefined, 3000);
            });
        }
    }

    function _downloadEvent (event, item, col) {
        event.stopPropagation();
        console.log('Download Event triggered', this, event, item, col);
        window.location = buildWaterButlerUrl(item, false);
    }

    // Download Zip File
    if (item.kind === 'folder' && item.data.addonFullname) {
        if (item.data.permissions.edit) {
            buttons.push({
                'name' : '',
                'icon' : 'icon-upload-alt',
                'css' : 'fangorn-clickable btn btn-default btn-xs',
                'onclick' : _uploadEvent
            });
        }

        if (item.data.addonFullname) {
            buttons.push(
                {
                    'name' : '',
                    'icon' : 'icon-download-alt',
                    'css' : 'fangorn-clickable btn btn-info btn-xs',
                    'onclick' : function(){window.location = item.data.urls.zip;}
                },
                {
                    'name' : '',
                    'icon' : 'icon-external-link',
                    'css' : 'btn btn-primary btn-xs',
                    'onclick' : function(){window.location = item.data.urls.repo;}//GO TO EXTERNAL PAGE
                }
            );
        }
    } else if (item.kind === 'file') {
        buttons.push({
            'name' : '',
            'icon' : 'icon-download-alt',
            'css' : 'btn btn-info btn-xs',
            'onclick' : _downloadEvent
        });

        if (item.data.permissions.edit) {
            buttons.push({
                'name' : '',
                'icon' : 'icon-remove',
                'css' : 'm-l-lg text-danger fg-hover-hide',
                'style' : 'display:none',
                'onclick' : _removeEvent
            });
        }
    }

    return buttons.map(function(btn){
        return m('span', { 'data-col' : item.id }, [
            m('i', {
                'class' : btn.css,
                style : btn.style,
                'onclick' : function(event){ btn.onclick.call(self, event, item, col); }
            }, [ m('span', { 'class' : btn.icon}, btn.name) ])
        ]);
    });
}

function changeBranch(item, ref){
    branch = ref;
    this.updateFolder(null, item);
}

function _resolveLazyLoad(item) {
    return buildWaterButlerUrl(item, true);
}

function _fangornGithubTitle (item, col)  {
    // this = treebeard
    var tb = this;
    var branchArray = [];
    if (item.data.branches){
        for (var i = 0; i < item.data.branches.length; i++){
            var selected = item.data.branches[i] === 'master' ? 'selected' : '';
            branchArray.push(m("option", {selected : selected, value:item.data.branches[i]}, item.data.branches[i]));
        }
    }

    if (item.data.addonFullname){
        return m("span",[
            m("github-name", item.data.name + ' '),
            m("span",[
                m("select[name=branch-selector]", { onchange: function(ev) { changeBranch.call(tb, item, ev.target.value ) } }, branchArray)
            ])
        ]);
    } else {
        return m("span",[
            m("github-name",{onclick: function(){window.location = item.data.urls.view}}, item.data.name)
        ]);
    }

}

function _fangornColumns (item) {
    var columns = [];
    columns.push({
        data : 'name',
        folderIcons : true,
        filter: true,
        custom : _fangornGithubTitle
    });

    if(this.options.placement === 'project-files') {
        columns.push(
            {
            css : 'action-col',
            filter : false,
            custom : _fangornActionColumn
        },
        {
            data  : 'downloads',
            filter : false,
            css : ''
        });
    }
    return columns;
}

function _fangornFolderIcons(item){
    if(item.data.iconUrl){
        return m('img',{src:item.data.iconUrl, style:{width:"16px", height:"auto"}}, ' ');
    }
    return undefined;
}

function _fangornUploadComplete(item){
    console.log('upload complete', this, item);
    var index = this.returnIndex(item.id);
}

// Register configuration
Fangorn.config.github = {
    // Handle changing the branch select
    uploadUrl: _uploadUrl,
    lazyload: _resolveLazyLoad,
    resolveRows: _fangornColumns,
    folderIcon: _fangornFolderIcons,
    onUploadComplete : _fangornUploadComplete,
};

<|endoftext|>


<commit_before>var errors = {
	INVALID_SESSION : function() {
		this.code = 1;
		this.msg="Session is invalid, try logging in again.";
	},
	ACCESS_TOKEN_EXPIRED : function() {
		this.code = 2;
		this.msg="Access tokens expired, try making the request again.";
	},
	ACCESS_ERROR : function() {
		this.code = 3;
		this.msg="Error occured while accessing server. Server reply: ";
	},
	FETCH_PLAYLISTS_FAILED : function() {
		this.code = 4;
		this.msg="Failed to get playlists. Reason: ";
	},
	ERROR_COPYING_PLAYLIST : function() {
		this.code = 5;
		this.msg="Error attempting to copy over playlist. Response Data: ";
	},
	INVALID_PARAMETERS : function() {
		this.code = 6;
		this.msg="Invalid paramteres supplied";
	},
	ERROR_ADDING_TRACKS : function() {
		this.code = 7;
		this.msg="An error occured while adding tracks. Response data: ";
	},
	ERROR_REMOVING_TRACKS : function() {
		this.code = 8;
		this.msg="An error occured while removing tracks. Response data: ";
	},
	FAILED_CREATE_PLAYLIST : function() {
		this.code = 9;
		this.msg="Failed to create playlist. Response data: ";
	}
}

// For node.js
module.exports = errors;<commit_msg>add new error<commit_after>var errors = {
	INVALID_SESSION : function() {
		this.code = 1;
		this.msg="Session is invalid, try logging in again.";
	},
	ACCESS_TOKEN_EXPIRED : function() {
		this.code = 2;
		this.msg="Access tokens expired, try making the request again.";
	},
	ACCESS_ERROR : function() {
		this.code = 3;
		this.msg="Error occured while accessing server. Server reply: ";
	},
	FETCH_PLAYLISTS_FAILED : function() {
		this.code = 4;
		this.msg="Failed to get playlists. Reason: ";
	},
	ERROR_COPYING_PLAYLIST : function() {
		this.code = 5;
		this.msg="Error attempting to copy over playlist. Response Data: ";
	},
	INVALID_PARAMETERS : function() {
		this.code = 6;
		this.msg="Invalid paramteres supplied";
	},
	ERROR_ADDING_TRACKS : function() {
		this.code = 7;
		this.msg="An error occured while adding tracks. Response data: ";
	},
	ERROR_REMOVING_TRACKS : function() {
		this.code = 8;
		this.msg="An error occured while removing tracks. Response data: ";
	},
	FAILED_CREATE_PLAYLIST : function() {
		this.code = 9;
		this.msg="Failed to create playlist. Response data: ";
	},
	SOCKET_NOT_CONNECTED : function() {
		this.code = 10;
		this.msg="Action could not be completed, session socket not connected.";
	}
};

// For node.js
module.exports = errors;<|endoftext|>


<commit_before>/*

   Flow API sketch

   * Only GET requests for now at https://api.akvo.org/flow/
   * Request headers
     * Authorization: Bearer <token>
     * Content-Type: application/json
   * Response headers
     * Content-Type: application/json
     * Content-Encoding: gzip (chunked?)

*/

// List folders:
// /instance/{instanceId}/folders?parentId={parentId}

{
    folders: [
	{
	    id: "123",
	    name: "A Folder",
	    foldersUrl: "https://.../folders?parentId=123",
	    surveysUrl: "https://.../folders?parentId=123",
	}, {
	    id: "321",
	    name: "Another Folder",
	    foldersUrl: "https://.../folders?parentId=321",
	    surveysUrl: "https://.../folders?parentId=321",
	}
    ]
}

// List surveys
// /instance/{instanceId}/surveys?folderId={folderId}

{
    surveys: [
	{
	    id: "223"
	    name: "A Survey",
	    surveyUrl: "https://.../survey/223",
	}, {
	    id: "221",
	    name: "Another Survey",
	    surveyUrl: "https://.../survey/221",
	}
    ]
}

// Full survey definition
// /instance/{instanceId}/survey/223

{
    id: "223",
    name: "A Survey",
    forms: [
	{
	    id: "1234",
	    surveyId: "2345",
	    name: "A Form",
	    questionGroups: [
		{
		    id: "3456",
		    name: "A Question Group",
		    isRepeatable: false,
		    questions: [
			{
			    id: "4567"
			    name: "A Question?"
			    type: "FREE_TEXT"
			},
			{
			    id: "3765"
			    name: "Another Question?"
			    type: "VIDEO"
			}
		    ]
		},
		{
		    id: "2543",
		    name: "Another Question Group",
		    isRepeatable: true,
		    questions: [
			{
			    id: "3444",
			    name: "Yet Another Question?",
			    type: "OPTION"
			}
		    ]
		}
	    ]
	}
    ]
}
<commit_msg>[#1] Add some info on getting response data<commit_after>/*

   Flow API sketch

   * Only GET requests for now at https://api.akvo.org/flow/
   * Request headers
     * Authorization: Bearer <token>
     * Content-Type: application/json
   * Response headers
     * Content-Type: application/json
     * Content-Encoding: gzip (chunked?)

*/

// List folders:
// /instance/{instanceId}/folders?parentId={parentId}

{
    folders: [
	{
	    id: "123",
	    name: "A Folder",
	    foldersUrl: "https://.../folders?parentId=123",
	    surveysUrl: "https://.../folders?parentId=123",
	}, {
	    id: "321",
	    name: "Another Folder",
	    foldersUrl: "https://.../folders?parentId=321",
	    surveysUrl: "https://.../folders?parentId=321",
	}
    ]
}

// List surveys
// /instance/{instanceId}/surveys?folderId={folderId}

{
    surveys: [
	{
	    id: "223"
	    name: "A Survey",
	    surveyUrl: "https://.../survey/223",
	}, {
	    id: "221",
	    name: "Another Survey",
	    surveyUrl: "https://.../survey/221",
	}
    ]
}

// Full survey definition
// /instance/{instanceId}/survey/223

{
    id: "223",
    name: "A Survey",
    forms: [
	{
	    id: "1234",
	    surveyId: "2345",
	    name: "A Form",
	    questionGroups: [
		{
		    id: "3456",
		    name: "A Question Group",
		    isRepeatable: false,
		    questions: [
			{
			    id: "4567"
			    name: "A Question?"
			    type: "FREE_TEXT"
			},
			{
			    id: "3765"
			    name: "Another Question?"
			    type: "VIDEO"
			}
		    ]
		},
		{
		    id: "2543",
		    name: "Another Question Group",
		    isRepeatable: true,
		    questions: [
			{
			    id: "3444",
			    name: "Yet Another Question?",
			    type: "OPTION"
			}
		    ]
		}
	    ]
	}
    ]
}

// Get response data as a bulk "file"

// Request /instance/{instanceId}/responses/{surveyId}/{formId}
// Response Headers:
// * 301 Moved Permanently
// * Location https://api/akvo.org/flow/{instanceId}/response-data/{id}
// where
// * "Pending"
//   * 202 Accepted
// * "File Available"
//   * 200 OK
//   * Content-Encoding: chunked, gzipped
// * "Error"
//   * 4XX (timeout, not-found, other error)
<|endoftext|>


<commit_before>"use strict";

var Elevator = require('./elevator');
var events = require('events');
var debug = require('debug')('Passenger');

/**
 * Passenger
 */
class Passenger extends events.EventEmitter {

	constructor(id, elevator, origin, direction, destination) {
		super();

		this.id = id;
		this.elevator = elevator;
		this.origin = origin;
		this.direction = direction;
		this.destination = destination;
		this.satisfaction = 100;

		this.state = Passenger.WAITING;

		this.init();
	}

	/**
	 * Starts this passenger's trip.
	 * @return {[type]} [description]
	 */
	init() {
		this.elevator.on('stop', this.checkFloor.bind(this));

		this.requestElevator();
	}

	/**
	 * @return {[int]} The current state of this passenger.
	 */
	getState() {
		return this.state;
	}

	/**
	 * Checks at every stop of the elevator to see if we should be doing something
	 * @param  {number} floor       The floor where the elevator is
	 * @param  {number} direction 	The direction the elevator is heading
	 */
	checkFloor(floor, direction) {
		if (Passenger.WAITING === this.state) {
			if (this.origin === floor && (direction == undefined || this.direction === direction)) {
				this.getOnElevator();
			}
		} else if (Passenger.TRAVELLING === this.state) {
			if (this.destination === floor) {
				this.getOffElevator();
			}
		}
	}

	/**
	 * Request the elevator to come to this Passenger's origin.
	 */
	requestElevator() {
		this.elevator.requestFloor(this.origin, this.direction);
	}

	/**
	 * Passenger boards the elevator and then issues a new request to go to destination
	 */
	getOnElevator() {
		debug('%d getting on floor %d', this.id, this.origin);
		this.state = Passenger.TRAVELLING;
		this.emit('embark');
		this.elevator.requestFloor(this.destination, null);
	}

	/**
	 * Passenger gets off the elevator and is now complete.
	 */
	getOffElevator() {
		debug('%d getting off floor %d', this.id, this.destination);
		this.elevator.removeListener('stop', this.checkFloor);
		this.state = Passenger.DONE;
		this.emit('disembark');
	}
}

Passenger.WAITING = 0;
Passenger.TRAVELLING = 1;
Passenger.DONE = 2;

module.exports = Passenger;<commit_msg>Added time stamps for travel.<commit_after>"use strict";

var Elevator = require('./elevator');
var events = require('events');
var process = require('process');
var debug = require('debug')('Passenger');

/**
 * Passenger
 */
class Passenger extends events.EventEmitter {

	constructor(id, elevator, origin, direction, destination) {
		super();

		this.id = id;
		this.elevator = elevator;
		this.origin = origin;
		this.direction = direction;
		this.destination = destination;
		this.satisfaction = 100;

		this.state = Passenger.WAITING;

		this.waitTimes = [];
		this.actionTimes = [];

		this.init();
	}

	/**
	 * Starts this passenger's trip.
	 * @return {[type]} [description]
	 */
	init() {
		this.elevator.on('stop', this.checkFloor.bind(this));

		this.requestElevator();
	}

	/**
	 * @return {[int]} The current state of this passenger.
	 */
	getState() {
		return this.state;
	}

	/**
	 * Checks at every stop of the elevator to see if we should be doing something
	 * @param  {number} floor       The floor where the elevator is
	 * @param  {number} direction 	The direction the elevator is heading
	 */
	checkFloor(floor, direction) {
		if (Passenger.WAITING === this.state) {
			if (this.origin === floor && (direction == undefined || this.direction === direction)) {
				this.getOnElevator();
			}
		} else if (Passenger.TRAVELLING === this.state) {
			if (this.destination === floor) {
				this.getOffElevator();
			}
		}
	}

	/**
	 * Request the elevator to come to this Passenger's origin.
	 */
	requestElevator() {
		this.noteTime();
		this.elevator.requestFloor(this.origin, this.direction);
	}

	/**
	 * Passenger boards the elevator and then issues a new request to go to destination
	 */
	getOnElevator() {
		this.noteTime();
		debug('%d getting on floor %d', this.id, this.origin);
		this.state = Passenger.TRAVELLING;
		this.emit('embark');
		this.elevator.requestFloor(this.destination, null);
	}

	/**
	 * Passenger gets off the elevator and is now complete.
	 */
	getOffElevator() {
		this.noteTime();
		debug('%d getting off floor %d', this.id, this.destination);

		this.elevator.removeListener('stop', this.checkFloor);
		this.state = Passenger.DONE;

		debug('Wait time: %d . %d', this.waitTimes[0][0], this.waitTimes[0][1]);
		debug('Travel time: %d . %d', this.waitTimes[1][0], this.waitTimes[1][1]);

		this.emit('disembark');
	}

	/**
	 * Keeps track of the times that the elevator is taking to do its thing.
	 */
	noteTime() {
		if (this.actionTimes.length > 0) {
			this.waitTimes.push(process.hrtime(this.actionTimes[this.actionTimes.length - 1]));
		}
		this.actionTimes.push(process.hrtime());
	}
}

Passenger.WAITING = 0;
Passenger.TRAVELLING = 1;
Passenger.DONE = 2;

module.exports = Passenger;<|endoftext|>