<commit_before>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var MatrixClientPeg = require("./MatrixClientPeg");
var MatrixTools = require("./MatrixTools");
var dis = require("./dispatcher");
var encryption = require("./encryption");
var Tinter = require("./Tinter");

class Command {
    constructor(name, paramArgs, runFn) {
        this.name = name;
        this.paramArgs = paramArgs;
        this.runFn = runFn;
    }

    getCommand() {
        return "/" + this.name;
    }

    getCommandWithArgs() {
        return this.getCommand() + " " + this.paramArgs;
    }

    run(roomId, args) {
        return this.runFn.bind(this)(roomId, args);
    }

    getUsage() {
        return "Usage: " + this.getCommandWithArgs()
    }
}

var reject = function(msg) {
    return {
        error: msg
    };
};

var success = function(promise) {
    return {
        promise: promise
    };
};

var commands = {
    // Change your nickname
    nick: new Command("nick", "<display_name>", function(room_id, args) {
        if (args) {
            return success(
                MatrixClientPeg.get().setDisplayName(args)
            );
        }
        return reject(this.getUsage());
    }),

    // Changes the colorscheme of your current room
    tint: new Command("tint", "<color1> [<color2>]", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}))( +(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})))?$/);
            if (matches) {
                Tinter.tint(matches[1], matches[4]);
                var colorScheme = {}
                colorScheme.primary_color = matches[1];
                if (matches[4]) {
                    colorScheme.secondary_color = matches[4];
                }
                return success(
                    MatrixClientPeg.get().setRoomAccountData(
                        room_id, "org.matrix.room.color_scheme", colorScheme
                    )
                );
            }
        }
        return reject(this.getUsage());
    }),

    encrypt: new Command("encrypt", "<on|off>", function(room_id, args) {
        if (args == "on") {
            var client = MatrixClientPeg.get();
            var members = client.getRoom(room_id).currentState.members;
            var user_ids = Object.keys(members);
            return success(
                encryption.enableEncryption(client, room_id, user_ids)
            );
        }
        if (args == "off") {
            var client = MatrixClientPeg.get();
            return success(
                encryption.disableEncryption(client, room_id)
            );

        }
        return reject(this.getUsage());
    }),

    // Change the room topic
    topic: new Command("topic", "<topic>", function(room_id, args) {
        if (args) {
            return success(
                MatrixClientPeg.get().setRoomTopic(room_id, args)
            );
        }
        return reject(this.getUsage());
    }),

    // Invite a user
    invite: new Command("invite", "<userId>", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+)$/);
            if (matches) {
                return success(
                    MatrixClientPeg.get().invite(room_id, matches[1])
                );
            }
        }
        return reject(this.getUsage());
    }),

    // Join a room
    join: new Command("join", "<room_alias>", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+)$/);
            if (matches) {
                var room_alias = matches[1];
                if (room_alias[0] !== '#') {
                    return reject("Usage: /join #alias:domain");
                }
                if (!room_alias.match(/:/)) {
                    var domain = MatrixClientPeg.get().credentials.userId.replace(/^.*:/, '');
                    room_alias += ':' + domain;
                }

                // Try to find a room with this alias
                // XXX: do we need to do this? Doesn't the JS SDK suppress duplicate attempts to join the same room?
                var foundRoom = MatrixTools.getRoomForAlias(
                    MatrixClientPeg.get().getRooms(),
                    room_alias
                );

                if (foundRoom) { // we've already joined this room, view it if it's not archived.
                    var me = foundRoom.getMember(MatrixClientPeg.get().credentials.userId);
                    if (me && me.membership !== "leave") {
                        dis.dispatch({
                            action: 'view_room',
                            room_id: foundRoom.roomId
                        });
                        return success();
                    }
                }

                // otherwise attempt to join this alias.
                return success(
                    MatrixClientPeg.get().joinRoom(room_alias).then(
                    function(room) {
                        dis.dispatch({
                            action: 'view_room',
                            room_id: room.roomId
                        });
                    })
                );
            }
        }
        return reject(this.getUsage());
    }),

    part: new Command("part", "[#alias:domain]", function(room_id, args) {
        var targetRoomId;
        if (args) {
            var matches = args.match(/^(\S+)$/);
            if (matches) {
                var room_alias = matches[1];
                if (room_alias[0] !== '#') {
                    return reject(this.getUsage());
                }
                if (!room_alias.match(/:/)) {
                    var domain = MatrixClientPeg.get().credentials.userId.replace(/^.*:/, '');
                    room_alias += ':' + domain;
                }

                // Try to find a room with this alias
                var rooms = MatrixClientPeg.get().getRooms();
                for (var i = 0; i < rooms.length; i++) {
                    var aliasEvents = rooms[i].currentState.getStateEvents(
                        "m.room.aliases"
                    );
                    for (var j = 0; j < aliasEvents.length; j++) {
                        var aliases = aliasEvents[j].getContent().aliases || [];
                        for (var k = 0; k < aliases.length; k++) {
                            if (aliases[k] === room_alias) {
                                targetRoomId = rooms[i].roomId;
                                break;
                            }
                        }
                        if (targetRoomId) { break; }
                    }
                    if (targetRoomId) { break; }
                }
            }
            if (!targetRoomId) {
                return reject("Unrecognised room alias: " + room_alias);
            }
        }
        if (!targetRoomId) targetRoomId = room_id;
        return success(
            MatrixClientPeg.get().leave(targetRoomId).then(
            function() {
                dis.dispatch({action: 'view_next_room'});
            })
        );
    }),

    // Kick a user from the room with an optional reason
    kick: new Command("kick", "<userId> [<reason>]", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+?)( +(.*))?$/);
            if (matches) {
                return success(
                    MatrixClientPeg.get().kick(room_id, matches[1], matches[3])
                );
            }
        }
        return reject(this.getUsage());
    }),

    // Ban a user from the room with an optional reason
    ban: new Command("ban", "<userId> [<reason>]", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+?)( +(.*))?$/);
            if (matches) {
                return success(
                    MatrixClientPeg.get().ban(room_id, matches[1], matches[3])
                );
            }
        }
        return reject(this.getUsage());
    }),

    // Unban a user from the room
    unban: new Command("unban", "<userId>", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+)$/);
            if (matches) {
                // Reset the user membership to "leave" to unban him
                return success(
                    MatrixClientPeg.get().unban(room_id, matches[1])
                );
            }
        }
        return reject(this.getUsage());
    }),

    // Define the power level of a user
    op: new Command("op", "<userId> [<power level>]", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+?)( +(\d+))?$/);
            var powerLevel = 50; // default power level for op
            if (matches) {
                var user_id = matches[1];
                if (matches.length === 4 && undefined !== matches[3]) {
                    powerLevel = parseInt(matches[3]);
                }
                if (powerLevel !== NaN) {
                    var room = MatrixClientPeg.get().getRoom(room_id);
                    if (!room) {
                        return reject("Bad room ID: " + room_id);
                    }
                    var powerLevelEvent = room.currentState.getStateEvents(
                        "m.room.power_levels", ""
                    );
                    return success(
                        MatrixClientPeg.get().setPowerLevel(
                            room_id, user_id, powerLevel, powerLevelEvent
                        )
                    );
                }
            }
        }
        return reject(this.getUsage());
    }),

    // Reset the power level of a user
    deop: new Command("deop", "<userId>", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+)$/);
            if (matches) {
                var room = MatrixClientPeg.get().getRoom(room_id);
                if (!room) {
                    return reject("Bad room ID: " + room_id);
                }

                var powerLevelEvent = room.currentState.getStateEvents(
                    "m.room.power_levels", ""
                );
                return success(
                    MatrixClientPeg.get().setPowerLevel(
                        room_id, args, undefined, powerLevelEvent
                    )
                );
            }
        }
        return reject(this.getUsage());
    })
};

// helpful aliases
var aliases = {
    j: "join"
}

