Search in sources :

Example 6 with MessageChannel

use of org.spongepowered.api.text.channel.MessageChannel in project SpongeVanilla by SpongePowered.

the class MixinNetHandlerPlayServer method onProcessChatMessage.

@Inject(method = "processChatMessage", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/management/PlayerList;sendMessage(Lnet/minecraft/util/text/ITextComponent;Z)V"), cancellable = true, locals = LocalCapture.CAPTURE_FAILHARD)
private void onProcessChatMessage(CPacketChatMessage packet, CallbackInfo ci, String s, ITextComponent component) {
    ChatFormatter.formatChatComponent((TextComponentTranslation) component);
    // safe cast
    final Text[] message = SpongeTexts.splitChatMessage((TextComponentTranslation) component);
    final MessageChannel originalChannel = ((Player) this.player).getMessageChannel();
    Sponge.getCauseStackManager().pushCause(this.player);
    final MessageChannelEvent.Chat event = SpongeEventFactory.createMessageChannelEventChat(Sponge.getCauseStackManager().getCurrentCause(), originalChannel, Optional.of(originalChannel), new MessageEvent.MessageFormatter(message[0], message[1]), Text.of(s), false);
    if (!SpongeImpl.postEvent(event) && !event.isMessageCancelled()) {
        event.getChannel().ifPresent(channel -> channel.send(this.player, event.getMessage(), ChatTypes.CHAT));
    } else {
        ci.cancel();
    }
    Sponge.getCauseStackManager().popCause();
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) MessageChannelEvent(org.spongepowered.api.event.message.MessageChannelEvent) MessageEvent(org.spongepowered.api.event.message.MessageEvent) Text(org.spongepowered.api.text.Text) Inject(org.spongepowered.asm.mixin.injection.Inject)

Example 7 with MessageChannel

use of org.spongepowered.api.text.channel.MessageChannel in project LanternServer by LanternPowered.

the class HandlerPlayInChatMessage method handle.

@Override
public void handle(NetworkContext context, MessagePlayInChatMessage message) {
    final NetworkSession session = context.getSession();
    final LanternPlayer player = session.getPlayer();
    player.resetIdleTimeoutCounter();
    final String message0 = message.getMessage();
    // Check for a valid click action callback
    final Matcher matcher = LanternClickActionCallbacks.COMMAND_PATTERN.matcher(message0);
    if (matcher.matches()) {
        final UUID uniqueId = UUID.fromString(matcher.group(1));
        final Optional<Consumer<CommandSource>> callback = LanternClickActionCallbacks.get().getCallbackForUUID(uniqueId);
        if (callback.isPresent()) {
            callback.get().accept(player);
        } else {
            player.sendMessage(error(t("The callback you provided was not valid. Keep in mind that callbacks will expire " + "after 10 minutes, so you might want to consider clicking faster next time!")));
        }
        return;
    }
    String message1 = StringUtils.normalizeSpace(message0);
    if (!isAllowedString(message0)) {
        session.disconnect(t("multiplayer.disconnect.illegal_characters"));
        return;
    }
    if (message1.startsWith("/")) {
        Lantern.getSyncExecutorService().submit(() -> Sponge.getCommandManager().process(player, message1.substring(1)));
    } else {
        final Text nameText = player.get(Keys.DISPLAY_NAME).get();
        final Text rawMessageText = Text.of(message0);
        final GlobalConfig.Chat.Urls urls = Lantern.getGame().getGlobalConfig().getChat().getUrls();
        final Text messageText;
        if (urls.isEnabled() && player.hasPermission(Permissions.Chat.FORMAT_URLS)) {
            messageText = newTextWithLinks(message0, urls.getTemplate(), false);
        } else {
            messageText = rawMessageText;
        }
        final MessageChannel channel = player.getMessageChannel();
        final CauseStack causeStack = CauseStack.current();
        try (CauseStack.Frame frame = causeStack.pushCauseFrame()) {
            frame.addContext(EventContextKeys.PLAYER, player);
            final MessageChannelEvent.Chat event = SpongeEventFactory.createMessageChannelEventChat(causeStack.getCurrentCause(), channel, Optional.of(channel), new MessageEvent.MessageFormatter(nameText, messageText), rawMessageText, false);
            if (!Sponge.getEventManager().post(event) && !event.isMessageCancelled()) {
                event.getChannel().ifPresent(c -> c.send(player, event.getMessage(), ChatTypes.CHAT));
            }
        }
    }
    final Attribute<ChatData> attr = context.getChannel().attr(CHAT_DATA);
    ChatData chatData = attr.get();
    if (chatData == null) {
        chatData = new ChatData();
        final ChatData chatData1 = attr.setIfAbsent(chatData);
        if (chatData1 != null) {
            chatData = chatData1;
        }
    }
    // noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (chatData) {
        final long currentTime = LanternGame.currentTimeTicks();
        if (chatData.lastChatTime != -1L) {
            chatData.chatThrottle = (int) Math.max(0, chatData.chatThrottle - (currentTime - chatData.lastChatTime));
        }
        chatData.lastChatTime = currentTime;
        chatData.chatThrottle += 20;
        if (chatData.chatThrottle > Lantern.getGame().getGlobalConfig().getChatSpamThreshold()) {
            session.disconnect(t("disconnect.spam"));
        }
    }
}
Also used : CauseStack(org.lanternpowered.server.event.CauseStack) NetworkSession(org.lanternpowered.server.network.NetworkSession) Matcher(java.util.regex.Matcher) MessageChannelEvent(org.spongepowered.api.event.message.MessageChannelEvent) MessageEvent(org.spongepowered.api.event.message.MessageEvent) Text(org.spongepowered.api.text.Text) Consumer(java.util.function.Consumer) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) UUID(java.util.UUID) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer)

