<commit_before>/* global SmartBot, FencesCollection, FieldsCollection,
    PlayersCollection, GameHistoryModel
*/
var BoardModel = Backbone.Model.extend({
    isPlayerMoved: false,
    isFenceMoved: false,

    bots: [],

    defaults: {
        botsCount       : 0,
        boardSize       : 9,
        playersCount    : 2,
        currentPlayer   : null,
        activePlayer    : null
    },

    resetModels: function () {
        this.fences.each(function (fence) {
            fence.set('state', '');
        });
        this.players.initPlayerPositions();
        this.run();
    },
    createModels: function () {
        this.fences = new FencesCollection();
        this.fields = new FieldsCollection();
        this.players = new PlayersCollection();
        this.infoModel = new Backbone.Model();
        this.history = new GameHistoryModel({
            boardSize: this.get('boardSize'),
            playersCount: this.get('playersCount')
        });
    },
    initModels   : function () {
        var me = this;
        var count = me.get('playersCount');
        if (count !== 2 && count !== 4) {
            me.set('playersCount', 2);
        }
        me.set('botsCount', Math.min(me.get('playersCount'), me.get('botsCount')));
        me.fields.createFields(+me.get('boardSize'));
        me.fences.createFences(+me.get('boardSize'));
        me.players.createPlayers(+me.get('playersCount'));
        this.history.initPlayers();
    },

    switchActivePlayer: function () {
        this.set('activePlayer', this.players.getNextActivePlayer(this.get('activePlayer')));
    },

    makeTurn: function () {
        /* jshint maxcomplexity:8 */
        var me = this;
        if (!(me.isPlayerMoved || me.isFenceMoved)) {
            return;
        }
        var active = me.getActivePlayer();
        var preBusy = me.fences.getPreBusy();
        var index = me.get('activePlayer');
        if (me.isFenceMoved) {
            me.getActivePlayer().placeFence();
            me.history.add({
                x: preBusy[0].get('x'),
                y: preBusy[0].get('y'),
                x2: preBusy[1].get('x'),
                y2: preBusy[1].get('y'),
                t: 'f'
            });
            me.fences.setBusy();
        }
        if (me.isPlayerMoved) {
            me.history.add({
                x: active.get('x'),
                y: active.get('y'),
                t: 'p'
            });
        }
        me.switchActivePlayer();
        /**
         * if local mode game then automatic change currentPlayer
         */
        if (!me.isOnlineGame()) {
            me.set('currentPlayer', me.get('activePlayer'));

            if (me.isFenceMoved) {
                me.emitEventToBots('server_move_fence', {
                    x: preBusy[0].get('x'),
                    y: preBusy[0].get('y'),
                    type: preBusy[0].get('type'),
                    playerIndex: index
                });
            }
            if (me.isPlayerMoved) {
                me.emitEventToBots('server_move_player', {
                    x: active.get('x'),
                    y: active.get('y'),
                    playerIndex: index
                });
            }
        }

        me.isPlayerMoved = false;
        me.isFenceMoved = false;
    },

    getNextActiveBot: function (next) {
        return _(this.bots).find(function (bot) {
            return bot.currentPlayer === next;
        }, this);
    },

    emitEventToBots: function (eventName, param) {
        var next = this.players.getNextActivePlayer(this.get('activePlayer'));
        _(this.bots).each(function (bot) {
            if (next !== bot.currentPlayer) {
                bot.trigger(eventName, param);
            }
        }, this);
        var nextBot = this.getNextActiveBot(next);
        if (nextBot) {
            nextBot.trigger(eventName, param);
        }
    },

    isOnlineGame: function () {
        return this.get('playerId') || this.get('roomId');
    },

    onMovePlayer: function (x, y) {
        var me = this;
        if (me.isValidCurrentPlayerPosition(x, y)) {
            var current = me.getActivePlayer();
            current.moveTo(x, y);
            me.fences.clearBusy();
            me.isFenceMoved = false;
            me.isPlayerMoved = true;
        } else {
            var activeBot = me.getActiveBot();
            if (activeBot) {
                activeBot.trigger('server_turn_fail');
            }
        }
    },

    updateInfo: function () {
        this.infoModel.set({
            currentplayer: this.get('currentPlayer'),
            activeplayer : this.get('activePlayer'),
            fences       : this.players.pluck('fencesRemaining')
        });
    },

    initEvents: function () {
        var me = this;

        this.on('maketurn', this.makeTurn);

        this.fields.on('moveplayer', me.onMovePlayer, this);
        this.fields.on('beforeselectfield', function (x, y) {
            if (me.isValidCurrentPlayerPosition(x, y)) {
                this.selectField(x, y);
            }
        });
        this.on('change:activePlayer', this.updateInfo, this);
        this.on('change:currentPlayer', this.updateInfo, this);
        this.players.on('change', this.updateInfo, this);

        if (!this.isOnlineGame()) {
            this.players.on('win', function (player) {
                if (window.confirm(player + ' выиграл. Начать сначала?')) {
                    me.resetModels();
                }
            });
        }
        this.fences.on({
            'selected'                     : function (model) {
                if (me.canSelectFences() &&
                    me.fences.validateFenceAndSibling(model) &&
                    me.notBreakSomePlayerPath(model)) {

                    me.fences.clearBusy();
                    me.fences.validateAndTriggerEventOnFenceAndSibling(model, 'movefence');

                    me.players.updatePlayersPositions();
                    me.isPlayerMoved = false;
                    me.isFenceMoved = true;
                } else {
                    var activeBot = me.getActiveBot();
                    if (activeBot) {
                        activeBot.trigger('server_turn_fail');
                    }
                }
            },
            'highlight_current_and_sibling': function (model) {
                if (me.canSelectFences()) {
                    me.fences.validateAndTriggerEventOnFenceAndSibling(model, 'markfence');
                }
            },
            'reset_current_and_sibling'    : function (model) {
                me.fences.triggerEventOnFenceAndSibling(model, 'unmarkfence');
            }
        });
    },
    run: function (activePlayer, currentPlayer) {
        this.set({
            activePlayer: activePlayer,
            currentPlayer: _.isUndefined(currentPlayer) ? activePlayer : currentPlayer
        });
        this.connectBots();
    },
    connectBots: function () {
        if (_.isUndefined(this.get('botsCount'))) {
            return;
        }

        var turns = this.history.get('turns').toJSON();

        _(this.get('botsCount')).times(function (i) {
            var botIndex = i + (this.get('playersCount') - this.get('botsCount'));
            var bot = new SmartBot(botIndex, this);

            bot.on('client_move_player', this.onSocketMovePlayer, this);
            bot.on('client_move_fence', function (pos) {
                if (this.onSocketMoveFence(pos) === false) {
                    var activeBot = this.getActiveBot();
                    if (activeBot) {
                        activeBot.trigger('server_turn_fail');
                    }
                }
            }, this);

            bot.trigger('server_start', botIndex, this.get('activePlayer'), turns);

            this.bots.push(bot);
        }, this);
    },
    initialize: function () {
        this.set('playersCount', +this.get('playersCount'));
        this.set('boardSize', +this.get('boardSize'));
        this.createModels();
        this.initEvents();
        this.initModels();
        if (this.isOnlineGame()) {
            this.socketEvents();
        } else {
            this.on('confirmturn', this.makeTurn);
            this.run(0, 0);
        }
    }
});
_.extend(BoardModel.prototype, window.BoardValidation);
_.extend(BoardModel.prototype, window.BoardSocketEvents);<commit_msg>fix tests<commit_after>/* global SmartBot, FencesCollection, FieldsCollection,
    PlayersCollection, GameHistoryModel
*/
var BoardModel = Backbone.Model.extend({
    isPlayerMoved: false,
    isFenceMoved: false,

    bots: [],

    defaults: {
        botsCount       : 0,
        boardSize       : 9,
        playersCount    : 2,
        currentPlayer   : null,
        activePlayer    : null
    },

    resetModels: function () {
        this.fences.each(function (fence) {
            fence.set('state', '');
        });
        this.players.initPlayerPositions();
        this.run();
    },
    createModels: function () {
        this.fences = new FencesCollection();
        this.fields = new FieldsCollection();
        this.players = new PlayersCollection();
        this.infoModel = new Backbone.Model();
        this.history = new GameHistoryModel({
            boardSize: this.get('boardSize'),
            playersCount: this.get('playersCount')
        });
    },
    initModels   : function () {
        var me = this;
        var count = me.get('playersCount');
        if (count !== 2 && count !== 4) {
            me.set('playersCount', 2);
        }
        me.set('botsCount', Math.min(me.get('playersCount'), me.get('botsCount')));
        me.fields.createFields(+me.get('boardSize'));
        me.fences.createFences(+me.get('boardSize'));
        me.players.createPlayers(+me.get('playersCount'));
    },

    switchActivePlayer: function () {
        this.set('activePlayer', this.players.getNextActivePlayer(this.get('activePlayer')));
    },

    makeTurn: function () {
        /* jshint maxcomplexity:8 */
        var me = this;
        if (!(me.isPlayerMoved || me.isFenceMoved)) {
            return;
        }
        var active = me.getActivePlayer();
        var preBusy = me.fences.getPreBusy();
        var index = me.get('activePlayer');
        if (me.isFenceMoved) {
            me.getActivePlayer().placeFence();
            me.history.add({
                x: preBusy[0].get('x'),
                y: preBusy[0].get('y'),
                x2: preBusy[1].get('x'),
                y2: preBusy[1].get('y'),
                t: 'f'
            });
            me.fences.setBusy();
        }
        if (me.isPlayerMoved) {
            me.history.add({
                x: active.get('x'),
                y: active.get('y'),
                t: 'p'
            });
        }
        me.switchActivePlayer();
        /**
         * if local mode game then automatic change currentPlayer
         */
        if (!me.isOnlineGame()) {
            me.set('currentPlayer', me.get('activePlayer'));

            if (me.isFenceMoved) {
                me.emitEventToBots('server_move_fence', {
                    x: preBusy[0].get('x'),
                    y: preBusy[0].get('y'),
                    type: preBusy[0].get('type'),
                    playerIndex: index
                });
            }
            if (me.isPlayerMoved) {
                me.emitEventToBots('server_move_player', {
                    x: active.get('x'),
                    y: active.get('y'),
                    playerIndex: index
                });
            }
        }

        me.isPlayerMoved = false;
        me.isFenceMoved = false;
    },

    getNextActiveBot: function (next) {
        return _(this.bots).find(function (bot) {
            return bot.currentPlayer === next;
        }, this);
    },

    emitEventToBots: function (eventName, param) {
        var next = this.players.getNextActivePlayer(this.get('activePlayer'));
        _(this.bots).each(function (bot) {
            if (next !== bot.currentPlayer) {
                bot.trigger(eventName, param);
            }
        }, this);
        var nextBot = this.getNextActiveBot(next);
        if (nextBot) {
            nextBot.trigger(eventName, param);
        }
    },

    isOnlineGame: function () {
        return this.get('playerId') || this.get('roomId');
    },

    onMovePlayer: function (x, y) {
        var me = this;
        if (me.isValidCurrentPlayerPosition(x, y)) {
            var current = me.getActivePlayer();
            current.moveTo(x, y);
            me.fences.clearBusy();
            me.isFenceMoved = false;
            me.isPlayerMoved = true;
        } else {
            var activeBot = me.getActiveBot();
            if (activeBot) {
                activeBot.trigger('server_turn_fail');
            }
        }
    },

    updateInfo: function () {
        this.infoModel.set({
            currentplayer: this.get('currentPlayer'),
            activeplayer : this.get('activePlayer'),
            fences       : this.players.pluck('fencesRemaining')
        });
    },

    initEvents: function () {
        var me = this;

        this.on('maketurn', this.makeTurn);

        this.fields.on('moveplayer', me.onMovePlayer, this);
        this.fields.on('beforeselectfield', function (x, y) {
            if (me.isValidCurrentPlayerPosition(x, y)) {
                this.selectField(x, y);
            }
        });
        this.on('change:activePlayer', this.updateInfo, this);
        this.on('change:currentPlayer', this.updateInfo, this);
        this.players.on('change', this.updateInfo, this);

        if (!this.isOnlineGame()) {
            this.players.on('win', function (player) {
                if (window.confirm(player + ' выиграл. Начать сначала?')) {
                    me.resetModels();
                }
            });
        }
        this.fences.on({
            'selected'                     : function (model) {
                if (me.canSelectFences() &&
                    me.fences.validateFenceAndSibling(model) &&
                    me.notBreakSomePlayerPath(model)) {

                    me.fences.clearBusy();
                    me.fences.validateAndTriggerEventOnFenceAndSibling(model, 'movefence');

                    me.players.updatePlayersPositions();
                    me.isPlayerMoved = false;
                    me.isFenceMoved = true;
                } else {
                    var activeBot = me.getActiveBot();
                    if (activeBot) {
                        activeBot.trigger('server_turn_fail');
                    }
                }
            },
            'highlight_current_and_sibling': function (model) {
                if (me.canSelectFences()) {
                    me.fences.validateAndTriggerEventOnFenceAndSibling(model, 'markfence');
                }
            },
            'reset_current_and_sibling'    : function (model) {
                me.fences.triggerEventOnFenceAndSibling(model, 'unmarkfence');
            }
        });
    },
    run: function (activePlayer, currentPlayer) {
        this.set({
            activePlayer: activePlayer,
            currentPlayer: _.isUndefined(currentPlayer) ? activePlayer : currentPlayer
        });
        this.history.initPlayers();
        this.connectBots();
    },
    connectBots: function () {
        if (_.isUndefined(this.get('botsCount'))) {
            return;
        }

        var turns = this.history.get('turns').toJSON();

        _(this.get('botsCount')).times(function (i) {
            var botIndex = i + (this.get('playersCount') - this.get('botsCount'));
            var bot = new SmartBot(botIndex, this);

            bot.on('client_move_player', this.onSocketMovePlayer, this);
            bot.on('client_move_fence', function (pos) {
                if (this.onSocketMoveFence(pos) === false) {
                    var activeBot = this.getActiveBot();
                    if (activeBot) {
                        activeBot.trigger('server_turn_fail');
                    }
                }
            }, this);

            bot.trigger('server_start', botIndex, this.get('activePlayer'), turns);

            this.bots.push(bot);
        }, this);
    },
    initialize: function () {
        this.set('playersCount', +this.get('playersCount'));
        this.set('boardSize', +this.get('boardSize'));
        this.createModels();
        this.initEvents();
        this.initModels();
        if (this.isOnlineGame()) {
            this.socketEvents();
        } else {
            this.on('confirmturn', this.makeTurn);
            this.run(0, 0);
        }
    }
});
_.extend(BoardModel.prototype, window.BoardValidation);
_.extend(BoardModel.prototype, window.BoardSocketEvents);<|endoftext|>