module.exports = {
    /**
     * Process the given text for /commands and perform them.
     * @param {string} roomId The room in which the command was performed.
     * @param {string} input The raw text input by the user.
     * @return {Object|null} An object with the property 'error' if there was an error
     * processing the command, or 'promise' if a request was sent out.
     * Returns null if the input didn't match a command.
     */
    processInput: function(roomId, input) {
        // trim any trailing whitespace, as it can confuse the parser for
        // IRC-style commands
        input = input.replace(/\s+$/, "");
        if (input[0] === "/" && input[1] !== "/") {
            var bits = input.match(/^(\S+?)( +(.*))?$/);
            var cmd = bits[1].substring(1).toLowerCase();
            var args = bits[3];
            if (cmd === "me") return null;
            if (aliases[cmd]) {
                cmd = aliases[cmd];
            }
            if (commands[cmd]) {
                return commands[cmd].run(roomId, args);
            }
            else {
                return reject("Unrecognised command: " + input);
            }
        }
        return null; // not a command
    },

    getCommandList: function() {
        return Object.keys(commands).sort().map(function(cmdKey) {
            return commands[cmdKey];
        });
    }
};
<commit_msg>Add /me to the list<commit_after>/*
Copyright 2015, 2016 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var MatrixClientPeg = require("./MatrixClientPeg");
var MatrixTools = require("./MatrixTools");
var dis = require("./dispatcher");
var encryption = require("./encryption");
var Tinter = require("./Tinter");

class Command {
    constructor(name, paramArgs, runFn) {
        this.name = name;
        this.paramArgs = paramArgs;
        this.runFn = runFn;
    }

    getCommand() {
        return "/" + this.name;
    }

    getCommandWithArgs() {
        return this.getCommand() + " " + this.paramArgs;
    }

    run(roomId, args) {
        return this.runFn.bind(this)(roomId, args);
    }

    getUsage() {
        return "Usage: " + this.getCommandWithArgs()
    }
}

var reject = function(msg) {
    return {
        error: msg
    };
};

var success = function(promise) {
    return {
        promise: promise
    };
};

var commands = {
    // Change your nickname
    nick: new Command("nick", "<display_name>", function(room_id, args) {
        if (args) {
            return success(
                MatrixClientPeg.get().setDisplayName(args)
            );
        }
        return reject(this.getUsage());
    }),

    // Changes the colorscheme of your current room
    tint: new Command("tint", "<color1> [<color2>]", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}))( +(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})))?$/);
            if (matches) {
                Tinter.tint(matches[1], matches[4]);
                var colorScheme = {}
                colorScheme.primary_color = matches[1];
                if (matches[4]) {
                    colorScheme.secondary_color = matches[4];
                }
                return success(
                    MatrixClientPeg.get().setRoomAccountData(
                        room_id, "org.matrix.room.color_scheme", colorScheme
                    )
                );
            }
        }
        return reject(this.getUsage());
    }),

    encrypt: new Command("encrypt", "<on|off>", function(room_id, args) {
        if (args == "on") {
            var client = MatrixClientPeg.get();
            var members = client.getRoom(room_id).currentState.members;
            var user_ids = Object.keys(members);
            return success(
                encryption.enableEncryption(client, room_id, user_ids)
            );
        }
        if (args == "off") {
            var client = MatrixClientPeg.get();
            return success(
                encryption.disableEncryption(client, room_id)
            );

        }
        return reject(this.getUsage());
    }),

    // Change the room topic
    topic: new Command("topic", "<topic>", function(room_id, args) {
        if (args) {
            return success(
                MatrixClientPeg.get().setRoomTopic(room_id, args)
            );
        }
        return reject(this.getUsage());
    }),

    // Invite a user
    invite: new Command("invite", "<userId>", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+)$/);
            if (matches) {
                return success(
                    MatrixClientPeg.get().invite(room_id, matches[1])
                );
            }
        }
        return reject(this.getUsage());
    }),

    // Join a room
    join: new Command("join", "<room_alias>", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+)$/);
            if (matches) {
                var room_alias = matches[1];
                if (room_alias[0] !== '#') {
                    return reject("Usage: /join #alias:domain");
                }
                if (!room_alias.match(/:/)) {
                    var domain = MatrixClientPeg.get().credentials.userId.replace(/^.*:/, '');
                    room_alias += ':' + domain;
                }

                // Try to find a room with this alias
                // XXX: do we need to do this? Doesn't the JS SDK suppress duplicate attempts to join the same room?
                var foundRoom = MatrixTools.getRoomForAlias(
                    MatrixClientPeg.get().getRooms(),
                    room_alias
                );

                if (foundRoom) { // we've already joined this room, view it if it's not archived.
                    var me = foundRoom.getMember(MatrixClientPeg.get().credentials.userId);
                    if (me && me.membership !== "leave") {
                        dis.dispatch({
                            action: 'view_room',
                            room_id: foundRoom.roomId
                        });
                        return success();
                    }
                }

                // otherwise attempt to join this alias.
                return success(
                    MatrixClientPeg.get().joinRoom(room_alias).then(
                    function(room) {
                        dis.dispatch({
                            action: 'view_room',
                            room_id: room.roomId
                        });
                    })
                );
            }
        }
        return reject(this.getUsage());
    }),

    part: new Command("part", "[#alias:domain]", function(room_id, args) {
        var targetRoomId;
        if (args) {
            var matches = args.match(/^(\S+)$/);
            if (matches) {
                var room_alias = matches[1];
                if (room_alias[0] !== '#') {
                    return reject(this.getUsage());
                }
                if (!room_alias.match(/:/)) {
                    var domain = MatrixClientPeg.get().credentials.userId.replace(/^.*:/, '');
                    room_alias += ':' + domain;
                }

                // Try to find a room with this alias
                var rooms = MatrixClientPeg.get().getRooms();
                for (var i = 0; i < rooms.length; i++) {
                    var aliasEvents = rooms[i].currentState.getStateEvents(
                        "m.room.aliases"
                    );
                    for (var j = 0; j < aliasEvents.length; j++) {
                        var aliases = aliasEvents[j].getContent().aliases || [];
                        for (var k = 0; k < aliases.length; k++) {
                            if (aliases[k] === room_alias) {
                                targetRoomId = rooms[i].roomId;
                                break;
                            }
                        }
                        if (targetRoomId) { break; }
                    }
                    if (targetRoomId) { break; }
                }
            }
            if (!targetRoomId) {
                return reject("Unrecognised room alias: " + room_alias);
            }
        }
        if (!targetRoomId) targetRoomId = room_id;
        return success(
            MatrixClientPeg.get().leave(targetRoomId).then(
            function() {
                dis.dispatch({action: 'view_next_room'});
            })
        );
    }),

    // Kick a user from the room with an optional reason
    kick: new Command("kick", "<userId> [<reason>]", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+?)( +(.*))?$/);
            if (matches) {
                return success(
                    MatrixClientPeg.get().kick(room_id, matches[1], matches[3])
                );
            }
        }
        return reject(this.getUsage());
    }),

    // Ban a user from the room with an optional reason
    ban: new Command("ban", "<userId> [<reason>]", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+?)( +(.*))?$/);
            if (matches) {
                return success(
                    MatrixClientPeg.get().ban(room_id, matches[1], matches[3])
                );
            }
        }
        return reject(this.getUsage());
    }),

    // Unban a user from the room
    unban: new Command("unban", "<userId>", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+)$/);
            if (matches) {
                // Reset the user membership to "leave" to unban him
                return success(
                    MatrixClientPeg.get().unban(room_id, matches[1])
                );
            }
        }
        return reject(this.getUsage());
    }),

    // Define the power level of a user
    op: new Command("op", "<userId> [<power level>]", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+?)( +(\d+))?$/);
            var powerLevel = 50; // default power level for op
            if (matches) {
                var user_id = matches[1];
                if (matches.length === 4 && undefined !== matches[3]) {
                    powerLevel = parseInt(matches[3]);
                }
                if (powerLevel !== NaN) {
                    var room = MatrixClientPeg.get().getRoom(room_id);
                    if (!room) {
                        return reject("Bad room ID: " + room_id);
                    }
                    var powerLevelEvent = room.currentState.getStateEvents(
                        "m.room.power_levels", ""
                    );
                    return success(
                        MatrixClientPeg.get().setPowerLevel(
                            room_id, user_id, powerLevel, powerLevelEvent
                        )
                    );
                }
            }
        }
        return reject(this.getUsage());
    }),

    // Reset the power level of a user
    deop: new Command("deop", "<userId>", function(room_id, args) {
        if (args) {
            var matches = args.match(/^(\S+)$/);
            if (matches) {
                var room = MatrixClientPeg.get().getRoom(room_id);
                if (!room) {
                    return reject("Bad room ID: " + room_id);
                }

                var powerLevelEvent = room.currentState.getStateEvents(
                    "m.room.power_levels", ""
                );
                return success(
                    MatrixClientPeg.get().setPowerLevel(
                        room_id, args, undefined, powerLevelEvent
                    )
                );
            }
        }
        return reject(this.getUsage());
    })
};

// helpful aliases
var aliases = {
    j: "join"
}

module.exports = {
    /**
     * Process the given text for /commands and perform them.
     * @param {string} roomId The room in which the command was performed.
     * @param {string} input The raw text input by the user.
     * @return {Object|null} An object with the property 'error' if there was an error
     * processing the command, or 'promise' if a request was sent out.
     * Returns null if the input didn't match a command.
     */
    processInput: function(roomId, input) {
        // trim any trailing whitespace, as it can confuse the parser for
        // IRC-style commands
        input = input.replace(/\s+$/, "");
        if (input[0] === "/" && input[1] !== "/") {
            var bits = input.match(/^(\S+?)( +(.*))?$/);
            var cmd = bits[1].substring(1).toLowerCase();
            var args = bits[3];
            if (cmd === "me") return null;
            if (aliases[cmd]) {
                cmd = aliases[cmd];
            }
            if (commands[cmd]) {
                return commands[cmd].run(roomId, args);
            }
            else {
                return reject("Unrecognised command: " + input);
            }
        }
        return null; // not a command
    },

    getCommandList: function() {
        // Return all the commands plus /me which isn't handled like normal commands
        var cmds = Object.keys(commands).sort().map(function(cmdKey) {
            return commands[cmdKey];
        })
        cmds.push(new Command("me", "<action>", function(){}));

        return cmds;
    }
};
<|endoftext|>


<commit_before>
/**
 * Bucket constructor
 */
var Bucket = function Bucket() {

};
<commit_msg>Added ordinal buckets to Bucket<commit_after>
/**
 * Bucket constructor
 */