Example 8 with MessageChannel

use of org.spongepowered.api.text.channel.MessageChannel in project LanternServer by LanternPowered.

the class LanternPlayer method simulateChat.

@Override
public MessageChannelEvent.Chat simulateChat(Text message, Cause cause) {
    checkNotNull(message, "message");
    checkNotNull(cause, "cause");
    final Text nameText = get(Keys.DISPLAY_NAME).get();
    final MessageChannel channel = getMessageChannel();
    final MessageChannelEvent.Chat event = SpongeEventFactory.createMessageChannelEventChat(cause, channel, Optional.of(channel), new MessageEvent.MessageFormatter(nameText, message), message, false);
    if (!Sponge.getEventManager().post(event) && !event.isMessageCancelled()) {
        event.getChannel().ifPresent(c -> c.send(this, event.getMessage(), ChatTypes.CHAT));
    }
    return event;
}
Also used : MessageChannel(org.spongepowered.api.text.channel.MessageChannel) MessageChannelEvent(org.spongepowered.api.event.message.MessageChannelEvent) MessageEvent(org.spongepowered.api.event.message.MessageEvent) Text(org.spongepowered.api.text.Text)

Example 9 with MessageChannel

use of org.spongepowered.api.text.channel.MessageChannel in project LanternServer by LanternPowered.

the class NetworkSession method initPlayer.

/**
 * Initializes the {@link LanternPlayer} instance
 * and spawns it in a world if permitted to join
 * the server.
 */
