Search in sources :

Example 1 with MessageChannel

use of org.spongepowered.api.text.channel.MessageChannel in project Skree by Skelril.

the class GoldRushInstance method tryToStart.

public void tryToStart() {
    BigDecimal coffersNeeded = getCoffersNeeded();
    if (coffersNeeded.compareTo(BigDecimal.ZERO) >= 0) {
        MessageChannel channel = getPlayerMessageChannel(PlayerClassifier.SPECTATOR);
        channel.send(Text.of(TextColors.RED, "Your party doesn't have a high enough coffer risk!"));
        channel.send(Text.of(TextColors.RED, "At least ", coffersNeeded, " more coffers must be risked."));
        return;
    }
    Optional<PlayerStateService> optService = Sponge.getServiceManager().provide(PlayerStateService.class);
    for (Player player : getPlayers(PlayerClassifier.PARTICIPANT)) {
        if (optService.isPresent()) {
            PlayerStateService service = optService.get();
            try {
                service.storeInventory(player);
                service.releaseInventory(player);
                player.getInventory().clear();
            } catch (InventoryStorageStateException e) {
                e.printStackTrace();
                player.sendMessage(Text.of(TextColors.RED, "An error occurred while saving your inventory, contact an admin!"));
                return;
            }
        } else {
            if (player.getInventory().query(PlayerInventory.class, EquipmentInventory.class).size() > 0) {
                getPlayerMessageChannel(PlayerClassifier.SPECTATOR).send(Text.of(TextColors.RED, "All players inventories must be empty."));
                return;
            }
        }
    }
    readyPlayers();
    calculateLootSplit();
    // Reset tryToStart clock
    startTime = System.currentTimeMillis();
    // Add content
    populateChest();
    runLavaChance();
    setFloodStartTime();
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) PlayerStateService(com.skelril.skree.service.PlayerStateService) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) InventoryStorageStateException(com.skelril.skree.service.internal.playerstate.InventoryStorageStateException) BigDecimal(java.math.BigDecimal)

Example 2 with MessageChannel

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

the class MixinPlayerList method initializeConnectionToPlayer.

