diff --git a/ansible/build.gradle.kts b/ansible/build.gradle.kts index 54523c236..83ff68fed 100644 --- a/ansible/build.gradle.kts +++ b/ansible/build.gradle.kts @@ -65,7 +65,7 @@ dependencies { pvpPlugin(project(path = ":plugins:civchat2-paper")) pvpPlugin(project(path = ":plugins:namecolors-paper")) - proxyPlugin(project(path = ":plugins:civproxy-velocity")) + proxyPlugin(project(path = ":plugins:civproxy-velocity", configuration = "shadow")) proxyPlugin(project(path = ":plugins:announcements-velocity", configuration = "shadow")) } diff --git a/plugins/announcements-velocity/build.gradle.kts b/plugins/announcements-velocity/build.gradle.kts index 9a5da4709..f48414595 100644 --- a/plugins/announcements-velocity/build.gradle.kts +++ b/plugins/announcements-velocity/build.gradle.kts @@ -9,5 +9,5 @@ dependencies { annotationProcessor(libs.velocity.api) implementation(libs.cron.utils) - implementation(libs.configurate.yaml) + api(libs.configurate.yaml) } diff --git a/plugins/citadel-paper/src/main/resources/config.yml b/plugins/citadel-paper/src/main/resources/config.yml index 6c6735957..f495a7ed5 100644 --- a/plugins/citadel-paper/src/main/resources/config.yml +++ b/plugins/citadel-paper/src/main/resources/config.yml @@ -221,7 +221,7 @@ hangers_inherit_reinforcement: false # reinforcement_damageMultiplier is m where BlockDamage = 2 ^ (n/m) where n is equal to the number of days the group has been inactive reinforcement_damageMultiplier: 365 database: - ==: vg.civcraft.mc.civmodcore.dao.DatabaseCredentials + ==: net.civmc.civcommon.DatabaseCredentials plugin: Citadel user: 'mc_namelayer' password: 'minecraft' diff --git a/plugins/civmodcore-paper/src/main/resources/config.yml b/plugins/civmodcore-paper/src/main/resources/config.yml index 116ad6090..4caf1420e 100644 --- a/plugins/civmodcore-paper/src/main/resources/config.yml +++ b/plugins/civmodcore-paper/src/main/resources/config.yml @@ -1,7 +1,7 @@ # Database connection details, should you want to have a database connection. # Do NOT change the ==: value. database: - ==: vg.civcraft.mc.civmodcore.dao.DatabaseCredentials + ==: net.civmc.civcommon.DatabaseCredentials username: username password: password host: localhost diff --git a/plugins/civproxy-velocity/build.gradle.kts b/plugins/civproxy-velocity/build.gradle.kts index 78e728e5b..a6669428a 100644 --- a/plugins/civproxy-velocity/build.gradle.kts +++ b/plugins/civproxy-velocity/build.gradle.kts @@ -1,8 +1,13 @@ +plugins { + alias(libs.plugins.shadow) +} version = "1.0.0" dependencies { compileOnly("com.velocitypowered:velocity-api:3.4.0-SNAPSHOT") compileOnly("us.ajg0702.queue.api:api:2.8.0") + implementation(libs.hikaricp) + api(libs.configurate.yaml) compileOnly(libs.luckperms.api) annotationProcessor("com.velocitypowered:velocity-api:3.4.0-SNAPSHOT") } diff --git a/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/CivProxyPlugin.java b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/CivProxyPlugin.java index c63e1b9d7..553055c06 100644 --- a/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/CivProxyPlugin.java +++ b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/CivProxyPlugin.java @@ -2,30 +2,22 @@ package net.civmc.civproxy; import com.google.inject.Inject; import com.velocitypowered.api.event.Subscribe; -import com.velocitypowered.api.event.connection.DisconnectEvent; -import com.velocitypowered.api.event.player.KickedFromServerEvent; -import com.velocitypowered.api.event.player.ServerPostConnectEvent; -import com.velocitypowered.api.event.player.ServerPreConnectEvent; import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; import com.velocitypowered.api.plugin.Dependency; import com.velocitypowered.api.plugin.Plugin; -import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.plugin.annotation.DataDirectory; import com.velocitypowered.api.proxy.ProxyServer; -import com.velocitypowered.api.proxy.ServerConnection; -import com.velocitypowered.api.proxy.server.RegisteredServer; -import java.time.Instant; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import net.kyori.adventure.text.Component; -import net.luckperms.api.LuckPermsProvider; -import net.luckperms.api.model.data.TemporaryNodeMergeStrategy; -import net.luckperms.api.model.user.UserManager; -import net.luckperms.api.node.types.PermissionNode; +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import javax.sql.DataSource; +import net.civmc.civproxy.renamer.PlayerRenamer; import org.slf4j.Logger; -import us.ajg0702.queue.api.AjQueueAPI; -import us.ajg0702.queue.api.QueueManager; -import us.ajg0702.queue.api.players.AdaptedPlayer; +import org.spongepowered.configurate.CommentedConfigurationNode; +import org.spongepowered.configurate.yaml.YamlConfigurationLoader; @Plugin(id = "civproxy", name = "CivProxy", version = "1.0.0", authors = {"Okx"}, dependencies = {@Dependency(id = "ajqueue"), @Dependency(id = "luckperms")}) public class CivProxyPlugin { @@ -33,16 +25,17 @@ public class CivProxyPlugin { private final ProxyServer server; private final Logger logger; + private CommentedConfigurationNode config; + + private DataSource source; + @Inject - public CivProxyPlugin(ProxyServer server, Logger logger) { + public CivProxyPlugin(ProxyServer server, Logger logger, @DataDirectory Path dataDirectory) { this.server = server; this.logger = logger; - } - - private final Map players = new ConcurrentHashMap<>(); - - record QueueRecord(Instant instant, String server) { + loadConfig(dataDirectory); + loadConnection(); } public Logger getLogger() { @@ -52,131 +45,63 @@ public class CivProxyPlugin { @Subscribe public void onProxyInitialization(ProxyInitializeEvent event) { new PlayerCount(this, server).start(); + new PlayerRenamer(this, server, source).start(); + new QueueListener(this, server).start(); } - @Subscribe - public void onToMain(KickedFromServerEvent event) { - // Other than banned players, kicked servers should go to the queue on the PvP server + private void loadConnection() { + CommentedConfigurationNode database = config.node("database"); - String name = event.getServer().getServerInfo().getName(); - if (name.equals("pvp")) { - return; + HikariConfig config = new HikariConfig(); + config.setJdbcUrl("jdbc:" + database.node("driver").getString("mysql") + "://" + database.node("host").getString("localhost") + ":" + + database.node("port").getInt(3306) + "/" + database.node("database").getString("minecraft")); + config.setConnectionTimeout(database.node("connection_timeout").getInt(10_000)); + config.setIdleTimeout(database.node("idle_timeout").getInt(600_000)); + config.setMaxLifetime(database.node("max_lifetime").getInt(7_200_000)); + config.setMaximumPoolSize(database.node("poolsize").getInt(10)); + config.setUsername(database.node("username").getString("root")); + String password = database.node("password").getString(); + if (password != null && !password.isBlank()) { + config.setPassword(password); } - if (event.getPlayer().getCurrentServer().isPresent()) { - return; - } - event.setResult(KickedFromServerEvent.RedirectPlayer.create(server.getServer("pvp").get())); - - players.put(event.getPlayer(), new QueueRecord(Instant.now(), name)); + this.source = new HikariDataSource(config); } - @Subscribe - public void onFromPvP(KickedFromServerEvent event) { - String name = event.getServer().getServerInfo().getName(); - if (!name.equals("pvp")) { - return; - } - - if (!(event.getResult() instanceof KickedFromServerEvent.RedirectPlayer)) { - return; - } - - event.setResult(KickedFromServerEvent.DisconnectPlayer.create(event.getServerKickReason().orElse(Component.text("Disconnected")))); - } - - @Subscribe - public void onConnect(ServerPreConnectEvent event) { - // If we are close to the cap, don't allow direct connections to the server and force them to go to the queue - // This prevents players being able to snipe positions and bypass the queue - - if (event.getPreviousServer() != null) { - return; - } - RegisteredServer mainServer = event.getOriginalServer(); - String name = mainServer.getServerInfo().getName(); - if (name.equals("pvp")) { - return; - } - - if (mainServer.getPlayersConnected().size() >= 145 && !event.getPlayer().hasPermission("joinbypass.use")) { -// RegisteredServer mini = server.getServer("mini").orElse(null); -// if (mini != null && mini.getPlayersConnected().size() < 110) { -// event.setResult(ServerPreConnectEvent.ServerResult.allowed(server.getServer("mini").get())); -// } else { - event.setResult(ServerPreConnectEvent.ServerResult.allowed(server.getServer("pvp").get())); -// } - - players.put(event.getPlayer(), new QueueRecord(Instant.now(), name)); - } - } - - @Subscribe - public void onConnect(ServerPostConnectEvent event) { - // Add players coming from the main server to the queue - - QueueRecord record = players.remove(event.getPlayer()); - if (record != null && record.instant().isAfter(Instant.now().minusSeconds(60))) { - QueueManager queueManager = AjQueueAPI.getInstance().getQueueManager(); - AdaptedPlayer player = AjQueueAPI.getInstance().getPlatformMethods().getPlayer(event.getPlayer().getUniqueId()); - queueManager.addToQueue(player, record.server()); - } - } - - @Subscribe - public void onChangeFromMain(ServerPreConnectEvent event) { - if (event.getPreviousServer() == null) { - return; - } - String name = event.getPreviousServer().getServerInfo().getName(); - if (name.equals("pvp")) { - return; - } - - addPriority(event.getPlayer(), name); - } - - @Subscribe - public void onKick(KickedFromServerEvent event) { - RegisteredServer server = event.getServer(); - String name = server.getServerInfo().getName(); - if (name.equals("pvp") - || event.kickedDuringServerConnect() - || event.getPlayer().getCurrentServer().map(c -> c.getServerInfo().getName().equals("pvp")).orElse(true)) { - return; - } - - addPriority(event.getPlayer(), name); - } - - @Subscribe - public void onDisconnect(DisconnectEvent event) { - ServerConnection server = event.getPlayer().getCurrentServer().orElse(null); - if (server == null) { - return; - } - String name = server.getServerInfo().getName(); - if (name.equals("pvp")) { - return; - } - - addPriority(event.getPlayer(), name); - } - - private void addPriority(Player player, String server) { - // Players who just disconnected get 5 minutes of queue priority - - UserManager userManager = LuckPermsProvider.get().getUserManager(); - userManager.loadUser(player.getUniqueId()).thenAccept(user -> { - if (user == null) { - return; + /** + * Loads the config from disk, and creates it if necessary + */ + private void loadConfig(Path dataDirectory) { + try { + // ensure data directory exists + if (!Files.exists(dataDirectory)) { + Files.createDirectories(dataDirectory); } - user.data().add( - PermissionNode.builder() - .permission("ajqueue.serverpriority." + server + ".10") - .expiry(5, TimeUnit.MINUTES) - .build(), - TemporaryNodeMergeStrategy.REPLACE_EXISTING_IF_DURATION_LONGER); - userManager.saveUser(user); - }); + } catch (IOException e) { + logger.error("Could not create data directory: {}", dataDirectory, e); + return; + } + + // create config file if it doesn't exist + Path configFile = dataDirectory.resolve("config.yml"); + if (!Files.exists(configFile)) { + try (InputStream in = getClass().getResourceAsStream("/config.yml")) { + if (in != null) { + Files.copy(in, configFile); + logger.info("Default configuration file created."); + } else { + logger.error("Default configuration file is missing in resources!"); + return; + } + } catch (IOException e) { + logger.error("Could not create default configuration file: {}", configFile, e); + } + } + + YamlConfigurationLoader loader = YamlConfigurationLoader.builder().path(configFile).build(); + try { + config = loader.load(); + } catch (IOException e) { + throw new RuntimeException("Could not load configuration file: " + configFile, e); + } } } diff --git a/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/QueueListener.java b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/QueueListener.java new file mode 100644 index 000000000..e8cd1bc89 --- /dev/null +++ b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/QueueListener.java @@ -0,0 +1,170 @@ +package net.civmc.civproxy; + +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.event.connection.DisconnectEvent; +import com.velocitypowered.api.event.player.KickedFromServerEvent; +import com.velocitypowered.api.event.player.ServerPostConnectEvent; +import com.velocitypowered.api.event.player.ServerPreConnectEvent; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import com.velocitypowered.api.proxy.ServerConnection; +import com.velocitypowered.api.proxy.server.RegisteredServer; +import java.time.Instant; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import net.kyori.adventure.text.Component; +import net.luckperms.api.LuckPermsProvider; +import net.luckperms.api.model.data.TemporaryNodeMergeStrategy; +import net.luckperms.api.model.user.UserManager; +import net.luckperms.api.node.types.PermissionNode; +import us.ajg0702.queue.api.AjQueueAPI; +import us.ajg0702.queue.api.QueueManager; +import us.ajg0702.queue.api.players.AdaptedPlayer; + +public class QueueListener { + + private final Map players = new ConcurrentHashMap<>(); + + private final CivProxyPlugin plugin; + private final ProxyServer server; + + public QueueListener(CivProxyPlugin plugin, ProxyServer server) { + this.plugin = plugin; + this.server = server; + } + + record QueueRecord(Instant instant, String server) { + + } + + public void start() { + server.getEventManager().register(plugin, this); + } + + @Subscribe + public void onToMain(KickedFromServerEvent event) { + // Other than banned players, kicked servers should go to the queue on the PvP server + + String name = event.getServer().getServerInfo().getName(); + if (name.equals("pvp")) { + return; + } + if (event.getPlayer().getCurrentServer().isPresent()) { + return; + } + event.setResult(KickedFromServerEvent.RedirectPlayer.create(server.getServer("pvp").get())); + + players.put(event.getPlayer(), new QueueRecord(Instant.now(), name)); + } + + @Subscribe + public void onFromPvP(KickedFromServerEvent event) { + String name = event.getServer().getServerInfo().getName(); + if (!name.equals("pvp")) { + return; + } + + if (!(event.getResult() instanceof KickedFromServerEvent.RedirectPlayer)) { + return; + } + + event.setResult(KickedFromServerEvent.DisconnectPlayer.create(event.getServerKickReason().orElse(Component.text("Disconnected")))); + } + + @Subscribe + public void onConnect(ServerPreConnectEvent event) { + // If we are close to the cap, don't allow direct connections to the server and force them to go to the queue + // This prevents players being able to snipe positions and bypass the queue + + if (event.getPreviousServer() != null) { + return; + } + RegisteredServer mainServer = event.getOriginalServer(); + String name = mainServer.getServerInfo().getName(); + if (name.equals("pvp")) { + return; + } + + if (mainServer.getPlayersConnected().size() >= 145 && !event.getPlayer().hasPermission("joinbypass.use")) { +// RegisteredServer mini = server.getServer("mini").orElse(null); +// if (mini != null && mini.getPlayersConnected().size() < 110) { +// event.setResult(ServerPreConnectEvent.ServerResult.allowed(server.getServer("mini").get())); +// } else { + event.setResult(ServerPreConnectEvent.ServerResult.allowed(server.getServer("pvp").get())); +// } + + players.put(event.getPlayer(), new QueueRecord(Instant.now(), name)); + } + } + + @Subscribe + public void onConnect(ServerPostConnectEvent event) { + // Add players coming from the main server to the queue + + QueueRecord record = players.remove(event.getPlayer()); + if (record != null && record.instant().isAfter(Instant.now().minusSeconds(60))) { + QueueManager queueManager = AjQueueAPI.getInstance().getQueueManager(); + AdaptedPlayer player = AjQueueAPI.getInstance().getPlatformMethods().getPlayer(event.getPlayer().getUniqueId()); + queueManager.addToQueue(player, record.server()); + } + } + + @Subscribe + public void onChangeFromMain(ServerPreConnectEvent event) { + if (event.getPreviousServer() == null) { + return; + } + String name = event.getPreviousServer().getServerInfo().getName(); + if (name.equals("pvp")) { + return; + } + + addPriority(event.getPlayer(), name); + } + + @Subscribe + public void onKick(KickedFromServerEvent event) { + RegisteredServer server = event.getServer(); + String name = server.getServerInfo().getName(); + if (name.equals("pvp") + || event.kickedDuringServerConnect() + || event.getPlayer().getCurrentServer().map(c -> c.getServerInfo().getName().equals("pvp")).orElse(true)) { + return; + } + + addPriority(event.getPlayer(), name); + } + + @Subscribe + public void onDisconnect(DisconnectEvent event) { + ServerConnection server = event.getPlayer().getCurrentServer().orElse(null); + if (server == null) { + return; + } + String name = server.getServerInfo().getName(); + if (name.equals("pvp")) { + return; + } + + addPriority(event.getPlayer(), name); + } + + private void addPriority(Player player, String server) { + // Players who just disconnected get 5 minutes of queue priority + + UserManager userManager = LuckPermsProvider.get().getUserManager(); + userManager.loadUser(player.getUniqueId()).thenAccept(user -> { + if (user == null) { + return; + } + user.data().add( + PermissionNode.builder() + .permission("ajqueue.serverpriority." + server + ".10") + .expiry(5, TimeUnit.MINUTES) + .build(), + TemporaryNodeMergeStrategy.REPLACE_EXISTING_IF_DURATION_LONGER); + userManager.saveUser(user); + }); + } +} diff --git a/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/database/Migrator.java b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/database/Migrator.java new file mode 100644 index 000000000..d0c0ca959 --- /dev/null +++ b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/database/Migrator.java @@ -0,0 +1,65 @@ +package net.civmc.civproxy.database; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; +import java.util.NavigableMap; +import java.util.Objects; +import java.util.TreeMap; + +public class Migrator { + + private final Map> migrations = new HashMap<>(); + + public void registerMigration(String namespace, int id, String... sql) { + Objects.requireNonNull(namespace); + Objects.requireNonNull(sql); + if (namespace.length() > 64) { + throw new IllegalArgumentException("namespace must not be longer than 64 characters"); + } + if (id < 0) { + throw new IllegalArgumentException("migation id must be at least 0"); + } + boolean present = this.migrations.computeIfAbsent(namespace, k -> new TreeMap<>()).putIfAbsent(id, sql) != null; + if (present) { + throw new IllegalStateException("Migration already exists with namespace " + namespace + " and ID " + id); + } + } + + public void migrate(Connection connection) throws SQLException { + connection.setAutoCommit(false); + connection.createStatement().executeUpdate("CREATE TABLE IF NOT EXISTS migrations (" + + "namespace VARCHAR(64) PRIMARY KEY," + + "id INT NOT NULL)"); + + for (Map.Entry> entry : migrations.entrySet()) { + PreparedStatement getMigrationId = connection.prepareStatement("SELECT id FROM migrations WHERE namespace = ? FOR UPDATE"); + getMigrationId.setString(1, entry.getKey()); + ResultSet resultSet = getMigrationId.executeQuery(); + int minId; + if (resultSet.next()) { + minId = resultSet.getInt("id"); + } else { + minId = -1; + } + + NavigableMap value = entry.getValue().tailMap(minId, false); + int maxId = entry.getValue().lastKey(); + for (String[] migration : value.sequencedValues()) { + for (String sql : migration) { + connection.createStatement().executeUpdate(sql); + } + } + + if (maxId != minId) { + PreparedStatement setMigrationId = connection.prepareStatement("REPLACE INTO migations (namespace, id) VALUES (?, ?)"); + setMigrationId.setString(1, entry.getKey()); + setMigrationId.setInt(2, maxId); + } + } + connection.setAutoCommit(true); + } +} diff --git a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/database/AssociationList.java b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/renamer/AssociationList.java similarity index 84% rename from plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/database/AssociationList.java rename to plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/renamer/AssociationList.java index 2377bf5db..c1a07182e 100644 --- a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/database/AssociationList.java +++ b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/renamer/AssociationList.java @@ -1,4 +1,4 @@ -package vg.civcraft.mc.namelayer.database; +package net.civmc.civproxy.renamer; import java.sql.Connection; import java.sql.PreparedStatement; @@ -7,13 +7,13 @@ import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import java.util.logging.Level; -import java.util.logging.Logger; -import vg.civcraft.mc.civmodcore.dao.ManagedDatasource; +import javax.sql.DataSource; +import net.civmc.civproxy.database.Migrator; +import org.slf4j.Logger; public class AssociationList { - private ManagedDatasource db; + private DataSource db; private Logger logger; private static final String addPlayer = "call addplayertotable(?, ?)"; // order player name, uuid @@ -22,15 +22,16 @@ public class AssociationList { private static final String changePlayerName = "update Name_player set player=? where uuid=?"; private static final String getAllPlayerInfo = "select * from Name_player"; - public AssociationList(Logger logger, ManagedDatasource db) { + public AssociationList(Logger logger, DataSource db) { this.db = db; this.logger = logger; } - public void registerMigrations() { + public void migrate() { + Migrator migrator = new Migrator(); // creates the player table // Where uuid and host names will be stored - db.registerMigration(-1, false, + migrator.registerMigration("renamer", 0, "CREATE TABLE IF NOT EXISTS `Name_player` (" + "`uuid` varchar(40) NOT NULL," + "`player` varchar(40) NOT NULL," @@ -41,7 +42,7 @@ public class AssociationList { + "amount int(10) not null," + "primary key (player));"); - db.registerMigration(0, false, + migrator.registerMigration("renamer", 1, "drop procedure if exists addplayertotable", "create definer=current_user procedure addplayertotable(" + "in pl varchar(40), in uu varchar(40)) sql security invoker begin " @@ -83,8 +84,12 @@ public class AssociationList { + "END LOOP setName;" + "end if;" + "end"); - // For future migrations, check the max migrations that is combination of here and - // GroupManagerDao! + + try { + migrator.migrate(db.getConnection()); + } catch (SQLException e) { + throw new RuntimeException(e); + } } /** @@ -102,10 +107,10 @@ public class AssociationList { String uuid = set.getString("uuid"); return UUID.fromString(uuid); } catch (SQLException se) { - logger.log(Level.WARNING, "Failed to get UUID for playername " + playername, se); + logger.warn("Failed to get UUID for playername " + playername, se); } } catch (SQLException e) { - logger.log(Level.WARNING, "Failed to set up query to get UUID for playername " + playername, e); + logger.warn("Failed to set up query to get UUID for playername " + playername, e); } return null; } @@ -125,10 +130,10 @@ public class AssociationList { String playername = set.getString("player"); return playername; } catch (SQLException se) { - logger.log(Level.WARNING, "Failed to get current player name for UUID " + uuid, se); + logger.warn("Failed to get current player name for UUID " + uuid, se); } } catch (SQLException e) { - logger.log(Level.WARNING, "Failed to set up query to get current player name for UUID " + uuid, e); + logger.warn("Failed to set up query to get current player name for UUID " + uuid, e); } return null; } @@ -140,9 +145,9 @@ public class AssociationList { addPlayer.setString(2, uuid.toString()); addPlayer.execute(); } catch (SQLException e) { - logger.log(Level.WARNING, "Failed to add new player mapping {0} <==> {1}, due to {2}", + logger.warn("Failed to add new player mapping {0} <==> {1}, due to {2}", new Object[]{playername, uuid, e.getMessage()}); - logger.log(Level.WARNING, "Add new player failure: ", e); + logger.warn("Add new player failure: ", e); } } @@ -153,9 +158,9 @@ public class AssociationList { changePlayerName.setString(2, uuid.toString()); changePlayerName.execute(); } catch (SQLException e) { - logger.log(Level.WARNING, "Failed to change player name mapping {0} <==> {1}, due to {2}", + logger.warn("Failed to change player name mapping {0} <==> {1}, due to {2}", new Object[]{newName, uuid, e.getMessage()}); - logger.log(Level.WARNING, "Change player failure: ", e); + logger.warn("Change player failure: ", e); return; // don't add on failure } } @@ -181,7 +186,7 @@ public class AssociationList { uuidMapping.put(uuid, playername); } } catch (SQLException e) { - logger.log(Level.WARNING, "Failed to get all player info", e); + logger.warn("Failed to get all player info", e); } return new PlayerMappingInfo(nameMapping, uuidMapping); } diff --git a/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/renamer/ChangePlayerNameCommand.java b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/renamer/ChangePlayerNameCommand.java new file mode 100644 index 000000000..7a91f03e7 --- /dev/null +++ b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/renamer/ChangePlayerNameCommand.java @@ -0,0 +1,45 @@ +package net.civmc.civproxy.renamer; + +import com.velocitypowered.api.command.CommandSource; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.proxy.ProxyServer; +import net.kyori.adventure.text.Component; +import java.util.UUID; + +public class ChangePlayerNameCommand implements SimpleCommand { + + private final ProxyServer server; + private final AssociationList associationList; + + public ChangePlayerNameCommand(ProxyServer server, AssociationList associationList) { + this.server = server; + this.associationList = associationList; + } + + @Override + public void execute(Invocation invocation) { + CommandSource source = invocation.source(); + String[] args = invocation.arguments(); + if (args.length < 2) { + source.sendPlainMessage("Usage: /" + invocation.alias() + " "); + return; + } + + UUID uuid = associationList.getUUID(args[0]); + if (uuid == null) { + source.sendPlainMessage("Player not found"); + return; + } + String newName = args[1].length() >= 16 ? args[1].substring(0, 16) : args[1]; + associationList.changePlayer(newName, uuid); + source.sendPlainMessage("Changed name of " + args[0] + " to " + newName); + + server.getPlayer(uuid).ifPresent(player -> + player.disconnect(Component.text("Your name has been changed! Please rejoin."))); + } + + @Override + public boolean hasPermission(Invocation invocation) { + return invocation.source().hasPermission("civproxy.changeplayername"); + } +} diff --git a/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/renamer/PlayerRenamer.java b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/renamer/PlayerRenamer.java new file mode 100644 index 000000000..d9720c406 --- /dev/null +++ b/plugins/civproxy-velocity/src/main/java/net/civmc/civproxy/renamer/PlayerRenamer.java @@ -0,0 +1,42 @@ +package net.civmc.civproxy.renamer; + +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.event.player.GameProfileRequestEvent; +import com.velocitypowered.api.proxy.ProxyServer; +import com.velocitypowered.api.util.GameProfile; +import javax.sql.DataSource; +import net.civmc.civproxy.CivProxyPlugin; + +public class PlayerRenamer { + + private final CivProxyPlugin plugin; + private final ProxyServer server; + + private final AssociationList associations; + + public PlayerRenamer(CivProxyPlugin plugin, ProxyServer server, DataSource source) { + this.plugin = plugin; + this.server = server; + this.associations = new AssociationList(plugin.getLogger(), source); + } + + @Subscribe + public void on(GameProfileRequestEvent requestEvent) { + GameProfile profile = requestEvent.getGameProfile(); + associations.addPlayer(profile.getName(), profile.getId()); + + String name = associations.getCurrentName(profile.getId()); + if (name == null) { + associations.addPlayer(profile.getName(), profile.getId()); + name = associations.getCurrentName(profile.getId()); + } + + requestEvent.setGameProfile(requestEvent.getGameProfile().withName(name)); + } + + public void start() { + server.getEventManager().register(plugin, this); + server.getCommandManager().register(server.getCommandManager().metaBuilder("changeplayername").aliases("nlcpn").plugin(this).build(), + new ChangePlayerNameCommand(server, associations)); + } +} diff --git a/plugins/essenceglue-paper/src/main/resources/config.yml b/plugins/essenceglue-paper/src/main/resources/config.yml index 2a43a4b73..d65a1a044 100644 --- a/plugins/essenceglue-paper/src/main/resources/config.yml +++ b/plugins/essenceglue-paper/src/main/resources/config.yml @@ -27,7 +27,7 @@ multiply_pearl_cost: true # KEEP THIS COMMENTED OUT IN THIS DEFAULT CONFIG OTHERWISE SOME CONFIG PARSING WILL CAUSE ISSUES! # Remember also to change the plugin value to match your plugin name. Do NOT change the ==: value. database: - ==: vg.civcraft.mc.civmodcore.dao.DatabaseCredentials + ==: net.civmc.civcommon.DatabaseCredentials plugin: EssenceGlue user: username password: password diff --git a/plugins/heliodor-paper/src/main/resources/config.yml b/plugins/heliodor-paper/src/main/resources/config.yml index 3f6905720..01ed89827 100644 --- a/plugins/heliodor-paper/src/main/resources/config.yml +++ b/plugins/heliodor-paper/src/main/resources/config.yml @@ -2,7 +2,7 @@ enable_heliodor: true database: - ==: vg.civcraft.mc.civmodcore.dao.DatabaseCredentials + ==: net.civmc.civcommon.DatabaseCredentials user: 'root' password: 'root' host: 'localhost' diff --git a/plugins/jukealert-paper/src/main/java/com/untamedears/jukealert/database/JukeAlertDAO.java b/plugins/jukealert-paper/src/main/java/com/untamedears/jukealert/database/JukeAlertDAO.java index 93dbf367a..3e6cb704b 100644 --- a/plugins/jukealert-paper/src/main/java/com/untamedears/jukealert/database/JukeAlertDAO.java +++ b/plugins/jukealert-paper/src/main/java/com/untamedears/jukealert/database/JukeAlertDAO.java @@ -5,11 +5,9 @@ import com.untamedears.jukealert.SnitchManager; import com.untamedears.jukealert.model.Snitch; import com.untamedears.jukealert.model.SnitchFactoryType; import com.untamedears.jukealert.model.SnitchTypeManager; -import com.untamedears.jukealert.model.actions.ActionCacheState; import com.untamedears.jukealert.model.actions.LoggedActionFactory; import com.untamedears.jukealert.model.actions.LoggedActionPersistence; import com.untamedears.jukealert.model.actions.abstr.LoggableAction; -import com.untamedears.jukealert.model.actions.abstr.LoggablePlayerAction; import com.untamedears.jukealert.model.appender.AbstractSnitchAppender; import com.untamedears.jukealert.model.appender.DormantCullingAppender; import com.untamedears.jukealert.model.appender.LeverToggleAppender; diff --git a/plugins/jukealert-paper/src/main/resources/config.yml b/plugins/jukealert-paper/src/main/resources/config.yml index 8b85d133a..00efcbb5d 100644 --- a/plugins/jukealert-paper/src/main/resources/config.yml +++ b/plugins/jukealert-paper/src/main/resources/config.yml @@ -1,5 +1,5 @@ database: - ==: vg.civcraft.mc.civmodcore.dao.DatabaseCredentials + ==: net.civmc.civcommon.DatabaseCredentials plugin: JukeAlert user: username password: squidLover69 diff --git a/plugins/kirabukkitgateway-paper/src/main/resources/config.yml b/plugins/kirabukkitgateway-paper/src/main/resources/config.yml index ed5fd3bbc..a1913a2fa 100644 --- a/plugins/kirabukkitgateway-paper/src/main/resources/config.yml +++ b/plugins/kirabukkitgateway-paper/src/main/resources/config.yml @@ -2,7 +2,7 @@ # KEEP THIS COMMENTED OUT IN THIS DEFAULT CONFIG OTHERWISE BAD THINGS! # Do NOT change the ==: value. #database: -# ==: vg.civcraft.mc.civmodcore.dao.ManagedDatasource +# ==: net.civmc.civcommon.ManagedDatasource # plugin: KiraBukkitGateway # user: username # password: password diff --git a/plugins/kitpvp-paper/src/main/java/net/civmc/kitpvp/sql/SqlKitPvpDao.java b/plugins/kitpvp-paper/src/main/java/net/civmc/kitpvp/sql/SqlKitPvpDao.java index 414e37b5a..95bdd042b 100644 --- a/plugins/kitpvp-paper/src/main/java/net/civmc/kitpvp/sql/SqlKitPvpDao.java +++ b/plugins/kitpvp-paper/src/main/java/net/civmc/kitpvp/sql/SqlKitPvpDao.java @@ -9,7 +9,6 @@ import java.util.List; import java.util.UUID; import net.civmc.kitpvp.kit.Kit; import net.civmc.kitpvp.kit.KitPvpDao; -import net.civmc.kitpvp.ranked.RankedDao; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import vg.civcraft.mc.civmodcore.dao.ManagedDatasource; diff --git a/plugins/kitpvp-paper/src/main/resources/config.yml b/plugins/kitpvp-paper/src/main/resources/config.yml index 6e55f2e11..8c86affd8 100644 --- a/plugins/kitpvp-paper/src/main/resources/config.yml +++ b/plugins/kitpvp-paper/src/main/resources/config.yml @@ -1,5 +1,5 @@ database: - ==: vg.civcraft.mc.civmodcore.dao.DatabaseCredentials + ==: net.civmc.civcommon.DatabaseCredentials username: username password: password host: localhost diff --git a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/MojangNames.java b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/MojangNames.java deleted file mode 100644 index 9f3c13e48..000000000 --- a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/MojangNames.java +++ /dev/null @@ -1,120 +0,0 @@ -package vg.civcraft.mc.namelayer; - -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.NoSuchFileException; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.util.Collections; -import java.util.Map; -import java.util.TreeMap; -import java.util.UUID; -import org.bukkit.Bukkit; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.scheduler.BukkitTask; -import vg.civcraft.mc.civmodcore.nbt.NbtCompound; -import vg.civcraft.mc.civmodcore.nbt.NbtUtils; -import vg.civcraft.mc.civmodcore.utilities.MoreMapUtils; -import vg.civcraft.mc.namelayer.listeners.AssociationListener; - -public final class MojangNames { - - private static final Map PROFILES = Collections.synchronizedMap( - new TreeMap<>(String.CASE_INSENSITIVE_ORDER)); - private static final String PROFILES_FILE = "mojang.dat"; - private static final long SAVE_DELAY = 20 * 60; // 60 seconds' worth of ticks - private static BukkitTask SAVE_TASK; - - public static void init(final NameLayerPlugin plugin) { - final Path mojangFile = plugin.getDataFile(PROFILES_FILE).toPath(); - // Load all the profiles that already exist - Bukkit.getScheduler().runTaskAsynchronously( - plugin, () -> load(plugin, mojangFile)); - // Set up a process of saving profiles - SAVE_TASK = Bukkit.getScheduler().runTaskTimerAsynchronously( - plugin, () -> save(plugin, mojangFile), SAVE_DELAY, SAVE_DELAY); - } - - public static void reset(final NameLayerPlugin plugin) { - if (!PROFILES.isEmpty()) { - save(plugin, plugin.getDataFile(PROFILES_FILE).toPath()); - PROFILES.clear(); - } - if (SAVE_TASK != null) { - SAVE_TASK.cancel(); - SAVE_TASK = null; - } - } - - private static void load(final NameLayerPlugin plugin, final Path file) { - PROFILES.clear(); - try { - final byte[] data = Files.readAllBytes(file); - final var nbt = new NbtCompound(NbtUtils.fromBytes(data)); - nbt.keys().forEach(key -> PROFILES.put(key, nbt.getUuid(key, null))); - plugin.info("[MojangNames] Mojang profiles loaded!"); - } catch (final NoSuchFileException ignored) { - } catch (final IOException exception) { - plugin.warning("[MojangNames] Could not load Mojang profiles!", exception); - } - } - - private static void save(final NameLayerPlugin plugin, final Path file) { - final var nbt = new NbtCompound(); - PROFILES.forEach(nbt::setUuid); - final byte[] data = NbtUtils.toBytes(nbt.internal()); - try { - Files.write(file, data, - StandardOpenOption.CREATE, - StandardOpenOption.TRUNCATE_EXISTING, - StandardOpenOption.WRITE); - } catch (final IOException exception) { - plugin.warning("[MojangNames] Could not save Mojang profiles!", exception); - return; - } - plugin.info("[MojangNames] Mojang profiles saved!"); - } - - /** - * Returns the player's uuid based on their Mojang name. - * - * @param name The player's Mojang name. - * @return Returns the player's uuid, or null. - */ - public static UUID getMojangUuid(final String name) { - if (Strings.isNullOrEmpty(name)) { - return null; - } - return PROFILES.get(name); - } - - /** - *