var Bucket = function Bucket() {

};

/**
 * Ordinal Bitmasks
 */
Bucket.FIRST = 1;
Bucket.SECOND = 2;
Bucket.THIRD = 4;
Bucket.FOURTH = 8;
Bucket.FIFTH = 16;
Bucket.SIXTH = 32;
Bucket.SEVENTH = 64;
Bucket.EIGHTH = 128;
Bucket.NINTH = 256;
Bucket.TENTH = 512;
Bucket.ALL = 1023;
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, { Component } from 'react';
import { Platform,TextInput, ScrollView, Button, Alert, Linking, StyleSheet, Text, View, PermissionsAndroid } from 'react-native';

import { OpenVidu } from 'openvidu-browser';
import { RTCView } from './node_modules/openvidu-browser/node_modules/react-native-webrtc';
import axios from 'axios';

const OPENVIDU_SERVER_URL = 'https://demos.openvidu.io:4443';
const OPENVIDU_SERVER_SECRET = 'MY_SECRET';

type Props = {};
export default class App extends Component<Props> {
    constructor(props) {
        super(props);

        this.state = {
            mySessionId: 'SessionA',
            myUserName: 'Participant' + Math.floor(Math.random() * 100),
            session: undefined,
            mainStreamManager: undefined,
            subscribers: [],
            role: 'PUBLISHER',
        };
    }

    componentDidMount() {
    }

    componentWillUnmount() {
        this.leaveSession();
    }

    async checkAndroidPermissions() {
        try {
            const camera = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA, {
                title: 'Camera Permission',
                message: 'OpenVidu needs access to your camera',
                buttonNeutral: 'Ask Me Later',
                buttonNegative: 'Cancel',
                buttonPositive: 'OK',
            });
            const audio = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, {
                title: 'Aduio Permission',
                message: 'OpenVidu needs access to your microphone',
                buttonNeutral: 'Ask Me Later',
                buttonNegative: 'Cancel',
                buttonPositive: 'OK',
            });
            const storage = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, {
                title: 'STORAGE',
                message: 'OpenVidu  needs access to your storage ',
                buttonNeutral: 'Ask Me Later',
                buttonNegative: 'Cancel',
                buttonPositive: 'OK',
            });
            if (camera === PermissionsAndroid.RESULTS.GRANTED) {
                console.log('You can use the camera');
            } else {
                console.log('Camera permission denied');
            }
            if (audio === PermissionsAndroid.RESULTS.GRANTED) {
                console.log('You can use the audio');
            } else {
                console.log('audio permission denied');
            }
            if (storage === PermissionsAndroid.RESULTS.GRANTED) {
                console.log('You can use the storage');
            } else {
                console.log('storage permission denied');
            }
        } catch (err) {
            console.warn(err);
        }
    }

    joinSession() {
        // --- 1) Get an OpenVidu object ---

        this.OV = new OpenVidu();

        // --- 2) Init a session ---

        this.setState(
            {
                session: this.OV.initSession(),
            },
            () => {
                var mySession = this.state.session;
                // --- 3) Specify the actions when events take place in the session ---

                // On every new Stream received...
                mySession.on('streamCreated', (event) => {
                    // Subscribe to the Stream to receive it. Second parameter is undefined
                    // so OpenVidu doesn't create an HTML video by its own
                    const subscriber = mySession.subscribe(event.stream, undefined);

                    var subscribers = this.state.subscribers;

                    subscribers.push(subscriber);
                    // Update the state with the new subscribers
                    this.setState({
                        subscribers: subscribers,
                    });
                });

                // On every Stream destroyed...
                mySession.on('streamDestroyed', (event) => {
                    event.preventDefault();
                    // Remove the stream from 'subscribers' array
                    this.deleteSubscriber(event.stream.streamManager);
                });

                // --- 4) Connect to the session with a valid user token ---
                // 'getToken' method is simulating what your server-side should do.
                // 'token' parameter should be retrieved and returned by your own backend
                this.getToken()
                    .then((token) => {
                        // First param is the token got from OpenVidu Server. Second param can be retrieved by every user on event
                        // 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
                        mySession
                            .connect(token, { clientData: this.state.myUserName })
                            .then(() => {
                                console.log('SESSION CONNECTED', Platform);
                                if (Platform.OS == 'android') {
                                    this.checkAndroidPermissions();
                                }

                                // --- 5) Get your own camera stream ---
                                if (this.state.role !== 'SUBSCRIBER') {
                                    // Init a publisher passing undefined as targetElement (we don't want OpenVidu to insert a video
                                    // element: we will manage it on our own) and with the desired properties
                                    let publisher = this.OV.initPublisher(undefined, {
                                        audioSource: undefined, // The source of audio. If undefined default microphone
                                        videoSource: undefined, // The source of video. If undefined default webcam
                                        publishAudio: true, // Whether you want to start publishing with your audio unmuted or not
                                        publishVideo: true, // Whether you want to start publishing with your video enabled or not
                                        resolution: '640x480', // The resolution of your video
                                        frameRate: 30, // The frame rate of your video
                                        insertMode: 'APPEND', // How the video is inserted in the target element 'video-container'
                                    });

                                    // --- 6) Publish your stream ---

                                    // Set the main video in the page to display our webcam and store our Publisher
                                    this.setState({
                                        mainStreamManager: publisher
                                    });
                                    mySession.publish(publisher);
                                }

                            })
                            .catch((error) => {
                                console.log('There was an error connecting to the session:', error.code, error.message);
                            });
                    })
                    .catch((error) => console.log('Error', error));
            },
        );
    }

    getNicknameTag(stream) {
        // Gets the nickName of the user
        if(stream.connection && JSON.parse(stream.connection.data) && JSON.parse(stream.connection.data).clientData) {
            return JSON.parse(stream.connection.data).clientData;
        }
        return '';
    }

    deleteSubscriber(streamManager) {
        setTimeout(() => {
            let subscribers = this.state.subscribers;
            const index = subscribers.indexOf(streamManager, 0);
            if (index > -1) {
                subscribers.splice(index, 1);
                this.setState({
                    subscribers: subscribers,
                });
            }
        });
    }

    leaveSession() {
        // --- 7) Leave the session by calling 'disconnect' method over the Session object ---

        const mySession = this.state.session;

        if (mySession) {
            mySession.disconnect();
        }

        // Empty all properties...
        setTimeout(() => {
            this.OV = null;
            this.setState({
                session: undefined,
                subscribers: [],
                mySessionId: 'SessionA',
                myUserName: 'Participant' + Math.floor(Math.random() * 100),
                mainStreamManager: undefined,
                publisher: undefined,
            });
        })

    }

    toggleCamera(){
        this.state.mainStreamManager.stream.getMediaStream().getVideoTracks()[0]._switchCamera();
    }

    render() {

        return (
            <ScrollView>
                {this.state.mainStreamManager ? (
                    <View>
                    <View style={styles.container}>
                        <Text>Session: {this.state.mySessionId}</Text>
                        <Text>{this.getNicknameTag(this.state.mainStreamManager.stream)}</Text>
                        <RTCView zOrder={0}  objectFit="cover"
                            ref={(rtcVideo) => {
                                if (!!rtcVideo) {
                                    this.state.mainStreamManager.addVideoElement(rtcVideo);
                                }
                            }}
                            style={styles.selfView}
                        />
                    </View>
                    <View>
                        <Button
                            onLongPress={() => this.toggleCamera()}
                            onPress={() => this.toggleCamera()}
                            title="Toggle Camera"
                            color="#841584"
                            />
                            <Button
                            onLongPress={() => this.leaveSession()}
                            onPress={() => this.leaveSession()}
                            title="Leave Session"
                            color="#ff0000"
                            />
                    </View>
                    </View>
                ) : (
                    <View style={{
                        flex: 1,
                        flexDirection: 'column',
                        justifyContent: 'center',
                        alignItems: 'stretch',
                        height: '100%',
                        paddingTop: 100
                      }}>
                        <TextInput
                            style={{height: 40, borderColor: 'gray', borderWidth: 1}}
                            onChangeText={(mySessionId) => this.setState({mySessionId})}
                            value={this.state.mySessionId}
                        />
                        <Button
                            onLongPress={() => this.joinSession()}
                            onPress={() => this.joinSession()}
                            title="Join"
                            color="#841584"
                            style={{width: '100%'}}
                            />
                    </View>
                )}

                <View style={[styles.container, {flexDirection: 'row', flexWrap: 'wrap'}] }>
                    {this.state.subscribers.map((item, index) => {
                        if(!!item){
                            return (
                                <View key={index}>
                                    <Text>{this.getNicknameTag(item.stream)}</Text>
                                    <RTCView zOrder={0}  objectFit="cover" style={styles.remoteView}  ref={(rtcVideo) => {
                                        if (!!rtcVideo){
                                            item.addVideoElement(rtcVideo);
                                        }
                                    }} />
                                </View>
                            )
                        }
                    })}
                </View>
            </ScrollView>
        );
    }

    /**
     * --------------------------
     * SERVER-SIDE RESPONSIBILITY
     * --------------------------
     * These methods retrieve the mandatory user token from OpenVidu Server.
     * This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
     * the API REST, openvidu-java-client or openvidu-node-client):
     *   1) Initialize a session in OpenVidu Server	(POST /api/sessions)
     *   2) Generate a token in OpenVidu Server		(POST /api/tokens)
     *   3) The token must be consumed in Session.connect() method
     */

    getToken() {
        return this.createSession(this.state.mySessionId)
            .then((sessionId) => this.createToken(sessionId))
            .catch((error) => console.log(error));
    }

    createSession(sessionId) {
        return new Promise((resolve) => {

            var data = JSON.stringify({ customSessionId: sessionId });
            axios
                .post(OPENVIDU_SERVER_URL + '/api/sessions', data, {
                    headers: {
                        Authorization: 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                })
                .then((response) => {
                    console.log('CREATE SESION', response);
                    resolve(response.data.id);
                })
                .catch((response) => {
                    console.log(response);
                    var error = Object.assign({}, response);
                    if (error.response.status === 409) {
                        console.log('RESOLVING WITH SESSIONID, 409');
                        resolve(sessionId);
                    } else {
                        console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + OPENVIDU_SERVER_URL);

                        Alert.alert(
                            'No connection to OpenVidu Server.',
                            'This may be a certificate error at "' +
                                OPENVIDU_SERVER_URL +
                                '"\n\nClick OK to navigate and accept it. ' +
                                'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' +
                                OPENVIDU_SERVER_URL +
                                '"',
                            [
                                {
                                    text: 'Cancel',
                                    onPress: () => console.log('Cancel Pressed'),
                                    style: 'cancel',
                                },
                                {
                                    text: 'OK',
                                    onPress: () =>
                                        Linking.openURL(OPENVIDU_SERVER_URL + '/accept-certificate').catch((err) =>
                                            console.error('An error occurred', err),
                                        ),
                                },
                            ],
                            { cancelable: false },
                        );
                    }
                });
        });
    }

    createToken(sessionId) {
        return new Promise((resolve, reject) => {
            var data = JSON.stringify({ session: sessionId });
            axios
                .post(OPENVIDU_SERVER_URL + '/api/tokens', data, {
                    headers: {
                        Authorization: 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
                        'Content-Type': 'application/json',
                    },
                })
                .then((response) => {
                    console.log('TOKEN', response);
                    resolve(response.data.token);
                })
                .catch((error) => reject(error));
        });
    }
}

