Merge branch 'development'

This commit is contained in:
Brianna 2019-10-21 11:04:17 -04:00
commit 20f8991544
307 changed files with 4912 additions and 3889 deletions

8
.gitignore vendored
View File

@ -11,7 +11,6 @@
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.settings
@ -27,3 +26,10 @@ hs_err_pid*
/.idea/
**/build/
/bin/
### Eclipse Patch ###
# Eclipse Core
.project
# JDT-specific (Eclipse Java Development Tools)
.classpath

View File

@ -3,7 +3,7 @@ image: gradle:alpine
variables:
name: "FabledSkyBlock"
path: "/builds/$CI_PROJECT_PATH"
version: "Build-79"
version: "2.0.7"
before_script:
- export GRADLE_USER_HOME=`pwd`/.gradle

View File

@ -1,65 +0,0 @@
import org.apache.tools.ant.filters.ReplaceTokens
configurations {
extraLibs
}
dependencies {
// Project Dependencies
compile project(':FabledSkyBlock-Legacy')
// PlaceholderAPI
compileOnly (group: 'be.maximvdw', name: 'placeholderapi', version: '2.5.1')
compileOnly (group: 'me.clip', name: 'placeholderapi', version: '2.10.2')
// Vault
compileOnly (group: 'net.milkbowl', name: 'vault', version: '1.7.1')
// Reserve
compileOnly (group: 'net.tnemc', name: 'Reserve', version: '0.1.3.0')
// Leaderheads
compileOnly (group: 'me.robin', name: 'leaderheads', version: '1.0')
// EpicSpawners
compileOnly (group: 'com.songoda', name: 'epicspawners', version: '6-pre4')
// EpicAnchors
compileOnly (group: 'com.songoda', name: 'epicanchors', version: '1.2.5')
// UltimateStacker
compileOnly (group: 'com.songoda', name: 'ultimatestacker', version: '1.3.1')
// WildStacker
compileOnly (group: 'com.github.OmerBenGera', name: 'WildStackerAPI', version: 'b15')
// WorldEdit
compileOnly (group: 'com.sk89q', name: 'worldedit', version: '7.0.0')
// Apache Commons
extraLibs (group: 'org.apache.commons', name: 'commons-lang3', version: '3.0')
extraLibs (group: 'commons-io', name: 'commons-io', version: '2.5')
// Spigot
compileOnly (group: 'org.spigotmc', name: 'spigot', version: '1.14.1')
// Songoda Updater
extraLibs (group: 'com.songoda', name: 'songodaupdater', version: '1')
configurations.compileOnly.extendsFrom(configurations.extraLibs)
}
processResources {
from (sourceSets.main.resources.srcDirs) {
include '**/*.yml'
filter ReplaceTokens, tokens: ["version": project.property("version")]
}
}
jar {
from {
configurations.extraLibs.collect {
it.isDirectory() ? it : zipTree(it)
}
}
}

View File

