-
-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathStateWrapper.java
More file actions
1500 lines (1233 loc) · 57.8 KB
/
Copy pathStateWrapper.java
File metadata and controls
1500 lines (1233 loc) · 57.8 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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package xyz.gianlu.librespot.player;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.protobuf.ByteString;
import com.google.protobuf.TextFormat;
import com.spotify.connectstate.Connect;
import com.spotify.connectstate.Player.*;
import com.spotify.context.ContextOuterClass.Context;
import com.spotify.context.ContextPageOuterClass.ContextPage;
import com.spotify.context.ContextTrackOuterClass.ContextTrack;
import com.spotify.metadata.Metadata;
import com.spotify.playlist4.Playlist4ApiProto;
import com.spotify.playlist4.Playlist4ApiProto.PlaylistModificationInfo;
import com.spotify.transfer.PlaybackOuterClass;
import com.spotify.transfer.QueueOuterClass;
import com.spotify.transfer.SessionOuterClass;
import com.spotify.transfer.TransferStateOuterClass;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import xyz.gianlu.librespot.common.FisherYatesShuffle;
import xyz.gianlu.librespot.common.ProtoUtils;
import xyz.gianlu.librespot.common.Utils;
import xyz.gianlu.librespot.core.Session;
import xyz.gianlu.librespot.core.TimeProvider;
import xyz.gianlu.librespot.dealer.DealerClient;
import xyz.gianlu.librespot.mercury.MercuryClient;
import xyz.gianlu.librespot.metadata.*;
import xyz.gianlu.librespot.player.contexts.AbsSpotifyContext;
import xyz.gianlu.librespot.player.state.DeviceStateHandler;
import xyz.gianlu.librespot.player.state.DeviceStateHandler.PlayCommandHelper;
import xyz.gianlu.librespot.player.state.RestrictionsManager;
import xyz.gianlu.librespot.player.state.RestrictionsManager.Action;
import java.io.Closeable;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
/**
* @author Gianlu
*/
public class StateWrapper implements DeviceStateHandler.Listener, DealerClient.MessageListener, Closeable {
private static final Logger LOGGER = LoggerFactory.getLogger(StateWrapper.class);
static {
try {
ProtoUtils.overrideDefaultValue(ContextIndex.getDescriptor().findFieldByName("track"), -1);
ProtoUtils.overrideDefaultValue(com.spotify.connectstate.Player.PlayerState.getDescriptor().findFieldByName("position_as_of_timestamp"), -1);
ProtoUtils.overrideDefaultValue(ContextPlayerOptions.getDescriptor().findFieldByName("shuffling_context"), "");
ProtoUtils.overrideDefaultValue(ContextPlayerOptions.getDescriptor().findFieldByName("repeating_track"), "");
ProtoUtils.overrideDefaultValue(ContextPlayerOptions.getDescriptor().findFieldByName("repeating_context"), "");
} catch (IllegalAccessException | NoSuchFieldException ex) {
LOGGER.warn("Failed changing default value!", ex);
}
}
private final PlayerState.Builder state;
private final Session session;
private final Player player;
private final DeviceStateHandler device;
private AbsSpotifyContext context;
private PagesLoader pages;
private TracksKeeper tracksKeeper;
StateWrapper(@NotNull Session session, @NotNull Player player, @NotNull PlayerConfiguration conf) {
this.session = session;
this.player = player;
this.device = new DeviceStateHandler(session, conf);
this.state = initState(PlayerState.newBuilder());
device.addListener(this);
session.dealer().addMessageListener(this, "spotify:user:attributes:update", "hm://playlist/", "hm://collection/collection/" + session.username() + "/json");
}
@NotNull
private static PlayerState.Builder initState(@NotNull PlayerState.Builder builder) {
return builder.setPlaybackSpeed(1.0)
.clearSessionId().clearPlaybackId()
.setSuppressions(Suppressions.newBuilder().build())
.setContextRestrictions(Restrictions.newBuilder().build())
.setOptions(ContextPlayerOptions.newBuilder()
.setRepeatingContext(false)
.setShufflingContext(false)
.setRepeatingTrack(false))
.setPositionAsOfTimestamp(0)
.setPosition(0)
.setIsPlaying(false);
}
@NotNull
public static String generatePlaybackId(@NotNull Random random) {
byte[] bytes = new byte[16];
random.nextBytes(bytes);
bytes[0] = 1;
return Utils.bytesToHex(bytes).toLowerCase();
}
@NotNull
private static String generateSessionId(@NotNull Random random) {
byte[] bytes = new byte[16];
random.nextBytes(bytes);
return Base64.getEncoder().withoutPadding().encodeToString(bytes);
}
private boolean shouldPlay(@NotNull ContextTrack track) {
if (!PlayableId.isSupported(track.getUri()) || !PlayableId.shouldPlay(track))
return false;
boolean filterExplicit = Objects.equals(session.getUserAttribute("filter-explicit-content"), "1");
if (!filterExplicit) return true;
return !Boolean.parseBoolean(track.getMetadataOrDefault("is_explicit", "false"));
}
boolean isActive() {
return device.isActive();
}
synchronized void setState(boolean playing, boolean paused, boolean buffering) {
if (paused && !playing) throw new IllegalStateException();
else if (buffering && !playing) throw new IllegalStateException();
boolean wasPaused = isPaused();
state.setIsPlaying(playing).setIsPaused(paused).setIsBuffering(buffering);
if (wasPaused && !paused) // Assume the position was set immediately before pausing
setPosition(state.getPositionAsOfTimestamp());
}
synchronized boolean isPaused() {
return state.getIsPlaying() && state.getIsPaused();
}
synchronized void setBuffering(boolean buffering) {
setState(true, state.getIsPaused(), buffering);
}
private boolean isShufflingContext() {
return state.getOptions().getShufflingContext();
}
void setShufflingContext(boolean value) {
if (context == null || tracksKeeper == null) return;
boolean old = isShufflingContext();
state.getOptionsBuilder().setShufflingContext(value && context.restrictions.can(Action.SHUFFLE));
if (old != isShufflingContext()) tracksKeeper.toggleShuffle(isShufflingContext());
}
private boolean isRepeatingContext() {
return state.getOptions().getRepeatingContext();
}
void setRepeatingContext(boolean value) {
if (context == null) return;
state.getOptionsBuilder().setRepeatingContext(value && context.restrictions.can(Action.REPEAT_CONTEXT));
}
private boolean isRepeatingTrack() {
return state.getOptions().getRepeatingTrack();
}
void setRepeatingTrack(boolean value) {
if (context == null) return;
state.getOptionsBuilder().setRepeatingTrack(value && context.restrictions.can(Action.REPEAT_TRACK));
}
@NotNull
public DeviceStateHandler device() {
return device;
}
@Nullable
public String getContextUri() {
return state.getContextUri();
}
@Nullable
public String getContextUrl() {
return state.getContextUrl();
}
private void loadTransforming() {
if (tracksKeeper == null) throw new IllegalStateException();
String url = state.getContextMetadataOrDefault("transforming.url", null);
if (url == null) return;
boolean shuffle = false;
if (state.containsContextMetadata("transforming.shuffle"))
shuffle = Boolean.parseBoolean(state.getContextMetadataOrThrow("transforming.shuffle"));
boolean willRequest = !tracksKeeper.getCurrentTrack().getMetadataMap().containsKey("audio.fwdbtn.fade_overlap"); // I don't see another way to do this
LOGGER.info("Context has transforming! {url: {}, shuffle: {}, willRequest: {}}", url, shuffle, willRequest);
if (!willRequest) return;
JsonObject obj = ProtoUtils.craftContextStateCombo(state, tracksKeeper.tracks);
try (Response resp = session.api().send("POST", HttpUrl.get(url).encodedPath(), null, RequestBody.create(obj.toString(), MediaType.get("application/json")))) {
ResponseBody body = resp.body();
if (resp.code() != 200) {
LOGGER.warn("Failed loading cuepoints! {code: {}, msg: {}, body: {}}", resp.code(), resp.message(), body == null ? null : body.string());
return;
}
if (body != null) updateContext(JsonParser.parseString(body.string()).getAsJsonObject());
else throw new IllegalArgumentException();
LOGGER.debug("Updated context with transforming information!");
} catch (MercuryClient.MercuryException | IOException ex) {
LOGGER.warn("Failed loading cuepoints!", ex);
}
}
@NotNull
private String setContext(@NotNull String uri) {
this.context = AbsSpotifyContext.from(uri);
this.state.setContextUri(uri);
if (!context.isFinite()) {
setRepeatingContext(false);
setShufflingContext(false);
}
this.state.clearContextUrl();
this.state.clearRestrictions();
this.state.clearContextRestrictions();
this.state.clearContextMetadata();
this.pages = PagesLoader.from(session, uri);
this.tracksKeeper = new TracksKeeper();
this.device.setIsActive(true);
return renewSessionId();
}
@NotNull
private String setContext(@NotNull Context ctx) {
String uri = ctx.getUri();
this.context = AbsSpotifyContext.from(uri);
this.state.setContextUri(uri);
if (!context.isFinite()) {
setRepeatingContext(false);
setShufflingContext(false);
}
if (ctx.hasUrl()) this.state.setContextUrl(ctx.getUrl());
else this.state.clearContextUrl();
state.clearContextMetadata();
ProtoUtils.copyOverMetadata(ctx, state);
this.pages = PagesLoader.from(session, ctx);
this.tracksKeeper = new TracksKeeper();
this.device.setIsActive(true);
return renewSessionId();
}
private void updateRestrictions() {
if (context == null) return;
if (tracksKeeper.isPlayingFirst() && !isRepeatingContext())
context.restrictions.disallow(Action.SKIP_PREV, RestrictionsManager.REASON_NO_PREV_TRACK);
else
context.restrictions.allow(Action.SKIP_PREV);
if (tracksKeeper.isPlayingLast() && !isRepeatingContext())
context.restrictions.disallow(Action.SKIP_NEXT, RestrictionsManager.REASON_NO_NEXT_TRACK);
else
context.restrictions.allow(Action.SKIP_NEXT);
state.setRestrictions(context.restrictions.toProto());
state.setContextRestrictions(context.restrictions.toProto());
}
synchronized void updated() {
updateRestrictions();
device.updateState(Connect.PutStateReason.PLAYER_STATE_CHANGED, player.time(), state.build());
}
void addListener(@NotNull DeviceStateHandler.Listener listener) {
device.addListener(listener);
}
public boolean isReady() {
return state.getIsSystemInitiated();
}
@Override
public synchronized void ready() {
state.setIsSystemInitiated(true);
device.updateState(Connect.PutStateReason.NEW_DEVICE, player.time(), state.build());
LOGGER.info("Notified new device (us)!");
}
@Override
public void command(@NotNull DeviceStateHandler.Endpoint endpoint, @NotNull DeviceStateHandler.CommandBody data) {
// Not interested
}
@Override
public synchronized void volumeChanged() {
device.updateState(Connect.PutStateReason.VOLUME_CHANGED, player.time(), state.build());
}
@Override
public synchronized void notActive() {
state.clear();
initState(state);
device.setIsActive(false);
device.updateState(Connect.PutStateReason.BECAME_INACTIVE, player.time(), state.build());
LOGGER.info("Notified inactivity!");
}
synchronized int getVolume() {
return device.getVolume();
}
void setVolume(int val) {
device.setVolume(val);
}
void enrichWithMetadata(@NotNull TrackOrEpisode metadata) {
if (metadata.isTrack()) enrichWithMetadata(metadata.track);
else if (metadata.isEpisode()) enrichWithMetadata(metadata.episode);
}
private synchronized void enrichWithMetadata(@NotNull Metadata.Track track) {
if (state.getTrack() == null) throw new IllegalStateException();
if (!ProtoUtils.isTrack(state.getTrack(), track)) {
LOGGER.warn("Failed updating metadata: tracks do not match. {current: {}, expected: {}}", ProtoUtils.toString(state.getTrack()), ProtoUtils.toString(track));
return;
}
if (track.hasDuration()) tracksKeeper.updateTrackDuration(track.getDuration());
ProvidedTrack.Builder builder = state.getTrackBuilder();
if (track.hasPopularity()) builder.putMetadata("popularity", String.valueOf(track.getPopularity()));
if (track.hasExplicit()) builder.putMetadata("is_explicit", String.valueOf(track.getExplicit()));
if (track.hasHasLyrics()) builder.putMetadata("has_lyrics", String.valueOf(track.getHasLyrics()));
if (track.hasName()) builder.putMetadata("title", track.getName());
if (track.hasDiscNumber()) builder.putMetadata("album_disc_number", String.valueOf(track.getDiscNumber()));
for (int i = 0; i < track.getArtistCount(); i++) {
Metadata.Artist artist = track.getArtist(i);
if (artist.hasName()) builder.putMetadata("artist_name" + (i == 0 ? "" : (":" + i)), artist.getName());
if (artist.hasGid()) builder.putMetadata("artist_uri" + (i == 0 ? "" : (":" + i)),
ArtistId.fromHex(Utils.bytesToHex(artist.getGid())).toSpotifyUri());
}
if (track.hasAlbum()) {
Metadata.Album album = track.getAlbum();
if (album.getDiscCount() > 0) {
builder.putMetadata("album_track_count", String.valueOf(ProtoUtils.getTrackCount(album)));
builder.putMetadata("album_disc_count", String.valueOf(album.getDiscCount()));
}
if (album.hasName()) builder.putMetadata("album_title", album.getName());
if (album.hasGid()) builder.putMetadata("album_uri",
AlbumId.fromHex(Utils.bytesToHex(album.getGid())).toSpotifyUri());
for (int i = 0; i < album.getArtistCount(); i++) {
Metadata.Artist artist = album.getArtist(i);
if (artist.hasName())
builder.putMetadata("album_artist_name" + (i == 0 ? "" : (":" + i)), artist.getName());
if (artist.hasGid()) builder.putMetadata("album_artist_uri" + (i == 0 ? "" : (":" + i)),
ArtistId.fromHex(Utils.bytesToHex(artist.getGid())).toSpotifyUri());
}
if (track.hasDiscNumber()) {
for (Metadata.Disc disc : album.getDiscList()) {
if (disc.getNumber() != track.getDiscNumber()) continue;
for (int i = 0; i < disc.getTrackCount(); i++) {
if (disc.getTrack(i).getGid().equals(track.getGid())) {
builder.putMetadata("album_track_number", String.valueOf(i + 1));
break;
}
}
}
}
if (album.hasCoverGroup()) ImageId.putAsMetadata(builder, album.getCoverGroup());
}
ProtoUtils.putFilesAsMetadata(builder, track.getFileList());
state.setTrack(builder.build());
}
private synchronized void enrichWithMetadata(@NotNull Metadata.Episode episode) {
if (state.getTrack() == null) throw new IllegalStateException();
if (!ProtoUtils.isEpisode(state.getTrack(), episode)) {
LOGGER.warn("Failed updating metadata: episodes do not match. {current: {}, expected: {}}", ProtoUtils.toString(state.getTrack()), ProtoUtils.toString(episode));
return;
}
if (episode.hasDuration()) tracksKeeper.updateTrackDuration(episode.getDuration());
ProvidedTrack.Builder builder = state.getTrackBuilder();
if (episode.hasExplicit()) builder.putMetadata("is_explicit", String.valueOf(episode.getExplicit()));
if (episode.hasName()) builder.putMetadata("title", episode.getName());
if (episode.hasShow()) {
Metadata.Show show = episode.getShow();
if (show.hasName()) builder.putMetadata("album_title", show.getName());
if (show.hasCoverImage()) ImageId.putAsMetadata(builder, show.getCoverImage());
}
if (episode.getAudioCount() > 0 && episode.getVideoCount() == 0) {
builder.putMetadata("media.type", "audio");
} else if (episode.getVideoCount() > 0) {
builder.putMetadata("media.type", "video");
}
ProtoUtils.putFilesAsMetadata(builder, episode.getAudioList());
state.setTrack(builder.build());
}
synchronized int getPosition() {
int diff = (int) (TimeProvider.currentTimeMillis() - state.getTimestamp());
return (int) (state.getPositionAsOfTimestamp() + diff);
}
synchronized void setPosition(long pos) {
state.setTimestamp(TimeProvider.currentTimeMillis());
state.setPositionAsOfTimestamp(pos);
state.clearPosition();
}
@NotNull
String loadContextWithTracks(@NotNull String uri, @NotNull List<ContextTrack> tracks) throws MercuryClient.MercuryException, IOException, AbsSpotifyContext.UnsupportedContextException {
state.setPlayOrigin(PlayOrigin.newBuilder().build());
state.setOptions(ContextPlayerOptions.newBuilder().build());
String sessionId = setContext(uri);
pages.putFirstPage(tracks, uri);
tracksKeeper.initializeStart();
setPosition(0);
loadTransforming();
return sessionId;
}
@NotNull
String loadContext(@NotNull String uri) throws MercuryClient.MercuryException, IOException, AbsSpotifyContext.UnsupportedContextException {
state.setPlayOrigin(PlayOrigin.newBuilder().build());
state.setOptions(ContextPlayerOptions.newBuilder().build());
String sessionId = setContext(uri);
tracksKeeper.initializeStart();
setPosition(0);
loadTransforming();
return sessionId;
}
@NotNull
String transfer(@NotNull TransferStateOuterClass.TransferState cmd) throws AbsSpotifyContext.UnsupportedContextException, IOException, MercuryClient.MercuryException {
SessionOuterClass.Session ps = cmd.getCurrentSession();
state.setPlayOrigin(ProtoUtils.convertPlayOrigin(ps.getPlayOrigin()));
state.setOptions(ProtoUtils.convertPlayerOptions(cmd.getOptions()));
String sessionId = setContext(ps.getContext());
PlaybackOuterClass.Playback pb = cmd.getPlayback();
try {
tracksKeeper.initializeFrom(tracks -> {
for (int i = 0; i < tracks.size(); i++) {
ContextTrack track = tracks.get(i);
if ((track.hasUid() && ps.getCurrentUid().equals(track.getUid())) || ProtoUtils.trackEquals(track, pb.getCurrentTrack()))
return i;
}
return -1;
}, pb.getCurrentTrack(), cmd.getQueue());
} catch (IllegalStateException ex) {
LOGGER.warn("Failed initializing tracks, falling back to start. {uid: {}}", ps.getCurrentUid());
tracksKeeper.initializeStart();
}
state.setPositionAsOfTimestamp(pb.getPositionAsOfTimestamp());
if (pb.getIsPaused()) state.setTimestamp(TimeProvider.currentTimeMillis());
else state.setTimestamp(pb.getTimestamp());
loadTransforming();
return sessionId;
}
@NotNull
String load(@NotNull JsonObject obj) throws AbsSpotifyContext.UnsupportedContextException, IOException, MercuryClient.MercuryException {
state.setPlayOrigin(ProtoUtils.jsonToPlayOrigin(PlayCommandHelper.getPlayOrigin(obj)));
state.setOptions(ProtoUtils.jsonToPlayerOptions(PlayCommandHelper.getPlayerOptionsOverride(obj), state.getOptions()));
String sessionId = setContext(ProtoUtils.jsonToContext(PlayCommandHelper.getContext(obj)));
String trackUid = PlayCommandHelper.getSkipToUid(obj);
String trackUri = PlayCommandHelper.getSkipToUri(obj);
Integer trackIndex = PlayCommandHelper.getSkipToIndex(obj);
try {
if (trackUri != null && !trackUri.isEmpty()) {
tracksKeeper.initializeFrom(tracks -> ProtoUtils.indexOfTrackByUri(tracks, trackUri), null, null);
} else if (trackUid != null && !trackUid.isEmpty()) {
tracksKeeper.initializeFrom(tracks -> ProtoUtils.indexOfTrackByUid(tracks, trackUid), null, null);
} else if (trackIndex != null) {
tracksKeeper.initializeFrom(tracks -> {
if (trackIndex < tracks.size()) return trackIndex;
else return -1;
}, null, null);
} else {
tracksKeeper.initializeStart();
}
} catch (IllegalStateException ex) {
LOGGER.warn("Failed initializing tracks, falling back to start. {uri: {}, uid: {}, index: {}}", trackUri, trackUid, trackIndex);
tracksKeeper.initializeStart();
}
Integer seekTo = PlayCommandHelper.getSeekTo(obj);
if (seekTo != null) setPosition(seekTo);
else setPosition(0);
loadTransforming();
return sessionId;
}
synchronized void updateContext(@NotNull JsonObject obj) {
String uri = obj.get("uri").getAsString();
if (!context.uri().equals(uri)) {
LOGGER.warn("Received update for the wrong context! {context: {}, newUri: {}}", context, uri);
return;
}
ProtoUtils.copyOverMetadata(obj.getAsJsonObject("metadata"), state);
tracksKeeper.updateContext(ProtoUtils.jsonToContextPages(obj.getAsJsonArray("pages")));
}
void skipTo(@NotNull ContextTrack track) {
tracksKeeper.skipTo(track);
setPosition(0);
}
@Nullable
public PlayableId getCurrentPlayable() {
return tracksKeeper == null ? null : PlayableId.from(tracksKeeper.getCurrentTrack());
}
@NotNull
PlayableId getCurrentPlayableOrThrow() {
PlayableId id = getCurrentPlayable();
if (id == null) throw new IllegalStateException();
return id;
}
@NotNull
NextPlayable nextPlayable(boolean autoplayEnabled) {
if (tracksKeeper == null) return NextPlayable.MISSING_TRACKS;
try {
return tracksKeeper.nextPlayable(autoplayEnabled);
} catch (IOException | MercuryClient.MercuryException ex) {
LOGGER.error("Failed fetching next playable.", ex);
return NextPlayable.MISSING_TRACKS;
}
}
@Nullable
PlayableId nextPlayableDoNotSet() {
try {
PlayableIdWithIndex id = tracksKeeper.nextPlayableDoNotSet();
return id == null ? null : id.id;
} catch (IOException | MercuryClient.MercuryException ex) {
LOGGER.error("Failed fetching next playable.", ex);
return null;
}
}
@NotNull
PreviousPlayable previousPlayable() {
if (tracksKeeper == null) return PreviousPlayable.MISSING_TRACKS;
return tracksKeeper.previousPlayable();
}
void removeListener(@NotNull DeviceStateHandler.Listener listener) {
device.removeListener(listener);
}
synchronized void addToQueue(@NotNull ContextTrack track) {
tracksKeeper.addToQueue(track);
}
synchronized void removeFromQueue(@NotNull String uri) {
tracksKeeper.removeFromQueue(uri);
}
synchronized void setQueue(@Nullable List<ContextTrack> prevTracks, @Nullable List<ContextTrack> nextTracks) {
tracksKeeper.setQueue(prevTracks, nextTracks);
}
@NotNull
Optional<Map<String, String>> metadataFor(@NotNull PlayableId id) {
if (tracksKeeper == null) return Optional.empty();
ContextTrack current = getCurrentTrack();
if (current != null && id.matches(current))
return Optional.of(current.getMetadataMap());
int index = PlayableId.indexOfTrack(tracksKeeper.tracks, id);
if (index == -1) {
index = PlayableId.indexOfTrack(tracksKeeper.queue, id);
if (index == -1) return Optional.empty();
}
return Optional.of(tracksKeeper.tracks.get(index).getMetadataMap());
}
/**
* Performs the given add operation. This also makes sure that {@link TracksKeeper#tracks} is in a non-shuffled state,
* even if {@link StateWrapper#isShufflingContext()} may return {@code true}. Context will be therefore reshuffled.
*/
private synchronized void performAdd(@NotNull Playlist4ApiProto.Add add) {
boolean wasShuffled = false;
if (isShufflingContext()) {
wasShuffled = true;
tracksKeeper.toggleShuffle(false);
}
try {
if (add.hasAddFirst() && add.getAddFirst())
tracksKeeper.addToTracks(0, add.getItemsList());
else if (add.hasAddLast() && add.getAddLast())
tracksKeeper.addToTracks(tracksKeeper.length(), add.getItemsList());
else if (add.hasFromIndex())
tracksKeeper.addToTracks(add.getFromIndex(), add.getItemsList());
else
throw new IllegalArgumentException(TextFormat.shortDebugString(add));
} finally {
if (wasShuffled) tracksKeeper.toggleShuffle(true);
}
}
/**
* Performs the given remove operation. This also makes sure that {@link TracksKeeper#tracks} is in a non-shuffled state,
* even if {@link StateWrapper#isShufflingContext()} may return {@code true}. Context will be therefore reshuffled.
*/
private synchronized void performRemove(@NotNull Playlist4ApiProto.Rem rem) {
boolean wasShuffled = false;
if (isShufflingContext()) {
wasShuffled = true;
tracksKeeper.toggleShuffle(false);
}
try {
if (rem.hasFromIndex() && rem.hasLength()) tracksKeeper.removeTracks(rem.getFromIndex(), rem.getLength());
else throw new IllegalArgumentException(TextFormat.shortDebugString(rem));
} finally {
if (wasShuffled) tracksKeeper.toggleShuffle(true);
}
}
/**
* Performs the given move operation. This also makes sure that {@link TracksKeeper#tracks} is in a non-shuffled state,
* even if {@link StateWrapper#isShufflingContext()} may return {@code true}. Context will be therefore reshuffled.
*/
private synchronized void performMove(@NotNull Playlist4ApiProto.Mov mov) {
boolean wasShuffled = false;
if (isShufflingContext()) {
wasShuffled = true;
tracksKeeper.toggleShuffle(false);
}
try {
if (mov.hasFromIndex() && mov.hasToIndex() && mov.hasLength())
tracksKeeper.moveTracks(mov.getFromIndex(), mov.getToIndex(), mov.getLength());
else
throw new IllegalArgumentException(TextFormat.shortDebugString(mov));
} finally {
if (wasShuffled) tracksKeeper.toggleShuffle(true);
}
}
@Override
public void onMessage(@NotNull String uri, @NotNull Map<String, String> headers, @NotNull byte[] payload) throws IOException {
if (uri.startsWith("hm://playlist/")) {
PlaylistModificationInfo mod = PlaylistModificationInfo.parseFrom(payload);
String modUri = mod.getUri().toStringUtf8();
if (context != null && Objects.equals(modUri, context.uri())) {
for (Playlist4ApiProto.Op op : mod.getOpsList()) {
switch (op.getKind()) {
case ADD:
performAdd(op.getAdd());
break;
case REM:
performRemove(op.getRem());
break;
case MOV:
performMove(op.getMov());
break;
case UPDATE_ITEM_ATTRIBUTES:
case UPDATE_LIST_ATTRIBUTES:
LOGGER.warn("Unsupported operation: " + TextFormat.shortDebugString(op));
break;
default:
case KIND_UNKNOWN:
LOGGER.warn("Received unknown op: " + op.getKind());
break;
}
}
LOGGER.info("Received update for current context! {uri: {}, ops: {}}", modUri, ProtoUtils.opsKindList(mod.getOpsList()));
updated();
} else if (context != null && AbsSpotifyContext.isCollection(session, modUri)) {
for (Playlist4ApiProto.Op op : mod.getOpsList()) {
List<String> uris = new ArrayList<>();
for (Playlist4ApiProto.Item item : op.getAdd().getItemsList())
uris.add(item.getUri());
if (op.getKind() == Playlist4ApiProto.Op.Kind.ADD)
performCollectionUpdate(uris, true);
else if (op.getKind() == Playlist4ApiProto.Op.Kind.REM)
performCollectionUpdate(uris, false);
}
LOGGER.info("Updated tracks in collection! {uri: {}, ops: {}}", modUri, ProtoUtils.opsKindList(mod.getOpsList()));
updated();
}
} else if (context != null && uri.equals("hm://collection/collection/" + session.username() + "/json")) {
List<String> added = null;
List<String> removed = null;
JsonArray items = JsonParser.parseString(new String(payload)).getAsJsonObject().getAsJsonArray("items");
for (JsonElement elm : items) {
JsonObject obj = elm.getAsJsonObject();
String itemUri = "spotify:" + obj.get("type").getAsString() + ":" + obj.get("identifier").getAsString();
if (obj.get("removed").getAsBoolean()) {
if (removed == null) removed = new ArrayList<>();
removed.add(itemUri);
} else {
if (added == null) added = new ArrayList<>();
added.add(itemUri);
}
}
if (added != null) performCollectionUpdate(added, true);
if (removed != null) performCollectionUpdate(removed, false);
LOGGER.info("Updated tracks in collection! {added: {}, removed: {}}", added != null, removed != null);
updated();
}
}
private synchronized void performCollectionUpdate(@NotNull List<String> uris, boolean inCollection) {
for (String uri : uris)
tracksKeeper.updateMetadataFor(uri, "collection.in_collection", String.valueOf(inCollection));
}
public int getContextSize() {
String trackCount = getContextMetadata("track_count");
if (trackCount != null) return Integer.parseInt(trackCount);
else if (tracksKeeper != null) return tracksKeeper.tracks.size();
else return 0;
}
@Nullable
public String getContextMetadata(@NotNull String key) {
return state.getContextMetadataOrDefault(key, null);
}
public void setContextMetadata(@NotNull String key, @Nullable String value) {
if (value == null) state.removeContextMetadata(key);
else state.putContextMetadata(key, value);
}
@NotNull
public List<ContextTrack> getNextTracks(boolean withQueue) {
if (tracksKeeper == null) return Collections.emptyList();
int index = tracksKeeper.getCurrentTrackIndex();
int size = tracksKeeper.tracks.size();
List<ContextTrack> list = new ArrayList<>(size - index);
for (int i = index + 1; i < size; i++)
list.add(tracksKeeper.tracks.get(i));
if (withQueue) list.addAll(0, tracksKeeper.queue);
return list;
}
@Nullable
public ContextTrack getCurrentTrack() {
int index = tracksKeeper.getCurrentTrackIndex();
return tracksKeeper == null || tracksKeeper.tracks.size() < index ? null : tracksKeeper.tracks.get(index);
}
@NotNull
public List<ContextTrack> getPrevTracks() {
if (tracksKeeper == null) return Collections.emptyList();
int index = tracksKeeper.getCurrentTrackIndex();
List<ContextTrack> list = new ArrayList<>(index);
for (int i = 0; i < index; i++)
list.add(tracksKeeper.tracks.get(i));
return list;
}
@NotNull
private String renewSessionId() {
String sessionId = generateSessionId(session.random());
state.setSessionId(sessionId);
return sessionId;
}
@NotNull
public String getSessionId() {
return state.getSessionId();
}
public void setPlaybackId(@NotNull String playbackId) {
state.setPlaybackId(playbackId);
}
@NotNull
public PlayOrigin getPlayOrigin() {
return state.getPlayOrigin();
}
@Override
public void close() {
session.dealer().removeMessageListener(this);
device.removeListener(this);
device.close();
}
public enum PreviousPlayable {
MISSING_TRACKS, OK;
public boolean isOk() {
return this == OK;
}
}
public enum NextPlayable {
MISSING_TRACKS, AUTOPLAY,
OK_PLAY, OK_PAUSE, OK_REPEAT;
public boolean isOk() {
return this == OK_PLAY || this == OK_PAUSE || this == OK_REPEAT;
}
}
private static class PlayableIdWithIndex {
private final PlayableId id;
private final int index;
PlayableIdWithIndex(@NotNull PlayableId id, int index) {
this.id = id;
this.index = index;
}
}
private class TracksKeeper {
private static final int MAX_PREV_TRACKS = 16;
private static final int MAX_NEXT_TRACKS = 48;
private final LinkedList<ContextTrack> queue = new LinkedList<>();
private final List<ContextTrack> tracks = new ArrayList<>();
private final FisherYatesShuffle<ContextTrack> shuffle = new FisherYatesShuffle<>(session.random());
private volatile boolean isPlayingQueue = false;
private volatile boolean cannotLoadMore = false;
private volatile int shuffleKeepIndex = -1;
private TracksKeeper() {
checkComplete();
}
private void updateTrackCount() {
if (context.isFinite())
state.putContextMetadata("track_count", String.valueOf(tracks.size() + queue.size()));
else
state.removeContextMetadata("track_count");
}
private void checkComplete() {
if (cannotLoadMore) return;
if (context.isFinite()) {
int total_tracks = Integer.parseInt(state.getContextMetadataOrDefault("track_count", "-1"));
if (total_tracks == -1) cannotLoadMore = false;
else cannotLoadMore = total_tracks == tracks.size();
} else {
cannotLoadMore = false;
}
}
@NotNull
synchronized ProvidedTrack getCurrentTrack() {
return state.getTrack();
}
private int getCurrentTrackIndex() {
return state.getIndex().getTrack();
}
/**
* Sets the current playing track index and updates the state.
*
* @param index The index of the track inside {@link TracksKeeper#tracks}
* @throws IllegalStateException if the queue is playing
*/
private void setCurrentTrackIndex(int index) {
if (isPlayingQueue) throw new IllegalStateException();
state.setIndex(ContextIndex.newBuilder().setTrack(index).build());
updateState();
}
private void shiftCurrentTrackIndex(int delta) {
state.getIndexBuilder().setTrack(state.getIndex().getTrack() + delta);
}
private void updatePrevNextTracks() {
int index = getCurrentTrackIndex();
state.clearPrevTracks();
for (int i = Math.max(0, index - MAX_PREV_TRACKS); i < index; i++)
state.addPrevTracks(ProtoUtils.toProvidedTrack(tracks.get(i), getContextUri()));
state.clearNextTracks();
for (ContextTrack track : queue)
state.addNextTracks(ProtoUtils.toProvidedTrack(track, getContextUri()));
for (int i = index + 1; i < Math.min(tracks.size(), index + 1 + MAX_NEXT_TRACKS); i++)
state.addNextTracks(ProtoUtils.toProvidedTrack(tracks.get(i), getContextUri()));
}
void updateTrackDuration(int duration) {
state.setDuration(duration);
state.getTrackBuilder().putMetadata("duration", String.valueOf(duration));
updateMetadataFor(getCurrentTrackIndex(), "duration", String.valueOf(duration));
}
private void updateTrackDuration() {
ProvidedTrack current = getCurrentTrack();
if (current.containsMetadata("duration"))
state.setDuration(Long.parseLong(current.getMetadataOrThrow("duration")));
else
state.clearDuration();
}
private void updateLikeDislike() {
if (Objects.equals(state.getContextMetadataOrDefault("like-feedback-enabled", "0"), "1")) {
state.putContextMetadata("like-feedback-selected",
state.getTrack().getMetadataOrDefault("like-feedback-selected", "0"));
} else {
state.removeContextMetadata("like-feedback-selected");
}
if (Objects.equals(state.getContextMetadataOrDefault("dislike-feedback-enabled", "0"), "1")) {
state.putContextMetadata("dislike-feedback-selected",
state.getTrack().getMetadataOrDefault("dislike-feedback-selected", "0"));
} else {
state.removeContextMetadata("dislike-feedback-selected");
}
}
/**
* Updates the currently playing track (not index), recomputes the prev/next tracks and sets the duration field.
*
* <b>This will also REMOVE a track from the queue if needed. Calling this twice will break the queue.</b>
*/
private void updateState() {
if (isPlayingQueue) state.setTrack(ProtoUtils.toProvidedTrack(queue.remove(), getContextUri()));
else state.setTrack(ProtoUtils.toProvidedTrack(tracks.get(getCurrentTrackIndex()), getContextUri()));
updateLikeDislike();
updateTrackDuration();
updatePrevNextTracks();
}
/**
* Adds a track to the end of the queue, recomputes the prev/next tracks and sets the duration field.
*
* <b>Calling {@link TracksKeeper#updateState()} would break it.</b>
*
* @param track The track to add to queue
*/
synchronized void addToQueue(@NotNull ContextTrack track) {
queue.add(track.toBuilder().putMetadata("is_queued", "true").build());