<commit_before>({
  name: 'event-error',
  description: 'Event "error"',
  spec: 'http://dev.w3.org/html5/spec/the-iframe-element.html#event-media-error',
  assert: function(finish) {
    var audio = this.audio;

    audio.addEventListener('error', function() {
      finish(true); // WIN
    }, false);

    audio.addEventListener('loadedmetadata', function() {
      audio.src = 'invalid:url';
    }, false);

    audio.src = AWPY.sound.mini.stream_url();
  }
})
<commit_msg>Simplify event-error<commit_after>({
  name: 'event-error',
  description: 'Event "error"',
  spec: 'http://dev.w3.org/html5/spec/the-iframe-element.html#event-media-error',
  assert: function(finish) {
    var audio = this.audio;

    audio.addEventListener('error', function() {
      finish(true); // WIN
    }, false);

    audio.src = 'invalid:url';
  }
})
<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleHauler = {

    /** @param {Creep} creep **/

    run: function(creep) {

        var notEmptyContainers = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) =>  structure.structureType == STRUCTURE_CONTAINER &&
                                            structure.store[RESOURCE_ENERGY] > 0

        })
        console.log(notEmptyContainers.length);
        var notFullStoragePlaces = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => {
                    return (structure.structureType == STRUCTURE_STORAGE) &&
                        (_.sum(structure.store) < structure.storeCapacity)
                    }
        })

        if(creep.memory.transporting && creep.carry.energy == 0) {
            creep.memory.transporting = false;
            creep.memory.idling = false;
            creep.say("C-Travelling");
        } else if (!creep.memory.transporting && creep.carry.energy == creep.carryCapacity || ((!creep.pos.findClosestByPath(notFullStoragePlaces)) && creep.carry.energy > 0)) {
            creep.memory.transporting = true;
            creep.memory.idling = false;
            creep.say("C-Xporting");
        } else if (notEmptyContainers.length = 0) {
            creep.memory.transporting = false;
            creep.memory.idling = true;
            creep.say("C-Idling")
        }

        if (creep.memory.transporting) {
            if (notFullStoragePlaces.length > 0) {
                var notFullStorage = creep.pos.findClosestByPath(notFullStoragePlaces);
                if (creep.transfer(notFullStorage, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(notFullStorage);
                }
            }
        } else if (!creep.memory.idling) {
            creep.say(notEmptyContainers.length);
            if(notEmptyContainers.length > 0) {
                creep.say("gathering");
                var notEmptyContainer = creep.pos.findClosestByPath(notEmptyContainers);
                if (creep.withdraw(notEmptyContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(notEmptyContainer);
                }
            }
        } else {
            //idle
            var targetFlag = creep.pos.findClosestByPath([Game.flags.Flag1,Game.flags.Flag2]);
            creep.moveTo(targetFlag);
        }
    }
};

module.exports = roleHauler;<commit_msg>debugging hauler<commit_after>/**
 * Created by truthlighting on 9/14/2016.
 */
var roleHauler = {

    /** @param {Creep} creep **/

    run: function(creep) {

        var notEmptyContainers = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) =>  structure.structureType == STRUCTURE_CONTAINER &&
                                            structure.store[RESOURCE_ENERGY] > 0

        })
        console.log(notEmptyContainers.length);
        var notFullStoragePlaces = creep.room.find(FIND_STRUCTURES, {
                    filter: (structure) => structure.structureType == STRUCTURE_STORAGE &&
                                           _.sum(structure.store) < structure.storeCapacity

        })

        if(creep.memory.transporting && creep.carry.energy == 0) {
            creep.memory.transporting = false;
            creep.memory.idling = false;
            creep.say("C-Travelling");
        } else if (!creep.memory.transporting && creep.carry.energy == creep.carryCapacity || ((!creep.pos.findClosestByPath(notFullStoragePlaces)) && creep.carry.energy > 0)) {
            creep.memory.transporting = true;
            creep.memory.idling = false;
            creep.say("C-Xporting");
        } else if (notEmptyContainers.length = 0) {
            creep.memory.transporting = false;
            creep.memory.idling = true;
            creep.say("C-Idling")
        }

        if (creep.memory.transporting) {
            if (notFullStoragePlaces.length > 0) {
                var notFullStorage = creep.pos.findClosestByPath(notFullStoragePlaces);
                if (creep.transfer(notFullStorage, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(notFullStorage);
                }
            }
        } else if (!creep.memory.idling) {
            creep.say(notEmptyContainers.length);
            if(notEmptyContainers.length > 0) {
                creep.say("gathering");
                var notEmptyContainer = creep.pos.findClosestByPath(notEmptyContainers);
                if (creep.withdraw(notEmptyContainer, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                    creep.moveTo(notEmptyContainer);
                }
            }
        } else {
            //idle
            var targetFlag = creep.pos.findClosestByPath([Game.flags.Flag1,Game.flags.Flag2]);
            creep.moveTo(targetFlag);
        }
    }
};

module.exports = roleHauler;<|endoftext|>


<commit_before>var tasks = require('tasks')

module.exports = {
	run : function(creep){
		if(creep.memory.delivering && creep.carry.energy == 0) {
            creep.memory.delivering = false;
            creep.say('getting');
	    }
	    if(!creep.memory.delivering && creep.carry.energy == creep.carryCapacity) {
	        creep.memory.delivering = true;
	        creep.say('delivering');
		}
		if(creep.memory.delivering){
			var mylist=[STRUCTURE_SPAWN,STRUCTURE_EXTENSION,STRUCTURE_TOWER,STRUCTURE_STORAGE];
			tasks.fill(creep,mylist);
		}
		else{
			var sources = creep.room.find(FIND_SOURCES);
			var mysource = sources[0]
			tasks.getenergy(creep,mysource);
		}
	}
}
<commit_msg>runners now pick up recycled energy<commit_after>var tasks = require('tasks')

