Refactored how commands are handled

This commit is contained in:
Isaac Parenteau
2020-01-01 13:36:33 -06:00
parent c8260444bb
commit c85bea52a2
17 changed files with 661 additions and 370 deletions

View File

@@ -51,7 +51,7 @@ import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.locusworks.discord.eighttrack.database.entities.DiscordGuild;
import net.locusworks.discord.eighttrack.events.AbstractEventHandler;
import net.locusworks.discord.eighttrack.events.main.AbstractMainEventHandler;
import net.locusworks.discord.eighttrack.services.ConfigurationService;
import net.locusworks.discord.eighttrack.services.GuildMusicService;
import net.locusworks.discord.eighttrack.services.RepositoryService;
@@ -71,10 +71,10 @@ public class DiscordEventHandler extends ListenerAdapter {
@Autowired
private ReactionHandler reactionHandler;
private Map<String, AbstractEventHandler> events;
private Map<String, AbstractMainEventHandler> events;
@Autowired
private void setup(ConfigurationService cService, List<AbstractEventHandler> eventHandlers) throws IOException {
private void setup(ConfigurationService cService, List<AbstractMainEventHandler> eventHandlers) throws IOException {
this.musicDir = cService.getMusicDirectory();
if (!Files.exists(this.musicDir.toAbsolutePath())) {
Files.createDirectories(this.musicDir.toAbsolutePath());
@@ -82,7 +82,7 @@ public class DiscordEventHandler extends ListenerAdapter {
events = new TreeMap<>();
for(AbstractEventHandler handler : eventHandlers) {
for(AbstractMainEventHandler handler : eventHandlers) {
events.put(handler.getCommand(), handler);
}
}
@@ -165,19 +165,13 @@ public class DiscordEventHandler extends ListenerAdapter {
String command = commands.remove(0);
AbstractEventHandler aeh = events.get(command.toLowerCase());
AbstractMainEventHandler aeh = events.get(command.toLowerCase());
if (aeh != null) {
aeh.executeEvent(gmh, event, commands);
return;
}
switch(command) {
case "-list":
gmh.list(event);
return;
case "-playlist":
gmh.playlist(event, commands);
return;
case "+playlist":
gmh.adminPlaylist(event, commands);
return;
@@ -189,7 +183,7 @@ public class DiscordEventHandler extends ListenerAdapter {
if (!command.equalsIgnoreCase("-help")) return;
StringBuilder sb = new StringBuilder();
for (Entry<String, AbstractEventHandler> entry : events.entrySet()) {
for (Entry<String, AbstractMainEventHandler> entry : events.entrySet()) {
sb.append(String.format("%s | %s%n", entry.getKey(), entry.getValue().help()));
}

View File

@@ -30,13 +30,10 @@ package net.locusworks.discord.eighttrack.handlers;
import java.awt.Color;
import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
@@ -59,11 +56,8 @@ import net.dv8tion.jda.api.managers.AudioManager;
import net.dv8tion.jda.api.requests.ErrorResponse;
import net.locusworks.discord.eighttrack.audio.EightTrackAudioSendHandler;
import net.locusworks.discord.eighttrack.audio.TrackManager;
import net.locusworks.discord.eighttrack.database.entities.DiscordGuild;
import net.locusworks.discord.eighttrack.database.entities.GuildPlaylist;
import net.locusworks.discord.eighttrack.database.entities.GuildPlaylistSong;
import net.locusworks.discord.eighttrack.database.entities.GuildSong;
import net.locusworks.discord.eighttrack.database.entities.Song;
import net.locusworks.discord.eighttrack.listeners.ReactionListener;
import net.locusworks.discord.eighttrack.services.RepositoryService;
import net.locusworks.discord.eighttrack.utils.Reactions;
@@ -97,31 +91,6 @@ public class GuildMusicHandler {
this.trackManager = new TrackManager();
}
public void playlist(GuildMessageReceivedEvent event, List<String> commands) throws Exception {
if (commands == null || commands.isEmpty()) {
event.getChannel().sendMessage("Missing command for -playlist. Valid commands are: add, delete, list, play").queue();
return;
}
String command = commands.remove(0);
switch(command) {
case "add":
addPlayList(event, commands);
return;
case "delete":
deletePlayList(event, commands);
return;
case "list":
listPlayList(event, commands);
return;
case "play":
playPlayList(event, commands);
return;
}
}
public Long getCurrentVoiceChannelId() {
return voiceChannelId;
}
@@ -284,43 +253,6 @@ public class GuildMusicHandler {
}
}
public void list(GuildMessageReceivedEvent event) {
List<GuildSong> gsList = guildSongRepoService.getGuildSongRepo().findByGuild(guildId);
if (gsList == null || gsList.isEmpty()) {
event.getChannel().sendMessage("There is no music for this guild.").queue();
return;
}
int longestSong = 0;
int longestArtist = 0;
for(GuildSong gs : gsList) {
if (gs.getSong().getTitle().length() > longestSong) longestSong = gs.getSong().getTitle().length();
if (gs.getSong().getArtist().length() > longestArtist) longestArtist = gs.getSong().getArtist().length();
}
event.getChannel().sendMessage(String.format("**Currently available songs for %s**\n\n", event.getGuild().getName())).complete();
int count = 0;
String fmt = "%6s | %-" + longestSong +"s | %-" + longestArtist +"s | %s%n";
StringBuilder sb = new StringBuilder("```");
sb.append(String.format(fmt, "Track", "Title", "Artist", "id"));
sb.append(StringUtils.repeat("-", 27 + longestSong + longestArtist)).append("\n");
for(GuildSong gs : gsList) {
String msg = String.format(fmt, ++count, gs.getSong().getTitle(), gs.getSong().getArtist(), gs.getUuid());
if (sb.length() + msg.length() > 2000) {
sb.append("```");
event.getChannel().sendMessage(sb.toString()).complete();
sb = new StringBuilder("```");
} else {
sb.append(msg);
}
}
sb.append("```");
event.getChannel().sendMessage(sb.toString()).queue();
}
public void adminPlaylist(GuildMessageReceivedEvent event, List<String> commands) throws IOException {
if(!isAdmin(event)) return;
if (!checkCommands(event, commands, event.getMember().getAsMention() + ", valid commands are +playst list, play, delete")) return;
@@ -340,7 +272,7 @@ public class GuildMusicHandler {
if(!isAdmin(event)) return;
if (commands == null || commands.isEmpty()) {
event.getChannel().sendMessage(event.getMember().getAsMention() + ", Missing command for +delete. Valid commandis : +delete song uuids...").queue();
event.getChannel().sendMessage(event.getMember().getAsMention() + ", Missing command for +delete. Valid command is : +delete song uuids...").queue();
return;
}
@@ -353,96 +285,6 @@ public class GuildMusicHandler {
}
}
private void playPlayList(GuildMessageReceivedEvent event, List<String> commands) throws Exception {
if (commands == null || commands.isEmpty()) {
event.getChannel().sendMessage(event.getAuthor().getAsMention() + " please provide the name of the playlist to play").queue();
return;
}
String playlist = commands.remove(0);
currentPlaylist = guildSongRepoService.getGuildPlaylistRepo().findByGuildAndUserIdAndPlaylist(guildId, event.getMember().getIdLong(), playlist);
if (currentPlaylist == null) {
event.getChannel().sendMessage(event.getAuthor().getAsMention() + ", no playlist with the name of " + playlist + " exists").queue();
return;
}
trackManager.clearTracks();
for(GuildPlaylistSong gpls : guildSongRepoService.getGuildPlaylistSongRepo().findByGuildPlaylist(currentPlaylist)) {
Song s = gpls.getGuildSong().getSong();
trackManager.queueLast(s.getFilePath());
}
playing.set(false);
play(event);
playing.set(true);
}
private void listPlayList(GuildMessageReceivedEvent event, List<String> commands) {
if (commands == null || commands.isEmpty()) {
List<GuildPlaylist> userPlaylist = guildSongRepoService.getGuildPlaylistRepo().findByGuildAndUserIdFetchSongs(event.getGuild().getIdLong(), event.getMember().getIdLong());
if (userPlaylist.isEmpty()) {
event.getChannel().sendMessage(event.getMember().getAsMention() + " you have no defined playlists on this server").queue();
return;
}
int longestPlaylist = 10;
for(GuildPlaylist gpl : userPlaylist) {
if (gpl.getPlaylist().length() > longestPlaylist) longestPlaylist = gpl.getPlaylist().length();
}
String fmt = "%6s | %-" + longestPlaylist +"s | %s%n";
StringBuilder sb = new StringBuilder("```");
sb.append(String.format(fmt, "", "Playlist", "Song Count"));
sb.append(StringUtils.repeat("-", 24 + longestPlaylist)).append("\n");
int count = 0;
for(GuildPlaylist gpl : userPlaylist) {
sb.append(String.format(fmt, ++count, gpl.getPlaylist(), gpl.getGuildPlaylistSongList().size()));
}
sb.append("```");
event.getChannel().sendMessage("**" + "Currently available playlists for " + event.getMember().getAsMention() + "**").queue((succcess)->
event.getChannel().sendMessage(sb.toString()).queue());
return;
}
String playlist = commands.remove(0);
GuildPlaylist gpl = guildSongRepoService.getGuildPlaylistRepo().findByGuildUserPlaylistFetchSongs(event.getGuild().getIdLong(), event.getMember().getIdLong(), playlist);
if (gpl == null) {
event.getChannel().sendMessage(event.getMember().getAsMention() + " you have no defined playlists on this server by the name of " + playlist).queue();
return;
}
if (gpl.getGuildPlaylistSongList().isEmpty()) {
event.getChannel().sendMessage(event.getMember().getAsMention() + " you have no defined songs for playlist " + playlist).queue();
return;
}
int longestSong = 0;
int longestArtist = 0;
for(GuildPlaylistSong gpls : gpl.getGuildPlaylistSongList()) {
GuildSong gs = gpls.getGuildSong();
if (gs.getSong().getTitle().length() > longestSong) longestSong = gs.getSong().getTitle().length();
if (gs.getSong().getArtist().length() > longestArtist) longestArtist = gs.getSong().getArtist().length();
}
String fmt = "%6s | %-" + longestSong +"s | %-" + longestArtist +"s | %s%n";
int count = 0;
StringBuilder sb = new StringBuilder("```");
sb.append(String.format(fmt, "Track", "Title", "Artist", "id"));
sb.append(StringUtils.repeat("-", 27 + longestSong + longestArtist)).append("\n");
for(GuildPlaylistSong gpls : gpl.getGuildPlaylistSongList()) {
GuildSong gs = gpls.getGuildSong();
sb.append(String.format(fmt, ++count, gs.getSong().getTitle(), gs.getSong().getArtist(), gs.getUuid()));
}
sb.append("```");
event.getChannel().sendMessage("**" + "Current songs in playlists " + playlist + " for " + event.getMember().getAsMention() + "**").queue((succcess)->
event.getChannel().sendMessage(sb.toString()).queue());
}
private void deleteSong(GuildMessageReceivedEvent event, List<String> commands) {
if(!checkCommands(event, commands,
event.getAuthor().getAsMention() + ", you have to provide the list of uuids for songs to remove")) return;
@@ -545,14 +387,12 @@ public class GuildMusicHandler {
ReactionListener<String> handler = new ReactionListener<>(userId, msg.getId());
handler.setExpiresIn(TimeUnit.MINUTES, 1);
handler.registerReaction(Reactions.CHECK_MARK_BUTTON, (ret) -> deletePlayListConfirm(gpl, event.getMember().getAsMention(), msg));
//handler.registerReaction(Reactions.CHECK_MARK_BUTTON, (ret) -> deletePlayListConfirm(gpl, event.getMember().getAsMention(), msg));
handler.registerReaction(Reactions.CROSS_MARK_BUTTON, (ret) -> deleteMessage(msg));
reactionHandler.addReactionListener(guildId, msg, handler);
});
return;
}
private void deleteGuildSongsConfirm(List<GuildSong> songs, String user, Message msg) {
@@ -568,181 +408,6 @@ public class GuildMusicHandler {
}
}
private void deletePlayList(GuildMessageReceivedEvent event, List<String> commands) {
if(!checkCommands(event, commands,
event.getAuthor().getAsMention() + " you have to provide the playlist name and optionally a list of uuids for songs to remove")) return;
Long guildId = event.getGuild().getIdLong();
DiscordGuild guild = guildSongRepoService.getGuildRepo().findByGuildId(guildId);
if (guild == null) {
event.getChannel().sendMessage("Unable to find guild in local database. Please contact administrator").queue();
return;
}
String playlist = commands.remove(0);
long userId = event.getMember().getIdLong();
GuildPlaylist gpl = guildSongRepoService.getGuildPlaylistRepo().findByGuildAndUserIdAndPlaylist(guild, userId, playlist);
if (commands.isEmpty()) {
MessageEmbed embed = new EmbedBuilder()
.setColor(Color.RED)
.setTitle("Delete Playlist " + playlist)
.setDescription("Are you sure you want to delete the playlist " + playlist)
.setTimestamp(OffsetDateTime.now())
.setFooter(event.getGuild().getSelfMember().getEffectiveName(), event.getGuild().getSelfMember().getUser().getAvatarUrl())
.build();
event.getChannel().sendMessage(embed).queue((msg) -> {
ReactionListener<String> handler = new ReactionListener<>(userId, msg.getId());
handler.setExpiresIn(TimeUnit.MINUTES, 1);
handler.registerReaction(Reactions.CHECK_MARK_BUTTON, (ret) -> deletePlayListConfirm(gpl, event.getMember().getAsMention(), msg));
handler.registerReaction(Reactions.CROSS_MARK_BUTTON, (ret) -> deleteMessage(msg));
reactionHandler.addReactionListener(guildId, msg, handler);
});
return;
}
List<GuildPlaylistSong> songs = guildSongRepoService.getGuildPlaylistSongRepo().findByGuildPlaylistAndSongIds(gpl, commands);
StringBuilder sb = new StringBuilder("Are you sure you want to delete the following songs from playlist " + playlist + "?\n");
for (GuildPlaylistSong gpls : songs) {
GuildSong gs = gpls.getGuildSong();
sb.append(String.format("**%s** by __%s__%n", gs.getSong().getTitle(), gs.getSong().getArtist()));
}
MessageEmbed embed = new EmbedBuilder()
.setColor(Color.RED)
.setTitle("Delete Playlist Songs")
.setDescription(sb.toString())
.setTimestamp(OffsetDateTime.now())
.setFooter(event.getGuild().getSelfMember().getEffectiveName(), event.getGuild().getSelfMember().getUser().getAvatarUrl())
.build();
event.getChannel().sendMessage(embed).queue((msg) -> {
ReactionListener<String> handler = new ReactionListener<>(userId, msg.getId());
handler.setExpiresIn(TimeUnit.MINUTES, 1);
handler.registerReaction(Reactions.CHECK_MARK_BUTTON, (ret) -> deletePlayListSongConfirm(songs, event.getMember().getAsMention(), msg));
handler.registerReaction(Reactions.CROSS_MARK_BUTTON, (ret) -> deleteMessage(msg));
reactionHandler.addReactionListener(guildId, msg, handler);
});
}
private void deletePlayListSongConfirm(List<GuildPlaylistSong> songs, String user, Message msg) {
try {
guildSongRepoService.getGuildPlaylistSongRepo().deleteAll(songs);
msg.getChannel().sendMessage(user + ", songs removed successfully fom playlist").complete();
} catch (Exception ex) {
msg.getChannel().sendMessage("Sorry " + user + " I was unable to remove songs from the playlist. Reason: " + ex.getMessage()).complete();
logger.error("Unable to delete songs from playlist : " + ex.getMessage());
logger.error(ex);
} finally {
deleteMessage(msg);
}
}
private void deletePlayListConfirm(GuildPlaylist gpl, String user, Message msg) {
String playlist = gpl.getPlaylist();
try {
guildSongRepoService.getGuildPlaylistRepo().delete(gpl);
msg.getChannel().sendMessage(user + " " + playlist + " deleted successfully").complete();
} catch (Exception ex) {
msg.getChannel().sendMessage("Sorry " + user + " I was unable to remove playlist " + playlist + ". Reason: " + ex.getMessage()).complete();
logger.error("Unable to delete playlist " + playlist + ": " + ex.getMessage());
logger.error(ex);
} finally {
deleteMessage(msg);
}
}
private void addPlayList(GuildMessageReceivedEvent event, List<String> commands) {
if(!checkCommands(event, commands,
event.getAuthor().getAsMention() + " you have to provide the playlist to create a new playlist (no spaces in name) and optionally a list of uuids for songs to add")) return;
Long guildId = event.getGuild().getIdLong();
DiscordGuild guild = guildSongRepoService.getGuildRepo().findByGuildId(guildId);
if (guild == null) {
event.getChannel().sendMessage("Unable to find guild in local database. Please contact administrator").queue();
return;
}
String playlist = commands.remove(0);
long userId = event.getMember().getIdLong();
GuildPlaylist gpl = guildSongRepoService.getGuildPlaylistRepo().findByGuildAndUserIdAndPlaylist(guild, userId, playlist);
boolean newList = false;
if (gpl != null && commands.isEmpty()) {
event.getChannel().sendMessage(event.getAuthor().getAsMention() + " a playlist with the name " + playlist + " already exist for you.").queue();
return;
} else if (gpl == null) {
newList = true;
gpl = new GuildPlaylist();
gpl.setDateAdded(new Date());
gpl.setGuild(guild);
gpl.setPlaylist(playlist);
gpl.setUserId(userId);
guildSongRepoService.getGuildPlaylistRepo().save(gpl);
}
if (commands.isEmpty() && newList) {
event.getChannel().sendMessage(event.getAuthor().getAsMention() + " playlist " + playlist + " successfully created.").queue();
return;
}
Set<String> songIds = guildSongRepoService.getGuildPlaylistSongRepo()
.findByGuildPlaylistAndSongIds(gpl, commands).stream()
.map(g -> g.getGuildSong().getUuid())
.collect(Collectors.toSet());
List<GuildPlaylistSong> gplsList = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for(String id : commands.stream().collect(Collectors.toSet())) {
GuildSong gs = guildSongRepoService.getGuildSongRepo().findByUuid(id);
if (songIds.contains(id)) {
sb.append(String.format("**%s** by __%s__ already exists in this playlist.%n", gs.getSong().getTitle(), gs.getSong().getArtist()));
continue;
}
if (gs == null) {
sb.append("Song with id `" + id + "` not found. Please check id\n");
continue;
}
GuildPlaylistSong gpls = new GuildPlaylistSong();
gpls.setDateAdded(new Date());
gpls.setGuildPlaylist(gpl);
gpls.setGuildSong(gs);
gplsList.add(gpls);
sb.append(String.format("**%s** by __%s__ added to playlist.%n", gs.getSong().getTitle(), gs.getSong().getArtist()));
}
if (!gplsList.isEmpty()) {
guildSongRepoService.getGuildPlaylistSongRepo().saveAll(gplsList);
}
MessageEmbed embed = new EmbedBuilder()
.setTitle("Results for adding playlist " + playlist)
.setAuthor(event.getMember().getEffectiveName(), null, event.getAuthor().getAvatarUrl())
.setColor(Color.GREEN)
.setDescription(sb.toString())
.setFooter("", event.getGuild().getSelfMember().getUser().getAvatarUrl())
.setTimestamp(OffsetDateTime.now())
.build();
event.getChannel().sendMessage(embed).queue();
}
private void loadRandomSong() throws Exception {
List<GuildSong> gsList = null;
@@ -801,4 +466,12 @@ public class GuildMusicHandler {
}
}
public void setCurrentPlaylist(GuildPlaylist currentPlaylist) {
this.currentPlaylist = currentPlaylist;
}
public TrackManager getTrackManager() {
return this.trackManager;
}
}