-
Notifications
You must be signed in to change notification settings - Fork 14
/
Spotify.java
1250 lines (1087 loc) · 54.1 KB
/
Spotify.java
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 v.blade.sources.spotify;
import android.content.Intent;
import android.os.Bundle;
import android.os.Process;
import android.util.ArrayMap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.spotify.sdk.android.auth.AuthorizationClient;
import com.spotify.sdk.android.auth.AuthorizationRequest;
import com.spotify.sdk.android.auth.AuthorizationResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Objects;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import v.blade.BladeApplication;
import v.blade.BuildConfig;
import v.blade.R;
import v.blade.databinding.SettingsFragmentSpotifyBinding;
import v.blade.library.Library;
import v.blade.library.Playlist;
import v.blade.library.Song;
import v.blade.sources.Source;
import v.blade.sources.SourceInformation;
import v.blade.ui.ExploreFragment;
import v.blade.ui.SettingsActivity;
import xyz.gianlu.librespot.audio.decoders.AudioQuality;
/*
* Spotify strategy :
* - For access to library, we do Web API access using official AUTH lib + Retrofit
* - For the player, we use librespot-java (the player part)
* It would be nice to use librespot for everything, but i don't think it is possible to
* use it 'as is' for web api access...
*/
//TODO : Spotify AUTH does not support PKCE if Spotify App is installed, i think ; we will need
// to go back to 'client secret' exchange, which is completely dumb, as then the secret is public
// (i have no backend) ; another solution would be to put the secret on valou3433.fr but yeah
public class Spotify extends Source
{
public static final int NAME_RESOURCE = R.string.spotify;
public static final int DESCRIPTION_RESOURCE = R.string.spotify_desc;
public static final int IMAGE_RESOURCE = R.drawable.ic_spotify;
private static final int CACHE_VERSION = 1;
protected static final int SPOTIFY_IMAGE_LEVEL = 10;
//Spotify AUTH : We are using 'Authorization Code Flow' with 'PKCE extension'
private static final String BASE_API_URL = "https://api.spotify.com/v1/";
private static final String AUTH_TYPE = "Bearer ";
private static final String CLIENT_ID = BuildConfig.SPOTIFY_CLIENT_ID;
//This should not be exposed, but i have no other choice, as the Spotify app does not seem to support PKCE
private static final String CLIENT_SECRET = BuildConfig.SPOTIFY_CLIENT_SECRET;
protected static final String[] SCOPES = {"app-remote-control", "streaming", "playlist-modify-public", "playlist-modify-private", "playlist-read-private", "playlist-read-collaborative", "user-follow-modify", "user-follow-read", "user-library-modify", "user-library-read", "user-read-email", "user-read-private",
"user-read-recently-played", "user-top-read", "user-read-playback-position", "user-read-playback-state", "user-modify-playback-state", "user-read-currently-playing"};
private static final int SPOTIFY_REQUEST_CODE = 0x11;
protected static final String REDIRECT_URI = "spotify-sdk://auth";
public AudioQuality spotifyAudioQuality = AudioQuality.HIGH;
public Spotify()
{
super();
this.name = BladeApplication.appContext.getString(NAME_RESOURCE);
this.player = new SpotifyPlayer(this);
}
@SuppressWarnings({"FieldMayBeFinal", "unused"})
private static class SpotifyTokenResponse
{
private String access_token = "";
private String token_type = "";
private int expires_in = -1;
private String refresh_token = "";
private String scope = "";
public SpotifyTokenResponse()
{
}
}
//Spotify login information
//Player login
private String account_name; //i.e. username, retrieved by api
private String account_login; //what the user uses to login (mail or username)
private String account_password;
private String user_id;
//API login
private String ACCESS_TOKEN;
private String REFRESH_TOKEN;
private int TOKEN_EXPIRES_IN;
protected String AUTH_STRING;
private Retrofit retrofit;
protected SpotifyService service;
@Override
public int getImageResource()
{
return IMAGE_RESOURCE;
}
private void notifyUiForStatus()
{
// Notify UI
if(BladeApplication.currentActivity instanceof SettingsActivity)
{
SettingsActivity settingsActivity = (SettingsActivity) BladeApplication.currentActivity;
settingsActivity.runOnUiThread(() ->
{
for(Fragment f : settingsActivity.getSupportFragmentManager().getFragments())
{
if(f instanceof SettingsActivity.SourcesFragment)
{
SettingsActivity.SourcesFragment sf = (SettingsActivity.SourcesFragment) f;
sf.updateSourcesView();
}
else if(f instanceof SettingsFragment)
{
SettingsFragment sf = (SettingsFragment) f;
sf.refreshStatus();
}
}
});
}
}
@Override
public void initSource()
{
if(status != SourceStatus.STATUS_NEED_INIT) return;
status = SourceStatus.STATUS_CONNECTING;
notifyUiForStatus();
//build retrofit client
retrofit = new Retrofit.Builder().baseUrl(BASE_API_URL).addConverterFactory(GsonConverterFactory.create()).build();
service = retrofit.create(SpotifyService.class);
//refresh access token
System.out.println("BLADE-SPOTIFY: Refresh token " + REFRESH_TOKEN);
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("grant_type", "refresh_token")
.add("refresh_token", REFRESH_TOKEN)
.add("client_id", CLIENT_ID)
.add("client_secret", CLIENT_SECRET)
.build();
Request request = new Request.Builder().url("https://accounts.spotify.com/api/token")
.post(requestBody).build();
okhttp3.Call call = client.newCall(request);
BladeApplication.obtainExecutorService().execute(() ->
{
Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
System.out.println("BLADE-SPOTIFY: Player is logging in...");
//First init the player
boolean login = ((SpotifyPlayer) player).login(account_login, account_password);
if(!login)
{
//Toast.makeText(BladeApplication.appContext, BladeApplication.appContext.getString(R.string.init_error) + " " + BladeApplication.appContext.getString(NAME_RESOURCE) + " (Could not login)", Toast.LENGTH_SHORT).show();
System.err.println("BLADE-SPOTIFY: " + BladeApplication.appContext.getString(R.string.init_error) + " " + BladeApplication.appContext.getString(NAME_RESOURCE) + " (Could not login)");
status = SourceStatus.STATUS_NEED_INIT;
return;
}
System.out.println("BLADE-SPOTIFY: Player logged in, initializing...");
player.init();
//Then init
try
{
System.out.println("BLADE-SPOTIFY: Initializing API, refreshing token...");
okhttp3.Response response = call.execute();
if(!response.isSuccessful() || response.code() != 200 || response.body() == null)
{
String responseBody = response.body() == null ? "Unknown error" : response.body().string();
//Toast.makeText(BladeApplication.appContext, BladeApplication.appContext.getString(R.string.init_error) + " " + BladeApplication.appContext.getString(NAME_RESOURCE) + " (" + response.code() + " : " + responseBody + ")", Toast.LENGTH_SHORT).show();
System.err.println("BLADE-SPOTIFY: " + BladeApplication.appContext.getString(R.string.init_error) + " " + BladeApplication.appContext.getString(NAME_RESOURCE) + " (" + response.code() + " : " + responseBody + ")");
status = SourceStatus.STATUS_NEED_INIT;
return;
}
Gson gson = new Gson();
String rstring = response.body().string();
SpotifyTokenResponse sr = gson.fromJson(rstring, SpotifyTokenResponse.class);
if(sr == null)
{
//Toast.makeText(BladeApplication.appContext, BladeApplication.appContext.getString(R.string.init_error) + " " + BladeApplication.appContext.getString(NAME_RESOURCE) + " (Could not parse JSON Token)", Toast.LENGTH_SHORT).show();
System.err.println("BLADE-SPOTIFY: " + BladeApplication.appContext.getString(R.string.init_error) + " " + BladeApplication.appContext.getString(NAME_RESOURCE) + " (Could not parse JSON Token)");
status = SourceStatus.STATUS_NEED_INIT;
return;
}
ACCESS_TOKEN = sr.access_token;
TOKEN_EXPIRES_IN = sr.expires_in;
if(sr.refresh_token != null && !sr.refresh_token.equals(""))
REFRESH_TOKEN = sr.refresh_token;
AUTH_STRING = AUTH_TYPE + ACCESS_TOKEN;
status = SourceStatus.STATUS_READY;
Source.saveSources();
System.out.println("BLADE-SPOTIFY: Spotify initialized");
// Notify UI
notifyUiForStatus();
}
catch(IOException e)
{
status = SourceStatus.STATUS_NEED_INIT;
//Toast.makeText(BladeApplication.appContext, BladeApplication.appContext.getString(R.string.init_error) + " " + BladeApplication.appContext.getString(NAME_RESOURCE) + " (IOException trying to obtain token)", Toast.LENGTH_SHORT).show();
System.err.println("BLADE-SPOTIFY: " + BladeApplication.appContext.getString(R.string.init_error) + " " + BladeApplication.appContext.getString(NAME_RESOURCE) + " (IOException trying to obtain token)");
}
});
}
protected void refreshAccessTokenSync()
{
//build retrofit client
retrofit = new Retrofit.Builder().baseUrl(BASE_API_URL).addConverterFactory(GsonConverterFactory.create()).build();
service = retrofit.create(SpotifyService.class);
//refresh access token
System.out.println("BLADE-SPOTIFY: Refresh token " + REFRESH_TOKEN);
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new FormBody.Builder()
.add("grant_type", "refresh_token")
.add("refresh_token", REFRESH_TOKEN)
.add("client_id", CLIENT_ID)
.add("client_secret", CLIENT_SECRET)
.build();
Request request = new Request.Builder().url("https://accounts.spotify.com/api/token")
.post(requestBody).build();
okhttp3.Call call = client.newCall(request);
try
{
okhttp3.Response response = call.execute();
if(!response.isSuccessful() || response.code() != 200 || response.body() == null)
{
String responseBody = response.body() == null ? "Unknown error" : response.body().string();
System.err.println("BLADE-SPOTIFY: Could not refresh token" + " (" + response.code() + " : " + responseBody + ")");
return;
}
Gson gson = new Gson();
String rstring = response.body().string();
SpotifyTokenResponse sr = gson.fromJson(rstring, SpotifyTokenResponse.class);
if(sr == null)
{
System.err.println("BLADE-SPOTIFY: Could not refresh token" + " (Could not parse JSON Token)");
return;
}
ACCESS_TOKEN = sr.access_token;
TOKEN_EXPIRES_IN = sr.expires_in;
if(sr.refresh_token != null && !sr.refresh_token.equals(""))
REFRESH_TOKEN = sr.refresh_token;
AUTH_STRING = AUTH_TYPE + ACCESS_TOKEN;
Source.saveSources();
}
catch(IOException e)
{
status = SourceStatus.STATUS_NEED_INIT;
System.err.println("BLADE-SPOTIFY: Could not refresh access token (IOException trying to obtain token)");
}
}
private static int computeTrackNumber(int discNumber, int trackNumber)
{
return 100 * discNumber + trackNumber;
}
@Override
public void synchronizeLibrary()
{
try
{
System.out.println("BLADE-SPOTIFY: Syncing lib");
/* Obtain user tracks */
int tracksLeft;
int tracksIndex = 0;
do
{
Call<SpotifyService.PagingObject<SpotifyService.SavedTrackObject>> userTracks =
service.getUserSavedTracks(AUTH_STRING, 50, tracksIndex * 50);
Response<SpotifyService.PagingObject<SpotifyService.SavedTrackObject>> response =
userTracks.execute();
if(response.code() == 401)
{
//Expired token
System.err.println("BLADE-SPOTIFY: Expired token while syncing library, refreshing...");
refreshAccessTokenSync();
synchronizeLibrary();
return;
}
if(response.code() != 200 || response.body() == null)
{
System.err.println("BLADE-SPOTIFY: Error while syncing library: non-200 error code " + response.code());
System.err.println("BLADE-SPOTIFY: Response error body: " + response.errorBody().string());
break;
}
SpotifyService.PagingObject<SpotifyService.SavedTrackObject> trackPaging = response.body();
for(SpotifyService.SavedTrackObject savedTrack : trackPaging.items)
{
SpotifyService.TrackObject track = savedTrack.track;
if(track.album == null || track.artists == null || track.album.images.length == 0)
continue; //TODO check ?
//album artists
String[] aartists = new String[track.album.artists.length];
String[] aartistsImages = new String[track.album.artists.length];
for(int j = 0; j < track.album.artists.length; j++)
{
aartists[j] = track.album.artists[j].name;
}
//song artists
String[] artists = new String[track.artists.length];
String[] artistsImages = new String[track.artists.length];
for(int j = 0; j < track.artists.length; j++)
{
artists[j] = track.artists[j].name;
//artistsImages[j] = track.artists[j].images //TODO artists images ?
}
Library.addSong(track.name, track.album.name, artists, this, track.id, aartists,
track.album.images[track.album.images.length - 2].url,
computeTrackNumber(track.disc_number, track.track_number),
artistsImages, aartistsImages, track.album.images[0].url, SPOTIFY_IMAGE_LEVEL);
}
tracksLeft = trackPaging.total - 50 * (tracksIndex + 1);
tracksIndex++;
}
while(tracksLeft > 0);
/* Obtain user albums */
int albumsLeft;
int albumIndex = 0;
do
{
Call<SpotifyService.PagingObject<SpotifyService.SavedAlbumObject>> userAlbums =
service.getUserSavedAlbums(AUTH_STRING, 50, albumIndex * 50);
Response<SpotifyService.PagingObject<SpotifyService.SavedAlbumObject>> response =
userAlbums.execute();
if(response.code() != 200 || response.body() == null) break;
SpotifyService.PagingObject<SpotifyService.SavedAlbumObject> albumPaging = response.body();
for(SpotifyService.SavedAlbumObject savedAlbum : albumPaging.items)
{
SpotifyService.AlbumObject album = savedAlbum.album;
if(album.artists == null || album.tracks == null || album.images.length == 0)
continue;
//album artists
String[] aartists = new String[album.artists.length];
String[] aartistsImages = new String[album.artists.length];
for(int j = 0; j < album.artists.length; j++)
{
aartists[j] = album.artists[j].name;
}
//add every song in album
for(SpotifyService.SimplifiedTrackObject track : album.tracks.items)
{
//song artists
String[] artists = new String[track.artists.length];
String[] artistsImages = new String[track.artists.length];
for(int j = 0; j < track.artists.length; j++)
{
artists[j] = track.artists[j].name;
//artistsImages[j] = track.artists[j].images //TODO artists images ?
}
Library.addSong(track.name, album.name, artists, this, track.id, aartists,
album.images[album.images.length - 2].url,
computeTrackNumber(track.disc_number, track.track_number),
artistsImages, aartistsImages, album.images[0].url, SPOTIFY_IMAGE_LEVEL);
}
}
albumsLeft = albumPaging.total - 50 * (albumIndex + 1);
albumIndex++;
}
while(albumsLeft > 0);
/* Obtain user playlists */
int playlistsLeft;
int playlistIndex = 0;
do
{
Call<SpotifyService.PagingObject<SpotifyService.SimplifiedPlaylistObject>> userPlaylists =
service.getListOfCurrentUserPlaylists(AUTH_STRING, 50, playlistIndex * 50);
Response<SpotifyService.PagingObject<SpotifyService.SimplifiedPlaylistObject>> response =
userPlaylists.execute();
if(response.code() != 200 || response.body() == null) break;
SpotifyService.PagingObject<SpotifyService.SimplifiedPlaylistObject> playlistPaging = response.body();
for(SpotifyService.SimplifiedPlaylistObject playlist : playlistPaging.items)
{
//Obtain song list
ArrayList<Song> songList = new ArrayList<>();
int songsLeft;
int songIndex = 0;
do
{
Call<SpotifyService.PagingObject<SpotifyService.PlaylistTrackObject>> playlistTracks =
service.getPlaylistItems(AUTH_STRING, playlist.id, 100, songIndex * 100);
Response<SpotifyService.PagingObject<SpotifyService.PlaylistTrackObject>> response2 =
playlistTracks.execute();
if(response2.code() != 200 || response2.body() == null) break;
SpotifyService.PagingObject<SpotifyService.PlaylistTrackObject> songsPaging = response2.body();
for(SpotifyService.PlaylistTrackObject playlistTrack : songsPaging.items)
{
SpotifyService.TrackObject track = playlistTrack.track;
if(track.album == null || track.artists == null || track.album.images.length == 0)
continue;
//album artists
String[] aartists = new String[track.album.artists.length];
String[] aartistsImages = new String[track.album.artists.length];
for(int j = 0; j < track.album.artists.length; j++)
{
aartists[j] = track.album.artists[j].name;
}
//song artists
String[] artists = new String[track.artists.length];
String[] artistsImages = new String[track.artists.length];
for(int j = 0; j < track.artists.length; j++)
{
artists[j] = track.artists[j].name;
//artistsImages[j] = track.artists[j].images //TODO artists images ?
}
Song song = Library.addSongHandle(track.name, track.album.name, artists, this, track.id, aartists,
track.album.images[track.album.images.length - 2].url,
computeTrackNumber(track.disc_number, track.track_number),
artistsImages, aartistsImages, track.album.images[0].url, SPOTIFY_IMAGE_LEVEL);
songList.add(song);
}
songsLeft = songsPaging.total - 100 * (songIndex + 1);
songIndex++;
}
while(songsLeft > 0);
Library.addPlaylist(playlist.name, songList,
playlist.images.length == 0 ? null :
(playlist.images[0] == null ? null : playlist.images[0].url),
(playlist.collaborative ? (BladeApplication.appContext.getString(R.string.collaborative) + " - ") : "") +
(playlist.owner.id.equals(user_id) ? "" : playlist.owner.display_name),
this, playlist.id);
}
playlistsLeft = playlistPaging.total - 50 * (playlistIndex + 1);
playlistIndex++;
}
while(playlistsLeft > 0);
}
catch(IOException e)
{
System.err.println("BLADE-SPOTIFY: Error while syncing library: " + e.getMessage());
e.printStackTrace();
}
System.out.println("BLADE-SPOTIFY: Lib sync done");
}
@Override
public Fragment getSettingsFragment()
{
return new Spotify.SettingsFragment(this);
}
@Override
public JsonObject saveToJSON()
{
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("class", Spotify.class.getName());
jsonObject.addProperty("account_name", account_name);
jsonObject.addProperty("refresh_token", REFRESH_TOKEN);
jsonObject.addProperty("cache_version", CACHE_VERSION);
jsonObject.addProperty("account_login", account_login);
jsonObject.addProperty("account_password", account_password);
jsonObject.addProperty("user_id", user_id);
return jsonObject;
}
@Override
public void restoreFromJSON(JsonObject jsonObject)
{
int cache_version = jsonObject.get("cache_version") == null ? 0 : jsonObject.get("cache_version").getAsInt();
if(cache_version > CACHE_VERSION)
System.err.println("Spotify cached source with version greater than current... Trying to read with old way.");
JsonElement accountLoginJson = jsonObject.get("account_login");
if(accountLoginJson != null) account_login = accountLoginJson.getAsString();
else account_login = "null";
JsonElement accountPasswordJson = jsonObject.get("account_password");
if(accountPasswordJson != null) account_password = accountPasswordJson.getAsString();
else account_password = "null";
JsonElement accountNameJson = jsonObject.get("account_name");
if(accountNameJson != null) account_name = accountNameJson.getAsString();
else account_name = account_login;
JsonElement refreshTokenJson = jsonObject.get("refresh_token");
if(refreshTokenJson != null) REFRESH_TOKEN = refreshTokenJson.getAsString();
else status = SourceStatus.STATUS_DOWN;
JsonElement userIdJson = jsonObject.get("user_id");
if(userIdJson != null) user_id = userIdJson.getAsString();
else status = SourceStatus.STATUS_DOWN;
}
@Override
public void explore(ExploreFragment view)
{
BladeApplication.obtainExecutorService().execute(() ->
{
Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Call<SpotifyService.FeaturedPlaylistsResult> call =
service.getFeaturedPlaylists(AUTH_STRING);
try
{
Response<SpotifyService.FeaturedPlaylistsResult> response =
call.execute();
if(response.code() == 401)
{
//Expired token
refreshAccessTokenSync();
explore(view);
return;
}
SpotifyService.FeaturedPlaylistsResult r = response.body();
if(response.code() != 200 || r == null || r.playlists == null)
{
System.err.println("BLADE-SPOTIFY: Could not explore");
view.requireActivity().runOnUiThread(() ->
Toast.makeText(view.requireContext(),
view.getString(R.string.could_not_show_explore),
Toast.LENGTH_SHORT).show());
view.current = null;
return;
}
SpotifyExploreAdapter adapter = new SpotifyExploreAdapter(view);
adapter.currentPlaylists = r.playlists;
view.requireActivity().runOnUiThread(() ->
view.updateContent(adapter, getName(), true));
}
catch(IOException e)
{
view.requireActivity().runOnUiThread(() ->
Toast.makeText(view.requireContext(),
view.getString(R.string.could_not_show_explore),
Toast.LENGTH_SHORT).show());
view.current = null;
}
});
}
@Override
public void exploreSearch(String query, ExploreFragment view)
{
BladeApplication.obtainExecutorService().execute(() ->
{
Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
//NOTE : for now we limit to 10 search results ; it seems ok (we could go to 50 but it is a lot...)
Call<SpotifyService.SearchResult> call = service.search(AUTH_STRING, query, "track,artist,album", 10);
try
{
Response<SpotifyService.SearchResult> response = call.execute();
if(response.code() == 401)
{
//Expired token
refreshAccessTokenSync();
exploreSearch(query, view);
return;
}
SpotifyService.SearchResult r = response.body();
if(response.code() != 200 || r == null)
{
System.err.println("BLADE-SPOTIFY: Could not search " + query);
view.requireActivity().runOnUiThread(() -> Toast.makeText(view.requireContext(), view.getString(R.string.could_not_search_for, query), Toast.LENGTH_SHORT).show());
return;
}
view.requireActivity().runOnUiThread(() ->
view.updateContent(new SpotifyExploreAdapter(r, view), query, true));
}
catch(IOException e)
{
view.requireActivity().runOnUiThread(() -> Toast.makeText(view.requireContext(), view.getString(R.string.could_not_search_for, query), Toast.LENGTH_SHORT).show());
}
});
}
@Override
public void addSongToPlaylist(Song song, Playlist playlist, Runnable callback, Runnable failureCallback)
{
BladeApplication.obtainExecutorService().execute(() ->
{
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
String id = null;
for(SourceInformation s : song.getSources())
{
if(s.source == this)
{
id = (String) s.id;
break;
}
}
//Add track to playlist on Spotify
Call<SpotifyService.PlaylistAddResponse> call =
service.appendTrackToPlaylist(AUTH_STRING, (String) playlist.getSource().id, "spotify:track:" + id);
try
{
Response<SpotifyService.PlaylistAddResponse> response = call.execute();
if(response.code() == 401)
{
//Expired token
refreshAccessTokenSync();
addSongToPlaylist(song, playlist, callback, failureCallback);
return;
}
if(response.code() != 201)
{
System.err.println("BLADE-SPOTIFY: Could not add " + song.getName() + " to playlist " + playlist.getName() + " : " + response.code());
failureCallback.run();
return;
}
}
catch(IOException e)
{
failureCallback.run();
return;
}
super.addSongToPlaylist(song, playlist, callback, failureCallback);
});
}
@Override
public void createPlaylist(String name, BladeApplication.Callback<Playlist> callback, Runnable failureCallback)
{
BladeApplication.obtainExecutorService().execute(() ->
{
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Map<String, Object> jsonParams = new ArrayMap<>();
jsonParams.put("name", name);
JSONObject jsonBody = new JSONObject(jsonParams);
System.out.println("json: " + jsonBody);
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody.toString());
Call<SpotifyService.SimplifiedPlaylistObject> call = service.createPlaylist(AUTH_STRING, user_id, body);
try
{
Response<SpotifyService.SimplifiedPlaylistObject> response = call.execute();
SpotifyService.SimplifiedPlaylistObject r = response.body();
if(response.code() == 401)
{
//Expired token
refreshAccessTokenSync();
createPlaylist(name, callback, failureCallback);
return;
}
if(response.code() != 201 || r == null)
{
System.err.println("BLADE-SPOTIFY: Could not create playlist " + name + " : " + response.code());
failureCallback.run();
return;
}
//Create playlist locally
Playlist playlist = Library.addPlaylist(name, new ArrayList<>(), null, "", this, r.id);
//Save library
Library.save();
saveSources();
//Run callback
callback.run(playlist);
}
catch(IOException e)
{
failureCallback.run();
}
});
}
@Override
public void removePlaylist(Playlist playlist, Runnable callback, Runnable failureCallback)
{
BladeApplication.obtainExecutorService().execute(() ->
{
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Call<Void> call = service.unfollowPlaylist(AUTH_STRING, (String) playlist.getSource().id);
try
{
Response<Void> response = call.execute();
if(response.code() == 401)
{
//Expired token
refreshAccessTokenSync();
removePlaylist(playlist, callback, failureCallback);
return;
}
if(response.code() != 200)
{
System.err.println("BLADE-SPOTIFY: Could not delete playlist " + playlist.getName() + " : " + response.code());
failureCallback.run();
return;
}
super.removePlaylist(playlist, callback, failureCallback);
}
catch(IOException e)
{
failureCallback.run();
}
});
}
@Override
public void addToLibrary(Song song, Runnable callback, Runnable failureCallback)
{
BladeApplication.obtainExecutorService().execute(() ->
{
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//Get song source
SourceInformation current = null;
for(SourceInformation s : song.getSources())
if(s.source == this) current = s;
if(current == null)
{
failureCallback.run();
return;
}
Call<Void> call = service.saveTrack(AUTH_STRING, (String) current.id);
try
{
Response<Void> response = call.execute();
if(response.code() == 401)
{
//Expired token
refreshAccessTokenSync();
addToLibrary(song, callback, failureCallback);
return;
}
if(response.code() != 200)
{
System.err.println("BLADE-SPOTIFY: Could not save song " + song.getName() + " : " + response.code());
failureCallback.run();
return;
}
super.addToLibrary(song, callback, failureCallback);
}
catch(IOException e)
{
failureCallback.run();
}
});
}
@Override
public void removeFromLibrary(Song song, Runnable callback, Runnable failureCallback)
{
BladeApplication.obtainExecutorService().execute(() ->
{
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//Get song source
SourceInformation current = null;
for(SourceInformation s : song.getSources())
if(s.source == this) current = s;
if(current == null)
{
failureCallback.run();
return;
}
Call<Void> call = service.removeTrack(AUTH_STRING, (String) current.id);
try
{
Response<Void> response = call.execute();
if(response.code() == 401)
{
//Expired token
refreshAccessTokenSync();
removeFromLibrary(song, callback, failureCallback);
return;
}
if(response.code() != 200)
{
System.err.println("BLADE-SPOTIFY: Could not remove song " + song.getName() + " : " + response.code());
failureCallback.run();
return;
}
super.removeFromLibrary(song, callback, failureCallback);
}
catch(IOException e)
{
failureCallback.run();
}
});
}
@Override
public void removeFromPlaylist(Song song, Playlist playlist, Runnable callback, Runnable failureCallback)
{
BladeApplication.obtainExecutorService().execute(() ->
{
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//Get song source
SourceInformation current = null;
for(SourceInformation s : song.getSources())
if(s.source == this) current = s;
if(current == null)
{
failureCallback.run();
return;
}
try
{
//Generate request body
JSONObject track = new JSONObject();
track.put("uri", "spotify:track:" + current.id);
JSONArray array = new JSONArray();
array.put(track);
Map<String, Object> jsonParams = new ArrayMap<>();
jsonParams.put("tracks", array);
JSONObject jsonBody = new JSONObject(jsonParams);
System.out.println("json: " + jsonBody);
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonBody.toString());
Call<SpotifyService.PlaylistAddResponse> call = service.removePlaylistItem(AUTH_STRING, (String) playlist.getSource().id, body);
Response<SpotifyService.PlaylistAddResponse> response = call.execute();
if(response.code() == 401)
{
//Expired token
refreshAccessTokenSync();
removeFromPlaylist(song, playlist, callback, failureCallback);
return;
}
if(response.code() != 200)
{
System.err.println("BLADE-SPOTIFY: Could not remove " + song.getName() + " from playlist " + playlist.getName() + " : " + response.code());
failureCallback.run();
return;
}
super.removeFromPlaylist(song, playlist, callback, failureCallback);
}
catch(IOException | JSONException e)
{
failureCallback.run();
}
});
}
public static class SettingsFragment extends Fragment
{
private final Spotify spotify;
private SettingsFragmentSpotifyBinding binding;
private String codeVerifier;
private SettingsFragment(Spotify spotify)
{
super(R.layout.settings_fragment_spotify);
this.spotify = spotify;
}
public void refreshStatus()
{
switch(spotify.getStatus())
{
case STATUS_DOWN:
binding.settingsSpotifyStatus.setText(R.string.source_down_desc);
break;
case STATUS_NEED_INIT:
binding.settingsSpotifyStatus.setText(R.string.source_need_init_desc);
break;
case STATUS_CONNECTING:
binding.settingsSpotifyStatus.setText(R.string.source_connecting_desc);
break;
case STATUS_READY:
binding.settingsSpotifyStatus.setText(R.string.source_ready_desc);
break;
}
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
binding = SettingsFragmentSpotifyBinding.inflate(inflater, container, false);
//Set status text
refreshStatus();
//Set account text
if(spotify.account_name == null)
{
binding.settingsSpotifyAccount.setText(R.string.disconnected);
binding.settingsSpotifyAccount.setTextColor(getResources().getColor(R.color.errorRed));
// Hide audio quality and force init buttons
binding.settingsSpotifyAudioQualityLayout.setVisibility(View.GONE);
binding.settingsSpotifyInit.setVisibility(View.GONE);
}
else
{
binding.settingsSpotifyAccount.setText(spotify.account_name);
binding.settingsSpotifyAccount.setTextColor(getResources().getColor(R.color.okGreen));
// Hide login buttons (we are already connected)
binding.settingsSpotifyUser.setVisibility(View.GONE);
binding.settingsSpotifyPassword.setVisibility(View.GONE);
binding.settingsSpotifySignIn.setVisibility(View.GONE);
binding.settingsSpotifyCredentialsTwice.setVisibility(View.GONE);
}
//Set 'sign in' button action : call spotify auth
binding.settingsSpotifySignIn.setOnClickListener(v ->
BladeApplication.obtainExecutorService().execute(() ->
{
Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
//Try to login player