module.exports = {
	run : function(creep){
		if(creep.memory.delivering && creep.carry.energy == 0) {
            creep.memory.delivering = false;
            creep.say('getting');
	    }
	    if(!creep.memory.delivering && creep.carry.energy == creep.carryCapacity) {
	        creep.memory.delivering = true;
	        creep.say('delivering');
		}
		if(creep.memory.delivering){
			var mylist=[STRUCTURE_SPAWN,STRUCTURE_EXTENSION,STRUCTURE_TOWER,STRUCTURE_STORAGE];
			tasks.fill(creep,mylist);
		}
		else{
			var spawn = creep.room.find(FIND_STRUCTURES,{filter: (s) => s.structureType == STRUCTURE_SPAWN});
			var dropped = spawn.pos.findInRange(FIND_DROPPED_ENERGY,1); //energy dropped from recycling
			if(dropped.length){
				tasks.pick(creep,dropped[0]);
			}
			else{
				var sources = creep.room.find(FIND_SOURCES);
				var mysource = sources[0]
				tasks.getenergy(creep,mysource);
			}
		}
	}
}
<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/20/2016.
 */
module.exports = {
    roleExists: function(role){
        try
        {
            if(!require("roles_" + role)) throw "roles_" + role + " does not exist.";
            return true;
        }
        catch(e)
        {
            console.log("Error: Role " + e);
            return false;
        }
    },

    getRole: function(role)
    {
        if(!this.roleExists(role))
            return false;

        var proto = require('role_prototype');

        var roleObject = require("roles_" + role);
        roleObject = require('extend')(roleObject, proto);
        return roleObject;
    },

    getRoleBodyParts: function(role) {
        if (!this.roleExists(role))
            return false;

        var roleObject = this.getRole(role);
        console.log("roleObject: " + roleObject);
        if (roleObject.getParts !== undefined) {
            //console.log("role.getParts.call(role): " + role.getParts.call(role));
            console.log("returning A");
            return roleObject.getParts.call(role);
        } else
        {
            console.log("returning B");
            return roleObject.prototype.getParts.call(role);
        }
    }
};<commit_msg>fixing miner<commit_after>/**
 * Created by truthlighting on 9/20/2016.
 */
module.exports = {
    roleExists: function(role){
        try
        {
            if(!require("roles_" + role)) throw "roles_" + role + " does not exist.";
            return true;
        }
        catch(e)
        {
            console.log("Error: Role " + e);
            return false;
        }
    },

    getRole: function(role)
    {
        if(!this.roleExists(role))
            return false;

        var proto = require('role_prototype');

        var roleObject = require("roles_" + role);
        roleObject = require('extend')(roleObject, proto);
        return roleObject;
    },

    getRoleBodyParts: function(role) {
        if (!this.roleExists(role))
            return false;

        var roleObject = this.getRole(role);
        console.log("roleObject: " + roleObject + " role: " + role);
        if (roleObject.getParts !== undefined) {
            //console.log("role.getParts.call(role): " + role.getParts.call(role));
            console.log("returning A");
            return roleObject.getParts.call(role);
        } else
        {
            console.log("returning B");
            return roleObject.prototype.getParts.call(role);
        }
    }
};<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var path = require('path');

var React = require('react');
var Router = require('react-router');
var sass = require('node-sass');

var routesMap = {
  'grommet-core': require('../docs/src/routes')('/docs/'),
  aruba: require('../docs/src/routes')('/docs/aruba'),
  hpe: require('../docs/src/routes')('/docs/hpe'),
  hpinc: require('../docs/src/routes')('/docs/hpinc')
}

function themeCompiler(theme) {
  return sass.renderSync({
    file: path.resolve(__dirname, '../docs/node_modules/grommet/scss/' + theme + '/index'),
    includePaths: [path.resolve(__dirname, '../node_modules')]
  });
}

