Search in sources :

Example 6 with ConnectedPlayer

use of com.velocitypowered.proxy.connection.client.ConnectedPlayer in project InteractiveChat by LOOHP.

the class InteractiveChatVelocity method onProxyInitialization.

@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
    plugin = this;
    try {
        JSONObject json = (JSONObject) new JSONParser().parse(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("velocity-plugin.json"), StandardCharsets.UTF_8));
        description = new VelocityPluginDescription(json);
    } catch (IOException | ParseException e1) {
        e1.printStackTrace();
    }
    if (!getDataFolder().exists()) {
        getDataFolder().mkdir();
    }
    try {
        Config.loadConfig(CONFIG_ID, new File(getDataFolder(), "bungeeconfig.yml"), getClass().getClassLoader().getResourceAsStream("config_proxy.yml"), getClass().getClassLoader().getResourceAsStream("config_proxy.yml"), true);
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
    loadConfig();
    CommandsVelocity.createBrigadierCommand();
    proxyServer.getChannelRegistrar().register(ICChannelIdentifier.INSTANCE);
    getLogger().info(TextColor.GREEN + "[InteractiveChat] Registered Plugin Messaging Channels!");
    Metrics metrics = metricsFactory.make(this, BSTATS_PLUGIN_ID);
    Charts.setup(metrics);
    playerCooldownManager = new ProxyPlayerCooldownManager(placeholderList.values().stream().flatMap(each -> each.stream()).distinct().collect(Collectors.toList()));
    messageForwardingHandler = new ProxyMessageForwardingHandler((info, component) -> {
        Player player = proxyServer.getPlayer(info.getPlayer()).get();
        ServerConnection server = player.getCurrentServer().get();
        proxyServer.getScheduler().buildTask(plugin, () -> {
            try {
                if (player != null && server != null) {
                    PluginMessageSendingVelocity.requestMessageProcess(player, server.getServer(), component, info.getId());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).delay(delay + 50, TimeUnit.MILLISECONDS).schedule();
    }, (info, component) -> {
        Chat chatPacket = new Chat(component + "<QUxSRUFEWVBST0NFU1NFRA==>", info.getPosition(), null);
        Optional<Player> optplayer = getServer().getPlayer(info.getPlayer());
        if (optplayer.isPresent()) {
            ConnectedPlayer userConnection = (ConnectedPlayer) optplayer.get();
            userConnection.getConnection().getChannel().write(chatPacket);
        }
    }, uuid -> {
        return proxyServer.getPlayer(uuid).isPresent();
    }, uuid -> {
        Optional<ServerConnection> optCurrentServer = proxyServer.getPlayer(uuid).get().getCurrentServer();
        return optCurrentServer.isPresent() && hasInteractiveChat(optCurrentServer.get().getServer());
    }, () -> (long) delay + 2000);
    ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("InteractiveChatProxy Async PluginMessage Processing Thread #%d").build();
    pluginMessageHandlingExecutor = new ThreadPoolExecutor(8, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(true), factory);
    getLogger().info(TextColor.GREEN + "[InteractiveChat] InteractiveChat (Velocity) has been enabled!");
    run();
}
Also used : Arrays(java.util.Arrays) Inject(com.google.inject.Inject) ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer) Random(java.util.Random) ProxyShutdownEvent(com.velocitypowered.api.event.proxy.ProxyShutdownEvent) ParsePlayer(com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer) ByteBuffer(java.nio.ByteBuffer) Matcher(java.util.regex.Matcher) ChannelPromise(io.netty.channel.ChannelPromise) PluginMessageEvent(com.velocitypowered.api.event.connection.PluginMessageEvent) Player(com.velocitypowered.api.proxy.Player) Map(java.util.Map) ProxyInitializeEvent(com.velocitypowered.api.event.proxy.ProxyInitializeEvent) ThreadFactory(java.util.concurrent.ThreadFactory) ServerPostConnectEvent(com.velocitypowered.api.event.player.ServerPostConnectEvent) Method(java.lang.reflect.Method) Path(java.nio.file.Path) ChatResult(com.velocitypowered.api.event.player.PlayerChatEvent.ChatResult) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) TextComponent(net.kyori.adventure.text.TextComponent) ForwardResult(com.velocitypowered.api.event.connection.PluginMessageEvent.ForwardResult) Filter(org.apache.logging.log4j.core.Filter) JSONParser(org.json.simple.parser.JSONParser) SynchronousQueue(java.util.concurrent.SynchronousQueue) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) VelocityServerConnection(com.velocitypowered.proxy.connection.backend.VelocityServerConnection) ChannelPipeline(io.netty.channel.ChannelPipeline) UUID(java.util.UUID) RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) JSONObject(org.json.simple.JSONObject) ClickEventAction(com.loohp.interactivechat.objectholders.CustomPlaceholder.ClickEventAction) ByteStreams(com.google.common.io.ByteStreams) Subscribe(com.velocitypowered.api.event.Subscribe) Optional(java.util.Optional) ChannelMessageSource(com.velocitypowered.api.proxy.messages.ChannelMessageSource) Pattern(java.util.regex.Pattern) CustomPlaceholderClickEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderClickEvent) HoverEvent(net.kyori.adventure.text.event.HoverEvent) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) ProxyPlayerCooldownManager(com.loohp.interactivechat.proxy.objectholders.ProxyPlayerCooldownManager) DisconnectEvent(com.velocitypowered.api.event.connection.DisconnectEvent) ServerConnection(com.velocitypowered.api.proxy.ServerConnection) Metrics(com.loohp.interactivechat.proxy.velocity.metrics.Metrics) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) Connections(com.velocitypowered.proxy.network.Connections) Registry(com.loohp.interactivechat.registry.Registry) Charts(com.loohp.interactivechat.proxy.velocity.metrics.Charts) Config(com.loohp.interactivechat.config.Config) DataTypeIO(com.loohp.interactivechat.utils.DataTypeIO) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) BuiltInPlaceholder(com.loohp.interactivechat.objectholders.BuiltInPlaceholder) CustomPlaceholderReplaceText(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderReplaceText) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Chat(com.velocitypowered.proxy.protocol.packet.Chat) PlayerChatEvent(com.velocitypowered.api.event.player.PlayerChatEvent) ParseException(org.json.simple.parser.ParseException) PostOrder(com.velocitypowered.api.event.PostOrder) Component(net.kyori.adventure.text.Component) ProxyServer(com.velocitypowered.api.proxy.ProxyServer) ByteArrayDataInput(com.google.common.io.ByteArrayDataInput) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) PostLoginEvent(com.velocitypowered.api.event.connection.PostLoginEvent) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) BackendInteractiveChatData(com.loohp.interactivechat.proxy.objectholders.BackendInteractiveChatData) IOException(java.io.IOException) Field(java.lang.reflect.Field) InputStreamReader(java.io.InputStreamReader) File(java.io.File) DataDirectory(com.velocitypowered.api.plugin.annotation.DataDirectory) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) CustomPlaceholderHoverEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderHoverEvent) LogFilter(com.loohp.interactivechat.objectholders.LogFilter) CommandSource(com.velocitypowered.api.command.CommandSource) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) ProxyMessageForwardingHandler(com.loohp.interactivechat.proxy.objectholders.ProxyMessageForwardingHandler) NativeAdventureConverter(com.loohp.interactivechat.utils.NativeAdventureConverter) ThreadFactory(java.util.concurrent.ThreadFactory) ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer) ParsePlayer(com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer) Player(com.velocitypowered.api.proxy.Player) InputStreamReader(java.io.InputStreamReader) Optional(java.util.Optional) ProxyPlayerCooldownManager(com.loohp.interactivechat.proxy.objectholders.ProxyPlayerCooldownManager) VelocityServerConnection(com.velocitypowered.proxy.connection.backend.VelocityServerConnection) ServerConnection(com.velocitypowered.api.proxy.ServerConnection) IOException(java.io.IOException) ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer) Metrics(com.loohp.interactivechat.proxy.velocity.metrics.Metrics) JSONObject(org.json.simple.JSONObject) ProxyMessageForwardingHandler(com.loohp.interactivechat.proxy.objectholders.ProxyMessageForwardingHandler) SynchronousQueue(java.util.concurrent.SynchronousQueue) Chat(com.velocitypowered.proxy.protocol.packet.Chat) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) File(java.io.File) Subscribe(com.velocitypowered.api.event.Subscribe)

