Search in sources :

Example 1 with AudioTrackContext

use of fredboat.audio.queue.AudioTrackContext in project FredBoat by Frederikam.

the class AbstractPlayer method loadAndPlay.

// request the next track from the track provider and start playing it
private void loadAndPlay() {
    log.trace("loadAndPlay()");
    AudioTrackContext atc = null;
    if (audioTrackProvider != null) {
        atc = audioTrackProvider.provideAudioTrack();
    } else {
        log.warn("TrackProvider doesn't exist");
    }
    if (atc != null) {
        queuedTrackInHistory = atc;
        playTrack(atc);
    }
}
Also used : SplitAudioTrackContext(fredboat.audio.queue.SplitAudioTrackContext) AudioTrackContext(fredboat.audio.queue.AudioTrackContext)

Example 2 with AudioTrackContext

use of fredboat.audio.queue.AudioTrackContext in project FredBoat by Frederikam.

the class MusicPersistenceHandler method reloadPlaylists.

private void reloadPlaylists(JDA jda) {
    File dir = new File("music_persistence");
    if (appConfig.isMusicDistribution()) {
        log.warn("Music persistence loading is disabled on the MUSIC distribution! Use PATRON or DEVELOPMENT instead" + "How did this call end up in here anyways?");
        return;
    }
    log.info("Began reloading playlists for shard {}", jda.getShardInfo().getShardId());
    if (!dir.exists()) {
        log.info("No music persistence directory found.");
        return;
    }
    File[] files = dir.listFiles();
    if (files == null || files.length == 0) {
        log.info("No files present in music persistence directory");
        return;
    }
    for (File file : files) {
        try {
            Guild guild = jda.getGuildById(file.getName());
            if (guild == null) {
                // only load guilds that are part of this shard
                continue;
            }
            JSONObject data = new JSONObject(FileUtils.readFileToString(file, Charset.forName("UTF-8")));
            boolean isPaused = data.getBoolean("isPaused");
            final JSONArray sources = data.getJSONArray("sources");
            @Nullable VoiceChannel vc = jda.getVoiceChannelById(data.getString("vc"));
            @Nullable TextChannel tc = jda.getTextChannelById(data.getString("tc"));
            float volume = Float.parseFloat(data.getString("volume"));
            RepeatMode repeatMode = data.getEnum(RepeatMode.class, "repeatMode");
            boolean shuffle = data.getBoolean("shuffle");
            GuildPlayer player = playerRegistry.getOrCreate(guild);
            if (tc != null) {
                musicTextChannelProvider.setMusicChannel(tc);
            }
            if (appConfig.getDistribution().volumeSupported()) {
                player.setVolume(volume);
            }
            player.setRepeatMode(repeatMode);
            player.setShuffle(shuffle);
            final boolean[] isFirst = { true };
            List<AudioTrackContext> tracks = new ArrayList<>();
            sources.forEach((Object t) -> {
                JSONObject json = (JSONObject) t;
                byte[] message = Base64.decodeBase64(json.getString("message"));
                Member member = guild.getMemberById(json.getLong("user"));
                if (member == null)
                    // member left the guild meanwhile, set ourselves as the one who added the song
                    member = guild.getSelfMember();
                AudioTrack at;
                try {
                    ByteArrayInputStream bais = new ByteArrayInputStream(message);
                    at = audioPlayerManager.decodeTrack(new MessageInput(bais)).decodedTrack;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (at == null) {
                    log.error("Loaded track that was null! Skipping...");
                    return;
                }
                // Handle split tracks
                AudioTrackContext atc;
                JSONObject split = json.optJSONObject("split");
                if (split != null) {
                    atc = new SplitAudioTrackContext(jdaEntityProvider, at, member, split.getLong("startPos"), split.getLong("endPos"), split.getString("title"));
                    at.setPosition(split.getLong("startPos"));
                    if (isFirst[0]) {
                        isFirst[0] = false;
                        if (data.has("position")) {
                            at.setPosition(split.getLong("startPos") + data.getLong("position"));
                        }
                    }
                } else {
                    atc = new AudioTrackContext(jdaEntityProvider, at, member);
                    if (isFirst[0]) {
                        isFirst[0] = false;
                        if (data.has("position")) {
                            at.setPosition(data.getLong("position"));
                        }
                    }
                }
                tracks.add(atc);
            });
            player.loadAll(tracks);
            if (!isPaused) {
                if (vc != null) {
                    try {
                        player.joinChannel(vc);
                        player.play();
                    } catch (Exception ignored) {
                    }
                }
                if (tc != null) {
                    CentralMessaging.message(tc, MessageFormat.format(I18n.get(guild).getString("reloadSuccess"), sources.length())).send(null);
                }
            }
        } catch (Exception ex) {
            log.error("Error when loading persistence file", ex);
        }
        boolean deleted = file.delete();
        log.info(deleted ? "Deleted persistence file: " + file : "Failed to delete persistence file: " + file);
    }
}
Also used : ArrayList(java.util.ArrayList) MessageInput(com.sedmelluq.discord.lavaplayer.tools.io.MessageInput) Guild(net.dv8tion.jda.core.entities.Guild) SplitAudioTrackContext(fredboat.audio.queue.SplitAudioTrackContext) TextChannel(net.dv8tion.jda.core.entities.TextChannel) RepeatMode(fredboat.definitions.RepeatMode) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) Member(net.dv8tion.jda.core.entities.Member) JSONArray(org.json.JSONArray) IOException(java.io.IOException) IOException(java.io.IOException) JSONObject(org.json.JSONObject) GuildPlayer(fredboat.audio.player.GuildPlayer) ByteArrayInputStream(java.io.ByteArrayInputStream) AudioTrackContext(fredboat.audio.queue.AudioTrackContext) SplitAudioTrackContext(fredboat.audio.queue.SplitAudioTrackContext) JSONObject(org.json.JSONObject) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) File(java.io.File) Nullable(javax.annotation.Nullable)