// Convert static resources defined by relative URLs when using HTML5 pushState
function translateStatics(req, res, next, theme) {
  if (req.url.match(/.+\/img\//)) { // img
    res.redirect(301, req.url.replace(/.*\/(img\/.*)$/, "/docs/" + theme + "$1"));
  } else if (req.url.match(/\/img\//)) { // img
    next();
  } else if (req.url.match(/.+\/font\//)) { // font
    res.redirect(301, req.url.replace(/.*\/(font\/.*)$/, "/docs/" + theme + "$1"));
  } else if (req.url.match(/\/font\//)) { // font
    next();
  } else if (req.url.match(/.+\/.*\.[^\/]*$/)) { // file
    res.redirect(301, req.url.replace(/.*\/([^\/]*)$/, "/docs/" + theme + "$1"));
  } else {
    next();
  }
}

function processPage(req, res, theme) {
  var reactRouter = Router.create({location: '/docs' + req.url, routes: routesMap[theme]});
  reactRouter.run(function(Handler, state) {
    var html = React.renderToString(<Handler/>);
    res.render('index.ejs', {appBody: html, styleContent: '<style>' + themeCompiler(theme).css + '</style>'});
  });
}

router.use('/hpe', function(req, res, next) {
  translateStatics(req, res, next, 'hpe/');
});
router.use('/hpe', function (req, res, next) {
  if (req.url === '/') {
    processPage(req, res, 'hpe');
  } else {
    next();
  }
});
router.use('/hpe', express.static(path.join(__dirname, '/../docs/dist/hpe')));
router.get('/hpe/*', function(req, res) {
  processPage(req, res, 'hpe');
});

router.use('/hpinc', function(req, res, next) {
  translateStatics(req, res, next, 'hpinc/');
});
router.use('/hpinc', function (req, res, next) {
  if (req.url === '/') {
    processPage(req, res, 'hpinc');
  } else {
    next();
  }
});
router.use('/hpinc', express.static(path.join(__dirname, '/../docs/dist/hpinc')));
router.get('/hpinc/*', function(req, res) {
  processPage(req, res, 'hpinc');
});

router.use('/aruba', function(req, res, next) {
  translateStatics(req, res, next, 'aruba/');
});
router.use('/aruba', function (req, res, next) {
  if (req.url === '/') {
    processPage(req, res, 'aruba');
  } else {
    next();
  }
});
router.use('/aruba', express.static(path.join(__dirname, '/../docs/dist/aruba')));
router.get('/aruba/*', function(req, res) {
  processPage(req, res, 'aruba');
});

router.use('/', function(req, res, next) {
  translateStatics(req, res, next, '');
});
router.use('/', function (req, res, next) {
  if (req.url === '/') {
    processPage(req, res, 'grommet-core');
  } else {
    next();
  }
});
router.use('/', express.static(path.join(__dirname, '/../docs/dist')));
router.get('/*', function(req, res) {
  processPage(req, res, 'grommet-core');
});

module.exports = router;
<commit_msg>Trying to fix issues with travis ci.<commit_after>var express = require('express');
var router = express.Router();
var path = require('path');

var React = require('react');
var Router = require('react-router');
var sass = require('node-sass');

console.log('#', __dirname, path.resolve(__dirname, '../docs/src/routes'));
var docsRoutes = require(path.resolve(__dirname, '../docs/src/routes'));

var routesMap = {
  'grommet-core': docsRoutes('/docs/'),
  aruba: docsRoutes('/docs/aruba'),
  hpe: docsRoutes('/docs/hpe'),
  hpinc: docsRoutes('/docs/hpinc')
}

function themeCompiler(theme) {
  return sass.renderSync({
    file: path.resolve(__dirname, '../docs/node_modules/grommet/scss/' + theme + '/index'),
    includePaths: [path.resolve(__dirname, '../node_modules')]
  });
}

// Convert static resources defined by relative URLs when using HTML5 pushState
function translateStatics(req, res, next, theme) {
  if (req.url.match(/.+\/img\//)) { // img
    res.redirect(301, req.url.replace(/.*\/(img\/.*)$/, "/docs/" + theme + "$1"));
  } else if (req.url.match(/\/img\//)) { // img
    next();
  } else if (req.url.match(/.+\/font\//)) { // font
    res.redirect(301, req.url.replace(/.*\/(font\/.*)$/, "/docs/" + theme + "$1"));
  } else if (req.url.match(/\/font\//)) { // font
    next();
  } else if (req.url.match(/.+\/.*\.[^\/]*$/)) { // file
    res.redirect(301, req.url.replace(/.*\/([^\/]*)$/, "/docs/" + theme + "$1"));
  } else {
    next();
  }
}

function processPage(req, res, theme) {
  var reactRouter = Router.create({location: '/docs' + req.url, routes: routesMap[theme]});
  reactRouter.run(function(Handler, state) {
    var html = React.renderToString(<Handler/>);
    res.render('index.ejs', {appBody: html, styleContent: '<style>' + themeCompiler(theme).css + '</style>'});
  });
}

router.use('/hpe', function(req, res, next) {
  translateStatics(req, res, next, 'hpe/');
});
router.use('/hpe', function (req, res, next) {
  if (req.url === '/') {
    processPage(req, res, 'hpe');
  } else {
    next();
  }
});
router.use('/hpe', express.static(path.join(__dirname, '/../docs/dist/hpe')));
router.get('/hpe/*', function(req, res) {
  processPage(req, res, 'hpe');
});

router.use('/hpinc', function(req, res, next) {
  translateStatics(req, res, next, 'hpinc/');
});
router.use('/hpinc', function (req, res, next) {
  if (req.url === '/') {
    processPage(req, res, 'hpinc');
  } else {
    next();
  }
});
router.use('/hpinc', express.static(path.join(__dirname, '/../docs/dist/hpinc')));
router.get('/hpinc/*', function(req, res) {
  processPage(req, res, 'hpinc');
});

router.use('/aruba', function(req, res, next) {
  translateStatics(req, res, next, 'aruba/');
});
router.use('/aruba', function (req, res, next) {
  if (req.url === '/') {
    processPage(req, res, 'aruba');
  } else {
    next();
  }
});
router.use('/aruba', express.static(path.join(__dirname, '/../docs/dist/aruba')));
router.get('/aruba/*', function(req, res) {
  processPage(req, res, 'aruba');
});

router.use('/', function(req, res, next) {
  translateStatics(req, res, next, '');
});
router.use('/', function (req, res, next) {
  if (req.url === '/') {
    processPage(req, res, 'grommet-core');
  } else {
    next();
  }
});
router.use('/', express.static(path.join(__dirname, '/../docs/dist')));
router.get('/*', function(req, res) {
  processPage(req, res, 'grommet-core');
});

module.exports = router;
<|endoftext|>


<commit_before>module.exports = function(data) {
  var spTimeString = new Date().toLocaleString(
    'en-US', {timeZone: 'America/Sao_Paulo'}
  );
  // FIX TODO test other dates
  // spTimeString = '8/27/2017, 10:14:55 AM';
  // FIX
  // console.log(spTimeString);
  data.today = new Date(spTimeString);
  data.today.setHours(0, 0, 0, 0);
  var todayDay = data.today.getDate() + '-' + data.today.getMonth() + '-' +
  data.today.getFullYear();
  data.todayDay = todayDay;
  data.showWelcome = true;
  data.errorDates = [];

  var news = data.news;
  for (var i = news.length - 1; i >= 0; i--) {
    var date = new Date(news[i].formatedDate);

    var dateDay = date.getDate() + '-' + date.getMonth() + '-' +
                  date.getFullYear();
    // Only send news for today
    if (dateDay === todayDay) {
      news[i] = {
        id: news[i].id,
        // NEW TODO delete in a future version
        date: date,
        testDate: dateDay,
        testToday: todayDay,
        highlight: {
          content: news[i].highlight,
          used: false,
          show: false,
          link: news[i].link
        },
        more: {
          content: news[i].more,
          used: false,
          entries: [
            {
              content: news[i].entriesContent1,
              link: news[i].entriesLink1
            },
            {
              content: news[i].entriesContent2,
              link: news[i].entriesLink2
            },
            {
              content: news[i].entriesContent3,
              link: news[i].entriesLink3
            },
            {
              content: news[i].entriesContent4,
              link: news[i].entriesLink4
            }
          ]
        },
        next: {
          content: news[i].next,
          used: false,
          hide: false
        }
      };
      // Remove unused "more" news
      for (var j = news[i].more.entries.length - 1; j >= 0; j--) {
        if (news[i].more.entries[j].content === "") {
          news[i].more.entries.splice([j], 1);
        }
      }
      // If it has no "more" news, delete the "more" object
      if (news[i].more.entries.length === 0) {
        delete news[i].more;
      }
    } else {
      news.splice([i], 1);
      data.errorDates.push(dateDay);
    }
  }

  if (data.news.length === 0) {
    var noNews = {
      date: data.today,
      todayDay: todayDay,
      noNews: true,
      highlight: {
        content: data.noNews,
        show: true,
        used: true
      }
    };
    data.news.push(noNews);
  }

  if (data.tutorialImages !== undefined && data.tutorialImages.length > 0) {
    data.tutorial = data.tutorialImages.split('\n');
    delete data.tutorialImages;
  }

  return data;
};
<commit_msg>[master] Fixed server date check<commit_after>module.exports = function(data) {
  // Fix date on São Paulo timezone
  var spDate = new Date().toLocaleString(
  'en-US',
    {
      timeZone: 'America/Sao_Paulo'
    });
  var today = new Date(spDate.split(',')[0] + ' 00:00:00 GMT-0000')
    .toISOString();

  var news = data.news;
  for (var i = news.length - 1; i >= 0; i--) {
    var date = new Date(news[i].formatedDate).toISOString();
    // DEBUG
    // console.log(today, date);
    // Only send news for today
    if (date === today) {
      news[i] = {
        id: news[i].id,
        // NEW TODO delete in a future version
        date: date,
        highlight: {
          content: news[i].highlight,
          used: false,
          show: false,
          link: news[i].link
        },
        more: {
          content: news[i].more,
          used: false,
          entries: [
            {
              content: news[i].entriesContent1,
              link: news[i].entriesLink1
            },
            {
              content: news[i].entriesContent2,
              link: news[i].entriesLink2
            },
            {
              content: news[i].entriesContent3,
              link: news[i].entriesLink3
            },
            {
              content: news[i].entriesContent4,
              link: news[i].entriesLink4
            }
          ]
        },
        next: {
          content: news[i].next,
          used: false,
          hide: false
        }
      };
      // Remove unused "more" news
      for (var j = news[i].more.entries.length - 1; j >= 0; j--) {
        if (news[i].more.entries[j].content === "") {
          news[i].more.entries.splice([j], 1);
        }
      }
      // If it has no "more" news, delete the "more" object
      if (news[i].more.entries.length === 0) {
        delete news[i].more;
      }
    } else {
      news.splice([i], 1);
    }
  }

  if (data.news.length === 0) {
    var noNews = {
      date: data.today,
      noNews: true,
      highlight: {
        content: data.noNews,
        show: true,
        used: true
      }
    };
    data.news.push(noNews);
  }

  if (data.tutorialImages !== undefined && data.tutorialImages.length > 0) {
    data.tutorial = data.tutorialImages.split('\n');
    delete data.tutorialImages;
  }

  data.showWelcome = true;

  return data;
};
<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/20/2016.
 */
/**
 * This guy just finds a source, and stays near it. His job is just to mine away and let the energy fall on the ground
 *
 * @TODO: See if we can't implement preffered spawn spots close to their source
 * @param creep
 */
var miner = {
    parts: [
        [MOVE, WORK, WORK, WORK, WORK],
        [MOVE, WORK, WORK, WORK, WORK, WORK]
    ],

    getOpenSource: function()
    {
        var creep = this.creep;

        var source = creep.pos.findClosestByPath(FIND_SOURCES, {
            filter: function(source)
            {
                if(Memory.sources[source.id] == undefined || Memory.sources[source.id].miner == undefined || Memory.sources[source.id].miner == creep.id)
                    return true;

                if(Game.getObjectById(Memory.sources[source.id].miner) == null)
                    return true;

                return false;
            }
        });

        return source;
    },

    setSourceToMine: function(source)
    {
        var creep = this.creep;

        if(!source)
            return;

        if(Memory.sources[source.id] == undefined)
            Memory.sources[source.id] = { id: source.id };

        Memory.sources[source.id].miner = creep.id;
        creep.memory.source = source.id;

        var helperSpawn = source.pos.findClosestByPath(FIND_MY_SPAWNS);
        var steps = helperSpawn.pos.findPathTo(source).length * 2;
        var creepsNeeded = Math.round((steps * 8) / 100);

        if(creepsNeeded > 5)
            creepsNeeded = 5;

        for(var i = 0; i < creepsNeeded; i++)
            Memory.spawnQue.unshift({ type: 'miner_helper', memory: {
                miner: creep.id
            }});

        console.log(creep.memory.helpersNeeded = creepsNeeded);
    },

    onSpawn: function()
    {
        var creep = this.creep;

        creep.memory.isNearSource = false;
        creep.memory.helpers = [];

        var source = this.getOpenSource();
        this.setSourceToMine(source);

        creep.memory.onCreated = true;
    },

    action: function()
    {
        var creep = this.creep;

        //Basically, each miner can empty a whole source by themselves. Also, since they're slow, we don't have them
        //moving away from the source when it's empty, it'd regenerate before they got to another one.
        //For this, we assign one miner to one source, and they stay with it
        var source = Game.getObjectById(creep.memory.source);

        if(source == null) {
            var source = this.getOpenSource();

            if(!source)
                return;

            this.setSourceToMine(source);
        }

        if(creep.pos.inRangeTo(source, 5))
            creep.memory.isNearSource = true;
        else
            creep.memory.isNearSource = false;

        if(Memory.sources[source.id] == undefined)
            Memory.sources[source.id] = { id: source.id };

        Memory.sources[source.id].miner = creep.id;
        //console.log("source: " + source);
        creep.moveTo(source);
        creep.harvest(source);
    }
};

module.exports = miner;<commit_msg>Fixing miner<commit_after>/**
 * Created by truthlighting on 9/20/2016.
 */
/**
 * This guy just finds a source, and stays near it. His job is just to mine away and let the energy fall on the ground
 *
 * @TODO: See if we can't implement preffered spawn spots close to their source
 * @param creep
 */
var miner = {
    parts: [
        [MOVE, WORK, WORK, WORK, WORK],
        [MOVE, WORK, WORK, WORK, WORK, WORK]
    ],

    getOpenSource: function()
    {
        var creep = this.creep;

        var source = creep.pos.findClosestByPath(FIND_SOURCES, {
            filter: function(source)
            {
                if(Memory.sources[source.id] == undefined || Memory.sources[source.id].miner == undefined || Memory.sources[source.id].miner == creep.id)
                    return true;

                if(Game.getObjectById(Memory.sources[source.id].miner) == null)
                    return true;

                return false;
            }
        });

        return source;
    },

    setSourceToMine: function(source)
    {
        var creep = this.creep;

        if(!source)
            return;

        if(Memory.sources[source.id] == undefined)
            Memory.sources[source.id] = { id: source.id };

        Memory.sources[source.id].miner = creep.id;
        creep.memory.source = source.id;

        var helperSpawn = source.pos.findClosestByPath(FIND_MY_SPAWNS);
        var steps = helperSpawn.pos.findPathTo(source).length * 2;
        var creepsNeeded = Math.round((steps * 8) / 100);

        if(creepsNeeded > 5)
            creepsNeeded = 5;
        console.log("gets here");
        for(var i = 0; i < creepsNeeded; i++)
            Memory.spawnQue.unshift({ type: 'miner_helper', memory: {
                miner: creep.id
            }});

        console.log(creep.memory.helpersNeeded = creepsNeeded);
    },

    onSpawn: function()
    {
        var creep = this.creep;

        creep.memory.isNearSource = false;
        creep.memory.helpers = [];

        var source = this.getOpenSource();
        this.setSourceToMine(source);

        creep.memory.onCreated = true;
    },

    action: function()
    {
        var creep = this.creep;

        //Basically, each miner can empty a whole source by themselves. Also, since they're slow, we don't have them
        //moving away from the source when it's empty, it'd regenerate before they got to another one.
        //For this, we assign one miner to one source, and they stay with it
        var source = Game.getObjectById(creep.memory.source);

        if(source == null) {
            var source = this.getOpenSource();

            if(!source)
                return;

            this.setSourceToMine(source);
        }

        if(creep.pos.inRangeTo(source, 5))
            creep.memory.isNearSource = true;
        else
            creep.memory.isNearSource = false;

        if(Memory.sources[source.id] == undefined)
            Memory.sources[source.id] = { id: source.id };

        Memory.sources[source.id].miner = creep.id;
        //console.log("source: " + source);
        creep.moveTo(source);
        creep.harvest(source);
    }
};

module.exports = miner;<|endoftext|>


<commit_before>/**
 * Created by truthlighting on 9/20/2016.
 */
/**
 * This guy just finds a source, and stays near it. His job is just to mine away and let the energy fall on the ground
 *
 * @TODO: See if we can't implement preffered spawn spots close to their source
 * @param creep
 */
var miner = {
    parts: [
        [MOVE, WORK],
        [MOVE, WORK, WORK],
        [MOVE, WORK, WORK, WORK],
        [MOVE, WORK, WORK, WORK, WORK],
        [MOVE, WORK, WORK, WORK, WORK, WORK]
    ],

    getOpenSource: function()
    {
        var creep = this.creep;

        var source = creep.pos.findClosestByPath(FIND_SOURCES, {
            filter: function(source)
            {
                if(Memory.sources[source.id] == undefined || Memory.sources[source.id].miner == undefined || Memory.sources[source.id].miner == creep.id)
                    return true;

                if(Game.getObjectById(Memory.sources[source.id].miner) == null)
                    return true;

                return false;
            }
        });

        return source;
    },

    setSourceToMine: function(source)
    {
        var creep = this.creep;

        if(!source)
            return;

        if(Memory.sources[source.id] == undefined)
            Memory.sources[source.id] = { id: source.id };

        Memory.sources[source.id].miner = creep.id;
        creep.memory.source = source.id;

        var helperSpawn = source.pos.findClosestByPath(FIND_MY_SPAWNS);
        var steps = helperSpawn.pos.findPathTo(source).length * 2;
        var creepsNeeded = Math.round((steps * 8) / 100);
        if(creepsNeeded > 5)
            creepsNeeded = 5;

        for(var i = 0; i < creepsNeeded; i++)
        {
            Memory.spawnQue.unshift('miner_helper'); // memory: {
              //  miner: creep.id
            //}});
            Memory.spawnQue[0].memory.miner = creep.id;
        }

        creep.memory.helpersNeeded = creepsNeeded;
    },

    onSpawn: function()
    {
        var creep = this.creep;

        creep.memory.isNearSource = false;
        creep.memory.helpers = [];

        var source = this.getOpenSource();
        this.setSourceToMine(source);

        creep.memory.onCreated = true;
    },

    action: function()
    {
        var creep = this.creep;

        //Basically, each miner can empty a whole source by themselves. Also, since they're slow, we don't have them
        //moving away from the source when it's empty, it'd regenerate before they got to another one.
        //For this, we assign one miner to one source, and they stay with it
        var source = Game.getObjectById(creep.memory.source);

        if(source == null) {
            var source = this.getOpenSource();

            if(!source)
                return;

            this.setSourceToMine(source);
        }

        if(creep.pos.inRangeTo(source, 5))
            creep.memory.isNearSource = true;
        else
            creep.memory.isNearSource = false;

        if(Memory.sources[source.id] == undefined)
            Memory.sources[source.id] = { id: source.id };

        Memory.sources[source.id].miner = creep.id;
        //console.log("source: " + source);
        console.log("I'm here1");
        creep.moveTo(source);
        creep.harvest(source);
    }
};

module.exports = miner;<commit_msg>fixing miner<commit_after>/**
 * Created by truthlighting on 9/20/2016.
 */
/**
 * This guy just finds a source, and stays near it. His job is just to mine away and let the energy fall on the ground
 *
 * @TODO: See if we can't implement preffered spawn spots close to their source
 * @param creep
 */
var miner = {
    parts: [
        [MOVE, WORK],
        [MOVE, WORK, WORK],
        [MOVE, WORK, WORK, WORK],
        [MOVE, WORK, WORK, WORK, WORK],
        [MOVE, WORK, WORK, WORK, WORK, WORK]
    ],

    getOpenSource: function()
    {
        var creep = this.creep;

        var source = creep.pos.findClosestByPath(FIND_SOURCES, {
            filter: function(source)
            {
                if(Memory.sources[source.id] == undefined || Memory.sources[source.id].miner == undefined || Memory.sources[source.id].miner == creep.id)
                    return true;

                if(Game.getObjectById(Memory.sources[source.id].miner) == null)
                    return true;

                return false;
            }
        });

        return source;
    },

    setSourceToMine: function(source)
    {
        var creep = this.creep;

        if(!source)
            return;

        if(Memory.sources[source.id] == undefined)
            Memory.sources[source.id] = { id: source.id };

        Memory.sources[source.id].miner = creep.id;
        creep.memory.source = source.id;

        var helperSpawn = source.pos.findClosestByPath(FIND_MY_SPAWNS);
        var steps = helperSpawn.pos.findPathTo(source).length * 2;
        var creepsNeeded = Math.round((steps * 8) / 100);
        if(creepsNeeded > 5)
            creepsNeeded = 5;

        for(var i = 0; i < creepsNeeded; i++)
        {
            Memory.spawnQue.unshift('miner_helper'); // memory: {
              //  miner: creep.id
            //}});
            Memory.spawnQue[0].memory.miner = creep.id;
        }

        creep.memory.helpersNeeded = creepsNeeded;
    },

    onSpawn: function()
    {
        var creep = this.creep;

        creep.memory.isNearSource = false;
        creep.memory.helpers = [];

        var source = this.getOpenSource();
        this.setSourceToMine(source);

        creep.memory.onCreated = true;
    },

    action: function()
    {
        var creep = this.creep;

        //Basically, each miner can empty a whole source by themselves. Also, since they're slow, we don't have them
        //moving away from the source when it's empty, it'd regenerate before they got to another one.
        //For this, we assign one miner to one source, and they stay with it
        var source = Game.getObjectById(creep.memory.source);

        if(source == null) {
            var source = this.getOpenSource();

            if(!source)
                return;

            this.setSourceToMine(source);
        }

        if(creep.pos.inRangeTo(source, 5))
            creep.memory.isNearSource = true;
        else
            creep.memory.isNearSource = false;

        if(Memory.sources[source.id] == undefined)
            Memory.sources[source.id] = { id: source.id };

        Memory.sources[source.id].miner = creep.id;
        console.log("source: " + source);

        console.log(creep.moveTo(source));
        creep.harvest(source);
    }
};

module.exports = miner;<|endoftext|>


<commit_before>
function cleanUpGamesAndPlayers(){
  var cutOff = moment().subtract(2, 'hours').toDate().getTime();
  console.log(cutOff);
  var numGamesRemoved = Games.remove({
    createdAt: {$lt: cutOff}
  });

  var numPlayersRemoved = Players.remove({
    createdAt: {$lt: cutOff}
  });

  var chatRemoved = Chat.remove({
    createdAt: {$lt: cutOff}
  });
  var newsRemoved = News.remove({
    createdAt: {$lt: cutOff}
  });
}

Meteor.startup(function () {
    Players.remove({});
    Chat.remove({});
    Games.remove({});
    News.remove({});
});

var everyMinute = new Cron(function() {
    cleanUpGamesAndPlayers();
}, {});

    Meteor.publish('games', function(accessCode) {
    return Games.find({"accessCode": accessCode});
  });

  Meteor.publish('players', function(gameID) {
    return Players.find({"gameID": gameID});
  });

   Meteor.publish('chat', function(gameID) {
    return Chat.find({"game": gameID});
  });

   Meteor.publish('news', function(gameID) {
    return News.find({"game": gameID});
  });<commit_msg>Chagned Cron time<commit_after>
function cleanUpGamesAndPlayers(){
  var cutOff = moment().subtract(2, 'hours').toDate().getTime();
  console.log(cutOff);
  var numGamesRemoved = Games.remove({
    createdAt: {$lt: cutOff}
  });

  var numPlayersRemoved = Players.remove({
    createdAt: {$lt: cutOff}
  });

  var chatRemoved = Chat.remove({
    createdAt: {$lt: cutOff}
  });
  var newsRemoved = News.remove({
    createdAt: {$lt: cutOff}
  });
}

Meteor.startup(function () {
    Players.remove({});
    Chat.remove({});
    Games.remove({});
    News.remove({});
});

var everyHour = new Cron(function() {
    cleanUpGamesAndPlayers();
}, {minute: 1});

    Meteor.publish('games', function(accessCode) {
    return Games.find({"accessCode": accessCode});
  });

  Meteor.publish('players', function(gameID) {
    return Players.find({"gameID": gameID});
  });

   Meteor.publish('chat', function(gameID) {
    return Chat.find({"game": gameID});
  });

   Meteor.publish('news', function(gameID) {
    return News.find({"game": gameID});
  });<|endoftext|>


<commit_before>const checkVersion = require('../build/check-versions');

checkVersion(); // 检查node.js和npm版本

const mongoose = require('mongoose');

const app = require('./app');
const config = require('../config/server');

const Socket = require('./models/socket');
const Group = require('./models/group');
const getRandomAvatar = require('../utils/getRandomAvatar');

global.mdb = new Map(); // 作为内存数据库使用
global.mdb.set('sealList', new Set()); // 封禁用户列表
global.mdb.set('newUserList', new Set()); // 新注册用户列表

mongoose.Promise = Promise;

mongoose.connect(config.database, async (err) => {
    if (err) {
        console.error('connect database error!');
        console.error(err);
        return process.exit(1);
    }

    // 判断默认群是否存在, 不存在就创建一个
    const group = await Group.findOne({ isDefault: true });
    if (!group) {
        const defaultGroup = await Group.create({
            name: config.defaultGroupName,
            avatar: getRandomAvatar(),
            isDefault: true,
        });
        if (!defaultGroup) {
            console.error('create default group fail');
            return process.exit(1);
        }
    }

    app.listen(config.port, async () => {
        await Socket.remove({}); // 删除Socket表所有历史数据
        console.log(` >>> server listen on http://localhost:${config.port}`);
    });
});
<commit_msg>feat: At startup, if the default group name is different from the configuration file, it is updated to the new name in the configuration file.<commit_after>const checkVersion = require('../build/check-versions');

checkVersion(); // 检查node.js和npm版本

const mongoose = require('mongoose');

const app = require('./app');
const config = require('../config/server');

const Socket = require('./models/socket');
const Group = require('./models/group');
const getRandomAvatar = require('../utils/getRandomAvatar');

global.mdb = new Map(); // 作为内存数据库使用
global.mdb.set('sealList', new Set()); // 封禁用户列表
global.mdb.set('newUserList', new Set()); // 新注册用户列表

mongoose.Promise = Promise;

mongoose.connect(config.database, async (err) => {
    if (err) {
        console.error('connect database error!');
        console.error(err);
        return process.exit(1);
    }

    // 判断默认群是否存在, 不存在就创建一个
    const group = await Group.findOne({ isDefault: true });
    if (!group) {
        const defaultGroup = await Group.create({
            name: config.defaultGroupName,
            avatar: getRandomAvatar(),
            isDefault: true,
        });
        if (!defaultGroup) {
            console.error('create default group fail');
            return process.exit(1);
        }
    } else if (group.name !== config.defaultGroupName) {
        group.name = config.defaultGroupName;
        await group.save();
    }

    app.listen(config.port, async () => {
        await Socket.remove({}); // 删除Socket表所有历史数据
        console.log(` >>> server listen on http://localhost:${config.port}`);
    });
});
<|endoftext|>


<commit_before>var Busboy = Meteor.npmRequire('busboy');
var Unzip = Meteor.npmRequire('unzip2');

// Global API configuration
var ApiV1config = {
    useDefaultAuth: true,
    prettyJson: true,
    enableCors: true,
    apipath: "/api",
    version: "v1"
};
var ApiV1 = new Restivus(ApiV1config);

// Maps to: /api/registrations
ApiV1.addRoute('registrations', {authRequired: true}, {
    get: function () {
        var regs = [];
        Registrations.find({createdBy: this.userId}).forEach(function (reg) {
            regs.push(reg);
        });
        return regs;
    }
});

// Maps to: /api/registrations/metadata
ApiV1.addRoute('registrations/metadata', {authRequired: true}, {
    get: function () {
        var regs = [];
        Registrations.find({createdBy: this.userId}).forEach(function (reg) {
            regs.push(reg);
        });
        return regs;
    }
});

// Maps to: /api/registrations/:id
ApiV1.addRoute('registrations/:id', {authRequired: true}, {
    get: function () {
        return Registrations.findOne({_id: this.urlParams.id, createdBy: this.userId});
    }
});

// Maps to: /api/smartwatchview
ApiV1.addRoute('smartwatchview', {authRequired: true}, {
    post: function () {
        console.log('Adding view data');

        var data = JSON.parse(this.bodyParams.data);

        SmartWatchView.insert({
            "date": this.bodyParams.date,
            "device": this.bodyParams.device,
            "userId": this.userId,
            "data": data
        });

        return {
            statusCode: 201
        };
    }
});

//picker
Picker.route("*",
    function (params, req, res, next) {
        //Authenticate user before further action
        console.log('x-user-id ', req.headers['x-user-id']);
        console.log('x-auth-token ', req.headers['x-auth-token']);
        var userSelector = {
            "_id": req.headers['x-user-id'],
            "services.resume.loginTokens.hashedToken": Accounts._hashLoginToken(req.headers['x-auth-token'])
        };
        console.log("userSelector: ", userSelector);
        var user = Meteor.users.findOne(userSelector);
        console.log("User: ", user);
        if (!user) {
            res.writeHead(401, {Connection: 'close'});
            res.end("Not authorized");
            return;
        }
        next();
    }
);
Picker.route(
    ApiV1config.apipath + "/" + ApiV1config.version + "/smartwatch",
    function (params, req, res, next) {
        console.log('x-user-id ', req.headers['x-user-id']);
        console.log('x-auth-token ', req.headers['x-auth-token']);

        var userSelector = {
            "_id": req.headers['x-user-id'],
            "services.resume.loginTokens.hashedToken": Accounts._hashLoginToken(req.headers['x-auth-token'])
        };
        console.log("userSelector: ", userSelector);
        var user = Meteor.users.findOne(userSelector);
        console.log("User: ", user);
        if (!user) {
            res.writeHead(401, {Connection: 'close'});
            res.end("Not authorized");
            return;
        }

        var busboy = new Busboy({headers: req.headers});
        busboy.on('file', Meteor.bindEnvironment(function (fieldname, file, filename, encoding, mimetype) {
            console.log('Receiving file [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);

            file.pipe(Unzip.Parse())
                .on('entry', Meteor.bindEnvironment(function (entry) {
                    console.log(entry);

                    var fileName = entry.path;
                    var type = entry.type; // 'Directory' or 'File'
                    var size = entry.size;
                    if (type === "File") {
                        var date = /_(\d*).csv/i.exec(fileName)[1];

                        // get stream to database
                        writeStream = SmartWatchFiles.upsertStream({
                            filename: fileName,
                            contentType: "text/csv",
                            metadata: {owner: req.headers['x-user-id'], date: date}
                        });

                        entry.pipe(writeStream);
                    } else {
                        entry.autodrain();
                    }
                }));

            file.on('end', function () {
                // res.end(Buffer.concat(bufs, bufSize));
                //          res.end();
                res.writeHead(200, {Connection: 'close'});
                res.end("Done uploading");
            });

        }));
        busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
            console.log('Field [' + fieldname + ']: value: ' + val);
        });
        busboy.on('finish', function () {
            console.log('Done parsing form!');
        });

        req.pipe(busboy);
    });

Picker.route(
    ApiV1config.apipath + "/" + ApiV1config.version + '/smartwatch/:date',
    Meteor.bindEnvironment(function (params, req, res, next) {
        console.log('x-user-id ', req.headers['x-user-id']);
        console.log('x-auth-token ', req.headers['x-auth-token']);

        var userSelector = {
            "_id": req.headers['x-user-id'],
            "services.resume.loginTokens.hashedToken": Accounts._hashLoginToken(req.headers['x-auth-token'])
        };
        console.log("userSelector: ", userSelector);
        var user = Meteor.users.findOne(userSelector);
        console.log("User: ", user);
        if (!user) {
            res.writeHead(401, {Connection: 'close'});
            res.end("Not authorized");
            return;
        }

        if (req.method == "GET") {
            console.log("download");

            var file = SmartWatchFiles.findOne({
                "metadata.date": params.date,
                "metadata.owner": req.headers['x-user-id']
            });
            console.log(file);
            if (file == null) {
                console.log('No file found!');
                res.writeHead(204, {Connection: 'close'});
                res.end("No Content found");
                return;
            }

            var fileStream = SmartWatchFiles.findOneStream({
                "metadata.date": params.date,
                "metadata.owner": req.headers['x-user-id']
            });

            res.writeHead(200, {
                'Content-Type': 'text/csv',
                'Content-Disposition': 'attachment; filename=file.csv'
            });

            fileStream.pipe(res);

            fileStream.on('error', function (err) {
                console.log('err:' + err);
            });

            fileStream.on('end', function () {
                res.end();
            });
        }
    })
);

ApiV1.addRoute('swagger.json', {authRequired: false}, {
    get: function () {
        var pat = /[^https?://][^/]*/i;
        var absurl = Meteor.absoluteUrl();
        var urlarr = pat.exec(absurl);
        var host = urlarr[0];

        return {
            "swagger": "2.0",
            "info": {
                "version": "1.0.0",
                "title": "How-R-you API",
                "description": "This API gives access to retrieve data registrations from the How-R-you database",
                "termsOfService": "http://how-r-you.dk/index.php/da/privatliv-og-betingelser",
                "contact": {
                    "name": "Morten Mathiasen"
                },
                "license": {
                    "name": "MIT"
                }
            },
            "consumes": [
                "application/x-www-form-urlencoded",
                "application/json"
            ],
            "host": host,
            "basePath": "/api/v1",
            "paths": {
                "/login": {
                    "parameters": [
                        {
                            "name": "username",
                            "in": "formData",
                            "description": "Username used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "password",
                            "in": "formData",
                            "description": "Password used to access How-R-you",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "post": {
                        "responses": {
                            "200": {
                                "description": "Login using username and password succeeded and reponse contains authentication token and user id."
                            }
                        }
                    }
                },
                "/logout": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "post": {
                        "responses": {
                            "200": {
                                "description": "Logout has successfully disabled retrieved authentication token and user id."
                            }
                        }
                    }
                },
                "/smartwatch": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "payload",
                            "in": "formData",
                            "description": "File to upload to How-R-you server",
                            "type": "file",
                            "format": "binary",
                            "required": true
                        }
                    ],
                    "post": {
                        "responses": {
                            "200": {
                                "description": "Logout has successfully disabled retrieved authentication token and user id."
                            }
                        }
                    }
                },
                "/smartwatch/{date}": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "date",
                            "in": "path",
                            "description": "Date of the file",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "get": {
                        "produces": [
                            "text/csv"
                        ],
                        "responses": {
                            "200": {
                                "description": "File for specified date.",
                                "schema": {
                                    "type": "file"
                                }
                            }
                        }
                    }
                },
                "/smartwatchview": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "date",
                            "in": "formData",
                            "description": "Date of the file",
                            "type": "string",
                            "format": "date-time",
                            "required": true
                        },
                        {
                            "name": "data",
                            "in": "formData",
                            "description": "View data",
                            "type": "string",
                            "required": true
                        },
                    ],
                    "post": {
                        "responses": {
                            "200": {
                                "description": "Successfully uploaded view data", //TODO check if full data exist for this view data
                            }
                        }
                    }
                },
                "/registrations": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "get": {
                        "responses": {
                            "200": {
                                "description": "Response contains all registrations owned by user."
                            }
                        }
                    }
                },
                "/registrations/metadata": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "get": {
                        "responses": {
                            "200": {
                                "description": "Response contains module annd field namess for registrations owned by user."
                            }
                        }
                    }
                },
                "/registrations/{id}": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "id",
                            "in": "path",
                            "description": "ID",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "get": {
                        "responses": {
                            "200": {
                                "description": "Response contains users registration for requested ID."
                            }
                        }
                    }
                }
            }
        };
    }
});
<commit_msg>Rest API to retrieve meta data<commit_after>var Busboy = Meteor.npmRequire('busboy');
var Unzip = Meteor.npmRequire('unzip2');

