Search in sources :

Example 1 with FileManager

use of me.wiefferink.areashop.managers.FileManager in project AreaShop by NLthijs48.

the class AreaShop method onEnable.

/**
 * Called on start or reload of the server.
 */
public void onEnable() {
    AreaShop.instance = this;
    Do.init(this);
    managers = new HashSet<>();
    boolean error = false;
    // Check if WorldGuard is present
    String wgVersion = null;
    String rawVersion = null;
    int major = 0;
    int minor = 0;
    int fixes = 0;
    Integer build = null;
    Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard");
    if (plugin == null || !(plugin instanceof WorldGuardPlugin) || !plugin.isEnabled()) {
        error("WorldGuard plugin is not present or has not loaded correctly");
        error = true;
    } else {
        worldGuard = (WorldGuardPlugin) plugin;
        // Get correct WorldGuardInterface (handles things that changed version to version)
        try {
            rawVersion = worldGuard.getDescription().getVersion();
            if (rawVersion.contains("-SNAPSHOT;")) {
                String buildNumber = rawVersion.substring(rawVersion.indexOf("-SNAPSHOT;") + 10, rawVersion.length());
                if (buildNumber.contains("-")) {
                    buildNumber = buildNumber.substring(0, buildNumber.indexOf("-"));
                    try {
                        build = Integer.parseInt(buildNumber);
                    } catch (NumberFormatException e) {
                        warn("Could not correctly parse the build of WorldGuard, raw version: " + rawVersion + ", buildNumber: " + buildNumber);
                    }
                }
            }
            // Clear stuff from the version string that is not a number
            String[] versionParts = rawVersion.split("\\.");
            for (int i = 0; i < versionParts.length; i++) {
                Pattern pattern = Pattern.compile("^\\d+");
                Matcher matcher = pattern.matcher(versionParts[i]);
                if (matcher.find()) {
                    versionParts[i] = matcher.group();
                }
            }
            // Find major, minor and fix numbers
            try {
                if (versionParts.length > 0) {
                    major = Integer.parseInt(versionParts[0]);
                }
                if (versionParts.length > 1) {
                    minor = Integer.parseInt(versionParts[1]);
                }
                if (versionParts.length > 2) {
                    fixes = Integer.parseInt(versionParts[2]);
                }
            } catch (NumberFormatException e) {
                warn("Something went wrong while parsing WorldGuard version number: " + rawVersion);
            }
            // Determine correct implementation to use
            if (worldGuard.getDescription().getVersion().startsWith("5.")) {
                wgVersion = "5";
            } else if (major == 6 && minor == 1 && fixes < 3) {
                wgVersion = "6";
            } else {
                if (build != null && build == 1672) {
                    error = true;
                    error("Build 1672 of WorldGuard is broken, update to a later build or a stable version!");
                } else if (build != null && build < 1672) {
                    wgVersion = "6";
                } else {
                    wgVersion = "6_1_3";
                }
            }
        } catch (Exception e) {
            // If version detection fails, at least try to load the latest version
            wgVersion = "6_1_3";
        }
        // Load chosen implementation
        try {
            final Class<?> clazz = Class.forName("me.wiefferink.areashop.handlers.WorldGuardHandler" + wgVersion);
            // Check if we have a NMSHandler class at that location.
            if (WorldGuardInterface.class.isAssignableFrom(clazz)) {
                // Make sure it actually implements WorldGuardInterface
                // Set our handler
                worldGuardInterface = (WorldGuardInterface) clazz.getConstructor(AreaShopInterface.class).newInstance(this);
            }
        } catch (final Exception e) {
            error("Could not load the handler for WorldGuard (tried to load " + wgVersion + "), report this problem to the author:" + ExceptionUtils.getStackTrace(e));
            error = true;
            wgVersion = null;
        }
    }
    // Check if WorldEdit is present
    String weVersion = null;
    plugin = getServer().getPluginManager().getPlugin("WorldEdit");
    if (plugin == null || !(plugin instanceof WorldEditPlugin) || !plugin.isEnabled()) {
        error("WorldEdit plugin is not present or has not loaded correctly");
        error = true;
    } else {
        worldEdit = (WorldEditPlugin) plugin;
        // Get correct WorldEditInterface (handles things that changed version to version)
        if (worldEdit.getDescription().getVersion().startsWith("5.")) {
            weVersion = "5";
        } else {
            weVersion = "6";
        }
        try {
            final Class<?> clazz = Class.forName("me.wiefferink.areashop.handlers.WorldEditHandler" + weVersion);
            // Check if we have a NMSHandler class at that location.
            if (WorldEditInterface.class.isAssignableFrom(clazz)) {
                // Make sure it actually implements WorldEditInterface
                // Set our handler
                worldEditInterface = (WorldEditInterface) clazz.getConstructor(AreaShopInterface.class).newInstance(this);
            }
        } catch (final Exception e) {
            error("Could not load the handler for WorldEdit (tried to load " + weVersion + "), report this problem to the author: " + ExceptionUtils.getStackTrace(e));
            error = true;
            weVersion = null;
        }
    }
    // Check if Vault is present
    if (getServer().getPluginManager().getPlugin("Vault") == null) {
        error("Vault plugin is not present or has not loaded correctly");
        error = true;
    }
    // Load all data from files and check versions
    fileManager = new FileManager();
    managers.add(fileManager);
    error = error | !fileManager.loadFiles(false);
    // Print loaded version of WG and WE in debug
    if (wgVersion != null) {
        AreaShop.debug("Loaded WorldGuardHandler" + wgVersion + " (raw version: " + rawVersion + ", major:" + major + ", minor:" + minor + ", fixes:" + fixes + ", build:" + build + ")");
    }
    if (weVersion != null) {
        AreaShop.debug("Loaded WorldEditHandler" + weVersion);
    }
    setupLanguageManager();
    if (error) {
        error("The plugin has not started, fix the errors listed above");
    } else {
        featureManager = new FeatureManager();
        managers.add(featureManager);
        // Register the event listeners
        getServer().getPluginManager().registerEvents(new PlayerLoginLogoutListener(this), this);
        setupTasks();
        // Startup the CommandManager (registers itself for the command)
        commandManager = new CommandManager();
        managers.add(commandManager);
        // Create a signLinkerManager
        signLinkerManager = new SignLinkerManager();
        managers.add(signLinkerManager);
        // Enable Metrics if config allows it
        if (getConfig().getBoolean("sendStats")) {
            Analytics.start();
        }
        // Register dynamic permission (things declared in config)
        registerDynamicPermissions();
        // Don't initialize the updatechecker if disabled in the config
        if (getConfig().getBoolean("checkForUpdates")) {
            githubUpdateCheck = new GithubUpdateCheck(AreaShop.getInstance(), "NLThijs48", "AreaShop").withVersionComparator((latestVersion, currentVersion) -> !cleanVersion(latestVersion).equals(cleanVersion(currentVersion))).checkUpdate((result) -> {
                AreaShop.debug("Update check result:", result);
                if (!result.hasUpdate()) {
                    return;
                }
                AreaShop.info("Update from AreaShop V" + cleanVersion(result.getCurrentVersion()) + " to AreaShop V" + cleanVersion(result.getLatestVersion()) + " available, get the latest version at https://www.spigotmc.org/resources/areashop.2991/");
                for (Player player : Utils.getOnlinePlayers()) {
                    notifyUpdate(player);
                }
            });
        }
    }
}
Also used : HandlerList(org.bukkit.event.HandlerList) Plugin(org.bukkit.plugin.Plugin) StringUtils(org.apache.commons.lang.StringUtils) Message(me.wiefferink.interactivemessenger.processing.Message) ConfigurationSection(org.bukkit.configuration.ConfigurationSection) CommandManager(me.wiefferink.areashop.managers.CommandManager) AreaShopInterface(me.wiefferink.areashop.interfaces.AreaShopInterface) Player(org.bukkit.entity.Player) HashSet(java.util.HashSet) PlayerLoginLogoutListener(me.wiefferink.areashop.listeners.PlayerLoginLogoutListener) Matcher(java.util.regex.Matcher) Analytics(me.wiefferink.areashop.tools.Analytics) SignLinkerManager(me.wiefferink.areashop.managers.SignLinkerManager) Nullable(javax.annotation.Nullable) Bukkit(org.bukkit.Bukkit) GithubUpdateCheck(me.wiefferink.areashop.tools.GithubUpdateCheck) CommandSender(org.bukkit.command.CommandSender) WorldEditInterface(me.wiefferink.areashop.interfaces.WorldEditInterface) Economy(net.milkbowl.vault.economy.Economy) Do(me.wiefferink.bukkitdo.Do) WorldGuardInterface(me.wiefferink.areashop.interfaces.WorldGuardInterface) ExceptionUtils(org.apache.commons.lang.exception.ExceptionUtils) WorldGuardPlugin(com.sk89q.worldguard.bukkit.WorldGuardPlugin) Set(java.util.Set) FileManager(me.wiefferink.areashop.managers.FileManager) Utils(me.wiefferink.areashop.tools.Utils) OfflinePlayer(org.bukkit.OfflinePlayer) Permission(org.bukkit.permissions.Permission) JavaPlugin(org.bukkit.plugin.java.JavaPlugin) WorldEditPlugin(com.sk89q.worldedit.bukkit.WorldEditPlugin) List(java.util.List) FeatureManager(me.wiefferink.areashop.managers.FeatureManager) YamlConfiguration(org.bukkit.configuration.file.YamlConfiguration) Pattern(java.util.regex.Pattern) LanguageManager(me.wiefferink.interactivemessenger.source.LanguageManager) Manager(me.wiefferink.areashop.managers.Manager) RegisteredServiceProvider(org.bukkit.plugin.RegisteredServiceProvider) Pattern(java.util.regex.Pattern) Player(org.bukkit.entity.Player) OfflinePlayer(org.bukkit.OfflinePlayer) Matcher(java.util.regex.Matcher) FileManager(me.wiefferink.areashop.managers.FileManager) PlayerLoginLogoutListener(me.wiefferink.areashop.listeners.PlayerLoginLogoutListener) WorldEditPlugin(com.sk89q.worldedit.bukkit.WorldEditPlugin) CommandManager(me.wiefferink.areashop.managers.CommandManager) WorldGuardPlugin(com.sk89q.worldguard.bukkit.WorldGuardPlugin) SignLinkerManager(me.wiefferink.areashop.managers.SignLinkerManager) GithubUpdateCheck(me.wiefferink.areashop.tools.GithubUpdateCheck) FeatureManager(me.wiefferink.areashop.managers.FeatureManager) Plugin(org.bukkit.plugin.Plugin) WorldGuardPlugin(com.sk89q.worldguard.bukkit.WorldGuardPlugin) JavaPlugin(org.bukkit.plugin.java.JavaPlugin) WorldEditPlugin(com.sk89q.worldedit.bukkit.WorldEditPlugin) AreaShopInterface(me.wiefferink.areashop.interfaces.AreaShopInterface)

