com.demigodsrpg.chitchat.bungee.BungeeChitchat.java Source code

Java tutorial

Introduction

Here is the source code for com.demigodsrpg.chitchat.bungee.BungeeChitchat.java

Source

/*
 * This file is part of BungeeChitchat, licensed under the MIT License (MIT).
 *
 * Copyright (c) DemigodsRPG.com <http://www.demigodsrpg.com>
 * Copyright (c) contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.demigodsrpg.chitchat.bungee;

import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PluginMessageEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class BungeeChitchat extends Plugin implements Listener {
    // -- IMPORTANT INFO -- //
    public static final Multimap<String, String> CHAT_CHANNELS;
    public static final Multimap<String, String> MUTED_PLAYERS;

    static {
        Supplier<Set<String>> setSupplier = new Supplier<Set<String>>() {
            @Override
            public Set<String> get() {
                return new HashSet<>();
            }
        };
        CHAT_CHANNELS = Multimaps.newSetMultimap(new HashMap<String, Collection<String>>(), setSupplier);
        MUTED_PLAYERS = Multimaps.newSetMultimap(new HashMap<String, Collection<String>>(), setSupplier);
    }

    // -- BUNGEE ENABLE METHOD -- //

    @Override
    public void onEnable() {
        getProxy().getPluginManager().registerListener(this, this);
    }

    // -- MESSAGE LISTENER -- //

    @EventHandler(priority = EventPriority.HIGHEST)
    public void onMessage(final PluginMessageEvent event) {
        if (event.getTag().equals("BungeeCord")) {
            // Get origin server
            ServerInfo origin = Iterables.find(getProxy().getServers().values(), new Predicate<ServerInfo>() {
                @Override
                public boolean apply(ServerInfo serverInfo) {
                    return serverInfo.getAddress().equals(event.getSender().getAddress());
                }
            }, null);

            // If origin doesn't exist (impossible?) throw an exception
            if (origin == null) {
                throw new NullPointerException("Origin server for a chat message was null.");
            }

            // Get the data
            ByteArrayDataInput in = ByteStreams.newDataInput(event.getData());

            // Needed for it to work because whynot
            String messageType = in.readUTF();
            String targetServer = in.readUTF();

            // Ignore messages that aren't the correct type
            if (!"Forward".equals(messageType)) {
                return;
            }

            // Get the chat channel and speaking player
            String chatChannelRaw = in.readUTF();

            // Don't continue if this message isn't from chitchat
            if (!chatChannelRaw.startsWith("chitchat")) {
                return;
            }

            // Grab the speaking player and clean up the chat channel name
            String speakingPlayerName = chatChannelRaw.split("\\$")[1];
            String chatChannel = chatChannelRaw.split("\\$")[2];

            // Is this a mute update?
            if (chatChannelRaw.startsWith("chatchatmute$")) {
                MUTED_PLAYERS.put(chatChannel, speakingPlayerName.toLowerCase());
                return;
            }

            // Is this an unmute update?
            if (chatChannelRaw.startsWith("chatchatunmute$")) {
                MUTED_PLAYERS.remove(chatChannel, speakingPlayerName.toLowerCase());
                return;
            }

            // Ignore muted players
            if (MUTED_PLAYERS.containsEntry(chatChannel, speakingPlayerName.toLowerCase())) {
                return;
            }

            // Is this a valid chat channel?
            if (!CHAT_CHANNELS.containsEntry(chatChannel, origin.getName())) {
                CHAT_CHANNELS.put(chatChannel, origin.getName());
            }

            // Process the data
            short len = in.readShort();
            byte[] msgbytes = new byte[len];
            in.readFully(msgbytes);

            DataInputStream msgin = new DataInputStream(new ByteArrayInputStream(msgbytes));

            try {
                // Finally get the message
                String message = msgin.readUTF();

                // Send the message to appropriate servers
                for (ServerInfo server : getProxy().getServers().values()) {
                    // Continue from invalid targets
                    if (origin.getName().equals(server.getName())
                            || !CHAT_CHANNELS.containsEntry(chatChannel, server.getName())) {
                        continue;
                    }

                    // Send the message to the appropriate players
                    for (ProxiedPlayer player : server.getPlayers()) {
                        player.sendMessage(message);
                    }
                }
            } catch (IOException oops) {
                oops.printStackTrace();
            }
        }
    }
}