// Global API configuration
var ApiV1config = {
    useDefaultAuth: true,
    prettyJson: true,
    enableCors: true,
    apipath: "/api",
    version: "v1"
};
var ApiV1 = new Restivus(ApiV1config);

// Maps to: /api/registrations
ApiV1.addRoute('registrations', {authRequired: true}, {
    get: function () {
        var regs = [];
        Registrations.find({createdBy: this.userId}).forEach(function (reg) {
            regs.push(reg);
        });
        return regs;
    }
});

// Maps to: /api/registrations/metadata
ApiV1.addRoute('registrations/metadata', {authRequired: true}, {
    get: function () {
        var modules = {};
        Registrations.find({createdBy: this.userId}).forEach(function(doc){
            for (var key in doc){
                var name = doc.moduleName;
                if (!modules[name]) {
                    modules[name] = [];
                }
                if(modules[name].indexOf(key) < 0){
                    modules[name].push(key);
                }
            }
        });
        return modules;
    }
});

// Maps to: /api/registrations/:id
ApiV1.addRoute('registrations/:id', {authRequired: true}, {
    get: function () {
        return Registrations.findOne({_id: this.urlParams.id, createdBy: this.userId});
    }
});

// Maps to: /api/smartwatchview
ApiV1.addRoute('smartwatchview', {authRequired: true}, {
    post: function () {
        console.log('Adding view data');

        var data = JSON.parse(this.bodyParams.data);

        SmartWatchView.insert({
            "date": this.bodyParams.date,
            "device": this.bodyParams.device,
            "userId": this.userId,
            "data": data
        });

        return {
            statusCode: 201
        };
    }
});