Example 2 with FileManager

use of me.wiefferink.areashop.managers.FileManager in project AreaShop by NLthijs48.

the class AreaShop method onDisable.

/**
 * Called on shutdown or reload of the server.
 */
public void onDisable() {
    Bukkit.getServer().getScheduler().cancelTasks(this);
    // Cleanup managers
    for (Manager manager : managers) {
        manager.shutdown();
    }
    managers = null;
    fileManager = null;
    languageManager = null;
    commandManager = null;
    signLinkerManager = null;
    featureManager = null;
    // Cleanup plugins
    worldGuard = null;
    worldGuardInterface = null;
    worldEdit = null;
    worldEditInterface = null;
    // Cleanup other stuff
    chatprefix = null;
    debug = false;
    ready = false;
    HandlerList.unregisterAll(this);
}
Also used : CommandManager(me.wiefferink.areashop.managers.CommandManager) SignLinkerManager(me.wiefferink.areashop.managers.SignLinkerManager) FileManager(me.wiefferink.areashop.managers.FileManager) FeatureManager(me.wiefferink.areashop.managers.FeatureManager) LanguageManager(me.wiefferink.interactivemessenger.source.LanguageManager) Manager(me.wiefferink.areashop.managers.Manager)

Example 3 with FileManager

use of me.wiefferink.areashop.managers.FileManager in project AreaShop by NLthijs48.