@ -1,505 +0,0 @@
package com.songoda.skyblock.api.island;
import com.google.common.base.Preconditions;
import com.songoda.skyblock.api.SkyBlockAPI;
import com.songoda.skyblock.api.ban.Ban;
import com.songoda.skyblock.api.utils.APIUtil;
import com.songoda.skyblock.api.visit.Visit;
import com.songoda.skyblock.island.IslandCoop;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.WeatherType;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.entity.Player;
import java.util.*;
public class Island {
private com.songoda.skyblock.island.Island handle;
private OfflinePlayer player;
public Island(com.songoda.skyblock.island.Island handle, OfflinePlayer player) {
this.handle = handle;
this.player = player;
}
/**
* @return The Island UUID
*/
public UUID getIslandUUID() {
return this.handle.getIslandUUID();
}
/**
* @return The Island owner UUID
*/
public UUID getOwnerUUID() {
return this.handle.getOwnerUUID();
}
/**
* @return The original Island owner UUID
*/
public UUID getOriginalOwnerUUID() {
return this.handle.getOriginalOwnerUUID();
}
/**
* @return The Island size
*/
public int getSize() {
return this.handle.getSize();
}
/**
* Set the size of the Island
*/
public void setSize(int size) {
Preconditions.checkArgument(size <= 1000, "Cannot set size to greater than 1000");
Preconditions.checkArgument(size >= 50, "Cannot set size to less than 50");
this.handle.setSize(size);
}
/**
* @return The Island radius
*/
public double getRadius() {
return this.handle.getRadius();
}
/**
* @return true if not null, false otherwise
*/
public boolean hasPassword() {
return this.handle.hasPassword();
}
/**
* Set the password for ownership
*/
public void setPassword(String password) {
Preconditions.checkArgument(password != null, "Cannot set password to null password");
this.handle.setPassword(password);
}
/**
* Get the Location from the World in island world from World in environment.
*
* @return Location of Island
*/
public Location getLocation(IslandWorld world, IslandEnvironment environment) {
Preconditions.checkArgument(world != null, "World in island world null does not exist");
Preconditions.checkArgument(environment != null, "World in environment null does not exist");
return handle.getLocation(APIUtil.toImplementation(world), APIUtil.toImplementation(environment));
}
/**
* Set the Location from the World in island world from world in environment
* followed by position
*/
public void setLocation(IslandWorld world, IslandEnvironment environment, int x, int y, int z) {
Preconditions.checkArgument(world != null, "World in island world null does not exist");
Preconditions.checkArgument(environment != null, "World in environment null does not exist");
World bukkitWorld = getLocation(world, environment).getWorld();
this.handle.setLocation(APIUtil.toImplementation(world), APIUtil.toImplementation(environment),
new Location(bukkitWorld, x, y, z));
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isBorder() {
return this.handle.isBorder();
}
/**
* Set the border visible to players for the Island
*/
public void setBorder(boolean border) {
this.handle.setBorder(border);
}
/**
* @return The color of the Island border
*/
public IslandBorderColor getBorderColor() {
return APIUtil.fromImplementation(this.handle.getBorderColor());
}
/**
* Set the border color for the Island
*/
public void setBorderColor(IslandBorderColor color) {
Preconditions.checkArgument(color != null, "IslandBorderColor null does not exist");
this.handle.setBorderColor(APIUtil.toImplementation(color));
}
/**
* @return The biome set for the Island
*/
public Biome getBiome() {
return this.handle.getBiome();
}
/**
* Set the biome for the Island
*/
public void setBiome(Biome biome) {
Preconditions.checkArgument(biome != null, "Cannot set biome to null biome");
this.handle.setBiome(biome);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isDayCycleSynchronizedSynchronized() {
return this.handle.isWeatherSynchronized();
}
/**
* Set the Day Cycle of the Island to be Synchronized with the World cycle
*/
public void setDayCycleSynchronzied(boolean sync) {
this.handle.setWeatherSynchronized(sync);
}
/**
* @return The WeatherType set for the Island
*/
public WeatherType getWeather() {
return this.handle.getWeather();
}
/**
* Set the weather for the Island
*/
public void setWeather(WeatherType weatherType) {
Preconditions.checkArgument(weatherType != null, "Cannot set weather to null weather");
this.handle.setWeather(weatherType);
}
/**
* @return The time set for the Island
*/
public int getTime() {
return this.handle.getTime();
}
/**
* Set the time for the Island
*/
public void setTime(int time) {
this.handle.setTime(time);
}
/**
* @return A Set of cooped players
*/
public Map<UUID, IslandCoop> getCoopPlayers() {
return this.handle.getCoopPlayers();
}
/**
* Add a player to the coop players for the Island
*/
public void addCoopPlayer(UUID uuid, IslandCoop islandCoop) {
Preconditions.checkArgument(uuid != null, "Cannot add coop player to null uuid");
this.handle.addCoopPlayer(uuid, islandCoop);
}
/**
* Add a player to the coop players for the Island
*/
public void addCoopPlayer(OfflinePlayer player, IslandCoop islandCoop) {
Preconditions.checkArgument(player != null, "Cannot add coop player to null player");
this.handle.addCoopPlayer(player.getUniqueId(), islandCoop);
}
/**
* Remove a player from the coop players for the Island
*/
public void removeCoopPlayer(UUID uuid) {
Preconditions.checkArgument(uuid != null, "Cannot remove coop player to null uuid");
this.handle.removeCoopPlayer(uuid);
}
/**
* Remove a player from the coop players for the Island
*/
public void removeCoopPlayer(OfflinePlayer player) {
Preconditions.checkArgument(player != null, "Cannot remove coop player to null player");
this.handle.removeCoopPlayer(player.getUniqueId());
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isCoopPlayer(UUID uuid) {
Preconditions.checkArgument(uuid != null, "Cannot return condition to null uuid");
return this.handle.isCoopPlayer(uuid);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isCoopPlayer(OfflinePlayer player) {
Preconditions.checkArgument(player != null, "Cannot return condition to null player");
return this.handle.isCoopPlayer(player.getUniqueId());
}
/**
* @return The IslandRole of a player
*/
public IslandRole getRole(OfflinePlayer player) {
Preconditions.checkArgument(player != null, "Cannot get role for null player");
for (com.songoda.skyblock.island.IslandRole role : com.songoda.skyblock.island.IslandRole.values()) {
if (this.handle.hasRole(role, player.getUniqueId())) {
return APIUtil.fromImplementation(role);
}
}
return null;
}
/**
* @return A Set of players with IslandRole
*/
public Set<UUID> getPlayersWithRole(IslandRole role) {
Preconditions.checkArgument(role != null, "Cannot get players will null role");
return this.handle.getRole(APIUtil.toImplementation(role));
}
/**
* Set the IslandRole of a player for the Island
*
* @return true of conditions met, false otherwise
*/
public boolean setRole(OfflinePlayer player, IslandRole role) {
Preconditions.checkArgument(player != null, "Cannot set role of null player");
return setRole(player.getUniqueId(), role);
}
/**
* Set the IslandRole of a player for the Island
*
* @return true of conditions met, false otherwise
*/
public boolean setRole(UUID uuid, IslandRole role) {
Preconditions.checkArgument(uuid != null, "Cannot set role of null player");
Preconditions.checkArgument(role != null, "Cannot set role to null role");
return this.handle.setRole(APIUtil.toImplementation(role), uuid);
}
/**
* Remove the IslandRole of a player for the Island
*
* @return true of conditions met, false otherwise
*/
public boolean removeRole(OfflinePlayer player, IslandRole role) {
Preconditions.checkArgument(player != null, "Cannot remove role of null player");
return removeRole(player.getUniqueId(), role);
}
/**
* Remove the IslandRole of a player for the Island
*
* @return true of conditions met, false otherwise
*/
public boolean removeRole(UUID uuid, IslandRole role) {
Preconditions.checkArgument(uuid != null, "Cannot remove role of null player");
Preconditions.checkArgument(role != null, "Cannot remove role to null role");
return this.handle.removeRole(APIUtil.toImplementation(role), uuid);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean hasRole(OfflinePlayer player, IslandRole role) {
Preconditions.checkArgument(player != null, "Cannot check role of null player");
return handle.hasRole(APIUtil.toImplementation(role), player.getUniqueId());
}
/**
* @return true of conditions met, false otherwise
*/
public boolean hasRole(UUID uuid, IslandRole role) {
Preconditions.checkArgument(uuid != null, "Cannot check role of null player");
Preconditions.checkArgument(role != null, "Cannot check role to null role");
return handle.hasRole(APIUtil.toImplementation(role), uuid);
}
/**
* Set the condition of an IslandUpgrade for the Island
*/
public void setUpgrade(Player player, IslandUpgrade upgrade, boolean status) {
Preconditions.checkArgument(upgrade != null, "Cannot set upgrade to null upgrade");
this.handle.setUpgrade(player, APIUtil.toImplementation(upgrade), status);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean hasUpgrade(IslandUpgrade upgrade) {
Preconditions.checkArgument(upgrade != null, "Cannot check upgrade to null upgrade");
return this.handle.hasUpgrade(APIUtil.toImplementation(upgrade));
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isUpgrade(IslandUpgrade upgrade) {
Preconditions.checkArgument(upgrade != null, "Cannot check upgrade to null upgrade");
return this.handle.isUpgrade(APIUtil.toImplementation(upgrade));
}
/**
* @return Setting of an IslandRole for the Island
*/
public IslandSetting getSetting(IslandRole role, String setting) {
Preconditions.checkArgument(role != null, "Cannot get setting to null role");
Preconditions.checkArgument(setting != null, "Cannot get setting for null setting");
return new IslandSetting(this.handle.getSetting(APIUtil.toImplementation(role), setting));
}
/**
* @return A List of Settings of an IslandRole for the Island
*/
public List<IslandSetting> getSettings(IslandRole role) {
Preconditions.checkArgument(role != null, "Cannot get settings to null role");
List<IslandSetting> settings = new ArrayList<>();
for (com.songoda.skyblock.island.IslandSetting settingList : this.handle
.getSettings(APIUtil.toImplementation(role))) {
settings.add(new IslandSetting(settingList));
}
return settings;
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isOpen() {
return handle.isOpen();
}
public void setOpen(boolean open) {
this.handle.setOpen(open);
}
/**
* @return A List from IslandMessage for the Island
*/
public List<String> getMessage(IslandMessage message) {
Preconditions.checkArgument(message != null, "Cannot get message for null message");
return this.handle.getMessage(APIUtil.toImplementation(message));
}
/**
* @return The author of an IslandMessage for the Island
*/
public String getMessageAuthor(IslandMessage message) {
Preconditions.checkArgument(message != null, "Cannot get message author for null message");
return this.handle.getMessageAuthor(APIUtil.toImplementation(message));
}
/**
* Set the IslandMessage for the Island
*/
public void setMessage(IslandMessage message, String author, List<String> messageLines) {
Preconditions.checkArgument(message != null, "Cannot set message for null message");
this.handle.setMessage(APIUtil.toImplementation(message), author, messageLines);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean hasStructure() {
return this.handle.hasStructure();
}
/**
* @return The Structure name for the Island
*/
public String getStructure() {
return this.handle.getStructure();
}
/**
* Set the Structure for the Island
*/
public void setStructure(String structure) {
Preconditions.checkArgument(structure != null, "Cannot set structure to null structure");
this.handle.setStructure(structure);
}
/**
* @return The Visit implementation for the Island
*/
public Visit getVisit() {
return new Visit(this);
}
/**
* @return The Ban implementation for the Island
*/
public Ban getBan() {
return new Ban(this);
}
/**
* @return The Level implementation for the Island
*/
public IslandLevel getLevel() {
return new IslandLevel(this);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isLoaded() {
return this.handle != null;
}
/**
* Loads the Island if unloaded
*/
public void load() {
if (this.handle == null) {
this.handle = SkyBlockAPI.getImplementation().getIslandManager().loadIsland(player);
}
}
/**
* Unloads the Island if loaded
*/
public void unload() {
if (this.handle != null) {
SkyBlockAPI.getImplementation().getIslandManager().unloadIsland(getIsland(), null);
this.handle = null;
}
}
/**
* Sets the player of the Island
*/
public void setPlayer(OfflinePlayer player) {
this.player = player;
}
/**
* @return Implementation for the Island
*/
public com.songoda.skyblock.island.Island getIsland() {
return handle;
}
}

View File

@ -1,300 +0,0 @@
package com.songoda.skyblock.cooldown;
import com.songoda.skyblock.SkyBlock;
import com.songoda.skyblock.config.FileManager;
import com.songoda.skyblock.config.FileManager.Config;
import com.songoda.skyblock.island.Island;
import com.songoda.skyblock.island.IslandManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CooldownManager {
private final SkyBlock skyblock;
private Map<CooldownType, List<CooldownPlayer>> cooldownStorage = new HashMap<>();
public CooldownManager(SkyBlock skyblock) {
this.skyblock = skyblock;
IslandManager islandManager = skyblock.getIslandManager();
for (CooldownType cooldownTypeList : CooldownType.values()) {
List<CooldownPlayer> cooldownPlayers = new ArrayList<>();
for (Player all : Bukkit.getOnlinePlayers()) {
CooldownPlayer cooldownPlayer = null;
if (cooldownTypeList == CooldownType.Biome || cooldownTypeList == CooldownType.Creation) {
cooldownPlayer = loadCooldownPlayer(cooldownTypeList, all);
} else if (cooldownTypeList == CooldownType.Levelling || cooldownTypeList == CooldownType.Ownership) {
Island island = islandManager.getIsland(all);
if (island != null) {
OfflinePlayer offlinePlayer = Bukkit.getServer().getOfflinePlayer(island.getOwnerUUID());
if (!hasPlayer(cooldownTypeList, offlinePlayer)) {
cooldownPlayer = loadCooldownPlayer(cooldownTypeList, offlinePlayer);
}
}
}
if (cooldownPlayer != null) {
cooldownPlayers.add(cooldownPlayer);
}
}
cooldownStorage.put(cooldownTypeList, cooldownPlayers);
}
new CooldownTask(this).runTaskTimerAsynchronously(skyblock, 0L, 20L);
}
public void onDisable() {
for (CooldownType cooldownTypeList : CooldownType.values()) {
setCooldownPlayer(cooldownTypeList);
saveCooldownPlayer(cooldownTypeList);
}
}
public CooldownPlayer loadCooldownPlayer(CooldownType cooldownType, OfflinePlayer player) {
if (cooldownType == CooldownType.Biome || cooldownType == CooldownType.Creation) {
Config config = skyblock.getFileManager()
.getConfig(new File(new File(skyblock.getDataFolder().toString() + "/player-data"),
player.getUniqueId().toString() + ".yml"));
FileConfiguration configLoad = config.getFileConfiguration();
if (configLoad.getString("Island." + cooldownType.name() + ".Cooldown") != null) {
return new CooldownPlayer(player.getUniqueId(),
new Cooldown(configLoad.getInt("Island." + cooldownType.name() + ".Cooldown")));
}
} else if (cooldownType == CooldownType.Levelling || cooldownType == CooldownType.Ownership) {
Config config = skyblock.getFileManager()
.getConfig(new File(new File(skyblock.getDataFolder().toString() + "/island-data"),
player.getUniqueId().toString() + ".yml"));
FileConfiguration configLoad = config.getFileConfiguration();
if (configLoad.getString(cooldownType.name() + ".Cooldown") != null) {
return new CooldownPlayer(player.getUniqueId(),
new Cooldown(configLoad.getInt(cooldownType.name() + ".Cooldown")));
}
}
return null;
}
public void createPlayer(CooldownType cooldownType, OfflinePlayer player) {
FileManager fileManager = skyblock.getFileManager();
if (cooldownStorage.containsKey(cooldownType)) {
int time = 0;
if (cooldownType == CooldownType.Biome || cooldownType == CooldownType.Creation) {
time = fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration()
.getInt("Island." + cooldownType.name() + ".Cooldown.Time");
Config config = fileManager
.getConfig(new File(new File(skyblock.getDataFolder().toString() + "/player-data"),
player.getUniqueId().toString() + ".yml"));
File configFile = config.getFile();
FileConfiguration configLoad = config.getFileConfiguration();
configLoad.set("Island." + cooldownType.name() + ".Cooldown", time);
try {
configLoad.save(configFile);
} catch (IOException e) {
e.printStackTrace();
}
} else if (cooldownType == CooldownType.Levelling || cooldownType == CooldownType.Ownership) {
time = fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration()
.getInt("Island." + cooldownType.name() + ".Cooldown.Time");
Config config = skyblock.getFileManager()
.getConfig(new File(new File(skyblock.getDataFolder().toString() + "/island-data"),
player.getUniqueId().toString() + ".yml"));
File configFile = config.getFile();
FileConfiguration configLoad = config.getFileConfiguration();
configLoad.set(cooldownType.name() + ".Cooldown", time);
try {
configLoad.save(configFile);
} catch (IOException e) {
e.printStackTrace();
}
}
cooldownStorage.get(cooldownType).add(new CooldownPlayer(player.getUniqueId(), new Cooldown(time)));
}
}
public void deletePlayer(CooldownType cooldownType, OfflinePlayer player) {
if (cooldownStorage.containsKey(cooldownType)) {
for (CooldownPlayer cooldownPlayerList : cooldownStorage.get(cooldownType)) {
if (cooldownPlayerList.getUUID().equals(player.getUniqueId())) {
if (cooldownType == CooldownType.Biome || cooldownType == CooldownType.Creation) {
skyblock.getFileManager()
.getConfig(new File(new File(skyblock.getDataFolder().toString() + "/player-data"),
player.getUniqueId().toString() + ".yml"))
.getFileConfiguration().set("Island." + cooldownType.name() + ".Cooldown", null);
} else if (cooldownType == CooldownType.Levelling || cooldownType == CooldownType.Ownership) {
skyblock.getFileManager()
.getConfig(new File(new File(skyblock.getDataFolder().toString() + "/island-data"),
player.getUniqueId().toString() + ".yml"))
.getFileConfiguration().set(cooldownType.name() + ".Cooldown", null);
}
cooldownStorage.get(cooldownType).remove(cooldownPlayerList);
break;
}
}
}
}
public boolean hasPlayer(CooldownType cooldownType, OfflinePlayer player) {
if (cooldownStorage.containsKey(cooldownType)) {
for (CooldownPlayer cooldownPlayerList : cooldownStorage.get(cooldownType)) {
if (cooldownPlayerList.getUUID().equals(player.getUniqueId())) {
return true;
}
}
}
return false;
}
public void transferPlayer(CooldownType cooldownType, OfflinePlayer player1, OfflinePlayer player2) {
if (cooldownStorage.containsKey(cooldownType)) {
for (CooldownPlayer cooldownPlayerList : cooldownStorage.get(cooldownType)) {
if (cooldownPlayerList.getUUID().equals(player1.getUniqueId())) {
cooldownPlayerList.setUUID(player2.getUniqueId());
break;
}
}
}
}
public void removeCooldownPlayer(CooldownType cooldownType, CooldownPlayer cooldownPlayer) {
if (cooldownStorage.containsKey(cooldownType)) {
cooldownStorage.get(cooldownType).remove(cooldownPlayer);
}
}
public void removeCooldownPlayer(CooldownType cooldownType, OfflinePlayer player) {
if (cooldownStorage.containsKey(cooldownType)) {
for (CooldownPlayer cooldownPlayerList : cooldownStorage.get(cooldownType)) {
if (cooldownPlayerList.getUUID().equals(player.getUniqueId())) {
cooldownStorage.get(cooldownType).remove(cooldownPlayerList);
break;
}
}
}
}
public void setCooldownPlayer(CooldownType cooldownType) {
if (cooldownStorage.containsKey(cooldownType)) {
for (CooldownPlayer cooldownPlayerList : cooldownStorage.get(cooldownType)) {
setCooldownPlayer(cooldownType, Bukkit.getServer().getOfflinePlayer(cooldownPlayerList.getUUID()));
}
}
}
public void setCooldownPlayer(CooldownType cooldownType, OfflinePlayer player) {
if (cooldownStorage.containsKey(cooldownType)) {
for (CooldownPlayer cooldownPlayerList : cooldownStorage.get(cooldownType)) {
if (cooldownPlayerList.getUUID().equals(player.getUniqueId())) {
if (cooldownType == CooldownType.Biome || cooldownType == CooldownType.Creation) {
skyblock.getFileManager()
.getConfig(new File(new File(skyblock.getDataFolder().toString() + "/player-data"),
player.getUniqueId().toString() + ".yml"))
.getFileConfiguration().set("Island." + cooldownType + ".Cooldown",
cooldownPlayerList.getCooldown().getTime());
} else if (cooldownType == CooldownType.Levelling || cooldownType == CooldownType.Ownership) {
skyblock.getFileManager()
.getConfig(new File(new File(skyblock.getDataFolder().toString() + "/island-data"),
player.getUniqueId().toString() + ".yml"))
.getFileConfiguration()
.set(cooldownType.name() + ".Cooldown", cooldownPlayerList.getCooldown().getTime());
}
break;
}
}
}
}
public void saveCooldownPlayer(CooldownType cooldownType) {
if (cooldownStorage.containsKey(cooldownType)) {
for (CooldownPlayer cooldownPlayerList : cooldownStorage.get(cooldownType)) {
saveCooldownPlayer(cooldownType, Bukkit.getServer().getOfflinePlayer(cooldownPlayerList.getUUID()));
}
}
}
public void saveCooldownPlayer(CooldownType cooldownType, OfflinePlayer player) {
Config config = null;
if (cooldownType == CooldownType.Biome || cooldownType == CooldownType.Creation) {
config = skyblock.getFileManager()
.getConfig(new File(new File(skyblock.getDataFolder().toString() + "/player-data"),
player.getUniqueId().toString() + ".yml"));
} else if (cooldownType == CooldownType.Levelling || cooldownType == CooldownType.Ownership) {
config = skyblock.getFileManager()
.getConfig(new File(new File(skyblock.getDataFolder().toString() + "/island-data"),
player.getUniqueId().toString() + ".yml"));
}
if (config != null) {
try {
config.getFileConfiguration().save(config.getFile());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void addCooldownPlayer(CooldownType cooldownType, CooldownPlayer cooldownPlayer) {
if (cooldownType != null && cooldownPlayer != null) {
if (cooldownStorage.containsKey(cooldownType)) {
cooldownStorage.get(cooldownType).add(cooldownPlayer);
}
}
}
public CooldownPlayer getCooldownPlayer(CooldownType cooldownType, OfflinePlayer player) {
if (cooldownStorage.containsKey(cooldownType)) {
for (CooldownPlayer cooldownPlayerList : cooldownStorage.get(cooldownType)) {
if (cooldownPlayerList.getUUID().equals(player.getUniqueId())) {
return cooldownPlayerList;
}
}
}
return null;
}
public List<CooldownPlayer> getCooldownPlayers(CooldownType cooldownType) {
if (cooldownStorage.containsKey(cooldownType)) {
return cooldownStorage.get(cooldownType);
}
return null;
}
public boolean hasCooldownType(CooldownType cooldownType) {
return cooldownStorage.containsKey(cooldownType);
}
}

View File

@ -1,36 +0,0 @@
package com.songoda.skyblock.cooldown;
import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.List;
public class CooldownTask extends BukkitRunnable {
private final CooldownManager cooldownManager;
public CooldownTask(CooldownManager cooldownManager) {
this.cooldownManager = cooldownManager;
}
@Override
public void run() {
for (CooldownType cooldownTypeList : CooldownType.values()) {
if (cooldownManager.hasCooldownType(cooldownTypeList)) {
List<CooldownPlayer> cooldownPlayers = cooldownManager.getCooldownPlayers(cooldownTypeList);
for (int i = 0; i < cooldownPlayers.size(); i++) {
CooldownPlayer cooldownPlayer = cooldownPlayers.get(i);
Cooldown cooldown = cooldownPlayer.getCooldown();
cooldown.setTime(cooldown.getTime() - 1);
if (cooldown.getTime() <= 0) {
cooldownManager.deletePlayer(cooldownTypeList,
Bukkit.getServer().getOfflinePlayer(cooldownPlayer.getUUID()));
}
}
}
}
}
}

View File

@ -1,7 +0,0 @@
package com.songoda.skyblock.cooldown;
public enum CooldownType {
Biome, Creation, Levelling, Ownership, Teleport
}

View File

@ -1,7 +0,0 @@
package com.songoda.skyblock.island;
public enum IslandRole {
Coop, Visitor, Member, Operator, Owner
}

View File

@ -1,115 +0,0 @@
package com.songoda.skyblock.limit;
import com.songoda.skyblock.SkyBlock;
import com.songoda.skyblock.island.Island;
import com.songoda.skyblock.island.IslandManager;
import com.songoda.skyblock.utils.version.Materials;
import org.bukkit.block.Block;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachmentInfo;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class LimitManager {
private final SkyBlock skyblock;
private Map<Materials, Long> blockLimits;
public LimitManager(SkyBlock skyblock) {
this.skyblock = skyblock;
this.blockLimits = new HashMap<>();
this.reload();
}
public void reload() {
this.blockLimits.clear();
FileConfiguration limitsConfig = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "limits.yml")).getFileConfiguration();
ConfigurationSection blockLimitSection = limitsConfig.getConfigurationSection("block");
if (blockLimitSection != null) {
for (String materialString : blockLimitSection.getKeys(false)) {
Materials material = Materials.fromString(materialString);
if (material != null) {
long limit = blockLimitSection.getLong(materialString);
this.blockLimits.put(material, limit);
}
}
}
}
/**
* Gets the max number of a type of block a player can place
*
* @param player The player to check
* @param block The block to check
* @return The max number of the type of block the player can place
*/
public long getBlockLimit(Player player, Block block) {
if (player == null || block == null)
return -1;
if (player.hasPermission("fabledskyblock.limit.block.*"))
return -1;
Materials material = Materials.getMaterials(block.getType(), block.getData());
if (material == null)
return -1;
long limit = -1;
if (this.blockLimits.containsKey(material))
limit = Math.max(limit, this.blockLimits.get(material));
Set<PermissionAttachmentInfo> permissions = player.getEffectivePermissions()
.stream()
.filter(x -> x.getPermission().toLowerCase().startsWith("fabledskyblock.limit.block." + material.name().toLowerCase()))
.collect(Collectors.toSet());
for (PermissionAttachmentInfo permission : permissions) {
try {
String permString = permission.getPermission();
String numberString = permString.substring(permString.lastIndexOf(".") + 1);
if (numberString.equals("*"))
return -1;
limit = Math.max(limit, Integer.parseInt(numberString));
} catch (Exception ignored) {
}
}
return limit;
}
/**
* Checks if a player has exceeded the number of blocks they can place
*
* @param player The player to check
* @param block The block to check
* @return true if the player has exceeded the block limit, otherwise false
*/
public boolean isBlockLimitExceeded(Player player, Block block) {
IslandManager islandManager = this.skyblock.getIslandManager();
long limit = this.getBlockLimit(player, block);
if (limit == -1)
return false;
Island island = islandManager.getIslandAtLocation(block.getLocation());
long totalPlaced;
if (block.getType() == Materials.SPAWNER.parseMaterial()) {
totalPlaced = island.getLevel().getMaterials().entrySet().stream().filter(x -> x.getKey().contains("SPAWNER")).mapToLong(Map.Entry::getValue).sum();
} else {
totalPlaced = island.getLevel().getMaterialAmount(Materials.getMaterials(block.getType(), block.getData()).name());
}
return limit < totalPlaced + 1;
}
}

View File

@ -1,734 +0,0 @@
package com.songoda.skyblock.listeners;
import com.songoda.skyblock.SkyBlock;
import com.songoda.skyblock.config.FileManager.Config;
import com.songoda.skyblock.generator.Generator;
import com.songoda.skyblock.generator.GeneratorManager;
import com.songoda.skyblock.island.*;
import com.songoda.skyblock.levelling.LevellingManager;
import com.songoda.skyblock.limit.LimitManager;
import com.songoda.skyblock.stackable.Stackable;
import com.songoda.skyblock.stackable.StackableManager;
import com.songoda.skyblock.upgrade.Upgrade;
import com.songoda.skyblock.utils.NumberUtil;
import com.songoda.skyblock.utils.version.Materials;
import com.songoda.skyblock.utils.version.NMSUtil;
import com.songoda.skyblock.utils.version.Sounds;
import com.songoda.skyblock.utils.world.LocationUtil;
import com.songoda.skyblock.world.WorldManager;
import org.apache.commons.lang3.text.WordUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.CreatureSpawner;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.*;
import org.bukkit.event.world.PortalCreateEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.Crops;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class Block implements Listener {
private final SkyBlock skyblock;
public Block(SkyBlock skyblock) {
this.skyblock = skyblock;
}
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOW)
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
org.bukkit.block.Block block = event.getBlock();
IslandManager islandManager = skyblock.getIslandManager();
StackableManager stackableManager = skyblock.getStackableManager();
WorldManager worldManager = skyblock.getWorldManager();
if (!worldManager.isIslandWorld(block.getWorld())) return;
IslandWorld world = worldManager.getIslandWorld(block.getWorld());
Island island = islandManager.getIslandAtLocation(block.getLocation());
if (island == null) {
event.setCancelled(true);
return;
}
if (!islandManager.hasPermission(player, block.getLocation(), "Destroy")) {
event.setCancelled(true);
skyblock.getMessageManager().sendMessage(player,
skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml"))
.getFileConfiguration().getString("Island.Settings.Permission.Message"));
skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F);
return;
}
if (stackableManager != null
&& stackableManager.isStacked(block.getLocation())) {
Stackable stackable = stackableManager.getStack(block.getLocation(), block.getType());
if (stackable != null) {
Material material = block.getType();
byte data = block.getData();
int droppedAmount = 0;
if (event.getPlayer().isSneaking()) {
Location dropLoc = event.getBlock().getLocation().clone().add(0.5, 0.5, 0.5);
int count = stackable.getSize();
droppedAmount = count;
while (count > 64) {
dropLoc.getWorld().dropItemNaturally(dropLoc, new ItemStack(material, 64, data));
count -= 64;
}
dropLoc.getWorld().dropItemNaturally(dropLoc, new ItemStack(material, count, block.getData()));
block.setType(Material.AIR);
stackable.setSize(0);
} else {
block.getWorld().dropItemNaturally(block.getLocation().clone().add(.5, 1, .5), new ItemStack(material, 1, data));
stackable.takeOne();
droppedAmount = 1;
}
if (stackable.getSize() <= 1) {
stackableManager.removeStack(stackable);
}
Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml"));
FileConfiguration configLoad = config.getFileConfiguration();
if (configLoad.getBoolean("Island.Block.Level.Enable")) {
Materials materials = Materials.getMaterials(material, data);
if (materials != null) {
IslandLevel level = island.getLevel();
if (level.hasMaterial(materials.name())) {
long materialAmount = level.getMaterialAmount(materials.name());
if (materialAmount - droppedAmount <= 0) {
level.removeMaterial(materials.name());
} else {
level.setMaterialAmount(materials.name(), materialAmount - droppedAmount);
}
}
}
}
event.setCancelled(true);
}
}
Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml"));
FileConfiguration configLoad = config.getFileConfiguration();
if (LocationUtil.isLocationLocation(block.getLocation(), island.getLocation(world, IslandEnvironment.Main).clone().subtract(0.0D, 1.0D, 0.0D))
|| LocationUtil.isLocationLocation(block.getLocation(), island.getLocation(world, IslandEnvironment.Main).clone())) {
if (configLoad.getBoolean("Island.Spawn.Protection")) {
event.setCancelled(true);
skyblock.getMessageManager().sendMessage(player,
skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml"))
.getFileConfiguration().getString("Island.SpawnProtection.Break.Message"));
skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F);
}
}
if (event.isCancelled() || !configLoad.getBoolean("Island.Block.Level.Enable")) return;
Materials materials = Materials.getMaterials(block.getType(), block.getData());
if (materials == null) return;
IslandLevel level = island.getLevel();
if (!level.hasMaterial(materials.name())) return;
long materialAmount = level.getMaterialAmount(materials.name());
if (materialAmount - 1 <= 0) {
level.removeMaterial(materials.name());
} else {
level.setMaterialAmount(materials.name(), materialAmount - 1);
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
org.bukkit.block.Block block = event.getBlock();
IslandManager islandManager = skyblock.getIslandManager();
WorldManager worldManager = skyblock.getWorldManager();
LevellingManager levellingManager = skyblock.getLevellingManager();
if (!worldManager.isIslandWorld(block.getWorld())) return;
IslandWorld world = worldManager.getIslandWorld(block.getWorld());
Island island = islandManager.getIslandAtLocation(block.getLocation());
if (island == null) {
event.setCancelled(true);
return;
}
if (levellingManager.isIslandLevelBeingScanned(island)) {
skyblock.getMessageManager().sendMessage(player,
skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml"))
.getFileConfiguration().getString("Command.Island.Level.Scanning.BlockPlacing.Message"));
event.setCancelled(true);
return;
}
if (!islandManager.hasPermission(player, block.getLocation(), "Place")) {
event.setCancelled(true);
skyblock.getMessageManager().sendMessage(player,
skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml"))
.getFileConfiguration().getString("Island.Settings.Permission.Message"));
skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F);
return;
}
Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml"));
FileConfiguration configLoad = config.getFileConfiguration();
if (configLoad.getBoolean("Island.WorldBorder.Block") && block.getType() == Material.DISPENSER) {
if (!islandManager.isLocationAtIsland(island, block.getLocation(), world)) {
event.setCancelled(true);
}
}
// Check spawn protection
if (configLoad.getBoolean("Island.Spawn.Protection")) {
boolean isObstructing = false;
// Directly on the block
if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) {
isObstructing = true;
}
// Specific check for beds
if (!isObstructing && event.getBlock().getState().getData() instanceof org.bukkit.material.Bed) {
BlockFace bedDirection = ((org.bukkit.material.Bed) event.getBlock().getState().getData()).getFacing();
org.bukkit.block.Block bedBlock = block.getRelative(bedDirection);
if (LocationUtil.isLocationAffectingIslandSpawn(bedBlock.getLocation(), island, world))
isObstructing = true;
}
if (isObstructing) {
skyblock.getMessageManager().sendMessage(player,
skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml"))
.getFileConfiguration().getString("Island.SpawnProtection.Place.Message"));
skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F);
event.setCancelled(true);
return;
}
}
LimitManager limitManager = skyblock.getLimitManager();
if (limitManager.isBlockLimitExceeded(player, block)) {
Materials material = Materials.getMaterials(block.getType(), block.getData());
skyblock.getMessageManager().sendMessage(player,
skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml"))
.getFileConfiguration().getString("Island.Limit.Block.Exceeded.Message")
.replace("%type", WordUtils.capitalizeFully(material.name().replace("_", " ")))
.replace("%limit", NumberUtil.formatNumber(limitManager.getBlockLimit(player, block))));
skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F);
event.setCancelled(true);
return;
}
if (!configLoad.getBoolean("Island.Block.Level.Enable"))
return;
// Fix a bug in Paper 1.8.8 when using ViaVersion on a 1.12.2 client.
// BUG: Player can infinitely increase their level by placing a block at their feet.
// It doesn't take the block away but still increments the level.
// This doesn't happen in Spigot, but does happen in PaperSpigot due to a BlockPlaceEvent being incorrectly fired.
// The solution is to wait a tick to make sure that the block was actually placed.
// This shouldn't cause any issues besides the task number being increased insanely fast.
Bukkit.getScheduler().runTask(skyblock, () -> {
@SuppressWarnings("deprecation")
Materials materials = Materials.getMaterials(block.getType(), block.getData());
if (materials == null || materials == Materials.AIR)
return;
if (materials.equals(Materials.SPAWNER)) {
if (Bukkit.getPluginManager().isPluginEnabled("EpicSpawners") || Bukkit.getPluginManager().isPluginEnabled("WildStacker"))
return;
CreatureSpawner creatureSpawner = (CreatureSpawner) block.getState();
EntityType spawnerType = creatureSpawner.getSpawnedType();
materials = Materials.getSpawner(spawnerType);
}
long materialAmount = 0;
IslandLevel level = island.getLevel();
if (level.hasMaterial(materials.name())) {
materialAmount = level.getMaterialAmount(materials.name());
}
level.setMaterialAmount(materials.name(), materialAmount + 1);
});
}
@EventHandler
public void onBlockFromTo(BlockFromToEvent event) {
if (!skyblock.getWorldManager().isIslandWorld(event.getBlock().getWorld())) return;
GeneratorManager generatorManager = skyblock.getGeneratorManager();
IslandManager islandManager = skyblock.getIslandManager();
WorldManager worldManager = skyblock.getWorldManager();
Island island = islandManager.getIslandAtLocation(event.getBlock().getLocation());
IslandWorld world = worldManager.getIslandWorld(event.getBlock().getWorld());
Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml"));
FileConfiguration configLoad = config.getFileConfiguration();
if (island == null) return;
org.bukkit.block.Block block = event.getToBlock();
// Protect outside of border
if (!islandManager.isLocationAtIsland(island, block.getLocation(), world)) {
event.setCancelled(true);
return;
}
// Protect spawn
if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world) && configLoad.getBoolean("Island.Spawn.Protection")) {
event.setCancelled(true);
return;
}
if (NMSUtil.getVersionNumber() < 12) {
if (generatorManager != null && generatorManager.getGenerators().size() > 0 && generatorManager.isGenerator(block)) {
List<Generator> generators = new ArrayList<>(generatorManager.getGenerators());
Collections.reverse(generators); // Use the highest generator available
// Filter valid players on the island
Set<Player> possiblePlayers = new HashSet<>();
for (Player p : Bukkit.getOnlinePlayers()) {
boolean isMember = island.hasRole(IslandRole.Owner, p.getUniqueId()) ||
island.hasRole(IslandRole.Member, p.getUniqueId()) ||
island.hasRole(IslandRole.Coop, p.getUniqueId()) ||
island.hasRole(IslandRole.Operator, p.getUniqueId());
if (isMember && islandManager.isLocationAtIsland(island, p.getLocation(), world)) {
possiblePlayers.add(p);
}
}
// Find highest generator available
for (Generator generator : generators) {
for (Player p : possiblePlayers) {
if (generator.isPermission()) {
if (!p.hasPermission(generator.getPermission())
&& !p.hasPermission("fabledskyblock.generator.*")
&& !p.hasPermission("fabledskyblock.*")) {
continue;
}
}
org.bukkit.block.BlockState genState = generatorManager.generateBlock(generator, block);
event.getToBlock().getState().setType(genState.getType());
event.getToBlock().getState().setData(genState.getData());
return;
}
}
}
}
}
@EventHandler
public void onBlockPistonExtend(BlockPistonExtendEvent event) {
if (!skyblock.getWorldManager().isIslandWorld(event.getBlock().getWorld())) return;
IslandManager islandManager = skyblock.getIslandManager();
WorldManager worldManager = skyblock.getWorldManager();
Island island = islandManager.getIslandAtLocation(event.getBlock().getLocation());
if (island == null) return;
IslandWorld world = worldManager.getIslandWorld(event.getBlock().getWorld());
Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml"));
FileConfiguration configLoad = config.getFileConfiguration();
for (org.bukkit.block.Block block : event.getBlocks()) {
if (!islandManager.isLocationAtIsland(island, block.getLocation(), world) || !islandManager.isLocationAtIsland(island, block.getRelative(event.getDirection()).getLocation(), world)) {
event.setCancelled(true);
return;
}
if (skyblock.getStackableManager() != null && skyblock.getStackableManager().isStacked(block.getLocation())) {
event.setCancelled(true);
return;
}
if (configLoad.getBoolean("Island.Spawn.Protection")) {
// Check exact block
if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) {
event.setCancelled(true);
return;
}
// Check block in direction
if (LocationUtil.isLocationAffectingIslandSpawn(block.getRelative(event.getDirection()).getLocation(), island, world)) {
event.setCancelled(true);
return;
}
}
if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Block.Piston.Connected.Extend")) {
if (block.getType() == Materials.PISTON.parseMaterial() || block.getType() == Materials.STICKY_PISTON.parseMaterial()) {
event.setCancelled(true);
return;
}
}
}
// Check piston head
if (configLoad.getBoolean("Island.Spawn.Protection")) {
if (LocationUtil.isLocationAffectingIslandSpawn(event.getBlock().getRelative(event.getDirection()).getLocation(), island, world)) {
event.setCancelled(true);
}
}
}
@EventHandler
public void onBlockPistonRetract(BlockPistonRetractEvent event) {
if (!skyblock.getWorldManager().isIslandWorld(event.getBlock().getWorld())) return;
IslandManager islandManager = skyblock.getIslandManager();
WorldManager worldManager = skyblock.getWorldManager();
Island island = islandManager.getIslandAtLocation(event.getBlock().getLocation());
if (island == null) return;
IslandWorld world = worldManager.getIslandWorld(event.getBlock().getWorld());
Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml"));
FileConfiguration configLoad = config.getFileConfiguration();
for (org.bukkit.block.Block block : event.getBlocks()) {
if (!islandManager.isLocationAtIsland(island, block.getLocation(), world)) {
event.setCancelled(true);
return;
}
if (skyblock.getStackableManager() != null && skyblock.getStackableManager().isStacked(block.getLocation())) {
event.setCancelled(true);
return;
}
if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world) && configLoad.getBoolean("Island.Spawn.Protection")) {
event.setCancelled(true);
return;
}
if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Block.Piston.Connected.Retract")) {
if (block.getType() == Materials.PISTON.parseMaterial() || block.getType() == Materials.STICKY_PISTON.parseMaterial()) {
event.setCancelled(true);
return;
}
}
}
}
@EventHandler
public void onBlockForm(BlockFormEvent event) {
org.bukkit.block.Block block = event.getBlock();
IslandManager islandManager = skyblock.getIslandManager();
GeneratorManager generatorManager = skyblock.getGeneratorManager();
WorldManager worldManager = skyblock.getWorldManager();
if (!worldManager.isIslandWorld(block.getWorld())) return;
Island island = islandManager.getIslandAtLocation(event.getBlock().getLocation());
if (island == null) return;
// Check ice/snow forming
if (block.getType() == Material.ICE || block.getType() == Material.SNOW) {
if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Weather.IceAndSnow")) {
event.setCancelled(true);
}
return;
}
// Check spawn block protection
IslandWorld world = worldManager.getIslandWorld(event.getBlock().getWorld());
if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) {
if (skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Spawn.Protection")) {
event.setCancelled(true);
return;
}
}
Material material = event.getBlock().getType();
if (material != Materials.WATER.parseMaterial() &&
material != Materials.LEGACY_STATIONARY_WATER.parseMaterial() &&
material != Materials.LAVA.parseMaterial() &&
material != Materials.LEGACY_STATIONARY_LAVA.parseMaterial())
return;
Material type = event.getNewState().getType();
if (type != Material.COBBLESTONE && type != Material.STONE)
return;
if (generatorManager != null && generatorManager.getGenerators().size() > 0) {
List<Generator> generators = new ArrayList<>(generatorManager.getGenerators());
Collections.reverse(generators); // Use the highest generator available
// Filter valid players on the island
Set<Player> possiblePlayers = new HashSet<>();
for (Player player : Bukkit.getOnlinePlayers()) {
boolean isMember = island.hasRole(IslandRole.Owner, player.getUniqueId()) ||
island.hasRole(IslandRole.Member, player.getUniqueId()) ||
island.hasRole(IslandRole.Coop, player.getUniqueId()) ||
island.hasRole(IslandRole.Operator, player.getUniqueId());
if (isMember && islandManager.isLocationAtIsland(island, player.getLocation(), world)) {
possiblePlayers.add(player);
}
}
// Find highest generator available
for (Generator generator : generators) {
for (Player player : possiblePlayers) {
if (generator.isPermission()) {
if (!player.hasPermission(generator.getPermission())
&& !player.hasPermission("fabledskyblock.generator.*")
&& !player.hasPermission("fabledskyblock.*")) {
continue;
}
}
org.bukkit.block.BlockState genState = generatorManager.generateBlock(generator, block);
event.getNewState().setType(genState.getType());
if (NMSUtil.getVersionNumber() < 13) {
event.getNewState().setData(genState.getData());
}
return;
}
}
}
}
@EventHandler
public void onBlockBurn(BlockBurnEvent event) {
org.bukkit.block.Block block = event.getBlock();
WorldManager worldManager = skyblock.getWorldManager();
if (worldManager.isIslandWorld(block.getWorld())) {
if (!skyblock.getIslandManager().hasSetting(block.getLocation(), IslandRole.Owner, "FireSpread")) {
event.setCancelled(true);
}
}
}
@EventHandler
public void onBlockSpread(BlockSpreadEvent event) {
org.bukkit.block.Block block = event.getBlock();
WorldManager worldManager = skyblock.getWorldManager();
if (event.getSource().getType() != Material.FIRE) {
return;
}
if (worldManager.isIslandWorld(block.getWorld())) {
if (!skyblock.getIslandManager().hasSetting(block.getLocation(), IslandRole.Owner, "FireSpread")) {
event.setCancelled(true);
}
}
}
@SuppressWarnings("deprecation")
@EventHandler
public void onBlockGrow(BlockGrowEvent event) {
org.bukkit.block.Block block = event.getBlock();
WorldManager worldManager = skyblock.getWorldManager();
IslandManager islandManager = skyblock.getIslandManager();
if (!skyblock.getWorldManager().isIslandWorld(block.getWorld())) return;
Island island = islandManager.getIslandAtLocation(block.getLocation());
if (island == null) return;
// Check spawn block protection
IslandWorld world = worldManager.getIslandWorld(event.getBlock().getWorld());
if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) {
if (skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Spawn.Protection")) {
event.setCancelled(true);
return;
}
}
List<Upgrade> upgrades = skyblock.getUpgradeManager().getUpgrades(Upgrade.Type.Crop);
if (upgrades != null && upgrades.size() > 0 && upgrades.get(0).isEnabled()
&& island.isUpgrade(Upgrade.Type.Crop)) {
if (NMSUtil.getVersionNumber() > 12) {
try {
Object blockData = block.getClass().getMethod("getBlockData").invoke(block);
if (blockData instanceof org.bukkit.block.data.Ageable) {
org.bukkit.block.data.Ageable ageable = (org.bukkit.block.data.Ageable) blockData;
ageable.setAge(ageable.getAge() + 1);
block.getClass()
.getMethod("setBlockData", Class.forName("org.bukkit.block.data.BlockData"))
.invoke(block, ageable);
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException | ClassNotFoundException e) {
e.printStackTrace();
}
} else {
if (block.getState().getData() instanceof Crops
|| block.getType().name().equals("BEETROOT_BLOCK")
|| block.getType().name().equals("CARROT")
|| block.getType().name().equals("POTATO")
|| block.getType().name().equals("CROPS")) {
try {
block.getClass().getMethod("setData", byte.class).invoke(block, (byte) (block.getData() + 1));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
}
}
}
}
@EventHandler
public void onLeavesDecay(LeavesDecayEvent event) {
org.bukkit.block.Block block = event.getBlock();
if (skyblock.getWorldManager().isIslandWorld(block.getWorld())) {
if (!skyblock.getIslandManager().hasSetting(block.getLocation(), IslandRole.Owner, "LeafDecay")) {
event.setCancelled(true);
}
}
}
@EventHandler
public void onStructureCreate(StructureGrowEvent event) {
WorldManager worldManager = skyblock.getWorldManager();
IslandManager islandManager = skyblock.getIslandManager();
if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Spawn.Protection"))
return;
if (event.getBlocks().isEmpty())
return;
Island island = islandManager.getIslandAtLocation(event.getLocation());
if (island == null)
return;
// Check spawn block protection
IslandWorld world = worldManager.getIslandWorld(event.getBlocks().get(0).getWorld());
Location islandLocation = island.getLocation(world, IslandEnvironment.Main);
for (org.bukkit.block.BlockState block : event.getBlocks()) {
if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) {
event.setCancelled(true);
return;
}
}
}
@EventHandler
public void onPortalCreate(PortalCreateEvent event) {
WorldManager worldManager = skyblock.getWorldManager();
IslandManager islandManager = skyblock.getIslandManager();
if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Spawn.Protection"))
return;
// PortalCreateEvent.getBlocks() changed from ArrayList<Block> to ArrayList<BlockState> in 1.14.1... why...
if (NMSUtil.getVersionNumber() > 13) {
List<BlockState> blocks = event.getBlocks();
if (event.getBlocks().isEmpty())
return;
Island island = islandManager.getIslandAtLocation(event.getBlocks().get(0).getLocation());
if (island == null)
return;
// Check spawn block protection
IslandWorld world = worldManager.getIslandWorld(event.getBlocks().get(0).getWorld());
for (BlockState block : blocks) {
if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) {
event.setCancelled(true);
return;
}
}
} else {
try {
@SuppressWarnings("unchecked")
List<org.bukkit.block.Block> blocks = (List<org.bukkit.block.Block>) event.getClass().getMethod("getBlocks").invoke(event);
if (blocks.isEmpty())
return;
Island island = islandManager.getIslandAtLocation(blocks.get(0).getLocation());
if (island == null)
return;
// Check spawn block protection
IslandWorld world = worldManager.getIslandWorld(blocks.get(0).getWorld());
for (org.bukkit.block.Block block : blocks) {
if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) {
event.setCancelled(true);
return;
}
}
} catch (ReflectiveOperationException ex) {
ex.printStackTrace();
}
}
}
@EventHandler
public void onDispenserDispenseBlock(BlockDispenseEvent event) {
WorldManager worldManager = skyblock.getWorldManager();
IslandManager islandManager = skyblock.getIslandManager();
if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Spawn.Protection"))
return;
BlockFace dispenserDirection = ((org.bukkit.material.Dispenser) event.getBlock().getState().getData()).getFacing();
org.bukkit.block.Block placeLocation = event.getBlock().getRelative(dispenserDirection);
Island island = islandManager.getIslandAtLocation(placeLocation.getLocation());
if (island == null)
return;
// Check spawn block protection
IslandWorld world = worldManager.getIslandWorld(placeLocation.getWorld());
if (LocationUtil.isLocationAffectingIslandSpawn(placeLocation.getLocation(), island, world)) {
event.setCancelled(true);
}
}
}