//picker
Picker.route("*",
    function (params, req, res, next) {
        //Authenticate user before further action
        console.log('x-user-id ', req.headers['x-user-id']);
        console.log('x-auth-token ', req.headers['x-auth-token']);
        var userSelector = {
            "_id": req.headers['x-user-id'],
            "services.resume.loginTokens.hashedToken": Accounts._hashLoginToken(req.headers['x-auth-token'])
        };
        console.log("userSelector: ", userSelector);
        var user = Meteor.users.findOne(userSelector);
        console.log("User: ", user);
        if (!user) {
            res.writeHead(401, {Connection: 'close'});
            res.end("Not authorized");
            return;
        }
        next();
    }
);
Picker.route(
    ApiV1config.apipath + "/" + ApiV1config.version + "/smartwatch",
    function (params, req, res, next) {
        console.log('x-user-id ', req.headers['x-user-id']);
        console.log('x-auth-token ', req.headers['x-auth-token']);

        var userSelector = {
            "_id": req.headers['x-user-id'],
            "services.resume.loginTokens.hashedToken": Accounts._hashLoginToken(req.headers['x-auth-token'])
        };
        console.log("userSelector: ", userSelector);
        var user = Meteor.users.findOne(userSelector);
        console.log("User: ", user);
        if (!user) {
            res.writeHead(401, {Connection: 'close'});
            res.end("Not authorized");
            return;
        }

        var busboy = new Busboy({headers: req.headers});
        busboy.on('file', Meteor.bindEnvironment(function (fieldname, file, filename, encoding, mimetype) {
            console.log('Receiving file [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);

            file.pipe(Unzip.Parse())
                .on('entry', Meteor.bindEnvironment(function (entry) {
                    console.log(entry);

                    var fileName = entry.path;
                    var type = entry.type; // 'Directory' or 'File'
                    var size = entry.size;
                    if (type === "File") {
                        var date = /_(\d*).csv/i.exec(fileName)[1];

                        // get stream to database
                        writeStream = SmartWatchFiles.upsertStream({
                            filename: fileName,
                            contentType: "text/csv",
                            metadata: {owner: req.headers['x-user-id'], date: date}
                        });

                        entry.pipe(writeStream);
                    } else {
                        entry.autodrain();
                    }
                }));

            file.on('end', function () {
                // res.end(Buffer.concat(bufs, bufSize));
                //          res.end();
                res.writeHead(200, {Connection: 'close'});
                res.end("Done uploading");
            });

        }));
        busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
            console.log('Field [' + fieldname + ']: value: ' + val);
        });
        busboy.on('finish', function () {
            console.log('Done parsing form!');
        });

        req.pipe(busboy);
    });

