Search in sources :

Example 1 with PlotCluster

use of com.plotsquared.core.plot.PlotCluster in project PlotSquared by IntellectualSites.

the class SQLManager method sendBatch.

public boolean sendBatch() {
    try {
        if (!getGlobalTasks().isEmpty()) {
            if (this.connection.getAutoCommit()) {
                this.connection.setAutoCommit(false);
            }
            Runnable task = getGlobalTasks().remove();
            if (task != null) {
                try {
                    task.run();
                } catch (Throwable e) {
                    LOGGER.error("============ DATABASE ERROR ============");
                    LOGGER.error("============ DATABASE ERROR ============");
                    LOGGER.error("There was an error updating the database.");
                    LOGGER.error(" - It will be corrected on shutdown");
                    e.printStackTrace();
                    LOGGER.error("========================================");
                }
            }
            commit();
            return true;
        }
        int count = -1;
        if (!this.plotTasks.isEmpty()) {
            count = Math.max(count, 0);
            if (this.connection.getAutoCommit()) {
                this.connection.setAutoCommit(false);
            }
            String method = null;
            PreparedStatement statement = null;
            UniqueStatement task = null;
            UniqueStatement lastTask = null;
            Iterator<Entry<Plot, Queue<UniqueStatement>>> iterator = this.plotTasks.entrySet().iterator();
            while (iterator.hasNext()) {
                try {
                    Entry<Plot, Queue<UniqueStatement>> entry = iterator.next();
                    Queue<UniqueStatement> tasks = entry.getValue();
                    if (tasks.isEmpty()) {
                        iterator.remove();
                        continue;
                    }
                    task = tasks.remove();
                    count++;
                    if (task != null) {
                        if (task.method == null || !task.method.equals(method) || statement == null) {
                            if (statement != null) {
                                lastTask.execute(statement);
                                statement.close();
                            }
                            method = task.method;
                            statement = task.get();
                        }
                        task.set(statement);
                        task.addBatch(statement);
                        try {
                            if (statement.isClosed()) {
                                statement = null;
                            }
                        } catch (NullPointerException | AbstractMethodError ignore) {
                        }
                    }
                    lastTask = task;
                } catch (Throwable e) {
                    LOGGER.error("============ DATABASE ERROR ============");
                    LOGGER.error("There was an error updating the database.");
                    LOGGER.error(" - It will be corrected on shutdown");
                    LOGGER.error("========================================");
                    e.printStackTrace();
                    LOGGER.error("========================================");
                }
            }
            if (statement != null && task != null) {
                task.execute(statement);
                statement.close();
            }
        }
        if (!this.playerTasks.isEmpty()) {
            count = Math.max(count, 0);
            if (this.connection.getAutoCommit()) {
                this.connection.setAutoCommit(false);
            }
            String method = null;
            PreparedStatement statement = null;
            UniqueStatement task = null;
            UniqueStatement lastTask = null;
            for (Entry<UUID, Queue<UniqueStatement>> entry : this.playerTasks.entrySet()) {
                try {
                    UUID uuid = entry.getKey();
                    if (this.playerTasks.get(uuid).isEmpty()) {
                        this.playerTasks.remove(uuid);
                        continue;
                    }
                    task = this.playerTasks.get(uuid).remove();
                    count++;
                    if (task != null) {
                        if (task.method == null || !task.method.equals(method)) {
                            if (statement != null) {
                                lastTask.execute(statement);
                                statement.close();
                            }
                            method = task.method;
                            statement = task.get();
                        }
                        task.set(statement);
                        task.addBatch(statement);
                    }
                    lastTask = task;
                } catch (Throwable e) {
                    LOGGER.error("============ DATABASE ERROR ============");
                    LOGGER.error("There was an error updating the database.");
                    LOGGER.error(" - It will be corrected on shutdown");
                    LOGGER.error("========================================");
                    e.printStackTrace();
                    LOGGER.error("========================================");
                }
            }
            if (statement != null && task != null) {
                task.execute(statement);
                statement.close();
            }
        }
        if (!this.clusterTasks.isEmpty()) {
            count = Math.max(count, 0);
            if (this.connection.getAutoCommit()) {
                this.connection.setAutoCommit(false);
            }
            String method = null;
            PreparedStatement statement = null;
            UniqueStatement task = null;
            UniqueStatement lastTask = null;
            for (Entry<PlotCluster, Queue<UniqueStatement>> entry : this.clusterTasks.entrySet()) {
                try {
                    PlotCluster cluster = entry.getKey();
                    if (this.clusterTasks.get(cluster).isEmpty()) {
                        this.clusterTasks.remove(cluster);
                        continue;
                    }
                    task = this.clusterTasks.get(cluster).remove();
                    count++;
                    if (task != null) {
                        if (task.method == null || !task.method.equals(method)) {
                            if (statement != null) {
                                lastTask.execute(statement);
                                statement.close();
                            }
                            method = task.method;
                            statement = task.get();
                        }
                        task.set(statement);
                        task.addBatch(statement);
                    }
                    lastTask = task;
                } catch (Throwable e) {
                    LOGGER.error("============ DATABASE ERROR ============");
                    LOGGER.error("There was an error updating the database.");
                    LOGGER.error(" - It will be corrected on shutdown");
                    LOGGER.error("========================================");
                    e.printStackTrace();
                    LOGGER.error("========================================");
                }
            }
            if (statement != null && task != null) {
                task.execute(statement);
                statement.close();
            }
        }
        if (count > 0) {
            commit();
            return true;
        }
        if (count != -1) {
            if (!this.connection.getAutoCommit()) {
                this.connection.setAutoCommit(true);
            }
        }
        if (!this.clusterTasks.isEmpty()) {
            this.clusterTasks.clear();
        }
        if (!this.plotTasks.isEmpty()) {
            this.plotTasks.clear();
        }
    } catch (Throwable e) {
        LOGGER.error("============ DATABASE ERROR ============");
        LOGGER.error("There was an error updating the database.");
        LOGGER.error(" - It will be corrected on shutdown");
        LOGGER.error("========================================");
        e.printStackTrace();
        LOGGER.error("========================================");
    }
    return false;
}
Also used : PlotCluster(com.plotsquared.core.plot.PlotCluster) Plot(com.plotsquared.core.plot.Plot) PreparedStatement(java.sql.PreparedStatement) Entry(java.util.Map.Entry) UUID(java.util.UUID) Queue(java.util.Queue) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue)