View File

@ -1,222 +0,0 @@
package com.songoda.skyblock.listeners;
import com.songoda.skyblock.SkyBlock;
import com.songoda.skyblock.config.FileManager;
import com.songoda.skyblock.config.FileManager.Config;
import com.songoda.skyblock.island.*;
import com.songoda.skyblock.message.MessageManager;
import com.songoda.skyblock.playerdata.PlayerData;
import com.songoda.skyblock.playerdata.PlayerDataManager;
import com.songoda.skyblock.sound.SoundManager;
import com.songoda.skyblock.utils.version.NMSUtil;
import com.songoda.skyblock.utils.version.Sounds;
import com.songoda.skyblock.utils.world.LocationUtil;
import com.songoda.skyblock.world.WorldManager;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.attribute.Attribute;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.potion.PotionEffect;
import java.io.File;
public class Move implements Listener {
private final SkyBlock skyblock;
public Move(SkyBlock skyblock) {
this.skyblock = skyblock;
}
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
Location from = event.getFrom();
Location to = event.getTo();
if (to == null || (from.getBlockX() == to.getBlockX() && from.getBlockY() == to.getBlockY() && from.getBlockZ() == to.getBlockZ())) {
return;
}
PlayerDataManager playerDataManager = skyblock.getPlayerDataManager();
MessageManager messageManager = skyblock.getMessageManager();
IslandManager islandManager = skyblock.getIslandManager();
SoundManager soundManager = skyblock.getSoundManager();
WorldManager worldManager = skyblock.getWorldManager();
FileManager fileManager = skyblock.getFileManager();
if (!worldManager.isIslandWorld(player.getWorld()))
return;
IslandWorld world = worldManager.getIslandWorld(player.getWorld());
if (world == IslandWorld.Nether || world == IslandWorld.End) {
if (!fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration()
.getBoolean("Island.World." + world.name() + ".Enable")) {
Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml"));
FileConfiguration configLoad = config.getFileConfiguration();
messageManager.sendMessage(player, configLoad.getString("Island.World.Message")
.replace(configLoad.getString("Island.World.Word." + world.name()), world.name()));
if (playerDataManager.hasPlayerData(player)) {
PlayerData playerData = playerDataManager.getPlayerData(player);
if (playerData.getIsland() != null) {
Island island = islandManager
.getIsland(Bukkit.getServer().getOfflinePlayer(playerData.getIsland()));
if (island != null) {
if (island.hasRole(IslandRole.Member, player.getUniqueId())
|| island.hasRole(IslandRole.Operator, player.getUniqueId())
|| island.hasRole(IslandRole.Owner, player.getUniqueId())) {
player.teleport(island.getLocation(IslandWorld.Normal, IslandEnvironment.Main));
} else {
player.teleport(island.getLocation(IslandWorld.Normal, IslandEnvironment.Visitor));
}
player.setFallDistance(0.0F);
soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F);
return;
}
}
}
LocationUtil.teleportPlayerToSpawn(player);
soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F);
}
}
if (playerDataManager.hasPlayerData(player)) {
PlayerData playerData = playerDataManager.getPlayerData(player);
if (playerData.getIsland() != null) {
Island island = islandManager
.getIsland(Bukkit.getServer().getOfflinePlayer(playerData.getIsland()));
if (island != null) {
if (islandManager.isLocationAtIsland(island, to)) {
Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml"));
FileConfiguration configLoad = config.getFileConfiguration();
boolean keepItemsOnDeath;
if (configLoad.getBoolean("Island.Settings.KeepItemsOnDeath.Enable")) {
keepItemsOnDeath = island.getSetting(IslandRole.Owner, "KeepItemsOnDeath").getStatus();
} else {
keepItemsOnDeath = configLoad.getBoolean("Island.KeepItemsOnDeath.Enable");
}
if (configLoad.getBoolean("Island.World." + world.name() + ".Liquid.Enable")) {
if (to.getY() <= configLoad.getInt("Island.World." + world.name() + ".Liquid.Height")) {
if (!configLoad.getBoolean("Island.Liquid.Teleport.Enable")) return;
if (keepItemsOnDeath) {
player.setFallDistance(0.0F);
if (island.hasRole(IslandRole.Member, player.getUniqueId())
|| island.hasRole(IslandRole.Operator, player.getUniqueId())
|| island.hasRole(IslandRole.Owner, player.getUniqueId())) {
player.teleport(
island.getLocation(IslandWorld.Normal, IslandEnvironment.Main));
} else {
player.teleport(
island.getLocation(IslandWorld.Normal, IslandEnvironment.Visitor));
}
player.setFallDistance(0.0F);
soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F,
1.0F);
}
return;
}
}
if (configLoad.getBoolean("Island.Void.Teleport.Enable")) {
if (to.getY() <= configLoad.getInt("Island.Void.Teleport.Offset")) {
if (!keepItemsOnDeath) {
player.getInventory().clear();
player.setLevel(0);
player.setExp(0.0F);
if (NMSUtil.getVersionNumber() > 8) {
player.setHealth(
player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue());
} else {
player.setHealth(player.getMaxHealth());
}
player.setFoodLevel(20);
for (PotionEffect potionEffect : player.getActivePotionEffects()) {
player.removePotionEffect(potionEffect.getType());
}
}
player.setFallDistance(0.0F);
if (configLoad.getBoolean("Island.Void.Teleport.Island")) {
if (island.hasRole(IslandRole.Member, player.getUniqueId())
|| island.hasRole(IslandRole.Operator, player.getUniqueId())
|| island.hasRole(IslandRole.Owner, player.getUniqueId())) {
player.teleport(
island.getLocation(IslandWorld.Normal, IslandEnvironment.Main));
} else {
player.teleport(
island.getLocation(IslandWorld.Normal, IslandEnvironment.Visitor));
}
} else {
LocationUtil.teleportPlayerToSpawn(player);
}
player.setFallDistance(0.0F);
soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F);
}
}
} else {
if (!LocationUtil.isLocationAtLocationRadius(island.getLocation(world, IslandEnvironment.Island), to, island.getRadius() + 0.5)) {
if (island.getVisit().isVisitor(player.getUniqueId())) {
player.teleport(island.getLocation(world, IslandEnvironment.Visitor));
} else {
player.teleport(island.getLocation(world, IslandEnvironment.Main));
}
player.setFallDistance(0.0F);
messageManager.sendMessage(player, skyblock.getFileManager()
.getConfig(new File(skyblock.getDataFolder(), "language.yml"))
.getFileConfiguration().getString("Island.WorldBorder.Outside.Message"));
soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F);
}
}
return;
}
}
// Load the island they are now on if one exists
if (player.hasPermission("fabledskyblock.bypass")
|| islandManager.getIslandAtLocation(player.getLocation()).isAlwaysLoaded()) {
Island loadedIsland = islandManager.loadIslandAtLocation(player.getLocation());
if (loadedIsland != null) {
playerData.setIsland(loadedIsland.getOwnerUUID());
return;
}
}
LocationUtil.teleportPlayerToSpawn(player);
messageManager.sendMessage(player,
skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml"))
.getFileConfiguration().getString("Island.WorldBorder.Disappeared.Message"));
soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F);
}
}
}

