Search in sources :

Example 21 with GuildPlayer

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

the class MusicPersistenceHandler method persist.

private void persist(int code) {
    File dir = new File("music_persistence");
    if (!dir.exists()) {
        boolean created = dir.mkdir();
        if (!created) {
            log.error("Failed to create music persistence directory");
            return;
        }
    }
    Map<Long, GuildPlayer> reg = playerRegistry.getRegistry();
    boolean isUpdate = code == ExitCodes.EXIT_CODE_UPDATE;
    boolean isRestart = code == ExitCodes.EXIT_CODE_RESTART;
    for (long gId : reg.keySet()) {
        try {
            GuildPlayer player = reg.get(gId);
            String msg;
            if (isUpdate) {
                msg = I18n.get(player.getGuild()).getString("shutdownUpdating");
            } else if (isRestart) {
                msg = I18n.get(player.getGuild()).getString("shutdownRestarting");
            } else {
                msg = I18n.get(player.getGuild()).getString("shutdownIndef");
            }
            TextChannel activeTextChannel = player.getActiveTextChannel();
            List<CompletableFuture> announcements = new ArrayList<>();
            if (activeTextChannel != null && player.isPlaying()) {
                announcements.add(CentralMessaging.message(activeTextChannel, msg).send(null));
            }
            for (Future announcement : announcements) {
                try {
                    // 30 seconds is enough on patron boat
                    announcement.get(30, TimeUnit.SECONDS);
                } catch (Exception ignored) {
                }
            }
            JSONObject data = new JSONObject();
            VoiceChannel vc = player.getCurrentVoiceChannel();
            data.put("vc", vc != null ? vc.getId() : "0");
            data.put("tc", activeTextChannel != null ? activeTextChannel.getId() : "");
            data.put("isPaused", player.isPaused());
            data.put("volume", Float.toString(player.getVolume()));
            data.put("repeatMode", player.getRepeatMode());
            data.put("shuffle", player.isShuffle());
            if (player.getPlayingTrack() != null) {
                data.put("position", player.getPosition());
            }
            ArrayList<JSONObject> identifiers = new ArrayList<>();
            for (AudioTrackContext atc : player.getRemainingTracks()) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                audioPlayerManager.encodeTrack(new MessageOutput(baos), atc.getTrack());
                JSONObject ident = new JSONObject().put("message", Base64.encodeBase64String(baos.toByteArray())).put("user", atc.getUserId());
                if (atc instanceof SplitAudioTrackContext) {
                    JSONObject split = new JSONObject();
                    SplitAudioTrackContext c = (SplitAudioTrackContext) atc;
                    split.put("title", c.getEffectiveTitle()).put("startPos", c.getStartPosition()).put("endPos", c.getStartPosition() + c.getEffectiveDuration());
                    ident.put("split", split);
                }
                identifiers.add(ident);
            }
            data.put("sources", identifiers);
            try {
                FileUtils.writeStringToFile(new File(dir, Long.toString(gId)), data.toString(), Charset.forName("UTF-8"));
            } catch (IOException ex) {
                if (activeTextChannel != null) {
                    CentralMessaging.message(activeTextChannel, MessageFormat.format(I18n.get(player.getGuild()).getString("shutdownPersistenceFail"), ex.getMessage())).send(null);
                }
            }
        } catch (Exception ex) {
            log.error("Error when saving persistence file", ex);
        }
    }
}
Also used : MessageOutput(com.sedmelluq.discord.lavaplayer.tools.io.MessageOutput) ArrayList(java.util.ArrayList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) SplitAudioTrackContext(fredboat.audio.queue.SplitAudioTrackContext) IOException(java.io.IOException) TextChannel(net.dv8tion.jda.core.entities.TextChannel) CompletableFuture(java.util.concurrent.CompletableFuture) JSONObject(org.json.JSONObject) GuildPlayer(fredboat.audio.player.GuildPlayer) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) AudioTrackContext(fredboat.audio.queue.AudioTrackContext) SplitAudioTrackContext(fredboat.audio.queue.SplitAudioTrackContext) File(java.io.File)

Example 22 with GuildPlayer

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

the class ShardReviveHandler method onShutdown.

@Override
public void onShutdown(ShutdownEvent event) {
    try {
        List<Long> channels = new ArrayList<>();
        int shardId = event.getJDA().getShardInfo().getShardId();
        playerRegistry.getPlayingPlayers().stream().filter(guildPlayer -> DiscordUtil.getShardId(guildPlayer.getGuildId(), credentials) == shardId).forEach(guildPlayer -> {
            VoiceChannel channel = guildPlayer.getCurrentVoiceChannel();
            if (channel != null)
                channels.add(channel.getIdLong());
        });
        channelsToRejoin.put(shardId, channels);
    } catch (Exception ex) {
        log.error("Caught exception while saving channels to revive shard {}", event.getJDA().getShardInfo(), ex);
    }
}
Also used : PlayerRegistry(fredboat.audio.player.PlayerRegistry) Credentials(fredboat.config.property.Credentials) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) ShutdownEvent(net.dv8tion.jda.core.events.ShutdownEvent) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ListenerAdapter(net.dv8tion.jda.core.hooks.ListenerAdapter) ArrayList(java.util.ArrayList) AudioConnectionFacade(fredboat.audio.player.AudioConnectionFacade) Component(org.springframework.stereotype.Component) List(java.util.List) GuildPlayer(fredboat.audio.player.GuildPlayer) Map(java.util.Map) DiscordUtil(fredboat.util.DiscordUtil) ReadyEvent(net.dv8tion.jda.core.events.ReadyEvent) ArrayList(java.util.ArrayList) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel)