public void initPlayer() {
    initKeepAliveTask();
    if (this.gameProfile == null) {
        throw new IllegalStateException("The game profile must first be available!");
    }
    this.player = new LanternPlayer(this.gameProfile, this);
    this.player.setNetworkId(EntityProtocolManager.acquireEntityId());
    this.player.setEntityProtocolType(EntityProtocolTypes.PLAYER);
    LanternWorld world = this.player.getWorld();
    if (world == null) {
        LanternWorldProperties worldProperties = this.player.getUserWorld();
        boolean fixSpawnLocation = false;
        if (worldProperties == null) {
            Lantern.getLogger().warn("The player [{}] attempted to login in a non-existent world, this is not possible " + "so we have moved them to the default's world spawn point.", this.gameProfile.getName().get());
            worldProperties = (LanternWorldProperties) Lantern.getServer().getDefaultWorld().get();
            fixSpawnLocation = true;
        } else if (!worldProperties.isEnabled()) {
            Lantern.getLogger().warn("The player [{}] attempted to login in a unloaded and not-enabled world [{}], this is not possible " + "so we have moved them to the default's world spawn point.", this.gameProfile.getName().get(), worldProperties.getWorldName());
            worldProperties = (LanternWorldProperties) Lantern.getServer().getDefaultWorld().get();
            fixSpawnLocation = true;
        }
        final Optional<World> optWorld = Lantern.getWorldManager().loadWorld(worldProperties);
        // Use the raw method to avoid triggering any network messages
        this.player.setRawWorld((LanternWorld) optWorld.get());
        this.player.setUserWorld(null);
        if (fixSpawnLocation) {
            // TODO: Use a proper spawn position
            this.player.setRawPosition(new Vector3d(0, 100, 0));
            this.player.setRawRotation(new Vector3d(0, 0, 0));
        }
    }
    // The kick reason
    Text kickReason = null;
    final BanService banService = Sponge.getServiceManager().provideUnchecked(BanService.class);
    // Check whether the player is banned and kick if necessary
    Ban ban = banService.getBanFor(this.gameProfile).orElse(null);
    if (ban == null) {
        final SocketAddress address = getChannel().remoteAddress();
        if (address instanceof InetSocketAddress) {
            ban = banService.getBanFor(((InetSocketAddress) address).getAddress()).orElse(null);
        }
    }
    if (ban != null) {
        final Optional<Instant> optExpirationDate = ban.getExpirationDate();
        final Optional<Text> optReason = ban.getReason();
        // Generate the kick message
        Text.Builder builder = Text.builder();
        if (ban instanceof Ban.Profile) {
            builder.append(t("multiplayer.disconnect.ban.banned"));
        } else {
            builder.append(t("multiplayer.disconnect.ban.ip_banned"));
        }
        // There is optionally a reason
        optReason.ifPresent(reason -> builder.append(Text.NEW_LINE).append(t("multiplayer.disconnect.ban.reason", reason)));
        // And a expiration date if present
        optExpirationDate.ifPresent(expirationDate -> {
            final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(tr("multiplayer.disconnect.ban.expiration_date_format").get());
            builder.append(Text.NEW_LINE).append(t("multiplayer.disconnect.ban.expiration", formatter.format(expirationDate)));
        });
        kickReason = builder.build();
    // Check for white-list
    } else if (!isWhitelisted(this.gameProfile)) {
        kickReason = t("multiplayer.disconnect.not_whitelisted");
    // Check whether the server is full
    } else if (Lantern.getServer().getOnlinePlayers().size() >= Lantern.getServer().getMaxPlayers() && !canBypassPlayerLimit(this.gameProfile)) {
        kickReason = t("multiplayer.disconnect.server_full");
    }
    final MessageEvent.MessageFormatter messageFormatter = new MessageEvent.MessageFormatter(kickReason != null ? kickReason : t("multiplayer.disconnect.not_allowed_to_join"));
    final Cause cause = Cause.builder().append(this).build(EventContext.builder().add(EventContextKeys.PLAYER, this.player).build());
    final Transform<World> fromTransform = this.player.getTransform();
    final ClientConnectionEvent.Login loginEvent = SpongeEventFactory.createClientConnectionEventLogin(cause, fromTransform, fromTransform, this, messageFormatter, this.gameProfile, this.player, false);
    if (kickReason != null) {
        loginEvent.setCancelled(true);
    }
    Sponge.getEventManager().post(loginEvent);
    if (loginEvent.isCancelled()) {
        disconnect(loginEvent.isMessageCancelled() ? t("multiplayer.disconnect.generic") : loginEvent.getMessage());
        return;
    }
    Lantern.getLogger().debug("The player {} successfully to joined from {}.", this.gameProfile.getName().get(), this.channel.remoteAddress());
    // Update the first join and last played data
    final Instant lastJoined = Instant.now();
    this.player.offer(Keys.LAST_DATE_PLAYED, lastJoined);
    if (!this.player.get(Keys.FIRST_DATE_PLAYED).isPresent()) {
        this.player.offer(Keys.FIRST_DATE_PLAYED, lastJoined);
    }
    final Transform<World> toTransform = loginEvent.getToTransform();
    world = (LanternWorld) toTransform.getExtent();
    final WorldConfig config = world.getProperties().getConfig();
    // Update the game mode if necessary
    if (config.isGameModeForced() || this.player.get(Keys.GAME_MODE).get().equals(GameModes.NOT_SET)) {
        this.player.offer(Keys.GAME_MODE, config.getGameMode());
    }
    // Reset the raw world
    this.player.setRawWorld(null);
    // Set the transform, this will trigger the initial
    // network messages to be send
    this.player.setTransform(toTransform);
    final MessageChannel messageChannel = this.player.getMessageChannel();
    final Text joinMessage;
    final GameProfile previousProfile = this.channel.attr(PREVIOUS_GAME_PROFILE).getAndSet(null);
    if (previousProfile != null && previousProfile.getName().isPresent() && !previousProfile.getName().get().equals(this.gameProfile.getName().get())) {
        joinMessage = t("multiplayer.player.joined.renamed", this.player.getName(), previousProfile.getName().get());
    } else {
        joinMessage = t("multiplayer.player.joined", this.player.getName());
    }
    final ClientConnectionEvent.Join joinEvent = SpongeEventFactory.createClientConnectionEventJoin(cause, messageChannel, Optional.of(messageChannel), new MessageEvent.MessageFormatter(joinMessage), this.player, false);
    Sponge.getEventManager().post(joinEvent);
    if (!joinEvent.isMessageCancelled()) {
        joinEvent.getChannel().ifPresent(channel -> channel.send(this.player, joinEvent.getMessage()));
    }
    this.server.getDefaultResourcePack().ifPresent(this.player::sendResourcePack);
    this.player.resetIdleTimeoutCounter();
}
Also used : InetSocketAddress(java.net.InetSocketAddress) MessageEvent(org.spongepowered.api.event.message.MessageEvent) WorldConfig(org.lanternpowered.server.config.world.WorldConfig) LanternWorld(org.lanternpowered.server.world.LanternWorld) World(org.spongepowered.api.world.World) LanternWorld(org.lanternpowered.server.world.LanternWorld) GameProfile(org.spongepowered.api.profile.GameProfile) LanternGameProfile(org.lanternpowered.server.profile.LanternGameProfile) Cause(org.spongepowered.api.event.cause.Cause) BanService(org.spongepowered.api.service.ban.BanService) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) LanternWorldProperties(org.lanternpowered.server.world.LanternWorldProperties) Instant(java.time.Instant) ClientConnectionEvent(org.spongepowered.api.event.network.ClientConnectionEvent) Text(org.spongepowered.api.text.Text) Ban(org.spongepowered.api.util.ban.Ban) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) Vector3d(com.flowpowered.math.vector.Vector3d) GameProfile(org.spongepowered.api.profile.GameProfile) LanternGameProfile(org.lanternpowered.server.profile.LanternGameProfile) DateTimeFormatter(java.time.format.DateTimeFormatter) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer)

