Search in sources :

Example 1 with BanService

use of org.spongepowered.api.service.ban.BanService in project LanternServer by LanternPowered.

the class LanternUserStorageService method getFromBanService.

/**
 * Attempts to get a {@link User} from the {@link BanService}.
 *
 * @param uniqueId The unique id
 * @return The user
 */
@Nullable
private ProxyUser getFromBanService(UUID uniqueId) {
    final LanternGameProfile gameProfile;
    final BanService banService = this.banService.get();
    if (banService instanceof BanConfig) {
        gameProfile = ((BanConfig) banService).getEntryByUUID(uniqueId).map(entry -> ((BanEntry.Profile) entry).getProfile()).orElse(null);
    } else {
        gameProfile = banService.getBanFor(new LanternGameProfile(uniqueId, null)).map(entry -> ((BanEntry.Profile) entry).getProfile()).orElse(null);
    }
    return gameProfile == null ? null : new ProxyUser(gameProfile);
}
Also used : LanternGameProfile(org.lanternpowered.server.profile.LanternGameProfile) BanConfig(org.lanternpowered.server.config.user.ban.BanConfig) ProxyUser(org.lanternpowered.server.entity.living.player.ProxyUser) BanService(org.spongepowered.api.service.ban.BanService) BanEntry(org.lanternpowered.server.config.user.ban.BanEntry) Nullable(javax.annotation.Nullable)

Example 2 with BanService

use of org.spongepowered.api.service.ban.BanService in project LanternServer by LanternPowered.

the class CommandListBans method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(GenericArguments.optional(new CommandElement(Text.of("ips")) {

        private final List<String> choices = Arrays.asList("ips", "players");

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            return args.next();
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            final String start = args.nextIfPresent().orElse("").toLowerCase();
            return this.choices.stream().filter(new StartsWithPredicate(start)).collect(Collectors.toList());
        }
    })).executor((src, args) -> {
        final boolean showIpBans = "ips".equalsIgnoreCase(args.<String>getOne("ips").orElse(null));
        final BanService banService = Lantern.getGame().getServiceManager().provideUnchecked(BanService.class);
        List<String> entries;
        if (showIpBans) {
            entries = banService.getIpBans().stream().map(ban -> ban.getAddress().getHostAddress()).collect(Collectors.toList());
            src.sendMessage(t("commands.banlist.ips", entries.size()));
        } else {
            entries = banService.getProfileBans().stream().map(ban -> ban.getProfile().getName().orElse(ban.getProfile().getUniqueId().toString())).collect(Collectors.toList());
            src.sendMessage(t("commands.banlist.players", entries.size()));
        }
        src.sendMessage(Text.of(Joiner.on(", ").join(entries)));
        return CommandResult.success();
    });
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandContext(org.spongepowered.api.command.args.CommandContext) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandSource(org.spongepowered.api.command.CommandSource) CommandElement(org.spongepowered.api.command.args.CommandElement) List(java.util.List) BanService(org.spongepowered.api.service.ban.BanService) Nullable(javax.annotation.Nullable)

Example 3 with BanService

use of org.spongepowered.api.service.ban.BanService in project LanternServer by LanternPowered.

the class LanternPlayer method handleDeath.

