Skip to content

Commit 5ed613f

Browse files
authored
Merge pull request #280 from librespot-org/core-refactoring
Core refactoring
2 parents 8170def + 4faab36 commit 5ed613f

19 files changed

Lines changed: 78 additions & 143 deletions

File tree

api/pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<groupId>xyz.gianlu.librespot</groupId>
77
<artifactId>librespot-java</artifactId>
88
<version>1.5.3-SNAPSHOT</version>
9-
<relativePath>../</relativePath>
9+
<relativePath>../pom.xml</relativePath>
1010
</parent>
1111

1212
<artifactId>librespot-api</artifactId>

api/src/main/java/xyz/gianlu/librespot/api/Utils.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public static Map<String, Deque<String>> readParameters(@NotNull HttpServerExcha
3030
byte[] buffer = new byte[1024];
3131
int count;
3232
while ((count = in.read(buffer)) > 0) out.write(buffer, 0, count);
33-
body = new String(out.toByteArray());
33+
body = out.toString();
3434
}
3535

3636
return QueryParameterUtils.mergeQueryParametersWithNewQueryString(map, body, "UTF-8");

api/src/main/java/xyz/gianlu/librespot/api/handlers/PlayerHandler.java

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -54,17 +54,11 @@ private static void setVolume(HttpServerExchange exchange, @NotNull Player playe
5454
return;
5555
}
5656

57-
if (val > 0) {
58-
player.volumeUp(val);
59-
} else if (val < 0) {
60-
player.volumeDown(Math.abs(val));
61-
} else {
62-
Utils.invalidParameter(exchange, "step", "Must be non zero");
63-
return;
64-
}
57+
if (val > 0) player.volumeUp(val);
58+
else if (val < 0) player.volumeDown(Math.abs(val));
59+
else Utils.invalidParameter(exchange, "step", "Must be non zero");
6560
} else {
6661
Utils.invalidParameter(exchange, "volume");
67-
return;
6862
}
6963
}
7064

lib/pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<groupId>xyz.gianlu.librespot</groupId>
77
<artifactId>librespot-java</artifactId>
88
<version>1.5.3-SNAPSHOT</version>
9-
<relativePath>../</relativePath>
9+
<relativePath>../pom.xml</relativePath>
1010
</parent>
1111

1212
<artifactId>librespot-lib</artifactId>

lib/src/main/java/xyz/gianlu/librespot/audio/AudioKeyManager.java

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import org.jetbrains.annotations.NotNull;
77
import org.jetbrains.annotations.Nullable;
88
import xyz.gianlu.librespot.common.Utils;
9-
import xyz.gianlu.librespot.core.PacketsManager;
9+
import xyz.gianlu.librespot.core.PacketsReceiver;
1010
import xyz.gianlu.librespot.core.Session;
1111
import xyz.gianlu.librespot.crypto.Packet;
1212

