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();
}
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
}
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."));
}
}
}
}
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);
}
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();
}
Aggregations