From 97dd68fbbfd28c6c0f42ac06f4d70606990667b4 Mon Sep 17 00:00:00 2001 From: Brandon Date: Sat, 14 Apr 2018 15:20:23 -0400 Subject: Add sound preemption + change structure --- src/main/java/soundchan/BotListener.java | 250 ------------------- .../java/soundchan/BotListener/BotListener.java | 265 +++++++++++++++++++++ .../soundchan/BotListener/BotListenerHelpers.java | 20 ++ src/main/java/soundchan/BotListener/Commands.java | 14 ++ src/main/java/soundchan/BotListenerHelpers.java | 20 -- src/main/java/soundchan/Commands.java | 14 -- src/main/java/soundchan/LocalAudioManager.java | 3 +- src/main/java/soundchan/Main.java | 1 + src/main/java/soundchan/TrackScheduler.java | 20 +- 9 files changed, 320 insertions(+), 287 deletions(-) delete mode 100644 src/main/java/soundchan/BotListener.java create mode 100644 src/main/java/soundchan/BotListener/BotListener.java create mode 100644 src/main/java/soundchan/BotListener/BotListenerHelpers.java create mode 100644 src/main/java/soundchan/BotListener/Commands.java delete mode 100644 src/main/java/soundchan/BotListenerHelpers.java delete mode 100644 src/main/java/soundchan/Commands.java diff --git a/src/main/java/soundchan/BotListener.java b/src/main/java/soundchan/BotListener.java deleted file mode 100644 index 8e43ca9..0000000 --- a/src/main/java/soundchan/BotListener.java +++ /dev/null @@ -1,250 +0,0 @@ -package soundchan; - -import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler; -import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; -import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; -import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers; -import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; -import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; -import com.sedmelluq.discord.lavaplayer.track.AudioTrack; -import net.dv8tion.jda.client.events.call.voice.CallVoiceJoinEvent; -import net.dv8tion.jda.core.entities.Guild; -import net.dv8tion.jda.core.entities.MessageChannel; -import net.dv8tion.jda.core.entities.VoiceChannel; -import net.dv8tion.jda.core.events.guild.voice.GuildVoiceMoveEvent; -import net.dv8tion.jda.core.events.message.MessageReceivedEvent; -import net.dv8tion.jda.core.hooks.ListenerAdapter; -import net.dv8tion.jda.core.managers.AudioManager; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -public class BotListener extends ListenerAdapter{ - - private long monitoredGuildId = -1; - private Guild monitoredGuild; - private static String followingUser; - private static String localFilePath; - private static LocalAudioManager localManager; - private final AudioPlayerManager playerManager; - private final Map musicManagers; - - public BotListener(Properties properties) { - this.musicManagers = new HashMap<>(); - - this.playerManager = new DefaultAudioPlayerManager(); - AudioSourceManagers.registerRemoteSources(playerManager); - AudioSourceManagers.registerLocalSource(playerManager); - - localFilePath = properties.getProperty("localFilePath"); - followingUser = properties.getProperty("followingUser"); - localManager = new LocalAudioManager(localFilePath); - } - - private synchronized GuildMusicManager getGuildAudioPlayer() { - long guildId = monitoredGuildId; - GuildMusicManager musicManager = musicManagers.get(guildId); - - if (musicManager == null) { - musicManager = new GuildMusicManager(playerManager); - musicManagers.put(guildId, musicManager); - } - - monitoredGuild.getAudioManager().setSendingHandler(musicManager.getSendHandler()); - - return musicManager; - } - - @Override - public void onCallVoiceJoin(CallVoiceJoinEvent event){ - - } - - - @Override - public void onGuildVoiceMove(GuildVoiceMoveEvent event) { - if(event.getMember().getEffectiveName().compareTo(followingUser) == 0) { - AudioManager audioManager = monitoredGuild.getAudioManager(); - if(!audioManager.isAttemptingToConnect()) { - audioManager.openAudioConnection(event.getChannelJoined()); - } - } - super.onGuildVoiceMove(event); - } - - @Override - public void onMessageReceived(MessageReceivedEvent event) { - String[] command = event.getMessage().getContentRaw().split(" ", 2); - BotListenerHelpers helper = new BotListenerHelpers(); - - Guild guild = event.getGuild(); - MessageChannel channel = helper.GetReplyChannel(event); - - // If we haven't set the Monitored Guild yet, set the value - if(monitoredGuildId == -1 && guild != null){ - monitoredGuildId = Long.parseLong(guild.getId()); - monitoredGuild = guild; - } - - if(monitoredGuild != null){ - - // "!" Signifies that you're looking to play a sound effect - if(command[0].startsWith("!") && command[0].length() > 1){ - String filepath = localManager.GetFilePath(command[0].substring(1)); - if(!filepath.contentEquals("")) { - loadAndPlay(channel, filepath); - } - else{ - channel.sendMessage("File \"" + command[0].substring(1) + "\" not found!").queue(); - } - } - - if(command[0].startsWith("~")){ - switch (Commands.valueOf(command[0].substring(1))){ - case play: { - if(command.length == 2) - loadAndPlay(channel, command[1]); - break; - } - case skip: { - skipTrack(channel); - break; - } - case volume: { - if(command.length == 2) - changeVolume(channel, command[1]); - break; - } - case list: { - if(command.length == 2){ - if(command[1].equals("queue")){ - listTracks(channel); - } - else if(command[1].equals("sounds")){ - localManager.ListSounds(channel); - } - } - break; - } - case pause: { - pauseTrack(channel); - break; - } - case unpause: { - unpauseTrack(channel); - break; - } - case playingnow: { - break; - } - } - } - - } - - super.onMessageReceived(event); - } - - private void changeVolume(final MessageChannel channel, final String volume) { - GuildMusicManager musicManager = getGuildAudioPlayer(); - musicManager.player.setVolume(Integer.parseInt(volume)); - channel.sendMessage("Volume now set to " + volume + "%").queue(); - } - - private void listTracks(final MessageChannel channel) { - GuildMusicManager musicManager = getGuildAudioPlayer(); - List queueContents = musicManager.scheduler.getQueueContents(); - String printMessage = "Tracks in the queue:\n"; - for (String track: - queueContents) { - printMessage = printMessage + track + "\n"; - } - channel.sendMessage(printMessage).queue(); - } - - private void pauseTrack(final MessageChannel channel){ - GuildMusicManager musicManager = getGuildAudioPlayer(); - musicManager.player.setPaused(true); - channel.sendMessage("Playback Paused.").queue(); - } - - private void unpauseTrack(final MessageChannel channel){ - GuildMusicManager musicManager = getGuildAudioPlayer(); - musicManager.player.setPaused(false); - channel.sendMessage("Unpaused playback.").queue(); - } - - private void loadAndPlay(final MessageChannel channel, final String trackUrl) { - GuildMusicManager musicManager = getGuildAudioPlayer(); - - playerManager.loadItemOrdered(musicManager, trackUrl, new AudioLoadResultHandler() { - @Override - public void trackLoaded(AudioTrack track) { - int timeStart = trackUrl.lastIndexOf('='); - if(timeStart != -1){ - String timeString = trackUrl.substring(timeStart); - - //The format will be 1h2m53s, need to parse that into seconds and then call - //track.setPosition(long position) - - } - channel.sendMessage("Adding to queue " + track.getInfo().title).queue(); - - play(monitoredGuild, musicManager, track); - } - - @Override - public void playlistLoaded(AudioPlaylist playlist) { - AudioTrack firstTrack = playlist.getSelectedTrack(); - - if (firstTrack == null) { - firstTrack = playlist.getTracks().get(0); - } - - channel.sendMessage("Adding to queue " + firstTrack.getInfo().title + " (first track of playlist " + playlist.getName() + ")").queue(); - - play(monitoredGuild, musicManager, firstTrack); - } - - @Override - public void noMatches() { - channel.sendMessage("Nothing found by " + trackUrl).queue(); - } - - @Override - public void loadFailed(FriendlyException exception) { - channel.sendMessage("Could not play: " + exception.getMessage()).queue(); - } - }); - } - - private void play(Guild guild, GuildMusicManager musicManager, AudioTrack track) { - connectToFollowingVoiceChannel(guild.getAudioManager()); - - musicManager.scheduler.queue(track); - } - - private void skipTrack(MessageChannel channel) { - GuildMusicManager musicManager = getGuildAudioPlayer(); - musicManager.scheduler.nextTrack(); - - channel.sendMessage("Skipped to next track.").queue(); - } - - - private static void connectToFollowingVoiceChannel(AudioManager audioManager) { - if (!audioManager.isConnected() && !audioManager.isAttemptingToConnect()) { - for (VoiceChannel voiceChannel : audioManager.getGuild().getVoiceChannels()) { - for (int i = 0; i < voiceChannel.getMembers().size(); i++) { - if (voiceChannel.getMembers().get(i).getEffectiveName().compareTo(followingUser) == 0) { - audioManager.openAudioConnection(voiceChannel); - break; - } - } - } - } - } - -} diff --git a/src/main/java/soundchan/BotListener/BotListener.java b/src/main/java/soundchan/BotListener/BotListener.java new file mode 100644 index 0000000..f97db95 --- /dev/null +++ b/src/main/java/soundchan/BotListener/BotListener.java @@ -0,0 +1,265 @@ +package soundchan.BotListener; + +import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler; +import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager; +import com.sedmelluq.discord.lavaplayer.player.DefaultAudioPlayerManager; +import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers; +import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; +import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; +import com.sedmelluq.discord.lavaplayer.track.AudioTrack; +import net.dv8tion.jda.client.events.call.voice.CallVoiceJoinEvent; +import net.dv8tion.jda.core.entities.Guild; +import net.dv8tion.jda.core.entities.MessageChannel; +import net.dv8tion.jda.core.entities.VoiceChannel; +import net.dv8tion.jda.core.events.guild.voice.GuildVoiceMoveEvent; +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; +import net.dv8tion.jda.core.hooks.ListenerAdapter; +import net.dv8tion.jda.core.managers.AudioManager; +import soundchan.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +public class BotListener extends ListenerAdapter{ + + private long monitoredGuildId = -1; + private Guild monitoredGuild; + private static String followingUser; + private static String localFilePath; + private static LocalAudioManager localManager; + private final AudioPlayerManager playerManager; + private final Map musicManagers; + + public BotListener(Properties properties) { + this.musicManagers = new HashMap<>(); + + this.playerManager = new DefaultAudioPlayerManager(); + AudioSourceManagers.registerRemoteSources(playerManager); + AudioSourceManagers.registerLocalSource(playerManager); + + localFilePath = properties.getProperty("localFilePath"); + followingUser = properties.getProperty("followingUser"); + localManager = new LocalAudioManager(localFilePath); + } + + private synchronized GuildMusicManager getGuildAudioPlayer() { + long guildId = monitoredGuildId; + GuildMusicManager musicManager = musicManagers.get(guildId); + + if (musicManager == null) { + musicManager = new GuildMusicManager(playerManager); + musicManagers.put(guildId, musicManager); + } + + monitoredGuild.getAudioManager().setSendingHandler(musicManager.getSendHandler()); + + return musicManager; + } + + @Override + public void onCallVoiceJoin(CallVoiceJoinEvent event){ + + } + + + @Override + public void onGuildVoiceMove(GuildVoiceMoveEvent event) { + if(event.getMember().getEffectiveName().compareTo(followingUser) == 0) { + AudioManager audioManager = monitoredGuild.getAudioManager(); + if(!audioManager.isAttemptingToConnect()) { + audioManager.openAudioConnection(event.getChannelJoined()); + } + } + super.onGuildVoiceMove(event); + } + + @Override + public void onMessageReceived(MessageReceivedEvent event) { + String[] command = event.getMessage().getContentRaw().split(" ", 2); + BotListenerHelpers helper = new BotListenerHelpers(); + + Guild guild = event.getGuild(); + MessageChannel channel = helper.GetReplyChannel(event); + + // If we haven't set the Monitored Guild yet, set the value + if(monitoredGuildId == -1 && guild != null){ + monitoredGuildId = Long.parseLong(guild.getId()); + monitoredGuild = guild; + } + + if(monitoredGuild != null){ + + // "!" Signifies that you're looking to play a sound effect + if(command[0].startsWith("!") && command[0].length() > 1){ + String filepath = localManager.GetFilePath(command[0].substring(1)); + if(!filepath.contentEquals("")) { + loadAndPlay(channel, filepath, true); + } + else{ + channel.sendMessage("File \"" + command[0].substring(1) + "\" not found!").queue(); + } + } + + if(command[0].startsWith("~")){ + Commands enumCommand = Commands.valueOf(command[0].substring(1)); + if(enumCommand == Commands.play){ + // Play a song or video + if(command.length == 2) + loadAndPlay(channel, command[1], false); + + }else if(enumCommand == Commands.skip){ + // Skip a song or video in the queue + skipTrack(channel); + + }else if(enumCommand == Commands.volume){ + // Change volume + if(command.length == 2) + changeVolume(channel, command[1]); + + }else if(enumCommand == Commands.list){ + // List the songs/commands in the queue + if(command.length == 2){ + if(command[1].equals("queue")){ + listTracks(channel); + } + else if(command[1].equals("sounds")){ + localManager.ListSounds(channel); + } + } + + }else if(enumCommand == Commands.pause){ + // Pause the song/sound in the queue + pauseTrack(channel); + + }else if(enumCommand == Commands.unpause){ + // Unpause the song/sound in the queue + unpauseTrack(channel); + + }else if(enumCommand == Commands.playingnow){ + // Print the currently playing song + printCurrentlyPlaying(channel); + + } + + + } + + } + + super.onMessageReceived(event); + } + + private void changeVolume(final MessageChannel channel, final String volume) { + GuildMusicManager musicManager = getGuildAudioPlayer(); + musicManager.player.setVolume(Integer.parseInt(volume)); + channel.sendMessage("Volume now set to " + volume + "%").queue(); + } + + private void listTracks(final MessageChannel channel) { + GuildMusicManager musicManager = getGuildAudioPlayer(); + List queueContents = musicManager.scheduler.getQueueContents(); + String printMessage = "Tracks in the queue:\n"; + for (String track: + queueContents) { + printMessage = printMessage + track + "\n"; + } + channel.sendMessage(printMessage).queue(); + } + + private void pauseTrack(final MessageChannel channel){ + GuildMusicManager musicManager = getGuildAudioPlayer(); + musicManager.player.setPaused(true); + channel.sendMessage("Playback Paused.").queue(); + } + + private void unpauseTrack(final MessageChannel channel){ + GuildMusicManager musicManager = getGuildAudioPlayer(); + musicManager.player.setPaused(false); + channel.sendMessage("Unpaused playback.").queue(); + } + + private void printCurrentlyPlaying(final MessageChannel channel){ + GuildMusicManager musicManager = getGuildAudioPlayer(); + AudioTrack currentlyPlaying = musicManager.player.getPlayingTrack(); + channel.sendMessage("Currently Playing: " + currentlyPlaying.getInfo().title + " by " + currentlyPlaying.getInfo().author).queue(); + + } + + private void loadAndPlay(final MessageChannel channel, final String trackUrl, boolean preempt) { + GuildMusicManager musicManager = getGuildAudioPlayer(); + + playerManager.loadItemOrdered(musicManager, trackUrl, new AudioLoadResultHandler() { + @Override + public void trackLoaded(AudioTrack track) { + int timeStart = trackUrl.lastIndexOf('='); + if(timeStart != -1){ + String timeString = trackUrl.substring(timeStart); + + //The format will be 1h2m53s, need to parse that into seconds and then call + //track.setPosition(long position) + + } + if(!preempt) + channel.sendMessage("Adding to queue " + track.getInfo().title).queue(); + + play(monitoredGuild, musicManager, track, preempt); + } + + @Override + public void playlistLoaded(AudioPlaylist playlist) { + AudioTrack firstTrack = playlist.getSelectedTrack(); + + if (firstTrack == null) { + firstTrack = playlist.getTracks().get(0); + } + + channel.sendMessage("Adding to queue " + firstTrack.getInfo().title + " (first track of playlist " + playlist.getName() + ")").queue(); + + play(monitoredGuild, musicManager, firstTrack, false); + } + + @Override + public void noMatches() { + channel.sendMessage("Nothing found by " + trackUrl).queue(); + } + + @Override + public void loadFailed(FriendlyException exception) { + channel.sendMessage("Could not play: " + exception.getMessage()).queue(); + } + }); + } + + private void play(Guild guild, GuildMusicManager musicManager, AudioTrack track, boolean preempt) { + connectToFollowingVoiceChannel(guild.getAudioManager()); + + if(!preempt) + musicManager.scheduler.queue(track); + else + musicManager.scheduler.playNow(track); + } + + private void skipTrack(MessageChannel channel) { + GuildMusicManager musicManager = getGuildAudioPlayer(); + musicManager.scheduler.nextTrack(); + + channel.sendMessage("Skipped to next track.").queue(); + } + + + private static void connectToFollowingVoiceChannel(AudioManager audioManager) { + if (!audioManager.isConnected() && !audioManager.isAttemptingToConnect()) { + for (VoiceChannel voiceChannel : audioManager.getGuild().getVoiceChannels()) { + for (int i = 0; i < voiceChannel.getMembers().size(); i++) { + if (voiceChannel.getMembers().get(i).getEffectiveName().compareTo(followingUser) == 0) { + audioManager.openAudioConnection(voiceChannel); + break; + } + } + } + } + } + +} diff --git a/src/main/java/soundchan/BotListener/BotListenerHelpers.java b/src/main/java/soundchan/BotListener/BotListenerHelpers.java new file mode 100644 index 0000000..6689255 --- /dev/null +++ b/src/main/java/soundchan/BotListener/BotListenerHelpers.java @@ -0,0 +1,20 @@ +package soundchan.BotListener; + +import net.dv8tion.jda.core.entities.Guild; +import net.dv8tion.jda.core.entities.MessageChannel; +import net.dv8tion.jda.core.events.message.MessageReceivedEvent; + +public class BotListenerHelpers { + + /** + * Given a MessageReceivedEvent, determines the correct reply channel for SoundChan. + * @param event a MessageReceivedEvent from the JDA ListenerAdapter + * @return Either a PrivateChannel (if SoundChan was DM'd) or a TextChannel (If SoundChan was commanded in one) + */ + public MessageChannel GetReplyChannel(MessageReceivedEvent event){ + Guild guild = event.getGuild(); + return (guild == null) ? event.getPrivateChannel() : event.getTextChannel(); + } + + +} diff --git a/src/main/java/soundchan/BotListener/Commands.java b/src/main/java/soundchan/BotListener/Commands.java new file mode 100644 index 0000000..da1f45f --- /dev/null +++ b/src/main/java/soundchan/BotListener/Commands.java @@ -0,0 +1,14 @@ +package soundchan.BotListener; + +/** + * An enum representing the possible commands SoundChan might receive + */ +public enum Commands { + play, + volume, + pause, + unpause, + skip, + list, + playingnow +} diff --git a/src/main/java/soundchan/BotListenerHelpers.java b/src/main/java/soundchan/BotListenerHelpers.java deleted file mode 100644 index 600e4b0..0000000 --- a/src/main/java/soundchan/BotListenerHelpers.java +++ /dev/null @@ -1,20 +0,0 @@ -package soundchan; - -import net.dv8tion.jda.core.entities.Guild; -import net.dv8tion.jda.core.entities.MessageChannel; -import net.dv8tion.jda.core.events.message.MessageReceivedEvent; - -public class BotListenerHelpers { - - /** - * Given a MessageReceivedEvent, determines the correct reply channel for SoundChan. - * @param event a MessageReceivedEvent from the JDA ListenerAdapter - * @return Either a PrivateChannel (if SoundChan was DM'd) or a TextChannel (If SoundChan was commanded in one) - */ - public MessageChannel GetReplyChannel(MessageReceivedEvent event){ - Guild guild = event.getGuild(); - return (guild == null) ? event.getPrivateChannel() : event.getTextChannel(); - } - - -} diff --git a/src/main/java/soundchan/Commands.java b/src/main/java/soundchan/Commands.java deleted file mode 100644 index 3f96d37..0000000 --- a/src/main/java/soundchan/Commands.java +++ /dev/null @@ -1,14 +0,0 @@ -package soundchan; - -/** - * An enum representing the possible commands SoundChan might receive - */ -public enum Commands { - play, - volume, - pause, - unpause, - skip, - list, - playingnow -} diff --git a/src/main/java/soundchan/LocalAudioManager.java b/src/main/java/soundchan/LocalAudioManager.java index 314f6b9..9a4e299 100644 --- a/src/main/java/soundchan/LocalAudioManager.java +++ b/src/main/java/soundchan/LocalAudioManager.java @@ -31,11 +31,12 @@ public class LocalAudioManager { public void ListSounds(MessageChannel channel){ Set localSounds = filenameDict.keySet(); - String toPrint = "The following sounds you can play are:\n"; + String toPrint = "The following sounds you can play are:\n```"; for (String sound: localSounds) { toPrint = toPrint + " * " + sound + "\n"; } + toPrint = toPrint + "```"; channel.sendMessage(toPrint).queue(); } diff --git a/src/main/java/soundchan/Main.java b/src/main/java/soundchan/Main.java index 2e666f4..a7aa6a3 100644 --- a/src/main/java/soundchan/Main.java +++ b/src/main/java/soundchan/Main.java @@ -3,6 +3,7 @@ package soundchan; import net.dv8tion.jda.core.AccountType; import net.dv8tion.jda.core.JDA; import net.dv8tion.jda.core.JDABuilder; +import soundchan.BotListener.*; import java.io.FileInputStream; import java.io.IOException; diff --git a/src/main/java/soundchan/TrackScheduler.java b/src/main/java/soundchan/TrackScheduler.java index 21bb6d4..cc68335 100644 --- a/src/main/java/soundchan/TrackScheduler.java +++ b/src/main/java/soundchan/TrackScheduler.java @@ -10,7 +10,9 @@ import com.sedmelluq.discord.lavaplayer.track.DelegatedAudioTrack; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; /** @@ -18,14 +20,14 @@ import java.util.concurrent.LinkedBlockingQueue; */ public class TrackScheduler extends AudioEventAdapter { private final AudioPlayer player; - private final BlockingQueue queue; + private final BlockingDeque queue; /** * @param player The audio player this scheduler uses */ public TrackScheduler(AudioPlayer player) { this.player = player; - this.queue = new LinkedBlockingQueue<>(); + this.queue = new LinkedBlockingDeque<>(); } /** @@ -42,6 +44,20 @@ public class TrackScheduler extends AudioEventAdapter { } } + public void playNow(AudioTrack track) { + AudioTrack currenlyPlaying = player.getPlayingTrack(); + AudioTrack cloned = currenlyPlaying.makeClone(); + cloned.setPosition(currenlyPlaying.getPosition()); + + // Don't re-enqueue if its just a soundclip + if(!(currenlyPlaying.getInfo().uri.contains(".mp3") || currenlyPlaying.getInfo().uri.contains(".wav"))) + // Re-enqueue the track + queue.addFirst(cloned); + + player.startTrack(track, false); + + } + public List getQueueContents() { // Returns a list of the tracks in the queue Object[] queueInfo = queue.toArray(); -- cgit v1.2.3