const styles = StyleSheet.create({
    container: {
        justifyContent: 'center',
        alignItems: 'center',
        flex: 1,
        paddingTop: Platform.OS == 'ios' ? 20 : 0
    },
    selfView: {
        width: 200,
        height: 200,
    },
    remoteView: {
        width: 150,
        height: 150,
    },
});
<commit_msg>openvidu-react-native: Removed unnecessary logs<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, { Component } from 'react';
import { Platform,TextInput, ScrollView, Button, Alert, Linking, StyleSheet, Text, View, PermissionsAndroid } from 'react-native';

import { OpenVidu } from 'openvidu-browser';
import { RTCView } from './node_modules/openvidu-browser/node_modules/react-native-webrtc';
import axios from 'axios';

const OPENVIDU_SERVER_URL = 'https://demos.openvidu.io:4443';
const OPENVIDU_SERVER_SECRET = 'MY_SECRET';

type Props = {};
export default class App extends Component<Props> {
    constructor(props) {
        super(props);

        this.state = {
            mySessionId: 'SessionA',
            myUserName: 'Participant' + Math.floor(Math.random() * 100),
            session: undefined,
            mainStreamManager: undefined,
            subscribers: [],
            role: 'PUBLISHER',
        };
    }

    componentDidMount() {
    }

    componentWillUnmount() {
        this.leaveSession();
    }

    async checkAndroidPermissions() {
        try {
            const camera = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.CAMERA, {
                title: 'Camera Permission',
                message: 'OpenVidu needs access to your camera',
                buttonNeutral: 'Ask Me Later',
                buttonNegative: 'Cancel',
                buttonPositive: 'OK',
            });
            const audio = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, {
                title: 'Aduio Permission',
                message: 'OpenVidu needs access to your microphone',
                buttonNeutral: 'Ask Me Later',
                buttonNegative: 'Cancel',
                buttonPositive: 'OK',
            });
            const storage = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, {
                title: 'STORAGE',
                message: 'OpenVidu  needs access to your storage ',
                buttonNeutral: 'Ask Me Later',
                buttonNegative: 'Cancel',
                buttonPositive: 'OK',
            });
            if (camera === PermissionsAndroid.RESULTS.GRANTED) {
                console.log('You can use the camera');
            } else {
                console.log('Camera permission denied');
            }
            if (audio === PermissionsAndroid.RESULTS.GRANTED) {
                console.log('You can use the audio');
            } else {
                console.log('audio permission denied');
            }
            if (storage === PermissionsAndroid.RESULTS.GRANTED) {
                console.log('You can use the storage');
            } else {
                console.log('storage permission denied');
            }
        } catch (err) {
            console.warn(err);
        }
    }

    joinSession() {
        // --- 1) Get an OpenVidu object ---

        this.OV = new OpenVidu();

        // --- 2) Init a session ---

        this.setState(
            {
                session: this.OV.initSession(),
            },
            () => {
                var mySession = this.state.session;
                // --- 3) Specify the actions when events take place in the session ---

                // On every new Stream received...
                mySession.on('streamCreated', (event) => {
                    // Subscribe to the Stream to receive it. Second parameter is undefined
                    // so OpenVidu doesn't create an HTML video by its own
                    const subscriber = mySession.subscribe(event.stream, undefined);

                    var subscribers = this.state.subscribers;

                    subscribers.push(subscriber);
                    // Update the state with the new subscribers
                    this.setState({
                        subscribers: subscribers,
                    });
                });

                // On every Stream destroyed...
                mySession.on('streamDestroyed', (event) => {
                    event.preventDefault();
                    // Remove the stream from 'subscribers' array
                    this.deleteSubscriber(event.stream.streamManager);
                });

                // --- 4) Connect to the session with a valid user token ---
                // 'getToken' method is simulating what your server-side should do.
                // 'token' parameter should be retrieved and returned by your own backend
                this.getToken()
                    .then((token) => {
                        // First param is the token got from OpenVidu Server. Second param can be retrieved by every user on event
                        // 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
                        mySession
                            .connect(token, { clientData: this.state.myUserName })
                            .then(() => {

                                if (Platform.OS == 'android') {
                                    this.checkAndroidPermissions();
                                }

                                // --- 5) Get your own camera stream ---
                                if (this.state.role !== 'SUBSCRIBER') {
                                    // Init a publisher passing undefined as targetElement (we don't want OpenVidu to insert a video
                                    // element: we will manage it on our own) and with the desired properties
                                    let publisher = this.OV.initPublisher(undefined, {
                                        audioSource: undefined, // The source of audio. If undefined default microphone
                                        videoSource: undefined, // The source of video. If undefined default webcam
                                        publishAudio: true, // Whether you want to start publishing with your audio unmuted or not
                                        publishVideo: true, // Whether you want to start publishing with your video enabled or not
                                        resolution: '640x480', // The resolution of your video
                                        frameRate: 30, // The frame rate of your video
                                        insertMode: 'APPEND', // How the video is inserted in the target element 'video-container'
                                    });

                                    // --- 6) Publish your stream ---

                                    // Set the main video in the page to display our webcam and store our Publisher
                                    this.setState({
                                        mainStreamManager: publisher
                                    });
                                    mySession.publish(publisher);
                                }

                            })
                            .catch((error) => {
                                console.log('There was an error connecting to the session:', error.code, error.message);
                            });
                    })
                    .catch((error) => console.log('Error', error));
            },
        );
    }

    getNicknameTag(stream) {
        // Gets the nickName of the user
        if(stream.connection && JSON.parse(stream.connection.data) && JSON.parse(stream.connection.data).clientData) {
            return JSON.parse(stream.connection.data).clientData;
        }
        return '';
    }

    deleteSubscriber(streamManager) {
        setTimeout(() => {
            let subscribers = this.state.subscribers;
            const index = subscribers.indexOf(streamManager, 0);
            if (index > -1) {
                subscribers.splice(index, 1);
                this.setState({
                    subscribers: subscribers,
                });
            }
        });
    }

    leaveSession() {
        // --- 7) Leave the session by calling 'disconnect' method over the Session object ---

        const mySession = this.state.session;

        if (mySession) {
            mySession.disconnect();
        }

        // Empty all properties...
        setTimeout(() => {
            this.OV = null;
            this.setState({
                session: undefined,
                subscribers: [],
                mySessionId: 'SessionA',
                myUserName: 'Participant' + Math.floor(Math.random() * 100),
                mainStreamManager: undefined,
                publisher: undefined,
            });
        })

    }

    toggleCamera(){
        this.state.mainStreamManager.stream.getMediaStream().getVideoTracks()[0]._switchCamera();
    }

    render() {

        return (
            <ScrollView>
                {this.state.mainStreamManager ? (
                    <View>
                    <View style={styles.container}>
                        <Text>Session: {this.state.mySessionId}</Text>
                        <Text>{this.getNicknameTag(this.state.mainStreamManager.stream)}</Text>
                        <RTCView zOrder={0}  objectFit="cover"
                            ref={(rtcVideo) => {
                                if (!!rtcVideo) {
                                    this.state.mainStreamManager.addVideoElement(rtcVideo);
                                }
                            }}
                            style={styles.selfView}
                        />
                    </View>
                    <View>
                        <Button
                            onLongPress={() => this.toggleCamera()}
                            onPress={() => this.toggleCamera()}
                            title="Toggle Camera"
                            color="#841584"
                            />
                            <Button
                            onLongPress={() => this.leaveSession()}
                            onPress={() => this.leaveSession()}
                            title="Leave Session"
                            color="#ff0000"
                            />
                    </View>
                    </View>
                ) : (
                    <View style={{
                        flex: 1,
                        flexDirection: 'column',
                        justifyContent: 'center',
                        alignItems: 'stretch',
                        height: '100%',
                        paddingTop: 100
                      }}>
                        <TextInput
                            style={{height: 40, borderColor: 'gray', borderWidth: 1}}
                            onChangeText={(mySessionId) => this.setState({mySessionId})}
                            value={this.state.mySessionId}
                        />
                        <Button
                            onLongPress={() => this.joinSession()}
                            onPress={() => this.joinSession()}
                            title="Join"
                            color="#841584"
                            style={{width: '100%'}}
                            />
                    </View>
                )}

                <View style={[styles.container, {flexDirection: 'row', flexWrap: 'wrap'}] }>
                    {this.state.subscribers.map((item, index) => {
                        if(!!item){
                            return (
                                <View key={index}>
                                    <Text>{this.getNicknameTag(item.stream)}</Text>
                                    <RTCView zOrder={0}  objectFit="cover" style={styles.remoteView}  ref={(rtcVideo) => {
                                        if (!!rtcVideo){
                                            item.addVideoElement(rtcVideo);
                                        }
                                    }} />
                                </View>
                            )
                        }
                    })}
                </View>
            </ScrollView>
        );
    }

    /**
     * --------------------------
     * SERVER-SIDE RESPONSIBILITY
     * --------------------------
     * These methods retrieve the mandatory user token from OpenVidu Server.
     * This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
     * the API REST, openvidu-java-client or openvidu-node-client):
     *   1) Initialize a session in OpenVidu Server	(POST /api/sessions)
     *   2) Generate a token in OpenVidu Server		(POST /api/tokens)
     *   3) The token must be consumed in Session.connect() method
     */

    getToken() {
        return this.createSession(this.state.mySessionId)
            .then((sessionId) => this.createToken(sessionId))
            .catch((error) => console.log(error));
    }

    createSession(sessionId) {
        return new Promise((resolve) => {

            var data = JSON.stringify({ customSessionId: sessionId });
            axios
                .post(OPENVIDU_SERVER_URL + '/api/sessions', data, {
                    headers: {
                        Authorization: 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                })
                .then((response) => {
                    console.log('CREATE SESION', response);
                    resolve(response.data.id);
                })
                .catch((response) => {
                    console.log(response);
                    var error = Object.assign({}, response);
                    if (error.response.status === 409) {
                        console.log('RESOLVING WITH SESSIONID, 409');
                        resolve(sessionId);
                    } else {
                        console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + OPENVIDU_SERVER_URL);

                        Alert.alert(
                            'No connection to OpenVidu Server.',
                            'This may be a certificate error at "' +
                                OPENVIDU_SERVER_URL +
                                '"\n\nClick OK to navigate and accept it. ' +
                                'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' +
                                OPENVIDU_SERVER_URL +
                                '"',
                            [
                                {
                                    text: 'Cancel',
                                    onPress: () => console.log('Cancel Pressed'),
                                    style: 'cancel',
                                },
                                {
                                    text: 'OK',
                                    onPress: () =>
                                        Linking.openURL(OPENVIDU_SERVER_URL + '/accept-certificate').catch((err) =>
                                            console.error('An error occurred', err),
                                        ),
                                },
                            ],
                            { cancelable: false },
                        );
                    }
                });
        });
    }

    createToken(sessionId) {
        return new Promise((resolve, reject) => {
            var data = JSON.stringify({ session: sessionId });
            axios
                .post(OPENVIDU_SERVER_URL + '/api/tokens', data, {
                    headers: {
                        Authorization: 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
                        'Content-Type': 'application/json',
                    },
                })
                .then((response) => {
                    console.log('TOKEN', response);
                    resolve(response.data.token);
                })
                .catch((error) => reject(error));
        });
    }
}

