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        Location location = player.getLocation();
074        final Plot plot = location.getPlotAbs();
075        if (plot == null) {
076            player.sendMessage(TranslatableCaption.of("errors.not_in_plot"));
077            return false;
078        }
079        if (!plot.hasOwner()) {
080            player.sendMessage(TranslatableCaption.of("info.plot_unowned"));
081            return false;
082        }
083        if (!plot.isOwner(player.getUUID()) && !player.hasPermission(Permission.PERMISSION_ADMIN_COMMAND_DENY)) {
084            player.sendMessage(TranslatableCaption.of("permission.no_plot_perms"));
085            return true;
086        }
087
088        int maxDenySize = player.hasPermissionRange(Permission.PERMISSION_DENY, Settings.Limit.MAX_PLOTS);
089        int size = plot.getDenied().size();
090        if (size >= maxDenySize) {
091            player.sendMessage(
092                    TranslatableCaption.of("members.plot_max_members_denied"),
093                    TagResolver.resolver("amount", Tag.inserting(Component.text(size)))
094            );
095            return false;
096        }
097
098        PlayerManager.getUUIDsFromString(args[0], (uuids, throwable) -> {
099            if (throwable instanceof TimeoutException) {
100                player.sendMessage(TranslatableCaption.of("players.fetching_players_timeout"));
101            } else if (throwable != null || uuids.isEmpty()) {
102                player.sendMessage(
103                        TranslatableCaption.of("errors.invalid_player"),
104                        TagResolver.resolver("value", Tag.inserting(Component.text(args[0])))
105                );
106            } else {
107                for (UUID uuid : uuids) {
108                    if (uuid == DBFunc.EVERYONE && !(
109                            player.hasPermission(Permission.PERMISSION_DENY_EVERYONE) || player.hasPermission(Permission.PERMISSION_ADMIN_COMMAND_DENY))) {
110                        player.sendMessage(
111                                TranslatableCaption.of("errors.invalid_player"),
112                                TagResolver.resolver("value", Tag.inserting(Component.text(args[0])))
113                        );
114                    } else if (plot.isOwner(uuid)) {
115                        player.sendMessage(TranslatableCaption.of("deny.cant_remove_owner"));
116                        return;
117                    } else if (plot.getDenied().contains(uuid)) {
118                        player.sendMessage(
119                                TranslatableCaption.of("member.already_added"),
120                                PlotSquared.platform().playerManager().getUsernameCaption(uuid)
121                                        .thenApply(caption -> TagResolver.resolver(
122                                        "player",
123                                        Tag.inserting(caption.toComponent(player))
124                                ))
125                        );
126                        return;
127                    } else {
128                        if (uuid != DBFunc.EVERYONE) {
129                            plot.removeMember(uuid);
130                            plot.removeTrusted(uuid);
131                        }
132                        plot.addDenied(uuid);
133                        this.eventDispatcher.callDenied(player, plot, uuid, true);
134                        if (!uuid.equals(DBFunc.EVERYONE)) {
135                            handleKick(PlotSquared.platform().playerManager().getPlayerIfExists(uuid), plot);
136                        } else {
137                            for (PlotPlayer<?> plotPlayer : plot.getPlayersInPlot()) {
138                                // Ignore plot-owners
139                                if (plot.isAdded(plotPlayer.getUUID())) {
140                                    continue;
141                                }
142                                handleKick(plotPlayer, plot);
143                            }
144                        }
145                    }
146                }
147                player.sendMessage(TranslatableCaption.of("deny.denied_added"));
148            }
149        });
150
151        return true;
152    }
153
154    @Override
155    public Collection<Command> tab(final PlotPlayer<?> player, final String[] args, final boolean space) {
156        return TabCompletions.completePlayers(player, String.join(",", args).trim(), Collections.emptyList());
157    }
158
159    private void handleKick(PlotPlayer<?> player, Plot plot) {
160        plot = plot.getBasePlot(false);
161        if (player == null) {
162            return;
163        }
164        if (!plot.equals(player.getCurrentPlot())) {
165            return;
166        }
167        if (player.hasPermission("plots.admin.entry.denied")) {
168            return;
169        }
170        if (player.getGameMode() == GameModes.SPECTATOR) {
171            player.stopSpectating();
172        }
173        Location location = player.getLocation();
174        Location spawn = this.worldUtil.getSpawn(location.getWorldName());
175        player.sendMessage(TranslatableCaption.of("deny.you_got_denied"));
176        if (plot.equals(spawn.getPlot())) {
177            Location newSpawn = this.worldUtil.getSpawn(this.plotAreaManager.getAllWorlds()[0]);
178            if (plot.equals(newSpawn.getPlot())) {
179                // Kick from server if you can't be teleported to spawn
180                // Use string based message here for legacy uses
181                player.kick("You got kicked from the plot! This server did not set up a loaded spawn, so you got " +
182                        "kicked from the server.");
183            } else {
184                player.teleport(newSpawn, TeleportCause.DENIED);
185            }
186        } else {
187            player.teleport(spawn, TeleportCause.DENIED);
188        }
189    }
190
191}