Search in sources :

Example 1 with RepeatMode

use of fredboat.definitions.RepeatMode 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 2 with RepeatMode

use of fredboat.definitions.RepeatMode in project FredBoat by Frederikam.

the class RepeatCommand method onInvoke.

@Override
public void onInvoke(@Nonnull CommandContext context) {
    if (!context.hasArguments()) {
        HelpCommand.sendFormattedCommandHelp(context);
        return;
    }
    RepeatMode desiredRepeatMode;
    String userInput = context.args[0];
    switch(userInput) {
        case "off":
        case "out":
            desiredRepeatMode = RepeatMode.OFF;
            break;
        case "single":
        case "one":
        case "track":
            desiredRepeatMode = RepeatMode.SINGLE;
            break;
        case "all":
        case "list":
        case "queue":
            desiredRepeatMode = RepeatMode.ALL;
            break;
        case "help":
        default:
            HelpCommand.sendFormattedCommandHelp(context);
            return;
    }
    Launcher.getBotController().getPlayerRegistry().getOrCreate(context.guild).setRepeatMode(desiredRepeatMode);
    switch(desiredRepeatMode) {
        case OFF:
            context.reply(context.i18n("repeatOff"));
            break;
        case SINGLE:
            context.reply(context.i18n("repeatOnSingle"));
            break;
        case ALL:
            context.reply(context.i18n("repeatOnAll"));
            break;
    }
}
Also used : RepeatMode(fredboat.definitions.RepeatMode)

Example 3 with RepeatMode

use of fredboat.definitions.RepeatMode in project Backend by FredBoat.

the class EnumTypesTest method testRepeatModeEnumAllAccepted.

@Test
public void testRepeatModeEnumAllAccepted() throws Exception {
    Map<String, Object> patch = new HashMap<>();
    MockHttpServletRequestBuilder request = patch("/v1/guilds/{guild_id}/player", generateUniqueSnowflakeId()).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    for (RepeatMode repeatMode : RepeatMode.values()) {
        patch.put("repeatMode", repeatMode);
        this.mockMvc.perform(request.content(this.gson.toJson(patch))).andExpect(jsonPath("$.repeatMode", is(equalToIgnoringCase(repeatMode.name()))));
    }
}
Also used : RepeatMode(fredboat.definitions.RepeatMode) HashMap(java.util.HashMap) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) Test(org.junit.jupiter.api.Test)

Example 4 with RepeatMode

use of fredboat.definitions.RepeatMode in project Backend by FredBoat.

the class SqlSauceGuildPlayerRepo method patch.

@Override
public GuildPlayer patch(Long id, Map<String, Object> partialUpdate) {
    Function<GuildPlayer, GuildPlayer> update = guildPlayer -> guildPlayer;
    // voice channel id
    if (partialUpdate.containsKey("voiceChannelId")) {
        DiscordSnowflake voiceChannelId = PatchParseUtil.parseDiscordSnowflake("voiceChannelId", partialUpdate);
        update = update.andThen(guildPlayer -> guildPlayer.setVoiceChannelId(voiceChannelId.longValue()));
    }
    // active text channel id
    if (partialUpdate.containsKey("activeTextChannelId")) {
        DiscordSnowflake activeTextChannelId = PatchParseUtil.parseDiscordSnowflake("activeTextChannelId", partialUpdate);
        update = update.andThen(guildPlayer -> guildPlayer.setActiveTextChannelId(activeTextChannelId.longValue()));
    }
    // is paused
    if (partialUpdate.containsKey("isPaused")) {
        boolean isPaused = PatchParseUtil.parseBoolean("isPaused", partialUpdate);
        update = update.andThen(guildPlayer -> guildPlayer.setPaused(isPaused));
    }
    // volume
    if (partialUpdate.containsKey("volume")) {
        int volume = PatchParseUtil.parseInt("volume", partialUpdate);
        update = update.andThen(guildPlayer -> guildPlayer.setVolume(volume));
    }
    // repeat mode
    if (partialUpdate.containsKey("repeatMode")) {
        String repeatModeRaw = PatchParseUtil.cast("repeatMode", partialUpdate, String.class);
        Optional<RepeatMode> parse = RepeatMode.parse(repeatModeRaw);
        if (parse.isPresent()) {
            update = update.andThen(guildPlayer -> guildPlayer.setRepeatMode(parse.get()));
        } else {
            throw new RepeatModeParseException(repeatModeRaw);
        }
    }
    // is shuffled
    if (partialUpdate.containsKey("isShuffled")) {
        boolean isShuffled = PatchParseUtil.parseBoolean("isShuffled", partialUpdate);
        update = update.andThen(guildPlayer -> guildPlayer.setShuffled(isShuffled));
    }
    return this.dbWrapper.findApplyAndMerge(GuildPlayer.key(id), update);
}
Also used : RepeatMode(fredboat.definitions.RepeatMode) Component(org.springframework.stereotype.Component) PatchParseUtil(com.fredboat.backend.quarterdeck.parsing.PatchParseUtil) RepeatModeParseException(com.fredboat.backend.quarterdeck.parsing.RepeatModeParseException) Map(java.util.Map) GuildPlayer(com.fredboat.backend.quarterdeck.db.entities.main.GuildPlayer) Optional(java.util.Optional) GuildPlayerRepo(com.fredboat.backend.quarterdeck.db.repositories.api.GuildPlayerRepo) DatabaseWrapper(space.npstr.sqlsauce.DatabaseWrapper) Function(java.util.function.Function) DiscordSnowflake(com.fredboat.backend.quarterdeck.rest.v1.transfer.DiscordSnowflake) RepeatMode(fredboat.definitions.RepeatMode) RepeatModeParseException(com.fredboat.backend.quarterdeck.parsing.RepeatModeParseException) GuildPlayer(com.fredboat.backend.quarterdeck.db.entities.main.GuildPlayer) DiscordSnowflake(com.fredboat.backend.quarterdeck.rest.v1.transfer.DiscordSnowflake)

Aggregations

RepeatMode (fredboat.definitions.RepeatMode)4 GuildPlayer (com.fredboat.backend.quarterdeck.db.entities.main.GuildPlayer)1 GuildPlayerRepo (com.fredboat.backend.quarterdeck.db.repositories.api.GuildPlayerRepo)1 PatchParseUtil (com.fredboat.backend.quarterdeck.parsing.PatchParseUtil)1 RepeatModeParseException (com.fredboat.backend.quarterdeck.parsing.RepeatModeParseException)1 DiscordSnowflake (com.fredboat.backend.quarterdeck.rest.v1.transfer.DiscordSnowflake)1 MessageInput (com.sedmelluq.discord.lavaplayer.tools.io.MessageInput)1 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)1 GuildPlayer (fredboat.audio.player.GuildPlayer)1 AudioTrackContext (fredboat.audio.queue.AudioTrackContext)1 SplitAudioTrackContext (fredboat.audio.queue.SplitAudioTrackContext)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Optional (java.util.Optional)1 Function (java.util.function.Function)1 Nullable (javax.annotation.Nullable)1