Example 3 with AudioTrackContext

use of fredboat.audio.queue.AudioTrackContext in project FredBoat by Frederikam.

the class HistoryCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    GuildPlayer player = Launcher.getBotController().getPlayerRegistry().getExisting(context.guild);
    if (player == null || player.isHistoryQueueEmpty()) {
        context.reply(context.i18n("npNotInHistory"));
        return;
    }
    int page = 1;
    if (context.hasArguments()) {
        try {
            page = Integer.valueOf(context.args[0]);
        } catch (NumberFormatException e) {
            page = 1;
        }
    }
    int tracksCount = player.getTrackCountInHistory();
    int maxPages = (int) Math.ceil(((double) tracksCount - 1d)) / PAGE_SIZE + 1;
    page = Math.max(page, 1);
    page = Math.min(page, maxPages);
    int i = (page - 1) * PAGE_SIZE;
    int listEnd = (page - 1) * PAGE_SIZE + PAGE_SIZE;
    listEnd = Math.min(listEnd, tracksCount);
    int numberLength = Integer.toString(listEnd).length();
    List<AudioTrackContext> sublist = player.getTracksInHistory(i, listEnd);
    MessageBuilder mb = CentralMessaging.getClearThreadLocalMessageBuilder().append(context.i18n("listShowHistory")).append("\n").append(MessageFormat.format(context.i18n("listPageNum"), page, maxPages)).append("\n").append("\n");
    for (AudioTrackContext atc : sublist) {
        String status = " ";
        Member member = atc.getMember();
        String username = member != null ? member.getEffectiveName() : context.guild.getSelfMember().getEffectiveName();
        mb.append("[" + TextUtils.forceNDigits(i + 1, numberLength) + "]", MessageBuilder.Formatting.BLOCK).append(status).append(context.i18nFormat("listAddedBy", TextUtils.escapeAndDefuse(atc.getEffectiveTitle()), TextUtils.escapeAndDefuse(username), TextUtils.formatTime(atc.getEffectiveDuration()))).append("\n");
        if (i == listEnd) {
            break;
        }
        i++;
    }
    context.reply(mb.build());
}
Also used : MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildPlayer(fredboat.audio.player.GuildPlayer) AudioTrackContext(fredboat.audio.queue.AudioTrackContext) Member(net.dv8tion.jda.core.entities.Member)

Example 4 with AudioTrackContext

use of fredboat.audio.queue.AudioTrackContext in project FredBoat by Frederikam.