View File

@ -1,58 +0,0 @@
package com.songoda.skyblock.listeners;
import com.songoda.skyblock.SkyBlock;
import com.songoda.skyblock.message.MessageManager;
import com.songoda.skyblock.sound.SoundManager;
import com.songoda.skyblock.utils.version.Sounds;
import org.bukkit.entity.FishHook;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import java.io.File;
public class Projectile implements Listener {
private final SkyBlock skyblock;
public Projectile(SkyBlock skyblock) {
this.skyblock = skyblock;
}
@EventHandler
public void onProjectileLaunch(ProjectileLaunchEvent event) {
if (!(event.getEntity().getShooter() instanceof Player)) {
return;
}
Player player = (Player) event.getEntity().getShooter();
MessageManager messageManager = skyblock.getMessageManager();
SoundManager soundManager = skyblock.getSoundManager();
if (skyblock.getWorldManager().isIslandWorld(player.getWorld())) {
if (event.getEntity() instanceof FishHook) {
if (!skyblock.getIslandManager().hasPermission(player, "Fishing")) {
event.setCancelled(true);
messageManager.sendMessage(player,
skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml"))
.getFileConfiguration().getString("Island.Settings.Permission.Message"));
soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F);
}
return;
}
if (!skyblock.getIslandManager().hasPermission(player, "Projectile")) {
event.setCancelled(true);
messageManager.sendMessage(player,
skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml"))
.getFileConfiguration().getString("Island.Settings.Permission.Message"));
soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F);
}
}
}
}

