From 17102a9e953ebeb88af83fe0f62a8aad629c1704 Mon Sep 17 00:00:00 2001 From: SebClem Date: Sat, 11 Jun 2022 17:24:45 +0200 Subject: [PATCH] :hammer: Return only visible voice/text channels --- .../Api/Controllers/GuildController.java | 10 +- .../net/Broken/Api/Services/GuildService.java | 17 +- src/main/java/net/Broken/BotListener.java | 16 +- .../DB/Entity/GuildPreferenceEntity.java | 26 +-- .../Repository/GuildPreferenceRepository.java | 4 +- .../Broken/RestApi/SettingAPIController.java | 73 ------- .../DayListener/Listeners/DailyMadame.java | 7 +- .../java/net/Broken/Tools/SettingsUtils.java | 199 +----------------- 8 files changed, 40 insertions(+), 312 deletions(-) delete mode 100644 src/main/java/net/Broken/RestApi/SettingAPIController.java diff --git a/src/main/java/net/Broken/Api/Controllers/GuildController.java b/src/main/java/net/Broken/Api/Controllers/GuildController.java index 20b49ad..617ce32 100644 --- a/src/main/java/net/Broken/Api/Controllers/GuildController.java +++ b/src/main/java/net/Broken/Api/Controllers/GuildController.java @@ -40,14 +40,16 @@ public class GuildController { @GetMapping("/{guildId}/voiceChannels") @PreAuthorize("isInGuild(#guildId)") - public List getVoiceChannels(@PathVariable String guildId){ - return guildService.getVoiceChannel(guildId); + public List getVoiceChannels(@PathVariable String guildId, Authentication authentication){ + JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); + return guildService.getVoiceChannel(guildId, principal.user().getDiscordId()); } @GetMapping("/{guildId}/textChannels") @PreAuthorize("isInGuild(#guildId)") - public List getTextChannels(@PathVariable String guildId){ - return guildService.getTextChannel(guildId); + public List getTextChannels(@PathVariable String guildId, Authentication authentication){ + JwtPrincipal principal = (JwtPrincipal) authentication.getPrincipal(); + return guildService.getTextChannel(guildId, principal.user().getDiscordId()); } @GetMapping("/{guildId}/roles") diff --git a/src/main/java/net/Broken/Api/Services/GuildService.java b/src/main/java/net/Broken/Api/Services/GuildService.java index 099399b..372a807 100644 --- a/src/main/java/net/Broken/Api/Services/GuildService.java +++ b/src/main/java/net/Broken/Api/Services/GuildService.java @@ -6,6 +6,8 @@ import net.Broken.Api.Data.Guild.Role; import net.Broken.DB.Entity.UserEntity; import net.Broken.MainBot; import net.Broken.Tools.CacheTools; +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.User; import org.springframework.stereotype.Service; @@ -25,21 +27,26 @@ public class GuildService { return guildList; } - public List getVoiceChannel(String guildId){ + public List getVoiceChannel(String guildId, String userId){ net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId); - + Member member = guild.getMemberById(userId); List voiceChannels = new ArrayList<>(); for(net.dv8tion.jda.api.entities.VoiceChannel voiceChannel : guild.getVoiceChannels()){ - voiceChannels.add(new Channel(voiceChannel.getId(), voiceChannel.getName())); + if(member.hasPermission(voiceChannel, Permission.VIEW_CHANNEL)){ + voiceChannels.add(new Channel(voiceChannel.getId(), voiceChannel.getName())); + } } return voiceChannels; } - public List getTextChannel(String guildId){ + public List getTextChannel(String guildId, String userId){ net.dv8tion.jda.api.entities.Guild guild = MainBot.jda.getGuildById(guildId); + Member member = guild.getMemberById(userId); List voiceChannels = new ArrayList<>(); for(net.dv8tion.jda.api.entities.TextChannel textChannel : guild.getTextChannels()){ - voiceChannels.add(new Channel(textChannel.getId(), textChannel.getName())); + if(member.hasPermission(textChannel, Permission.VIEW_CHANNEL)) { + voiceChannels.add(new Channel(textChannel.getId(), textChannel.getName())); + } } return voiceChannels; } diff --git a/src/main/java/net/Broken/BotListener.java b/src/main/java/net/Broken/BotListener.java index fcac4cf..af6b530 100644 --- a/src/main/java/net/Broken/BotListener.java +++ b/src/main/java/net/Broken/BotListener.java @@ -27,7 +27,7 @@ import org.springframework.context.ApplicationContext; import java.awt.*; import java.util.HashMap; -import java.util.List; +import java.util.Optional; /** @@ -213,15 +213,13 @@ public class BotListener extends ListenerAdapter { } private GuildPreferenceEntity getPreference(Guild guild) { - List guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId()); - GuildPreferenceEntity guildPref; - if (guildPrefList.isEmpty()) { + Optional guildPref = guildPreferenceRepository.findByGuildId(guild.getId()); + if (guildPref.isEmpty()) { logger.info("[" + guild.getName() + "] : Generate default pref"); - guildPref = GuildPreferenceEntity.getDefault(guild); - guildPref = guildPreferenceRepository.save(guildPref); - } else - guildPref = guildPrefList.get(0); - return guildPref; + return guildPreferenceRepository.save(GuildPreferenceEntity.getDefault(guild.getId())); + } else{ + return guildPref.get(); + } } diff --git a/src/main/java/net/Broken/DB/Entity/GuildPreferenceEntity.java b/src/main/java/net/Broken/DB/Entity/GuildPreferenceEntity.java index 906a8c1..f13ab11 100644 --- a/src/main/java/net/Broken/DB/Entity/GuildPreferenceEntity.java +++ b/src/main/java/net/Broken/DB/Entity/GuildPreferenceEntity.java @@ -1,11 +1,11 @@ package net.Broken.DB.Entity; +import net.Broken.Api.Data.Settings.Value; import net.dv8tion.jda.api.entities.Guild; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; @Entity public class GuildPreferenceEntity { @@ -13,10 +13,9 @@ public class GuildPreferenceEntity { @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; + @Column(unique=true) private String guildId; - private boolean antiSpam; - private boolean welcome; private String welcomeMessage; @@ -35,7 +34,6 @@ public class GuildPreferenceEntity { public GuildPreferenceEntity(String guildId, - boolean antiSpam, boolean welcome, String welcomeMessage, String welcomeChanelID, @@ -46,7 +44,6 @@ public class GuildPreferenceEntity { String autoVoiceChannelID, String autoVoiceChannelTitle) { this.guildId = guildId; - this.antiSpam = antiSpam; this.welcome = welcome; this.welcomeMessage = welcomeMessage; this.welcomeChanelID = welcomeChanelID; @@ -62,9 +59,8 @@ public class GuildPreferenceEntity { } - public static GuildPreferenceEntity getDefault(Guild guild) { - - return new GuildPreferenceEntity(guild.getId(), false, false, "Welcome to this awesome server @name! ", " ", false, " ", true, false, " ", " "); + public static GuildPreferenceEntity getDefault(String guildId) { + return new GuildPreferenceEntity(guildId, false, "Welcome to this awesome server @name! ", " ", false, " ", true, false, " ", " "); } public Integer getId() { @@ -83,14 +79,6 @@ public class GuildPreferenceEntity { this.guildId = guildId; } - public boolean isAntiSpam() { - return antiSpam; - } - - public void setAntiSpam(boolean antiSpam) { - this.antiSpam = antiSpam; - } - public boolean isWelcome() { return welcome; } diff --git a/src/main/java/net/Broken/DB/Repository/GuildPreferenceRepository.java b/src/main/java/net/Broken/DB/Repository/GuildPreferenceRepository.java index f27973c..d0da66a 100644 --- a/src/main/java/net/Broken/DB/Repository/GuildPreferenceRepository.java +++ b/src/main/java/net/Broken/DB/Repository/GuildPreferenceRepository.java @@ -3,9 +3,9 @@ package net.Broken.DB.Repository; import net.Broken.DB.Entity.GuildPreferenceEntity; import org.springframework.data.repository.CrudRepository; -import java.util.List; +import java.util.Optional; public interface GuildPreferenceRepository extends CrudRepository { - List findByGuildId(String id); + Optional findByGuildId(String id); } diff --git a/src/main/java/net/Broken/RestApi/SettingAPIController.java b/src/main/java/net/Broken/RestApi/SettingAPIController.java deleted file mode 100644 index fda8209..0000000 --- a/src/main/java/net/Broken/RestApi/SettingAPIController.java +++ /dev/null @@ -1,73 +0,0 @@ -package net.Broken.RestApi; - -import net.Broken.DB.Entity.UserEntity; -import net.Broken.DB.Repository.UserRepository; -import net.Broken.MainBot; -import net.Broken.RestApi.Data.Settings.GetSettingsData; -import net.Broken.RestApi.Data.Settings.ListPostSetting; -import net.Broken.Tools.SettingsUtils; -import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException; -import net.Broken.Tools.UserManager.UserUtils; -import net.dv8tion.jda.api.entities.Guild; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.ArrayList; - -@RestController -@RequestMapping("/api") -public class SettingAPIController { - final - UserRepository userRepository; - private Logger logger = LogManager.getLogger(); - - @Autowired - public SettingAPIController(UserRepository userRepository) { - this.userRepository = userRepository; - } - - - @RequestMapping(value = "/settings", method = RequestMethod.GET) - public ResponseEntity> getSettings(@CookieValue("token") String token, @CookieValue("guild") String guild) { - SettingsUtils settingUtils = SettingsUtils.getInstance(); - if (settingUtils.checkPermission(token, guild)) { - Guild jdaGuild = MainBot.jda.getGuildById(guild); - return new ResponseEntity<>(settingUtils.extractSettings(jdaGuild), HttpStatus.OK); - } else { - return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); - } - } - - @RequestMapping(value = "/settings", method = RequestMethod.POST) - public ResponseEntity setSetting(@CookieValue("token") String token, @CookieValue("guild") String guild, @RequestBody ListPostSetting settings) { - SettingsUtils settingUtils = SettingsUtils.getInstance(); - - if (settingUtils.checkPermission(token, guild)) { - Guild jdaGuild = MainBot.jda.getGuildById(guild); - try { - UserEntity user = UserUtils.getInstance().getUserWithApiToken(userRepository, token); - logger.info(user.getUsername() + " change config of " + jdaGuild.getName()); - } catch (UnknownTokenException e) { - e.printStackTrace(); - } - if (settingUtils.setSettings(jdaGuild, settings.settings)) { - return new ResponseEntity<>(HttpStatus.OK); - - } else { - return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); - - } - - - } else { - logger.warn("Try to change setting, UNAUTHORIZED. TOKEN: " + token + " GUILD: " + guild); - return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); - } - } - - -} diff --git a/src/main/java/net/Broken/Tools/DayListener/Listeners/DailyMadame.java b/src/main/java/net/Broken/Tools/DayListener/Listeners/DailyMadame.java index 3ec80bd..1ab89b0 100644 --- a/src/main/java/net/Broken/Tools/DayListener/Listeners/DailyMadame.java +++ b/src/main/java/net/Broken/Tools/DayListener/Listeners/DailyMadame.java @@ -18,6 +18,7 @@ import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.List; +import java.util.Optional; /** * Daily Listener for DailyMadame @@ -58,8 +59,8 @@ public class DailyMadame implements NewDayListener { for (Guild guild : guilds) { TextChannel chanel = null; logger.debug(guild.getName()); - List guildPref = guildPreferenceRepository.findByGuildId(guild.getId()); - if (guildPref.size() > 0 && guildPref.get(0).isDailyMadame()) { + Optional guildPref = guildPreferenceRepository.findByGuildId(guild.getId()); + if (guildPref.isPresent() && guildPref.get().isDailyMadame()) { for (TextChannel iterator : guild.getTextChannels()) { if (iterator.isNSFW() && iterator.canTalk()) { chanel = iterator; @@ -76,8 +77,6 @@ public class DailyMadame implements NewDayListener { logger.info("No NSFW chanel found for " + guild.getName() + ", ignoring it!"); } } - - } } catch (IOException e) { logger.catching(e); diff --git a/src/main/java/net/Broken/Tools/SettingsUtils.java b/src/main/java/net/Broken/Tools/SettingsUtils.java index d745db6..99f4887 100644 --- a/src/main/java/net/Broken/Tools/SettingsUtils.java +++ b/src/main/java/net/Broken/Tools/SettingsUtils.java @@ -37,113 +37,6 @@ public class SettingsUtils { return (INSTANCE == null) ? new SettingsUtils() : INSTANCE; } - /** - * Extract all settings for displaying on webpage - * - * @param guild The guild - * @return All formatted settings - */ - public ArrayList extractSettings(Guild guild) { - - ArrayList list = new ArrayList<>(); - List guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId()); - GuildPreferenceEntity guildPref; - if (guildPrefList.isEmpty()) { - guildPref = GuildPreferenceEntity.getDefault(guild); - guildPreferenceRepository.save(guildPref); - } else - guildPref = guildPrefList.get(0); - - list.add(new GetSettingsData( - "Enable Welcome Message", - null, - "welcome", - GetSettingsData.TYPE.BOOL, - null, - Boolean.toString(guildPref.isWelcome()) - )); - list.add(new GetSettingsData( - "Welcome Message chanel", - null, - "welcome_chanel_id", - GetSettingsData.TYPE.LIST, - getTextChannels(guild), - guildPref.getWelcomeChanelID() - )); - list.add(new GetSettingsData( - "Welcome Message", - null, - "welcome_message", - GetSettingsData.TYPE.STRING, - null, - guildPref.getWelcomeMessage() - )); - - - list.add(new GetSettingsData( - "Enable Default Role", - null, - "default_role", - GetSettingsData.TYPE.BOOL, - null, - Boolean.toString(guildPref.isDefaultRole()) - )); - list.add(new GetSettingsData( - "Default Role", - null, - "default_role_id", - GetSettingsData.TYPE.LIST, - getRoles(guild), - guildPref.getDefaultRoleId() - )); - - list.add(new GetSettingsData( - "Enable Anti Spam", - null, - "anti_spam", - GetSettingsData.TYPE.BOOL, - null, - Boolean.toString(guildPref.isAntiSpam()) - )); - - list.add(new GetSettingsData( - "Enable Daily Madame Message", - null, - "daily_madame", - GetSettingsData.TYPE.BOOL, - null, - Boolean.toString(guildPref.isDailyMadame()) - )); - - list.add(new GetSettingsData( - "Enable Auto Create Voice Chanel", - null, - "auto_voice", - GetSettingsData.TYPE.BOOL, - null, - Boolean.toString(guildPref.isAutoVoice()) - )); - list.add(new GetSettingsData( - "Base Voice Channel For Auto Create", - "If someone joint this channel, a new voice channel will be created with the same settings.", - "auto_voice_base_channel", - GetSettingsData.TYPE.LIST, - getVoiceChannels(guild, null), - guildPref.getAutoVoiceChannelID() - )); - list.add(new GetSettingsData( - "Auto Created Voice Channel title", - "Auto created voice channel will use this title, @count will be replaced by the channel count.", - "auto_voice_channel_title", - GetSettingsData.TYPE.STRING, - null, - guildPref.getAutoVoiceChannelTitle() - )); - - return list; - - } - /** * Check if the user have the permission to set settings * @@ -174,87 +67,6 @@ public class SettingsUtils { } - public boolean setSettings(Guild guild, List settings) { - GuildPreferenceEntity pref = getPreference(guild); - for (PostSetSettings setting : settings) { - String value = setting.val; - logger.debug(setting.id + " : " + value); - switch (setting.id) { - case "anti_spam": - boolean result_as = Boolean.parseBoolean(value); - pref.setAntiSpam(result_as); - break; - - case "default_role": - boolean result_df = Boolean.parseBoolean(value); - pref.setDefaultRole(result_df); - pref = guildPreferenceRepository.save(pref); - break; - - case "default_role_id": - try { - Role role = guild.getRoleById(value); - if (role != null) { - pref.setDefaultRoleId(role.getId()); - pref = guildPreferenceRepository.save(pref); - } else - throw new NumberFormatException(); - } catch (NumberFormatException e) { - logger.error("default_role_id error. Key: " + setting.id + " Val: " + setting.val); - return false; - } - break; - - case "welcome": - boolean result_w = Boolean.parseBoolean(value); - pref.setWelcome(result_w); - break; - case "welcome_chanel_id": - try { - TextChannel channel = guild.getTextChannelById(value); - if (channel != null) { - pref.setWelcomeChanelID(channel.getId()); - } else - throw new NumberFormatException(); - } catch (NumberFormatException e) { - logger.error("welcome_chanel_id error. Key: " + setting.id + " Val: " + setting.val); - return false; - } - break; - - case "welcome_message": - pref.setWelcomeMessage(value); - break; - - case "daily_madame": - boolean result_dm = Boolean.parseBoolean(value); - pref.setDailyMadame(result_dm); - break; - - case "auto_voice": - boolean result_av = Boolean.parseBoolean(value); - pref.setAutoVoice(result_av); - break; - - case "auto_voice_base_channel": - VoiceChannel channel = guild.getVoiceChannelById(value); - if (channel == null) { - logger.error("voices_channels error, bad ID."); - return false; - } else - pref.setAutoVoiceChannelID(channel.getId()); - break; - - case "auto_voice_channel_title": - pref.setAutoVoiceChannelTitle(value); - break; - } - } - guildPreferenceRepository.save(pref); - return true; - } - - private List getTextChannels(Guild guild) { List channels = new ArrayList<>(); for (TextChannel channel : guild.getTextChannels()) { @@ -298,14 +110,9 @@ public class SettingsUtils { } public GuildPreferenceEntity getPreference(Guild guild) { - List guildPrefList = guildPreferenceRepository.findByGuildId(guild.getId()); - GuildPreferenceEntity guildPref; - if (guildPrefList.isEmpty()) { + return guildPreferenceRepository.findByGuildId(guild.getId()).orElseGet(()->{ logger.info("Generate default pref for " + guild.getName()); - guildPref = GuildPreferenceEntity.getDefault(guild); - guildPreferenceRepository.save(guildPref); - } else - guildPref = guildPrefList.get(0); - return guildPref; + return guildPreferenceRepository.save(GuildPreferenceEntity.getDefault(guild.getId())); + }); } }