Example 7 with ConnectedPlayer

use of com.velocitypowered.proxy.connection.client.ConnectedPlayer in project InteractiveChat by LOOHP.

the class InteractiveChatVelocity method onPlayerConnected.

@Subscribe
public void onPlayerConnected(PostLoginEvent event) {
    if (!filtersAdded) {
        addFilters();
    }
    Player player = event.getPlayer();
    forwardedMessages.put(player.getUniqueId(), new ConcurrentHashMap<>());
    if (player.hasPermission("interactivechat.backendinfo")) {
        String proxyVersion = getDescription().getVersion();
        for (BackendInteractiveChatData data : serverInteractiveChatInfo.values()) {
            if (data.isOnline() && data.getProtocolVersion() != Registry.PLUGIN_MESSAGING_PROTOCOL_VERSION) {
                String msg = TextColor.RED + "[InteractiveChat] Warning: Backend Server " + data.getServer() + " is not running a version of InteractiveChat which has the same plugin messaging protocol version as the proxy!";
                HoverEvent<Component> hoverComponent = Component.text(TextColor.YELLOW + "Proxy Version: " + proxyVersion + " (" + Registry.PLUGIN_MESSAGING_PROTOCOL_VERSION + ")\n" + TextColor.RED + data.getServer() + " Version: " + data.getVersion() + " (" + data.getProtocolVersion() + ")").asHoverEvent();
                TextComponent text = Component.text(msg).hoverEvent(hoverComponent);
                sendMessage(player, text);
                sendMessage(getServer().getConsoleCommandSource(), text);
            }
        }
    }
    ConnectedPlayer userConnection = (ConnectedPlayer) player;
    ChannelPipeline pipeline = userConnection.getConnection().getChannel().pipeline();
    pipeline.addBefore(Connections.HANDLER, "interactivechat_interceptor", new ChannelDuplexHandler() {

        @Override
        public void write(ChannelHandlerContext channelHandlerContext, Object obj, ChannelPromise channelPromise) throws Exception {
            try {
                if (obj instanceof Chat) {
                    Chat packet = (Chat) obj;
                    String message = packet.getMessage();
                    byte position = packet.getType();
                    if ((position == 0 || position == 1) && message != null) {
                        if (message.contains("<QUxSRUFEWVBST0NFU1NFRA==>")) {
                            message = message.replace("<QUxSRUFEWVBST0NFU1NFRA==>", "");
                            if (Registry.ID_PATTERN.matcher(message).find()) {
                                message = Registry.ID_PATTERN.matcher(message).replaceAll("").trim();
                            }
                            packet.setMessage(message);
                        } else if (player.getCurrentServer().isPresent() && hasInteractiveChat(player.getCurrentServer().get().getServer())) {
                            messageForwardingHandler.processMessage(player.getUniqueId(), message, position);
                            return;
                        }
                    }
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
            super.write(channelHandlerContext, obj, channelPromise);
        }
    });
}
Also used : TextComponent(net.kyori.adventure.text.TextComponent) ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer) ParsePlayer(com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer) Player(com.velocitypowered.api.proxy.Player) BackendInteractiveChatData(com.loohp.interactivechat.proxy.objectholders.BackendInteractiveChatData) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer) ChannelPipeline(io.netty.channel.ChannelPipeline) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) Chat(com.velocitypowered.proxy.protocol.packet.Chat) JSONObject(org.json.simple.JSONObject) TextComponent(net.kyori.adventure.text.TextComponent) Component(net.kyori.adventure.text.Component) Subscribe(com.velocitypowered.api.event.Subscribe)