public void initializeConnectionToPlayer(NetworkManager netManager, EntityPlayerMP playerIn, @Nullable NetHandlerPlayServer handler) {
    GameProfile gameprofile = playerIn.getGameProfile();
    PlayerProfileCache playerprofilecache = this.mcServer.getPlayerProfileCache();
    GameProfile gameprofile1 = playerprofilecache.getProfileByUUID(gameprofile.getId());
    String s = gameprofile1 == null ? gameprofile.getName() : gameprofile1.getName();
    playerprofilecache.addEntry(gameprofile);
    // Sponge start - save changes to offline User before reading player data
    SpongeUser user = (SpongeUser) ((IMixinEntityPlayerMP) playerIn).getUserObject();
    if (SpongeUser.dirtyUsers.contains(user)) {
        user.save();
    }
    // Sponge end
    NBTTagCompound nbttagcompound = this.readPlayerDataFromFile(playerIn);
    WorldServer worldServer = this.mcServer.getWorld(playerIn.dimension);
    int actualDimensionId = ((IMixinWorldServer) worldServer).getDimensionId();
    BlockPos spawnPos = null;
    // Join data
    Optional<Instant> firstJoined = SpongePlayerDataHandler.getFirstJoined(playerIn.getUniqueID());
    Instant lastJoined = Instant.now();
    SpongePlayerDataHandler.setPlayerInfo(playerIn.getUniqueID(), firstJoined.orElse(lastJoined), lastJoined);
    if (actualDimensionId != playerIn.dimension) {
        SpongeImpl.getLogger().warn("Player [{}] has attempted to login to unloaded world [{}]. This is not safe so we have moved them to " + "the default world's spawn point.", playerIn.getName(), playerIn.dimension);
        if (!firstJoined.isPresent()) {
            spawnPos = SpongeImplHooks.getRandomizedSpawnPoint(worldServer);
        } else {
            spawnPos = worldServer.getSpawnPoint();
        }
        playerIn.dimension = actualDimensionId;
        playerIn.setPosition(spawnPos.getX(), spawnPos.getY(), spawnPos.getZ());
    }
    // Sponge start - fire login event
    @Nullable String kickReason = allowUserToConnect(netManager.getRemoteAddress(), gameprofile);
    Text disconnectMessage;
    if (kickReason != null) {
        disconnectMessage = SpongeTexts.fromLegacy(kickReason);
    } else {
        disconnectMessage = Text.of("You are not allowed to log in to this server.");
    }
    Player player = (Player) playerIn;
    Transform<World> fromTransform = player.getTransform().setExtent((World) worldServer);
    Sponge.getCauseStackManager().pushCause(player);
    ClientConnectionEvent.Login loginEvent = SpongeEventFactory.createClientConnectionEventLogin(Sponge.getCauseStackManager().getCurrentCause(), fromTransform, fromTransform, (RemoteConnection) netManager, new MessageEvent.MessageFormatter(disconnectMessage), (org.spongepowered.api.profile.GameProfile) gameprofile, player, false);
    if (kickReason != null) {
        loginEvent.setCancelled(true);
    }
    if (SpongeImpl.postEvent(loginEvent)) {
        Sponge.getCauseStackManager().popCause();
        disconnectClient(netManager, loginEvent.isMessageCancelled() ? Optional.empty() : Optional.of(loginEvent.getMessage()), gameprofile);
        return;
    }
    Sponge.getCauseStackManager().popCause();
    // Sponge end
    worldServer = (WorldServer) loginEvent.getToTransform().getExtent();
    double x = loginEvent.getToTransform().getPosition().getX();
    double y = loginEvent.getToTransform().getPosition().getY();
    double z = loginEvent.getToTransform().getPosition().getZ();
    float pitch = (float) loginEvent.getToTransform().getPitch();
    float yaw = (float) loginEvent.getToTransform().getYaw();
    playerIn.dimension = ((IMixinWorldServer) worldServer).getDimensionId();
    playerIn.setWorld(worldServer);
    playerIn.interactionManager.setWorld((WorldServer) playerIn.world);
    playerIn.setPositionAndRotation(x, y, z, yaw, pitch);
    // make sure the chunk is loaded for login
    worldServer.getChunkProvider().loadChunk(loginEvent.getToTransform().getLocation().getChunkPosition().getX(), loginEvent.getToTransform().getLocation().getChunkPosition().getZ());
    // Sponge end
    String s1 = "local";
    if (netManager.getRemoteAddress() != null) {
        s1 = netManager.getRemoteAddress().toString();
    }
    final WorldInfo worldinfo = worldServer.getWorldInfo();
    final BlockPos spawnBlockPos = worldServer.getSpawnPoint();
    this.setPlayerGameTypeBasedOnOther(playerIn, null, worldServer);
    // Sponge start
    if (handler == null) {
        // Create the handler here (so the player's gets set)
        handler = new NetHandlerPlayServer(this.mcServer, netManager, playerIn);
    }
    playerIn.connection = handler;
    // Sponge end
    // Support vanilla clients logging into custom dimensions
    final int dimensionId = WorldManager.getClientDimensionId(playerIn, worldServer);
    // Send dimension registration
    WorldManager.sendDimensionRegistration(playerIn, worldServer.provider);
    handler.sendPacket(new SPacketJoinGame(playerIn.getEntityId(), playerIn.interactionManager.getGameType(), worldinfo.isHardcoreModeEnabled(), dimensionId, worldServer.getDifficulty(), this.getMaxPlayers(), worldinfo.getTerrainType(), worldServer.getGameRules().getBoolean("reducedDebugInfo")));
    handler.sendPacket(new SPacketCustomPayload("MC|Brand", (new PacketBuffer(Unpooled.buffer())).writeString(this.getServerInstance().getServerModName())));
    handler.sendPacket(new SPacketServerDifficulty(worldinfo.getDifficulty(), worldinfo.isDifficultyLocked()));
    handler.sendPacket(new SPacketSpawnPosition(spawnBlockPos));
    handler.sendPacket(new SPacketPlayerAbilities(playerIn.capabilities));
    handler.sendPacket(new SPacketHeldItemChange(playerIn.inventory.currentItem));
    this.updatePermissionLevel(playerIn);
    playerIn.getStatFile().markAllDirty();
    playerIn.getRecipeBook().init(playerIn);
    this.mcServer.refreshStatusNextTick();
    handler.setPlayerLocation(x, y, z, yaw, pitch);
    this.playerLoggedIn(playerIn);
    // Sponge start - add world name to message
    LOGGER.info(playerIn.getName() + "[" + s1 + "] logged in with entity id " + playerIn.getEntityId() + " in " + worldServer.getWorldInfo().getWorldName() + "(" + ((IMixinWorldServer) worldServer).getDimensionId() + ") at (" + playerIn.posX + ", " + playerIn.posY + ", " + playerIn.posZ + ")");
    // Sponge end
    this.updateTimeAndWeatherForPlayer(playerIn, worldServer);
    // Sponge Start - Use the server's ResourcePack object
    Optional<ResourcePack> pack = ((Server) this.mcServer).getDefaultResourcePack();
    if (pack.isPresent()) {
        ((Player) playerIn).sendResourcePack(pack.get());
    }
    // Sponge End
    // Sponge Start
    // 
    // This sends the objective/score creation packets
    // to the player, without attempting to remove them from their
    // previous scoreboard (which is set in a field initializer).
    // This allows #getWorldScoreboard to function
    // as normal, without causing issues when it is initialized on the client.
    ((IMixinEntityPlayerMP) playerIn).initScoreboard();
    for (PotionEffect potioneffect : playerIn.getActivePotionEffects()) {
        handler.sendPacket(new SPacketEntityEffect(playerIn.getEntityId(), potioneffect));
    }
    if (nbttagcompound != null) {
        if (nbttagcompound.hasKey("RootVehicle", 10)) {
            NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("RootVehicle");
            Entity entity2 = AnvilChunkLoader.readWorldEntity(nbttagcompound1.getCompoundTag("Entity"), worldServer, true);
            if (entity2 != null) {
                UUID uuid = nbttagcompound1.getUniqueId("Attach");
                if (entity2.getUniqueID().equals(uuid)) {
                    playerIn.startRiding(entity2, true);
                } else {
                    for (Entity entity : entity2.getRecursivePassengers()) {
                        if (entity.getUniqueID().equals(uuid)) {
                            playerIn.startRiding(entity, true);
                            break;
                        }
                    }
                }
                if (!playerIn.isRiding()) {
                    LOGGER.warn("Couldn\'t reattach entity to player");
                    worldServer.removeEntityDangerously(entity2);
                    for (Entity entity3 : entity2.getRecursivePassengers()) {
                        worldServer.removeEntityDangerously(entity3);
                    }
                }
            }
        } else if (nbttagcompound.hasKey("Riding", 10)) {
            Entity entity1 = AnvilChunkLoader.readWorldEntity(nbttagcompound.getCompoundTag("Riding"), worldServer, true);
            if (entity1 != null) {
                playerIn.startRiding(entity1, true);
            }
        }
    }
    playerIn.addSelfToInternalCraftingInventory();
    TextComponentTranslation chatcomponenttranslation;
    if (!playerIn.getName().equalsIgnoreCase(s)) {
        chatcomponenttranslation = new TextComponentTranslation("multiplayer.player.joined.renamed", playerIn.getDisplayName(), s);
    } else {
        chatcomponenttranslation = new TextComponentTranslation("multiplayer.player.joined", playerIn.getDisplayName());
    }
    chatcomponenttranslation.getStyle().setColor(TextFormatting.YELLOW);
    // Fire PlayerJoinEvent
    Text originalMessage = SpongeTexts.toText(chatcomponenttranslation);
    MessageChannel originalChannel = player.getMessageChannel();
    Sponge.getCauseStackManager().pushCause(player);
    final ClientConnectionEvent.Join event = SpongeEventFactory.createClientConnectionEventJoin(Sponge.getCauseStackManager().getCurrentCause(), originalChannel, Optional.of(originalChannel), new MessageEvent.MessageFormatter(originalMessage), player, false);
    SpongeImpl.postEvent(event);
    Sponge.getCauseStackManager().popCause();
    // Send to the channel
    if (!event.isMessageCancelled()) {
        event.getChannel().ifPresent(channel -> channel.send(player, event.getMessage()));
    }
// Sponge end
}
Also used : SPacketPlayerAbilities(net.minecraft.network.play.server.SPacketPlayerAbilities) IMixinEntity(org.spongepowered.common.interfaces.entity.IMixinEntity) Entity(net.minecraft.entity.Entity) SPacketSpawnPosition(net.minecraft.network.play.server.SPacketSpawnPosition) MinecraftServer(net.minecraft.server.MinecraftServer) NetHandlerPlayServer(net.minecraft.network.NetHandlerPlayServer) Server(org.spongepowered.api.Server) WorldServer(net.minecraft.world.WorldServer) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) PlayerProfileCache(net.minecraft.server.management.PlayerProfileCache) PotionEffect(net.minecraft.potion.PotionEffect) MessageEvent(org.spongepowered.api.event.message.MessageEvent) ResourcePack(org.spongepowered.api.resourcepack.ResourcePack) NBTTagCompound(net.minecraft.nbt.NBTTagCompound) WorldServer(net.minecraft.world.WorldServer) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) IMixinEntityPlayerMP(org.spongepowered.common.interfaces.entity.player.IMixinEntityPlayerMP) World(org.spongepowered.api.world.World) SPacketServerDifficulty(net.minecraft.network.play.server.SPacketServerDifficulty) SPacketHeldItemChange(net.minecraft.network.play.server.SPacketHeldItemChange) WorldInfo(net.minecraft.world.storage.WorldInfo) BlockPos(net.minecraft.util.math.BlockPos) UUID(java.util.UUID) PacketBuffer(net.minecraft.network.PacketBuffer) Player(org.spongepowered.api.entity.living.player.Player) TextComponentTranslation(net.minecraft.util.text.TextComponentTranslation) Instant(java.time.Instant) ClientConnectionEvent(org.spongepowered.api.event.network.ClientConnectionEvent) IMixinWorldServer(org.spongepowered.common.interfaces.world.IMixinWorldServer) Text(org.spongepowered.api.text.Text) NetHandlerPlayServer(net.minecraft.network.NetHandlerPlayServer) SpongeUser(org.spongepowered.common.entity.player.SpongeUser) SPacketJoinGame(net.minecraft.network.play.server.SPacketJoinGame) SPacketCustomPayload(net.minecraft.network.play.server.SPacketCustomPayload) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) GameProfile(com.mojang.authlib.GameProfile) SPacketEntityEffect(net.minecraft.network.play.server.SPacketEntityEffect) Nullable(javax.annotation.Nullable)

