Search in sources :

Example 6 with ServerConnection

use of com.velocitypowered.api.proxy.ServerConnection in project ProxyQueues by JLyne.

the class ProxyDiscordHandler method onPlayerJoinQueue.

@Subscribe
public void onPlayerJoinQueue(PlayerQueueEvent event) {
    if (event.isCancelled()) {
        return;
    }
    if (verificationManager.isPublicServer(event.getServer())) {
        return;
    }
    VerificationResult result = verificationManager.checkVerificationStatus(event.getPlayer());
    if (result.isVerified()) {
        Optional<ServerConnection> currentServer = event.getPlayer().getCurrentServer();
        if (currentServer.isPresent() && verificationManager.isPublicServer(currentServer.get().getServer())) {
            if (plugin.getWaitingServer().isPresent()) {
                event.getPlayer().createConnectionRequest(plugin.getWaitingServer().get()).fireAndForget();
            }
        }
        return;
    }
    event.setCancelled(true);
    RegisteredServer linkingServer = verificationManager.getLinkingServer();
    RegisteredServer currentServer = event.getPlayer().getCurrentServer().map(ServerConnection::getServer).orElse(null);
    if (linkingServer != null && (currentServer == null || !currentServer.equals(linkingServer))) {
        event.getPlayer().createConnectionRequest(linkingServer).fireAndForget();
    }
    switch(result) {
        case NOT_LINKED:
            event.setReason(Messages.get("errors.discord-not-linked"));
            break;
        case LINKED_NOT_VERIFIED:
            event.setReason(Messages.get("errors.discord-not-verified"));
            break;
        default:
            event.setReason("An error has occurred.");
    }
}
Also used : VerificationResult(uk.co.notnull.proxydiscord.api.VerificationResult) RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) ServerConnection(com.velocitypowered.api.proxy.ServerConnection) Subscribe(com.velocitypowered.api.event.Subscribe)

Example 7 with ServerConnection

use of com.velocitypowered.api.proxy.ServerConnection in project CloudNet-v3 by CloudNetService.

the class CommandHub method execute.

@Override
public void execute(@MaybePresent CommandSource source, @NonNull @MaybePresent String[] args) {
    if (!(source instanceof Player)) {
        return;
    }
    Player player = (Player) source;
    if (VelocityCloudNetHelper.isOnAFallbackInstance(player)) {
        source.sendMessage(LegacyComponentSerializer.legacyLinking().deserialize(BridgeConfigurationProvider.load().getMessages().get("command-hub-already-in-hub").replace("&", "§")));
        return;
    }
    VelocityCloudNetHelper.connectToFallback(player, player.getCurrentServer().map(ServerConnection::getServerInfo).map(ServerInfo::getName).orElse(null)).thenAccept(connectedFallback -> {
        if (connectedFallback != null) {
            source.sendMessage(LegacyComponentSerializer.legacyLinking().deserialize(BridgeConfigurationProvider.load().getMessages().get("command-hub-success-connect").replace("%server%", connectedFallback.getName()).replace("&", "§")));
        } else {
            source.sendMessage(LegacyComponentSerializer.legacyLinking().deserialize(BridgeConfigurationProvider.load().getMessages().get("command-hub-no-server-found").replace("&", "§")));
        }
    });
}
Also used : Player(com.velocitypowered.api.proxy.Player) ServerConnection(com.velocitypowered.api.proxy.ServerConnection)

Example 8 with ServerConnection

use of com.velocitypowered.api.proxy.ServerConnection in project Chocolate by GiansCode.

the class PluginMessageListener method onPluginMessage.