the class AddCommand method execute.

@Override
public void execute(final CommandSender sender, final String[] args) {
    if (!sender.hasPermission("areashop.createrent") && !sender.hasPermission("areashop.createrent.member") && !sender.hasPermission("areashop.createrent.owner") && !sender.hasPermission("areashop.createbuy") && !sender.hasPermission("areashop.createbuy.member") && !sender.hasPermission("areashop.createbuy.owner")) {
        plugin.message(sender, "add-noPermission");
        return;
    }
    if (args.length < 2 || args[1] == null || (!"rent".equals(args[1].toLowerCase()) && !"buy".equals(args[1].toLowerCase()))) {
        plugin.message(sender, "add-help");
        return;
    }
    Map<String, ProtectedRegion> regions = new HashMap<>();
    World world;
    Player player = null;
    if (sender instanceof Player) {
        player = (Player) sender;
    }
    if (args.length == 2) {
        if (player == null) {
            plugin.message(sender, "cmd-weOnlyByPlayer");
            return;
        }
        Selection selection = plugin.getWorldEdit().getSelection(player);
        if (selection == null) {
            plugin.message(player, "cmd-noSelection");
            return;
        }
        world = selection.getWorld();
        regions = Utils.getWorldEditRegionsInSelection(selection).stream().collect(Collectors.toMap(ProtectedRegion::getId, region -> region));
        if (regions.size() == 0) {
            plugin.message(player, "cmd-noWERegionsFound");
            return;
        }
    } else {
        if (player != null) {
            if (args.length == 4) {
                world = Bukkit.getWorld(args[3]);
                if (world == null) {
                    plugin.message(sender, "add-incorrectWorld", args[3]);
                    return;
                }
            } else {
                world = ((Player) sender).getWorld();
            }
        } else {
            if (args.length < 4) {
                plugin.message(sender, "add-specifyWorld");
                return;
            } else {
                world = Bukkit.getWorld(args[3]);
                if (world == null) {
                    plugin.message(sender, "add-incorrectWorld", args[3]);
                    return;
                }
            }
        }
        ProtectedRegion region = plugin.getWorldGuard().getRegionManager(world).getRegion(args[2]);
        if (region == null) {
            plugin.message(sender, "cmd-noRegion", args[2]);
            return;
        }
        regions.put(args[2], region);
    }
    final boolean isRent = "rent".equals(args[1].toLowerCase());
    final Map<String, ProtectedRegion> finalRegions = regions;
    final Player finalPlayer = player;
    final World finalWorld = world;
    AreaShop.debug("Starting add task with " + regions.size() + " regions");
    TreeSet<GeneralRegion> regionsSuccess = new TreeSet<>();
    TreeSet<GeneralRegion> regionsAlready = new TreeSet<>();
    TreeSet<String> namesBlacklisted = new TreeSet<>();
    TreeSet<String> namesNoPermission = new TreeSet<>();
    Do.forAll(plugin.getConfig().getInt("adding.regionsPerTick"), regions.entrySet(), regionEntry -> {
        String regionName = regionEntry.getKey();
        ProtectedRegion region = regionEntry.getValue();
        // Determine if the player is an owner or member of the region
        boolean isMember = finalPlayer != null && plugin.getWorldGuardHandler().containsMember(region, finalPlayer.getUniqueId());
        boolean isOwner = finalPlayer != null && plugin.getWorldGuardHandler().containsMember(region, finalPlayer.getUniqueId());
        String type;
        if (isRent) {
            type = "rent";
        } else {
            type = "buy";
        }
        FileManager.AddResult result = plugin.getFileManager().checkRegionAdd(sender, region, isRent ? GeneralRegion.RegionType.RENT : GeneralRegion.RegionType.BUY);
        if (result == FileManager.AddResult.ALREADYADDED) {
            regionsAlready.add(plugin.getFileManager().getRegion(regionName));
        } else if (result == FileManager.AddResult.BLACKLISTED) {
            namesBlacklisted.add(regionName);
        } else if (result == FileManager.AddResult.NOPERMISSION) {
            namesNoPermission.add(regionName);
        } else {
            // Check if the player should be landlord
            boolean landlord = (!sender.hasPermission("areashop.create" + type) && ((sender.hasPermission("areashop.create" + type + ".owner") && isOwner) || (sender.hasPermission("areashop.create" + type + ".member") && isMember)));
            List<UUID> existing = new ArrayList<>();
            existing.addAll(plugin.getWorldGuardHandler().getOwners(region).asUniqueIdList());
            existing.addAll(plugin.getWorldGuardHandler().getMembers(region).asUniqueIdList());
            if (isRent) {
                RentRegion rent = new RentRegion(regionName, finalWorld);
                // Set landlord
                if (landlord) {
                    rent.setLandlord(finalPlayer.getUniqueId(), finalPlayer.getName());
                }
                // Run commands
                rent.runEventCommands(GeneralRegion.RegionEvent.CREATED, true);
                plugin.getFileManager().addRent(rent);
                rent.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
                rent.update();
                // Run commands
                rent.runEventCommands(GeneralRegion.RegionEvent.CREATED, false);
                // Add existing owners/members if any
                if (!landlord && !existing.isEmpty()) {
                    // TODO also execute rent events to notify other plugins?
                    // Run commands
                    rent.runEventCommands(GeneralRegion.RegionEvent.RENTED, true);
                    // Add values to the rent and send it to FileManager
                    rent.setRentedUntil(Calendar.getInstance().getTimeInMillis() + rent.getDuration());
                    rent.setRenter(existing.remove(0));
                    rent.updateLastActiveTime();
                    // Add others as friends
                    for (UUID friend : existing) {
                        rent.getFriendsFeature().addFriend(friend, null);
                    }
                    // Fire schematic event and updated times extended
                    rent.handleSchematicEvent(GeneralRegion.RegionEvent.RENTED);
                    // Notify about updates
                    rent.update();
                    rent.runEventCommands(GeneralRegion.RegionEvent.RENTED, false);
                }
                regionsSuccess.add(rent);
            } else {
                BuyRegion buy = new BuyRegion(regionName, finalWorld);
                // Set landlord
                if (landlord) {
                    buy.setLandlord(finalPlayer.getUniqueId(), finalPlayer.getName());
                }
                // Run commands
                buy.runEventCommands(GeneralRegion.RegionEvent.CREATED, true);
                plugin.getFileManager().addBuy(buy);
                buy.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
                buy.update();
                // Run commands
                buy.runEventCommands(GeneralRegion.RegionEvent.CREATED, false);
                // Add existing owners/members if any
                if (!landlord && !existing.isEmpty()) {
                    // TODO also execute buy events to notify for other plugins?
                    // Run commands
                    buy.runEventCommands(GeneralRegion.RegionEvent.BOUGHT, true);
                    // Set the owner
                    buy.setBuyer(existing.remove(0));
                    buy.updateLastActiveTime();
                    // Add others as friends
                    for (UUID friend : existing) {
                        buy.getFriendsFeature().addFriend(friend, null);
                    }
                    // Notify about updates
                    buy.update();
                    // Update everything
                    buy.handleSchematicEvent(GeneralRegion.RegionEvent.BOUGHT);
                    // Run commands
                    buy.runEventCommands(GeneralRegion.RegionEvent.BOUGHT, false);
                }
                regionsSuccess.add(buy);
            }
        }
    }, () -> {
        if (!regionsSuccess.isEmpty()) {
            plugin.message(sender, "add-success", args[1], Utils.combinedMessage(regionsSuccess, "region"));
        }
        if (!regionsAlready.isEmpty()) {
            plugin.message(sender, "add-failed", Utils.combinedMessage(regionsAlready, "region"));
        }
        if (!namesBlacklisted.isEmpty()) {
            plugin.message(sender, "add-blacklisted", Utils.createCommaSeparatedList(namesBlacklisted));
        }
        if (!namesNoPermission.isEmpty()) {
            plugin.message(sender, "add-noPermissionRegions", Utils.createCommaSeparatedList(namesNoPermission));
            plugin.message(sender, "add-noPermissionOwnerMember");
        }
    });
}
Also used : Player(org.bukkit.entity.Player) HashMap(java.util.HashMap) Selection(com.sk89q.worldedit.bukkit.selections.Selection) ArrayList(java.util.ArrayList) RentRegion(me.wiefferink.areashop.regions.RentRegion) World(org.bukkit.World) FileManager(me.wiefferink.areashop.managers.FileManager) TreeSet(java.util.TreeSet) BuyRegion(me.wiefferink.areashop.regions.BuyRegion) ProtectedRegion(com.sk89q.worldguard.protection.regions.ProtectedRegion) GeneralRegion(me.wiefferink.areashop.regions.GeneralRegion) UUID(java.util.UUID)