Example 23 with GuildPlayer

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

the class ShardReviveHandler method onReady.

@Override
public void onReady(ReadyEvent event) {
    // Rejoin old channels if revived
    List<Long> channels = channelsToRejoin.computeIfAbsent(event.getJDA().getShardInfo().getShardId(), ArrayList::new);
    List<Long> toRejoin = new ArrayList<>(channels);
    // avoid situations where this method is called twice with the same channels
    channels.clear();
    toRejoin.forEach(vcid -> {
        VoiceChannel channel = event.getJDA().getVoiceChannelById(vcid);
        if (channel == null)
            return;
        GuildPlayer player = playerRegistry.getOrCreate(channel.getGuild());
        audioConnectionFacade.openConnection(channel, player);
    });
}
Also used : GuildPlayer(fredboat.audio.player.GuildPlayer) ArrayList(java.util.ArrayList) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel)

Example 24 with GuildPlayer

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

the class VolumeCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    if (Launcher.getBotController().getAppConfig().getDistribution().volumeSupported()) {
        GuildPlayer player = Launcher.getBotController().getPlayerRegistry().getOrCreate(context.guild);
        try {
            float volume = Float.parseFloat(context.args[0]) / 100;
            volume = Math.max(0, Math.min(1.5f, volume));
            context.reply(context.i18nFormat("volumeSuccess", Math.floor(player.getVolume() * 100), Math.floor(volume * 100)));
            player.setVolume(volume);
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException ex) {
            throw new MessagingException(context.i18nFormat("volumeSyntax", 100 * PlayerRegistry.DEFAULT_VOLUME, Math.floor(player.getVolume() * 100)));
        }
    } else {
        String out = context.i18n("volumeApology") + "\n<" + BotConstants.DOCS_DONATE_URL + ">";
        context.replyImage("https://fred.moe/1vD.png", out, msg -> CentralMessaging.restService.schedule(() -> CentralMessaging.deleteMessage(msg), 2, TimeUnit.MINUTES));
    }
}
Also used : GuildPlayer(fredboat.audio.player.GuildPlayer) MessagingException(fredboat.commandmeta.MessagingException)

Example 25 with GuildPlayer

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

the class VoteSkipCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    // While you can join another vc and then voteskip i don't think this will be common
    if (!context.invoker.getVoiceState().inVoiceChannel()) {
        context.reply(context.i18n("playerUserNotInChannel"));
        return;
    }
    GuildPlayer player = Launcher.getBotController().getPlayerRegistry().getExisting(context.guild);
    if (player == null || player.isQueueEmpty()) {
        context.reply(context.i18n("skipEmpty"));
        return;
    }
    if (isOnCooldown(context.guild)) {
        return;
    } else {
        guildIdToLastSkip.put(context.guild.getId(), System.currentTimeMillis());
    }
    if (!context.hasArguments()) {
        String response = addVoteWithResponse(context);
        float actualMinSkip = player.getHumanUsersInCurrentVC().size() < 3 ? 1.0f : MIN_SKIP_PERCENTAGE;
        float skipPercentage = getSkipPercentage(context.guild, player);
        if (skipPercentage >= actualMinSkip) {
            AudioTrackContext atc = player.getPlayingTrack();
            if (atc == null) {
                context.reply(context.i18n("skipTrackNotFound"));
            } else {
                String skipPerc = "`" + TextUtils.formatPercent(skipPercentage) + "`";
                String trackTitle = "**" + TextUtils.escapeAndDefuse(atc.getEffectiveTitle()) + "**";
                context.reply(response + "\n" + context.i18nFormat("voteSkipSkipping", skipPerc, trackTitle));
                player.skip();
            }
        } else {
            String skipPerc = "`" + TextUtils.formatPercent(skipPercentage) + "`";
            String minSkipPerc = "`" + TextUtils.formatPercent(actualMinSkip) + "`";
            context.reply(response + "\n" + context.i18nFormat("voteSkipNotEnough", skipPerc, minSkipPerc));
        }
    } else if (context.args[0].toLowerCase().equals("list")) {
        displayVoteList(context, player);
    } else {
        HelpCommand.sendFormattedCommandHelp(context);
    }
}
Also used : GuildPlayer(fredboat.audio.player.GuildPlayer) AudioTrackContext(fredboat.audio.queue.AudioTrackContext)

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