Example 10 with MessageChannel

use of org.spongepowered.api.text.channel.MessageChannel in project Nucleus by NucleusPowered.

the class CloneWorldCommand method executeCommand.

@Override
protected CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    WorldProperties worldToCopy = args.<WorldProperties>getOne(this.worldKey).get();
    final String oldName = worldToCopy.getWorldName();
    final String newName = args.<String>getOne(this.newKey).get();
    if (Sponge.getServer().getWorldProperties(newName).isPresent()) {
        throw ReturnMessageException.fromKey("command.world.clone.alreadyexists", newName);
    }
    Text message = Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.world.clone.starting", oldName, newName);
    src.sendMessage(message);
    if (!(src instanceof ConsoleSource)) {
        Sponge.getServer().getConsole().sendMessage(message);
    }
    // Well, you never know, the player might die or disconnect - we have to be vigilant.
    final Supplier<MessageReceiver> mr;
    if (src instanceof Player) {
        UUID uuid = ((Player) src).getUniqueId();
        mr = () -> Sponge.getServer().getPlayer(uuid).map(x -> (MessageReceiver) x).orElseGet(() -> new MessageReceiver() {

            @Override
            public void sendMessage(Text message) {
            }

            @Override
            public MessageChannel getMessageChannel() {
                return MessageChannel.TO_NONE;
            }

            @Override
            public void setMessageChannel(MessageChannel channel) {
            }
        });
    } else {
        mr = () -> src;
    }
    Sponge.getServer().copyWorld(worldToCopy, newName).handle((result, ex) -> {
        MessageReceiver m = mr.get();
        Text msg;
        if (ex == null && result.isPresent()) {
            msg = Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.world.clone.success", oldName, newName);
        } else {
            msg = Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.world.clone.failed", oldName, newName);
        }
        m.sendMessage(msg);
        if (!(m instanceof ConsoleSource)) {
            Sponge.getServer().getConsole().sendMessage(msg);
        }
        return result;
    });
    return CommandResult.success();
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) MessageReceiver(org.spongepowered.api.text.channel.MessageReceiver) Text(org.spongepowered.api.text.Text) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) UUID(java.util.UUID) WorldProperties(org.spongepowered.api.world.storage.WorldProperties)

Aggregations

MessageChannel (org.spongepowered.api.text.channel.MessageChannel)24 Player (org.spongepowered.api.entity.living.player.Player)17 Text (org.spongepowered.api.text.Text)17 MessageEvent (org.spongepowered.api.event.message.MessageEvent)11 UUID (java.util.UUID)6 ClientConnectionEvent (org.spongepowered.api.event.network.ClientConnectionEvent)5 Instant (java.time.Instant)4 MessageChannelEvent (org.spongepowered.api.event.message.MessageChannelEvent)4 NucleusTextTemplateImpl (io.github.nucleuspowered.nucleus.internal.text.NucleusTextTemplateImpl)3 Optional (java.util.Optional)3 Sponge (org.spongepowered.api.Sponge)3 User (org.spongepowered.api.entity.living.player.User)3 Listener (org.spongepowered.api.event.Listener)3 Cause (org.spongepowered.api.event.cause.Cause)3 ChatTypes (org.spongepowered.api.text.chat.ChatTypes)3 Preconditions (com.google.common.base.Preconditions)2 HashMultimap (com.google.common.collect.HashMultimap)2 Lists (com.google.common.collect.Lists)2 Maps (com.google.common.collect.Maps)2 Multimap (com.google.common.collect.Multimap)2