Example 3 with MessageChannel

use of org.spongepowered.api.text.channel.MessageChannel in project Skree by Skelril.

the class GoldRushListener method onChestClose.

@Listener
public void onChestClose(InteractInventoryEvent.Close event) {
    Inventory inventory = event.getTargetInventory();
    if (inventory instanceof ContainerChest) {
        IInventory chestInv = ((ContainerChest) inventory).getLowerChestInventory();
        if (chestInv instanceof ILockableContainer) {
            String lockCode = ((ILockableContainer) chestInv).getLockCode().getLock();
            Optional<Player> optPlayer = Optional.ofNullable(tileEntityClaimMap.remove(lockCode));
            if (optPlayer.isPresent()) {
                Player player = optPlayer.get();
                ((ILockableContainer) chestInv).setLockCode(LockCode.EMPTY_CODE);
                Optional<GoldRushInstance> optInst = manager.getApplicableZone(player);
                if (!optInst.isPresent()) {
                    return;
                }
                // TODO Sponge port
                GoldRushInstance inst = optInst.get();
                List<org.spongepowered.api.item.inventory.ItemStack> toEvaluate = new ArrayList<>();
                ArrayDeque<org.spongepowered.api.item.inventory.ItemStack> toReturn = new ArrayDeque<>();
                for (int i = 0; i < chestInv.getSizeInventory(); ++i) {
                    ItemStack stack = chestInv.getStackInSlot(i);
                    if (stack == ItemStack.EMPTY) {
                        continue;
                    }
                    if (stack.getItem() instanceof CofferItem) {
                        toEvaluate.add(tf(stack));
                    } else {
                        toReturn.add(tf(stack));
                    }
                    chestInv.setInventorySlotContents(i, ItemStack.EMPTY);
                }
                BigDecimal value = BigDecimal.ZERO;
                for (org.spongepowered.api.item.inventory.ItemStack stack : toEvaluate) {
                    value = value.add(new BigDecimal(CofferValueMap.inst().getValue(Collections.singleton(stack)).orElse(BigInteger.ZERO)));
                }
                inst.cofferRisk.put(player.getUniqueId(), value);
                for (Inventory slot : player.getInventory().slots()) {
                    if (toReturn.isEmpty()) {
                        break;
                    }
                    if (slot.size() == 0) {
                        slot.set(toReturn.poll());
                    }
                }
                if (!toReturn.isEmpty()) {
                    new ItemDropper(player.getLocation()).dropStacks(toReturn, SpawnTypes.PLUGIN);
                }
                player.sendMessage(Text.of(TextColors.YELLOW, "You are now risking ", format(value), " coffers."));
                MessageChannel targetChannel = inst.getPlayerMessageChannel(PlayerClassifier.SPECTATOR);
                targetChannel.send(Text.of(TextColors.YELLOW, "Group risk of ", format(inst.getTotalRisk()), " coffers."));
                targetChannel.send(Text.of(TextColors.YELLOW, "Risk of lava ", inst.getChanceOfLava(), " / 100."));
                targetChannel.send(Text.of(TextColors.YELLOW, "Security system delay ", inst.getBaseTime(), " +/- ", inst.getTimeVariance(), " seconds."));
            }
        }
    }
}
Also used : ItemDropper(com.skelril.nitro.item.ItemDropper) ILockableContainer(net.minecraft.world.ILockableContainer) ContainerChest(net.minecraft.inventory.ContainerChest) IInventory(net.minecraft.inventory.IInventory) Player(org.spongepowered.api.entity.living.player.Player) BigDecimal(java.math.BigDecimal) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) CofferItem(com.skelril.skree.content.registry.item.currency.CofferItem) ItemStack(net.minecraft.item.ItemStack) Inventory(org.spongepowered.api.item.inventory.Inventory) IInventory(net.minecraft.inventory.IInventory) Listener(org.spongepowered.api.event.Listener)