View File

@ -1,36 +0,0 @@
package com.songoda.skyblock.utils;
import org.apache.commons.io.IOUtils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public final class GZipUtil {
public static byte[] compress(byte[] data) throws IOException {
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(data);
gzip.flush();
gzip.close();
return obj.toByteArray();
}
public static byte[] decompress(final byte[] compressedData) throws IOException {
if (isCompressed(compressedData)) {
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(compressedData));
return IOUtils.toByteArray(gis);
}
return new byte[512];
}
public static boolean isCompressed(final byte[] compressedData) {
return (compressedData[0] == (byte) (GZIPInputStream.GZIP_MAGIC))
&& (compressedData[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}
}

View File

@ -1,692 +0,0 @@
package com.songoda.skyblock.utils;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Metrics {
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Should failed requests be logged?
private static boolean logFailedRequests;
// Should the sent data be logged?
private static boolean logSentData;
// Should the response text be logged?
private static boolean logResponseStatusText;
// The uuid of the server
private static String serverUUID;
static {
// You can use the property to disable the check in your test environment
if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) {
// Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D
final String defaultPackage = new String(
new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'});
final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});
// We want to make sure nobody just copy & pastes the example and use the wrong package names
if (Metrics.class.getPackage().getName().equals(defaultPackage) || Metrics.class.getPackage().getName().equals(examplePackage)) {
throw new IllegalStateException("bStats Metrics class has not been relocated correctly!");
}
}
}
// The plugin
private final Plugin plugin;
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
// Is bStats enabled on this server?
private boolean enabled;
/**
* Class constructor.
*
* @param plugin The plugin which stats should be submitted.
*/
public Metrics(Plugin plugin) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null!");
}
this.plugin = plugin;
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Should the sent data be logged?
config.addDefault("logSentData", false);
// Should the response text be logged?
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) {
}
}
// Load the data
enabled = config.getBoolean("enabled", true);
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
if (enabled) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) {
}
}
// Register our service
Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal);
if (!found) {
// We are the first!
startSubmitting();
}
}
}
/**
* Sends the data to the bStats server.
*
* @param plugin Any plugin. It's just used to get a logger instance.
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(Plugin plugin, JSONObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
if (logSentData) {
plugin.getLogger().info("Sending data to bStats: " + data.toString());
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
if (logResponseStatusText) {
plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
}
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return null;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes(StandardCharsets.UTF_8));
gzip.close();
return outputStream.toByteArray();
}
/**
* Checks if bStats is enabled.
*
* @return Whether bStats is enabled or not.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Adds a custom chart.
*
* @param chart The chart to add.
*/
public void addCustomChart(CustomChart chart) {
if (chart == null) {
throw new IllegalArgumentException("Chart cannot be null!");
}
charts.add(chart);
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000 * 60 * 5, 1000 * 60 * 30);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JSONObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.put("customCharts", customCharts);
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JSONObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JSONObject data = new JSONObject();
data.put("serverUUID", serverUUID);
data.put("playerAmount", playerAmount);
data.put("onlineMode", onlineMode);
data.put("bukkitVersion", bukkitVersion);
data.put("javaVersion", javaVersion);
data.put("osName", osName);
data.put("osArch", osArch);
data.put("osVersion", osVersion);
data.put("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JSONObject data = getServerData();
JSONArray pluginData = new JSONArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider()));
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
}
}
} catch (NoSuchFieldException ignored) {
}
}
data.put("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}
}).start();
}
/**
* Represents a custom chart.
*/
public static abstract class CustomChart {
// The id of the chart
final String chartId;
/**
* Class constructor.
*
* @param chartId The id of the chart.
*/
CustomChart(String chartId) {
if (chartId == null || chartId.isEmpty()) {
throw new IllegalArgumentException("ChartId cannot be null or empty!");
}
this.chartId = chartId;
}
private JSONObject getRequestJsonObject() {
JSONObject chart = new JSONObject();
chart.put("chartId", chartId);
try {
JSONObject data = getChartData();
if (data == null) {
// If the data is null we don't send the chart.
return null;
}
chart.put("data", data);
} catch (Throwable t) {
if (logFailedRequests) {
Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
}
return null;
}
return chart;
}
protected abstract JSONObject getChartData() throws Exception;
}
/**
* Represents a custom simple pie.
*/
public static class SimplePie extends CustomChart {
private final Callable<String> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimplePie(String chartId, Callable<String> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
String value = callable.call();
if (value == null || value.isEmpty()) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom advanced pie.
*/
public static class AdvancedPie extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom drilldown pie.
*/
public static class DrilldownPie extends CustomChart {
private final Callable<Map<String, Map<String, Integer>>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {
super(chartId);
this.callable = callable;
}
@Override
public JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Map<String, Integer>> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean reallyAllSkipped = true;
for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {
JSONObject value = new JSONObject();
boolean allSkipped = true;
for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {
value.put(valueEntry.getKey(), valueEntry.getValue());
allSkipped = false;
}
if (!allSkipped) {
reallyAllSkipped = false;
values.put(entryValues.getKey(), value);
}
}
if (reallyAllSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom single line chart.
*/
public static class SingleLineChart extends CustomChart {
private final Callable<Integer> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SingleLineChart(String chartId, Callable<Integer> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
int value = callable.call();
if (value == 0) {
// Null = skip the chart
return null;
}
data.put("value", value);
return data;
}
}
/**
* Represents a custom multi line chart.
*/
public static class MultiLineChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() == 0) {
continue; // Skip this invalid
}
allSkipped = false;
values.put(entry.getKey(), entry.getValue());
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom simple bar chart.
*/
public static class SimpleBarChart extends CustomChart {
private final Callable<Map<String, Integer>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JSONArray categoryValues = new JSONArray();
categoryValues.add(entry.getValue());
values.put(entry.getKey(), categoryValues);
}
data.put("values", values);
return data;
}
}
/**
* Represents a custom advanced bar chart.
*/
public static class AdvancedBarChart extends CustomChart {
private final Callable<Map<String, int[]>> callable;
/**
* Class constructor.
*
* @param chartId The id of the chart.
* @param callable The callable which is used to request the chart data.
*/
public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {
super(chartId);
this.callable = callable;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, int[]> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
boolean allSkipped = true;
for (Map.Entry<String, int[]> entry : map.entrySet()) {
if (entry.getValue().length == 0) {
continue; // Skip this invalid
}
allSkipped = false;
JSONArray categoryValues = new JSONArray();
for (int categoryValue : entry.getValue()) {
categoryValues.add(categoryValue);
}
values.put(entry.getKey(), categoryValues);
}
if (allSkipped) {
// Null = skip the chart
return null;
}
data.put("values", values);
return data;
}
}
}

View File