@Subscribe
public void onPluginMessage(PluginMessageEvent event) {
    if (!event.getIdentifier().equals(LEGACY_CHANNEL) && !event.getIdentifier().equals(MODERN_CHANNEL))
        return;
    event.setResult(PluginMessageEvent.ForwardResult.handled());
    if (!(event.getSource() instanceof ServerConnection))
        return;
    ServerConnection connection = (ServerConnection) event.getSource();
    ByteArrayDataInput input = event.dataAsDataStream();
    ByteArrayDataOutput output = ByteStreams.newDataOutput();
    String subChannel = input.readUTF();
    switch(subChannel.toUpperCase()) {
        case "PLAYERLIST":
            {
                String server = input.readUTF();
                Set<UUID> players = plugin.getCacheManager().getOnlinePlayersInServer(server.toLowerCase());
                StringBuilder sb = new StringBuilder();
                for (UUID uuid : players) sb.append(uuid).append(", ");
                if (sb.length() != 0)
                    sb.setLength(sb.length() - 2);
                output.writeUTF("PlayerList");
                output.writeUTF(server);
                output.writeUTF(sb.toString());
                break;
            }
        case "PLAYERCOUNT":
            {
                String server = input.readUTF();
                int players;
                if (server.equalsIgnoreCase("ALL"))
                    players = plugin.getSyncManager().getOnlinePlayers();
                else
                    players = plugin.getCacheManager().getOnlinePlayersInServer(server.toLowerCase()).size();
                output.writeUTF("PlayerCount");
                output.writeUTF(server);
                output.writeInt(players);
                break;
            }
        case "LASTONLINE":
            {
                String name = input.readUTF();
                PlayerData data = plugin.getCacheManager().getPlayerData(name);
                output.writeUTF("LastOnline");
                output.writeUTF(name);
                output.writeLong(data.getLastOnline());
                break;
            }
        case "PROXY":
            {
                String uuidS = input.readUTF();
                output.writeUTF("Proxy");
                output.writeUTF(uuidS);
                UUID uuid = UUID.fromString(uuidS);
                if (plugin.getServer().getPlayer(uuid).isPresent())
                    output.writeUTF(plugin.getRedisManager().getProxyId());
                else
                    output.writeUTF(plugin.getCacheManager().getPlayerData(uuid).getProxy());
                break;
            }
        default:
            return;
    }
    connection.sendPluginMessage(event.getIdentifier(), output.toByteArray());
}
Also used : Set(java.util.Set) ByteArrayDataOutput(com.google.common.io.ByteArrayDataOutput) ServerConnection(com.velocitypowered.api.proxy.ServerConnection) ByteArrayDataInput(com.google.common.io.ByteArrayDataInput) UUID(java.util.UUID) PlayerData(io.alerium.chocolate.object.PlayerData) Subscribe(com.velocitypowered.api.event.Subscribe)

Example 9 with ServerConnection

use of com.velocitypowered.api.proxy.ServerConnection in project Advanced-Portals by sekwah41.

the class AdvancedPortalsPlugin method onPluginMessage.

@Subscribe
public void onPluginMessage(PluginMessageEvent event) {
    if (event.getIdentifier().equals(AP_CHANNEL)) {
        if (event.getSource() instanceof ServerConnection) {
            ByteArrayDataInput in = ByteStreams.newDataInput(event.getData());
            String subChannel = in.readUTF();
            if (subChannel.equalsIgnoreCase(BungeeMessages.ENTER_PORTAL)) {
                String targetServer = in.readUTF();
                String targetDestination = in.readUTF();
                String targetUUID = in.readUTF();
                PlayerDestiMap.put(targetUUID, new String[] { targetServer, targetDestination, targetUUID });
                proxy.getScheduler().buildTask(this, () -> PlayerDestiMap.remove(targetUUID)).delay(10, TimeUnit.SECONDS).schedule();
            } else if (subChannel.equalsIgnoreCase(BungeeMessages.BUNGEE_COMMAND)) {
                String command = in.readUTF();
                ServerConnection connection = (ServerConnection) event.getSource();
                if (connection.getPlayer() != null) {
                    proxy.getCommandManager().executeAsync(connection.getPlayer(), command);
                }
            }
        }
        // So that client packets don't make it through to the servers, always trigger on this channel.
        event.setResult(PluginMessageEvent.ForwardResult.handled());
    }
}
Also used : ServerConnection(com.velocitypowered.api.proxy.ServerConnection) ByteArrayDataInput(com.google.common.io.ByteArrayDataInput) Subscribe(com.velocitypowered.api.event.Subscribe)

