<commit_before>var Discord = require('discord.js'),
    config = require('./config'),
    fs = require('fs'),
    unirest = require('unirest'),
    token = config.TOKEN,
    bot = new Discord.Client(),
    server,
    version,
    exec,
    sbbusy = false;

/* VERSION */
function getVersion(callback) {
    exec = exec || require('child_process').exec;

    exec('git rev-parse --short=4 HEAD', function (error, version) {
        if (error) {
            console.log('Error getting version', error);
            return callback('unknown');
        }

        callback(version.trim());
    });
}

/* BOT EVENTS */
bot.on('ready', function () {
    online();
    console.log(getDateTime() + 'I am ready!');
    getVersion(function (v) {
        version = v;
        bot.user.setGame('version ' + version);

        if (config.DEBUG) bot.channels.find('id', config.BOT_CH).sendMessage('I am ready, running version `' + version + '`! 👌');
    });

    if (!bot.guilds.exists('id', config.SERVER_ID)) {
        console.log('Bot is not connected to the selected server!');
        process.exit();
    }

    server = bot.guilds.find('id', config.SERVER_ID);
});

bot.on('guildMemberAdd', function (member) {
    //bot.channels.find('id', config.DEFAULT_CH).sendMessage(member + ' Willkommen auf dem offiziellen Discord Server von Bronies.de ... Wirf doch für den Anfang einen Blick in den #info Bereich. :lyra_1:');
});

function onMessage(message) {
    if (message.author.id == bot.user.id) {
        return;
    }

    if (message.channel.type == 'group') {
        return;
    }

    function handleCommand() {
        var match = /^[\/!]([a-zA-Z]+).*$/.exec(message.content);

        if (message.channel.type == 'dm') {
            match = /^[\/!]?([a-zA-Z]+).*$/.exec(message.content);
        }

        if (match) {
            var args = message.content.split(' ').splice(1);

            processCommand(message, match[1].toLowerCase(), args);
        }
    }

    if (server.channels.exists('id', message.channel.id)) {
        handleCommand();
    } else {
        if (server.members.exists('id', message.author.id)) {
            handleCommand();
        } else {
            return message.channel.sendMessage('You have to be member of ' + server.name + '!');
        }
    }
}

bot.on('message', onMessage);

bot.on('messageUpdate', function (oldMessage, newMessage) {
    if (typeof newMessage.author === 'undefined')
        return;

    onMessage(newMessage);
});

/* PERMISSIONS */
function Permission(checker) {
    return {
        check: function (user) {
            if (!server.members.exists('id', user.id)) {
                return false;
            }

            var member = server.members.find('id', user.id);

            return checker(member);
        }
    };
}

var isAdmin = new Permission(function (member) {
    return member.roles.exists('name', 'Admin') || member.roles.exists('name', 'Co-Admin');
});

var isMod = new Permission(function (member) {
    return isAdmin.check(member) ? true : member.roles.exists('name', 'Moderator');
});

var isUser = new Permission(function (member) {
    return isMod.check(member) ? true : member.roles.exists('name', '⬛ Community');
});

function getGuildMemeber(user) {
    return server.members.find('id', user.id);
}

function respond(message, response, mention) {
    if (typeof mention === 'undefined') {
        mention = false;
    }

    if (mention) {
        message.reply(response);
    } else {
        message.channel.sendMessage(response);
    }
}

function respondPm(message, response) {
    message.author.sendMessage(response);
}

function getEmoji(name) {
    if(server.emojis.exists('name', name)) {
        return server.emojis.find('name', name).toString();
    } else {
        return ':robot:';
    }
}

