001/*
002 * PlotSquared, a land and world management plugin for Minecraft.
003 * Copyright (C) IntellectualSites <https://intellectualsites.com>
004 * Copyright (C) IntellectualSites team and contributors
005 *
006 * This program is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU General Public License for more details.
015 *
016 * You should have received a copy of the GNU General Public License
017 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
018 */
019package com.plotsquared.core.command;
020
021import com.google.inject.Inject;
022import com.plotsquared.core.PlotSquared;
023import com.plotsquared.core.configuration.Settings;
024import com.plotsquared.core.configuration.caption.TranslatableCaption;
025import com.plotsquared.core.database.DBFunc;
026import com.plotsquared.core.events.TeleportCause;
027import com.plotsquared.core.location.Location;
028import com.plotsquared.core.permissions.Permission;
029import com.plotsquared.core.player.PlotPlayer;
030import com.plotsquared.core.plot.Plot;
031import com.plotsquared.core.plot.world.PlotAreaManager;
032import com.plotsquared.core.util.EventDispatcher;
033import com.plotsquared.core.util.PlayerManager;
034import com.plotsquared.core.util.TabCompletions;
035import com.plotsquared.core.util.WorldUtil;
036import com.sk89q.worldedit.world.gamemode.GameModes;
037import net.kyori.adventure.text.Component;
038import net.kyori.adventure.text.minimessage.tag.Tag;
039import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver;
040import org.checkerframework.checker.nullness.qual.NonNull;
041
042import java.util.Collection;
043import java.util.Collections;
044import java.util.UUID;
045import java.util.concurrent.TimeoutException;
046
047@CommandDeclaration(command = "deny",
048        aliases = {"d", "ban"},
049        usage = "/plot deny <player>",
050        category = CommandCategory.SETTINGS,
051        requiredType = RequiredType.PLAYER)
052public class Deny extends SubCommand {
053
054    private final PlotAreaManager plotAreaManager;
055    private final EventDispatcher eventDispatcher;
056    private final WorldUtil worldUtil;
057
058    @Inject
059    public Deny(
060            final @NonNull PlotAreaManager plotAreaManager,
061            final @NonNull EventDispatcher eventDispatcher,
062            final @NonNull WorldUtil worldUtil
063    ) {
064        super(Argument.PlayerName);
065        this.plotAreaManager = plotAreaManager;
066        this.eventDispatcher = eventDispatcher;
067        this.worldUtil = worldUtil;
068    }
069
070    @Override
071    public boolean onCommand(PlotPlayer<?> player, String[] args) {
072
073        final Plot plot = player.getCurrentPlot();
074        if (plot == null) {
075            player.sendMessage(TranslatableCaption.of("errors.not_in_plot"));
076            return false;
077        }
078        if (!plot.hasOwner()) {
079            player.sendMessage(TranslatableCaption.of("info.plot_unowned"));
080            return false;
081        }
082        if (!plot.isOwner(player.getUUID()) && !player.hasPermission(Permission.PERMISSION_ADMIN_COMMAND_DENY)) {
083            player.sendMessage(TranslatableCaption.of("permission.no_plot_perms"));
084            return true;
085        }
086
087        int maxDenySize = player.hasPermissionRange(Permission.PERMISSION_DENY, Settings.Limit.MAX_PLOTS);
088        int size = plot.getDenied().size();
089        if (size >= maxDenySize) {
090            player.sendMessage(
091                    TranslatableCaption.of("members.plot_max_members_denied"),
092                    TagResolver.resolver("amount", Tag.inserting(Component.text(size)))
093            );
094            return false;
095        }
096
097        PlayerManager.getUUIDsFromString(args[0], (uuids, throwable) -> {
098            if (throwable instanceof TimeoutException) {
099                player.sendMessage(TranslatableCaption.of("players.fetching_players_timeout"));
100            } else if (throwable != null || uuids.isEmpty()) {
101                player.sendMessage(
102                        TranslatableCaption.of("errors.invalid_player"),
103                        TagResolver.resolver("value", Tag.inserting(Component.text(args[0])))
104                );
105            } else {
106                for (UUID uuid : uuids) {
107                    if (uuid == DBFunc.EVERYONE && !(
108                            player.hasPermission(Permission.PERMISSION_DENY_EVERYONE) || player.hasPermission(Permission.PERMISSION_ADMIN_COMMAND_DENY))) {
109                        player.sendMessage(
110                                TranslatableCaption.of("errors.invalid_player"),
111                                TagResolver.resolver("value", Tag.inserting(Component.text(args[0])))
112                        );
113                    } else if (plot.isOwner(uuid)) {
114                        player.sendMessage(TranslatableCaption.of("deny.cant_remove_owner"));
115                        return;
116                    } else if (plot.getDenied().contains(uuid)) {
117                        player.sendMessage(
118                                TranslatableCaption.of("member.already_added"),
119                                PlotSquared.platform().playerManager().getUsernameCaption(uuid)
120                                        .thenApply(caption -> TagResolver.resolver(
121                                        "player",
122                                        Tag.inserting(caption.toComponent(player))
123                                ))
124                        );
125                        return;
126                    } else {
127                        if (uuid != DBFunc.EVERYONE) {
128                            plot.removeMember(uuid);
129                            plot.removeTrusted(uuid);
130                        }
131                        plot.addDenied(uuid);
132                        this.eventDispatcher.callDenied(player, plot, uuid, true);
133                        if (!uuid.equals(DBFunc.EVERYONE)) {
134                            handleKick(PlotSquared.platform().playerManager().getPlayerIfExists(uuid), plot);
135                        } else {
136                            for (PlotPlayer<?> plotPlayer : plot.getPlayersInPlot()) {
137                                // Ignore plot-owners
138                                if (plot.isAdded(plotPlayer.getUUID())) {
139                                    continue;
140                                }
141                                handleKick(plotPlayer, plot);
142                            }
143                        }
144                    }
145                }
146                player.sendMessage(TranslatableCaption.of("deny.denied_added"));
147            }
148        });
149
150        return true;
151    }
152
153    @Override
154    public Collection<Command> tab(final PlotPlayer<?> player, final String[] args, final boolean space) {
155        return TabCompletions.completePlayers(player, String.join(",", args).trim(), Collections.emptyList());
156    }
157
158    private void handleKick(PlotPlayer<?> player, Plot plot) {
159        plot = plot.getBasePlot(false);
160        if (player == null) {
161            return;
162        }
163        if (!plot.equals(player.getCurrentPlot())) {
164            return;
165        }
166        if (player.hasPermission("plots.admin.entry.denied")) {
167            return;
168        }
169        if (player.getGameMode() == GameModes.SPECTATOR) {
170            player.stopSpectating();
171        }
172        Location location = player.getLocation();
173        Location spawn = this.worldUtil.getSpawn(location.getWorldName());
174        player.sendMessage(TranslatableCaption.of("deny.you_got_denied"));
175        if (plot.equals(spawn.getPlot())) {
176            Location newSpawn = this.worldUtil.getSpawn(this.plotAreaManager.getAllWorlds()[0]);
177            if (plot.equals(newSpawn.getPlot())) {
178                // Kick from server if you can't be teleported to spawn
179                // Use string based message here for legacy uses
180                player.kick("You got kicked from the plot! This server did not set up a loaded spawn, so you got " +
181                        "kicked from the server.");
182            } else {
183                player.teleport(newSpawn, TeleportCause.DENIED);
184            }
185        } else {
186            player.teleport(spawn, TeleportCause.DENIED);
187        }
188    }
189
190}