Compare commits

..
Author SHA1 Message Date
Andrew Wong 9f04efb3e8 Add a sign error logger 2021-06-03 11:58:55 +02:00
86 changed files with 7566 additions and 10283 deletions

No files matched your search

+285 -342
View File
@@ -1,342 +1,285 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>1.0</version>
</parent>
<artifactId>areashop</artifactId>
<packaging>jar</packaging>
<name>AreaShop</name>
<version>2.7</version> <!-- Main plugin version -->
<repositories>
<repository>
<id>papermc</id>
<url>https://papermc.io/repo/repository/maven-public/</url>
</repository>
<repository>
<id>aikar</id>
<url>https://repo.aikar.co/content/groups/aikar/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>20.1.0</version>
</dependency>
<!-- Bukkit, AreaShop aims to support 1.15.2+ -->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.15.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- InteractiveMessenger library -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>interactivemessenger</artifactId>
<version>1.1-SNAPSHOT</version>
</dependency>
<!-- TaskChain library -->
<dependency>
<groupId>co.aikar</groupId>
<artifactId>taskchain-bukkit</artifactId>
<version>3.7.2</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>5.0.1</version>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.inject.extensions</groupId>
<artifactId>guice-assistedinject</artifactId>
<version>5.0.1</version>
<exclusions>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- PaperLib -->
<dependency>
<groupId>io.papermc</groupId>
<artifactId>paperlib</artifactId>
<version>1.0.6</version>
</dependency>
<!-- WorldEdit/WorldGuard -->
<dependency>
<groupId>com.sk89q.worldedit</groupId>
<artifactId>worldedit-bukkit</artifactId>
<version>7.1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
<version>7.0.3</version>
<scope>provided</scope>
</dependency>
<!-- Interfaces that specific WorldGuard and WorldEdit versions are built against -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>latest</version>
<scope>compile</scope>
</dependency>
<!-- WorldGuard implementations -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldguard-7</artifactId>
<version>latest</version>
<scope>compile</scope>
</dependency>
<!-- WorldEdit implementations -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldedit-7</artifactId>
<version>latest</version>
<scope>compile</scope>
</dependency>
<!-- FAWE compat -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-fawe-1-15</artifactId>
<version>latest</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- NMS Implementations -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-nms-1-15</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-nms-1-16</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!-- Vault -->
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
</dependency>
<!-- bStats -->
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
<profiles>
<!-- Copy the jar file to a test server, activate by using -DcopyResult="/path/to/test/server" -->
<profile>
<id>test-locally</id>
<activation>
<property>
<name>copyResult</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<configuration>
<target>
<copy file="./target/${project.build.finalName}.jar"
tofile="${copyResult}\${project.build.finalName}.jar"/>
</target>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- Package the source files in a jar, activate by using -Dsources -->
<profile>
<id>package-sources</id>
<activation>
<property>
<name>sources</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- Produce javadoc files, activate by using -Djavadoc -->
<profile>
<id>generate-javadoc</id>
<activation>
<property>
<name>javadoc</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<excludePackageNames>me.wiefferink.areashop.lib</excludePackageNames>
<destDir>${javadoc}</destDir>
<links>
<link>https://hub.spigotmc.org/javadocs/bukkit/</link>
<link>http://docs.sk89q.com/worldedit/apidocs/</link>
<link>http://docs.sk89q.com/worldguard/apidocs/</link>
</links>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<directory>target</directory>
<finalName>AreaShop</finalName>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>plugin.yml</include>
<include>config.yml</include>
<include>hiddenConfig.yml</include>
<include>default.yml</include>
<include>README.md</include>
<include>lang/*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<!-- Relocate TaskChain -->
<relocation>
<pattern>co.aikar.taskchain</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.taskchain</shadedPattern>
</relocation>
<!-- Relocate messaging framework -->
<relocation>
<pattern>me.wiefferink.interactivemessenger</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.interactivemessenger</shadedPattern>
</relocation>
<!-- Relocate bstats -->
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.bstats</shadedPattern>
</relocation>
<!-- Relocate PaperLib -->
<relocation>
<pattern>io.papermc</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.paperlib</shadedPattern>
</relocation>
<!-- Relocate Guice -->
<relocation>
<pattern>com.google.inject</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.google.inject</shadedPattern>
</relocation>
<relocation>
<pattern>javax.inject</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.javax.inject</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>1.0</version>
</parent>
<artifactId>areashop</artifactId>
<packaging>jar</packaging>
<name>AreaShop</name>
<version>2.7</version> <!-- Main plugin version -->
<repositories>
<repository>
<id>papermc</id>
<url>https://papermc.io/repo/repository/maven-public/</url>
</repository>
<repository>
<id>aikar</id>
<url>https://repo.aikar.co/content/groups/aikar/</url>
</repository>
</repositories>
<dependencies>
<!-- Bukkit, AreaShop aims to support 1.16.5+ -->
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.16.5-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<!-- InteractiveMessenger library -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>interactivemessenger</artifactId>
<version>1.1-SNAPSHOT</version>
</dependency>
<!-- TaskChain library -->
<dependency>
<groupId>co.aikar</groupId>
<artifactId>taskchain-bukkit</artifactId>
<version>3.7.2</version>
</dependency>
<dependency>
<groupId>io.papermc</groupId>
<artifactId>paperlib</artifactId>
<version>1.0.4</version>
</dependency>
<!-- WorldEdit/WorldGuard -->
<dependency>
<groupId>com.sk89q.worldedit</groupId>
<artifactId>worldedit-bukkit</artifactId>
<version>7.1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
<version>7.0.3</version>
<scope>provided</scope>
</dependency>
<!-- Interfaces that specific WorldGuard and WorldEdit versions are built against -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>latest</version>
<scope>compile</scope>
</dependency>
<!-- WorldGuard implementations -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldguard-7</artifactId>
<version>latest</version>
<scope>compile</scope>
</dependency>
<!-- WorldEdit implementations -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-worldedit-7</artifactId>
<version>latest</version>
<scope>compile</scope>
</dependency>
<!-- FAWE compat -->
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-fawe-1-15</artifactId>
<version>latest</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Vault -->
<dependency>
<groupId>net.milkbowl.vault</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.7</version>
<scope>provided</scope>
</dependency>
<!-- bStats -->
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
<profiles>
<!-- Copy the jar file to a test server, activate by using -DcopyResult="/path/to/test/server" -->
<profile>
<id>test-locally</id>
<activation>
<property>
<name>copyResult</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<configuration>
<target>
<copy file="./target/${project.build.finalName}.jar"
tofile="${copyResult}\${project.build.finalName}.jar"/>
</target>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- Package the source files in a jar, activate by using -Dsources -->
<profile>
<id>package-sources</id>
<activation>
<property>
<name>sources</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<!-- Produce javadoc files, activate by using -Djavadoc -->
<profile>
<id>generate-javadoc</id>
<activation>
<property>
<name>javadoc</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>package</phase>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<excludePackageNames>me.wiefferink.areashop.lib</excludePackageNames>
<destDir>${javadoc}</destDir>
<links>
<link>https://hub.spigotmc.org/javadocs/bukkit/</link>
<link>http://docs.sk89q.com/worldedit/apidocs/</link>
<link>http://docs.sk89q.com/worldguard/apidocs/</link>
</links>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<build>
<directory>target</directory>
<finalName>AreaShop</finalName>
<resources>
<resource>
<targetPath>.</targetPath>
<filtering>true</filtering>
<directory>src/main/resources</directory>
<includes>
<include>plugin.yml</include>
<include>config.yml</include>
<include>hiddenConfig.yml</include>
<include>default.yml</include>
<include>README.md</include>
<include>lang/*.yml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<relocations>
<!-- Relocate TaskChain -->
<relocation>
<pattern>co.aikar.taskchain</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.taskchain</shadedPattern>
</relocation>
<!-- Relocate messaging framework -->
<relocation>
<pattern>me.wiefferink.interactivemessenger</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.interactivemessenger</shadedPattern>
</relocation>
<!-- Relocate bstats -->
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.bstats</shadedPattern>
</relocation>
<relocation>
<pattern>io.papermc</pattern>
<shadedPattern>me.wiefferink.areashop.shaded.paperlib</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
File diff suppressed because it is too large. Load diff
@@ -10,10 +10,8 @@ import me.wiefferink.areashop.events.notify.RentedRegionEvent;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.managers.FileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.regions.util.RegionEvent;
import me.wiefferink.areashop.regions.util.RegionType;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
@@ -118,11 +116,11 @@ public class AddCommand extends CommandAreaShop {
final Player finalPlayer = player;
AreaShop.debug("Starting add task with " + regions.size() + " regions");
TreeSet<LegacyGeneralRegion> regionsSuccess = new TreeSet<>();
TreeSet<LegacyGeneralRegion> regionsAlready = new TreeSet<>();
TreeSet<LegacyGeneralRegion> regionsAlreadyOtherWorld = new TreeSet<>();
TreeSet<LegacyGeneralRegion> regionsRentCancelled = new TreeSet<>(); // Denied by an event listener
TreeSet<LegacyGeneralRegion> regionsBuyCancelled = new TreeSet<>(); // Denied by an event listener
TreeSet<GeneralRegion> regionsSuccess = new TreeSet<>();
TreeSet<GeneralRegion> regionsAlready = new TreeSet<>();
TreeSet<GeneralRegion> regionsAlreadyOtherWorld = new TreeSet<>();
TreeSet<GeneralRegion> regionsRentCancelled = new TreeSet<>(); // Denied by an event listener
TreeSet<GeneralRegion> regionsBuyCancelled = new TreeSet<>(); // Denied by an event listener
TreeSet<String> namesBlacklisted = new TreeSet<>();
TreeSet<String> namesNoPermission = new TreeSet<>();
TreeSet<String> namesAddCancelled = new TreeSet<>(); // Denied by an event listener
@@ -140,7 +138,7 @@ public class AddCommand extends CommandAreaShop {
} else {
type = "buy";
}
FileManager.AddResult result = plugin.getFileManager().checkRegionAdd(sender, region, world, isRent ? RegionType.RENT : RegionType.BUY);
FileManager.AddResult result = plugin.getFileManager().checkRegionAdd(sender, region, world, isRent ? GeneralRegion.RegionType.RENT : GeneralRegion.RegionType.BUY);
if(result == FileManager.AddResult.ALREADYADDED) {
regionsAlready.add(plugin.getFileManager().getRegion(regionName));
} else if(result == FileManager.AddResult.ALREADYADDEDOTHERWORLD) {
@@ -176,10 +174,10 @@ public class AddCommand extends CommandAreaShop {
AddingRegionEvent event = plugin.getFileManager().addRegion(rent);
if (event.isCancelled()) {
namesAddCancelled.add(rent.getRegionId());
namesAddCancelled.add(rent.getName());
return;
}
rent.handleSchematicEvent(RegionEvent.CREATED);
rent.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
rent.update();
// Add existing owners/members if any
@@ -198,7 +196,7 @@ public class AddCommand extends CommandAreaShop {
rent.updateLastActiveTime();
// Fire schematic event and updated times extended
rent.handleSchematicEvent(RegionEvent.RENTED);
rent.handleSchematicEvent(GeneralRegion.RegionEvent.RENTED);
// Add others as friends
for(UUID friend : existing) {
@@ -219,11 +217,11 @@ public class AddCommand extends CommandAreaShop {
AddingRegionEvent event = plugin.getFileManager().addRegion(buy);
if (event.isCancelled()) {
namesAddCancelled.add(buy.getRegionId());
namesAddCancelled.add(buy.getName());
return;
}
buy.handleSchematicEvent(RegionEvent.CREATED);
buy.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
buy.update();
// Add existing owners/members if any
@@ -241,7 +239,7 @@ public class AddCommand extends CommandAreaShop {
buy.updateLastActiveTime();
// Update everything
buy.handleSchematicEvent(RegionEvent.BOUGHT);
buy.handleSchematicEvent(GeneralRegion.RegionEvent.BOUGHT);
// Add others as friends
for (UUID friend : existing) {
@@ -1,141 +1,141 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class AddfriendCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop addfriend";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.addfriendall") || target.hasPermission("areashop.addfriend")) {
return "help-addFriend";
}
return null;
}
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.addfriend") && !sender.hasPermission("areashop.addfriendall")) {
plugin.message(sender, "addfriend-noPermission");
return;
}
if(args.length < 2) {
plugin.message(sender, "addfriend-help");
return;
}
LegacyGeneralRegion region;
if(args.length <= 2) {
if(sender instanceof Player) {
// get the region by location
List<LegacyGeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
}
if(sender.hasPermission("areashop.addfriendall")) {
if((region instanceof RentRegion && !((RentRegion)region).isRented())
|| (region instanceof BuyRegion && !((BuyRegion)region).isSold())) {
plugin.message(sender, "addfriend-noOwner", region);
return;
}
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(friend.getLastPlayed() == 0 && !friend.isOnline() && !plugin.getConfig().getBoolean("addFriendNotExistingPlayers")) {
plugin.message(sender, "addfriend-notVisited", args[1], region);
return;
}
if(region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "addfriend-alreadyAdded", friend.getName(), region);
return;
}
if(region.isOwner(friend.getUniqueId())) {
plugin.message(sender, "addfriend-self", friend.getName(), region);
return;
}
if(region.getFriendsFeature().addFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "addfriend-successOther", friend.getName(), region);
}
} else {
if(sender.hasPermission("areashop.addfriend") && sender instanceof Player) {
if(region.isOwner((Player)sender)) {
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(friend.getLastPlayed() == 0 && !friend.isOnline() && !plugin.getConfig().getBoolean("addFriendNotExistingPlayers")) {
plugin.message(sender, "addfriend-notVisited", args[1], region);
return;
}
if(region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "addfriend-alreadyAdded", friend.getName(), region);
return;
}
if(region.isOwner(friend.getUniqueId())) {
plugin.message(sender, "addfriend-self", friend.getName(), region);
return;
}
if(region.getFriendsFeature().addFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "addfriend-success", friend.getName(), region);
}
} else {
plugin.message(sender, "addfriend-noPermissionOther", region);
}
} else {
plugin.message(sender, "addfriend-noPermission", region);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class AddfriendCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop addfriend";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.addfriendall") || target.hasPermission("areashop.addfriend")) {
return "help-addFriend";
}
return null;
}
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.addfriend") && !sender.hasPermission("areashop.addfriendall")) {
plugin.message(sender, "addfriend-noPermission");
return;
}
if(args.length < 2) {
plugin.message(sender, "addfriend-help");
return;
}
GeneralRegion region;
if(args.length <= 2) {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
}
if(sender.hasPermission("areashop.addfriendall")) {
if((region instanceof RentRegion && !((RentRegion)region).isRented())
|| (region instanceof BuyRegion && !((BuyRegion)region).isSold())) {
plugin.message(sender, "addfriend-noOwner", region);
return;
}
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(friend.getLastPlayed() == 0 && !friend.isOnline() && !plugin.getConfig().getBoolean("addFriendNotExistingPlayers")) {
plugin.message(sender, "addfriend-notVisited", args[1], region);
return;
}
if(region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "addfriend-alreadyAdded", friend.getName(), region);
return;
}
if(region.isOwner(friend.getUniqueId())) {
plugin.message(sender, "addfriend-self", friend.getName(), region);
return;
}
if(region.getFriendsFeature().addFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "addfriend-successOther", friend.getName(), region);
}
} else {
if(sender.hasPermission("areashop.addfriend") && sender instanceof Player) {
if(region.isOwner((Player)sender)) {
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(friend.getLastPlayed() == 0 && !friend.isOnline() && !plugin.getConfig().getBoolean("addFriendNotExistingPlayers")) {
plugin.message(sender, "addfriend-notVisited", args[1], region);
return;
}
if(region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "addfriend-alreadyAdded", friend.getName(), region);
return;
}
if(region.isOwner(friend.getUniqueId())) {
plugin.message(sender, "addfriend-self", friend.getName(), region);
return;
}
if(region.getFriendsFeature().addFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "addfriend-success", friend.getName(), region);
}
} else {
plugin.message(sender, "addfriend-noPermissionOther", region);
}
} else {
plugin.message(sender, "addfriend-noPermission", region);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
}
return result;
}
}
@@ -2,7 +2,7 @@ package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.features.signs.RegionSign;
import me.wiefferink.areashop.features.signs.SignsFeature;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Materials;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Material;
@@ -60,7 +60,7 @@ public class AddsignCommand extends CommandAreaShop {
return;
}
LegacyGeneralRegion region;
GeneralRegion region;
if (args.length > 1) {
// Get region by argument
region = plugin.getFileManager().getRegion(args[1]);
@@ -70,12 +70,12 @@ public class AddsignCommand extends CommandAreaShop {
}
} else {
// Get region by sign position
List<LegacyGeneralRegion> regions = Utils.getImportantRegions(block.getLocation());
List<GeneralRegion> regions = Utils.getImportantRegions(block.getLocation());
if (regions.isEmpty()) {
plugin.message(sender, "addsign-noRegions");
return;
} else if (regions.size() > 1) {
plugin.message(sender, "addsign-couldNotDetect", regions.get(0).getRegionId(), regions.get(1).getRegionId());
plugin.message(sender, "addsign-couldNotDetect", regions.get(0).getName(), regions.get(1).getName());
return;
}
region = regions.get(0);
@@ -1,69 +1,69 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class BuyCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop buy";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.buy")) {
return "help-buy";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.buy")) {
plugin.message(sender, "buy-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
Player player = (Player)sender;
if(args.length > 1 && args[1] != null) {
BuyRegion region = plugin.getFileManager().getBuy(args[1]);
if(region == null) {
plugin.message(player, "buy-notBuyable", args[1]);
} else {
region.buy(player);
}
} else {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
} else {
regions.get(0).buy(player);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(BuyRegion region : plugin.getFileManager().getBuys()) {
if(!region.isSold()) {
result.add(region.getRegionId());
}
}
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class BuyCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop buy";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.buy")) {
return "help-buy";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.buy")) {
plugin.message(sender, "buy-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
Player player = (Player)sender;
if(args.length > 1 && args[1] != null) {
BuyRegion region = plugin.getFileManager().getBuy(args[1]);
if(region == null) {
plugin.message(player, "buy-notBuyable", args[1]);
} else {
region.buy(player);
}
} else {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
} else {
regions.get(0).buy(player);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(BuyRegion region : plugin.getFileManager().getBuys()) {
if(!region.isSold()) {
result.add(region.getName());
}
}
}
return result;
}
}
@@ -28,11 +28,12 @@ public abstract class CommandAreaShop {
* @return true if it can execute the command, false otherwise
*/
public boolean canExecute(Command command, String[] args) {
String commandString = command.getName() + " " + StringUtils.join(args, " ");
if(commandString.length() > getCommandStart().length()) {
return commandString.toLowerCase().startsWith(getCommandStart().toLowerCase() + " ");
String commandString = command.getName() + " " + StringUtils.join(args, " ").toLowerCase();
final String start = getCommandStart().toLowerCase();
if(commandString.length() > start.length()) {
return commandString.startsWith(start + " ");
}
return commandString.toLowerCase().startsWith(getCommandStart().toLowerCase());
return commandString.startsWith(start);
}
/**
@@ -3,7 +3,7 @@ package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.events.ask.DeletingRegionEvent;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
@@ -50,16 +50,16 @@ public class DelCommand extends CommandAreaShop {
plugin.message(player, "cmd-noSelection");
return;
}
List<LegacyGeneralRegion> regions = Utils.getRegionsInSelection(selection);
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions == null || regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound");
return;
}
// Start removing the regions that he has permission for
ArrayList<String> namesSuccess = new ArrayList<>();
TreeSet<LegacyGeneralRegion> regionsFailed = new TreeSet<>();
TreeSet<LegacyGeneralRegion> regionsCancelled = new TreeSet<>();
for(LegacyGeneralRegion region : regions) {
TreeSet<GeneralRegion> regionsFailed = new TreeSet<>();
TreeSet<GeneralRegion> regionsCancelled = new TreeSet<>();
for(GeneralRegion region : regions) {
boolean isLandlord = region.isLandlord(((Player)sender).getUniqueId());
if(region instanceof RentRegion) {
if(!sender.hasPermission("areashop.destroyrent") && !(isLandlord && sender.hasPermission("areashop.destroyrent.landlord"))) {
@@ -77,7 +77,7 @@ public class DelCommand extends CommandAreaShop {
if (event.isCancelled()) {
regionsCancelled.add(region);
} else {
namesSuccess.add(region.getRegionId());
namesSuccess.add(region.getName());
}
}
@@ -92,7 +92,7 @@ public class DelCommand extends CommandAreaShop {
plugin.message(sender, "del-cancelled", Utils.combinedMessage(regionsCancelled, "region"));
}
} else {
LegacyGeneralRegion region = plugin.getFileManager().getRegion(args[1]);
GeneralRegion region = plugin.getFileManager().getRegion(args[1]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[1]);
return;
@@ -1,139 +1,139 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class DelfriendCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop delfriend";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.delfriendall") || target.hasPermission("areashop.delfriend")) {
return "help-delFriend";
}
return null;
}
/**
* Check if a person can remove friends.
* @param person The person to check
* @param region The region to check for
* @return true if the person can remove friends, otherwise false
*/
public static boolean canUse(CommandSender person, LegacyGeneralRegion region) {
if(person.hasPermission("areashop.delfriendall")) {
return true;
}
if(person instanceof Player) {
Player player = (Player)person;
return region.isOwner(player) && player.hasPermission("areashop.delfriend");
}
return false;
}
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.delfriend") && !sender.hasPermission("areashop.delfriendall")) {
plugin.message(sender, "delfriend-noPermission");
return;
}
if(args.length < 2) {
plugin.message(sender, "delfriend-help");
return;
}
LegacyGeneralRegion region;
if(args.length <= 2) {
if(sender instanceof Player) {
// get the region by location
List<LegacyGeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
}
if(sender.hasPermission("areashop.delfriendall")) {
if((region instanceof RentRegion && !((RentRegion)region).isRented())
|| (region instanceof BuyRegion && !((BuyRegion)region).isSold())) {
plugin.message(sender, "delfriend-noOwner", region);
return;
}
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(!region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "delfriend-notAdded", friend.getName(), region);
return;
}
if(region.getFriendsFeature().deleteFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "delfriend-successOther", friend.getName(), region);
}
} else {
if(sender.hasPermission("areashop.delfriend") && sender instanceof Player) {
if(region.isOwner((Player)sender)) {
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(!region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "delfriend-notAdded", friend.getName(), region);
return;
}
if(region.getFriendsFeature().deleteFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "delfriend-success", friend.getName(), region);
}
} else {
plugin.message(sender, "delfriend-noPermissionOther", region);
}
} else {
plugin.message(sender, "delfriend-noPermission", region);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class DelfriendCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop delfriend";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.delfriendall") || target.hasPermission("areashop.delfriend")) {
return "help-delFriend";
}
return null;
}
/**
* Check if a person can remove friends.
* @param person The person to check
* @param region The region to check for
* @return true if the person can remove friends, otherwise false
*/
public static boolean canUse(CommandSender person, GeneralRegion region) {
if(person.hasPermission("areashop.delfriendall")) {
return true;
}
if(person instanceof Player) {
Player player = (Player)person;
return region.isOwner(player) && player.hasPermission("areashop.delfriend");
}
return false;
}
@SuppressWarnings("deprecation")
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.delfriend") && !sender.hasPermission("areashop.delfriendall")) {
plugin.message(sender, "delfriend-noPermission");
return;
}
if(args.length < 2) {
plugin.message(sender, "delfriend-help");
return;
}
GeneralRegion region;
if(args.length <= 2) {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
}
if(sender.hasPermission("areashop.delfriendall")) {
if((region instanceof RentRegion && !((RentRegion)region).isRented())
|| (region instanceof BuyRegion && !((BuyRegion)region).isSold())) {
plugin.message(sender, "delfriend-noOwner", region);
return;
}
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(!region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "delfriend-notAdded", friend.getName(), region);
return;
}
if(region.getFriendsFeature().deleteFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "delfriend-successOther", friend.getName(), region);
}
} else {
if(sender.hasPermission("areashop.delfriend") && sender instanceof Player) {
if(region.isOwner((Player)sender)) {
OfflinePlayer friend = Bukkit.getOfflinePlayer(args[1]);
if(!region.getFriendsFeature().getFriends().contains(friend.getUniqueId())) {
plugin.message(sender, "delfriend-notAdded", friend.getName(), region);
return;
}
if(region.getFriendsFeature().deleteFriend(friend.getUniqueId(), sender)) {
region.update();
plugin.message(sender, "delfriend-success", friend.getName(), region);
}
} else {
plugin.message(sender, "delfriend-noPermissionOther", region);
}
} else {
plugin.message(sender, "delfriend-noPermission", region);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
}
return result;
}
}
@@ -1,113 +1,113 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
public class GroupaddCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop groupadd";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.groupadd")) {
return "help-groupadd";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.groupadd")) {
plugin.message(sender, "groupadd-noPermission");
return;
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "groupadd-help");
return;
}
RegionGroup group = plugin.getFileManager().getGroup(args[1]);
if(group == null) {
group = new RegionGroup(plugin, args[1]);
plugin.getFileManager().addGroup(group);
}
if(args.length == 2) {
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-weOnlyByPlayer");
return;
}
Player player = (Player)sender;
WorldEditSelection selection = plugin.getWorldEditHandler().getPlayerSelection(player);
if(selection == null) {
plugin.message(player, "cmd-noSelection");
return;
}
List<LegacyGeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound");
return;
}
TreeSet<LegacyGeneralRegion> regionsSuccess = new TreeSet<>();
TreeSet<LegacyGeneralRegion> regionsFailed = new TreeSet<>();
for(LegacyGeneralRegion region : regions) {
if(group.addMember(region)) {
regionsSuccess.add(region);
} else {
regionsFailed.add(region);
}
}
if(!regionsSuccess.isEmpty()) {
plugin.message(player, "groupadd-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region"));
}
if(!regionsFailed.isEmpty()) {
plugin.message(player, "groupadd-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region"));
}
// Update all regions, this does it in a task, updating them without lag
plugin.getFileManager().updateRegions(new ArrayList<>(regionsSuccess), player);
} else {
LegacyGeneralRegion region = plugin.getFileManager().getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
if(group.addMember(region)) {
region.update();
plugin.message(sender, "groupadd-success", group.getName(), group.getMembers().size(), region);
} else {
plugin.message(sender, "groupadd-failed", group.getName(), region);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getGroupNames();
} else if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
public class GroupaddCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop groupadd";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.groupadd")) {
return "help-groupadd";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.groupadd")) {
plugin.message(sender, "groupadd-noPermission");
return;
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "groupadd-help");
return;
}
RegionGroup group = plugin.getFileManager().getGroup(args[1]);
if(group == null) {
group = new RegionGroup(plugin, args[1]);
plugin.getFileManager().addGroup(group);
}
if(args.length == 2) {
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-weOnlyByPlayer");
return;
}
Player player = (Player)sender;
WorldEditSelection selection = plugin.getWorldEditHandler().getPlayerSelection(player);
if(selection == null) {
plugin.message(player, "cmd-noSelection");
return;
}
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound");
return;
}
TreeSet<GeneralRegion> regionsSuccess = new TreeSet<>();
TreeSet<GeneralRegion> regionsFailed = new TreeSet<>();
for(GeneralRegion region : regions) {
if(group.addMember(region)) {
regionsSuccess.add(region);
} else {
regionsFailed.add(region);
}
}
if(!regionsSuccess.isEmpty()) {
plugin.message(player, "groupadd-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region"));
}
if(!regionsFailed.isEmpty()) {
plugin.message(player, "groupadd-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region"));
}
// Update all regions, this does it in a task, updating them without lag
plugin.getFileManager().updateRegions(new ArrayList<>(regionsSuccess), player);
} else {
GeneralRegion region = plugin.getFileManager().getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
if(group.addMember(region)) {
region.update();
plugin.message(sender, "groupadd-success", group.getName(), group.getMembers().size(), region);
} else {
plugin.message(sender, "groupadd-failed", group.getName(), region);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getGroupNames();
} else if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
}
return result;
}
}
@@ -1,115 +1,115 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
public class GroupdelCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop groupdel";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.groupdel")) {
return "help-groupdel";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.groupdel")) {
plugin.message(sender, "groupdel-noPermission");
return;
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "groupdel-help");
return;
}
RegionGroup group = plugin.getFileManager().getGroup(args[1]);
if(group == null) {
plugin.message(sender, "groupdel-wrongGroup", args[1]);
return;
}
if(args.length == 2) {
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-weOnlyByPlayer");
return;
}
Player player = (Player)sender;
WorldEditSelection selection = plugin.getWorldEditHandler().getPlayerSelection(player);
if(selection == null) {
plugin.message(player, "cmd-noSelection");
return;
}
List<LegacyGeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound");
return;
}
TreeSet<LegacyGeneralRegion> regionsSuccess = new TreeSet<>();
TreeSet<LegacyGeneralRegion> regionsFailed = new TreeSet<>();
for(LegacyGeneralRegion region : regions) {
if(group.removeMember(region)) {
regionsSuccess.add(region);
} else {
regionsFailed.add(region);
}
}
if(!regionsSuccess.isEmpty()) {
plugin.message(player, "groupdel-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region"));
}
if(!regionsFailed.isEmpty()) {
plugin.message(player, "groupdel-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region"));
}
// Update all regions, this does it in a task, updating them without lag
plugin.getFileManager().updateRegions(new ArrayList<>(regionsSuccess), player);
group.saveRequired();
} else {
LegacyGeneralRegion region = plugin.getFileManager().getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
if(group.removeMember(region)) {
region.update();
plugin.message(sender, "groupdel-success", group.getName(), group.getMembers().size(), region);
} else {
plugin.message(sender, "groupdel-failed", group.getName(), region);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getGroupNames();
} else if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
public class GroupdelCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop groupdel";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.groupdel")) {
return "help-groupdel";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.groupdel")) {
plugin.message(sender, "groupdel-noPermission");
return;
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "groupdel-help");
return;
}
RegionGroup group = plugin.getFileManager().getGroup(args[1]);
if(group == null) {
plugin.message(sender, "groupdel-wrongGroup", args[1]);
return;
}
if(args.length == 2) {
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-weOnlyByPlayer");
return;
}
Player player = (Player)sender;
WorldEditSelection selection = plugin.getWorldEditHandler().getPlayerSelection(player);
if(selection == null) {
plugin.message(player, "cmd-noSelection");
return;
}
List<GeneralRegion> regions = Utils.getRegionsInSelection(selection);
if(regions.isEmpty()) {
plugin.message(player, "cmd-noRegionsFound");
return;
}
TreeSet<GeneralRegion> regionsSuccess = new TreeSet<>();
TreeSet<GeneralRegion> regionsFailed = new TreeSet<>();
for(GeneralRegion region : regions) {
if(group.removeMember(region)) {
regionsSuccess.add(region);
} else {
regionsFailed.add(region);
}
}
if(!regionsSuccess.isEmpty()) {
plugin.message(player, "groupdel-weSuccess", group.getName(), Utils.combinedMessage(regionsSuccess, "region"));
}
if(!regionsFailed.isEmpty()) {
plugin.message(player, "groupdel-weFailed", group.getName(), Utils.combinedMessage(regionsFailed, "region"));
}
// Update all regions, this does it in a task, updating them without lag
plugin.getFileManager().updateRegions(new ArrayList<>(regionsSuccess), player);
group.saveRequired();
} else {
GeneralRegion region = plugin.getFileManager().getRegion(args[2]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
if(group.removeMember(region)) {
region.update();
plugin.message(sender, "groupdel-success", group.getName(), group.getMembers().size(), region);
} else {
plugin.message(sender, "groupdel-failed", group.getName(), region);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getGroupNames();
} else if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
}
return result;
}
}
@@ -1,481 +1,481 @@
package me.wiefferink.areashop.commands;
import com.google.common.base.Charsets;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.features.signs.RegionSign;
import me.wiefferink.areashop.features.signs.SignsFeature;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class ImportJob {
private final AreaShop plugin;
private final CommandSender sender;
/**
* Create and execute the import.
* @param sender CommandSender that should receive progress updates
*/
public ImportJob(CommandSender sender) {
this.sender = sender;
this.plugin = AreaShop.getInstance();
execute();
}
/**
* Execute the job.
*/
private void execute() {
// Check for RegionForSale data
File regionForSaleFolder = new File(plugin.getDataFolder().getParentFile().getAbsolutePath(), "RegionForSale");
if(!regionForSaleFolder.exists()) {
message("import-noPluginFolder", regionForSaleFolder.getName());
return;
}
File worldsFolder = new File(regionForSaleFolder.getAbsolutePath(), "worlds");
if(!worldsFolder.exists()) {
message("import-noWorldsFolder");
return;
}
File[] worldFolders = worldsFolder.listFiles();
if(worldFolders == null) {
message("import-noWorldsFolder");
return;
}
// Import data for each world
message("import-start");
// Group with settings for all imported regions
RegionGroup regionForSaleGroup = new RegionGroup(plugin, "RegionForSale");
plugin.getFileManager().addGroup(regionForSaleGroup);
// Import /RegionForSale/config.yml settings
File regionForSaleConfigFile = new File(regionForSaleFolder.getAbsolutePath(), "config.yml");
YamlConfiguration regionForSaleConfig = loadConfiguration(regionForSaleConfigFile);
if(regionForSaleConfig == null) {
messageNoPrefix("import-loadConfigFailed", regionForSaleConfigFile.getAbsolutePath());
regionForSaleConfig = new YamlConfiguration();
} else {
importRegionSettings(regionForSaleConfig, regionForSaleGroup.getSettings(), null, false);
regionForSaleGroup.setSetting("priority", 0);
}
// Import /RegionForSale/general.yml settings
File regionForSaleGeneralFile = new File(regionForSaleFolder.getAbsolutePath(), "config.yml");
YamlConfiguration regionForSaleGeneral = loadConfiguration(regionForSaleConfigFile);
if(regionForSaleGeneral == null) {
messageNoPrefix("import-loadConfigFailed", regionForSaleGeneralFile.getAbsolutePath());
} else {
// Collection interval of RegionForSale maps to rent duration
String duration = "1 day";
if(regionForSaleGeneral.isLong("interval.collect_money")) {
duration = minutesToString(regionForSaleGeneral.getLong("interval.collect_money"));
}
regionForSaleGroup.setSetting("rent.duration", duration);
// Global economy account has an effect close to landlord in AreaShop
if(regionForSaleGeneral.isString("global_econ_account")) {
regionForSaleGroup.setSetting("general.landlordName", regionForSaleGeneral.getString("global_econ_account"));
}
}
regionForSaleGroup.saveRequired();
////////// Handle defaults of RegionForSale
// Set autoExtend, to keep the same behavior as RegionForSale had
regionForSaleGroup.setSetting("rent.autoExtend", true);
// Import regions from each world
for(File worldFolder : worldFolders) {
// Skip files
if(!worldFolder.isDirectory() || worldFolder.isHidden()) {
continue;
}
messageNoPrefix("import-doWorld", worldFolder.getName());
// Get the Bukkit world
World world = Bukkit.getWorld(worldFolder.getName());
if(world == null) {
messageNoPrefix("import-noBukkitWorld");
continue;
}
// Get the WorldGuard RegionManager
RegionManager regionManager = plugin.getRegionManager(world);
if(regionManager == null) {
messageNoPrefix("import-noRegionManger");
continue;
}
// Load the /worlds/<world>/regions.yml file
File regionsFile = new File(worldFolder.getAbsolutePath(), "regions.yml");
YamlConfiguration regions = loadConfiguration(regionsFile);
if(regions == null) {
messageNoPrefix("import-loadRegionsFailed", regionsFile.getAbsolutePath());
continue;
}
// Load /worlds/<world>/config.yml file
File worldConfigFile = new File(worldFolder.getAbsolutePath(), "config.yml");
YamlConfiguration worldConfig = loadConfiguration(worldConfigFile);
if(worldConfig == null) {
messageNoPrefix("import-loadWorldConfigFailed", worldConfigFile.getAbsolutePath());
// Simply skip importing the settings, since this is not really fatal
worldConfig = new YamlConfiguration();
} else {
// RegionGroup with all world settings
RegionGroup worldGroup = new RegionGroup(plugin, "RegionForSale-" + worldFolder.getName());
importRegionSettings(worldConfig, worldGroup.getSettings(), null, false);
worldGroup.setSetting("priority", 1);
worldGroup.addWorld(worldFolder.getName());
plugin.getFileManager().addGroup(regionForSaleGroup);
worldGroup.saveRequired();
}
// Create groups to hold settings of /worlds/<world>/parent-regions.yml
File parentRegionsFile = new File(worldFolder.getAbsolutePath(), "parent-regions.yml");
YamlConfiguration parentRegions = loadConfiguration(parentRegionsFile);
if(parentRegions == null) {
messageNoPrefix("import-loadParentRegionsFailed", parentRegionsFile.getAbsolutePath());
// Non-fatal, so just continue
} else {
for(String parentRegionName : parentRegions.getKeys(false)) {
// Get WorldGuard region
ProtectedRegion worldGuardRegion = regionManager.getRegion(parentRegionName);
if(worldGuardRegion == null) {
messageNoPrefix("import-noWorldGuardRegionParent", parentRegionName);
continue;
}
// Get settings section
ConfigurationSection parentRegionSection = parentRegions.getConfigurationSection(parentRegionName);
if(parentRegionSection == null) {
messageNoPrefix("import-improperParentRegion", parentRegionName);
continue;
}
// Skip if it does not have any settings
if(parentRegionSection.getKeys(false).isEmpty()) {
continue;
}
// Import parent region settings into a RegionGroup
RegionGroup parentRegionGroup = new RegionGroup(plugin, "RegionForSale-" + worldFolder.getName() + "-" + parentRegionName);
importRegionSettings(parentRegionSection, parentRegionGroup.getSettings(), null, false);
parentRegionGroup.setSetting("priority", 2 + parentRegionSection.getLong("info.priority", 0));
parentRegionGroup.saveRequired();
// TODO add all regions that are contained in this parent region
// Utils.getWorldEditRegionsInSelection()
}
}
// Read and import regions
for(String regionKey : regions.getKeys(false)) {
LegacyGeneralRegion existingRegion = plugin.getFileManager().getRegion(regionKey);
if(existingRegion != null) {
if(world.getName().equalsIgnoreCase(existingRegion.getWorldName())) {
messageNoPrefix("import-alreadyAdded", regionKey);
} else {
messageNoPrefix("import-alreadyAddedOtherWorld", regionKey, existingRegion.getWorldName(), world.getName());
}
continue;
}
ConfigurationSection regionSection = regions.getConfigurationSection(regionKey);
if(regionSection == null) {
messageNoPrefix("import-invalidRegionSection", regionKey);
continue;
}
// Get WorldGuard region
ProtectedRegion worldGuardRegion = regionManager.getRegion(regionKey);
if(worldGuardRegion == null) {
messageNoPrefix("import-noWorldGuardRegion", regionKey);
continue;
}
String owner = regionSection.getString("info.owner", null);
boolean isBought = regionSection.getBoolean("info.is-bought");
// TODO: should also take into config settings of parent regions
boolean rentable = regionSection.getBoolean("economic-settings.rentable", worldConfig.getBoolean("economic-settings.rentable", regionForSaleConfig.getBoolean("economic-settings.rentable")));
boolean buyable = regionSection.getBoolean("economic-settings.buyable", worldConfig.getBoolean("economic-settings.buyable", regionForSaleConfig.getBoolean("economic-settings.buyable")));
// Can be bought and rented, import as buy
if(buyable && rentable) {
messageNoPrefix("import-buyAndRent", regionKey);
}
// Cannot be bought or rented, skip
if(!buyable && !rentable && owner == null) {
messageNoPrefix("import-noBuyAndNoRent", regionKey);
continue;
}
// Create region
LegacyGeneralRegion region;
if(rentable || (owner != null && !isBought)) {
region = new RentRegion(regionKey, world);
} else {
region = new BuyRegion(regionKey, world);
}
AddingRegionEvent event = plugin.getFileManager().addRegion(region);
if (event.isCancelled()) {
messageNoPrefix("general-cancelled", event.getReason());
continue;
}
// Import settings
importRegionSettings(regionSection, region.getConfig(), region, !buyable && !rentable);
region.getConfig().set("general.importedFrom", "RegionForSale");
// Get existing owners and members
List<UUID> existing = new ArrayList<>();
if(owner != null) {
@SuppressWarnings("deprecation")
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(owner);
if(offlinePlayer != null) {
existing.add(offlinePlayer.getUniqueId());
}
}
for(UUID uuid : plugin.getWorldGuardHandler().getOwners(worldGuardRegion).asUniqueIdList()) {
if(!existing.contains(uuid)) {
existing.add(uuid);
}
}
for(UUID uuid : plugin.getWorldGuardHandler().getMembers(worldGuardRegion).asUniqueIdList()) {
if(!existing.contains(uuid)) {
existing.add(uuid);
}
}
// First owner (or if none, the first member) will be the renter/buyer
if(!existing.isEmpty()) {
region.setOwner(existing.remove(0));
}
// Add others as friends
for(UUID friend : existing) {
region.getFriendsFeature().addFriend(friend, null);
}
region.saveRequired();
messageNoPrefix("import-imported", regionKey);
}
}
// Update all regions
plugin.getFileManager().updateAllRegions(sender);
// Write all imported regions and settings to disk
plugin.getFileManager().saveRequiredFiles();
}
/**
* Load a YamlConfiguration from disk using UTF-8 encoding.
* @param from File to read the configuration from
* @return YamlConfiguration if the file exists and got read wihout problems, otherwise null
*/
private YamlConfiguration loadConfiguration(File from) {
try(
InputStreamReader reader = new InputStreamReader(new FileInputStream(from), Charsets.UTF_8)
) {
return YamlConfiguration.loadConfiguration(reader);
} catch(IOException e) {
return null;
}
}
/**
* Import region specific settings from a RegionForSale source to an AreaShop target ConfigurationSection.
* @param from RegionForSale config section that specifies region settings
* @param to AreaShop config section that specifies region settings
* @param region GeneralRegion to copy settings to, or null if doing generic settings
* @param permanent Region cannot be rented or bought, disables some features
*/
private void importRegionSettings(ConfigurationSection from, ConfigurationSection to, LegacyGeneralRegion region, boolean permanent) {
// Maximum rental time, TODO check if this is actually the same
if(from.isLong("permissions.max-rent-time")) {
to.set("rent.maxRentTime", minutesToString(from.getLong("permissions.max-rent-time")));
}
// Region rebuild
if(from.getBoolean("region-rebuilding.auto-rebuild")) {
to.set("general.enableRestore", true);
}
// Get price settings
String unit = from.getString("economic-settings.unit-type");
String rentPrice = from.getString("economic-settings.cost-per-unit.rent");
String buyPrice = from.getString("economic-settings.cost-per-unit.buy");
String sellPrice = from.getString("economic-settings.cost-per-unit.selling-price");
// TODO: There is no easy way to import this, setup eventCommandsProfile?
// String taxes = from.getString("economic-settings.cost-per-unit.taxes");
// Determine unit and add that to the price
String unitSuffix = "";
if("region".equalsIgnoreCase(unit)) {
// add nothing
} else if("m3".equalsIgnoreCase(unit)) {
unitSuffix = "*%volume%";
} else { // m2 or nothing (in case not set, we should actually look in parent files to correctly set this...)
unitSuffix = "*(%volume%/%height%)"; // This is better than width*depth because of polygon regions
}
// Apply settings
if(rentPrice != null) {
to.set("rent.price", rentPrice + unitSuffix);
}
if(buyPrice != null) {
to.set("buy.price", buyPrice + unitSuffix);
if(sellPrice != null) {
try {
double buyPriceAmount = Double.parseDouble(buyPrice);
double sellPriceAmount = Double.parseDouble(sellPrice);
to.set("buy.moneyBack", sellPriceAmount / buyPriceAmount * 100);
} catch(NumberFormatException e) {
// There is not always a region here for the message, should probably indicate something though
message("import-moneyBackFailed", buyPrice, sellPrice);
}
}
}
// Apply permanent region settings
if(permanent) {
to.set("buy.resellDisabled", true);
to.set("buy.sellDisabled", true);
to.set("general.countForLimits", false);
}
// Set rented until
if(from.isLong("info.last-withdrawal")
&& region instanceof RentRegion) {
RentRegion rentRegion = (RentRegion)region;
long lastWithdrawal = from.getLong("info.last-withdrawal");
// Because the rental duration is already imported into the region and its parents this should be correct
rentRegion.setRentedUntil(lastWithdrawal + rentRegion.getDuration());
}
// Import signs (list of strings like "297, 71, -22")
if(from.isList("info.signs") && region != null) {
for(String signLocation : from.getStringList("info.signs")) {
String[] locationParts = signLocation.split(", ");
if(locationParts.length != 3) {
message("import-invalidSignLocation", region.getRegionId(), signLocation);
continue;
}
// Parse the location
Location location;
try {
location = new Location(region.getWorld(), Double.parseDouble(locationParts[0]), Double.parseDouble(locationParts[1]), Double.parseDouble(locationParts[2]));
} catch(NumberFormatException e) {
message("import-invalidSignLocation", region.getRegionId(), signLocation);
continue;
}
// Check if this location is already added to a region
RegionSign regionSign = SignsFeature.getSignByLocation(location);
if(regionSign != null) {
if(!regionSign.getRegion().equals(region)) {
message("import-signAlreadyAdded", region.getRegionId(), signLocation, regionSign.getRegion().getRegionId());
}
continue;
}
// SignType and Facing will be written when the sign is updated later
region.getSignsFeature().addSign(location, null, null, null);
}
}
}
private static class TimeUnit {
public final long minutes;
public final String identifier;
TimeUnit(long minutes, String identifier) {
this.minutes = minutes;
this.identifier = identifier;
}
}
private static final List<TimeUnit> timeUnitLookup = new ArrayList<TimeUnit>() {
{
add(new TimeUnit(60 * 24 * 30 * 12, "year"));
add(new TimeUnit(60 * 24 * 30, "month"));
add(new TimeUnit(60 * 24, "day"));
add(new TimeUnit(60, "hour"));
}
};
/**
* Convert minutes to a human-readable string.
* @param minutes Value to convert
* @return String that represents the same length of time in a readable format, like "1 day", "5 minutes", "3 months"
*/
private String minutesToString(long minutes) {
// If the specified number of minutes can map nicely to a higher unit, use that one
String resultUnit = "minute";
long resultValue = minutes;
for(TimeUnit unit : timeUnitLookup) {
long result = minutes / unit.minutes;
if(resultValue * unit.minutes == minutes) {
resultUnit = unit.identifier;
resultValue = result;
break;
}
}
return resultValue + " " + resultUnit + (resultValue == 1 ? "" : "s");
}
/**
* Send a message to a target without a prefix.
* @param key The key of the language string
* @param replacements The replacements to insert in the message
*/
public void messageNoPrefix(String key, Object... replacements) {
plugin.messageNoPrefix(sender, key, replacements);
if(!(sender instanceof ConsoleCommandSender)) {
plugin.messageNoPrefix(Bukkit.getConsoleSender(), key, replacements);
}
}
/**
* Send a message to a target, prefixed by the default chat prefix.
* @param key The key of the language string
* @param replacements The replacements to insert in the message
*/
public void message(String key, Object... replacements) {
plugin.message(sender, key, replacements);
if(!(sender instanceof ConsoleCommandSender)) {
plugin.message(Bukkit.getConsoleSender(), key, replacements);
}
}
}
package me.wiefferink.areashop.commands;
import com.google.common.base.Charsets;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.features.signs.RegionSign;
import me.wiefferink.areashop.features.signs.SignsFeature;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class ImportJob {
private final AreaShop plugin;
private final CommandSender sender;
/**
* Create and execute the import.
* @param sender CommandSender that should receive progress updates
*/
public ImportJob(CommandSender sender) {
this.sender = sender;
this.plugin = AreaShop.getInstance();
execute();
}
/**
* Execute the job.
*/
private void execute() {
// Check for RegionForSale data
File regionForSaleFolder = new File(plugin.getDataFolder().getParentFile().getAbsolutePath(), "RegionForSale");
if(!regionForSaleFolder.exists()) {
message("import-noPluginFolder", regionForSaleFolder.getName());
return;
}
File worldsFolder = new File(regionForSaleFolder.getAbsolutePath(), "worlds");
if(!worldsFolder.exists()) {
message("import-noWorldsFolder");
return;
}
File[] worldFolders = worldsFolder.listFiles();
if(worldFolders == null) {
message("import-noWorldsFolder");
return;
}
// Import data for each world
message("import-start");
// Group with settings for all imported regions
RegionGroup regionForSaleGroup = new RegionGroup(plugin, "RegionForSale");
plugin.getFileManager().addGroup(regionForSaleGroup);
// Import /RegionForSale/config.yml settings
File regionForSaleConfigFile = new File(regionForSaleFolder.getAbsolutePath(), "config.yml");
YamlConfiguration regionForSaleConfig = loadConfiguration(regionForSaleConfigFile);
if(regionForSaleConfig == null) {
messageNoPrefix("import-loadConfigFailed", regionForSaleConfigFile.getAbsolutePath());
regionForSaleConfig = new YamlConfiguration();
} else {
importRegionSettings(regionForSaleConfig, regionForSaleGroup.getSettings(), null, false);
regionForSaleGroup.setSetting("priority", 0);
}
// Import /RegionForSale/general.yml settings
File regionForSaleGeneralFile = new File(regionForSaleFolder.getAbsolutePath(), "config.yml");
YamlConfiguration regionForSaleGeneral = loadConfiguration(regionForSaleConfigFile);
if(regionForSaleGeneral == null) {
messageNoPrefix("import-loadConfigFailed", regionForSaleGeneralFile.getAbsolutePath());
} else {
// Collection interval of RegionForSale maps to rent duration
String duration = "1 day";
if(regionForSaleGeneral.isLong("interval.collect_money")) {
duration = minutesToString(regionForSaleGeneral.getLong("interval.collect_money"));
}
regionForSaleGroup.setSetting("rent.duration", duration);
// Global economy account has an effect close to landlord in AreaShop
if(regionForSaleGeneral.isString("global_econ_account")) {
regionForSaleGroup.setSetting("general.landlordName", regionForSaleGeneral.getString("global_econ_account"));
}
}
regionForSaleGroup.saveRequired();
////////// Handle defaults of RegionForSale
// Set autoExtend, to keep the same behavior as RegionForSale had
regionForSaleGroup.setSetting("rent.autoExtend", true);
// Import regions from each world
for(File worldFolder : worldFolders) {
// Skip files
if(!worldFolder.isDirectory() || worldFolder.isHidden()) {
continue;
}
messageNoPrefix("import-doWorld", worldFolder.getName());
// Get the Bukkit world
World world = Bukkit.getWorld(worldFolder.getName());
if(world == null) {
messageNoPrefix("import-noBukkitWorld");
continue;
}
// Get the WorldGuard RegionManager
RegionManager regionManager = plugin.getRegionManager(world);
if(regionManager == null) {
messageNoPrefix("import-noRegionManger");
continue;
}
// Load the /worlds/<world>/regions.yml file
File regionsFile = new File(worldFolder.getAbsolutePath(), "regions.yml");
YamlConfiguration regions = loadConfiguration(regionsFile);
if(regions == null) {
messageNoPrefix("import-loadRegionsFailed", regionsFile.getAbsolutePath());
continue;
}
// Load /worlds/<world>/config.yml file
File worldConfigFile = new File(worldFolder.getAbsolutePath(), "config.yml");
YamlConfiguration worldConfig = loadConfiguration(worldConfigFile);
if(worldConfig == null) {
messageNoPrefix("import-loadWorldConfigFailed", worldConfigFile.getAbsolutePath());
// Simply skip importing the settings, since this is not really fatal
worldConfig = new YamlConfiguration();
} else {
// RegionGroup with all world settings
RegionGroup worldGroup = new RegionGroup(plugin, "RegionForSale-" + worldFolder.getName());
importRegionSettings(worldConfig, worldGroup.getSettings(), null, false);
worldGroup.setSetting("priority", 1);
worldGroup.addWorld(worldFolder.getName());
plugin.getFileManager().addGroup(regionForSaleGroup);
worldGroup.saveRequired();
}
// Create groups to hold settings of /worlds/<world>/parent-regions.yml
File parentRegionsFile = new File(worldFolder.getAbsolutePath(), "parent-regions.yml");
YamlConfiguration parentRegions = loadConfiguration(parentRegionsFile);
if(parentRegions == null) {
messageNoPrefix("import-loadParentRegionsFailed", parentRegionsFile.getAbsolutePath());
// Non-fatal, so just continue
} else {
for(String parentRegionName : parentRegions.getKeys(false)) {
// Get WorldGuard region
ProtectedRegion worldGuardRegion = regionManager.getRegion(parentRegionName);
if(worldGuardRegion == null) {
messageNoPrefix("import-noWorldGuardRegionParent", parentRegionName);
continue;
}
// Get settings section
ConfigurationSection parentRegionSection = parentRegions.getConfigurationSection(parentRegionName);
if(parentRegionSection == null) {
messageNoPrefix("import-improperParentRegion", parentRegionName);
continue;
}
// Skip if it does not have any settings
if(parentRegionSection.getKeys(false).isEmpty()) {
continue;
}
// Import parent region settings into a RegionGroup
RegionGroup parentRegionGroup = new RegionGroup(plugin, "RegionForSale-" + worldFolder.getName() + "-" + parentRegionName);
importRegionSettings(parentRegionSection, parentRegionGroup.getSettings(), null, false);
parentRegionGroup.setSetting("priority", 2 + parentRegionSection.getLong("info.priority", 0));
parentRegionGroup.saveRequired();
// TODO add all regions that are contained in this parent region
// Utils.getWorldEditRegionsInSelection()
}
}
// Read and import regions
for(String regionKey : regions.getKeys(false)) {
GeneralRegion existingRegion = plugin.getFileManager().getRegion(regionKey);
if(existingRegion != null) {
if(world.getName().equalsIgnoreCase(existingRegion.getWorldName())) {
messageNoPrefix("import-alreadyAdded", regionKey);
} else {
messageNoPrefix("import-alreadyAddedOtherWorld", regionKey, existingRegion.getWorldName(), world.getName());
}
continue;
}
ConfigurationSection regionSection = regions.getConfigurationSection(regionKey);
if(regionSection == null) {
messageNoPrefix("import-invalidRegionSection", regionKey);
continue;
}
// Get WorldGuard region
ProtectedRegion worldGuardRegion = regionManager.getRegion(regionKey);
if(worldGuardRegion == null) {
messageNoPrefix("import-noWorldGuardRegion", regionKey);
continue;
}
String owner = regionSection.getString("info.owner", null);
boolean isBought = regionSection.getBoolean("info.is-bought");
// TODO: should also take into config settings of parent regions
boolean rentable = regionSection.getBoolean("economic-settings.rentable", worldConfig.getBoolean("economic-settings.rentable", regionForSaleConfig.getBoolean("economic-settings.rentable")));
boolean buyable = regionSection.getBoolean("economic-settings.buyable", worldConfig.getBoolean("economic-settings.buyable", regionForSaleConfig.getBoolean("economic-settings.buyable")));
// Can be bought and rented, import as buy
if(buyable && rentable) {
messageNoPrefix("import-buyAndRent", regionKey);
}
// Cannot be bought or rented, skip
if(!buyable && !rentable && owner == null) {
messageNoPrefix("import-noBuyAndNoRent", regionKey);
continue;
}
// Create region
GeneralRegion region;
if(rentable || (owner != null && !isBought)) {
region = new RentRegion(regionKey, world);
} else {
region = new BuyRegion(regionKey, world);
}
AddingRegionEvent event = plugin.getFileManager().addRegion(region);
if (event.isCancelled()) {
messageNoPrefix("general-cancelled", event.getReason());
continue;
}
// Import settings
importRegionSettings(regionSection, region.getConfig(), region, !buyable && !rentable);
region.getConfig().set("general.importedFrom", "RegionForSale");
// Get existing owners and members
List<UUID> existing = new ArrayList<>();
if(owner != null) {
@SuppressWarnings("deprecation")
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(owner);
if(offlinePlayer != null) {
existing.add(offlinePlayer.getUniqueId());
}
}
for(UUID uuid : plugin.getWorldGuardHandler().getOwners(worldGuardRegion).asUniqueIdList()) {
if(!existing.contains(uuid)) {
existing.add(uuid);
}
}
for(UUID uuid : plugin.getWorldGuardHandler().getMembers(worldGuardRegion).asUniqueIdList()) {
if(!existing.contains(uuid)) {
existing.add(uuid);
}
}
// First owner (or if none, the first member) will be the renter/buyer
if(!existing.isEmpty()) {
region.setOwner(existing.remove(0));
}
// Add others as friends
for(UUID friend : existing) {
region.getFriendsFeature().addFriend(friend, null);
}
region.saveRequired();
messageNoPrefix("import-imported", regionKey);
}
}
// Update all regions
plugin.getFileManager().updateAllRegions(sender);
// Write all imported regions and settings to disk
plugin.getFileManager().saveRequiredFiles();
}
/**
* Load a YamlConfiguration from disk using UTF-8 encoding.
* @param from File to read the configuration from
* @return YamlConfiguration if the file exists and got read wihout problems, otherwise null
*/
private YamlConfiguration loadConfiguration(File from) {
try(
InputStreamReader reader = new InputStreamReader(new FileInputStream(from), Charsets.UTF_8)
) {
return YamlConfiguration.loadConfiguration(reader);
} catch(IOException e) {
return null;
}
}
/**
* Import region specific settings from a RegionForSale source to an AreaShop target ConfigurationSection.
* @param from RegionForSale config section that specifies region settings
* @param to AreaShop config section that specifies region settings
* @param region GeneralRegion to copy settings to, or null if doing generic settings
* @param permanent Region cannot be rented or bought, disables some features
*/
private void importRegionSettings(ConfigurationSection from, ConfigurationSection to, GeneralRegion region, boolean permanent) {
// Maximum rental time, TODO check if this is actually the same
if(from.isLong("permissions.max-rent-time")) {
to.set("rent.maxRentTime", minutesToString(from.getLong("permissions.max-rent-time")));
}
// Region rebuild
if(from.getBoolean("region-rebuilding.auto-rebuild")) {
to.set("general.enableRestore", true);
}
// Get price settings
String unit = from.getString("economic-settings.unit-type");
String rentPrice = from.getString("economic-settings.cost-per-unit.rent");
String buyPrice = from.getString("economic-settings.cost-per-unit.buy");
String sellPrice = from.getString("economic-settings.cost-per-unit.selling-price");
// TODO: There is no easy way to import this, setup eventCommandsProfile?
// String taxes = from.getString("economic-settings.cost-per-unit.taxes");
// Determine unit and add that to the price
String unitSuffix = "";
if("region".equalsIgnoreCase(unit)) {
// add nothing
} else if("m3".equalsIgnoreCase(unit)) {
unitSuffix = "*%volume%";
} else { // m2 or nothing (in case not set, we should actually look in parent files to correctly set this...)
unitSuffix = "*(%volume%/%height%)"; // This is better than width*depth because of polygon regions
}
// Apply settings
if(rentPrice != null) {
to.set("rent.price", rentPrice + unitSuffix);
}
if(buyPrice != null) {
to.set("buy.price", buyPrice + unitSuffix);
if(sellPrice != null) {
try {
double buyPriceAmount = Double.parseDouble(buyPrice);
double sellPriceAmount = Double.parseDouble(sellPrice);
to.set("buy.moneyBack", sellPriceAmount / buyPriceAmount * 100);
} catch(NumberFormatException e) {
// There is not always a region here for the message, should probably indicate something though
message("import-moneyBackFailed", buyPrice, sellPrice);
}
}
}
// Apply permanent region settings
if(permanent) {
to.set("buy.resellDisabled", true);
to.set("buy.sellDisabled", true);
to.set("general.countForLimits", false);
}
// Set rented until
if(from.isLong("info.last-withdrawal")
&& region instanceof RentRegion) {
RentRegion rentRegion = (RentRegion)region;
long lastWithdrawal = from.getLong("info.last-withdrawal");
// Because the rental duration is already imported into the region and its parents this should be correct
rentRegion.setRentedUntil(lastWithdrawal + rentRegion.getDuration());
}
// Import signs (list of strings like "297, 71, -22")
if(from.isList("info.signs") && region != null) {
for(String signLocation : from.getStringList("info.signs")) {
String[] locationParts = signLocation.split(", ");
if(locationParts.length != 3) {
message("import-invalidSignLocation", region.getName(), signLocation);
continue;
}
// Parse the location
Location location;
try {
location = new Location(region.getWorld(), Double.parseDouble(locationParts[0]), Double.parseDouble(locationParts[1]), Double.parseDouble(locationParts[2]));
} catch(NumberFormatException e) {
message("import-invalidSignLocation", region.getName(), signLocation);
continue;
}
// Check if this location is already added to a region
RegionSign regionSign = SignsFeature.getSignByLocation(location);
if(regionSign != null) {
if(!regionSign.getRegion().equals(region)) {
message("import-signAlreadyAdded", region.getName(), signLocation, regionSign.getRegion().getName());
}
continue;
}
// SignType and Facing will be written when the sign is updated later
region.getSignsFeature().addSign(location, null, null, null);
}
}
}
private static class TimeUnit {
public final long minutes;
public final String identifier;
TimeUnit(long minutes, String identifier) {
this.minutes = minutes;
this.identifier = identifier;
}
}
private static final List<TimeUnit> timeUnitLookup = new ArrayList<TimeUnit>() {
{
add(new TimeUnit(60 * 24 * 30 * 12, "year"));
add(new TimeUnit(60 * 24 * 30, "month"));
add(new TimeUnit(60 * 24, "day"));
add(new TimeUnit(60, "hour"));
}
};
/**
* Convert minutes to a human-readable string.
* @param minutes Value to convert
* @return String that represents the same length of time in a readable format, like "1 day", "5 minutes", "3 months"
*/
private String minutesToString(long minutes) {
// If the specified number of minutes can map nicely to a higher unit, use that one
String resultUnit = "minute";
long resultValue = minutes;
for(TimeUnit unit : timeUnitLookup) {
long result = minutes / unit.minutes;
if(resultValue * unit.minutes == minutes) {
resultUnit = unit.identifier;
resultValue = result;
break;
}
}
return resultValue + " " + resultUnit + (resultValue == 1 ? "" : "s");
}
/**
* Send a message to a target without a prefix.
* @param key The key of the language string
* @param replacements The replacements to insert in the message
*/
public void messageNoPrefix(String key, Object... replacements) {
plugin.messageNoPrefix(sender, key, replacements);
if(!(sender instanceof ConsoleCommandSender)) {
plugin.messageNoPrefix(Bukkit.getConsoleSender(), key, replacements);
}
}
/**
* Send a message to a target, prefixed by the default chat prefix.
* @param key The key of the language string
* @param replacements The replacements to insert in the message
*/
public void message(String key, Object... replacements) {
plugin.message(sender, key, replacements);
if(!(sender instanceof ConsoleCommandSender)) {
plugin.message(Bukkit.getConsoleSender(), key, replacements);
}
}
}
@@ -1,484 +1,484 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.interactivemessenger.processing.Message;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
// TODO fix '/as info' help message hitting replacement limit (improve depth tracking?)
// TODO add info about autoExtend
public class InfoCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop info";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.info")) {
return "help-info";
}
return null;
}
/**
* Display a page of a list of regions.
* @param sender The CommandSender to send the messages to
* @param regions The regions to display
* @param filterGroup The group to filter the regions by
* @param keyHeader The header to print above the page
* @param pageInput The page number, if any
* @param baseCommand The command to execute for next/previous page (/areashop will be added)
*/
private void showSortedPagedList(CommandSender sender, List<? extends LegacyGeneralRegion> regions, RegionGroup filterGroup, String keyHeader, String pageInput, String baseCommand) {
int maximumItems = 20;
int itemsPerPage = maximumItems - 2;
int page = 1;
if(pageInput != null && Utils.isNumeric(pageInput)) {
try {
page = Integer.parseInt(pageInput);
} catch(NumberFormatException e) {
plugin.message(sender, "info-wrongPage", pageInput);
return;
}
}
if(filterGroup != null) {
regions.removeIf(generalRegion -> !filterGroup.isMember(generalRegion));
}
if(regions.isEmpty()) {
plugin.message(sender, "info-noRegions");
} else {
// First sort by type, then by name
regions.sort((one, two) -> {
int typeCompare = getTypeOrder(two).compareTo(getTypeOrder(one));
if(typeCompare != 0) {
return typeCompare;
} else {
return one.getRegionId().compareTo(two.getRegionId());
}
});
// Header
Message limitedToGroup = Message.empty();
if(filterGroup != null) {
limitedToGroup = Message.fromKey("info-limitedToGroup").replacements(filterGroup.getName());
}
plugin.message(sender, keyHeader, limitedToGroup);
// Page entries
int totalPages = (int)Math.ceil(regions.size() / (double)itemsPerPage); // Clip page to correct boundaries, not much need to tell the user
if(regions.size() == itemsPerPage + 1) { // 19 total items is mapped to 1 page of 19
itemsPerPage++;
totalPages = 1;
}
page = Math.max(1, Math.min(totalPages, page));
int linesPrinted = 1; // header
for(int i = (page - 1) * itemsPerPage; i < page * itemsPerPage && i < regions.size(); i++) {
String state;
LegacyGeneralRegion region = regions.get(i);
if(region.getType() == LegacyGeneralRegion.RegionType.RENT) {
if(region.getOwner() == null) {
state = "Forrent";
} else {
state = "Rented";
}
} else {
if(region.getOwner() == null) {
state = "Forsale";
} else if(!((BuyRegion)region).isInResellingMode()) {
state = "Sold";
} else {
state = "Reselling";
}
}
plugin.messageNoPrefix(sender, "info-entry" + state, region);
linesPrinted++;
}
Message footer = Message.empty();
// Previous button
if(page > 1) {
footer.append(Message.fromKey("info-pagePrevious").replacements(baseCommand + " " + (page - 1)));
} else {
footer.append(Message.fromKey("info-pageNoPrevious"));
}
// Page status
if(totalPages > 1) {
StringBuilder pageString = new StringBuilder("" + page);
for(int i = pageString.length(); i < (totalPages + "").length(); i++) {
pageString.insert(0, "0");
}
footer.append(Message.fromKey("info-pageStatus").replacements(page, totalPages));
if(page < totalPages) {
footer.append(Message.fromKey("info-pageNext").replacements(baseCommand + " " + (page + 1)));
} else {
footer.append(Message.fromKey("info-pageNoNext"));
}
// Fill up space if the page is not full (aligns header nicely)
for(int i = linesPrinted; i < maximumItems - 1; i++) {
sender.sendMessage(" ");
}
footer.send(sender);
}
}
}
/**
* Get an integer to order by type, usable for Comparators.
* @param region The region to get the order for
* @return An integer for sorting by type
*/
private Integer getTypeOrder(LegacyGeneralRegion region) {
if(region.getType() == LegacyGeneralRegion.RegionType.RENT) {
if(region.getOwner() == null) {
return 1;
} else {
return 2;
}
} else {
if(region.getOwner() == null) {
return 3;
} else if(!((BuyRegion)region).isInResellingMode()) {
return 4;
} else {
return 5;
}
}
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.info")) {
plugin.message(sender, "info-noPermission");
return;
}
if(args.length > 1 && args[1] != null) {
// Get filter group (only used by some commands)
RegionGroup filterGroup = null;
Set<String> groupFilters = new HashSet<>(Arrays.asList("all", "rented", "forrent", "sold", "forsale", "reselling"));
if(groupFilters.contains(args[1].toLowerCase()) && args.length > 2) {
if(!Utils.isNumeric(args[2])) {
filterGroup = plugin.getFileManager().getGroup(args[2]);
if(filterGroup == null) {
plugin.message(sender, "info-noFiltergroup", args[2]);
return;
}
// Pass page number to args[2] if available
if(args.length > 3) {
args[2] = args[3];
}
}
}
// All regions
if(args[1].equalsIgnoreCase("all")) {
showSortedPagedList(sender, plugin.getFileManager().getRegions(), filterGroup, "info-allHeader", (args.length > 2 ? args[2] : null), "info all");
}
// Rented regions
else if(args[1].equalsIgnoreCase("rented")) {
List<RentRegion> regions = plugin.getFileManager().getRents();
regions.removeIf(RentRegion::isAvailable);
showSortedPagedList(sender, regions, filterGroup, "info-rentedHeader", (args.length > 2 ? args[2] : null), "info rented");
}
// Forrent regions
else if(args[1].equalsIgnoreCase("forrent")) {
List<RentRegion> regions = plugin.getFileManager().getRents();
regions.removeIf(RentRegion::isRented);
showSortedPagedList(sender, regions, filterGroup, "info-forrentHeader", (args.length > 2 ? args[2] : null), "info forrent");
}
// Sold regions
else if(args[1].equalsIgnoreCase("sold")) {
List<BuyRegion> regions = plugin.getFileManager().getBuys();
regions.removeIf(BuyRegion::isAvailable);
showSortedPagedList(sender, regions, filterGroup, "info-soldHeader", (args.length > 2 ? args[2] : null), "info sold");
}
// Forsale regions
else if(args[1].equalsIgnoreCase("forsale")) {
List<BuyRegion> regions = plugin.getFileManager().getBuys();
regions.removeIf(BuyRegion::isSold);
showSortedPagedList(sender, regions, filterGroup, "info-forsaleHeader", (args.length > 2 ? args[2] : null), "info forsale");
}
// Reselling regions
else if(args[1].equalsIgnoreCase("reselling")) {
List<BuyRegion> regions = plugin.getFileManager().getBuys();
regions.removeIf(region -> !region.isInResellingMode());
showSortedPagedList(sender, regions, filterGroup, "info-resellingHeader", (args.length > 2 ? args[2] : null), "info reselling");
}
// List of regions without a group
else if(args[1].equalsIgnoreCase("nogroup")) {
List<LegacyGeneralRegion> regions = plugin.getFileManager().getRegions();
for(RegionGroup group : plugin.getFileManager().getGroups()) {
regions.removeAll(group.getMemberRegions());
}
if(regions.isEmpty()) {
plugin.message(sender, "info-nogroupNone");
} else {
showSortedPagedList(sender, regions, filterGroup, "info-nogroupHeader", (args.length > 2 ? args[2] : null), "info nogroup");
}
}
// Region info
else if(args[1].equalsIgnoreCase("region")) {
if(args.length > 1) {
RentRegion rent = null;
BuyRegion buy = null;
if(args.length > 2) {
rent = plugin.getFileManager().getRent(args[2]);
buy = plugin.getFileManager().getBuy(args[2]);
} else {
if(sender instanceof Player) {
// get the region by location
List<LegacyGeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
if(regions.get(0) instanceof RentRegion) {
rent = (RentRegion)regions.get(0);
} else if(regions.get(0) instanceof BuyRegion) {
buy = (BuyRegion)regions.get(0);
}
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
if(rent == null && buy == null) {
plugin.message(sender, "info-regionNotExisting", args[2]);
return;
}
if(rent != null) {
plugin.message(sender, "info-regionHeaderRent", rent);
if(rent.isRented()) {
plugin.messageNoPrefix(sender, "info-regionRented", rent);
plugin.messageNoPrefix(sender, "info-regionExtending", rent);
// Money back
if(UnrentCommand.canUse(sender, rent)) {
plugin.messageNoPrefix(sender, "info-regionMoneyBackRentClick", rent);
} else {
plugin.messageNoPrefix(sender, "info-regionMoneyBackRent", rent);
}
// Friends
if(!rent.getFriendsFeature().getFriendNames().isEmpty()) {
String messagePart = "info-friend";
if(DelfriendCommand.canUse(sender, rent)) {
messagePart = "info-friendRemove";
}
plugin.messageNoPrefix(sender, "info-regionFriends", rent, Utils.combinedMessage(rent.getFriendsFeature().getFriendNames(), messagePart));
}
} else {
plugin.messageNoPrefix(sender, "info-regionCanBeRented", rent);
}
if(rent.getLandlordName() != null) {
plugin.messageNoPrefix(sender, "info-regionLandlord", rent);
}
// Maximum extends
if(rent.getMaxExtends() != -1) {
if(rent.getMaxExtends() == 0) {
plugin.messageNoPrefix(sender, "info-regionNoExtending", rent);
} else if(rent.isRented()) {
plugin.messageNoPrefix(sender, "info-regionExtendsLeft", rent);
} else {
plugin.messageNoPrefix(sender, "info-regionMaxExtends", rent);
}
}
// If maxExtends is zero it does not make sense to show this message
if(rent.getMaxRentTime() != -1 && rent.getMaxExtends() != 0) {
plugin.messageNoPrefix(sender, "info-regionMaxRentTime", rent);
}
if(rent.getInactiveTimeUntilUnrent() != -1) {
plugin.messageNoPrefix(sender, "info-regionInactiveUnrent", rent);
}
// Teleport
Message tp = Message.fromKey("info-prefix");
boolean foundSomething = false;
if(TeleportCommand.canUse(sender, rent)) {
foundSomething = true;
tp.append(Message.fromKey("info-regionTeleport").replacements(rent));
}
if(SetteleportCommand.canUse(sender, rent)) {
if(foundSomething) {
tp.append(", ");
}
foundSomething = true;
tp.append(Message.fromKey("info-setRegionTeleport").replacements(rent));
}
if(foundSomething) {
tp.append(".");
tp.send(sender);
}
// Signs
List<String> signLocations = new ArrayList<>();
for(Location location : rent.getSignsFeature().getSignLocations()) {
signLocations.add(Message.fromKey("info-regionSignLocation").replacements(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()).getPlain());
}
if(!signLocations.isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionSigns", Utils.createCommaSeparatedList(signLocations));
}
// Groups
if(sender.hasPermission("areashop.groupinfo") && !rent.getGroupNames().isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionGroups", Utils.createCommaSeparatedList(rent.getGroupNames()));
}
// Restoring
if(rent.isRestoreEnabled()) {
plugin.messageNoPrefix(sender, "info-regionRestoringRent", rent);
}
// Restrictions
if(!rent.isRented()) {
if(rent.restrictedToRegion()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedRegionRent", rent);
} else if(rent.restrictedToWorld()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedWorldRent", rent);
}
}
plugin.messageNoPrefix(sender, "info-regionFooterRent", rent);
} else if(buy != null) {
plugin.message(sender, "info-regionHeaderBuy", buy);
if(buy.isSold()) {
if(buy.isInResellingMode()) {
plugin.messageNoPrefix(sender, "info-regionReselling", buy);
plugin.messageNoPrefix(sender, "info-regionReselPrice", buy);
} else {
plugin.messageNoPrefix(sender, "info-regionBought", buy);
}
// Money back
if(!buy.getBooleanSetting("buy.sellDisabled")) {
if (SellCommand.canUse(sender, buy)) {
plugin.messageNoPrefix(sender, "info-regionMoneyBackBuyClick", buy);
} else {
plugin.messageNoPrefix(sender, "info-regionMoneyBackBuy", buy);
}
}
// Friends
if(!buy.getFriendsFeature().getFriendNames().isEmpty()) {
String messagePart = "info-friend";
if(DelfriendCommand.canUse(sender, buy)) {
messagePart = "info-friendRemove";
}
plugin.messageNoPrefix(sender, "info-regionFriends", buy, Utils.combinedMessage(buy.getFriendsFeature().getFriendNames(), messagePart));
}
} else {
plugin.messageNoPrefix(sender, "info-regionCanBeBought", buy);
}
if(buy.getLandlord() != null) {
plugin.messageNoPrefix(sender, "info-regionLandlord", buy);
}
if(buy.getInactiveTimeUntilSell() != -1) {
plugin.messageNoPrefix(sender, "info-regionInactiveSell", buy);
}
// Teleport
Message tp = Message.fromKey("info-prefix");
boolean foundSomething = false;
if(TeleportCommand.canUse(sender, buy)) {
foundSomething = true;
tp.append(Message.fromKey("info-regionTeleport").replacements(buy));
}
if(SetteleportCommand.canUse(sender, buy)) {
if(foundSomething) {
tp.append(", ");
}
foundSomething = true;
tp.append(Message.fromKey("info-setRegionTeleport").replacements(buy));
}
if(foundSomething) {
tp.append(".");
tp.send(sender);
}
// Signs
List<String> signLocations = new ArrayList<>();
for(Location location : buy.getSignsFeature().getSignLocations()) {
signLocations.add(Message.fromKey("info-regionSignLocation").replacements(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()).getPlain());
}
if(!signLocations.isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionSigns", Utils.createCommaSeparatedList(signLocations));
}
// Groups
if(sender.hasPermission("areashop.groupinfo") && !buy.getGroupNames().isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionGroups", Utils.createCommaSeparatedList(buy.getGroupNames()));
}
// Restoring
if(buy.isRestoreEnabled()) {
plugin.messageNoPrefix(sender, "info-regionRestoringBuy", buy);
}
// Restrictions
if(!buy.isSold()) {
if(buy.restrictedToRegion()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedRegionBuy", buy);
} else if(buy.restrictedToWorld()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedWorldBuy", buy);
}
}
plugin.messageNoPrefix(sender, "info-regionFooterBuy", buy);
}
} else {
plugin.message(sender, "info-regionHelp");
}
} else {
plugin.message(sender, "info-help");
}
} else {
plugin.message(sender, "info-help");
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result.addAll(Arrays.asList("all", "rented", "forrent", "sold", "forsale", "player", "region", "nogroup", "reselling"));
} else if(toComplete == 3) {
if(start[2].equalsIgnoreCase("player")) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
} else if(start[2].equalsIgnoreCase("region")) {
result.addAll(plugin.getFileManager().getBuyNames());
result.addAll(plugin.getFileManager().getRentNames());
}
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.interactivemessenger.processing.Message;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
// TODO fix '/as info' help message hitting replacement limit (improve depth tracking?)
// TODO add info about autoExtend
public class InfoCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop info";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.info")) {
return "help-info";
}
return null;
}
/**
* Display a page of a list of regions.
* @param sender The CommandSender to send the messages to
* @param regions The regions to display
* @param filterGroup The group to filter the regions by
* @param keyHeader The header to print above the page
* @param pageInput The page number, if any
* @param baseCommand The command to execute for next/previous page (/areashop will be added)
*/
private void showSortedPagedList(CommandSender sender, List<? extends GeneralRegion> regions, RegionGroup filterGroup, String keyHeader, String pageInput, String baseCommand) {
int maximumItems = 20;
int itemsPerPage = maximumItems - 2;
int page = 1;
if(pageInput != null && Utils.isNumeric(pageInput)) {
try {
page = Integer.parseInt(pageInput);
} catch(NumberFormatException e) {
plugin.message(sender, "info-wrongPage", pageInput);
return;
}
}
if(filterGroup != null) {
regions.removeIf(generalRegion -> !filterGroup.isMember(generalRegion));
}
if(regions.isEmpty()) {
plugin.message(sender, "info-noRegions");
} else {
// First sort by type, then by name
regions.sort((one, two) -> {
int typeCompare = getTypeOrder(two).compareTo(getTypeOrder(one));
if(typeCompare != 0) {
return typeCompare;
} else {
return one.getName().compareTo(two.getName());
}
});
// Header
Message limitedToGroup = Message.empty();
if(filterGroup != null) {
limitedToGroup = Message.fromKey("info-limitedToGroup").replacements(filterGroup.getName());
}
plugin.message(sender, keyHeader, limitedToGroup);
// Page entries
int totalPages = (int)Math.ceil(regions.size() / (double)itemsPerPage); // Clip page to correct boundaries, not much need to tell the user
if(regions.size() == itemsPerPage + 1) { // 19 total items is mapped to 1 page of 19
itemsPerPage++;
totalPages = 1;
}
page = Math.max(1, Math.min(totalPages, page));
int linesPrinted = 1; // header
for(int i = (page - 1) * itemsPerPage; i < page * itemsPerPage && i < regions.size(); i++) {
String state;
GeneralRegion region = regions.get(i);
if(region.getType() == GeneralRegion.RegionType.RENT) {
if(region.getOwner() == null) {
state = "Forrent";
} else {
state = "Rented";
}
} else {
if(region.getOwner() == null) {
state = "Forsale";
} else if(!((BuyRegion)region).isInResellingMode()) {
state = "Sold";
} else {
state = "Reselling";
}
}
plugin.messageNoPrefix(sender, "info-entry" + state, region);
linesPrinted++;
}
Message footer = Message.empty();
// Previous button
if(page > 1) {
footer.append(Message.fromKey("info-pagePrevious").replacements(baseCommand + " " + (page - 1)));
} else {
footer.append(Message.fromKey("info-pageNoPrevious"));
}
// Page status
if(totalPages > 1) {
StringBuilder pageString = new StringBuilder("" + page);
for(int i = pageString.length(); i < (totalPages + "").length(); i++) {
pageString.insert(0, "0");
}
footer.append(Message.fromKey("info-pageStatus").replacements(page, totalPages));
if(page < totalPages) {
footer.append(Message.fromKey("info-pageNext").replacements(baseCommand + " " + (page + 1)));
} else {
footer.append(Message.fromKey("info-pageNoNext"));
}
// Fill up space if the page is not full (aligns header nicely)
for(int i = linesPrinted; i < maximumItems - 1; i++) {
sender.sendMessage(" ");
}
footer.send(sender);
}
}
}
/**
* Get an integer to order by type, usable for Comparators.
* @param region The region to get the order for
* @return An integer for sorting by type
*/
private Integer getTypeOrder(GeneralRegion region) {
if(region.getType() == GeneralRegion.RegionType.RENT) {
if(region.getOwner() == null) {
return 1;
} else {
return 2;
}
} else {
if(region.getOwner() == null) {
return 3;
} else if(!((BuyRegion)region).isInResellingMode()) {
return 4;
} else {
return 5;
}
}
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.info")) {
plugin.message(sender, "info-noPermission");
return;
}
if(args.length > 1 && args[1] != null) {
// Get filter group (only used by some commands)
RegionGroup filterGroup = null;
Set<String> groupFilters = new HashSet<>(Arrays.asList("all", "rented", "forrent", "sold", "forsale", "reselling"));
if(groupFilters.contains(args[1].toLowerCase()) && args.length > 2) {
if(!Utils.isNumeric(args[2])) {
filterGroup = plugin.getFileManager().getGroup(args[2]);
if(filterGroup == null) {
plugin.message(sender, "info-noFiltergroup", args[2]);
return;
}
// Pass page number to args[2] if available
if(args.length > 3) {
args[2] = args[3];
}
}
}
// All regions
if(args[1].equalsIgnoreCase("all")) {
showSortedPagedList(sender, plugin.getFileManager().getRegions(), filterGroup, "info-allHeader", (args.length > 2 ? args[2] : null), "info all");
}
// Rented regions
else if(args[1].equalsIgnoreCase("rented")) {
List<RentRegion> regions = plugin.getFileManager().getRents();
regions.removeIf(RentRegion::isAvailable);
showSortedPagedList(sender, regions, filterGroup, "info-rentedHeader", (args.length > 2 ? args[2] : null), "info rented");
}
// Forrent regions
else if(args[1].equalsIgnoreCase("forrent")) {
List<RentRegion> regions = plugin.getFileManager().getRents();
regions.removeIf(RentRegion::isRented);
showSortedPagedList(sender, regions, filterGroup, "info-forrentHeader", (args.length > 2 ? args[2] : null), "info forrent");
}
// Sold regions
else if(args[1].equalsIgnoreCase("sold")) {
List<BuyRegion> regions = plugin.getFileManager().getBuys();
regions.removeIf(BuyRegion::isAvailable);
showSortedPagedList(sender, regions, filterGroup, "info-soldHeader", (args.length > 2 ? args[2] : null), "info sold");
}
// Forsale regions
else if(args[1].equalsIgnoreCase("forsale")) {
List<BuyRegion> regions = plugin.getFileManager().getBuys();
regions.removeIf(BuyRegion::isSold);
showSortedPagedList(sender, regions, filterGroup, "info-forsaleHeader", (args.length > 2 ? args[2] : null), "info forsale");
}
// Reselling regions
else if(args[1].equalsIgnoreCase("reselling")) {
List<BuyRegion> regions = plugin.getFileManager().getBuys();
regions.removeIf(region -> !region.isInResellingMode());
showSortedPagedList(sender, regions, filterGroup, "info-resellingHeader", (args.length > 2 ? args[2] : null), "info reselling");
}
// List of regions without a group
else if(args[1].equalsIgnoreCase("nogroup")) {
List<GeneralRegion> regions = plugin.getFileManager().getRegions();
for(RegionGroup group : plugin.getFileManager().getGroups()) {
regions.removeAll(group.getMemberRegions());
}
if(regions.isEmpty()) {
plugin.message(sender, "info-nogroupNone");
} else {
showSortedPagedList(sender, regions, filterGroup, "info-nogroupHeader", (args.length > 2 ? args[2] : null), "info nogroup");
}
}
// Region info
else if(args[1].equalsIgnoreCase("region")) {
if(args.length > 1) {
RentRegion rent = null;
BuyRegion buy = null;
if(args.length > 2) {
rent = plugin.getFileManager().getRent(args[2]);
buy = plugin.getFileManager().getBuy(args[2]);
} else {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
if(regions.get(0) instanceof RentRegion) {
rent = (RentRegion)regions.get(0);
} else if(regions.get(0) instanceof BuyRegion) {
buy = (BuyRegion)regions.get(0);
}
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
}
if(rent == null && buy == null) {
plugin.message(sender, "info-regionNotExisting", args[2]);
return;
}
if(rent != null) {
plugin.message(sender, "info-regionHeaderRent", rent);
if(rent.isRented()) {
plugin.messageNoPrefix(sender, "info-regionRented", rent);
plugin.messageNoPrefix(sender, "info-regionExtending", rent);
// Money back
if(UnrentCommand.canUse(sender, rent)) {
plugin.messageNoPrefix(sender, "info-regionMoneyBackRentClick", rent);
} else {
plugin.messageNoPrefix(sender, "info-regionMoneyBackRent", rent);
}
// Friends
if(!rent.getFriendsFeature().getFriendNames().isEmpty()) {
String messagePart = "info-friend";
if(DelfriendCommand.canUse(sender, rent)) {
messagePart = "info-friendRemove";
}
plugin.messageNoPrefix(sender, "info-regionFriends", rent, Utils.combinedMessage(rent.getFriendsFeature().getFriendNames(), messagePart));
}
} else {
plugin.messageNoPrefix(sender, "info-regionCanBeRented", rent);
}
if(rent.getLandlordName() != null) {
plugin.messageNoPrefix(sender, "info-regionLandlord", rent);
}
// Maximum extends
if(rent.getMaxExtends() != -1) {
if(rent.getMaxExtends() == 0) {
plugin.messageNoPrefix(sender, "info-regionNoExtending", rent);
} else if(rent.isRented()) {
plugin.messageNoPrefix(sender, "info-regionExtendsLeft", rent);
} else {
plugin.messageNoPrefix(sender, "info-regionMaxExtends", rent);
}
}
// If maxExtends is zero it does not make sense to show this message
if(rent.getMaxRentTime() != -1 && rent.getMaxExtends() != 0) {
plugin.messageNoPrefix(sender, "info-regionMaxRentTime", rent);
}
if(rent.getInactiveTimeUntilUnrent() != -1) {
plugin.messageNoPrefix(sender, "info-regionInactiveUnrent", rent);
}
// Teleport
Message tp = Message.fromKey("info-prefix");
boolean foundSomething = false;
if(TeleportCommand.canUse(sender, rent)) {
foundSomething = true;
tp.append(Message.fromKey("info-regionTeleport").replacements(rent));
}
if(SetteleportCommand.canUse(sender, rent)) {
if(foundSomething) {
tp.append(", ");
}
foundSomething = true;
tp.append(Message.fromKey("info-setRegionTeleport").replacements(rent));
}
if(foundSomething) {
tp.append(".");
tp.send(sender);
}
// Signs
List<String> signLocations = new ArrayList<>();
for(Location location : rent.getSignsFeature().getSignLocations()) {
signLocations.add(Message.fromKey("info-regionSignLocation").replacements(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()).getPlain());
}
if(!signLocations.isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionSigns", Utils.createCommaSeparatedList(signLocations));
}
// Groups
if(sender.hasPermission("areashop.groupinfo") && !rent.getGroupNames().isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionGroups", Utils.createCommaSeparatedList(rent.getGroupNames()));
}
// Restoring
if(rent.isRestoreEnabled()) {
plugin.messageNoPrefix(sender, "info-regionRestoringRent", rent);
}
// Restrictions
if(!rent.isRented()) {
if(rent.restrictedToRegion()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedRegionRent", rent);
} else if(rent.restrictedToWorld()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedWorldRent", rent);
}
}
plugin.messageNoPrefix(sender, "info-regionFooterRent", rent);
} else if(buy != null) {
plugin.message(sender, "info-regionHeaderBuy", buy);
if(buy.isSold()) {
if(buy.isInResellingMode()) {
plugin.messageNoPrefix(sender, "info-regionReselling", buy);
plugin.messageNoPrefix(sender, "info-regionReselPrice", buy);
} else {
plugin.messageNoPrefix(sender, "info-regionBought", buy);
}
// Money back
if(!buy.getBooleanSetting("buy.sellDisabled")) {
if (SellCommand.canUse(sender, buy)) {
plugin.messageNoPrefix(sender, "info-regionMoneyBackBuyClick", buy);
} else {
plugin.messageNoPrefix(sender, "info-regionMoneyBackBuy", buy);
}
}
// Friends
if(!buy.getFriendsFeature().getFriendNames().isEmpty()) {
String messagePart = "info-friend";
if(DelfriendCommand.canUse(sender, buy)) {
messagePart = "info-friendRemove";
}
plugin.messageNoPrefix(sender, "info-regionFriends", buy, Utils.combinedMessage(buy.getFriendsFeature().getFriendNames(), messagePart));
}
} else {
plugin.messageNoPrefix(sender, "info-regionCanBeBought", buy);
}
if(buy.getLandlord() != null) {
plugin.messageNoPrefix(sender, "info-regionLandlord", buy);
}
if(buy.getInactiveTimeUntilSell() != -1) {
plugin.messageNoPrefix(sender, "info-regionInactiveSell", buy);
}
// Teleport
Message tp = Message.fromKey("info-prefix");
boolean foundSomething = false;
if(TeleportCommand.canUse(sender, buy)) {
foundSomething = true;
tp.append(Message.fromKey("info-regionTeleport").replacements(buy));
}
if(SetteleportCommand.canUse(sender, buy)) {
if(foundSomething) {
tp.append(", ");
}
foundSomething = true;
tp.append(Message.fromKey("info-setRegionTeleport").replacements(buy));
}
if(foundSomething) {
tp.append(".");
tp.send(sender);
}
// Signs
List<String> signLocations = new ArrayList<>();
for(Location location : buy.getSignsFeature().getSignLocations()) {
signLocations.add(Message.fromKey("info-regionSignLocation").replacements(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()).getPlain());
}
if(!signLocations.isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionSigns", Utils.createCommaSeparatedList(signLocations));
}
// Groups
if(sender.hasPermission("areashop.groupinfo") && !buy.getGroupNames().isEmpty()) {
plugin.messageNoPrefix(sender, "info-regionGroups", Utils.createCommaSeparatedList(buy.getGroupNames()));
}
// Restoring
if(buy.isRestoreEnabled()) {
plugin.messageNoPrefix(sender, "info-regionRestoringBuy", buy);
}
// Restrictions
if(!buy.isSold()) {
if(buy.restrictedToRegion()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedRegionBuy", buy);
} else if(buy.restrictedToWorld()) {
plugin.messageNoPrefix(sender, "info-regionRestrictedWorldBuy", buy);
}
}
plugin.messageNoPrefix(sender, "info-regionFooterBuy", buy);
}
} else {
plugin.message(sender, "info-regionHelp");
}
} else {
plugin.message(sender, "info-help");
}
} else {
plugin.message(sender, "info-help");
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result.addAll(Arrays.asList("all", "rented", "forrent", "sold", "forsale", "player", "region", "nogroup", "reselling"));
} else if(toComplete == 3) {
if(start[2].equalsIgnoreCase("player")) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
} else if(start[2].equalsIgnoreCase("region")) {
result.addAll(plugin.getFileManager().getBuyNames());
result.addAll(plugin.getFileManager().getRentNames());
}
}
return result;
}
}
@@ -1,143 +1,143 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MeCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop me";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.me")) {
return "help-me";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.me")) {
plugin.message(sender, "me-noPermission");
return;
}
OfflinePlayer player = null;
if(!(sender instanceof Player)) {
if(args.length <= 1) {
plugin.message(sender, "me-notAPlayer");
return;
}
} else {
player = (OfflinePlayer)sender;
}
if(args.length > 1) {
player = Bukkit.getOfflinePlayer(args[1]);
if(player == null) {
plugin.message(sender, "me-noPlayer", args[1]);
return;
}
}
if(player == null) {
return;
}
// Get the regions owned by the player
Set<RentRegion> rentRegions = new HashSet<>();
for(RentRegion region : plugin.getFileManager().getRents()) {
if(region.isOwner(player)) {
rentRegions.add(region);
}
}
Set<BuyRegion> buyRegions = new HashSet<>();
for(BuyRegion region : plugin.getFileManager().getBuys()) {
if(region.isOwner(player)) {
buyRegions.add(region);
}
}
// Get the regions the player is added as friend
Set<LegacyGeneralRegion> friendRegions = new HashSet<>();
for(LegacyGeneralRegion region : plugin.getFileManager().getRegions()) {
if(region.getFriendsFeature().getFriends().contains(player.getUniqueId())) {
friendRegions.add(region);
}
}
// Send messages
boolean foundSome = !rentRegions.isEmpty() || !buyRegions.isEmpty() || !friendRegions.isEmpty();
if(foundSome) {
plugin.message(sender, "me-header", player.getName());
}
if(!rentRegions.isEmpty()) {
for(RentRegion region : rentRegions) {
plugin.messageNoPrefix(sender, "me-rentLine", region);
}
}
if(!buyRegions.isEmpty()) {
for(BuyRegion region : buyRegions) {
plugin.messageNoPrefix(sender, "me-buyLine", region);
}
}
if(!friendRegions.isEmpty()) {
for(LegacyGeneralRegion region : friendRegions) {
plugin.messageNoPrefix(sender, "me-friendLine", region);
}
}
if(!foundSome) {
plugin.message(sender, "me-nothing", player.getName());
} else {
plugin.messageNoPrefix(sender, "me-clickHint");
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MeCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop me";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.me")) {
return "help-me";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.me")) {
plugin.message(sender, "me-noPermission");
return;
}
OfflinePlayer player = null;
if(!(sender instanceof Player)) {
if(args.length <= 1) {
plugin.message(sender, "me-notAPlayer");
return;
}
} else {
player = (OfflinePlayer)sender;
}
if(args.length > 1) {
player = Bukkit.getOfflinePlayer(args[1]);
if(player == null) {
plugin.message(sender, "me-noPlayer", args[1]);
return;
}
}
if(player == null) {
return;
}
// Get the regions owned by the player
Set<RentRegion> rentRegions = new HashSet<>();
for(RentRegion region : plugin.getFileManager().getRents()) {
if(region.isOwner(player)) {
rentRegions.add(region);
}
}
Set<BuyRegion> buyRegions = new HashSet<>();
for(BuyRegion region : plugin.getFileManager().getBuys()) {
if(region.isOwner(player)) {
buyRegions.add(region);
}
}
// Get the regions the player is added as friend
Set<GeneralRegion> friendRegions = new HashSet<>();
for(GeneralRegion region : plugin.getFileManager().getRegions()) {
if(region.getFriendsFeature().getFriends().contains(player.getUniqueId())) {
friendRegions.add(region);
}
}
// Send messages
boolean foundSome = !rentRegions.isEmpty() || !buyRegions.isEmpty() || !friendRegions.isEmpty();
if(foundSome) {
plugin.message(sender, "me-header", player.getName());
}
if(!rentRegions.isEmpty()) {
for(RentRegion region : rentRegions) {
plugin.messageNoPrefix(sender, "me-rentLine", region);
}
}
if(!buyRegions.isEmpty()) {
for(BuyRegion region : buyRegions) {
plugin.messageNoPrefix(sender, "me-buyLine", region);
}
}
if(!friendRegions.isEmpty()) {
for(GeneralRegion region : friendRegions) {
plugin.messageNoPrefix(sender, "me-friendLine", region);
}
}
if(!foundSome) {
plugin.message(sender, "me-nothing", player.getName());
} else {
plugin.messageNoPrefix(sender, "me-clickHint");
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
}
return result;
}
}
@@ -1,69 +1,69 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class RentCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop rent";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.rent")) {
return "help-rent";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.rent")) {
plugin.message(sender, "rent-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
Player player = (Player)sender;
if(args.length > 1 && args[1] != null) {
RentRegion rent = plugin.getFileManager().getRent(args[1]);
if(rent == null) {
plugin.message(sender, "rent-notRentable", args[1]);
} else {
rent.rent(player);
}
} else {
// get the region by location
List<RentRegion> regions = Utils.getImportantRentRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
} else {
regions.get(0).rent(player);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(RentRegion region : plugin.getFileManager().getRents()) {
if(!region.isRented()) {
result.add(region.getRegionId());
}
}
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class RentCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop rent";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.rent")) {
return "help-rent";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.rent")) {
plugin.message(sender, "rent-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
Player player = (Player)sender;
if(args.length > 1 && args[1] != null) {
RentRegion rent = plugin.getFileManager().getRent(args[1]);
if(rent == null) {
plugin.message(sender, "rent-notRentable", args[1]);
} else {
rent.rent(player);
}
} else {
// get the region by location
List<RentRegion> regions = Utils.getImportantRentRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
} else {
regions.get(0).rent(player);
}
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(RentRegion region : plugin.getFileManager().getRents()) {
if(!region.isRented()) {
result.add(region.getName());
}
}
}
return result;
}
}
@@ -1,134 +1,134 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class ResellCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop resell";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.resellall") || target.hasPermission("areashop.resell")) {
return "help-resell";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.resell") && !sender.hasPermission("areashop.resellall")) {
plugin.message(sender, "resell-noPermissionOther");
return;
}
if(args.length <= 1) {
plugin.message(sender, "resell-help");
return;
}
double price;
try {
price = Double.parseDouble(args[1]);
} catch(NumberFormatException e) {
plugin.message(sender, "resell-wrongPrice", args[1]);
return;
}
if(price < 0) {
plugin.message(sender, "resell-wrongPrice", args[1]);
return;
}
BuyRegion buy;
if(args.length <= 2) {
if(sender instanceof Player) {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
buy = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
buy = plugin.getFileManager().getBuy(args[2]);
if(buy == null) {
plugin.message(sender, "resell-notRegistered", args[2]);
return;
}
}
if(buy == null) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
}
if(!buy.isSold()) {
plugin.message(sender, "resell-notBought", buy);
return;
}
if(sender.hasPermission("areashop.resellall")) {
buy.enableReselling(price);
buy.update();
plugin.message(sender, "resell-success", buy);
} else if(sender.hasPermission("areashop.resell") && sender instanceof Player) {
if(!buy.isOwner((Player)sender)) {
plugin.message(sender, "resell-noPermissionOther", buy);
return;
}
if(buy.getBooleanSetting("buy.resellDisabled")) {
plugin.message(sender, "resell-disabled", buy);
return;
}
buy.enableReselling(price);
buy.update();
plugin.message(sender, "resell-success", buy);
} else {
plugin.message(sender, "resell-noPermission", buy);
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 3) {
for(BuyRegion region : plugin.getFileManager().getBuys()) {
if(region.isSold() && !region.isInResellingMode()) {
result.add(region.getRegionId());
}
}
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class ResellCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop resell";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.resellall") || target.hasPermission("areashop.resell")) {
return "help-resell";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.resell") && !sender.hasPermission("areashop.resellall")) {
plugin.message(sender, "resell-noPermissionOther");
return;
}
if(args.length <= 1) {
plugin.message(sender, "resell-help");
return;
}
double price;
try {
price = Double.parseDouble(args[1]);
} catch(NumberFormatException e) {
plugin.message(sender, "resell-wrongPrice", args[1]);
return;
}
if(price < 0) {
plugin.message(sender, "resell-wrongPrice", args[1]);
return;
}
BuyRegion buy;
if(args.length <= 2) {
if(sender instanceof Player) {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
buy = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
buy = plugin.getFileManager().getBuy(args[2]);
if(buy == null) {
plugin.message(sender, "resell-notRegistered", args[2]);
return;
}
}
if(buy == null) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
}
if(!buy.isSold()) {
plugin.message(sender, "resell-notBought", buy);
return;
}
if(sender.hasPermission("areashop.resellall")) {
buy.enableReselling(price);
buy.update();
plugin.message(sender, "resell-success", buy);
} else if(sender.hasPermission("areashop.resell") && sender instanceof Player) {
if(!buy.isOwner((Player)sender)) {
plugin.message(sender, "resell-noPermissionOther", buy);
return;
}
if(buy.getBooleanSetting("buy.resellDisabled")) {
plugin.message(sender, "resell-disabled", buy);
return;
}
buy.enableReselling(price);
buy.update();
plugin.message(sender, "resell-success", buy);
} else {
plugin.message(sender, "resell-noPermission", buy);
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 3) {
for(BuyRegion region : plugin.getFileManager().getBuys()) {
if(region.isSold() && !region.isInResellingMode()) {
result.add(region.getName());
}
}
}
return result;
}
}
@@ -1,87 +1,86 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.regions.util.RegionEvent;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SchematiceventCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop schemevent";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.schematicevents")) {
return "help-schemevent";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.schematicevents")) {
plugin.message(sender, "schemevent-noPermission");
return;
}
if(args.length < 3 || args[1] == null || args[2] == null) {
plugin.message(sender, "schemevent-help");
return;
}
LegacyGeneralRegion region = plugin.getFileManager().getRegion(args[1]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[1]);
return;
}
if(region.getRegion() == null) {
plugin.message(sender, "general-noRegion", region);
return;
}
RegionEvent event = null;
boolean exception = false;
try {
event = RegionEvent.valueOf(args[2].toUpperCase());
} catch(IllegalArgumentException e) {
exception = true;
}
// Check for a totally wrong event or a non matching event
if(exception) {
ArrayList<String> values = new ArrayList<>();
for(RegionEvent value : RegionEvent.values()) {
values.add(value.getValue().toLowerCase());
}
plugin.message(sender, "schemevent-wrongEvent", args[2], Utils.createCommaSeparatedList(values), region);
return;
}
region.handleSchematicEvent(event);
region.update();
plugin.message(sender, "schemevent-success", args[2], region);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
result.addAll(plugin.getFileManager().getRegionNames());
} else if(toComplete == 3) {
LegacyGeneralRegion region = plugin.getFileManager().getRegion(start[2]);
if(region != null) {
if(region instanceof RentRegion) {
result.addAll(Arrays.asList("created", "deleted", "rented", "unrented"));
} else if(region instanceof BuyRegion) {
result.addAll(Arrays.asList("created", "deleted", "bought", "sold"));
}
}
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SchematiceventCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop schemevent";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.schematicevents")) {
return "help-schemevent";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.schematicevents")) {
plugin.message(sender, "schemevent-noPermission");
return;
}
if(args.length < 3 || args[1] == null || args[2] == null) {
plugin.message(sender, "schemevent-help");
return;
}
GeneralRegion region = plugin.getFileManager().getRegion(args[1]);
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[1]);
return;
}
if(region.getRegion() == null) {
plugin.message(sender, "general-noRegion", region);
return;
}
GeneralRegion.RegionEvent event = null;
boolean exception = false;
try {
event = GeneralRegion.RegionEvent.valueOf(args[2].toUpperCase());
} catch(IllegalArgumentException e) {
exception = true;
}
// Check for a totally wrong event or a non matching event
if(exception) {
ArrayList<String> values = new ArrayList<>();
for(GeneralRegion.RegionEvent value : GeneralRegion.RegionEvent.values()) {
values.add(value.getValue().toLowerCase());
}
plugin.message(sender, "schemevent-wrongEvent", args[2], Utils.createCommaSeparatedList(values), region);
return;
}
region.handleSchematicEvent(event);
region.update();
plugin.message(sender, "schemevent-success", args[2], region);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
result.addAll(plugin.getFileManager().getRegionNames());
} else if(toComplete == 3) {
GeneralRegion region = plugin.getFileManager().getRegion(start[2]);
if(region != null) {
if(region instanceof RentRegion) {
result.addAll(Arrays.asList("created", "deleted", "rented", "unrented"));
} else if(region instanceof BuyRegion) {
result.addAll(Arrays.asList("created", "deleted", "bought", "sold"));
}
}
}
return result;
}
}
@@ -1,110 +1,110 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class SellCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop sell";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.sell") || target.hasPermission("areashop.sellown")) {
return "help-sell";
}
return null;
}
/**
* Check if a person can sell the region.
* @param person The person to check
* @param region The region to check for
* @return true if the person can sell it, otherwise false
*/
public static boolean canUse(CommandSender person, LegacyGeneralRegion region) {
if(person.hasPermission("areashop.sell")) {
return true;
}
if(person instanceof Player) {
Player player = (Player)person;
return region.isOwner(player) && person.hasPermission("areashop.sellown");
}
return false;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.sell") && !sender.hasPermission("areashop.sellown")) {
plugin.message(sender, "sell-noPermission");
return;
}
BuyRegion buy;
if(args.length <= 1) {
if(sender instanceof Player) {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
buy = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
buy = plugin.getFileManager().getBuy(args[1]);
}
if(buy == null) {
plugin.message(sender, "sell-notRegistered");
return;
}
if(!buy.isSold()) {
plugin.message(sender, "sell-notBought", buy);
return;
}
buy.sell(true, sender);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(BuyRegion region : plugin.getFileManager().getBuys()) {
if(region.isSold()) {
result.add(region.getRegionId());
}
}
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class SellCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop sell";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.sell") || target.hasPermission("areashop.sellown")) {
return "help-sell";
}
return null;
}
/**
* Check if a person can sell the region.
* @param person The person to check
* @param region The region to check for
* @return true if the person can sell it, otherwise false
*/
public static boolean canUse(CommandSender person, GeneralRegion region) {
if(person.hasPermission("areashop.sell")) {
return true;
}
if(person instanceof Player) {
Player player = (Player)person;
return region.isOwner(player) && person.hasPermission("areashop.sellown");
}
return false;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.sell") && !sender.hasPermission("areashop.sellown")) {
plugin.message(sender, "sell-noPermission");
return;
}
BuyRegion buy;
if(args.length <= 1) {
if(sender instanceof Player) {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
buy = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
buy = plugin.getFileManager().getBuy(args[1]);
}
if(buy == null) {
plugin.message(sender, "sell-notRegistered");
return;
}
if(!buy.isSold()) {
plugin.message(sender, "sell-notBought", buy);
return;
}
buy.sell(true, sender);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(BuyRegion region : plugin.getFileManager().getBuys()) {
if(region.isSold()) {
result.add(region.getName());
}
}
}
return result;
}
}
@@ -1,87 +1,87 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class SetlandlordCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop setlandlord";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setlandlord")) {
return "help-setlandlord";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setlandlord")) {
plugin.message(sender, "setlandlord-noPermission");
return;
}
if(args.length < 2) {
plugin.message(sender, "setlandlord-help");
return;
}
@SuppressWarnings("deprecation")
OfflinePlayer player = Bukkit.getOfflinePlayer(args[1]);
LegacyGeneralRegion region;
if(args.length < 3) {
if(sender instanceof Player) {
// get the region by location
List<LegacyGeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
}
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
String playerName = player.getName();
if(playerName == null || playerName.isEmpty()) {
playerName = args[1];
}
region.setLandlord(player.getUniqueId(), playerName);
region.update();
plugin.message(sender, "setlandlord-success", playerName, region);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class SetlandlordCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop setlandlord";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setlandlord")) {
return "help-setlandlord";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setlandlord")) {
plugin.message(sender, "setlandlord-noPermission");
return;
}
if(args.length < 2) {
plugin.message(sender, "setlandlord-help");
return;
}
@SuppressWarnings("deprecation")
OfflinePlayer player = Bukkit.getOfflinePlayer(args[1]);
GeneralRegion region;
if(args.length < 3) {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
}
if(region == null) {
plugin.message(sender, "cmd-notRegistered", args[2]);
return;
}
String playerName = player.getName();
if(playerName == null || playerName.isEmpty()) {
playerName = args[1];
}
region.setLandlord(player.getUniqueId(), playerName);
region.update();
plugin.message(sender, "setlandlord-success", playerName, region);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
}
return result;
}
}
@@ -1,134 +1,134 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
public class SetownerCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop setowner";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setownerrent") || target.hasPermission("areashop.setownerbuy")) {
return "help-setowner";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setownerrent") && !sender.hasPermission("areashop.setownerbuy")) {
plugin.message(sender, "setowner-noPermission");
return;
}
LegacyGeneralRegion region;
if(args.length < 2) {
plugin.message(sender, "setowner-help");
return;
}
if(args.length == 2) {
if(sender instanceof Player) {
// get the region by location
List<LegacyGeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
}
if(region == null) {
plugin.message(sender, "setowner-notRegistered");
return;
}
if(region instanceof RentRegion && !sender.hasPermission("areashop.setownerrent")) {
plugin.message(sender, "setowner-noPermissionRent", region);
return;
}
if(region instanceof BuyRegion && !sender.hasPermission("areashop.setownerbuy")) {
plugin.message(sender, "setowner-noPermissionBuy", region);
return;
}
UUID uuid = null;
@SuppressWarnings("deprecation")
OfflinePlayer player = Bukkit.getOfflinePlayer(args[1]);
if(player != null) {
uuid = player.getUniqueId();
}
if(uuid == null) {
plugin.message(sender, "setowner-noPlayer", args[1], region);
return;
}
if(region instanceof RentRegion) {
RentRegion rent = (RentRegion)region;
if(rent.isRenter(uuid)) {
// extend
rent.setRentedUntil(rent.getRentedUntil() + rent.getDuration());
rent.setRenter(uuid);
plugin.message(sender, "setowner-succesRentExtend", region);
} else {
// change
if(!rent.isRented()) {
rent.setRentedUntil(Calendar.getInstance().getTimeInMillis() + rent.getDuration());
}
rent.setRenter(uuid);
plugin.message(sender, "setowner-succesRent", region);
}
}
if(region instanceof BuyRegion) {
BuyRegion buy = (BuyRegion)region;
buy.setBuyer(uuid);
plugin.message(sender, "setowner-succesBuy", region);
}
region.getFriendsFeature().deleteFriend(region.getOwner(), null);
region.update();
region.saveRequired();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;
public class SetownerCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop setowner";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setownerrent") || target.hasPermission("areashop.setownerbuy")) {
return "help-setowner";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setownerrent") && !sender.hasPermission("areashop.setownerbuy")) {
plugin.message(sender, "setowner-noPermission");
return;
}
GeneralRegion region;
if(args.length < 2) {
plugin.message(sender, "setowner-help");
return;
}
if(args.length == 2) {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
}
if(region == null) {
plugin.message(sender, "setowner-notRegistered");
return;
}
if(region instanceof RentRegion && !sender.hasPermission("areashop.setownerrent")) {
plugin.message(sender, "setowner-noPermissionRent", region);
return;
}
if(region instanceof BuyRegion && !sender.hasPermission("areashop.setownerbuy")) {
plugin.message(sender, "setowner-noPermissionBuy", region);
return;
}
UUID uuid = null;
@SuppressWarnings("deprecation")
OfflinePlayer player = Bukkit.getOfflinePlayer(args[1]);
if(player != null) {
uuid = player.getUniqueId();
}
if(uuid == null) {
plugin.message(sender, "setowner-noPlayer", args[1], region);
return;
}
if(region instanceof RentRegion) {
RentRegion rent = (RentRegion)region;
if(rent.isRenter(uuid)) {
// extend
rent.setRentedUntil(rent.getRentedUntil() + rent.getDuration());
rent.setRenter(uuid);
plugin.message(sender, "setowner-succesRentExtend", region);
} else {
// change
if(!rent.isRented()) {
rent.setRentedUntil(Calendar.getInstance().getTimeInMillis() + rent.getDuration());
}
rent.setRenter(uuid);
plugin.message(sender, "setowner-succesRent", region);
}
}
if(region instanceof BuyRegion) {
BuyRegion buy = (BuyRegion)region;
buy.setBuyer(uuid);
plugin.message(sender, "setowner-succesBuy", region);
}
region.getFriendsFeature().deleteFriend(region.getOwner(), null);
region.update();
region.saveRequired();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(Player player : Utils.getOnlinePlayers()) {
result.add(player.getName());
}
} else if(toComplete == 3) {
result.addAll(plugin.getFileManager().getRegionNames());
}
return result;
}
}
@@ -1,103 +1,103 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class SetpriceCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop setprice";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setprice")) {
return "help-setprice";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setprice") && (!sender.hasPermission("areashop.setprice.landlord") && sender instanceof Player)) {
plugin.message(sender, "setprice-noPermission");
return;
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "setprice-help");
return;
}
LegacyGeneralRegion region;
if(args.length < 3) {
if(sender instanceof Player) {
// get the region by location
List<LegacyGeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
}
if(region == null) {
plugin.message(sender, "setprice-notRegistered", args[2]);
return;
}
if(!sender.hasPermission("areashop.setprice") && !(sender instanceof Player && region.isLandlord(((Player)sender).getUniqueId()))) {
plugin.message(sender, "setprice-noLandlord", region);
return;
}
if("default".equalsIgnoreCase(args[1]) || "reset".equalsIgnoreCase(args[1])) {
if(region instanceof RentRegion) {
((RentRegion)region).setPrice(null);
} else if(region instanceof BuyRegion) {
((BuyRegion)region).setPrice(null);
}
region.update();
plugin.message(sender, "setprice-successRemoved", region);
return;
}
double price;
try {
price = Double.parseDouble(args[1]);
} catch(NumberFormatException e) {
plugin.message(sender, "setprice-wrongPrice", args[1], region);
return;
}
if(region instanceof RentRegion) {
((RentRegion)region).setPrice(price);
plugin.message(sender, "setprice-successRent", region);
} else if(region instanceof BuyRegion) {
((BuyRegion)region).setPrice(price);
plugin.message(sender, "setprice-successBuy", region);
}
region.update();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class SetpriceCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop setprice";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setprice")) {
return "help-setprice";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setprice") && (!sender.hasPermission("areashop.setprice.landlord") && sender instanceof Player)) {
plugin.message(sender, "setprice-noPermission");
return;
}
if(args.length < 2 || args[1] == null) {
plugin.message(sender, "setprice-help");
return;
}
GeneralRegion region;
if(args.length < 3) {
if(sender instanceof Player) {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
region = plugin.getFileManager().getRegion(args[2]);
}
if(region == null) {
plugin.message(sender, "setprice-notRegistered", args[2]);
return;
}
if(!sender.hasPermission("areashop.setprice") && !(sender instanceof Player && region.isLandlord(((Player)sender).getUniqueId()))) {
plugin.message(sender, "setprice-noLandlord", region);
return;
}
if("default".equalsIgnoreCase(args[1]) || "reset".equalsIgnoreCase(args[1])) {
if(region instanceof RentRegion) {
((RentRegion)region).setPrice(null);
} else if(region instanceof BuyRegion) {
((BuyRegion)region).setPrice(null);
}
region.update();
plugin.message(sender, "setprice-successRemoved", region);
return;
}
double price;
try {
price = Double.parseDouble(args[1]);
} catch(NumberFormatException e) {
plugin.message(sender, "setprice-wrongPrice", args[1], region);
return;
}
if(region instanceof RentRegion) {
((RentRegion)region).setPrice(price);
plugin.message(sender, "setprice-successRent", region);
} else if(region instanceof BuyRegion) {
((BuyRegion)region).setPrice(price);
plugin.message(sender, "setprice-successBuy", region);
}
region.update();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 3) {
result = plugin.getFileManager().getRegionNames();
}
return result;
}
}
@@ -1,73 +1,73 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.List;
public class SetrestoreCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop setrestore";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setrestore")) {
return "help-setrestore";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setrestore")) {
plugin.message(sender, "setrestore-noPermission");
return;
}
if(args.length <= 2 || args[1] == null || args[2] == null) {
plugin.message(sender, "setrestore-help");
return;
}
LegacyGeneralRegion region = plugin.getFileManager().getRegion(args[1]);
if(region == null) {
plugin.message(sender, "setrestore-notRegistered", args[1]);
return;
}
Boolean value = null;
if(args[2].equalsIgnoreCase("true")) {
value = true;
} else if(args[2].equalsIgnoreCase("false")) {
value = false;
}
region.setRestoreSetting(value);
String valueString = "general";
if(value != null) {
valueString = value + "";
}
if(args.length > 3) {
region.setSchematicProfile(args[3]);
plugin.message(sender, "setrestore-successProfile", valueString, args[3], region);
} else {
plugin.message(sender, "setrestore-success", valueString, region);
}
region.update();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getRegionNames();
} else if(toComplete == 3) {
result.add("true");
result.add("false");
result.add("general");
} else if(toComplete == 4) {
result.addAll(plugin.getConfig().getConfigurationSection("schematicProfiles").getKeys(false));
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.GeneralRegion;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.List;
public class SetrestoreCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop setrestore";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setrestore")) {
return "help-setrestore";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setrestore")) {
plugin.message(sender, "setrestore-noPermission");
return;
}
if(args.length <= 2 || args[1] == null || args[2] == null) {
plugin.message(sender, "setrestore-help");
return;
}
GeneralRegion region = plugin.getFileManager().getRegion(args[1]);
if(region == null) {
plugin.message(sender, "setrestore-notRegistered", args[1]);
return;
}
Boolean value = null;
if(args[2].equalsIgnoreCase("true")) {
value = true;
} else if(args[2].equalsIgnoreCase("false")) {
value = false;
}
region.setRestoreSetting(value);
String valueString = "general";
if(value != null) {
valueString = value + "";
}
if(args.length > 3) {
region.setSchematicProfile(args[3]);
plugin.message(sender, "setrestore-successProfile", valueString, args[3], region);
} else {
plugin.message(sender, "setrestore-success", valueString, region);
}
region.update();
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 2) {
result = plugin.getFileManager().getRegionNames();
} else if(toComplete == 3) {
result.add("true");
result.add("false");
result.add("general");
} else if(toComplete == 4) {
result.addAll(plugin.getConfig().getConfigurationSection("schematicProfiles").getKeys(false));
}
return result;
}
}
@@ -1,118 +1,118 @@
package me.wiefferink.areashop.commands;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class SetteleportCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop settp";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setteleportall") || target.hasPermission("areashop.setteleport")) {
return "help-setteleport";
}
return null;
}
/**
* Check if a person can set the teleport location of the region.
* @param person The person to check
* @param region The region to check for
* @return true if the person can set the teleport location, otherwise false
*/
public static boolean canUse(CommandSender person, LegacyGeneralRegion region) {
if(!(person instanceof Player)) {
return false;
}
Player player = (Player)person;
return player.hasPermission("areashop.setteleportall")
|| region.isOwner(player) && player.hasPermission("areashop.setteleport");
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setteleport") && !sender.hasPermission("areashop.setteleportall")) {
plugin.message(sender, "setteleport-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "onlyByPlayer");
return;
}
Player player = (Player)sender;
LegacyGeneralRegion region;
if(args.length < 2) {
// get the region by location
List<LegacyGeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
region = plugin.getFileManager().getRegion(args[1]);
}
boolean owner;
if(region == null) {
plugin.message(player, "setteleport-noRentOrBuy", args[1]);
return;
}
if(region instanceof RentRegion) {
owner = player.getUniqueId().equals(((RentRegion)region).getRenter());
} else {
owner = player.getUniqueId().equals(((BuyRegion)region).getBuyer());
}
if(!player.hasPermission("areashop.setteleport")) {
plugin.message(player, "setteleport-noPermission", region);
return;
} else if(!owner && !player.hasPermission("areashop.setteleportall")) {
plugin.message(player, "setteleport-noPermissionOther", region);
return;
}
ProtectedRegion wgRegion = region.getRegion();
if(args.length > 2 && args[2] != null && (args[2].equalsIgnoreCase("reset") || args[2].equalsIgnoreCase("yes") || args[2].equalsIgnoreCase("true"))) {
region.getTeleportFeature().setTeleport(null);
region.update();
plugin.message(player, "setteleport-reset", region);
return;
}
if(!player.hasPermission("areashop.setteleportoutsideregion") && (wgRegion == null || !wgRegion.contains(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()))) {
plugin.message(player, "setteleport-notInside", region);
return;
}
region.getTeleportFeature().setTeleport(player.getLocation());
region.update();
plugin.message(player, "setteleport-success", region);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
result.addAll(plugin.getFileManager().getRegionNames());
} else if(toComplete == 3) {
result.add("reset");
}
return result;
}
}
package me.wiefferink.areashop.commands;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class SetteleportCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop settp";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.setteleportall") || target.hasPermission("areashop.setteleport")) {
return "help-setteleport";
}
return null;
}
/**
* Check if a person can set the teleport location of the region.
* @param person The person to check
* @param region The region to check for
* @return true if the person can set the teleport location, otherwise false
*/
public static boolean canUse(CommandSender person, GeneralRegion region) {
if(!(person instanceof Player)) {
return false;
}
Player player = (Player)person;
return player.hasPermission("areashop.setteleportall")
|| region.isOwner(player) && player.hasPermission("areashop.setteleport");
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.setteleport") && !sender.hasPermission("areashop.setteleportall")) {
plugin.message(sender, "setteleport-noPermission");
return;
}
if(!(sender instanceof Player)) {
plugin.message(sender, "onlyByPlayer");
return;
}
Player player = (Player)sender;
GeneralRegion region;
if(args.length < 2) {
// get the region by location
List<GeneralRegion> regions = Utils.getImportantRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
region = regions.get(0);
}
} else {
region = plugin.getFileManager().getRegion(args[1]);
}
boolean owner;
if(region == null) {
plugin.message(player, "setteleport-noRentOrBuy", args[1]);
return;
}
if(region instanceof RentRegion) {
owner = player.getUniqueId().equals(((RentRegion)region).getRenter());
} else {
owner = player.getUniqueId().equals(((BuyRegion)region).getBuyer());
}
if(!player.hasPermission("areashop.setteleport")) {
plugin.message(player, "setteleport-noPermission", region);
return;
} else if(!owner && !player.hasPermission("areashop.setteleportall")) {
plugin.message(player, "setteleport-noPermissionOther", region);
return;
}
ProtectedRegion wgRegion = region.getRegion();
if(args.length > 2 && args[2] != null && (args[2].equalsIgnoreCase("reset") || args[2].equalsIgnoreCase("yes") || args[2].equalsIgnoreCase("true"))) {
region.getTeleportFeature().setTeleport(null);
region.update();
plugin.message(player, "setteleport-reset", region);
return;
}
if(!player.hasPermission("areashop.setteleportoutsideregion") && (wgRegion == null || !wgRegion.contains(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()))) {
plugin.message(player, "setteleport-notInside", region);
return;
}
region.getTeleportFeature().setTeleport(player.getLocation());
region.update();
plugin.message(player, "setteleport-success", region);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
result.addAll(plugin.getFileManager().getRegionNames());
} else if(toComplete == 3) {
result.add("reset");
}
return result;
}
}
@@ -1,264 +1,263 @@
package me.wiefferink.areashop.commands;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.regions.util.RegionEvent;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.interactivemessenger.processing.Message;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.List;
public class StackCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop stack";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.stack")) {
return "help-stack";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
// Check permission
if(!sender.hasPermission("areashop.stack")) {
plugin.message(sender, "stack-noPermission");
return;
}
// Only from ingame
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
final Player player = (Player)sender;
// Specify enough arguments
if(args.length < 5) {
plugin.message(sender, "stack-help");
return;
}
// Check amount
int tempAmount = -1;
try {
tempAmount = Integer.parseInt(args[1]);
} catch(NumberFormatException e) {
// Incorrect number
}
if(tempAmount <= 0) {
plugin.message(player, "stack-wrongAmount", args[1]);
return;
}
// Check gap
int gap;
try {
gap = Integer.parseInt(args[2]);
} catch(NumberFormatException e) {
plugin.message(player, "stack-wrongGap", args[2]);
return;
}
// Check region type
if(!"rent".equalsIgnoreCase(args[4]) && !"buy".equalsIgnoreCase(args[4])) {
plugin.message(sender, "stack-help");
return;
}
// Get WorldEdit selection
final WorldEditSelection selection = plugin.getWorldEditHandler().getPlayerSelection(player);
if(selection == null) {
plugin.message(player, "stack-noSelection");
return;
}
// Get or create group
RegionGroup group = null;
if(args.length > 5) {
group = plugin.getFileManager().getGroup(args[5]);
if(group == null) {
group = new RegionGroup(plugin, args[5]);
plugin.getFileManager().addGroup(group);
}
}
// Get facing of the player (must be clearly one of the four directions to make sure it is no mistake)
BlockFace facing = Utils.yawToFacing(player.getLocation().getYaw());
if(player.getLocation().getPitch() > 45) {
facing = BlockFace.DOWN;
} else if(player.getLocation().getPitch() < -45) {
facing = BlockFace.UP;
}
if(!(facing == BlockFace.NORTH || facing == BlockFace.EAST || facing == BlockFace.SOUTH || facing == BlockFace.WEST || facing == BlockFace.UP || facing == BlockFace.DOWN)) {
plugin.message(player, "stack-unclearDirection", facing.toString().toLowerCase().replace('_', '-'));
return;
}
Vector shift = new Vector(0, 0, 0);
if(facing == BlockFace.SOUTH) {
shift = shift.setZ(-selection.getLength() - gap);
} else if(facing == BlockFace.WEST) {
shift = shift.setX(selection.getWidth() + gap);
} else if(facing == BlockFace.NORTH) {
shift = shift.setZ(selection.getLength() + gap);
} else if(facing == BlockFace.EAST) {
shift = shift.setX(-selection.getWidth() - gap);
} else if(facing == BlockFace.DOWN) {
shift = shift.setY(-selection.getHeight() - gap);
} else if(facing == BlockFace.UP) {
shift = shift.setY(selection.getHeight() + gap);
}
AreaShop.debug(" calculated shift vector: " + shift + ", with facing=" + facing);
// Create regions and add them to AreaShop
final String nameTemplate = args[3];
final int regionsPerTick = plugin.getConfig().getInt("adding.regionsPerTick");
final boolean rentRegions = "rent".equalsIgnoreCase(args[4]);
final int amount = tempAmount;
final RegionGroup finalGroup = group;
final Vector finalShift = shift;
String type;
if(rentRegions) {
type = "rent";
} else {
type = "buy";
}
Message groupsMessage = Message.empty();
if(group != null) {
groupsMessage = Message.fromKey("stack-addToGroup").replacements(group.getName());
}
plugin.message(player, "stack-accepted", amount, type, gap, nameTemplate, groupsMessage);
plugin.message(player, "stack-addStart", amount, regionsPerTick * 20);
Location minimumLocation = selection.getMinimumLocation();
Vector minimumVector = new Vector(minimumLocation.getX(), minimumLocation.getY(), minimumLocation.getZ());
Location maximumLocation = selection.getMaximumLocation();
Vector maximumVector = new Vector(maximumLocation.getX(), maximumLocation.getY(), maximumLocation.getZ());
new BukkitRunnable() {
private int current = -1;
private final RegionManager manager = AreaShop.getInstance().getRegionManager(selection.getWorld());
private int counter = 1;
private int tooLow = 0;
private int tooHigh = 0;
@Override
public void run() {
for(int i = 0; i < regionsPerTick; i++) {
current++;
if(current < amount) {
// Create the region name
String regionName = countToName(nameTemplate, counter);
while(manager.getRegion(regionName) != null || AreaShop.getInstance().getFileManager().getRegion(regionName) != null) {
counter++;
regionName = countToName(nameTemplate, counter);
}
// Add the region to WorldGuard (at startposition shifted by the number of this region times the blocks it should shift)
Vector minimum = minimumVector.clone().add(finalShift.clone().multiply(current));
Vector maximum = maximumVector.clone().add(finalShift.clone().multiply(current));
// Check for out of bounds
if(minimum.getBlockY() < 0) {
tooLow++;
continue;
} else if(maximum.getBlockY() > 256) {
tooHigh++;
continue;
}
ProtectedCuboidRegion region = plugin.getWorldGuardHandler().createCuboidRegion(regionName, minimum,maximum);
manager.addRegion(region);
// Add the region to AreaShop
LegacyGeneralRegion newRegion;
if(rentRegions) {
newRegion = new RentRegion(regionName, selection.getWorld());
} else {
newRegion = new BuyRegion(regionName, selection.getWorld());
}
if(finalGroup != null) {
finalGroup.addMember(newRegion);
}
AddingRegionEvent event = plugin.getFileManager().addRegion(newRegion);
if (event.isCancelled()) {
plugin.message(player, "general-cancelled", event.getReason());
continue;
}
newRegion.handleSchematicEvent(RegionEvent.CREATED);
newRegion.update();
}
}
if(current >= amount) {
if(player.isOnline()) {
int added = amount - tooLow - tooHigh;
Message wrong = Message.empty();
if(tooHigh > 0) {
wrong.append(Message.fromKey("stack-tooHigh").replacements(tooHigh));
}
if(tooLow > 0) {
wrong.append(Message.fromKey("stack-tooLow").replacements(tooLow));
}
plugin.message(player, "stack-addComplete", added, wrong);
}
this.cancel();
}
}
}.runTaskTimer(plugin, 1, 1);
}
/**
* Build a name from a count, with the right length.
* @param template Template to put the name in (# to put the count there, otherwise count is appended)
* @param count Number to use
* @return name with prepended 0's
*/
private String countToName(String template, int count) {
StringBuilder counterName = new StringBuilder().append(count);
int minimumLength = plugin.getConfig().getInt("stackRegionNumberLength");
while(counterName.length() < minimumLength) {
counterName.insert(0, "0");
}
if(template.contains("#")) {
return template.replace("#", counterName);
} else {
return template + counterName;
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 5) {
result.add("rent");
result.add("buy");
} else if(toComplete == 6) {
result.addAll(plugin.getFileManager().getGroupNames());
}
return result;
}
}
package me.wiefferink.areashop.commands;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.interactivemessenger.processing.Message;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.List;
public class StackCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop stack";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.stack")) {
return "help-stack";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
// Check permission
if(!sender.hasPermission("areashop.stack")) {
plugin.message(sender, "stack-noPermission");
return;
}
// Only from ingame
if(!(sender instanceof Player)) {
plugin.message(sender, "cmd-onlyByPlayer");
return;
}
final Player player = (Player)sender;
// Specify enough arguments
if(args.length < 5) {
plugin.message(sender, "stack-help");
return;
}
// Check amount
int tempAmount = -1;
try {
tempAmount = Integer.parseInt(args[1]);
} catch(NumberFormatException e) {
// Incorrect number
}
if(tempAmount <= 0) {
plugin.message(player, "stack-wrongAmount", args[1]);
return;
}
// Check gap
int gap;
try {
gap = Integer.parseInt(args[2]);
} catch(NumberFormatException e) {
plugin.message(player, "stack-wrongGap", args[2]);
return;
}
// Check region type
if(!"rent".equalsIgnoreCase(args[4]) && !"buy".equalsIgnoreCase(args[4])) {
plugin.message(sender, "stack-help");
return;
}
// Get WorldEdit selection
final WorldEditSelection selection = plugin.getWorldEditHandler().getPlayerSelection(player);
if(selection == null) {
plugin.message(player, "stack-noSelection");
return;
}
// Get or create group
RegionGroup group = null;
if(args.length > 5) {
group = plugin.getFileManager().getGroup(args[5]);
if(group == null) {
group = new RegionGroup(plugin, args[5]);
plugin.getFileManager().addGroup(group);
}
}
// Get facing of the player (must be clearly one of the four directions to make sure it is no mistake)
BlockFace facing = Utils.yawToFacing(player.getLocation().getYaw());
if(player.getLocation().getPitch() > 45) {
facing = BlockFace.DOWN;
} else if(player.getLocation().getPitch() < -45) {
facing = BlockFace.UP;
}
if(!(facing == BlockFace.NORTH || facing == BlockFace.EAST || facing == BlockFace.SOUTH || facing == BlockFace.WEST || facing == BlockFace.UP || facing == BlockFace.DOWN)) {
plugin.message(player, "stack-unclearDirection", facing.toString().toLowerCase().replace('_', '-'));
return;
}
Vector shift = new Vector(0, 0, 0);
if(facing == BlockFace.SOUTH) {
shift = shift.setZ(-selection.getLength() - gap);
} else if(facing == BlockFace.WEST) {
shift = shift.setX(selection.getWidth() + gap);
} else if(facing == BlockFace.NORTH) {
shift = shift.setZ(selection.getLength() + gap);
} else if(facing == BlockFace.EAST) {
shift = shift.setX(-selection.getWidth() - gap);
} else if(facing == BlockFace.DOWN) {
shift = shift.setY(-selection.getHeight() - gap);
} else if(facing == BlockFace.UP) {
shift = shift.setY(selection.getHeight() + gap);
}
AreaShop.debug(" calculated shift vector: " + shift + ", with facing=" + facing);
// Create regions and add them to AreaShop
final String nameTemplate = args[3];
final int regionsPerTick = plugin.getConfig().getInt("adding.regionsPerTick");
final boolean rentRegions = "rent".equalsIgnoreCase(args[4]);
final int amount = tempAmount;
final RegionGroup finalGroup = group;
final Vector finalShift = shift;
String type;
if(rentRegions) {
type = "rent";
} else {
type = "buy";
}
Message groupsMessage = Message.empty();
if(group != null) {
groupsMessage = Message.fromKey("stack-addToGroup").replacements(group.getName());
}
plugin.message(player, "stack-accepted", amount, type, gap, nameTemplate, groupsMessage);
plugin.message(player, "stack-addStart", amount, regionsPerTick * 20);
Location minimumLocation = selection.getMinimumLocation();
Vector minimumVector = new Vector(minimumLocation.getX(), minimumLocation.getY(), minimumLocation.getZ());
Location maximumLocation = selection.getMaximumLocation();
Vector maximumVector = new Vector(maximumLocation.getX(), maximumLocation.getY(), maximumLocation.getZ());
new BukkitRunnable() {
private int current = -1;
private final RegionManager manager = AreaShop.getInstance().getRegionManager(selection.getWorld());
private int counter = 1;
private int tooLow = 0;
private int tooHigh = 0;
@Override
public void run() {
for(int i = 0; i < regionsPerTick; i++) {
current++;
if(current < amount) {
// Create the region name
String regionName = countToName(nameTemplate, counter);
while(manager.getRegion(regionName) != null || AreaShop.getInstance().getFileManager().getRegion(regionName) != null) {
counter++;
regionName = countToName(nameTemplate, counter);
}
// Add the region to WorldGuard (at startposition shifted by the number of this region times the blocks it should shift)
Vector minimum = minimumVector.clone().add(finalShift.clone().multiply(current));
Vector maximum = maximumVector.clone().add(finalShift.clone().multiply(current));
// Check for out of bounds
if(minimum.getBlockY() < 0) {
tooLow++;
continue;
} else if(maximum.getBlockY() > 256) {
tooHigh++;
continue;
}
ProtectedCuboidRegion region = plugin.getWorldGuardHandler().createCuboidRegion(regionName, minimum,maximum);
manager.addRegion(region);
// Add the region to AreaShop
GeneralRegion newRegion;
if(rentRegions) {
newRegion = new RentRegion(regionName, selection.getWorld());
} else {
newRegion = new BuyRegion(regionName, selection.getWorld());
}
if(finalGroup != null) {
finalGroup.addMember(newRegion);
}
AddingRegionEvent event = plugin.getFileManager().addRegion(newRegion);
if (event.isCancelled()) {
plugin.message(player, "general-cancelled", event.getReason());
continue;
}
newRegion.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
newRegion.update();
}
}
if(current >= amount) {
if(player.isOnline()) {
int added = amount - tooLow - tooHigh;
Message wrong = Message.empty();
if(tooHigh > 0) {
wrong.append(Message.fromKey("stack-tooHigh").replacements(tooHigh));
}
if(tooLow > 0) {
wrong.append(Message.fromKey("stack-tooLow").replacements(tooLow));
}
plugin.message(player, "stack-addComplete", added, wrong);
}
this.cancel();
}
}
}.runTaskTimer(plugin, 1, 1);
}
/**
* Build a name from a count, with the right length.
* @param template Template to put the name in (# to put the count there, otherwise count is appended)
* @param count Number to use
* @return name with prepended 0's
*/
private String countToName(String template, int count) {
StringBuilder counterName = new StringBuilder().append(count);
int minimumLength = plugin.getConfig().getInt("stackRegionNumberLength");
while(counterName.length() < minimumLength) {
counterName.insert(0, "0");
}
if(template.contains("#")) {
return template.replace("#", counterName);
} else {
return template + counterName;
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
List<String> result = new ArrayList<>();
if(toComplete == 5) {
result.add("rent");
result.add("buy");
} else if(toComplete == 6) {
result.addAll(plugin.getFileManager().getGroupNames());
}
return result;
}
}
@@ -1,111 +1,111 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class StopresellCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop stopresell";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.stopresellall") || target.hasPermission("areashop.stopresell")) {
return "help-stopResell";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.stopresell") && !sender.hasPermission("areashop.stopresellall")) {
plugin.message(sender, "stopresell-noPermissionOther");
return;
}
BuyRegion buy;
if(args.length <= 1) {
if(sender instanceof Player) {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
buy = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
buy = plugin.getFileManager().getBuy(args[1]);
if(buy == null) {
plugin.message(sender, "stopresell-notRegistered", args[1]);
return;
}
}
if(buy == null) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
}
if(!buy.isInResellingMode()) {
plugin.message(sender, "stopresell-notResell", buy);
return;
}
if(sender.hasPermission("areashop.stopresellall")) {
buy.disableReselling();
buy.update();
plugin.message(sender, "stopresell-success", buy);
} else if(sender.hasPermission("areashop.stopresell") && sender instanceof Player) {
if(buy.isOwner((Player)sender)) {
buy.disableReselling();
buy.update();
plugin.message(sender, "stopresell-success", buy);
} else {
plugin.message(sender, "stopresell-noPermissionOther", buy);
}
} else {
plugin.message(sender, "stopresell-noPermission", buy);
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(BuyRegion region : plugin.getFileManager().getBuys()) {
if(region.isSold() && region.isInResellingMode()) {
result.add(region.getRegionId());
}
}
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class StopresellCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop stopresell";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.stopresellall") || target.hasPermission("areashop.stopresell")) {
return "help-stopResell";
}
return null;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.stopresell") && !sender.hasPermission("areashop.stopresellall")) {
plugin.message(sender, "stopresell-noPermissionOther");
return;
}
BuyRegion buy;
if(args.length <= 1) {
if(sender instanceof Player) {
// get the region by location
List<BuyRegion> regions = Utils.getImportantBuyRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
buy = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
buy = plugin.getFileManager().getBuy(args[1]);
if(buy == null) {
plugin.message(sender, "stopresell-notRegistered", args[1]);
return;
}
}
if(buy == null) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
}
if(!buy.isInResellingMode()) {
plugin.message(sender, "stopresell-notResell", buy);
return;
}
if(sender.hasPermission("areashop.stopresellall")) {
buy.disableReselling();
buy.update();
plugin.message(sender, "stopresell-success", buy);
} else if(sender.hasPermission("areashop.stopresell") && sender instanceof Player) {
if(buy.isOwner((Player)sender)) {
buy.disableReselling();
buy.update();
plugin.message(sender, "stopresell-success", buy);
} else {
plugin.message(sender, "stopresell-noPermissionOther", buy);
}
} else {
plugin.message(sender, "stopresell-noPermission", buy);
}
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(BuyRegion region : plugin.getFileManager().getBuys()) {
if(region.isSold() && region.isInResellingMode()) {
result.add(region.getName());
}
}
}
return result;
}
}
@@ -1,9 +1,10 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -16,7 +17,7 @@ public class TeleportCommand extends CommandAreaShop {
* @param region The region to check for
* @return true if the person can teleport to it, otherwise false
*/
public static boolean canUse(CommandSender person, LegacyGeneralRegion region) {
public static boolean canUse(CommandSender person, GeneralRegion region) {
if (!(person instanceof Player)) {
return false;
}
@@ -55,7 +56,7 @@ public class TeleportCommand extends CommandAreaShop {
return;
}
Player player = (Player) sender;
LegacyGeneralRegion region = plugin.getFileManager().getRegion(args[1]);
GeneralRegion region = plugin.getFileManager().getRegion(args[1]);
if (region == null) {
plugin.message(player, "teleport-noRentOrBuy", args[1]);
return;
@@ -1,102 +1,102 @@
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class UnrentCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop unrent";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.unrent") || target.hasPermission("areashop.unrentown")) {
return "help-unrent";
}
return null;
}
/**
* Check if a person can unrent the region.
* @param person The person to check
* @param region The region to check for
* @return true if the person can unrent it, otherwise false
*/
public static boolean canUse(CommandSender person, LegacyGeneralRegion region) {
if(person.hasPermission("areashop.unrent")) {
return true;
}
if(person instanceof Player) {
Player player = (Player)person;
return region.isOwner(player) && person.hasPermission("areashop.unrentown");
}
return false;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.unrent") && !sender.hasPermission("areashop.unrentown")) {
plugin.message(sender, "unrent-noPermission");
return;
}
RentRegion rent;
if(args.length <= 1) {
if(sender instanceof Player) {
// get the region by location
List<RentRegion> regions = Utils.getImportantRentRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
rent = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
rent = plugin.getFileManager().getRent(args[1]);
}
if(rent == null) {
plugin.message(sender, "unrent-notRegistered");
return;
}
if(!rent.isRented()) {
plugin.message(sender, "unrent-notRented", rent);
return;
}
rent.unRent(true, sender);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(RentRegion region : plugin.getFileManager().getRents()) {
if(region.isRented()) {
result.add(region.getRegionId());
}
}
}
return result;
}
}
package me.wiefferink.areashop.commands;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class UnrentCommand extends CommandAreaShop {
@Override
public String getCommandStart() {
return "areashop unrent";
}
@Override
public String getHelp(CommandSender target) {
if(target.hasPermission("areashop.unrent") || target.hasPermission("areashop.unrentown")) {
return "help-unrent";
}
return null;
}
/**
* Check if a person can unrent the region.
* @param person The person to check
* @param region The region to check for
* @return true if the person can unrent it, otherwise false
*/
public static boolean canUse(CommandSender person, GeneralRegion region) {
if(person.hasPermission("areashop.unrent")) {
return true;
}
if(person instanceof Player) {
Player player = (Player)person;
return region.isOwner(player) && person.hasPermission("areashop.unrentown");
}
return false;
}
@Override
public void execute(CommandSender sender, String[] args) {
if(!sender.hasPermission("areashop.unrent") && !sender.hasPermission("areashop.unrentown")) {
plugin.message(sender, "unrent-noPermission");
return;
}
RentRegion rent;
if(args.length <= 1) {
if(sender instanceof Player) {
// get the region by location
List<RentRegion> regions = Utils.getImportantRentRegions(((Player)sender).getLocation());
if(regions.isEmpty()) {
plugin.message(sender, "cmd-noRegionsAtLocation");
return;
} else if(regions.size() > 1) {
plugin.message(sender, "cmd-moreRegionsAtLocation");
return;
} else {
rent = regions.get(0);
}
} else {
plugin.message(sender, "cmd-automaticRegionOnlyByPlayer");
return;
}
} else {
rent = plugin.getFileManager().getRent(args[1]);
}
if(rent == null) {
plugin.message(sender, "unrent-notRegistered");
return;
}
if(!rent.isRented()) {
plugin.message(sender, "unrent-notRented", rent);
return;
}
rent.unRent(true, sender);
}
@Override
public List<String> getTabCompleteList(int toComplete, String[] start, CommandSender sender) {
ArrayList<String> result = new ArrayList<>();
if(toComplete == 2) {
for(RentRegion region : plugin.getFileManager().getRents()) {
if(region.isRented()) {
result.add(region.getName());
}
}
}
return result;
}
}
@@ -1,19 +1,19 @@
package me.wiefferink.areashop.events.ask;
import me.wiefferink.areashop.events.CancellableRegionEvent;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
/**
* Broadcasted when a region has been added to AreaShop.
*/
public class AddingRegionEvent extends CancellableRegionEvent<LegacyGeneralRegion> {
/**
* Constructor.
* @param region The region that has been added
*/
public AddingRegionEvent(LegacyGeneralRegion region) {
super(region);
}
}
package me.wiefferink.areashop.events.ask;
import me.wiefferink.areashop.events.CancellableRegionEvent;
import me.wiefferink.areashop.regions.GeneralRegion;
/**
* Broadcasted when a region has been added to AreaShop.
*/
public class AddingRegionEvent extends CancellableRegionEvent<GeneralRegion> {
/**
* Constructor.
* @param region The region that has been added
*/
public AddingRegionEvent(GeneralRegion region) {
super(region);
}
}
@@ -1,19 +1,19 @@
package me.wiefferink.areashop.events.ask;
import me.wiefferink.areashop.events.CancellableRegionEvent;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
/**
* Broadcasted when a region has been added to AreaShop.
*/
public class DeletingRegionEvent extends CancellableRegionEvent<LegacyGeneralRegion> {
/**
* Constructor.
* @param region The region that has been added
*/
public DeletingRegionEvent(LegacyGeneralRegion region) {
super(region);
}
}
package me.wiefferink.areashop.events.ask;
import me.wiefferink.areashop.events.CancellableRegionEvent;
import me.wiefferink.areashop.regions.GeneralRegion;
/**
* Broadcasted when a region has been added to AreaShop.
*/
public class DeletingRegionEvent extends CancellableRegionEvent<GeneralRegion> {
/**
* Constructor.
* @param region The region that has been added
*/
public DeletingRegionEvent(GeneralRegion region) {
super(region);
}
}
@@ -1,43 +1,43 @@
package me.wiefferink.areashop.events.askandnotify;
import me.wiefferink.areashop.events.CancellableRegionEvent;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
/**
* Broadcasted when a friend is being added to a region.
*/
public class AddedFriendEvent extends CancellableRegionEvent<LegacyGeneralRegion> {
private final OfflinePlayer friend;
private final CommandSender by;
/**
* Constructor.
* @param region The region the friend is getting added to
* @param friend The friend that is about to be added
* @param by The CommandSender that is adding the friend, or null if none
*/
public AddedFriendEvent(LegacyGeneralRegion region, OfflinePlayer friend, CommandSender by) {
super(region);
this.friend = friend;
this.by = by;
}
/**
* Get the OfflinePlayer that is getting added as friend.
* @return The friend that is getting added
*/
public OfflinePlayer getFriend() {
return friend;
}
/**
* Get the CommandSender that is adding the friend.
* @return null if none, a CommandSender if done by someone (likely Player or ConsoleCommandSender)
*/
public CommandSender getBy() {
return by;
}
}
package me.wiefferink.areashop.events.askandnotify;
import me.wiefferink.areashop.events.CancellableRegionEvent;
import me.wiefferink.areashop.regions.GeneralRegion;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
/**
* Broadcasted when a friend is being added to a region.
*/
public class AddedFriendEvent extends CancellableRegionEvent<GeneralRegion> {
private final OfflinePlayer friend;
private final CommandSender by;
/**
* Constructor.
* @param region The region the friend is getting added to
* @param friend The friend that is about to be added
* @param by The CommandSender that is adding the friend, or null if none
*/
public AddedFriendEvent(GeneralRegion region, OfflinePlayer friend, CommandSender by) {
super(region);
this.friend = friend;
this.by = by;
}
/**
* Get the OfflinePlayer that is getting added as friend.
* @return The friend that is getting added
*/
public OfflinePlayer getFriend() {
return friend;
}
/**
* Get the CommandSender that is adding the friend.
* @return null if none, a CommandSender if done by someone (likely Player or ConsoleCommandSender)
*/
public CommandSender getBy() {
return by;
}
}
@@ -1,43 +1,43 @@
package me.wiefferink.areashop.events.askandnotify;
import me.wiefferink.areashop.events.CancellableRegionEvent;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
/**
* Broadcasted when a friend is being added to a region.
*/
public class DeletedFriendEvent extends CancellableRegionEvent<LegacyGeneralRegion> {
private final OfflinePlayer friend;
private final CommandSender by;
/**
* Constructor.
* @param region The region the friend is getting added to
* @param friend The friend that is about to be added
* @param by The CommandSender that is adding the friend, or null if none
*/
public DeletedFriendEvent(LegacyGeneralRegion region, OfflinePlayer friend, CommandSender by) {
super(region);
this.friend = friend;
this.by = by;
}
/**
* Get the OfflinePlayer that is getting added as friend.
* @return The friend that is getting added
*/
public OfflinePlayer getFriend() {
return friend;
}
/**
* Get the CommandSender that is adding the friend.
* @return null if none, a CommandSender if done by someone (likely Player or ConsoleCommandSender)
*/
public CommandSender getBy() {
return by;
}
}
package me.wiefferink.areashop.events.askandnotify;
import me.wiefferink.areashop.events.CancellableRegionEvent;
import me.wiefferink.areashop.regions.GeneralRegion;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
/**
* Broadcasted when a friend is being added to a region.
*/
public class DeletedFriendEvent extends CancellableRegionEvent<GeneralRegion> {
private final OfflinePlayer friend;
private final CommandSender by;
/**
* Constructor.
* @param region The region the friend is getting added to
* @param friend The friend that is about to be added
* @param by The CommandSender that is adding the friend, or null if none
*/
public DeletedFriendEvent(GeneralRegion region, OfflinePlayer friend, CommandSender by) {
super(region);
this.friend = friend;
this.by = by;
}
/**
* Get the OfflinePlayer that is getting added as friend.
* @return The friend that is getting added
*/
public OfflinePlayer getFriend() {
return friend;
}
/**
* Get the CommandSender that is adding the friend.
* @return null if none, a CommandSender if done by someone (likely Player or ConsoleCommandSender)
*/
public CommandSender getBy() {
return by;
}
}
@@ -1,19 +1,19 @@
package me.wiefferink.areashop.events.notify;
import me.wiefferink.areashop.events.NotifyRegionEvent;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
/**
* Broadcasted when a region has been added to AreaShop.
*/
public class AddedRegionEvent extends NotifyRegionEvent<LegacyGeneralRegion> {
/**
* Constructor.
* @param region The region that has been added
*/
public AddedRegionEvent(LegacyGeneralRegion region) {
super(region);
}
}
package me.wiefferink.areashop.events.notify;
import me.wiefferink.areashop.events.NotifyRegionEvent;
import me.wiefferink.areashop.regions.GeneralRegion;
/**
* Broadcasted when a region has been added to AreaShop.
*/
public class AddedRegionEvent extends NotifyRegionEvent<GeneralRegion> {
/**
* Constructor.
* @param region The region that has been added
*/
public AddedRegionEvent(GeneralRegion region) {
super(region);
}
}
@@ -1,18 +1,18 @@
package me.wiefferink.areashop.events.notify;
import me.wiefferink.areashop.events.NotifyRegionEvent;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
/**
* Broadcasted when a region has been removed from AreaShop.
*/
public class DeletedRegionEvent extends NotifyRegionEvent<LegacyGeneralRegion> {
/**
* Constructor.
* @param region The region that has been removed
*/
public DeletedRegionEvent(LegacyGeneralRegion region) {
super(region);
}
}
package me.wiefferink.areashop.events.notify;
import me.wiefferink.areashop.events.NotifyRegionEvent;
import me.wiefferink.areashop.regions.GeneralRegion;
/**
* Broadcasted when a region has been removed from AreaShop.
*/
public class DeletedRegionEvent extends NotifyRegionEvent<GeneralRegion> {
/**
* Constructor.
* @param region The region that has been removed
*/
public DeletedRegionEvent(GeneralRegion region) {
super(region);
}
}
@@ -1,20 +1,19 @@
package me.wiefferink.areashop.events.notify;
import me.wiefferink.areashop.events.NotifyRegionEvent;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.MarketableRegion;
/**
* Broadcasted when the data of a region changes.
* Should be used for updating displays that use region data.
*/
public class UpdateRegionEvent extends NotifyRegionEvent<MarketableRegion> {
/**
* Contructor.
* @param region The region that has been updated
*/
public UpdateRegionEvent(MarketableRegion region) {
super(region);
}
}
package me.wiefferink.areashop.events.notify;
import me.wiefferink.areashop.events.NotifyRegionEvent;
import me.wiefferink.areashop.regions.GeneralRegion;
/**
* Broadcasted when the data of a region changes.
* Should be used for updating displays that use region data.
*/
public class UpdateRegionEvent extends NotifyRegionEvent<GeneralRegion> {
/**
* Contructor.
* @param region The region that has been updated
*/
public UpdateRegionEvent(GeneralRegion region) {
super(region);
}
}
@@ -1,119 +1,118 @@
package me.wiefferink.areashop.features;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.events.ask.BuyingRegionEvent;
import me.wiefferink.areashop.events.ask.DeletingRegionEvent;
import me.wiefferink.areashop.events.ask.RentingRegionEvent;
import me.wiefferink.areashop.events.ask.ResellingRegionEvent;
import me.wiefferink.areashop.events.ask.SellingRegionEvent;
import me.wiefferink.areashop.events.ask.UnrentingRegionEvent;
import me.wiefferink.areashop.events.notify.AddedRegionEvent;
import me.wiefferink.areashop.events.notify.BoughtRegionEvent;
import me.wiefferink.areashop.events.notify.DeletedRegionEvent;
import me.wiefferink.areashop.events.notify.RentedRegionEvent;
import me.wiefferink.areashop.events.notify.ResoldRegionEvent;
import me.wiefferink.areashop.events.notify.SoldRegionEvent;
import me.wiefferink.areashop.events.notify.UnrentedRegionEvent;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.util.RegionEvent;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import java.util.List;
public class CommandsFeature extends RegionFeature {
/**
* Run command for a certain event.
* @param region Region to execute the events for
* @param event The event
* @param before The 'before' or 'after' commands
*/
public void runEventCommands(LegacyGeneralRegion region, RegionEvent event, boolean before) {
ConfigurationSection eventCommandProfileSection = region.getConfigurationSectionSetting("general.eventCommandProfile", "eventCommandProfiles");
if(eventCommandProfileSection == null) {
return;
}
List<String> commands = eventCommandProfileSection.getStringList(event.getValue() + "." + (before ? "before" : "after"));
if(commands.isEmpty()) {
return;
}
region.runCommands(Bukkit.getConsoleSender(), commands);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void addingRegion(AddingRegionEvent event) {
runEventCommands(event.getRegion(), RegionEvent.CREATED, true);
}
@EventHandler
public void addedRegion(AddedRegionEvent event) {
runEventCommands(event.getRegion(), RegionEvent.CREATED, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void deletingRegion(DeletingRegionEvent event) {
runEventCommands(event.getRegion(), RegionEvent.DELETED, true);
}
@EventHandler
public void deletedRegion(DeletedRegionEvent event) {
runEventCommands(event.getRegion(), RegionEvent.DELETED, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void rentingRegion(RentingRegionEvent event) {
// Technically the rent can still be cancelled if the payment fails...
runEventCommands(event.getRegion(), event.isExtending() ? RegionEvent.EXTENDED : RegionEvent.RENTED, true);
}
@EventHandler
public void rentedRegion(RentedRegionEvent event) {
runEventCommands(event.getRegion(), event.hasExtended() ? RegionEvent.EXTENDED : RegionEvent.RENTED, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void buyingRegion(BuyingRegionEvent event) {
// Technically the buy can still be cancelled if the payment fails...
runEventCommands(event.getRegion(), RegionEvent.BOUGHT, true);
}
@EventHandler
public void boughtRegion(BoughtRegionEvent event) {
runEventCommands(event.getRegion(), RegionEvent.BOUGHT, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void resellingRegion(ResellingRegionEvent event) {
// Technically the resell can still be cancelled if the payment fails...
runEventCommands(event.getRegion(), RegionEvent.RESELL, true);
}
@EventHandler
public void resoldRegion(ResoldRegionEvent event) {
runEventCommands(event.getRegion(), RegionEvent.RESELL, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void sellingRegion(SellingRegionEvent event) {
runEventCommands(event.getRegion(), RegionEvent.SOLD, true);
}
@EventHandler
public void soldRegion(SoldRegionEvent event) {
runEventCommands(event.getRegion(), RegionEvent.SOLD, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void unrentingRegion(UnrentingRegionEvent event) {
runEventCommands(event.getRegion(), RegionEvent.UNRENTED, true);
}
@EventHandler
public void unrentedRegion(UnrentedRegionEvent event) {
runEventCommands(event.getRegion(), RegionEvent.UNRENTED, false);
}
}
package me.wiefferink.areashop.features;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.events.ask.BuyingRegionEvent;
import me.wiefferink.areashop.events.ask.DeletingRegionEvent;
import me.wiefferink.areashop.events.ask.RentingRegionEvent;
import me.wiefferink.areashop.events.ask.ResellingRegionEvent;
import me.wiefferink.areashop.events.ask.SellingRegionEvent;
import me.wiefferink.areashop.events.ask.UnrentingRegionEvent;
import me.wiefferink.areashop.events.notify.AddedRegionEvent;
import me.wiefferink.areashop.events.notify.BoughtRegionEvent;
import me.wiefferink.areashop.events.notify.DeletedRegionEvent;
import me.wiefferink.areashop.events.notify.RentedRegionEvent;
import me.wiefferink.areashop.events.notify.ResoldRegionEvent;
import me.wiefferink.areashop.events.notify.SoldRegionEvent;
import me.wiefferink.areashop.events.notify.UnrentedRegionEvent;
import me.wiefferink.areashop.regions.GeneralRegion;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import java.util.List;
public class CommandsFeature extends RegionFeature {
/**
* Run command for a certain event.
* @param region Region to execute the events for
* @param event The event
* @param before The 'before' or 'after' commands
*/
public void runEventCommands(GeneralRegion region, GeneralRegion.RegionEvent event, boolean before) {
ConfigurationSection eventCommandProfileSection = region.getConfigurationSectionSetting("general.eventCommandProfile", "eventCommandProfiles");
if(eventCommandProfileSection == null) {
return;
}
List<String> commands = eventCommandProfileSection.getStringList(event.getValue() + "." + (before ? "before" : "after"));
if(commands == null || commands.isEmpty()) {
return;
}
region.runCommands(Bukkit.getConsoleSender(), commands);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void addingRegion(AddingRegionEvent event) {
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.CREATED, true);
}
@EventHandler
public void addedRegion(AddedRegionEvent event) {
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.CREATED, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void deletingRegion(DeletingRegionEvent event) {
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.DELETED, true);
}
@EventHandler
public void deletedRegion(DeletedRegionEvent event) {
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.DELETED, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void rentingRegion(RentingRegionEvent event) {
// Technically the rent can still be cancelled if the payment fails...
runEventCommands(event.getRegion(), event.isExtending() ? GeneralRegion.RegionEvent.EXTENDED : GeneralRegion.RegionEvent.RENTED, true);
}
@EventHandler
public void rentedRegion(RentedRegionEvent event) {
runEventCommands(event.getRegion(), event.hasExtended() ? GeneralRegion.RegionEvent.EXTENDED : GeneralRegion.RegionEvent.RENTED, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void buyingRegion(BuyingRegionEvent event) {
// Technically the buy can still be cancelled if the payment fails...
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.BOUGHT, true);
}
@EventHandler
public void boughtRegion(BoughtRegionEvent event) {
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.BOUGHT, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void resellingRegion(ResellingRegionEvent event) {
// Technically the resell can still be cancelled if the payment fails...
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.RESELL, true);
}
@EventHandler
public void resoldRegion(ResoldRegionEvent event) {
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.RESELL, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void sellingRegion(SellingRegionEvent event) {
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.SOLD, true);
}
@EventHandler
public void soldRegion(SoldRegionEvent event) {
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.SOLD, false);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void unrentingRegion(UnrentingRegionEvent event) {
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.UNRENTED, true);
}
@EventHandler
public void unrentedRegion(UnrentedRegionEvent event) {
runEventCommands(event.getRegion(), GeneralRegion.RegionEvent.UNRENTED, false);
}
}
@@ -1,98 +1,98 @@
package me.wiefferink.areashop.features;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.BuyingRegionEvent;
import me.wiefferink.areashop.events.ask.RentingRegionEvent;
import me.wiefferink.areashop.events.ask.ResellingRegionEvent;
import me.wiefferink.areashop.events.ask.SellingRegionEvent;
import me.wiefferink.areashop.events.ask.UnrentingRegionEvent;
import me.wiefferink.areashop.events.askandnotify.AddedFriendEvent;
import me.wiefferink.areashop.events.askandnotify.DeletedFriendEvent;
import me.wiefferink.areashop.events.notify.AddedRegionEvent;
import me.wiefferink.areashop.events.notify.BoughtRegionEvent;
import me.wiefferink.areashop.events.notify.DeletedRegionEvent;
import me.wiefferink.areashop.events.notify.RentedRegionEvent;
import me.wiefferink.areashop.events.notify.ResoldRegionEvent;
import me.wiefferink.areashop.events.notify.SoldRegionEvent;
import me.wiefferink.areashop.events.notify.UnrentedRegionEvent;
import me.wiefferink.areashop.events.notify.UpdateRegionEvent;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.event.EventHandler;
public class DebugFeature extends RegionFeature {
@EventHandler
public void buyingRegion(BuyingRegionEvent event) {
AreaShop.debug("BuyingRegionEvent: " + event.getPlayer().getName() + " is trying to buy " + event.getRegion().getRegionId());
}
@EventHandler
public void boughtRegion(BoughtRegionEvent event) {
AreaShop.debug("BoughtRegionEvent: " + event.getRegion().getPlayerName() + " bought " + event.getRegion().getRegionId());
}
@EventHandler
public void sellingRegion(SellingRegionEvent event) {
AreaShop.debug("SellingRegionEvent: " + event.getRegion().getRegionId() + " is trying to sell " + event.getRegion().getRegionId());
}
@EventHandler
public void soldRegion(SoldRegionEvent event) {
AreaShop.debug("SoldRegionEvent: " + Utils.toName(event.getOldBuyer()) + " sold " + event.getRegion().getRegionId());
}
@EventHandler
public void resellingRegion(ResellingRegionEvent event) {
AreaShop.debug("ResellingRegionEvent: " + event.getRegion().getRegionId() + " is trying to resell " + event.getRegion().getRegionId());
}
@EventHandler
public void resoldRegion(ResoldRegionEvent event) {
AreaShop.debug("ResoldRegionEvent: " + Utils.toName(event.getFromPlayer()) + " resold " + event.getRegion().getRegionId() + " to " + event.getRegion().getPlayerName());
}
@EventHandler
public void rentingRegion(RentingRegionEvent event) {
AreaShop.debug("RentingRegionEvent: " + event.getPlayer().getName() + " is trying to rent " + event.getRegion().getRegionId() + ", extending=" + event.isExtending());
}
@EventHandler
public void rentedRegion(RentedRegionEvent event) {
AreaShop.debug("RentedRegionEvent: " + event.getRegion().getPlayerName() + " rented " + event.getRegion().getRegionId() + ", extending=" + event.hasExtended());
}
@EventHandler
public void unrentingRegion(UnrentingRegionEvent event) {
AreaShop.debug("UnrentingRegionEvent: " + event.getRegion().getPlayerName() + " is trying to unrent " + event.getRegion().getRegionId());
}
@EventHandler
public void unrentedRegion(UnrentedRegionEvent event) {
AreaShop.debug("UnrentedRegionEvent: " + Utils.toName(event.getOldRenter()) + " unrented " + event.getRegion().getRegionId());
}
@EventHandler
public void regionUpdate(UpdateRegionEvent event) {
//AreaShop.debug("UpdateRegionEvent: " + event.getRegion().getName() + " updated");
}
@EventHandler
public void addedRegion(AddedRegionEvent event) {
AreaShop.debug("AddedRegionEvent: " + event.getRegion().getRegionId());
}
@EventHandler
public void removedRegion(DeletedRegionEvent event) {
AreaShop.debug("DeletedRegionEvent: " + event.getRegion().getRegionId());
}
@EventHandler
public void addedFriend(AddedFriendEvent event) {
AreaShop.debug("AddedFriendEvent: region " + event.getRegion().getRegionId() + ", " + event.getFriend().getName() + " by " + (event.getBy() == null ? "<nobody>" : event.getBy().getName()));
}
@EventHandler
public void deleteFriend(DeletedFriendEvent event) {
AreaShop.debug("DeletedFriendEvent: region " + event.getRegion().getRegionId() + ", " + event.getFriend().getName() + " by " + (event.getBy() == null ? "<nobody>" : event.getBy().getName()));
}
}
package me.wiefferink.areashop.features;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.BuyingRegionEvent;
import me.wiefferink.areashop.events.ask.RentingRegionEvent;
import me.wiefferink.areashop.events.ask.ResellingRegionEvent;
import me.wiefferink.areashop.events.ask.SellingRegionEvent;
import me.wiefferink.areashop.events.ask.UnrentingRegionEvent;
import me.wiefferink.areashop.events.askandnotify.AddedFriendEvent;
import me.wiefferink.areashop.events.askandnotify.DeletedFriendEvent;
import me.wiefferink.areashop.events.notify.AddedRegionEvent;
import me.wiefferink.areashop.events.notify.BoughtRegionEvent;
import me.wiefferink.areashop.events.notify.DeletedRegionEvent;
import me.wiefferink.areashop.events.notify.RentedRegionEvent;
import me.wiefferink.areashop.events.notify.ResoldRegionEvent;
import me.wiefferink.areashop.events.notify.SoldRegionEvent;
import me.wiefferink.areashop.events.notify.UnrentedRegionEvent;
import me.wiefferink.areashop.events.notify.UpdateRegionEvent;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.event.EventHandler;
public class DebugFeature extends RegionFeature {
@EventHandler
public void buyingRegion(BuyingRegionEvent event) {
AreaShop.debug("BuyingRegionEvent: " + event.getPlayer().getName() + " is trying to buy " + event.getRegion().getName());
}
@EventHandler
public void boughtRegion(BoughtRegionEvent event) {
AreaShop.debug("BoughtRegionEvent: " + event.getRegion().getPlayerName() + " bought " + event.getRegion().getName());
}
@EventHandler
public void sellingRegion(SellingRegionEvent event) {
AreaShop.debug("SellingRegionEvent: " + event.getRegion().getName() + " is trying to sell " + event.getRegion().getName());
}
@EventHandler
public void soldRegion(SoldRegionEvent event) {
AreaShop.debug("SoldRegionEvent: " + Utils.toName(event.getOldBuyer()) + " sold " + event.getRegion().getName());
}
@EventHandler
public void resellingRegion(ResellingRegionEvent event) {
AreaShop.debug("ResellingRegionEvent: " + event.getRegion().getName() + " is trying to resell " + event.getRegion().getName());
}
@EventHandler
public void resoldRegion(ResoldRegionEvent event) {
AreaShop.debug("ResoldRegionEvent: " + Utils.toName(event.getFromPlayer()) + " resold " + event.getRegion().getName() + " to " + event.getRegion().getPlayerName());
}
@EventHandler
public void rentingRegion(RentingRegionEvent event) {
AreaShop.debug("RentingRegionEvent: " + event.getPlayer().getName() + " is trying to rent " + event.getRegion().getName() + ", extending=" + event.isExtending());
}
@EventHandler
public void rentedRegion(RentedRegionEvent event) {
AreaShop.debug("RentedRegionEvent: " + event.getRegion().getPlayerName() + " rented " + event.getRegion().getName() + ", extending=" + event.hasExtended());
}
@EventHandler
public void unrentingRegion(UnrentingRegionEvent event) {
AreaShop.debug("UnrentingRegionEvent: " + event.getRegion().getPlayerName() + " is trying to unrent " + event.getRegion().getName());
}
@EventHandler
public void unrentedRegion(UnrentedRegionEvent event) {
AreaShop.debug("UnrentedRegionEvent: " + Utils.toName(event.getOldRenter()) + " unrented " + event.getRegion().getName());
}
@EventHandler
public void regionUpdate(UpdateRegionEvent event) {
//AreaShop.debug("UpdateRegionEvent: " + event.getRegion().getName() + " updated");
}
@EventHandler
public void addedRegion(AddedRegionEvent event) {
AreaShop.debug("AddedRegionEvent: " + event.getRegion().getName());
}
@EventHandler
public void removedRegion(DeletedRegionEvent event) {
AreaShop.debug("DeletedRegionEvent: " + event.getRegion().getName());
}
@EventHandler
public void addedFriend(AddedFriendEvent event) {
AreaShop.debug("AddedFriendEvent: region " + event.getRegion().getName() + ", " + event.getFriend().getName() + " by " + (event.getBy() == null ? "<nobody>" : event.getBy().getName()));
}
@EventHandler
public void deleteFriend(DeletedFriendEvent event) {
AreaShop.debug("DeletedFriendEvent: region " + event.getRegion().getName() + ", " + event.getFriend().getName() + " by " + (event.getBy() == null ? "<nobody>" : event.getBy().getName()));
}
}
@@ -2,7 +2,7 @@ package me.wiefferink.areashop.features;
import me.wiefferink.areashop.events.askandnotify.AddedFriendEvent;
import me.wiefferink.areashop.events.askandnotify.DeletedFriendEvent;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
@@ -15,7 +15,7 @@ import java.util.UUID;
public class FriendsFeature extends RegionFeature {
public FriendsFeature(LegacyGeneralRegion region) {
public FriendsFeature(GeneralRegion region) {
setRegion(region);
}
@@ -1,7 +1,7 @@
package me.wiefferink.areashop.features;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
@@ -31,13 +31,13 @@ public abstract class RegionFeature implements Listener {
public static final AreaShop plugin = AreaShop.getInstance();
protected YamlConfiguration config = plugin.getConfig();
private LegacyGeneralRegion region;
private GeneralRegion region;
/**
* Set the region for this feature.
* @param region Feature region
*/
public void setRegion(LegacyGeneralRegion region) {
public void setRegion(GeneralRegion region) {
this.region = region;
}
@@ -45,7 +45,7 @@ public abstract class RegionFeature implements Listener {
* Get the region of this feature.
* @return region of this feature, or null if generic
*/
public LegacyGeneralRegion getRegion() {
public GeneralRegion getRegion() {
return region;
}
@@ -8,8 +8,7 @@ import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.notify.UpdateRegionEvent;
import me.wiefferink.areashop.interfaces.RegionAccessSet;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.util.RegionStatus;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.interactivemessenger.processing.Message;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.EventHandler;
@@ -31,7 +30,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
* @param region The region to update the flags for
* @return true if the flags have been set correctly, otherwise false
*/
private boolean updateRegionFlags(LegacyGeneralRegion region) {
private boolean updateRegionFlags(GeneralRegion region) {
boolean result = true;
// Get section defining the region flag profile
@@ -50,7 +49,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
ConfigurationSection stateFlags = flagProfileSection.getConfigurationSection(region.getState().getValue());
// If in reselling mode, fallback to 'resale' section if 'resell' is not found (legacy configuration problem: https://github.com/NLthijs48/AreaShop/issues/303)
if(stateFlags == null && region.getState() == RegionStatus.RESELL) {
if(stateFlags == null && region.getState() == GeneralRegion.RegionState.RESELL) {
stateFlags = flagProfileSection.getConfigurationSection("resale");
}
if(stateFlags != null) {
@@ -66,7 +65,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
* @param flags The flags to apply
* @return true if the flags have been set correctly, otherwise false
*/
private boolean updateRegionFlags(LegacyGeneralRegion region, ConfigurationSection flags) {
private boolean updateRegionFlags(GeneralRegion region, ConfigurationSection flags) {
boolean result = true;
Set<String> flagNames = flags.getKeys(false);
@@ -75,7 +74,7 @@ public class WorldGuardRegionFlagsFeature extends RegionFeature {
// Get the region
ProtectedRegion worldguardRegion = region.getRegion();
if(worldguardRegion == null) {
AreaShop.debug("Region '" + region.getRegionId() + "' does not exist, setting flags failed");
AreaShop.debug("Region '" + region.getName() + "' does not exist, setting flags failed");
return false;
}
// Loop through all flags that are set in the config
@@ -4,15 +4,15 @@ import com.google.common.base.Objects;
import io.papermc.lib.PaperLib;
import io.papermc.lib.features.blockstatesnapshot.BlockStateSnapshotResult;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.interfaces.BlockBehaviourHelper;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.util.ClickType;
import me.wiefferink.areashop.managers.SignErrorLogger;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Materials;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.interactivemessenger.processing.Message;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Tag;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
@@ -25,50 +25,12 @@ import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
/**
* Sign that is connected to a region to display information and interact with the region.
*/
public class RegionSign {
public static final BlockBehaviourHelper behaviourHelper = AreaShop.getInstance().getNMSHelper().behaviourHelper();
public static Level invalidSignLogLevel;
public static boolean removeInvalidSigns;
static {
YamlConfiguration configuration = AreaShop.getInstance().getConfig();
removeInvalidSigns = configuration.getBoolean("signs.removeInvalid");
final String rawLogLevel = configuration.getString("signs.invalidSignLogLevel", "WARNING");
try {
assert rawLogLevel != null;
invalidSignLogLevel = Level.parse(rawLogLevel);
} catch (IllegalArgumentException ex) {
AreaShop.warn("Invalid Logging Level: " + rawLogLevel);
invalidSignLogLevel = Level.WARNING;
}
}
private static boolean canLogSignError() {
return AreaShop.getInstance().getLogger().isLoggable(invalidSignLogLevel);
}
private static void logSignError(String... messages) {
if (invalidSignLogLevel == Level.OFF) {
return;
}
if (invalidSignLogLevel == Level.SEVERE) {
AreaShop.error((Object) messages);
} else if (invalidSignLogLevel == Level.WARNING) {
AreaShop.warn((Object) messages);
} else if (invalidSignLogLevel.intValue() >= Level.FINE.intValue()) {
AreaShop.debug((Object) messages);
} else {
AreaShop.info((Object) messages);
}
}
private final SignsFeature signsFeature;
private final String key;
@@ -109,7 +71,7 @@ public class RegionSign {
*
* @return The region this sign is linked to
*/
public LegacyGeneralRegion getRegion() {
public GeneralRegion getRegion() {
return signsFeature.getRegion();
}
@@ -117,11 +79,7 @@ public class RegionSign {
* Remove this sign from the region.
*/
public void remove() {
final Block block = getLocation().getBlock();
if (block.getType() == getMaterial()) {
// If removing a valid sign, replace with air, otherwise ignore.
block.setType(Material.AIR);
}
getLocation().getBlock().setType(Material.AIR);
signsFeature.getSignsRef().remove(getStringLocation());
SignsFeature.getAllSigns().remove(getStringLocation());
SignsFeature.getSignsByChunk().get(getStringChunk()).remove(this);
@@ -153,7 +111,7 @@ public class RegionSign {
/**
* Get the material of the sign as saved in the config.
*
* @return Material of the sign, usually, a sign or {@link Material#AIR} if none.
* @return Material of the sign, usually or one of the other wood types (different result for 1.13-), Material.AIR if none.
*/
public Material getMaterial() {
String name = getRegion().getConfig().getString("general.signs." + key + ".signType");
@@ -176,7 +134,7 @@ public class RegionSign {
return false;
}
final LegacyGeneralRegion region = getRegion();
final GeneralRegion region = getRegion();
if (region.isDeleted()) {
return false;
@@ -205,43 +163,31 @@ public class RegionSign {
return true;
}
final BlockStateSnapshotResult snapshot = PaperLib.getBlockState(block, true);
final BlockStateSnapshotResult snapshot = PaperLib.getBlockState(block, false);
final BlockState blockState = snapshot.getState();
final BlockData blockData = blockState.getBlockData();
final SignErrorLogger errorLogger = AreaShop.getInstance().getSignErrorLogger();
Material signType = getMaterial();
// Place the sign back (with proper rotation and type) after it has been hidden or (indirectly) destroyed
if (!Materials.isSign(block.getType())) {
Material signType = getMaterial();
if (Materials.isSign(signType)) {
// Don't do physics here, we first need to update the direction
blockState.setType(signType);
if (blockData instanceof WallSign) {
((WallSign) blockData).setFacing(getFacing());
} else if (blockData instanceof Sign) {
((org.bukkit.block.data.type.Sign) blockData).setRotation(getFacing());
}
if (behaviourHelper.canPlace(block.getLocation(), blockData)) {
blockState.setBlockData(blockData);
// Update the block if its valid but don't apply physics
blockState.update(true, false);
} else {
if (canLogSignError()) {
logSignError("Setting sign", key, "of region", region.getRegionId(), "failed, could not set sign block back");
}
if (removeInvalidSigns) {
remove();
}
return false;
}
} else {
if (canLogSignError()) {
logSignError("Setting sign", key, "of region", region.getRegionId(), "failed, RegionSign material was: " + signType.name());
}
if (removeInvalidSigns) {
remove();
return false;
}
if (!Tag.SIGNS.isTagged(blockState.getType())) {
// Don't do physics here, we first need to update the direction
blockState.setType(signType);
if (blockData instanceof WallSign) {
((WallSign) blockData).setFacing(getFacing());
} else if (blockData instanceof Sign) {
((org.bukkit.block.data.type.Sign) blockData).setRotation(getFacing());
}
blockState.setBlockData(blockData);
blockState.update(false, true);
// Check if the sign has popped
if (!Materials.isSign(block.getType())) {
final String message = String.format("Setting sign of $1%s of region $2%s failed, could not set sign block back", key, region.getName());
errorLogger.submitWarning(message);
return false;
}
} else {
final String message = "Setting sign $1%s of region $2%s failed, RegionSign material was: $3%s";
errorLogger.submitWarning(String.format(message, key, region.getName(), signType.name()));
}
// Save current rotation and type
@@ -276,7 +222,8 @@ public class RegionSign {
signState.setLine(i, signLines[i]);
}
// BlockState#update *should* return true here.
return blockState.update(true, false);
blockState.update(false, false);
return true;
}
/**
@@ -312,12 +259,12 @@ public class RegionSign {
* @param clickType The type of clicking
* @return true if the commands ran successfully, false if any of them failed
*/
public boolean runSignCommands(Player clicker, ClickType clickType) {
public boolean runSignCommands(Player clicker, GeneralRegion.ClickType clickType) {
ConfigurationSection signConfig = getProfile();
if (signConfig == null) {
return false;
}
final LegacyGeneralRegion region = getRegion();
final GeneralRegion region = getRegion();
ConfigurationSection stateConfig = signConfig.getConfigurationSection(region.getState().getValue().toLowerCase());
// Run player commands if specified
@@ -345,6 +292,6 @@ public class RegionSign {
@Override
public int hashCode() {
return Objects.hashCode(key, getRegion().getRegionId());
return Objects.hashCode(key, getRegion().getName());
}
}
@@ -1,523 +0,0 @@
package me.wiefferink.areashop.features.signs;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.events.notify.UpdateRegionEvent;
import me.wiefferink.areashop.interfaces.BlockBehaviourHelper;
import me.wiefferink.areashop.managers.FileManager;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.regions.util.ClickType;
import me.wiefferink.areashop.regions.util.RegionEvent;
import me.wiefferink.areashop.regions.util.RegionType;
import me.wiefferink.areashop.tools.Materials;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Sign;
import org.bukkit.block.data.type.WallSign;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import java.util.*;
public class SignCache implements Listener {
private final Map<String, RegionSign> allSigns = new HashMap<>();
private final Map<String, List<RegionSign>> signsByChunk = new HashMap<>();
private final BlockBehaviourHelper behaviourHelper = AreaShop.getInstance().getNMSHelper().behaviourHelper();
private final AreaShop plugin = AreaShop.getInstance();
public void registerListeners() {
Bukkit.getPluginManager().registerEvents(this, AreaShop.getInstance());
}
/**
* Convert a location to a string to use as map key.
*
* @param location The location to get the key for
* @return A string to use in a map for a location
*/
public static String locationToString(Location location) {
return location.getWorld().getName() + ";" + location.getBlockX() + ";" + location.getBlockY() + ";" + location.getBlockZ();
}
/**
* Convert a chunk to a string to use as map key.
*
* @param location The location to get the key for
* @return A string to use in a map for a chunk
*/
public static String chunkToString(Location location) {
return location.getWorld().getName() + ";" + (location.getBlockX() >> 4) + ";" + (location.getBlockZ() >> 4);
}
/**
* Convert a chunk to a string to use as map key.
* Use a Location argument to prevent chunk loading!
*
* @param chunk The location to get the key for
* @return A string to use in a map for a chunk
*/
public static String chunkToString(Chunk chunk) {
return chunk.getWorld().getName() + ";" + chunk.getX() + ";" + chunk.getZ();
}
/**
* Get a sign by a location.
*
* @param location The location to get the sign for
* @return The RegionSign that is at the location, or null if none
*/
public RegionSign getSignByLocation(Location location) {
return allSigns.get(locationToString(location));
}
/**
* Get the map with all signs.
*
* @return Map with all signs: locationString -&gt; RegionSign
*/
public Map<String, RegionSign> getAllSigns() {
return allSigns;
}
/**
* Get the map with signs by chunk.
*
* @return Map with signs by chunk: chunkString -&gt; List&lt;RegionSign&gt;
*/
public Map<String, List<RegionSign>> getSignsByChunk() {
return signsByChunk;
}
public void addSign(RegionSign regionSign) {
signsByChunk.computeIfAbsent(regionSign.getStringChunk(), (unused) -> new ArrayList<>()).add(regionSign);
}
public void removeSign(RegionSign regionSign) {
final List<RegionSign> signs = signsByChunk.get(regionSign.getStringChunk());
if (signs != null) {
signs.remove(regionSign);
}
allSigns.remove(regionSign.getStringLocation());
}
public void shutdown() {
HandlerList.unregisterAll(this);
signsByChunk.clear();
allSigns.clear();
}
@EventHandler
public void regionUpdate(UpdateRegionEvent event) {
event.getRegion().getSignsFeature().update();
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onIndirectSignBreak(BlockPhysicsEvent event) {
// Check if the block is a sign
if (!Materials.isSign(event.getBlock().getType())) {
return;
}
final Block block = event.getBlock();
// Check if the sign is really the same as a saved rent
RegionSign regionSign = SignsFeature.getSignByLocation(event.getBlock().getLocation());
if (regionSign == null) {
return;
}
// If the block is in an invalid position then we remove the sign
if (!behaviourHelper.isBlockValid(block)) {
regionSign.remove();
}
// Remove the sign so that it does not fall on the floor as an item (next region update will place it back when possible)
AreaShop.debug("onIndirectSignBreak: Removed block of sign for", regionSign.getRegion().getRegionId(), "at", regionSign.getStringLocation());
event.getBlock().setType(Material.AIR);
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.MONITOR)
public void onChunkLoad(ChunkLoadEvent event) {
List<RegionSign> chunkSigns = signsByChunk.get(chunkToString(event.getChunk()));
if (chunkSigns == null) {
return;
}
int batchSize = Math.max(chunkSigns.size() / 10, 10);
Utils.runAsBatches(chunkSigns, batchSize, RegionSign::update, false);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignBreak(BlockBreakEvent event) {
Block block = event.getBlock();
// Check if it is a sign
if (Materials.isSign(block.getType())) {
// Check if the rent sign is really the same as a saved rent
RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
if (regionSign == null) {
return;
}
if (regionSign.getRegion().invalidated()) {
AreaShop.warn("SignsFeature: Sign feature for an invalidated region object is still active!");
}
// Remove the sign of the rental region if the player has permission
if (event.getPlayer().hasPermission("areashop.delsign")) {
regionSign.remove();
plugin.message(event.getPlayer(), "delsign-success", regionSign.getRegion());
} else { // Cancel the breaking of the sign
event.setCancelled(true);
plugin.message(event.getPlayer(), "delsign-noPermission", regionSign.getRegion());
}
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignClick(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
if (block == null) {
return;
}
// Only listen to left and right clicks on blocks
if (!(event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)) {
return;
}
// Only care about clicking blocks
if (!Materials.isSign(block.getType())) {
return;
}
// Check if this sign belongs to a region
RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
if (regionSign == null) {
return;
}
// Ignore players that are in sign link mode (which will handle the event itself)
Player player = event.getPlayer();
if (plugin.getSignlinkerManager().isInSignLinkMode(player)) {
return;
}
// Get the clicktype
ClickType clickType = null;
if (player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) {
clickType = ClickType.SHIFTLEFTCLICK;
} else if (!player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) {
clickType = ClickType.LEFTCLICK;
} else if (player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
clickType = ClickType.SHIFTRIGHTCLICK;
} else if (!player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
clickType = ClickType.RIGHTCLICK;
}
boolean ran = regionSign.runSignCommands(player, clickType);
// Only cancel event if at least one command has been executed
event.setCancelled(ran);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onSignChange(SignChangeEvent event) {
Player player = event.getPlayer();
if (!plugin.isReady()) {
plugin.message(player, "general-notReady");
return;
}
final BlockFace rotation;
final BlockData data = event.getBlock().getBlockData();
if (data instanceof Sign) {
rotation = ((Sign) data).getRotation();
} else if (data instanceof WallSign) {
rotation = ((WallSign) data).getFacing();
} else {
rotation = null;
}
final String line0 = event.getLine(0) == null ? "" : event.getLine(0);
// Check if the sign is meant for this plugin
if (line0.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.getRegionManager(event.getPlayer().getWorld());
// If the secondLine does not contain a name try to find the region by location
if (secondLine == null || secondLine.isEmpty()) {
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.getParent() != null && pr.getParent().equals(candidate)) {
candidate = pr;
} else {
plugin.message(player, "setup-couldNotDetect", candidate.getId(), pr.getId());
return;
}
}
}
if (candidate != null) {
secondLine = candidate.getId();
}
}
}
boolean priceSet = fourthLine != null && !fourthLine.isEmpty();
boolean durationSet = thirdLine != null && !thirdLine.isEmpty();
// check if all the lines are correct
if (secondLine == null || secondLine.isEmpty()) {
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), event.getPlayer().getWorld(), RegionType.RENT);
switch (addResult) {
case BLACKLISTED:
plugin.message(player, "setup-blacklisted", secondLine);
break;
case ALREADYADDED:
plugin.message(player, "setup-alreadyRentSign");
break;
case ALREADYADDEDOTHERWORLD:
plugin.message(player, "setup-alreadyOtherWorld");
break;
case NOPERMISSION:
plugin.message(player, "setup-noPermission", secondLine);
break;
default:
if (thirdLine != null && !thirdLine.isEmpty() && !Utils.checkTimeFormat(thirdLine)) {
plugin.message(player, "setup-wrongDuration");
break;
}
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);
}
rent.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), rotation, null);
AddingRegionEvent addingRegionEvent = plugin.getFileManager().addRegion(rent);
if (addingRegionEvent.isCancelled()) {
plugin.message(player, "general-cancelled", addingRegionEvent.getReason());
return;
}
rent.handleSchematicEvent(RegionEvent.CREATED);
plugin.message(player, "setup-rentSuccess", rent);
// Update the region after the event has written its lines
Bukkit.getScheduler().runTask(plugin, rent::update);
}
} else if (line0.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.getRegionManager(event.getPlayer().getWorld());
// If the secondLine does not contain a name try to find the region by location
if (secondLine == null || secondLine.isEmpty()) {
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.getParent() != null && pr.getParent().equals(candidate)) {
candidate = pr;
} else {
plugin.message(player, "setup-couldNotDetect", candidate.getId(), pr.getId());
return;
}
}
}
if (candidate != null) {
secondLine = candidate.getId();
}
}
}
boolean priceSet = thirdLine != null && !thirdLine.isEmpty();
// Check if all the lines are correct
if (secondLine == null || secondLine.isEmpty()) {
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, event.getPlayer().getWorld(), 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.ALREADYADDEDOTHERWORLD) {
plugin.message(player, "setup-alreadyOtherWorld");
} 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);
}
buy.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), rotation, null);
AddingRegionEvent addingRegionEvent = plugin.getFileManager().addRegion(buy);
if (addingRegionEvent.isCancelled()) {
plugin.message(player, "general-cancelled", addingRegionEvent.getReason());
return;
}
buy.handleSchematicEvent(RegionEvent.CREATED);
plugin.message(player, "setup-buySuccess", buy);
// Update the region after the event has written its lines
Bukkit.getScheduler().runTask(plugin, buy::update);
}
} 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);
LegacyGeneralRegion region;
if (secondLine != null && !secondLine.isEmpty()) {
// 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<LegacyGeneralRegion> regions = Utils.getImportantRegions(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).getRegionId(), regions.get(1).getRegionId());
return;
}
region = regions.get(0);
}
String profile = thirdLine == null || thirdLine.isEmpty() ? null : thirdLine;
region.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), rotation, profile);
if (profile == null) {
plugin.message(player, "addsign-success", region);
} else {
plugin.message(player, "addsign-successProfile", thirdLine, region);
}
// Update the region later because this event will do it first
Bukkit.getScheduler().runTask(plugin, region::update);
}
}
}
@@ -1,27 +1,44 @@
package me.wiefferink.areashop.features.signs;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.AddingRegionEvent;
import me.wiefferink.areashop.events.notify.UpdateRegionEvent;
import me.wiefferink.areashop.features.RegionFeature;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.managers.FileManager;
import me.wiefferink.areashop.managers.SignErrorLogger;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Materials;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.type.Sign;
import org.bukkit.block.data.type.WallSign;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
public class SignsFeature extends RegionFeature {
public static final SignCache signCache = new SignCache();
static {
signCache.registerListeners();
}
private static final Map<String, RegionSign> allSigns = Collections.synchronizedMap(new HashMap<>());
private static final Map<String, List<RegionSign>> signsByChunk = Collections.synchronizedMap(new HashMap<>());
private Map<String, RegionSign> signs;
@@ -34,29 +51,29 @@ public class SignsFeature extends RegionFeature {
*
* @param region The region to bind to
*/
public SignsFeature(LegacyGeneralRegion region) {
public SignsFeature(GeneralRegion region) {
setRegion(region);
signs = new HashMap<>();
// Setup current signs
ConfigurationSection signSection = region.getConfig().getConfigurationSection("general.signs");
SignErrorLogger errorLogger = AreaShop.getInstance().getSignErrorLogger();
if (signSection != null) {
for (String signKey : signSection.getKeys(false)) {
RegionSign sign = new RegionSign(this, signKey);
Location location = sign.getLocation();
if (location == null) {
AreaShop.warn("Sign with key " + signKey + " of region " + region.getRegionId() + " does not have a proper location");
final String message = "Sign with key $1%s of region $2%s does not have a proper location";
errorLogger.submitWarning(String.format(message, signKey, region.getName()));
continue;
}
signs.put(sign.getStringLocation(), sign);
signCache.addSign(sign);
signsByChunk.computeIfAbsent(sign.getStringChunk(), key -> new ArrayList<>())
.add(sign);
}
allSigns.putAll(signs);
}
}
public static void shutdownGlobalState() {
signCache.shutdown();
}
/**
* Convert a location to a string to use as map key.
*
@@ -95,7 +112,7 @@ public class SignsFeature extends RegionFeature {
* @return The RegionSign that is at the location, or null if none
*/
public static RegionSign getSignByLocation(Location location) {
return signCache.getSignByLocation(location);
return allSigns.get(locationToString(location));
}
/**
@@ -104,7 +121,7 @@ public class SignsFeature extends RegionFeature {
* @return Map with all signs: locationString -&gt; RegionSign
*/
public static Map<String, RegionSign> getAllSigns() {
return signCache.getAllSigns();
return allSigns;
}
/**
@@ -113,7 +130,7 @@ public class SignsFeature extends RegionFeature {
* @return Map with signs by chunk: chunkString -&gt; List&lt;RegionSign&gt;
*/
public static Map<String, List<RegionSign>> getSignsByChunk() {
return signCache.getSignsByChunk();
return signsByChunk;
}
@Override
@@ -121,11 +138,417 @@ public class SignsFeature extends RegionFeature {
// Deregister signs from the registry
if (signs != null) {
for (Map.Entry<String, RegionSign> entry : signs.entrySet()) {
signCache.removeSign(entry.getValue());
allSigns.remove(entry.getKey());
signsByChunk.get(entry.getValue().getStringChunk()).remove(entry.getValue());
}
}
}
@EventHandler(priority = EventPriority.HIGH)
public void onSignBreak(BlockBreakEvent event) {
if (event.isCancelled()) {
return;
}
Block block = event.getBlock();
// Check if it is a sign
if (Materials.isSign(block.getType())) {
// Check if the rent sign is really the same as a saved rent
RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
if (regionSign == null) {
return;
}
// Remove the sign of the rental region if the player has permission
if (event.getPlayer().hasPermission("areashop.delsign")) {
regionSign.remove();
plugin.message(event.getPlayer(), "delsign-success", regionSign.getRegion());
} else { // Cancel the breaking of the sign
event.setCancelled(true);
plugin.message(event.getPlayer(), "delsign-noPermission", regionSign.getRegion());
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onIndirectSignBreak(BlockPhysicsEvent event) {
// Check if the block is a sign
if (!Materials.isSign(event.getBlock().getType())) {
return;
}
final Block block = event.getBlock();
final BlockData blockData = block.getBlockData();
final Block attachedBlock;
if (blockData instanceof WallSign) {
attachedBlock = block.getRelative(((WallSign) blockData).getFacing().getOppositeFace());
} else if (blockData instanceof Sign) {
attachedBlock = block.getRelative(BlockFace.DOWN);
} else {
attachedBlock = null;
}
// Check if still attached to a block
// TODO: signs cannot be placed on all blocks, improve this check to isSolid()?
if (attachedBlock == null || attachedBlock.getType() != Material.AIR) {
return;
}
// Check if the sign is really the same as a saved rent
RegionSign regionSign = SignsFeature.getSignByLocation(event.getBlock().getLocation());
if (regionSign == null) {
return;
}
// Remove the sign so that it does not fall on the floor as an item (next region update will place it back when possible)
AreaShop.debug("onIndirectSignBreak: Removed block of sign for", regionSign.getRegion().getName(), "at", regionSign.getStringLocation());
event.getBlock().setType(Material.AIR);
event.setCancelled(true);
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onSignClick(PlayerInteractEvent event) {
Block block = event.getClickedBlock();
if (block == null) {
return;
}
// Only listen to left and right clicks on blocks
if (!(event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)) {
return;
}
// Only care about clicking blocks
if (!Materials.isSign(block.getType())) {
return;
}
// Check if this sign belongs to a region
RegionSign regionSign = SignsFeature.getSignByLocation(block.getLocation());
if (regionSign == null) {
return;
}
// Ignore players that are in sign link mode (which will handle the event itself)
Player player = event.getPlayer();
if (plugin.getSignlinkerManager().isInSignLinkMode(player)) {
return;
}
// Get the clicktype
GeneralRegion.ClickType clickType = null;
if (player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.SHIFTLEFTCLICK;
} else if (!player.isSneaking() && event.getAction() == Action.LEFT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.LEFTCLICK;
} else if (player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.SHIFTRIGHTCLICK;
} else if (!player.isSneaking() && event.getAction() == Action.RIGHT_CLICK_BLOCK) {
clickType = GeneralRegion.ClickType.RIGHTCLICK;
}
boolean ran = regionSign.runSignCommands(player, clickType);
// Only cancel event if at least one command has been executed
event.setCancelled(ran);
}
@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;
}
final BlockFace rotation;
final BlockData data = event.getBlock().getBlockData();
if (data instanceof Sign) {
rotation = ((Sign) data).getRotation();
} else if (data instanceof WallSign) {
rotation = ((WallSign) data).getFacing();
} else {
rotation = null;
}
final String line0 = event.getLine(0) == null ? "" : event.getLine(0);
// Check if the sign is meant for this plugin
if (line0.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.getRegionManager(event.getPlayer().getWorld());
// If the secondLine does not contain a name try to find the region by location
if (secondLine == null || secondLine.isEmpty()) {
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.getParent() != null && pr.getParent().equals(candidate)) {
candidate = pr;
} else {
plugin.message(player, "setup-couldNotDetect", candidate.getId(), pr.getId());
return;
}
}
}
if (candidate != null) {
secondLine = candidate.getId();
}
}
}
boolean priceSet = fourthLine != null && !fourthLine.isEmpty();
boolean durationSet = thirdLine != null && !thirdLine.isEmpty();
// check if all the lines are correct
if (secondLine == null || secondLine.isEmpty()) {
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), event.getPlayer().getWorld(), GeneralRegion.RegionType.RENT);
switch (addResult) {
case BLACKLISTED:
plugin.message(player, "setup-blacklisted", secondLine);
break;
case ALREADYADDED:
plugin.message(player, "setup-alreadyRentSign");
break;
case ALREADYADDEDOTHERWORLD:
plugin.message(player, "setup-alreadyOtherWorld");
break;
case NOPERMISSION:
plugin.message(player, "setup-noPermission", secondLine);
break;
default:
if (thirdLine != null && !thirdLine.isEmpty() && !Utils.checkTimeFormat(thirdLine)) {
plugin.message(player, "setup-wrongDuration");
break;
}
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);
}
rent.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), rotation, null);
AddingRegionEvent addingRegionEvent = plugin.getFileManager().addRegion(rent);
if (addingRegionEvent.isCancelled()) {
plugin.message(player, "general-cancelled", addingRegionEvent.getReason());
return;
}
rent.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
plugin.message(player, "setup-rentSuccess", rent);
// Update the region after the event has written its lines
Bukkit.getScheduler().runTask(plugin, rent::update);
}
} else if (line0.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.getRegionManager(event.getPlayer().getWorld());
// If the secondLine does not contain a name try to find the region by location
if (secondLine == null || secondLine.isEmpty()) {
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.getParent() != null && pr.getParent().equals(candidate)) {
candidate = pr;
} else {
plugin.message(player, "setup-couldNotDetect", candidate.getId(), pr.getId());
return;
}
}
}
if (candidate != null) {
secondLine = candidate.getId();
}
}
}
boolean priceSet = thirdLine != null && !thirdLine.isEmpty();
// Check if all the lines are correct
if (secondLine == null || secondLine.isEmpty()) {
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, event.getPlayer().getWorld(), 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.ALREADYADDEDOTHERWORLD) {
plugin.message(player, "setup-alreadyOtherWorld");
} 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);
}
buy.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), rotation, null);
AddingRegionEvent addingRegionEvent = plugin.getFileManager().addRegion(buy);
if (addingRegionEvent.isCancelled()) {
plugin.message(player, "general-cancelled", addingRegionEvent.getReason());
return;
}
buy.handleSchematicEvent(GeneralRegion.RegionEvent.CREATED);
plugin.message(player, "setup-buySuccess", buy);
// Update the region after the event has written its lines
Bukkit.getScheduler().runTask(plugin, buy::update);
}
} 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.isEmpty()) {
// 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.getImportantRegions(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);
}
String profile = thirdLine == null || thirdLine.isEmpty() ? null : thirdLine;
region.getSignsFeature().addSign(event.getBlock().getLocation(), event.getBlock().getType(), rotation, profile);
if (profile == null) {
plugin.message(player, "addsign-success", region);
} else {
plugin.message(player, "addsign-successProfile", thirdLine, region);
}
// Update the region later because this event will do it first
Bukkit.getScheduler().runTask(plugin, region::update);
}
}
@EventHandler
public void regionUpdate(UpdateRegionEvent event) {
event.getRegion().getSignsFeature().update();
}
@EventHandler(priority = EventPriority.MONITOR)
public void onChunkLoad(ChunkLoadEvent event) {
List<RegionSign> chunkSigns = signsByChunk.get(chunkToString(event.getChunk()));
if (chunkSigns == null) {
return;
}
int batchSize = Math.max(chunkSigns.size() / 10, 10);
Utils.runAsBatches(chunkSigns, batchSize, RegionSign::update, false);
}
/**
* Update all signs connected to this region.
*
@@ -198,7 +621,7 @@ public class SignsFeature extends RegionFeature {
i++;
}
String signPath = "general.signs." + i + ".";
final LegacyGeneralRegion region = getRegion();
final GeneralRegion region = getRegion();
region.setSetting(signPath + "location", Utils.locationToConfig(location));
region.setSetting(signPath + "facing", facing != null ? facing.name() : null);
region.setSetting(signPath + "signType", signType != null ? signType.name() : null);
@@ -208,7 +631,9 @@ public class SignsFeature extends RegionFeature {
// Add to the map
RegionSign sign = new RegionSign(this, String.valueOf(i));
signs.put(sign.getStringLocation(), sign);
signCache.addSign(sign);
allSigns.put(sign.getStringLocation(), sign);
signsByChunk.computeIfAbsent(sign.getStringChunk(), key -> new ArrayList<>())
.add(sign);
}
}
@@ -1,10 +1,13 @@
package me.wiefferink.areashop.features.teleport;
import co.aikar.taskchain.TaskChain;
import com.sk89q.worldedit.math.BlockVector3;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import io.papermc.lib.PaperLib;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.features.RegionFeature;
import me.wiefferink.areashop.features.signs.RegionSign;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.areashop.tools.Value;
import org.bukkit.*;
@@ -13,6 +16,7 @@ import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -23,7 +27,7 @@ public class TeleportFeature extends RegionFeature {
public TeleportFeature() {
}
public TeleportFeature(LegacyGeneralRegion region) {
public TeleportFeature(GeneralRegion region) {
setRegion(region);
}
@@ -9,7 +9,7 @@ import com.sk89q.worldguard.protection.regions.ProtectedPolygonalRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import io.papermc.lib.PaperLib;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Utils;
import me.wiefferink.areashop.tools.Value;
import org.bukkit.Bukkit;
@@ -28,7 +28,7 @@ import java.util.function.Function;
class TeleportJob {
private final AreaShop plugin;
private final LegacyGeneralRegion region;
private final GeneralRegion region;
private final TeleportFeature feature;
private BukkitTask notifierTask;
@@ -2,7 +2,7 @@ package me.wiefferink.areashop.listeners;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.entity.Player;
@@ -79,8 +79,8 @@ public final class PlayerLoginLogoutListener implements Listener {
return true;
}
List<LegacyGeneralRegion> regions = new ArrayList<>();
for (LegacyGeneralRegion region : plugin.getFileManager().getRegions()) {
List<GeneralRegion> regions = new ArrayList<>();
for (GeneralRegion region : plugin.getFileManager().getRegions()) {
if (region.isOwner(player)) {
regions.add(region);
}
@@ -118,7 +118,7 @@ public final class PlayerLoginLogoutListener implements Listener {
* @param player The player to update the active times for
*/
private void updateLastActive(Player player) {
for (LegacyGeneralRegion region : plugin.getFileManager().getRegions()) {
for (GeneralRegion region : plugin.getFileManager().getRegions()) {
if (region.isOwner(player)) {
region.updateLastActiveTime();
}
@@ -8,9 +8,7 @@ import me.wiefferink.areashop.features.RegionFeature;
import me.wiefferink.areashop.features.teleport.TeleportFeature;
import me.wiefferink.areashop.features.WorldGuardRegionFlagsFeature;
import me.wiefferink.areashop.features.signs.SignsFeature;
import me.wiefferink.areashop.interfaces.IRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import org.jetbrains.annotations.NotNull;
import me.wiefferink.areashop.regions.GeneralRegion;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
@@ -58,7 +56,7 @@ public class FeatureManager extends Manager {
regionFeatureConstructors = new HashMap<>();
for(Class<? extends RegionFeature> clazz : featureClasses) {
try {
regionFeatureConstructors.put(clazz, clazz.getConstructor(IRegion.class));
regionFeatureConstructors.put(clazz, clazz.getConstructor(GeneralRegion.class));
} catch(NoSuchMethodException | IllegalArgumentException ignored) {
// The feature does not have a region specific part
}
@@ -70,8 +68,6 @@ public class FeatureManager extends Manager {
for(RegionFeature feature : globalFeatures) {
feature.shutdown();
}
// FIXME make this system less hacky!
SignsFeature.shutdownGlobalState();
}
/**
@@ -80,9 +76,9 @@ public class FeatureManager extends Manager {
* @param featureClazz The class of the feature to create
* @return The feature class
*/
public <T extends RegionFeature> T getRegionFeature(@NotNull IRegion region, @NotNull Class<T> featureClazz) {
public RegionFeature getRegionFeature(GeneralRegion region, Class<? extends RegionFeature> featureClazz) {
try {
return featureClazz.cast(regionFeatureConstructors.get(featureClazz).newInstance(region));
return regionFeatureConstructors.get(featureClazz).newInstance(region);
} catch(InstantiationException | InvocationTargetException | IllegalAccessException | IllegalArgumentException e) {
AreaShop.error("Failed to instantiate feature", featureClazz, "for region", region, e, e.getCause());
}
@@ -10,11 +10,11 @@ import me.wiefferink.areashop.events.ask.DeletingRegionEvent;
import me.wiefferink.areashop.events.notify.AddedRegionEvent;
import me.wiefferink.areashop.events.notify.DeletedRegionEvent;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion.RegionEvent;
import me.wiefferink.areashop.regions.GeneralRegion.RegionType;
import me.wiefferink.areashop.regions.RegionGroup;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.areashop.regions.util.RegionEvent;
import me.wiefferink.areashop.regions.util.RegionType;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.*;
import org.bukkit.command.CommandSender;
@@ -30,6 +30,7 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class FileManager extends Manager {
@@ -74,7 +75,7 @@ public class FileManager extends Manager {
@Override
public void shutdown() {
// Update lastactive time for players that are online now
for (LegacyGeneralRegion region : getRegions()) {
for (GeneralRegion region : getRegions()) {
Player player = Bukkit.getPlayer(region.getOwner());
if (player != null) {
region.updateLastActiveTime();
@@ -150,8 +151,8 @@ public class FileManager extends Manager {
* @param name The name of the region to get (will be normalized)
* @return The region if found, otherwise null
*/
public LegacyGeneralRegion getRegion(String name) {
LegacyGeneralRegion region = buyRegions.get(name.toLowerCase());
public GeneralRegion getRegion(String name) {
GeneralRegion region = buyRegions.get(name.toLowerCase());
return region == null ? rentRegions.get(name.toLowerCase()) : region;
}
@@ -198,8 +199,8 @@ public class FileManager extends Manager {
*
* @return List of all regions (it is safe to modify the list)
*/
public List<LegacyGeneralRegion> getRegions() {
List<LegacyGeneralRegion> regions = new ArrayList<>(buyRegions.size() + rentRegions.size());
public List<GeneralRegion> getRegions() {
List<GeneralRegion> regions = new ArrayList<>(buyRegions.size() + rentRegions.size());
regions.addAll(buyRegions.values());
regions.addAll(rentRegions.values());
return regions;
@@ -253,7 +254,7 @@ public class FileManager extends Manager {
* @param region Then region to add
* @return true when successful, otherwise false (denied by an event listener)
*/
public AddingRegionEvent addRegion(LegacyGeneralRegion region) {
public AddingRegionEvent addRegion(GeneralRegion region) {
AddingRegionEvent event = addRegionNoSave(region);
if (event.isCancelled()) {
return event;
@@ -269,7 +270,7 @@ public class FileManager extends Manager {
* @param region The region to add
* @return true when successful, otherwise false (denied by an event listener)
*/
public AddingRegionEvent addRegionNoSave(LegacyGeneralRegion region) {
public AddingRegionEvent addRegionNoSave(GeneralRegion region) {
AddingRegionEvent event = new AddingRegionEvent(region);
if (region == null) {
AreaShop.debug("Tried adding a null region!");
@@ -280,16 +281,10 @@ public class FileManager extends Manager {
if (event.isCancelled()) {
return event;
}
final LegacyGeneralRegion existing;
if (region instanceof BuyRegion) {
existing = buyRegions.put(region.getRegionId().toLowerCase(), (BuyRegion) region);
buyRegions.put(region.getName().toLowerCase(), (BuyRegion) region);
} else if (region instanceof RentRegion) {
existing = rentRegions.put(region.getRegionId().toLowerCase(), (RentRegion) region);
} else {
existing = null;
}
if (existing != null) {
AreaShop.debug("FileManager: Region ", existing.getRegionId(), " was overwritten.");
rentRegions.put(region.getName().toLowerCase(), (RentRegion) region);
}
Bukkit.getPluginManager().callEvent(new AddedRegionEvent(region));
return event;
@@ -347,7 +342,7 @@ public class FileManager extends Manager {
|| (sender.hasPermission("areashop.create" + typeString + ".member") && isMember))) {
return AddResult.NOPERMISSION;
}
LegacyGeneralRegion asRegion = plugin.getFileManager().getRegion(region.getId());
GeneralRegion asRegion = plugin.getFileManager().getRegion(region.getId());
if (asRegion != null) {
if (asRegion.getWorld().equals(world)) {
return AddResult.ALREADYADDED;
@@ -368,7 +363,7 @@ public class FileManager extends Manager {
* @param giveMoneyBack use true to give money back to the player if someone is currently holding this region, otherwise false
* @return true if the region has been removed, false otherwise
*/
public DeletingRegionEvent deleteRegion(LegacyGeneralRegion region, boolean giveMoneyBack) {
public DeletingRegionEvent deleteRegion(GeneralRegion region, boolean giveMoneyBack) {
DeletingRegionEvent event = new DeletingRegionEvent(region);
if (region == null) {
event.cancel("null region");
@@ -463,12 +458,12 @@ public class FileManager extends Manager {
* @param regions Regions to update
* @param confirmationReceiver The CommandSender that should be notified at completion
*/
public void updateRegions(final List<LegacyGeneralRegion> regions, final CommandSender confirmationReceiver) {
public void updateRegions(final List<GeneralRegion> regions, final CommandSender confirmationReceiver) {
final int regionsPerTick = plugin.getConfig().getInt("update.regionsPerTick");
if (confirmationReceiver != null) {
plugin.message(confirmationReceiver, "reload-updateStart", regions.size(), regionsPerTick * 20);
}
CompletableFuture<?> task = Utils.runAsBatches(regions, regionsPerTick, LegacyGeneralRegion::update, false);
CompletableFuture<?> task = Utils.runAsBatches(regions, regionsPerTick, GeneralRegion::update, false);
task.thenAccept((unused) -> {
if (confirmationReceiver != null) {
plugin.message(confirmationReceiver, "reload-updateComplete");
@@ -481,7 +476,7 @@ public class FileManager extends Manager {
*
* @param regions The list of regions to update.
*/
public void updateRegions(List<LegacyGeneralRegion> regions) {
public void updateRegions(List<GeneralRegion> regions) {
updateRegions(regions, null);
}
@@ -554,7 +549,7 @@ public class FileManager extends Manager {
this.saveWorldGuardRegions();
final AtomicInteger processed = new AtomicInteger();
for (LegacyGeneralRegion region : getRegions()) {
for (GeneralRegion region : getRegions()) {
if (region.isSaveRequired()) {
region.saveNowAsync().thenAccept((unused) -> processed.getAndIncrement());
}
@@ -581,7 +576,7 @@ public class FileManager extends Manager {
if (isSaveGroupsRequired()) {
saveGroupsNow();
}
for (LegacyGeneralRegion region : getRegions()) {
for (GeneralRegion region : getRegions()) {
if (region.isSaveRequired()) {
region.saveNow();
}
@@ -663,7 +658,7 @@ public class FileManager extends Manager {
if (checksPerTick < 1) {
checksPerTick = Math.min(getRegions().size() / 10, 10);
}
Utils.runAsBatches(getRegions(), checksPerTick, LegacyGeneralRegion::checkInactive, false);
Utils.runAsBatches(getRegions(), checksPerTick, GeneralRegion::checkInactive, false);
}
/**
@@ -859,9 +854,7 @@ public class FileManager extends Manager {
* Load all region files.
*/
public void loadRegionFiles() {
buyRegions.values().forEach(LegacyGeneralRegion::invalidate);
buyRegions.clear();
rentRegions.values().forEach(LegacyGeneralRegion::invalidate);
rentRegions.clear();
final File file = new File(regionsPath);
if (!file.exists()) {
@@ -885,9 +878,9 @@ public class FileManager extends Manager {
List<String> noRegionType = new ArrayList<>();
List<String> noNamePaths = new ArrayList<>();
List<LegacyGeneralRegion> noWorld = new ArrayList<>();
List<LegacyGeneralRegion> noRegion = new ArrayList<>();
List<LegacyGeneralRegion> incorrectDuration = new ArrayList<>();
List<GeneralRegion> noWorld = new ArrayList<>();
List<GeneralRegion> noRegion = new ArrayList<>();
List<GeneralRegion> incorrectDuration = new ArrayList<>();
for (File regionFile : regionFiles) {
if (regionFile.exists() && regionFile.isFile() && !regionFile.isHidden()) {
@@ -907,7 +900,7 @@ public class FileManager extends Manager {
// Construct the correct type of region
String type = regionConfig.getString("general.type");
LegacyGeneralRegion region;
GeneralRegion region;
if (RegionType.RENT.getValue().equals(type)) {
region = new RentRegion(regionConfig);
} else if (RegionType.BUY.getValue().equals(type)) {
@@ -919,7 +912,7 @@ public class FileManager extends Manager {
// Check consistency
boolean added = false;
if (region.getRegionId() == null) {
if (region.getName() == null) {
noNamePaths.add(regionFile.getPath());
} else if (region.getWorld() == null) {
noWorld.add(region);
@@ -948,8 +941,8 @@ public class FileManager extends Manager {
if (!noRegion.isEmpty()) {
List<String> noRegionNames = new ArrayList<>();
for (LegacyGeneralRegion region : noRegion) {
noRegionNames.add(region.getRegionId());
for (GeneralRegion region : noRegion) {
noRegionNames.add(region.getName());
}
AreaShop.warn("AreaShop regions that are missing their WorldGuard region: " + Utils.createCommaSeparatedList(noRegionNames));
AreaShop.warn("Remove these regions from AreaShop with '/as del' or recreate their regions in WorldGuard.");
@@ -957,7 +950,7 @@ public class FileManager extends Manager {
boolean noWorldRegions = !noWorld.isEmpty();
while (!noWorld.isEmpty()) {
List<LegacyGeneralRegion> toDisplay = new ArrayList<>();
List<GeneralRegion> toDisplay = new ArrayList<>();
String missingWorld = noWorld.get(0).getWorldName();
toDisplay.add(noWorld.get(0));
for (int i = 1; i < noWorld.size(); i++) {
@@ -966,8 +959,8 @@ public class FileManager extends Manager {
}
}
List<String> noWorldNames = new ArrayList<>();
for (LegacyGeneralRegion region : toDisplay) {
noWorldNames.add(region.getRegionId());
for (GeneralRegion region : toDisplay) {
noWorldNames.add(region.getName());
}
AreaShop.warn("World " + missingWorld + " is not loaded, the following AreaShop regions are not functional now: " + Utils.createCommaSeparatedList(noWorldNames));
noWorld.removeAll(toDisplay);
@@ -978,8 +971,8 @@ public class FileManager extends Manager {
if (!incorrectDuration.isEmpty()) {
List<String> incorrectDurationNames = new ArrayList<>();
for (LegacyGeneralRegion region : incorrectDuration) {
incorrectDurationNames.add(region.getRegionId());
for (GeneralRegion region : incorrectDuration) {
incorrectDurationNames.add(region.getName());
}
AreaShop.warn("The following regions have an incorrect time format as duration: " + Utils.createCommaSeparatedList(incorrectDurationNames));
}
@@ -1285,7 +1278,7 @@ public class FileManager extends Manager {
// Add 'general.lastActive' to rented/bought regions (initialize at current time)
if (fileStatus == null || fileStatus < 3) {
for (LegacyGeneralRegion region : getRegions()) {
for (GeneralRegion region : getRegions()) {
region.updateLastActiveTime();
}
// Update versions file to 3
@@ -0,0 +1,79 @@
package me.wiefferink.areashop.managers;
import me.wiefferink.areashop.AreaShop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicBoolean;
public class SignErrorLogger {
public static final String PREFIX_WARN = "[Warning] [Sign Feature] ";
public static final DateFormat FORMAT = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
private final List<String> cache = new LinkedList<>();
private final AtomicBoolean needsSaving = new AtomicBoolean(false);
private final File file;
public SignErrorLogger(File file) {
this.file = Objects.requireNonNull(file);
}
public void clearCache() {
synchronized (this.cache) {
this.cache.clear();
}
}
public SignErrorLogger submitWarning(String message) {
final String actual = FORMAT.format(Date.from(Instant.now())) + PREFIX_WARN + message;
synchronized (this.cache) {
this.cache.add(actual);
}
return this;
}
public void queueSave() {
this.needsSaving.set(true);
}
public void saveIfDirty() {
if (this.needsSaving.get()) {
save();
}
}
public synchronized void save() {
AreaShop.debugTask("[Sign Feature] Dumping sign errors to disk...");
final String[] copy;
synchronized (this.cache) {
copy = cache.toArray(new String[0]);
}
final StringJoiner joiner = new StringJoiner(System.lineSeparator());
for (String s : copy) {
joiner.add(s);
}
try (OutputStream os = new FileOutputStream(file);
OutputStreamWriter writer = new OutputStreamWriter(os, StandardCharsets.UTF_8)) {
writer.write(joiner.toString());
} catch (IOException ex) {
ex.printStackTrace();
AreaShop.error("Failed to update the sign error log!");
} finally {
AreaShop.debugTask("[Sign Feature] Error dump complete.");
}
}
}
@@ -2,7 +2,7 @@ package me.wiefferink.areashop.managers;
import me.wiefferink.areashop.features.signs.RegionSign;
import me.wiefferink.areashop.features.signs.SignsFeature;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.tools.Materials;
import me.wiefferink.areashop.tools.Utils;
import org.bukkit.Bukkit;
@@ -110,14 +110,14 @@ public class SignLinkerManager extends Manager implements Listener {
BlockIterator blockIterator = new BlockIterator(player, 100);
while(blockIterator.hasNext()) {
Block next = blockIterator.next();
List<LegacyGeneralRegion> regions = Utils.getRegions(next.getLocation());
List<GeneralRegion> regions = Utils.getRegions(next.getLocation());
if(regions.size() == 1) {
linker.setRegion(regions.get(0));
return;
} else if(regions.size() > 1) {
Set<String> names = new HashSet<>();
for(LegacyGeneralRegion region : regions) {
names.add(region.getRegionId());
for(GeneralRegion region : regions) {
names.add(region.getName());
}
plugin.message(player, "linksigns-multipleRegions", Utils.createCommaSeparatedList(names));
plugin.message(player, "linksigns-multipleRegionsAdvice");
@@ -178,7 +178,7 @@ public class SignLinkerManager extends Manager implements Listener {
public final Player linker;
public final String profile;
public LegacyGeneralRegion region = null;
public GeneralRegion region = null;
public Location location = null;
public Material type = null;
@@ -189,7 +189,7 @@ public class SignLinkerManager extends Manager implements Listener {
this.profile = profile;
}
public void setRegion(LegacyGeneralRegion region) {
public void setRegion(GeneralRegion region) {
this.region = region;
hasRegion = true;
if(!isComplete()) {
@@ -1,15 +0,0 @@
package me.wiefferink.areashop.module;
import me.wiefferink.areashop.interfaces.IRegion;
import me.wiefferink.areashop.regions.util.RegionFeatureHelper;
import org.jetbrains.annotations.NotNull;
import java.util.concurrent.locks.ReadWriteLock;
public interface RegionFactory {
@NotNull RegionFeatureHelper createFeatureHelper(@NotNull IRegion region, @NotNull ReadWriteLock readWriteLock);
@NotNull RegionFeatureHelper createFeatureHelper(@NotNull IRegion region);
}
File diff suppressed because it is too large. Load diff
@@ -1,352 +0,0 @@
package me.wiefferink.areashop.regions;
import me.wiefferink.areashop.regions.util.RegionStatus;
import me.wiefferink.areashop.regions.util.RegionType;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class AbstractRegionMeta implements RegionMeta {
private static final String KEY_REGION_ID = "name";
private static final String KEY_RESTORE = "enableRestore";
private static final String KEY_SCHEMATIC_PROFILE = "schematicProfile";
//private static final String KEY_LAST_ACTIVE = "lastActive";
private static final String KEY_WORLD_NAME = "world";
private static final String KEY_LANDLORD = "landlord";
private static final String KEY_LANDLORD_NAME = "landlordName";
private static final String KEY_COUNT_FOR_LIMITS = "countForLimits";
protected transient final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private @NotNull String regionId;
private @NotNull String world;
private @Nullable String schematicProfile;
private @NotNull RegionStatus regionStatus;
private @Nullable UUID landlord;
private @Nullable String lastKnownLandlordName;
private boolean restoreEnabled;
private boolean restrictedToRegion;
private boolean restrictedToWorld;
private boolean countForLimits;
protected AbstractRegionMeta(@NotNull ConfigurationSection configurationSection) {
load0(configurationSection);
}
protected AbstractRegionMeta(@NotNull String regionId,
@NotNull String world,
@Nullable String schematicProfile,
@NotNull RegionType regionType,
@NotNull RegionStatus regionStatus,
boolean restoreEnabled,
boolean restrictedToRegion,
boolean restrictedToWorld) {
this.regionId = Objects.requireNonNull(regionId);
this.world = Objects.requireNonNull(world);
this.schematicProfile = Objects.requireNonNull(schematicProfile);
this.regionStatus = Objects.requireNonNull(regionStatus);
this.restoreEnabled = restoreEnabled;
this.restrictedToRegion = restrictedToRegion;
this.restrictedToWorld = restrictedToWorld;
}
private void load0(@NotNull ConfigurationSection section) {
this.regionId = Objects.requireNonNull(section.getString(KEY_REGION_ID));
this.world = Objects.requireNonNull(section.getString(KEY_WORLD_NAME));
this.schematicProfile = section.getString(KEY_SCHEMATIC_PROFILE);
}
@Override
public void load(@NotNull ConfigurationSection section) {
lockWrite();
try {
load0(section);
} finally {
unlockWrite();
}
}
@Override
public void removeLandlord() {
lockWrite();
try {
this.landlord = null;
this.lastKnownLandlordName = null;
} finally {
unlockWrite();
}
}
@Override
public void landlord(@NotNull UUID landlord, @NotNull String lastKnownName) {
lockWrite();
try {
this.landlord = Objects.requireNonNull(landlord);
this.lastKnownLandlordName = Objects.requireNonNull(lastKnownName);
} finally {
unlockWrite();
}
}
@Override
public @NotNull Optional<@NotNull UUID> landlord() {
return Optional.ofNullable(this.landlord);
}
@Override
public @NotNull Optional<@NotNull String> landlordLastKnownName() {
lockWrite();
try {
return Optional.ofNullable(this.lastKnownLandlordName);
} finally {
unlockWrite();
}
}
@Override
public @NotNull String regionId() {
lockRead();
try {
return this.regionId;
} finally {
unlockRead();
}
}
@Override
public @NotNull String worldName() {
lockRead();
try {
return this.world;
} finally {
unlockRead();
}
}
@Override
public @NotNull Optional<@NotNull String> schematicProfile() {
lockRead();
try {
return Optional.ofNullable(this.schematicProfile);
} finally {
unlockRead();
}
}
@Override
public @NotNull RegionStatus status() {
lockRead();
try {
return this.regionStatus;
} finally {
unlockRead();
}
}
@Override
public boolean restoreEnabled() {
lockRead();
try {
return this.restoreEnabled;
} finally {
unlockRead();
}
}
@Override
public boolean restrictedToRegion() {
lockRead();
try {
return this.restrictedToRegion;
} finally {
unlockRead();
}
}
@Override
public boolean restrictedToWorld() {
lockRead();
try {
return this.restrictedToWorld || restrictedToRegion();
} finally {
unlockRead();
}
}
@Override
public void regionId(@NotNull String regionId) {
lockWrite();
try {
this.regionId = Objects.requireNonNull(regionId);
} finally {
unlockWrite();
}
}
@Override
public void world(@NotNull World world) {
lockWrite();
try {
this.world = world.getName();
} finally {
unlockWrite();
}
}
@Override
public void world(@NotNull String world) {
lockWrite();
try {
this.world = Objects.requireNonNull(world);
} finally {
unlockWrite();
}
}
@Override
public void schematicProfile(@Nullable String schematicProfile) {
lockWrite();
try {
this.schematicProfile = schematicProfile;
} finally {
unlockWrite();
}
}
@Override
public void status(@NotNull RegionStatus regionStatus) {
lockWrite();
try {
this.regionStatus = regionStatus;
} finally {
unlockWrite();
}
}
@Override
public void restoreEnabled(boolean restoreEnabled) {
lockWrite();
try {
this.restoreEnabled = restoreEnabled;
} finally {
unlockWrite();
}
}
@Override
public void restrictedToRegion(boolean restrictedToRegion) {
lockWrite();
try {
this.restrictedToRegion = restrictedToRegion;
} finally {
unlockWrite();
}
}
@Override
public void restrictedToWorld(boolean restrictedToWorld) {
lockWrite();
try {
this.restrictedToWorld = restrictedToWorld;
} finally {
unlockWrite();
}
}
@Override
public boolean countForLimits() {
lockRead();
try {
return this.countForLimits;
} finally {
unlockRead();
}
}
@Override
public void countForLimits(boolean countForLimits) {
lockWrite();
try {
this.countForLimits = countForLimits;
} finally {
unlockWrite();
}
}
@Override
public void saveTo(@NotNull ConfigurationSection section) {
section.set(KEY_REGION_ID, this.regionId);
section.set(KEY_RESTORE, this.restoreEnabled);
section.set(KEY_SCHEMATIC_PROFILE, this.schematicProfile);
section.set(KEY_WORLD_NAME, this.world);
section.set(KEY_LANDLORD, this.landlord);
section.set(KEY_LANDLORD_NAME, this.lastKnownLandlordName);
section.set(KEY_COUNT_FOR_LIMITS, this.countForLimits);
}
protected final void lockRead() {
this.readWriteLock.readLock().lock();
}
protected final void unlockRead() {
this.readWriteLock.readLock().unlock();
}
protected final void lockWrite() {
this.readWriteLock.writeLock().lock();
}
protected final void unlockWrite() {
this.readWriteLock.writeLock().unlock();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractRegionMeta that = (AbstractRegionMeta) o;
if (restoreEnabled != that.restoreEnabled) return false;
if (restrictedToRegion != that.restrictedToRegion) return false;
if (restrictedToWorld != that.restrictedToWorld) return false;
if (countForLimits != that.countForLimits) return false;
if (!regionId.equals(that.regionId)) return false;
if (!world.equals(that.world)) return false;
if (!Objects.equals(schematicProfile, that.schematicProfile))
return false;
if (regionStatus != that.regionStatus) return false;
if (!Objects.equals(landlord, that.landlord)) return false;
return Objects.equals(lastKnownLandlordName, that.lastKnownLandlordName);
}
@Override
public int hashCode() {
int result = regionId.hashCode();
result = 31 * result + world.hashCode();
result = 31 * result + (schematicProfile != null ? schematicProfile.hashCode() : 0);
result = 31 * result + regionStatus.hashCode();
result = 31 * result + (landlord != null ? landlord.hashCode() : 0);
result = 31 * result + (lastKnownLandlordName != null ? lastKnownLandlordName.hashCode() : 0);
result = 31 * result + (restoreEnabled ? 1 : 0);
result = 31 * result + (restrictedToRegion ? 1 : 0);
result = 31 * result + (restrictedToWorld ? 1 : 0);
result = 31 * result + (countForLimits ? 1 : 0);
return result;
}
}
@@ -1,7 +0,0 @@
package me.wiefferink.areashop.regions;
public interface BuyMeta extends RegionMeta {
}
@@ -1,7 +1,5 @@
package me.wiefferink.areashop.regions;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.events.ask.BuyingRegionEvent;
import me.wiefferink.areashop.events.ask.ResellingRegionEvent;
@@ -9,11 +7,6 @@ import me.wiefferink.areashop.events.ask.SellingRegionEvent;
import me.wiefferink.areashop.events.notify.BoughtRegionEvent;
import me.wiefferink.areashop.events.notify.ResoldRegionEvent;
import me.wiefferink.areashop.events.notify.SoldRegionEvent;
import me.wiefferink.areashop.handlers.worldedit.v7.WorldEditHandler;
import me.wiefferink.areashop.handlers.worldguard.v7.WorldGuardHandler;
import me.wiefferink.areashop.managers.FileManager;
import me.wiefferink.areashop.module.RegionFactory;
import me.wiefferink.areashop.regions.util.*;
import me.wiefferink.areashop.tools.Utils;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
@@ -22,30 +15,18 @@ import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.Calendar;
import java.util.UUID;
public class BuyRegion extends AbstractRegion {
public class BuyRegion extends GeneralRegion {
public static String KEY_SECTION = "buy";
public BuyRegion(YamlConfiguration config) {
super(config);
}
public static String KEY_BUYER = "buyer";
public static String KEY_BUYER_NAME = "buyerName";
public static String KEY_PRICE = "price";
public static String KEY_RESELL_MODE = "resellMode";
public static String KEY_RESELL_PRICE = "resellPrice";
public static String KEY_MONEY_BACK_PERCENTAGE = "moneyBack";
public static String KEY_INACTIVE_TIME_THRESHOLD = "inactiveTimeUntilSell";
@AssistedInject
public BuyRegion(@NotNull @Assisted YamlConfiguration config,
@NotNull RegionFactory regionFactory,
@NotNull AreaShop plugin,
@NotNull FileManager fileManager,
@NotNull WorldEditHandler worldEditHandler,
@NotNull WorldGuardHandler worldGuardHandler) {
super(config, regionFactory, plugin, fileManager, worldEditHandler, worldGuardHandler);
public BuyRegion(String name, World world) {
super(name, world);
}
@Override
@@ -54,18 +35,13 @@ public class BuyRegion extends AbstractRegion {
}
@Override
public @NotNull BuyMeta regionMeta() {
return (BuyMeta) super.regionMeta();
}
@Override
public RegionStatus status() {
public RegionState getState() {
if(isSold() && isInResellingMode()) {
return RegionStatus.RESELL;
return RegionState.RESELL;
} else if(isSold() && !isInResellingMode()) {
return RegionStatus.SOLD;
return RegionState.SOLD;
} else {
return RegionStatus.FORSALE;
return RegionState.FORSALE;
}
}
@@ -384,7 +360,7 @@ public class BuyRegion extends AbstractRegion {
EconomyResponse r = plugin.getEconomy().withdrawPlayer(offlinePlayer, getWorldName(), getResellPrice());
if(!r.transactionSuccess()) {
message(offlinePlayer, "buy-payError");
AreaShop.debug("Something went wrong with getting money from " + offlinePlayer.getName() + " while buying " + getRegionId() + ": " + r.errorMessage);
AreaShop.debug("Something went wrong with getting money from " + offlinePlayer.getName() + " while buying " + getName() + ": " + r.errorMessage);
return false;
}
r = null;
@@ -397,7 +373,7 @@ public class BuyRegion extends AbstractRegion {
r = plugin.getEconomy().depositPlayer(oldOwnerName, getWorldName(), getResellPrice());
}
if(r == null || !r.transactionSuccess()) {
AreaShop.warn("Something went wrong with paying '" + oldOwnerName + "' " + getFormattedPrice() + " for his resell of region " + getRegionId() + " to " + offlinePlayer.getName());
AreaShop.warn("Something went wrong with paying '" + oldOwnerName + "' " + getFormattedPrice() + " for his resell of region " + getName() + " to " + offlinePlayer.getName());
}
// Resell is done, disable that now
disableReselling();
@@ -446,7 +422,7 @@ public class BuyRegion extends AbstractRegion {
r = plugin.getEconomy().depositPlayer(landlordName, getWorldName(), getPrice());
}
if(r != null && !r.transactionSuccess()) {
AreaShop.warn("Something went wrong with paying '" + landlordName + "' " + getFormattedPrice() + " for his sell of region " + getRegionId() + " to " + offlinePlayer.getName());
AreaShop.warn("Something went wrong with paying '" + landlordName + "' " + getFormattedPrice() + " for his sell of region " + getName() + " to " + offlinePlayer.getName());
}
}
@@ -542,7 +518,7 @@ public class BuyRegion extends AbstractRegion {
error = true;
}
if(error || response == null || !response.transactionSuccess()) {
AreaShop.warn("Something went wrong with paying back money to " + getPlayerName() + " while selling region " + getRegionId());
AreaShop.warn("Something went wrong with paying back money to " + getPlayerName() + " while selling region " + getName());
}
}
}
@@ -578,7 +554,7 @@ public class BuyRegion extends AbstractRegion {
long now = System.currentTimeMillis();
//AreaShop.debug("currentTime=" + Calendar.getInstance().getTimeInMillis() + ", getLastPlayed()=" + lastPlayed + ", timeInactive=" + (Calendar.getInstance().getTimeInMillis()-player.getLastPlayed()) + ", inactiveSetting=" + inactiveSetting);
if(now > (lastPlayed + inactiveSetting)) {
AreaShop.info("Region " + getRegionId() + " unrented because of inactivity for player " + getPlayerName());
AreaShop.info("Region " + getName() + " unrented because of inactivity for player " + getPlayerName());
AreaShop.debug("currentTime=" + now + ", getLastPlayed()=" + lastPlayed + ", timeInactive=" + (now - player.getLastPlayed()) + ", inactiveSetting=" + inactiveSetting);
return this.sell(true, null);
}
@@ -1,6 +0,0 @@
package me.wiefferink.areashop.regions;
public class BuyRegionMetaImpl extends AbstractRegionMeta {
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,228 +0,0 @@
package me.wiefferink.areashop.regions;
import me.wiefferink.areashop.events.NotifyRegionEvent;
import me.wiefferink.areashop.interfaces.IRegion;
import me.wiefferink.areashop.regions.util.*;
import me.wiefferink.interactivemessenger.processing.ReplacementProvider;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.util.Vector;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
public interface MarketableRegion extends IRegion, Comparable<MarketableRegion>, ReplacementProvider {
/**
* Get the amount of regions a player has matching a certain limits group (config.yml -- limitGroups)
*
* @param player The player to check the amount for
* @param limitGroup The group to check
* @param regions All the regions a player has bought or rented
* @param exclude Exclude this region from the count
* @return The number of regions that the player has bought or rented matching the limit group (worlds and groups filters)
*/
static int hasRegionsInLimitGroup(OfflinePlayer player, String limitGroup, List<? extends MarketableRegion> regions, MarketableRegion exclude) {
int result = 0;
for (MarketableRegion region : regions) {
final RegionMeta meta = region.regionMeta();
if (meta.countForLimits()
// && region.isOwner(player)
&& region.matchesLimitGroup(limitGroup)
&& (exclude == null || !exclude.getRegionId().equals(region.getRegionId()))) {
result++;
}
}
return result;
}
@NotNull RegionMeta regionMeta();
@NotNull RegionFeatureHelper featureHelper();
/**
* Shared setup of all constructors.
*/
void setup();
/**
* Deregister everything.
*/
void destroy();
/**
* Broadcast an event to indicate that region settings have been changed.
* This will update region flags, signs, etc.
*/
void update();
/**
* Broadcast the given event and update the region status.
*
* @param event The update event that should be broadcasted
*/
void notifyAndUpdate(NotifyRegionEvent<?> event);
/**
* Check if the region has been deleted.
*
* @return true if the region has been deleted, otherwise false
*/
boolean isDeleted();
/**
* Indicate that this region has been deleted.
*/
void delete();
/**
* Get the minimum corner of the region.
*
* @return Vector
*/
Vector getMinimumPoint();
/**
* Get the maximum corner of the region.
*
* @return Vector
*/
Vector getMaximumPoint();
/**
* Get the groups that this region is added to.
*
* @return A Set with all groups of this region
*/
Set<RegionGroup> getGroups();
/**
* Get a list of names from groups this region is in.
*
* @return A list of groups this region is part of
*/
List<String> getGroupNames();
/**
* Method to send a message to a CommandSender, using chatprefix if it is a player.
* Automatically includes the region in the message, enabling the use of all variables.
*
* @param target The CommandSender you wan't to send the message to (e.g. a player)
* @param key The key to get the translation
* @param prefix Specify if the message should have a prefix
* @param params The parameters to inject into the message string
*/
void configurableMessage(Object target, String key, boolean prefix, Object... params);
void messageNoPrefix(Object target, String key, Object... params);
void message(Object target, String key, Object... params);
/**
* Save all blocks in a region for restoring later.
*
* @param fileName The name of the file to save to (extension and folder will be added)
* @return true if the region has been saved properly, otherwise false
*/
boolean saveRegionBlocks(String fileName);
/**
* Save all blocks in a region for restoring later.
*
* @param fileName The name of the file to save to (extension and folder will be added)
* @return true if the region has been saved properly, otherwise false
*/
CompletableFuture<Boolean> saveRegionBlocksAsync(String fileName);
/**
* Restore all blocks in a region for restoring later.
*
* @param fileName The name of the file to save to (extension and folder will be added)
* @return true if the region has been restored properly, otherwise false
*/
boolean restoreRegionBlocks(String fileName);
/**
* Restore all blocks in a region for restoring later.
*
* @param fileName The name of the file to save to (extension and folder will be added)
* @return true if the region has been restored properly, otherwise false
*/
CompletableFuture<Boolean> restoreRegionBlocksAsync(String fileName);
/**
* Reset all flags of the region.
*/
void resetRegionFlags();
/**
* Indicate this region needs to be saved, saving will happen by a repeating task.
*/
void saveRequired();
/**
* Check if a save is required.
*
* @return true if a save is required because some data changed, otherwise false
*/
boolean isSaveRequired();
/**
* Save this region to disk now, using this method could slow down the plugin, normally saveRequired() should be used.
*
* @return true if the region is saved successfully, otherwise false
*/
boolean saveNow();
CompletableFuture<Boolean> saveNowAsync();
/**
* Check if the player can buy/rent this region, detailed info in the result object.
*
* @param type The type of region to check
* @param player The player to check it for
* @return LimitResult containing if it is allowed, why and limiting factor
*/
LimitResult limitsAllow(RegionType type, OfflinePlayer player);
/**
* Check if the player can buy/rent this region, detailed info in the result object.
*
* @param type The type of region to check
* @param offlinePlayer The player to check it for
* @param extend Check for extending of rental regions
* @return LimitResult containing if it is allowed, why and limiting factor
*/
LimitResult limitsAllow(RegionType type, OfflinePlayer offlinePlayer, boolean extend);
/**
* Check if this region matches the filters of a limit group.
*
* @param group The group to check
* @return true if the region applies to the limit group, otherwise false
*/
boolean matchesLimitGroup(String group);
/**
* Checks an event and handles saving to and restoring from schematic for it.
*
* @param type The type of event
*/
void handleSchematicEvent(RegionEvent type);
/**
* Run commands as the CommandsSender, replacing all tags with the relevant values.
*
* @param sender The sender that should perform the command
* @param commands A list of the commands to run (without slash and with tags)
*/
void runCommands(CommandSender sender, List<String> commands);
/**
* Get the volume of the region (number of blocks inside it).
*
* @return Number of blocks in the region
*/
long volume();
}
@@ -1,225 +1,225 @@
package me.wiefferink.areashop.regions;
import me.wiefferink.areashop.AreaShop;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
// TODO consider switching to saving lowercase regions
public class RegionGroup {
private final AreaShop plugin;
private final String name;
private final Set<String> regions;
private Set<String> autoRegions;
private boolean autoDirty;
private final Set<String> worlds;
/**
* Constructor, used when creating new groups or restoring them from groups.yml at server boot.
* @param plugin The AreaShop plugin
* @param name Name of the group, has to be unique
*/
public RegionGroup(AreaShop plugin, String name) {
this.plugin = plugin;
this.name = name;
this.autoDirty = true;
setSetting("name", name);
// Load regions and worlds
regions = new HashSet<>(getSettings().getStringList("regions"));
worlds = new HashSet<>(getSettings().getStringList("worlds"));
}
/**
* Get automatically added regions.
* @return Set of regions automatically added by the configuration
*/
public Set<String> getAutoRegions() {
if(autoDirty) {
autoRegions = new HashSet<>();
for(LegacyGeneralRegion region : plugin.getFileManager().getRegions()) {
if(worlds.contains(region.getWorldName())) {
autoRegions.add(region.getRegionId());
}
}
autoDirty = false;
}
return autoRegions;
}
/**
* Mark that automatically added regions should be regenerated.
*/
public void autoDirty() {
autoDirty = true;
}
/**
* Adds a world from which all regions should be added to the group.
* @param world World from which all regions should be added
* @return true if the region was not already added, otherwise false
*/
public boolean addWorld(String world) {
if(worlds.add(world)) {
setSetting("regionsFromWorlds", new ArrayList<>(worlds));
saveRequired();
autoDirty();
return true;
}
return false;
}
/**
* Remove a member from the group.
* @param world World to remove
* @return true if the region was in the group before, otherwise false
*/
public boolean removeWorld(String world) {
if(worlds.remove(world)) {
setSetting("regionsFromWorlds", new ArrayList<>(worlds));
saveRequired();
autoDirty();
return true;
}
return false;
}
/**
* Get all worlds from which regions are added automatically.
* @return A list with the names of all worlds (immutable)
*/
public Set<String> getWorlds() {
return new HashSet<>(worlds);
}
/**
* Adds a member to a group.
* @param region The region to add to the group (GeneralRegion or a subclass of it)
* @return true if the region was not already added, otherwise false
*/
public boolean addMember(MarketableRegion region) {
if(regions.add(region.getRegionId())) {
setSetting("regions", new ArrayList<>(regions));
saveRequired();
return true;
}
return false;
}
/**
* Remove a member from the group.
* @param region The region to remove
* @return true if the region was in the group before, otherwise false
*/
public boolean removeMember(MarketableRegion region) {
if(regions.remove(region.getRegionId())) {
setSetting("regions", new ArrayList<>(regions));
saveRequired();
return true;
}
return false;
}
/**
* Get all members of the group.
* @return A list with the names of all members of the group (immutable)
*/
public Set<String> getMembers() {
HashSet<String> result = new HashSet<>(regions);
result.addAll(getAutoRegions());
return result;
}
/**
* Get all manually added members of the group.
* @return A list with the names of all members of the group (immutable)
*/
public Set<String> getManualMembers() {
return new HashSet<>(regions);
}
/**
* Get all members of the group as GeneralRegions.
* @return A Set with all group members
*/
public Set<LegacyGeneralRegion> getMemberRegions() {
Set<LegacyGeneralRegion> result = new HashSet<>();
for(String playerName : getMembers()) {
result.add(plugin.getFileManager().getRegion(playerName));
}
return result;
}
/**
* Get the name of the group.
* @return The name of the group
*/
public String getName() {
return name;
}
/**
* Get the lowercase name of the group (used for getting the config etc).
* @return The name of the group in lowercase
*/
public String getLowerCaseName() {
return getName().toLowerCase();
}
/**
* Check if a region is member of the group.
* @param region Region to check
* @return true if the region is in the group, otherwise false
*/
public boolean isMember(LegacyGeneralRegion region) {
return getMembers().contains(region.getRegionId());
}
/**
* Get the priority of the group (higher overwrites).
* @return The priority of the group
*/
public int getPriority() {
return getSettings().getInt("priority");
}
/**
* Get the configurationsection with the settings of this group.
* @return The ConfigurationSection with the settings of the group
*/
public ConfigurationSection getSettings() {
ConfigurationSection result = plugin.getFileManager().getGroupSettings(name);
if(result != null) {
return result;
} else {
return new YamlConfiguration();
}
}
/**
* Set a setting of this group.
* @param path The path to set
* @param setting The value to set
*/
public void setSetting(String path, Object setting) {
plugin.getFileManager().setGroupSetting(this, path, setting);
}
/**
* Indicates this file needs to be saved, will actually get saved later by a task.
*/
public void saveRequired() {
plugin.getFileManager().saveGroupsIsRequired();
}
/**
* Save the groups to disk now, normally saveRequired() is preferred because of performance.
*/
public void saveNow() {
plugin.getFileManager().saveGroupsNow();
}
}
package me.wiefferink.areashop.regions;
import me.wiefferink.areashop.AreaShop;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
// TODO consider switching to saving lowercase regions
public class RegionGroup {
private final AreaShop plugin;
private final String name;
private final Set<String> regions;
private Set<String> autoRegions;
private boolean autoDirty;
private final Set<String> worlds;
/**
* Constructor, used when creating new groups or restoring them from groups.yml at server boot.
* @param plugin The AreaShop plugin
* @param name Name of the group, has to be unique
*/
public RegionGroup(AreaShop plugin, String name) {
this.plugin = plugin;
this.name = name;
this.autoDirty = true;
setSetting("name", name);
// Load regions and worlds
regions = new HashSet<>(getSettings().getStringList("regions"));
worlds = new HashSet<>(getSettings().getStringList("worlds"));
}
/**
* Get automatically added regions.
* @return Set of regions automatically added by the configuration
*/
public Set<String> getAutoRegions() {
if(autoDirty) {
autoRegions = new HashSet<>();
for(GeneralRegion region : plugin.getFileManager().getRegions()) {
if(worlds.contains(region.getWorldName())) {
autoRegions.add(region.getName());
}
}
autoDirty = false;
}
return autoRegions;
}
/**
* Mark that automatically added regions should be regenerated.
*/
public void autoDirty() {
autoDirty = true;
}
/**
* Adds a world from which all regions should be added to the group.
* @param world World from which all regions should be added
* @return true if the region was not already added, otherwise false
*/
public boolean addWorld(String world) {
if(worlds.add(world)) {
setSetting("regionsFromWorlds", new ArrayList<>(worlds));
saveRequired();
autoDirty();
return true;
}
return false;
}
/**
* Remove a member from the group.
* @param world World to remove
* @return true if the region was in the group before, otherwise false
*/
public boolean removeWorld(String world) {
if(worlds.remove(world)) {
setSetting("regionsFromWorlds", new ArrayList<>(worlds));
saveRequired();
autoDirty();
return true;
}
return false;
}
/**
* Get all worlds from which regions are added automatically.
* @return A list with the names of all worlds (immutable)
*/
public Set<String> getWorlds() {
return new HashSet<>(worlds);
}
/**
* Adds a member to a group.
* @param region The region to add to the group (GeneralRegion or a subclass of it)
* @return true if the region was not already added, otherwise false
*/
public boolean addMember(GeneralRegion region) {
if(regions.add(region.getName())) {
setSetting("regions", new ArrayList<>(regions));
saveRequired();
return true;
}
return false;
}
/**
* Remove a member from the group.
* @param region The region to remove
* @return true if the region was in the group before, otherwise false
*/
public boolean removeMember(GeneralRegion region) {
if(regions.remove(region.getName())) {
setSetting("regions", new ArrayList<>(regions));
saveRequired();
return true;
}
return false;
}
/**
* Get all members of the group.
* @return A list with the names of all members of the group (immutable)
*/
public Set<String> getMembers() {
HashSet<String> result = new HashSet<>(regions);
result.addAll(getAutoRegions());
return result;
}
/**
* Get all manually added members of the group.
* @return A list with the names of all members of the group (immutable)
*/
public Set<String> getManualMembers() {
return new HashSet<>(regions);
}
/**
* Get all members of the group as GeneralRegions.
* @return A Set with all group members
*/
public Set<GeneralRegion> getMemberRegions() {
Set<GeneralRegion> result = new HashSet<>();
for(String playerName : getMembers()) {
result.add(plugin.getFileManager().getRegion(playerName));
}
return result;
}
/**
* Get the name of the group.
* @return The name of the group
*/
public String getName() {
return name;
}
/**
* Get the lowercase name of the group (used for getting the config etc).
* @return The name of the group in lowercase
*/
public String getLowerCaseName() {
return getName().toLowerCase();
}
/**
* Check if a region is member of the group.
* @param region Region to check
* @return true if the region is in the group, otherwise false
*/
public boolean isMember(GeneralRegion region) {
return getMembers().contains(region.getName());
}
/**
* Get the priority of the group (higher overwrites).
* @return The priority of the group
*/
public int getPriority() {
return getSettings().getInt("priority");
}
/**
* Get the configurationsection with the settings of this group.
* @return The ConfigurationSection with the settings of the group
*/
public ConfigurationSection getSettings() {
ConfigurationSection result = plugin.getFileManager().getGroupSettings(name);
if(result != null) {
return result;
} else {
return new YamlConfiguration();
}
}
/**
* Set a setting of this group.
* @param path The path to set
* @param setting The value to set
*/
public void setSetting(String path, Object setting) {
plugin.getFileManager().setGroupSetting(this, path, setting);
}
/**
* Indicates this file needs to be saved, will actually get saved later by a task.
*/
public void saveRequired() {
plugin.getFileManager().saveGroupsIsRequired();
}
/**
* Save the groups to disk now, normally saveRequired() is preferred because of performance.
*/
public void saveNow() {
plugin.getFileManager().saveGroupsNow();
}
}
@@ -1,65 +0,0 @@
package me.wiefferink.areashop.regions;
import me.wiefferink.areashop.regions.util.RegionStatus;
import me.wiefferink.areashop.regions.util.RegionType;
import org.bukkit.World;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Optional;
import java.util.UUID;
public interface RegionMeta {
void load(@NotNull ConfigurationSection section);
@NotNull String regionId();
void regionId(@NotNull String regionId);
@NotNull String worldName();
@NotNull Optional<@NotNull UUID> landlord();
@NotNull Optional<@NotNull String> landlordLastKnownName();
void removeLandlord();
void landlord(@NotNull UUID landlord, @NotNull String lastKnownName);
default void landlord(@NotNull Player player) {
landlord(player.getUniqueId(), player.getName());
}
void world(@NotNull World world);
void world(@NotNull String worldName);
@NotNull Optional<@NotNull String> schematicProfile();
void schematicProfile(@Nullable String schematicProfile);
@NotNull RegionStatus status();
void status(@NotNull RegionStatus status);
boolean restoreEnabled();
void restoreEnabled(boolean enabled);
boolean restrictedToRegion();
void restrictedToRegion(boolean restricted);
boolean restrictedToWorld();
void restrictedToWorld(boolean restricted);
boolean countForLimits();
void countForLimits(boolean counts);
void saveTo(@NotNull ConfigurationSection configurationSection);
}
@@ -5,7 +5,6 @@ import me.wiefferink.areashop.events.ask.RentingRegionEvent;
import me.wiefferink.areashop.events.ask.UnrentingRegionEvent;
import me.wiefferink.areashop.events.notify.RentedRegionEvent;
import me.wiefferink.areashop.events.notify.UnrentedRegionEvent;
import me.wiefferink.areashop.regions.util.*;
import me.wiefferink.areashop.tools.Utils;
import net.milkbowl.vault.economy.EconomyResponse;
import org.bukkit.Bukkit;
@@ -24,7 +23,7 @@ import java.util.UUID;
import static me.wiefferink.areashop.tools.Utils.millisToHumanFormat;
public class RentRegion extends LegacyGeneralRegion {
public class RentRegion extends GeneralRegion {
private long warningsDoneUntil = Calendar.getInstance().getTimeInMillis();
/**
@@ -50,11 +49,11 @@ public class RentRegion extends LegacyGeneralRegion {
}
@Override
public RegionStatus getState() {
public RegionState getState() {
if(isRented()) {
return RegionStatus.RENTED;
return RegionState.RENTED;
} else {
return RegionStatus.FORRENT;
return RegionState.FORRENT;
}
}
@@ -562,7 +561,7 @@ public class RentRegion extends LegacyGeneralRegion {
EconomyResponse r = plugin.getEconomy().withdrawPlayer(offlinePlayer, getWorldName(), price);
if(!r.transactionSuccess()) {
message(offlinePlayer, "rent-payError");
AreaShop.debug("Something went wrong with getting money from " + offlinePlayer.getName() + " while renting " + getRegionId() + ": " + r.errorMessage);
AreaShop.debug("Something went wrong with getting money from " + offlinePlayer.getName() + " while renting " + getName() + ": " + r.errorMessage);
return false;
}
// Optionally give money to the landlord
@@ -578,7 +577,7 @@ public class RentRegion extends LegacyGeneralRegion {
r = plugin.getEconomy().depositPlayer(landlordName, getWorldName(), price);
}
if(r == null || !r.transactionSuccess()) {
AreaShop.warn("Something went wrong with paying '" + landlordName + "' " + Utils.formatCurrency(price) + " for his rent of region " + getRegionId() + " to " + offlinePlayer.getName());
AreaShop.warn("Something went wrong with paying '" + landlordName + "' " + Utils.formatCurrency(price) + " for his rent of region " + getName() + " to " + offlinePlayer.getName());
}
}
@@ -687,7 +686,7 @@ public class RentRegion extends LegacyGeneralRegion {
error = true;
}
if(error || r == null || !r.transactionSuccess()) {
AreaShop.warn("Something went wrong with paying back to " + getPlayerName() + " money while unrenting region " + getRegionId());
AreaShop.warn("Something went wrong with paying back to " + getPlayerName() + " money while unrenting region " + getName());
}
}
}
@@ -725,7 +724,7 @@ public class RentRegion extends LegacyGeneralRegion {
final long now = System.currentTimeMillis();
//AreaShop.debug("currentTime=" + Calendar.getInstance().getTimeInMillis() + ", getLastPlayed()=" + lastPlayed + ", timeInactive=" + (Calendar.getInstance().getTimeInMillis()-player.getLastPlayed()) + ", inactiveSetting=" + inactiveSetting);
if(now > (lastPlayed + inactiveSetting)) {
AreaShop.info("Region " + getRegionId() + " unrented because of inactivity for player " + getPlayerName());
AreaShop.info("Region " + getName() + " unrented because of inactivity for player " + getPlayerName());
AreaShop.debug("currentTime=" + now + ", getLastPlayed()=" + lastPlayed + ", timeInactive=" + (now - player.getLastPlayed()) + ", inactiveSetting=" + inactiveSetting);
return this.unRent(true, null);
}
@@ -1,19 +0,0 @@
package me.wiefferink.areashop.regions.util;
// Enum for click types
public enum ClickType {
RIGHTCLICK("rightClick"),
LEFTCLICK("leftClick"),
SHIFTRIGHTCLICK("shiftRightClick"),
SHIFTLEFTCLICK("shiftLeftClick");
private final String value;
ClickType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
@@ -1,79 +0,0 @@
package me.wiefferink.areashop.regions.util;
/**
* Class to store the result of a limits check.
*/
public class LimitResult {
private final boolean actionAllowed;
private final LimitType limitingFactor;
private final int maximum;
private final int current;
private final String limitingGroup;
/**
* Constructor.
*
* @param actionAllowed has the action been allowed?
* @param limitingFactor The LimitType that has prevented the action (if actionAllowed is false)
* @param maximum The maximum number of regions allowed (if actionAllowed is false)
* @param current The current number of regions the player has (if actionAllowed is false)
* @param limitingGroup The group that is enforcing this limit (if actionAllowed is false)
*/
public LimitResult(boolean actionAllowed, LimitType limitingFactor, int maximum, int current, String limitingGroup) {
this.actionAllowed = actionAllowed;
this.limitingFactor = limitingFactor;
this.maximum = maximum;
this.current = current;
this.limitingGroup = limitingGroup;
}
/**
* Check if the action is allowed.
*
* @return true if the actions is allowed, otherwise false
*/
public boolean actionAllowed() {
return actionAllowed;
}
/**
* Get the type of the factor that is limiting the action, assuming actionAllowed() is false.
*
* @return The type of the limiting factor
*/
public LimitType getLimitingFactor() {
return limitingFactor;
}
/**
* Get the maximum number of the group that is the limiting factor, assuming actionAllowed() is false.
*
* @return The maximum
*/
public int getMaximum() {
return maximum;
}
/**
* Get the current number of regions in the group that is the limiting factor, assuming actionAllowed() is false.
*
* @return The current number of regions the player has
*/
public int getCurrent() {
return current;
}
/**
* Get the name of the group that is limiting the action, assuming actionAllowed() is false.
*
* @return The name of the group
*/
public String getLimitingGroup() {
return limitingGroup;
}
@Override
public String toString() {
return "actionAllowed=" + actionAllowed + ", limitingFactor=" + limitingFactor + ", maximum=" + maximum + ", current=" + current + ", limitingGroup=" + limitingGroup;
}
}
@@ -1,19 +0,0 @@
package me.wiefferink.areashop.regions.util;
// Enum for limit types
public enum LimitType {
RENTS("rents"),
BUYS("buys"),
TOTAL("total"),
EXTEND("extend");
private final String value;
LimitType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
@@ -1,23 +0,0 @@
package me.wiefferink.areashop.regions.util;
// Enum for schematic event types
public enum RegionEvent {
CREATED("created"),
DELETED("deleted"),
RENTED("rented"),
EXTENDED("extended"),
UNRENTED("unrented"),
BOUGHT("bought"),
SOLD("sold"),
RESELL("resell");
private final String value;
RegionEvent(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
@@ -1,72 +0,0 @@
package me.wiefferink.areashop.regions.util;
import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.MutableClassToInstanceMap;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import me.wiefferink.areashop.features.RegionFeature;
import me.wiefferink.areashop.interfaces.IRegion;
import me.wiefferink.areashop.managers.FeatureManager;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class RegionFeatureHelper {
@Inject
private FeatureManager featureManager;
private final ReadWriteLock readWriteLock;
private final IRegion region;
private final ClassToInstanceMap<RegionFeature> features = MutableClassToInstanceMap.create();
@AssistedInject
public RegionFeatureHelper(@NotNull @Assisted IRegion region, @NotNull @Assisted ReadWriteLock readWriteLock) {
this.region = region;
this.readWriteLock = readWriteLock;
}
@AssistedInject
public RegionFeatureHelper(@NotNull @Assisted IRegion region) {
this(region, new ReentrantReadWriteLock());
}
public <T extends RegionFeature> @NotNull T feature(@NotNull Class<T> clazz) {
this.readWriteLock.writeLock().lock();
try {
if (this.features.containsKey(clazz)) {
return this.features.getInstance(clazz);
}
final T feature = featureManager.getRegionFeature(this.region, clazz);
this.features.put(clazz, feature);
return feature;
} finally {
this.readWriteLock.writeLock().unlock();
}
}
public @NotNull Collection<? extends RegionFeature> valuesCopy() {
this.readWriteLock.readLock().lock();
try {
return new HashSet<>(this.features.values());
} finally {
this.readWriteLock.readLock().unlock();
}
}
public @NotNull Collection<? extends RegionFeature> values() {
this.readWriteLock.readLock().lock();
try {
return Collections.unmodifiableCollection(this.features.values());
} finally {
this.readWriteLock.readLock().unlock();
}
}
}
@@ -1,21 +0,0 @@
package me.wiefferink.areashop.regions.util;
// Enum for Region states
public enum RegionStatus {
FORRENT("forrent"),
RENTED("rented"),
FORSALE("forsale"),
SOLD("sold"),
RESELL("resell");
private final String value;
RegionStatus(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
@@ -1,17 +0,0 @@
package me.wiefferink.areashop.regions.util;
// Enum for region types
public enum RegionType {
RENT("rent"),
BUY("buy");
private final String value;
RegionType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
@@ -2,7 +2,7 @@ package me.wiefferink.areashop.tools;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import org.bstats.Metrics;
@@ -118,7 +118,7 @@ public class Analytics {
private static RegionStateStats getStateStats() {
RegionStateStats result = new RegionStateStats();
for(LegacyGeneralRegion region : AreaShop.getInstance().getFileManager().getRegions()) {
for(GeneralRegion region : AreaShop.getInstance().getFileManager().getRegions()) {
if(region instanceof RentRegion) {
RentRegion rent = (RentRegion)region;
if(rent.isAvailable()) {
@@ -1,135 +1,132 @@
package me.wiefferink.areashop.tools;
import me.wiefferink.areashop.AreaShop;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
public class Materials {
private static final Pattern SIGN_PATTERN = Pattern.compile("(SIGN)");
private Materials() {
}
private static final HashSet<String> WALL_SIGN_TYPES = new HashSet<>(Arrays.asList(
// 1.14+ types
"ACACIA_WALL_SIGN",
"BIRCH_WALL_SIGN",
"DARK_OAK_WALL_SIGN",
"JUNGLE_WALL_SIGN",
"OAK_WALL_SIGN",
"SPRUCE_WALL_SIGN",
// Legacy types
"LEGACY_WALL_SIGN",
"WALL_SIGN"
));
private static final HashSet<String> FLOOR_SIGN_TYPES = new HashSet<>(Arrays.asList(
// 1.14+ types
"ACACIA_SIGN",
"BIRCH_SIGN",
"DARK_OAK_SIGN",
"JUNGLE_SIGN",
"OAK_SIGN",
"SPRUCE_SIGN",
// Legacy types
"LEGACY_SIGN",
"LEGACY_SIGN_POST",
"SIGN",
"SIGN_POST"
));
private static boolean legacyMaterials = false;
static {
List<String> legacyMaterialVersions = Arrays.asList("1.7", "1.8", "1.9", "1.10", "1.11", "1.12");
for(String legacyMaterialVersion : legacyMaterialVersions) {
String version = Bukkit.getBukkitVersion();
// Detects '1.8', '1.8.3', '1.8-pre1' style versions
if(version.equals(legacyMaterialVersion)
|| version.startsWith(legacyMaterialVersion + ".")
|| version.startsWith(legacyMaterialVersion + "-")) {
legacyMaterials = true;
break;
}
}
}
/**
* Get material based on a sign material name.
* @param name Name of the sign material
* @return null if not a sign, otherwise the material matching the name (when the material is not available on the current minecraft version, it returns the base type)
*/
public static Material signNameToMaterial(String name) {
// Expected null case
if (!isSign(name)) {
return null;
}
Material result = null;
if (legacyMaterials) {
// 1.12 and lower just know SIGN_POST, WALL_SIGN and SIGN
if (FLOOR_SIGN_TYPES.contains(name)) {
result = Material.getMaterial("SIGN_POST");
} else if (WALL_SIGN_TYPES.contains(name)) {
result = Material.getMaterial("WALL_SIGN");
if (result == null) {
result = Material.getMaterial("SIGN");
}
}
} else {
// Try saved name (works for wood types on 1.14, regular types for below)
result = Material.getMaterial(name);
if (result == null) {
// Cases for 1.13, which don't know wood types, but need new materials
if (FLOOR_SIGN_TYPES.contains(name)) {
// SIGN -> OAK_SIGN for 1.14
result = Material.getMaterial("OAK_SIGN");
// Fallback for 1.13
if (result == null) {
result = Material.getMaterial("SIGN");
}
} else if (WALL_SIGN_TYPES.contains(name)) {
// WALL_SIGN -> OAK_WALL_SIGN for 1.14
result = Material.getMaterial("OAK_WALL_SIGN");
// Fallback for 1.13
if (result == null) {
result = Material.getMaterial("WALL_SIGN");
}
}
}
}
if (result == null) {
AreaShop.debug("Materials.get() null result:", name, "legacyMaterials:", legacyMaterials);
}
return result;
}
/**
* Check if a Material is a sign (of either the wall or floor type).
* @param material Material to check
* @return true if the given material is a sign
*/
public static boolean isSign(Material material) {
return isSign(material.name());
}
/**
* Check if a Material is a sign (of either the wall or floor type).
* @param name String to check
* @return true if the given material is a sign
*/
public static boolean isSign(String name) {
return name != null && SIGN_PATTERN.matcher(name).find();
}
}
package me.wiefferink.areashop.tools;
import me.wiefferink.areashop.AreaShop;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class Materials {
private Materials() {
}
private static final HashSet<String> WALL_SIGN_TYPES = new HashSet<>(Arrays.asList(
// 1.14+ types
"ACACIA_WALL_SIGN",
"BIRCH_WALL_SIGN",
"DARK_OAK_WALL_SIGN",
"JUNGLE_WALL_SIGN",
"OAK_WALL_SIGN",
"SPRUCE_WALL_SIGN",
// Legacy types
"LEGACY_WALL_SIGN",
"WALL_SIGN"
));
private static final HashSet<String> FLOOR_SIGN_TYPES = new HashSet<>(Arrays.asList(
// 1.14+ types
"ACACIA_SIGN",
"BIRCH_SIGN",
"DARK_OAK_SIGN",
"JUNGLE_SIGN",
"OAK_SIGN",
"SPRUCE_SIGN",
// Legacy types
"LEGACY_SIGN",
"LEGACY_SIGN_POST",
"SIGN",
"SIGN_POST"
));
private static boolean legacyMaterials = false;
static {
List<String> legacyMaterialVersions = Arrays.asList("1.7", "1.8", "1.9", "1.10", "1.11", "1.12");
for(String legacyMaterialVersion : legacyMaterialVersions) {
String version = Bukkit.getBukkitVersion();
// Detects '1.8', '1.8.3', '1.8-pre1' style versions
if(version.equals(legacyMaterialVersion)
|| version.startsWith(legacyMaterialVersion + ".")
|| version.startsWith(legacyMaterialVersion + "-")) {
legacyMaterials = true;
break;
}
}
}
/**
* Get material based on a sign material name.
* @param name Name of the sign material
* @return null if not a sign, otherwise the material matching the name (when the material is not available on the current minecraft version, it returns the base type)
*/
public static Material signNameToMaterial(String name) {
// Expected null case
if (!isSign(name)) {
return null;
}
Material result = null;
if (legacyMaterials) {
// 1.12 and lower just know SIGN_POST, WALL_SIGN and SIGN
if (FLOOR_SIGN_TYPES.contains(name)) {
result = Material.getMaterial("SIGN_POST");
} else if (WALL_SIGN_TYPES.contains(name)) {
result = Material.getMaterial("WALL_SIGN");
if (result == null) {
result = Material.getMaterial("SIGN");
}
}
} else {
// Try saved name (works for wood types on 1.14, regular types for below)
result = Material.getMaterial(name);
if (result == null) {
// Cases for 1.13, which don't know wood types, but need new materials
if (FLOOR_SIGN_TYPES.contains(name)) {
// SIGN -> OAK_SIGN for 1.14
result = Material.getMaterial("OAK_SIGN");
// Fallback for 1.13
if (result == null) {
result = Material.getMaterial("SIGN");
}
} else if (WALL_SIGN_TYPES.contains(name)) {
// WALL_SIGN -> OAK_WALL_SIGN for 1.14
result = Material.getMaterial("OAK_WALL_SIGN");
// Fallback for 1.13
if (result == null) {
result = Material.getMaterial("WALL_SIGN");
}
}
}
}
if (result == null) {
AreaShop.debug("Materials.get() null result:", name, "legacyMaterials:", legacyMaterials);
}
return result;
}
/**
* Check if a Material is a sign (of either the wall or floor type).
* @param material Material to check
* @return true if the given material is a sign
*/
public static boolean isSign(Material material) {
return isSign(material.name());
}
/**
* Check if a Material is a sign (of either the wall or floor type).
* @param name String to check
* @return true if the given material is a sign
*/
public static boolean isSign(String name) {
return name != null && (FLOOR_SIGN_TYPES.contains(name) || WALL_SIGN_TYPES.contains(name));
}
}
@@ -7,7 +7,7 @@ import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import me.wiefferink.areashop.AreaShop;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import me.wiefferink.areashop.regions.BuyRegion;
import me.wiefferink.areashop.regions.LegacyGeneralRegion;
import me.wiefferink.areashop.regions.GeneralRegion;
import me.wiefferink.areashop.regions.RentRegion;
import me.wiefferink.interactivemessenger.Log;
import me.wiefferink.interactivemessenger.processing.Message;
@@ -325,10 +325,10 @@ public class Utils {
* @param selection The selection to check
* @return A list with all the AreaShop regions intersecting with the selection
*/
public static List<LegacyGeneralRegion> getRegionsInSelection(WorldEditSelection selection) {
ArrayList<LegacyGeneralRegion> result = new ArrayList<>();
public static List<GeneralRegion> getRegionsInSelection(WorldEditSelection selection) {
ArrayList<GeneralRegion> result = new ArrayList<>();
for (ProtectedRegion region : getWorldEditRegionsInSelection(selection)) {
LegacyGeneralRegion asRegion = AreaShop.getInstance().getFileManager().getRegion(region.getId());
GeneralRegion asRegion = AreaShop.getInstance().getFileManager().getRegion(region.getId());
if (asRegion != null) {
result.add(asRegion);
}
@@ -342,7 +342,7 @@ public class Utils {
* @param location The location to check
* @return A list with all the AreaShop regions that contain the location
*/
public static List<LegacyGeneralRegion> getRegions(Location location) {
public static List<GeneralRegion> getRegions(Location location) {
return getRegionsInSelection(new WorldEditSelection(location.getWorld(), location, location));
}
@@ -427,7 +427,7 @@ public class Utils {
*/
public static List<RentRegion> getImportantRentRegions(Location location) {
List<RentRegion> result = new ArrayList<>();
for (LegacyGeneralRegion region : getImportantRegions(location, LegacyGeneralRegion.RegionType.RENT)) {
for (GeneralRegion region : getImportantRegions(location, GeneralRegion.RegionType.RENT)) {
result.add((RentRegion) region);
}
return result;
@@ -442,7 +442,7 @@ public class Utils {
*/
public static List<BuyRegion> getImportantBuyRegions(Location location) {
List<BuyRegion> result = new ArrayList<>();
for (LegacyGeneralRegion region : getImportantRegions(location, LegacyGeneralRegion.RegionType.BUY)) {
for (GeneralRegion region : getImportantRegions(location, GeneralRegion.RegionType.BUY)) {
result.add((BuyRegion) region);
}
return result;
@@ -455,7 +455,7 @@ public class Utils {
* @param location The location to check for regions
* @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority
*/
public static List<LegacyGeneralRegion> getImportantRegions(Location location) {
public static List<GeneralRegion> getImportantRegions(Location location) {
return getImportantRegions(location, null);
}
@@ -467,22 +467,22 @@ public class Utils {
* @param type The type of regions to look for, null for all
* @return empty list if no regions found, 1 member if 1 region is a priority, more if regions with the same priority
*/
public static List<LegacyGeneralRegion> getImportantRegions(Location location, LegacyGeneralRegion.RegionType type) {
List<LegacyGeneralRegion> result = new ArrayList<>();
public static List<GeneralRegion> getImportantRegions(Location location, GeneralRegion.RegionType type) {
List<GeneralRegion> result = new ArrayList<>();
Set<ProtectedRegion> regions = AreaShop.getInstance().getWorldGuardHandler().getApplicableRegionsSet(location);
if (regions != null) {
List<LegacyGeneralRegion> candidates = new ArrayList<>();
List<GeneralRegion> candidates = new ArrayList<>();
for (ProtectedRegion pr : regions) {
LegacyGeneralRegion region = AreaShop.getInstance().getFileManager().getRegion(pr.getId());
GeneralRegion region = AreaShop.getInstance().getFileManager().getRegion(pr.getId());
if (region != null && (
(type == LegacyGeneralRegion.RegionType.RENT && region instanceof RentRegion)
|| (type == LegacyGeneralRegion.RegionType.BUY && region instanceof BuyRegion)
(type == GeneralRegion.RegionType.RENT && region instanceof RentRegion)
|| (type == GeneralRegion.RegionType.BUY && region instanceof BuyRegion)
|| type == null)) {
candidates.add(region);
}
}
boolean first = true;
for (LegacyGeneralRegion region : candidates) {
for (GeneralRegion region : candidates) {
if (region == null) {
AreaShop.debug("skipped null region");
continue;
@@ -768,7 +768,7 @@ public class Utils {
* @param region The region to apply replacements for and use for logging
* @return double evaluated from the input or a very high default in case of a script exception
*/
public static double evaluateToDouble(String input, LegacyGeneralRegion region) {
public static double evaluateToDouble(String input, GeneralRegion region) {
// Replace variables
input = Message.fromString(input).replacements(region).getSingle();
@@ -787,7 +787,7 @@ public class Utils {
try {
result = scriptEngine.eval(input);
} catch (ScriptException e) {
AreaShop.warn("Price of region", region.getRegionId(), "is set with an invalid expression: '" + input + "', exception:", ExceptionUtils.getStackTrace(e));
AreaShop.warn("Price of region", region.getName(), "is set with an invalid expression: '" + input + "', exception:", ExceptionUtils.getStackTrace(e));
return 99999999999.0; // High fallback for safety
}
@@ -795,7 +795,7 @@ public class Utils {
if (Utils.isDouble(result.toString())) {
return Double.parseDouble(result.toString());
} else {
AreaShop.warn("Price of region", region.getRegionId(), "is set with the expression '" + input + "' that returns a result that is not a number:", result);
AreaShop.warn("Price of region", region.getName(), "is set with the expression '" + input + "' that returns a result that is not a number:", result);
return 99999999999.0; // High fallback for safety
}
}
+58 -60
View File
@@ -1,60 +1,58 @@
# ╔════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗
# ║ hiddenConfig.yml file of the AreaShop plugin created by NLThijs48. ║
# ║ Options in this file are available in config.yml, but are not shown by default there. ║
# ║ The options in these file are either very advanced, or not useful for the majority of users. ║
# ╚════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ TIMERS: Settings to define how often scheduled tasks run. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Setting the 'delay' setting to 0 or lower will prevent the taks from runnning.
# The 'delay' settings are specified using a number followed by one of the identifiers as defined in config.yml.
# The 'regionsPerTick' settings are to configure how fast something goes, lower value is less lag, but slower updates.
# There are 20 ticks in 1 second, so if you set 'regionPerTick' to 5, then 5*20=100 regions per second will be updated.
# Timings for saving files that need saving.
saving:
delay: '11 minutes'
regionsPerTick: 1
# Timings for rent expiration checking.
expiration:
delay: '14 seconds'
regionsPerTick: 5
# Timings for expiration warning to online players.
expireWarning:
delay: '11 seconds'
regionsPerTick: 5
# Timings for updating signs and region flags ('/as reload' or after '/as groupadd' or '/as groupdel').
update:
regionsPerTick: 10
# Time between checking if any regions need to be unrented because the player was not online for the specified time period.
inactive:
delay: '17 minutes'
regionsPerTick: 5
# Timings for the periodic updating of signs (for timeleft tags etc).
signs:
delay: '1 minute'
regionsPerTick: 3
invalidSignLogLevel: WARNING
removeInvalid: false
# Number of regions per tick to check when a player joins to see if his name changed for regions he owned (updates the regions when changed).
nameupdate:
regionsPerTick: 10
# Timings for adding regions to AreaShop ('/as stack').
adding:
regionsPerTick: 2
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ OTHER: All other settings. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Allow or disallow extending a rental region when the player is above his limits enforced by the 'limitGroups' section below.
# false will ensure a player will eventually lose his region when he has no access anymore.
allowRegionExtendsWhenAboveLimits: false
# Flag profiles that can be used by the 'general.flagProfile' setting in default.yml
flagProfiles:
# Event command profiles that can be used by the 'general.eventCommandProfile' setting in default.yml
eventCommandProfiles:
# Sign profiles that can be used by the 'general.signProfile' setting in default.yml
signProfiles:
# Schematic profiles that can be used by the 'general.schematicProfile' setting in default.yml
schematicProfiles:
# ╔════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗
# ║ hiddenConfig.yml file of the AreaShop plugin created by NLThijs48. ║
# ║ Options in this file are available in config.yml, but are not shown by default there. ║
# ║ The options in these file are either very advanced, or not useful for the majority of users. ║
# ╚════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ TIMERS: Settings to define how often scheduled tasks run. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Setting the 'delay' setting to 0 or lower will prevent the taks from runnning.
# The 'delay' settings are specified using a number followed by one of the identifiers as defined in config.yml.
# The 'regionsPerTick' settings are to configure how fast something goes, lower value is less lag, but slower updates.
# There are 20 ticks in 1 second, so if you set 'regionPerTick' to 5, then 5*20=100 regions per second will be updated.
# Timings for saving files that need saving.
saving:
delay: '11 minutes'
regionsPerTick: 1
# Timings for rent expiration checking.
expiration:
delay: '14 seconds'
regionsPerTick: 5
# Timings for expiration warning to online players.
expireWarning:
delay: '11 seconds'
regionsPerTick: 5
# Timings for updating signs and region flags ('/as reload' or after '/as groupadd' or '/as groupdel').
update:
regionsPerTick: 10
# Time between checking if any regions need to be unrented because the player was not online for the specified time period.
inactive:
delay: '17 minutes'
regionsPerTick: 5
# Timings for the periodic updating of signs (for timeleft tags etc).
signs:
delay: '1 minute'
regionsPerTick: 3
# Number of regions per tick to check when a player joins to see if his name changed for regions he owned (updates the regions when changed).
nameupdate:
regionsPerTick: 10
# Timings for adding regions to AreaShop ('/as stack').
adding:
regionsPerTick: 2
# ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
# │ OTHER: All other settings. │
# └────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
# Allow or disallow extending a rental region when the player is above his limits enforced by the 'limitGroups' section below.
# false will ensure a player will eventually lose his region when he has no access anymore.
allowRegionExtendsWhenAboveLimits: false
# Flag profiles that can be used by the 'general.flagProfile' setting in default.yml
flagProfiles:
# Event command profiles that can be used by the 'general.eventCommandProfile' setting in default.yml
eventCommandProfiles:
# Sign profiles that can be used by the 'general.signProfile' setting in default.yml
signProfiles:
# Schematic profiles that can be used by the 'general.schematicProfile' setting in default.yml
schematicProfiles:
+53 -53
View File
@@ -1,53 +1,53 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>areashop-fawe-1-15</artifactId>
<packaging>jar</packaging>
<name>AreaShop FastAsyncWorldEdit 1.14+</name>
<version>latest</version>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>1.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<repositories>
<repository>
<id>IS-Repo</id>
<url>https://mvn.intellectualsites.com/content/repositories/releases/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.15.2-R0.1-SNAPSHOT</version>
<type>jar</type>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.intellectualsites.fawe</groupId>
<artifactId>FAWE-Bukkit</artifactId>
<version>1.16-583</version> <!-- Equivalent to WE 7.0.2? -->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
<version>7.0.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>latest</version>
<type>jar</type>
</dependency>
</dependencies>
</project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>areashop-fawe-1-15</artifactId>
<packaging>jar</packaging>
<name>AreaShop FastAsyncWorldEdit 1.14+</name>
<version>latest</version>
<parent>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<version>1.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<repositories>
<repository>
<id>IS-Repo</id>
<url>https://mvn.intellectualsites.com/content/repositories/releases/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.14.4-R0.1-SNAPSHOT</version>
<type>jar</type>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.intellectualsites.fawe</groupId>
<artifactId>FAWE-Bukkit</artifactId>
<version>1.16-380</version> <!-- Equivalent to WE 7.0.2? -->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sk89q.worldguard</groupId>
<artifactId>worldguard-bukkit</artifactId>
<version>7.0.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>latest</version>
<type>jar</type>
</dependency>
</dependencies>
</project>
@@ -27,7 +27,7 @@ import com.sk89q.worldedit.world.World;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionType;
import me.wiefferink.areashop.interfaces.AreaShopInterface;
import me.wiefferink.areashop.interfaces.IRegion;
import me.wiefferink.areashop.interfaces.GeneralRegionInterface;
import me.wiefferink.areashop.interfaces.WorldEditInterface;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import org.apache.commons.lang.exception.ExceptionUtils;
@@ -77,7 +77,7 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
@Override
@Beta
public CompletableFuture<Boolean> restoreRegionBlocksAsync(File rawFile, IRegion regionInterface) {
public CompletableFuture<Boolean> restoreRegionBlocksAsync(File rawFile, GeneralRegionInterface regionInterface) {
File file = null;
ClipboardFormat format = null;
for (ClipboardFormat formatOption : BuiltInClipboardFormat.values()) {
@@ -90,20 +90,20 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
}
}
if (file == null) {
pluginInterface.getLogger().info("Did not restore region " + regionInterface.getRegionId()
pluginInterface.getLogger().info("Did not restore region " + regionInterface.getName()
+ ", schematic file does not exist: " + rawFile.getAbsolutePath());
return CompletableFuture.completedFuture(false);
}
pluginInterface.debugI("Trying to restore region", regionInterface.getRegionId(), " from file",
pluginInterface.debugI("Trying to restore region", regionInterface.getName(), " from file",
file.getAbsolutePath(), "with format", format.getName());
com.sk89q.worldedit.world.World world = null;
if (regionInterface.getRegionId() != null) {
if (regionInterface.getName() != null) {
world = BukkitAdapter.adapt(regionInterface.getWorld());
}
if (world == null) {
pluginInterface.getLogger().info(
"Did not restore region " + regionInterface.getRegionId() + ", world not found: "
"Did not restore region " + regionInterface.getName() + ", world not found: "
+ regionInterface.getWorldName());
return CompletableFuture.completedFuture(false);
}
@@ -120,7 +120,7 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
region.getMinimumPoint().getBlockZ());
final RegionBoundMask mask = new RegionBoundMask(region);
final File finalFile = file;
final String regionName = regionInterface.getRegionId();
final String regionName = regionInterface.getName();
final double regionWidth = regionInterface.getWidth(), regionHeight = regionInterface.getHeight(), regionDepth = regionInterface.getDepth();
final LocalSession session =
new LocalSession(pluginInterface.getWorldEdit().getLocalConfiguration());
@@ -165,19 +165,19 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
Operations.completeLegacy(copy);
} catch (MaxChangedBlocksException e) {
pluginInterface.getLogger().warning(
"exceeded the block limit while restoring schematic of " + regionInterface.getRegionId()
"exceeded the block limit while restoring schematic of " + regionInterface.getName()
+ ", limit in exception: " + e.getBlockLimit() + ", limit passed by AreaShop: "
+ pluginInterface.getConfig().getInt("maximumBlocks"));
CompletableFuture.completedFuture(false);
} catch (IOException e) {
pluginInterface.getLogger().warning(
"An error occured while restoring schematic of " + regionInterface.getRegionId()
"An error occured while restoring schematic of " + regionInterface.getName()
+ ", enable debug to see the complete stacktrace");
pluginInterface.debugI(ExceptionUtils.getStackTrace(e));
CompletableFuture.completedFuture(false);
} catch (Exception e) {
pluginInterface.getLogger()
.warning("crashed during restore of " + regionInterface.getRegionId());
.warning("crashed during restore of " + regionInterface.getName());
pluginInterface.debugI(ExceptionUtils.getStackTrace(e));
CompletableFuture.completedFuture(false);
}
@@ -188,19 +188,19 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
}
@Override
public boolean restoreRegionBlocks(File rawFile, IRegion regionInterface) {
public boolean restoreRegionBlocks(File rawFile, GeneralRegionInterface regionInterface) {
return restoreRegionBlocksAsync(rawFile, regionInterface).join();
}
@Override
@Beta
public CompletableFuture<Boolean> saveRegionBlocksAsync(File file, IRegion regionInterface) {
public CompletableFuture<Boolean> saveRegionBlocksAsync(File file, GeneralRegionInterface regionInterface) {
// TODO implement using the FastAsyncWorldEdit api to save async
ClipboardFormat format = BuiltInClipboardFormat.MINECRAFT_STRUCTURE;
// TODO allow selecting FAWE format in the config? (when enabled you cannot go back to vanilla WorldEdit easily)
file = new File(file.getAbsolutePath() + "." + format.getPrimaryFileExtension());
pluginInterface.debugI("Trying to save region", regionInterface.getRegionId(), " to file",
pluginInterface.debugI("Trying to save region", regionInterface.getName(), " to file",
file.getAbsolutePath(), "with format", format.getName());
com.sk89q.worldedit.world.World world = null;
if (regionInterface.getWorld() != null) {
@@ -208,7 +208,7 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
}
if (world == null) {
pluginInterface.getLogger().warning(
"Did not save region " + regionInterface.getRegionId() + ", world not found: "
"Did not save region " + regionInterface.getName() + ", world not found: "
+ regionInterface.getWorldName());
return CompletableFuture.completedFuture(false);
}
@@ -218,7 +218,7 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
final ProtectedRegion region = regionInterface.getRegion();
final BlockVector3 min = region.getMinimumPoint(), max = region.getMaximumPoint();
final String regionName = regionInterface.getRegionId();
final String regionName = regionInterface.getName();
final World finalWorld = world;
final CompletableFuture<Boolean> completableFuture = new CompletableFuture<>();
final File finalFile = file;
@@ -264,7 +264,7 @@ public class FastAsyncWorldEditHandler extends WorldEditInterface {
}
@Override
public boolean saveRegionBlocks(File file, IRegion regionInterface) {
public boolean saveRegionBlocks(File file, GeneralRegionInterface regionInterface) {
return saveRegionBlocksAsync(file, regionInterface).join();
}
@@ -1,27 +0,0 @@
package me.wiefferink.areashop.interfaces;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.BlockData;
public interface BlockBehaviourHelper {
default boolean canPlace(Location location, Material material) {
return canPlace(location, material.createBlockData());
}
boolean canPlace(Location location, BlockData blockData);
/**
* Check if a sign is valid.
*
* @param block The block
* @return Returns true if the sign can exist in that location, false otherwise.
*/
boolean isBlockValid(Block block);
boolean isBlockStateValid(BlockState blockState);
}
@@ -3,11 +3,10 @@ package me.wiefferink.areashop.interfaces;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import org.bukkit.World;
public interface IRegion {
public interface GeneralRegionInterface {
ProtectedRegion getRegion();
String getRegionId();
String getName();
World getWorld();
@@ -18,5 +17,4 @@ public interface IRegion {
int getDepth();
int getHeight();
}
@@ -1,7 +0,0 @@
package me.wiefferink.areashop.interfaces;
public interface NMS {
BlockBehaviourHelper behaviourHelper();
}
@@ -19,9 +19,9 @@ public abstract class WorldEditInterface {
* @param regionInterface Region to restore from
* @return true when successful, otherwise false
*/
public abstract boolean restoreRegionBlocks(File file, IRegion regionInterface);
public abstract boolean restoreRegionBlocks(File file, GeneralRegionInterface regionInterface);
public CompletableFuture<Boolean> restoreRegionBlocksAsync(File file, IRegion regionInterface) {
public CompletableFuture<Boolean> restoreRegionBlocksAsync(File file, GeneralRegionInterface regionInterface) {
return CompletableFuture.completedFuture(restoreRegionBlocks(file, regionInterface));
}
@@ -32,9 +32,9 @@ public abstract class WorldEditInterface {
* @param regionInterface Region to restore from
* @return true when successful, otherwise false
*/
public abstract boolean saveRegionBlocks(File file, IRegion regionInterface);
public abstract boolean saveRegionBlocks(File file, GeneralRegionInterface regionInterface);
public CompletableFuture<Boolean> saveRegionBlocksAsync(File file, IRegion regionInterface) {
public CompletableFuture<Boolean> saveRegionBlocksAsync(File file, GeneralRegionInterface regionInterface) {
return CompletableFuture.completedFuture(saveRegionBlocks(file, regionInterface));
}
-86
View File
@@ -1,86 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>areashop-parent</artifactId>
<groupId>me.wiefferink</groupId>
<version>1.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>areashop-nms-1-15</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AreaShop NMS v1_15_R2</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>spigotmc-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>sonatype</id>
<url>https://oss.sonatype.org/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.15.2-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>latest</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
@@ -1,47 +0,0 @@
package me.wiefferink.areashop.nms.v1_15_R1;
import me.wiefferink.areashop.interfaces.BlockBehaviourHelper;
import net.minecraft.server.v1_15_R1.BlockPosition;
import net.minecraft.server.v1_15_R1.IBlockData;
import net.minecraft.server.v1_15_R1.World;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.v1_15_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_15_R1.block.CraftBlock;
import org.bukkit.craftbukkit.v1_15_R1.block.CraftBlockState;
import org.bukkit.craftbukkit.v1_15_R1.block.data.CraftBlockData;
import java.util.Objects;
public class BlockBehaviourHelperImpl implements BlockBehaviourHelper {
@Override
public boolean canPlace(Location location, BlockData blockData) {
Objects.requireNonNull(location.getWorld(), "Null World!");
final BlockPosition blockPosition = new BlockPosition(location.getX(), location.getY(), location.getZ());
final CraftWorld craftWorld = (CraftWorld) location.getWorld();
final World world = craftWorld.getHandle();
final CraftBlockData craftBlockData = (CraftBlockData) blockData;
final IBlockData ibd = craftBlockData.getState();
return ibd.canPlace(world, blockPosition);
}
@Override
public boolean isBlockValid(Block block) {
final CraftBlock craftBlock = (CraftBlock) block;
final CraftWorld craftWorld = (CraftWorld) craftBlock.getWorld();
final World world = craftWorld.getHandle();
final IBlockData ibd = craftBlock.getNMS();
return ibd.canPlace(world, craftBlock.getPosition());
}
@Override
public boolean isBlockStateValid(BlockState blockState) {
final CraftBlockState craftBlockState = (CraftBlockState) blockState;
final IBlockData ibd = craftBlockState.getHandle();
return ibd.canPlace(craftBlockState.getBlock().getCraftWorld().getHandle(), craftBlockState.getPosition());
}
}
@@ -1,15 +0,0 @@
package me.wiefferink.areashop.nms.v1_15_R1;
import me.wiefferink.areashop.interfaces.BlockBehaviourHelper;
import me.wiefferink.areashop.interfaces.NMS;
public final class NMSImpl implements NMS {
private BlockBehaviourHelper signHelper = new BlockBehaviourHelperImpl();
@Override
public BlockBehaviourHelper behaviourHelper() {
return this.signHelper;
}
}
-86
View File
@@ -1,86 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>areashop-parent</artifactId>
<groupId>me.wiefferink</groupId>
<version>1.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>areashop-nms-1-16</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AreaShop NMS v1_16_R3</name>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<repositories>
<repository>
<id>spigotmc-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
<repository>
<id>sonatype</id>
<url>https://oss.sonatype.org/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.16.5-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-interface</artifactId>
<version>latest</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
@@ -1,47 +0,0 @@
package me.wiefferink.areashop.nms.v1_16_R3;
import me.wiefferink.areashop.interfaces.BlockBehaviourHelper;
import net.minecraft.server.v1_16_R3.BlockPosition;
import net.minecraft.server.v1_16_R3.IBlockData;
import net.minecraft.server.v1_16_R3.World;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.BlockData;
import org.bukkit.craftbukkit.v1_16_R3.CraftWorld;
import org.bukkit.craftbukkit.v1_16_R3.block.CraftBlock;
import org.bukkit.craftbukkit.v1_16_R3.block.CraftBlockState;
import org.bukkit.craftbukkit.v1_16_R3.block.data.CraftBlockData;
import java.util.Objects;
public class BlockBehaviourHelperImpl implements BlockBehaviourHelper {
@Override
public boolean canPlace(Location location, BlockData blockData) {
Objects.requireNonNull(location.getWorld(), "Null World!");
final BlockPosition blockPosition = new BlockPosition(location.getX(), location.getY(), location.getZ());
final CraftWorld craftWorld = (CraftWorld) location.getWorld();
final World world = craftWorld.getHandle();
final CraftBlockData craftBlockData = (CraftBlockData) blockData;
final IBlockData ibd = craftBlockData.getState();
return ibd.canPlace(world, blockPosition);
}
@Override
public boolean isBlockValid(Block block) {
final CraftBlock craftBlock = (CraftBlock) block;
final CraftWorld craftWorld = (CraftWorld) craftBlock.getWorld();
final World world = craftWorld.getHandle();
final IBlockData ibd = craftBlock.getNMS();
return ibd.canPlace(world, craftBlock.getPosition());
}
@Override
public boolean isBlockStateValid(BlockState blockState) {
final CraftBlockState craftBlockState = (CraftBlockState) blockState;
final IBlockData ibd = craftBlockState.getHandle();
return ibd.canPlace(craftBlockState.getBlock().getCraftWorld().getHandle(), craftBlockState.getPosition());
}
}
@@ -1,15 +0,0 @@
package me.wiefferink.areashop.nms.v1_16_R3;
import me.wiefferink.areashop.interfaces.BlockBehaviourHelper;
import me.wiefferink.areashop.interfaces.NMS;
public final class NMSImpl implements NMS {
private BlockBehaviourHelper signHelper = new BlockBehaviourHelperImpl();
@Override
public BlockBehaviourHelper behaviourHelper() {
return this.signHelper;
}
}
@@ -24,7 +24,7 @@ import com.sk89q.worldedit.util.io.Closer;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.RegionType;
import me.wiefferink.areashop.interfaces.AreaShopInterface;
import me.wiefferink.areashop.interfaces.IRegion;
import me.wiefferink.areashop.interfaces.GeneralRegionInterface;
import me.wiefferink.areashop.interfaces.WorldEditInterface;
import me.wiefferink.areashop.interfaces.WorldEditSelection;
import org.apache.commons.lang.exception.ExceptionUtils;
@@ -58,7 +58,7 @@ public class WorldEditHandler extends WorldEditInterface {
}
@Override
public boolean restoreRegionBlocks(File rawFile, IRegion regionInterface) {
public boolean restoreRegionBlocks(File rawFile, GeneralRegionInterface regionInterface) {
File file = null;
ClipboardFormat format = null;
for (ClipboardFormat formatOption : ClipboardFormats.getAll()) {
@@ -71,17 +71,17 @@ public class WorldEditHandler extends WorldEditInterface {
}
}
if(file == null) {
pluginInterface.getLogger().info("Did not restore region " + regionInterface.getRegionId() + ", schematic file does not exist: " + rawFile.getAbsolutePath());
pluginInterface.getLogger().info("Did not restore region " + regionInterface.getName() + ", schematic file does not exist: " + rawFile.getAbsolutePath());
return false;
}
pluginInterface.debugI("Trying to restore region", regionInterface.getRegionId(), "from file", file.getAbsolutePath(), "with format", format.getName());
pluginInterface.debugI("Trying to restore region", regionInterface.getName(), "from file", file.getAbsolutePath(), "with format", format.getName());
com.sk89q.worldedit.world.World world = null;
if(regionInterface.getRegionId() != null) {
if(regionInterface.getName() != null) {
world = BukkitAdapter.adapt(regionInterface.getWorld());
}
if(world == null) {
pluginInterface.getLogger().info("Did not restore region " + regionInterface.getRegionId() + ", world not found: " + regionInterface.getWorldName());
pluginInterface.getLogger().info("Did not restore region " + regionInterface.getName() + ", world not found: " + regionInterface.getWorldName());
return false;
}
EditSession editSession = pluginInterface.getWorldEdit().getWorldEdit() // WARNING Deprecated in 7.2.0!
@@ -103,7 +103,7 @@ public class WorldEditHandler extends WorldEditInterface {
if(clipboard.getDimensions().getY() != regionInterface.getHeight()
|| clipboard.getDimensions().getX() != regionInterface.getWidth()
|| clipboard.getDimensions().getZ() != regionInterface.getDepth()) {
pluginInterface.getLogger().warning("Size of the region " + regionInterface.getRegionId() + " is not the same as the schematic to restore!");
pluginInterface.getLogger().warning("Size of the region " + regionInterface.getName() + " is not the same as the schematic to restore!");
pluginInterface.debugI("schematic|region, x:" + clipboard.getDimensions().getX() + "|" + regionInterface.getWidth() + ", y:" + clipboard.getDimensions().getY() + "|" + regionInterface.getHeight() + ", z:" + clipboard.getDimensions().getZ() + "|" + regionInterface.getDepth());
}
clipboard.setOrigin(clipboard.getMinimumPoint());
@@ -133,14 +133,14 @@ public class WorldEditHandler extends WorldEditInterface {
}
Operations.completeLegacy(copy);
} catch(MaxChangedBlocksException e) {
pluginInterface.getLogger().warning("exceeded the block limit while restoring schematic of " + regionInterface.getRegionId() + ", limit in exception: " + e.getBlockLimit() + ", limit passed by AreaShop: " + pluginInterface.getConfig().getInt("maximumBlocks"));
pluginInterface.getLogger().warning("exceeded the block limit while restoring schematic of " + regionInterface.getName() + ", limit in exception: " + e.getBlockLimit() + ", limit passed by AreaShop: " + pluginInterface.getConfig().getInt("maximumBlocks"));
return false;
} catch(IOException e) {
pluginInterface.getLogger().warning("An error occured while restoring schematic of " + regionInterface.getRegionId() + ", enable debug to see the complete stacktrace");
pluginInterface.getLogger().warning("An error occured while restoring schematic of " + regionInterface.getName() + ", enable debug to see the complete stacktrace");
pluginInterface.debugI(ExceptionUtils.getStackTrace(e));
return false;
} catch (Exception e) {
pluginInterface.getLogger().warning("crashed during restore of " + regionInterface.getRegionId());
pluginInterface.getLogger().warning("crashed during restore of " + regionInterface.getName());
pluginInterface.debugI(ExceptionUtils.getStackTrace(e));
return false;
}
@@ -149,7 +149,7 @@ public class WorldEditHandler extends WorldEditInterface {
}
@Override
public boolean saveRegionBlocks(File file, IRegion regionInterface) {
public boolean saveRegionBlocks(File file, GeneralRegionInterface regionInterface) {
ClipboardFormat format = ClipboardFormats.findByAlias("sponge");
if(format == null) {
// Sponge format does not exist, try to select another one
@@ -163,13 +163,13 @@ public class WorldEditHandler extends WorldEditInterface {
}
file = new File(file.getAbsolutePath() + "." + format.getPrimaryFileExtension());
pluginInterface.debugI("Trying to save region", regionInterface.getRegionId(), " to file", file.getAbsolutePath(), "with format", format.getName());
pluginInterface.debugI("Trying to save region", regionInterface.getName(), " to file", file.getAbsolutePath(), "with format", format.getName());
com.sk89q.worldedit.world.World world = null;
if(regionInterface.getWorld() != null) {
world = BukkitAdapter.adapt(regionInterface.getWorld());
}
if(world == null) {
pluginInterface.getLogger().warning("Did not save region " + regionInterface.getRegionId() + ", world not found: " + regionInterface.getWorldName());
pluginInterface.getLogger().warning("Did not save region " + regionInterface.getName() + ", world not found: " + regionInterface.getWorldName());
return false;
}
EditSession editSession = pluginInterface.getWorldEdit().getWorldEdit() // WARNING Deprecated in 7.2.0!
@@ -184,7 +184,7 @@ public class WorldEditHandler extends WorldEditInterface {
try {
Operations.completeLegacy(copy);
} catch(MaxChangedBlocksException e) {
pluginInterface.getLogger().warning("Exceeded the block limit while saving schematic of " + regionInterface.getRegionId() + ", limit in exception: " + e.getBlockLimit() + ", limit passed by AreaShop: " + pluginInterface.getConfig().getInt("maximumBlocks"));
pluginInterface.getLogger().warning("Exceeded the block limit while saving schematic of " + regionInterface.getName() + ", limit in exception: " + e.getBlockLimit() + ", limit passed by AreaShop: " + pluginInterface.getConfig().getInt("maximumBlocks"));
return false;
}
@@ -194,11 +194,11 @@ public class WorldEditHandler extends WorldEditInterface {
ClipboardWriter writer = closer.register(format.getWriter(bos));
writer.write(clipboard);
} catch(IOException e) {
pluginInterface.getLogger().warning("An error occured while saving schematic of " + regionInterface.getRegionId() + ", enable debug to see the complete stacktrace");
pluginInterface.getLogger().warning("An error occured while saving schematic of " + regionInterface.getName() + ", enable debug to see the complete stacktrace");
pluginInterface.debugI(ExceptionUtils.getStackTrace(e));
return false;
} catch (Exception e) {
pluginInterface.getLogger().warning("crashed during save of " + regionInterface.getRegionId());
pluginInterface.getLogger().warning("crashed during save of " + regionInterface.getName());
pluginInterface.debugI(ExceptionUtils.getStackTrace(e));
return false;
}
+116 -120
View File
@@ -1,120 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<packaging>pom</packaging>
<version>1.0</version>
<name>AreaShop Parent</name>
<url>https://github.com/NLthijs48/AreaShop</url>
<licenses>
<license>
<name>GNU General Public License v3.0</name>
<url>https://www.gnu.org/licenses/gpl-3.0.en.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<issueManagement>
<url>https://github.com/NLthijs48/AreaShop/issues</url>
<system>GitHub Issues</system>
</issueManagement>
<ciManagement>
<system>Jenkins</system>
<url>http://jenkins.wiefferink.me/job/AreaShop</url>
</ciManagement>
<repositories>
<repository>
<id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
<repository>
<id>wiefferink-repo</id>
<url>http://maven.wiefferink.me</url>
</repository>
<repository>
<id>bstats-repo</id>
<url>http://repo.bstats.org/content/repositories/releases/</url>
</repository>
<repository>
<id>mvn-repo</id>
<url>https://mvnrepository.com/artifact/org.bstats/bstats-bukkit</url>
</repository>
<repository>
<id>sk89q-repo</id>
<url>https://maven.enginehub.org/repo/</url>
</repository>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!--build.number>#CUSTOM</build.number-->
</properties>
<modules>
<module>hooks/areashop-interface</module>
<!-- NMS Abstractions -->
<module>hooks/areashop-nms-1-16-5</module>
<module>hooks/areashop-nms-1-15-2</module>
<!-- FAWE Compat -->
<module>hooks/areashop-fawe-1-15</module>
<!-- World Edit Compat -->
<module>hooks/areashop-worldedit-7</module>
<!-- World Guard Compat -->
<module>hooks/areashop-worldguard-7</module>
<module>AreaShop</module>
</modules>
<build>
<defaultGoal>clean package</defaultGoal>
<!--plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.0</version>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>8.29</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>validate</id>
<phase>validate</phase>
<configuration>
<configLocation>config/checkstyle.xml</configLocation>
<suppressionsLocation>config/checkstyle-suppressions.xml</suppressionsLocation>
<suppressionsFileExpression>config/checkstyle.suppressions.file
</suppressionsFileExpression>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<violationSeverity>error</violationSeverity>
</configuration>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins-->
</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>me.wiefferink</groupId>
<artifactId>areashop-parent</artifactId>
<packaging>pom</packaging>
<version>1.0</version>
<name>AreaShop Parent</name>
<url>https://github.com/NLthijs48/AreaShop</url>
<licenses>
<license>
<name>GNU General Public License v3.0</name>
<url>https://www.gnu.org/licenses/gpl-3.0.en.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<issueManagement>
<url>https://github.com/NLthijs48/AreaShop/issues</url>
<system>GitHub Issues</system>
</issueManagement>
<ciManagement>
<system>Jenkins</system>
<url>http://jenkins.wiefferink.me/job/AreaShop</url>
</ciManagement>
<repositories>
<repository>
<id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
<repository>
<id>wiefferink-repo</id>
<url>http://maven.wiefferink.me</url>
</repository>
<repository>
<id>bstats-repo</id>
<url>http://repo.bstats.org/content/repositories/releases/</url>
</repository>
<repository>
<id>mvn-repo</id>
<url>https://mvnrepository.com/artifact/org.bstats/bstats-bukkit</url>
</repository>
<repository>
<id>sk89q-repo</id>
<url>https://maven.enginehub.org/repo/</url>
</repository>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!--build.number>#CUSTOM</build.number-->
</properties>
<modules>
<module>hooks/areashop-interface</module>
<!-- FAWE Compat -->
<module>hooks/areashop-fawe-1-15</module>
<!-- World Edit Compat -->
<module>hooks/areashop-worldedit-7</module>
<!-- World Guard Compat -->
<module>hooks/areashop-worldguard-7</module>
<module>AreaShop</module>
</modules>
<build>
<defaultGoal>clean package</defaultGoal>
<!--plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.1.0</version>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>8.29</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>validate</id>
<phase>validate</phase>
<configuration>
<configLocation>config/checkstyle.xml</configLocation>
<suppressionsLocation>config/checkstyle-suppressions.xml</suppressionsLocation>
<suppressionsFileExpression>config/checkstyle.suppressions.file
</suppressionsFileExpression>
<encoding>UTF-8</encoding>
<consoleOutput>true</consoleOutput>
<failsOnError>true</failsOnError>
<violationSeverity>error</violationSeverity>
</configuration>
<goals>
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins-->
</build>
</project>