Example 2 with PlotCluster

use of com.plotsquared.core.plot.PlotCluster in project PlotSquared by IntellectualSites.

the class SQLManager method getClusters.

@Override
public HashMap<String, Set<PlotCluster>> getClusters() {
    LinkedHashMap<String, Set<PlotCluster>> newClusters = new LinkedHashMap<>();
    HashMap<Integer, PlotCluster> clusters = new HashMap<>();
    try {
        HashSet<String> areas = new HashSet<>();
        if (this.worldConfiguration.contains("worlds")) {
            ConfigurationSection worldSection = this.worldConfiguration.getConfigurationSection("worlds");
            if (worldSection != null) {
                for (String worldKey : worldSection.getKeys(false)) {
                    areas.add(worldKey);
                    ConfigurationSection areaSection = worldSection.getConfigurationSection(worldKey + ".areas");
                    if (areaSection != null) {
                        for (String areaKey : areaSection.getKeys(false)) {
                            String[] split = areaKey.split("(?<![;])-");
                            if (split.length == 3) {
                                areas.add(worldKey + ';' + split[0]);
                            }
                        }
                    }
                }
            }
        }
        HashMap<String, UUID> uuids = new HashMap<>();
        HashMap<String, Integer> noExist = new HashMap<>();
        /*
             * Getting clusters
             */
        try (Statement stmt = this.connection.createStatement()) {
            ResultSet resultSet = stmt.executeQuery("SELECT * FROM `" + this.prefix + "cluster`");
            PlotCluster cluster;
            String owner;
            UUID user;
            int id;
            while (resultSet.next()) {
                PlotId pos1 = PlotId.of(resultSet.getInt("pos1_x"), resultSet.getInt("pos1_z"));
                PlotId pos2 = PlotId.of(resultSet.getInt("pos2_x"), resultSet.getInt("pos2_z"));
                id = resultSet.getInt("id");
                String areaid = resultSet.getString("world");
                if (!areas.contains(areaid)) {
                    noExist.merge(areaid, 1, Integer::sum);
                }
                owner = resultSet.getString("owner");
                user = uuids.get(owner);
                if (user == null) {
                    user = UUID.fromString(owner);
                    uuids.put(owner, user);
                }
                cluster = new PlotCluster(null, pos1, pos2, user, id);
                clusters.put(id, cluster);
                Set<PlotCluster> set = newClusters.computeIfAbsent(areaid, k -> new HashSet<>());
                set.add(cluster);
            }
            // Getting helpers
            resultSet = stmt.executeQuery("SELECT `user_uuid`, `cluster_id` FROM `" + this.prefix + "cluster_helpers`");
            while (resultSet.next()) {
                id = resultSet.getInt("cluster_id");
                owner = resultSet.getString("user_uuid");
                user = uuids.get(owner);
                if (user == null) {
                    user = UUID.fromString(owner);
                    uuids.put(owner, user);
                }
                cluster = clusters.get(id);
                if (cluster != null) {
                    cluster.helpers.add(user);
                } else {
                    LOGGER.warn("Cluster #{}({}) in cluster_helpers does not exist." + " Please create the cluster or remove this entry", id, cluster);
                }
            }
            // Getting invited
            resultSet = stmt.executeQuery("SELECT `user_uuid`, `cluster_id` FROM `" + this.prefix + "cluster_invited`");
            while (resultSet.next()) {
                id = resultSet.getInt("cluster_id");
                owner = resultSet.getString("user_uuid");
                user = uuids.get(owner);
                if (user == null) {
                    user = UUID.fromString(owner);
                    uuids.put(owner, user);
                }
                cluster = clusters.get(id);
                if (cluster != null) {
                    cluster.invited.add(user);
                } else {
                    LOGGER.warn("Cluster #{}({}) in cluster_helpers does not exist." + " Please create the cluster or remove this entry", id, cluster);
                }
            }
            resultSet = stmt.executeQuery("SELECT * FROM `" + this.prefix + "cluster_settings`");
            while (resultSet.next()) {
                id = resultSet.getInt("cluster_id");
                cluster = clusters.get(id);
                if (cluster != null) {
                    String alias = resultSet.getString("alias");
                    if (alias != null) {
                        cluster.settings.setAlias(alias);
                    }
                    String pos = resultSet.getString("position");
                    switch(pos.toLowerCase()) {
                        case "":
                        case "default":
                        case "0,0,0":
                        case "center":
                        case "centre":
                            break;
                        default:
                            try {
                                BlockLoc loc = BlockLoc.fromString(pos);
                                cluster.settings.setPosition(loc);
                            } catch (Exception ignored) {
                            }
                    }
                    int m = resultSet.getInt("merged");
                    boolean[] merged = new boolean[4];
                    for (int i = 0; i < 4; i++) {
                        merged[3 - i] = (m & 1 << i) != 0;
                    }
                    cluster.settings.setMerged(merged);
                } else {
                    LOGGER.warn("Cluster #{}({}) in cluster_helpers does not exist." + " Please create the cluster or remove this entry", id, cluster);
                }
            }
            resultSet.close();
        }
        boolean invalidPlot = false;
        for (Entry<String, Integer> entry : noExist.entrySet()) {
            String a = entry.getKey();
            invalidPlot = true;
            LOGGER.warn("Warning! Found {} clusters in DB for non existent area; '{}'", noExist.get(a), a);
        }
        if (invalidPlot) {
            LOGGER.warn("Warning! Please create the world(s) or remove the clusters using the purge command");
        }
    } catch (SQLException e) {
        LOGGER.error("Failed to load clusters", e);
    }
    return newClusters;
}
Also used : ResultSet(java.sql.ResultSet) Set(java.util.Set) HashSet(java.util.HashSet) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) SQLException(java.sql.SQLException) LinkedHashMap(java.util.LinkedHashMap) PlotId(com.plotsquared.core.plot.PlotId) ResultSet(java.sql.ResultSet) UUID(java.util.UUID) HashSet(java.util.HashSet) PlotCluster(com.plotsquared.core.plot.PlotCluster) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) BlockLoc(com.plotsquared.core.location.BlockLoc) ParseException(java.text.ParseException) FlagParseException(com.plotsquared.core.plot.flag.FlagParseException) SQLException(java.sql.SQLException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConfigurationSection(com.plotsquared.core.configuration.ConfigurationSection)

Example 3 with PlotCluster

use of com.plotsquared.core.plot.PlotCluster in project PlotSquared by IntellectualSites.

the class Cluster method onCommand.

@Override
public boolean onCommand(PlotPlayer<?> player, String[] args) {
    // list, create, delete, resize, invite, kick, leave, helpers, tp, sethome
    if (args.length == 0) {
        // return arguments
        player.sendMessage(TranslatableCaption.of("cluster.cluster_available_args"), Template.of("list", "<dark_aqua>list</dark_aqua><gray>, </gray><dark_aqua>create</dark_aqua><gray>, </gray><dark_aqua>delete</dark_aqua><gray>, </gray><dark_aqua>resize</dark_aqua><gray>, </gray><dark_aqua>invite</dark_aqua><gray>, </gray><dark_aqua>kick</dark_aqua><gray>, </gray><dark_aqua>leave</dark_aqua><gray>, </gray><dark_aqua>members</dark_aqua><gray>, </gray><dark_aqua>info</dark_aqua><gray>, </gray><dark_aqua>tp</dark_aqua><gray>, </gray><dark_aqua>sethome</dark_aqua>"));
        return false;
    }
    String sub = args[0].toLowerCase();
    switch(sub) {
        case "l":
        case "list":
            {
                if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_LIST)) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", String.valueOf(Permission.PERMISSION_CLUSTER_LIST)));
                    return false;
                }
                if (args.length != 1) {
                    player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster list"));
                    return false;
                }
                PlotArea area = player.getApplicablePlotArea();
                if (area == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
                    return false;
                }
                Set<PlotCluster> clusters = area.getClusters();
                player.sendMessage(TranslatableCaption.of("cluster.cluster_list_heading"), Template.of("amount", clusters.size() + ""));
                for (PlotCluster cluster : clusters) {
                    // Ignore unmanaged clusters
                    String name = "'" + cluster.getName() + "' : " + cluster;
                    if (player.getUUID().equals(cluster.owner)) {
                        player.sendMessage(TranslatableCaption.of("cluster.cluster_list_element_owner"), Template.of("cluster", name));
                    } else if (cluster.helpers.contains(player.getUUID())) {
                        player.sendMessage(TranslatableCaption.of("cluster.cluster_list_element_helpers"), Template.of("cluster", name));
                    } else if (cluster.invited.contains(player.getUUID())) {
                        player.sendMessage(TranslatableCaption.of("cluster.cluster_list_element_invited"), Template.of("cluster", name));
                    } else {
                        player.sendMessage(TranslatableCaption.of("cluster.cluster_list_element"), Template.of("cluster", cluster.toString()));
                    }
                }
                return true;
            }
        case "c":
        case "create":
            {
                if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_CREATE)) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", String.valueOf(Permission.PERMISSION_CLUSTER_CREATE)));
                    return false;
                }
                PlotArea area = player.getApplicablePlotArea();
                if (area == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
                    return false;
                }
                if (args.length != 4) {
                    player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster create <name> <id-bot> <id-top>"));
                    return false;
                }
                int currentClusters = Settings.Limit.GLOBAL ? player.getClusterCount() : player.getPlotCount(player.getLocation().getWorldName());
                if (currentClusters >= player.getAllowedPlots()) {
                    player.sendMessage(TranslatableCaption.of("permission.cant_claim_more_clusters"), Template.of("amount", String.valueOf(player.getAllowedPlots())));
                }
                PlotId pos1;
                PlotId pos2;
                // check pos1 / pos2
                try {
                    pos1 = PlotId.fromString(args[2]);
                    pos2 = PlotId.fromString(args[3]);
                } catch (IllegalArgumentException ignored) {
                    player.sendMessage(TranslatableCaption.of("invalid.not_valid_plot_id"));
                    return false;
                }
                // check if name is taken
                String name = args[1];
                if (area.getCluster(name) != null) {
                    player.sendMessage(TranslatableCaption.of("alias.alias_is_taken"), Template.of("alias", name));
                    return false;
                }
                if (pos2.getX() < pos1.getX() || pos2.getY() < pos1.getY()) {
                    PlotId tmp = PlotId.of(Math.min(pos1.getX(), pos2.getX()), Math.min(pos1.getY(), pos2.getY()));
                    pos2 = PlotId.of(Math.max(pos1.getX(), pos2.getX()), Math.max(pos1.getY(), pos2.getY()));
                    pos1 = tmp;
                }
                // check if overlap
                PlotCluster cluster = area.getFirstIntersectingCluster(pos1, pos2);
                if (cluster != null) {
                    player.sendMessage(TranslatableCaption.of("cluster.cluster_intersection"), Template.of("cluster", cluster.getName()));
                    return false;
                }
                // Check if it occupies existing plots
                if (!area.contains(pos1) || !area.contains(pos2)) {
                    player.sendMessage(TranslatableCaption.of("cluster.cluster_outside"), Template.of("area", String.valueOf(area)));
                    return false;
                }
                Set<Plot> plots = area.getPlotSelectionOwned(pos1, pos2);
                if (!plots.isEmpty()) {
                    if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_CREATE_OTHER)) {
                        UUID uuid = player.getUUID();
                        for (Plot plot : plots) {
                            if (!plot.isOwner(uuid)) {
                                player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", String.valueOf(Permission.PERMISSION_CLUSTER_CREATE_OTHER)));
                                return false;
                            }
                        }
                    }
                }
                // Check allowed cluster size
                cluster = new PlotCluster(area, pos1, pos2, player.getUUID());
                int current;
                if (Settings.Limit.GLOBAL) {
                    current = player.getPlayerClusterCount();
                } else {
                    current = player.getPlayerClusterCount(player.getLocation().getWorldName());
                }
                int allowed = Permissions.hasPermissionRange(player, Permission.PERMISSION_CLUSTER_SIZE, Settings.Limit.MAX_PLOTS);
                if (current + cluster.getArea() > allowed) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER_SIZE + "." + (current + cluster.getArea())));
                    return false;
                }
                // create cluster
                cluster.settings.setAlias(name);
                area.addCluster(cluster);
                DBFunc.createCluster(cluster);
                // Add any existing plots to the current cluster
                for (Plot plot : plots) {
                    if (plot.hasOwner()) {
                        if (!cluster.isAdded(plot.getOwner())) {
                            cluster.invited.add(plot.getOwner());
                            DBFunc.setInvited(cluster, plot.getOwner());
                        }
                    }
                }
                player.sendMessage(TranslatableCaption.of("cluster.cluster_created"), Template.of("name", name));
                return true;
            }
        case "disband":
        case "del":
        case "delete":
            {
                if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_DELETE)) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", String.valueOf(Permission.PERMISSION_CLUSTER_DELETE)));
                    return false;
                }
                if (args.length != 1 && args.length != 2) {
                    player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster delete [name]"));
                    return false;
                }
                PlotArea area = player.getApplicablePlotArea();
                if (area == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
                    return false;
                }
                PlotCluster cluster;
                if (args.length == 2) {
                    cluster = area.getCluster(args[1]);
                    if (cluster == null) {
                        player.sendMessage(TranslatableCaption.of("cluster.invalid_cluster_name"), Template.of("cluster", args[1]));
                        return false;
                    }
                } else {
                    cluster = area.getCluster(player.getLocation());
                    if (cluster == null) {
                        player.sendMessage(TranslatableCaption.of("errors.not_in_cluster"));
                        return false;
                    }
                }
                if (!cluster.owner.equals(player.getUUID())) {
                    if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_DELETE_OTHER)) {
                        player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", String.valueOf(Permission.PERMISSION_CLUSTER_DELETE_OTHER)));
                        return false;
                    }
                }
                DBFunc.delete(cluster);
                player.sendMessage(TranslatableCaption.of("cluster.cluster_deleted"), Template.of("cluster", String.valueOf(cluster)));
                return true;
            }
        case "res":
        case "resize":
            {
                if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_RESIZE)) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", String.valueOf(Permission.PERMISSION_CLUSTER_RESIZE)));
                    return false;
                }
                if (args.length != 3) {
                    player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster resize [name]"));
                    return false;
                }
                PlotId pos1;
                PlotId pos2;
                // check pos1 / pos2
                try {
                    pos1 = PlotId.fromString(args[2]);
                    pos2 = PlotId.fromString(args[3]);
                } catch (IllegalArgumentException ignored) {
                    player.sendMessage(TranslatableCaption.of("invalid.not_valid_plot_id"));
                    return false;
                }
                if (pos2.getX() < pos1.getX() || pos2.getY() < pos1.getY()) {
                    pos1 = PlotId.of(Math.min(pos1.getX(), pos2.getX()), Math.min(pos1.getY(), pos2.getY()));
                    pos2 = PlotId.of(Math.max(pos1.getX(), pos2.getX()), Math.max(pos1.getY(), pos2.getY()));
                }
                // check if in cluster
                PlotArea area = player.getApplicablePlotArea();
                if (area == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
                    return false;
                }
                PlotCluster cluster = area.getCluster(player.getLocation());
                if (cluster == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_cluster"));
                    return false;
                }
                if (!cluster.hasHelperRights(player.getUUID())) {
                    if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_RESIZE_OTHER)) {
                        player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", String.valueOf(Permission.PERMISSION_CLUSTER_RESIZE_OTHER)));
                        return false;
                    }
                }
                // check if overlap
                PlotCluster intersect = area.getFirstIntersectingCluster(pos1, pos2);
                if (intersect != null) {
                    player.sendMessage(TranslatableCaption.of("cluster.cluster_intersection"), Template.of("cluster", intersect.getName()));
                    return false;
                }
                Set<Plot> existing = area.getPlotSelectionOwned(cluster.getP1(), cluster.getP2());
                Set<Plot> newPlots = area.getPlotSelectionOwned(pos1, pos2);
                // Set<Plot> removed = (HashSet<Plot>) existing.clone();
                Set<Plot> removed = new HashSet<>(existing);
                removed.removeAll(newPlots);
                // Check expand / shrink
                if (!removed.isEmpty()) {
                    if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_RESIZE_SHRINK)) {
                        player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", String.valueOf(Permission.PERMISSION_CLUSTER_RESIZE_SHRINK)));
                        return false;
                    }
                }
                newPlots.removeAll(existing);
                if (!newPlots.isEmpty()) {
                    if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_RESIZE_EXPAND)) {
                        player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", String.valueOf(Permission.PERMISSION_CLUSTER_RESIZE_EXPAND)));
                        return false;
                    }
                }
                // Check allowed cluster size
                int current;
                if (Settings.Limit.GLOBAL) {
                    current = player.getPlayerClusterCount();
                } else {
                    current = player.getPlayerClusterCount(player.getLocation().getWorldName());
                }
                current -= cluster.getArea() + (1 + pos2.getX() - pos1.getX()) * (1 + pos2.getY() - pos1.getY());
                int allowed = Permissions.hasPermissionRange(player, Permission.PERMISSION_CLUSTER, Settings.Limit.MAX_PLOTS);
                if (current + cluster.getArea() > allowed) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER + "." + (current + cluster.getArea())));
                    return false;
                }
                // resize cluster
                DBFunc.resizeCluster(cluster, pos1, pos2);
                player.sendMessage(TranslatableCaption.of("cluster.cluster_resized"));
                return true;
            }
        case "add":
        case "inv":
        case "invite":
            {
                if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_INVITE)) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", String.valueOf(Permission.PERMISSION_CLUSTER_INVITE)));
                    return false;
                }
                if (args.length != 2) {
                    player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster invite <player>"));
                    return false;
                }
                // check if in cluster
                PlotArea area = player.getApplicablePlotArea();
                if (area == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
                }
                PlotCluster cluster = area.getCluster(player.getLocation());
                if (cluster == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_cluster"));
                    return false;
                }
                if (!cluster.hasHelperRights(player.getUUID())) {
                    if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_INVITE_OTHER)) {
                        player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER_INVITE_OTHER.toString()));
                        return false;
                    }
                }
                PlotSquared.get().getImpromptuUUIDPipeline().getSingle(args[1], (uuid, throwable) -> {
                    if (throwable instanceof TimeoutException) {
                        player.sendMessage(TranslatableCaption.of("players.fetching_players_timeout"));
                    } else if (throwable != null) {
                        player.sendMessage(TranslatableCaption.of("errors.invalid_player"), Template.of("value", args[1]));
                    } else {
                        if (!cluster.isAdded(uuid)) {
                            // add the user if not added
                            cluster.invited.add(uuid);
                            DBFunc.setInvited(cluster, uuid);
                            final PlotPlayer<?> otherPlayer = PlotSquared.platform().playerManager().getPlayerIfExists(uuid);
                            if (otherPlayer != null) {
                                player.sendMessage(TranslatableCaption.of("cluster.cluster_invited"), Template.of("cluster", cluster.getName()));
                            }
                        }
                        player.sendMessage(TranslatableCaption.of("cluster.cluster_added_user"));
                    }
                });
                return true;
            }
        case "k":
        case "remove":
        case "kick":
            {
                if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_KICK)) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER_KICK.toString()));
                    return false;
                }
                if (args.length != 2) {
                    player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster kick <player>"));
                    return false;
                }
                PlotArea area = player.getApplicablePlotArea();
                if (area == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
                }
                PlotCluster cluster = area.getCluster(player.getLocation());
                if (cluster == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_cluster"));
                    return false;
                }
                if (!cluster.hasHelperRights(player.getUUID())) {
                    if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_KICK_OTHER)) {
                        player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER_KICK_OTHER.toString()));
                        return false;
                    }
                }
                // check uuid
                PlotSquared.get().getImpromptuUUIDPipeline().getSingle(args[1], (uuid, throwable) -> {
                    if (throwable instanceof TimeoutException) {
                        player.sendMessage(TranslatableCaption.of("players.fetching_players_timeout"));
                    } else if (throwable != null) {
                        player.sendMessage(TranslatableCaption.of("errors.invalid_player"), Template.of("value", args[1]));
                    } else {
                        // Can't kick if the player is yourself, the owner, or not added to the cluster
                        if (uuid.equals(player.getUUID()) || uuid.equals(cluster.owner) || !cluster.isAdded(uuid)) {
                            player.sendMessage(TranslatableCaption.of("cluster.cannot_kick_player"), Template.of("value", cluster.getName()));
                        } else {
                            if (cluster.helpers.contains(uuid)) {
                                cluster.helpers.remove(uuid);
                                DBFunc.removeHelper(cluster, uuid);
                            }
                            cluster.invited.remove(uuid);
                            DBFunc.removeInvited(cluster, uuid);
                            final PlotPlayer<?> player2 = PlotSquared.platform().playerManager().getPlayerIfExists(uuid);
                            if (player2 != null) {
                                player.sendMessage(TranslatableCaption.of("cluster.cluster_removed"), Template.of("cluster", cluster.getName()));
                            }
                            removePlayerPlots(cluster, uuid, player2.getLocation().getWorldName());
                            player.sendMessage(TranslatableCaption.of("cluster.cluster_kicked_user"));
                        }
                    }
                });
                return true;
            }
        case "quit":
        case "leave":
            {
                if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_LEAVE)) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER_LEAVE.toString()));
                    return false;
                }
                if (args.length != 1 && args.length != 2) {
                    player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster leave [name]"));
                    return false;
                }
                PlotArea area = player.getApplicablePlotArea();
                if (area == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
                }
                PlotCluster cluster;
                if (args.length == 2) {
                    cluster = area.getCluster(args[1]);
                    if (cluster == null) {
                        player.sendMessage(TranslatableCaption.of("cluster.invalid_cluster_name"), Template.of("cluster", args[1]));
                        return false;
                    }
                } else {
                    cluster = area.getCluster(player.getLocation());
                    if (cluster == null) {
                        player.sendMessage(TranslatableCaption.of("errors.not_in_cluster"));
                        return false;
                    }
                }
                UUID uuid = player.getUUID();
                if (!cluster.isAdded(uuid)) {
                    player.sendMessage(TranslatableCaption.of("cluster.cluster_not_added"));
                    return false;
                }
                if (uuid.equals(cluster.owner)) {
                    player.sendMessage(TranslatableCaption.of("cluster.cluster_cannot_leave"));
                    return false;
                }
                if (cluster.helpers.contains(uuid)) {
                    cluster.helpers.remove(uuid);
                    DBFunc.removeHelper(cluster, uuid);
                }
                cluster.invited.remove(uuid);
                DBFunc.removeInvited(cluster, uuid);
                player.sendMessage(TranslatableCaption.of("cluster.cluster_removed"), Template.of("cluster", cluster.getName()));
                removePlayerPlots(cluster, uuid, player.getLocation().getWorldName());
                return true;
            }
        case "members":
            {
                if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_HELPERS)) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER_HELPERS.toString()));
                    return false;
                }
                if (args.length != 3) {
                    player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster members <add | remove> <player>"));
                    return false;
                }
                PlotArea area = player.getApplicablePlotArea();
                if (area == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
                }
                PlotCluster cluster = area.getCluster(player.getLocation());
                if (cluster == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_cluster"));
                    return false;
                }
                PlotSquared.get().getImpromptuUUIDPipeline().getSingle(args[2], (uuid, throwable) -> {
                    if (throwable instanceof TimeoutException) {
                        player.sendMessage(TranslatableCaption.of("players.fetching_players_timeout"));
                    } else if (throwable != null) {
                        player.sendMessage(TranslatableCaption.of("errors.invalid_player"), Template.of("value", args[2]));
                    } else {
                        if (args[1].equalsIgnoreCase("add")) {
                            cluster.helpers.add(uuid);
                            DBFunc.setHelper(cluster, uuid);
                            player.sendMessage(TranslatableCaption.of("cluster.cluster_added_helper"));
                        } else if (args[1].equalsIgnoreCase("remove")) {
                            cluster.helpers.remove(uuid);
                            DBFunc.removeHelper(cluster, uuid);
                            player.sendMessage(TranslatableCaption.of("cluster.cluster_removed_helper"));
                        } else {
                            player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster members <add | remove> <player>"));
                        }
                    }
                });
                return true;
            }
        case "spawn":
        case "home":
        case "tp":
            {
                if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_TP)) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER_TP.toString()));
                    return false;
                }
                if (args.length != 2) {
                    player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster tp <name>"));
                    return false;
                }
                PlotArea area = player.getApplicablePlotArea();
                if (area == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
                    return false;
                }
                PlotCluster cluster = area.getCluster(args[1]);
                if (cluster == null) {
                    player.sendMessage(TranslatableCaption.of("cluster.invalid_cluster_name"), Template.of("cluster", args[1]));
                    return false;
                }
                UUID uuid = player.getUUID();
                if (!cluster.isAdded(uuid)) {
                    if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_TP_OTHER)) {
                        player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER_TP_OTHER.toString()));
                        return false;
                    }
                }
                cluster.getHome(home -> player.teleport(home, TeleportCause.COMMAND_CLUSTER_TELEPORT));
                player.sendMessage(TranslatableCaption.of("cluster.cluster_teleporting"));
                return true;
            }
        case "i":
        case "info":
        case "show":
        case "information":
            {
                if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_INFO)) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER_TP.toString()));
                    return false;
                }
                if (args.length != 1 && args.length != 2) {
                    player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster info [name]"));
                }
                PlotArea area = player.getApplicablePlotArea();
                if (area == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
                    return false;
                }
                PlotCluster cluster;
                if (args.length == 2) {
                    cluster = area.getCluster(args[1]);
                    if (cluster == null) {
                        player.sendMessage(TranslatableCaption.of("cluster.invalid_cluster_name"), Template.of("cluster", args[1]));
                        return false;
                    }
                } else {
                    cluster = area.getCluster(player.getLocation());
                    if (cluster == null) {
                        player.sendMessage(TranslatableCaption.of("errors.not_in_cluster"));
                        return false;
                    }
                }
                String id = cluster.toString();
                PlotSquared.get().getImpromptuUUIDPipeline().getSingle(cluster.owner, (username, throwable) -> {
                    if (throwable instanceof TimeoutException) {
                        player.sendMessage(TranslatableCaption.of("players.fetching_players_timeout"));
                    } else {
                        final String owner;
                        if (username == null) {
                            owner = "unknown";
                        } else {
                            owner = username;
                        }
                        String name = cluster.getName();
                        String size = (cluster.getP2().getX() - cluster.getP1().getX() + 1) + "x" + (cluster.getP2().getY() - cluster.getP1().getY() + 1);
                        String rights = cluster.isAdded(player.getUUID()) + "";
                        Caption message = TranslatableCaption.of("cluster.cluster_info");
                        Template idTemplate = Template.of("id", id);
                        Template ownerTemplate = Template.of("owner", owner);
                        Template nameTemplate = Template.of("name", name);
                        Template sizeTemplate = Template.of("size", size);
                        Template rightsTemplate = Template.of("rights", rights);
                        player.sendMessage(message, idTemplate, ownerTemplate, nameTemplate, sizeTemplate, rightsTemplate);
                    }
                });
                return true;
            }
        case "sh":
        case "setspawn":
        case "sethome":
            {
                if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_SETHOME)) {
                    player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER_SETHOME.toString()));
                    return false;
                }
                if (args.length != 1 && args.length != 2) {
                    player.sendMessage(TranslatableCaption.of("commandconfig.command_syntax"), Template.of("value", "/plot cluster sethome"));
                    return false;
                }
                PlotArea area = player.getApplicablePlotArea();
                if (area == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_plot_world"));
                }
                PlotCluster cluster = area.getCluster(player.getLocation());
                if (cluster == null) {
                    player.sendMessage(TranslatableCaption.of("errors.not_in_cluster"));
                    return false;
                }
                if (!cluster.hasHelperRights(player.getUUID())) {
                    if (!Permissions.hasPermission(player, Permission.PERMISSION_CLUSTER_SETHOME_OTHER)) {
                        player.sendMessage(TranslatableCaption.of("permission.no_permission"), Template.of("node", Permission.PERMISSION_CLUSTER_SETHOME_OTHER.toString()));
                        return false;
                    }
                }
                Location base = cluster.getClusterBottom();
                Location relative = player.getLocation().subtract(base.getX(), 0, base.getZ());
                BlockLoc blockloc = new BlockLoc(relative.getX(), relative.getY(), relative.getZ());
                cluster.settings.setPosition(blockloc);
                DBFunc.setPosition(cluster, relative.getX() + "," + relative.getY() + "," + relative.getZ());
                player.sendMessage(TranslatableCaption.of("position.position_set"));
                return true;
            }
    }
    player.sendMessage(TranslatableCaption.of("cluster.cluster_available_args"), Template.of("list", "<dark_aqua>list</dark_aqua><gray>, </gray><dark_aqua>create</dark_aqua><gray>, </gray><dark_aqua>delete</dark_aqua><gray>, </gray><dark_aqua>resize</dark_aqua><gray>, </gray><dark_aqua>invite</dark_aqua><gray>, </gray><dark_aqua>kick</dark_aqua><gray>, </gray><dark_aqua>leave</dark_aqua><gray>, </gray><dark_aqua>members</dark_aqua><gray>, </gray><dark_aqua>info</dark_aqua><gray>, </gray><dark_aqua>tp</dark_aqua><gray>, </gray><dark_aqua>sethome</dark_aqua>"));
    return false;
}
Also used : TeleportCause(com.plotsquared.core.events.TeleportCause) PlotId(com.plotsquared.core.plot.PlotId) TimeoutException(java.util.concurrent.TimeoutException) Permission(com.plotsquared.core.permissions.Permission) PlotQuery(com.plotsquared.core.util.query.PlotQuery) HashSet(java.util.HashSet) BlockLoc(com.plotsquared.core.location.BlockLoc) LinkedList(java.util.LinkedList) Template(net.kyori.adventure.text.minimessage.Template) Caption(com.plotsquared.core.configuration.caption.Caption) DBFunc(com.plotsquared.core.database.DBFunc) Location(com.plotsquared.core.location.Location) PlotCluster(com.plotsquared.core.plot.PlotCluster) Permissions(com.plotsquared.core.util.Permissions) Plot(com.plotsquared.core.plot.Plot) Collection(java.util.Collection) TabCompletions(com.plotsquared.core.util.TabCompletions) Set(java.util.Set) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) List(java.util.List) PlotSquared(com.plotsquared.core.PlotSquared) PlotPlayer(com.plotsquared.core.player.PlotPlayer) TranslatableCaption(com.plotsquared.core.configuration.caption.TranslatableCaption) Settings(com.plotsquared.core.configuration.Settings) PlotArea(com.plotsquared.core.plot.PlotArea) Collections(java.util.Collections) PlotCluster(com.plotsquared.core.plot.PlotCluster) HashSet(java.util.HashSet) Set(java.util.Set) PlotArea(com.plotsquared.core.plot.PlotArea) Plot(com.plotsquared.core.plot.Plot) Caption(com.plotsquared.core.configuration.caption.Caption) TranslatableCaption(com.plotsquared.core.configuration.caption.TranslatableCaption) BlockLoc(com.plotsquared.core.location.BlockLoc) Template(net.kyori.adventure.text.minimessage.Template) PlotId(com.plotsquared.core.plot.PlotId) UUID(java.util.UUID) TimeoutException(java.util.concurrent.TimeoutException) Location(com.plotsquared.core.location.Location)

Aggregations

PlotCluster (com.plotsquared.core.plot.PlotCluster)3 UUID (java.util.UUID)3 BlockLoc (com.plotsquared.core.location.BlockLoc)2 Plot (com.plotsquared.core.plot.Plot)2 PlotId (com.plotsquared.core.plot.PlotId)2 PreparedStatement (java.sql.PreparedStatement)2 HashSet (java.util.HashSet)2 Set (java.util.Set)2 PlotSquared (com.plotsquared.core.PlotSquared)1 ConfigurationSection (com.plotsquared.core.configuration.ConfigurationSection)1 Settings (com.plotsquared.core.configuration.Settings)1 Caption (com.plotsquared.core.configuration.caption.Caption)1 TranslatableCaption (com.plotsquared.core.configuration.caption.TranslatableCaption)1 DBFunc (com.plotsquared.core.database.DBFunc)1 TeleportCause (com.plotsquared.core.events.TeleportCause)1 Location (com.plotsquared.core.location.Location)1 Permission (com.plotsquared.core.permissions.Permission)1 PlotPlayer (com.plotsquared.core.player.PlotPlayer)1 PlotArea (com.plotsquared.core.plot.PlotArea)1 FlagParseException (com.plotsquared.core.plot.flag.FlagParseException)1