forked from librespot-org/librespot-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApiClient.java
More file actions
389 lines (323 loc) · 17.2 KB
/
ApiClient.java
File metadata and controls
389 lines (323 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
* Copyright 2022 devgianlu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.gianlu.librespot.dealer;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.protobuf.Message;
import com.spotify.clienttoken.data.v0.Connectivity;
import com.spotify.clienttoken.http.v0.ClientToken;
import com.spotify.connectstate.Connect;
import com.spotify.extendedmetadata.ExtendedMetadata;
import com.spotify.extendedmetadata.ExtensionKindOuterClass;
import com.spotify.metadata.Metadata;
import com.spotify.playlist4.Playlist4ApiProto;
import okhttp3.*;
import okio.BufferedSink;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.gianlu.librespot.Version;
import xyz.gianlu.librespot.core.Session;
import xyz.gianlu.librespot.core.TokenProvider;
import xyz.gianlu.librespot.json.StationsWrapper;
import xyz.gianlu.librespot.mercury.MercuryRequests;
import xyz.gianlu.librespot.metadata.*;
import java.io.IOException;
import java.util.List;
import static com.spotify.canvaz.CanvazOuterClass.EntityCanvazRequest;
import static com.spotify.canvaz.CanvazOuterClass.EntityCanvazResponse;
/**
* @author devgianlu
*/
public final class ApiClient {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiClient.class);
private final Session session;
private final String baseUrl;
private String clientToken = null;
public ApiClient(@NotNull Session session) {
this.session = session;
this.baseUrl = "https://" + session.apResolver().getRandomSpclient();
}
@NotNull
public static RequestBody protoBody(@NotNull Message msg) {
return new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.get("application/x-protobuf");
}
@Override
public void writeTo(@NotNull BufferedSink sink) throws IOException {
sink.write(msg.toByteArray());
}
};
}
@NotNull
private Request buildRequest(@NotNull String method, @NotNull String suffix, @Nullable Headers headers, @Nullable RequestBody body) throws IOException, TokenProvider.TokenException {
if (clientToken == null) {
ClientToken.ClientTokenResponse resp = clientToken();
clientToken = resp.getGrantedToken().getToken();
LOGGER.debug("Updated client token: {}", clientToken);
}
Request.Builder request = new Request.Builder();
request.method(method, body);
if (headers != null) request.headers(headers);
request.addHeader("Authorization", "Bearer " + session.tokens().get());
request.addHeader("client-token", clientToken);
request.url(baseUrl + suffix);
return request.build();
}
public void sendAsync(@NotNull String method, @NotNull String suffix, @Nullable Headers headers, @Nullable RequestBody body, @NotNull Callback callback) throws IOException, TokenProvider.TokenException {
session.client().newCall(buildRequest(method, suffix, headers, body)).enqueue(callback);
}
/**
* Sends a request to the Spotify API.
*
* @param method The request method
* @param suffix The suffix to be appended to {@link #baseUrl} also known as path
* @param headers Additional headers
* @param body The request body
* @param tries How many times the request should be reattempted (0 = none)
* @return The response
* @throws IOException The last {@link IOException} thrown by {@link Call#execute()}
* @throws TokenProvider.TokenException If the API token couldn't be requested
*/
@NotNull
public Response send(@NotNull String method, @NotNull String suffix, @Nullable Headers headers, @Nullable RequestBody body, int tries) throws IOException, TokenProvider.TokenException {
IOException lastEx;
do {
try {
Response resp = session.client().newCall(buildRequest(method, suffix, headers, body)).execute();
if (resp.code() == 503) {
lastEx = new StatusCodeException(resp);
continue;
}
return resp;
} catch (IOException ex) {
lastEx = ex;
}
} while (tries-- > 1);
throw lastEx;
}
@NotNull
public Response send(@NotNull String method, @NotNull String suffix, @Nullable Headers headers, @Nullable RequestBody body) throws IOException, TokenProvider.TokenException {
return send(method, suffix, headers, body, 1);
}
public void putConnectState(@NotNull String connectionId, @NotNull Connect.PutStateRequest proto) throws IOException, TokenProvider.TokenException {
try (Response resp = send("PUT", "/connect-state/v1/devices/" + session.deviceId(), new Headers.Builder()
.add("X-Spotify-Connection-Id", connectionId).build(), protoBody(proto), 5 /* We want this to succeed */)) {
if (resp.code() == 413)
LOGGER.warn("PUT state payload is too large: {} bytes uncompressed.", proto.getSerializedSize());
else if (resp.code() != 200)
LOGGER.warn("PUT state returned {}. {headers: {}}", resp.code(), resp.headers());
}
}
@NotNull
public Metadata.Track getMetadata4Track(@NotNull TrackId track) throws IOException, TokenProvider.TokenException {
ExtendedMetadata.BatchedExtensionResponse response = getExtendedMetadata(ExtensionKindOuterClass.ExtensionKind.TRACK_V4, track);
checkExtendedMetadataResponse(response);
return Metadata.Track.parseFrom(response.getExtendedMetadata(0).getExtensionData(0).getExtensionData().getValue());
}
@NotNull
public Metadata.Episode getMetadata4Episode(@NotNull EpisodeId episode) throws IOException, TokenProvider.TokenException {
ExtendedMetadata.BatchedExtensionResponse response = getExtendedMetadata(ExtensionKindOuterClass.ExtensionKind.EPISODE_V4, episode);
checkExtendedMetadataResponse(response);
return Metadata.Episode.parseFrom(response.getExtendedMetadata(0).getExtensionData(0).getExtensionData().getValue());
}
@NotNull
public Metadata.Album getMetadata4Album(@NotNull AlbumId album) throws IOException, TokenProvider.TokenException {
ExtendedMetadata.BatchedExtensionResponse response = getExtendedMetadata(ExtensionKindOuterClass.ExtensionKind.ALBUM_V4, album);
checkExtendedMetadataResponse(response);
return Metadata.Album.parseFrom(response.getExtendedMetadata(0).getExtensionData(0).getExtensionData().getValue());
}
@NotNull
public Metadata.Artist getMetadata4Artist(@NotNull ArtistId artist) throws IOException, TokenProvider.TokenException {
ExtendedMetadata.BatchedExtensionResponse response = getExtendedMetadata(ExtensionKindOuterClass.ExtensionKind.ARTIST_V4, artist);
checkExtendedMetadataResponse(response);
return Metadata.Artist.parseFrom(response.getExtendedMetadata(0).getExtensionData(0).getExtensionData().getValue());
}
@NotNull
public Metadata.Show getMetadata4Show(@NotNull ShowId show) throws IOException, TokenProvider.TokenException {
ExtendedMetadata.BatchedExtensionResponse response = getExtendedMetadata(ExtensionKindOuterClass.ExtensionKind.SHOW_V4, show);
checkExtendedMetadataResponse(response);
return Metadata.Show.parseFrom(response.getExtendedMetadata(0).getExtensionData(0).getExtensionData().getValue());
}
@NotNull
public EntityCanvazResponse getCanvases(@NotNull EntityCanvazRequest req) throws IOException, TokenProvider.TokenException {
try (Response resp = send("POST", "/canvaz-cache/v0/canvases", null, protoBody(req))) {
StatusCodeException.checkStatus(resp);
ResponseBody body;
if ((body = resp.body()) == null) throw new IOException();
return EntityCanvazResponse.parseFrom(body.byteStream());
}
}
public void checkExtendedMetadataResponse(ExtendedMetadata.BatchedExtensionResponse response) throws IOException {
if (response.getExtendedMetadataCount() == 0)
throw new IOException("No metadata in BatchedExtensionResponse");
if (response.getExtendedMetadata(0).getExtensionDataCount() == 0)
throw new IOException("No metadata in ExtendedMetadata in BatchedExtensionResponse");
if (response.getExtendedMetadata(0).getExtensionData(0).getHeader().getStatusCode() != 200)
throw new IOException("Bad status code for metadata: " + response.getExtendedMetadata(0).getExtensionData(0).getHeader().getStatusCode());
}
@NotNull
public ExtendedMetadata.BatchedExtensionResponse getExtendedMetadata(@NotNull ExtendedMetadata.BatchedEntityRequest req) throws IOException, TokenProvider.TokenException {
try (Response resp = send("POST", "/extended-metadata/v0/extended-metadata", null, protoBody(req))) {
StatusCodeException.checkStatus(resp);
ResponseBody body;
if ((body = resp.body()) == null) throw new IOException();
return ExtendedMetadata.BatchedExtensionResponse.parseFrom(body.byteStream());
}
}
@NotNull
public ExtendedMetadata.BatchedExtensionResponse getExtendedMetadata(@NotNull ExtensionKindOuterClass.ExtensionKind extensionKind, @NotNull SpotifyId spotifyId) throws IOException, TokenProvider.TokenException {
try (Response resp = send("POST", "/extended-metadata/v0/extended-metadata", null, protoBody(ExtendedMetadata.BatchedEntityRequest.newBuilder()
.addEntityRequest(ExtendedMetadata.EntityRequest.newBuilder()
.setEntityUri(spotifyId.toSpotifyUri())
.addQuery(ExtendedMetadata.ExtensionQuery.newBuilder()
.setExtensionKind(extensionKind)
.build())
.build())
.build()))) {
StatusCodeException.checkStatus(resp);
ResponseBody body;
if ((body = resp.body()) == null) throw new IOException();
return ExtendedMetadata.BatchedExtensionResponse.parseFrom(body.byteStream());
}
}
@NotNull
public Playlist4ApiProto.SelectedListContent getPlaylist(@NotNull PlaylistId id) throws IOException, TokenProvider.TokenException {
try (Response resp = send("GET", "/playlist/v2/playlist/" + id.id(), null, null)) {
StatusCodeException.checkStatus(resp);
ResponseBody body;
if ((body = resp.body()) == null) throw new IOException();
return Playlist4ApiProto.SelectedListContent.parseFrom(body.byteStream());
}
}
@NotNull
public JsonObject getUserProfile(@NotNull String id, @Nullable Integer playlistLimit, @Nullable Integer artistLimit) throws IOException, TokenProvider.TokenException {
StringBuilder url = new StringBuilder();
url.append("/user-profile-view/v3/profile/");
url.append(id);
if (playlistLimit != null || artistLimit != null) {
url.append("?");
if (playlistLimit != null) {
url.append("playlist_limit=");
url.append(playlistLimit);
if (artistLimit != null)
url.append("&");
}
if (artistLimit != null) {
url.append("artist_limit=");
url.append(artistLimit);
}
}
try (Response resp = send("GET", url.toString(), null, null)) {
StatusCodeException.checkStatus(resp);
ResponseBody body;
if ((body = resp.body()) == null) throw new IOException();
return JsonParser.parseReader(body.charStream()).getAsJsonObject();
}
}
@NotNull
public JsonObject getUserFollowers(@NotNull String id) throws IOException, TokenProvider.TokenException {
try (Response resp = send("GET", "/user-profile-view/v3/profile/" + id + "/followers", null, null)) {
StatusCodeException.checkStatus(resp);
ResponseBody body;
if ((body = resp.body()) == null) throw new IOException();
return JsonParser.parseReader(body.charStream()).getAsJsonObject();
}
}
@NotNull
public JsonObject getUserFollowing(@NotNull String id) throws IOException, TokenProvider.TokenException {
try (Response resp = send("GET", "/user-profile-view/v3/profile/" + id + "/following", null, null)) {
StatusCodeException.checkStatus(resp);
ResponseBody body;
if ((body = resp.body()) == null) throw new IOException();
return JsonParser.parseReader(body.charStream()).getAsJsonObject();
}
}
@NotNull
public JsonObject getRadioForTrack(@NotNull PlayableId id) throws IOException, TokenProvider.TokenException {
try (Response resp = send("GET", "/inspiredby-mix/v2/seed_to_playlist/" + id.toSpotifyUri() + "?response-format=json", null, null)) {
StatusCodeException.checkStatus(resp);
ResponseBody body;
if ((body = resp.body()) == null) throw new IOException();
return JsonParser.parseReader(body.charStream()).getAsJsonObject();
}
}
@NotNull
public StationsWrapper getApolloStation(@NotNull String context, @NotNull List<String> prevTracks, int count, boolean autoplay) throws IOException, TokenProvider.TokenException {
StringBuilder prevTracksStr = new StringBuilder();
for (int i = 0; i < prevTracks.size(); i++) {
if (i != 0) prevTracksStr.append(",");
prevTracksStr.append(prevTracks.get(i));
}
try (Response resp = send("GET", String.format("/radio-apollo/v3/stations/%s?count=%d&prev_tracks=%s&autoplay=%b", context, count, prevTracksStr, autoplay), null, null)) {
StatusCodeException.checkStatus(resp);
ResponseBody body;
if ((body = resp.body()) == null) throw new IOException();
return new StationsWrapper(JsonParser.parseReader(body.charStream()).getAsJsonObject());
}
}
@NotNull
private ClientToken.ClientTokenResponse clientToken() throws IOException {
ClientToken.ClientTokenRequest protoReq = ClientToken.ClientTokenRequest.newBuilder()
.setRequestType(ClientToken.ClientTokenRequestType.REQUEST_CLIENT_DATA_REQUEST)
.setClientData(ClientToken.ClientDataRequest.newBuilder()
.setClientId(MercuryRequests.KEYMASTER_CLIENT_ID)
.setClientVersion(Version.versionNumber())
.setConnectivitySdkData(Connectivity.ConnectivitySdkData.newBuilder()
.setDeviceId(session.deviceId())
.setPlatformSpecificData(Connectivity.PlatformSpecificData.newBuilder()
.setWindows(Connectivity.NativeWindowsData.newBuilder()
.setSomething1(10)
.setSomething3(21370)
.setSomething4(2)
.setSomething6(9)
.setSomething7(332)
.setSomething8(34404)
.setSomething10(true)
.build())
.build())
.build())
.build())
.build();
Request.Builder req = new Request.Builder()
.url("https://clienttoken.spotify.com/v1/clienttoken")
.header("Accept", "application/x-protobuf")
.header("Content-Encoding", "")
.post(protoBody(protoReq));
try (Response resp = session.client().newCall(req.build()).execute()) {
StatusCodeException.checkStatus(resp);
ResponseBody body = resp.body();
if (body == null) throw new IOException();
return ClientToken.ClientTokenResponse.parseFrom(body.byteStream());
}
}
public void setClientToken(@Nullable String clientToken) {
this.clientToken = clientToken;
}
public static class StatusCodeException extends IOException {
public final int code;
StatusCodeException(@NotNull Response resp) {
super(String.format("%d: %s", resp.code(), resp.message()));
code = resp.code();
}
private static void checkStatus(@NotNull Response resp) throws StatusCodeException {
if (resp.code() != 200) throw new StatusCodeException(resp);
}
}
}