@Override
protected void handleDeath(CauseStack causeStack) {
    // Call the harvest event
    final boolean keepsInventory = getWorld().getOrCreateRule(RuleTypes.KEEP_INVENTORY).getValue();
    final int exp = keepsInventory ? 0 : Math.min(100, get(Keys.EXPERIENCE_LEVEL).orElse(0) * 7);
    // Humanoids get their own sub-interface for the event
    final HarvestEntityEvent.TargetPlayer harvestEvent = SpongeEventFactory.createHarvestEntityEventTargetPlayer(causeStack.getCurrentCause(), exp, exp, this, keepsInventory, keepsInventory, 0);
    Sponge.getEventManager().post(harvestEvent);
    if (!harvestEvent.isCancelled()) {
        final List<ItemStackSnapshot> drops = new ArrayList<>();
        if (!harvestEvent.keepsInventory()) {
            // Make a copy of all the items in the players inventory, and put them in the drops
            getInventory().<AbstractSlot>slots().forEach(slot -> slot.peek().ifPresent(itemStack -> drops.add(LanternItemStackSnapshot.wrap(itemStack))));
        }
        if (!harvestEvent.keepsLevel()) {
            offer(Keys.EXPERIENCE_LEVEL, harvestEvent.getLevel());
        }
        // Finalize the harvest event
        finalizeHarvestEvent(causeStack, harvestEvent, drops);
    }
    // Ban the player if the world is hardcode
    if (getWorld().getProperties().isHardcore()) {
        final BanService banService = Sponge.getServiceManager().provideUnchecked(BanService.class);
        // Add a permanent ban
        banService.addBan(Ban.of(getProfile(), t("gameMode.hardcore.banMessage")));
        // Bye, bye!
        kick(t("deathScreen.title.hardcore"));
    }
}
Also used : LanternPlayerAdvancements(org.lanternpowered.server.advancement.LanternPlayerAdvancements) LanternPlayerInventory(org.lanternpowered.server.inventory.vanilla.LanternPlayerInventory) LanternItemStackSnapshot(org.lanternpowered.server.inventory.LanternItemStackSnapshot) WorldConfig(org.lanternpowered.server.config.world.WorldConfig) ValueCollection(org.lanternpowered.server.data.ValueCollection) SoundCategory(org.spongepowered.api.effect.sound.SoundCategory) BookView(org.spongepowered.api.text.BookView) ItemStack(org.spongepowered.api.item.inventory.ItemStack) BlockRegistryModule(org.lanternpowered.server.game.registry.type.block.BlockRegistryModule) VanillaInventoryArchetypes(org.lanternpowered.server.inventory.vanilla.VanillaInventoryArchetypes) GameProfile(org.spongepowered.api.profile.GameProfile) LanternSoundType(org.lanternpowered.server.effect.sound.LanternSoundType) AdvancementProgress(org.spongepowered.api.advancement.AdvancementProgress) MessagePlayOutParticleEffect(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutParticleEffect) EnumSet(java.util.EnumSet) GlobalTabListEntry(org.lanternpowered.server.entity.living.player.tab.GlobalTabListEntry) MessagePlayOutSetReducedDebug(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSetReducedDebug) LanternBossBar(org.lanternpowered.server.boss.LanternBossBar) Location(org.spongepowered.api.world.Location) AbstractViewer(org.lanternpowered.server.effect.AbstractViewer) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) LanternWeatherUniverse(org.lanternpowered.server.world.LanternWeatherUniverse) DataContainer(org.spongepowered.api.data.DataContainer) Set(java.util.Set) WorldBorder(org.spongepowered.api.world.WorldBorder) BlockState(org.spongepowered.api.block.BlockState) MessageChannelEvent(org.spongepowered.api.event.message.MessageChannelEvent) World(org.spongepowered.api.world.World) MessagePlayOutRecord(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutRecord) HandTypes(org.spongepowered.api.data.type.HandTypes) AbstractOrderedInventory(org.lanternpowered.server.inventory.AbstractOrderedInventory) Player(org.spongepowered.api.entity.living.player.Player) RespawnPlayerEvent(org.spongepowered.api.event.entity.living.humanoid.player.RespawnPlayerEvent) MessagePlayInOutBrand(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayInOutBrand) ChangeWorldBorderEvent(org.spongepowered.api.event.world.ChangeWorldBorderEvent) LanternKeys(org.lanternpowered.server.data.key.LanternKeys) ItemTypes(org.spongepowered.api.item.ItemTypes) GuiIdProperty(org.spongepowered.api.item.inventory.property.GuiIdProperty) Vector3d(com.flowpowered.math.vector.Vector3d) LanternCooldownTracker(org.lanternpowered.server.item.LanternCooldownTracker) AABB(org.spongepowered.api.util.AABB) LanternDifficulty(org.lanternpowered.server.world.difficulty.LanternDifficulty) ArrayList(java.util.ArrayList) Vector2i(com.flowpowered.math.vector.Vector2i) SpectateEntityEvent(org.lanternpowered.server.entity.event.SpectateEntityEvent) LanternTabListEntryBuilder(org.lanternpowered.server.entity.living.player.tab.LanternTabListEntryBuilder) LanternTitles(org.lanternpowered.server.text.title.LanternTitles) LanternTabList(org.lanternpowered.server.entity.living.player.tab.LanternTabList) CauseStack(org.lanternpowered.server.event.CauseStack) Text(org.spongepowered.api.text.Text) PlayerInventoryContainer(org.lanternpowered.server.inventory.PlayerInventoryContainer) LanternWorld(org.lanternpowered.server.world.LanternWorld) GlobalTabList(org.lanternpowered.server.entity.living.player.tab.GlobalTabList) LanternTabListEntry(org.lanternpowered.server.entity.living.player.tab.LanternTabListEntry) DimensionTypes(org.spongepowered.api.world.DimensionTypes) Nullable(javax.annotation.Nullable) MessagePlayOutPlayerRespawn(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutPlayerRespawn) MessagePlayOutStopSounds(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutStopSounds) WrittenBookItemTypeObjectSerializer(org.lanternpowered.server.data.io.store.item.WrittenBookItemTypeObjectSerializer) MessagePlayOutBlockChange(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutBlockChange) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) MessagePlayOutOpenBook(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutOpenBook) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) Entity(org.spongepowered.api.entity.Entity) LanternGameMode(org.lanternpowered.server.entity.living.player.gamemode.LanternGameMode) DataView(org.spongepowered.api.data.DataView) MessagePlayOutUnlockRecipes(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutUnlockRecipes) Vector3i(com.flowpowered.math.vector.Vector3i) ChatVisibilities(org.spongepowered.api.text.chat.ChatVisibilities) ChatVisibility(org.spongepowered.api.text.chat.ChatVisibility) MessageEvent(org.spongepowered.api.event.message.MessageEvent) AdvancementTree(org.spongepowered.api.advancement.AdvancementTree) BanService(org.spongepowered.api.service.ban.BanService) EventContextKeys(org.spongepowered.api.event.cause.EventContextKeys) NetworkIdHolder(org.lanternpowered.server.network.entity.NetworkIdHolder) ChunkTicketManager(org.spongepowered.api.world.ChunkTicketManager) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) Ban(org.spongepowered.api.util.ban.Ban) ChatType(org.spongepowered.api.text.chat.ChatType) RawItemStack(org.lanternpowered.server.network.objects.RawItemStack) UserStorageService(org.spongepowered.api.service.user.UserStorageService) ParticleEffect(org.spongepowered.api.effect.particle.ParticleEffect) ElementKeyRegistration(org.lanternpowered.server.data.element.ElementKeyRegistration) MessagePlayOutSetWindowSlot(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSetWindowSlot) Locale(java.util.Locale) RuleTypes(org.lanternpowered.server.world.rules.RuleTypes) Title(org.spongepowered.api.text.title.Title) AbstractSlot(org.lanternpowered.server.inventory.AbstractSlot) SoundType(org.spongepowered.api.effect.sound.SoundType) Collection(java.util.Collection) ChunkLoadingTicket(org.lanternpowered.server.world.chunk.ChunkLoadingTicket) Sponge(org.spongepowered.api.Sponge) ResourcePack(org.spongepowered.api.resourcepack.ResourcePack) Sets(com.google.common.collect.Sets) Cause(org.spongepowered.api.event.cause.Cause) List(java.util.List) Lantern(org.lanternpowered.server.game.Lantern) Transform(org.spongepowered.api.entity.Transform) MessagePlayOutPlayerJoinGame(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutPlayerJoinGame) RelativePositions(org.spongepowered.api.util.RelativePositions) Optional(java.util.Optional) RecordType(org.spongepowered.api.effect.sound.record.RecordType) MessagePlayOutPlayerPositionAndLook(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutPlayerPositionAndLook) HarvestEntityEvent(org.spongepowered.api.event.entity.HarvestEntityEvent) IntArrayList(it.unimi.dsi.fastutil.ints.IntArrayList) LanternChatType(org.lanternpowered.server.text.chat.LanternChatType) Inventory(org.spongepowered.api.item.inventory.Inventory) ChatTypes(org.spongepowered.api.text.chat.ChatTypes) Keys(org.spongepowered.api.data.key.Keys) PlayerContainerSession(org.lanternpowered.server.inventory.PlayerContainerSession) HashSet(java.util.HashSet) LanternContainer(org.lanternpowered.server.inventory.LanternContainer) NetworkSession(org.lanternpowered.server.network.NetworkSession) SkinPart(org.spongepowered.api.data.type.SkinPart) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) LanternGameProfile(org.lanternpowered.server.profile.LanternGameProfile) Container(org.spongepowered.api.item.inventory.Container) MessagePlayOutSelectAdvancementTree(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSelectAdvancementTree) LanternDimensionType(org.lanternpowered.server.world.dimension.LanternDimensionType) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) Advancement(org.spongepowered.api.advancement.Advancement) EquipmentTypes(org.spongepowered.api.item.inventory.equipment.EquipmentTypes) Collections(java.util.Collections) LanternScoreboard(org.lanternpowered.server.scoreboard.LanternScoreboard) PlayerInventoryShiftClickBehavior(org.lanternpowered.server.inventory.vanilla.PlayerInventoryShiftClickBehavior) LanternWorldBorder(org.lanternpowered.server.world.LanternWorldBorder) HarvestEntityEvent(org.spongepowered.api.event.entity.HarvestEntityEvent) ArrayList(java.util.ArrayList) IntArrayList(it.unimi.dsi.fastutil.ints.IntArrayList) LanternItemStackSnapshot(org.lanternpowered.server.inventory.LanternItemStackSnapshot) ItemStackSnapshot(org.spongepowered.api.item.inventory.ItemStackSnapshot) BanService(org.spongepowered.api.service.ban.BanService)