const styles = StyleSheet.create({
    container: {
        justifyContent: 'center',
        alignItems: 'center',
        flex: 1,
        paddingTop: Platform.OS == 'ios' ? 20 : 0
    },
    selfView: {
        width: 200,
        height: 200,
    },
    remoteView: {
        width: 150,
        height: 150,
    },
});
<|endoftext|>


<commit_before>const UTIL = require('./util');
const FS = require('fs');

module.exports = {

  getRandomEvent: function(message) {
    switch (UTIL.getRandomInt(0, 256)) {
      case 1:
        module.exports.getingRobbed(message);
        break;
      case 2:
        message.channel.send('just a placeholder for a new event');
        break;
      default:
        //message.channel.send('Just the default case for an event.\nOr should I say: You lucky bastard !!!! Nothing happend ..... ? ');
    }
  },

getingRobbed: function(message) {
  var ammount = UTIL.getRandomInt(1, 100);
  message.channel.send(message.author + ' OHHHHH NOOOO!!!!!! \nYou gabled too much and fell asleep. \n\nIn the meantime someone stole your hard earned cash....\n' + ammount + ' coins are missing');
  var path = '/tmp/' + message.author.id + '.json';
  var obj;
  if (FS.existsSync(path)) {
    var readFileInput = FS.readFileSync(path);
    obj = JSON.parse(readFileInput);
    obj.coins = Number(obj.coins) - ammount;
  }
    FS.writeFileSync(path, JSON.stringify(obj));
}
};
<commit_msg>changes i don't remember<commit_after>const UTIL = require('./util');
const FS = require('fs');