/* COMMAND PROCESSING */
function processCommand(message, command, args) {
    switch (command) {
        case 'help':
            (function () {
                var text = '\n\nBefehle müssen `/` oder `!` vorangestellt haben. Groß- und Kleinschreibung wird nicht beachtet.\nIn PMs wird kein Präfix benötigt.\n\n';

                text += 'Liste aller Befehle, die **du** nutzen kannst:\n\n';

                commands.forEach(function (command) {
                    if (command.role == "Admin") {
                        if (!isAdmin.check(message.author)) {
                            return;
                        }
                    } else if (command.role == "Moderator") {
                        if (!isMod.check(message.author)) {
                            return;
                        }
                    } else if (command.role == "Community") {
                        if (!isUser.check(message.author)) {
                            return;
                        }
                    }

                    text += '**`' + command.name + '`**';
                    if ('aliases' in command) {
                        text += ' (alternativ: ';
                        text += '`' + command.aliases.join('`, `');
                        text += '`)';
                    }

                    text += '\n```' + command.help + '```\n\n';
                });

                respondPm(message, text);

                if (message.channel.type == 'text') {
                    message.delete();
                }
            })();
            break;
        case 'ver':
        case 'version':
            (function () {
                respond(message, "Bronies.de DSB version `" + version + "`.\nAktuellster Commit: https://github.com/DerAtrox/Bronies.de-DSB/commit/" + version);
            })();
            break;
        case 'nsfw':
            (function () {
                if (message.guild != server) {
                    return respondPm(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!');
                }

                var msg = message;
                message.delete();

                if (!isUser.check(msg.author)) {
                    return respondPm(msg, 'Du besitzt nicht genügend Rechte!');
                }

                if (args.length != 1) {
                    return respondPm(msg, 'Nutze `!nsfw <join|leave>` um den NSFW Bereich zu betreten bzw. zu verlassen.\nBeispiel: `!nsfw join`');
                }

                var arg = args[0].toLowerCase();

                var nsfwRole = server.roles.find('name', 'NSFW');
                var member = getGuildMemeber(msg.author);

                if (arg == 'join') {
                    if (member.roles.exists('name', 'NSFW')) {
                        return respondPm(msg, 'Du hast bereits Zugriff auf den NSFW Bereich.');
                    } else {
                        member.addRole(nsfwRole);
                        return respondPm(msg, 'Bronies.de NSFW Bereich beigetreten. :smirk:');
                    }
                } else if (arg == 'leave') {
                    if (!member.roles.exists('name', 'NSFW')) {
                        return respondPm(msg, 'Du hast bereits keinen Zugriff auf den NSFW Bereich.');
                    } else {
                        member.removeRole(nsfwRole);
                        return respondPm(msg, 'Bronies.de NSFW Bereich verlassen.');
                    }
                } else {
                    return respondPm(msg, 'Nutze `!nsfw <join|leave>` um den NSFW Bereich zu betreten bzw. zu verlassen.\nBeispiel: `!nsfw join`');
                }
            })();
            break;
        case 'soundboard':
        case 'sb':
            (function () {
                if (message.guild != server) {
                    return respondPm(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!');
                }

                if (!isUser.check(message.author)) {
                    return respondPm(message, 'Du besitzt nicht genügend Rechte!');
                    message.delete();
                }

                if (args.length != 1) {
                    return respondPm(message, 'Spiele Pony Sounds in deinem aktuellen Voicechannel ab. Nutze `!sb help` um alle Sounds anzuzeigen.\nBeispiel: `!sb lunafun`');
                    message.delete();
                }

                var arg = args[0].toLowerCase();

                if (arg == 'help') {
                    respondPm(message, 'Folgende Sounds können abgespielt werden:\n```' + Object.keys(sounds).join(' ') + '```');
                    return message.delete();
                } else {
                    if (sbbusy) {
                        return;
                    }

                    var member = getGuildMemeber(message.author);

                    if (typeof member.voiceChannel == 'undefined') {
                        return;
                    }

                    if (!(arg in sounds)) {
                        return;
                    }

                    var soundPath = './sounds/' + sounds[arg];

                    fs.access(soundPath, fs.constants.R_OK, function (err) {
                        if (!err) {
                            sbbusy = true;
                            member.voiceChannel.join().then(function (connection) {
                                const dispatcher = connection.playFile('./sounds/' + sounds[arg]);

                                dispatcher.on('end', function () {
                                    sbbusy = false;
                                    connection.disconnect();

                                });

                                dispatcher.on('error', function (message) {
                                    console.log(message);
                                });
                            })
                                .catch(console.error);
                        } else {
                            console.log('Soundfile not found: ' + arg + ' file ' + sounds[arg]);
                        }
                    });
                }

            })();
            break;
        case 'derpi':
        case 'db':
            (function () {
                if (message.guild != server) {
                    return respondPm(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!');
                }

                if (!isUser.check(message.author)) {
                    return respondPm(message, 'Du besitzt nicht genügend Rechte!');
                    message.delete();
                }

                if (args.length < 1) {
                    return respond(message, 'Dieser Befehl benötigt zusätzliche Parameter. Mehr unter `!help`');
                }

                var regexOrder = /\bo:(desc|asc)\b/i,
                    regexSort = /\bby:(score|relevance|width|height|comments|random)\b/i,
                    parameters = '',
                    query = args.join(' ');

                if(message.channel == server.channels.find('name', 'nsfw')) {
                    parameters += '&filter_id=134114';
                }

                if(regexOrder.test(query)) {
                    parameters += '&sd=' + query.match(regexOrder)[1];
                    query = query.replace(regexOrder, '');
                }

                if(regexSort.test(query)) {
                    parameters += '&sf=' + query.match(regexSort)[1];
                    query = query.replace(regexSort, '');
                } else {
                    parameters += '&sf=random';
                }

                query = query.replace(/,{2,}/g, ',').replace(/(^,|,$)/, '');
                var url = 'https://derpibooru.org/search.json?q=' + encodeURIComponent(query) + parameters;
                console.log(message.author.username + '#' + message.author.discriminator + ' - Derpibooru search: ' + url);

                unirest.get(url)
                    .header("Accept", "application/json")
                    .end(function (result) {
                        if (result.error || typeof result.body !== 'object') {
                            console.log(result.error, result.body);
                            return respond(message, 'Derpibooru Anfrage fehlgeschlagen (HTTP ' + result.status + ')');
                        }

                        var data = result.body;
                        if (typeof data.search === 'undefined' || typeof data.search[0] === 'undefined')
                            return respond(message, 'Keine Suchergebnisse gefunden.');

                        var img = data.search[0];

                        if (!img.is_rendered) {
                            return respond(message, 'Dieses Bild wurde noch nicht von Derpibooru verarbeitet. Bitte versuche es später erneut.');
                        }

                        respond(message, '<http://derpibooru.org/' + img.id + '>\nhttps:' + (img.image.replace(/__[^.]+(.\w+)$/, '$1')));
                    });

            })();
            break;
    }
}

var commands = [
    {
        name: 'help',
        help: 'Zeigt alle verfügbaren Befehle an.'
    },
    {
        name: 'version',
        help: 'Zeigt die verwendete Bronies.de DSB Version an.',
        aliases: ['ver']
    },
    {
        name: 'nsfw <join|leave>',
        help: '#nsfw betreten oder verlassen.',
        role: 'Community'
    },
    {
        name: 'soundboard <sound>',
        help: 'Sound in aktuellem Sprachchannel abspielen. Liste aller Sounds mit !sb help',
        aliases: ['sb'],
        role: 'Community'
    },
    {
        name: 'derpi <search>',
        help: 'Gibt das erste Bild einer Derpibooru Suche zurück.\n\n' +
        'Optionen:\n' +
        ' - Reihenfolge  o:<desc|asc>\n' +
        ' - Sortierung   by:<score|relevance|width|height|comments|random>',
        aliases: ['db'],
        role: 'Community'
    },
    {
        name: 'nowplaying',
        help: 'Zeigt den aktuell gespielten Track des BRG-Musikbots an.',
        aliases: ['np']
    }
];

var sounds = {
    'lunafun': 'Princess Luna/the fun has been doubled.mp3',
    'eyyup': 'Big Macintosh/eyup.mp3',
    'nope': 'Big Macintosh/nnope.mp3',
    'yeehaw': 'Applejack/yeehaw.mp3',
    'laugh': 'Rainbow Dash/laughing.mp3',
    'catchy': 'Twilight Sparkle/wow catchy.mp3',
    'crazy': 'Twilight Sparkle/are you crazy.mp3',
    'grin': 'Fluttershy/(grin).mp3',
    'choochoo': 'Fluttershy/choo choo train.mp3',
    'yay': 'Fluttershy/yay.mp3',
    'boring': 'Pinkie Pie/boring.mp3',
    'giggle': 'Pinkie Pie/giggle.mp3',
    'oki': 'Pinkie Pie/oki doki loki.mp3',
    'rimshot': 'Pinkie Pie/rimshot.mp3',
    'yeah': 'Snowflake/yeah2.mp3',
    'fanfare': 'Trixie/fanfare.mp3',
    'youmad': 'Zecora/have you gone mad.mp3',
    '10seconds': 'Rainbow Dash/10 seconds flat.mp3',
    'style': 'Pinkie Pie/pinkie pie style.mp3',
    'notcool': 'Rainbow Dash/not cool.mp3',
    'wrong': 'Derpy/i just dont know what went wrong.mp3'
};

/* GENERAL APPLICATION STUFF */
process.on('exit', idle);

process.on('SIGINT', function () {
    idle();
    process.exit();

});

function getDateTime() {
    return "[" + new Date().toLocaleString() + "] ";
}

function idle() {
    bot.user.setStatus('idle');
}

function online() {
    bot.user.setStatus('online');
}

/* LOGIN */
bot.login(token);

<commit_msg>update filter_id<commit_after>var Discord = require('discord.js'),
    config = require('./config'),
    fs = require('fs'),
    unirest = require('unirest'),
    token = config.TOKEN,
    bot = new Discord.Client(),
    server,
    version,
    exec,
    sbbusy = false;

/* VERSION */
function getVersion(callback) {
    exec = exec || require('child_process').exec;

    exec('git rev-parse --short=4 HEAD', function (error, version) {
        if (error) {
            console.log('Error getting version', error);
            return callback('unknown');
        }

        callback(version.trim());
    });
}

/* BOT EVENTS */
bot.on('ready', function () {
    online();
    console.log(getDateTime() + 'I am ready!');
    getVersion(function (v) {
        version = v;
        bot.user.setGame('version ' + version);

        if (config.DEBUG) bot.channels.find('id', config.BOT_CH).sendMessage('I am ready, running version `' + version + '`! 👌');
    });

    if (!bot.guilds.exists('id', config.SERVER_ID)) {
        console.log('Bot is not connected to the selected server!');
        process.exit();
    }

    server = bot.guilds.find('id', config.SERVER_ID);
});

bot.on('guildMemberAdd', function (member) {
    //bot.channels.find('id', config.DEFAULT_CH).sendMessage(member + ' Willkommen auf dem offiziellen Discord Server von Bronies.de ... Wirf doch für den Anfang einen Blick in den #info Bereich. :lyra_1:');
});

function onMessage(message) {
    if (message.author.id == bot.user.id) {
        return;
    }

    if (message.channel.type == 'group') {
        return;
    }

    function handleCommand() {
        var match = /^[\/!]([a-zA-Z]+).*$/.exec(message.content);

        if (message.channel.type == 'dm') {
            match = /^[\/!]?([a-zA-Z]+).*$/.exec(message.content);
        }

        if (match) {
            var args = message.content.split(' ').splice(1);

            processCommand(message, match[1].toLowerCase(), args);
        }
    }

    if (server.channels.exists('id', message.channel.id)) {
        handleCommand();
    } else {
        if (server.members.exists('id', message.author.id)) {
            handleCommand();
        } else {
            return message.channel.sendMessage('You have to be member of ' + server.name + '!');
        }
    }
}

bot.on('message', onMessage);

bot.on('messageUpdate', function (oldMessage, newMessage) {
    if (typeof newMessage.author === 'undefined')
        return;

    onMessage(newMessage);
});

/* PERMISSIONS */
function Permission(checker) {
    return {
        check: function (user) {
            if (!server.members.exists('id', user.id)) {
                return false;
            }

            var member = server.members.find('id', user.id);

            return checker(member);
        }
    };
}

var isAdmin = new Permission(function (member) {
    return member.roles.exists('name', 'Admin') || member.roles.exists('name', 'Co-Admin');
});

var isMod = new Permission(function (member) {
    return isAdmin.check(member) ? true : member.roles.exists('name', 'Moderator');
});

var isUser = new Permission(function (member) {
    return isMod.check(member) ? true : member.roles.exists('name', '⬛ Community');
});

function getGuildMemeber(user) {
    return server.members.find('id', user.id);
}

function respond(message, response, mention) {
    if (typeof mention === 'undefined') {
        mention = false;
    }

    if (mention) {
        message.reply(response);
    } else {
        message.channel.sendMessage(response);
    }
}

function respondPm(message, response) {
    message.author.sendMessage(response);
}

function getEmoji(name) {
    if(server.emojis.exists('name', name)) {
        return server.emojis.find('name', name).toString();
    } else {
        return ':robot:';
    }
}

/* COMMAND PROCESSING */
function processCommand(message, command, args) {
    switch (command) {
        case 'help':
            (function () {
                var text = '\n\nBefehle müssen `/` oder `!` vorangestellt haben. Groß- und Kleinschreibung wird nicht beachtet.\nIn PMs wird kein Präfix benötigt.\n\n';

                text += 'Liste aller Befehle, die **du** nutzen kannst:\n\n';

                commands.forEach(function (command) {
                    if (command.role == "Admin") {
                        if (!isAdmin.check(message.author)) {
                            return;
                        }
                    } else if (command.role == "Moderator") {
                        if (!isMod.check(message.author)) {
                            return;
                        }
                    } else if (command.role == "Community") {
                        if (!isUser.check(message.author)) {
                            return;
                        }
                    }

                    text += '**`' + command.name + '`**';
                    if ('aliases' in command) {
                        text += ' (alternativ: ';
                        text += '`' + command.aliases.join('`, `');
                        text += '`)';
                    }

                    text += '\n```' + command.help + '```\n\n';
                });

                respondPm(message, text);

                if (message.channel.type == 'text') {
                    message.delete();
                }
            })();
            break;
        case 'ver':
        case 'version':
            (function () {
                respond(message, "Bronies.de DSB version `" + version + "`.\nAktuellster Commit: https://github.com/DerAtrox/Bronies.de-DSB/commit/" + version);
            })();
            break;
        case 'nsfw':
            (function () {
                if (message.guild != server) {
                    return respondPm(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!');
                }

                var msg = message;
                message.delete();

                if (!isUser.check(msg.author)) {
                    return respondPm(msg, 'Du besitzt nicht genügend Rechte!');
                }

                if (args.length != 1) {
                    return respondPm(msg, 'Nutze `!nsfw <join|leave>` um den NSFW Bereich zu betreten bzw. zu verlassen.\nBeispiel: `!nsfw join`');
                }

                var arg = args[0].toLowerCase();

                var nsfwRole = server.roles.find('name', 'NSFW');
                var member = getGuildMemeber(msg.author);

                if (arg == 'join') {
                    if (member.roles.exists('name', 'NSFW')) {
                        return respondPm(msg, 'Du hast bereits Zugriff auf den NSFW Bereich.');
                    } else {
                        member.addRole(nsfwRole);
                        return respondPm(msg, 'Bronies.de NSFW Bereich beigetreten. :smirk:');
                    }
                } else if (arg == 'leave') {
                    if (!member.roles.exists('name', 'NSFW')) {
                        return respondPm(msg, 'Du hast bereits keinen Zugriff auf den NSFW Bereich.');
                    } else {
                        member.removeRole(nsfwRole);
                        return respondPm(msg, 'Bronies.de NSFW Bereich verlassen.');
                    }
                } else {
                    return respondPm(msg, 'Nutze `!nsfw <join|leave>` um den NSFW Bereich zu betreten bzw. zu verlassen.\nBeispiel: `!nsfw join`');
                }
            })();
            break;
        case 'soundboard':
        case 'sb':
            (function () {
                if (message.guild != server) {
                    return respondPm(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!');
                }

                if (!isUser.check(message.author)) {
                    return respondPm(message, 'Du besitzt nicht genügend Rechte!');
                    message.delete();
                }

                if (args.length != 1) {
                    return respondPm(message, 'Spiele Pony Sounds in deinem aktuellen Voicechannel ab. Nutze `!sb help` um alle Sounds anzuzeigen.\nBeispiel: `!sb lunafun`');
                    message.delete();
                }

                var arg = args[0].toLowerCase();

                if (arg == 'help') {
                    respondPm(message, 'Folgende Sounds können abgespielt werden:\n```' + Object.keys(sounds).join(' ') + '```');
                    return message.delete();
                } else {
                    if (sbbusy) {
                        return;
                    }

                    var member = getGuildMemeber(message.author);

                    if (typeof member.voiceChannel == 'undefined') {
                        return;
                    }

                    if (!(arg in sounds)) {
                        return;
                    }

                    var soundPath = './sounds/' + sounds[arg];

                    fs.access(soundPath, fs.constants.R_OK, function (err) {
                        if (!err) {
                            sbbusy = true;
                            member.voiceChannel.join().then(function (connection) {
                                const dispatcher = connection.playFile('./sounds/' + sounds[arg]);

                                dispatcher.on('end', function () {
                                    sbbusy = false;
                                    connection.disconnect();

                                });

                                dispatcher.on('error', function (message) {
                                    console.log(message);
                                });
                            })
                                .catch(console.error);
                        } else {
                            console.log('Soundfile not found: ' + arg + ' file ' + sounds[arg]);
                        }
                    });
                }

            })();
            break;
        case 'derpi':
        case 'db':
            (function () {
                if (message.guild != server) {
                    return respondPm(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!');
                }

                if (!isUser.check(message.author)) {
                    return respondPm(message, 'Du besitzt nicht genügend Rechte!');
                    message.delete();
                }

                if (args.length < 1) {
                    return respond(message, 'Dieser Befehl benötigt zusätzliche Parameter. Mehr unter `!help`');
                }

                var regexOrder = /\bo:(desc|asc)\b/i,
                    regexSort = /\bby:(score|relevance|width|height|comments|random)\b/i,
                    parameters = '',
                    query = args.join(' ');

                if(message.channel == server.channels.find('name', 'nsfw')) {
                    parameters += '&filter_id=134141';
                }

                if(regexOrder.test(query)) {
                    parameters += '&sd=' + query.match(regexOrder)[1];
                    query = query.replace(regexOrder, '');
                }

                if(regexSort.test(query)) {
                    parameters += '&sf=' + query.match(regexSort)[1];
                    query = query.replace(regexSort, '');
                } else {
                    parameters += '&sf=random';
                }

                query = query.replace(/,{2,}/g, ',').replace(/(^,|,$)/, '');
                var url = 'https://derpibooru.org/search.json?q=' + encodeURIComponent(query) + parameters;
                console.log(message.author.username + '#' + message.author.discriminator + ' - Derpibooru search: ' + url);

                unirest.get(url)
                    .header("Accept", "application/json")
                    .end(function (result) {
                        if (result.error || typeof result.body !== 'object') {
                            console.log(result.error, result.body);
                            return respond(message, 'Derpibooru Anfrage fehlgeschlagen (HTTP ' + result.status + ')');
                        }

                        var data = result.body;
                        if (typeof data.search === 'undefined' || typeof data.search[0] === 'undefined')
                            return respond(message, 'Keine Suchergebnisse gefunden.');

                        var img = data.search[0];

                        if (!img.is_rendered) {
                            return respond(message, 'Dieses Bild wurde noch nicht von Derpibooru verarbeitet. Bitte versuche es später erneut.');
                        }

                        respond(message, '<http://derpibooru.org/' + img.id + '>\nhttps:' + (img.image.replace(/__[^.]+(.\w+)$/, '$1')));
                    });

            })();
            break;
    }
}

var commands = [
    {
        name: 'help',
        help: 'Zeigt alle verfügbaren Befehle an.'
    },
    {
        name: 'version',
        help: 'Zeigt die verwendete Bronies.de DSB Version an.',
        aliases: ['ver']
    },
    {
        name: 'nsfw <join|leave>',
        help: '#nsfw betreten oder verlassen.',
        role: 'Community'
    },
    {
        name: 'soundboard <sound>',
        help: 'Sound in aktuellem Sprachchannel abspielen. Liste aller Sounds mit !sb help',
        aliases: ['sb'],
        role: 'Community'
    },
    {
        name: 'derpi <search>',
        help: 'Gibt das erste Bild einer Derpibooru Suche zurück.\n\n' +
        'Optionen:\n' +
        ' - Reihenfolge  o:<desc|asc>\n' +
        ' - Sortierung   by:<score|relevance|width|height|comments|random>',
        aliases: ['db'],
        role: 'Community'
    },
    {
        name: 'nowplaying',
        help: 'Zeigt den aktuell gespielten Track des BRG-Musikbots an.',
        aliases: ['np']
    }
];

var sounds = {
    'lunafun': 'Princess Luna/the fun has been doubled.mp3',
    'eyyup': 'Big Macintosh/eyup.mp3',
    'nope': 'Big Macintosh/nnope.mp3',
    'yeehaw': 'Applejack/yeehaw.mp3',
    'laugh': 'Rainbow Dash/laughing.mp3',
    'catchy': 'Twilight Sparkle/wow catchy.mp3',
    'crazy': 'Twilight Sparkle/are you crazy.mp3',
    'grin': 'Fluttershy/(grin).mp3',
    'choochoo': 'Fluttershy/choo choo train.mp3',
    'yay': 'Fluttershy/yay.mp3',
    'boring': 'Pinkie Pie/boring.mp3',
    'giggle': 'Pinkie Pie/giggle.mp3',
    'oki': 'Pinkie Pie/oki doki loki.mp3',
    'rimshot': 'Pinkie Pie/rimshot.mp3',
    'yeah': 'Snowflake/yeah2.mp3',
    'fanfare': 'Trixie/fanfare.mp3',
    'youmad': 'Zecora/have you gone mad.mp3',
    '10seconds': 'Rainbow Dash/10 seconds flat.mp3',
    'style': 'Pinkie Pie/pinkie pie style.mp3',
    'notcool': 'Rainbow Dash/not cool.mp3',
    'wrong': 'Derpy/i just dont know what went wrong.mp3'
};

/* GENERAL APPLICATION STUFF */
process.on('exit', idle);

process.on('SIGINT', function () {
    idle();
    process.exit();

});

function getDateTime() {
    return "[" + new Date().toLocaleString() + "] ";
}

function idle() {
    bot.user.setStatus('idle');
}

function online() {
    bot.user.setStatus('online');
}

/* LOGIN */
bot.login(token);

<|endoftext|>


<commit_before>var Discord = require('discord.js'),
    config = require('./config'),
    fs = require('fs'),
    unirest = require('unirest'),
    token = config.TOKEN,
    bot = new Discord.Client(),
    server,
    version,
    exec,
    sbbusy = false;

/* VERSION */
function getVersion(callback) {
    exec = exec || require('child_process').exec;

    exec('git rev-parse --short=4 HEAD', function (error, version) {
        if (error) {
            console.log('Error getting version', error);
            return callback('unknown');
        }

        callback(version.trim());
    });
}

/* BOT EVENTS */
bot.on('ready', function () {
    online();
    console.log(getDateTime() + 'I am ready!');
    getVersion(function (v) {
        version = v;
        bot.user.setGame('version ' + version);

        if (config.DEBUG) bot.channels.find('id', config.BOT_CH).sendMessage('I am ready, running version `' + version + '`! 👌');
    });

    if (!bot.guilds.exists('id', config.SERVER_ID)) {
        console.log('Bot is not connected to the selected server!');
        process.exit();
    }

    server = bot.guilds.find('id', config.SERVER_ID);
});

bot.on('guildMemberAdd', function (member) {
    //bot.channels.find('id', config.DEFAULT_CH).sendMessage(member + ' Willkommen auf dem offiziellen Discord Server von Bronies.de ... Wirf doch für den Anfang einen Blick in den #info Bereich. :lyra_1:');
});

function onMessage(message) {
    if (message.author.id == bot.user.id) {
        return;
    }

    if (message.channel.type == 'group') {
        return;
    }

    function handleCommand() {
        var match = /^[\/!]([a-zA-Z]+).*$/.exec(message.content);

        if (message.channel.type == 'dm') {
            match = /^[\/!]?([a-zA-Z]+).*$/.exec(message.content);
        }

        if (match) {
            var args = message.content.split(' ').splice(1);

            processCommand(message, match[1].toLowerCase(), args);
        }
    }

    if (server.channels.exists('id', message.channel.id)) {
        handleCommand();
    } else {
        if (server.members.exists('id', message.author.id)) {
            handleCommand();
        } else {
            return message.channel.sendMessage('You have to be member of ' + server.name + '!');
        }
    }
}

bot.on('message', onMessage);

bot.on('messageUpdate', function (oldMessage, newMessage) {
    if (typeof newMessage.author === 'undefined')
        return;

    onMessage(newMessage);
});

/* PERMISSIONS */
function Permission(checker) {
    return {
        check: function (user) {
            if (!server.members.exists('id', user.id)) {
                return false;
            }

            var member = server.members.find('id', user.id);

            return checker(member);
        }
    };
}

var isAdmin = new Permission(function (member) {
    return member.roles.exists('name', 'Admin') || member.roles.exists('name', 'Co-Admin');
});

var isMod = new Permission(function (member) {
    return isAdmin.check(member) ? true : member.roles.exists('name', 'Moderator');
});

var isUser = new Permission(function (member) {
    return isMod.check(member) ? true : member.roles.exists('name', '⬛ Community');
});

function getGuildMemeber(user) {
    return server.members.find('id', user.id);
}

function respond(message, response, pm) {
    if (typeof pm === 'undefined') {
        pm = false;
    }

    if (pm) {
        message.author.sendMessage(response);
    } else {
        message.reply(response);
    }
}

/* COMMAND PROCESSING */
function processCommand(message, command, args) {
    switch (command) {
        case 'help':
            (function () {
                var text = '\n\nBefehle müssen `/` oder `!` vorangestellt haben. Groß- und Kleinschreibung wird nicht beachtet.\nIn PMs wird kein Präfix benötigt.\n\n';

                text += 'Liste aller Befehle, die **du** nutzen kannst:\n\n';

                commands.forEach(function (command) {
                    if (command.role == "Admin") {
                        if (!isAdmin.check(message.author)) {
                            return;
                        }
                    } else if (command.role == "Moderator") {
                        if (!isMod.check(message.author)) {
                            return;
                        }
                    } else if (command.role == "Community") {
                        if (!isUser.check(message.author)) {
                            return;
                        }
                    }

                    text += '**`' + command.name + '`**';
                    if ('aliases' in command) {
                        text += ' (alternativ: ';
                        text += '`' + command.aliases.join('`, `');
                        text += '`)';
                    }

                    text += '\n```' + command.help + '```\n\n';
                });

                respond(message, text, true);
                if (message.channel.type == 'text') {
                    message.delete();
                }
            })();
            break;
        case 'ver':
        case 'version':
            (function () {
                respond(message, "Bronies.de DSB version `" + version + "`.\nAktuellster Commit: https://github.com/DerAtrox/Bronies.de-DSB/commit/" + version);
            })();
            break;
        case 'nsfw':
            (function () {
                if (message.guild != server) {
                    return respond(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!', true);
                }

                var msg = message;
                message.delete();

                if (!isUser.check(msg.author)) {
                    return respond(msg, 'Du besitzt nicht genügend Rechte!', true);
                }

                if (args.length != 1) {
                    return respond(msg, 'Nutze `!nsfw <join|leave>` um den NSFW Bereich zu betreten bzw. zu verlassen.\nBeispiel: `!nsfw join`', true);
                }

                var arg = args[0].toLowerCase();

                var nsfwRole = server.roles.find('name', 'NSFW');
                var member = getGuildMemeber(msg.author);

                if (arg == 'join') {
                    if (member.roles.exists('name', 'NSFW')) {
                        return respond(msg, 'Du hast bereits Zugriff auf den NSFW Bereich.', true);
                    } else {
                        member.addRole(nsfwRole);
                        return respond(msg, 'Bronies.de NSFW Bereich beigetreten. :smirk:', true);
                    }
                } else if (arg == 'leave') {
                    if (!member.roles.exists('name', 'NSFW')) {
                        return respond(msg, 'Du hast bereits keinen Zugriff auf den NSFW Bereich.', true);
                    } else {
                        member.removeRole(nsfwRole);
                        return respond(msg, 'Bronies.de NSFW Bereich verlassen.', true);
                    }
                } else {
                    return respond(msg, 'Nutze `!nsfw <join|leave>` um den NSFW Bereich zu betreten bzw. zu verlassen.\nBeispiel: `!nsfw join`', true);
                }
            })();
            break;
        case 'soundboard':
        case 'sb':
            (function () {
                if (message.guild != server) {
                    return respond(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!', true);
                }

                if (!isUser.check(message.author)) {
                    return respond(message, 'Du besitzt nicht genügend Rechte!', true);
                    message.delete();
                }

                if (args.length != 1) {
                    return respond(message, 'Spiele Pony Sounds in deinem aktuellen Voicechannel ab. Nutze `!sb help` um alle Sounds anzuzeigen.\nBeispiel: `!sb lunafun`', true);
                    message.delete();
                }

                var arg = args[0].toLowerCase();

                if (arg == 'help') {
                    respond(message, 'Folgende Sounds können abgespielt werden:\n```' + Object.keys(sounds).join(' ') + '```', true);
                    return message.delete();
                } else {
                    if (sbbusy) {
                        return;
                    }

                    var member = getGuildMemeber(message.author);

                    if (typeof member.voiceChannel == 'undefined') {
                        return;
                    }

                    if (!(arg in sounds)) {
                        return;
                    }

                    var soundPath = './sounds/' + sounds[arg];

                    fs.access(soundPath, fs.constants.R_OK, function (err) {
                        if (!err) {
                            sbbusy = true;
                            member.voiceChannel.join().then(function (connection) {
                                const dispatcher = connection.playFile('./sounds/' + sounds[arg]);

                                dispatcher.on('end', function () {
                                    sbbusy = false;
                                    connection.disconnect();

                                });

                                dispatcher.on('error', function (message) {
                                    console.log(message);
                                });
                            })
                                .catch(console.error);
                        } else {
                            console.log('Soundfile not found: ' + arg + ' file ' + sounds[arg]);
                        }
                    });
                }

            })();
            break;
        case 'derpi':
        case 'db':
            (function () {
                if (message.guild != server) {
                    return respond(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!', true);
                }

                if (!isUser.check(message.author)) {
                    return respond(message, 'Du besitzt nicht genügend Rechte!', true);
                    message.delete();
                }

                if (args.length < 1) {
                    return respond(message, 'Dieser Befehl benötigt zusätzliche Parameter. Mehr unter `!help`');
                }

                var regexOrder = /\bo:(desc|asc)\b/i,
                    regexSort = /\bby:(score|relevance|width|height|comments|random)\b/i,
                    parameters = '',
                    query = args.join(' ');

                if(message.channel == server.channels.find('name', 'nsfw')) {
                    parameters += '&filter_id=134114';
                }

                if(regexOrder.test(query)) {
                    parameters += '&sd=' + query.match(regexOrder)[1];
                    query = query.replace(regexOrder, '');
                }

                if(regexSort.test(query)) {
                    parameters += '&sf=' + query.match(regexSort)[1];
                    query = query.replace(regexSort, '');
                } else {
                    parameters += '&sf=random';
                }

                query = query.replace(/,{2,}/g, ',').replace(/(^,|,$)/, '');
                var url = 'https://derpibooru.org/search.json?q=' + encodeURIComponent(query) + parameters;
                console.log(message.author.username + '#' + message.author.discriminator + ' - Derpibooru search: ' + url);

                unirest.get(url)
                    .header("Accept", "application/json")
                    .end(function (result) {
                        if (result.error || typeof result.body !== 'object') {
                            console.log(result.error, result.body);
                            return respond(message, 'Derpibooru Anfrage fehlgeschlagen (HTTP ' + result.status + ')');
                        }

                        var data = result.body;
                        if (typeof data.search === 'undefined' || typeof data.search[0] === 'undefined')
                            return respond(message, 'Keine Suchergebnisse gefunden.');

                        var img = data.search[0];

                        if (!img.is_rendered) {
                            return respond(message, 'Dieses Bild wurde noch nicht von Derpibooru verarbeitet. Bitte versuche es später erneut.');
                        }

                        respond(message, '<http://derpibooru.org/' + img.id + '>\nhttps:' + (img.image.replace(/__[^.]+(.\w+)$/, '$1')));
                    });

            })();
            break;
    }
}

var commands = [
    {
        name: 'help',
        help: 'Zeigt alle verfügbaren Befehle an.'
    },
    {
        name: 'version',
        help: 'Zeigt die verwendete Bronies.de DSB Version an.',
        aliases: ['ver']
    },
    {
        name: 'nsfw <join|leave>',
        help: '#nsfw betreten oder verlassen.',
        role: 'Community'
    },
    {
        name: 'soundboard <sound>',
        help: 'Sound in aktuellem Sprachchannel abspielen. Liste aller Sounds mit !sb help',
        aliases: ['sb'],
        role: 'Community'
    },
    {
        name: 'derpi <search>',
        help: 'Gibt das erste Bild einer Derpibooru Suche zurück.\n\n' +
        'Optionen:\n' +
        ' - Reihenfolge  o:<desc|asc>\n' +
        ' - Sortierung   by:<score|relevance|width|height|comments|random>',
        aliases: ['db'],
        role: 'Community'
    },
    {
        name: 'nowplaying',
        help: 'Zeigt den aktuell gespielten Track des BRG-Musikbots an.',
        aliases: ['np']
    }
];

var sounds = {
    'lunafun': 'Princess Luna/the fun has been doubled.mp3',
    'eyyup': 'Big Macintosh/eyup.mp3',
    'nope': 'Big Macintosh/nnope.mp3',
    'yeehaw': 'Applejack/yeehaw.mp3',
    'laugh': 'Rainbow Dash/laughing.mp3',
    'catchy': 'Twilight Sparkle/wow catchy.mp3',
    'crazy': 'Twilight Sparkle/are you crazy.mp3',
    'grin': 'Fluttershy/(grin).mp3',
    'choochoo': 'Fluttershy/choo choo train.mp3',
    'yay': 'Fluttershy/yay.mp3',
    'boring': 'Pinkie Pie/boring.mp3',
    'giggle': 'Pinkie Pie/giggle.mp3',
    'oki': 'Pinkie Pie/oki doki loki.mp3',
    'rimshot': 'Pinkie Pie/rimshot.mp3',
    'yeah': 'Snowflake/yeah2.mp3',
    'fanfare': 'Trixie/fanfare.mp3',
    'youmad': 'Zecora/have you gone mad.mp3',
    '10seconds': 'Rainbow Dash/10 seconds flat.mp3',
    'style': 'Pinkie Pie/pinkie pie style.mp3'
};

/* GENERAL APPLICATION STUFF */
process.on('exit', idle);

process.on('SIGINT', function () {
    idle();
    process.exit();

});

function getDateTime() {
    return "[" + new Date().toLocaleString() + "] ";
}

function idle() {
    bot.user.setStatus('idle');
}

function online() {
    bot.user.setStatus('online');
}

/* LOGIN */
bot.login(token);

<commit_msg>split respond in 2 functions, added notcool sound<commit_after>var Discord = require('discord.js'),
    config = require('./config'),
    fs = require('fs'),
    unirest = require('unirest'),
    token = config.TOKEN,
    bot = new Discord.Client(),
    server,
    version,
    exec,
    sbbusy = false;

/* VERSION */
function getVersion(callback) {
    exec = exec || require('child_process').exec;

    exec('git rev-parse --short=4 HEAD', function (error, version) {
        if (error) {
            console.log('Error getting version', error);
            return callback('unknown');
        }

        callback(version.trim());
    });
}

/* BOT EVENTS */
bot.on('ready', function () {
    online();
    console.log(getDateTime() + 'I am ready!');
    getVersion(function (v) {
        version = v;
        bot.user.setGame('version ' + version);

        if (config.DEBUG) bot.channels.find('id', config.BOT_CH).sendMessage('I am ready, running version `' + version + '`! 👌');
    });

    if (!bot.guilds.exists('id', config.SERVER_ID)) {
        console.log('Bot is not connected to the selected server!');
        process.exit();
    }

    server = bot.guilds.find('id', config.SERVER_ID);
});

bot.on('guildMemberAdd', function (member) {
    //bot.channels.find('id', config.DEFAULT_CH).sendMessage(member + ' Willkommen auf dem offiziellen Discord Server von Bronies.de ... Wirf doch für den Anfang einen Blick in den #info Bereich. :lyra_1:');
});

function onMessage(message) {
    if (message.author.id == bot.user.id) {
        return;
    }

    if (message.channel.type == 'group') {
        return;
    }

    function handleCommand() {
        var match = /^[\/!]([a-zA-Z]+).*$/.exec(message.content);

        if (message.channel.type == 'dm') {
            match = /^[\/!]?([a-zA-Z]+).*$/.exec(message.content);
        }

        if (match) {
            var args = message.content.split(' ').splice(1);

            processCommand(message, match[1].toLowerCase(), args);
        }
    }

    if (server.channels.exists('id', message.channel.id)) {
        handleCommand();
    } else {
        if (server.members.exists('id', message.author.id)) {
            handleCommand();
        } else {
            return message.channel.sendMessage('You have to be member of ' + server.name + '!');
        }
    }
}

bot.on('message', onMessage);

bot.on('messageUpdate', function (oldMessage, newMessage) {
    if (typeof newMessage.author === 'undefined')
        return;

    onMessage(newMessage);
});

/* PERMISSIONS */
function Permission(checker) {
    return {
        check: function (user) {
            if (!server.members.exists('id', user.id)) {
                return false;
            }

            var member = server.members.find('id', user.id);

            return checker(member);
        }
    };
}

var isAdmin = new Permission(function (member) {
    return member.roles.exists('name', 'Admin') || member.roles.exists('name', 'Co-Admin');
});

var isMod = new Permission(function (member) {
    return isAdmin.check(member) ? true : member.roles.exists('name', 'Moderator');
});

var isUser = new Permission(function (member) {
    return isMod.check(member) ? true : member.roles.exists('name', '⬛ Community');
});

function getGuildMemeber(user) {
    return server.members.find('id', user.id);
}

function respond(message, response, mention) {
    if (typeof mention === 'undefined') {
        mention = false;
    }

    if (mention) {
        message.reply(response);
    } else {
        message.channel.sendMessage(response);
    }
}

function respondPm(message, response) {
    message.author.sendMessage(response);
}

/* COMMAND PROCESSING */
function processCommand(message, command, args) {
    switch (command) {
        case 'help':
            (function () {
                var text = '\n\nBefehle müssen `/` oder `!` vorangestellt haben. Groß- und Kleinschreibung wird nicht beachtet.\nIn PMs wird kein Präfix benötigt.\n\n';

                text += 'Liste aller Befehle, die **du** nutzen kannst:\n\n';

                commands.forEach(function (command) {
                    if (command.role == "Admin") {
                        if (!isAdmin.check(message.author)) {
                            return;
                        }
                    } else if (command.role == "Moderator") {
                        if (!isMod.check(message.author)) {
                            return;
                        }
                    } else if (command.role == "Community") {
                        if (!isUser.check(message.author)) {
                            return;
                        }
                    }

                    text += '**`' + command.name + '`**';
                    if ('aliases' in command) {
                        text += ' (alternativ: ';
                        text += '`' + command.aliases.join('`, `');
                        text += '`)';
                    }

                    text += '\n```' + command.help + '```\n\n';
                });

                respondPm(message, text);

                if (message.channel.type == 'text') {
                    message.delete();
                }
            })();
            break;
        case 'ver':
        case 'version':
            (function () {
                respond(message, "Bronies.de DSB version `" + version + "`.\nAktuellster Commit: https://github.com/DerAtrox/Bronies.de-DSB/commit/" + version);
            })();
            break;
        case 'nsfw':
            (function () {
                if (message.guild != server) {
                    return respondPm(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!');
                }

                var msg = message;
                message.delete();

                if (!isUser.check(msg.author)) {
                    return respondPm(msg, 'Du besitzt nicht genügend Rechte!');
                }

                if (args.length != 1) {
                    return respondPm(msg, 'Nutze `!nsfw <join|leave>` um den NSFW Bereich zu betreten bzw. zu verlassen.\nBeispiel: `!nsfw join`');
                }

                var arg = args[0].toLowerCase();

                var nsfwRole = server.roles.find('name', 'NSFW');
                var member = getGuildMemeber(msg.author);

                if (arg == 'join') {
                    if (member.roles.exists('name', 'NSFW')) {
                        return respondPm(msg, 'Du hast bereits Zugriff auf den NSFW Bereich.');
                    } else {
                        member.addRole(nsfwRole);
                        return respondPm(msg, 'Bronies.de NSFW Bereich beigetreten. :smirk:');
                    }
                } else if (arg == 'leave') {
                    if (!member.roles.exists('name', 'NSFW')) {
                        return respondPm(msg, 'Du hast bereits keinen Zugriff auf den NSFW Bereich.');
                    } else {
                        member.removeRole(nsfwRole);
                        return respondPm(msg, 'Bronies.de NSFW Bereich verlassen.');
                    }
                } else {
                    return respondPm(msg, 'Nutze `!nsfw <join|leave>` um den NSFW Bereich zu betreten bzw. zu verlassen.\nBeispiel: `!nsfw join`');
                }
            })();
            break;
        case 'soundboard':
        case 'sb':
            (function () {
                if (message.guild != server) {
                    return respondPm(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!');
                }

                if (!isUser.check(message.author)) {
                    return respondPm(message, 'Du besitzt nicht genügend Rechte!');
                    message.delete();
                }

                if (args.length != 1) {
                    return respondPm(message, 'Spiele Pony Sounds in deinem aktuellen Voicechannel ab. Nutze `!sb help` um alle Sounds anzuzeigen.\nBeispiel: `!sb lunafun`');
                    message.delete();
                }

                var arg = args[0].toLowerCase();

                if (arg == 'help') {
                    respondPm(message, 'Folgende Sounds können abgespielt werden:\n```' + Object.keys(sounds).join(' ') + '```');
                    return message.delete();
                } else {
                    if (sbbusy) {
                        return;
                    }

                    var member = getGuildMemeber(message.author);

                    if (typeof member.voiceChannel == 'undefined') {
                        return;
                    }

                    if (!(arg in sounds)) {
                        return;
                    }

                    var soundPath = './sounds/' + sounds[arg];

                    fs.access(soundPath, fs.constants.R_OK, function (err) {
                        if (!err) {
                            sbbusy = true;
                            member.voiceChannel.join().then(function (connection) {
                                const dispatcher = connection.playFile('./sounds/' + sounds[arg]);

                                dispatcher.on('end', function () {
                                    sbbusy = false;
                                    connection.disconnect();

                                });

                                dispatcher.on('error', function (message) {
                                    console.log(message);
                                });
                            })
                                .catch(console.error);
                        } else {
                            console.log('Soundfile not found: ' + arg + ' file ' + sounds[arg]);
                        }
                    });
                }

            })();
            break;
        case 'derpi':
        case 'db':
            (function () {
                if (message.guild != server) {
                    return respondPm(message, 'Dieser Befehl kann nur auf dem Bronies.de Discord Server ausgeführt werden!');
                }

                if (!isUser.check(message.author)) {
                    return respondPm(message, 'Du besitzt nicht genügend Rechte!');
                    message.delete();
                }

                if (args.length < 1) {
                    return respond(message, 'Dieser Befehl benötigt zusätzliche Parameter. Mehr unter `!help`');
                }

                var regexOrder = /\bo:(desc|asc)\b/i,
                    regexSort = /\bby:(score|relevance|width|height|comments|random)\b/i,
                    parameters = '',
                    query = args.join(' ');

                if(message.channel == server.channels.find('name', 'nsfw')) {
                    parameters += '&filter_id=134114';
                }

                if(regexOrder.test(query)) {
                    parameters += '&sd=' + query.match(regexOrder)[1];
                    query = query.replace(regexOrder, '');
                }

                if(regexSort.test(query)) {
                    parameters += '&sf=' + query.match(regexSort)[1];
                    query = query.replace(regexSort, '');
                } else {
                    parameters += '&sf=random';
                }

                query = query.replace(/,{2,}/g, ',').replace(/(^,|,$)/, '');
                var url = 'https://derpibooru.org/search.json?q=' + encodeURIComponent(query) + parameters;
                console.log(message.author.username + '#' + message.author.discriminator + ' - Derpibooru search: ' + url);

                unirest.get(url)
                    .header("Accept", "application/json")
                    .end(function (result) {
                        if (result.error || typeof result.body !== 'object') {
                            console.log(result.error, result.body);
                            return respond(message, 'Derpibooru Anfrage fehlgeschlagen (HTTP ' + result.status + ')');
                        }

                        var data = result.body;
                        if (typeof data.search === 'undefined' || typeof data.search[0] === 'undefined')
                            return respond(message, 'Keine Suchergebnisse gefunden.');

                        var img = data.search[0];

                        if (!img.is_rendered) {
                            return respond(message, 'Dieses Bild wurde noch nicht von Derpibooru verarbeitet. Bitte versuche es später erneut.');
                        }

                        respond(message, '<http://derpibooru.org/' + img.id + '>\nhttps:' + (img.image.replace(/__[^.]+(.\w+)$/, '$1')));
                    });

            })();
            break;
    }
}

var commands = [
    {
        name: 'help',
        help: 'Zeigt alle verfügbaren Befehle an.'
    },
    {
        name: 'version',
        help: 'Zeigt die verwendete Bronies.de DSB Version an.',
        aliases: ['ver']
    },
    {
        name: 'nsfw <join|leave>',
        help: '#nsfw betreten oder verlassen.',
        role: 'Community'
    },
    {
        name: 'soundboard <sound>',
        help: 'Sound in aktuellem Sprachchannel abspielen. Liste aller Sounds mit !sb help',
        aliases: ['sb'],
        role: 'Community'
    },
    {
        name: 'derpi <search>',
        help: 'Gibt das erste Bild einer Derpibooru Suche zurück.\n\n' +
        'Optionen:\n' +
        ' - Reihenfolge  o:<desc|asc>\n' +
        ' - Sortierung   by:<score|relevance|width|height|comments|random>',
        aliases: ['db'],
        role: 'Community'
    },
    {
        name: 'nowplaying',
        help: 'Zeigt den aktuell gespielten Track des BRG-Musikbots an.',
        aliases: ['np']
    }
];

var sounds = {
    'lunafun': 'Princess Luna/the fun has been doubled.mp3',
    'eyyup': 'Big Macintosh/eyup.mp3',
    'nope': 'Big Macintosh/nnope.mp3',
    'yeehaw': 'Applejack/yeehaw.mp3',
    'laugh': 'Rainbow Dash/laughing.mp3',
    'catchy': 'Twilight Sparkle/wow catchy.mp3',
    'crazy': 'Twilight Sparkle/are you crazy.mp3',
    'grin': 'Fluttershy/(grin).mp3',
    'choochoo': 'Fluttershy/choo choo train.mp3',
    'yay': 'Fluttershy/yay.mp3',
    'boring': 'Pinkie Pie/boring.mp3',
    'giggle': 'Pinkie Pie/giggle.mp3',
    'oki': 'Pinkie Pie/oki doki loki.mp3',
    'rimshot': 'Pinkie Pie/rimshot.mp3',
    'yeah': 'Snowflake/yeah2.mp3',
    'fanfare': 'Trixie/fanfare.mp3',
    'youmad': 'Zecora/have you gone mad.mp3',
    '10seconds': 'Rainbow Dash/10 seconds flat.mp3',
    'style': 'Pinkie Pie/pinkie pie style.mp3',
    'notcool': 'Rainbow Dash/not cool.mp3'
};

/* GENERAL APPLICATION STUFF */
process.on('exit', idle);

process.on('SIGINT', function () {
    idle();
    process.exit();

});

function getDateTime() {
    return "[" + new Date().toLocaleString() + "] ";
}

function idle() {
    bot.user.setStatus('idle');
}

function online() {
    bot.user.setStatus('online');
}

/* LOGIN */
bot.login(token);

<|endoftext|>


<commit_before>var pictureSource; // picture source
var destinationType; // sets the format of returned value
var pictureFiles = new Array();

// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);

// device APIs are available
//
function onDeviceReady() {
    pictureSource=navigator.camera.PictureSourceType;
    destinationType=navigator.camera.DestinationType;
}

// get Photo from Album
//
function getPhoto(source) {
    // Retrieve image file location from specified source
    navigator.camera.getPicture(onPhotoURISuccess, onFail, {
        quality: 50,
        destinationType: destinationType.FILE_URI,
        sourceType: source
    });
}

function onPhotoURISuccess(imageURI) {
    jQuery("p#pics").prepend("");
    pictureFiles.push(imageURI);
}

function captureSuccess(mediaFiles) {
    var i, len;
    for (i = 0, len = mediaFiles.length; i < len; i += 1) {
        pPath = mediaFiles[i].fullPath;

        pictureFiles.push(mediaFiles[i]);
        jQuery("p#pics").prepend("");
    }
}

function uploadFiles() {
    var j, leng;

    mesLen = pictureFiles.length;

    for (j = 0, leng = pictureFiles.length; j < leng; j += 1) {
        uploadFile(pictureFiles[j]);
        jQuery("p#pics img:first-child").remove();
    }
    pictureFiles = [];

    if(mesLen>0) {
        setTimeout("alert(\"Es werden "+mesLen+" Bilder hochgeladen\")", 500);
    }
}

// Called if something bad happens.
//
function captureError(error) {
    var msg = 'An error occurred during capture: ' + error.code;
    navigator.notification.alert(msg, null, 'Uh oh!');
}

// A button will call this function
//
function captureImage() {
    // Launch device camera application,
    // allowing user to capture up to 2 images
    navigator.device.capture.captureImage(captureSuccess, captureError,{limit: 1});
    alert("captureImage");
}

// Upload files to server
function uploadFile(mediaFile) {

    var ft = new FileTransfer(),
    path = mediaFile.fullPath,
    name = mediaFile.name;

    ft.upload(path,
        "http://ids-services.at/ma-test/upload.php",
        function(result) {
            console.log('Upload success: ' + result.responseCode);
            console.log(result.bytesSent + ' bytes sent');
        },
        function(error) {
            console.log('Error uploading file ' + path + ': ' + error.code);
        },
        {
            fileName: name
        });
}

function deleteImage(){
    jQuery("p#pics img:first-child").remove();
    pictureFiles.pop();
}

function onFail(message) {
  alert('Fehlgeschlagen: ' + message);
}<commit_msg>Capture Image<commit_after>var pictureSource; // picture source
var destinationType; // sets the format of returned value
var pictureFiles = new Array();

// Wait for device API libraries to load
//
// document.addEventListener("deviceready",onDeviceReady,false);

// device APIs are available
//
window.onload = function onDeviceReady() {
    pictureSource=navigator.camera.PictureSourceType;
    destinationType=navigator.camera.DestinationType;
}

// get Photo from Album
//
function getPhoto(source) {
    // Retrieve image file location from specified source
    navigator.camera.getPicture(onPhotoURISuccess, onFail, {
        quality: 50,
        destinationType: destinationType.FILE_URI,
        sourceType: source
    });
}

function onPhotoURISuccess(imageURI) {
    jQuery("p#pics").prepend("");
    pictureFiles.push(imageURI);
}

function captureSuccess(mediaFiles) {
    var i, len;
    for (i = 0, len = mediaFiles.length; i < len; i += 1) {
        pPath = mediaFiles[i].fullPath;

        pictureFiles.push(mediaFiles[i]);
        jQuery("p#pics").prepend("");
    }
}

function uploadFiles() {
    var j, leng;

    mesLen = pictureFiles.length;

    for (j = 0, leng = pictureFiles.length; j < leng; j += 1) {
        uploadFile(pictureFiles[j]);
        jQuery("p#pics img:first-child").remove();
    }
    pictureFiles = [];

    if(mesLen>0) {
        setTimeout("alert(\"Es werden "+mesLen+" Bilder hochgeladen\")", 500);
    }
}

// Called if something bad happens.
//
function captureError(error) {
    var msg = 'An error occurred during capture: ' + error.code;
    navigator.notification.alert(msg, null, 'Uh oh!');
}

// A button will call this function
//
function captureImage() {
    // Launch device camera application,
    // allowing user to capture up to 2 images
    navigator.device.capture.captureImage(captureSuccess, captureError,{limit: 1});
    alert("captureImage");
}

// Upload files to server
function uploadFile(mediaFile) {

    var ft = new FileTransfer(),
    path = mediaFile.fullPath,
    name = mediaFile.name;

    ft.upload(path,
        "http://ids-services.at/ma-test/upload.php",
        function(result) {
            console.log('Upload success: ' + result.responseCode);
            console.log(result.bytesSent + ' bytes sent');
        },
        function(error) {
            console.log('Error uploading file ' + path + ': ' + error.code);
        },
        {
            fileName: name
        });
}

function deleteImage(){
    jQuery("p#pics img:first-child").remove();
    pictureFiles.pop();
}

function onFail(message) {
  alert('Fehlgeschlagen: ' + message);
}<|endoftext|>


<commit_before>(function(FMS, Backbone, _) {
    _.extend( FMS, {
        Locate: function() { return {
            locating: 0,
            updating: 0,

            lookup: function(q) {
                var that = this;
                if (!q) {
                    this.trigger('search_failed', { msg: FMS.strings.missing_location } );
                    return false;
                }

                var url = CONFIG.FMS_URL + '/ajax/lookup_location?term=' + q;

                var x = $.ajax( {
                    url: url,
                    dataType: 'json',
                    timeout: 30000,
                    success: function(data, status) {
                        if ( status == 'success' ) {
                            if ( data.latitude ) {
                                that.trigger('search_located', { coordinates: { latitude: data.latitude, longitude: data.longitude } } );
                            } else if ( data.suggestions ) {
                                that.trigger( 'search_failed', { suggestions: data.suggestions, locations: data.locations } );
                            } else {
                                that.trigger( 'search_failed', { msg: data.error } );
                            }
                        } else {
                            that.trigger( 'search_failed', { msg: FMS.strings.location_problem } );
                        }
                    },
                    error: function(data, status, errorThrown) {
                        that.trigger( 'search_failed', { msg: FMS.strings.location_problem } );
                    }
                } );
            },

            geolocate: function( minAccuracy ) {
                console.log('geolocation');
                this.locating = 1;

                $('#ajaxOverlay').show();
                console.log(this);
                var that = this;
                this.watch_id = navigator.geolocation.watchPosition(
                    function(location) {
                    console.log('success');
                    console.log(location);
                        if ( that.watch_id === undefined ) { console.log( 'no watch id' ); return; }

                        if ( minAccuracy && location.coords.accuracy > minAccuracy ) {
                            that.trigger('gps_locating', location.coords.accuracy);
                        } else {
                            console.log( 'located with accuracy of ' + location.coords.accuracy );
                            that.locating = 0;
                            navigator.geolocation.clearWatch( that.watch_id );
                            delete that.watch_id;

                            that.check_location(location.coords);
                        }
                    },
                    function() {
                        if ( that.watch_id === undefined ) { return; }
                        that.locating = 0;
                        navigator.geolocation.clearWatch( that.watch_id );
                        delete that.watch_id;
                        that.trigger('gps_failed', { msg: FMS.strings.geolocation_failed } );
                    },
                    { timeout: 20000, enableHighAccuracy: true }
                );
            },

            updatePosition: function() {
                console.log('updatePosition');
                this.updating = 1;
                var that = this;
                this.update_watch_id = navigator.geolocation.watchPosition(
                    function(location) {
                        if ( that.update_watch_id === undefined ) { console.log( 'no update watch id' ); return; }

                        that.trigger('gps_current_position', { coordinates: location.coords } );
                    },
                    function() {},
                    { timeout: 20000, enableHighAccuracy: true }
                );
            },

            stopUpdating: function() {
                this.updating = 0;
                if ( this.update_watch_id ) {
                    navigator.geolocation.clearWatch( this.update_watch_id );
                    delete this.update_watch_id;
                }
            },

            check_location: function(coords) {
                console.log('check_location');
                var that = this;
                $.ajax( {
                    url: CONFIG.FMS_URL + 'report/new/ajax',
                    dataType: 'json',
                    data: {
                        latitude: coords.latitude,
                        longitude: coords.longitude
                    },
                    timeout: 10000,
                    success: function(data) {
                        if (data.error) {
                            that.trigger('gps_failed', { msg: data.error } );
                            return;
                        }
                        that.trigger('gps_located', { coordinates: coords, details: data } );
                    },
                    error: function (data, status, errorThrown) {
                        that.trigger('gps_failed', { msg: FMS.strings.location_check_failed } );
                    }
                } );
            }
        }; }
    });
})(FMS, Backbone, _);
<commit_msg>The first time this is called the watch id doesn't seem to be available so if we only call this once, as is aften the case if you move to one screen and back to aroun screen, then it never sets the posiotion of the dot<commit_after>(function(FMS, Backbone, _) {
    _.extend( FMS, {
        Locate: function() { return {
            locating: 0,
            updating: 0,

            lookup: function(q) {
                var that = this;
                if (!q) {
                    this.trigger('search_failed', { msg: FMS.strings.missing_location } );
                    return false;
                }

                var url = CONFIG.FMS_URL + '/ajax/lookup_location?term=' + q;

                var x = $.ajax( {
                    url: url,
                    dataType: 'json',
                    timeout: 30000,
                    success: function(data, status) {
                        if ( status == 'success' ) {
                            if ( data.latitude ) {
                                that.trigger('search_located', { coordinates: { latitude: data.latitude, longitude: data.longitude } } );
                            } else if ( data.suggestions ) {
                                that.trigger( 'search_failed', { suggestions: data.suggestions, locations: data.locations } );
                            } else {
                                that.trigger( 'search_failed', { msg: data.error } );
                            }
                        } else {
                            that.trigger( 'search_failed', { msg: FMS.strings.location_problem } );
                        }
                    },
                    error: function(data, status, errorThrown) {
                        that.trigger( 'search_failed', { msg: FMS.strings.location_problem } );
                    }
                } );
            },

            geolocate: function( minAccuracy ) {
                console.log('geolocation');
                this.locating = 1;

                $('#ajaxOverlay').show();
                console.log(this);
                var that = this;
                this.watch_id = navigator.geolocation.watchPosition(
                    function(location) {
                    console.log('success');
                    console.log(location);
                        if ( that.watch_id === undefined ) { console.log( 'no watch id' ); return; }

                        if ( minAccuracy && location.coords.accuracy > minAccuracy ) {
                            that.trigger('gps_locating', location.coords.accuracy);
                        } else {
                            console.log( 'located with accuracy of ' + location.coords.accuracy );
                            that.locating = 0;
                            navigator.geolocation.clearWatch( that.watch_id );
                            delete that.watch_id;

                            that.check_location(location.coords);
                        }
                    },
                    function() {
                        if ( that.watch_id === undefined ) { return; }
                        that.locating = 0;
                        navigator.geolocation.clearWatch( that.watch_id );
                        delete that.watch_id;
                        that.trigger('gps_failed', { msg: FMS.strings.geolocation_failed } );
                    },
                    { timeout: 20000, enableHighAccuracy: true }
                );
            },

            updatePosition: function() {
                console.log('updatePosition');
                this.updating = 1;
                var that = this;
                this.update_watch_id = navigator.geolocation.watchPosition(
                    function(location) {
                        that.trigger('gps_current_position', { coordinates: location.coords } );
                    },
                    function() {},
                    { timeout: 20000, enableHighAccuracy: true }
                );
            },

            stopUpdating: function() {
                this.updating = 0;
                if ( this.update_watch_id ) {
                    navigator.geolocation.clearWatch( this.update_watch_id );
                    delete this.update_watch_id;
                }
            },

            check_location: function(coords) {
                console.log('check_location');
                var that = this;
                $.ajax( {
                    url: CONFIG.FMS_URL + 'report/new/ajax',
                    dataType: 'json',
                    data: {
                        latitude: coords.latitude,
                        longitude: coords.longitude
                    },
                    timeout: 10000,
                    success: function(data) {
                        if (data.error) {
                            that.trigger('gps_failed', { msg: data.error } );
                            return;
                        }
                        that.trigger('gps_located', { coordinates: coords, details: data } );
                    },
                    error: function (data, status, errorThrown) {
                        that.trigger('gps_failed', { msg: FMS.strings.location_check_failed } );
                    }
                } );
            }
        }; }
    });
})(FMS, Backbone, _);
<|endoftext|>


<commit_before>;(function(){
/**
 * Created with JetBrains PhpStorm.
 * User: Karl
 * Date: 2013-10-08
 * Time: 10:59 AM
 * To change this template use File | Settings | File Templates.
 */

App.MenuItems = Backbone.Model.extend({
    defaults: {
        "logo":  "",
        "icon":  ""
    }
});

App.getDynamicModelUrl = function(view) { // just swap which line is commented out to change location
   return 'api/' + view; // this is for local
//    return "http://theplayatimes.com/welcome/api/v1/listings/" + view + "/true.json"; // this is for running live
};

App.MenuCollection = Backbone.Collection.extend({
    model: App.MenuItems,
    url: 'api/menu'
//    url: 'http://theplayatimes.com/welcome/api/v1/listing_categories'
});

App.GenericModel = Backbone.Model.extend({
    defaults: {
        "logo":  ""
    }
});

App.GenericCollection = Backbone.Collection.extend({
    model: App.GenericModel,
    url: function(){
        return App.getDynamicModelUrl(window.location.hash.replace("#", ""));
    }
});

App.PicturesCollection = Backbone.Collection.extend({
   model: App.PictureModel
});

App.PictureModel = Backbone.Model.extend();

App.getModelUrl = function(view) { // just swap which line is commented out to change location
    return 'api/' + view; // this is for local
//    return "http://theplayatimes.com/welcome/api/v1/listings/" + view + '/true.json'; // this is for running live
};

//Restaurants ------------------------------------------------------
App.Restaurants = Backbone.Model.extend({
    defaults: {
        "logo":  "" // to make sure that it has a value.
    }
});

App.RestaurantsCollection = Backbone.Collection.extend({
    model: App.Restaurants,
    url: function() {
        data =  App.getModelUrl('restaurant');
        console.log(data);
        return data;
    }
//    url:"http://theplayatimes.com/welcome/api/v1/listings/restaurant/true.json"

});

//Accommodations ------------------------------------------------------
App.Accommodations = Backbone.Model.extend();

App.AccommodationsCollection = Backbone.Collection.extend({
    model: App.Accommodations,
    url: function() {
        return App.getModelUrl('accommodation');
    }
//    url:"http://theplayatimes.com/welcome/api/v1/listings/accommodation/true.json"
});

//Attractions ------------------------------------------------------
App.Attractions = Backbone.Model.extend();

App.AttractionsCollection = Backbone.Collection.extend({
    model: App.Attractions,
    url: function() {
        return App.getModelUrl('attraction');
    }
//    url:"http://theplayatimes.com/welcome/api/v1/listings/attraction/true.json"
});

})();<commit_msg>Testing the device property. URL<commit_after>;(function(){
/**
 * Created with JetBrains PhpStorm.
 * User: Karl
 * Date: 2013-10-08
 * Time: 10:59 AM
 * To change this template use File | Settings | File Templates.
 */

App.MenuItems = Backbone.Model.extend({
    defaults: {
        "logo":  "",
        "icon":  ""
    }
});

App.getDynamicModelUrl = function(view) { // just swap which line is commented out to change location
//   return 'api/' + view; // this is for local
    return "http://theplayatimes.com/welcome/api/v1/listings/" + view + "/true.json"; // this is for running live
};

App.MenuCollection = Backbone.Collection.extend({
    model: App.MenuItems,
//    url: 'api/menu'
    url: 'http://theplayatimes.com/welcome/api/v1/listing_categories'
});

App.GenericModel = Backbone.Model.extend({
    defaults: {
        "logo":  ""
    }
});

App.GenericCollection = Backbone.Collection.extend({
    model: App.GenericModel,
    url: function(){
        return App.getDynamicModelUrl(window.location.hash.replace("#", ""));
    }
});

App.PicturesCollection = Backbone.Collection.extend({
   model: App.PictureModel
});

App.PictureModel = Backbone.Model.extend();

App.getModelUrl = function(view) { // just swap which line is commented out to change location
    return 'api/' + view; // this is for local
//    return "http://theplayatimes.com/welcome/api/v1/listings/" + view + '/true.json'; // this is for running live
};

//Restaurants ------------------------------------------------------
App.Restaurants = Backbone.Model.extend({
    defaults: {
        "logo":  "" // to make sure that it has a value.
    }
});

App.RestaurantsCollection = Backbone.Collection.extend({
    model: App.Restaurants,
    url: function() {
        data =  App.getModelUrl('restaurant');
        console.log(data);
        return data;
    }
//    url:"http://theplayatimes.com/welcome/api/v1/listings/restaurant/true.json"

});

//Accommodations ------------------------------------------------------
App.Accommodations = Backbone.Model.extend();

App.AccommodationsCollection = Backbone.Collection.extend({
    model: App.Accommodations,
    url: function() {
        return App.getModelUrl('accommodation');
    }
//    url:"http://theplayatimes.com/welcome/api/v1/listings/accommodation/true.json"
});

//Attractions ------------------------------------------------------
App.Attractions = Backbone.Model.extend();

App.AttractionsCollection = Backbone.Collection.extend({
    model: App.Attractions,
    url: function() {
        return App.getModelUrl('attraction');
    }
//    url:"http://theplayatimes.com/welcome/api/v1/listings/attraction/true.json"
});

})();<|endoftext|>


<commit_before>"use strict";

function DropdownMenu(parent)
{
	Element.call(this, parent);

	this.element.style.backgroundColor = Editor.theme.buttonColor;
	this.element.style.cursor = "pointer";

	this.preventDragEvents();

	//Text
	this.text = new Text(this.element);

	//Panel
	this.panel = document.createElement("div");
	this.panel.style.position = "absolute";
	this.panel.style.display = "none";
	this.panel.style.cursor = "default";
	this.panel.style.zIndex = "300";

	//Icon
	this.icon = document.createElement("img");
	this.icon.style.display = "none";
	this.icon.style.position = "absolute";
	this.icon.style.left = "5px";
	this.icon.style.top = "3px";
	this.icon.style.width = "12px";
	this.icon.style.height = "12px";
	this.element.appendChild(this.icon);

	//Arrow
	this.arrow = document.createElement("img");
	this.arrow.style.display = "none";
	this.arrow.style.position = "absolute";
	this.arrow.style.right = "5px";
	this.arrow.style.top = "3px";
	this.arrow.style.width = "12px";
	this.arrow.style.height = "12px";
	this.arrow.src = Editor.filePath + "icons/misc/arrow_right.png";
	this.element.appendChild(this.arrow);

	//Options
	this.optionsLocation = DropdownMenu.DOWN;
	this.optionsSize = new THREE.Vector2(150, 20);
	this.options = [];
	this.expanded = false;

	//Self pointer
	var self = this;

	//Mouse over
	this.element.onmouseenter = function()
	{
		self.setExpanded(true);
		self.element.style.backgroundColor = Editor.theme.buttonOverColor;
	};

	//Mouse leave
	this.element.onmouseleave = function()
	{
		self.setExpanded(false);
		self.element.style.backgroundColor = Editor.theme.buttonColor;
	};

	//Mouve over
	this.panel.onmouseenter = function()
	{
		self.setExpanded(true);
	};

	//Mouse leave
	this.panel.onmouseleave = function()
	{
		self.setExpanded(false);
	};

	//Add element to document
	this.parent.appendChild(this.panel);
}

//Dropdown position
DropdownMenu.DOWN = 0;
DropdownMenu.UP = 1;
DropdownMenu.LEFT = 2;
DropdownMenu.RIGHT = 3;

DropdownMenu.prototype = Object.create(Element.prototype);

//Set location to where options should open
DropdownMenu.prototype.setLocation = function(location)
{
	this.optionsLocation = location;
};

//Enable arrow
DropdownMenu.prototype.showArrow = function()
{
	this.arrow.style.display = "block";
};

//Set icon
DropdownMenu.prototype.setIcon = function(icon)
{
	this.icon.style.display = "block";
	this.icon.src = icon;
};

//Set Text
DropdownMenu.prototype.setText = function(text)
{
	this.text.setText(text);
};

//Destroy element
DropdownMenu.prototype.destroy = function()
{
	if(this.parent.contains(this.element))
	{
		this.parent.removeChild(this.element);
	}

	if(this.parent.contains(this.panel))
	{
		this.parent.removeChild(this.panel);
	}
};

//Remove option from dropdown menu
DropdownMenu.prototype.removeOption = function(index)
{
	if(index >= 0 && index < this.options.length)
	{
		this.options[index].destroy();
		this.options.splice(index, 1);
	}
};

//Add new option to dropdown menu
DropdownMenu.prototype.addOption = function(name, callback, icon)
{
	var button = new ButtonMenu(this.panel);
	button.element.style.zIndex = "200";
	button.text.setText(name);
	button.text.setAlignment(Text.LEFT);
	button.text.position.set(25, 0);

	var self = this;
	button.setCallback(function()
	{
		callback();
		self.setExpanded(false);
	});

	if(icon !== undefined)
	{
		button.setIcon(icon);
	}

	this.options.push(button);

	return button;
};

//Add new Option to dropdown menu
DropdownMenu.prototype.addMenu = function(name, icon)
{
	var menu = new DropdownMenu(this.panel);
	menu.setText(name);
	menu.setLocation(DropdownMenu.LEFT);
	menu.showArrow();
	menu.text.setAlignment(Text.LEFT);
	menu.text.position.set(25, 0);

	if(icon !== undefined)
	{
		menu.setIcon(icon);
	}

	this.options.push(menu);

	return menu;
};

//Update expanded state
DropdownMenu.prototype.setExpanded = function(expanded)
{
	this.expanded = expanded;

	if(this.expanded)
	{
		this.panel.style.display = "block";

		if(this.optionsLocation === DropdownMenu.DOWN)
		{
			this.panel.style.top = (this.position.y + this.size.y) + "px";
			this.panel.style.left = this.position.x + "px";

			var out = DOMUtils.checkBorder(this.panel);
			if(out.y !== 0)
			{
				this.panel.style.top = "";
				this.panel.style.bottom = (this.position.y + this.size.y) + "px";
			}
			if(out.x !== 0)
			{
				this.panel.style.left = (this.position.x - out.x) + "px";
			}
		}
		else if(this.optionsLocation === DropdownMenu.UP)
		{
			this.panel.style.bottom = (this.position.y + this.size.y) + "px";
			this.panel.style.left = this.position.x + "px";

			var out = DOMUtils.checkBorder(this.panel);
			if(out.y !== 0)
			{
				this.panel.style.bottom = "";
				this.panel.style.top = (this.position.y + this.size.y) + "px";
			}
			if(out.x !== 0)
			{
				this.panel.style.left = (this.position.x - out.x) + "px";
			}
		}
		else if(this.optionsLocation === DropdownMenu.LEFT)
		{
			this.panel.style.top = this.position.y + "px";
			this.panel.style.left = (this.position.x + this.size.x) + "px";

			var out = DOMUtils.checkBorder(this.panel);
			if(out.x !== 0)
			{
				this.panel.style.left = (this.position.x - this.size.x) + "px";
			}
			if(out.y !== 0)
			{
				this.panel.style.top = (this.position.y - out.y) + "px";
			}
		}
		else if(this.optionsLocation === DropdownMenu.RIGHT)
		{
			this.panel.style.top = this.position.y + "px";
			this.panel.style.left = (this.position.x - this.size.x) + "px";

			var out = DOMUtils.checkBorder(this.panel);
			if(out.x !== 0)
			{
				this.panel.style.left = (this.position.x + this.size.x) + "px";
			}
			if(out.y !== 0)
			{
				this.panel.style.top = (this.position.y - out.y) + "px";
			}
		}
	}
	else
	{
		this.panel.style.display = "none";
	}
};

//Update options
DropdownMenu.prototype.updateOptions = function()
{
	//Options
	for(var i = 0; i < this.options.length; i++)
	{
		this.options[i].size.set(this.optionsSize.x, this.optionsSize.y);
		this.options[i].position.set(0, this.optionsSize.y * i);
		this.options[i].updateInterface();
	}

	//Panel
	this.panel.style.width = this.size.x + "px";
	this.panel.style.height = (this.optionsSize.y * this.options.length) + "px";
};

//Update interface
DropdownMenu.prototype.updateInterface = function()
{
	if(this.visible)
	{
		this.element.style.visibility = "visible";

		this.updateOptions();

		//Text
		this.text.size.set(this.size.x, this.size.y);
		this.text.visible = this.visible;
		this.text.updateInterface();

		//Element
		this.element.style.top = this.position.y + "px";
		this.element.style.left = this.position.x + "px";
		this.element.style.width = this.size.x + "px";
		this.element.style.height = this.size.y + "px";
	}
	else
	{
		this.element.style.visibility = "hidden";
	}
};
<commit_msg>Clean up<commit_after>"use strict";

function DropdownMenu(parent)
{
	Element.call(this, parent);

	this.element.style.backgroundColor = Editor.theme.buttonColor;
	this.element.style.cursor = "pointer";

	this.preventDragEvents();

	//Text
	this.text = new Text(this.element);

	//Panel
	this.panel = document.createElement("div");
	this.panel.style.position = "absolute";
	this.panel.style.display = "none";
	this.panel.style.cursor = "default";
	this.panel.style.zIndex = "300";

	//Icon
	this.icon = document.createElement("img");
	this.icon.style.display = "none";
	this.icon.style.position = "absolute";
	this.icon.style.left = "5px";
	this.icon.style.top = "3px";
	this.icon.style.width = "12px";
	this.icon.style.height = "12px";
	this.element.appendChild(this.icon);

	//Arrow
	this.arrow = document.createElement("img");
	this.arrow.style.display = "none";
	this.arrow.style.position = "absolute";
	this.arrow.style.right = "5px";
	this.arrow.style.top = "3px";
	this.arrow.style.width = "12px";
	this.arrow.style.height = "12px";
	this.arrow.src = Editor.filePath + "icons/misc/arrow_right.png";
	this.element.appendChild(this.arrow);

	//Options
	this.optionsLocation = DropdownMenu.DOWN;
	this.optionsSize = new THREE.Vector2(150, 20);
	this.options = [];
	this.expanded = false;

	//Self pointer
	var self = this;

	//Mouse over
	this.element.onmouseenter = function()
	{
		self.setExpanded(true);
		self.element.style.backgroundColor = Editor.theme.buttonOverColor;
	};

	//Mouse leave
	this.element.onmouseleave = function()
	{
		self.setExpanded(false);
		self.element.style.backgroundColor = Editor.theme.buttonColor;
	};

	//Mouve over
	this.panel.onmouseenter = function()
	{
		self.setExpanded(true);
	};

	//Mouse leave
	this.panel.onmouseleave = function()
	{
		self.setExpanded(false);
	};

	//Add element to document
	this.parent.appendChild(this.panel);
}

//Dropdown position
DropdownMenu.DOWN = 0;
DropdownMenu.UP = 1;
DropdownMenu.LEFT = 2;
DropdownMenu.RIGHT = 3;

DropdownMenu.prototype = Object.create(Element.prototype);

//Set location to where options should open
DropdownMenu.prototype.setLocation = function(location)
{
	this.optionsLocation = location;
};

//Enable arrow
DropdownMenu.prototype.showArrow = function()
{
	this.arrow.style.display = "block";
};

//Set icon
DropdownMenu.prototype.setIcon = function(icon)
{
	this.icon.style.display = "block";
	this.icon.src = icon;
};

//Set Text
DropdownMenu.prototype.setText = function(text)
{
	this.text.setText(text);
};

//Destroy element
DropdownMenu.prototype.destroy = function()
{
	if(this.parent.contains(this.element))
	{
		this.parent.removeChild(this.element);
	}

	if(this.parent.contains(this.panel))
	{
		this.parent.removeChild(this.panel);
	}
};

//Remove option from dropdown menu
DropdownMenu.prototype.removeOption = function(index)
{
	if(index >= 0 && index < this.options.length)
	{
		this.options[index].destroy();
		this.options.splice(index, 1);
	}
};

//Add new option to dropdown menu
DropdownMenu.prototype.addOption = function(name, callback, icon)
{
	var button = new ButtonMenu(this.panel);
	button.element.style.zIndex = "200";
	button.text.setText(name);
	button.text.setAlignment(Text.LEFT);
	button.text.position.set(25, 0);

	var self = this;
	button.setCallback(function()
	{
		callback();
		self.setExpanded(false);
	});

	if(icon !== undefined)
	{
		button.setIcon(icon);
	}

	this.options.push(button);

	return button;
};

//Add new Option to dropdown menu
DropdownMenu.prototype.addMenu = function(name, icon)
{
	var menu = new DropdownMenu(this.panel);
	menu.setText(name);
	menu.setLocation(DropdownMenu.LEFT);
	menu.showArrow();
	menu.text.setAlignment(Text.LEFT);
	menu.text.position.set(25, 0);

	if(icon !== undefined)
	{
		menu.setIcon(icon);
	}

	this.options.push(menu);

	return menu;
};

//Update expanded state
DropdownMenu.prototype.setExpanded = function(expanded)
{
	this.expanded = expanded;

	if(this.expanded)
	{
		this.panel.style.display = "block";

		if(this.optionsLocation === DropdownMenu.DOWN)
		{
			this.panel.style.top = (this.position.y + this.size.y) + "px";
			this.panel.style.left = this.position.x + "px";

			var out = DOMUtils.checkBorder(this.panel);
			if(out.y !== 0)
			{
				this.panel.style.top = "";
				this.panel.style.bottom = (this.position.y + this.size.y) + "px";
			}
			if(out.x !== 0)
			{
				this.panel.style.left = (this.position.x - out.x) + "px";
			}
		}
		else if(this.optionsLocation === DropdownMenu.UP)
		{
			this.panel.style.bottom = (this.position.y + this.size.y) + "px";
			this.panel.style.left = this.position.x + "px";

			var out = DOMUtils.checkBorder(this.panel);
			if(out.y !== 0)
			{
				this.panel.style.bottom = "";
				this.panel.style.top = (this.position.y + this.size.y) + "px";
			}
			if(out.x !== 0)
			{
				this.panel.style.left = (this.position.x - out.x) + "px";
			}
		}
		else if(this.optionsLocation === DropdownMenu.LEFT)
		{
			this.panel.style.top = this.position.y + "px";
			this.panel.style.left = (this.position.x + this.size.x) + "px";

			var out = DOMUtils.checkBorder(this.panel);
			if(out.x !== 0)
			{
				this.panel.style.left = (this.position.x - this.size.x) + "px";
			}
			if(out.y !== 0)
			{
				this.panel.style.top = (this.position.y - out.y) + "px";
			}
		}
		else if(this.optionsLocation === DropdownMenu.RIGHT)
		{
			this.panel.style.top = this.position.y + "px";
			this.panel.style.left = (this.position.x - this.size.x) + "px";

			var out = DOMUtils.checkBorder(this.panel);
			if(out.x !== 0)
			{
				this.panel.style.left = (this.position.x + this.size.x) + "px";
			}
			if(out.y !== 0)
			{
				this.panel.style.top = (this.position.y - out.y) + "px";
			}
		}
	}
	else
	{
		this.panel.style.display = "none";
	}
};

//Update options
DropdownMenu.prototype.updateOptions = function()
{
	//Options
	for(var i = 0; i < this.options.length; i++)
	{
		this.options[i].size.set(this.optionsSize.x, this.optionsSize.y);
		this.options[i].position.set(0, this.optionsSize.y * i);
		this.options[i].updateInterface();
	}

	//Panel
	this.panel.style.width = this.size.x + "px";
	this.panel.style.height = (this.optionsSize.y * this.options.length) + "px";
};

//Update interface
DropdownMenu.prototype.updateInterface = function()
{
	if(this.visible)
	{
		this.element.style.visibility = "visible";

		this.updateOptions();

		//Text
		this.text.size.set(this.size.x, this.size.y);
		this.text.visible = this.visible;
		this.text.updateInterface();

		//Element
		this.element.style.top = this.position.y + "px";
		this.element.style.left = this.position.x + "px";
		this.element.style.width = this.size.x + "px";
		this.element.style.height = this.size.y + "px";
	}
	else
	{
		this.element.style.visibility = "hidden";
	}
};
<|endoftext|>


<commit_before>fs = require('fs');

fs.readFile('sampleNumbers.txt', 'utf8', function(err,data){
	if(err){
		return console.log(err);
	}
	content = data;
	processFile();
});
<commit_msg>adds a callback feature<commit_after>fs = require('fs'); // imports modules

var content;

fs.readFile('sampleNumbers.txt', 'utf8', function(err,data){
	if(err){
		return console.log(err);
	}
	content = data;
	processFile(); // gives it call back
});

function processFile(){
	console.log(content[0]);
}
<|endoftext|>


<commit_before>'use strict';

var registerSubmit   = require('mano-auth/controller/server-master/register')
  , sendNotification = require('../../server/email-notifications/create-account');

// Add user
exports['user-add'] = {
	submit: function (data) {
		return registerSubmit.apply(this, arguments)(function (result) {
			sendNotification(data).done();
			return result;
		});
	}
};
<commit_msg>Fix users admin controller<commit_after>'use strict';

var registerSubmit   = require('mano-auth/controller/server-master/register').submit
  , sendNotification = require('../../server/email-notifications/create-account');

// Add user
exports['user-add'] = {
	submit: function (data) {
		return registerSubmit.apply(this, arguments)(function (result) {
			sendNotification(data).done();
			return result;
		});
	}
};
<|endoftext|>