the class ListCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    GuildPlayer player = Launcher.getBotController().getPlayerRegistry().getExisting(context.guild);
    if (player == null || player.isQueueEmpty()) {
        context.reply(context.i18n("npNotPlaying"));
        return;
    }
    MessageBuilder mb = CentralMessaging.getClearThreadLocalMessageBuilder();
    int page = 1;
    if (context.hasArguments()) {
        try {
            page = Integer.valueOf(context.args[0]);
        } catch (NumberFormatException e) {
            page = 1;
        }
    }
    int tracksCount = player.getTrackCount();
    int maxPages = (int) Math.ceil(((double) tracksCount - 1d)) / PAGE_SIZE + 1;
    page = Math.max(page, 1);
    page = Math.min(page, maxPages);
    int i = (page - 1) * PAGE_SIZE;
    int listEnd = (page - 1) * PAGE_SIZE + PAGE_SIZE;
    listEnd = Math.min(listEnd, tracksCount);
    int numberLength = Integer.toString(listEnd).length();
    List<AudioTrackContext> sublist = player.getTracksInRange(i, listEnd);
    if (player.isShuffle()) {
        mb.append(context.i18n("listShowShuffled"));
        mb.append("\n");
        if (player.getRepeatMode() == RepeatMode.OFF)
            mb.append("\n");
    }
    if (player.getRepeatMode() == RepeatMode.SINGLE) {
        mb.append(context.i18n("listShowRepeatSingle"));
        mb.append("\n");
    } else if (player.getRepeatMode() == RepeatMode.ALL) {
        mb.append(context.i18n("listShowRepeatAll"));
        mb.append("\n");
    }
    mb.append(context.i18nFormat("listPageNum", page, maxPages));
    mb.append("\n");
    mb.append("\n");
    for (AudioTrackContext atc : sublist) {
        String status = " ";
        if (i == 0) {
            // Escaped play and pause emojis
            status = player.isPlaying() ? " \\▶" : " \\\u23F8";
        }
        Member member = atc.getMember();
        String username = member != null ? member.getEffectiveName() : context.guild.getSelfMember().getEffectiveName();
        mb.append("[" + TextUtils.forceNDigits(i + 1, numberLength) + "]", MessageBuilder.Formatting.BLOCK).append(status).append(context.i18nFormat("listAddedBy", TextUtils.escapeAndDefuse(atc.getEffectiveTitle()), TextUtils.escapeAndDefuse(username), TextUtils.formatTime(atc.getEffectiveDuration()))).append("\n");
        if (i == listEnd) {
            break;
        }
        i++;
    }
    // Now add a timestamp for how much is remaining
    String timestamp = TextUtils.formatTime(player.getTotalRemainingMusicTimeMillis());
    long streams = player.getStreamsCount();
    long numTracks = tracksCount - streams;
    String desc;
    if (numTracks == 0) {
        // We are only listening to streams
        desc = context.i18nFormat(streams == 1 ? "listStreamsOnlySingle" : "listStreamsOnlyMultiple", streams, streams == 1 ? context.i18n("streamSingular") : context.i18n("streamPlural"));
    } else {
        desc = context.i18nFormat(numTracks == 1 ? "listStreamsOrTracksSingle" : "listStreamsOrTracksMultiple", numTracks, numTracks == 1 ? context.i18n("trackSingular") : context.i18n("trackPlural"), timestamp, streams == 0 ? "" : context.i18nFormat("listAsWellAsLiveStreams", streams, streams == 1 ? context.i18n("streamSingular") : context.i18n("streamPlural")));
    }
    mb.append("\n").append(desc);
    context.reply(mb.build());
}
Also used : MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildPlayer(fredboat.audio.player.GuildPlayer) AudioTrackContext(fredboat.audio.queue.AudioTrackContext) Member(net.dv8tion.jda.core.entities.Member)

Example 5 with AudioTrackContext

use of fredboat.audio.queue.AudioTrackContext in project FredBoat by Frederikam.