Example 4 with FileManager

use of me.wiefferink.areashop.managers.FileManager in project AreaShop by NLthijs48.

the class SignsFeature method onSignChange.

@EventHandler(priority = EventPriority.MONITOR)
public void onSignChange(SignChangeEvent event) {
    if (event.isCancelled()) {
        return;
    }
    Player player = event.getPlayer();
    if (!plugin.isReady()) {
        plugin.message(player, "general-notReady");
        return;
    }
    // Check if the sign is meant for this plugin
    if (event.getLine(0).contains(plugin.getConfig().getString("signTags.rent"))) {
        if (!player.hasPermission("areashop.createrent") && !player.hasPermission("areashop.createrent.member") && !player.hasPermission("areashop.createrent.owner")) {
            plugin.message(player, "setup-noPermissionRent");
            return;
        }
        // Get the other lines
        String secondLine = event.getLine(1);
        String thirdLine = event.getLine(2);
        String fourthLine = event.getLine(3);
        // Get the regionManager for accessing regions
        RegionManager regionManager = plugin.getWorldGuard().getRegionManager(event.getPlayer().getWorld());
        // If the secondLine does not contain a name try to find the region by location
        if (secondLine == null || secondLine.length() == 0) {
            Set<ProtectedRegion> regions = plugin.getWorldGuardHandler().getApplicableRegionsSet(event.getBlock().getLocation());
            if (regions != null) {
                boolean first = true;
                ProtectedRegion candidate = null;
                for (ProtectedRegion pr : regions) {
                    if (first) {
                        candidate = pr;
                        first = false;
                    } else {
                        if (pr.getPriority() > candidate.getPriority()) {
                            candidate = pr;
                        } else if (pr.getPriority() < candidate.getPriority()) {
                        // Already got the correct one
                        } else if (pr.getParent() != null && pr.getParent().equals(candidate)) {
                            candidate = pr;
                        } else if (candidate.getParent() != null && candidate.getParent().equals(pr)) {
                        // Already got the correct one
                        } else {
                            plugin.message(player, "setup-couldNotDetect", candidate.getId(), pr.getId());
                            return;
                        }
                    }
                }
                if (candidate != null) {
                    secondLine = candidate.getId();
                }
            }
        }
        boolean priceSet = fourthLine != null && fourthLine.length() != 0;
        boolean durationSet = thirdLine != null && thirdLine.length() != 0;
        // check if all the lines are correct
        if (secondLine == null || secondLine.length() == 0) {
            plugin.message(player, "setup-noRegion");
            return;
        }
        ProtectedRegion region = regionManager.getRegion(secondLine);
        if (region == null) {
            plugin.message(player, "cmd-noRegion", secondLine);
            return;
        }
        FileManager.AddResult addResult = plugin.getFileManager().checkRegionAdd(player, regionManager.getRegion(secondLine), GeneralRegion.RegionType.RENT);
        if (addResult == FileManager.AddResult.BLACKLISTED) {
            plugin.message(player, "setup-blacklisted", secondLine);
        } else if (addResult == FileManager.AddResult.ALREADYADDED) {
            plugin.message(player, "setup-alreadyRentSign");
        } else if (addResult == FileManager.AddResult.NOPERMISSION) {
            plugin.message(player, "setup-noPermission", secondLine);
        } else if (thirdLine != null && thirdLine.length() != 0 && !Utils.checkTimeFormat(thirdLine)) {
            plugin.message(player, "setup-wrongDuration");
        } else {
            double price = 0.0;
            if (priceSet) {
                // Check the fourth line
                try {
                    price = Double.parseDouble(fourthLine);
                } catch (NumberFormatException e) {
                    plugin.message(player, "setup-wrongPrice");
                    return;
                }
            }
            // Add rent to the FileManager
            final RentRegion rent = new RentRegion(secondLine, event.getPlayer().getWorld());
            boolean isMember = plugin.getWorldGuardHandler().containsMember(rent.getRegion(), player.getUniqueId());
            boolean isOwner = plugin.getWorldGuardHandler().containsOwner(rent.getRegion(), player.getUniqueId());
            boolean landlord = (!player.hasPermission("areashop.createrent") && ((player.hasPermission("areashop.createrent.owner") && isOwner) || (player.hasPermission("areashop.createrent.member") && isMember)));
            if (landlord) {
                rent.setLandlord(player.getUniqueId(), player.getName());
            }
            if (priceSet) {
                rent.setPrice(price);
            }
            if (durationSet) {
                rent.setDuration(thirdLine);
            }
            org.bukkit.material.Sign sign = (org.bukkit.material.Sign) event.getBlock().getState().getData();
            rent.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), sign.getFacing(), null);
            // Run commands
            rent.runEventCommands(GeneralRegion.RegionEvent.CREATED, true);
            plugin.getFileManager().addRent(rent);
            rent.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
            plugin.message(player, "setup-rentSuccess", rent);
            // Update the region after the event has written its lines
            Do.sync(rent::update);
            // Run commands
            rent.runEventCommands(GeneralRegion.RegionEvent.CREATED, false);
        }
    } else if (event.getLine(0).contains(plugin.getConfig().getString("signTags.buy"))) {
        // Check for permission
        if (!player.hasPermission("areashop.createbuy") && !player.hasPermission("areashop.createbuy.member") && !player.hasPermission("areashop.createbuy.owner")) {
            plugin.message(player, "setup-noPermissionBuy");
            return;
        }
        // Get the other lines
        String secondLine = event.getLine(1);
        String thirdLine = event.getLine(2);
        // Get the regionManager for accessing regions
        RegionManager regionManager = plugin.getWorldGuard().getRegionManager(event.getPlayer().getWorld());
        // If the secondLine does not contain a name try to find the region by location
        if (secondLine == null || secondLine.length() == 0) {
            Set<ProtectedRegion> regions = plugin.getWorldGuardHandler().getApplicableRegionsSet(event.getBlock().getLocation());
            if (regions != null) {
                boolean first = true;
                ProtectedRegion candidate = null;
                for (ProtectedRegion pr : regions) {
                    if (first) {
                        candidate = pr;
                        first = false;
                    } else {
                        if (pr.getPriority() > candidate.getPriority()) {
                            candidate = pr;
                        } else if (pr.getPriority() < candidate.getPriority()) {
                        // Already got the correct one
                        } else if (pr.getParent() != null && pr.getParent().equals(candidate)) {
                            candidate = pr;
                        } else if (candidate.getParent() != null && candidate.getParent().equals(pr)) {
                        // Already got the correct one
                        } else {
                            plugin.message(player, "setup-couldNotDetect", candidate.getId(), pr.getId());
                            return;
                        }
                    }
                }
                if (candidate != null) {
                    secondLine = candidate.getId();
                }
            }
        }
        boolean priceSet = thirdLine != null && thirdLine.length() != 0;
        // Check if all the lines are correct
        if (secondLine == null || secondLine.length() == 0) {
            plugin.message(player, "setup-noRegion");
            return;
        }
        ProtectedRegion region = regionManager.getRegion(secondLine);
        if (region == null) {
            plugin.message(player, "cmd-noRegion", secondLine);
            return;
        }
        FileManager.AddResult addResult = plugin.getFileManager().checkRegionAdd(player, region, GeneralRegion.RegionType.BUY);
        if (addResult == FileManager.AddResult.BLACKLISTED) {
            plugin.message(player, "setup-blacklisted", secondLine);
        } else if (addResult == FileManager.AddResult.ALREADYADDED) {
            plugin.message(player, "setup-alreadyRentSign");
        } else if (addResult == FileManager.AddResult.NOPERMISSION) {
            plugin.message(player, "setup-noPermission", secondLine);
        } else {
            double price = 0.0;
            if (priceSet) {
                // Check the fourth line
                try {
                    price = Double.parseDouble(thirdLine);
                } catch (NumberFormatException e) {
                    plugin.message(player, "setup-wrongPrice");
                    return;
                }
            }
            // Add buy to the FileManager
            final BuyRegion buy = new BuyRegion(secondLine, event.getPlayer().getWorld());
            boolean isMember = plugin.getWorldGuardHandler().containsMember(buy.getRegion(), player.getUniqueId());
            boolean isOwner = plugin.getWorldGuardHandler().containsOwner(buy.getRegion(), player.getUniqueId());
            boolean landlord = (!player.hasPermission("areashop.createbuy") && ((player.hasPermission("areashop.createbuy.owner") && isOwner) || (player.hasPermission("areashop.createbuy.member") && isMember)));
            if (landlord) {
                buy.setLandlord(player.getUniqueId(), player.getName());
            }
            if (priceSet) {
                buy.setPrice(price);
            }
            org.bukkit.material.Sign sign = (org.bukkit.material.Sign) event.getBlock().getState().getData();
            buy.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), sign.getFacing(), null);
            // Run commands
            buy.runEventCommands(GeneralRegion.RegionEvent.CREATED, true);
            plugin.getFileManager().addBuy(buy);
            buy.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
            plugin.message(player, "setup-buySuccess", buy);
            // Update the region after the event has written its lines
            Do.sync(buy::update);
            // Run commands
            buy.runEventCommands(GeneralRegion.RegionEvent.CREATED, false);
        }
    } else if (event.getLine(0).contains(plugin.getConfig().getString("signTags.add"))) {
        // Check for permission
        if (!player.hasPermission("areashop.addsign")) {
            plugin.message(player, "addsign-noPermission");
            return;
        }
        // Get the other lines
        String secondLine = event.getLine(1);
        String thirdLine = event.getLine(2);
        GeneralRegion region;
        if (secondLine != null && secondLine.length() != 0) {
            // Get region by secondLine of the sign
            region = plugin.getFileManager().getRegion(secondLine);
            if (region == null) {
                plugin.message(player, "addSign-notRegistered", secondLine);
                return;
            }
        } else {
            // Get region by sign position
            List<GeneralRegion> regions = Utils.getRegionsInSelection(new CuboidSelection(event.getBlock().getWorld(), event.getBlock().getLocation(), event.getBlock().getLocation()));
            if (regions.isEmpty()) {
                plugin.message(player, "addsign-noRegions");
                return;
            } else if (regions.size() > 1) {
                plugin.message(player, "addsign-couldNotDetectSign", regions.get(0).getName(), regions.get(1).getName());
                return;
            }
            region = regions.get(0);
        }
        org.bukkit.material.Sign sign = (org.bukkit.material.Sign) event.getBlock().getState().getData();
        if (thirdLine == null || thirdLine.length() == 0) {
            region.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), sign.getFacing(), null);
            plugin.message(player, "addsign-success", region);
        } else {
            region.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), sign.getFacing(), thirdLine);
            plugin.message(player, "addsign-successProfile", thirdLine, region);
        }
        // Update the region later because this event will do it first
        Do.sync(region::update);
    }
}
Also used : Player(org.bukkit.entity.Player) Set(java.util.Set) RentRegion(me.wiefferink.areashop.regions.RentRegion) FileManager(me.wiefferink.areashop.managers.FileManager) CuboidSelection(com.sk89q.worldedit.bukkit.selections.CuboidSelection) BuyRegion(me.wiefferink.areashop.regions.BuyRegion) ProtectedRegion(com.sk89q.worldguard.protection.regions.ProtectedRegion) GeneralRegion(me.wiefferink.areashop.regions.GeneralRegion) RegionManager(com.sk89q.worldguard.protection.managers.RegionManager) EventHandler(org.bukkit.event.EventHandler)

