Skip to content

Commit

Permalink
V4 works!
Browse files Browse the repository at this point in the history
  • Loading branch information
duncte123 committed Nov 26, 2023
1 parent 6341f8d commit 60b46dd
Show file tree
Hide file tree
Showing 25 changed files with 253 additions and 251 deletions.
8 changes: 7 additions & 1 deletion bot/src/main/java/fredboat/audio/player/LavalinkManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import dev.arbjerg.lavalink.client.*;
import dev.arbjerg.lavalink.protocol.v4.Message;
import dev.arbjerg.lavalink.protocol.v4.Track;
import ml.duncte123.skybot.SkyBot;
import ml.duncte123.skybot.objects.config.DunctebotConfig;
import ml.duncte123.skybot.utils.AirUtils;
Expand Down Expand Up @@ -170,12 +171,15 @@ private void registerPlayerUpdateEvent() {

private void registerTrackStartEvent() {
lavalink.on(TrackStartEvent.class).subscribe((data) -> {
System.out.println("Track start event: " + data);
final var event = data.getEvent();
final long guildIdLong = Long.parseUnsignedLong(event.getGuildId());
final var mng = audioUtils.getMusicManagers().get(guildIdLong);

if (mng != null) {
mng.getScheduler().onTrackStart(event.getTrack());
final Track track = event.getTrack();
mng.getPlayer().updateCurrentTrack(track);
mng.getScheduler().onTrackStart(track);
}
});
}
Expand All @@ -187,6 +191,7 @@ private void registerTrackEndEvent() {
final var mng = audioUtils.getMusicManagers().get(guildIdLong);

if (mng != null) {
mng.getPlayer().updateCurrentTrack(null);
mng.getScheduler().onTrackEnd(event.getTrack(), event.getReason());
}
});
Expand All @@ -199,6 +204,7 @@ private void registerTrackExceptionEvent() {
final var mng = audioUtils.getMusicManagers().get(guildIdLong);

if (mng != null) {
mng.getPlayer().updateCurrentTrack(null);
mng.getScheduler().onTrackException(event.getTrack(), event.getException());
}
});
Expand Down
53 changes: 27 additions & 26 deletions bot/src/main/java/ml/duncte123/skybot/audio/AudioLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@

import javax.annotation.Nullable;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;