module.exports = {

  getRandomEvent: function(message) {
    switch (UTIL.getRandomInt(0, 10)) {
      case 1:
        module.exports.getingRobbed(message);
        break;
      case 2:
        message.channel.send('just a placeholder for a new event');
        break;
      case 3:
        module.exports.rainbow(message);
      default:
        //message.channel.send('Just the default case for an event.\nOr should I say: You lucky bastard !!!! Nothing happend ..... ? ');
    }
  },

getingRobbed: function(message) {
  var ammount = UTIL.getRandomInt(1, 100);
  message.channel.send(message.author + ' OHHHHH NOOOO!!!!!! \nYou gabled too much and fell asleep. \n\nIn the meantime someone stole your hard earned cash....\n' + ammount + ' coins are missing');
  var path = '/tmp/' + message.author.id + '.json';
  var obj;
  if (FS.existsSync(path)) {
    var readFileInput = FS.readFileSync(path);
    obj = JSON.parse(readFileInput);
    obj.coins = Number(obj.coins) - ammount;
  }
    FS.writeFileSync(path, JSON.stringify(obj));
}

rainbow: function(message) {
  var ammount = UTIL.getRandomInt(1, 5000);
  message.channel.send(message.author + 'Super lucky !!! \nYou found a pod of golden coins in the backyard... \n You found ' + ammount + ' coins');
  var path = '/tmp/' + message.author.id + '.json';
  var obj;
  if (FS.existsSync(path)) {
    var readFileInput = FS.readFileSync(path);
    obj = JSON.parse(readFileInput);
    obj.coins = Number(obj.coins) + ammount;
  }
    FS.writeFileSync(path, JSON.stringify(obj));
};
<|endoftext|>


<commit_before>var verification = require('./middleware/verification'),
    config = require("../config/config.js"),
    pkg = require("../package.json"),
    _ = require("underscore"),
    mongoose = require('mongoose'),
    fs = require("fs");

var passport = require("passport")
var routes = {
    base: {
        urls: [{
            type: "post",
            endpoint: "/api/ROUTE_NAME",
            method: "create"
        }, {
            type: "get",
            endpoint: "/api/ROUTE_NAME/:id",
            method: "getById"
        }, {
            type: "get",
            endpoint: "/api/ROUTE_NAME",
            method: "getAll"
        }, {
            type: "put",
            endpoint: "/api/ROUTE_NAME/:id",
            method: "update"
        }, {
            type: "put",
            endpoint: "/api/ROUTE_NAME/:id/change-position/:position",
            method: "changePosition"
        }, {
            type: "delete",
            endpoint: "/api/ROUTE_NAME/:id",
            method: "deleteById"
        }, {
            type: "delete",
            endpoint: "/api/ROUTE_NAME",
            method: "deleteAll"
        }]
    },
    user: {
        middleware: [passport.authenticate("bearer", {
            session: false
        })],
        urls: [{
            type: "post",
            endpoint: "/api/users",
            method: "register",
            middleware: []
        }, {
            type: "get",
            endpoint: "/api/users/me",
            method: "getMe"
        }, {
            type: "get",
            endpoint: "/api/users/access_token",
            method: "accessToken",
            middleware: [passport.authenticate('local', {
                session: false
            })]
        }, {
            type: "get",
            endpoint: "/api/users",
            method: "getAll"
        }, {
            type: "get",
            endpoint: "/api/users/:id",
            method: "getById"
        }, {
            type: "get",
            endpoint: "/api/users/activate/:hash",
            method: "activate"
        }, {
            type: "put",
            endpoint: "/api/users/me",
            method: "updateMe"
        }, {
            type: "put",
            endpoint: "/api/users/:id",
            method: "updateById"
        }, {
            type: "delete",
            endpoint: "/api/users/:id",
            method: "deleteById"
        }, {
            type: "delete",
            endpoint: "/api/users",
            method: "deleteAll"
        }]
    }
}

module.exports = function(app) {

    // Frontend part
    var indexController = require('./frontend/controllers/index');
    app.get('/', indexController.index);

    // API part
    app.get('/api', function(req, res) {
        res.status(200).json({
            name: pkg.name,
            version: pkg.version
        });
    });

    var baseController = require("./api/controllers/base")

    var responseCallback = function(res, status, result) {
        if (status.type == 'success') {
            res.status(status.code).json(result)
        } else {
            res.status(status.code).json(status)
        }
    }

    var generateRoute = function(route, controller, Model) {
        if (!route.middleware) {
            route.middleware = function(req, res, next) {
                next()
            }
        }
        app[route.type](route.endpoint, route.middleware, function(req, res) {

            if (controller) {
                if (Model.modelName == "User") {
                    controller[route.method](req, Model, function(status, result) {
                        responseCallback(res, status, result)
                    })
                } else {
                    controller[route.method](req, res)
                }

            } else {
                baseController[route.method](req, Model, function(status, result) {
                    responseCallback(res, status, result)
                })
            }

        })
    }

    _.each(config.models, function(model) {
        if (model.name == "User") {
            if (config.users) {
                var User = mongoose.model("User")
                var controller = require("./api/controllers/user")
                _.each(routes.user.urls, function(route) {
                    if (!route.middleware) {
                        route.middleware = routes.user.middleware
                    }
                    generateRoute(route, controller, User)
                })
            }
        } else {
            var name = model.name.toLowerCase()
            var routeName = model.routeName || name
            var path = "./api/controllers/" + name
            var exists = fs.existsSync(path)
            var controller = null
            var Model = mongoose.model(model.name)
            if (exists) {
                controller = require(path)
            }
            var modelRoutes = routes[name] || routes.base
            _.each(modelRoutes.urls, function(route) {
                if (!route.middleware) {
                    route.middleware = modelRoutes.middleware
                }
                route.endpoint = route.endpoint.replace("ROUTE_NAME", routeName)
                if (route.method == "changePosition") {
                    if (model.positionable) {
                        generateRoute(route, controller, Model)
                    }
                } else {
                    generateRoute(route, controller, Model)
                }
            })
        }
    })

    app.all('*', function(req, res) {
        res.status(404).json({
            type: 'error',
            description: 'This endpoint does not exist.'
        })
    })

}<commit_msg>updated router for other controllers<commit_after>var verification = require('./middleware/verification'),
    config = require("../config/config.js"),
    pkg = require("../package.json"),
    _ = require("underscore"),
    mongoose = require('mongoose'),
    fs = require("fs");

var passport = require("passport")
var routes = {
    base: {
        urls: [{
            type: "post",
            endpoint: "/api/ROUTE_NAME",
            method: "create"
        }, {
            type: "get",
            endpoint: "/api/ROUTE_NAME/:id",
            method: "getById"
        }, {
            type: "get",
            endpoint: "/api/ROUTE_NAME",
            method: "getAll"
        }, {
            type: "put",
            endpoint: "/api/ROUTE_NAME/:id",
            method: "update"
        }, {
            type: "put",
            endpoint: "/api/ROUTE_NAME/:id/change-position/:position",
            method: "changePosition"
        }, {
            type: "delete",
            endpoint: "/api/ROUTE_NAME/:id",
            method: "deleteById"
        }, {
            type: "delete",
            endpoint: "/api/ROUTE_NAME",
            method: "deleteAll"
        }]
    },
    user: {
        middleware: [passport.authenticate("bearer", {
            session: false
        })],
        urls: [{
            type: "post",
            endpoint: "/api/users",
            method: "register",
            middleware: []
        }, {
            type: "get",
            endpoint: "/api/users/me",
            method: "getMe"
        }, {
            type: "get",
            endpoint: "/api/users/access_token",
            method: "accessToken",
            middleware: [passport.authenticate('local', {
                session: false
            })]
        }, {
            type: "get",
            endpoint: "/api/users",
            method: "getAll"
        }, {
            type: "get",
            endpoint: "/api/users/:id",
            method: "getById"
        }, {
            type: "get",
            endpoint: "/api/users/activate/:hash",
            method: "activate"
        }, {
            type: "put",
            endpoint: "/api/users/me",
            method: "updateMe"
        }, {
            type: "put",
            endpoint: "/api/users/:id",
            method: "updateById"
        }, {
            type: "delete",
            endpoint: "/api/users/:id",
            method: "deleteById"
        }, {
            type: "delete",
            endpoint: "/api/users",
            method: "deleteAll"
        }]
    }
}

module.exports = function(app) {

    // Frontend part
    var indexController = require('./frontend/controllers/index');
    app.get('/', indexController.index);

    // API part
    app.get('/api', function(req, res) {
        res.status(200).json({
            name: pkg.name,
            version: pkg.version
        });
    });

    var baseController = require("./api/controllers/base")

    var responseCallback = function(res, status, result) {
        if (status.type == 'success') {
            res.status(status.code).json(result)
        } else {
            res.status(status.code).json(status)
        }
    }

    var generateRoute = function(route, controller, Model) {
        if (!route.middleware) {
            route.middleware = function(req, res, next) {
                next()
            }
        }
        app[route.type](route.endpoint, route.middleware, function(req, res) {
            if (controller && controller[route.method]) {
                if (Model.modelName == "User") {
                    controller[route.method](req, Model, function(status, result) {
                        responseCallback(res, status, result)
                    })
                } else {
                    controller[route.method](req, res)
                }

            } else {
                if (baseController[route.method]) {
                    baseController[route.method](req, Model, function(status, result) {
                        responseCallback(res, status, result)
                    })
                } else {
                    res.status(404).json({
                        type: 'error',
                        description: 'This endpoint does not exist.'
                    })
                }

            }
        })
    }

    _.each(config.models, function(model, index) {
        if (model.name == "User") {
            if (config.users) {
                var User = mongoose.model("User")
                var controller = require("./api/controllers/user")
                _.each(routes.user.urls, function(route) {
                    if (!route.middleware) {
                        route.middleware = routes.user.middleware
                    }
                    generateRoute(route, controller, User)
                })
            }
        } else {
            var name = model.name.toLowerCase()
            var routeName = model.routeName || name
            var path = process.cwd() + "/app/api/controllers/" + name + ".js"
            fs.access(path, function(err) {
                var controller = null
                var Model = mongoose.model(model.name)
                if (err == null) {
                    controller = require(path)
                }
                var modelRoutes = routes[name] || routes.base
                _.each(modelRoutes.urls, function(route) {
                    var routeObject = _.clone(route)
                    if (!routeObject.middleware) {
                        routeObject.middleware = modelRoutes.middleware
                    }
                    routeObject.endpoint = routeObject.endpoint.replace("ROUTE_NAME", routeName)
                    if (routeObject.method == "changePosition") {
                        if (model.positionable) {
                            generateRoute(routeObject, controller, Model)
                        }
                    } else {
                        generateRoute(routeObject, controller, Model)
                    }
                })
            })
        }
    })
}<|endoftext|>


<commit_before>var mojangson = require('mojangson');
var vsprintf = require('sprintf-js').vsprintf;
var fs = require('fs');

var lang = {}
fs.readFileSync('en_us.lang','utf8').split('\n').forEach(function (l) {
  var c = l.split(/=(.+)/);
  if (c.length === 3) lang[c[0]] = c[1];
})

module.exports = ChatMessage;

/**
 * ChatMessage Constructor
 * @param {String|Object} message content of ChatMessage
 */
function ChatMessage(message) {
  if(typeof message === 'string') {
    this.json = {text: message};
  } else if(typeof message === 'object' && !Array.isArray(message)) {
    this.json = message;
  } else {
    throw new Error('Expected String or Object for Message argument');
  }
  this.parse();
}

/**
 * Parses the this.json property to decorate the properties of the ChatMessage.
 * Called by the Constructor
 * @return {void}
 */
ChatMessage.prototype.parse = function() {
  var json = this.json;
  // Message scope for callback functions
  var that = this;

  // There is EITHER, a text property or a translate property
  // If there is no translate property, there is no with property
  // HOWEVER! If there is a translate property, there may not be a with property
  if(typeof json.text === 'string') {
    this.text = json.text;
  } else if(typeof json.translate === 'string') {
    this.translate = json.translate;
    if(typeof json.with === 'object' || Array.isArray(json.with)) {
      this.with = json.with.map(function(entry) {
        return new ChatMessage(entry);
      });
    }
  }
  // Parse extra property
  // Extras are appended to the initial text
  if(typeof json.extra === 'object') {
    if(!Array.isArray(json.extra)) {
      throw new Error('Expected extra property to be an Array in ChatMessage');
    }
    this.extra = json.extra.map(function(entry) {
      return new ChatMessage(entry);
    });
  }
  // Text modifiers
  this.bold = json.bold;
  this.italic = json.italic;
  this.underlined = json.underlined;
  this.strikethrough = json.strikethrough;
  this.obfuscated = json.obfuscated;

  // Supported constants @ 2014-04-21
  var supportedColors = ['black', 'dark_blue', 'dark_green', 'dark_aqua', 'dark_red', 'dark_purple',
    'gold', 'gray', 'dark_gray', 'blue', 'green', 'aqua', 'red', 'light_purple',
    'yellow', 'white', 'obfuscated', 'bold', 'strikethrough', 'underlined', 'italic',
    'reset'];
  var supportedClick = ['open_url', 'open_file', 'run_command', 'suggest_command'];
  var supportedHover = ['show_text', 'show_achievement', 'show_item', 'show_entity'];

  // Parse color
  this.color = json.color;
  switch(this.color) {
    case 'obfuscated':
      this.obfuscated = true;
      this.color = null;
      break;
    case 'bold':
      this.bold = true;
      this.color = null;
      break;
    case 'strikethrough':
      this.strikethrough = true;
      this.color = null;
      break;
    case 'underlined':
      this.underlined = true;
      this.color = null;
      break;
    case 'italic':
      this.italic = true;
      this.color = null;
      break;
    case 'reset':
      this.reset = true;
      this.color = null;
      break;
  }
  if(Array.prototype.indexOf && this.color &&
    supportedColors.indexOf(this.color) === -1) {
    console.warn('ChatMessage parsed with unsupported color', this.color);
  }

  // Parse click event
  if(typeof json.clickEvent === 'object') {
    this.clickEvent = json.clickEvent;
    if(typeof this.clickEvent.action !== 'string') {
      throw new Error('ClickEvent action missing in ChatMessage');
    } else if(Array.prototype.indexOf && supportedClick.indexOf(this.clickEvent.action) === -1) {
      console.warn('ChatMessage parsed with unsupported clickEvent', this.clickEvent.action);
    }
  }

  // Parse hover event
  if(typeof json.hoverEvent === 'object') {
    this.hoverEvent = json.hoverEvent;
    if(typeof this.hoverEvent.action !== 'string') {
      throw new Error('HoverEvent action missing in ChatMessage');
    } else if(Array.prototype.indexOf && supportedHover.indexOf(this.hoverEvent.action) === -1) {
      console.warn('ChatMessage parsed with unsupported hoverEvent', this.hoverEvent.action);
    }
    // Special case
    if(this.hoverEvent.action === 'show_item') {
      let content;
      if(this.hoverEvent.value instanceof Array) {
        if(this.hoverEvent.value[0] instanceof Object)
          content=this.hoverEvent.value[0].text;
        else
          content=this.hoverEvent.value[0];
      }
      else {
        if(this.hoverEvent.value instanceof Object)
          content=this.hoverEvent.value.text;
        else
          content=this.hoverEvent.value;
      }
      this.hoverEvent.value = mojangson.parse(content);
    }
  }
};

/**
 * Returns the count of text extras and child ChatMessages
 * Does not count recursively in to the children
 * @return {Number}
 */
ChatMessage.prototype.length = function() {
  var count = 0;
  if(this.text) count++;
  else if(this.with) count += this.with.length;

  if(this.extra) count += this.extra.length;
  return count;
};

/**
 * Returns a text part from the message
 * @param  {Number} idx Index of the part
 * @return {String}
 */
ChatMessage.prototype.getText = function(idx) {
  // If the index is not defined is is invalid, return toString
  if(typeof idx !== 'number') return this.toString();
  // If we are not a translating message, return the text
  if(this.text && idx === 0) return this.text.replace(/§[0-9a-flnmokr]/g, "").trim();
  // Else return the with child if it's in range
  else if(this.with.length > idx) return this.with[idx].toString();
  // Else return the extra if it's in range
  if(this.extra && this.extra.length + (this.text ? 1 : this.with.length) > idx)
    return this.extra[idx - (this.text ? 1 : this.with.length)].toString();
  // Not sure how you want to default this
  // Undefined, an error ?
  return "";
};

/**
 * Flattens the message in to plain-text
 * @return {String}
 */
ChatMessage.prototype.toString = function() {
  var message = "";
  if(typeof this.text === 'string') message += this.text + " ";
  else if(this.with) {
    var args = this.with.map(function(entry) {
      return entry.toString();
    })
    var format = lang[this.translate]
    if (!format) message += args.join(" ") + " ";
    else message += vsprintf(format, args) + " ";
  }
  if(this.extra) {
    this.extra.forEach(function(entry) {
      message += entry.toString() + " ";
    })
  }
  return message.replace(/§[0-9a-flnmokr]/g, "").trim();
};

ChatMessage.prototype.toMotd = function(motd) {
  var codes = {
    color:{
      black: '§0',
      dark_blue: '§1',
      dark_green: '§2',
      dark_aqua: '§3',
      dark_red: '§4',
      dark_purple: '§5',
      gold: '§6',
      gray: '§7',
      dark_gray: '§8',
      blue: '§9',
      green: '§a',
      aqua: '§b',
      red: '§c',
      light_purple: '§d',
      yellow: '§e',
      white: '§f',
    },
    bold: '§l',
    italic: '§o',
    underlined: '§n',
    strikethrough: '§m',
    obfuscated : '§k'
  }

  var message = Object.keys(codes).map((function (code) {
    if (!this[code] || this[code] === 'false') return null;
    if (code === 'color') return codes.color[this.color];
    return codes[code];
  }).bind(this)).join('');

  if(typeof this.text === 'string') message += this.text + "§r ";
  else if(this.with) {
    var args = this.with.map(function(entry) {
      return entry.toMotd();
    })
    var format = lang[this.translate]
    if (!format) message += args.join(" ") + " ";
    else message += vsprintf(format, args) + " ";
  }
  if(this.extra) {
    this.extra.forEach(function(entry) {
      message += entry.toMotd() + " ";
    })
  }
  return message.trim();
};

ChatMessage.prototype.toAnsi = function(motd) {
  var codes = {
    '§0': '\u001b[30m',
    '§1': '\u001b[34m',
    '§2': '\u001b[32m',
    '§3': '\u001b[36m',
    '§4': '\u001b[31m',
    '§5': '\u001b[35m',
    '§6': '\u001b[33m',
    '§7': '\u001b[37m',
    '§8': '\u001b[90m',
    '§9': '\u001b[94m',
    '§a': '\u001b[92m',
    '§b': '\u001b[96m',
    '§c': '\u001b[91m',
    '§d': '\u001b[95m',
    '§e': '\u001b[93m',
    '§f': '\u001b[97m',
    '§l': '\u001b[1m',
    '§o': '\u001b[3m',
    '§n': '\u001b[4m',
    '§m': '\u001b[9m',
    '§k': '\u001b[6m',
    '§r': '\u001b[0m'
  };

  var message = this.toMotd();
  for (k in codes) {
    message = message.replace(new RegExp(k, 'g'), codes[k]);
  }
  return message;
};

if(require.main === module) {
  testParseShowItemHoverEventValue();
}
<commit_msg>fixed issue in ChatMessage with mapping<commit_after>var mojangson = require('mojangson');
var vsprintf = require('sprintf-js').vsprintf;
var fs = require('fs');

var lang = {}
fs.readFileSync('en_us.lang','utf8').split('\n').forEach(function (l) {
  var c = l.split(/=(.+)/);
  if (c.length === 3) lang[c[0]] = c[1];
})

module.exports = ChatMessage;

/**
 * ChatMessage Constructor
 * @param {String|Object} message content of ChatMessage
 */
function ChatMessage(message) {
  if(typeof message === 'string') {
    this.json = {text: message};
  } else if(typeof message === 'object' && !Array.isArray(message)) {
    this.json = message;
  } else {
    throw new Error('Expected String or Object for Message argument');
  }
  this.parse();
}

/**
 * Parses the this.json property to decorate the properties of the ChatMessage.
 * Called by the Constructor
 * @return {void}
 */
ChatMessage.prototype.parse = function() {
  var json = this.json;
  // Message scope for callback functions
  var that = this;

  // There is EITHER, a text property or a translate property
  // If there is no translate property, there is no with property
  // HOWEVER! If there is a translate property, there may not be a with property
  if(typeof json.text === 'string') {
    this.text = json.text;
  } else if(typeof json.translate === 'string') {
    this.translate = json.translate;
    if(typeof json.with === 'object') {
      if(!Array.isArray(json.with)) {
        throw new Error('Expected with property to be an Array in ChatMessage');
      }
      this.with = json.with.map(function(entry) {
        return new ChatMessage(entry);
      });
    }
  }
  // Parse extra property
  // Extras are appended to the initial text
  if(typeof json.extra === 'object') {
    if(!Array.isArray(json.extra)) {
      throw new Error('Expected extra property to be an Array in ChatMessage');
    }
    this.extra = json.extra.map(function(entry) {
      return new ChatMessage(entry);
    });
  }
  // Text modifiers
  this.bold = json.bold;
  this.italic = json.italic;
  this.underlined = json.underlined;
  this.strikethrough = json.strikethrough;
  this.obfuscated = json.obfuscated;

  // Supported constants @ 2014-04-21
  var supportedColors = ['black', 'dark_blue', 'dark_green', 'dark_aqua', 'dark_red', 'dark_purple',
    'gold', 'gray', 'dark_gray', 'blue', 'green', 'aqua', 'red', 'light_purple',
    'yellow', 'white', 'obfuscated', 'bold', 'strikethrough', 'underlined', 'italic',
    'reset'];
  var supportedClick = ['open_url', 'open_file', 'run_command', 'suggest_command'];
  var supportedHover = ['show_text', 'show_achievement', 'show_item', 'show_entity'];

  // Parse color
  this.color = json.color;
  switch(this.color) {
    case 'obfuscated':
      this.obfuscated = true;
      this.color = null;
      break;
    case 'bold':
      this.bold = true;
      this.color = null;
      break;
    case 'strikethrough':
      this.strikethrough = true;
      this.color = null;
      break;
    case 'underlined':
      this.underlined = true;
      this.color = null;
      break;
    case 'italic':
      this.italic = true;
      this.color = null;
      break;
    case 'reset':
      this.reset = true;
      this.color = null;
      break;
  }
  if(Array.prototype.indexOf && this.color &&
    supportedColors.indexOf(this.color) === -1) {
    console.warn('ChatMessage parsed with unsupported color', this.color);
  }

  // Parse click event
  if(typeof json.clickEvent === 'object') {
    this.clickEvent = json.clickEvent;
    if(typeof this.clickEvent.action !== 'string') {
      throw new Error('ClickEvent action missing in ChatMessage');
    } else if(Array.prototype.indexOf && supportedClick.indexOf(this.clickEvent.action) === -1) {
      console.warn('ChatMessage parsed with unsupported clickEvent', this.clickEvent.action);
    }
  }

  // Parse hover event
  if(typeof json.hoverEvent === 'object') {
    this.hoverEvent = json.hoverEvent;
    if(typeof this.hoverEvent.action !== 'string') {
      throw new Error('HoverEvent action missing in ChatMessage');
    } else if(Array.prototype.indexOf && supportedHover.indexOf(this.hoverEvent.action) === -1) {
      console.warn('ChatMessage parsed with unsupported hoverEvent', this.hoverEvent.action);
    }
    // Special case
    if(this.hoverEvent.action === 'show_item') {
      let content;
      if(this.hoverEvent.value instanceof Array) {
        if(this.hoverEvent.value[0] instanceof Object)
          content=this.hoverEvent.value[0].text;
        else
          content=this.hoverEvent.value[0];
      }
      else {
        if(this.hoverEvent.value instanceof Object)
          content=this.hoverEvent.value.text;
        else
          content=this.hoverEvent.value;
      }
      this.hoverEvent.value = mojangson.parse(content);
    }
  }
};

/**
 * Returns the count of text extras and child ChatMessages
 * Does not count recursively in to the children
 * @return {Number}
 */
ChatMessage.prototype.length = function() {
  var count = 0;
  if(this.text) count++;
  else if(this.with) count += this.with.length;

  if(this.extra) count += this.extra.length;
  return count;
};

/**
 * Returns a text part from the message
 * @param  {Number} idx Index of the part
 * @return {String}
 */
ChatMessage.prototype.getText = function(idx) {
  // If the index is not defined is is invalid, return toString
  if(typeof idx !== 'number') return this.toString();
  // If we are not a translating message, return the text
  if(this.text && idx === 0) return this.text.replace(/§[0-9a-flnmokr]/g, "").trim();
  // Else return the with child if it's in range
  else if(this.with.length > idx) return this.with[idx].toString();
  // Else return the extra if it's in range
  if(this.extra && this.extra.length + (this.text ? 1 : this.with.length) > idx)
    return this.extra[idx - (this.text ? 1 : this.with.length)].toString();
  // Not sure how you want to default this
  // Undefined, an error ?
  return "";
};

/**
 * Flattens the message in to plain-text
 * @return {String}
 */
ChatMessage.prototype.toString = function() {
  var message = "";
  if(typeof this.text === 'string') message += this.text + " ";
  else if(this.with) {
    var args = this.with.map(function(entry) {
      return entry.toString();
    })
    var format = lang[this.translate]
    if (!format) message += args.join(" ") + " ";
    else message += vsprintf(format, args) + " ";
  }
  if(this.extra) {
    this.extra.forEach(function(entry) {
      message += entry.toString() + " ";
    })
  }
  return message.replace(/§[0-9a-flnmokr]/g, "").trim();
};

ChatMessage.prototype.toMotd = function(motd) {
  var codes = {
    color:{
      black: '§0',
      dark_blue: '§1',
      dark_green: '§2',
      dark_aqua: '§3',
      dark_red: '§4',
      dark_purple: '§5',
      gold: '§6',
      gray: '§7',
      dark_gray: '§8',
      blue: '§9',
      green: '§a',
      aqua: '§b',
      red: '§c',
      light_purple: '§d',
      yellow: '§e',
      white: '§f',
    },
    bold: '§l',
    italic: '§o',
    underlined: '§n',
    strikethrough: '§m',
    obfuscated : '§k'
  }

  var message = Object.keys(codes).map((function (code) {
    if (!this[code] || this[code] === 'false') return null;
    if (code === 'color') return codes.color[this.color];
    return codes[code];
  }).bind(this)).join('');

  if(typeof this.text === 'string') message += this.text + "§r ";
  else if(this.with) {
    var args = this.with.map(function(entry) {
      return entry.toMotd();
    })
    var format = lang[this.translate]
    if (!format) message += args.join(" ") + " ";
    else message += vsprintf(format, args) + " ";
  }
  if(this.extra) {
    this.extra.forEach(function(entry) {
      message += entry.toMotd() + " ";
    })
  }
  return message.trim();
};

ChatMessage.prototype.toAnsi = function(motd) {
  var codes = {
    '§0': '\u001b[30m',
    '§1': '\u001b[34m',
    '§2': '\u001b[32m',
    '§3': '\u001b[36m',
    '§4': '\u001b[31m',
    '§5': '\u001b[35m',
    '§6': '\u001b[33m',
    '§7': '\u001b[37m',
    '§8': '\u001b[90m',
    '§9': '\u001b[94m',
    '§a': '\u001b[92m',
    '§b': '\u001b[96m',
    '§c': '\u001b[91m',
    '§d': '\u001b[95m',
    '§e': '\u001b[93m',
    '§f': '\u001b[97m',
    '§l': '\u001b[1m',
    '§o': '\u001b[3m',
    '§n': '\u001b[4m',
    '§m': '\u001b[9m',
    '§k': '\u001b[6m',
    '§r': '\u001b[0m'
  };

  var message = this.toMotd();
  for (k in codes) {
    message = message.replace(new RegExp(k, 'g'), codes[k]);
  }
  return message;
};

if(require.main === module) {
  testParseShowItemHoverEventValue();
}
<|endoftext|>


<commit_before>module.exports = function(schema, mongoose) {
  'use strict';

  mongoose = mongoose || require('mongoose');

  var clonedSchema = new mongoose.Schema();

  schema.eachPath(function(key, path) {
    if (key === "_id") {
      return;
    }

    var clonedPath = {};

    clonedPath[key] = path.options;
    clonedPath[key].unique = false;

    clonedSchema.add(clonedPath);
  });

  return clonedSchema;
};<commit_msg>Check that 'unique' exists. Fixes #26<commit_after>module.exports = function(schema, mongoose) {
  'use strict';

  mongoose = mongoose || require('mongoose');

  var clonedSchema = new mongoose.Schema();

  schema.eachPath(function(key, path) {
    if (key === "_id") {
      return;
    }

    var clonedPath = {};

    clonedPath[key] = path.options;
    delete clonedPath[key].unique;

    clonedSchema.add(clonedPath);
  });

  return clonedSchema;
};<|endoftext|>