Example 8 with ConnectedPlayer

use of com.velocitypowered.proxy.connection.client.ConnectedPlayer in project LimboAPI by Elytrium.

the class LimboImpl method spawnPlayer.

@Override
public void spawnPlayer(Player apiPlayer, LimboSessionHandler handler) {
    ConnectedPlayer player = (ConnectedPlayer) apiPlayer;
    MinecraftConnection connection = player.getConnection();
    Class<? extends LimboSessionHandler> handlerClass = handler.getClass();
    if (this.limboName == null) {
        this.limboName = handlerClass.getSimpleName();
    }
    connection.eventLoop().execute(() -> {
        ChannelPipeline pipeline = connection.getChannel().pipeline();
        if (Settings.IMP.MAIN.LOGGING_ENABLED) {
            this.plugin.getLogger().info(player.getUsername() + " (" + player.getRemoteAddress() + ") has connected to the " + this.limboName + " Limbo");
        }
        if (!pipeline.names().contains("prepared-encoder")) {
            // and an error occurs that "minecraft-encoder" doesn't exist.
            if (!pipeline.names().contains(Connections.MINECRAFT_ENCODER)) {
                connection.close();
                return;
            }
            pipeline.addAfter(Connections.MINECRAFT_ENCODER, "prepared-encoder", new PreparedPacketEncoder(connection.getProtocolVersion()));
        }
        RegisteredServer previousServer = null;
        if (connection.getState() != LimboProtocol.getLimboRegistry()) {
            connection.setState(LimboProtocol.getLimboRegistry());
            VelocityServerConnection server = player.getConnectedServer();
            if (server != null) {
                server.disconnect();
                player.setConnectedServer(null);
                previousServer = server.getServer();
                this.plugin.setLimboJoined(player);
            }
        }
        if (this.plugin.isLimboJoined(player)) {
            if (connection.getType() == ConnectionTypes.LEGACY_FORGE) {
                connection.delayedWrite(this.safeRejoinPackets);
            } else {
                connection.delayedWrite(this.fastRejoinPackets);
            }
        } else {
            connection.delayedWrite(this.joinPackets);
        }
        connection.delayedWrite(this.postJoinPackets);
        connection.delayedWrite(this.getBrandMessage(handlerClass));
        this.plugin.setLimboJoined(player);
        LimboSessionHandlerImpl sessionHandler = new LimboSessionHandlerImpl(this.plugin, player, handler, connection.getSessionHandler(), previousServer, () -> this.limboName);
        connection.setSessionHandler(sessionHandler);
        connection.flush();
        if (connection.getProtocolVersion().compareTo(ProtocolVersion.MINECRAFT_1_18_2) >= 0) {
            this.plugin.getServer().getScheduler().buildTask(this.plugin, () -> connection.eventLoop().execute(() -> this.proceed(player, sessionHandler))).delay(Settings.IMP.MAIN.RECEIVER_LEVEL_1_18_2_FIXER_DELAY, TimeUnit.MILLISECONDS).schedule();
        } else {
            this.proceed(player, sessionHandler);
        }
    });
}
Also used : PreparedPacketEncoder(net.elytrium.limboapi.injection.packet.PreparedPacketEncoder) RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) VelocityServerConnection(com.velocitypowered.proxy.connection.backend.VelocityServerConnection) MinecraftConnection(com.velocitypowered.proxy.connection.MinecraftConnection) ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 9 with ConnectedPlayer