Example 10 with ServerConnection

use of com.velocitypowered.api.proxy.ServerConnection in project InteractiveChat by LOOHP.

the class InteractiveChatVelocity method onReceive.

@Subscribe
public void onReceive(PluginMessageEvent event) {
    if (!event.getIdentifier().getId().equals("interchat:main")) {
        return;
    }
    ChannelMessageSource source = event.getSource();
    if (!(source instanceof ServerConnection)) {
        return;
    }
    event.setResult(ForwardResult.handled());
    RegisteredServer server = ((ServerConnection) source).getServer();
    String senderServer = server.getServerInfo().getName();
    byte[] packet = Arrays.copyOf(event.getData(), event.getData().length);
    ByteArrayDataInput in = ByteStreams.newDataInput(packet);
    int packetNumber = in.readInt();
    int packetId = in.readShort();
    if (!Registry.PROXY_PASSTHROUGH_RELAY_PACKETS.contains(packetId)) {
        boolean isEnding = in.readBoolean();
        byte[] data = new byte[packet.length - 7];
        in.readFully(data);
        byte[] chain = incomming.remove(packetNumber);
        if (chain != null) {
            ByteBuffer buff = ByteBuffer.allocate(chain.length + data.length);
            buff.put(chain);
            buff.put(data);
            data = buff.array();
        }
        if (!isEnding) {
            incomming.put(packetNumber, data);
            return;
        }
        byte[] finalData = data;
        pluginMessageHandlingExecutor.submit(() -> {
            try {
                ByteArrayDataInput input = ByteStreams.newDataInput(finalData);
                switch(packetId) {
                    case 0x07:
                        int cooldownType = input.readByte();
                        switch(cooldownType) {
                            case 0:
                                UUID uuid = DataTypeIO.readUUID(input);
                                long time = input.readLong();
                                playerCooldownManager.setPlayerUniversalLastTimestamp(uuid, time);
                                break;
                            case 1:
                                uuid = DataTypeIO.readUUID(input);
                                UUID internalId = DataTypeIO.readUUID(input);
                                time = input.readLong();
                                playerCooldownManager.setPlayerPlaceholderLastTimestamp(uuid, internalId, time);
                                break;
                        }
                        for (RegisteredServer eachServer : getServer().getAllServers()) {
                            if (!eachServer.getServerInfo().getName().equals(senderServer) && eachServer.getPlayersConnected().size() > 0) {
                                eachServer.sendPluginMessage(ICChannelIdentifier.INSTANCE, finalData);
                                pluginMessagesCounter.incrementAndGet();
                            }
                        }
                        break;
                    case 0x08:
                        UUID messageId = DataTypeIO.readUUID(input);
                        String component = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        messageForwardingHandler.receivedProcessedMessage(messageId, component);
                        break;
                    case 0x09:
                        loadConfig();
                        break;
                    case 0x0B:
                        int id = input.readInt();
                        boolean permissionValue = input.readBoolean();
                        permissionChecks.put(id, permissionValue);
                        break;
                    case 0x0C:
                        int size1 = input.readInt();
                        List<ICPlaceholder> list = new ArrayList<>(size1);
                        for (int i = 0; i < size1; i++) {
                            boolean isBuiltIn = input.readBoolean();
                            if (isBuiltIn) {
                                String keyword = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                                String name = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                                String description = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                                String permission = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                                long cooldown = input.readLong();
                                list.add(new BuiltInPlaceholder(Pattern.compile(keyword), name, description, permission, cooldown));
                            } else {
                                int customNo = input.readInt();
                                ParsePlayer parseplayer = ParsePlayer.fromOrder(input.readByte());
                                String placeholder = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                                boolean parseKeyword = input.readBoolean();
                                long cooldown = input.readLong();
                                boolean hoverEnabled = input.readBoolean();
                                String hoverText = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                                boolean clickEnabled = input.readBoolean();
                                String clickAction = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                                String clickValue = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                                boolean replaceEnabled = input.readBoolean();
                                String replaceText = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                                String name = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                                String description = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                                list.add(new CustomPlaceholder(customNo, parseplayer, Pattern.compile(placeholder), parseKeyword, cooldown, new CustomPlaceholderHoverEvent(hoverEnabled, hoverText), new CustomPlaceholderClickEvent(clickEnabled, clickEnabled ? ClickEventAction.valueOf(clickAction) : null, clickValue), new CustomPlaceholderReplaceText(replaceEnabled, replaceText), name, description));
                            }
                        }
                        placeholderList.put(server.getServerInfo().getName(), list);
                        playerCooldownManager.reloadPlaceholders(placeholderList.values().stream().flatMap(each -> each.stream()).distinct().collect(Collectors.toList()));
                        PluginMessageSendingVelocity.forwardPlaceholderList(list, server);
                        break;
                    case 0x0D:
                        UUID uuid2 = DataTypeIO.readUUID(input);
                        PluginMessageSendingVelocity.reloadPlayerData(uuid2, server);
                        break;
                    case 0x10:
                        UUID requestUUID = DataTypeIO.readUUID(input);
                        int requestType = input.readByte();
                        switch(requestType) {
                            case 0:
                                PluginMessageSendingVelocity.respondPlayerListRequest(requestUUID, server);
                                break;
                            default:
                                break;
                        }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    } else {
        pluginMessageHandlingExecutor.submit(() -> {
            for (RegisteredServer eachServer : getServer().getAllServers()) {
                if (!eachServer.getServerInfo().getName().equals(senderServer) && eachServer.getPlayersConnected().size() > 0) {
                    eachServer.sendPluginMessage(ICChannelIdentifier.INSTANCE, event.getData());
                    pluginMessagesCounter.incrementAndGet();
                }
            }
        });
    }
}
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) CustomPlaceholderHoverEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderHoverEvent) ArrayList(java.util.ArrayList) VelocityServerConnection(com.velocitypowered.proxy.connection.backend.VelocityServerConnection) ServerConnection(com.velocitypowered.api.proxy.ServerConnection) CustomPlaceholderClickEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderClickEvent) CustomPlaceholderReplaceText(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderReplaceText) IOException(java.io.IOException) ByteArrayDataInput(com.google.common.io.ByteArrayDataInput) ByteBuffer(java.nio.ByteBuffer) ChannelMessageSource(com.velocitypowered.api.proxy.messages.ChannelMessageSource) ParsePlayer(com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) BuiltInPlaceholder(com.loohp.interactivechat.objectholders.BuiltInPlaceholder) CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) UUID(java.util.UUID) Subscribe(com.velocitypowered.api.event.Subscribe)