Expand Down Expand Up @@ -75,8 +76,7 @@ public void accept(LoadResult loadResult) {
private void trackLoaded(LoadResult.TrackLoaded data) {
final Track track = data.getData();

// TODO: Find a way to keep track of user-data
track.setUserData(new TrackUserData(this.requester));
mng.getScheduler().storeUserData(track, new TrackUserData(this.requester));

final TrackScheduler scheduler = this.mng.getScheduler();

Expand Down Expand Up @@ -150,27 +150,16 @@ private void playlistLoaded(LoadResult.PlaylistLoaded playlistLoaded) {

final List<Track> tracks = tracksRaw.stream().peek((track) -> {
// don't store this externally since it will cause issues
track.setUserData(new TrackUserData(this.requester));
mng.getScheduler().storeUserData(track, new TrackUserData(this.requester));
}).toList();

for (final Track track : tracks) {
trackScheduler.addToQueue(track, this.isPatron);
}

if (this.announce) {
final String sizeMsg;

if (playlist instanceof BigChungusPlaylist bigBoi && bigBoi.isBig()) {
sizeMsg = tracks.size() + "/" + bigBoi.getOriginalSize();
} else {
sizeMsg = String.valueOf(tracks.size());
}

final String msg = String.format(
"Adding **%s** tracks to the queue from **%s**",
sizeMsg,
playlistInfo.getName()
);
// TODO: find a way to fix up BigChungusPlaylist
final String msg = getPlaylistMsg(tracks, playlistInfo);

sendMsg(
new MessageConfig.Builder()
Expand All @@ -196,6 +185,22 @@ private void playlistLoaded(LoadResult.PlaylistLoaded playlistLoaded) {
}
}

private String getPlaylistMsg(List<Track> tracks, PlaylistInfo playlistInfo) {
final String sizeMsg = String.valueOf(tracks.size());

/*if (playlist instanceof BigChungusPlaylist bigBoi && bigBoi.isBig()) {
sizeMsg = tracks.size() + "/" + bigBoi.getOriginalSize();
} else {
sizeMsg = String.valueOf(tracks.size());
}*/

return String.format(
"Adding **%s** tracks to the queue from **%s**",
sizeMsg,
playlistInfo.getName()
);
}

private void searchLoaded(LoadResult.SearchResult searchResult) {
// TODO: common method for handling playlists
}
Expand All @@ -213,7 +218,7 @@ private void noMatches() {
}

private void loadFailed(Exception exception) {
if (exception.getCause() != null && exception.getCause() instanceof final LimitReachedException cause) {
/*if (exception.getCause() != null && exception.getCause() instanceof final LimitReachedException cause) {
sendMsg(
new MessageConfig.Builder()
.setChannel(this.data.getChannel())
Expand All @@ -225,13 +230,15 @@ private void loadFailed(Exception exception) {
);
return;
}
}*/

if (!this.announce) {
return;
}

if (exception.getMessage().endsWith("Playback on other websites has been disabled by the video owner.")) {
final String finalCause = Objects.requireNonNullElse(exception.getMessage(), exception.getCause());

if (finalCause.endsWith("Playback on other websites has been disabled by the video owner.")) {
sendMsg(
new MessageConfig.Builder()
.setChannel(this.data.getChannel())
Expand All @@ -245,18 +252,12 @@ private void loadFailed(Exception exception) {
return;
}

@Nullable Throwable root = ExceptionUtils.getRootCause(exception);

if (root == null) {
root = exception;
}

sendMsg(
new MessageConfig.Builder()
.setChannel(this.data.getChannel())
.replyTo(this.data.getReplyToMessage())
.setEmbeds(
embedMessage("Could not play: " + StringKt.abbreviate(root.getMessage(), MessageEmbed.VALUE_MAX_LENGTH)
embedMessage("Could not play: " + StringKt.abbreviate(finalCause, MessageEmbed.VALUE_MAX_LENGTH)
+ "\nIf this happens often try another link or join our [discord server](https://duncte.bot/server) to get help!")
)
.build()
Expand Down
27 changes: 27 additions & 0 deletions bot/src/main/java/ml/duncte123/skybot/audio/LocalPlayer.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@

package ml.duncte123.skybot.audio;

import dev.arbjerg.lavalink.client.LavalinkPlayer;
import dev.arbjerg.lavalink.client.Link;
import dev.arbjerg.lavalink.protocol.v4.Filters;
import dev.arbjerg.lavalink.protocol.v4.PlayerState;
import dev.arbjerg.lavalink.protocol.v4.Track;
import fredboat.audio.player.LavalinkManager;
import reactor.core.publisher.Mono;

import javax.annotation.Nullable;
import java.util.concurrent.atomic.AtomicReference;
Expand All @@ -39,6 +42,10 @@ public Link getLink() {
return LavalinkManager.INS.getLavalink().getLink(this.guildId);
}

public Mono<LavalinkPlayer> getLavalinkPlayer() {
return this.getLink().getPlayer();
}

public void stopPlayback() {
this.getLink()
.updatePlayer(
Expand All @@ -48,6 +55,22 @@ public void stopPlayback() {
.subscribe();
}

public void setFilters(Filters filters) {
this.getLink()
.updatePlayer(
(player) -> player.setFilters(filters)
)
.subscribe();
}

public void seekTo(long position) {
this.getLink()
.updatePlayer(
(player) -> player.setPosition(position)
)
.subscribe();
}

@Nullable
public Track getCurrentTrack() {
return this.currentTrack.get();
Expand All @@ -72,4 +95,8 @@ public long getPosition() {
public void updateLocalPlayerState(PlayerState state) {
this.state.set(state);
}

public void updateCurrentTrack(Track track) {
this.currentTrack.set(track);
}
}
31 changes: 11 additions & 20 deletions bot/src/main/java/ml/duncte123/skybot/audio/TrackScheduler.java
Original file line number Diff line number Diff line change
Expand Up @@ -97,17 +97,6 @@ public void addToQueue(Track track, boolean isPatron) throws LimitReachedExcepti
* This is a special case for the skip command where it has to announce the next track
* due to it being a user interaction
*/
public void specialSkipCase() {
// Get the currently playing track
final Track playingTrack = this.guildMusicManager.getPlayer().getCurrentTrack();
// Set in the data that it was from a skip
getUserData(playingTrack).setWasFromSkip(true);

// We trigger a fake on track end here to make it adhere to the normal loop flow
// and inject a boolean for forcing the announcement on skip
this.onTrackEnd(playingTrack, AudioTrackEndReason.FINISHED);
}

public void skipCurrentTrack() {
this.skipTrack(true);
}
Expand Down Expand Up @@ -149,18 +138,20 @@ public void onTrackStart(Track track) {
data.setWasFromSkip(false);
}

final EmbedBuilder message = AudioTrackKt.toEmbed(
AudioTrackKt.toEmbed(
track,
this.guildMusicManager,
getInstance().getShardManager(),
false
);


sendMsg(
new MessageConfig.Builder()
.setChannel(guildMusicManager.getLatestChannel())
.setEmbeds(false, message)
false,
(message) -> {
sendMsg(
new MessageConfig.Builder()
.setChannel(guildMusicManager.getLatestChannel())
.setEmbeds(false, message)
);

return null;
}
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@

package ml.duncte123.skybot.commands.music;

import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import lavalink.client.player.LavalinkPlayer;
import dev.arbjerg.lavalink.protocol.v4.Track;
import ml.duncte123.skybot.Variables;
import ml.duncte123.skybot.audio.LocalPlayer;
import ml.duncte123.skybot.objects.command.CommandContext;
import ml.duncte123.skybot.objects.command.MusicCommand;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
Expand Down Expand Up @@ -66,15 +66,15 @@ public void run(@NotNull CommandContext ctx) {
}

public void run0(@Nonnull CommandContext ctx) throws NumberFormatException {
final LavalinkPlayer player = ctx.getAudioUtils().getMusicManager(ctx.getGuildId()).player;
final AudioTrack currentTrack = player.getPlayingTrack();
final var player = ctx.getAudioUtils().getMusicManager(ctx.getGuildId()).getPlayer();
final Track currentTrack = player.getCurrentTrack();

if (currentTrack == null) {
sendMsg(ctx, "The player is currently not playing anything");
return;
}

if (!currentTrack.isSeekable()) {
if (!currentTrack.getInfo().isSeekable()) {
sendMsg(ctx, "This track is not seekable");
return;
}
Expand All @@ -95,7 +95,7 @@ public void run0(@Nonnull CommandContext ctx) throws NumberFormatException {
}

// To hopefully prevent race conditions
final Supplier<Long> trackDuration = () -> player.getPlayingTrack().getDuration();
final Supplier<Long> trackDuration = () -> player.getCurrentTrack().getInfo().getLength();

int seconds = Integer.parseInt(seekTime) * 1000;

Expand All @@ -109,7 +109,7 @@ public void run0(@Nonnull CommandContext ctx) throws NumberFormatException {
seconds = ~seconds;
}

final Supplier<Long> trackPosition = () -> player.getPlayingTrack().getPosition();
final Supplier<Long> trackPosition = player::getPosition;
final long currentPosition = trackPosition.get();
final long newPosition = currentPosition + seconds;

Expand All @@ -131,7 +131,7 @@ public void handleEvent(@NotNull SlashCommandInteractionEvent event, @NotNull Va
event.reply("Slash command not supported yet, sorry. Please report this issue.").queue();
}

private void handleOverSkip(@NotNull CommandContext ctx, LavalinkPlayer player, String arg0, Supplier<Long> trackDuration) {
private void handleOverSkip(@NotNull CommandContext ctx, LocalPlayer player, String arg0, Supplier<Long> trackDuration) {
if (arg0.charAt(0) == '-') {
sendMsg(ctx, "You're trying to skip more than the length of the track into the negatives?");
return;
Expand All @@ -141,7 +141,7 @@ private void handleOverSkip(@NotNull CommandContext ctx, LavalinkPlayer player,
player.seekTo(trackDuration.get());
}

private void handleTimeSkip(@NotNull CommandContext ctx, LavalinkPlayer player, Matcher matcher) {
private void handleTimeSkip(@NotNull CommandContext ctx, LocalPlayer player, Matcher matcher) {
final long minutes = Long.parseLong(matcher.group(1)) * 60 * 1000;
final long seconds = Long.parseLong(matcher.group(2)) * 1000;

Expand Down
19 changes: 14 additions & 5 deletions bot/src/main/java/ml/duncte123/skybot/utils/AudioUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@
import com.sedmelluq.discord.lavaplayer.track.AudioItem;
import com.sedmelluq.discord.lavaplayer.track.AudioReference;
import com.sedmelluq.discord.lavaplayer.track.BasicAudioPlaylist;
import fredboat.audio.player.LavalinkManager;
import gnu.trove.map.TLongObjectMap;
import lavalink.client.LavalinkUtil;
import ml.duncte123.skybot.Variables;
import ml.duncte123.skybot.audio.AudioLoader;
import ml.duncte123.skybot.audio.GuildMusicManager;
Expand All @@ -43,6 +43,7 @@
import net.dv8tion.jda.api.entities.Guild;
import org.jetbrains.annotations.Nullable;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

public class AudioUtils {
Expand All @@ -66,7 +67,6 @@ public AudioUtils(DunctebotConfig.Apis config, Variables variables) {
playerManager.registerSourceManager(this.youtubeManager);

DuncteBotSources.registerDuncteBot(playerManager, "en-AU", 6);
DuncteBotSources.registerDuncteBot(LavalinkUtil.getPlayerManager(), "en-AU", 6);

playerManager.registerSourceManager(SoundCloudAudioSourceManager.createDefault());
playerManager.registerSourceManager(new BandcampAudioSourceManager());
Expand Down Expand Up @@ -106,9 +106,18 @@ public Future<Void> loadAndPlay(final AudioData data, final String trackUrlRaw,

final GuildMusicManager mng = getMusicManager(data.getGuildId());
final AudioLoader loader = new AudioLoader(data, mng, announce, trackUrl, isPatron);
final DBAudioRef reference = new DBAudioRef(trackUrl, null, isPatron);

return getPlayerManager().loadItemOrdered(mng, reference, loader);
// final DBAudioRef reference = new DBAudioRef(trackUrl, null, isPatron);
final CompletableFuture<Void> future = new CompletableFuture<>();

LavalinkManager.INS.getLavalink()
.getLink(data.getGuildId())
.loadItem(trackUrl)
.subscribe((result) -> {
future.complete(null);
loader.accept(result);
});

return future;
}

public GuildMusicManager getMusicManager(long guildId) {
Expand Down
Loading

0 comments on commit 60b46dd

Please sign in to comment.