Aggregations

FileManager (me.wiefferink.areashop.managers.FileManager)4 Player (org.bukkit.entity.Player)3 ProtectedRegion (com.sk89q.worldguard.protection.regions.ProtectedRegion)2 Set (java.util.Set)2 CommandManager (me.wiefferink.areashop.managers.CommandManager)2 FeatureManager (me.wiefferink.areashop.managers.FeatureManager)2 Manager (me.wiefferink.areashop.managers.Manager)2 SignLinkerManager (me.wiefferink.areashop.managers.SignLinkerManager)2 BuyRegion (me.wiefferink.areashop.regions.BuyRegion)2 GeneralRegion (me.wiefferink.areashop.regions.GeneralRegion)2 RentRegion (me.wiefferink.areashop.regions.RentRegion)2 LanguageManager (me.wiefferink.interactivemessenger.source.LanguageManager)2 WorldEditPlugin (com.sk89q.worldedit.bukkit.WorldEditPlugin)1 CuboidSelection (com.sk89q.worldedit.bukkit.selections.CuboidSelection)1 Selection (com.sk89q.worldedit.bukkit.selections.Selection)1 WorldGuardPlugin (com.sk89q.worldguard.bukkit.WorldGuardPlugin)1 RegionManager (com.sk89q.worldguard.protection.managers.RegionManager)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1