BlueMap/implementations/spigot/src/main/java/de/bluecolored/bluemap/bukkit/BukkitPlugin.java

298 lines
9.9 KiB
Java
Raw Normal View History

2020-04-20 12:50:28 +02:00
/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
2020-01-11 11:32:47 +01:00
package de.bluecolored.bluemap.bukkit;
import de.bluecolored.bluemap.common.plugin.Plugin;
import de.bluecolored.bluemap.common.plugin.serverinterface.Player;
import de.bluecolored.bluemap.common.plugin.serverinterface.ServerEventListener;
import de.bluecolored.bluemap.common.plugin.serverinterface.ServerInterface;
import de.bluecolored.bluemap.core.MinecraftVersion;
import de.bluecolored.bluemap.core.logger.Logger;
import de.bluecolored.bluemap.core.resourcepack.ParseResourceException;
2020-01-15 20:20:22 +01:00
import org.bstats.bukkit.MetricsLite;
2020-01-18 00:59:51 +01:00
import org.bukkit.Bukkit;
2020-01-15 20:20:22 +01:00
import org.bukkit.World;
2020-05-10 01:28:09 +02:00
import org.bukkit.command.CommandMap;
import org.bukkit.command.defaults.BukkitCommand;
2020-08-07 17:29:28 +02:00
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
2020-01-11 11:32:47 +01:00
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
2020-01-11 11:32:47 +01:00
2020-08-07 17:29:28 +02:00
public class BukkitPlugin extends JavaPlugin implements ServerInterface, Listener {
2020-01-15 20:20:22 +01:00
2020-01-18 00:59:51 +01:00
private static BukkitPlugin instance;
2020-08-19 20:31:20 +02:00
private Plugin pluginInstance;
2020-01-15 20:20:22 +01:00
private EventForwarder eventForwarder;
private BukkitCommands commands;
2020-01-15 20:20:22 +01:00
2020-08-07 17:29:28 +02:00
private int playerUpdateIndex = 0;
private Map<UUID, Player> onlinePlayerMap;
private List<BukkitPlayer> onlinePlayerList;
2020-01-15 20:20:22 +01:00
public BukkitPlugin() {
Logger.global = new JavaLogger(getLogger());
2020-08-25 15:07:42 +02:00
MinecraftVersion version = MinecraftVersion.getLatest();
2020-08-25 18:05:25 +02:00
//try to get best matching minecraft-version
2020-08-25 15:07:42 +02:00
try {
2020-08-25 18:05:25 +02:00
String versionString = getServer().getBukkitVersion();
Matcher versionMatcher = Pattern.compile("(\\d+\\.\\d+\\.\\d+)[-_].*").matcher(versionString);
if (!versionMatcher.matches()) throw new IllegalArgumentException();
version = MinecraftVersion.fromVersionString(versionMatcher.group(1));
2020-08-25 15:07:42 +02:00
} catch (IllegalArgumentException e) {
2020-08-25 18:05:25 +02:00
Logger.global.logWarning("Failed to detect the minecraft version of this server! Using latest version: " + version.getVersionString());
2020-08-25 15:07:42 +02:00
}
2020-08-07 17:29:28 +02:00
this.onlinePlayerMap = new ConcurrentHashMap<>();
this.onlinePlayerList = Collections.synchronizedList(new ArrayList<>());
2020-01-15 20:20:22 +01:00
this.eventForwarder = new EventForwarder();
2020-08-25 15:07:42 +02:00
this.pluginInstance = new Plugin(version, "bukkit", this);
2020-08-19 20:31:20 +02:00
this.commands = new BukkitCommands(this.pluginInstance);
2020-01-18 00:59:51 +01:00
BukkitPlugin.instance = this;
2020-01-15 20:20:22 +01:00
}
2020-01-11 11:32:47 +01:00
@Override
public void onEnable() {
2020-01-18 01:30:38 +01:00
//save world so the level.dat is present on new worlds
2020-01-21 23:32:54 +01:00
Logger.global.logInfo("Saving all worlds once, to make sure the level.dat is present...");
2020-01-18 01:30:38 +01:00
for (World world : getServer().getWorlds()) {
world.save();
}
2020-05-10 01:28:09 +02:00
//register events
2020-08-07 17:29:28 +02:00
getServer().getPluginManager().registerEvents(this, this);
2020-01-15 20:20:22 +01:00
getServer().getPluginManager().registerEvents(eventForwarder, this);
2020-05-10 01:28:09 +02:00
//register commands
try {
final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
bukkitCommandMap.setAccessible(true);
CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer());
for (BukkitCommand command : commands.getRootCommands()) {
commandMap.register(command.getLabel(), command);
}
} catch(NoSuchFieldException | SecurityException | IllegalAccessException e) {
Logger.global.logError("Failed to register commands!", e);
}
//tab completions
getServer().getPluginManager().registerEvents(commands, this);
//update online-player collections
this.onlinePlayerList.clear();
this.onlinePlayerMap.clear();
for (org.bukkit.entity.Player player : getServer().getOnlinePlayers()) {
BukkitPlayer bukkitPlayer = new BukkitPlayer(player.getUniqueId());
onlinePlayerMap.put(player.getUniqueId(), bukkitPlayer);
onlinePlayerList.add(bukkitPlayer);
}
2020-08-07 17:29:28 +02:00
//start updating players
getServer().getScheduler().runTaskTimer(this, this::updateSomePlayers, 1, 1);
2020-05-10 01:28:09 +02:00
//load bluemap
2020-01-15 20:20:22 +01:00
getServer().getScheduler().runTaskAsynchronously(this, () -> {
try {
Logger.global.logInfo("Loading...");
2020-08-19 20:31:20 +02:00
this.pluginInstance.load();
if (pluginInstance.isLoaded()) Logger.global.logInfo("Loaded!");
} catch (IOException | ParseResourceException | RuntimeException e) {
Logger.global.logError("Failed to load!", e);
2020-08-19 20:31:20 +02:00
this.pluginInstance.unload();
2020-01-15 20:20:22 +01:00
}
});
//init bstats
new MetricsLite(this);
2020-01-11 11:32:47 +01:00
}
@Override
public void onDisable() {
2020-01-15 20:20:22 +01:00
Logger.global.logInfo("Stopping...");
2020-08-07 17:29:28 +02:00
getServer().getScheduler().cancelTasks(this);
2020-08-19 20:31:20 +02:00
pluginInstance.unload();
2020-01-15 20:20:22 +01:00
Logger.global.logInfo("Saved and stopped!");
}
@Override
public void registerListener(ServerEventListener listener) {
eventForwarder.addListener(listener);
}
@Override
public void unregisterAllListeners() {
eventForwarder.removeAllListeners();
}
@Override
public UUID getUUIDForWorld(File worldFolder) throws IOException {
//if it is a dimension folder
if (!new File(worldFolder, "level.dat").exists()) {
worldFolder = worldFolder.getParentFile();
}
2020-01-18 00:59:51 +01:00
final File normalizedWorldFolder = worldFolder.getCanonicalFile();
Future<UUID> futureUUID;
if (!Bukkit.isPrimaryThread()) {
futureUUID = Bukkit.getScheduler().callSyncMethod(BukkitPlugin.getInstance(), () -> getUUIDForWorldSync(normalizedWorldFolder));
} else {
futureUUID = CompletableFuture.completedFuture(getUUIDForWorldSync(normalizedWorldFolder));
}
try {
return futureUUID.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
2020-01-18 00:59:51 +01:00
throw new IOException(e);
} catch (ExecutionException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
} else {
throw new IOException(e);
}
}
}
2020-05-10 17:29:16 +02:00
@Override
public String getWorldName(UUID worldUUID) {
World world = getServer().getWorld(worldUUID);
if (world != null) return world.getName();
return null;
}
2020-01-18 00:59:51 +01:00
private UUID getUUIDForWorldSync (File worldFolder) throws IOException {
2020-01-15 20:20:22 +01:00
for (World world : getServer().getWorlds()) {
if (worldFolder.equals(world.getWorldFolder().getCanonicalFile())) return world.getUID();
2020-01-15 20:20:22 +01:00
}
2020-01-11 11:32:47 +01:00
throw new IOException("There is no world with this folder loaded: " + worldFolder.getPath());
2020-01-15 20:20:22 +01:00
}
@Override
public File getConfigFolder() {
return getDataFolder();
2020-01-11 11:32:47 +01:00
}
2020-01-15 20:20:22 +01:00
public Plugin getBlueMap() {
2020-08-19 20:31:20 +02:00
return pluginInstance;
2020-01-11 11:32:47 +01:00
}
2020-01-18 00:59:51 +01:00
public static BukkitPlugin getInstance() {
return instance;
}
2020-08-07 17:29:28 +02:00
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerJoin(PlayerJoinEvent evt) {
BukkitPlayer player = new BukkitPlayer(evt.getPlayer().getUniqueId());
2020-08-07 17:29:28 +02:00
onlinePlayerMap.put(evt.getPlayer().getUniqueId(), player);
onlinePlayerList.add(player);
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerLeave(PlayerQuitEvent evt) {
UUID playerUUID = evt.getPlayer().getUniqueId();
onlinePlayerMap.remove(playerUUID);
synchronized (onlinePlayerList) {
onlinePlayerList.removeIf(p -> p.getUuid().equals(playerUUID));
}
}
2020-07-02 13:08:47 +02:00
@Override
public Collection<Player> getOnlinePlayers() {
2020-08-07 17:29:28 +02:00
return onlinePlayerMap.values();
2020-07-02 13:08:47 +02:00
}
@Override
public Optional<Player> getPlayer(UUID uuid) {
2020-08-07 17:29:28 +02:00
return Optional.ofNullable(onlinePlayerMap.get(uuid));
}
@Override
public boolean persistWorldChanges(UUID worldUUID) throws IOException, IllegalArgumentException {
try {
return Bukkit.getScheduler().callSyncMethod(this, () -> {
World world = Bukkit.getWorld(worldUUID);
if (world == null) throw new IllegalArgumentException("There is no world with this uuid: " + worldUUID);
world.save();
return true;
}).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(e);
} catch (ExecutionException e) {
Throwable t = e.getCause();
if (t instanceof IOException) throw (IOException) t;
if (t instanceof IllegalArgumentException) throw (IllegalArgumentException) t;
throw new IOException(t);
}
}
2020-08-07 17:29:28 +02:00
/**
* Only update some of the online players each tick to minimize performance impact on the server-thread.
* Only call this method on the server-thread.
*/
private void updateSomePlayers() {
int onlinePlayerCount = onlinePlayerList.size();
if (onlinePlayerCount == 0) return;
int playersToBeUpdated = onlinePlayerCount / 20; //with 20 tps, each player is updated once a second
if (playersToBeUpdated == 0) playersToBeUpdated = 1;
for (int i = 0; i < playersToBeUpdated; i++) {
playerUpdateIndex++;
if (playerUpdateIndex >= 20 && playerUpdateIndex >= onlinePlayerCount) playerUpdateIndex = 0;
if (playerUpdateIndex < onlinePlayerCount) {
onlinePlayerList.get(playerUpdateIndex).update();
2020-08-07 17:29:28 +02:00
}
}
2020-07-02 13:08:47 +02:00
}
2020-01-18 00:59:51 +01:00
2020-01-11 11:32:47 +01:00
}