Example 4 with BanService

use of org.spongepowered.api.service.ban.BanService 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 5 with BanService

use of org.spongepowered.api.service.ban.BanService in project Nucleus by NucleusPowered.

the class TempBanCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    User u = args.<User>getOne(user).get();
    Long time = args.<Long>getOne(duration).get();
    String reason = args.<String>getOne(reasonKey).orElse(plugin.getMessageProvider().getMessageWithFormat("ban.defaultreason"));
    if (permissions.testSuffix(u, "exempt.target", src, false)) {
        throw new ReturnMessageException(plugin.getMessageProvider().getTextMessageWithFormat("command.tempban.exempt", u.getName()));
    }
    if (!u.isOnline() && !permissions.testSuffix(src, "offline")) {
        throw new ReturnMessageException(plugin.getMessageProvider().getTextMessageWithFormat("command.tempban.offline.noperms"));
    }
    if (time > banConfig.getMaximumTempBanLength() && banConfig.getMaximumTempBanLength() != -1 && !permissions.testSuffix(src, "exempt.length")) {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.tempban.length.toolong", Util.getTimeStringFromSeconds(this.banConfig.getMaximumTempBanLength())));
        return CommandResult.success();
    }
    BanService service = Sponge.getServiceManager().provideUnchecked(BanService.class);
    if (service.isBanned(u.getProfile())) {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.ban.alreadyset", u.getName()));
        return CommandResult.empty();
    }
    // Expiration date
    Instant date = Instant.now().plus(time, ChronoUnit.SECONDS);
    // Create the ban.
    Ban bp = Ban.builder().type(BanTypes.PROFILE).profile(u.getProfile()).source(src).expirationDate(date).reason(TextSerializers.FORMATTING_CODE.deserialize(reason)).build();
    service.addBan(bp);
    MutableMessageChannel send = new PermissionMessageChannel(BanCommand.notifyPermission).asMutable();
    send.addMember(src);
    send.send(plugin.getMessageProvider().getTextMessageWithFormat("command.tempban.applied", u.getName(), Util.getTimeStringFromSeconds(time), src.getName()));
    send.send(plugin.getMessageProvider().getTextMessageWithFormat("standard.reasoncoloured", reason));
    if (Sponge.getServer().getPlayer(u.getUniqueId()).isPresent()) {
        Sponge.getServer().getPlayer(u.getUniqueId()).get().kick(TextSerializers.FORMATTING_CODE.deserialize(reason));
    }
    return CommandResult.success();
}
Also used : PermissionMessageChannel(io.github.nucleuspowered.nucleus.util.PermissionMessageChannel) User(org.spongepowered.api.entity.living.player.User) Instant(java.time.Instant) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) BanService(org.spongepowered.api.service.ban.BanService) Ban(org.spongepowered.api.util.ban.Ban) MutableMessageChannel(org.spongepowered.api.text.channel.MutableMessageChannel)

Aggregations

BanService (org.spongepowered.api.service.ban.BanService)12 Ban (org.spongepowered.api.util.ban.Ban)6 GameProfile (org.spongepowered.api.profile.GameProfile)4 PermissionMessageChannel (io.github.nucleuspowered.nucleus.util.PermissionMessageChannel)3 List (java.util.List)3 Nullable (javax.annotation.Nullable)3 LanternGameProfile (org.lanternpowered.server.profile.LanternGameProfile)3 Text (org.spongepowered.api.text.Text)3 MutableMessageChannel (org.spongepowered.api.text.channel.MutableMessageChannel)3 Vector3d (com.flowpowered.math.vector.Vector3d)2 InetAddress (java.net.InetAddress)2 UnknownHostException (java.net.UnknownHostException)2 Instant (java.time.Instant)2 Optional (java.util.Optional)2 WorldConfig (org.lanternpowered.server.config.world.WorldConfig)2 LanternWorld (org.lanternpowered.server.world.LanternWorld)2 CommandException (org.spongepowered.api.command.CommandException)2 Cause (org.spongepowered.api.event.cause.Cause)2 MessageEvent (org.spongepowered.api.event.message.MessageEvent)2 MessageChannel (org.spongepowered.api.text.channel.MessageChannel)2