Skip to content

Commit

Permalink
playlist load faster and queue command shows np
Browse files Browse the repository at this point in the history
  • Loading branch information
jagrosh committed Jul 4, 2017
1 parent 8f7e53a commit cb9644d
Show file tree
Hide file tree
Showing 11 changed files with 217 additions and 176 deletions.
5 changes: 3 additions & 2 deletions src/main/java/com/jagrosh/jmusicbot/Bot.java
Original file line number Diff line number Diff line change
Expand Up @@ -207,10 +207,11 @@ public void onReady(ReadyEvent event) {
try
{
String defpl = getSettings(guild).getDefaultPlaylist();
if(defpl!=null)
VoiceChannel vc = guild.getVoiceChannelById(getSettings(guild).getVoiceId());
if(defpl!=null && vc!=null)
{
if(setUpHandler(guild).playFromDefault())
guild.getAudioManager().openAudioConnection(guild.getVoiceChannelById(getSettings(guild).getVoiceId()));
guild.getAudioManager().openAudioConnection(vc);
}
}
catch(Exception ex) {System.err.println(ex);}
Expand Down
1 change: 1 addition & 0 deletions src/main/java/com/jagrosh/jmusicbot/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public Config(boolean nogui)
List<String> lines;
try {
lines = Files.readAllLines(Paths.get("config.txt"));
System.out.println("[INFO] Loading config: "+Paths.get("config.txt").toFile().getAbsolutePath());
for(String line: lines)
{
String[] parts = line.split("=",2);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/jagrosh/jmusicbot/JMusicBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public static void main(String[] args){
.setHelpWord(config.getHelp())
.addCommands(
new AboutCommand(Color.BLUE.brighter(),
"a music bot that is [easy to host yourself!](https://github.com/jagrosh/MusicBot) (v0.0.6)",
"a music bot that is [easy to host yourself!](https://github.com/jagrosh/MusicBot) (v0.0.7)",
new String[]{"High-quality music playback", "FairQueue™ Technology", "Easy to host yourself"},
RECOMMENDED_PERMS),
new PingCommand(),
Expand Down
29 changes: 23 additions & 6 deletions src/main/java/com/jagrosh/jmusicbot/audio/AudioHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,19 @@ public FairQueue<QueuedTrack> getQueue()
return queue;
}

public void stopAndClear()
{
queue.clear();
defaultQueue.clear();
audioPlayer.stopTrack();
//current = null;
}

public boolean isMusicPlaying()
{
return guild.getSelfMember().getVoiceState().inVoiceChannel() && current!=null;
}

public Set<String> getVotes()
{
return votes;
Expand All @@ -103,18 +116,21 @@ public boolean playFromDefault()
Playlist pl = Playlist.loadPlaylist(bot.getSettings(guild).getDefaultPlaylist());
if(pl==null || pl.getItems().isEmpty())
return false;
pl.loadTracks(bot.getAudioManager(), () -> {
pl.loadTracks(bot.getAudioManager(), (at) -> {
if(current==null)
{
current = new QueuedTrack(at, null);
audioPlayer.playTrack(at);
}
else
defaultQueue.add(at);
}, () -> {
if(pl.getTracks().isEmpty())
{
current = null;
if(!STAY_IN_CHANNEL)
guild.getAudioManager().closeAudioConnection();
}
else
{
defaultQueue.addAll(pl.getTracks());
playFromDefault();
}
});
return true;
}
Expand All @@ -123,6 +139,7 @@ public boolean playFromDefault()
public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) {
if(queue.isEmpty())
{
current = null;
if(!playFromDefault())
{
current = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ protected void execute(CommandEvent event) {
}
if(bePlaying
&& (event.getGuild().getAudioManager().getSendingHandler()==null
|| ((AudioHandler)event.getGuild().getAudioManager().getSendingHandler()).getCurrentTrack()==null))
|| !((AudioHandler)event.getGuild().getAudioManager().getSendingHandler()).isMusicPlaying()))
{
event.reply(event.getClient().getError()+" There must be music playing to use that!");
return;
Expand Down
27 changes: 14 additions & 13 deletions src/main/java/com/jagrosh/jmusicbot/commands/NowplayingCmd.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,27 @@ public void doCommand(CommandEvent event) {
eb.setColor(event.getSelfMember().getColor());
AudioHandler ah = (AudioHandler)event.getGuild().getAudioManager().getSendingHandler();

if(ah==null || ah.getCurrentTrack()==null)
if(ah==null || !ah.isMusicPlaying())
{
eb.setTitle("No music playing");
eb.setDescription("\u23F9 "+FormatUtil.progressBar(-1)+" "+FormatUtil.volumeIcon(ah==null?100:ah.getPlayer().getVolume()));
event.reply(eb.build());
return;
}

User u;
try {
u = event.getJDA().getUserById(ah.getCurrentTrack().getIdentifier());
} catch(Exception e) {
u = null;
if(ah.getCurrentTrack().getIdentifier()!=null)
{
User u;
try {
u = event.getJDA().getUserById(ah.getCurrentTrack().getIdentifier());
} catch(Exception e) {
u = null;
}
if(u==null)
eb.setAuthor("Unknown (ID:"+ah.getCurrentTrack().getIdentifier()+")", null, null);
else
eb.setAuthor(u.getName()+"#"+u.getDiscriminator(), null, u.getEffectiveAvatarUrl());
}
if(u==null)
eb.setAuthor("Unknown (ID:"+ah.getCurrentTrack().getIdentifier()+")", null, null);
else
eb.setAuthor(u.getName()+"#"+u.getDiscriminator(), null, u.getEffectiveAvatarUrl());

try {
eb.setTitle(ah.getCurrentTrack().getTrack().getInfo().title, ah.getCurrentTrack().getTrack().getInfo().uri);
Expand All @@ -74,9 +77,7 @@ public void doCommand(CommandEvent event) {
if(ah.getCurrentTrack().getTrack() instanceof YoutubeAudioTrack)
eb.setThumbnail("https://img.youtube.com/vi/"+ah.getCurrentTrack().getTrack().getIdentifier()+"/maxresdefault.jpg");

eb.setDescription((ah.getPlayer().isPaused()?"\u23F8":"\u25B6")+" "+FormatUtil.progressBar((double)ah.getCurrentTrack().getTrack().getPosition()/ah.getCurrentTrack().getTrack().getDuration())
+" `["+FormatUtil.formatTime(ah.getCurrentTrack().getTrack().getPosition()) + "/" + FormatUtil.formatTime(ah.getCurrentTrack().getTrack().getDuration()) +"]` "
+FormatUtil.volumeIcon(ah.getPlayer().getVolume()));
eb.setDescription(FormatUtil.embedformattedAudio(ah));

event.reply(eb.build());
}
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/com/jagrosh/jmusicbot/commands/PlayCmd.java
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,8 @@ public void doCommand(CommandEvent event) {
event.reply(event.getClient().getError()+" I could not find `"+event.getArgs()+".txt` in the Playlists folder.");
return;
}
event.getChannel().sendMessage("\u231A Loading playlist **"+event.getArgs()+"**...").queue(m -> {
playlist.loadTracks(bot.getAudioManager(), () -> {
event.getChannel().sendMessage("\u231A Loading playlist **"+event.getArgs()+"**... ("+playlist.getItems().size()+" items)").queue(m -> {
playlist.loadTracks(bot.getAudioManager(), (at)->bot.queueTrack(event, at), () -> {
StringBuilder builder = new StringBuilder(playlist.getTracks().isEmpty()
? event.getClient().getWarning()+" No tracks were loaded!"
: event.getClient().getSuccess()+" Loaded **"+playlist.getTracks().size()+"** tracks!");
Expand All @@ -176,7 +176,6 @@ public void doCommand(CommandEvent event) {
if(str.length()>2000)
str = str.substring(0,1994)+" (...)";
m.editMessage(str).queue();
playlist.getTracks().forEach(track -> bot.queueTrack(event, track));
});
});
}
Expand Down
178 changes: 94 additions & 84 deletions src/main/java/com/jagrosh/jmusicbot/commands/QueueCmd.java
Original file line number Diff line number Diff line change
@@ -1,84 +1,94 @@
/*
* Copyright 2016 John Grosh <[email protected]>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jagrosh.jmusicbot.commands;

import java.util.List;
import java.util.concurrent.TimeUnit;
import com.jagrosh.jdautilities.commandclient.CommandEvent;
import com.jagrosh.jdautilities.menu.pagination.PaginatorBuilder;
import com.jagrosh.jmusicbot.Bot;
import com.jagrosh.jmusicbot.audio.AudioHandler;
import com.jagrosh.jmusicbot.audio.QueuedTrack;
import com.jagrosh.jmusicbot.utils.FormatUtil;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.exceptions.PermissionException;

/**
*
* @author John Grosh <[email protected]>
*/
public class QueueCmd extends MusicCommand {

private final PaginatorBuilder builder;
public QueueCmd(Bot bot)
{
super(bot);
this.name = "queue";
this.help = "shows the current queue";
this.arguments = "[pagenum]";
this.aliases = new String[]{"list"};
this.bePlaying = true;
this.botPermissions = new Permission[]{Permission.MESSAGE_ADD_REACTION,Permission.MESSAGE_EMBED_LINKS};
builder = new PaginatorBuilder()
.setColumns(1)
.setFinalAction(m -> {try{m.clearReactions().queue();}catch(PermissionException e){}})
.setItemsPerPage(10)
.waitOnSinglePage(false)
.useNumberedItems(true)
.showPageNumbers(true)
.setEventWaiter(bot.getWaiter())
.setTimeout(1, TimeUnit.MINUTES)
;
}

@Override
public void doCommand(CommandEvent event) {
int pagenum = 1;
try{
pagenum = Integer.parseInt(event.getArgs());
}catch(NumberFormatException e){}
List<QueuedTrack> list = ((AudioHandler)event.getGuild().getAudioManager().getSendingHandler()).getQueue().getList();
if(list.isEmpty())
{
event.reply(event.getClient().getWarning()+" There is no music in the queue!");
return;
}
String[] songs = new String[list.size()];
long total = 0;
for(int i=0; i<list.size(); i++)
{
total += list.get(i).getTrack().getDuration();
songs[i] = list.get(i).toString();
}
builder.setText(event.getClient().getSuccess()+" Current Queue | "+songs.length+" entries | `"+FormatUtil.formatTime(total)+"` ")
.setItems(songs)
.setUsers(event.getAuthor())
.setColor(event.getSelfMember().getColor())
;
builder.build().paginate(event.getChannel(), pagenum);
}

}
/*
* Copyright 2016 John Grosh <[email protected]>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jagrosh.jmusicbot.commands;

import java.util.List;
import java.util.concurrent.TimeUnit;
import com.jagrosh.jdautilities.commandclient.CommandEvent;
import com.jagrosh.jdautilities.menu.pagination.PaginatorBuilder;
import com.jagrosh.jmusicbot.Bot;
import com.jagrosh.jmusicbot.audio.AudioHandler;
import com.jagrosh.jmusicbot.audio.QueuedTrack;
import com.jagrosh.jmusicbot.utils.FormatUtil;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.exceptions.PermissionException;

/**
*
* @author John Grosh <[email protected]>
*/
public class QueueCmd extends MusicCommand {

private final PaginatorBuilder builder;
public QueueCmd(Bot bot)
{
super(bot);
this.name = "queue";
this.help = "shows the current queue";
this.arguments = "[pagenum]";
this.aliases = new String[]{"list"};
this.bePlaying = true;
this.botPermissions = new Permission[]{Permission.MESSAGE_ADD_REACTION,Permission.MESSAGE_EMBED_LINKS};
builder = new PaginatorBuilder()
.setColumns(1)
.setFinalAction(m -> {try{m.clearReactions().queue();}catch(PermissionException e){}})
.setItemsPerPage(10)
.waitOnSinglePage(false)
.useNumberedItems(true)
.showPageNumbers(true)
.setEventWaiter(bot.getWaiter())
.setTimeout(1, TimeUnit.MINUTES)
;
}

@Override
public void doCommand(CommandEvent event) {
int pagenum = 1;
try{
pagenum = Integer.parseInt(event.getArgs());
}catch(NumberFormatException e){}
AudioHandler ah = (AudioHandler)event.getGuild().getAudioManager().getSendingHandler();
List<QueuedTrack> list = ah.getQueue().getList();
if(list.isEmpty())
{
event.replyWarning("There is no music in the queue!"
+(!ah.isMusicPlaying() ? "" : " Now playing:\n\n**"+ah.getCurrentTrack().getTrack().getInfo().title+"**\n"+FormatUtil.embedformattedAudio(ah)));
return;
}
String[] songs = new String[list.size()];
long total = 0;
for(int i=0; i<list.size(); i++)
{
total += list.get(i).getTrack().getDuration();
songs[i] = list.get(i).toString();
}
long fintotal = total;
builder.setText((i1,i2) -> getQueueTitle(ah, event.getClient().getSuccess(), songs.length, fintotal))
.setItems(songs)
.setUsers(event.getAuthor())
.setColor(event.getSelfMember().getColor())
;
builder.build().paginate(event.getChannel(), pagenum);
}

private String getQueueTitle(AudioHandler ah, String success, int songslength, long total)
{
StringBuilder sb = new StringBuilder();
if(ah.getCurrentTrack()!=null)
sb.append("**").append(ah.getCurrentTrack().getTrack().getInfo().title).append("**\n").append(FormatUtil.embedformattedAudio(ah)).append("\n\n");
return sb.append(success).append(" Current Queue | ").append(songslength).append(" entries | `").append(FormatUtil.formatTime(total)).append("` ").toString();
}
}
Loading

0 comments on commit cb9644d

Please sign in to comment.