use of com.velocitypowered.proxy.connection.client.ConnectedPlayer in project LimboFilter by Elytrium.

the class LimboFilterCommand method execute.

@Override
public void execute(SimpleCommand.Invocation invocation) {
    CommandSource source = invocation.source();
    String[] args = invocation.arguments();
    if (args.length == 1) {
        switch(args[0].toLowerCase(Locale.ROOT)) {
            case "reload":
                {
                    if (source.hasPermission("limbofilter.reload")) {
                        try {
                            this.plugin.reload();
                            source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.RELOAD));
                        } catch (Exception e) {
                            source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.RELOAD_FAILED));
                            e.printStackTrace();
                        }
                    } else {
                        this.showHelp(source);
                    }
                    return;
                }
            case "stats":
                {
                    if (source instanceof Player) {
                        if (source.hasPermission("limbofilter.stats")) {
                            ConnectedPlayer player = (ConnectedPlayer) source;
                            if (!this.playersWithStats.contains(player.getUniqueId())) {
                                source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.STATS_ENABLED));
                                this.playersWithStats.add(player.getUniqueId());
                            } else {
                                source.sendMessage(LegacyComponentSerializer.legacyAmpersand().deserialize(Settings.IMP.MAIN.STRINGS.STATS_DISABLED));
                                this.playersWithStats.remove(player.getUniqueId());
                            }
                        } else {
                            this.showHelp(source);
                        }
                    } else {
                        source.sendMessage(this.createStatsComponent(0));
                    }
                    return;
                }
            default:
                {
                    this.showHelp(source);
                }
        }
    }
    this.showHelp(source);
}
Also used : ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer) Player(com.velocitypowered.api.proxy.Player) CommandSource(com.velocitypowered.api.command.CommandSource) ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer)

Aggregations

ConnectedPlayer (com.velocitypowered.proxy.connection.client.ConnectedPlayer)9 Subscribe (com.velocitypowered.api.event.Subscribe)4 Player (com.velocitypowered.api.proxy.Player)4 MinecraftConnection (com.velocitypowered.proxy.connection.MinecraftConnection)4 VelocityServerConnection (com.velocitypowered.proxy.connection.backend.VelocityServerConnection)4 ChannelPipeline (io.netty.channel.ChannelPipeline)4 UUID (java.util.UUID)4 ParsePlayer (com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer)3 RegisteredServer (com.velocitypowered.api.proxy.server.RegisteredServer)3 Chat (com.velocitypowered.proxy.protocol.packet.Chat)3 ChannelDuplexHandler (io.netty.channel.ChannelDuplexHandler)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 ChannelPromise (io.netty.channel.ChannelPromise)3 IOException (java.io.IOException)3 JSONObject (org.json.simple.JSONObject)3 ParseException (org.json.simple.parser.ParseException)3 ICPlaceholder (com.loohp.interactivechat.objectholders.ICPlaceholder)2 BackendInteractiveChatData (com.loohp.interactivechat.proxy.objectholders.BackendInteractiveChatData)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2