Added a terrible way to sync parties cus I don't have time to implement a proper solution atm

This commit is contained in:
Teriuihi 2021-08-08 13:30:57 +02:00
parent 30cc4b3ead
commit 9551785f83
7 changed files with 132 additions and 87 deletions

View File

@ -1,14 +1,12 @@
package com.alttd.chat.database;
import com.alttd.chat.managers.ChatUserManager;
import com.alttd.chat.managers.PartyManager;
import com.alttd.chat.objects.ChatUser;
import com.alttd.chat.objects.Mail;
import com.alttd.chat.objects.Party;
import com.alttd.chat.objects.channels.Channel;
import com.alttd.chat.util.ALogger;
import net.kyori.adventure.text.minimessage.MiniMessage;
import java.awt.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -24,7 +22,7 @@ public class Queries {
List<String> tables = new ArrayList<>();
tables.add("CREATE TABLE IF NOT EXISTS ignored_users (`uuid` VARCHAR(36) NOT NULL, `ignored_uuid` VARCHAR(36) NOT NULL, PRIMARY KEY (`uuid`, `ignored_uuid`))");
tables.add("CREATE TABLE IF NOT EXISTS parties (`id` INT NOT NULL AUTO_INCREMENT, `owner_uuid` VARCHAR(36) NOT NULL, `party_name` VARCHAR(36) NOT NULL, `password` VARCHAR(36), PRIMARY KEY (`id`))");
tables.add("CREATE TABLE IF NOT EXISTS chat_users (`uuid` VARCHAR(36) NOT NULL, `party_id` INT NOT NULL, `toggled_chat` BIT(1) DEFAULT b'0', `toggled_gc` BIT(1) DEFAULT b'0', PRIMARY KEY (`uuid`))");
tables.add("CREATE TABLE IF NOT EXISTS chat_users (`uuid` VARCHAR(36) NOT NULL, `party_id` INT NOT NULL, `toggled_channel` VARCHAR(36) NULL DEFAULT NULL, PRIMARY KEY (`uuid`))");
tables.add("CREATE TABLE IF NOT EXISTS mails (`id` INT NOT NULL AUTO_INCREMENT, `uuid` VARCHAR(36) NOT NULL, `from` VARCHAR(36) NOT NULL, `message` VARCHAR(256) NOT NULL, `sendtime` BIGINT default 0, `readtime` BIGINT default 0, PRIMARY KEY (`id`))");
try {
@ -197,6 +195,42 @@ public class Queries {
}
}
public static void loadPartyUsers(int id) {
String query = "SELECT chat_users.uuid, nicknames.nickname, utility_users.Username " +
"FROM chat_users " +
"LEFT OUTER JOIN nicknames ON chat_users.UUID = nicknames.uuid " +
"LEFT OUTER JOIN utility_users ON chat_users.uuid = utility_users.UUID " +
"WHERE party_id = ?";
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, id);
ResultSet resultSet = preparedStatement.executeQuery();
Party party = PartyManager.getParty(id);
if (party == null) {
ALogger.warn("Tried to load invalid party");
return;
}
party.resetPartyUsers();
while (resultSet.next()) {
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
// String displayName = resultSet.getString("nickname");
// if (displayName == null || displayName.isEmpty()) {
// displayName = resultSet.getString("Username");
// }
String displayName = resultSet.getString("Username"); // FIXME: 08/08/2021 only using display name till we can fix nickname colors
party.putUser(uuid, displayName);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Party addParty(UUID partyOwner, String partyName, String password) {
String query = "INSERT INTO parties (owner_uuid, party_name, password) VALUES (?, ?, ?)";
@ -321,27 +355,6 @@ public class Queries {
//-----------------------------------------
public static void loadChatUsers() { //TODO Get parties from cache somewhere
String query = "SELECT * FROM chat_users WHERE party_id > -1";
try {
Connection connection = DatabaseConnection.getConnection();
ResultSet resultSet = connection.prepareStatement(query).executeQuery();
while (resultSet.next()) {
UUID uuid = UUID.fromString(resultSet.getString("uuid"));
int partyId = resultSet.getInt("party_id");
boolean toggled_chat = resultSet.getInt("toggled_chat") == 1;
boolean toggle_Gc = resultSet.getInt("toggled_gc") == 1;
ChatUserManager.addUser(new ChatUser(uuid, partyId, toggled_chat, toggle_Gc));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static ChatUser loadChatUser(UUID uuid) { //TODO Get parties from cache somewhere
String query = "SELECT * FROM chat_users WHERE uuid = ?";
ChatUser user = null;
@ -356,9 +369,9 @@ public class Queries {
while (resultSet.next()) {
int partyId = resultSet.getInt("party_id");
boolean toggled_chat = resultSet.getInt("toggled_chat") == 1;
boolean toggle_Gc = resultSet.getInt("toggled_gc") == 1;
user = new ChatUser(uuid, partyId, toggled_chat, toggle_Gc);
String toggledChannel = resultSet.getString("toggled_channel");
Channel channel = toggledChannel == null ? null : Channel.getChatChannel(toggledChannel);
user = new ChatUser(uuid, partyId, channel);
}
} catch (SQLException e) {
@ -367,20 +380,13 @@ public class Queries {
return user;
}
public static void setPartyChatState(boolean toggledChat, UUID uuid) {
setBitWhereId("UPDATE chat_users set toggled_chat = ? WHERE uuid = ?", toggledChat, uuid);
}
public static void setGlobalChatState(boolean globalChat, UUID uuid) {
setBitWhereId("UPDATE chat_users set toggled_gc = ? WHERE uuid = ?", globalChat, uuid);
}
private static void setBitWhereId(String query, boolean bool, UUID uuid) {
public static void setToggledChannel(Channel channel, UUID uuid) {
String sql = "UPDATE chat_users set toggled_channel = ? WHERE uuid = ?";
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, bool ? 1 : 0);
statement.setString(1, channel.getChannelName());
statement.setString(2, uuid.toString());
statement.execute();
@ -418,19 +424,17 @@ public class Queries {
}
public static void saveUser(ChatUser user) {
String query = "INSERT INTO chat_users (uuid, party_id, toggled_chat, toggled_gc) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE party_id = ?, toggled_chat = ?, toggled_gc = ?";
String query = "INSERT INTO chat_users (uuid, party_id, toggled_channel) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE party_id = ?, toggled_channel = ?";
try {
Connection connection = DatabaseConnection.getConnection();
PreparedStatement statement = connection.prepareStatement(query);
Channel toggledChannel = user.getToggledChannel();
statement.setString(1, user.getUuid().toString());
statement.setInt(2, user.getPartyId());
statement.setInt(3, user.toggledPartyChat() ? 1 : 0);
statement.setInt(4, 0);
statement.setInt(5, user.getPartyId());
statement.setInt(6, user.toggledPartyChat() ? 1 : 0);
statement.setInt(7, 0);
statement.setString(3, toggledChannel == null ? null : toggledChannel.getChannelName());
statement.setInt(4, user.getPartyId());
statement.setString(5, toggledChannel == null ? null : toggledChannel.getChannelName());
statement.execute();
} catch (SQLException e) {

View File

@ -1,8 +1,10 @@
package com.alttd.chat.objects;
import com.alttd.chat.database.Queries;
import com.alttd.chat.objects.channels.Channel;
import com.alttd.chat.util.Utility;
import net.kyori.adventure.text.Component;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.List;
@ -11,7 +13,7 @@ import java.util.UUID;
public class ChatUser {
private final UUID uuid; // player uuid
private int partyId; // the party they are in
private boolean toggledPartyChat; // should chat messages instantly go to party chat when added, idk if this should be saved
private Channel toggledChannel;
private String name; // the nickname, doesn't need to be saved with the chatuser object, could be saved but we can get it from the nicknamesview
private Component displayName; // the nickname, doesn't need to be saved with the chatuser object, could be saved but we can get it from the nicknamesview
// private Component prefix; // doesn't need saving, we get this from luckperms
@ -25,10 +27,10 @@ public class ChatUser {
private List<UUID> ignoredPlayers; // a list of UUID, a new table non unique, where one is is the player select * from ignores where ignoredby = thisplayer? where the result is the uuid of the player ignored by this player?
private List<UUID> ignoredBy; // a list of UUID, same table as above but select * from ignores where ignored = thisplayer? result should be the other user that ignored this player?
public ChatUser(UUID uuid, int partyId, boolean toggledChat, boolean toggleGc) {
public ChatUser(UUID uuid, int partyId, Channel toggledChannel) {
this.uuid = uuid;
this.partyId = partyId;
this.toggledPartyChat = toggledChat;
this.toggledChannel = toggledChannel;
name = Queries.getDisplayName(uuid);
if (name == null) {
@ -41,7 +43,6 @@ public class ChatUser {
//
// prefixAll = Utility.getPrefix(uuid, false);
//this.toggleGc = toggleGc;
replyTarget = null;
gcCooldown = System.currentTimeMillis(); // players can't use gc for 30 seconds after logging in if we use this?
mails = Queries.getMails(uuid);
@ -61,13 +62,13 @@ public class ChatUser {
this.partyId = partyId;
}
public boolean toggledPartyChat() {
return toggledPartyChat;
public Channel getToggledChannel() {
return toggledChannel;
}
public void togglePartyChat() {
toggledPartyChat = !toggledPartyChat;
Queries.setPartyChatState(toggledPartyChat, uuid); //TODO: Async pls - no CompleteableFuture<>!
public void setToggledChannel(Channel channel) {
toggledChannel = channel;
Queries.setToggledChannel(toggledChannel, uuid); //TODO: Async pls - no CompleteableFuture<>!
}
public Component getDisplayName() {

View File

@ -3,7 +3,6 @@ package com.alttd.chat.objects;
import com.alttd.chat.database.Queries;
import com.alttd.chat.managers.ChatUserManager;
import com.alttd.chat.managers.PartyManager;
import net.kyori.adventure.text.serializer.plain.PlainComponentSerializer;
import java.util.*;
import java.util.List;
@ -103,4 +102,8 @@ public class Party {
public String getUserDisplayName(UUID uuid) {
return partyUsers.get(uuid);
}
public void resetPartyUsers() { // FIXME: 08/08/2021 This is a temp solution until bungee messages take over updating parties
partyUsers.clear();
}
}

View File

@ -1,14 +1,18 @@
package com.alttd.chat.commands;
import com.alttd.chat.ChatPlugin;
import com.alttd.chat.config.Config;
import com.alttd.chat.database.Queries;
import com.alttd.chat.managers.ChatUserManager;
import com.alttd.chat.managers.PartyManager;
import com.alttd.chat.objects.ChatUser;
import com.alttd.chat.objects.Party;
import com.alttd.chat.util.Utility;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
@ -47,16 +51,17 @@ public class ChatParty implements CommandExecutor, TabCompleter {
break;
}
if (PartyManager.getParty(args[1]) != null) {
sender.sendMessage(MiniMessage.get().parse("<red>A party with this name already exists.</red>"));
sender.sendMessage(MiniMessage.get().parse("<red>A chat party with this name already exists.</red>"));
break;
}
Party party = Queries.addParty(player.getUniqueId(), args[1], args[2]);
// party.addUser(ChatUserManager.getChatUser(player.getUniqueId())); //Removed until we can get nicknames to translate to colors correctly
party.addUser(ChatUserManager.getChatUser(player.getUniqueId()), player.getName());
PartyManager.addParty(party);
sender.sendMessage(MiniMessage.get().parse("<green>You created a party called: '<gold>" +
sender.sendMessage(MiniMessage.get().parse("<green>You created a chat party called: '<gold>" +
party.getPartyName() + "</gold>' with the password: '<gold>" +
party.getPartyPassword() + "</gold>'</green>"));
update(player, party.getPartyId());
}
case "invite" -> {
if (args.length < 2) {
@ -65,11 +70,11 @@ public class ChatParty implements CommandExecutor, TabCompleter {
}
Party party = PartyManager.getParty(player.getUniqueId());
if (party == null) {
sender.sendMessage(MiniMessage.get().parse("<red>You're not in a party.</red>"));
sender.sendMessage(MiniMessage.get().parse("<red>You're not in a chat party.</red>"));
break;
}
if (!party.getOwnerUuid().equals(player.getUniqueId())) {
sender.sendMessage("<red>You don't own this party.</red>");
sender.sendMessage("<red>You don't own this chat party.</red>");
break;
}
Player target = Bukkit.getPlayer(args[1]);
@ -78,9 +83,9 @@ public class ChatParty implements CommandExecutor, TabCompleter {
break;
}
target.sendMessage(MiniMessage.get().parse("<click:run_command:'/party join " + party.getPartyName() + " " + party.getPartyPassword() +
target.sendMessage(MiniMessage.get().parse("<click:run_command:'/chatparty join " + party.getPartyName() + " " + party.getPartyPassword() +
"'><dark_aqua>You received an invite to join " + party.getPartyName() + " click this message to accept.</dark_aqua></click>"));
sender.sendMessage(MiniMessage.get().parse("<green>You send a party invite to " + target.getName() + "!</green>"));
sender.sendMessage(MiniMessage.get().parse("<green>You send a chat party invite to " + target.getName() + "!</green>"));
}
case "join" -> {
if (args.length < 3 || !args[1].matches("[\\w]{3,16}") || !args[2].matches("[\\w]{3,16}")) {
@ -90,7 +95,7 @@ public class ChatParty implements CommandExecutor, TabCompleter {
Party party = PartyManager.getParty(args[1]);
if (party == null) {
sender.sendMessage(MiniMessage.get().parse("<red>This party does not exist.</red>"));
sender.sendMessage(MiniMessage.get().parse("<red>This chat party does not exist.</red>"));
break;
}
if (!party.getPartyPassword().equals(args[2])) {
@ -101,11 +106,12 @@ public class ChatParty implements CommandExecutor, TabCompleter {
// party.addUser(ChatUserManager.getChatUser(player.getUniqueId())); //Removed until we can get nicknames to translate to colors correctly
party.addUser(ChatUserManager.getChatUser(player.getUniqueId()), player.getName());
sender.sendMessage(MiniMessage.get().parse("<green>You joined " + party.getPartyName() + "!</green>"));
update(player, party.getPartyId());
}
case "leave" -> {
Party party = PartyManager.getParty(player.getUniqueId());
if (party == null) {
sender.sendMessage(MiniMessage.get().parse("<red>You're not in a party.</red>"));
sender.sendMessage(MiniMessage.get().parse("<red>You're not in a chat party.</red>"));
break;
}
@ -113,15 +119,17 @@ public class ChatParty implements CommandExecutor, TabCompleter {
if (party.getOwnerUuid().equals(player.getUniqueId())) {
if (party.getPartyUsers().size() > 0) {
ChatUser chatUser = ChatUserManager.getChatUser(party.newOwner());
sender.sendMessage(MiniMessage.get().parse("<dark_aqua>Since you own this party a new party owner will be chosen.<dark_aqua>"));
sender.sendMessage(MiniMessage.get().parse("<dark_aqua>Since you own this chat party a new party owner will be chosen.<dark_aqua>"));
ChatPlugin.getInstance().getChatHandler().partyMessage(party, player, "<dark_aqua>" +
ChatUserManager.getChatUser(player.getUniqueId()).getDisplayName() +
" left the party, the new party owner is " + chatUser.getDisplayName());
player.getName() +
" left the chat party, the new party owner is " + chatUser.getDisplayName());
} else {
party.delete();
}
} else {
sender.sendMessage(MiniMessage.get().parse("<green>You have left the chat party!</green>"));
}
// TODO: 07/08/2021 leave the party
update(player, party.getPartyId());
}
case "remove" -> {
if (args.length < 2) {
@ -130,11 +138,11 @@ public class ChatParty implements CommandExecutor, TabCompleter {
}
Party party = PartyManager.getParty(player.getUniqueId());
if (party == null) {
sender.sendMessage(MiniMessage.get().parse("<red>You're not in a party.</red>"));
sender.sendMessage(MiniMessage.get().parse("<red>You're not in a chat party.</red>"));
break;
}
if (!party.getOwnerUuid().equals(player.getUniqueId())) {
sender.sendMessage("<red>You don't own this party.</red>");
sender.sendMessage("<red>You don't own this chat party.</red>");
break;
}
OfflinePlayer offlinePlayerIfCached = Bukkit.getOfflinePlayerIfCached((args[1]));
@ -146,24 +154,25 @@ public class ChatParty implements CommandExecutor, TabCompleter {
if (offlinePlayerIfCached.isOnline()) {
Objects.requireNonNull(offlinePlayerIfCached.getPlayer())
.sendMessage(MiniMessage.get().parse("<red>You were removed from the '" + party.getPartyName() + "' party."));
.sendMessage(MiniMessage.get().parse("<red>You were removed from the '" + party.getPartyName() + "' chat party."));
}
sender.sendMessage(MiniMessage.get().parse("<green>You removed " + offlinePlayerIfCached.getName() + " from the party!</green>"));
sender.sendMessage(MiniMessage.get().parse("<green>You removed " + offlinePlayerIfCached.getName() + " from the chat party!</green>"));
update(player, party.getPartyId());
}
case "info" -> {
Party party = PartyManager.getParty(player.getUniqueId());
if (party == null) {
sender.sendMessage(MiniMessage.get().parse("<red>You're not in a party.</red>"));
sender.sendMessage(MiniMessage.get().parse("<red>You're not in a chat party.</red>"));
break;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<gold><bold>Party info</bold>:\n</gold>")
.append("<green>Party name: <dark_aqua>").append(party.getPartyName()).append("</dark_aqua>\n")
.append(party.getOwnerUuid().equals(player.getUniqueId()) ? "Party password: <dark_aqua>" + party.getPartyPassword() + "</dark_aqua>\n" : "")
.append("Party owner: ").append(party.getUserDisplayName(party.getOwnerUuid())).append("\n")
.append("Party members: ");
stringBuilder.append("<gold><bold>Chat party info</bold>:\n</gold>")
.append("<green>Name: <dark_aqua>").append(party.getPartyName()).append("</dark_aqua>\n")
.append(party.getOwnerUuid().equals(player.getUniqueId()) ? "Password: <dark_aqua>" + party.getPartyPassword() + "</dark_aqua>\n" : "")
.append("Owner: ").append(party.getUserDisplayName(party.getOwnerUuid())).append("\n")
.append("Members: ");
for (String displayName : party.getPartyUsers().values()) {
stringBuilder.append(displayName).append(", ");
}
@ -188,7 +197,7 @@ public class ChatParty implements CommandExecutor, TabCompleter {
private void helpMessage(CommandSender sender) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<dark_aqua>Party commands:</dark_aqua><green>");
stringBuilder.append("<dark_aqua>Chat party commands:</dark_aqua><green>");
for (CommandUsage commandUsage : CommandUsage.values()) {
stringBuilder.append("\n- ").append(commandUsage.message);
}
@ -232,15 +241,22 @@ public class ChatParty implements CommandExecutor, TabCompleter {
return finalValues;
}
private void update(Player player, int partyId) { // FIXME: 08/08/2021 This only updates members btw and should be replaced with per change messages
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("tmppartyupdate");
out.writeUTF(String.valueOf(partyId));
player.sendPluginMessage(ChatPlugin.getInstance(), Config.MESSAGECHANNEL, out.toByteArray());
}
private enum CommandUsage {
CREATE("<gold>/party create <#FFE800><hover:show_text:'<gold>A party name must be 3-16 characters</gold>'><name></hover> " +
"<hover:show_text:'<gold>A party password must be 3-16 characters\n</gold>" +
CREATE("<gold>/chatparty create <#FFE800><hover:show_text:'<gold>A chat party name must be 3-16 characters</gold>'><name></hover> " +
"<hover:show_text:'<gold>A chat party password must be 3-16 characters\n</gold>" +
"<red>When choosing a password keep in mind staff can see it and you might need to share it with other players!</red>'><password></#FFE800></hover></gold>"),
INVITE("<gold>/party invite <username></gold>"),
JOIN("<gold>/party join <party name> <password></gold>"),
LEAVE("<gold><hover:show_text:'<red>If the party owner leaves the server will choose a new party owner</red>'>/party leave</hover></gold>"),
REMOVE("<gold>/party remove <username></gold>"),
INFO("<gold>/party info</gold>");
INVITE("<gold>/chatparty invite <username></gold>"),
JOIN("<gold>/chatparty join <chat party name> <password></gold>"),
LEAVE("<gold><hover:show_text:'<red>If the chat party owner leaves the server will choose a new chat party owner</red>'>/chatparty leave</hover></gold>"),
REMOVE("<gold>/chatparty remove <username></gold>"),
INFO("<gold>/chatparty info</gold>");
private final String message;

View File

@ -26,7 +26,7 @@ public class PlayerListener implements Listener {
if(user != null) return;
// user failed to load - create a new one
ChatUser chatUser = new ChatUser(uuid, -1, false, false);
ChatUser chatUser = new ChatUser(uuid, -1, null);
ChatUserManager.addUser(chatUser);
Queries.saveUser(chatUser);

View File

@ -2,6 +2,7 @@ package com.alttd.chat.listeners;
import com.alttd.chat.ChatPlugin;
import com.alttd.chat.config.Config;
import com.alttd.chat.database.Queries;
import com.alttd.chat.managers.ChatUserManager;
import com.alttd.chat.objects.channels.Channel;
import com.alttd.chat.objects.channels.CustomChannel;
@ -71,6 +72,17 @@ public class PluginMessage implements PluginMessageListener {
if (ChatPlugin.getInstance().serverMuted()) break;
chatChannel(in);
break;
}
case "tmppartyupdate" : {
int id = Integer.parseInt(in.readUTF());
new BukkitRunnable() {
@Override
public void run() {
Queries.loadPartyUsers(id);
}
}.runTaskAsynchronously(ChatPlugin.getInstance());
break;
}
default:
break;

View File

@ -1,6 +1,8 @@
package com.alttd.chat.listeners;
import com.alttd.chat.VelocityChat;
import com.alttd.chat.database.Queries;
import com.alttd.chat.managers.PartyManager;
import com.alttd.chat.objects.channels.CustomChannel;
import com.alttd.chat.util.ALogger;
import com.google.common.io.ByteArrayDataInput;
@ -14,6 +16,7 @@ import com.velocitypowered.api.proxy.messages.ChannelIdentifier;
import com.velocitypowered.api.proxy.server.RegisteredServer;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import java.util.Collection;
import java.util.UUID;
public class PluginMessageListener {
@ -66,6 +69,12 @@ public class PluginMessageListener {
VelocityChat.getPlugin().getChatHandler().partyChat(in.readUTF(), UUID.fromString(in.readUTF()), GsonComponentSerializer.gson().deserialize(in.readUTF()));
break;
}
case "tmppartyupdate": {
int id = Integer.parseInt(in.readUTF());
Queries.loadPartyUsers(id);
VelocityChat.getPlugin().getProxy().getAllServers().forEach(registeredServer -> registeredServer.sendPluginMessage(VelocityChat.getPlugin().getChannelIdentifier(), event.getData()));
break;
}
default:
VelocityChat.getPlugin().getLogger().info("server " + event.getSource());
ProxyServer proxy = VelocityChat.getPlugin().getProxy();