🔨 Audio refracto

This commit is contained in:
SebClem 2022-06-23 13:30:54 +02:00
parent a295002fee
commit 2339e7cde6
Signed by: sebclem
GPG Key ID: 5A4308F6A359EA50
35 changed files with 126 additions and 1129 deletions

View File

@ -2,7 +2,7 @@ package net.Broken.Api.Data.Music;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import net.Broken.Api.Data.UserInfo;
import net.Broken.audio.UserAudioTrack;
import net.Broken.Audio.UserAudioTrack;
public record TrackInfo(UserInfo submitter, AudioTrackInfo detail) {
public TrackInfo(UserInfo submitter, AudioTrackInfo detail) {

View File

@ -4,12 +4,11 @@ import net.Broken.Api.Data.Music.Connect;
import net.Broken.Api.Security.Data.JwtPrincipal;
import net.Broken.MainBot;
import net.Broken.Tools.CacheTools;
import net.Broken.audio.AudioM;
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;
import net.dv8tion.jda.api.entities.VoiceChannel;
import okhttp3.Cache;
import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
import org.springframework.security.core.Authentication;
@ -62,8 +61,8 @@ public class CustomMethodSecurityExpressionRoot
public boolean canInteractWithVoiceChannel(String guildId) {
JwtPrincipal jwtPrincipal = (JwtPrincipal) authentication.getPrincipal();
Guild guild = MainBot.jda.getGuildById(guildId);
AudioM audioM = AudioM.getInstance(guild);
VoiceChannel channel = audioM.getPlayedChanel();
GuildAudioWrapper guildAudioWrapper = GuildAudioWrapper.getInstance(guild);
VoiceChannel channel = guild.getAudioManager().getConnectedChannel();
if (channel == null) {
return false;

View File

@ -6,8 +6,8 @@ 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.AudioM;
import net.Broken.audio.UserAudioTrack;
import net.Broken.Audio.GuildAudioWrapper;
import net.Broken.Audio.UserAudioTrack;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.audio.hooks.ConnectionStatus;
import net.dv8tion.jda.api.entities.Guild;
@ -38,7 +38,7 @@ public class AudioService {
boolean canView = member.hasPermission(channel, Permission.VIEW_CHANNEL)
|| (member.getVoiceState() != null
&& member.getVoiceState().getChannel() == channel);
AudioM audioM = AudioM.getInstance(guild);
GuildAudioWrapper guildAudioWrapper = GuildAudioWrapper.getInstance(guild);
if (canView) {
// The user can interact with the audio if:
@ -51,12 +51,12 @@ public class AudioService {
&& member.hasPermission(channel, Permission.VOICE_SPEAK);
boolean stopped = audioM.getGuildAudioPlayer().player.getPlayingTrack() == null;
boolean stopped = guildAudioWrapper.getGuidAudioManager().player.getPlayingTrack() == null;
PlayBackInfo playBackInfo;
if (!stopped) {
boolean paused = audioM.getGuildAudioPlayer().player.isPaused();
long position = audioM.getGuildAudioPlayer().player.getPlayingTrack().getPosition();
UserAudioTrack userAudioTrack = audioM.getGuildAudioPlayer().scheduler.getCurrentPlayingTrack();
boolean paused = guildAudioWrapper.getGuidAudioManager().player.isPaused();
long position = guildAudioWrapper.getGuidAudioManager().player.getPlayingTrack().getPosition();
UserAudioTrack userAudioTrack = guildAudioWrapper.getGuidAudioManager().scheduler.getCurrentPlayingTrack();
playBackInfo = new PlayBackInfo(paused, false, position, new TrackInfo(userAudioTrack));
@ -75,20 +75,18 @@ public class AudioService {
public ResponseEntity<Status> connect(String guildId, Connect body, String userId) {
Guild guild = MainBot.jda.getGuildById(guildId);
AudioM audioM = AudioM.getInstance(guild);
GuildAudioWrapper guildAudioWrapper = GuildAudioWrapper.getInstance(guild);
VoiceChannel voiceChannel = guild.getVoiceChannelById(body.channelId());
audioM.getGuildAudioPlayer();
guildAudioWrapper.getGuidAudioManager();
guild.getAudioManager().openAudioConnection(voiceChannel);
audioM.setPlayedChanel(voiceChannel);
Status status = getGuildAudioStatus(guildId, userId);
return new ResponseEntity<>(status, HttpStatus.OK);
}
public ResponseEntity<Status> disconnect(String guildId, String userId) {
Guild guild = MainBot.jda.getGuildById(guildId);
AudioM audioM = AudioM.getInstance(guild);
audioM.disconnect();
GuildAudioWrapper guildAudioWrapper = GuildAudioWrapper.getInstance(guild);
guildAudioWrapper.disconnect();
Status status = getGuildAudioStatus(guildId, userId);
return new ResponseEntity<>(status, HttpStatus.OK);
}

View File

@ -1,4 +1,4 @@
package net.Broken.audio;
package net.Broken.Audio;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.playback.MutableAudioFrame;

View File

@ -1,4 +1,4 @@
package net.Broken.audio;
package net.Broken.Audio;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
@ -7,7 +7,7 @@ import net.dv8tion.jda.api.entities.Guild;
/**
* Holder for both the player and a track scheduler for one guild.
*/
public class GuildMusicManager {
public class GuildAudioManager {
/**
* Audio player for the guild.
*/
@ -24,7 +24,7 @@ public class GuildMusicManager {
*
* @param manager Audio player manager to use for creating the player.
*/
public GuildMusicManager(AudioPlayerManager manager, Guild guild) {
public GuildAudioManager(AudioPlayerManager manager, Guild guild) {
player = manager.createPlayer();
scheduler = new TrackScheduler(player, guild);
player.addListener(scheduler);

View File

@ -1,4 +1,4 @@
package net.Broken.audio;
package net.Broken.Audio;
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
@ -27,49 +27,37 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class AudioM {
public class GuildAudioWrapper {
private static final HashMap<Guild, GuildAudioWrapper> INSTANCES = new HashMap<>();
private final GuildAudioManager guildAudioManager;
private final AudioPlayerManager audioPlayerManager;
private static HashMap<Guild, AudioM> INSTANCES = new HashMap<>();
/**
* Music manager for this guild
*/
private GuildMusicManager musicManager;
/**
* Audio player manager for this guild
*/
private AudioPlayerManager playerManager;
/**
* Current voice chanel (null if not connected)
*/
private VoiceChannel playedChanel;
/**
* Time out for list message
*/
private int listTimeOut = 30;
/**
* Extrem limit for playlist
*/
private int listExtremLimit = 300;
/**
* Current guild
*/
private Guild guild;
private Logger logger = LogManager.getLogger();
private final int listExtremLimit = 300;
private final Guild guild;
private final Logger logger = LogManager.getLogger();
private Message lastMessageWithButton;
private AudioM(Guild guild) {
this.playerManager = new DefaultAudioPlayerManager();
AudioSourceManagers.registerRemoteSources(playerManager);
AudioSourceManagers.registerLocalSource(playerManager);
private GuildAudioWrapper(Guild guild) {
this.audioPlayerManager = new DefaultAudioPlayerManager();
AudioSourceManagers.registerRemoteSources(audioPlayerManager);
AudioSourceManagers.registerLocalSource(audioPlayerManager);
this.guildAudioManager = new GuildAudioManager(audioPlayerManager, guild);
guild.getAudioManager().setSendingHandler(guildAudioManager.getSendHandler());
this.guild = guild;
}
public static AudioM getInstance(Guild guild) {
public static GuildAudioWrapper getInstance(Guild guild) {
if (!INSTANCES.containsKey(guild)) {
INSTANCES.put(guild, new AudioM(guild));
INSTANCES.put(guild, new GuildAudioWrapper(guild));
}
return INSTANCES.get(guild);
}
@ -83,10 +71,9 @@ public class AudioM {
* @param onHead True for adding audio track on top of playlist
*/
public void loadAndPlay(SlashCommandEvent event, VoiceChannel voiceChannel, final String trackUrl, int playlistLimit, boolean onHead) {
GuildMusicManager musicManager = getGuildAudioPlayer();
playedChanel = voiceChannel;
GuildAudioManager guidAudioManager = getGuidAudioManager();
playerManager.loadItemOrdered(musicManager, trackUrl, new AudioLoadResultHandler() {
audioPlayerManager.loadItemOrdered(guidAudioManager, trackUrl, new AudioLoadResultHandler() {
@Override
public void trackLoaded(AudioTrack track) {
logger.info("[" + guild + "] Single Track detected!");
@ -96,7 +83,7 @@ public class AudioM {
.build();
clearLastButton();
lastMessageWithButton = event.getHook().sendMessage(message).addActionRow(getActionButton()).complete();
play(guild, voiceChannel, musicManager, uat, onHead);
play(guild, voiceChannel, guidAudioManager, uat, onHead);
}
@Override
@ -130,12 +117,13 @@ public class AudioM {
}
public void loadAndPlayAuto(String trackUrl) {
playerManager.loadItemOrdered(musicManager, trackUrl, new AudioLoadResultHandler() {
VoiceChannel playedChanel = guild.getAudioManager().getConnectedChannel();
audioPlayerManager.loadItemOrdered(guildAudioManager, trackUrl, new AudioLoadResultHandler() {
@Override
public void trackLoaded(AudioTrack track) {
logger.info("[" + guild + "] Auto add " + track.getInfo().title + " to playlist.");
UserAudioTrack userAudioTrack = new UserAudioTrack(MainBot.jda.getSelfUser(), track);
play(guild, playedChanel, musicManager, userAudioTrack, true);
play(guild, playedChanel, guildAudioManager, userAudioTrack, true);
}
@Override
@ -143,7 +131,7 @@ public class AudioM {
AudioTrack track = playlist.getTracks().get(0);
logger.info("[" + guild + "] Auto add " + track.getInfo().title + " to playlist.");
UserAudioTrack userAudioTrack = new UserAudioTrack(MainBot.jda.getSelfUser(), track);
play(guild, playedChanel, musicManager, userAudioTrack, true);
play(guild, playedChanel, guildAudioManager, userAudioTrack, true);
}
@Override
@ -169,30 +157,24 @@ public class AudioM {
* @param onHead True for adding audio track on top of playlist
*/
public void playListLoader(AudioPlaylist playlist, int playlistLimit, User user, boolean onHead) {
int i = 0;
VoiceChannel playedChanel = guild.getAudioManager().getConnectedChannel();
List<AudioTrack> tracks = playlist.getTracks();
if (onHead)
Collections.reverse(tracks);
int i = 0;
for (AudioTrack track : playlist.getTracks()) {
UserAudioTrack uat = new UserAudioTrack(user, track);
play(guild, playedChanel, musicManager, uat, onHead);
i++;
if ((i >= playlistLimit && i != -1) || i > listExtremLimit)
play(guild, playedChanel, guildAudioManager, uat, onHead);
if ((playlistLimit != -1 && i >= playlistLimit) || i > listExtremLimit)
break;
i++;
}
}
public GuildMusicManager getGuildAudioPlayer() {
if (musicManager == null) {
musicManager = new GuildMusicManager(playerManager, guild);
}
guild.getAudioManager().setSendingHandler(musicManager.getSendHandler());
return musicManager;
}
/**
* Add single track to playlist, auto-connect if not connected to vocal chanel
@ -203,7 +185,7 @@ public class AudioM {
* @param track Track to add to playlist
* @param onHead True for adding audio track on top of playlist
*/
public void play(Guild guild, VoiceChannel channel, GuildMusicManager musicManager, UserAudioTrack track, boolean onHead) {
public void play(Guild guild, VoiceChannel channel, GuildAudioManager musicManager, UserAudioTrack track, boolean onHead) {
if (!guild.getAudioManager().isConnected())
guild.getAudioManager().openAudioConnection(channel);
if (!onHead)
@ -218,7 +200,7 @@ public class AudioM {
* @param event
*/
public void skipTrack(GenericInteractionCreateEvent event) {
GuildMusicManager musicManager = getGuildAudioPlayer();
GuildAudioManager musicManager = getGuidAudioManager();
musicManager.scheduler.nextTrack();
Message message = new MessageBuilder().setEmbeds(
EmbedMessageUtils.buildStandar(
@ -236,7 +218,7 @@ public class AudioM {
* @param event
*/
public void pause(GenericInteractionCreateEvent event) {
GuildMusicManager musicManager = getGuildAudioPlayer();
GuildAudioManager musicManager = getGuidAudioManager();
musicManager.scheduler.pause();
Message message = new MessageBuilder().setEmbeds(
EmbedMessageUtils.buildStandar(
@ -256,7 +238,7 @@ public class AudioM {
* @param event
*/
public void resume(GenericInteractionCreateEvent event) {
GuildMusicManager musicManager = getGuildAudioPlayer();
GuildAudioManager musicManager = getGuidAudioManager();
Message message;
if (musicManager.player.getPlayingTrack() == null) {
message = new MessageBuilder().setEmbeds(
@ -284,7 +266,7 @@ public class AudioM {
* @param event
*/
public void info(GenericInteractionCreateEvent event) {
GuildMusicManager musicManager = getGuildAudioPlayer();
GuildAudioManager musicManager = getGuidAudioManager();
AudioTrackInfo info = musicManager.scheduler.getInfo();
UserAudioTrack userAudioTrack = musicManager.scheduler.getCurrentPlayingTrack();
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicInfo(info, userAudioTrack)).build();
@ -293,7 +275,7 @@ public class AudioM {
}
public void flush(GenericInteractionCreateEvent event) {
GuildMusicManager musicManager = getGuildAudioPlayer();
GuildAudioManager musicManager = getGuidAudioManager();
musicManager.scheduler.flush();
Message message = new MessageBuilder().setEmbeds(
EmbedMessageUtils.buildStandar(
@ -311,7 +293,7 @@ public class AudioM {
* @param event
*/
public void list(GenericInteractionCreateEvent event) {
GuildMusicManager musicManager = getGuildAudioPlayer();
GuildAudioManager musicManager = getGuidAudioManager();
List<UserAudioTrackData> list = musicManager.scheduler.getList();
if (list.size() == 0) {
@ -361,8 +343,8 @@ public class AudioM {
* @param onHead True for adding audio track on top of playlist
*/
public void add(SlashCommandEvent event, String url, int playListLimit, boolean onHead) {
if (playedChanel != null) {
loadAndPlay(event, playedChanel, url, playListLimit, onHead);
if (guild.getAudioManager().isConnected()) {
loadAndPlay(event, guild.getAudioManager().getConnectedChannel(), url, playListLimit, onHead);
} else {
Message message = new MessageBuilder().setEmbeds(EmbedMessageUtils.getMusicError("Not connected to vocal chanel !")).build();
event.getHook().setEphemeral(true).sendMessage(message).queue();
@ -375,8 +357,8 @@ public class AudioM {
* @param event
*/
public void stop(GenericInteractionCreateEvent event) {
musicManager.scheduler.stop();
musicManager.scheduler.flush();
guildAudioManager.scheduler.stop();
guildAudioManager.scheduler.flush();
if (event != null) {
Message message = new MessageBuilder().setEmbeds(
@ -390,6 +372,14 @@ public class AudioM {
}
}
public void stop() {
GuildAudioManager musicManager = getGuidAudioManager();
musicManager.scheduler.stop();
musicManager.scheduler.flush();
clearLastButton();
}
public void disconnect(GenericInteractionCreateEvent event) {
disconnect();
Message message = new MessageBuilder().setEmbeds(
@ -403,47 +393,25 @@ public class AudioM {
}
public void disconnect() {
GuildMusicManager musicManager = getGuildAudioPlayer();
GuildAudioManager musicManager = getGuidAudioManager();
musicManager.scheduler.stop();
musicManager.scheduler.flush();
playedChanel = null;
guild.getAudioManager().closeAudioConnection();
clearLastButton();
}
/**
* Stop current playing track and flush playlist (no confirmation message)
*/
public void stop() {
GuildMusicManager musicManager = getGuildAudioPlayer();
musicManager.scheduler.stop();
musicManager.scheduler.flush();
clearLastButton();
}
public GuildMusicManager getGuildMusicManager() {
if (musicManager == null)
musicManager = getGuildAudioPlayer();
return musicManager;
}
public Guild getGuild() {
return guild;
}
public AudioPlayerManager getPlayerManager() {
return playerManager;
public AudioPlayerManager getAudioPlayerManager() {
return audioPlayerManager;
}
public GuildAudioManager getGuidAudioManager() {
return guildAudioManager;
}
public VoiceChannel getPlayedChanel() {
return playedChanel;
}
public void setPlayedChanel(VoiceChannel playedChanel) {
this.playedChanel = playedChanel;
}
public void clearLastButton() {
if (lastMessageWithButton != null) {
@ -452,6 +420,7 @@ public class AudioM {
}
}
public void updateLastButton() {
if (lastMessageWithButton != null)
lastMessageWithButton = lastMessageWithButton.editMessageComponents(ActionRow.of(getActionButton())).complete();
@ -460,17 +429,16 @@ public class AudioM {
private List<Button> getActionButton() {
ArrayList<Button> buttonArrayList = new ArrayList<>();
if(musicManager.player.getPlayingTrack() == null){
if (guildAudioManager.player.getPlayingTrack() == null) {
buttonArrayList.add(Button.success("play", Emoji.fromUnicode("▶️")).withDisabled(true));
buttonArrayList.add(Button.primary("next", Emoji.fromUnicode("⏭️")).withDisabled(true));
buttonArrayList.add(Button.primary("stop", Emoji.fromUnicode("⏹️")).withDisabled(true));
buttonArrayList.add(Button.danger("disconnect", Emoji.fromUnicode("⏏️")));
return buttonArrayList;
}
if(musicManager.player.isPaused()){
if (guildAudioManager.player.isPaused()) {
buttonArrayList.add(Button.success("play", Emoji.fromUnicode("▶️")));
}
else{
} else {
buttonArrayList.add(Button.success("pause", Emoji.fromUnicode("⏸️")));
}
buttonArrayList.add(Button.primary("next", Emoji.fromUnicode("⏭️")));

View File

@ -1,4 +1,4 @@
package net.Broken.audio;
package net.Broken.Audio;
/**

View File

@ -1,4 +1,4 @@
package net.Broken.audio;
package net.Broken.Audio;
/**
* Null music manager

View File

@ -1,4 +1,4 @@
package net.Broken.audio;
package net.Broken.Audio;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
@ -9,9 +9,9 @@ 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.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;
@ -178,7 +178,7 @@ public class TrackScheduler extends AudioEventAdapter {
if (endReason.mayStartNext) {
if(queue.isEmpty()){
logger.debug("[" + guild.getName() + "] End of track, Playlist empty.");
AudioM.getInstance(guild).updateLastButton();
GuildAudioWrapper.getInstance(guild).updateLastButton();
}else{
logger.debug("[" + guild.getName() + "] End of track, start next.");
nextTrack();
@ -191,49 +191,49 @@ public class TrackScheduler extends AudioEventAdapter {
@Override
public void onTrackStart(AudioPlayer player, AudioTrack track) {
super.onTrackStart(player, track);
AudioM.getInstance(guild).updateLastButton();
GuildAudioWrapper.getInstance(guild).updateLastButton();
}
@Override
public void onPlayerPause(AudioPlayer player) {
super.onPlayerPause(player);
AudioM.getInstance(guild).updateLastButton();
GuildAudioWrapper.getInstance(guild).updateLastButton();
}
@Override
public void onPlayerResume(AudioPlayer player) {
super.onPlayerResume(player);
AudioM.getInstance(guild).updateLastButton();
GuildAudioWrapper.getInstance(guild).updateLastButton();
}
@Override
public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) {
super.onTrackException(player, track, exception);
AudioM.getInstance(guild).updateLastButton();
GuildAudioWrapper.getInstance(guild).updateLastButton();
}
@Override
public void onTrackStuck(AudioPlayer player, AudioTrack track, long thresholdMs) {
super.onTrackStuck(player, track, thresholdMs);
AudioM.getInstance(guild).updateLastButton();
GuildAudioWrapper.getInstance(guild).updateLastButton();
}
private void needAutoPlay() {
if ((queue.size() < 1) && autoFlow && currentPlayingTrack != null) {
logger.debug("[" + guild.getName() + "] Auto add needed!");
AudioM audioM = AudioM.getInstance(guild);
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);
audioM.loadAndPlayAuto(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);
audioM.loadAndPlayAuto(id);
guildAudioWrapper.loadAndPlayAuto(id);
} catch (GoogleJsonResponseException e) {
logger.error("[" + guild.getName() + "] There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());

View File

@ -1,4 +1,4 @@
package net.Broken.audio;
package net.Broken.Audio;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.dv8tion.jda.api.entities.User;

View File

@ -1,4 +1,4 @@
package net.Broken.audio.Youtube;
package net.Broken.Audio.Youtube;
public class RelatedIdNotFound extends Exception {
}

View File

@ -1,4 +1,4 @@
package net.Broken.audio.Youtube;
package net.Broken.Audio.Youtube;
public class SearchResult {
public String id;

View File

@ -1,4 +1,4 @@
package net.Broken.audio.Youtube;
package net.Broken.Audio.Youtube;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioTrack;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeSearchProvider;

View File

@ -1,4 +1,4 @@
package net.Broken.audio.Youtube;
package net.Broken.Audio.Youtube;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
@ -68,7 +68,7 @@ public class YoutubeTools {
}
public ArrayList<net.Broken.audio.Youtube.SearchResult> search(String query, long max, boolean playlist) throws IOException {
public ArrayList<net.Broken.Audio.Youtube.SearchResult> search(String query, long max, boolean playlist) throws IOException {
YouTube youTube = getYoutubeService();
YouTube.Search.List searchList = youTube.search().list(Collections.singletonList("snippet"));
if (playlist)
@ -98,10 +98,10 @@ public class YoutubeTools {
for (Playlist item : playlistResponse.getItems()) {
playlistHashMap.put(item.getId(), item);
}
ArrayList<net.Broken.audio.Youtube.SearchResult> finalResult = new ArrayList<>();
ArrayList<net.Broken.Audio.Youtube.SearchResult> 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)"));
finalResult.add(new net.Broken.Audio.Youtube.SearchResult(item, playlistHashMap.get(item.getId().getPlaylistId()).getContentDetails().getItemCount().toString() + " Video(s)"));
}
return finalResult;
@ -117,10 +117,10 @@ public class YoutubeTools {
for (Video item : videoResponse.getItems()) {
videoHashMap.put(item.getId(), item);
}
ArrayList<net.Broken.audio.Youtube.SearchResult> finalResult = new ArrayList<>();
ArrayList<net.Broken.Audio.Youtube.SearchResult> 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()));
finalResult.add(new net.Broken.Audio.Youtube.SearchResult(item, videoHashMap.get(item.getId().getVideoId()).getContentDetails().getDuration()));
}
return finalResult;
}

View File

@ -5,7 +5,7 @@ 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.AudioM;
import net.Broken.Audio.GuildAudioWrapper;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.*;
@ -119,10 +119,10 @@ public class BotListener extends ListenerAdapter {
if (event.getGuild().getAudioManager().getConnectedChannel().getMembers().size() == 1) {
logger.debug("I'm alone, close audio connection.");
AudioM.getInstance(event.getGuild()).stop();
GuildAudioWrapper.getInstance(event.getGuild()).stop();
}
} else if (event.getMember().getUser() == MainBot.jda.getSelfUser()) {
AudioM.getInstance(event.getGuild()).clearLastButton();
GuildAudioWrapper.getInstance(event.getGuild()).clearLastButton();
}
AutoVoiceChannel autoVoiceChannel = AutoVoiceChannel.getInstance(event.getGuild());
autoVoiceChannel.leave(event.getChannelLeft());
@ -147,13 +147,13 @@ public class BotListener extends ListenerAdapter {
public void onButtonClick(@NotNull ButtonClickEvent event) {
super.onButtonClick(event);
event.deferReply().queue();
AudioM audioM = AudioM.getInstance(event.getGuild());
GuildAudioWrapper guildAudioWrapper = GuildAudioWrapper.getInstance(event.getGuild());
switch (event.getComponentId()) {
case "pause" -> audioM.pause(event);
case "play" -> audioM.resume(event);
case "next" -> audioM.skipTrack(event);
case "stop" -> audioM.stop(event);
case "disconnect" -> audioM.disconnect(event);
case "pause" -> guildAudioWrapper.pause(event);
case "play" -> guildAudioWrapper.resume(event);
case "next" -> guildAudioWrapper.skipTrack(event);
case "stop" -> guildAudioWrapper.stop(event);
case "disconnect" -> guildAudioWrapper.disconnect(event);
}
}

View File

@ -1,19 +0,0 @@
package net.Broken.RestApi.Commands;
import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.WebLoadUtils;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import org.springframework.http.ResponseEntity;
/**
* Add track RestApi
*/
public class Add implements CommandInterface {
@Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
return new WebLoadUtils(data, user, guild, true).getResponse();
}
}

View File

@ -1,22 +0,0 @@
package net.Broken.RestApi.Commands;
import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.AudioM;
import net.Broken.audio.TrackScheduler;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class AutoFlowOff implements CommandInterface {
@Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM audioM = AudioM.getInstance(guild);
TrackScheduler scheduler = audioM.getGuildMusicManager().scheduler;
scheduler.setAutoFlow(false);
return new ResponseEntity<>(new CommandResponseData(data.command, "ok"), HttpStatus.OK);
}
}

View File

@ -1,23 +0,0 @@
package net.Broken.RestApi.Commands;
import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.AudioM;
import net.Broken.audio.TrackScheduler;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class AutoFlowOn implements CommandInterface {
@Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM audioM = AudioM.getInstance(guild);
TrackScheduler scheduler = audioM.getGuildMusicManager().scheduler;
scheduler.setAutoFlow(true);
return new ResponseEntity<>(new CommandResponseData(data.command, "ok"), HttpStatus.OK);
}
}

View File

@ -1,37 +0,0 @@
package net.Broken.RestApi.Commands;
import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.VoiceChannel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Connect to vocal channel RestApi command
*/
public class Connect implements CommandInterface {
@Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM audioM = AudioM.getInstance(guild);
if (data.chanelId == null)
return new ResponseEntity<>(new CommandResponseData(data.command, "Missing chanelId"), HttpStatus.BAD_REQUEST);
VoiceChannel voiceChannel = null;
try {
voiceChannel = guild.getVoiceChannelById(data.chanelId);
} catch (NumberFormatException ignored) {
}
if (voiceChannel == null) {
return new ResponseEntity<>(new CommandResponseData(data.command, "Channel Not found"), HttpStatus.BAD_REQUEST);
}
audioM.getGuildAudioPlayer();
guild.getAudioManager().openAudioConnection(guild.getVoiceChannelById(data.chanelId));
audioM.setPlayedChanel(voiceChannel);
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
}
}

View File

@ -1,27 +0,0 @@
package net.Broken.RestApi.Commands;
import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Delete track RestApi command
*/
public class Dell implements CommandInterface {
@Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
if (data.url != null) {
if (AudioM.getInstance(guild).getGuildMusicManager().scheduler.remove(data.url)) {
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
} else
return new ResponseEntity<>(new CommandResponseData(data.command, "URL not found"), HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(new CommandResponseData(data.command, "Missing URL"), HttpStatus.NOT_ACCEPTABLE);
}
}

View File

@ -1,22 +0,0 @@
package net.Broken.RestApi.Commands;
import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Disconnect from vocal chanel RestApi Command
*/
public class Disconnect implements CommandInterface {
@Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM.getInstance(guild).stop();
return new ResponseEntity<>(new CommandResponseData(data.command, "Ok"), HttpStatus.OK);
}
}

View File

@ -1,21 +0,0 @@
package net.Broken.RestApi.Commands;
import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Flush playlist RestApi Command
*/
public class Flush implements CommandInterface {
@Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM.getInstance(guild).getGuildMusicManager().scheduler.flush();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
}
}

View File

@ -1,21 +0,0 @@
package net.Broken.RestApi.Commands;
import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Next Track RestApi command
*/
public class Next implements CommandInterface {
@Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM.getInstance(guild).getGuildMusicManager().scheduler.nextTrack();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
}
}

View File

@ -1,21 +0,0 @@
package net.Broken.RestApi.Commands;
import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Pause track RestApi command
*/
public class Pause implements CommandInterface {
@Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM.getInstance(guild).getGuildMusicManager().scheduler.pause();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
}
}

View File

@ -1,21 +0,0 @@
package net.Broken.RestApi.Commands;
import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Resume (play button) RestApi command
*/
public class Play implements CommandInterface {
@Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM.getInstance(guild).getGuildMusicManager().scheduler.resume();
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
}
}

View File

@ -1,22 +0,0 @@
package net.Broken.RestApi.Commands;
import net.Broken.RestApi.CommandInterface;
import net.Broken.RestApi.Data.CommandPostData;
import net.Broken.RestApi.Data.CommandResponseData;
import net.Broken.audio.AudioM;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Stop RestApi Command
*/
public class Stop implements CommandInterface {
@Override
public ResponseEntity<CommandResponseData> action(CommandPostData data, User user, Guild guild) {
AudioM.getInstance(guild).stop(null);
return new ResponseEntity<>(new CommandResponseData(data.command, "Accepted"), HttpStatus.OK);
}
}

View File

@ -1,7 +1,7 @@
package net.Broken.RestApi.Data;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import net.Broken.audio.UserAudioTrack;
import net.Broken.Audio.UserAudioTrack;
/**
* Data for JSON Parsing

View File

@ -1,239 +0,0 @@
package net.Broken.RestApi;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.UserRepository;
import net.Broken.MainBot;
import net.Broken.RestApi.Data.*;
import net.Broken.Tools.CacheTools;
import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException;
import net.Broken.Tools.UserManager.Stats.UserStatsUtils;
import net.Broken.Tools.UserManager.UserUtils;
import net.Broken.audio.AudioM;
import net.Broken.audio.GetVoiceChanels;
import net.Broken.audio.Youtube.SearchResult;
import net.Broken.audio.Youtube.YoutubeSearchRework;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Rest Api Controller for /api/music
*/
@RestController
@RequestMapping("/api/music/")
public class MusicWebAPIController {
private final
UserRepository userRepository;
Logger logger = LogManager.getLogger();
UserUtils userUtils = UserUtils.getInstance();
@Autowired
public MusicWebAPIController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@RequestMapping("/currentMusicInfo")
public ResponseEntity<CurrentMusicData> getCurrentM(@RequestParam(value = "guild") String guildId) { //TODO security issue ???!!!
Guild guild = MainBot.jda.getGuildById(guildId);
if (guild == null) {
logger.warn("Request whit no guild!");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} else {
logger.trace("currentMusicInfo for " + guild.getName());
}
if (guild.getAudioManager().isConnected()) {
AudioPlayer player = AudioM.getInstance(guild).getGuildMusicManager().player;
AudioTrack currentTrack = player.getPlayingTrack();
if (currentTrack == null) {
return new ResponseEntity<>(new CurrentMusicData(null, 0, "STOP", false, AudioM.getInstance(guild).getGuildMusicManager().scheduler.isAutoFlow()), HttpStatus.OK);
}
UserAudioTrackData uat = new UserAudioTrackData(AudioM.getInstance(guild).getGuildMusicManager().scheduler.getCurrentPlayingTrack());
return new ResponseEntity<>(new CurrentMusicData(uat, currentTrack.getPosition(), currentTrack.getState().toString(), player.isPaused(), AudioM.getInstance(guild).getGuildMusicManager().scheduler.isAutoFlow()), HttpStatus.OK);
} else {
return new ResponseEntity<>(new CurrentMusicData(null, 0, "DISCONNECTED", false, false), HttpStatus.OK);
}
}
@RequestMapping("/getPlaylist")
public ResponseEntity<PlaylistData> getPlaylist(@RequestParam(value = "guild") String guildId) { //TODO security issue ???!!!
Guild guild = MainBot.jda.getGuildById(guildId);
if (guild == null) {
logger.warn("Request whit no guild!");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} else {
logger.trace("getPlaylist for " + guild.getName());
}
List<UserAudioTrackData> list = null;
list = AudioM.getInstance(guild).getGuildMusicManager().scheduler.getList();
return new ResponseEntity<>(new PlaylistData(list), HttpStatus.OK);
}
@RequestMapping("/getAllInfo")
public ResponseEntity<AllMusicInfoData> getAllInfo(@RequestParam(value = "guild") String guildId, @CookieValue("token") String token) {
if (token != null) {
Guild guild = MainBot.jda.getGuildById(guildId);
if (guild == null) {
logger.warn("All info without guild!");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
try {
UserEntity user = userUtils.getUserWithApiToken(userRepository, token);
logger.trace("All info from USER: " + user.getUsername() + " GUILD: " + guild.getName());
PlaylistData list = new PlaylistData(AudioM.getInstance(guild).getGuildMusicManager().scheduler.getList());
CurrentMusicData musicData;
if (guild.getAudioManager().isConnected()) {
AudioPlayer player = AudioM.getInstance(guild).getGuildMusicManager().player;
AudioTrack currentTrack = player.getPlayingTrack();
if (currentTrack == null) {
musicData = new CurrentMusicData(null, 0, "STOP", false, AudioM.getInstance(guild).getGuildMusicManager().scheduler.isAutoFlow());
} else {
UserAudioTrackData uat = new UserAudioTrackData(AudioM.getInstance(guild).getGuildMusicManager().scheduler.getCurrentPlayingTrack());
musicData = new CurrentMusicData(uat, currentTrack.getPosition(), currentTrack.getState().toString(), player.isPaused(), AudioM.getInstance(guild).getGuildMusicManager().scheduler.isAutoFlow());
}
} else {
musicData = new CurrentMusicData(null, 0, "DISCONNECTED", false, false);
}
return new ResponseEntity<>(new AllMusicInfoData(musicData, list), HttpStatus.OK);
} catch (UnknownTokenException e) {
logger.warn("All info with unknown token");
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
} else {
logger.warn("All Info without token!");
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
@RequestMapping(value = "/command", method = RequestMethod.POST)
public ResponseEntity<CommandResponseData> command(@RequestBody CommandPostData data, HttpServletRequest request, @RequestParam(value = "guild") String guildId, @CookieValue("token") String token) {
if (data.command != null) {
if (token != null) {
Guild guild = MainBot.jda.getGuildById(guildId);
if (guild == null) {
logger.warn("Request whit no guild!");
return new ResponseEntity<>(new CommandResponseData(data.command, "Missing Guild!\nPlease Re-connect.", "token"), HttpStatus.UNAUTHORIZED);
}
try {
UserEntity user = userUtils.getUserWithApiToken(userRepository, token);
logger.info("[" + guild.getName() + "] Receive command" + data.command + " from" + request.getRemoteAddr() + " USER:" + user.getUsername() + " GUILD:" + guild.getName());
if (ApiCommandLoader.apiCommands.containsKey(data.command)) {
UserStatsUtils.getINSTANCE().addApiCount(user, guildId);
return ApiCommandLoader.apiCommands.get(data.command).action(data, MainBot.jda.getUserById(user.getDiscordId()), guild);
} else
return new ResponseEntity<>(new CommandResponseData(data.command, "Unknown Command", "command"), HttpStatus.BAD_REQUEST);
} catch (UnknownTokenException e) {
logger.warn("Command with unknown token from: " + request.getRemoteAddr());
return new ResponseEntity<>(new CommandResponseData(data.command, "Unknown Token!\nPlease Re-connect.", "token"), HttpStatus.UNAUTHORIZED);
}
} else {
logger.warn("Command without token! ip: " + request.getRemoteAddr());
return new ResponseEntity<>(new CommandResponseData(data.command, "Missing token!\nPlease Re-connect.", "token"), HttpStatus.UNAUTHORIZED);
}
} else
logger.info("Null");
return new ResponseEntity<>(new CommandResponseData(null, null), HttpStatus.NO_CONTENT);
}
@RequestMapping(value = "/getChanel", method = RequestMethod.GET)
public ResponseEntity<List<ChanelData>> getChanel(@CookieValue(name = "token", defaultValue = "") String token, @RequestParam(value = "guild") String guildId) {
if (token != null && !token.isEmpty()) {
try {
UserEntity user = userUtils.getUserWithApiToken(userRepository, token);
Guild guild = MainBot.jda.getGuildById(guildId);
if (guild == null) {
logger.warn("Request whit no guild!");
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Member member = guild.getMember(CacheTools.getJdaUser(user));
if (member == null) {
member = guild.retrieveMember(CacheTools.getJdaUser(user)).complete();
if (member == null) {
logger.warn("Can't find member " + user.getUsername() + " for guild " + guild.getName() + ", User not in guild ?");
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
logger.trace("getPlaylist for " + guild.getName());
List<ChanelData> temp = new ArrayList<>();
for (VoiceChannel aChanel : GetVoiceChanels.find(guild, member)) {
temp.add(new ChanelData(aChanel.getName(), aChanel.getId(), aChanel.getPosition()));
}
return new ResponseEntity<>(temp, HttpStatus.OK);
} catch (UnknownTokenException e) {
logger.warn("Get Chanel without token!");
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
} else {
logger.warn("Get Chanel without token!");
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
@RequestMapping(value = "/search", method = RequestMethod.GET)
public ResponseEntity<List<SearchResult>> search(@CookieValue(name = "token", defaultValue = "") String token, @RequestParam(value = "query") String query) {
if (token != null && !token.isEmpty()) {
try {
UserEntity user = userUtils.getUserWithApiToken(userRepository, token);
YoutubeSearchRework youtubeSearch = YoutubeSearchRework.getInstance();
List<SearchResult> result = youtubeSearch.searchVideo(query, 25, false);
return new ResponseEntity<>(result, HttpStatus.OK);
} catch (UnknownTokenException e) {
logger.warn("Search without token!");
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
} catch (GoogleJsonResponseException e) {
logger.error("There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (IOException e) {
logger.catching(e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
} else {
logger.warn("Search without token!");
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
}
}

View File

@ -1,99 +0,0 @@
package net.Broken.RestApi;
import net.Broken.DB.Entity.PlaylistEntity;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.PlaylistRepository;
import net.Broken.DB.Repository.TrackRepository;
import net.Broken.DB.Repository.UserRepository;
import net.Broken.RestApi.Data.Playlist.*;
import net.Broken.audio.Playlist.PlaylistManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/playlist/")
public class PlaylistAPIController {
private final
UserRepository userRepository;
private final
PlaylistRepository playlistRepository;
private final
TrackRepository trackRepository;
private Logger logger = LogManager.getLogger();
@Autowired
public PlaylistAPIController(UserRepository userRepository, PlaylistRepository playlistRepository, TrackRepository trackRepository) {
this.userRepository = userRepository;
this.playlistRepository = playlistRepository;
this.trackRepository = trackRepository;
}
// @RequestMapping("/myPlaylist")
// public List<PlaylistEntity> myPlaylist(@CookieValue(value = "token", defaultValue = "") String token) {
// if (token.isEmpty())
// return null;
// else {
// UserEntity user = userRepository.findByApiToken(token).get(0);
// return user.getPlaylists();
// }
//
// }
// @RequestMapping("/createPlaylist")
// public ResponseEntity<PlaylistResponseData> createPlaylist(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody CreatePlaylistData data) {
//
// if (token.isEmpty())
// return new ResponseEntity<>(new PlaylistResponseData("Unknown Token!\nPlease Re-connect.", "token"), HttpStatus.UNAUTHORIZED);
// else {
// UserEntity user = userRepository.findByApiToken(token).get(0);
// PlaylistEntity playlistEntity = new PlaylistEntity(data.name, user);
// playlistEntity = playlistRepository.save(playlistEntity);
// user.addPlaylist(playlistEntity);
// userRepository.save(user);
// return new ResponseEntity<>(new PlaylistResponseData("Ok", playlistEntity), HttpStatus.OK);
// }
//
//
// }
@RequestMapping("/addToPlaylist")
public ResponseEntity<PlaylistResponseData> addToPlaylist(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody AddToPlaylistData data) {
PlaylistManager playlistManager = PlaylistManager.getINSTANCE();
return playlistManager.addToPlaylist(token, data);
}
@RequestMapping("/dellTrack")
public ResponseEntity<PlaylistResponseData> dellTrack(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody DeleteTrackData data) {
PlaylistManager playlistManager = PlaylistManager.getINSTANCE();
return playlistManager.removeTrack(token, data);
}
@RequestMapping("/moveTrack")
public ResponseEntity<PlaylistResponseData> moveTrack(@CookieValue(value = "token", defaultValue = "") String token, @RequestBody MoveTrackData data) {
PlaylistManager playlistManager = PlaylistManager.getINSTANCE();
return playlistManager.moveTrack(token, data);
}
}

View File

@ -3,7 +3,7 @@ package net.Broken.SlashCommands;
import net.Broken.SlashCommand;
import net.Broken.Tools.EmbedMessageUtils;
import net.Broken.audio.AudioM;
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;
@ -27,7 +27,7 @@ public class Music implements SlashCommand {
@Override
public void action(SlashCommandEvent event) {
AudioM audio = AudioM.getInstance(event.getGuild());
GuildAudioWrapper audio = GuildAudioWrapper.getInstance(event.getGuild());
String action = event.getSubcommandName();
event.deferReply().queue();
switch (action) {

View File

@ -4,16 +4,12 @@ import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import net.Broken.BotConfigLoader;
import net.Broken.MainBot;
import net.Broken.SpringContext;
import net.Broken.audio.UserAudioTrack;
import net.Broken.audio.Youtube.SearchResult;
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;
import net.dv8tion.jda.api.entities.User;
import org.springframework.context.ApplicationContext;
import java.awt.*;
import java.io.FileNotFoundException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

View File

@ -1,47 +0,0 @@
package net.Broken.audio;
import net.Broken.DB.Entity.GuildPreferenceEntity;
import net.Broken.Tools.SettingsUtils;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.GuildChannel;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.VoiceChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* Used to find general voice channels
*/
public class GetVoiceChanels {
private static final Logger logger = LogManager.getLogger();
/**
* Search for all voice channel where the user can connect
*
* @param guild Current guild
* @return General Category
*/
public static List<VoiceChannel> find(Guild guild, Member member) {
ArrayList<VoiceChannel> list = new ArrayList<>();
VoiceChannel afk = guild.getAfkChannel();
GuildPreferenceEntity pref = SettingsUtils.getInstance().getPreference(guild);
String autoVoice = pref.getAutoVoiceChannelID();
for (VoiceChannel channel : guild.getVoiceChannels()) {
if (channel != afk && !channel.getId().equals(autoVoice) && member.getPermissions(channel).contains(Permission.VOICE_CONNECT)) {
list.add(channel);
}
}
list.sort(Comparator.comparingInt(GuildChannel::getPositionRaw));
return list;
}
}

View File

@ -1,4 +0,0 @@
package net.Broken.audio.Playlist.Exception;
public class PlaylistNotFoundException extends Exception {
}

View File

@ -1,218 +0,0 @@
package net.Broken.audio.Playlist;
import net.Broken.DB.Entity.PlaylistEntity;
import net.Broken.DB.Entity.TrackEntity;
import net.Broken.DB.Entity.UserEntity;
import net.Broken.DB.Repository.PlaylistRepository;
import net.Broken.DB.Repository.TrackRepository;
import net.Broken.DB.Repository.UserRepository;
import net.Broken.MainBot;
import net.Broken.RestApi.Data.Playlist.AddToPlaylistData;
import net.Broken.RestApi.Data.Playlist.DeleteTrackData;
import net.Broken.RestApi.Data.Playlist.MoveTrackData;
import net.Broken.RestApi.Data.Playlist.PlaylistResponseData;
import net.Broken.SpringContext;
import net.Broken.Tools.UserManager.Exceptions.UnknownTokenException;
import net.Broken.Tools.UserManager.UserUtils;
import net.Broken.audio.Playlist.Exception.PlaylistNotFoundException;
import net.Broken.audio.WebLoadUtils;
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.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.List;
public class PlaylistManager {
private static PlaylistManager INSTANCE = new PlaylistManager();
private final ResponseEntity<PlaylistResponseData> TOKEN_ERROR = new ResponseEntity<>(new PlaylistResponseData("Unknown Token!\nPlease Re-connect.", "token"), HttpStatus.UNAUTHORIZED);
private final ResponseEntity<PlaylistResponseData> PLAYLIST_NOT_FOUND = new ResponseEntity<>(new PlaylistResponseData("Playlist not found", "playlist"), HttpStatus.NOT_FOUND);
private final ResponseEntity<PlaylistResponseData> TRACK_NOT_FOUND = new ResponseEntity<>(new PlaylistResponseData("Can't find media!", "track"), HttpStatus.NOT_FOUND);
Logger logger = LogManager.getLogger();
private PlaylistRepository playlistRepository;
private TrackRepository trackRepository;
private UserRepository userRepository;
private PlaylistManager() {
ApplicationContext context = SpringContext.getAppContext();
playlistRepository = (PlaylistRepository) context.getBean("playlistRepository");
trackRepository = (TrackRepository) context.getBean("trackRepository");
userRepository = (UserRepository) context.getBean("userRepository");
}
public static PlaylistManager getINSTANCE() {
return INSTANCE;
}
public ResponseEntity<PlaylistResponseData> addToPlaylist(String token, AddToPlaylistData data) {
UserUtils userUtils = UserUtils.getInstance();
try {
UserEntity user = userUtils.getUserWithApiToken(userRepository, token);
PlaylistEntity playlist = getPlaylist(data.playlistId);
User jdaUser = MainBot.jda.getUserById(user.getDiscordId());
WebLoadUtils webLoadUtils = new WebLoadUtils(data, jdaUser, MainBot.jda.getGuilds().get(0), false);
webLoadUtils.getResponse();
if (webLoadUtils.userAudioTrack == null) {
return TRACK_NOT_FOUND;
} else {
TrackEntity trackEntity = new TrackEntity(webLoadUtils.userAudioTrack.getAudioTrack().getInfo(), data.pos, playlist);
playlist = insert(playlist, trackEntity);
return new ResponseEntity<>(new PlaylistResponseData("Ok", playlist), HttpStatus.OK);
}
} catch (UnknownTokenException e) {
logger.warn("Unknown token: " + token);
return TOKEN_ERROR;
} catch (PlaylistNotFoundException e) {
logger.debug("Playlist not found: " + data.playlistId);
return PLAYLIST_NOT_FOUND;
}
}
public ResponseEntity<PlaylistResponseData> removeTrack(String token, DeleteTrackData data) {
UserUtils userUtils = UserUtils.getInstance();
try {
UserEntity user = userUtils.getUserWithApiToken(userRepository, token);
PlaylistEntity playlist = getPlaylist(data.playlistId);
TrackEntity toDelete = trackRepository.findById(data.id);
playlist = remove(playlist, toDelete);
if (playlist == null) {
logger.warn("Playlist: " + data.playlistId + " Track: " + data.id);
return TRACK_NOT_FOUND;
}
return new ResponseEntity<>(new PlaylistResponseData("Ok", playlist), HttpStatus.OK);
} catch (UnknownTokenException e) {
logger.warn("Unknown token: " + token);
return TOKEN_ERROR;
} catch (PlaylistNotFoundException e) {
logger.debug("Playlist not found: " + data.playlistId);
return PLAYLIST_NOT_FOUND;
}
}
public ResponseEntity<PlaylistResponseData> moveTrack(String token, MoveTrackData data) {
UserUtils userUtils = UserUtils.getInstance();
try {
UserEntity user = userUtils.getUserWithApiToken(userRepository, token);
PlaylistEntity playlist = getPlaylist(data.playlistId);
TrackEntity toMove = trackRepository.findById(data.id);
TrackEntity save = new TrackEntity(toMove);
playlist = remove(playlist, toMove);
if (playlist == null) {
logger.warn("Playlist: " + data.playlistId + " Track: " + data.id);
return TRACK_NOT_FOUND;
}
save.setPos(data.newPos);
playlist = insert(playlist, save);
return new ResponseEntity<>(new PlaylistResponseData("Ok", playlist), HttpStatus.OK);
} catch (UnknownTokenException e) {
logger.warn("Unknown token: " + token);
return TOKEN_ERROR;
} catch (PlaylistNotFoundException e) {
logger.debug("Playlist not found: " + data.playlistId);
return PLAYLIST_NOT_FOUND;
}
}
private PlaylistEntity getPlaylist(int id) throws PlaylistNotFoundException {
PlaylistEntity playlist = playlistRepository.findById(id);
if (playlist == null)
throw new PlaylistNotFoundException();
else
return playlist;
}
private PlaylistEntity insert(PlaylistEntity playlistEntity, TrackEntity trackEntity) {
List<TrackEntity> tracks = trackRepository.findDistinctByPlaylistOrderByPos(playlistEntity);
boolean increase = false;
for (TrackEntity track : tracks) {
if (track.getPos().equals(trackEntity.getPos())) {
logger.debug("Need re-organisation");
increase = true;
}
if (increase) {
track.setPos(track.getPos() + 1);
trackRepository.save(track);
}
}
if (!increase) {
trackEntity.setPos(tracks.size());
}
trackRepository.save(trackEntity);
playlistEntity.addTracks(trackEntity);
return playlistRepository.save(playlistEntity);
}
private PlaylistEntity remove(PlaylistEntity playlistEntity, TrackEntity trackEntity) {
if (trackEntity == null) {
logger.warn("Track not found in DB!");
return null;
}
List<TrackEntity> tracks = trackRepository.findDistinctByPlaylistOrderByPos(playlistEntity);
int toDeleteIndex = tracks.indexOf(trackEntity);
logger.debug("To delete index: " + toDeleteIndex);
if (toDeleteIndex == -1) {
logger.warn("Track not found in playlist");
return null;
}
for (int i = toDeleteIndex + 1; i < tracks.size(); i++) {
tracks.get(i).setPos(tracks.get(i).getPos() - 1);
trackRepository.save(tracks.get(i));
}
tracks.remove(trackEntity);
trackRepository.delete(trackEntity);
playlistEntity.setTracks(tracks);
playlistEntity = playlistRepository.save(playlistEntity);
return playlistEntity;
}
}

View File

@ -1,101 +0,0 @@
package net.Broken.audio;
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
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.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Interface between WebApi and Music bot for submitting track
*/
public class WebLoadUtils {
public UserAudioTrack userAudioTrack;
private ResponseEntity<CommandResponseData> response;
private Logger logger = LogManager.getLogger();
/**
* Submit a track or playlist to Music bot
*
* @param data Received data from API
* @param user User who submit the track
* @param guild
*/
public WebLoadUtils(CommandPostData data, User user, Guild guild, boolean submit) {
AudioPlayerManager playerM = AudioM.getInstance(guild).getPlayerManager();
try {
AudioM audioM = AudioM.getInstance(guild);
playerM.loadItemOrdered(audioM.getGuildMusicManager(), data.url, new AudioLoadResultHandler() {
@Override
public void trackLoaded(AudioTrack track) {
logger.info("Single Track detected from web!");
userAudioTrack = new UserAudioTrack(user, track);
if (submit)
audioM.play(audioM.getGuild(), audioM.getPlayedChanel(), audioM.getGuildMusicManager(), userAudioTrack, data.onHead);
response = new ResponseEntity<>(new CommandResponseData("ADD", "Loaded"), HttpStatus.OK);
}
@Override
public void playlistLoaded(AudioPlaylist playlist) {
if (submit) {
logger.info("Playlist detected from web! Limit: " + data.playlistLimit);
audioM.playListLoader(playlist, data.playlistLimit, user, data.onHead);
response = new ResponseEntity<>(new CommandResponseData("ADD", "Loaded"), HttpStatus.OK);
} else {
response = new ResponseEntity<>(new CommandResponseData("ADD", "Adding a list on saved playlist is currently not supported"), HttpStatus.NOT_ACCEPTABLE);
}
}
@Override
public void noMatches() {
logger.warn("Cant find media ! (web) url: " + data.url);
response = new ResponseEntity<>(new CommandResponseData("ADD", "Can't find media!"), HttpStatus.NOT_FOUND);
}
@Override
public void loadFailed(FriendlyException exception) {
logger.error("Cant load media ! (web)");
response = new ResponseEntity<>(new CommandResponseData("ADD", "Cant load media !"), HttpStatus.INTERNAL_SERVER_ERROR);
}
});
while (response == null)
Thread.sleep(10);
} catch (InterruptedException nullMusicManager) {
nullMusicManager.printStackTrace();
}
}
/**
* Wait for the end of submit process and return ResponseEntity
*
* @return HTTP Response
*/
public ResponseEntity<CommandResponseData> getResponse() {
while (response == null) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return response;
}
}