Search in sources :

Example 6 with GuildPlayer

use of fredboat.audio.player.GuildPlayer in project FredBoat by Frederikam.

the class EventListenerBoat method checkForAutoResume.

private void checkForAutoResume(VoiceChannel joinedChannel, Member joined) {
    Guild guild = joinedChannel.getGuild();
    // ignore bot users that arent us joining / moving
    if (joined.getUser().isBot() && guild.getSelfMember().getUser().getIdLong() != joined.getUser().getIdLong())
        return;
    GuildPlayer player = playerRegistry.getExisting(guild);
    if (player != null && player.isPaused() && player.getPlayingTrack() != null && joinedChannel.getMembers().contains(guild.getSelfMember()) && player.getHumanUsersInCurrentVC().size() > 0 && guildConfigService.fetchGuildConfig(guild).isAutoResume()) {
        player.setPause(false);
        TextChannel activeTextChannel = player.getActiveTextChannel();
        if (activeTextChannel != null) {
            CentralMessaging.message(activeTextChannel, I18n.get(guild).getString("eventAutoResumed")).send(null);
        }
    }
}
Also used : GuildPlayer(fredboat.audio.player.GuildPlayer)

Example 7 with GuildPlayer

use of fredboat.audio.player.GuildPlayer 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 8 with GuildPlayer

use of fredboat.audio.player.GuildPlayer in project FredBoat by Frederikam.

the class ExportCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    GuildPlayer player = Launcher.getBotController().getPlayerRegistry().getExisting(context.guild);
    if (player == null || player.isQueueEmpty()) {
        throw new MessagingException(context.i18n("exportEmpty"));
    }
    String out = player.getRemainingTracks().stream().map(atc -> atc.getTrack().getInfo().uri).collect(Collectors.joining("\n"));
    TextUtils.postToPasteService(out).thenApply(pasteUrl -> {
        if (pasteUrl.isPresent()) {
            String url = pasteUrl.get() + ".fredboat";
            return context.i18nFormat("exportPlaylistResulted", url);
        } else {
            return context.i18n("exportPlaylistFail") + "\n" + context.i18n("tryLater");
        }
    }).thenAccept(context::reply);
}
Also used : IMusicCommand(fredboat.commandmeta.abs.IMusicCommand) Launcher(fredboat.main.Launcher) GuildPlayer(fredboat.audio.player.GuildPlayer) Context(fredboat.messaging.internal.Context) Command(fredboat.commandmeta.abs.Command) MessagingException(fredboat.commandmeta.MessagingException) CommandContext(fredboat.commandmeta.abs.CommandContext) TextUtils(fredboat.util.TextUtils) Nonnull(javax.annotation.Nonnull) Collectors(java.util.stream.Collectors) GuildPlayer(fredboat.audio.player.GuildPlayer) MessagingException(fredboat.commandmeta.MessagingException)

Example 9 with GuildPlayer

use of fredboat.audio.player.GuildPlayer 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 10 with GuildPlayer

use of fredboat.audio.player.GuildPlayer 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)

Aggregations

GuildPlayer (fredboat.audio.player.GuildPlayer)29 AudioTrackContext (fredboat.audio.queue.AudioTrackContext)9 ArrayList (java.util.ArrayList)5 Member (net.dv8tion.jda.core.entities.Member)5 VoiceChannel (net.dv8tion.jda.core.entities.VoiceChannel)5 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)4 TextChannel (net.dv8tion.jda.core.entities.TextChannel)4 Command (fredboat.commandmeta.abs.Command)3 CommandContext (fredboat.commandmeta.abs.CommandContext)3 Launcher (fredboat.main.Launcher)3 Context (fredboat.messaging.internal.Context)3 TextUtils (fredboat.util.TextUtils)3 Nonnull (javax.annotation.Nonnull)3 Guild (net.dv8tion.jda.core.entities.Guild)3 JSONObject (org.json.JSONObject)3 PlayerRegistry (fredboat.audio.player.PlayerRegistry)2 SplitAudioTrackContext (fredboat.audio.queue.SplitAudioTrackContext)2 MessagingException (fredboat.commandmeta.MessagingException)2 ICommandRestricted (fredboat.commandmeta.abs.ICommandRestricted)2 PermissionLevel (fredboat.definitions.PermissionLevel)2