diff --git a/src/main/java/com/diamondfire/helpbot/sys/externalfile/ExternalFiles.java b/src/main/java/com/diamondfire/helpbot/sys/externalfile/ExternalFiles.java index 2b4a826c..853f2d4c 100644 --- a/src/main/java/com/diamondfire/helpbot/sys/externalfile/ExternalFiles.java +++ b/src/main/java/com/diamondfire/helpbot/sys/externalfile/ExternalFiles.java @@ -55,11 +55,6 @@ public interface ExternalFiles { .setFileType("png") .buildFile(); - File VIP_ROLES = new ExternalFileBuilder() - .isDirectory(false) - .setName("vip_roles") - .setFileType("json") - .buildFile(); File SAM_QUOTES = new ExternalFileBuilder() .isDirectory(false) diff --git a/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java b/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java index 93207b64..03fa8514 100644 --- a/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java +++ b/src/main/java/com/diamondfire/helpbot/sys/tasks/impl/VIPStarTask.java @@ -3,49 +3,136 @@ import com.diamondfire.helpbot.bot.HelpBotInstance; import com.diamondfire.helpbot.sys.tasks.LoopingTask; import com.diamondfire.helpbot.sys.vip.VIPRoleHandler; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.*; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.concurrent.TimeUnit; +/** + * Gives every VIP the star role for their name color, takes stars from everyone else, + * and deletes star roles that no VIP needs. + */ public class VIPStarTask implements LoopingTask { - + @Override public long getInitialStart() { return 0; } - + @Override public long getNextLoop() { return TimeUnit.MINUTES.toMillis(30L); } - + + private record Seen(long id, boolean vip, int color, Set stars) { + + } + @Override public void run() { Guild guild = HelpBotInstance.getJda().getGuildById(HelpBotInstance.DF_GUILD); + if (guild == null) { + return; + } + Set vipIds = VIPRoleHandler.retrieveVIPs(); + if (vipIds.isEmpty()) { + // Most likely a failed lookup; acting on it would strip every star. + System.out.println("No VIPs found, skipping VIP star update."); + return; + } + + VIPRoleHandler.syncWithGuild(guild); + + // Only VIPs and members holding a star matter, so only those are kept while members load. + List relevant = Collections.synchronizedList(new ArrayList<>()); + try { + guild.loadMembers(member -> { + Set stars = new HashSet<>(); + for (Role role : member.getRoles()) { + if (VIPRoleHandler.isStarRole(role)) { + stars.add(role.getIdLong()); + } + } + + boolean vip = vipIds.contains(member.getIdLong()); + if (vip || !stars.isEmpty()) { + relevant.add(new Seen(member.getIdLong(), vip, VIPRoleHandler.getNameColor(member), stars)); + } + }).get(); + } catch (Exception e) { + // Without every member, a star in use can't be told apart from an unused one. + System.out.println("Could not load members, skipping VIP star update: " + e); + return; + } + + // The colors VIPs need, and the existing roles that serve them. + Set neededColors = new HashSet<>(); + for (Seen member : relevant) { + if (member.vip() && member.color() != Role.DEFAULT_COLOR_RAW) { + neededColors.add(member.color()); + } + } + + Set keep = new HashSet<>(); + for (int color : neededColors) { + Role role = VIPRoleHandler.getRole(guild, color); + if (role != null) { + keep.add(role.getIdLong()); + } + } - guild.loadMembers((member) -> { - Role role = VIPRoleHandler.getRole(member.getColorRaw()); + // Delete unused star roles first: that takes the star from anyone still holding one, and frees room for new roles. + int deleted = 0; + for (Role role : guild.getRoles()) { + if (VIPRoleHandler.isStarRole(role) && !keep.contains(role.getIdLong())) { + VIPRoleHandler.deleteRole(role); + deleted++; + } + } + + int created = 0; + Map roles = new HashMap<>(); + for (int color : neededColors) { + Role role = VIPRoleHandler.getRole(guild, color); if (role == null) { - return; + role = VIPRoleHandler.createRole(guild, color); + if (role != null) { + created++; + } + } + if (role != null) { + roles.put(color, role); } - if (vipIds.contains(member.getIdLong()) && !member.getRoles().contains(role)) { - guild.addRoleToMember(member, role) + } + + for (Seen member : relevant) { + UserSnowflake user = UserSnowflake.fromId(member.id()); + Role wanted = member.vip() ? roles.get(member.color()) : null; + + if (wanted != null && !member.stars().contains(wanted.getIdLong())) { + guild.addRoleToMember(user, wanted) .reason("User has VIP Pass") .queue(); - return; } - if (!vipIds.contains(member.getIdLong()) && member.getRoles().contains(role)) { - guild.removeRoleFromMember(member, role) - .reason("User's VIP Pass has expired") - .queue(); + + for (long roleId : member.stars()) { + if (!keep.contains(roleId) || (wanted != null && roleId == wanted.getIdLong())) { + // Deleted above, or the one they should have. + continue; + } + + Role role = guild.getRoleById(roleId); + if (role != null) { + guild.removeRoleFromMember(user, role) + .reason(member.vip() ? "User's name color changed" : "User's VIP Pass has expired") + .queue(); + } } - }); + } + if (deleted > 0 || created > 0) { + System.out.printf("VIP stars: %s VIPs, %s colors, %s roles deleted, %s created%n", vipIds.size(), neededColors.size(), deleted, created); + } } - } diff --git a/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java b/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java index 2743407f..f5ea8458 100644 --- a/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java +++ b/src/main/java/com/diamondfire/helpbot/sys/vip/VIPRoleHandler.java @@ -1,114 +1,165 @@ package com.diamondfire.helpbot.sys.vip; -import com.diamondfire.helpbot.bot.HelpBotInstance; +import com.diamondfire.helpbot.sys.database.ConnectionProvider; import com.diamondfire.helpbot.sys.database.impl.DatabaseQuery; import com.diamondfire.helpbot.sys.database.impl.queries.BasicQuery; -import com.diamondfire.helpbot.sys.externalfile.ExternalFiles; import com.diamondfire.helpbot.util.StarUtil; -import com.google.gson.*; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Icon; -import net.dv8tion.jda.api.entities.Role; +import net.dv8tion.jda.api.entities.*; +import org.jetbrains.annotations.Nullable; import javax.imageio.ImageIO; -import java.awt.*; -import java.io.*; -import java.nio.file.Files; -import java.nio.file.StandardOpenOption; -import java.sql.ResultSet; +import java.awt.Color; +import java.io.ByteArrayOutputStream; +import java.sql.*; import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +/** + * Star roles for VIPs: one role per name color, with a star icon in that color. + * Which role belongs to which color is kept in {@code owen.vip_roles}, so it survives redeploys. + */ public class VIPRoleHandler { private static final String ROLE_NAME = "VIP"; - - private static final File FILE = ExternalFiles.VIP_ROLES; - private static final Map COLOR_ROLE_MAP = new HashMap<>(); + + private static final Map COLOR_ROLE_MAP = new ConcurrentHashMap<>(); static { - try { - cacheJson(); - - Guild guild = HelpBotInstance.getJda().getGuildById(HelpBotInstance.DF_GUILD); - for (Role role : guild.getRoles()) { - int color = role.getColorRaw(); - if (color == Role.DEFAULT_COLOR_RAW) { - continue; - } - if (role.getIcon() != null) { - continue; - } - if (!COLOR_ROLE_MAP.containsKey(color)) { - // Create the coloured star and register it on discord. - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ImageIO.write(StarUtil.create(new Color(color)), "png", baos); - baos.flush(); - role = guild.createRole() - .setName(ROLE_NAME) - .setIcon(Icon.from(baos.toByteArray())) - .setPermissions(0L) - .complete(); - COLOR_ROLE_MAP.put(color, role.getIdLong()); + try (Connection connection = ConnectionProvider.getConnection(); + Statement statement = connection.createStatement()) { + statement.executeUpdate(""" + CREATE TABLE IF NOT EXISTS owen.vip_roles ( + color INT NOT NULL PRIMARY KEY, + role_id BIGINT NOT NULL + )"""); + + try (ResultSet set = statement.executeQuery("SELECT color, role_id FROM owen.vip_roles")) { + while (set.next()) { + COLOR_ROLE_MAP.put(set.getInt("color"), set.getLong("role_id")); } } - save(); - } catch (IOException e) { + } catch (SQLException e) { e.printStackTrace(); } } - - public static void cacheJson() throws IOException { - String content = new String(Files.readAllBytes(FILE.toPath())); - - if (content.isEmpty()) { - content = "{}"; - } - - JsonObject obj = JsonParser.parseString(content).getAsJsonObject(); - - for (String key : obj.keySet()) { - long roleId = obj.get(key).getAsLong(); - COLOR_ROLE_MAP.put(Integer.parseInt(key), roleId); - } - } - - public static void save() throws IOException { - JsonObject json = new JsonObject(); - - for (int color : COLOR_ROLE_MAP.keySet()) { - json.addProperty(String.valueOf(color), COLOR_ROLE_MAP.get(color)); - } - - FILE.delete(); - FILE.createNewFile(); - Files.write(FILE.toPath(), json.toString().getBytes(), StandardOpenOption.WRITE); - } public static Set retrieveVIPs() { Set vips = new HashSet<>(); new DatabaseQuery() - .query(new BasicQuery("SELECT linked_accounts.discord_id FROM linked_accounts, hypercube.ranks " + + .query(new BasicQuery("SELECT linked_accounts.discord_id FROM linked_accounts, hypercube.ranks " + "WHERE linked_accounts.player_uuid = ranks.uuid AND ranks.vip = 1")) .compile() .run(result -> { - ResultSet set = result.getResult(); - while (set.next()) { + for (ResultSet set : result) { vips.add(set.getLong("discord_id")); } }); return vips; } - public static Role getRole(int color) { - if (color == Role.DEFAULT_COLOR_RAW) { - return null; + /** + * Whether a role is one of the bot's star roles: named "VIP", with an icon and no permissions. + */ + public static boolean isStarRole(Role role) { + return role.getName().equals(ROLE_NAME) + && role.getIcon() != null + && role.getPermissionsRaw() == 0 + && !role.isManaged(); + } + + /** + * A member's name color from their other roles, so a star role never decides it. + */ + public static int getNameColor(Member member) { + for (Role role : member.getRoles()) { + if (!isStarRole(role) && role.getColorRaw() != Role.DEFAULT_COLOR_RAW) { + return role.getColorRaw(); + } + } + return Role.DEFAULT_COLOR_RAW; + } + + /** + * Drops mappings to roles that no longer exist, and adopts older star roles that carry their color, + * so they are reused instead of created again. + */ + public static void syncWithGuild(Guild guild) { + COLOR_ROLE_MAP.entrySet().removeIf(entry -> { + if (guild.getRoleById(entry.getValue()) != null) { + return false; + } + forget(entry.getValue()); + return true; + }); + + for (Role role : guild.getRoles()) { + int color = role.getColorRaw(); + if (isStarRole(role) && color != Role.DEFAULT_COLOR_RAW && !COLOR_ROLE_MAP.containsKey(color)) { + remember(color, role.getIdLong()); + } } - Guild guild = HelpBotInstance.getJda().getGuildById(HelpBotInstance.DF_GUILD); - if (!COLOR_ROLE_MAP.containsKey(color)) { + } + + /** + * @return the existing star role for this color, or null + */ + public static @Nullable Role getRole(Guild guild, int color) { + Long roleId = COLOR_ROLE_MAP.get(color); + return roleId == null ? null : guild.getRoleById(roleId); + } + + /** + * Creates the star role for a color. Blocks, so it must not be called from a JDA callback thread. + * + * @return the new role, or null if it could not be created + */ + public static @Nullable Role createRole(Guild guild, int color) { + try { + ByteArrayOutputStream image = new ByteArrayOutputStream(); + ImageIO.write(StarUtil.create(new Color(color)), "png", image); + Role role = guild.createRole() + .setName(ROLE_NAME) + .setIcon(Icon.from(image.toByteArray())) + .setPermissions(0L) + .reason("A VIP has this name color") + .complete(); + remember(color, role.getIdLong()); + return role; + } catch (Exception e) { + e.printStackTrace(); return null; } - return guild.getRoleById(COLOR_ROLE_MAP.get(color)); } - + /** + * Deletes a star role and forgets it. Blocks until Discord confirms. + */ + public static void deleteRole(Role role) { + COLOR_ROLE_MAP.values().removeIf(id -> id == role.getIdLong()); + forget(role.getIdLong()); + + try { + role.delete() + .reason("No VIP uses this star role") + .complete(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static void remember(int color, long roleId) { + COLOR_ROLE_MAP.put(color, roleId); + new DatabaseQuery() + .query(new BasicQuery("REPLACE INTO owen.vip_roles (color, role_id) VALUES (?, ?)", (statement) -> { + statement.setInt(1, color); + statement.setLong(2, roleId); + })) + .compile(); + } + + private static void forget(long roleId) { + new DatabaseQuery() + .query(new BasicQuery("DELETE FROM owen.vip_roles WHERE role_id = ?", (statement) -> statement.setLong(1, roleId))) + .compile(); + } }