Skip to content
This repository has been archived by the owner on Jul 23, 2020. It is now read-only.

Commit

Permalink
Merge pull request #3 from SamOphis/dev-version
Browse files Browse the repository at this point in the history
Update LavaClient to v1.2
  • Loading branch information
luaugg authored Jun 5, 2018
2 parents f3fe7fa + 9bfac09 commit 1a04382
Show file tree
Hide file tree
Showing 11 changed files with 98 additions and 17 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ plugins {

group 'samophis'
description 'Fast client implementation for Lavalink.'
version '1.1.0'
version '1.2.0'

task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,11 @@ public interface AudioNode {
*/
@SuppressWarnings("all")
boolean isAvailable();

/**
* Returns whether or not this node is running Lavalink v3 based on response headers from the initial connection + possible fallback on entry.
* <br><p>This method will fallback on the deprecated {@link AudioNodeEntry#isUsingLavalinkVersionThree()}} method if it doesn't automatically detect v3.</p>
* @return Whether or not this node is running Lavalink v3.
*/
boolean isUsingLavalinkVersionThree();
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
* Represents an entry for an {@link AudioNode AudioNode} with configuration options.
Expand Down Expand Up @@ -85,8 +86,16 @@ public interface AudioNodeEntry {

/**
* Returns whether or not the {@link AudioNode AudioNode} this entry represents is running Lavalink Server v3.
* <br><p>If this value is true, any {@link AudioWrapper AudioWrapper} returned from loading tracks will be missing everything besides the track list.</p>
* <br><p>If this value is true, any {@link AudioWrapper AudioWrapper} returned from loading tracks will be missing everything besides the track list.
* <br>Deprecated since v1.2 as the newest versions of Lavalink v3 report their version server-side.</p>
* @return Whether or not this node is running Lavalink Server v3.
*/
@Deprecated
boolean isUsingLavalinkVersionThree();

/**
* Fetches the <b>possibly-null</b> {@link SocketInitializer SocketInitializer} used to "initialize" a LavaClient WebSocket connection.
* @return The <b>possibly-null</b> {@link SocketInitializer SocketInitializer} attached to this node entry.
*/
@Nullable SocketInitializer getSocketInitializer();
}
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,11 @@ public interface LavaClient {

/**
* Fetches whether LavaClient should by-default treat all {@link AudioNode AudioNodes} it has access to as using Lavalink Server v3.
* <br><p>This value equates to {@value VERSION_THREE_ENABLED} if it's not specified during the construction of the LavaClient instance.</p>
* <br><p>This value equates to {@value VERSION_THREE_ENABLED} if it's not specified during the construction of the LavaClient instance.
* <br>Deprecated since v1.2 as the newest versions of Lavalink v3 report their version server-side.</p>
* @return Whether LavaClient should treat all nodes as using Lavalink Server v3.
*/
@Deprecated
boolean isGloballyUsingLavalinkVersionThree();

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package samophis.lavalink.client.entities;

import com.neovisionaries.ws.client.WebSocket;
import javax.annotation.Nonnull;

/**
* Represents an initializer that allows users to modify the raw WebSocket instance before LavaClient opens a connection to it.
* <br><p>Any node created with this initializer will maintain its set properties even after being re-created.
* Additionally, it is recommended to use the Java 8 Lambda features for code cleanliness. If you don't know how to use them LavaClient probably isn't the library for you.</p>
*
* @since 1.2
* @author SamOphis
*/

@FunctionalInterface
public interface SocketInitializer {
/**
* The actual method used to initialize a pre-created WebSocket before a connection is made with it.
* @param socket A WebSocket instance.
* @return A <b>not-null</b> WebSocket instance with the updated properties.
*/
@Nonnull WebSocket initialize(WebSocket socket);
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import samophis.lavalink.client.entities.AudioNodeEntry;
import samophis.lavalink.client.entities.LavaClient;
import samophis.lavalink.client.entities.SocketInitializer;
import samophis.lavalink.client.entities.internal.AudioNodeEntryImpl;
import samophis.lavalink.client.util.Asserter;

Expand All @@ -28,7 +29,8 @@ public class AudioNodeEntryBuilder {
private String address, password;
private int restPort, wsPort;
private boolean isUsingVersionThree;
@SuppressWarnings("WeakerAccess")
private SocketInitializer initializer;
@SuppressWarnings({"deprecation", "WeakerAccess"})
public AudioNodeEntryBuilder(@Nonnull LavaClient client) {
this.client = Asserter.requireNotNull(client);
this.isUsingVersionThree = client.isGloballyUsingLavalinkVersionThree();
Expand All @@ -49,11 +51,18 @@ public AudioNodeEntryBuilder setWsPort(int wsPort) {
this.wsPort = wsPort;
return this;
}
public AudioNodeEntryBuilder setSocketInitializer(SocketInitializer initializer) {
this.initializer = initializer;
return this;
}
@Deprecated
// LavaClient automatically detects if a node is running v3 based on response headers.
// This serves no use besides compatibility with older v3 nodes.
public AudioNodeEntryBuilder setIsUsingVersionThree(boolean isUsingVersionThree) {
this.isUsingVersionThree = isUsingVersionThree;
return this;
}
public AudioNodeEntry build() {
return new AudioNodeEntryImpl(client, address, password, restPort, wsPort, isUsingVersionThree);
return new AudioNodeEntryImpl(client, address, password, restPort, wsPort, isUsingVersionThree, initializer);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,9 @@ public LavaClientBuilder setGlobalWebSocketPort(int wsPort) {
this.wsPort = wsPort;
return this;
}
@Deprecated
// LavaClient automatically detects if a node is running v3 based on response headers.
// This serves no use besides compatibility with older v3 nodes.
public LavaClientBuilder setGloballyUsingLavalinkVersionThree(boolean usingLavalinkVersionThree) {
this.isGloballyUsingLavalinkVersionThree = usingLavalinkVersionThree;
return this;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@

import samophis.lavalink.client.entities.AudioNodeEntry;
import samophis.lavalink.client.entities.LavaClient;
import samophis.lavalink.client.entities.SocketInitializer;
import samophis.lavalink.client.util.Asserter;

import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.regex.Pattern;

public class AudioNodeEntryImpl implements AudioNodeEntry {
Expand All @@ -31,7 +33,8 @@ public class AudioNodeEntryImpl implements AudioNodeEntry {
private final String address, password, httpAddress, wsAddress;
private final int rest, ws;
private final boolean isUsingVersionThree;
public AudioNodeEntryImpl(LavaClient client, String address, String password, int rest, int ws, boolean isUsingVersionThree) {
private final SocketInitializer initializer;
public AudioNodeEntryImpl(LavaClient client, String address, String password, int rest, int ws, boolean isUsingVersionThree, SocketInitializer initializer) {
this.client = Asserter.requireNotNull(client);
this.address = Asserter.requireNotNull(address);
this.httpAddress = !HTTP_PATTERN.matcher(address).find() ? "http://" + address : address;
Expand All @@ -40,6 +43,7 @@ public AudioNodeEntryImpl(LavaClient client, String address, String password, in
this.rest = rest == 0 ? client.getGlobalRestPort() : rest;
this.ws = ws == 0 ? client.getGlobalWebSocketPort() : ws;
this.isUsingVersionThree = isUsingVersionThree;
this.initializer = initializer;
}
@Override
@Nonnull
Expand Down Expand Up @@ -80,4 +84,9 @@ public int getWebSocketPort() {
public boolean isUsingLavalinkVersionThree() {
return isUsingVersionThree;
}
@Nullable
@Override
public SocketInitializer getSocketInitializer() {
return initializer;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ public class AudioNodeImpl extends WebSocketAdapter implements AudioNode {
private final AudioNodeEntry entry;
private WebSocket socket;
private Statistics statistics;
private AtomicInteger reconnectInterval;
private AtomicInteger reconnectInterval, reconnectAttempts;
private volatile boolean usingVersionThree;
@SuppressWarnings("WeakerAccess")
public AudioNodeImpl(@Nonnull LavaClient client, @Nonnull AudioNodeEntry entry) {
Asserter.requireNotNull(client);
Expand All @@ -57,10 +58,14 @@ public AudioNodeImpl(@Nonnull LavaClient client, @Nonnull AudioNodeEntry entry)
this.balancer = new LoadBalancerImpl(this);
this.entry = entry;
this.reconnectInterval = new AtomicInteger(1000);
this.reconnectAttempts = new AtomicInteger(0);
this.usingVersionThree = false;
try {
this.socket = new WebSocketFactory()
.createSocket(entry.getWebSocketAddress() + ":" + entry.getWebSocketPort())
.addListener(this)
WebSocket socket = new WebSocketFactory().createSocket(entry.getWebSocketAddress() + ":" + entry.getWebSocketPort());
SocketInitializer init = entry.getSocketInitializer();
if (init != null)
socket = Asserter.requireNotNull(init.initialize(socket));
this.socket = socket.addListener(this)
.addHeader("Authorization", entry.getPassword())
.addHeader("Num-Shards", String.valueOf(client.getShardCount()))
.addHeader("User-Id", String.valueOf(client.getUserId()))
Expand All @@ -87,8 +92,15 @@ public void onError(WebSocket websocket, WebSocketException cause){
}
@Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers) {
if (reconnectAttempts.get() == 0)
LOGGER.info("Connected!");
else
LOGGER.info("Connected after {} Reconnect Attempt(s)!", reconnectAttempts.get());
List<String> found = headers.get("Lavalink-Major-Version");
this.usingVersionThree = (found != null && found.get(0).equals("3"));
client.getPlayers().forEach(player -> player.setNode(LavaClient.getBestNode()));
reconnectInterval.set(1000);
reconnectAttempts.set(0);
}
@Override
public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
Expand All @@ -100,10 +112,11 @@ public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame,
int code = closedByServer ? serverCloseFrame.getCloseCode() : clientCloseFrame.getCloseCode();
if (closedByServer) {
if (code == 1000)
LOGGER.info("Lavalink-Server ({}:{}) closed the connection gracefully with the reason: {}", entry.getWebSocketAddress(), entry.getWebSocketPort(), reason);
LOGGER.info("Lavalink Server - {}:{} - closed the connection gracefully with the reason: {}", entry.getWebSocketAddress(), entry.getWebSocketPort(), reason);
else {
LOGGER.warn("Lavalink-Server ({}:{}) closed the connection unexpectedly with the reason: {}", entry.getWebSocketAddress(), entry.getWebSocketPort(), reason);
LOGGER.warn("Lavalink Server - {}:{} - closed the connection unexpectedly with the reason: {}", entry.getWebSocketAddress(), entry.getWebSocketPort(), reason);
int time = reconnectInterval.getAndSet(Math.min(reconnectInterval.get() * 2, 64000));
LOGGER.info("Reconnect Attempt #{}: Attempting to reconnect in {}ms...", reconnectAttempts.incrementAndGet(), time);
try {
Thread.sleep(time);
} catch (InterruptedException exc) {
Expand Down Expand Up @@ -195,4 +208,10 @@ public boolean isAvailable() {
public WebSocket getSocket() {
return socket;
}
@Override
@SuppressWarnings("deprecation")
// fallback on client-set v3 if usingVersionThree is false (in the rare case that someone is running an older version of v3)
public boolean isUsingLavalinkVersionThree() {
return usingVersionThree || entry.isUsingLavalinkVersionThree();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
package samophis.lavalink.client.entities.internal;

import com.jsoniter.JsonIterator;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
Expand All @@ -33,7 +32,6 @@
import samophis.lavalink.client.entities.messages.server.TrackLoadResult;
import samophis.lavalink.client.exceptions.HttpRequestException;
import samophis.lavalink.client.util.Asserter;
import samophis.lavalink.client.util.LavaClientUtil;

import javax.annotation.Nonnull;
import java.io.IOException;
Expand Down Expand Up @@ -76,9 +74,10 @@ public void resolveTracks(@Nonnull String identifier, @Nonnull Consumer<AudioWra
} catch (UnsupportedEncodingException exc) {
throw new HttpRequestException(exc);
}
AudioNodeEntry node = LavaClient.getBestNode().getEntry();
HttpGet request = new HttpGet(node.getHttpAddress() + ":" + node.getRestPort() + "/loadtracks?identifier=" + identifier);
request.addHeader("Authorization", node.getPassword());
AudioNode node = LavaClient.getBestNode();
AudioNodeEntry entry = node.getEntry();
HttpGet request = new HttpGet(entry.getHttpAddress() + ":" + entry.getRestPort() + "/loadtracks?identifier=" + identifier);
request.addHeader("Authorization", entry.getPassword());
http.execute(request, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse result) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ public void playTrack(@Nonnull AudioTrack track, @Nonnegative long startTime, lo
public void playTrack(@Nonnull String identifier, @Nonnegative long startTime, long endTime) {
Asserter.requireNotNegative(startTime);
TrackDataPair pair = client.getIdentifierCache().getIfPresent(identifier);
setNode(LavaClient.getBestNode());
if (pair == null) {
client.getHttpManager().resolveTracks(identifier, wrapper -> {
List<TrackDataPair> tracks = wrapper.getLoadedTracks();
Expand Down

0 comments on commit 1a04382

Please sign in to comment.