Picker.route(
    ApiV1config.apipath + "/" + ApiV1config.version + '/smartwatch/:date',
    Meteor.bindEnvironment(function (params, req, res, next) {
        console.log('x-user-id ', req.headers['x-user-id']);
        console.log('x-auth-token ', req.headers['x-auth-token']);

        var userSelector = {
            "_id": req.headers['x-user-id'],
            "services.resume.loginTokens.hashedToken": Accounts._hashLoginToken(req.headers['x-auth-token'])
        };
        console.log("userSelector: ", userSelector);
        var user = Meteor.users.findOne(userSelector);
        console.log("User: ", user);
        if (!user) {
            res.writeHead(401, {Connection: 'close'});
            res.end("Not authorized");
            return;
        }

        if (req.method == "GET") {
            console.log("download");

            var file = SmartWatchFiles.findOne({
                "metadata.date": params.date,
                "metadata.owner": req.headers['x-user-id']
            });
            console.log(file);
            if (file == null) {
                console.log('No file found!');
                res.writeHead(204, {Connection: 'close'});
                res.end("No Content found");
                return;
            }

            var fileStream = SmartWatchFiles.findOneStream({
                "metadata.date": params.date,
                "metadata.owner": req.headers['x-user-id']
            });

            res.writeHead(200, {
                'Content-Type': 'text/csv',
                'Content-Disposition': 'attachment; filename=file.csv'
            });

            fileStream.pipe(res);

            fileStream.on('error', function (err) {
                console.log('err:' + err);
            });

            fileStream.on('end', function () {
                res.end();
            });
        }
    })
);

ApiV1.addRoute('swagger.json', {authRequired: false}, {
    get: function () {
        var pat = /[^https?://][^/]*/i;
        var absurl = Meteor.absoluteUrl();
        var urlarr = pat.exec(absurl);
        var host = urlarr[0];

        return {
            "swagger": "2.0",
            "info": {
                "version": "1.0.0",
                "title": "How-R-you API",
                "description": "This API gives access to retrieve data registrations from the How-R-you database",
                "termsOfService": "http://how-r-you.dk/index.php/da/privatliv-og-betingelser",
                "contact": {
                    "name": "Morten Mathiasen"
                },
                "license": {
                    "name": "MIT"
                }
            },
            "consumes": [
                "application/x-www-form-urlencoded",
                "application/json"
            ],
            "host": host,
            "basePath": "/api/v1",
            "paths": {
                "/login": {
                    "parameters": [
                        {
                            "name": "username",
                            "in": "formData",
                            "description": "Username used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "password",
                            "in": "formData",
                            "description": "Password used to access How-R-you",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "post": {
                        "responses": {
                            "200": {
                                "description": "Login using username and password succeeded and reponse contains authentication token and user id."
                            }
                        }
                    }
                },
                "/logout": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "post": {
                        "responses": {
                            "200": {
                                "description": "Logout has successfully disabled retrieved authentication token and user id."
                            }
                        }
                    }
                },
                "/smartwatch": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "payload",
                            "in": "formData",
                            "description": "File to upload to How-R-you server",
                            "type": "file",
                            "format": "binary",
                            "required": true
                        }
                    ],
                    "post": {
                        "responses": {
                            "200": {
                                "description": "Logout has successfully disabled retrieved authentication token and user id."
                            }
                        }
                    }
                },
                "/smartwatch/{date}": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "date",
                            "in": "path",
                            "description": "Date of the file",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "get": {
                        "produces": [
                            "text/csv"
                        ],
                        "responses": {
                            "200": {
                                "description": "File for specified date.",
                                "schema": {
                                    "type": "file"
                                }
                            }
                        }
                    }
                },
                "/smartwatchview": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "date",
                            "in": "formData",
                            "description": "Date of the file",
                            "type": "string",
                            "format": "date-time",
                            "required": true
                        },
                        {
                            "name": "data",
                            "in": "formData",
                            "description": "View data",
                            "type": "string",
                            "required": true
                        },
                    ],
                    "post": {
                        "responses": {
                            "200": {
                                "description": "Successfully uploaded view data", //TODO check if full data exist for this view data
                            }
                        }
                    }
                },
                "/registrations": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "get": {
                        "responses": {
                            "200": {
                                "description": "Response contains all registrations owned by user."
                            }
                        }
                    }
                },
                "/registrations/metadata": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "get": {
                        "responses": {
                            "200": {
                                "description": "Response contains module annd field namess for registrations owned by user."
                            }
                        }
                    }
                },
                "/registrations/{id}": {
                    "parameters": [
                        {
                            "name": "X-Auth-Token",
                            "in": "header",
                            "description": "Token used to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "X-User-id",
                            "in": "header",
                            "description": "User identifier to access How-R-you",
                            "type": "string",
                            "required": true
                        },
                        {
                            "name": "id",
                            "in": "path",
                            "description": "ID",
                            "type": "string",
                            "required": true
                        }
                    ],
                    "get": {
                        "responses": {
                            "200": {
                                "description": "Response contains users registration for requested ID."
                            }
                        }
                    }
                }
            }
        };
    }
});
<|endoftext|>


<commit_before>/*
 *
 * WordPres版微信小程序
 * author: jianbo
 * organization: 守望轩  www.watch-life.net
 * github:    https://github.com/iamxjb/winxin-app-watch-life.net
 * 技术支持微信号：iamxjb
 * 开源协议：MIT
 * Copyright (c) 2017 https://www.watch-life.net All rights reserved.
 */

