| 1 | package net.minecraft.server.jsonrpc.methods;
|
| 2 |
|
| 3 | import com.mojang.serialization.MapCodec;
|
| 4 | import com.mojang.serialization.codecs.RecordCodecBuilder;
|
| 5 | import java.util.ArrayList;
|
| 6 | import java.util.List;
|
| 7 | import java.util.Optional;
|
| 8 | import net.minecraft.network.chat.Component;
|
| 9 | import net.minecraft.server.jsonrpc.api.PlayerDto;
|
| 10 | import net.minecraft.server.jsonrpc.internalapi.MinecraftApi;
|
| 11 | import net.minecraft.server.level.ServerPlayer;
|
| 12 | import org.jspecify.annotations.Nullable;
|
| 13 |
|
| 14 | public class PlayerService {
|
| 15 | private static final Component DEFAULT_KICK_MESSAGE = Component.translatable("multiplayer.disconnect.kicked");
|
| 16 |
|
| 17 | public static List<PlayerDto> get(final MinecraftApi minecraftApi) {
|
| 18 | return minecraftApi.playerListService().getPlayers().stream().map(PlayerDto::from).toList();
|
| 19 | }
|
| 20 |
|
| 21 | public static List<PlayerDto> kick(final MinecraftApi minecraftApi, final List<PlayerService.KickDto> kick, final ClientInfo clientInfo) {
|
| 22 | List<PlayerDto> kicked = new ArrayList<>();
|
| 23 |
|
| 24 | for (PlayerService.KickDto kickDto : kick) {
|
| 25 | ServerPlayer serverPlayer = getServerPlayer(minecraftApi, kickDto.player());
|
| 26 | if (serverPlayer != null) {
|
| 27 | minecraftApi.playerListService().remove(serverPlayer, clientInfo);
|
| 28 | serverPlayer.connection.disconnect(kickDto.message.flatMap(Message::asComponent).orElse(DEFAULT_KICK_MESSAGE));
|
| 29 | kicked.add(kickDto.player());
|
| 30 | }
|
| 31 | }
|
| 32 |
|
| 33 | return kicked;
|
| 34 | }
|
| 35 |
|
| 36 | private static @Nullable ServerPlayer getServerPlayer(final MinecraftApi minecraftApi, final PlayerDto playerDto) {
|
| 37 | if (playerDto.id().isPresent()) {
|
| 38 | return minecraftApi.playerListService().getPlayer(playerDto.id().get());
|
| 39 | } else {
|
| 40 | return playerDto.name().isPresent() ? minecraftApi.playerListService().getPlayerByName(playerDto.name().get()) : null;
|
| 41 | }
|
| 42 | }
|
| 43 |
|
| 44 | public record KickDto(PlayerDto player, Optional<Message> message) {
|
| 45 | public static final MapCodec<PlayerService.KickDto> CODEC = RecordCodecBuilder.mapCodec(
|
| 46 | i -> i.group(
|
| 47 | PlayerDto.CODEC.codec().fieldOf("player").forGetter(PlayerService.KickDto::player),
|
| 48 | Message.CODEC.optionalFieldOf("message").forGetter(PlayerService.KickDto::message)
|
| 49 | )
|
| 50 | .apply(i, PlayerService.KickDto::new)
|
| 51 | );
|
| 52 | }
|
| 53 | }
|
| 54 |
|