@ -1,565 +0,0 @@
package com.songoda.skyblock.utils.world.block;
import com.songoda.skyblock.utils.item.ItemStackUtil;
import com.songoda.skyblock.utils.item.MaterialUtil;
import com.songoda.skyblock.utils.version.Materials;
import com.songoda.skyblock.utils.version.NMSUtil;
import org.bukkit.*;
import org.bukkit.block.*;
import org.bukkit.block.banner.Pattern;
import org.bukkit.block.banner.PatternType;
import org.bukkit.entity.EntityType;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.material.Stairs;
import org.bukkit.potion.PotionEffectType;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings("deprecation")
public final class BlockUtil {
public static BlockData convertBlockToBlockData(Block block, int x, int y, int z) {
BlockData blockData = new BlockData(block.getType().toString(), block.getData(), x, y, z,
block.getBiome().toString());
int NMSVersion = NMSUtil.getVersionNumber();
blockData.setVersion(NMSVersion);
if (NMSVersion > 12) {
blockData.setBlockData(block.getBlockData().getAsString());
}
BlockState blockState = block.getState();
MaterialData materialData = blockState.getData();
if (blockState instanceof Banner) {
Banner banner = (Banner) blockState;
blockData.setBaseColor(banner.getBaseColor().toString());
List<String> patterns = new ArrayList<>();
for (Pattern patternList : banner.getPatterns()) {
patterns.add(patternList.getPattern().toString() + ":" + patternList.getColor().toString());
}
blockData.setPatterns(patterns);
blockData.setStateType(BlockStateType.BANNER.toString());
} else if (blockState instanceof Beacon) {
Beacon beacon = (Beacon) blockState;
String primaryEffectName = beacon.getPrimaryEffect() != null ? beacon.getPrimaryEffect().toString() : "null";
String secondaryEffectName = beacon.getSecondaryEffect() != null ? beacon.getSecondaryEffect().toString() : "null";
blockData.setPotionEffect(primaryEffectName + ":" + secondaryEffectName);
blockData.setStateType(BlockStateType.BEACON.toString());
} else if (blockState instanceof BrewingStand) {
BrewingStand brewingStand = (BrewingStand) blockState;
blockData.setBrewingTime(brewingStand.getBrewingTime());
blockData.setFuelLevel(brewingStand.getFuelLevel());
blockData.setStateType(BlockStateType.BREWINGSTAND.toString());
} else if (blockState instanceof Furnace) {
Furnace furnace = (Furnace) blockState;
blockData.setBurnTime(furnace.getBurnTime());
blockData.setCookTime(furnace.getCookTime());
for (int i = 0; i < furnace.getInventory().getSize(); i++) {
ItemStack is = furnace.getInventory().getItem(i);
if (is != null && is.getType() != Material.AIR) {
blockData.addItem(i, ItemStackUtil.serializeItemStack(is));
}
}
blockData.setStateType(BlockStateType.FURNACE.toString());
} else if (blockState instanceof Chest) {
Chest chest = (Chest) blockState;
for (int i = 0; i < chest.getInventory().getSize(); i++) {
ItemStack is = chest.getInventory().getItem(i);
if (is != null && is.getType() != Material.AIR) {
blockData.addItem(i, ItemStackUtil.serializeItemStack(is));
}
}
blockData.setStateType(BlockStateType.CHEST.toString());
} else if (blockState instanceof Dispenser) {
Dispenser dispenser = (Dispenser) blockState;
for (int i = 0; i < dispenser.getInventory().getSize(); i++) {
ItemStack is = dispenser.getInventory().getItem(i);
if (is != null && is.getType() != Material.AIR) {
blockData.addItem(i, ItemStackUtil.serializeItemStack(is));
}
}
blockData.setStateType(BlockStateType.DISPENSER.toString());
} else if (blockState instanceof Dropper) {
Dropper dropper = (Dropper) blockState;
for (int i = 0; i < dropper.getInventory().getSize(); i++) {
ItemStack is = dropper.getInventory().getItem(i);
if (is != null && is.getType() != Material.AIR) {
blockData.addItem(i, ItemStackUtil.serializeItemStack(is));
}
}
blockData.setStateType(BlockStateType.DROPPER.toString());
} else if (blockState instanceof Hopper) {
Hopper hopper = (Hopper) blockState;
for (int i = 0; i < hopper.getInventory().getSize(); i++) {
ItemStack is = hopper.getInventory().getItem(i);
if (is != null && is.getType() != Material.AIR) {
blockData.addItem(i, ItemStackUtil.serializeItemStack(is));
}
}
blockData.setStateType(BlockStateType.HOPPER.toString());
} else if (blockState instanceof CommandBlock) {
CommandBlock commandBlock = (CommandBlock) blockState;
blockData.setCommand(commandBlock.getCommand());
blockData.setCommandBlockName(commandBlock.getName());
blockData.setStateType(BlockStateType.COMMANDBLOCK.toString());
} else if (blockState instanceof CreatureSpawner) {
CreatureSpawner creatureSpawner = (CreatureSpawner) blockState;
if (creatureSpawner.getSpawnedType() != null) {
blockData.setEntity(creatureSpawner.getSpawnedType().toString());
}
blockData.setDelay(creatureSpawner.getDelay());
blockData.setStateType(BlockStateType.CREATURESPAWNER.toString());
} else if (blockState instanceof Jukebox) {
Jukebox jukebox = (Jukebox) blockState;
if (jukebox.getPlaying() != null) {
blockData.setPlaying(jukebox.getPlaying().toString());
}
blockData.setStateType(BlockStateType.JUKEBOX.toString());
} else if (blockState instanceof Sign) {
Sign sign = (Sign) blockState;
String[] signLines = sign.getLines();
if (signLines != null) {
List<String> correctedSignLines = new ArrayList<>();
for (String signLineList : signLines) {
for (ChatColor chatColorList : ChatColor.values()) {
signLineList = signLineList.replace(chatColorList + "",
"&" + chatColorList.toString().substring(chatColorList.toString().length() - 1));
}
correctedSignLines.add(signLineList);
}
signLines = correctedSignLines.toArray(new String[correctedSignLines.size()]);
}
blockData.setSignLines(signLines);
blockData.setStateType(BlockStateType.SIGN.toString());
} else if (blockState instanceof Skull) {
Skull skull = (Skull) blockState;
blockData.setSkullOwner(skull.getOwner());
blockData.setSkullType(skull.getSkullType().toString());
blockData.setRotateFace(skull.getRotation().toString());
blockData.setStateType(BlockStateType.SKULL.toString());
} else {
if (NMSVersion > 8) {
if (blockState instanceof EndGateway) {
EndGateway endGateway = (EndGateway) blockState;
blockData.setExactTeleport(endGateway.isExactTeleport());
Location location = endGateway.getExitLocation();
blockData.setExitLocation(location.getX() + ":" + location.getY() + ":" + location.getZ() + ":"
+ location.getWorld().getName());
blockData.setStateType(BlockStateType.ENDGATEWAY.toString());
}
if (NMSVersion > 10) {
if (blockState instanceof ShulkerBox) {
ShulkerBox shulkerBox = (ShulkerBox) blockState;
for (int i = 0; i < shulkerBox.getInventory().getSize(); i++) {
ItemStack is = shulkerBox.getInventory().getItem(i);
if (is != null && is.getType() != Material.AIR) {
blockData.addItem(i, ItemStackUtil.serializeItemStack(is));
}
}
blockData.setStateType(BlockStateType.SHULKERBOX.toString());
}
}
}
}
if (materialData instanceof Stairs) {
blockData.setFacing(((Stairs) materialData).getFacing().toString());
blockData.setDataType(BlockDataType.STAIRS.toString());
} else if (materialData instanceof org.bukkit.material.FlowerPot) {
if (NMSVersion >= 8 && NMSVersion <= 12) {
try {
World world = block.getWorld();
Class<?> blockPositionClass = NMSUtil.getNMSClass("BlockPosition");
Object worldHandle = world.getClass().getMethod("getHandle").invoke(world);
Object blockPosition = blockPositionClass.getConstructor(int.class, int.class, int.class)
.newInstance(block.getX(), block.getY(), block.getZ());
Object tileEntity = worldHandle.getClass().getMethod("getTileEntity", blockPositionClass)
.invoke(worldHandle, blockPosition);
Field aField = tileEntity.getClass().getDeclaredField("a");
aField.setAccessible(true);
Object item = aField.get(tileEntity);
if (item != null) {
Object itemStackNMS = NMSUtil.getNMSClass("ItemStack")
.getConstructor(NMSUtil.getNMSClass("Item")).newInstance(item);
ItemStack itemStack = (ItemStack) NMSUtil.getCraftClass("inventory.CraftItemStack")
.getMethod("asBukkitCopy", itemStackNMS.getClass()).invoke(null, itemStackNMS);
Field fField = tileEntity.getClass().getDeclaredField("f");
fField.setAccessible(true);
int data = (int) fField.get(tileEntity);
blockData.setFlower(itemStack.getType().name() + ":" + data);
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
org.bukkit.material.FlowerPot flowerPot = (org.bukkit.material.FlowerPot) materialData;
if (flowerPot.getContents() != null && flowerPot.getContents().getItemType() != Material.AIR) {
blockData.setFlower(
flowerPot.getContents().getItemType().toString() + ":" + flowerPot.getContents().getData());
}
}
blockData.setDataType(BlockDataType.FLOWERPOT.toString());
}
return blockData;
}
public static void convertBlockDataToBlock(Block block, BlockData blockData) {
int NMSVersion = NMSUtil.getVersionNumber();
Material material = null;
if (NMSVersion > 12 && blockData.getVersion() > 12 && blockData.getBlockData() != null) {
block.setBlockData(Bukkit.getServer().createBlockData(blockData.getBlockData()));
} else {
material = MaterialUtil.getMaterial(NMSVersion, blockData.getVersion(),
blockData.getMaterial(), block.getData());
setBlockFast(block.getWorld(), block.getX(), block.getY(), block.getZ(), material, blockData.getData());
}
// TODO Create a class to support biome changes
// block.setBiome(Biome.valueOf(blockData.getBiome().toUpperCase()));
BlockStateType blockTypeState = BlockStateType.valueOf(blockData.getStateType());
if (blockTypeState == BlockStateType.BANNER) {
Banner banner = (Banner) block.getState();
banner.setBaseColor(DyeColor.valueOf(blockData.getBaseColor().toUpperCase()));
for (String patternList : blockData.getPatterns()) {
String[] pattern = patternList.split(":");
banner.addPattern(new Pattern(DyeColor.valueOf(pattern[1].toUpperCase()),
PatternType.valueOf(pattern[0].toUpperCase())));
}
} else if (blockTypeState == BlockStateType.BEACON) {
Beacon beacon = (Beacon) block.getState();
String[] potionEffect = blockData.getPotionEffect().split(":");
if (!potionEffect[0].equals("null")) {
beacon.setPrimaryEffect(PotionEffectType.getByName(potionEffect[0].toUpperCase()));
}
if (!potionEffect[1].equals("null")) {
beacon.setSecondaryEffect(PotionEffectType.getByName(potionEffect[1].toUpperCase()));
}
} else if (blockTypeState == BlockStateType.BREWINGSTAND) {
BrewingStand brewingStand = (BrewingStand) block.getState();
brewingStand.setBrewingTime(blockData.getBrewingTime());
brewingStand.setFuelLevel(blockData.getFuelLevel());
} else if (blockTypeState == BlockStateType.COMMANDBLOCK) {
CommandBlock commandBlock = (CommandBlock) block.getState();
commandBlock.setCommand(blockData.getCommand());
commandBlock.setName(blockData.getCommandBlockName());
} else if (blockTypeState == BlockStateType.CHEST) {
Chest chest = (Chest) block.getState();
for (Integer slotList : blockData.getInventory().keySet()) {
if (slotList < chest.getInventory().getSize()) {
ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList));
chest.getInventory().setItem(slotList, is);
}
}
} else if (blockTypeState == BlockStateType.DISPENSER) {
Dispenser dispenser = (Dispenser) block.getState();
for (Integer slotList : blockData.getInventory().keySet()) {
if (slotList < dispenser.getInventory().getSize()) {
ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList));
dispenser.getInventory().setItem(slotList, is);
}
}
} else if (blockTypeState == BlockStateType.DROPPER) {
Dropper dropper = (Dropper) block.getState();
for (Integer slotList : blockData.getInventory().keySet()) {
if (slotList < dropper.getInventory().getSize()) {
ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList));
dropper.getInventory().setItem(slotList, is);
}
}
} else if (blockTypeState == BlockStateType.HOPPER) {
Hopper hopper = (Hopper) block.getState();
for (Integer slotList : blockData.getInventory().keySet()) {
if (slotList < hopper.getInventory().getSize()) {
ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList));
hopper.getInventory().setItem(slotList, is);
}
}
} else if (blockTypeState == BlockStateType.CREATURESPAWNER) {
CreatureSpawner creatureSpawner = (CreatureSpawner) block.getState();
if (blockData.getEntity() != null) {
creatureSpawner.setSpawnedType(EntityType.valueOf(blockData.getEntity().toUpperCase()));
}
creatureSpawner.setDelay(blockData.getDelay());
} else if (blockTypeState == BlockStateType.FURNACE) {
Furnace furnace = (Furnace) block.getState();
furnace.setBurnTime(blockData.getBurnTime());
furnace.setCookTime(blockData.getCookTime());
for (Integer slotList : blockData.getInventory().keySet()) {
if (slotList < furnace.getInventory().getSize()) {
ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList));
furnace.getInventory().setItem(slotList, is);
}
}
} else if (blockTypeState == BlockStateType.JUKEBOX) {
Jukebox jukebox = (Jukebox) block.getState();
if (blockData.getPlaying() != null) {
jukebox.setPlaying(Material.valueOf(blockData.getPlaying().toUpperCase()));
}
} else if (blockTypeState == BlockStateType.SIGN) {
Sign sign = (Sign) block.getState();
for (int i = 0; i < blockData.getSignLines().length; i++) {
sign.setLine(i, ChatColor.translateAlternateColorCodes('&', blockData.getSignLines()[i]));
}
} else if (blockTypeState == BlockStateType.SKULL) {
Skull skull = (Skull) block.getState();
skull.setRotation(BlockFace.valueOf(blockData.getRotateFace().toUpperCase()));
skull.setSkullType(SkullType.valueOf(blockData.getSkullType().toUpperCase()));
if (NMSVersion > 9) {
skull.setOwningPlayer(Bukkit.getServer().getOfflinePlayer(blockData.getSkullOwner()));
} else {
skull.setOwner(blockData.getSkullOwner());
}
} else {
if (NMSVersion > 8) {
if (blockTypeState == BlockStateType.ENDGATEWAY) {
EndGateway endGateway = (EndGateway) block.getState();
endGateway.setExactTeleport(blockData.isExactTeleport());
String[] exitLocation = blockData.getExitLocation().split(":");
World exitLocationWorld = Bukkit.getServer().getWorld(exitLocation[3]);
double exitLocationX = Double.parseDouble(exitLocation[0]);
double exitLocationY = Double.parseDouble(exitLocation[1]);
double exitLocationZ = Double.parseDouble(exitLocation[2]);
endGateway.setExitLocation(
new Location(exitLocationWorld, exitLocationX, exitLocationY, exitLocationZ));
}
if (NMSVersion > 9) {
if (NMSVersion > 10) {
if (blockTypeState == BlockStateType.SHULKERBOX) {
ShulkerBox shulkerBox = (ShulkerBox) block.getState();
for (Integer slotList : blockData.getInventory().keySet()) {
if (slotList < shulkerBox.getInventory().getSize()) {
ItemStack is = ItemStackUtil
.deserializeItemStack(blockData.getInventory().get(slotList));
shulkerBox.getInventory().setItem(slotList, is);
}
}
}
}
}
}
}
BlockDataType blockDataType = BlockDataType.valueOf(blockData.getDataType());
if (blockDataType == BlockDataType.STAIRS) {
Stairs stairs = (Stairs) block.getState().getData();
stairs.setFacingDirection(BlockFace.valueOf(blockData.getFacing()));
block.getState().setData(stairs);
} else if (blockDataType == BlockDataType.FLOWERPOT) {
if (NMSVersion >= 8 && NMSVersion <= 12) {
if (block.getLocation().clone().subtract(0.0D, 1.0D, 0.0D).getBlock().getType() == Material.AIR) {
setBlockFast(block.getWorld(), block.getX(), block.getY() - 1, block.getZ(), Material.STONE,
(byte) 0);
}
if (blockData.getFlower() != null && !blockData.getFlower().isEmpty()) {
try {
String[] flower = blockData.getFlower().split(":");
int materialData = Integer.parseInt(flower[1]);
material = MaterialUtil.getMaterial(NMSVersion,
blockData.getVersion(), flower[0].toUpperCase(), materialData);
if (material != null) {
ItemStack is = new ItemStack(material, 1, (byte) materialData);
World world = block.getWorld();
Class<?> blockPositionClass = NMSUtil.getNMSClass("BlockPosition");
Object worldHandle = world.getClass().getMethod("getHandle").invoke(world);
Object blockPosition = blockPositionClass.getConstructor(int.class, int.class, int.class)
.newInstance(block.getX(), block.getY(), block.getZ());
Object tileEntity = worldHandle.getClass().getMethod("getTileEntity", blockPositionClass)
.invoke(worldHandle, blockPosition);
Object itemStack = NMSUtil.getCraftClass("inventory.CraftItemStack")
.getMethod("asNMSCopy", is.getClass()).invoke(null, is);
Object item = itemStack.getClass().getMethod("getItem").invoke(itemStack);
Object data = itemStack.getClass().getMethod("getData").invoke(itemStack);
Field aField = tileEntity.getClass().getDeclaredField("a");
aField.setAccessible(true);
aField.set(tileEntity, item);
Field fField = tileEntity.getClass().getDeclaredField("f");
fField.setAccessible(true);
fField.set(tileEntity, data);
tileEntity.getClass().getMethod("update").invoke(tileEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
if (blockData.getFlower() != null && !blockData.getFlower().isEmpty()) {
org.bukkit.material.FlowerPot flowerPot = (org.bukkit.material.FlowerPot) block.getState()
.getData();
String[] flower = blockData.getFlower().split(":");
material = null;
if (blockData.getVersion() > 12) {
if (NMSVersion > 12) {
material = Material.valueOf(flower[0].toUpperCase());
}
} else {
if (NMSVersion < 13) {
material = Material.valueOf(flower[0].toUpperCase());
}
}
if (material != null) {
flowerPot.setContents(new MaterialData(material, (byte) Integer.parseInt(flower[1])));
}
block.getState().setData(flowerPot);
}
}
}
if (NMSVersion < 13) {
block.getState().update();
}
if (blockData.getMaterial().equals("DOUBLE_PLANT")) {
Block topBlock = block.getLocation().clone().add(0.0D, 1.0D, 0.0D).getBlock();
Block bottomBlock = block.getLocation().clone().subtract(0.0D, 1.0D, 0.0D).getBlock();
if (bottomBlock.getType() == Material.AIR && !topBlock.getType().name().equals("DOUBLE_PLANT")) {
bottomBlock.setType(Materials.LEGACY_DOUBLE_PLANT.getPostMaterial());
if (NMSVersion < 13) {
try {
bottomBlock.getClass().getMethod("setData", byte.class).invoke(bottomBlock, (byte) 2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public static List<Block> getNearbyBlocks(Location loc, int rx, int ry, int rz) {
List<Block> nearbyBlocks = new ArrayList<>();
for (int x = -(rx); x <= rx; x++) {
for (int y = -(ry); y <= ry; y++) {
for (int z = -(rz); z <= rz; z++) {
nearbyBlocks.add(
new Location(loc.getWorld(), loc.getX() + x, loc.getY() + y, loc.getZ() + z).getBlock());
}
}
}
return nearbyBlocks;
}
private static void setBlockFast(World world, int x, int y, int z, Material material, byte data) {
try {
Class<?> IBlockDataClass = NMSUtil.getNMSClass("IBlockData");
Object worldHandle = world.getClass().getMethod("getHandle").invoke(world);
Object chunk = worldHandle.getClass().getMethod("getChunkAt", int.class, int.class).invoke(worldHandle,
x >> 4, z >> 4);
Object blockPosition = NMSUtil.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class)
.newInstance(x & 0xF, y, z & 0xF);
if (NMSUtil.getVersionNumber() > 12) {
Object block = NMSUtil.getNMSClass("Blocks").getField(material.name()).get(null);
Object IBlockData = block.getClass().getMethod("getBlockData").invoke(block);
worldHandle.getClass().getMethod("setTypeAndData", blockPosition.getClass(), IBlockDataClass, int.class)
.invoke(worldHandle, blockPosition, IBlockData, 2);
try {
chunk.getClass().getMethod("a", blockPosition.getClass(), IBlockDataClass, boolean.class)
.invoke(chunk, blockPosition, IBlockData, true);
} catch (Exception e) {
chunk.getClass().getMethod("setType", blockPosition.getClass(), IBlockDataClass, boolean.class)
.invoke(chunk, blockPosition, IBlockData, true);
}
} else {
Object IBlockData = NMSUtil.getNMSClass("Block").getMethod("getByCombinedId", int.class).invoke(null,
material.getId() + (data << 12));
worldHandle.getClass().getMethod("setTypeAndData", blockPosition.getClass(), IBlockDataClass, int.class)
.invoke(worldHandle, blockPosition, IBlockData, 3);
chunk.getClass().getMethod("a", blockPosition.getClass(), IBlockDataClass).invoke(chunk, blockPosition,
IBlockData);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -1,3 +0,0 @@
block:
BEDROCK: 0
END_PORTAL_FRAME: 12

View File

@ -1,3 +0,0 @@
dependencies {
compileOnly 'org.spigotmc:spigot:1.12.2'
}

View File

@ -1,23 +0,0 @@
package com.songoda.skyblock.levelling;
import org.bukkit.Material;
public class LegacyChunkSnapshotData {
private Material material;
private int data;
public LegacyChunkSnapshotData(Material material, int data) {
this.material = material;
this.data = data;
}
public Material getMaterial() {
return this.material;
}
public int getData() {
return this.data;
}
}

View File

@ -1,13 +0,0 @@
package com.songoda.skyblock.levelling;
import org.bukkit.ChunkSnapshot;
import org.bukkit.Material;
public class LegacyChunkSnapshotFetcher {
// Uses a 1.12.2 jar in a separate project to avoid needing to use reflection during level scanning, much faster.
public static LegacyChunkSnapshotData fetch(ChunkSnapshot snapshot, int x, int y, int z) {
return new LegacyChunkSnapshotData(Material.getMaterial(snapshot.getBlockTypeId(x, y, z)), snapshot.getBlockData(x, y, z));
}
}

View File

@ -1,46 +1,109 @@
import org.apache.tools.ant.filters.ReplaceTokens
allprojects {
apply plugin: 'java'
group = 'com.goodandevil.skyblock'
version = 'maven-version-number'
}
subprojects {
sourceCompatibility = 1.8
repositories {
mavenCentral()
jcenter()
maven {
url = 'http://repo.songoda.com/artifactory/private'
}
maven {
url = 'https://jitpack.io'
}
}
}
dependencies {
compile project(':FabledSkyBlock-Legacy')
compile project(':FabledSkyBlock-Core')
apply plugin: 'java'
apply plugin: 'eclipse'
group = 'com.songoda.skyblock'
version = 'maven-version-number'
}
configurations {
childJars
shade
compile.extendsFrom shade
}
repositories {
mavenCentral()
jcenter()
//Spigot
maven {
url 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/'
}
// Bungeecord
maven {
url 'https://oss.sonatype.org/content/repositories/snapshots/'
}
// Songoda
maven {
url 'http://repo.songoda.com/artifactory/private'
}
// Mojang
maven {
url 'https://libraries.minecraft.net/'
}
//Jitpack
maven {
url 'https://jitpack.io'
}
}
dependencies {
subprojects.each {
childJars project(it.path)
}
// Spigot
implementation (group: 'org.spigotmc', name: 'spigot-api', version: '1.14.4-R0.1-SNAPSHOT')
// GameProfile's Mojang
implementation (group: 'com.mojang', name: 'authlib', version: '1.5.3')
// PlaceholderAPI
implementation (group: 'be.maximvdw', name: 'placeholderapi', version: '2.5.1')
implementation (group: 'me.clip', name: 'placeholderapi', version: '2.10.2')
// Vault
implementation (group: 'net.milkbowl', name: 'vault', version: '1.7.1')
// Reserve
implementation (group: 'net.tnemc', name: 'Reserve', version: '0.1.3.0')
// Leaderheads
implementation (group: 'me.robin', name: 'leaderheads', version: '1.0')
// EpicSpawners
implementation (group: 'com.songoda', name: 'epicspawners', version: '6-pre4')
// EpicAnchors
implementation (group: 'com.songoda', name: 'EpicAnchors', version: '1.4.2')
// UltimateStacker
implementation (group: 'com.songoda', name: 'ultimatestacker', version: '1.3.1')
// WildStacker
implementation (group: 'com.github.OmerBenGera', name: 'WildStackerAPI', version: 'b15')
// WorldEdit
implementation (group: 'com.sk89q', name: 'worldedit', version: '7.0.0')
// Apache Commons
shade (group: 'org.apache.commons', name: 'commons-lang3', version: '3.0')
shade (group: 'commons-io', name: 'commons-io', version: '2.5')
// JSON.org
shade (group: 'org.json', name: 'json', version: '20190722')
// Songoda Updater
shade (group: 'com.songoda', name: 'songodaupdater', version: '1')
shade fileTree(dir: 'libraries', include: '*.jar')
}
processResources {
filter ReplaceTokens, tokens: ["version": project.property("version")]
from (sourceSets.main.resources.srcDirs) {
include '**/*.yml'
}
}
jar {
dependsOn configurations.childJars
from {
configurations.childJars.collect {
zipTree(it)
}
}
configurations.shade.each { dep ->
from(project.zipTree(dep)){
exclude 'META-INF', 'META-INF/**'
exclude '**/*.yml'
}
}
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

6
gradlew vendored
View File

@ -7,7 +7,7 @@
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
@ -125,8 +125,8 @@ if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`

2
gradlew.bat vendored
View File

@ -5,7 +5,7 @@
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem http://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,

Binary file not shown.

View File

@ -1,7 +1 @@
rootProject.name = 'FabledSkyBlock'
include(':FabledSkyBlock-Core')
project(':FabledSkyBlock-Core').projectDir = file('FabledSkyBlock/Core')
include(':FabledSkyBlock-Legacy')
project(':FabledSkyBlock-Legacy').projectDir = file('FabledSkyBlock/Legacy')
rootProject.name = 'FabledSkyblock'

View File

@ -15,7 +15,7 @@ import com.songoda.skyblock.invite.InviteManager;
import com.songoda.skyblock.island.IslandManager;
import com.songoda.skyblock.leaderboard.LeaderboardManager;
import com.songoda.skyblock.levelling.LevellingManager;
import com.songoda.skyblock.limit.LimitManager;
import com.songoda.skyblock.limit.LimitationInstanceHandler;
import com.songoda.skyblock.listeners.*;
import com.songoda.skyblock.menus.Rollback;
import com.songoda.skyblock.menus.admin.Creator;
@ -61,7 +61,6 @@ public class SkyBlock extends JavaPlugin {
private UpgradeManager upgradeManager;
private PlayerDataManager playerDataManager;
private CooldownManager cooldownManager;
private LimitManager limitManager;
private ScoreboardManager scoreboardManager;
private InviteManager inviteManager;
private BiomeManager biomeManager;
@ -76,6 +75,7 @@ public class SkyBlock extends JavaPlugin {
private MessageManager messageManager;
private EconomyManager economyManager;
private HologramManager hologramManager;
private LimitationInstanceHandler limitationHandler;
public static SkyBlock getInstance() {
return instance;
@ -101,7 +101,7 @@ public class SkyBlock extends JavaPlugin {
upgradeManager = new UpgradeManager(this);
playerDataManager = new PlayerDataManager(this);
cooldownManager = new CooldownManager(this);
limitManager = new LimitManager(this);
limitationHandler = new LimitationInstanceHandler();
if (fileManager.getConfig(new File(getDataFolder(), "config.yml")).getFileConfiguration()
.getBoolean("Island.Scoreboard.Enable")) {
@ -156,6 +156,7 @@ public class SkyBlock extends JavaPlugin {
pluginManager.registerEvents(new Chat(this), this);
pluginManager.registerEvents(new Spawner(this), this);
pluginManager.registerEvents(new Food(this), this);
pluginManager.registerEvents(new Grow(this), this);
if (pluginManager.isPluginEnabled("EpicSpawners"))
pluginManager.registerEvents(new EpicSpawners(this), this);
@ -260,10 +261,6 @@ public class SkyBlock extends JavaPlugin {
return cooldownManager;
}
public LimitManager getLimitManager() {
return limitManager;
}
public ScoreboardManager getScoreboardManager() {
return scoreboardManager;
}
@ -328,6 +325,10 @@ public class SkyBlock extends JavaPlugin {
return stackableManager;
}
public LimitationInstanceHandler getLimitationHandler() {
return limitationHandler;
}
@Override
public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) {
return new VoidGenerator();

View File

@ -20,7 +20,7 @@ public class PlayerIslandLeaveEvent extends PlayerEvent implements Cancellable {
return HANDLERS;
}
public HandlerList getHandlerList() {
public static HandlerList getHandlerList() {
return HANDLERS;
}

View File

@ -0,0 +1,516 @@
package com.songoda.skyblock.api.island;
import com.google.common.base.Preconditions;
import com.songoda.skyblock.api.SkyBlockAPI;
import com.songoda.skyblock.api.ban.Ban;
import com.songoda.skyblock.api.utils.APIUtil;
import com.songoda.skyblock.api.visit.Visit;
import com.songoda.skyblock.island.IslandCoop;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.WeatherType;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.entity.Player;
import java.util.*;
public class Island {
private com.songoda.skyblock.island.Island handle;
private OfflinePlayer player;
public Island(com.songoda.skyblock.island.Island handle, OfflinePlayer player) {
this.handle = handle;
this.player = player;
}
/**
* @return The Island UUID
*/
public UUID getIslandUUID() {
return this.handle.getIslandUUID();
}
/**
* @return The Island owner UUID
*/
public UUID getOwnerUUID() {
return this.handle.getOwnerUUID();
}
/**
* @return The original Island owner UUID
*/
public UUID getOriginalOwnerUUID() {
return this.handle.getOriginalOwnerUUID();
}
/**
* @return The Island size
*/
public int getSize() {
return this.handle.getSize();
}
/**
* Set the size of the Island
*/
public void setSize(int size) {
Preconditions.checkArgument(size <= 1000, "Cannot set size to greater than 1000");
Preconditions.checkArgument(size >= 50, "Cannot set size to less than 50");
this.handle.setSize(size);
}
/**
* @return The Island radius
*/
public double getRadius() {
return this.handle.getRadius();
}
/**
* @return true if not null, false otherwise
*/
public boolean hasPassword() {
return this.handle.hasPassword();
}
/**
* Set the password for ownership
*/
public void setPassword(String password) {
Preconditions.checkArgument(password != null, "Cannot set password to null password");
this.handle.setPassword(password);
}
/**
* Get the Location from the World in island world from World in environment.
*
* @return Location of Island
*/
public Location getLocation(IslandWorld world, IslandEnvironment environment) {
Preconditions.checkArgument(world != null, "World in island world null does not exist");
Preconditions.checkArgument(environment != null, "World in environment null does not exist");
return handle.getLocation(APIUtil.toImplementation(world), APIUtil.toImplementation(environment));
}
/**
* Set the Location from the World in island world from world in environment
* followed by position
*/
public void setLocation(IslandWorld world, IslandEnvironment environment, int x, int y, int z) {
Preconditions.checkArgument(world != null, "World in island world null does not exist");
Preconditions.checkArgument(environment != null, "World in environment null does not exist");
World bukkitWorld = getLocation(world, environment).getWorld();
this.handle.setLocation(APIUtil.toImplementation(world), APIUtil.toImplementation(environment),
new Location(bukkitWorld, x, y, z));
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isBorder() {
return this.handle.isBorder();
}
/**
* Set the border visible to players for the Island
*/
public void setBorder(boolean border) {
this.handle.setBorder(border);
}
/**
* @return The color of the Island border
*/
public IslandBorderColor getBorderColor() {
return APIUtil.fromImplementation(this.handle.getBorderColor());
}
/**
* Set the border color for the Island
*/
public void setBorderColor(IslandBorderColor color) {
Preconditions.checkArgument(color != null, "IslandBorderColor null does not exist");
this.handle.setBorderColor(APIUtil.toImplementation(color));
}
/**
* @return The biome set for the Island
*/
public Biome getBiome() {
return this.handle.getBiome();
}
/**
* Set the biome for the Island
*/
public void setBiome(Biome biome) {
Preconditions.checkArgument(biome != null, "Cannot set biome to null biome");
this.handle.setBiome(biome);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isDayCycleSynchronizedSynchronized() {
return this.handle.isWeatherSynchronized();
}
/**
* Set the Day Cycle of the Island to be Synchronized with the World cycle
*/
public void setDayCycleSynchronzied(boolean sync) {
this.handle.setWeatherSynchronized(sync);
}
/**
* @return The WeatherType set for the Island
*/
public WeatherType getWeather() {
return this.handle.getWeather();
}
/**
* Set the weather for the Island
*/
public void setWeather(WeatherType weatherType) {
Preconditions.checkArgument(weatherType != null, "Cannot set weather to null weather");
this.handle.setWeather(weatherType);
}
/**
* @return The time set for the Island
*/
public int getTime() {
return this.handle.getTime();
}
/**
* Set the time for the Island
*/
public void setTime(int time) {
this.handle.setTime(time);
}
/**
* @return A Set of cooped players
*/
public Map<UUID, IslandCoop> getCoopPlayers() {
return this.handle.getCoopPlayers();
}
/**
* Add a player to the coop players for the Island
*/
public void addCoopPlayer(UUID uuid, IslandCoop islandCoop) {
Preconditions.checkArgument(uuid != null, "Cannot add coop player to null uuid");
this.handle.addCoopPlayer(uuid, islandCoop);
}
/**
* Add a player to the coop players for the Island
*/
public void addCoopPlayer(OfflinePlayer player, IslandCoop islandCoop) {
Preconditions.checkArgument(player != null, "Cannot add coop player to null player");
this.handle.addCoopPlayer(player.getUniqueId(), islandCoop);
}
/**
* Remove a player from the coop players for the Island
*/
public void removeCoopPlayer(UUID uuid) {
Preconditions.checkArgument(uuid != null, "Cannot remove coop player to null uuid");
this.handle.removeCoopPlayer(uuid);
}
/**
* Remove a player from the coop players for the Island
*/
public void removeCoopPlayer(OfflinePlayer player) {
Preconditions.checkArgument(player != null, "Cannot remove coop player to null player");
this.handle.removeCoopPlayer(player.getUniqueId());
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isCoopPlayer(UUID uuid) {
Preconditions.checkArgument(uuid != null, "Cannot return condition to null uuid");
return this.handle.isCoopPlayer(uuid);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isCoopPlayer(OfflinePlayer player) {
Preconditions.checkArgument(player != null, "Cannot return condition to null player");
return this.handle.isCoopPlayer(player.getUniqueId());
}
/**
* @return The IslandRole of a player
*/
public IslandRole getRole(OfflinePlayer player) {
Preconditions.checkArgument(player != null, "Cannot get role for null player");
for (com.songoda.skyblock.island.IslandRole role : com.songoda.skyblock.island.IslandRole.values()) {
if (this.handle.hasRole(role, player.getUniqueId())) {
return APIUtil.fromImplementation(role);
}
}
return null;
}
/**
* @return A Set of players with IslandRole
*/
public Set<UUID> getPlayersWithRole(IslandRole role) {
Preconditions.checkArgument(role != null, "Cannot get players will null role");
return this.handle.getRole(APIUtil.toImplementation(role));
}
/**
* Set the IslandRole of a player for the Island
*
* @return true of conditions met, false otherwise
*/
public boolean setRole(OfflinePlayer player, IslandRole role) {
Preconditions.checkArgument(player != null, "Cannot set role of null player");
return setRole(player.getUniqueId(), role);
}
/**
* Set the IslandRole of a player for the Island
*
* @return true of conditions met, false otherwise
*/
public boolean setRole(UUID uuid, IslandRole role) {
Preconditions.checkArgument(uuid != null, "Cannot set role of null player");
Preconditions.checkArgument(role != null, "Cannot set role to null role");
return this.handle.setRole(APIUtil.toImplementation(role), uuid);
}
/**
* Remove the IslandRole of a player for the Island
*
* @return true of conditions met, false otherwise
*/
public boolean removeRole(OfflinePlayer player, IslandRole role) {
Preconditions.checkArgument(player != null, "Cannot remove role of null player");
return removeRole(player.getUniqueId(), role);
}
/**
* Remove the IslandRole of a player for the Island
*
* @return true of conditions met, false otherwise
*/
public boolean removeRole(UUID uuid, IslandRole role) {
Preconditions.checkArgument(uuid != null, "Cannot remove role of null player");
Preconditions.checkArgument(role != null, "Cannot remove role to null role");
return this.handle.removeRole(APIUtil.toImplementation(role), uuid);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean hasRole(OfflinePlayer player, IslandRole role) {
Preconditions.checkArgument(player != null, "Cannot check role of null player");
return handle.hasRole(APIUtil.toImplementation(role), player.getUniqueId());
}
/**
* @return true of conditions met, false otherwise
*/
public boolean hasRole(UUID uuid, IslandRole role) {
Preconditions.checkArgument(uuid != null, "Cannot check role of null player");
Preconditions.checkArgument(role != null, "Cannot check role to null role");
return handle.hasRole(APIUtil.toImplementation(role), uuid);
}
/**
* Set the condition of an IslandUpgrade for the Island
*/
public void setUpgrade(Player player, IslandUpgrade upgrade, boolean status) {
Preconditions.checkArgument(upgrade != null, "Cannot set upgrade to null upgrade");
this.handle.setUpgrade(player, APIUtil.toImplementation(upgrade), status);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean hasUpgrade(IslandUpgrade upgrade) {
Preconditions.checkArgument(upgrade != null, "Cannot check upgrade to null upgrade");
return this.handle.hasUpgrade(APIUtil.toImplementation(upgrade));
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isUpgrade(IslandUpgrade upgrade) {
Preconditions.checkArgument(upgrade != null, "Cannot check upgrade to null upgrade");
return this.handle.isUpgrade(APIUtil.toImplementation(upgrade));
}
/**
* @return Setting of an IslandRole for the Island
*/
public IslandSetting getSetting(IslandRole role, String setting) {
Preconditions.checkArgument(role != null, "Cannot get setting to null role");
Preconditions.checkArgument(setting != null, "Cannot get setting for null setting");
return new IslandSetting(this.handle.getSetting(APIUtil.toImplementation(role), setting));
}
/**
* @return A List of Settings of an IslandRole for the Island
*/
public List<IslandSetting> getSettings(IslandRole role) {
Preconditions.checkArgument(role != null, "Cannot get settings to null role");
List<IslandSetting> settings = new ArrayList<>();
for (com.songoda.skyblock.island.IslandSetting settingList : this.handle
.getSettings(APIUtil.toImplementation(role))) {
settings.add(new IslandSetting(settingList));
}
return settings;
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isOpen() {
return handle.isOpen();
}
public void setOpen(boolean open) {
this.handle.setOpen(open);
}
/**
* @return A List from IslandMessage for the Island
*/
public List<String> getMessage(IslandMessage message) {
Preconditions.checkArgument(message != null, "Cannot get message for null message");
return this.handle.getMessage(APIUtil.toImplementation(message));
}
/**
* @return The author of an IslandMessage for the Island
*/
public String getMessageAuthor(IslandMessage message) {
Preconditions.checkArgument(message != null, "Cannot get message author for null message");
return this.handle.getMessageAuthor(APIUtil.toImplementation(message));
}
/**
* Set the IslandMessage for the Island
*/
public void setMessage(IslandMessage message, String author, List<String> messageLines) {
Preconditions.checkArgument(message != null, "Cannot set message for null message");
this.handle.setMessage(APIUtil.toImplementation(message), author, messageLines);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean hasStructure() {
return this.handle.hasStructure();
}
/**
* @return The Structure name for the Island
*/
public String getStructure() {
return this.handle.getStructure();
}
/**
* Set the Structure for the Island
*/
public void setStructure(String structure) {
Preconditions.checkArgument(structure != null, "Cannot set structure to null structure");
this.handle.setStructure(structure);
}
/**
* @return The Visit implementation for the Island
*/
public Visit getVisit() {
return new Visit(this);
}
/**
* @return The Ban implementation for the Island
*/
public Ban getBan() {
return new Ban(this);
}
/**
* @return The Level implementation for the Island
*/
public IslandLevel getLevel() {
return new IslandLevel(this);
}
/**
* @return true of conditions met, false otherwise
*/
public boolean isLoaded() {
return this.handle != null;
}
/**
* Loads the Island if unloaded
*/
public void load() {
if (this.handle == null) {
this.handle = SkyBlockAPI.getImplementation().getIslandManager().loadIsland(player);
}
}
/**
* Unloads the Island if loaded
*/
public void unload() {
if (this.handle != null) {
SkyBlockAPI.getImplementation().getIslandManager().unloadIsland(getIsland(), null);
this.handle = null;
}
}
/**
* Sets the player of the Island
*/
public void setPlayer(OfflinePlayer player) {
this.player = player;
}
/**
* @return Implementation for the Island
*/
public com.songoda.skyblock.island.Island getIsland() {
return handle;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Island))
return false;
Island other = (Island) object;
if (!other.getIslandUUID().equals(getIslandUUID()))
return false;
return true;
}
}

View File

@ -31,8 +31,7 @@ public class BanManager {
public void onDisable() {
Map<UUID, Ban> banIslands = getIslands();
for (UUID banIslandList : banIslands.keySet()) {
Ban ban = banIslands.get(banIslandList);
for (Ban ban : banIslands.values()) {
ban.save();
}
}
@ -96,11 +95,7 @@ public class BanManager {
}
public Ban getIsland(UUID islandOwnerUUID) {
if (hasIsland(islandOwnerUUID)) {
return banStorage.get(islandOwnerUUID);
}
return null;
return banStorage.get(islandOwnerUUID);
}
public Map<UUID, Ban> getIslands() {
@ -116,9 +111,7 @@ public class BanManager {
}
public void removeIsland(UUID islandOwnerUUID) {
if (hasIsland(islandOwnerUUID)) {
banStorage.remove(islandOwnerUUID);
}
banStorage.remove(islandOwnerUUID);
}
public void unloadIsland(UUID islandOwnerUUID) {

View File

@ -11,8 +11,8 @@ import org.bukkit.block.Biome;
import org.bukkit.entity.Player;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
import java.util.Set;
public class BiomeManager {
@ -23,7 +23,7 @@ public class BiomeManager {
}
public void setBiome(Island island, Biome biome) {
List<Chunk> chunks = new ArrayList<>();
Set<Chunk> chunks = new HashSet<>();
Location location = island.getLocation(IslandWorld.Normal, IslandEnvironment.Island);
int radius = (int) Math.ceil(island.getRadius());
@ -31,8 +31,7 @@ public class BiomeManager {
for (int z = location.getBlockZ() - radius; z < location.getBlockZ() + radius; z++) {
location.getWorld().setBiome(x, z, biome);
Chunk chunk = location.getWorld().getChunkAt(x >> 4, z >> 4);
if (!chunks.contains(chunk))
chunks.add(chunk);
chunks.add(chunk);
}
}

View File

@ -110,7 +110,8 @@ public class CommandManager implements CommandExecutor, TabCompleter {
new com.songoda.skyblock.command.commands.admin.SetSpawnCommand(),
new com.songoda.skyblock.command.commands.admin.SettingsCommand(),
new StructureCommand(),
new com.songoda.skyblock.command.commands.admin.UpgradeCommand()
new com.songoda.skyblock.command.commands.admin.UpgradeCommand(),
new StackableCommand()
);
}

View File

@ -31,7 +31,6 @@ public class ProxyCommand extends SubCommand {
}
public void onCommand(CommandSender sender, String[] args) {
PlayerDataManager playerDataManager = skyblock.getPlayerDataManager();
MessageManager messageManager = skyblock.getMessageManager();
IslandManager islandManager = skyblock.getIslandManager();
SoundManager soundManager = skyblock.getSoundManager();
@ -41,31 +40,24 @@ public class ProxyCommand extends SubCommand {
FileConfiguration configLoad = config.getFileConfiguration();
if (args.length == 1) {
Player targetPlayer = Bukkit.getServer().getPlayer(args[0]);
UUID islandOwnerUUID;
if (targetPlayer == null) {
OfflinePlayer targetPlayerOffline = new OfflinePlayer(args[0]);
islandOwnerUUID = targetPlayerOffline.getOwner();
} else {
islandOwnerUUID = playerDataManager.getPlayerData(targetPlayer).getOwner();
}
OfflinePlayer targetPlayerOffline = new OfflinePlayer(args[0]);
UUID islandOwnerUUID = targetPlayerOffline.getOwner();
if (islandManager.containsIsland(islandOwnerUUID)) {
if (islandManager.isPlayerProxyingAnotherPlayer(((Player)sender).getUniqueId())) {
messageManager.sendMessage(sender,
configLoad.getString("Command.Island.Admin.Proxy.IsOffPlayer.Message")
.replace("%player", targetPlayer.getName()));
.replace("%player", targetPlayerOffline.getName()));
soundManager.playSound(sender, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F);
islandManager.removeProxyingPlayer(((Player)sender).getUniqueId());
} else {
messageManager.sendMessage(sender,
configLoad.getString("Command.Island.Admin.Proxy.IsOn.Message")
.replace("%player", targetPlayer.getName()));
.replace("%player", targetPlayerOffline.getName()));
soundManager.playSound(sender, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F);
islandManager.addProxiedPlayer(((Player)sender).getUniqueId(), targetPlayer.getUniqueId());
islandManager.addProxiedPlayer(((Player)sender).getUniqueId(), targetPlayerOffline.getUniqueId());
}
}
} else if (args.length == 0){

View File

@ -1,25 +1,25 @@
package com.songoda.skyblock.command.commands.admin;
import com.songoda.skyblock.command.SubCommand;
import com.songoda.skyblock.config.FileManager;
import com.songoda.skyblock.config.FileManager.Config;
import com.songoda.skyblock.generator.GeneratorManager;
import com.songoda.skyblock.hologram.HologramManager;
import com.songoda.skyblock.leaderboard.LeaderboardManager;
import com.songoda.skyblock.levelling.LevellingManager;
import com.songoda.skyblock.limit.LimitManager;
import com.songoda.skyblock.message.MessageManager;
import com.songoda.skyblock.scoreboard.ScoreboardManager;
import com.songoda.skyblock.sound.SoundManager;
import com.songoda.skyblock.utils.version.Sounds;
import java.io.File;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.io.File;
import java.util.Map;
import com.songoda.skyblock.command.SubCommand;
import com.songoda.skyblock.config.FileManager;
import com.songoda.skyblock.config.FileManager.Config;
import com.songoda.skyblock.generator.GeneratorManager;
import com.songoda.skyblock.leaderboard.LeaderboardManager;
import com.songoda.skyblock.levelling.LevellingManager;
import com.songoda.skyblock.limit.LimitationInstanceHandler;
import com.songoda.skyblock.message.MessageManager;
import com.songoda.skyblock.scoreboard.ScoreboardManager;
import com.songoda.skyblock.sound.SoundManager;
import com.songoda.skyblock.utils.version.Sounds;
public class ReloadCommand extends SubCommand {
@ -35,10 +35,9 @@ public class ReloadCommand extends SubCommand {
public void onCommand(CommandSender sender, String[] args) {
LeaderboardManager leaderboardManager = skyblock.getLeaderboardManager();
HologramManager hologramManager = skyblock.getHologramManager();
MessageManager messageManager = skyblock.getMessageManager();
SoundManager soundManager = skyblock.getSoundManager();
LimitManager limitManager = skyblock.getLimitManager();
LimitationInstanceHandler limitHandler = skyblock.getLimitationHandler();
FileManager fileManager = skyblock.getFileManager();
messageManager.sendMessage(sender, "&cPlease note that this command is not supported and may " +
@ -96,7 +95,7 @@ public class ReloadCommand extends SubCommand {
Bukkit.getScheduler().runTask(skyblock, () -> skyblock.getHologramManager().resetHologram());
});
limitManager.reload();
limitHandler.reloadAll();
messageManager.sendMessage(sender, configLoad.getString("Command.Island.Admin.Reload.Reloaded.Message"));
soundManager.playSound(sender, Sounds.ANVIL_USE.bukkitSound(), 1.0F, 1.0F);

View File

@ -1,5 +1,14 @@
package com.songoda.skyblock.command.commands.admin;
import java.io.File;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import com.songoda.skyblock.command.SubCommand;
import com.songoda.skyblock.config.FileManager;
import com.songoda.skyblock.config.FileManager.Config;
@ -10,16 +19,6 @@ import com.songoda.skyblock.playerdata.PlayerDataManager;
import com.songoda.skyblock.sound.SoundManager;
import com.songoda.skyblock.utils.player.OfflinePlayer;
import com.songoda.skyblock.utils.version.Sounds;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
public class SetAlwaysLoadedCommand extends SubCommand {
@ -34,14 +33,21 @@ public class SetAlwaysLoadedCommand extends SubCommand {
}
public void onCommand(CommandSender sender, String[] args) {
PlayerDataManager playerDataManager = skyblock.getPlayerDataManager();
MessageManager messageManager = skyblock.getMessageManager();
IslandManager islandManager = skyblock.getIslandManager();
SoundManager soundManager = skyblock.getSoundManager();
FileManager fileManager = skyblock.getFileManager();
FileManager fileManager = skyblock.getFileManager();
Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml"));
FileConfiguration configLoad = config.getFileConfiguration();
MessageManager messageManager = skyblock.getMessageManager();
if (args.length == 0) {
messageManager.sendMessage(sender,
configLoad.getString("Command.Island.Admin.SetAlwaysLoaded.No-Player-Input.Message"));
return;
}
PlayerDataManager playerDataManager = skyblock.getPlayerDataManager();
IslandManager islandManager = skyblock.getIslandManager();
SoundManager soundManager = skyblock.getSoundManager();
if (args.length == 1) {
Player targetPlayer = Bukkit.getServer().getPlayer(args[0]);

Some files were not shown because too many files have changed in this diff Show More