@@ -22,15 +22,16 @@
2222
/**
2323
* @author Gianlu
2424
*/
25-
public final class AudioKeyManager extends PacketsManager {
25+
public final class AudioKeyManager implements PacketsReceiver {
2626
private static final byte[] ZERO_SHORT = new byte[]{0, 0};
2727
private static final Logger LOGGER = LogManager.getLogger(AudioKeyManager.class);
2828
private static final long AUDIO_KEY_REQUEST_TIMEOUT = 2000;
2929
private final AtomicInteger seqHolder = new AtomicInteger(0);
3030
private final Map<Integer, Callback> callbacks = Collections.synchronizedMap(new HashMap<>());
31+
private final Session session;
3132

3233
public AudioKeyManager(@NotNull Session session) {
33-
super(session, "audio-keys");
34+
this.session = session;
3435
}
3536

3637
@NotNull
@@ -67,7 +68,7 @@ else throw new AesKeyException(String.format("Failed fetching audio key! {gid: %
6768
}
6869

6970
@Override
70-
protected void handle(@NotNull Packet packet) {
71+
public void dispatch(@NotNull Packet packet) {
7172
ByteBuffer payload = ByteBuffer.wrap(packet.payload);
7273
int seq = payload.getInt();
7374

@@ -89,11 +90,6 @@ protected void handle(@NotNull Packet packet) {
8990
}
9091
}
9192

92-
@Override
93-
protected void exception(@NotNull Exception ex) {
94-
LOGGER.fatal("Failed handling packet!", ex);
95-
}
96-
9793
private interface Callback {
9894
void key(byte[] key);
9995

lib/src/main/java/xyz/gianlu/librespot/audio/decrypt/AesAudioDecrypt.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public AesAudioDecrypt(byte[] key) {
3737

3838
@Override
3939
public synchronized void decryptChunk(int chunkIndex, @NotNull byte[] buffer) throws IOException {
40-
BigInteger iv = IV_INT.add(BigInteger.valueOf(CHUNK_SIZE * chunkIndex / 16));
40+
BigInteger iv = IV_INT.add(BigInteger.valueOf((long) CHUNK_SIZE * chunkIndex / 16));
4141
try {
4242
long start = System.nanoTime();
4343
for (int i = 0; i < buffer.length; i += 4096) {

lib/src/main/java/xyz/gianlu/librespot/audio/storage/ChannelManager.java

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@
66
import org.jetbrains.annotations.NotNull;
77
import xyz.gianlu.librespot.common.NameThreadFactory;
88
import xyz.gianlu.librespot.common.Utils;
9-
import xyz.gianlu.librespot.core.PacketsManager;
9+
import xyz.gianlu.librespot.core.PacketsReceiver;
1010
import xyz.gianlu.librespot.core.Session;
1111
import xyz.gianlu.librespot.crypto.Packet;
1212

1313
import java.io.ByteArrayOutputStream;
14+
import java.io.Closeable;
1415
import java.io.DataOutputStream;
1516
import java.io.IOException;
1617
import java.nio.ByteBuffer;
@@ -25,15 +26,16 @@
2526
/**
2627
* @author Gianlu
2728
*/
28-
public class ChannelManager extends PacketsManager {
29+
public class ChannelManager implements Closeable, PacketsReceiver {
2930
public static final int CHUNK_SIZE = 128 * 1024;
3031
private static final Logger LOGGER = LogManager.getLogger(ChannelManager.class);
3132
private final Map<Short, Channel> channels = new HashMap<>();
3233
private final AtomicInteger seqHolder = new AtomicInteger(0);
3334
private final ExecutorService executorService = Executors.newCachedThreadPool(new NameThreadFactory(r -> "channel-queue-" + r.hashCode()));
35+
private final Session session;
3436

3537
public ChannelManager(@NotNull Session session) {
36-
super(session, "channels");
38+
this.session = session;
3739
}
3840

3941
void requestChunk(@NotNull ByteString fileId, int index, @NotNull AudioFile file) throws IOException {
@@ -59,12 +61,7 @@ void requestChunk(@NotNull ByteString fileId, int index, @NotNull AudioFile file
5961
}
6062

6163
@Override
62-
protected void handle(@NotNull Packet packet) {
63-
throw new UnsupportedOperationException();
64-
}
65-
66-
@Override
67-
protected void appendToQueue(@NotNull Packet packet) {
64+
public void dispatch(@NotNull Packet packet) {
6865
ByteBuffer payload = ByteBuffer.wrap(packet.payload);
6966
if (packet.is(Packet.Type.StreamChunkRes)) {
7067
short id = payload.getShort();
@@ -89,15 +86,9 @@ protected void appendToQueue(@NotNull Packet packet) {
8986
}
9087
}
9188

92-
@Override
93-
protected void exception(@NotNull Exception ex) {
94-
LOGGER.fatal("Failed handling packet!", ex);
95-
}
96-
9789
@Override
9890
public void close() {
9991
executorService.shutdown();
100-
super.close();
10192
}
10293

10394
public class Channel {

lib/src/main/java/xyz/gianlu/librespot/cache/CacheJournal.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ List<String> getEntries() throws IOException {
138138

139139
int i = 0;
140140
while (true) {
141-
io.seek(i * JOURNAL_ENTRY_SIZE);
141+
io.seek((long) i * JOURNAL_ENTRY_SIZE);
142142

143143
int first = io.read();
144144
if (first == -1) // EOF
@@ -178,7 +178,7 @@ private Entry find(@NotNull String id) throws IOException {
178178

179179
int i = 0;
180180
while (true) {
181-
io.seek(i * JOURNAL_ENTRY_SIZE);
181+
io.seek((long) i * JOURNAL_ENTRY_SIZE);
182182

183183
int first = io.read();
184184
if (first == -1) // EOF
@@ -208,7 +208,7 @@ void createIfNeeded(@NotNull String id) throws IOException {
208208

209209
int i = 0;
210210
while (true) {
211-
io.seek(i * JOURNAL_ENTRY_SIZE);
211+
io.seek((long) i * JOURNAL_ENTRY_SIZE);
212212

213213
int first = io.read();
214214
if (first == 0 || first == -1) { // First empty spot or EOF
@@ -280,7 +280,7 @@ void setHeader(int id, @NotNull String value) throws IOException {
280280
if (index == -1) throw new IllegalStateException();
281281
}
282282

283-
io.seek(offset + MAX_ID_LENGTH + MAX_CHUNKS_SIZE + index * (MAX_HEADER_LENGTH + 1));
283+
io.seek(offset + MAX_ID_LENGTH + MAX_CHUNKS_SIZE + (long) index * (MAX_HEADER_LENGTH + 1));
284284
io.write(id);
285285
io.write(value.getBytes(StandardCharsets.US_ASCII));
286286
}
@@ -308,7 +308,7 @@ JournalHeader getHeader(int id) throws IOException {
308308
int index = findHeader(id);
309309
if (index == -1) return null;
310310

311-
io.seek(offset + MAX_ID_LENGTH + MAX_CHUNKS_SIZE + index * (MAX_HEADER_LENGTH + 1) + 1);
311+
io.seek(offset + MAX_ID_LENGTH + MAX_CHUNKS_SIZE + (long) index * (MAX_HEADER_LENGTH + 1) + 1);
312312
byte[] read = new byte[MAX_HEADER_LENGTH];
313313
io.read(read);
314314

lib/src/main/java/xyz/gianlu/librespot/cache/CacheManager.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ public boolean hasChunk(int index) throws IOException {
197197
updateTimestamp();
198198

199199
synchronized (io) {
200-
if (io.length() < (index + 1) * CHUNK_SIZE)
200+
if (io.length() < (long) (index + 1) * CHUNK_SIZE)
201201
return false;
202202
}
203203

@@ -219,7 +219,7 @@ public byte[] readChunk(int index) throws IOException, BadChunkHashException {
219219
updateTimestamp();
220220

221221
synchronized (io) {
222-
io.seek(index * CHUNK_SIZE);
222+
io.seek((long) index * CHUNK_SIZE);
223223

224224
byte[] buffer = new byte[CHUNK_SIZE];
225225
int read = io.read(buffer);
@@ -248,7 +248,7 @@ public byte[] readChunk(int index) throws IOException, BadChunkHashException {
248248

249249
public void writeChunk(byte[] buffer, int index) throws IOException {
250250
synchronized (io) {
251-
io.seek(index * CHUNK_SIZE);
251+
io.seek((long) index * CHUNK_SIZE);
252252
io.write(buffer);
253253
}
254254

lib/src/main/java/xyz/gianlu/librespot/common/ProtoUtils.java

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -165,12 +165,12 @@ public static Player.PlayOrigin convertPlayOrigin(@Nullable PlayOrigin po) {
165165

166166
Player.PlayOrigin.Builder builder = Player.PlayOrigin.newBuilder();
167167

168-
Optional.ofNullable(po.getFeatureIdentifier()).ifPresent(builder::setFeatureIdentifier);
169-
Optional.ofNullable(po.getFeatureVersion()).ifPresent(builder::setFeatureVersion);
170-
Optional.ofNullable(po.getViewUri()).ifPresent(builder::setViewUri);
171-
Optional.ofNullable(po.getExternalReferrer()).ifPresent(builder::setExternalReferrer);
172-
Optional.ofNullable(po.getReferrerIdentifier()).ifPresent(builder::setReferrerIdentifier);
173-
Optional.ofNullable(po.getDeviceIdentifier()).ifPresent(builder::setDeviceIdentifier);
168+
if (po.hasFeatureIdentifier()) builder.setFeatureIdentifier(po.getFeatureIdentifier());
169+
if (po.hasFeatureVersion()) builder.setFeatureVersion(po.getFeatureVersion());
170+
if (po.hasViewUri()) builder.setViewUri(po.getViewUri());
171+
if (po.hasExternalReferrer()) builder.setExternalReferrer(po.getExternalReferrer());
172+
if (po.hasReferrerIdentifier()) builder.setReferrerIdentifier(po.getReferrerIdentifier());
173+
if (po.hasDeviceIdentifier()) builder.setDeviceIdentifier(po.getDeviceIdentifier());
174174

175175
if (po.getFeatureClassesCount() > 0)
176176
for (String feature : po.getFeatureClassesList())
@@ -254,9 +254,11 @@ public static int indexOfTrackByUri(@NotNull List<ContextTrack> tracks, @NotNull
254254
}
255255

256256
public static boolean isQueued(@NotNull ContextTrack track) {
257-
String value = track.getMetadataOrDefault("is_queued", null);
258-
if (value == null) return false;
259-
else return Boolean.parseBoolean(value);
257+
try {
258+
return Boolean.parseBoolean(track.getMetadataOrThrow("is_queued"));
259+
} catch (IllegalArgumentException ex) {
260+
return false;
261+
}
260262
}
261263

262264
public static void enrichTrack(@NotNull ContextTrack.Builder subject, @NotNull ContextTrack track) {
@@ -283,10 +285,18 @@ public static Player.ProvidedTrack convertToProvidedTrack(@Nullable ContextTrack
283285

284286
Player.ProvidedTrack.Builder builder = Player.ProvidedTrack.newBuilder();
285287
builder.setProvider("context");
286-
Optional.ofNullable(track.getUri()).ifPresent(builder::setUri);
287-
Optional.ofNullable(track.getUid()).ifPresent(builder::setUid);
288-
Optional.ofNullable(track.getMetadataOrDefault("album_uri", null)).ifPresent(builder::setAlbumUri);
289-
Optional.ofNullable(track.getMetadataOrDefault("artist_uri", null)).ifPresent(builder::setArtistUri);
288+
if (track.hasUri()) builder.setUri(track.getUri());
289+
if (track.hasUid()) builder.setUid(track.getUid());
290+
291+
try {
292+
builder.setAlbumUri(track.getMetadataOrThrow("album_uri"));
293+
} catch (IllegalArgumentException ignored) {
294+
}
295+
296+
try {
297+
builder.setArtistUri(track.getMetadataOrThrow("artist_uri"));
298+
} catch (IllegalArgumentException ignored) {
299+
}
290300

291301
builder.putAllMetadata(track.getMetadataMap());
292302

0 commit comments

Comments
 (0)