This repository has been archived by the owner on Jan 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Source.java
2275 lines (1996 loc) · 99.7 KB
/
Source.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.library;
import android.app.Application;
import android.content.*;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Looper;
import android.provider.MediaStore;
import android.util.Log;
import android.util.LongSparseArray;
import android.widget.Toast;
import com.deezer.sdk.model.User;
import com.deezer.sdk.network.connect.DeezerConnect;
import com.deezer.sdk.network.connect.SessionStore;
import com.deezer.sdk.network.request.DeezerRequest;
import com.deezer.sdk.network.request.DeezerRequestFactory;
import com.deezer.sdk.network.request.JsonUtils;
import com.deezer.sdk.player.TrackPlayer;
import com.deezer.sdk.player.event.OnPlayerStateChangeListener;
import com.deezer.sdk.player.event.PlayerState;
import com.deezer.sdk.player.networkcheck.WifiAndMobileNetworkStateChecker;
import com.spotify.sdk.android.player.*;
import com.spotify.sdk.android.player.Error;
import kaaes.spotify.webapi.android.SpotifyApi;
import kaaes.spotify.webapi.android.SpotifyError;
import kaaes.spotify.webapi.android.SpotifyService;
import kaaes.spotify.webapi.android.models.*;
import retrofit.RetrofitError;
import v.blade.R;
import v.blade.player.PlayerMediaPlayer;
import v.blade.ui.settings.SettingsActivity;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static v.blade.library.LibraryService.CACHE_SEPARATOR;
public abstract class Source
{
private final int iconImage;
private final int logoImage;
private int priority;
private boolean available;
private String name;
private Source(int iconImage, int logoImage, String name) {this.iconImage = iconImage; this.logoImage = logoImage; this.name = name;}
public int getIconImage() {return iconImage;}
public int getLogoImage() {return logoImage;}
public int getPriority() {return priority;}
public void setPriority(int priority) {this.priority = priority;}
public void setAvailable(boolean available) {this.available = available;}
public boolean isAvailable() {return this.available;}
public String getName() {return name;}
@Override public String toString() {return name;}
//source settings/init/player...
public abstract void initConfig(SharedPreferences accountsPrefs);
public abstract void disconnect();
public abstract String getUserName();
public abstract SourcePlayer getPlayer();
//source songs registering
public abstract void registerCachedSongs();
public abstract void loadCachedArts();
public abstract void registerSongs();
//source querying
public abstract List<LibraryObject> query(String query);
public abstract boolean searchForSong(Song song);
/* operations */
public interface OperationCallback {void onSucess(LibraryObject result); void onFailure();}
//playlist management operations
public abstract void addSongsToPlaylist(List<Song> songs, Playlist list, OperationCallback callback);
public abstract void removeSongFromPlaylist(Song song, Playlist list, OperationCallback callback);
public abstract void addPlaylist(String name, OperationCallback callback, boolean isPublic, boolean isCollaborative);
public abstract void removePlaylist(Playlist playlist, OperationCallback callback);
//library management operations
public abstract void addSongToLibrary(Song song, OperationCallback callback);
public abstract void removeSongFromLibrary(Song song, OperationCallback callback);
public abstract void addAlbumToLibrary(Album album, OperationCallback callback);
public abstract void removeAlbumFromLibrary(Album album, OperationCallback callback);
public static Source SOURCE_LOCAL_LIB = new Source(R.drawable.ic_local, 0, "Local")
{
private LongSparseArray<Album> idsorted_albums = null;
private SourcePlayer player = new SourcePlayer()
{
MediaPlayer mediaPlayer;
int duration = 1000; //getDuration may throw if unprepared...
@Override
public void init()
{
mediaPlayer = new MediaPlayer();
setListener(PlayerMediaPlayer.playerListener);
}
@Override
public void setListener(PlayerListener listener)
{
if(mediaPlayer == null) return;
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
listener.onSongCompletion();
}
});
}
@Override
public void play(PlayerCallback callback)
{
if(mediaPlayer == null) {if(callback != null) callback.onFailure(player); return;}
mediaPlayer.start();
if(callback != null) callback.onSucess(player);
}
@Override
public void pause(PlayerCallback callback)
{
if(mediaPlayer == null) {if(callback != null) callback.onFailure(player); return;}
mediaPlayer.pause();
if(callback != null) callback.onSucess(player);
}
@Override
public void playSong(Song song, PlayerCallback callback)
{
SongSources.SongSource local = song.getSources().getLocal();
if(local == null) {if(callback != null) callback.onFailure(player); return;}
if(mediaPlayer == null) {if(callback != null) callback.onFailure(player); return;}
if(song.getFormat().equals("audio/x-ms-wma"))
{
Toast.makeText(LibraryService.appContext, LibraryService.appContext.getString(R.string.format_unsupported), Toast.LENGTH_SHORT).show();
callback.onFailure(player);
return;
}
Uri songUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, (long) song.getSources().getLocal().getId());
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(LibraryService.appContext, songUri);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
@Override
public void onPrepared(MediaPlayer mp) {duration = mediaPlayer.getDuration(); play(callback);}
});
}
catch(Exception e) {if(callback != null) callback.onFailure(player);}
}
@Override
public void seekTo(int msec)
{
mediaPlayer.seekTo(msec);
}
@Override
public int getCurrentPosition()
{
return mediaPlayer.getCurrentPosition();
}
@Override
public int getDuration()
{
return duration;
}
};
@Override
public String getUserName() {return "";}
@Override
public SourcePlayer getPlayer() {return player;}
@Override
public List<LibraryObject> query(String query) {return new ArrayList<>();}
@Override
public void initConfig(SharedPreferences accountsPrefs)
{
setPriority(999);
player.init();
}
@Override
public void registerCachedSongs()
{
registerSongs();
}
@Override
public void registerSongs()
{
if(!LibraryService.configured) return;
System.out.println("[BLADE-LOCAL] Registering songs...");
//empty lists
LibraryService.getArtists().clear();
LibraryService.getAlbums().clear();
LibraryService.getSongs().clear();
LibraryService.getPlaylists().clear();
LibraryService.songsByName.clear();
/* get content resolver and init temp sorted arrays */
final ContentResolver musicResolver = LibraryService.appContext.getContentResolver();
boolean loadAlbumArts = true;
if(idsorted_albums != null) //load of album art is not finished but resync was called
loadAlbumArts = false;
if(loadAlbumArts) idsorted_albums = new LongSparseArray<>();
LongSparseArray<Song> idsorted_songs = new LongSparseArray<>();
/* let's get all music files of the user, and register them and their attributes */
android.database.Cursor musicCursor = musicResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst())
{
//get columns
int titleColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
int artistIdColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID);
int albumColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
int albumIdColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
int albumTrackColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.TRACK);
int songDurationColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
int formatColumn = musicCursor.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE);
int fileColumn = musicCursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
//add songs to list
do
{
long thisId = musicCursor.getLong(idColumn);
long artistId = musicCursor.getLong(artistIdColumn);
long albumId = musicCursor.getLong(albumIdColumn);
int albumTrack = musicCursor.getInt(albumTrackColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
String thisAlbum = musicCursor.getString(albumColumn);
long thisDuration = musicCursor.getLong(songDurationColumn);
String thisPath = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/" + musicCursor.getString(fileColumn);
//resolve null artist name
if(thisArtist == null || thisArtist.equals("<unknown>"))
thisArtist = LibraryService.appContext.getString(R.string.unknown_artist);
//resolve null album name (should not happen)
if(thisAlbum == null || thisAlbum.equals("<unknown>"))
thisAlbum = LibraryService.appContext.getString(R.string.unknown_album);
//set to empty string to avoid crashes (NullPointer), should definitely not happen but who knows
if(thisTitle == null) thisTitle = "";
Song s = LibraryService.registerSong(thisArtist, thisAlbum, albumTrack, thisDuration, thisTitle, new SongSources.SongSource(thisId, SOURCE_LOCAL_LIB));
s.setFormat(musicCursor.getString(formatColumn));
s.setPath(thisPath);
idsorted_songs.put(thisId, s);
if(loadAlbumArts)
if(idsorted_albums.get(albumId) == null) idsorted_albums.put(albumId, s.getAlbum());
}
while (musicCursor.moveToNext());
musicCursor.close();
}
/* we also need to get playlists on device */
android.database.Cursor playlistCursor = musicResolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, null, null, null, null);
if(playlistCursor!=null && playlistCursor.moveToFirst())
{
int idColumn = playlistCursor.getColumnIndex(MediaStore.Audio.Playlists._ID);
int nameColumn = playlistCursor.getColumnIndex(MediaStore.Audio.Playlists.NAME);
do
{
long thisId = playlistCursor.getLong(idColumn);
String thisName = playlistCursor.getString(nameColumn);
//now we have to resolve the content of this playlist
ArrayList<Song> thisList = new ArrayList<>();
android.database.Cursor thisPlaylistCursor = musicResolver.query(MediaStore.Audio.Playlists.Members.getContentUri("external", thisId), null, null, null, null);
if(thisPlaylistCursor!=null && thisPlaylistCursor.moveToFirst())
{
int audioIdColumn = thisPlaylistCursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID);
do
{
thisList.add(idsorted_songs.get(thisPlaylistCursor.getLong(audioIdColumn)));
} while(thisPlaylistCursor.moveToNext());
thisPlaylistCursor.close();
}
Playlist list = new Playlist(thisName, thisList);
list.getSources().addSource(new SongSources.SongSource(thisId, SOURCE_LOCAL_LIB));
LibraryService.getPlaylists().add(list);
if(LibraryService.currentCallback != null) LibraryService.currentCallback.onLibraryChange();
} while(playlistCursor.moveToNext());
playlistCursor.close();
}
System.out.println("[BLADE-LOCAL] Songs registered");
}
@Override
public void loadCachedArts()
{
if(idsorted_albums == null) return;
Cursor albumCursor = LibraryService.appContext.getContentResolver().
query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, null, null, null, null, null);
if(albumCursor!=null && albumCursor.moveToFirst())
{
int idCol = albumCursor.getColumnIndex(MediaStore.Audio.Albums._ID);
int artCol = albumCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART);
do
{
long thisId = albumCursor.getLong(idCol);
String path = albumCursor.getString(artCol);
Album a = idsorted_albums.get(thisId);
if(a != null)
{
LibraryService.loadArt(a, path, true);
}
} while (albumCursor.moveToNext());
albumCursor.close();
}
idsorted_albums = null;
}
@Override
public void addSongsToPlaylist(List<Song> songs, Playlist list, OperationCallback callback)
{
if(list.getSources().getSourceByPriority(0).getSource() != SOURCE_LOCAL_LIB) {callback.onFailure(); return;}
int count = list.getContent().size();
ContentValues[] values = new ContentValues[songs.size()];
for (int i = 0; i < songs.size(); i++)
{
SongSources.SongSource local = songs.get(i).getSources().getLocal();
if(local == null) {callback.onFailure(); return;}
values[i] = new ContentValues();
values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, i + count + 1);
values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, (long) songs.get(i).getSources().getLocal().getId());
}
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", (long) list.getSources().getLocal().getId());
ContentResolver resolver = LibraryService.appContext.getContentResolver();
int num = resolver.bulkInsert(uri, values);
resolver.notifyChange(Uri.parse("content://media"), null);
list.getContent().addAll(songs);
callback.onSucess(null);
}
@Override
public void removeSongFromPlaylist(Song song, Playlist list, OperationCallback callback)
{
if(list.getSources().getSourceByPriority(0).getSource() != SOURCE_LOCAL_LIB) {callback.onFailure(); return;}
ContentResolver resolver = LibraryService.appContext.getContentResolver();
try
{
Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", (long) list.getSources().getLocal().getId());
int countDel = resolver.delete(uri, MediaStore.Audio.Playlists.Members.AUDIO_ID + " = ? ",
new String[]{Long.toString((long) song.getSources().getLocal().getId())});
if(countDel >= 1)
{
callback.onSucess(null);
list.getContent().remove(song);
if(LibraryService.currentCallback != null) LibraryService.currentCallback.onLibraryChange();
}
else callback.onFailure();
}
catch (Exception e)
{
callback.onFailure();
e.printStackTrace();
}
}
@Override
public boolean searchForSong(Song song) {return false;}
@Override
public void disconnect() {}
@Override
public void addPlaylist(String name, OperationCallback callback, boolean isPublic, boolean isCollaborative)
{
ContentResolver contentResolver = LibraryService.appContext.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Audio.Playlists.NAME, name);
contentValues.put(MediaStore.Audio.Playlists.DATE_ADDED, System.currentTimeMillis());
contentValues.put(MediaStore.Audio.Playlists.DATE_MODIFIED, System.currentTimeMillis());
Uri uri = contentResolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, contentValues);
if(uri != null)
{
long mPlaylistId = Long.parseLong(uri.getLastPathSegment());
//add playlist in RAM
Playlist list = new Playlist(name, new ArrayList<>());
list.getSources().addSource(new SongSources.SongSource(mPlaylistId, SOURCE_LOCAL_LIB));
LibraryService.getPlaylists().add(list);
if(LibraryService.currentCallback != null) LibraryService.currentCallback.onLibraryChange();
callback.onSucess(list);
}
else callback.onFailure();
}
@Override
public void removePlaylist(Playlist list, OperationCallback callback)
{
if(list.getSources().getSourceByPriority(0).getSource() != SOURCE_LOCAL_LIB) {callback.onFailure(); return;}
//TODO : delete playlist file
ContentResolver contentResolver = LibraryService.appContext.getContentResolver();
String where = MediaStore.Audio.Playlists._ID + "=?";
String[] whereVal = {Long.toString((long) list.getSources().getLocal().getId())};
int deleteCount = contentResolver.delete(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, where, whereVal);
if(deleteCount >= 1)
{
//remove playlist from ram
LibraryService.getPlaylists().remove(list);
if(LibraryService.currentCallback != null) LibraryService.currentCallback.onLibraryChange();
callback.onSucess(null);
}
else callback.onFailure();
}
public void addSongToLibrary(Song song, OperationCallback callback)
{callback.onFailure();}
public void removeSongFromLibrary(Song song, OperationCallback callback)
{
SongSources.SongSource local = song.getSources().getLocal();
if(local == null) {if(callback != null) callback.onFailure(); return;}
new File(song.getPath()).delete();
ContentResolver resolver = LibraryService.appContext.getContentResolver();
int count = resolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
MediaStore.Audio.Media._ID + " = " + local.getId(),
null);
if(count >= 1)
{
//unregister song from library
LibraryService.unregisterSong(song, local);
if(callback != null) callback.onSucess(null);
}
else if(callback != null) callback.onFailure();
}
public void addAlbumToLibrary(Album album, OperationCallback callback)
{callback.onFailure();}
public void removeAlbumFromLibrary(Album album, OperationCallback callback)
{
//TODO : handle errors
for(Song s : album.getSongs())
{
removeSongFromLibrary(s, null);
}
callback.onSucess(null);
//TODO : should i delete album entry from content resolver ? (++artist entry if last album)
}
};
public static Spotify SOURCE_SPOTIFY = new Spotify();
public static Deezer SOURCE_DEEZER = new Deezer();
public static Source SOURCES[] = new Source[]{SOURCE_LOCAL_LIB, SOURCE_SPOTIFY, SOURCE_DEEZER};
public static class Spotify extends Source
{
public final String SPOTIFY_CLIENT_ID = "2f95bc7168584e7aa67697418a684bae";
public final String SPOTIFY_REDIRECT_URI = "http://valou3433.fr/";
public String SPOTIFY_USER_TOKEN;
public String SPOTIFY_REFRESH_TOKEN;
public final SpotifyApi spotifyApi = new SpotifyApi();
public UserPrivate mePrivate;
private File spotifyCacheFile;
private File spotifyPlaylistsCache;
private ArrayList<LibraryObject> spotifyCachedToLoadArt;
public SourcePlayer player = new SourcePlayer()
{
SpotifyPlayer spotifyPlayer;
@Override
public void init()
{
Config playerConfig = new Config(LibraryService.appContext, SPOTIFY_USER_TOKEN, SPOTIFY_CLIENT_ID);
com.spotify.sdk.android.player.Spotify.getPlayer(playerConfig, LibraryService.appContext, new SpotifyPlayer.InitializationObserver()
{
@Override
public void onInitialized(final SpotifyPlayer p)
{
spotifyPlayer = p;
setListener(PlayerMediaPlayer.playerListener);
spotifyPlayer.addConnectionStateCallback(new ConnectionStateCallback()
{
@Override
public void onLoggedIn() {}
@Override
public void onLoggedOut() {}
@Override
public void onLoginFailed(Error error)
{
Toast.makeText(LibraryService.appContext, LibraryService.appContext.getString(R.string.player_login_error) + " Spotify", Toast.LENGTH_SHORT).show();
}
@Override
public void onTemporaryError() {}
@Override
public void onConnectionMessage(String s) {}
});
}
@Override
public void onError(Throwable throwable)
{
Toast.makeText(LibraryService.appContext, LibraryService.appContext.getString(R.string.player_unknown_error) + " Spotify", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void setListener(PlayerListener listener)
{
spotifyPlayer.addNotificationCallback(new Player.NotificationCallback()
{
@Override
public void onPlaybackEvent(PlayerEvent playerEvent)
{
if(playerEvent.equals(PlayerEvent.kSpPlaybackNotifyAudioDeliveryDone))
{
listener.onSongCompletion();
}
}
@Override
public void onPlaybackError(Error error)
{
listener.onPlaybackError(player, error.name());
}
});
}
@Override
public void play(PlayerCallback callback)
{
if(spotifyPlayer == null) {callback.onFailure(this); return;}
spotifyPlayer.resume(new Player.OperationCallback()
{
@Override
public void onSuccess() {callback.onSucess(player);}
@Override
public void onError(Error error) {callback.onFailure(player);}
});
}
@Override
public void pause(PlayerCallback callback)
{
if(spotifyPlayer == null) {if(callback != null) callback.onFailure(player); return;}
spotifyPlayer.pause(new Player.OperationCallback()
{
@Override
public void onSuccess() {if(callback != null) callback.onSucess(player);}
@Override
public void onError(Error error) {if(callback != null) callback.onFailure(player);}
});
}
@Override
public void playSong(Song song, PlayerCallback callback)
{
SongSources.SongSource spot = song.getSources().getSpotify();
if(spot == null) {if(callback != null) callback.onFailure(player); return;}
if(spotifyPlayer == null)
{
if(callback != null) callback.onFailure(player);
return;
}
spotifyPlayer.playUri(new Player.OperationCallback()
{
@Override
public void onSuccess() {if(callback != null) callback.onSucess(player);}
@Override
public void onError(Error error) {if(callback != null) callback.onFailure(player);}
}, "spotify:track:" + spot.getId(), 0, 0);
}
@Override
public void seekTo(int msec)
{
if(spotifyPlayer != null) spotifyPlayer.seekToPosition(null, msec);
}
@Override
public int getCurrentPosition()
{
return spotifyPlayer == null ? 0 : (int) spotifyPlayer.getPlaybackState().positionMs;
}
};
Spotify()
{
super(R.drawable.ic_spotify, R.drawable.ic_spotify_logo, "Spotify");
}
@Override
public SourcePlayer getPlayer() {return player;}
@Override
public String getUserName() {return mePrivate == null ? "" : (mePrivate.display_name == null ? mePrivate.id : mePrivate.display_name);}
@Override
public void initConfig(SharedPreferences accountsPrefs)
{
spotifyCacheFile = new File(LibraryService.appContext.getCacheDir().getAbsolutePath() + "/spotify.cached");
spotifyPlaylistsCache = new File(LibraryService.appContext.getCacheDir().getAbsolutePath() + "/spotifyPlaylists/");
if(!spotifyPlaylistsCache.exists()) spotifyPlaylistsCache.mkdir();
setPriority(accountsPrefs.getInt("spotify_prior", 0));
//setup spotify api
if(SPOTIFY_USER_TOKEN == null)
{
SPOTIFY_USER_TOKEN = accountsPrefs.getString("spotify_token", null);
SPOTIFY_REFRESH_TOKEN = accountsPrefs.getString("spotify_refresh_token", null);
}
if(SPOTIFY_USER_TOKEN != null)
{
spotifyApi.setAccessToken(SPOTIFY_USER_TOKEN);
//check for token validity
new Thread()
{
public void run()
{
try
{
mePrivate = spotifyApi.getService().getMe();
}
catch(RetrofitError e)
{
if(e.getResponse() != null && e.getResponse().getStatus() == 401)
{
Log.println(Log.INFO, "[BLADE-SPOTIFY]", "Actualizing token.");
refreshSpotifyToken();
mePrivate = spotifyApi.getService().getMe();
}
}
player.init();
}
}.start();
setAvailable(true);
}
}
@Override
public void disconnect()
{
setAvailable(false);
setPriority(0);
SPOTIFY_USER_TOKEN = null;
SPOTIFY_REFRESH_TOKEN = null;
mePrivate = null;
SharedPreferences accountsPrefs = LibraryService.appContext.getSharedPreferences(SettingsActivity.PREFERENCES_ACCOUNT_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = accountsPrefs.edit();
editor.remove("spotify_token");
editor.remove("spotify_refresh_token");
editor.remove("spotify_prior");
editor.apply();
//remove cache
spotifyCacheFile.delete();
if(spotifyPlaylistsCache.exists())
{
for(File f : spotifyPlaylistsCache.listFiles()) f.delete();
spotifyPlaylistsCache.delete();
}
//wait for resync
}
@Override
public void registerCachedSongs()
{
if(!LibraryService.configured) return;
spotifyCachedToLoadArt = new ArrayList<>();
System.out.println("[BLADE-SPOTIFY] Registering cached songs...");
try
{
if(spotifyCacheFile.exists())
{
//spotify library
BufferedReader spr = new BufferedReader(new FileReader(spotifyCacheFile));
while(spr.ready())
{
String[] tp = spr.readLine().split(CACHE_SEPARATOR);
Song song = LibraryService.registerSong(tp[2], tp[1],
Integer.parseInt(tp[4]), Long.parseLong(tp[5]), tp[0], new SongSources.SongSource(tp[6], SOURCE_SPOTIFY));
song.setFormat(tp[3]);
if(!song.getAlbum().hasArt() && !song.getAlbum().getArtLoading())
{
//the image is supposed to be cached locally, so no need to provide URL
spotifyCachedToLoadArt.add(song.getAlbum());
song.getAlbum().setArtLoading();
}
}
spr.close();
//spotify playlists
for(File f : spotifyPlaylistsCache.listFiles())
{
ArrayList<Song> thisList = new ArrayList<>();
BufferedReader sppr = new BufferedReader(new FileReader(f));
String id = sppr.readLine();
boolean isMine = Boolean.parseBoolean(sppr.readLine());
String owner = null; String ownerID = null;
if(!isMine) {owner = sppr.readLine(); ownerID = sppr.readLine();}
boolean isCollab = Boolean.parseBoolean(sppr.readLine());
while(sppr.ready())
{
String[] tp = sppr.readLine().split(CACHE_SEPARATOR);
Song song = LibraryService.SAVE_PLAYLISTS_TO_LIBRARY ?
LibraryService.registerSong(tp[2], tp[1], Integer.parseInt(tp[4]),
Long.parseLong(tp[5]), tp[0], new SongSources.SongSource(tp[6], SOURCE_SPOTIFY))
: LibraryService.getSongHandle(tp[0], tp[1], tp[2], Long.parseLong(tp[5]),
new SongSources.SongSource(tp[6], SOURCE_SPOTIFY), Integer.parseInt(tp[4]));
song.setFormat(tp[3]);
thisList.add(song);
if(!song.getAlbum().hasArt() && !song.getAlbum().getArtLoading())
{
//the image is supposed to be cached locally, so no need to provide URL
spotifyCachedToLoadArt.add(song.getAlbum());
song.getAlbum().setArtLoading();
}
}
sppr.close();
Playlist p = new Playlist(f.getName(), thisList);
if(!isMine) p.setOwner(owner, ownerID);
if(isCollab) p.setCollaborative();
spotifyCachedToLoadArt.add(p);
p.setArtLoading();
p.getSources().addSource(new SongSources.SongSource(id, SOURCE_SPOTIFY));
LibraryService.getPlaylists().add(p);
}
}
}
catch(IOException e)
{
Log.println(Log.ERROR, "[BLADE-SPOTIFY]", "Cache restore : IOException");
e.printStackTrace();
}
System.out.println("[BLADE-SPOTIFY] Cached songs registered.");
}
@Override
public void loadCachedArts()
{
if(spotifyCachedToLoadArt == null) return;
for(LibraryObject alb : spotifyCachedToLoadArt)
{
LibraryService.loadArt(alb, "", false);
}
spotifyCachedToLoadArt = null;
}
@Override
public void registerSongs()
{
if(!LibraryService.configured) return;
if(SPOTIFY_USER_TOKEN == null) return;
// list used for spotify cache
ArrayList<Song> spotifySongs = new ArrayList<>();
ArrayList<Playlist> spotifyPlaylists = new ArrayList<>();
SpotifyService service = spotifyApi.getService();
try
{
if(mePrivate == null) mePrivate = service.getMe();
//requests
HashMap<String, Object> params = new HashMap<>();
params.put("limit", 50);
Pager<SavedTrack> userTracks = service.getMySavedTracks(params);
//parse user tracks request response
int count = userTracks.total;
int offset = 0;
while(true)
{
for (SavedTrack track : userTracks.items)
{
Track t = track.track;
Song s = LibraryService.registerSong(t.artists.get(0).name, t.album.name,
t.track_number, t.duration_ms, t.name, new SongSources.SongSource(t.id, SOURCE_SPOTIFY));
spotifySongs.add(s);
if(!s.getAlbum().hasArt())
{
if(t.album.images != null && t.album.images.size() >= 1)
{
Image albumImage = t.album.images.get(0);
LibraryService.loadArt(s.getAlbum(), albumImage.url, false);
}
}
}
count -= 50;
if(count <= 0) break;
else
{
offset += 50;
params.put("offset", offset);
userTracks = service.getMySavedTracks(params);
}
}
params.put("limit", 50);
params.put("offset", 0);
Pager<SavedAlbum> userAlbums = service.getMySavedAlbums(params);
offset = 0;
count = userAlbums.total;
while(true)
{
//parse user albums request response
for(SavedAlbum album : userAlbums.items)
{
Album savedAlbum = null;
kaaes.spotify.webapi.android.models.Album alb = album.album;
Pager<Track> tracks = service.getAlbumTracks(alb.id);
for(Track t : tracks.items)
{
Song s = LibraryService.registerSong(t.artists.get(0).name, alb.name,
t.track_number, t.duration_ms, t.name, new SongSources.SongSource(t.id, SOURCE_SPOTIFY));
spotifySongs.add(s);
if (savedAlbum == null) savedAlbum = s.getAlbum();
}
if(!savedAlbum.hasArt())
{
if(alb.images != null && alb.images.size() >= 1)
{
Image albumImage = alb.images.get(0);
LibraryService.loadArt(savedAlbum, albumImage.url, false);
}
}
}
count-=50;
if(count <= 0) break;
else
{
offset += 50;
params.put("offset", offset);
userAlbums = service.getMySavedAlbums(params);
}
}
params.put("limit", 20);
params.put("offset", 0);
Pager<PlaylistSimple> userPlaylists = service.getMyPlaylists();
offset = 0;
count = userPlaylists.total;
while(true)
{
//parse user playlists request response
for(PlaylistSimple playlistBase : userPlaylists.items)
{
ArrayList<Song> thisList = new ArrayList<>();
HashMap<String, Object> map = new HashMap<>();
int trackNbr = playlistBase.tracks.total;
int poffset = 0;
while(trackNbr > 0)
{
map.put("offset", poffset);
Pager<PlaylistTrack> tracks = service.getPlaylistTracks(playlistBase.owner.id, playlistBase.id, map);
for(PlaylistTrack pt : tracks.items)
{
Track t = pt.track;
Song s;
if(LibraryService.SAVE_PLAYLISTS_TO_LIBRARY)
s = LibraryService.registerSong(t.artists.get(0).name, t.album.name,
t.track_number, t.duration_ms, t.name, new SongSources.SongSource(t.id, SOURCE_SPOTIFY));
else
s = LibraryService.getSongHandle(t.name, t.album.name, t.artists.get(0).name, t.duration_ms, new SongSources.SongSource(t.id, SOURCE_SPOTIFY),
t.track_number);
//get albumart for this song
if(!s.getAlbum().hasArt())
{
if(t.album.images != null && t.album.images.size() >= 1)
{
Image albumImage = t.album.images.get(0);
LibraryService.loadArt(s.getAlbum(), albumImage.url, false);
}
}
thisList.add(s);
}
poffset+=100;
trackNbr-=100;
}
Playlist list = new Playlist(playlistBase.name, thisList);
list.getSources().addSource(new SongSources.SongSource(playlistBase.id, SOURCE_SPOTIFY));
if(playlistBase.collaborative) list.setCollaborative();
if(playlistBase.owner != null) if(!playlistBase.owner.id.equals(mePrivate.id)) list.setOwner(playlistBase.owner.display_name == null ? playlistBase.owner.id : playlistBase.owner.display_name, playlistBase.owner.id);
spotifyPlaylists.add(list);
LibraryService.getPlaylists().add(list);
if(LibraryService.currentCallback != null) LibraryService.currentCallback.onLibraryChange();
if(playlistBase.images != null && playlistBase.images.size() >= 1)
LibraryService.loadArt(list, playlistBase.images.get(0).url, false);
}
count -= 20;
if(count <= 0) break;
else
{
offset += 20;
params.put("offset", offset);
userPlaylists = service.getMyPlaylists(params);
}
}
// cache all spotifySongs and spotifyPlaylists
try
{
//library songs
BufferedWriter bw = new BufferedWriter(new FileWriter((spotifyCacheFile)));
for(Song song : spotifySongs)
{
bw.write(song.getTitle() + CACHE_SEPARATOR + song.getAlbum().getName() + CACHE_SEPARATOR + song.getArtist().getName() + CACHE_SEPARATOR
+ song.getFormat() + CACHE_SEPARATOR + song.getTrackNumber() + CACHE_SEPARATOR + song.getDuration() + CACHE_SEPARATOR + song.getSources().getSpotify().getId()
+ CACHE_SEPARATOR);
bw.newLine();
}
bw.close();
//playlists
if(spotifyPlaylistsCache.exists() && spotifyPlaylistsCache.listFiles() != null)
for(File f : spotifyPlaylistsCache.listFiles()) f.delete();
for(Playlist p : spotifyPlaylists)
{
cachePlaylist(p);
}
}
catch(IOException e)
{
Log.println(Log.ERROR, "[BLADE-SPOTIFY]", "Error while writing cache !");
}
}
catch (RetrofitError error)
{
error.printStackTrace();
if(error.getResponse() == null) return;
if(error.getResponse().getStatus() == 401)
{
Log.println(Log.INFO, "[BLADE-SPOTIFY]", "Actualizing token.");
refreshSpotifyToken();
registerSongs();