From 545a99a02c43d81692b9702b35188a79dbb78725 Mon Sep 17 00:00:00 2001 From: SebClem Date: Thu, 23 Jun 2022 14:43:40 +0200 Subject: [PATCH] :hammer: Big refracto --- .../Api/Controllers/AuthController.java | 3 - .../Controllers/CrossOptionController.java | 7 +- .../Api/Controllers/GuildController.java | 2 +- .../Api/Controllers/HelloController.java | 5 - .../net/Broken/Api/Data/Music/TrackInfo.java | 4 - .../net/Broken/Api/OpenApi/OpenApiConfig.java | 1 - .../Components/UnauthorizedHandler.java | 3 +- .../Security/Data/AccessTokenResponse.java | 2 - .../Broken/Api/Security/Data/JwtResponse.java | 2 - ...CustomMethodSecurityExpressionHandler.java | 3 +- .../CustomMethodSecurityExpressionRoot.java | 2 +- .../Broken/Api/Security/SecurityConfig.java | 3 - .../Services/DiscordOauthService.java | 3 +- .../Api/Security/Services/JwtService.java | 5 +- .../net/Broken/Api/Services/AudioService.java | 2 +- .../net/Broken/Api/Services/GuildService.java | 3 +- .../Broken/Api/Services/SettingService.java | 3 - .../Broken/Audio/AudioPlayerSendHandler.java | 2 +- .../net/Broken/Audio/GuildAudioWrapper.java | 9 +- .../Broken/Audio/NotConnectedException.java | 8 - .../net/Broken/Audio/NullMusicManager.java | 7 - .../java/net/Broken/Audio/TrackScheduler.java | 74 +------- .../java/net/Broken/Audio/UserAudioTrack.java | 4 +- .../Audio/Youtube/RelatedIdNotFound.java | 4 - .../Broken/Audio/Youtube/SearchResult.java | 37 ---- .../Audio/Youtube/YoutubeSearchRework.java | 140 -------------- .../Broken/Audio/Youtube/YoutubeTools.java | 175 ------------------ src/main/java/net/Broken/BotConfigLoader.java | 2 +- src/main/java/net/Broken/BotListener.java | 6 +- .../net/Broken/Commands/ChannelsReview.java | 6 +- .../java/net/Broken/Commands/ReportUsers.java | 9 +- .../DB/Entity/GuildPreferenceEntity.java | 5 - .../net/Broken/DB/Entity/PlaylistEntity.java | 79 -------- .../net/Broken/DB/Entity/TrackEntity.java | 94 ---------- .../java/net/Broken/DB/Entity/UserEntity.java | 25 +-- .../DB/Repository/PlaylistRepository.java | 8 - .../Broken/DB/Repository/TrackRepository.java | 13 -- src/main/java/net/Broken/Init.java | 3 - src/main/java/net/Broken/MainBot.java | 5 +- .../net/Broken/RestApi/ApiCommandLoader.java | 44 ----- .../net/Broken/RestApi/CommandInterface.java | 24 --- .../Broken/RestApi/Data/AllMusicInfoData.java | 11 -- .../net/Broken/RestApi/Data/ChanelData.java | 17 -- .../Broken/RestApi/Data/CommandPostData.java | 13 -- .../RestApi/Data/CommandResponseData.java | 24 --- .../Broken/RestApi/Data/CurrentMusicData.java | 43 ----- .../Data/Playlist/AddToPlaylistData.java | 11 -- .../Data/Playlist/CreatePlaylistData.java | 5 - .../Data/Playlist/DeleteTrackData.java | 6 - .../RestApi/Data/Playlist/MoveTrackData.java | 10 - .../Data/Playlist/PlaylistResponseData.java | 21 --- .../net/Broken/RestApi/Data/PlaylistData.java | 19 -- .../Data/Settings/GetSettingsData.java | 32 ---- .../Data/Settings/ListPostSetting.java | 7 - .../Data/Settings/PostSetSettings.java | 9 - .../Broken/RestApi/Data/Settings/Value.java | 21 --- .../RestApi/Data/UserAudioTrackData.java | 38 ---- .../Data/UserManager/CheckResposeData.java | 18 -- .../RestApi/Data/UserManager/ConfirmData.java | 10 - .../RestApi/Data/UserManager/GuildInfo.java | 16 -- .../Data/UserManager/UserConnectionData.java | 28 --- .../Data/UserManager/UserInfoData.java | 9 - .../Broken/RestApi/GeneralApiController.java | 42 ----- src/main/java/net/Broken/SlashCommand.java | 6 - .../java/net/Broken/SlashCommands/Cat.java | 7 +- .../java/net/Broken/SlashCommands/Clear.java | 1 - .../java/net/Broken/SlashCommands/Music.java | 5 +- .../net/Broken/SlashCommands/Over18/Ass.java | 5 - .../Broken/SlashCommands/Over18/Madame.java | 3 +- .../java/net/Broken/SlashCommands/Rank.java | 1 - .../java/net/Broken/Tools/CacheTools.java | 2 +- .../Broken/Tools/Command/CommandParser.java | 11 +- .../Tools/Command/NumberedSlashCommand.java | 16 +- .../Tools/Command/SlashCommandLoader.java | 2 +- .../Broken/Tools/DayListener/DayListener.java | 26 +-- .../DayListener/Listeners/DailyMadame.java | 4 +- .../net/Broken/Tools/EmbedMessageUtils.java | 5 +- .../Broken/Tools/FindContentOnWebPage.java | 3 +- .../java/net/Broken/Tools/LimitChecker.java | 2 +- .../java/net/Broken/Tools/ResourceLoader.java | 47 ----- .../java/net/Broken/Tools/SettingsUtils.java | 84 +-------- .../java/net/Broken/Tools/TrueRandom.java | 3 +- .../UserManager/Stats/GuildStatsPack.java | 13 +- .../UserManager/Stats/UserStatsUtils.java | 44 ++--- .../Broken/Tools/UserManager/UserUtils.java | 24 +-- .../MessagesTemplates/RegisterMessage.md | 4 - .../db/changelog/db.changelog-master.yml | 54 ++++++ 87 files changed, 141 insertions(+), 1477 deletions(-) delete mode 100644 src/main/java/net/Broken/Audio/NotConnectedException.java delete mode 100644 src/main/java/net/Broken/Audio/NullMusicManager.java delete mode 100644 src/main/java/net/Broken/Audio/Youtube/RelatedIdNotFound.java delete mode 100644 src/main/java/net/Broken/Audio/Youtube/SearchResult.java delete mode 100644 src/main/java/net/Broken/Audio/Youtube/YoutubeSearchRework.java delete mode 100644 src/main/java/net/Broken/Audio/Youtube/YoutubeTools.java delete mode 100644 src/main/java/net/Broken/DB/Entity/PlaylistEntity.java delete mode 100644 src/main/java/net/Broken/DB/Entity/TrackEntity.java delete mode 100644 src/main/java/net/Broken/DB/Repository/PlaylistRepository.java delete mode 100644 src/main/java/net/Broken/DB/Repository/TrackRepository.java delete mode 100644 src/main/java/net/Broken/RestApi/ApiCommandLoader.java delete mode 100644 src/main/java/net/Broken/RestApi/CommandInterface.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/AllMusicInfoData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/ChanelData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/CommandPostData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/CommandResponseData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/CurrentMusicData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/Playlist/AddToPlaylistData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/Playlist/CreatePlaylistData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/Playlist/DeleteTrackData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/Playlist/MoveTrackData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/Playlist/PlaylistResponseData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/PlaylistData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/Settings/GetSettingsData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/Settings/ListPostSetting.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/Settings/PostSetSettings.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/Settings/Value.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/UserAudioTrackData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/UserManager/CheckResposeData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/UserManager/ConfirmData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/UserManager/GuildInfo.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/UserManager/UserConnectionData.java delete mode 100644 src/main/java/net/Broken/RestApi/Data/UserManager/UserInfoData.java delete mode 100644 src/main/java/net/Broken/RestApi/GeneralApiController.java delete mode 100644 src/main/java/net/Broken/Tools/ResourceLoader.java delete mode 100644 src/main/resources/MessagesTemplates/RegisterMessage.md diff --git a/src/main/java/net/Broken/Api/Controllers/AuthController.java b/src/main/java/net/Broken/Api/Controllers/AuthController.java index 30d790e..75d6c43 100644 --- a/src/main/java/net/Broken/Api/Controllers/AuthController.java +++ b/src/main/java/net/Broken/Api/Controllers/AuthController.java @@ -11,8 +11,6 @@ import org.springframework.security.core.Authentication; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; -import io.swagger.v3.oas.annotations.security.SecurityRequirements; - @RestController @RequestMapping("/api/v2/auth") @CrossOrigin(origins = "*", maxAge = 3600) @@ -27,7 +25,6 @@ public class AuthController { } @PostMapping("/discord") - @SecurityRequirements(value = {}) public JwtResponse loginDiscord(@Validated @RequestBody Login login) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(login.redirectUri(), login.code()) diff --git a/src/main/java/net/Broken/Api/Controllers/CrossOptionController.java b/src/main/java/net/Broken/Api/Controllers/CrossOptionController.java index 03c3470..69b7b24 100644 --- a/src/main/java/net/Broken/Api/Controllers/CrossOptionController.java +++ b/src/main/java/net/Broken/Api/Controllers/CrossOptionController.java @@ -1,5 +1,6 @@ package net.Broken.Api.Controllers; +import io.swagger.v3.oas.annotations.Hidden; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; @@ -7,8 +8,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; -import io.swagger.v3.oas.annotations.Hidden; - @RestController @RequestMapping("/api/v2") @@ -23,7 +22,7 @@ public class CrossOptionController { value = "/**", method = RequestMethod.OPTIONS ) - public ResponseEntity handle() { - return new ResponseEntity(HttpStatus.OK); + public ResponseEntity handle() { + return new ResponseEntity<>("",HttpStatus.OK); } } diff --git a/src/main/java/net/Broken/Api/Controllers/GuildController.java b/src/main/java/net/Broken/Api/Controllers/GuildController.java index b2da436..783a55a 100644 --- a/src/main/java/net/Broken/Api/Controllers/GuildController.java +++ b/src/main/java/net/Broken/Api/Controllers/GuildController.java @@ -1,9 +1,9 @@ package net.Broken.Api.Controllers; +import net.Broken.Api.Data.Guild.Channel; import net.Broken.Api.Data.Guild.Guild; import net.Broken.Api.Data.Guild.Role; import net.Broken.Api.Data.InviteLink; -import net.Broken.Api.Data.Guild.Channel; import net.Broken.Api.Security.Data.JwtPrincipal; import net.Broken.Api.Services.GuildService; import net.Broken.MainBot; diff --git a/src/main/java/net/Broken/Api/Controllers/HelloController.java b/src/main/java/net/Broken/Api/Controllers/HelloController.java index bb3ecba..2287cfb 100644 --- a/src/main/java/net/Broken/Api/Controllers/HelloController.java +++ b/src/main/java/net/Broken/Api/Controllers/HelloController.java @@ -1,11 +1,6 @@ package net.Broken.Api.Controllers; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.security.SecurityRequirement; -import io.swagger.v3.oas.annotations.security.SecurityRequirements; import net.Broken.Api.Security.Data.JwtPrincipal; -import net.Broken.DB.Entity.UserEntity; -import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; diff --git a/src/main/java/net/Broken/Api/Data/Music/TrackInfo.java b/src/main/java/net/Broken/Api/Data/Music/TrackInfo.java index 8a1885e..1d99679 100644 --- a/src/main/java/net/Broken/Api/Data/Music/TrackInfo.java +++ b/src/main/java/net/Broken/Api/Data/Music/TrackInfo.java @@ -5,10 +5,6 @@ import net.Broken.Api.Data.UserInfo; import net.Broken.Audio.UserAudioTrack; public record TrackInfo(UserInfo submitter, AudioTrackInfo detail) { - public TrackInfo(UserInfo submitter, AudioTrackInfo detail) { - this.submitter = submitter; - this.detail = detail; - } public TrackInfo(UserAudioTrack userAudioTrack) { this(new UserInfo(userAudioTrack.getSubmittedUser().getId(), userAudioTrack.getSubmittedUser().getName(), userAudioTrack.getSubmittedUser().getAvatarUrl()), diff --git a/src/main/java/net/Broken/Api/OpenApi/OpenApiConfig.java b/src/main/java/net/Broken/Api/OpenApi/OpenApiConfig.java index 8ea91a8..64d839a 100644 --- a/src/main/java/net/Broken/Api/OpenApi/OpenApiConfig.java +++ b/src/main/java/net/Broken/Api/OpenApi/OpenApiConfig.java @@ -5,7 +5,6 @@ import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.security.SecurityRequirement; import io.swagger.v3.oas.models.security.SecurityScheme; import io.swagger.v3.oas.models.servers.Server; -import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/net/Broken/Api/Security/Components/UnauthorizedHandler.java b/src/main/java/net/Broken/Api/Security/Components/UnauthorizedHandler.java index 1f3ef57..0cb9d77 100644 --- a/src/main/java/net/Broken/Api/Security/Components/UnauthorizedHandler.java +++ b/src/main/java/net/Broken/Api/Security/Components/UnauthorizedHandler.java @@ -8,7 +8,6 @@ import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -20,7 +19,7 @@ public class UnauthorizedHandler implements AuthenticationEntryPoint { private final Logger logger = LogManager.getLogger(); @Override - public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException { + public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { logger.error("[API] Unauthorized error: {}", authException.getMessage()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); diff --git a/src/main/java/net/Broken/Api/Security/Data/AccessTokenResponse.java b/src/main/java/net/Broken/Api/Security/Data/AccessTokenResponse.java index 01e52c6..5512583 100644 --- a/src/main/java/net/Broken/Api/Security/Data/AccessTokenResponse.java +++ b/src/main/java/net/Broken/Api/Security/Data/AccessTokenResponse.java @@ -1,7 +1,5 @@ package net.Broken.Api.Security.Data; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - public record AccessTokenResponse( String access_token, String token_type, diff --git a/src/main/java/net/Broken/Api/Security/Data/JwtResponse.java b/src/main/java/net/Broken/Api/Security/Data/JwtResponse.java index 1510763..8f93ab2 100644 --- a/src/main/java/net/Broken/Api/Security/Data/JwtResponse.java +++ b/src/main/java/net/Broken/Api/Security/Data/JwtResponse.java @@ -1,7 +1,5 @@ package net.Broken.Api.Security.Data; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; - public record JwtResponse(String token) { } diff --git a/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionHandler.java b/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionHandler.java index 6799caa..87edfa8 100644 --- a/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionHandler.java +++ b/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionHandler.java @@ -1,6 +1,5 @@ package net.Broken.Api.Security.Expression; -import net.Broken.Api.Security.Expression.CustomMethodSecurityExpressionRoot; import org.aopalliance.intercept.MethodInvocation; import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations; @@ -10,7 +9,7 @@ import org.springframework.security.core.Authentication; public class CustomMethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler { - private AuthenticationTrustResolver trustResolver = + private final AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl(); @Override diff --git a/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionRoot.java b/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionRoot.java index 27ab12c..85fc3f9 100644 --- a/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionRoot.java +++ b/src/main/java/net/Broken/Api/Security/Expression/CustomMethodSecurityExpressionRoot.java @@ -2,9 +2,9 @@ package net.Broken.Api.Security.Expression; import net.Broken.Api.Data.Music.Connect; import net.Broken.Api.Security.Data.JwtPrincipal; +import net.Broken.Audio.GuildAudioWrapper; import net.Broken.MainBot; import net.Broken.Tools.CacheTools; -import net.Broken.Audio.GuildAudioWrapper; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; diff --git a/src/main/java/net/Broken/Api/Security/SecurityConfig.java b/src/main/java/net/Broken/Api/Security/SecurityConfig.java index a650b55..dfaee16 100644 --- a/src/main/java/net/Broken/Api/Security/SecurityConfig.java +++ b/src/main/java/net/Broken/Api/Security/SecurityConfig.java @@ -33,9 +33,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { http.addFilterBefore(jwtFilter(), UsernamePasswordAuthenticationFilter.class); -// http.exceptionHandling().authenticationEntryPoint((request, response, authException) -> { -// response.sendError(HttpServletResponse.SC_UNAUTHORIZED); -// }); } @Bean diff --git a/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java b/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java index 6d77e84..5676833 100644 --- a/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java +++ b/src/main/java/net/Broken/Api/Security/Services/DiscordOauthService.java @@ -12,7 +12,6 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.IOException; -import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; @@ -143,7 +142,7 @@ public class DiscordOauthService { } - private String getFormString(HashMap params) throws UnsupportedEncodingException { + private String getFormString(HashMap params) { StringBuilder result = new StringBuilder(); boolean first = true; for (Map.Entry entry : params.entrySet()) { diff --git a/src/main/java/net/Broken/Api/Security/Services/JwtService.java b/src/main/java/net/Broken/Api/Security/Services/JwtService.java index 0672f6a..1e4df47 100644 --- a/src/main/java/net/Broken/Api/Security/Services/JwtService.java +++ b/src/main/java/net/Broken/Api/Security/Services/JwtService.java @@ -1,7 +1,10 @@ package net.Broken.Api.Security.Services; -import io.jsonwebtoken.*; +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.security.Keys; import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Repository.UserRepository; diff --git a/src/main/java/net/Broken/Api/Services/AudioService.java b/src/main/java/net/Broken/Api/Services/AudioService.java index 6518df6..9d4af52 100644 --- a/src/main/java/net/Broken/Api/Services/AudioService.java +++ b/src/main/java/net/Broken/Api/Services/AudioService.java @@ -5,9 +5,9 @@ import net.Broken.Api.Data.Music.Connect; import net.Broken.Api.Data.Music.PlayBackInfo; import net.Broken.Api.Data.Music.Status; import net.Broken.Api.Data.Music.TrackInfo; -import net.Broken.MainBot; import net.Broken.Audio.GuildAudioWrapper; import net.Broken.Audio.UserAudioTrack; +import net.Broken.MainBot; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.audio.hooks.ConnectionStatus; import net.dv8tion.jda.api.entities.Guild; diff --git a/src/main/java/net/Broken/Api/Services/GuildService.java b/src/main/java/net/Broken/Api/Services/GuildService.java index 3a51d0f..007f2d9 100644 --- a/src/main/java/net/Broken/Api/Services/GuildService.java +++ b/src/main/java/net/Broken/Api/Services/GuildService.java @@ -1,11 +1,10 @@ package net.Broken.Api.Services; -import net.Broken.Api.Data.Guild.Guild; import net.Broken.Api.Data.Guild.Channel; +import net.Broken.Api.Data.Guild.Guild; 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; diff --git a/src/main/java/net/Broken/Api/Services/SettingService.java b/src/main/java/net/Broken/Api/Services/SettingService.java index d608639..827597e 100644 --- a/src/main/java/net/Broken/Api/Services/SettingService.java +++ b/src/main/java/net/Broken/Api/Services/SettingService.java @@ -1,7 +1,5 @@ package net.Broken.Api.Services; -import liquibase.pro.packaged.V; -import net.Broken.Api.Data.Settings.SettingDescriber; import net.Broken.Api.Data.Settings.SettingGroup; import net.Broken.Api.Data.Settings.Value; import net.Broken.DB.Entity.GuildPreferenceEntity; @@ -13,7 +11,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Service; -import java.util.ArrayList; import java.util.List; @Service diff --git a/src/main/java/net/Broken/Audio/AudioPlayerSendHandler.java b/src/main/java/net/Broken/Audio/AudioPlayerSendHandler.java index 5d99c8f..665d3aa 100644 --- a/src/main/java/net/Broken/Audio/AudioPlayerSendHandler.java +++ b/src/main/java/net/Broken/Audio/AudioPlayerSendHandler.java @@ -33,7 +33,7 @@ public class AudioPlayerSendHandler implements AudioSendHandler { @Override public ByteBuffer provide20MsAudio() { - return (ByteBuffer) buffer.flip(); + return buffer.flip(); } @Override diff --git a/src/main/java/net/Broken/Audio/GuildAudioWrapper.java b/src/main/java/net/Broken/Audio/GuildAudioWrapper.java index cbb39f8..85555b5 100644 --- a/src/main/java/net/Broken/Audio/GuildAudioWrapper.java +++ b/src/main/java/net/Broken/Audio/GuildAudioWrapper.java @@ -9,7 +9,6 @@ import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import net.Broken.MainBot; -import net.Broken.RestApi.Data.UserAudioTrackData; import net.Broken.Tools.EmbedMessageUtils; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.MessageBuilder; @@ -294,7 +293,7 @@ public class GuildAudioWrapper { */ public void list(GenericInteractionCreateEvent event) { GuildAudioManager musicManager = getGuidAudioManager(); - List list = musicManager.scheduler.getList(); + List list = musicManager.scheduler.getList(); if (list.size() == 0) { Message message = new MessageBuilder().setEmbeds( @@ -308,11 +307,11 @@ public class GuildAudioWrapper { } else { StringBuilder resp = new StringBuilder(); int i = 0; - for (UserAudioTrackData trackInfo : list) { + for (UserAudioTrack trackInfo : list) { resp.append(":arrow_right: "); - resp.append(trackInfo.getAudioTrackInfo().title); + resp.append(trackInfo.getAudioTrack().getInfo().title); resp.append(" - "); - resp.append(trackInfo.getAudioTrackInfo().author); + resp.append(trackInfo.getAudioTrack().getInfo().author); resp.append("\n\n"); if (i >= 5) { resp.append(":arrow_forward: And "); diff --git a/src/main/java/net/Broken/Audio/NotConnectedException.java b/src/main/java/net/Broken/Audio/NotConnectedException.java deleted file mode 100644 index 695d4bc..0000000 --- a/src/main/java/net/Broken/Audio/NotConnectedException.java +++ /dev/null @@ -1,8 +0,0 @@ -package net.Broken.Audio; - - -/** - * Not connected Exception (Voice Channel) - */ -public class NotConnectedException extends Exception { -} diff --git a/src/main/java/net/Broken/Audio/NullMusicManager.java b/src/main/java/net/Broken/Audio/NullMusicManager.java deleted file mode 100644 index 3b6c2c8..0000000 --- a/src/main/java/net/Broken/Audio/NullMusicManager.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.Broken.Audio; - -/** - * Null music manager - */ -public class NullMusicManager extends Exception { -} diff --git a/src/main/java/net/Broken/Audio/TrackScheduler.java b/src/main/java/net/Broken/Audio/TrackScheduler.java index e3cda96..2b19d97 100644 --- a/src/main/java/net/Broken/Audio/TrackScheduler.java +++ b/src/main/java/net/Broken/Audio/TrackScheduler.java @@ -1,6 +1,5 @@ package net.Broken.Audio; -import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter; import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; @@ -8,15 +7,10 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; import net.Broken.MainBot; -import net.Broken.RestApi.Data.UserAudioTrackData; -import net.Broken.Audio.Youtube.RelatedIdNotFound; -import net.Broken.Audio.Youtube.YoutubeSearchRework; -import net.Broken.Audio.Youtube.YoutubeTools; import net.dv8tion.jda.api.entities.Guild; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingDeque; @@ -31,9 +25,7 @@ public class TrackScheduler extends AudioEventAdapter { private final Guild guild; private UserAudioTrack currentPlayingTrack; - private boolean autoFlow = false; - private ArrayList history = new ArrayList<>(); - private Logger logger = LogManager.getLogger(); + private final Logger logger = LogManager.getLogger(); /** * @param player The audio player this scheduler uses @@ -57,20 +49,13 @@ public class TrackScheduler extends AudioEventAdapter { // track goes to the queue instead. if (track.getSubmittedUser() != MainBot.jda.getSelfUser()) { logger.debug("[" + guild + "] Flush history"); - history = new ArrayList<>(); } - history.add(track.getAudioTrack().getIdentifier()); if (!player.startTrack(track.getAudioTrack(), true)) { queue.offer(track); } else { currentPlayingTrack = track; } - if (track.getSubmittedUser() != MainBot.jda.getSelfUser()) { - needAutoPlay(); - } - - } /** @@ -82,22 +67,11 @@ public class TrackScheduler extends AudioEventAdapter { // Calling startTrack with the noInterrupt set to true will start the track only if nothing is currently playing. If // something is playing, it returns false and does nothing. In that case the player was already playing so this // track goes to the queue instead. - if (track.getSubmittedUser() != MainBot.jda.getSelfUser()) { - logger.debug("Flush history"); - history = new ArrayList<>(); - } - - history.add(track.getAudioTrack().getIdentifier()); if (!player.startTrack(track.getAudioTrack(), true)) { queue.addFirst(track); } else { currentPlayingTrack = track; } - if (track.getSubmittedUser() != MainBot.jda.getSelfUser()) { - - needAutoPlay(); - } else - logger.debug("[" + guild + "] Bot add, ignore autoFlow"); } public void pause() { @@ -119,14 +93,12 @@ public class TrackScheduler extends AudioEventAdapter { queue.clear(); } - public List getList() { -// AudioTrack[] test = (AudioTrack[]) queue.toArray(); - - List temp = new ArrayList<>(); + public List getList() { + List temp = new ArrayList<>(); Object[] test = queue.toArray(); for (Object track : test) { UserAudioTrack casted = (UserAudioTrack) track; - temp.add(new UserAudioTrackData(casted.getSubmittedUser().getName(), casted.getAudioTrack().getInfo())); + temp.add(casted); } return temp; } @@ -147,7 +119,6 @@ public class TrackScheduler extends AudioEventAdapter { return false; } else { logger.info("[" + guild + "] Delete successful"); - needAutoPlay(); return true; } } @@ -168,8 +139,6 @@ public class TrackScheduler extends AudioEventAdapter { this.currentPlayingTrack = track; player.startTrack(track.getAudioTrack(), false); } - - needAutoPlay(); } @Override @@ -217,39 +186,4 @@ public class TrackScheduler extends AudioEventAdapter { super.onTrackStuck(player, track, thresholdMs); GuildAudioWrapper.getInstance(guild).updateLastButton(); } - - private void needAutoPlay() { - if ((queue.size() < 1) && autoFlow && currentPlayingTrack != null) { - logger.debug("[" + guild.getName() + "] Auto add needed!"); - GuildAudioWrapper guildAudioWrapper = GuildAudioWrapper.getInstance(guild); - YoutubeSearchRework youtubeSearchRework = YoutubeSearchRework.getInstance(); - try { - String id = youtubeSearchRework.getRelatedVideo(currentPlayingTrack.getAudioTrack().getInfo().identifier); - logger.debug("[" + guild.getName() + "] Related id: " + id); - guildAudioWrapper.loadAndPlayAuto(id); - } catch (IOException | RelatedIdNotFound ex) { - logger.debug("[" + guild.getName() + "] Can't find related id, try API..."); - YoutubeTools youtubeTools = YoutubeTools.getInstance(); - try { - String id = youtubeTools.getRelatedVideo(currentPlayingTrack.getAudioTrack().getInfo().identifier, history); - logger.debug("[" + guild.getName() + "] Related id: " + id); - guildAudioWrapper.loadAndPlayAuto(id); - - } catch (GoogleJsonResponseException e) { - logger.error("[" + guild.getName() + "] There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage()); - } catch (IOException t) { - logger.catching(t); - } - } - } - } - - public boolean isAutoFlow() { - return autoFlow; - } - - public void setAutoFlow(boolean autoFlow) { - this.autoFlow = autoFlow; - needAutoPlay(); - } } diff --git a/src/main/java/net/Broken/Audio/UserAudioTrack.java b/src/main/java/net/Broken/Audio/UserAudioTrack.java index 584cff2..edbe18a 100644 --- a/src/main/java/net/Broken/Audio/UserAudioTrack.java +++ b/src/main/java/net/Broken/Audio/UserAudioTrack.java @@ -7,8 +7,8 @@ import net.dv8tion.jda.api.entities.User; * Container that link AudioTrack to who submit it (User) */ public class UserAudioTrack { - private User user; - private AudioTrack audioTrack; + private final User user; + private final AudioTrack audioTrack; public UserAudioTrack(User user, AudioTrack audioTrack) { this.user = user; diff --git a/src/main/java/net/Broken/Audio/Youtube/RelatedIdNotFound.java b/src/main/java/net/Broken/Audio/Youtube/RelatedIdNotFound.java deleted file mode 100644 index 89d71d6..0000000 --- a/src/main/java/net/Broken/Audio/Youtube/RelatedIdNotFound.java +++ /dev/null @@ -1,4 +0,0 @@ -package net.Broken.Audio.Youtube; - -public class RelatedIdNotFound extends Exception { -} diff --git a/src/main/java/net/Broken/Audio/Youtube/SearchResult.java b/src/main/java/net/Broken/Audio/Youtube/SearchResult.java deleted file mode 100644 index b00e1d5..0000000 --- a/src/main/java/net/Broken/Audio/Youtube/SearchResult.java +++ /dev/null @@ -1,37 +0,0 @@ -package net.Broken.Audio.Youtube; - -public class SearchResult { - public String id; - public String title; - public String description; - public String publishedAt; - public String channelId; - public String channelTittle; - public String imageUrl; - public String duration; - - public SearchResult(com.google.api.services.youtube.model.SearchResult result, String duration) { - if (result.getId().getVideoId() == null) - id = result.getId().getPlaylistId(); - else - id = result.getId().getVideoId(); - title = result.getSnippet().getTitle(); - description = result.getSnippet().getDescription(); - publishedAt = result.getSnippet().getPublishedAt().toString(); - channelId = result.getSnippet().getChannelId(); - channelTittle = result.getSnippet().getChannelTitle(); - imageUrl = result.getSnippet().getThumbnails().getDefault().getUrl(); - this.duration = duration; - } - - public SearchResult(String id, String title, String description, String publishedAt, String channelId, String channelTittle, String imageUrl, String duration) { - this.id = id; - this.title = title; - this.description = description; - this.publishedAt = publishedAt; - this.channelId = channelId; - this.channelTittle = channelTittle; - this.imageUrl = imageUrl; - this.duration = duration; - } -} diff --git a/src/main/java/net/Broken/Audio/Youtube/YoutubeSearchRework.java b/src/main/java/net/Broken/Audio/Youtube/YoutubeSearchRework.java deleted file mode 100644 index 755a20f..0000000 --- a/src/main/java/net/Broken/Audio/Youtube/YoutubeSearchRework.java +++ /dev/null @@ -1,140 +0,0 @@ -package net.Broken.Audio.Youtube; - -import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioTrack; -import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeSearchProvider; -import com.sedmelluq.discord.lavaplayer.track.AudioTrack; -import com.sedmelluq.discord.lavaplayer.track.BasicAudioPlaylist; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.jsoup.Jsoup; -import org.jsoup.nodes.Document; -import org.jsoup.nodes.Element; -import org.jsoup.select.Elements; - -import java.io.IOException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; - -public class YoutubeSearchRework { - - private static YoutubeSearchRework INSTANCE; - private Logger logger = LogManager.getLogger(); - - public static YoutubeSearchRework getInstance() { - if (INSTANCE == null) { - INSTANCE = new YoutubeSearchRework(); - } - return INSTANCE; - } - - - public List searchVideo(String search, int maxResult, boolean playlist) throws IOException { - search = URLEncoder.encode(search, StandardCharsets.UTF_8.toString()); - - YoutubeSearchProvider searchProvider = new YoutubeSearchProvider(); - BasicAudioPlaylist rawResult = (BasicAudioPlaylist) searchProvider.loadSearchResult(search, audioTrackInfo -> new YoutubeAudioTrack(audioTrackInfo, null)); - List results = new ArrayList<>(); - for (AudioTrack track : rawResult.getTracks()) { - String imageUrl = "https://i.ytimg.com/vi/" + track.getIdentifier() + "/hqdefault.jpg"; - long hour = TimeUnit.MILLISECONDS.toHours(track.getInfo().length); - String hms = hour == 0 ? "" : Long.toString(hour); - hms += String.format("%02d:%02d", - TimeUnit.MILLISECONDS.toMinutes(track.getInfo().length) % TimeUnit.HOURS.toMinutes(1), - TimeUnit.MILLISECONDS.toSeconds(track.getInfo().length) % TimeUnit.MINUTES.toSeconds(1)); - results.add(new SearchResult(track.getIdentifier(), track.getInfo().title, "", "", "", track.getInfo().author, imageUrl, hms)); - } - - return results; - } - - - private Document getYoutubeSearchDocument(String URL) throws IOException { - - return Jsoup.connect(URL).userAgent("Googlebot/2.1 (+http://www.googlebot.com/bot.html)").header("Accept-Language", "en-US").get(); - - - } - - // video = EgIQAQ== - private List extractVideoInfo(Document doc, int maxResult, boolean playlist) { - Elements videosDivs = doc.select(".yt-lockup"); - List results = new ArrayList<>(); - int i = 0; - for (Element videoDiv : videosDivs) { - if (i >= maxResult) - break; - Element titleDiv = videoDiv.selectFirst(".yt-uix-tile-link"); - String id; - if (!playlist) - id = titleDiv.attributes().get("href").replace("/watch?v=", ""); - else { - String listUrl = titleDiv.attributes().get("href"); - int listIndex = listUrl.indexOf("list="); - id = listUrl.substring(listIndex).replace("list=", ""); - - } - - String title = titleDiv.text(); - Elements metas = videoDiv.selectFirst(".yt-lockup-meta-info").getElementsByTag("li"); - String view = ""; - String date = ""; - if (!playlist) { - for (Element metaElem : metas) { - - if (metaElem.text().contains("view")) { - view = metaElem.text(); - } else { - date = metaElem.text(); - } - } - } - - - Element chanelTag = videoDiv.selectFirst(".yt-lockup-byline").getElementsByTag("a").get(0); - String channelTittle = chanelTag.text(); - String channelId = chanelTag.attributes().get("href").replace("/channel/", ""); - - String imageUrl; - String duration; - if (!playlist) { - duration = videoDiv.selectFirst(".video-time").text(); - imageUrl = "https://i.ytimg.com/vi/" + id + "/hqdefault.jpg"; - } else { - String listUrl = titleDiv.attributes().get("href"); - int listIndex = listUrl.indexOf("&list="); - listUrl = listUrl.substring(0, listIndex).replace("/watch?v=", ""); - imageUrl = "https://i.ytimg.com/vi/" + listUrl + "/hqdefault.jpg"; - duration = videoDiv.selectFirst(".formatted-video-count-label").text(); - } - - - results.add(new SearchResult(id, title, "", date, channelId, channelTittle, imageUrl, duration)); - i++; - - - } - return results; - } - - public String getRelatedVideo(String sourceVideoId) throws IOException, RelatedIdNotFound { - sourceVideoId = URLEncoder.encode(sourceVideoId, StandardCharsets.UTF_8.toString()); - String url = "https://www.youtube.com/watch?v=" + sourceVideoId; - Document doc = getYoutubeSearchDocument(url); - - return extractRelatedVideoId(doc); - } - - private String extractRelatedVideoId(Document doc) throws RelatedIdNotFound { - Elements elements = doc.select(".ytd-compact-autoplay-renderer .yt-simple-endpoint"); - if (elements.size() == 0) { - throw new RelatedIdNotFound(); - } - Element elem = elements.get(0); - String url = elem.attributes().get("href"); - return url.replace("/watch?v=", ""); - } - -} diff --git a/src/main/java/net/Broken/Audio/Youtube/YoutubeTools.java b/src/main/java/net/Broken/Audio/Youtube/YoutubeTools.java deleted file mode 100644 index a126570..0000000 --- a/src/main/java/net/Broken/Audio/Youtube/YoutubeTools.java +++ /dev/null @@ -1,175 +0,0 @@ -package net.Broken.Audio.Youtube; - -import com.google.api.client.http.javanet.NetHttpTransport; -import com.google.api.client.json.gson.GsonFactory; -import com.google.api.services.youtube.YouTube; -import com.google.api.services.youtube.model.SearchResult; -import com.google.api.services.youtube.model.*; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; - -public class YoutubeTools { - - private static YoutubeTools INSTANCE; - private Logger logger = LogManager.getLogger(); - private String apiKey = System.getenv("GOOGLE_API_KEY"); - - private YoutubeTools() { - - } - - public static YoutubeTools getInstance() { - if (INSTANCE == null) - INSTANCE = new YoutubeTools(); - return INSTANCE; - } - - - private YouTube getYoutubeService() { - - YouTube.Builder builder = new YouTube.Builder(new NetHttpTransport(), new GsonFactory(), request -> { - }); - builder.setApplicationName("BotDiscord"); - return builder.build(); - - } - - - public String getRelatedVideo(String videoId, ArrayList history) throws IOException { - - - YouTube youtube = getYoutubeService(); - - - YouTube.Search.List searchListRelatedVideosRequest = youtube.search().list(Collections.singletonList("snippet")); - searchListRelatedVideosRequest.setRelatedToVideoId(videoId); - searchListRelatedVideosRequest.setType(Collections.singletonList("video")); - - searchListRelatedVideosRequest.setKey(apiKey); - - SearchListResponse response = searchListRelatedVideosRequest.execute(); - - for (SearchResult item : response.getItems()) { - if (!history.contains(item.getId().getVideoId())) { - if (item.getSnippet() != null) - return item.getId().getVideoId(); - } else - logger.debug("ID already on history"); - } - - logger.debug("All on history ?"); - return response.getItems().get(0).getId().getVideoId(); - - } - - - public ArrayList search(String query, long max, boolean playlist) throws IOException { - YouTube youTube = getYoutubeService(); - YouTube.Search.List searchList = youTube.search().list(Collections.singletonList("snippet")); - if (playlist) - searchList.setType(Collections.singletonList("playlist")); - else - searchList.setType(Collections.singletonList("video")); - searchList.setSafeSearch("none"); - searchList.setMaxResults(max); - searchList.setQ(query); - searchList.setKey(apiKey); - searchList.setOrder("relevance"); - - SearchListResponse response = searchList.execute(); - - StringBuilder idString = new StringBuilder(); - - - if (playlist) { - for (SearchResult item : response.getItems()) { - idString.append(item.getId().getPlaylistId()).append(","); - } - HashMap playlistHashMap = new HashMap<>(); - YouTube.Playlists.List list = youTube.playlists().list(Collections.singletonList("contentDetails")); - list.setId(Collections.singletonList(idString.toString())); - list.setKey(apiKey); - PlaylistListResponse playlistResponse = list.execute(); - for (Playlist item : playlistResponse.getItems()) { - playlistHashMap.put(item.getId(), item); - } - ArrayList finalResult = new ArrayList<>(); - for (SearchResult item : response.getItems()) { - logger.trace(item.getSnippet().getTitle()); - finalResult.add(new net.Broken.Audio.Youtube.SearchResult(item, playlistHashMap.get(item.getId().getPlaylistId()).getContentDetails().getItemCount().toString() + " Video(s)")); - - } - return finalResult; - } else { - for (SearchResult item : response.getItems()) { - idString.append(item.getId().getVideoId()).append(","); - } - HashMap videoHashMap = new HashMap<>(); - YouTube.Videos.List video = youTube.videos().list(Collections.singletonList("contentDetails")); - video.setId(Collections.singletonList(idString.toString())); - video.setKey(apiKey); - VideoListResponse videoResponse = video.execute(); - for (Video item : videoResponse.getItems()) { - videoHashMap.put(item.getId(), item); - } - ArrayList finalResult = new ArrayList<>(); - for (SearchResult item : response.getItems()) { - logger.trace(item.getSnippet().getTitle()); - finalResult.add(new net.Broken.Audio.Youtube.SearchResult(item, videoHashMap.get(item.getId().getVideoId()).getContentDetails().getDuration())); - } - return finalResult; - } - - - } - - - public String ytTimeToString(String time) { - int hours; - int minutes; - int seconds; - if (time.equals("PT0S")) - return ":red_circle: LIVE"; - - time = time.replace("PT", ""); - if (time.contains("H")) { - - String matched = time.substring(0, time.indexOf("H") + 1); - time = time.replace(matched, ""); - hours = Integer.parseInt(matched.replace("H", "")); - } else - hours = 0; - logger.trace(time); - - if (time.contains("M")) { - - String matched = time.substring(0, time.indexOf("M") + 1); - time = time.replace(matched, ""); - minutes = Integer.parseInt(matched.replace("M", "")); - } else - minutes = 0; - logger.trace(time); - if (time.contains("S")) { - - String matched = time.substring(0, time.indexOf("S") + 1); - time = time.replace(matched, ""); - seconds = Integer.parseInt(matched.replace("S", "")); - } else - seconds = 0; - logger.trace(time); - - String hoursStr = (hours < 10) ? "0" + hours : String.valueOf(hours); - String minutesStr = (minutes < 10) ? "0" + minutes : String.valueOf(minutes); - String secondsStr = (seconds < 10) ? "0" + seconds : String.valueOf(seconds); - if (hours > 0) - return hoursStr + ":" + minutesStr + ":" + secondsStr; - else - return minutesStr + ":" + secondsStr; - - } -} diff --git a/src/main/java/net/Broken/BotConfigLoader.java b/src/main/java/net/Broken/BotConfigLoader.java index 702cbe9..72c2e02 100644 --- a/src/main/java/net/Broken/BotConfigLoader.java +++ b/src/main/java/net/Broken/BotConfigLoader.java @@ -2,7 +2,7 @@ package net.Broken; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConstructorBinding; -import org.springframework.context.annotation.Configuration; + @ConfigurationProperties(prefix = "discord.bot") @ConstructorBinding public record BotConfigLoader ( diff --git a/src/main/java/net/Broken/BotListener.java b/src/main/java/net/Broken/BotListener.java index 830c9f1..d9d3679 100644 --- a/src/main/java/net/Broken/BotListener.java +++ b/src/main/java/net/Broken/BotListener.java @@ -1,11 +1,11 @@ package net.Broken; +import net.Broken.Audio.GuildAudioWrapper; import net.Broken.DB.Entity.GuildPreferenceEntity; import net.Broken.DB.Repository.GuildPreferenceRepository; import net.Broken.Tools.AutoVoiceChannel; import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.UserManager.Stats.UserStatsUtils; -import net.Broken.Audio.GuildAudioWrapper; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.entities.*; @@ -193,9 +193,7 @@ public class BotListener extends ListenerAdapter { logger.info("Join new guild! (" + event.getGuild().getName() + " " + event.getGuild().getMembers().size() + " Members)"); super.onGuildJoin(event); getPreference(event.getGuild()); - event.getGuild().loadMembers().onSuccess((members -> { - logger.debug("[" + event.getGuild().getName() + "] Members loaded"); - })); + event.getGuild().loadMembers().onSuccess((members -> logger.debug("[" + event.getGuild().getName() + "] Members loaded"))); EmbedBuilder eb = new EmbedBuilder().setColor(Color.GREEN) .setTitle("Hello there !") .setDescription("Allow me to introduce myself -- I am a CL4P-TP the discord bot, but my friends call me Claptrap ! Or they would, if any of them were real...\n" + diff --git a/src/main/java/net/Broken/Commands/ChannelsReview.java b/src/main/java/net/Broken/Commands/ChannelsReview.java index b298c6a..46b1db6 100644 --- a/src/main/java/net/Broken/Commands/ChannelsReview.java +++ b/src/main/java/net/Broken/Commands/ChannelsReview.java @@ -17,7 +17,7 @@ import java.util.HashMap; import java.util.Locale; public class ChannelsReview implements Commande { - Logger logger = LogManager.getLogger(); + final Logger logger = LogManager.getLogger(); @Override public void action(String[] args, MessageReceivedEvent event) { @@ -45,7 +45,7 @@ public class ChannelsReview implements Commande { try { Message lastMessage = textChannel.retrieveMessageById(lastMessageId).complete(); if (beforeDate.compareTo(format.parse(lastMessage.getTimeCreated().format(formatter))) > 0) { - logger.debug("Last message in channel " + textChannel.toString() + " is " + lastMessageId); + logger.debug("Last message in channel " + textChannel + " is " + lastMessageId); String date = lastMessage.getTimeCreated().format(formatter); charCtl += textChannel.getName().length() + date.length(); result.put(textChannel.getName(), date); @@ -77,7 +77,7 @@ public class ChannelsReview implements Commande { for (TextChannel textChannel : event.getGuild().getTextChannels()) { if (textChannel.hasLatestMessage()) { String lastMessageId = textChannel.getLatestMessageId(); - logger.debug("Last message in channel " + textChannel.toString() + " is " + lastMessageId); + logger.debug("Last message in channel " + textChannel + " is " + lastMessageId); try { Message lastMessage = textChannel.retrieveMessageById(lastMessageId).complete(); diff --git a/src/main/java/net/Broken/Commands/ReportUsers.java b/src/main/java/net/Broken/Commands/ReportUsers.java index cc1298c..ccb9f09 100644 --- a/src/main/java/net/Broken/Commands/ReportUsers.java +++ b/src/main/java/net/Broken/Commands/ReportUsers.java @@ -6,6 +6,8 @@ import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.requests.RestAction; +import java.util.Objects; + public class ReportUsers implements Commande { @@ -18,11 +20,8 @@ public class ReportUsers implements Commande { for (Member member : members) { if (member.getRoles().size() == 1) { //check if the member has a role if (member.getRoles().contains(event.getMessage().getMentionedRoles().get(0))) { //check if the mentioned role is the same as the member's role - if (restAction == null) { - restAction = event.getTextChannel().sendMessage("List des membres : ").and(event.getTextChannel().sendMessage(member.getEffectiveName())); - } else { - restAction = restAction.and(event.getTextChannel().sendMessage(member.getEffectiveName())); - } + restAction = Objects.requireNonNullElseGet(restAction, () -> event.getTextChannel().sendMessage("List des membres : ")) + .and(event.getTextChannel().sendMessage(member.getEffectiveName())); } } } diff --git a/src/main/java/net/Broken/DB/Entity/GuildPreferenceEntity.java b/src/main/java/net/Broken/DB/Entity/GuildPreferenceEntity.java index 5af4ab3..647aaa4 100644 --- a/src/main/java/net/Broken/DB/Entity/GuildPreferenceEntity.java +++ b/src/main/java/net/Broken/DB/Entity/GuildPreferenceEntity.java @@ -1,11 +1,6 @@ package net.Broken.DB.Entity; -import net.Broken.Api.Data.Settings.Value; -import net.dv8tion.jda.api.entities.Guild; - import javax.persistence.*; -import java.util.ArrayList; -import java.util.List; @Entity public class GuildPreferenceEntity { diff --git a/src/main/java/net/Broken/DB/Entity/PlaylistEntity.java b/src/main/java/net/Broken/DB/Entity/PlaylistEntity.java deleted file mode 100644 index aff033d..0000000 --- a/src/main/java/net/Broken/DB/Entity/PlaylistEntity.java +++ /dev/null @@ -1,79 +0,0 @@ -package net.Broken.DB.Entity; - - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import javax.persistence.*; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -@Entity -public class PlaylistEntity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Integer id; - - private String name; - - @JsonIgnore - @ManyToOne - @JoinColumn(name = "userEntity_id", nullable = false) - private UserEntity user; - - - @OneToMany(mappedBy = "playlist") - private List tracks; - - - public PlaylistEntity() { - } - - public PlaylistEntity(String name, UserEntity user) { - this.name = name; - this.user = user; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public UserEntity getUser() { - return user; - } - - public void setUser(UserEntity user) { - this.user = user; - } - - public List getTracks() { - return tracks; - } - - public void setTracks(List tracks) { - this.tracks = tracks; - } - - public void addTracks(TrackEntity... tracks) { - if (this.tracks == null) - this.tracks = new ArrayList<>(); - - this.tracks.addAll(Arrays.asList(tracks)); - } - - -} diff --git a/src/main/java/net/Broken/DB/Entity/TrackEntity.java b/src/main/java/net/Broken/DB/Entity/TrackEntity.java deleted file mode 100644 index ee449cb..0000000 --- a/src/main/java/net/Broken/DB/Entity/TrackEntity.java +++ /dev/null @@ -1,94 +0,0 @@ -package net.Broken.DB.Entity; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; - -import javax.persistence.*; - -@Entity -public class TrackEntity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Integer id; - - private String title; - - private String url; - - private String identifier; - - private Integer pos; - - @JsonIgnore - @ManyToOne - @JoinColumn(name = "playlistEntity_id", nullable = false) - private PlaylistEntity playlist; - - public TrackEntity() { - } - - public TrackEntity(AudioTrackInfo trackInfo, int pos, PlaylistEntity playlist) { - this.title = trackInfo.title; - this.url = trackInfo.uri; - this.identifier = trackInfo.identifier; - this.playlist = playlist; - this.pos = pos; - } - - public TrackEntity(TrackEntity trackEntity) { - this.title = trackEntity.title; - this.url = trackEntity.url; - this.identifier = trackEntity.identifier; - this.pos = trackEntity.pos; - this.playlist = trackEntity.playlist; - } - - public Integer getId() { - return id; - } - - public void setId(Integer id) { - this.id = id; - } - - public PlaylistEntity getPlaylist() { - return playlist; - } - - public void setPlaylist(PlaylistEntity playlist) { - this.playlist = playlist; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getIdentifier() { - return identifier; - } - - public void setIdentifier(String identifier) { - this.identifier = identifier; - } - - public Integer getPos() { - return pos; - } - - public void setPos(Integer pos) { - this.pos = pos; - } -} diff --git a/src/main/java/net/Broken/DB/Entity/UserEntity.java b/src/main/java/net/Broken/DB/Entity/UserEntity.java index a35cbad..9b5aeee 100644 --- a/src/main/java/net/Broken/DB/Entity/UserEntity.java +++ b/src/main/java/net/Broken/DB/Entity/UserEntity.java @@ -5,8 +5,6 @@ import net.Broken.Api.Security.Data.DiscordOauthUserInfo; import net.dv8tion.jda.api.entities.User; import javax.persistence.*; -import java.util.ArrayList; -import java.util.Arrays; import java.util.List; /** @@ -22,7 +20,7 @@ public class UserEntity { private String discriminator; - @Column(unique=true) + @Column(unique = true) private String discordId; private String avatar; @@ -33,10 +31,6 @@ public class UserEntity { @OneToMany(fetch = FetchType.EAGER, mappedBy = "user") private List userStats; - @OneToMany(mappedBy = "user") - private List playlists; - - public UserEntity() { } @@ -50,7 +44,7 @@ public class UserEntity { this.discordId = id; } - public UserEntity(DiscordOauthUserInfo discordOauthUserInfo){ + public UserEntity(DiscordOauthUserInfo discordOauthUserInfo) { this.username = discordOauthUserInfo.username(); this.discriminator = discordOauthUserInfo.discriminator(); this.discordId = discordOauthUserInfo.id(); @@ -82,21 +76,6 @@ public class UserEntity { this.discordId = discordId; } - public List getPlaylists() { - return playlists; - } - - public void setPlaylists(List playlists) { - this.playlists = playlists; - } - - public void addPlaylist(PlaylistEntity... playlists) { - if (this.playlists == null) - this.playlists = new ArrayList<>(); - - this.playlists.addAll(Arrays.asList(playlists)); - } - public List getUserStats() { return userStats; } diff --git a/src/main/java/net/Broken/DB/Repository/PlaylistRepository.java b/src/main/java/net/Broken/DB/Repository/PlaylistRepository.java deleted file mode 100644 index 4113cbe..0000000 --- a/src/main/java/net/Broken/DB/Repository/PlaylistRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package net.Broken.DB.Repository; - -import net.Broken.DB.Entity.PlaylistEntity; -import org.springframework.data.repository.CrudRepository; - -public interface PlaylistRepository extends CrudRepository { - PlaylistEntity findById(int id); -} diff --git a/src/main/java/net/Broken/DB/Repository/TrackRepository.java b/src/main/java/net/Broken/DB/Repository/TrackRepository.java deleted file mode 100644 index b09ba14..0000000 --- a/src/main/java/net/Broken/DB/Repository/TrackRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.Broken.DB.Repository; - -import net.Broken.DB.Entity.PlaylistEntity; -import net.Broken.DB.Entity.TrackEntity; -import org.springframework.data.repository.CrudRepository; - -import java.util.List; - -public interface TrackRepository extends CrudRepository { - List findDistinctByPlaylistOrderByPos(PlaylistEntity playlistEntity); - - TrackEntity findById(int id); -} diff --git a/src/main/java/net/Broken/Init.java b/src/main/java/net/Broken/Init.java index e8f0186..6318c47 100644 --- a/src/main/java/net/Broken/Init.java +++ b/src/main/java/net/Broken/Init.java @@ -4,7 +4,6 @@ import net.Broken.DB.Entity.GuildPreferenceEntity; import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Repository.GuildPreferenceRepository; import net.Broken.DB.Repository.UserRepository; -import net.Broken.RestApi.ApiCommandLoader; import net.Broken.Tools.Command.SlashCommandLoader; import net.Broken.Tools.DayListener.DayListener; import net.Broken.Tools.DayListener.Listeners.DailyMadame; @@ -19,7 +18,6 @@ import net.dv8tion.jda.api.utils.MemberCachePolicy; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; -import org.thymeleaf.spring5.processor.SpringOptionFieldTagProcessor; import javax.security.auth.login.LoginException; import java.util.List; @@ -68,7 +66,6 @@ public class Init { logger.info("Loading commands"); SlashCommandLoader.load(config); SlashCommandLoader.registerSlashCommands(jda.updateCommands()); - ApiCommandLoader.load(); DayListener dayListener = DayListener.getInstance(); dayListener.addListener(new DailyMadame()); dayListener.start(); diff --git a/src/main/java/net/Broken/MainBot.java b/src/main/java/net/Broken/MainBot.java index 98e7144..db53fc6 100644 --- a/src/main/java/net/Broken/MainBot.java +++ b/src/main/java/net/Broken/MainBot.java @@ -3,7 +3,6 @@ package net.Broken; import net.dv8tion.jda.api.JDA; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.springframework.boot.ExitCodeGenerator; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; @@ -19,7 +18,7 @@ import java.util.HashMap; public class MainBot { public static HashMap commandes = new HashMap<>(); - public static HashMap slashCommands = new HashMap<>(); + public static final HashMap slashCommands = new HashMap<>(); public static HashMap mutualGuildCount = new HashMap<>(); public static boolean roleFlag = false; public static JDA jda; @@ -42,7 +41,7 @@ public class MainBot { jda = Init.initJda(config); if (jda == null) { - System.exit(SpringApplication.exit(ctx, (ExitCodeGenerator) () -> { + System.exit(SpringApplication.exit(ctx, () -> { logger.fatal("Init error! Close application!"); return 1; })); diff --git a/src/main/java/net/Broken/RestApi/ApiCommandLoader.java b/src/main/java/net/Broken/RestApi/ApiCommandLoader.java deleted file mode 100644 index 6b7ae5c..0000000 --- a/src/main/java/net/Broken/RestApi/ApiCommandLoader.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.Broken.RestApi; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.reflections.Reflections; -import org.reflections.util.ClasspathHelper; -import org.reflections.util.ConfigurationBuilder; - -import java.util.HashMap; -import java.util.Set; - -public class ApiCommandLoader { - public static HashMap apiCommands = new HashMap<>(); - private static Logger logger = LogManager.getLogger(); - - public static void load() { - logger.info("Loading Api Command..."); -// Reflections reflections = new Reflections("net.Broken.RestApi.Command"); - Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage( - "net.Broken.RestApi.Commands", - ClasspathHelper.contextClassLoader(), - ClasspathHelper.staticClassLoader())) - ); - Set> modules = - reflections.getSubTypesOf(CommandInterface.class); - logger.info("Find " + modules.size() + " Command:"); - for (Class apiClass : modules) { - - String reference = apiClass.getName(); - String[] splited = reference.split("\\."); - String name = splited[splited.length - 1].toUpperCase(); - - logger.info("..." + name); - - try { - apiCommands.put(name, apiClass.newInstance()); - } catch (InstantiationException | IllegalAccessException e) { - logger.error("Failed to load " + name + "!"); - } - - } - } - -} diff --git a/src/main/java/net/Broken/RestApi/CommandInterface.java b/src/main/java/net/Broken/RestApi/CommandInterface.java deleted file mode 100644 index 68c2256..0000000 --- a/src/main/java/net/Broken/RestApi/CommandInterface.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.Broken.RestApi; - -import net.Broken.RestApi.Data.CommandPostData; -import net.Broken.RestApi.Data.CommandResponseData; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.User; -import org.springframework.http.ResponseEntity; - - -/** - * Represent RestApi command - */ -public interface CommandInterface { - /** - * Main action - * - * @param musicCommande Current guild music command - * @param data Received data - * @param user User who submit RestApi command - * @param guild - * @return HTTP Response - */ - ResponseEntity action(CommandPostData data, User user, Guild guild); -} diff --git a/src/main/java/net/Broken/RestApi/Data/AllMusicInfoData.java b/src/main/java/net/Broken/RestApi/Data/AllMusicInfoData.java deleted file mode 100644 index 4932304..0000000 --- a/src/main/java/net/Broken/RestApi/Data/AllMusicInfoData.java +++ /dev/null @@ -1,11 +0,0 @@ -package net.Broken.RestApi.Data; - -public class AllMusicInfoData { - public CurrentMusicData currentMusic; - public PlaylistData playlist; - - public AllMusicInfoData(CurrentMusicData currentMusic, PlaylistData playlist) { - this.currentMusic = currentMusic; - this.playlist = playlist; - } -} diff --git a/src/main/java/net/Broken/RestApi/Data/ChanelData.java b/src/main/java/net/Broken/RestApi/Data/ChanelData.java deleted file mode 100644 index 57e3b5c..0000000 --- a/src/main/java/net/Broken/RestApi/Data/ChanelData.java +++ /dev/null @@ -1,17 +0,0 @@ -package net.Broken.RestApi.Data; - -/** - * Data for JSON Parsing - */ -public class ChanelData { - public String name; - public String id; - public int pos; - - public ChanelData(String name, String id, int pos) { - this.name = name; - this.id = id; - this.pos = pos; - - } -} diff --git a/src/main/java/net/Broken/RestApi/Data/CommandPostData.java b/src/main/java/net/Broken/RestApi/Data/CommandPostData.java deleted file mode 100644 index 9ddffce..0000000 --- a/src/main/java/net/Broken/RestApi/Data/CommandPostData.java +++ /dev/null @@ -1,13 +0,0 @@ -package net.Broken.RestApi.Data; - -/** - * Data for JSON Parsing - */ -public class CommandPostData { - public String command; - public boolean onHead; - public String url; - public int playlistLimit; - public String chanelId; - public String name; -} diff --git a/src/main/java/net/Broken/RestApi/Data/CommandResponseData.java b/src/main/java/net/Broken/RestApi/Data/CommandResponseData.java deleted file mode 100644 index 680558c..0000000 --- a/src/main/java/net/Broken/RestApi/Data/CommandResponseData.java +++ /dev/null @@ -1,24 +0,0 @@ -package net.Broken.RestApi.Data; - -import com.fasterxml.jackson.annotation.JsonInclude; - -/** - * Data for JSON Parsing - */ -@JsonInclude(JsonInclude.Include.NON_NULL) -public class CommandResponseData { - public String Commande; - public String Message; - public String error; - - public CommandResponseData(String commande, String message) { - Commande = commande; - Message = message; - } - - public CommandResponseData(String commande, String message, String error) { - Commande = commande; - Message = message; - this.error = error; - } -} diff --git a/src/main/java/net/Broken/RestApi/Data/CurrentMusicData.java b/src/main/java/net/Broken/RestApi/Data/CurrentMusicData.java deleted file mode 100644 index ff5a54c..0000000 --- a/src/main/java/net/Broken/RestApi/Data/CurrentMusicData.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.Broken.RestApi.Data; - -import com.fasterxml.jackson.annotation.JsonInclude; - -/** - * Data for JSON Parsing - */ -@JsonInclude(JsonInclude.Include.NON_NULL) -public class CurrentMusicData { - private final UserAudioTrackData info; - private final long currentPos; - private final String state; - private final boolean pause; - private final boolean autoflow; - - - public CurrentMusicData(UserAudioTrackData info, long currentPos, String state, boolean pause, boolean autoflow) { - this.info = info; - this.currentPos = currentPos; - this.state = state; - this.pause = pause; - this.autoflow = autoflow; - } - - public UserAudioTrackData getInfo() { - return info; - } - - public long getCurrentPos() { - return currentPos; - } - - public String getState() { - if (pause) - return "PAUSE"; - else - return state; - } - - public boolean isAutoflow() { - return autoflow; - } -} diff --git a/src/main/java/net/Broken/RestApi/Data/Playlist/AddToPlaylistData.java b/src/main/java/net/Broken/RestApi/Data/Playlist/AddToPlaylistData.java deleted file mode 100644 index c2f1c94..0000000 --- a/src/main/java/net/Broken/RestApi/Data/Playlist/AddToPlaylistData.java +++ /dev/null @@ -1,11 +0,0 @@ -package net.Broken.RestApi.Data.Playlist; - -import net.Broken.RestApi.Data.CommandPostData; - -public class AddToPlaylistData extends CommandPostData { - - public int playlistId; - - - public int pos; -} diff --git a/src/main/java/net/Broken/RestApi/Data/Playlist/CreatePlaylistData.java b/src/main/java/net/Broken/RestApi/Data/Playlist/CreatePlaylistData.java deleted file mode 100644 index ace8663..0000000 --- a/src/main/java/net/Broken/RestApi/Data/Playlist/CreatePlaylistData.java +++ /dev/null @@ -1,5 +0,0 @@ -package net.Broken.RestApi.Data.Playlist; - -public class CreatePlaylistData { - public String name; -} diff --git a/src/main/java/net/Broken/RestApi/Data/Playlist/DeleteTrackData.java b/src/main/java/net/Broken/RestApi/Data/Playlist/DeleteTrackData.java deleted file mode 100644 index d6b2e3f..0000000 --- a/src/main/java/net/Broken/RestApi/Data/Playlist/DeleteTrackData.java +++ /dev/null @@ -1,6 +0,0 @@ -package net.Broken.RestApi.Data.Playlist; - -public class DeleteTrackData { - public int id; - public int playlistId; -} diff --git a/src/main/java/net/Broken/RestApi/Data/Playlist/MoveTrackData.java b/src/main/java/net/Broken/RestApi/Data/Playlist/MoveTrackData.java deleted file mode 100644 index 950affb..0000000 --- a/src/main/java/net/Broken/RestApi/Data/Playlist/MoveTrackData.java +++ /dev/null @@ -1,10 +0,0 @@ -package net.Broken.RestApi.Data.Playlist; - -public class MoveTrackData { - - public int playlistId; - - public int id; - - public int newPos; -} diff --git a/src/main/java/net/Broken/RestApi/Data/Playlist/PlaylistResponseData.java b/src/main/java/net/Broken/RestApi/Data/Playlist/PlaylistResponseData.java deleted file mode 100644 index 908f9eb..0000000 --- a/src/main/java/net/Broken/RestApi/Data/Playlist/PlaylistResponseData.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.Broken.RestApi.Data.Playlist; - -import com.fasterxml.jackson.annotation.JsonInclude; -import net.Broken.DB.Entity.PlaylistEntity; - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class PlaylistResponseData { - public String message; - public String error; - public PlaylistEntity playlist; - - public PlaylistResponseData(String message, PlaylistEntity playlist) { - this.message = message; - this.playlist = playlist; - } - - public PlaylistResponseData(String message, String error) { - this.message = message; - this.error = error; - } -} diff --git a/src/main/java/net/Broken/RestApi/Data/PlaylistData.java b/src/main/java/net/Broken/RestApi/Data/PlaylistData.java deleted file mode 100644 index c313678..0000000 --- a/src/main/java/net/Broken/RestApi/Data/PlaylistData.java +++ /dev/null @@ -1,19 +0,0 @@ -package net.Broken.RestApi.Data; - -import java.util.List; - -/** - * Data for JSON Parsing - */ -public class PlaylistData { - - private List list; - - public PlaylistData(List list) { - this.list = list; - } - - public List getList() { - return list; - } -} diff --git a/src/main/java/net/Broken/RestApi/Data/Settings/GetSettingsData.java b/src/main/java/net/Broken/RestApi/Data/Settings/GetSettingsData.java deleted file mode 100644 index f5f261b..0000000 --- a/src/main/java/net/Broken/RestApi/Data/Settings/GetSettingsData.java +++ /dev/null @@ -1,32 +0,0 @@ -package net.Broken.RestApi.Data.Settings; - -import com.fasterxml.jackson.annotation.JsonInclude; - -import java.util.List; - -@JsonInclude(JsonInclude.Include.NON_NULL) -public class GetSettingsData { - public String description; - public String name; - public String id; - public TYPE type; - public List values; - public String current; - - public GetSettingsData() { - } - - public GetSettingsData(String name, String description, String id, TYPE type, List values, String current) { - this.name = name; - this.description = description; - this.id = id; - this.type = type; - this.values = values; - this.current = current; - } - - public enum TYPE { - BOOL, LIST, STRING, SELECT_LIST - } -} - diff --git a/src/main/java/net/Broken/RestApi/Data/Settings/ListPostSetting.java b/src/main/java/net/Broken/RestApi/Data/Settings/ListPostSetting.java deleted file mode 100644 index 78f2bc7..0000000 --- a/src/main/java/net/Broken/RestApi/Data/Settings/ListPostSetting.java +++ /dev/null @@ -1,7 +0,0 @@ -package net.Broken.RestApi.Data.Settings; - -import java.util.List; - -public class ListPostSetting { - public List settings; -} diff --git a/src/main/java/net/Broken/RestApi/Data/Settings/PostSetSettings.java b/src/main/java/net/Broken/RestApi/Data/Settings/PostSetSettings.java deleted file mode 100644 index d8e04ae..0000000 --- a/src/main/java/net/Broken/RestApi/Data/Settings/PostSetSettings.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.Broken.RestApi.Data.Settings; - -import java.util.List; - -public class PostSetSettings { - public String id; - public String val; - public List vals; -} diff --git a/src/main/java/net/Broken/RestApi/Data/Settings/Value.java b/src/main/java/net/Broken/RestApi/Data/Settings/Value.java deleted file mode 100644 index ee98931..0000000 --- a/src/main/java/net/Broken/RestApi/Data/Settings/Value.java +++ /dev/null @@ -1,21 +0,0 @@ -package net.Broken.RestApi.Data.Settings; - -public class Value { - public String name; - public String id; - public boolean selected; - - public Value() { - } - - public Value(String name, String id) { - this.name = name; - this.id = id; - } - - public Value(String name, String id, boolean selected) { - this.name = name; - this.id = id; - this.selected = selected; - } -} diff --git a/src/main/java/net/Broken/RestApi/Data/UserAudioTrackData.java b/src/main/java/net/Broken/RestApi/Data/UserAudioTrackData.java deleted file mode 100644 index 37a7f18..0000000 --- a/src/main/java/net/Broken/RestApi/Data/UserAudioTrackData.java +++ /dev/null @@ -1,38 +0,0 @@ -package net.Broken.RestApi.Data; - -import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; -import net.Broken.Audio.UserAudioTrack; - -/** - * Data for JSON Parsing - */ -public class UserAudioTrackData { - private String user; - private AudioTrackInfo audioTrackInfo; - - public UserAudioTrackData(String user, AudioTrackInfo audioTrackInfo) { - this.user = user; - this.audioTrackInfo = audioTrackInfo; - } - - public UserAudioTrackData(UserAudioTrack userAudioTrack) { - this.audioTrackInfo = userAudioTrack.getAudioTrack().getInfo(); - this.user = userAudioTrack.getSubmittedUser().getName(); - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public AudioTrackInfo getAudioTrackInfo() { - return audioTrackInfo; - } - - public void setAudioTrackInfo(AudioTrackInfo audioTrackInfo) { - this.audioTrackInfo = audioTrackInfo; - } -} diff --git a/src/main/java/net/Broken/RestApi/Data/UserManager/CheckResposeData.java b/src/main/java/net/Broken/RestApi/Data/UserManager/CheckResposeData.java deleted file mode 100644 index 7f391e1..0000000 --- a/src/main/java/net/Broken/RestApi/Data/UserManager/CheckResposeData.java +++ /dev/null @@ -1,18 +0,0 @@ -package net.Broken.RestApi.Data.UserManager; - -/** - * Data for JSON Parsing - */ -public class CheckResposeData { - public boolean accepted; - public String name; - public String message; - public String id; - - public CheckResposeData(boolean accepted, String name, String message, String id) { - this.accepted = accepted; - this.name = name; - this.message = message; - this.id = id; - } -} diff --git a/src/main/java/net/Broken/RestApi/Data/UserManager/ConfirmData.java b/src/main/java/net/Broken/RestApi/Data/UserManager/ConfirmData.java deleted file mode 100644 index 1e7b537..0000000 --- a/src/main/java/net/Broken/RestApi/Data/UserManager/ConfirmData.java +++ /dev/null @@ -1,10 +0,0 @@ -package net.Broken.RestApi.Data.UserManager; - -/** - * Data for JSON Parsing - */ -public class ConfirmData { - public String id; - public String checkToken; - -} diff --git a/src/main/java/net/Broken/RestApi/Data/UserManager/GuildInfo.java b/src/main/java/net/Broken/RestApi/Data/UserManager/GuildInfo.java deleted file mode 100644 index 4b66271..0000000 --- a/src/main/java/net/Broken/RestApi/Data/UserManager/GuildInfo.java +++ /dev/null @@ -1,16 +0,0 @@ -package net.Broken.RestApi.Data.UserManager; - -public class GuildInfo { - public String name; - public String id; - public boolean isAdmin; - public String imageUrl; - - public GuildInfo(String name, String id, boolean isAdmin, String imageUrl) { - this.name = name; - this.id = id; - this.isAdmin = isAdmin; - this.imageUrl = imageUrl; - - } -} diff --git a/src/main/java/net/Broken/RestApi/Data/UserManager/UserConnectionData.java b/src/main/java/net/Broken/RestApi/Data/UserManager/UserConnectionData.java deleted file mode 100644 index 9ef2088..0000000 --- a/src/main/java/net/Broken/RestApi/Data/UserManager/UserConnectionData.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.Broken.RestApi.Data.UserManager; - -/** - * Data for JSON Parsing - */ -public class UserConnectionData { - public boolean accepted; - public String token; - public String message; - public String error; - public String name; - - public UserConnectionData(boolean accepted, String name, String token, String message) { - this.accepted = accepted; - this.token = token; - this.message = message; - this.name = name; - this.error = null; - } - - public UserConnectionData(boolean accepted, String message, String error) { - this.accepted = accepted; - this.token = null; - this.message = message; - this.error = error; - this.name = null; - } -} diff --git a/src/main/java/net/Broken/RestApi/Data/UserManager/UserInfoData.java b/src/main/java/net/Broken/RestApi/Data/UserManager/UserInfoData.java deleted file mode 100644 index 9a099a4..0000000 --- a/src/main/java/net/Broken/RestApi/Data/UserManager/UserInfoData.java +++ /dev/null @@ -1,9 +0,0 @@ -package net.Broken.RestApi.Data.UserManager; - -/** - * Data for JSON Parsing - */ -public class UserInfoData { - public String name; - public String password; -} diff --git a/src/main/java/net/Broken/RestApi/GeneralApiController.java b/src/main/java/net/Broken/RestApi/GeneralApiController.java deleted file mode 100644 index b4c4284..0000000 --- a/src/main/java/net/Broken/RestApi/GeneralApiController.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.Broken.RestApi; - -import net.Broken.DB.Repository.PlaylistRepository; -import net.Broken.DB.Repository.TrackRepository; -import net.Broken.DB.Repository.UserRepository; -import net.Broken.MainBot; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -@RestController -@RequestMapping("/api/") -public class GeneralApiController { - - private final - UserRepository userRepository; - - private final - PlaylistRepository playlistRepository; - - private final - TrackRepository trackRepository; - - @Autowired - public GeneralApiController(UserRepository userRepository, PlaylistRepository playlistRepository, TrackRepository trackRepository) { - this.userRepository = userRepository; - this.playlistRepository = playlistRepository; - this.trackRepository = trackRepository; - } - - @RequestMapping(value = "/isReady", method = RequestMethod.GET) - public ResponseEntity isReady() { - if (MainBot.ready) { - return new ResponseEntity<>(HttpStatus.OK); - } else { - return new ResponseEntity<>(HttpStatus.NOT_FOUND); - } - } -} diff --git a/src/main/java/net/Broken/SlashCommand.java b/src/main/java/net/Broken/SlashCommand.java index c9a07c1..ed24759 100644 --- a/src/main/java/net/Broken/SlashCommand.java +++ b/src/main/java/net/Broken/SlashCommand.java @@ -10,12 +10,6 @@ import java.util.List; * Interface that define command structure. */ public interface SlashCommand { - /** - * Main action of command - * - * @param args Command args. - * @param event Command MessageReceivedEvent - */ void action(SlashCommandEvent event); String getDescription(); diff --git a/src/main/java/net/Broken/SlashCommands/Cat.java b/src/main/java/net/Broken/SlashCommands/Cat.java index 85fb326..d171cee 100644 --- a/src/main/java/net/Broken/SlashCommands/Cat.java +++ b/src/main/java/net/Broken/SlashCommands/Cat.java @@ -16,15 +16,14 @@ import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; -import java.util.ArrayList; +import java.nio.charset.StandardCharsets; import java.util.List; /** * Command that return a random picture of cat. */ public class Cat implements SlashCommand { - private Logger logger = LogManager.getLogger(); - ; + private final Logger logger = LogManager.getLogger(); @Override public void action(SlashCommandEvent event) { @@ -32,7 +31,7 @@ public class Cat implements SlashCommand { URL urlC = new URL("http://aws.random.cat/meo"); URLConnection yc = urlC.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader( - yc.getInputStream(), "UTF-8")); + yc.getInputStream(), StandardCharsets.UTF_8)); String inputLine; StringBuilder a = new StringBuilder(); while ((inputLine = in.readLine()) != null) diff --git a/src/main/java/net/Broken/SlashCommands/Clear.java b/src/main/java/net/Broken/SlashCommands/Clear.java index c171a0d..bc2640d 100644 --- a/src/main/java/net/Broken/SlashCommands/Clear.java +++ b/src/main/java/net/Broken/SlashCommands/Clear.java @@ -2,7 +2,6 @@ package net.Broken.SlashCommands; import net.Broken.SlashCommand; import net.Broken.Tools.EmbedMessageUtils; -import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Message; diff --git a/src/main/java/net/Broken/SlashCommands/Music.java b/src/main/java/net/Broken/SlashCommands/Music.java index 301cbde..f4eb8d4 100644 --- a/src/main/java/net/Broken/SlashCommands/Music.java +++ b/src/main/java/net/Broken/SlashCommands/Music.java @@ -1,9 +1,9 @@ package net.Broken.SlashCommands; +import net.Broken.Audio.GuildAudioWrapper; import net.Broken.SlashCommand; import net.Broken.Tools.EmbedMessageUtils; -import net.Broken.Audio.GuildAudioWrapper; import net.dv8tion.jda.api.MessageBuilder; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.VoiceChannel; @@ -22,8 +22,7 @@ import java.util.List; * Command that return a random picture of cat. */ public class Music implements SlashCommand { - private Logger logger = LogManager.getLogger(); - ; + private final Logger logger = LogManager.getLogger(); @Override public void action(SlashCommandEvent event) { diff --git a/src/main/java/net/Broken/SlashCommands/Over18/Ass.java b/src/main/java/net/Broken/SlashCommands/Over18/Ass.java index a6079e7..af6bd77 100644 --- a/src/main/java/net/Broken/SlashCommands/Over18/Ass.java +++ b/src/main/java/net/Broken/SlashCommands/Over18/Ass.java @@ -3,16 +3,11 @@ package net.Broken.SlashCommands.Over18; import net.Broken.Tools.Command.Ignore; import net.Broken.Tools.Command.NoDev; import net.Broken.Tools.Command.NumberedSlashCommand; -import net.Broken.Tools.FindContentOnWebPage; import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.IOException; @NoDev @Ignore public class Ass extends NumberedSlashCommand { - Logger logger = LogManager.getLogger(); public Ass() { super(LogManager.getLogger(), "http://les400culs.com/", "-2/", "featured-img", "img"); diff --git a/src/main/java/net/Broken/SlashCommands/Over18/Madame.java b/src/main/java/net/Broken/SlashCommands/Over18/Madame.java index e94710e..b7854c7 100644 --- a/src/main/java/net/Broken/SlashCommands/Over18/Madame.java +++ b/src/main/java/net/Broken/SlashCommands/Over18/Madame.java @@ -1,6 +1,5 @@ package net.Broken.SlashCommands.Over18; -import net.Broken.Tools.Command.Ignore; import net.Broken.Tools.Command.NoDev; import net.Broken.Tools.Command.NumberedSlashCommand; import net.Broken.Tools.FindContentOnWebPage; @@ -11,7 +10,7 @@ import java.io.IOException; @NoDev public class Madame extends NumberedSlashCommand { - Logger logger = LogManager.getLogger(); + final Logger logger = LogManager.getLogger(); public Madame() { super(LogManager.getLogger(), "https://www.bonjourmadame.fr/page/", "/"); diff --git a/src/main/java/net/Broken/SlashCommands/Rank.java b/src/main/java/net/Broken/SlashCommands/Rank.java index 762edeb..603d900 100644 --- a/src/main/java/net/Broken/SlashCommands/Rank.java +++ b/src/main/java/net/Broken/SlashCommands/Rank.java @@ -1,7 +1,6 @@ package net.Broken.SlashCommands; import net.Broken.BotConfigLoader; -import net.Broken.MainBot; import net.Broken.SlashCommand; import net.Broken.SpringContext; import net.Broken.Tools.UserManager.Stats.UserStatsUtils; diff --git a/src/main/java/net/Broken/Tools/CacheTools.java b/src/main/java/net/Broken/Tools/CacheTools.java index 22b0673..ca786ca 100644 --- a/src/main/java/net/Broken/Tools/CacheTools.java +++ b/src/main/java/net/Broken/Tools/CacheTools.java @@ -10,7 +10,7 @@ import org.apache.logging.log4j.Logger; import java.util.List; public class CacheTools { - private static Logger logger = LogManager.getLogger(); + private static final Logger logger = LogManager.getLogger(); public static void loadAllGuildMembers() { List guilds = MainBot.jda.getGuilds(); diff --git a/src/main/java/net/Broken/Tools/Command/CommandParser.java b/src/main/java/net/Broken/Tools/Command/CommandParser.java index 5365af3..58c4e77 100644 --- a/src/main/java/net/Broken/Tools/Command/CommandParser.java +++ b/src/main/java/net/Broken/Tools/Command/CommandParser.java @@ -12,7 +12,7 @@ import java.util.Arrays; */ public class CommandParser { - private Logger logger = LogManager.getLogger(); + private final Logger logger = LogManager.getLogger(); /** * Parse raw received string. @@ -22,9 +22,8 @@ public class CommandParser { * @return Readable container that contain all useful data */ public CommandContainer parse(String brt, MessageReceivedEvent e) { - ArrayList split = new ArrayList(); - String brut = brt; - String sansTete = brut.replaceFirst("//", ""); + ArrayList split = new ArrayList<>(); + String sansTete = brt.replaceFirst("//", ""); String[] splitSansTete = sansTete.split(" "); for (String s : splitSansTete) { @@ -42,14 +41,14 @@ public class CommandParser { logger.info("Author: " + e.getAuthor().getName() + ", Command: " + commande + ", args: " + Arrays.toString(args)); - return new CommandContainer(brut, sansTete, splitSansTete, commande, args, e); + return new CommandContainer(brt, sansTete, splitSansTete, commande, args, e); } /** * Container */ - public class CommandContainer { + public static class CommandContainer { public final String brut; public final String sansTete; public final String[] splitSansTete; diff --git a/src/main/java/net/Broken/Tools/Command/NumberedSlashCommand.java b/src/main/java/net/Broken/Tools/Command/NumberedSlashCommand.java index 7e80e21..385a1d7 100644 --- a/src/main/java/net/Broken/Tools/Command/NumberedSlashCommand.java +++ b/src/main/java/net/Broken/Tools/Command/NumberedSlashCommand.java @@ -1,6 +1,5 @@ package net.Broken.Tools.Command; -import net.Broken.Commande; import net.Broken.SlashCommand; import net.Broken.Tools.EmbedMessageUtils; import net.Broken.Tools.FindContentOnWebPage; @@ -8,15 +7,12 @@ import net.Broken.Tools.LimitChecker; import net.Broken.Tools.TrueRandom; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; @@ -26,13 +22,13 @@ import java.util.concurrent.LinkedBlockingQueue; */ @Ignore public abstract class NumberedSlashCommand implements SlashCommand { - protected int minNumber = 1; + protected final int minNumber = 1; protected int maxNumber = -1; - protected String baseURL; - protected String divClass; - protected String htmlType; - protected String urlSuffix; - protected LinkedBlockingQueue randomQueue = new LinkedBlockingQueue<>(); + protected final String baseURL; + protected final String divClass; + protected final String htmlType; + protected final String urlSuffix; + protected final LinkedBlockingQueue randomQueue = new LinkedBlockingQueue<>(); private Logger logger = LogManager.getLogger(); /** diff --git a/src/main/java/net/Broken/Tools/Command/SlashCommandLoader.java b/src/main/java/net/Broken/Tools/Command/SlashCommandLoader.java index 35152ea..8c8c3f8 100644 --- a/src/main/java/net/Broken/Tools/Command/SlashCommandLoader.java +++ b/src/main/java/net/Broken/Tools/Command/SlashCommandLoader.java @@ -19,7 +19,7 @@ import java.util.Set; * Find and load bot's command */ public class SlashCommandLoader { - private static Logger logger = LogManager.getLogger(); + private static final Logger logger = LogManager.getLogger(); /** * Search all implemented Command interface class and add it to MainBot.commands HashMap diff --git a/src/main/java/net/Broken/Tools/DayListener/DayListener.java b/src/main/java/net/Broken/Tools/DayListener/DayListener.java index 761fcf8..6a001af 100644 --- a/src/main/java/net/Broken/Tools/DayListener/DayListener.java +++ b/src/main/java/net/Broken/Tools/DayListener/DayListener.java @@ -11,46 +11,26 @@ import java.util.GregorianCalendar; * Day change listener */ public class DayListener extends Thread { - private static DayListener INSTANCE = new DayListener(); - private Logger logger = LogManager.getLogger(); + private static final DayListener INSTANCE = new DayListener(); + private final Logger logger = LogManager.getLogger(); private Calendar calendar; private int previousDay; - /** - * List of listeners to need to be triggered - */ - private ArrayList listeners = new ArrayList<>(); + private final ArrayList listeners = new ArrayList<>(); - /** - * Default private constructor - */ private DayListener() { calendar = Calendar.getInstance(); previousDay = calendar.get(GregorianCalendar.DAY_OF_MONTH); } - - /** - * Singleton - * - * @return Unique DayListener instance. - */ public static DayListener getInstance() { return INSTANCE; } - /** - * Add Listener who will be triggered - * - * @param listener - */ public void addListener(NewDayListener listener) { listeners.add(listener); } - /** - * Trigger all listeners - */ public void trigger() { for (NewDayListener listener : listeners) { try { 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 1ab89b0..32ed7aa 100644 --- a/src/main/java/net/Broken/Tools/DayListener/Listeners/DailyMadame.java +++ b/src/main/java/net/Broken/Tools/DayListener/Listeners/DailyMadame.java @@ -25,8 +25,8 @@ import java.util.Optional; */ public class DailyMadame implements NewDayListener { - private GuildPreferenceRepository guildPreferenceRepository; - private Logger logger = LogManager.getLogger(); + private final GuildPreferenceRepository guildPreferenceRepository; + private final Logger logger = LogManager.getLogger(); public DailyMadame() { ApplicationContext context = SpringContext.getAppContext(); diff --git a/src/main/java/net/Broken/Tools/EmbedMessageUtils.java b/src/main/java/net/Broken/Tools/EmbedMessageUtils.java index 1aa1e6c..20919f7 100644 --- a/src/main/java/net/Broken/Tools/EmbedMessageUtils.java +++ b/src/main/java/net/Broken/Tools/EmbedMessageUtils.java @@ -1,10 +1,10 @@ package net.Broken.Tools; import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo; +import net.Broken.Audio.UserAudioTrack; import net.Broken.BotConfigLoader; import net.Broken.MainBot; import net.Broken.SpringContext; -import net.Broken.Audio.UserAudioTrack; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.MessageEmbed; @@ -20,11 +20,10 @@ import java.util.Map; public class EmbedMessageUtils { public static EmbedBuilder getError(String message) { - EmbedBuilder temp = new EmbedBuilder() + return new EmbedBuilder() .setTitle(":warning: Error!") .setColor(Color.red) .setDescription(message); - return temp; } diff --git a/src/main/java/net/Broken/Tools/FindContentOnWebPage.java b/src/main/java/net/Broken/Tools/FindContentOnWebPage.java index d30142d..849cb1d 100644 --- a/src/main/java/net/Broken/Tools/FindContentOnWebPage.java +++ b/src/main/java/net/Broken/Tools/FindContentOnWebPage.java @@ -5,6 +5,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; +import java.nio.charset.StandardCharsets; public class FindContentOnWebPage { /** @@ -43,7 +44,7 @@ public class FindContentOnWebPage { URLConnection yc = urlC.openConnection(); yc.setRequestProperty("User-Agent", "Googlebot/2.1 (+http://www.googlebot.com/bot.html)"); BufferedReader in = new BufferedReader(new InputStreamReader( - yc.getInputStream(), "UTF-8")); + yc.getInputStream(), StandardCharsets.UTF_8)); String inputLine; StringBuilder a = new StringBuilder(); while ((inputLine = in.readLine()) != null) diff --git a/src/main/java/net/Broken/Tools/LimitChecker.java b/src/main/java/net/Broken/Tools/LimitChecker.java index 4d7caa0..1471cc6 100644 --- a/src/main/java/net/Broken/Tools/LimitChecker.java +++ b/src/main/java/net/Broken/Tools/LimitChecker.java @@ -10,7 +10,7 @@ import java.net.URL; * Find max webPage for web site like baseURL.com/number-2/ */ public class LimitChecker { - static Logger logger = LogManager.getLogger(); + static final Logger logger = LogManager.getLogger(); /** diff --git a/src/main/java/net/Broken/Tools/ResourceLoader.java b/src/main/java/net/Broken/Tools/ResourceLoader.java deleted file mode 100644 index 7c646fd..0000000 --- a/src/main/java/net/Broken/Tools/ResourceLoader.java +++ /dev/null @@ -1,47 +0,0 @@ -package net.Broken.Tools; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.Scanner; - - -public class ResourceLoader { - - private Logger logger = LogManager.getLogger(); - - /** - * Get file contents as string for resource folder - * - * @param fileName Requested file - * @return File contents as string - * @throws FileNotFoundException - */ - public String getFile(String fileName) throws FileNotFoundException { - - StringBuilder result = new StringBuilder(""); - - //Get file from resources folder - ClassLoader classLoader = getClass().getClassLoader(); - InputStream file = classLoader.getResourceAsStream(fileName); - if (file == null) - throw new FileNotFoundException(); - - try (Scanner scanner = new Scanner(file, "UTF-8")) { - - while (scanner.hasNextLine()) { - String line = scanner.nextLine(); - result.append(line).append("\n"); - } - - scanner.close(); - - } - - return result.toString(); - - } - -} diff --git a/src/main/java/net/Broken/Tools/SettingsUtils.java b/src/main/java/net/Broken/Tools/SettingsUtils.java index 99f4887..374db05 100644 --- a/src/main/java/net/Broken/Tools/SettingsUtils.java +++ b/src/main/java/net/Broken/Tools/SettingsUtils.java @@ -1,24 +1,14 @@ package net.Broken.Tools; import net.Broken.DB.Entity.GuildPreferenceEntity; -import net.Broken.DB.Entity.UserEntity; import net.Broken.DB.Repository.GuildPreferenceRepository; import net.Broken.DB.Repository.UserRepository; -import net.Broken.MainBot; -import net.Broken.RestApi.Data.Settings.GetSettingsData; -import net.Broken.RestApi.Data.Settings.PostSetSettings; -import net.Broken.RestApi.Data.Settings.Value; import net.Broken.SpringContext; -import net.Broken.Tools.UserManager.UserUtils; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.entities.Guild; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; -import java.util.ArrayList; -import java.util.List; - public class SettingsUtils { private static SettingsUtils INSTANCE; @@ -37,78 +27,6 @@ public class SettingsUtils { return (INSTANCE == null) ? new SettingsUtils() : INSTANCE; } - /** - * Check if the user have the permission to set settings - * - * @param token User token - * @param guild Guild - * @return True if user have ADMINISTRATOR permission - */ - public boolean checkPermission(String token, String guild) { - if (token == null || guild == null) { - return false; - } else { - try { - UserEntity user = UserUtils.getInstance().getUserWithApiToken(userRepository, token); - User jdaUser = MainBot.jda.getUserById(user.getDiscordId()); - Guild jdaGuild = MainBot.jda.getGuildById(guild); - if (jdaGuild == null || jdaUser == null) - return false; - - Member guildUser = jdaGuild.getMember(jdaUser); - if (guildUser == null) - return false; - return guildUser.hasPermission(Permission.ADMINISTRATOR); - } catch (Exception e) { - logger.debug("Unknown Token or user :" + token); - return false; - } - } - } - - - private List getTextChannels(Guild guild) { - List channels = new ArrayList<>(); - for (TextChannel channel : guild.getTextChannels()) { - channels.add(new Value(channel.getName(), channel.getId())); - } - return channels; - } - - private List getRoles(Guild guild) { - List roles = new ArrayList<>(); - for (Role role : guild.getRoles()) { - roles.add(new Value(role.getName(), role.getId())); - } - return roles; - } - - - private List getVoiceChannels(Guild guild, List selected) { - List channels = new ArrayList<>(); - for (VoiceChannel voiceChannel : guild.getVoiceChannels()) { - if (selected == null) - channels.add(new Value(voiceChannel.getName(), voiceChannel.getId())); - else - channels.add(new Value(voiceChannel.getName(), voiceChannel.getId(), selected.contains(voiceChannel.getId()))); - } - return channels; - } - - private List checkVoiceChanel(Guild guild, List values) { - List list = new ArrayList<>(); - for (String value : values) { - if (guild.getVoiceChannelById(value) != null) { - list.add(value); - } else { - logger.error("Unknown voice channel id: " + value); - list = null; - break; - } - } - return list; - } - public GuildPreferenceEntity getPreference(Guild guild) { return guildPreferenceRepository.findByGuildId(guild.getId()).orElseGet(()->{ logger.info("Generate default pref for " + guild.getName()); diff --git a/src/main/java/net/Broken/Tools/TrueRandom.java b/src/main/java/net/Broken/Tools/TrueRandom.java index 96c30c5..91c41df 100644 --- a/src/main/java/net/Broken/Tools/TrueRandom.java +++ b/src/main/java/net/Broken/Tools/TrueRandom.java @@ -15,6 +15,7 @@ import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -54,7 +55,7 @@ public class TrueRandom { InputStream responseIS = response.getEntity().getContent(); - String content = IOUtils.toString(responseIS, "UTF-8"); + String content = IOUtils.toString(responseIS, StandardCharsets.UTF_8); logger.trace(content); JSONObject json = new JSONObject(content); diff --git a/src/main/java/net/Broken/Tools/UserManager/Stats/GuildStatsPack.java b/src/main/java/net/Broken/Tools/UserManager/Stats/GuildStatsPack.java index 8553e6d..e708234 100644 --- a/src/main/java/net/Broken/Tools/UserManager/Stats/GuildStatsPack.java +++ b/src/main/java/net/Broken/Tools/UserManager/Stats/GuildStatsPack.java @@ -2,16 +2,5 @@ package net.Broken.Tools.UserManager.Stats; import java.util.List; -public class GuildStatsPack { - - - public int rank; - public GuildStats selfStats; - public List ranking; - - public GuildStatsPack(int rank, GuildStats selfStats, List ranking) { - this.rank = rank; - this.selfStats = selfStats; - this.ranking = ranking; - } +public record GuildStatsPack(int rank, GuildStats selfStats, List ranking) { } diff --git a/src/main/java/net/Broken/Tools/UserManager/Stats/UserStatsUtils.java b/src/main/java/net/Broken/Tools/UserManager/Stats/UserStatsUtils.java index d05a5ac..43ad202 100644 --- a/src/main/java/net/Broken/Tools/UserManager/Stats/UserStatsUtils.java +++ b/src/main/java/net/Broken/Tools/UserManager/Stats/UserStatsUtils.java @@ -8,8 +8,6 @@ import net.Broken.MainBot; import net.Broken.SpringContext; import net.Broken.Tools.CacheTools; import net.Broken.Tools.EmbedMessageUtils; -import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException; -import net.Broken.Tools.UserManager.UserUtils; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; @@ -18,7 +16,6 @@ import net.dv8tion.jda.api.entities.User; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.context.ApplicationContext; -import org.springframework.security.crypto.password.PasswordEncoder; import java.awt.*; import java.util.ArrayList; @@ -27,23 +24,22 @@ import java.util.List; public class UserStatsUtils { - static double XP_PER_VOICE_TIME = 0.01; - static double XP_PER_MESSAGE = 4; - static double XP_PER_API_COUNT = 1; + static final double XP_PER_VOICE_TIME = 0.01; + static final double XP_PER_MESSAGE = 4; + static final double XP_PER_API_COUNT = 1; private static UserStatsUtils INSTANCE = new UserStatsUtils(); private final UserStatsRepository userStatsRepository; private final UserRepository userRepository; - private final PasswordEncoder passwordEncoder; private final Logger logger = LogManager.getLogger(); - public HashMap runningCounters = new HashMap<>(); + public final HashMap runningCounters = new HashMap<>(); private UserStatsUtils() { ApplicationContext context = SpringContext.getAppContext(); userStatsRepository = (UserStatsRepository) context.getBean("userStatsRepository"); userRepository = (UserRepository) context.getBean("userRepository"); - passwordEncoder = (PasswordEncoder) context.getBean("passwordEncoder"); + } @@ -99,11 +95,6 @@ public class UserStatsUtils { return userEntity.getUserStats(); } - public List getUserStats(String token) throws UnknownTokenException { - UserEntity user = UserUtils.getInstance().getUserWithApiToken(userRepository, token); - return getUserStats(user); - } - public List getUserStats(User user) { UserEntity userEntity = userRepository.findByDiscordId(user.getId()) .orElseGet(() -> genUserEntity(user)); @@ -227,7 +218,7 @@ public class UserStatsUtils { GuildStatsPack pack = getStatPack(userStats.getUser(), member.getGuild().getId()); StringBuilder stringBuilder = new StringBuilder(); int i = 1; - for (GuildStats stats : pack.ranking) { + for (GuildStats stats : pack.ranking()) { if (i >= 6) { break; } @@ -240,24 +231,15 @@ public class UserStatsUtils { embedBuilder.setColor(Color.yellow); embedBuilder.setTitle(":trophy: " + member.getGuild().getName() + " Ranking"); embedBuilder.addField("Top 5:", stringBuilder.toString(), false); - String rank; - switch (pack.selfStats.rank) { - case 1: - rank = "1st"; - break; - case 2: - rank = "2nd"; - break; - case 3: - rank = "3rd"; - break; - default: - rank = pack.selfStats.rank + "th"; - break; - } + String rank = switch (pack.selfStats().rank) { + case 1 -> "1st"; + case 2 -> "2nd"; + case 3 -> "3rd"; + default -> pack.selfStats().rank + "th"; + }; - embedBuilder.addField("Your stats:", rank + " with " + pack.selfStats.total + " points", false); + embedBuilder.addField("Your stats:", rank + " with " + pack.selfStats().total + " points", false); return EmbedMessageUtils.buildStandar(embedBuilder); } diff --git a/src/main/java/net/Broken/Tools/UserManager/UserUtils.java b/src/main/java/net/Broken/Tools/UserManager/UserUtils.java index e7f39c9..5be5c3f 100644 --- a/src/main/java/net/Broken/Tools/UserManager/UserUtils.java +++ b/src/main/java/net/Broken/Tools/UserManager/UserUtils.java @@ -1,15 +1,12 @@ package net.Broken.Tools.UserManager; -import net.Broken.DB.Entity.UserEntity; -import net.Broken.DB.Repository.UserRepository; -import net.Broken.Tools.UserManager.Exceptions.*; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class UserUtils { - private static UserUtils INSTANCE = new UserUtils(); - private Logger logger = LogManager.getLogger(); + private static final UserUtils INSTANCE = new UserUtils(); + private final Logger logger = LogManager.getLogger(); /** * Private default constructor @@ -26,21 +23,4 @@ public class UserUtils { return INSTANCE; } - /** - * return token's UserEntity - * - * @param userRepository User DB interface - * @param token Received token - * @return User Entity - * @throws UnknownTokenException Can't find token on User DB - */ - public UserEntity getUserWithApiToken(UserRepository userRepository, String token) throws UnknownTokenException { -// List users = userRepository.findByApiToken(token); -// if (users.size() > 0) { -// return users.get(0); -// } else -// throw new UnknownTokenException(); - return null; - - } } diff --git a/src/main/resources/MessagesTemplates/RegisterMessage.md b/src/main/resources/MessagesTemplates/RegisterMessage.md deleted file mode 100644 index b7712ef..0000000 --- a/src/main/resources/MessagesTemplates/RegisterMessage.md +++ /dev/null @@ -1,4 +0,0 @@ -An attempt to associate your discord name was requested. - -Here is the verification code: -**%code** diff --git a/src/main/resources/db/changelog/db.changelog-master.yml b/src/main/resources/db/changelog/db.changelog-master.yml index 7258d35..402ac4a 100644 --- a/src/main/resources/db/changelog/db.changelog-master.yml +++ b/src/main/resources/db/changelog/db.changelog-master.yml @@ -733,3 +733,57 @@ databaseChangeLog: columnName: anti_spam tableName: guild_preference_entity +# 23/06/2022 Sync +- changeSet: + id: 1655987923540-1 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: avatar + tableName: user_entity +- changeSet: + id: 1655987923540-2 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: discriminator + tableName: user_entity +- changeSet: + id: 1655987923540-3 + author: seb65 (generated) + changes: + - dropDefaultValue: + columnDataType: varchar(255) + columnName: username + tableName: user_entity + +# 23/06/2022 Drop playlist and tracks +- changeSet: + id: 1655988013822-1 + author: seb65 (generated) + changes: + - dropForeignKeyConstraint: + baseTableName: playlist_entity + constraintName: FKi0pu9fhjbhs223glek7baeuwm +- changeSet: + id: 1655988013822-2 + author: seb65 (generated) + changes: + - dropForeignKeyConstraint: + baseTableName: track_entity + constraintName: FKjrr0flblumxnll3re0apujvr +- changeSet: + id: 1655988013822-3 + author: seb65 (generated) + changes: + - dropTable: + tableName: playlist_entity +- changeSet: + id: 1655988013822-4 + author: seb65 (generated) + changes: + - dropTable: + tableName: track_entity +