Example 4 with MessageChannel

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

the class SpongeForgeEventFactory method createMessageChannelEventChat.

public static MessageChannelEvent.Chat createMessageChannelEventChat(ServerChatEvent forgeEvent) {
    final ITextComponent forgeComponent = forgeEvent.getComponent();
    final MessageFormatter formatter = new MessageFormatter();
    MessageChannel channel;
    Text[] chat = SpongeTexts.splitChatMessage((TextComponentTranslation) forgeComponent);
    if (chat[1] == null) {
        // Move content from head part to body part
        chat[1] = chat[0] != null ? chat[0] : SpongeTexts.toText(forgeComponent);
        chat[0] = null;
    }
    if (chat[0] != null) {
        formatter.getHeader().add(new DefaultHeaderApplier(chat[0]));
    }
    formatter.getBody().add(new DefaultBodyApplier(chat[1]));
    Text rawSpongeMessage = Text.of(forgeEvent.getMessage());
    MessageChannel originalChannel = channel = ((Player) forgeEvent.getPlayer()).getMessageChannel();
    Sponge.getCauseStackManager().pushCause(forgeEvent.getPlayer());
    return SpongeEventFactory.createMessageChannelEventChat(Sponge.getCauseStackManager().getCurrentCause(), originalChannel, Optional.ofNullable(channel), formatter, rawSpongeMessage, false);
}
Also used : MessageChannel(org.spongepowered.api.text.channel.MessageChannel) DefaultHeaderApplier(org.spongepowered.api.event.message.MessageEvent.DefaultHeaderApplier) ITextComponent(net.minecraft.util.text.ITextComponent) DefaultBodyApplier(org.spongepowered.api.event.message.MessageEvent.DefaultBodyApplier) Text(org.spongepowered.api.text.Text) MessageFormatter(org.spongepowered.api.event.message.MessageEvent.MessageFormatter)

Example 5 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)

Aggregations

MessageChannel (org.spongepowered.api.text.channel.MessageChannel)22 Player (org.spongepowered.api.entity.living.player.Player)15 Text (org.spongepowered.api.text.Text)15 MessageEvent (org.spongepowered.api.event.message.MessageEvent)10 UUID (java.util.UUID)6 ClientConnectionEvent (org.spongepowered.api.event.network.ClientConnectionEvent)5 Instant (java.time.Instant)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 Cause (org.spongepowered.api.event.cause.Cause)3 MessageChannelEvent (org.spongepowered.api.event.message.MessageChannelEvent)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 Sets (com.google.common.collect.Sets)2