<commit_before><commit_msg>moved functions to read colors, write colors, and invert colors to colorHandler.js<commit_after>'use strict';

var colorHandler = {};

colorHandler.readColors = function(i, bitmapImage) {
  var colorHandler = {};
  colorHandler.r = bitmapImage.readUInt8(i);
  colorHandler.b = bitmapImage.readUInt8(i + 1);
  colorHandler.g = bitmapImage.readUInt8(i + 2);
  colorHandler.a = bitmapImage.readUInt8(i + 3);
  return colorHandler;
};

colorHandler.writeColors = function(i, bitmapImage, colorHandlerObj) {
  bitmapImage.writeUInt8(colorHandlerObj.r, i);
  bitmapImage.writeUInt8(colorHandlerObj.b, i + 1);
  bitmapImage.writeUInt8(colorHandlerObj.g, i + 2);
  bitmapImage.writeUInt8(colorHandlerObj.a, i + 3);
}

colorHandler.invertColors = function(colorHandlerObj) {
  var colorsList = ['r', 'g', 'b', 'a'];
  colorList.forEach(function(current) {
    var thisColor = colorHandlerObj[current];
    colorHandlerObj[current] = 255 - thisColor;
  });
  return colorHandlerObj
}

module.exports = colorHandler;
<|endoftext|>