Aggregations

ServerConnection (com.velocitypowered.api.proxy.ServerConnection)21 Subscribe (com.velocitypowered.api.event.Subscribe)12 Player (com.velocitypowered.api.proxy.Player)12 RegisteredServer (com.velocitypowered.api.proxy.server.RegisteredServer)8 ByteArrayDataInput (com.google.common.io.ByteArrayDataInput)6 UUID (java.util.UUID)6 Component (net.kyori.adventure.text.Component)5 File (java.io.File)4 InputStreamReader (java.io.InputStreamReader)4 TimeUnit (java.util.concurrent.TimeUnit)4 Inject (com.google.inject.Inject)3 CommandSource (com.velocitypowered.api.command.CommandSource)3 PostOrder (com.velocitypowered.api.event.PostOrder)3 DisconnectEvent (com.velocitypowered.api.event.connection.DisconnectEvent)3 ServerPostConnectEvent (com.velocitypowered.api.event.player.ServerPostConnectEvent)3 ProxyServer (com.velocitypowered.api.proxy.ProxyServer)3 IOException (java.io.IOException)3 TextComponent (net.kyori.adventure.text.TextComponent)3 HoverEvent (net.kyori.adventure.text.event.HoverEvent)3 ByteArrayDataOutput (com.google.common.io.ByteArrayDataOutput)2