Search in sources :

Example 6 with ICPlaceholder

use of com.loohp.interactivechat.objectholders.ICPlaceholder 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)

Example 7 with ICPlaceholder

use of com.loohp.interactivechat.objectholders.ICPlaceholder in project InteractiveChat by LOOHP.

the class InteractiveChatVelocity method onServerConnected.

@Subscribe
public void onServerConnected(ServerPostConnectEvent event) {
    Player player = event.getPlayer();
    RegisteredServer to = player.getCurrentServer().get().getServer();
    UUID uuid = player.getUniqueId();
    if (!placeholderList.containsKey(to.getServerInfo().getName())) {
        try {
            PluginMessageSendingVelocity.requestPlaceholderList(to);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        PluginMessageSendingVelocity.sendPlayerListData();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    long universalTime = playerCooldownManager.getPlayerUniversalLastTimestamp(uuid);
    if (universalTime >= 0) {
        try {
            PluginMessageSendingVelocity.sendPlayerUniversalCooldown(to, uuid, universalTime);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    List<ICPlaceholder> placeholders = placeholderList.get(to.getServerInfo().getName());
    if (placeholders != null) {
        for (ICPlaceholder placeholder : placeholders) {
            long placeholderTime = playerCooldownManager.getPlayerPlaceholderLastTimestamp(uuid, placeholder.getInternalId());
            if (placeholderTime >= 0) {
                try {
                    PluginMessageSendingVelocity.sendPlayerPlaceholderCooldown(to, uuid, placeholder, placeholderTime);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    proxyServer.getScheduler().buildTask(plugin, () -> {
        try {
            PluginMessageSendingVelocity.sendDelayAndScheme();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }).schedule();
    proxyServer.getScheduler().buildTask(plugin, () -> {
        if (event.getPlayer().getUsername().equals("LOOHP") || event.getPlayer().getUsername().equals("AppLEskakE")) {
            sendMessage(event.getPlayer(), Component.text(TextColor.GOLD + "InteractiveChat (Velocity) " + getDescription().getVersion() + " is running!"));
        }
    }).delay(100, TimeUnit.MILLISECONDS).schedule();
    VelocityServerConnection serverConnection = ((ConnectedPlayer) event.getPlayer()).getConnectedServer();
    ChannelPipeline pipeline = serverConnection.ensureConnected().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;
                    UUID uuid = player.getUniqueId();
                    String message = packet.getMessage();
                    byte position = packet.getType();
                    if ((position == 0 || position == 1) && uuid != null && message != null) {
                        Map<String, Long> list = forwardedMessages.get(uuid);
                        if (list != null) {
                            list.put(message, System.currentTimeMillis());
                        }
                    }
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
            super.write(channelHandlerContext, obj, channelPromise);
        }
    });
}
Also used : ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer) ParsePlayer(com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer) Player(com.velocitypowered.api.proxy.Player) VelocityServerConnection(com.velocitypowered.proxy.connection.backend.VelocityServerConnection) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) IOException(java.io.IOException) ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer) ChannelPipeline(io.netty.channel.ChannelPipeline) ParseException(org.json.simple.parser.ParseException) IOException(java.io.IOException) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) Chat(com.velocitypowered.proxy.protocol.packet.Chat) JSONObject(org.json.simple.JSONObject) UUID(java.util.UUID) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Subscribe(com.velocitypowered.api.event.Subscribe)

Example 8 with ICPlaceholder

use of com.loohp.interactivechat.objectholders.ICPlaceholder in project InteractiveChat by LOOHP.

the class ChatEvents method checkCommand.

private void checkCommand(PlayerCommandPreprocessEvent event) {
    if (!InteractiveChat.bungeecordMode) {
        event.setMessage(Registry.ID_PATTERN.matcher(event.getMessage()).replaceAll(""));
    }
    boolean flag = true;
    String command = event.getMessage();
    for (String parsecommand : InteractiveChat.commandList) {
        if (command.matches(parsecommand)) {
            if (flag) {
                translateAltColorCode(event);
                command = event.getMessage();
                flag = false;
            }
            CooldownResult cooldownResult = InteractiveChat.placeholderCooldownManager.checkMessage(event.getPlayer().getUniqueId(), command);
            if (!cooldownResult.getOutcome().isAllowed()) {
                event.setCancelled(true);
                Component cancelmessage;
                switch(cooldownResult.getOutcome()) {
                    case DENY_PLACEHOLDER:
                        cancelmessage = LegacyComponentSerializer.legacySection().deserialize(ChatColorUtils.translateAlternateColorCodes('&', PlaceholderAPI.setPlaceholders(event.getPlayer(), InteractiveChat.placeholderCooldownMessage.replace("{Time}", TimeUtils.getReadableTimeBetween(System.currentTimeMillis(), cooldownResult.getCooldownExpireTime())))));
                        cancelmessage = ComponentReplacing.replace(cancelmessage, "\\{Keyword\\}", Component.text(cooldownResult.getPlaceholder().getName()).hoverEvent(HoverEvent.showText(LegacyComponentSerializer.legacySection().deserialize(cooldownResult.getPlaceholder().getDescription()))));
                        break;
                    case DENY_UNIVERSAL:
                        cancelmessage = LegacyComponentSerializer.legacySection().deserialize(ChatColorUtils.translateAlternateColorCodes('&', PlaceholderAPI.setPlaceholders(event.getPlayer(), InteractiveChat.universalCooldownMessage.replace("{Time}", TimeUtils.getReadableTimeBetween(System.currentTimeMillis(), cooldownResult.getCooldownExpireTime())))));
                        break;
                    default:
                        cancelmessage = Component.empty();
                        break;
                }
                InteractiveChatAPI.sendMessageUnprocessed(event.getPlayer(), cancelmessage);
                return;
            }
            int count = 0;
            for (ICPlaceholder icplaceholder : InteractiveChat.placeholderList.values()) {
                Matcher matcher = icplaceholder.getKeyword().matcher(command);
                if (matcher.find()) {
                    int start = matcher.start();
                    if ((start < 1 || command.charAt(start - 1) != '\\') || (start > 1 && command.charAt(start - 1) == '\\' && command.charAt(start - 2) == '\\')) {
                        if (icplaceholder.getKeyword().equals(InteractiveChat.itemPlaceholder) && !InteractiveChat.itemAirAllow && PlayerUtils.getHeldItem(event.getPlayer()).getType().equals(Material.AIR) && PlayerUtils.hasPermission(event.getPlayer().getUniqueId(), "interactivechat.module.item", false, 200)) {
                            event.setCancelled(true);
                            String cancelmessage = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderAPI.setPlaceholders(event.getPlayer(), InteractiveChat.itemAirErrorMessage));
                            event.getPlayer().sendMessage(cancelmessage);
                            return;
                        }
                        Matcher matcher1 = icplaceholder.getKeyword().matcher(command);
                        while (matcher1.find()) {
                            int startPos = matcher1.start();
                            if ((startPos < 1 || command.charAt(startPos - 1) != '\\') || (startPos > 1 && command.charAt(startPos - 1) == '\\' && command.charAt(startPos - 2) == '\\')) {
                                count++;
                            }
                        }
                    }
                }
            }
            if (InteractiveChat.maxPlaceholders >= 0 && count > InteractiveChat.maxPlaceholders) {
                event.setCancelled(true);
                String cancelmessage = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderAPI.setPlaceholders(event.getPlayer(), InteractiveChat.limitReachMessage));
                event.getPlayer().sendMessage(cancelmessage);
                return;
            } else if (count <= 0) {
                return;
            }
            if (InteractiveChat.tagEveryIdentifiableMessage) {
                String uuidmatch = " <cmd=" + event.getPlayer().getUniqueId() + ">";
                event.setMessage(command + uuidmatch);
                break;
            } else {
                if (!Registry.ID_PATTERN.matcher(command).find()) {
                    for (ICPlaceholder icplaceholder : InteractiveChat.placeholderList.values()) {
                        Pattern placeholder = icplaceholder.getKeyword();
                        Matcher matcher = placeholder.matcher(command);
                        if (matcher.find()) {
                            int start = matcher.start();
                            if ((start < 1 || command.charAt(start - 1) != '\\') || (start > 1 && command.charAt(start - 1) == '\\' && command.charAt(start - 2) == '\\')) {
                                String uuidmatch = "<cmd=" + event.getPlayer().getUniqueId() + ":" + Registry.ID_ESCAPE_PATTERN.matcher(command.substring(matcher.start(), matcher.end())).replaceAll("\\>") + ":>";
                                command = command.substring(0, matcher.start()) + uuidmatch + command.substring(matcher.end());
                                event.setMessage(command);
                                break;
                            }
                        }
                    }
                    break;
                }
            }
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) Matcher(java.util.regex.Matcher) Component(net.kyori.adventure.text.Component) CooldownResult(com.loohp.interactivechat.objectholders.CooldownResult)

Example 9 with ICPlaceholder

use of com.loohp.interactivechat.objectholders.ICPlaceholder in project InteractiveChat by LOOHP.

the class InteractiveChatBungee method onSwitch.

@EventHandler
public void onSwitch(ServerSwitchEvent event) {
    ServerInfo to = event.getPlayer().getServer().getInfo();
    ProxiedPlayer player = event.getPlayer();
    UUID uuid = player.getUniqueId();
    if (!placeholderList.containsKey(to.getName())) {
        try {
            PluginMessageSendingBungee.requestPlaceholderList(to);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        PluginMessageSendingBungee.sendPlayerListData();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    long universalTime = playerCooldownManager.getPlayerUniversalLastTimestamp(uuid);
    if (universalTime >= 0) {
        try {
            PluginMessageSendingBungee.sendPlayerUniversalCooldown(to, uuid, universalTime);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    List<ICPlaceholder> placeholders = placeholderList.get(to.getName());
    if (placeholders != null) {
        for (ICPlaceholder placeholder : placeholders) {
            long placeholderTime = playerCooldownManager.getPlayerPlaceholderLastTimestamp(uuid, placeholder.getInternalId());
            if (placeholderTime >= 0) {
                try {
                    PluginMessageSendingBungee.sendPlayerPlaceholderCooldown(to, uuid, placeholder, placeholderTime);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    ProxyServer.getInstance().getScheduler().runAsync(plugin, () -> {
        try {
            PluginMessageSendingBungee.sendDelayAndScheme();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
    ProxyServer.getInstance().getScheduler().schedule(plugin, () -> {
        if (event.getPlayer().getName().equals("LOOHP") || event.getPlayer().getName().equals("AppLEskakE")) {
            sendMessage(event.getPlayer(), LegacyComponentSerializer.legacySection().deserialize(ChatColor.GOLD + "InteractiveChat (Bungeecord) " + plugin.getDescription().getVersion() + " is running!"));
        }
    }, 100, TimeUnit.MILLISECONDS);
}
Also used : ProxiedPlayer(net.md_5.bungee.api.connection.ProxiedPlayer) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) ServerInfo(net.md_5.bungee.api.config.ServerInfo) IOException(java.io.IOException) UUID(java.util.UUID) EventHandler(net.md_5.bungee.event.EventHandler)

Example 10 with ICPlaceholder

use of com.loohp.interactivechat.objectholders.ICPlaceholder in project InteractiveChat by LOOHP.

the class ProcessExternalMessage method processWithoutReceiver0.

@SuppressWarnings("deprecation")
public String processWithoutReceiver0(String message) {
    UUID senderUUID = ProcessAccurateSender.find(message);
    ICPlayer sender;
    if (senderUUID == null) {
        sender = null;
    } else {
        sender = ICPlayerFactory.getICPlayer(senderUUID);
    }
    message = message.replaceAll(ProcessCommands.COLOR_IGNORE_PATTERN_0.pattern(), "").replaceAll(ProcessCommands.COLOR_IGNORE_PATTERN_1.pattern(), "").replaceAll(ProcessAccurateSender.COLOR_IGNORE_PATTERN.pattern(), "");
    message = message.replaceAll(ProcessAccurateSender.PATTERN_0.pattern(), "$2");
    Matcher matcher = ProcessAccurateSender.PATTERN_0.matcher(message);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String replacement = Registry.ID_UNESCAPE_PATTERN.matcher(matcher.group(2)).replaceAll(">");
        matcher.appendReplacement(sb, replacement);
    }
    matcher.appendTail(sb);
    message = sb.toString();
    message = Registry.MENTION_TAG_CONVERTER.revertTags(message);
    if (sender == null) {
        return message;
    }
    long now = System.currentTimeMillis();
    long uniCooldown = InteractiveChatAPI.getPlayerUniversalCooldown(sender.getUniqueId()) - now;
    if (!(uniCooldown < 0 || uniCooldown + 100 > InteractiveChat.universalCooldown)) {
        return message;
    }
    if (InteractiveChat.rgbTags) {
        message = CustomStringUtils.clearPluginRGBTags(message);
    }
    if (InteractiveChat.fontTags) {
        message = CustomStringUtils.clearPluginFontTags(message);
    }
    Component component = LegacyComponentSerializer.legacySection().deserialize(message);
    for (ICPlaceholder placeholder : InteractiveChatAPI.getICPlaceholderList()) {
        if (!placeholder.isBuildIn()) {
            CustomPlaceholder customP = (CustomPlaceholder) placeholder;
            if (!InteractiveChat.useCustomPlaceholderPermissions || (InteractiveChat.useCustomPlaceholderPermissions && PlayerUtils.hasPermission(sender.getUniqueId(), customP.getPermission(), true, 250))) {
                if (customP.getKeyword().matcher(message).find()) {
                    if (customP.getReplace().isEnabled()) {
                        String replace = ChatColor.WHITE + ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(sender, customP.getReplace().getReplaceText()));
                        component = ComponentReplacing.replace(component, customP.getKeyword().pattern(), true, result -> {
                            String replaceString = CustomStringUtils.applyReplacementRegex(replace, result, 1);
                            return LegacyComponentSerializer.legacySection().deserialize(replaceString);
                        });
                    }
                }
            }
        }
    }
    if (InteractiveChat.t && WebData.getInstance() != null) {
        for (CustomPlaceholder customP : WebData.getInstance().getSpecialPlaceholders()) {
            if (customP.getKeyword().matcher(message).find()) {
                if (customP.getReplace().isEnabled()) {
                    String replace = ChatColor.WHITE + ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(sender, customP.getReplace().getReplaceText()));
                    component = ComponentReplacing.replace(component, customP.getKeyword().pattern(), true, result -> {
                        String replaceString = CustomStringUtils.applyReplacementRegex(replace, result, 1);
                        return LegacyComponentSerializer.legacySection().deserialize(replaceString);
                    });
                }
            }
        }
    }
    if (InteractiveChat.useItem && PlayerUtils.hasPermission(sender.getUniqueId(), "interactivechat.module.item", true, 250)) {
        Pattern placeholder = InteractiveChat.itemPlaceholder;
        if (placeholder.matcher(message).find()) {
            ItemStack item = sender.getEquipment().getItemInHand();
            if (item == null) {
                item = new ItemStack(Material.AIR);
            }
            String itemStr = InteractiveChatComponentSerializer.bungeecordApiLegacy().serialize(ItemStackUtils.getDisplayName(item), InteractiveChat.language);
            int amount = item.getAmount();
            if (item == null || item.getType().equals(Material.AIR)) {
                amount = 1;
            }
            itemStr = RarityUtils.getRarityColor(item) + itemStr;
            String replaceText;
            if (amount == 1) {
                replaceText = PlaceholderParser.parse(sender, InteractiveChat.itemSingularReplaceText.replace("{Item}", itemStr));
            } else {
                replaceText = PlaceholderParser.parse(sender, InteractiveChat.itemReplaceText.replace("{Amount}", String.valueOf(amount)).replace("{Item}", itemStr));
            }
            component = ComponentReplacing.replace(component, placeholder.pattern(), true, LegacyComponentSerializer.legacySection().deserialize(replaceText));
        }
    }
    if (InteractiveChat.useInventory && PlayerUtils.hasPermission(sender.getUniqueId(), "interactivechat.module.inventory", true, 250)) {
        Pattern placeholder = InteractiveChat.invPlaceholder;
        if (placeholder.matcher(message).find()) {
            String replaceText = PlaceholderParser.parse(sender, InteractiveChat.invReplaceText);
            component = ComponentReplacing.replace(component, placeholder.pattern(), true, LegacyComponentSerializer.legacySection().deserialize(replaceText));
        }
    }
    if (InteractiveChat.useEnder && PlayerUtils.hasPermission(sender.getUniqueId(), "interactivechat.module.enderchest", true, 250)) {
        Pattern placeholder = InteractiveChat.enderPlaceholder;
        if (placeholder.matcher(message).find()) {
            String replaceText = PlaceholderParser.parse(sender, InteractiveChat.enderReplaceText);
            component = ComponentReplacing.replace(component, placeholder.pattern(), true, LegacyComponentSerializer.legacySection().deserialize(replaceText));
        }
    }
    return LegacyComponentSerializer.builder().character(ChatColorUtils.COLOR_CHAR).hexColors().useUnusualXRepeatedCharacterHexFormat().build().serialize(component);
}
Also used : Plugin(org.bukkit.plugin.Plugin) ComponentReplacing(com.loohp.interactivechat.utils.ComponentReplacing) MCVersion(com.loohp.interactivechat.utils.MCVersion) PlayerUtils(com.loohp.interactivechat.utils.PlayerUtils) CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) InteractiveChatAPI(com.loohp.interactivechat.api.InteractiveChatAPI) PlayerData(com.loohp.interactivechat.data.PlayerDataManager.PlayerData) WebData(com.loohp.interactivechat.objectholders.WebData) Registry(com.loohp.interactivechat.registry.Registry) JsonUtils(com.loohp.interactivechat.utils.JsonUtils) Player(org.bukkit.entity.Player) ComponentModernizing(com.loohp.interactivechat.utils.ComponentModernizing) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) ComponentFont(com.loohp.interactivechat.utils.ComponentFont) InteractiveChatComponentSerializer(com.loohp.interactivechat.utils.InteractiveChatComponentSerializer) Matcher(java.util.regex.Matcher) Component(net.kyori.adventure.text.Component) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) LegacyComponentSerializer(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) Method(java.lang.reflect.Method) ItemStackUtils(com.loohp.interactivechat.utils.ItemStackUtils) Material(org.bukkit.Material) ChatColor(net.md_5.bungee.api.ChatColor) Bukkit(org.bukkit.Bukkit) Collection(java.util.Collection) RarityUtils(com.loohp.interactivechat.utils.RarityUtils) UUID(java.util.UUID) Field(java.lang.reflect.Field) ItemStack(org.bukkit.inventory.ItemStack) InteractiveChat(com.loohp.interactivechat.InteractiveChat) TimeUnit(java.util.concurrent.TimeUnit) ICPlayerFactory(com.loohp.interactivechat.objectholders.ICPlayerFactory) ChatColorUtils(com.loohp.interactivechat.utils.ChatColorUtils) CustomStringUtils(com.loohp.interactivechat.utils.CustomStringUtils) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) PlaceholderParser(com.loohp.interactivechat.utils.PlaceholderParser) ProcessSenderResult(com.loohp.interactivechat.objectholders.ProcessSenderResult) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) UUID(java.util.UUID) Component(net.kyori.adventure.text.Component) ItemStack(org.bukkit.inventory.ItemStack)

Aggregations

ICPlaceholder (com.loohp.interactivechat.objectholders.ICPlaceholder)26 UUID (java.util.UUID)15 Pattern (java.util.regex.Pattern)13 IOException (java.io.IOException)12 Matcher (java.util.regex.Matcher)12 CustomPlaceholder (com.loohp.interactivechat.objectholders.CustomPlaceholder)11 ArrayList (java.util.ArrayList)11 List (java.util.List)10 ICPlayer (com.loohp.interactivechat.objectholders.ICPlayer)9 ParsePlayer (com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer)8 Component (net.kyori.adventure.text.Component)8 Player (org.bukkit.entity.Player)8 InteractiveChat (com.loohp.interactivechat.InteractiveChat)7 ItemStack (org.bukkit.inventory.ItemStack)7 CustomPlaceholderClickEvent (com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderClickEvent)6 CustomPlaceholderHoverEvent (com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderHoverEvent)6 CustomPlaceholderReplaceText (com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderReplaceText)6 BackendInteractiveChatData (com.loohp.interactivechat.proxy.objectholders.BackendInteractiveChatData)6 ChatColorUtils (com.loohp.interactivechat.utils.ChatColorUtils)6 Field (java.lang.reflect.Field)6