//配置域名,域名只修改此处。
//如果wordpress没有安装在网站根目录请加上目录路径,例如："www.watch-life.net/blog"
var DOMAIN = "www.watch-life.net";
var MINAPPTYPE="0";//小程序的类型，如果是企业小程序请填：0 ，如果是个人小程序请填：1
var WEBSITENAME="守望轩"; //网站名称
var ABOUTID = 1136; //wordpress网站"页面"的id,注意这个"页面"是wordpress的"页面"，不是"文章"
var PAGECOUNT='10'; //每页文章数目
//CATEGORIESID 指定为all或者指定具体的分类id，请选择其一。
var CATEGORIESID='all';  //专题页显示全部的分类
//var CATEGORIESID = '1,1059,98,416,189,374,6,463';//指定专题页显示的分类的id
//INDEXLISTTYPE 指定为all或者指定具体的分类id，请选择其一。
var INDEXLISTTYPE="all"; //首页显示所有分类
//var INDEXLISTTYPE ="11" //指定首页显示分类的id
var PAYTEMPPLATEID = 'hzKpxuPF2rw7O-qTElkeoE0lMwr0O4t9PJkLyt6v8rk';//鼓励消息模版id
var REPLAYTEMPPLATEID = 'IiAVoBWP34u1uwt801rI_Crgen7Xl2lvAGP67ofJLo8';//回复评论消息模版id
var ZANIMAGEURL = 'https://www.watch-life.net/images/2017/07/zsm400.jpg';//微信鼓励的图片链接，用于个人小程序的赞赏
var LOGO = "../../images/logo-icon.png"; // 网站的logo图片
var POSTERIMGURL ="../../images/logo700.png"; //生成海报如果没有首图，使用此处设置的图片作为海报图片。
//设置downloadFile合法域名,不带https ,在中括号([])里增加域名，格式：{id=**,domain:'www.**.com'}，用英文逗号分隔。
//此处设置的域名和小程序与小程序后台设置的downloadFile合法域名要一致。
var DOWNLOADFILEDOMAIN = [
    { id: 1, domain: 'www.watch-life.net' },
    { id: 2, domain: 'watch-life.net' },
    { id: 3, domain: 'worldcup.minapper.com' }
];
 //首页图标导航
 //参数说明：'name'为名称，'image'为图标路径，'url'为跳转的页面，'redirecttype'为跳转的类型，apppage为本小程序的页面，miniapp为其他微信小程序,webpage为web-view的页面
 //redirecttype 是 miniapp 就是跳转其他小程序  url 为其他小程序的页面
 //redirecttype 为 apppage 就是跳转本小程序的页面，url为本小程序的页面路径
 //redirecttype 为 webpage 是跳转网址，是通过web-view打开网址，url就是你要打开的网址，不过这个网址的域名要是业务域名
 //'appid' 当redirecttype为miniapp时，这个值为其他微信小程序的appid，如果redirecttype为apppage，webpage时，这个值设置为空。
 //'extraData'当redirecttype为miniapp时，这个值为提交到其他微信小程序的参数，如果redirecttype为apppage，webpage时，这个值设置为空。
var INDEXNAV = [
  { id: '1', name: '微慕', image: '../../images/nav-icon1.png', url: 'pages/index/index', redirecttype: 'miniapp', appid: 'wx074a216a7aabc30c', extraData: '' },
  { id: '2', name: '企业版', image: '../../images/nav-icon2.png', url: 'pages/index/index', redirecttype: 'miniapp', appid: 'wxc1771b619b83316b', extraData: '' },
  { id: '3', name: '旅游版', image: '../../images/nav-icon3.png', url: 'pages/index/index', redirecttype: 'miniapp', appid: 'wxa43aaa8416cdbd61', extraData: '' },
  { id: '4', name: '图片版', image: '../../images/nav-icon4.png', url: 'pages/index/index', redirecttype: 'miniapp', appid: 'wxe9440e3d24b04152', extraData: ''},
  { id: '5', name: '微店', image: '../../images/nav-icon5.png', url: 'pages/shelf/shelf', redirecttype: 'miniapp', appid: 'wx55ea6098e41af5c4', extraData: ''}
  // { id: '6', name: '教程', image: '../../images/app.png', url: '../../pages/list/list?categoryID=1059', redirecttype: 'apppage', appid: '', extraData: ''}

    ];

export default {
  getDomain: DOMAIN,
  getWebsiteName: WEBSITENAME,
  getAboutId: ABOUTID,
  getPayTemplateId: PAYTEMPPLATEID,
  getPageCount: PAGECOUNT,
  getCategoriesID :CATEGORIESID,
  getIndexNav: INDEXNAV,
  getReplayTemplateId: REPLAYTEMPPLATEID,
  getMinAppType: MINAPPTYPE,
  getZanImageUrl: ZANIMAGEURL,
  getIndexListType: INDEXLISTTYPE,
  getLogo: LOGO,
  getPostImageUrl: POSTERIMGURL,
  getDownloadFileDomain: DOWNLOADFILEDOMAIN
}<commit_msg>update<commit_after>/*
 *
 * WordPres版微信小程序
 * author: jianbo
 * organization: 守望轩  www.watch-life.net
 * github:    https://github.com/iamxjb/winxin-app-watch-life.net
 * 技术支持微信号：iamxjb
 * 开源协议：MIT
 * Copyright (c) 2017 https://www.watch-life.net All rights reserved.
 */

//配置域名,域名只修改此处。
//如果wordpress没有安装在网站根目录请加上目录路径,例如："www.watch-life.net/blog"
var DOMAIN = "www.watch-life.net";
var MINAPPTYPE="0";//小程序的类型，如果是企业小程序请填：0 ，如果是个人小程序请填：1
var WEBSITENAME="守望轩"; //网站名称
var ABOUTID = 1136; //wordpress网站"页面"的id,注意这个"页面"是wordpress的"页面"，不是"文章"
var PAGECOUNT='10'; //每页文章数目
//CATEGORIESID 指定为all或者指定具体的分类id，请选择其一。
var CATEGORIESID='all';  //专题页显示全部的分类
//var CATEGORIESID = '1,1059,98,416,189,374,6,463';//指定专题页显示的分类的id
//INDEXLISTTYPE 指定为all或者指定具体的分类id，请选择其一。
var INDEXLISTTYPE="all"; //首页显示所有分类
//var INDEXLISTTYPE ="11" //指定首页显示分类的id
var PAYTEMPPLATEID = 'hzKpxuPF2rw7O-qTElkeoE0lMwr0O4t9PJkLyt6v8rk';//鼓励消息模版id
var REPLAYTEMPPLATEID = 'IiAVoBWP34u1uwt801rI_Crgen7Xl2lvAGP67ofJLo8';//回复评论消息模版id
var ZANIMAGEURL = 'https://www.watch-life.net/images/2017/07/zsm400.jpg';//微信鼓励的图片链接，用于个人小程序的赞赏
var LOGO = "../../images/logo-icon.png"; // 网站的logo图片
var POSTERIMGURL ="../../images/logo700.png"; //生成海报如果没有首图，使用此处设置的图片作为海报图片。
//设置downloadFile合法域名,不带https ,在中括号([])里增加域名，格式：{id=**,domain:'www.**.com'}，用英文逗号分隔。
//此处设置的域名和小程序与小程序后台设置的downloadFile合法域名要一致。
var DOWNLOADFILEDOMAIN = [
    { id: 1, domain: 'www.watch-life.net'}

];
 //首页图标导航
 //参数说明：'name'为名称，'image'为图标路径，'url'为跳转的页面，'redirecttype'为跳转的类型，apppage为本小程序的页面，miniapp为其他微信小程序,webpage为web-view的页面
 //redirecttype 是 miniapp 就是跳转其他小程序  url 为其他小程序的页面
 //redirecttype 为 apppage 就是跳转本小程序的页面，url为本小程序的页面路径
 //redirecttype 为 webpage 是跳转网址，是通过web-view打开网址，url就是你要打开的网址，不过这个网址的域名要是业务域名
 //'appid' 当redirecttype为miniapp时，这个值为其他微信小程序的appid，如果redirecttype为apppage，webpage时，这个值设置为空。
 //'extraData'当redirecttype为miniapp时，这个值为提交到其他微信小程序的参数，如果redirecttype为apppage，webpage时，这个值设置为空。
var INDEXNAV = [
  { id: '1', name: '微慕', image: '../../images/nav-icon1.png', url: 'pages/index/index', redirecttype: 'miniapp', appid: 'wx074a216a7aabc30c', extraData: '' },
  { id: '2', name: '企业版', image: '../../images/nav-icon2.png', url: 'pages/index/index', redirecttype: 'miniapp', appid: 'wxc1771b619b83316b', extraData: '' },
  { id: '3', name: '旅游版', image: '../../images/nav-icon3.png', url: 'pages/index/index', redirecttype: 'miniapp', appid: 'wxa43aaa8416cdbd61', extraData: '' },
  { id: '4', name: '图片版', image: '../../images/nav-icon4.png', url: 'pages/index/index', redirecttype: 'miniapp', appid: 'wxe9440e3d24b04152', extraData: ''},
  { id: '5', name: '微店', image: '../../images/nav-icon5.png', url: 'pages/shelf/shelf', redirecttype: 'miniapp', appid: 'wx55ea6098e41af5c4', extraData: ''}
  // { id: '6', name: '教程', image: '../../images/app.png', url: '../../pages/list/list?categoryID=1059', redirecttype: 'apppage', appid: '', extraData: ''}

    ];

export default {
  getDomain: DOMAIN,
  getWebsiteName: WEBSITENAME,
  getAboutId: ABOUTID,
  getPayTemplateId: PAYTEMPPLATEID,
  getPageCount: PAGECOUNT,
  getCategoriesID :CATEGORIESID,
  getIndexNav: INDEXNAV,
  getReplayTemplateId: REPLAYTEMPPLATEID,
  getMinAppType: MINAPPTYPE,
  getZanImageUrl: ZANIMAGEURL,
  getIndexListType: INDEXLISTTYPE,
  getLogo: LOGO,
  getPostImageUrl: POSTERIMGURL,
  getDownloadFileDomain: DOWNLOADFILEDOMAIN
}<|endoftext|>