diff --git a/src/me/despawningbone/discordbot/command/music/AudioTrackHandler.java b/src/me/despawningbone/discordbot/command/music/AudioTrackHandler.java index 6abde85..c3d384e 100644 --- a/src/me/despawningbone/discordbot/command/music/AudioTrackHandler.java +++ b/src/me/despawningbone/discordbot/command/music/AudioTrackHandler.java @@ -1,526 +1,526 @@ package me.despawningbone.discordbot.command.music; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.awaitility.Awaitility; import org.awaitility.core.ConditionTimeoutException; import org.json.JSONObject; import org.json.JSONTokener; import com.google.common.util.concurrent.ThreadFactoryBuilder; 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.tools.io.HttpClientTools; import com.sedmelluq.discord.lavaplayer.tools.io.HttpInterface; import com.sedmelluq.discord.lavaplayer.tools.io.HttpInterfaceManager; import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.wrapper.spotify.SpotifyApi; import dev.lavalink.youtube.YoutubeAudioSourceManager; import me.despawningbone.discordbot.DiscordBot; import me.despawningbone.discordbot.command.CommandResult; import me.despawningbone.discordbot.command.CommandResult.CommandResultType; import me.despawningbone.discordbot.utils.MiscUtils; import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; 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.channel.concrete.TextChannel; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel; import net.dv8tion.jda.api.managers.AudioManager; import net.dv8tion.jda.internal.utils.PermissionUtil; /** * Helper class for the entire music subbot instance; * For working in tandem with Music.java */ public class AudioTrackHandler { private ConcurrentHashMap musicManagers; private AudioPlayerManager playerManager; final HttpInterfaceManager httpInterfaceManager; //package final since TrackScheduler will also access it //not anymore, but its fine leaving it as is public ScheduledExecutorService ex = Executors.newScheduledThreadPool(2, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("audio-scheduler-%d").build()); static class TrackData { private String url; private String uDis; private String fDur; private String ytAp = null; private List votes = new ArrayList<>(); public String getUrl() { return url; } public String getUserWithDiscriminator() { return uDis; } public String getFormattedDuration() { return fDur; } public String getYoutubeAutoplayParam() { return ytAp; } public int voteSkip(User user, int req) { if (votes.contains(user.getId())) throw new UnsupportedOperationException("You have already voted!"); votes.add(user.getId()); if (votes.size() < req) { return votes.size(); } else { votes.clear(); return -1; } } public TrackData(String url, User user, long durMillis) { this.url = url; this.uDis = user.getName() + "#" + user.getDiscriminator(); this.fDur = MiscUtils.convertMillis(durMillis); //ytAp is default null } //overload for autoplay public TrackData(String url, long durMillis, String ytAutoplayParam) { this.url = url; this.uDis = "Autoplay"; this.fDur = MiscUtils.convertMillis(durMillis); this.ytAp = ytAutoplayParam; //null for other autoplays } //for cloning; reset votes public TrackData(TrackData orig) { this.url = orig.url; this.uDis = orig.uDis; this.fDur = orig.fDur; this.ytAp = orig.ytAp; //null for other autoplays } } public AudioTrackHandler() { this.musicManagers = new ConcurrentHashMap<>(); this.playerManager = new DefaultAudioPlayerManager(); this.httpInterfaceManager = HttpClientTools.createCookielessThreadLocalManager(); playerManager.setFrameBufferDuration(1000); playerManager.getConfiguration().setFilterHotSwapEnabled(true); try { //register spotify source manager playerManager.registerSourceManager(new SpotifyAudioSourceManager(new SpotifyApi.Builder().setClientId(DiscordBot.tokens.getProperty("spotifyid")).setClientSecret(DiscordBot.tokens.getProperty("spotifysecret")).build(), playerManager, this)); //register new youtube source manager to replace the internal/broken one playerManager.registerSourceManager(new YoutubeAudioSourceManager()); } catch (Exception e) { e.printStackTrace(); } AudioSourceManagers.registerRemoteSources(playerManager); AudioSourceManagers.registerLocalSource(playerManager); } public GuildMusicManager getGuildMusicManager(Guild guild) { String guildId = guild.getId(); GuildMusicManager musicManager; musicManager = musicManagers.get(guildId); if (musicManager == null) { musicManager = new GuildMusicManager(guild, this, playerManager); musicManagers.put(guildId, musicManager); } guild.getAudioManager().setSendingHandler(musicManager.getSendHandler()); return musicManager; } public CompletableFuture searchAndPlay(String search, String type, Member user, TextChannel channel) throws NoSuchElementException { CompletableFuture resFuture = new CompletableFuture<>(); String url = search; try { new URL(url); } catch (MalformedURLException e) { try { url = fetchUrlFromSearch(search, type); } catch (Exception ex) { resFuture.complete(new CommandResult(CommandResultType.ERROR, ExceptionUtils.getStackTrace(ex))); return resFuture; //something broke, halt further codes } } if (url == null) throw new NoSuchElementException(); load(user, url, (n, l) -> { if(l.isEmpty()) { resFuture.complete(new CommandResult(CommandResultType.NORESULT)); return; } if (l.size() > 100) { resFuture.complete(new CommandResult(CommandResultType.INVALIDARGS, "Cannot queue in a playlist of more than 100 tracks.")); return; } if(!user.getVoiceState().inAudioChannel()) { //have to check here for pending to always work even though queueTrack would check again resFuture.complete(new CommandResult(CommandResultType.FAILURE, "You are not in a voice channel.")); return; } if((channel.getGuild().getAudioManager().isConnected() && !channel.getGuild().getAudioManager().getConnectedChannel().getId().equals(user.getVoiceState().getChannel().getId()))) { resFuture.complete(new CommandResult(CommandResultType.FAILURE, "You are not in the same channel as the bot.")); return; } if (l.size() > 10 || l.stream().anyMatch(t -> t.getInfo().isStream)) { //put to pending GuildMusicManager mm = getGuildMusicManager(user.getGuild()); int req = (int) Math.ceil(user.getVoiceState().getChannel().getMembers().stream().filter(mem -> !mem.getUser().isBot()).count() / 2.0); if(req > 1 && !DiscordBot.ModID.contains(user.getId())) { if(mm.pending != null) { resFuture.complete(new CommandResult(CommandResultType.FAILURE, "There is already a pending playlist or livestream.")); return; } mm.vote(user.getUser(), "tracks", req); //self vote; should never return -1 (success) coz req > 1 channel.sendMessage("Due to the total duration of your requested tracks, it has been added to pending. It will be automatically removed if it has not been approved by the users in the channel for longer than 1 minute.\n" + "Others in the channel should use `!desp music approve` to vote.").queue(); mm.pending = l; mm.pendingCleanup = ex.schedule(() -> { mm.clearVotes("tracks"); mm.pending = null; mm.pendingCleanup = null; channel.sendMessage(user.getUser().getName() + "'s" + (l.size() > 1 ? " playlist " : " livestream ") + "request has timed out.").queue(); }, 1, TimeUnit.MINUTES); resFuture.complete(new CommandResult(CommandResultType.SUCCESS, "Pending approval")); return; } } try { //if everything passes try queuing int startIndex = queueTracks(l, user) + 1; if (n == null) { //no name == not playlist channel.sendMessage("Adding `" + l.get(0).getInfo().title + "` (" + (l.get(0).getDuration() == Long.MAX_VALUE ? "N/A" : l.get(0).getUserData(TrackData.class).getFormattedDuration()) + ") to the queue. [`" + startIndex + "`]").queue(); } else { channel.sendMessage("Adding playlist `" + n + "` to the queue, queue now has a total of `" + (startIndex + l.size() - 1) + "` tracks.").queue(); channel.sendMessage((startIndex == 1 ? "Playing `" : "First track: `") + l.get(0).getInfo().title + "` (" + l.get(0).getUserData(TrackData.class).getFormattedDuration() + ") [`" + startIndex + "`].").queue(); } resFuture.complete(new CommandResult(CommandResultType.SUCCESS)); } catch (UnsupportedOperationException e) { resFuture.complete(new CommandResult(CommandResultType.FAILURE, e.getMessage())); } }, (ex) -> resFuture.complete(ex.getStackTrace()[0].getMethodName().equals("readPlaylistName") ? new CommandResult(CommandResultType.FAILURE, "Cannot read the playlist specified. Is it private?") : new CommandResult(CommandResultType.ERROR, ExceptionUtils.getStackTrace(ex)))); return resFuture; } private String fetchUrlFromSearch(String search, String type) throws IOException { if (type.startsWith("youtube")) { type = type.substring(8, type.length()); if (type.equals("video")) { return "ytsearch:" + search; } else { //scrape with our own code since YoutubeSearchProvider only scrapes videos //NOADD check if theres a way to search for playlists and vids at the same time //using different commands now try (HttpInterface httpInterface = httpInterfaceManager.getInterface()) { URI url = new URIBuilder("https://www.youtube.com/results") //sp is filter param, EgIQAw== is the base64 encoding of playlist option .addParameter("search_query", search).addParameter("sp", "EgIQAw==").build(); try (CloseableHttpResponse response = httpInterface.execute(new HttpGet(url))) { //connection code borrowed from lavaplayer's YoutubeSearchProvider int statusCode = response.getStatusLine().getStatusCode(); if (!HttpClientTools.isSuccessWithContent(statusCode)) { throw new IOException("Invalid status code for search response: " + statusCode); } //start parsing String data = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); data = data.substring(data.indexOf("var ytInitialData = ") + 20); JSONObject result = new JSONObject(new JSONTokener(data.substring(0, data.indexOf(";")))) .getJSONObject("contents").getJSONObject("twoColumnSearchResultsRenderer").getJSONObject("primaryContents") .getJSONObject("sectionListRenderer").getJSONArray("contents").getJSONObject(0).getJSONObject("itemSectionRenderer"); //iterate to get first playlist for(Object obj : result.getJSONArray("contents")) { JSONObject renderer = (JSONObject) obj; - if(renderer.has("playlistRenderer")) { - return "https://www.youtube.com" + renderer.getJSONObject("playlistRenderer").getJSONObject("navigationEndpoint") - .getJSONObject("commandMetadata").getJSONObject("webCommandMetadata").getString("url"); //return first found + if(renderer.has("lockupViewModel")) { + //return first found + return "https://www.youtube.com/playlist?list=" + renderer.getJSONObject("lockupViewModel").getString("contentId"); } } return null; //if no result } } catch (URISyntaxException e) { e.printStackTrace(); //should be unreachable } } } else if (type.equals("soundcloud")) { return "scsearch:" + search; } throw new UnsupportedOperationException("This provider is not implemented yet!"); } //package private void load(Member user, String url, BiConsumer> resultHandler, Consumer exceptionally) { playerManager.loadItemOrdered(getGuildMusicManager(user.getGuild()), url, new AudioLoadResultHandler() { @Override public void trackLoaded(AudioTrack track) { try { track.setUserData(new TrackData(track.getInfo().uri, user.getUser(), track.getDuration())); resultHandler.accept(null, Arrays.asList(track)); } catch (Exception e) { exceptionally.accept(e); //so i dont lose my sanity over silenced errors } } @Override public void playlistLoaded(AudioPlaylist playlist) { try { if(playlist.getTracks().size() == 0) { //somehow its possible; do the same as noResult() if(url.startsWith("ytsearch:")) load(user, url.replaceFirst("yt", "sc"), resultHandler, exceptionally); //searches in soundcloud, since apparently yt pretty frequently returns no result else resultHandler.accept(null, new ArrayList<>()); return; } String plName = playlist.getName(); List tracks = playlist.getTracks(); String plId = ""; if(playlist.isSearchResult()) { tracks = tracks.subList(0, 1); //only get first result if search plName = null; //no actual playlist name } else { if(url.contains("://soundcloud.com") || url.contains("://www.youtube.com")) //add pl id if is playlist plId = url.contains("://soundcloud.com") ? "?in=" + url.split("soundcloud.com/")[1] : "&list=" + url.split("list=")[1].split("&")[0]; } for (AudioTrack track : tracks) //TODO tell users that we skipped some tracks? if(track != null) track.setUserData(new TrackData(track.getInfo().uri + plId, user.getUser(), track.getDuration())); if (playlist.getSelectedTrack() != null) tracks.add(0, tracks.remove(tracks.indexOf(playlist.getSelectedTrack()))); //shift selected track to first track resultHandler.accept(plName, tracks.stream().filter(t -> t != null).collect(Collectors.toList())); } catch (Exception e) { exceptionally.accept(e); //so i dont lose my sanity over silenced errors } } @Override public void noMatches() { if(url.startsWith("ytsearch:")) load(user, url.replaceFirst("yt", "sc"), resultHandler, exceptionally); //searches in soundcloud, since apparently yt pretty frequently returns no result else resultHandler.accept(null, new ArrayList<>()); } @Override public void loadFailed(FriendlyException exception) { if((exception.getMessage() != null && exception.getMessage().contains("Unknown file format.")) && url.contains("open.spotify.com")) { resultHandler.accept(null, new ArrayList<>()); //TODO TEMPORARY FIX } else { exceptionally.accept(exception.getCause() != null ? exception.getCause() : exception); } } }); } public int queueTracks(List tracks, Member user) throws UnsupportedOperationException { Guild guild = user.getGuild(); GuildMusicManager musicManager = getGuildMusicManager(guild); int startIndex = musicManager.scheduler.getQueueSize() + (musicManager.player.getPlayingTrack() != null ? 1 : 0); if (user.getVoiceState().inAudioChannel()) { if (!guild.getAudioManager().isConnected()) { VoiceChannel voice = user.getVoiceState().getChannel().asVoiceChannel(); if (PermissionUtil.checkPermission(voice, guild.getSelfMember(), Permission.VOICE_CONNECT, Permission.VOICE_SPEAK)) { guild.getAudioManager().openAudioConnection(voice); //already checked permissions so no need to try catch } else { throw new UnsupportedOperationException("The bot cannot play music in that channel."); } } } else { throw new UnsupportedOperationException("You are currently not in a voice channel."); } try { if (!guild.getAudioManager().isConnected()) { Awaitility.await().atMost(3, TimeUnit.SECONDS).until(() -> guild.getAudioManager().isConnected()); } } catch (ConditionTimeoutException e) { throw new UnsupportedOperationException("Error while connecting to voice channel: The connection timed out."); } if (guild.getAudioManager().getConnectedChannel().equals(user.getVoiceState().getChannel())) { for (AudioTrack track : tracks) musicManager.scheduler.queue(track); //nulls should already be handled; if it aint its my fault lmao } else { throw new UnsupportedOperationException("You are currently not in the same channel as the bot."); } return startIndex; //if it successfully returned it means that nothing failed } public String skipTrack(Guild guild) { GuildMusicManager musicManager = getGuildMusicManager(guild); musicManager.scheduler.nextTrack(); musicManager.player.setPaused(false); //implicit resume try { return musicManager.player.getPlayingTrack().getInfo().title; } catch (NullPointerException e) { musicManager.scheduler.loop = null; return null; } } public String setTrackPosition(Guild guild, long hour, long min, long sec, String rel) throws IllegalArgumentException { GuildMusicManager mm = getGuildMusicManager(guild); Long millis = TimeUnit.HOURS.toMillis(hour) + TimeUnit.MINUTES.toMillis(min) + TimeUnit.SECONDS.toMillis(sec); AudioTrack track = mm.player.getPlayingTrack(); if(!rel.isEmpty()) millis = track.getPosition() + (rel.equals("-") ? -millis : millis); if (track.getDuration() > millis && !track.getInfo().isStream) { track.setPosition(millis); return MiscUtils.convertMillis(track.getPosition()); } else if (track.getInfo().isStream) { throw new IllegalArgumentException("You cannot set the track time in a stream!"); } else { throw new IllegalArgumentException("You cannot set the track time over the track duration."); } } //not zero-based public MessageCreateBuilder getTrackInfo(Guild guild, int index) { //TODO add views, etc by storing them when getting with lavaplayer? GuildMusicManager mm = getGuildMusicManager(guild); if(index - 1 > mm.scheduler.getQueueSize() || index < 1) return null; AudioTrack track = index == 1 ? mm.player.getPlayingTrack() : mm.scheduler.findTracks(index - 1, 1).get(0); TrackData data = track.getUserData(TrackData.class); MessageCreateBuilder smsg = new MessageCreateBuilder(); String fpos = MiscUtils.convertMillis(track.getPosition()); String fdur = data.getFormattedDuration(); smsg.addContent((index == 1 ? "Current" : MiscUtils.ordinal(index)) + " track: `" + track.getInfo().title + "` (" + fpos + "/" + (track.getDuration() == Long.MAX_VALUE ? "???" : fdur) + ")\n"); smsg.addContent("Author: " + track.getInfo().author + "\n"); smsg.addContent("Requested by: `" + data.getUserWithDiscriminator() + "`\n"); String timeTag = ""; if(data.getUrl().startsWith("https://www.youtube.com")) timeTag = "&="; else if(data.getUrl().startsWith("https://soundcloud.com")) timeTag = "#="; smsg.addContent("URL: " + data.getUrl() + (timeTag.isEmpty() ? "" : timeTag + TimeUnit.MILLISECONDS.toSeconds(track.getPosition()))); return smsg; } //TODO migrate to embed? public MessageCreateBuilder queueCheck(Guild guild, int page) throws IllegalArgumentException { GuildMusicManager mm = getGuildMusicManager(guild); AudioTrack playing = mm.player.getPlayingTrack(); if(playing == null) return null; MessageCreateBuilder smsg = new MessageCreateBuilder(); List tracks = mm.scheduler.findTracks(1, Integer.MAX_VALUE).stream().filter(a -> a != null).collect(Collectors.toList()); //get all tracks in queue tracks.add(0, playing); int maxPage = (int) Math.ceil(tracks.size() / 10f); if(page > maxPage) throw new IllegalArgumentException("There is no such page."); smsg.addContent("The current queue (page " + page + "/" + maxPage + "): \n"); if (mm.scheduler.loop != null) { smsg.addContent("There is a total of `" + tracks.size() + "` tracks " + (mm.scheduler.loop.equals("loop") ? "looping" : "in autoplay") + ".\n\n"); } else { long millis = 0; for(AudioTrack track : tracks) millis += track.getDuration(); smsg.addContent("There is a total of `" + tracks.size() + "` tracks queued" + ((millis == Long.MAX_VALUE || millis < 0) ? ".\n\n" : ", with a total duration of `" + MiscUtils.convertMillis(millis - playing.getPosition()) + "`.\n\n")); } int times = (page - 1) * 10; for (AudioTrack track : tracks.subList((page - 1) * 10, Math.min(tracks.size(), page * 10))) { times++; TrackData data = track.getUserData(TrackData.class); smsg.addContent("[" + times + "]: `" + track.getInfo().title + "` (" + (track.getDuration() == Long.MAX_VALUE ? "N/A" : data.getFormattedDuration()) + ") requested by `" + data.getUserWithDiscriminator() + "`\n"); } if(maxPage > page) smsg.addContent("\nDo `!desp music queue " + (page + 1) + "` to see the next page."); return smsg; } public boolean togglePause(Guild guild, boolean pause) throws IllegalStateException { GuildMusicManager mm = getGuildMusicManager(guild); if (mm.player.isPaused() == !pause) { mm.player.setPaused(pause); return mm.player.isPaused(); } else { throw new IllegalStateException("The player is already " + (mm.player.isPaused() ? "paused!" : "unpaused!")); } } public boolean toggleLoopQueue(Guild guild, String type) { type = type.toLowerCase(); GuildMusicManager mm = getGuildMusicManager(guild); if (mm.scheduler.loop == null || !mm.scheduler.loop.equals(type)) { mm.scheduler.loop = type; if (type != null && type.equals("autoplay") && mm.scheduler.getQueueSize() < 1) { mm.scheduler.queueAutoplay(mm.player.getPlayingTrack()); } return true; } else { //remove autoplay queued track when disabling autoplay? if (mm.scheduler.loop.equals("autoplay") && mm.scheduler.getQueueSize() == 1 && mm.scheduler.findTracks(1, 1).get(0).getUserData(TrackData.class).uDis.equals("Autoplay")) { //including autoplay, theres only 2 tracks; only remove tracks that is autoplayed mm.scheduler.removeTrack(1); } mm.scheduler.loop = null; return false; } } public void stopAndClearQueue(Guild guild) { GuildMusicManager mm = getGuildMusicManager(guild); mm.pending = null; mm.pendingCleanup = null; mm.clearQueueCleanup = null; mm.scheduler.loop = null; mm.scheduler.clearSchedulerQueue(); mm.clearAllVotes(); mm.player.stopTrack(); mm.player.setPaused(false); guild.getAudioManager().closeAudioConnection(); } //should ALWAYS be called before discarding this instance public void shutdown() { musicManagers.forEach((s, mm) -> { //System.out.println(DiscordBot.mainJDA.getGuildById(s).getName()); mm.player.destroy(); mm.scheduler.clearSchedulerQueue(); AudioManager man = DiscordBot.mainJDA.getGuildById(s).getAudioManager(); if(man.isConnected()) { man.closeAudioConnection(); DiscordBot.lastMusicCmd.get(s).sendMessage("The music bot is going into maintenance and it will now disconnect. Sorry for the inconvenience.").queue(); } }); musicManagers = null; //so further operations wont be possible even if i forgot to set this instance to null playerManager.shutdown(); ex.shutdown(); } } diff --git a/src/me/despawningbone/discordbot/command/music/Music.java b/src/me/despawningbone/discordbot/command/music/Music.java index d59a224..166f201 100644 --- a/src/me/despawningbone/discordbot/command/music/Music.java +++ b/src/me/despawningbone/discordbot/command/music/Music.java @@ -1,680 +1,626 @@ package me.despawningbone.discordbot.command.music; import java.awt.Color; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.safety.Whitelist; import org.jsoup.select.Elements; import com.google.common.base.Splitter; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import me.despawningbone.discordbot.DiscordBot; import me.despawningbone.discordbot.command.Command; import me.despawningbone.discordbot.command.CommandResult; import me.despawningbone.discordbot.command.CommandResult.CommandResultType; import me.despawningbone.discordbot.command.music.AudioTrackHandler.TrackData; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel; import net.dv8tion.jda.api.managers.AudioManager; @SuppressWarnings("deprecation") public class Music extends Command { private AudioTrackHandler handler; public Music() { this.alias = Arrays.asList("m"); this.desc = "The music sub-bot!"; this.usage = ""; this.handler = new AudioTrackHandler(); //DONE merge p, pl and ps? registerSubCommand("play", Arrays.asList("p"), (c, u, m, a) -> { List params = new ArrayList<>(Arrays.asList(a)); String type = params.removeAll(Collections.singleton("-s")) ? "soundcloud" : "youtube " + (params.removeAll(Collections.singleton("-l")) ? "playlist" : "video"); if(a.length < 1) return new CommandResult(CommandResultType.INVALIDARGS, "Please enter something to search or an URL to play."); try { return handler.searchAndPlay(String.join(" ", params), type, c.getGuild().getMember(u), c).get(); } catch (NoSuchElementException e) { return new CommandResult(CommandResultType.NORESULT); } catch (InterruptedException | ExecutionException e) { return new CommandResult(CommandResultType.ERROR, ExceptionUtils.getStackTrace(e)); } }, "[-s/-l] ", Arrays.asList("despacito", "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "-l tpz sega", "-s asymmetry reol"), "Queue some music to play!", Arrays.asList( " * this also supports all opus streams and common audio format as long as you provide the url.", " * you can specify `-s` when searching to search soundcloud instead of youtube,", " * or `-l` to search for youtube playlists instead.")); //TODO merge? i dont think it can be though //TODO guild config for non restricted loop/autoplay registerSubCommand("autoplay", Arrays.asList("ap"), (c, u, m, a) -> { VoiceChannel vc = c.getGuild().getAudioManager().getConnectedChannel().asVoiceChannel(); if (vc.getMembers().size() <= 2 || DiscordBot.ModID.contains(u.getId())) { c.sendMessage("Autoplay mode toggled " + (handler.toggleLoopQueue(c.getGuild(), "autoplay") ? "on.\nIt will end once someone joins the music channel." : "off.")) .queue(); return new CommandResult(CommandResultType.SUCCESS); } else { return new CommandResult(CommandResultType.INVALIDARGS, "You are currently not alone in the music channel, therefore this feature is disabled."); } }, "", null, "Auto-queues related tracks when you are alone!", Arrays.asList(" * Currently only works if the last track in the queue is a youtube video.", " Note: it will autoplay indefinitely until you toggle it again or someone joins.")); registerSubCommand("loop", Arrays.asList("l", "loopqueue"), (c, u, m, a) -> { VoiceChannel vc = c.getGuild().getAudioManager().getConnectedChannel().asVoiceChannel(); if (vc.getMembers().size() <= 2 || DiscordBot.ModID.contains(u.getId())) { c.sendMessage("Looping mode toggled " + (handler.toggleLoopQueue(c.getGuild(), "loop") ? "on.\nIt will end once someone joins the music channel." : "off.")) .queue(); return new CommandResult(CommandResultType.SUCCESS); } else { return new CommandResult(CommandResultType.INVALIDARGS, "You are currently not alone in the music channel, therefore this feature is disabled."); } }, "", null, "Loop the queue indefinitely if you are alone!", Arrays.asList(" Note: skipping tracks will remove it from the loop too.")); registerSubCommand("approve", Arrays.asList("a"), (c, u, m, a) -> { GuildMusicManager mm = handler.getGuildMusicManager(c.getGuild()); if (mm.pending == null) { return new CommandResult(CommandResultType.FAILURE, "There is currently no pending playlists/livestreams."); } Member requester = c.getGuild().getMemberByTag(mm.pending.get(0).getUserData(TrackData.class).getUserWithDiscriminator()); VoiceChannel vc = c.getGuild().getAudioManager().getConnectedChannel().asVoiceChannel(); if(vc == null) vc = requester.getVoiceState().getChannel().asVoiceChannel(); //fallback to requester, usually due to bot not joined yet (first track needs approval) if(vc == null) vc = c.getGuild().getMember(u).getVoiceState().getChannel().asVoiceChannel(); //fallback to approver in case requester left voice channel try { int req = (int) Math.ceil(vc.getMembers().stream().filter(mem -> !mem.getUser().isBot()).count() / 2.0); List tracks = mm.pending; //have to place before vote or else it gets wiped int votes = mm.vote(u, "tracks", req); if (votes == -1) { //automatically cleaned up in guildmusicmanager already c.sendMessage("Pending playlist/livestream approved. Queuing...").queue(); handler.queueTracks(tracks, requester); } else { c.sendMessage("You voted for the pending playlist! (" + votes + "/"+ req + ")").queue(); } return new CommandResult(CommandResultType.SUCCESS); } catch(UnsupportedOperationException e) { return new CommandResult(CommandResultType.FAILURE, e.getMessage()); } }, "", null, "Approve the pending playlist or livestream.", null); registerSubCommand("skip", Arrays.asList("s"), (c, u, m, a) -> { TrackData track = handler.getGuildMusicManager(c.getGuild()).player.getPlayingTrack().getUserData(TrackData.class); if(!u.getAsTag().equals(track.getUserWithDiscriminator())) { VoiceChannel vc = c.getGuild().getAudioManager().getConnectedChannel().asVoiceChannel(); int req = (int) Math.ceil(vc.getMembers().stream().filter(mem -> !mem.getUser().isBot()).count() / 2.0); try { int votes = track.voteSkip(u, req); if (votes != -1) { c.sendMessage("You voted to skip the current track! (" + votes + "/" + req + ")").queue(); return new CommandResult(CommandResultType.SUCCESS); } } catch (UnsupportedOperationException e) { return new CommandResult(CommandResultType.INVALIDARGS, e.getMessage()); } } //else skips track if no need votes or vote passed String next = handler.skipTrack(c.getGuild()); if(next != null) { c.sendMessage("Skipped to the next track: `" + next + "`.").queue(); } else { c.sendMessage("No tracks found after this one. Stopping the player...").queue(); } return new CommandResult(CommandResultType.SUCCESS); }, "", null, "Vote to skip the currently playing track.", Arrays.asList(" * this is equivalent to `forceskip` if you are the one who requested the track.")); //TODO merge? i dont think i can either though registerSubCommand("forceskip", Arrays.asList("fs"), (c, u, m, a) -> { String next = handler.skipTrack(c.getGuild()); if(next != null) { c.sendMessage("Skipped to the next track: `" + next + "`.").queue(); } else { c.sendMessage("No tracks found after this one. Stopping the player...").queue(); } return new CommandResult(CommandResultType.SUCCESS); }, "", null, "Skip the currently playing track without voting.", null, EnumSet.of(Permission.VOICE_MOVE_OTHERS), -BotUserLevel.BOT_MOD.ordinal()); registerSubCommand("info", Arrays.asList("i", "trackinfo", "track", "nowplaying", "np", "current", "c"), (c, u, m, a) -> { try { c.sendMessage(handler.getTrackInfo(c.getGuild(), a.length > 0 ? Integer.parseInt(a[0]) : 1).build()).queue(); return new CommandResult(CommandResultType.SUCCESS); } catch(NumberFormatException | NullPointerException e) { return new CommandResult(CommandResultType.INVALIDARGS, "Invalid track index specified."); } }, "[index]", Arrays.asList("", "2"), "See the info about a track in the queue.", Arrays.asList(" * If you did not specify an index, it will return info about the current track playing.")); registerSubCommand("queue", Arrays.asList("q", "page", "list"), (c, u, m, a) -> { try { c.sendMessage(handler.queueCheck(c.getGuild(), a.length > 0 ? Integer.parseInt(a[0]) : 1).build()).queue(); return new CommandResult(CommandResultType.SUCCESS); } catch(NumberFormatException e) { return new CommandResult(CommandResultType.INVALIDARGS, "Invalid page index specified."); } catch(IllegalArgumentException e) { return new CommandResult(CommandResultType.INVALIDARGS, e.getMessage()); } }, "[page]", Arrays.asList("", "2"), "See the queue of tracks to play.", Arrays.asList(" * If you did not specify an page number, it will return the first page.")); //TODO allow pausing when alone? unpause when people join; or vote system? //TODO yet another merge lmao but this time idk coz rythm has them as seperate commands registerSubCommand("pause", Arrays.asList("pa"), (c, u, m, a) -> { try { handler.togglePause(c.getGuild(), true); c.sendMessage("Successfully paused the player.").queue(); return new CommandResult(CommandResultType.SUCCESS); } catch(IllegalStateException e) { return new CommandResult(CommandResultType.INVALIDARGS, e.getMessage()); } }, "", null, "Pauses the music player.", null, EnumSet.of(Permission.VOICE_MOVE_OTHERS), BotUserLevel.DEFAULT.ordinal()); registerSubCommand("resume", Arrays.asList("re", "unpause"), (c, u, m, a) -> { try { handler.togglePause(c.getGuild(), false); c.sendMessage("Successfully resumed the player.").queue(); return new CommandResult(CommandResultType.SUCCESS); } catch(IllegalStateException e) { return new CommandResult(CommandResultType.INVALIDARGS, e.getMessage()); } }, "", null, "Resumes the music player.", null, EnumSet.of(Permission.VOICE_MOVE_OTHERS), BotUserLevel.DEFAULT.ordinal()); registerSubCommand("setposition", Arrays.asList("set", "setpos", "seek"), (c, u, m, a) -> { try { String[] s = a[0].split("(?<=[+-])"); //get type of relative pos; only first +/- is used and consecutive +/-s get ignored String[] t = s[s.length - 1].split(":"); int index = t.length > 2 ? 1 : 0; String setT = handler.setTrackPosition(c.getGuild(), index == 1 ? Long.parseLong(t[0]) : 0 , Long.parseLong(t[index]), Long.parseLong(t[index + 1]), s.length == 1 ? "" : s[0]); c.sendMessage("Successfully set the timestamp to `" + setT + "`.").queue(); return new CommandResult(CommandResultType.SUCCESS); } catch (IndexOutOfBoundsException | NumberFormatException e) { return new CommandResult(CommandResultType.INVALIDARGS, "Please enter a valid timestamp with colons."); } catch (IllegalArgumentException e) { return new CommandResult(CommandResultType.INVALIDARGS, e.getMessage()); } }, "[+/-][hr:]", Arrays.asList("4:52:21", "2:00", "+30:00", "-1:23:45"), "Set the playing position in the current track!", Arrays.asList("timestamps without signs are absolute, whereas `+`/`-` means go forward or backward from the current position for the amount of time specified respectively.", " * the person who requested the current track can always set the position, regardless of perms."), EnumSet.of(Permission.VOICE_MOVE_OTHERS), -BotUserLevel.BOT_MOD.ordinal()); //TODO merge with skip? registerSubCommand("removetrack", Arrays.asList("rt", "r", "skiptrack", "st"), (c, u, m, a) -> { if(a.length > 0) { try { int num = Integer.parseInt(a[0]); if(num == 1) return new CommandResult(CommandResultType.INVALIDARGS, "You cannot remove the current track from the queue with this command. Use !desp music skip instead."); if(num < 1) return new CommandResult(CommandResultType.INVALIDARGS, "The index you entered is invalid."); AudioTrack removed = handler.getGuildMusicManager(c.getGuild()).scheduler.removeTrack(num - 1); if(removed != null) { c.sendMessage("Removed track `" + removed.getInfo().title + "` requested by `" + removed.getUserData(TrackData.class).getUserWithDiscriminator() + "`.").queue(); return new CommandResult(CommandResultType.SUCCESS); } else { return new CommandResult(CommandResultType.INVALIDARGS, "The track does not exist."); } } catch(NumberFormatException e) { return new CommandResult(CommandResultType.INVALIDARGS, "Please enter a valid index number."); } } else { return new CommandResult(CommandResultType.INVALIDARGS, "Please enter an index."); } }, "", null, "Remove a track at the specified index of the queue.", Arrays.asList(" * the person who requested the track which is to be removed can always execute the command, regardless of perms."), EnumSet.of(Permission.VOICE_MOVE_OTHERS), -BotUserLevel.BOT_MOD.ordinal()); registerSubCommand("move", Arrays.asList("m", "movetrack"), (c, u, m, a) -> { try { if(a[0].equals("1") || a[1].equals("1")) return new CommandResult(CommandResultType.INVALIDARGS, "You cannot move the currently playing track."); AudioTrack track = handler.getGuildMusicManager(c.getGuild()).scheduler.moveTrack(Integer.parseInt(a[0]) - 2, Integer.parseInt(a[1]) - 2); c.sendMessage("Successfully moved `" + track.getInfo().title + "` to position `" + a[1] + "`.").queue(); return new CommandResult(CommandResultType.SUCCESS); } catch(IndexOutOfBoundsException | NumberFormatException | NullPointerException e) { return new CommandResult(CommandResultType.INVALIDARGS, "Please valid indices."); } }, " ", Arrays.asList("2 3"), "Move a track to the specified index.", Arrays.asList(" * you can also run this command regardless of perms if you are alone with the bot.") , EnumSet.of(Permission.VOICE_MOVE_OTHERS), -BotUserLevel.BOT_MOD.ordinal()); //TODO make vote system for this registerSubCommand("shuffle", null, (c, u, m, a) -> { VoiceChannel vc = c.getGuild().getAudioManager().getConnectedChannel().asVoiceChannel(); if (vc.getMembers().size() <= 2 || DiscordBot.ModID.contains(u.getId())) { handler.getGuildMusicManager(c.getGuild()).scheduler.shuffleQueue(); c.sendMessage("Successfully shuffled the queue.").queue(); return new CommandResult(CommandResultType.SUCCESS); } else { return new CommandResult(CommandResultType.INVALIDARGS, "You are currently not alone in the music channel, therefore this feature is disabled."); } }, "", null, "Shuffle the tracks in the queue when you are alone!", null); //TODO make vote system for this registerSubCommand("clear", Arrays.asList("disconnect", "dc", "stop", "clearqueue"), (c, u, m, a) -> { handler.stopAndClearQueue(c.getGuild()); c.sendMessage("The queue has been cleared.").queue(); return new CommandResult(CommandResultType.SUCCESS); }, "", null, "Clear the queue and stop the player.", Arrays.asList(" * you can also run this command regardless of perms if you are alone with the bot.") , EnumSet.of(Permission.VOICE_MUTE_OTHERS, Permission.VOICE_MOVE_OTHERS), -BotUserLevel.BOT_MOD.ordinal()); registerSubCommand("lyrics", Arrays.asList("ly"), (c, u, m, a) -> { c.sendTyping().queue(); try { String search = a.length > 0 ? String.join(" ", a) : handler.getGuildMusicManager(c.getGuild()).player.getPlayingTrack().getInfo().title - .split("ft.")[0].replaceAll("\\(.*?\\)", "") + .split("ft\\.")[0].replaceAll("\\(.*?\\)", "") .replaceAll("\\[.*?\\]", "") .replaceAll("\\ใ€.*?\\ใ€‘", "") + .replaceAll("/", " ") .replaceAll("-", "").trim(); getLyrics(search).forEach(em -> c.sendMessageEmbeds(em).queue()); return new CommandResult(CommandResultType.SUCCESS); } catch(IllegalArgumentException | UnsupportedOperationException e) { return new CommandResult(CommandResultType.FAILURE, e.getMessage()); } catch(NullPointerException e) { return new CommandResult(CommandResultType.INVALIDARGS, "There is nothing playing currently! Please specify a song title to search the lyrics up."); } catch(IOException e) { return new CommandResult(CommandResultType.ERROR, ExceptionUtils.getStackTrace(e)); } }, "[search words]", Arrays.asList(""), "Search some lyrics up!", Arrays.asList(" * if you did not specify any search words, the bot will try to fetch the lyrics of the current track playing, if any.")); //TODO equalizer persistence? //make this premium? registerSubCommand("equalizer", Arrays.asList("eq"), (c, u, m, a) -> { GuildMusicManager mm = handler.getGuildMusicManager(c.getGuild()); Float[] vals; if(a.length == 0) { vals = mm.getCurrentGain(); } else { try { try { if(a.length != 15) throw new NumberFormatException(); vals = new Float[15]; for(int i = 0; i < a.length; i++) { vals[i] = Float.parseFloat(a[i]); } mm.setGain(0, vals); } catch(NumberFormatException e) { vals = mm.setPresetGain(a[0]); } } catch(IllegalArgumentException e2) { return new CommandResult(CommandResultType.INVALIDARGS, e2.getMessage()); } } //formatting DecimalFormat df = new DecimalFormat("0.00"); df.setPositivePrefix("+"); EmbedBuilder eb = new EmbedBuilder(); eb.setTitle("Current equalizer graph"); eb.appendDescription("```\n"); for(double line = 0.25; line >= -0.25; line -= 0.05) { eb.appendDescription(df.format(line) + " "); for(int band = 0; band < 15; band++) { if(Math.abs(0.05 * Math.round(vals[band] / 0.05) - line) < 1E-7) eb.appendDescription("๐Ÿ”˜"); else eb.appendDescription("โ€†โ˜ "); } eb.appendDescription("\n"); } eb.appendDescription("```"); eb.addField("Actual values", Arrays.asList(vals).stream().map(f -> df.format(f)).collect(Collectors.joining(" ")), false); c.sendMessageEmbeds(eb.build()).queue(); return new CommandResult(CommandResultType.SUCCESS); }, "[bandvalues/presetname]", Arrays.asList("", "0.09 0.07 0.07 0.01 0 0 -0.02 -0.02 0.03 0.03 0.05 0.07 0.09 0.1 0.1", "bassboost"), "Sets the equalizer for the music player in this guild!", Arrays.asList("Accepts 15 bands with values ranging from -0.25 to 0.25, where -0.25 is muted and 0.25 is double volume.", "* presets include: `bassboost`, `default`, `rock`.", "Input nothing to return the current settings.", "", "Note: you might experience some audio cracking for band values >0.1, since amplifying volumes remotely does not work well.", "It is recommended to use values from -0.25 to 0.1, and turning discord volume up instead.") , EnumSet.of(Permission.VOICE_MUTE_OTHERS, Permission.VOICE_MOVE_OTHERS), -BotUserLevel.BOT_MOD.ordinal()); registerSubCommand("shutdown", null, (c, u, m, a) -> { handler.shutdown(); handler = null; c.sendMessage("Successfully destroyed the music player instance.").queue(); return new CommandResult(CommandResultType.SUCCESS); }, "", null, "Shuts down the music player sub-bot.", null, EnumSet.noneOf(Permission.class), BotUserLevel.BOT_OWNER.ordinal()); registerSubCommand("startup", Arrays.asList("start"), (c, u, m, a) -> { if(handler != null) return new CommandResult(CommandResultType.FAILURE, "An instance is already running. Please shut it down first."); else handler = new AudioTrackHandler(); c.sendMessage("Successfully created the music player instance.").queue(); return new CommandResult(CommandResultType.SUCCESS); }, "", null, "Boots up the music player sub-bot.", null, EnumSet.noneOf(Permission.class), BotUserLevel.BOT_OWNER.ordinal()); registerSubCommand("restart", Arrays.asList("reboot"), (c, u, m, a) -> { handler.shutdown(); handler = new AudioTrackHandler(); c.sendMessage("Successfully rebooted the music player instance.").queue(); return new CommandResult(CommandResultType.SUCCESS); }, "", null, "Reboots the music player sub-bot.", null, EnumSet.noneOf(Permission.class), BotUserLevel.BOT_OWNER.ordinal()); } public AudioTrackHandler getAudioTrackHandler() { return handler; } //TODO make a skipuntil command that requires voting? //prob not //TODO make clear accessible on vote? @Override public CommandResult execute(TextChannel channel, User author, Message msg, String[] args) { DiscordBot.lastMusicCmd.put(channel.getGuild().getId(), channel); Command sub = args.length > 0 ? getSubCommand(args[0].toLowerCase()) : null; if(sub != null) { //only run if not null, else hand to normal sub command handler //if handler is null it means the music player is shut down if(!sub.getName().equals("startup")) { if(handler == null) return new CommandResult(CommandResultType.FAILURE, "The music bot is in maintenance right now!"); //pre check to block out all music commands if the player is not running List exception = Arrays.asList("play", "approve", "shutdown", "lyrics", "equalizer"); GuildMusicManager mm = handler.getGuildMusicManager(channel.getGuild()); if(mm.player.getPlayingTrack() == null && !exception.contains(sub.getName())) return new CommandResult(CommandResultType.INVALIDARGS, "There are no tracks playing currently."); else { //else block out all users that are not in the same voice channel exception = Arrays.asList("lyrics", "queue", "info"); AudioManager man = channel.getGuild().getAudioManager(); if(man.isConnected() && !man.getConnectedChannel().getMembers().contains(channel.getGuild().getMember(author)) && !(exception.contains(sub.getName()) || DiscordBot.ModID.contains(author.getId()))) { return new CommandResult(CommandResultType.INVALIDARGS, "You are not in the same channel as the bot."); } } //perms overriding for queuer if(Arrays.asList("forceskip", "skip", "setposition").contains(sub.getName())) { if(author.getAsTag().equals(mm.player.getPlayingTrack().getUserData(TrackData.class).getUserWithDiscriminator())) return sub.execute(channel, author, msg, Arrays.copyOfRange(args, 1, args.length)); } else if(sub.getName().equals("removetrack")) { try { if(author.getAsTag().equals(mm.scheduler.findTracks(Integer.parseInt(args[1]) - 1, 1).get(0).getUserData(TrackData.class).getUserWithDiscriminator())) return sub.execute(channel, author, msg, Arrays.copyOfRange(args, 1, args.length)); } catch(Exception ignored) { ignored.printStackTrace(); } } //perms overriding for when alone if(Arrays.asList("move", "clear").contains(sub.getName())) { //should always be connected to vc if(channel.getGuild().getAudioManager().getConnectedChannel().getMembers().size() == 2) { //alone; no need to check if the other member is requester, since its checked before return sub.execute(channel, author, msg, Arrays.copyOfRange(args, 1, args.length)); } } } } CommandResult res = super.execute(channel, author, msg, args); //pass to subcommand handler for perms checking if(res.getResultType() == CommandResultType.NOPERMS && Arrays.asList("forceskip", "skip", "setposition", "removetrack").contains(sub.getName())) { //add back info to command result res = new CommandResult(CommandResultType.INVALIDARGS, res.getMessage().getContent().split(" to execute")[0] + ", or have requested the track to execute this command."); } return res; } //maybe move the lyrics stuff elsewhere? private final String geniusAuth = DiscordBot.tokens.getProperty("genius"); //annotated usually isnt actual lyrics, but the following are known to be some private List whitelist = Arrays.asList("https://genius.com/Noma-jpn-brain-power-annotated"); //private ExecutorService executor = Executors.newCachedThreadPool(); //unfortunately i need to finish the api search to get the url to start the html scrape, which means i cannot use future for multithread here public List getLyrics(String search) throws IOException { //DONE dont splice words between embeds; make whole sentence to be spliced instead //System.out.println(search); JSONObject main = null; try { URLConnection searchCon = new URL("https://api.genius.com/search?access_token=" + geniusAuth + "&q=" + URLEncoder.encode(search, "UTF-8").replaceAll("\\+", "%20")).openConnection(); searchCon.addRequestProperty("User-Agent", "Mozilla/4.0"); InputStream searchStream = searchCon.getInputStream(); JSONTokener searchResult = new JSONTokener(searchStream); JSONArray list = new JSONObject(searchResult).getJSONObject("response").getJSONArray("hits"); //get first valid result for(int i = 0; i < list.length(); i++) { JSONObject check = list.getJSONObject(i).getJSONObject("result"); if(!check.getString("url").endsWith("lyrics") && !whitelist.contains(check.getString("url"))) { System.out.println(" " + check.getString("url")); continue; } main = check; break; } searchStream.close(); } catch (JSONException | ArrayIndexOutOfBoundsException e) { e.printStackTrace(); throw new IllegalArgumentException("There were no results unfortunately :cry:"); } if(main == null) { throw new IllegalArgumentException("There were no results unfortunately :cry:"); } //get actual lyrics String url = main.getString("url"); Document document = Jsoup.connect(url).userAgent("Mozilla/4.0").get(); Element html = document.body(); //parse and lint - Element el = html.selectFirst("div[class=\"lyrics\"]"); - String s; - if(el == null) { - el = html.selectFirst("div[class*=\"Lyrics__Root\"]"); //second version of the page - el.select("div[class*=\"Ad__Container\"]").remove(); - el.select("a, span, i, div[class*=\"Lyrics__Container\"]").unwrap(); - el.select("div[class*=\"Lyrics__Footer\"]").remove(); - } else { - el.select("br").append("\\n"); - el.select("p").prepend("\\n\\n"); - } - s = el.html().replaceAll("\\\\n", "\n"); + Element el = html.selectFirst("#lyrics-root"); + el.select("div[class*=\"LyricsHeader-sc\"]").remove(); + el.select("div[class*=\"InreadContainer-sc\"]").remove(); + el.select("div[class*=\"RightSidebar-sc\"]").remove(); + el.select("div[class*=\"LyricsFooter-sc\"]").remove(); + el.select("a, span, i").unwrap(); + el.select("br").append("\\n"); + el.select("p").prepend("\\n\\n"); + String s = el.text().replaceAll("\\\\n", "\n"); String lyrics = Jsoup.clean(s, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false)); //split into lyrics segments List lyList = new ArrayList(Splitter.fixedLength(2000).splitToList( lyrics.trim().replaceAll("&", "&").replaceAll(" ", " ") .replaceAll("\n ", "\n"))); //retain this formatting? it looks more clean yet more jumbled at the same time if(lyList.size() > 5) { //failover catch for whats most likely not lyrics throw new UnsupportedOperationException("The lyrics is too long for a normal song :poop:"); } //build first embed EmbedBuilder eb = new EmbedBuilder(); String auImg = main.getJSONObject("primary_artist").getString("header_image_url"); eb.setAuthor(main.getString("full_title"), url, auImg.contains("https://assets.genius.com/images/default_avatar_300.png") ? null : auImg); String alImg = main.getString("song_art_image_thumbnail_url"); eb.setThumbnail(alImg.contains("https://assets.genius.com/images/default_cover_image.png") ? null : alImg); formatLyrics(eb, "**Lyrics**\n\n " + (lyList.size() > 0 ? lyList.get(0).trim() : "N/A"), lyList, 0); eb.setColor(new Color(255, 255, 100)); //build rest of the embeds List em = new ArrayList(); if(lyList.size() > 1) { em.add(eb.build()); for(int i = 1; i < lyList.size(); i++) { EmbedBuilder loopEm = new EmbedBuilder(); loopEm.setColor(new Color(255, 255, 100)); formatLyrics(loopEm, lyList.get(i), lyList, i); if(i == lyList.size() - 1) { setFinalLyricsEmbed(loopEm, main, html); } em.add(loopEm.build()); } } else { //first and last same embed, thus set final setFinalLyricsEmbed(eb, main, html); em = Arrays.asList(eb.build()); } //System.out.println(lyrics); return em; } //set given embed's description, shifting lyrics to the next embed "page" if overflow private void formatLyrics(EmbedBuilder eb, String segment, List lyList, int i) { if(segment.length() < 2000) { eb.setDescription(segment.trim()); return; } String includeSeg = segment.length() > 2000 ? segment.substring(0, 2000) : segment; int index = includeSeg.lastIndexOf("\n"); eb.setDescription(segment.substring(0, index)); String move = segment.substring(includeSeg.lastIndexOf("\n")); try { if(!move.isEmpty()) lyList.set(i + 1, move + lyList.get(i + 1)); } catch (IndexOutOfBoundsException e) { lyList.add(move); } } //appends metadata portion to the given embed (should be the last one) private void setFinalLyricsEmbed(EmbedBuilder eb, JSONObject main, Element html) { //change the format for the supplementary info in artists and albums from italic to sth else? try { String name = main.getJSONObject("primary_artist").getString("name"); try { String others = html.select("script:containsData(_sf_async_config)").html().split("_sf_async_config.authors = '")[1].split("';")[0].replace(",", ", "); eb.addField("Artists", new StringBuffer(others).insert(others.indexOf(name) + name.length() + 2, "\n*").toString() + "*", true); } catch (IndexOutOfBoundsException e) { eb.addField("Artist", name, true); } } catch (JSONException e) { e.printStackTrace(); eb.addField("Artist", "Unknown", true); } - if(!html.select("div[class=\"lyrics\"]").isEmpty()) { - Elements buffer = html.select("span:contains(Album) ~ span[class=\"metadata_unit-info\"] a"); - - //parse albums - if(buffer.size() > 0) { - String album = buffer.get(0).ownText(); - StringBuilder sb = new StringBuilder(); - JSONObject data = new JSONObject(html.select("script[type=\"application/ld+json\"]").get(0).html()); - data.getJSONArray("inAlbum").forEach(obj -> { - String n = ((JSONObject) obj).getString("name"); - if(!n.equals(album)) { - sb.append("*" + n.trim() + "*\n"); - } - }); - String others = sb.toString(); - eb.addField("Album" + (others.isEmpty() ? "" : "s"), album + (others.isEmpty() ? "" : "\n" + others), true); //add link? - } - - //parse release date - buffer = html.select("span:contains(Release Date) ~ span[class*=\"metadata_unit-info\"]"); - if(buffer.size() > 0) eb.addField("Release Date", buffer.get(0).ownText(), true); - - //parse tags - try { - String sbuff = URLDecoder.decode(html.select("img[src*=\"page-genres=\"]").first().absUrl("src").split("page-genres=")[1].split("&page-type")[0].replaceAll("\\+", " ").split("&")[0], "UTF-8"); - if(!sbuff.isEmpty()) { - eb.addField("Tags", sbuff.trim().replaceAll(",", ", "), false); - } - } catch (UnsupportedEncodingException | NullPointerException e) { - e.printStackTrace(); - } - - //parse background info - buffer = html.select("div[class=\"annotation_label\"] ~ div[class=\"rich_text_formatting\"]"); - if(buffer.size() > 0) { - buffer.get(0).select("blockquote p").prepend("> "); - buffer.get(0).select("p").prepend("\\n\\n"); - String bgInfo = buffer.get(0).text().replaceAll("\\\\n", "\n"); - if(!bgInfo.trim().isEmpty()) { - if(bgInfo.length() > 1024) { - bgInfo = bgInfo.substring(0, 1021) + "..."; - } - eb.addField("Background info", bgInfo, false); - } - } - } else { //second version -- actually has a lot more info, use? - System.out.println("Second ver"); - - String temp = html.select("script:containsData(__PRELOADED_STATE__)").html().split("JSON.parse\\(\'", 2)[1].split("\'\\);\n", 2)[0]; - JSONObject preload = new JSONObject(StringEscapeUtils.unescapeJson(temp)); - JSONObject song = preload.getJSONObject("entities").getJSONObject("songs").getJSONObject(Integer.toString(preload.getJSONObject("songPage").getInt("song"))); - - //parse albums - try { - StringBuilder sb = new StringBuilder(); - String album = IntStream.range(0, song.getJSONArray("trackingData").length()).mapToObj(i -> song.getJSONArray("trackingData").getJSONObject(i)).filter(obj -> obj.getString("key").equals("Primary Album")).findFirst().get().getString("value").trim(); - song.getJSONArray("albums").forEach(obj -> { - String n = ((JSONObject) obj).getString("name"); - if(!n.trim().equals(album)) { - sb.append("*" + n.trim() + "*\n"); - } - }); - String others = sb.toString(); - eb.addField("Album" + (others.isEmpty() ? "" : "s"), album + (others.isEmpty() ? "" : "\n" + others), true); //add link? - } catch (JSONException ignored) { - //no albums; value is null - } - - //release date + String temp = html.select("script:containsData(__PRELOADED_STATE__)").html().split("JSON.parse\\(\'", 2)[1].split("\'\\);\n", 2)[0]; + JSONObject preload = new JSONObject(StringEscapeUtils.unescapeJson(temp)); + JSONObject song = preload.getJSONObject("entities").getJSONObject("songs").getJSONObject(Integer.toString(preload.getJSONObject("songPage").getInt("song"))); + + //parse albums + try { + StringBuilder sb = new StringBuilder(); + String album = IntStream.range(0, song.getJSONArray("trackingData").length()).mapToObj(i -> song.getJSONArray("trackingData").getJSONObject(i)).filter(obj -> obj.getString("key").equals("Primary Album")).findFirst().get().getString("value").trim(); + //other albums are now IDs only, which means if we want them we need to fetch secondary results which isnt particularly worth it + String others = sb.toString(); + eb.addField("Album" + (others.isEmpty() ? "" : "s"), album + (others.isEmpty() ? "" : "\n" + others), true); //add link? + } catch (JSONException ignored) { + //no albums; value is null + } + + //release date + if(!song.isNull("releaseDateForDisplay")) { eb.addField("Release Date", song.getString("releaseDateForDisplay"), true); - - //parse tags - ArrayList tags = new ArrayList<>(); - for(int i = 0; i < song.getJSONArray("tags").length(); i++) { - tags.add(song.getJSONArray("tags").getJSONObject(i).getString("name")); - } - if(!tags.isEmpty()) eb.addField("Tags", String.join(", ", tags), false); - - //parse background info - String bgInfo = song.getJSONObject("description").getString("markdown"); - if(bgInfo.length() > 1024) { - bgInfo = bgInfo.substring(0, 1021) + "..."; - } - if(!bgInfo.equals("?")) eb.addField("Background info", bgInfo, false); //apparently its ? for empty descs lol } + + //parse tags + ArrayList tags = new ArrayList<>(); + for(int i = 0; i < song.getJSONArray("tags").length(); i++) { + tags.add(song.getJSONArray("tags").getJSONObject(i).getString("name")); + } + if(!tags.isEmpty()) eb.addField("Tags", String.join(", ", tags), false); + + //parse background info + String bgInfo = song.getJSONObject("description").getString("markdown"); + if(bgInfo.length() > 1024) { + bgInfo = bgInfo.substring(0, 1021) + "..."; + } + if(!bgInfo.equals("?")) eb.addField("Background info", bgInfo, false); //apparently its ? for empty descs lol eb.setFooter((main.getJSONObject("stats").has("pageviews") ? NumberFormat.getIntegerInstance().format(main.getJSONObject("stats").getInt("pageviews")) + " views | " : "") + "Powered by Genius", "https://yt3.ggpht.com/a/AATXAJzPOKLs0x9W_yNpTUPvwg-zeSnJaxqzf2CU0g=s900-c-k-c0xffffffff-no-rj-mo"); } } diff --git a/src/me/despawningbone/discordbot/command/music/TrackScheduler.java b/src/me/despawningbone/discordbot/command/music/TrackScheduler.java index 6c63351..da36964 100644 --- a/src/me/despawningbone/discordbot/command/music/TrackScheduler.java +++ b/src/me/despawningbone/discordbot/command/music/TrackScheduler.java @@ -1,192 +1,196 @@ package me.despawningbone.discordbot.command.music; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason; import me.despawningbone.discordbot.DiscordBot; import me.despawningbone.discordbot.command.music.AudioTrackHandler.TrackData; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; +import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONTokener; import org.jsoup.Connection; import org.jsoup.Jsoup; /** * Handles everything related to music queuing * Boilerplate from https://github.com/sedmelluq/lavaplayer/tree/master/demo-jda/src/main/java/com/sedmelluq/discord/lavaplayer/demo/jda */ public class TrackScheduler extends AudioEventAdapter { private final AudioPlayer player; private final BlockingQueue queue; private AudioTrackHandler ap; private Guild guild; public String loop = null; //way too lazy to use getter setters lmao public TrackScheduler(Guild parent, AudioTrackHandler handler, AudioPlayer player) { this.player = player; this.queue = new LinkedBlockingQueue<>(); this.ap = handler; this.guild = parent; } public void queue(AudioTrack track) { if (!player.startTrack(track, true)) { queue.offer(track); } else if (loop != null && loop.equals("autoplay")) { //i dont think this is needed as people need to play something before autoplay can be toggled anyways queueAutoplay(track); } } public void nextTrack() { //DONE rewrite to not include q.remove here so that stuff like interrupted wont break the queue? AudioTrack track = queue.poll(); player.startTrack(track, false); if(track == null) { //System.out.println("finished"); //debug loop = null; //reset loop and autoplay tracking delayCloseConnection(player); //required because if not it will throw InterruptedException } } //externally called from AudioTrackHandler.skipTrack() public void queueAutoplay(AudioTrack track) { //DONE check duplicate please, some can get into a dead loop like cosMo@ๆšด่ตฐP - WalpurgisNacht and Ice - ็ตถ //using yt tracking params now; still can get into loops but random should fix ap.ex.submit(() -> { //async so it can free up the event try { //System.out.println("autoplay"); //debug - Connection con = Jsoup.connect("https://www.youtube.com/watch?v=" + track.getIdentifier() + "&pbj=1"); - + Connection con = Jsoup.connect("https://www.youtube.com/watch?v=" + track.getIdentifier()); + + //TODO change to using proper tracking params (maybe VISITOR_INFO1_LIVE or sth?) String cmd = track.getUserData(TrackData.class).getYoutubeAutoplayParam(); if(cmd != null) con.data("command", cmd); //use tracking params to prevent dupes - JSONArray autoplayFeed = new JSONArray(new JSONTokener(con.ignoreContentType(true).post().text())) - .getJSONObject(3).getJSONObject("response").getJSONObject("contents").getJSONObject("twoColumnWatchNextResults") + String data = con.ignoreContentType(true).get().outerHtml(); + data = data.substring(data.indexOf("var ytInitialData = ") + 20); + JSONArray autoplayFeed = new JSONObject(new JSONTokener(data.substring(0, data.indexOf(";")))) + .getJSONObject("contents").getJSONObject("twoColumnWatchNextResults") .getJSONObject("secondaryResults").getJSONObject("secondaryResults").getJSONArray("results"); //filter non video results out for(int i = 0; i < autoplayFeed.length(); i++) if(!autoplayFeed.getJSONObject(i).has("compactVideoRenderer")) autoplayFeed.remove(i--); //remove and reset index pointer by 1 //choose one from top 2 results (should always have more than 2); second result should still be consistent due to tracking unlike without JSONObject autoplay = autoplayFeed.getJSONObject(ThreadLocalRandom.current().nextInt(2)) .getJSONObject("compactVideoRenderer").getJSONObject("navigationEndpoint"); String url = "https://youtube.com" + autoplay.getJSONObject("commandMetadata").getJSONObject("webCommandMetadata").getString("url"); //load Member user = guild.getMemberById(DiscordBot.BotID); //no need to use original track user as it would introduce performance overhead and other complications when leaving channels ap.load(user, url, (n, l) -> { AudioTrack auto = l.get(0); auto.setUserData(new TrackData(auto.getInfo().uri, auto.getDuration(), autoplay.toString())); //set new tracking ap.queueTracks(l, user); //no need sublist coz l is always a single video }, ex -> { ex.printStackTrace(); DiscordBot.lastMusicCmd.get(guild.getId()).sendMessage("Something went wrong when loading next autoplay track: " + ex.getMessage()).queue(); loop = null; }); } catch (Exception e) { e.printStackTrace(); DiscordBot.lastMusicCmd.get(guild.getId()).sendMessage("Something went wrong when loading next autoplay track. Is the last track a youtube video?").queue(); loop = null; } }); } public List findTracks(int startIndex, int range) { AudioTrack[] a = queue.toArray(new AudioTrack[queue.size()]); int i = startIndex - 1 + range < 0 ? Integer.MAX_VALUE : startIndex - 1 + range; //prevent overflow AudioTrack[] t = Arrays.copyOfRange(a, startIndex - 1, Math.min(queue.size() + 1, i)); //accounts for first track player thats not in queue return Arrays.asList(t); } public AudioTrack removeTrack(int num) { Iterator i = queue.iterator(); num = num - 1; for (int times = 0; i.hasNext(); times++) { AudioTrack removed = i.next(); if (num == times) { i.remove(); return removed; } } return null; } public AudioTrack moveTrack(int from, int to) { List q = new ArrayList<>(Arrays.asList(queue.toArray(new AudioTrack[queue.size()]))); AudioTrack track = q.remove(from); q.add(to, track); synchronized (queue) { //obtain lock and operate before releasing or else queue might not be complete queue.clear(); for(AudioTrack t : q) queue.offer(t); } return track; } public void shuffleQueue() { List q = Arrays.asList(queue.toArray(new AudioTrack[queue.size()])); Collections.shuffle(q); synchronized (queue) { //obtain lock and operate before releasing or else queue might not be complete queue.clear(); for(AudioTrack t : q) queue.offer(t); } } public void clearSchedulerQueue() { queue.clear(); } public int getQueueSize() { return queue.size(); } @Override public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) { //System.out.println(endReason); //debug boolean mayStartNext = endReason.mayStartNext; if (mayStartNext) { //doesnt queue clone if skipped if (loop != null && loop.equals("loop")) { //so what the hecc if loop is null and i do loop.equals("Loop") it freezes the thread AudioTrack clone = track.makeClone(); clone.setUserData(new TrackData(clone.getUserData(TrackData.class))); //clone track data queue.offer(clone); } nextTrack(); } if(mayStartNext || endReason == AudioTrackEndReason.REPLACED) { //queues new if skipped too if (loop != null && loop.equals("autoplay") && queue.size() < 1) { queueAutoplay(player.getPlayingTrack()); } } } private void delayCloseConnection(AudioPlayer player) { //TODO configurable delay; dont leave if new things play within the delay ap.ex.schedule(() -> guild.getAudioManager().closeAudioConnection(), 1, TimeUnit.MILLISECONDS); } } \ No newline at end of file