Returns the player's Mojang name based on their uuid.

- * - *

Note: The name will be lowercase.

- * - * @param uuid The player's uuid. - * @return Returns the player's Mojang name, or null. - */ - public static String getMojangName(final UUID uuid) { - if (uuid == null) { - return null; - } - return MoreMapUtils.getKeyFromValue(PROFILES, uuid); - } - - /** - * DO NOT USE THIS ANYWHERE OTHER THAN {@link AssociationListener#OnPlayerJoin(PlayerJoinEvent)} - * - * @param uuid The player's uuid. - * @param name The player's Mojang name. - */ - public static void declareMojangName(final UUID uuid, final String name) { - Preconditions.checkNotNull(uuid); - Preconditions.checkArgument(!Strings.isNullOrEmpty(name)); - PROFILES.put(name, uuid); - } - -} diff --git a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/NameAPI.java b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/NameAPI.java index 220d6cdbc..caaf1f1c5 100644 --- a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/NameAPI.java +++ b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/NameAPI.java @@ -3,69 +3,34 @@ package vg.civcraft.mc.namelayer; import java.util.HashMap; import java.util.Map; import java.util.UUID; -import vg.civcraft.mc.namelayer.database.AssociationList; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; public class NameAPI { private static GroupManager groupManager; - private static AssociationList associations; + private static final Map uuidToPlayer = new HashMap<>(); + private static final Map playerToUuid = new HashMap<>(); - private static Map uuidsToName = new HashMap(); - private static Map nameToUUIDS = new HashMap(); - - public NameAPI(GroupManager man, AssociationList ass) { + public NameAPI(GroupManager man) { groupManager = man; - associations = ass; - loadAllPlayerInfo(); + Bukkit.getScheduler().runTaskAsynchronously(NameLayerPlugin.getInstance(), () -> { + Map uuidToPlayer = new HashMap<>(); + Map playerToUuid = new HashMap<>(); + for (OfflinePlayer offlinePlayer : Bukkit.getOfflinePlayers()) { + playerToUuid.put(offlinePlayer.getName(), offlinePlayer.getUniqueId()); + uuidToPlayer.put(offlinePlayer.getUniqueId(), offlinePlayer.getName()); + } + Bukkit.getScheduler().runTask(NameLayerPlugin.getInstance(), () -> { + this.uuidToPlayer.putAll(uuidToPlayer); + this.playerToUuid.putAll(playerToUuid); + }); + }); } - public void loadAllPlayerInfo() { - uuidsToName.clear(); - nameToUUIDS.clear(); - - boolean load = NameLayerPlugin.getInstance().getConfig().getBoolean("persistance.forceloadnamecaching", false); - if (!load) - return; - AssociationList.PlayerMappingInfo pmi = associations.getAllPlayerInfo(); - nameToUUIDS = pmi.nameMapping; - uuidsToName = pmi.uuidMapping; - - } - - public static void resetCache(UUID uuid) { - String name = getCurrentName(uuid); - uuidsToName.remove(uuid); - nameToUUIDS.remove(name); - } - - /** - * Returns the UUID of the player on the given server. - * - * @param playerName The playername. - * @return Returns the UUID of the player. - */ - public static UUID getUUID(String playerName) { - UUID uuid = nameToUUIDS.get(playerName); - if (uuid == null) { - uuid = associations.getUUID(playerName); - nameToUUIDS.put(playerName, uuid); - } - return uuid; - } - - /** - * Gets the playername from a given server from their uuid. - * - * @param uuid uuid of target player - * @return Returns the PlayerName from the UUID. - */ - public static String getCurrentName(UUID uuid) { - String name = uuidsToName.get(uuid); - if (name == null) { - name = associations.getCurrentName(uuid); - uuidsToName.put(uuid, name); - } - return name; + public static void associate(String playerName, UUID uuid) { + uuidToPlayer.put(uuid, playerName); + playerToUuid.put(playerName, uuid); } /** @@ -75,10 +40,11 @@ public class NameAPI { return groupManager; } - /** - * @return Returns an instance of the AssociationList. - */ - public static AssociationList getAssociationList() { - return associations; + public static UUID getUUID(String s) { + return playerToUuid.get(s); + } + + public static String getCurrentName(UUID uuid) { + return uuidToPlayer.get(uuid); } } diff --git a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/NameLayerPlugin.java b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/NameLayerPlugin.java index 5b0973e81..6bac888a4 100644 --- a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/NameLayerPlugin.java +++ b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/NameLayerPlugin.java @@ -11,20 +11,16 @@ import vg.civcraft.mc.civmodcore.ACivMod; import vg.civcraft.mc.civmodcore.dao.DatabaseCredentials; import vg.civcraft.mc.civmodcore.dao.ManagedDatasource; import vg.civcraft.mc.namelayer.command.CommandHandler; -import vg.civcraft.mc.namelayer.database.AssociationList; import vg.civcraft.mc.namelayer.database.GroupManagerDao; import vg.civcraft.mc.namelayer.group.AutoAcceptHandler; import vg.civcraft.mc.namelayer.group.BlackList; import vg.civcraft.mc.namelayer.group.DefaultGroupHandler; -import vg.civcraft.mc.namelayer.listeners.AssociationListener; import vg.civcraft.mc.namelayer.listeners.PlayerListener; import vg.civcraft.mc.namelayer.misc.ClassHandler; -import vg.civcraft.mc.namelayer.misc.NameCleanser; import vg.civcraft.mc.namelayer.permission.PermissionType; public class NameLayerPlugin extends ACivMod { - private static AssociationList associations; private static BlackList blackList; private static GroupManagerDao groupManagerDao; private static DefaultGroupHandler defaultGroupHandler; @@ -49,9 +45,7 @@ public class NameLayerPlugin extends ACivMod { instance = this; loadDatabases(); ClassHandler.Initialize(Bukkit.getServer()); - new NameAPI(new GroupManager(), associations); - NameCleanser.load(config.getConfigurationSection("name_cleanser")); - MojangNames.init(this); + new NameAPI(new GroupManager()); registerListeners(); if (loadGroups) { PermissionType.initialize(); @@ -66,13 +60,11 @@ public class NameLayerPlugin extends ACivMod { } public void registerListeners() { - registerListener(new AssociationListener()); registerListener(new PlayerListener()); } @Override public void onDisable() { - MojangNames.reset(this); super.onDisable(); } @@ -142,9 +134,6 @@ public class NameLayerPlugin extends ACivMod { } - associations = new AssociationList(getLogger(), db); - associations.registerMigrations(); - if (loadGroups) { groupManagerDao = new GroupManagerDao(getLogger(), db); groupManagerDao.registerMigrations(); @@ -170,13 +159,6 @@ public class NameLayerPlugin extends ACivMod { } - /** - * @return Returns the AssocationList. - */ - public static AssociationList getAssociationList() { - return associations; - } - /** * @return Returns the GroupManagerDatabase. */ diff --git a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/command/CommandHandler.java b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/command/CommandHandler.java index 23d0afeaa..5b8713f4a 100644 --- a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/command/CommandHandler.java +++ b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/command/CommandHandler.java @@ -2,6 +2,8 @@ package vg.civcraft.mc.namelayer.command; import co.aikar.commands.BukkitCommandCompletionContext; import co.aikar.commands.CommandCompletions; +import java.util.Arrays; +import java.util.stream.Collectors; import org.jetbrains.annotations.NotNull; import vg.civcraft.mc.civmodcore.commands.CommandManager; import vg.civcraft.mc.namelayer.GroupManager; @@ -9,7 +11,6 @@ import vg.civcraft.mc.namelayer.NameLayerPlugin; import vg.civcraft.mc.namelayer.command.TabCompleters.GroupTabCompleter; import vg.civcraft.mc.namelayer.command.commands.AcceptInvite; import vg.civcraft.mc.namelayer.command.commands.AddBlacklist; -import vg.civcraft.mc.namelayer.command.commands.ChangePlayerName; import vg.civcraft.mc.namelayer.command.commands.CreateGroup; import vg.civcraft.mc.namelayer.command.commands.DeleteGroup; import vg.civcraft.mc.namelayer.command.commands.DisciplineGroup; @@ -41,9 +42,6 @@ import vg.civcraft.mc.namelayer.command.commands.TransferGroup; import vg.civcraft.mc.namelayer.command.commands.UpdateName; import vg.civcraft.mc.namelayer.permission.PermissionType; -import java.util.Arrays; -import java.util.stream.Collectors; - public class CommandHandler extends CommandManager { public CommandHandler(NameLayerPlugin plugin) { @@ -78,7 +76,6 @@ public class CommandHandler extends CommandManager { registerCommand(new PromotePlayer()); registerCommand(new RejectInvite()); registerCommand(new RevokeInvite()); - registerCommand(new ChangePlayerName()); registerCommand(new SetDefaultGroup()); registerCommand(new GetDefaultGroup()); registerCommand(new UpdateName()); diff --git a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/command/commands/ChangePlayerName.java b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/command/commands/ChangePlayerName.java deleted file mode 100644 index d97e28ebc..000000000 --- a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/command/commands/ChangePlayerName.java +++ /dev/null @@ -1,39 +0,0 @@ -package vg.civcraft.mc.namelayer.command.commands; - -import co.aikar.commands.annotation.CommandAlias; -import co.aikar.commands.annotation.CommandPermission; -import co.aikar.commands.annotation.Description; -import co.aikar.commands.annotation.Syntax; -import java.util.UUID; -import org.bukkit.command.CommandSender; -import vg.civcraft.mc.namelayer.NameAPI; -import vg.civcraft.mc.namelayer.command.BaseCommandMiddle; - -/** - * Created by isaac on 2/6/15. - */ - -public class ChangePlayerName extends BaseCommandMiddle { - - @CommandAlias("nlcpn|changeplayername") - @CommandPermission("namelayer.admin") - @Syntax(" ") - @Description("Used by ops to change a players name") - public void execute(CommandSender sender, String currentName, String changedName) { - if (!sender.isOp() && !sender.hasPermission("namelayer.admin")) { - sender.sendMessage("You're not an op. "); - return; - } - UUID player = NameAPI.getUUID(currentName); - if (player == null) { - sender.sendMessage(currentName + " has never logged in"); - return; - } - - String newName = changedName.length() >= 16 ? changedName.substring(0, 16) : changedName; - NameAPI.getAssociationList().changePlayer(newName, player); - NameAPI.resetCache(player); - - sender.sendMessage(currentName + "'s name has been changed to " + newName + ". Have them relog for it to take affect"); - } -} diff --git a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/listeners/AssociationListener.java b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/listeners/AssociationListener.java deleted file mode 100644 index 8bc184f1c..000000000 --- a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/listeners/AssociationListener.java +++ /dev/null @@ -1,74 +0,0 @@ -package vg.civcraft.mc.namelayer.listeners; - -import java.util.UUID; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -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.PlayerLoginEvent; -import vg.civcraft.mc.namelayer.MojangNames; -import vg.civcraft.mc.namelayer.NameAPI; -import vg.civcraft.mc.namelayer.NameLayerPlugin; -import vg.civcraft.mc.namelayer.database.AssociationList; -import vg.civcraft.mc.namelayer.misc.ClassHandler; -import vg.civcraft.mc.namelayer.misc.NameCleanser; -import vg.civcraft.mc.namelayer.misc.ProfileInterface; - -public class AssociationListener implements Listener { - - private AssociationList associations; - - private ClassHandler ch; - - private ProfileInterface game; - - public AssociationListener() { - Bukkit.getScheduler().runTaskLater(NameLayerPlugin.getInstance(), new Runnable() { - - @Override - public void run() { - ch = ClassHandler.ch; - if (ClassHandler.properlyEnabled) - game = ch.getProfileClass(); - - associations = NameAPI.getAssociationList(); - } - - }, 1); - } - - @EventHandler(priority = EventPriority.LOWEST) - public void OnPlayerJoin(PlayerJoinEvent event) { - String playername = event.getPlayer().getName(); - if (NameCleanser.isDirty(playername)) { - if (NameCleanser.isAlertOps()) { - String msg = playername + " has a dirty name"; - if (NameCleanser.isCleanNames()) { - msg += ", this will be fixed"; - } - Bukkit.broadcast(msg, NameCleanser.getAlertPerm()); - } - if (NameCleanser.isCleanNames()) { - playername = NameCleanser.cleanName(playername); - } - } - UUID uuid = event.getPlayer().getUniqueId(); - associations.addPlayer(playername, uuid); - event.setJoinMessage(ChatColor.YELLOW + NameAPI.getCurrentName(uuid) + " joined the game"); - - final Player player = event.getPlayer(); - MojangNames.declareMojangName(player.getUniqueId(), player.getName()); - String name = associations.getCurrentName(player.getUniqueId()); - if (name == null) { - associations.addPlayer(player.getName(), player.getUniqueId()); - name = associations.getCurrentName(player.getUniqueId()); - } - - - if (game != null) - game.setPlayerProfile(player, name); - } -} diff --git a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/listeners/PlayerListener.java b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/listeners/PlayerListener.java index 96a53ad83..919dcb2c7 100644 --- a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/listeners/PlayerListener.java +++ b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/listeners/PlayerListener.java @@ -27,6 +27,8 @@ public class PlayerListener implements Listener { Player p = event.getPlayer(); UUID uuid = p.getUniqueId(); + NameAPI.associate(p.getName(), p.getUniqueId()); + if (!p.hasPlayedBefore()) { handleFirstJoin(p); } diff --git a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/misc/NameCleanser.java b/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/misc/NameCleanser.java deleted file mode 100644 index a82046e07..000000000 --- a/plugins/namelayer-paper/src/main/java/vg/civcraft/mc/namelayer/misc/NameCleanser.java +++ /dev/null @@ -1,100 +0,0 @@ -package vg.civcraft.mc.namelayer.misc; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.bukkit.configuration.ConfigurationSection; - -public class NameCleanser { - - private static boolean enabled = true; - private static boolean cleanNames; - private static boolean alertOps; - private static String alertPerm; - private static List cleanWords; - private static Pattern wordPattern; - private static Random rng; - - public static void load(ConfigurationSection config) { - if (config == null) { - enabled = false; - return; - } - try { - List badWords = config.getStringList("bad_words"); - ConfigurationSection opts = config.getConfigurationSection("opts"); - List> options = new ArrayList<>(); - for (String key : opts.getKeys(false)) { - options.add(opts.getCharacterList(key)); - } - StringBuilder patternBuilder = new StringBuilder(); - patternBuilder.append("("); - for (String word : badWords) { - for (char c : word.toCharArray()) { - patternBuilder.append("["); - if (Character.isAlphabetic(c)) { - patternBuilder.append(Character.toUpperCase(c)); - patternBuilder.append(Character.toLowerCase(c)); - } - for (List list : options) { - if (list.contains(c)) { - for (Character other : list) { - if (!other.equals(c)) { - if (Character.isAlphabetic(other)) { - patternBuilder.append(Character.toUpperCase(other)); - patternBuilder.append(Character.toLowerCase(other)); - } else { - patternBuilder.append(other); - } - } - } - } - } - patternBuilder.append("]"); - } - patternBuilder.append("|"); - } - patternBuilder.setCharAt(patternBuilder.lastIndexOf("|"), ')'); - wordPattern = Pattern.compile(patternBuilder.toString()); - cleanWords = config.getStringList("clean_words"); - cleanNames = config.getBoolean("clean_names"); - alertOps = config.getBoolean("alert_ops"); - alertPerm = config.getString("alert_perm", "namelayer.alert_dirty_name"); - rng = new Random(); - } catch (Exception e) { - enabled = false; - } - } - - public static boolean isDirty(String name) { - return enabled && wordPattern.matcher(name).find(); - } - - public static String cleanName(String name) { - if (!enabled) return name; - Matcher matcher = wordPattern.matcher(name); - while (matcher.find()) { - name = matcher.replaceFirst(cleanWords.get(rng.nextInt(cleanWords.size()))); - matcher.reset(name); - } - return name; - } - - public static boolean isCleanNames() { - return cleanNames; - } - - public static boolean isAlertOps() { - return alertOps; - } - - public static String getAlertPerm() { - return alertPerm; - } - - public static boolean isEnabled() { - return enabled; - } -} diff --git a/plugins/realisticbiomes-paper/src/main/resources/config.yml b/plugins/realisticbiomes-paper/src/main/resources/config.yml index 3ef8c018f..0c53ec28c 100644 --- a/plugins/realisticbiomes-paper/src/main/resources/config.yml +++ b/plugins/realisticbiomes-paper/src/main/resources/config.yml @@ -1057,7 +1057,7 @@ plants: cold_forest: 1.0 freshwater: 1.0 database: - ==: vg.civcraft.mc.civmodcore.dao.DatabaseCredentials + ==: net.civmc.civcommon.DatabaseCredentials plugin: RealisticBiomes user: 'root' password: 'root' diff --git a/plugins/realisticbiomes2-paper/src/main/resources/config.yml b/plugins/realisticbiomes2-paper/src/main/resources/config.yml index 670180857..473d69a97 100644 --- a/plugins/realisticbiomes2-paper/src/main/resources/config.yml +++ b/plugins/realisticbiomes2-paper/src/main/resources/config.yml @@ -872,7 +872,7 @@ plants: max_yield: 64 database: - ==: vg.civcraft.mc.civmodcore.dao.DatabaseCredentials + ==: net.civmc.civcommon.DatabaseCredentials plugin: RealisticBiomes user: 'root' password: 'root'