the class NowplayingCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    GuildPlayer player = Launcher.getBotController().getPlayerRegistry().getExisting(context.guild);
    if (player != null && player.isPlaying()) {
        AudioTrackContext atc = player.getPlayingTrack();
        AudioTrack at = atc.getTrack();
        EmbedBuilder builder;
        if (at instanceof YoutubeAudioTrack) {
            builder = getYoutubeEmbed(atc, player, (YoutubeAudioTrack) at);
        } else if (at instanceof SoundCloudAudioTrack) {
            builder = getSoundcloudEmbed(atc, player, (SoundCloudAudioTrack) at);
        } else if (at instanceof HttpAudioTrack && at.getIdentifier().contains("gensokyoradio.net")) {
            // Special handling for GR
            builder = getGensokyoRadioEmbed(context);
        } else if (at instanceof HttpAudioTrack) {
            builder = getHttpEmbed(atc, player, (HttpAudioTrack) at);
        } else if (at instanceof BandcampAudioTrack) {
            builder = getBandcampResponse(atc, player, (BandcampAudioTrack) at);
        } else if (at instanceof TwitchStreamAudioTrack) {
            builder = getTwitchEmbed(atc, (TwitchStreamAudioTrack) at);
        } else if (at instanceof BeamAudioTrack) {
            builder = getBeamEmbed(atc, (BeamAudioTrack) at);
        } else {
            builder = getDefaultEmbed(atc, player, at);
        }
        Member requester = atc.getMember() != null ? atc.getMember() : context.guild.getSelfMember();
        builder = CentralMessaging.addNpFooter(builder, requester);
        context.reply(builder.build());
    } else {
        context.reply(context.i18n("npNotPlaying"));
    }
}
Also used : TwitchStreamAudioTrack(com.sedmelluq.discord.lavaplayer.source.twitch.TwitchStreamAudioTrack) HttpAudioTrack(com.sedmelluq.discord.lavaplayer.source.http.HttpAudioTrack) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) GuildPlayer(fredboat.audio.player.GuildPlayer) AudioTrackContext(fredboat.audio.queue.AudioTrackContext) YoutubeAudioTrack(com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioTrack) HttpAudioTrack(com.sedmelluq.discord.lavaplayer.source.http.HttpAudioTrack) BeamAudioTrack(com.sedmelluq.discord.lavaplayer.source.beam.BeamAudioTrack) YoutubeAudioTrack(com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioTrack) SoundCloudAudioTrack(com.sedmelluq.discord.lavaplayer.source.soundcloud.SoundCloudAudioTrack) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) BandcampAudioTrack(com.sedmelluq.discord.lavaplayer.source.bandcamp.BandcampAudioTrack) TwitchStreamAudioTrack(com.sedmelluq.discord.lavaplayer.source.twitch.TwitchStreamAudioTrack) BeamAudioTrack(com.sedmelluq.discord.lavaplayer.source.beam.BeamAudioTrack) SoundCloudAudioTrack(com.sedmelluq.discord.lavaplayer.source.soundcloud.SoundCloudAudioTrack) BandcampAudioTrack(com.sedmelluq.discord.lavaplayer.source.bandcamp.BandcampAudioTrack) Member(net.dv8tion.jda.core.entities.Member)

Aggregations

AudioTrackContext (fredboat.audio.queue.AudioTrackContext)14 GuildPlayer (fredboat.audio.player.GuildPlayer)9 Member (net.dv8tion.jda.core.entities.Member)5 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)4 SplitAudioTrackContext (fredboat.audio.queue.SplitAudioTrackContext)4 ArrayList (java.util.ArrayList)4 TextChannel (net.dv8tion.jda.core.entities.TextChannel)3 File (java.io.File)2 IOException (java.io.IOException)2 MessageBuilder (net.dv8tion.jda.core.MessageBuilder)2 VoiceChannel (net.dv8tion.jda.core.entities.VoiceChannel)2 JSONObject (org.json.JSONObject)2 BandcampAudioTrack (com.sedmelluq.discord.lavaplayer.source.bandcamp.BandcampAudioTrack)1 BeamAudioTrack (com.sedmelluq.discord.lavaplayer.source.beam.BeamAudioTrack)1 HttpAudioTrack (com.sedmelluq.discord.lavaplayer.source.http.HttpAudioTrack)1 SoundCloudAudioTrack (com.sedmelluq.discord.lavaplayer.source.soundcloud.SoundCloudAudioTrack)1 TwitchStreamAudioTrack (com.sedmelluq.discord.lavaplayer.source.twitch.TwitchStreamAudioTrack)1 YoutubeAudioTrack (com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioTrack)1 MessageInput (com.sedmelluq.discord.lavaplayer.tools.io.MessageInput)1 MessageOutput (com.sedmelluq.discord.lavaplayer.tools.io.MessageOutput)1