This repository has been archived by the owner on Jun 23, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
PlaylistManager.cs
1345 lines (1189 loc) · 61.9 KB
/
PlaylistManager.cs
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
using Android.App;
using Android.Content;
using Android.Database;
using Android.Graphics;
using Android.OS;
using Android.Provider;
using Android.Support.Design.Widget;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
using Opus.Adapter;
using Opus.Api.Services;
using Opus.DataStructure;
using Opus.Others;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static Android.Provider.MediaStore.Audio;
using AlertDialog = Android.Support.V7.App.AlertDialog;
using CursorLoader = Android.Support.V4.Content.CursorLoader;
using Environment = System.Environment;
using Path = System.IO.Path;
using Playlist = Google.Apis.YouTube.v3.Data.Playlist;
using PlaylistItem = Opus.DataStructure.PlaylistItem;
using Uri = Android.Net.Uri;
namespace Opus.Api
{
public class PlaylistManager
{
/// <summary>
/// Return a complete PlaylistItem object from the youtube id of the playlist
/// </summary>
/// <param name="playlistID"></param>
/// <returns></returns>
public static async Task<PlaylistItem> GetPlaylist(string playlistID)
{
try
{
PlaylistsResource.ListRequest request = YoutubeManager.YoutubeService.Playlists.List("snippet");
request.Id = playlistID;
PlaylistListResponse response = await request.ExecuteAsync();
if (response.Items.Count > 0)
{
return new PlaylistItem(response.Items[0].Snippet.Title, -1, playlistID)
{
HasWritePermission = false,
ImageURL = response.Items[0].Snippet.Thumbnails.Standard.Url,
Owner = response.Items[0].Snippet.ChannelTitle
};
}
else
return null;
}
catch(Exception ex)
{
Console.WriteLine("&Get playlist catch called, ex: " + ex.Message);
return null;
}
}
#region PlayInOrder
/// <summary>
/// Play all tracks of a playlist in the default order. Handle both youtube and local playlists.
/// </summary>
/// <param name="item"></param>
/// <param name="startingPosition">The position where you want to start playing</param>
public static void PlayInOrder(PlaylistItem item, int startingPosition = 0)
{
if (item.LocalID != -1 && item.LocalID != 0 || item.SyncState == SyncState.True)
PlayInOrder(item.LocalID, startingPosition);
else
PlayInOrder(item.YoutubeID, startingPosition);
}
/// <summary>
/// Play a local playlist in the default order.
/// </summary>
/// <param name="LocalID"></param>
/// <param name="startingPosition">The position where you want to start playing</param>
public static async void PlayInOrder(long LocalID, int startingPosition = 0)
{
List<Song> tracks = await GetTracksFromLocalPlaylist(LocalID);
if (tracks.Count == 0)
return;
SongManager.Play(tracks[startingPosition]);
tracks.RemoveAt(startingPosition);
await Task.Delay(1000);
while (MusicPlayer.instance == null)
await Task.Delay(10);
MusicPlayer.instance.InsertToQueue(0, tracks.GetRange(0, startingPosition).ToArray());
MusicPlayer.currentID = startingPosition;
Queue.instance?.RefreshCurrent();
Player.instance?.RefreshPlayer();
MusicPlayer.instance.AddToQueue(tracks.GetRange(startingPosition, tracks.Count - startingPosition));
}
/// <summary>
/// Play a youtube playlist in the default order.
/// </summary>
/// <param name="YoutubeID"></param>
/// <param name="startingPosition">The position where you want to start playing</param>
public static async void PlayInOrder(string YoutubeID, int startingPosition = 0)
{
List<Song> tracks = await GetTracksFromYoutubePlaylist(YoutubeID, (song) =>
{
SongManager.Play(song);
}, startingPosition);
if (tracks.Count == 0)
return;
tracks.RemoveAt(startingPosition);
await Task.Delay(1000);
while (MusicPlayer.instance == null)
await Task.Delay(10);
MusicPlayer.instance.InsertToQueue(0, tracks.GetRange(0, startingPosition).ToArray());
MusicPlayer.currentID = startingPosition;
Queue.instance?.RefreshCurrent();
Player.instance?.RefreshPlayer();
MusicPlayer.instance.AddToQueue(tracks.GetRange(startingPosition, tracks.Count - startingPosition));
}
#endregion
#region Shuffle
/// <summary>
/// Play all tracks of a playlist in a random order. Handle both youtube and local playlists.
/// </summary>
/// <param name="item"></param>
public static void Shuffle(PlaylistItem item)
{
if (item.LocalID != -1 && item.LocalID != 0 || item.SyncState == SyncState.True)
Shuffle(item.LocalID);
else
Shuffle(item.YoutubeID);
}
/// <summary>
/// Play all tracks of a local playlist in a random order.
/// </summary>
/// <param name="LocalID"></param>
public async static void Shuffle(long LocalID)
{
List<Song> tracks = await GetTracksFromLocalPlaylist(LocalID);
if (tracks.Count == 0)
return;
Random r = new Random();
tracks = tracks.OrderBy(x => r.Next()).ToList();
SongManager.Play(tracks[0]);
tracks.RemoveAt(0);
await Task.Delay(1000);
while (MusicPlayer.instance == null)
await Task.Delay(10);
MusicPlayer.instance.AddToQueue(tracks);
}
/// <summary>
/// Play all tracks of a youtube playlist in a random order.
/// </summary>
/// <param name="YoutubeID"></param>
public static async void Shuffle(string YoutubeID)
{
Random r = new Random();
int playPos = r.Next(50);
List<Song> tracks = await GetTracksFromYoutubePlaylist(YoutubeID, (song) =>
{
MusicPlayer.currentID = -1;
SongManager.Play(song);
}, playPos);
if (tracks.Count == 0)
return;
if (tracks.Count >= playPos)
{
tracks.RemoveAt(playPos);
tracks = tracks.OrderBy(x => r.Next()).ToList();
MusicPlayer.instance.AddToQueue(tracks);
}
else
{
playPos = r.Next(tracks.Count);
MusicPlayer.currentID = -1;
SongManager.Play(tracks[playPos]);
tracks.RemoveAt(playPos);
tracks = tracks.OrderBy(x => r.Next()).ToList();
MusicPlayer.instance.AddToQueue(tracks);
}
}
#endregion
#region AddToQueue
/// <summary>
/// Add every song of a playlist in the queue. (Using default order). Handle both local and youtube playlists.
/// </summary>
/// <param name="item"></param>
public static void AddToQueue(PlaylistItem item)
{
if (item.LocalID != -1 && item.LocalID != 0 || item.SyncState == SyncState.True)
AddToQueue(item.LocalID);
else
AddToQueue(item.YoutubeID);
}
/// <summary>
/// Add every song of a local playlist in the queue. (Using default order).
/// </summary>
/// <param name="LocalID"></param>
public async static void AddToQueue(long LocalID)
{
if (MusicPlayer.instance == null || MusicPlayer.queue == null || MusicPlayer.queue?.Count == 0)
{
PlayInOrder(LocalID);
return;
}
List<Song> tracks = await GetTracksFromLocalPlaylist(LocalID);
MusicPlayer.instance.AddToQueue(tracks);
}
/// <summary>
/// Add every song of a youtube playlist in the queue. (Using default order).
/// </summary>
/// <param name="YoutubeID"></param>
public static async void AddToQueue(string YoutubeID)
{
if (MusicPlayer.instance == null || MusicPlayer.queue == null || MusicPlayer.queue?.Count == 0)
{
PlayInOrder(YoutubeID);
return;
}
MusicPlayer.instance.AddToQueue((await GetTracksFromYoutubePlaylist(YoutubeID)));
}
#endregion
#region UI
/// <summary>
/// Display the create playlist dialog (where the user can choose a location and a name). After completing the creation, the songs array will be added to this playlist.
/// </summary>
/// <param name="songs"></param>
public static void CreatePlalistDialog(Song[] songs)
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.instance, MainActivity.dialogTheme);
builder.SetTitle(Resource.String.new_playlist);
View view = MainActivity.instance.LayoutInflater.Inflate(Resource.Layout.CreatePlaylistDialog, null);
builder.SetView(view);
PlaylistLocationAdapter adapter = new PlaylistLocationAdapter(MainActivity.instance, Android.Resource.Layout.SimpleSpinnerItem, new string[] { MainActivity.instance.GetString(Resource.String.create_local), MainActivity.instance.GetString(Resource.String.create_youtube), MainActivity.instance.GetString(Resource.String.create_synced) })
{
YoutubeWorkflow = YoutubeManager.IsUsingAPI || (songs.Length == 1 && songs[0].YoutubeID == null) ? false : true
};
adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
view.FindViewById<Spinner>(Resource.Id.playlistLocation).Adapter = adapter;
builder.SetNegativeButton(Resource.String.cancel, (senderAlert, args) => { });
builder.SetPositiveButton(Resource.String.ok, (senderAlert, args) =>
{
switch (view.FindViewById<Spinner>(Resource.Id.playlistLocation).SelectedItemPosition)
{
case 0:
CreateLocalPlaylist(view.FindViewById<EditText>(Resource.Id.playlistName).Text, songs);
break;
case 1:
CreateYoutubePlaylist(view.FindViewById<EditText>(Resource.Id.playlistName).Text, songs);
break;
case 2:
CreateLocalPlaylist(view.FindViewById<EditText>(Resource.Id.playlistName).Text, songs, true);
CreateYoutubePlaylist(view.FindViewById<EditText>(Resource.Id.playlistName).Text, songs);
break;
}
});
builder.Show();
}
/// <summary>
/// Display the dialog listing all the playlist where you can add a song. If the song is already contained in one of the playlist, it will be displayed.
/// </summary>
/// <param name="item"></param>
public static async void AddSongToPlaylistDialog(Song item)
{
if (item.YoutubeID == null)
item = LocalManager.CompleteItem(item);
List<PlaylistItem> playlists = new List<PlaylistItem>();
List<PlaylistItem> synced = new List<PlaylistItem>();
(List<PlaylistItem> localPlaylists, string error) = await GetLocalPlaylists();
if (localPlaylists != null)
{
foreach (PlaylistItem playlist in localPlaylists)
playlist.SongContained = await LocalManager.SongIsContained(item.LocalID, playlist.LocalID);
(playlists, synced) = await ProcessSyncedPlaylists(localPlaylists);
playlists.AddRange(synced);
}
PlaylistItem Loading = new PlaylistItem("Loading", null);
playlists.Add(Loading);
View Layout = MainActivity.instance.LayoutInflater.Inflate(Resource.Layout.AddToPlaylistLayout, null);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.instance, MainActivity.dialogTheme);
builder.SetTitle(Resource.String.save_playlist);
builder.SetView(Layout);
RecyclerView ListView = Layout.FindViewById<RecyclerView>(Resource.Id.recycler);
ListView.SetLayoutManager(new LinearLayoutManager(MainActivity.instance));
AddToPlaylistAdapter adapter = new AddToPlaylistAdapter(playlists);
ListView.SetAdapter(adapter);
adapter.ItemClick += async (sender, position) =>
{
AddToPlaylistHolder holder = (AddToPlaylistHolder)ListView.GetChildViewHolder(ListView.GetChildAt(position));
bool add = !holder.Added.Checked;
holder.Added.Checked = add;
PlaylistItem playlist = playlists[position];
if (add)
{
if (playlist.LocalID != 0)
{
if (item.LocalID == 0 || item.LocalID == -1)
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
YoutubeManager.DownloadFiles(new[] { DownloadFile.From(item, playlist.Name) });
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
else
AddToLocalPlaylist(playlist.LocalID, new[] { item });
}
if (playlist.YoutubeID != null)
YoutubeManager.AddToPlaylist(new[] { item }, playlist.YoutubeID);
}
else
{
if (playlist.YoutubeID != null)
item = await CompleteItem(item, playlist.YoutubeID);
if (item.TrackID != null)
RemoveFromYoutubePlaylist(item.TrackID);
if (playlist.LocalID != 0)
{
ContentResolver resolver = MainActivity.instance.ContentResolver;
Uri plUri = Playlists.Members.GetContentUri("external", playlist.LocalID);
resolver.Delete(plUri, Playlists.Members.AudioId + "=?", new string[] { item.LocalID.ToString() });
}
}
};
builder.SetPositiveButton(Resource.String.ok, (sender, e) => { });
AlertDialog dialog = builder.Create();
Layout.FindViewById<LinearLayout>(Resource.Id.CreatePlaylist).Click += (sender, e) => { dialog.Dismiss(); CreatePlalistDialog(new[] { item }); };
dialog.Show();
if (item.YoutubeID == null)
{
if (item.YoutubeID == null)
{
playlists.Remove(Loading);
adapter.NotifyItemRemoved(playlists.Count);
return;
}
}
if (YoutubeManager.IsUsingAPI || !await MainActivity.instance.WaitForYoutube())
{
//Toast.MakeText(MainActivity.instance, Resource.String.youtube_loading_error, ToastLength.Long).Show();
playlists.Remove(Loading);
adapter.NotifyItemRemoved(playlists.Count);
return;
}
(List<PlaylistItem> youtube, string er) = await GetOwnedYoutubePlaylists(synced, (playlist, position) =>
{
AddToPlaylistHolder holder = (AddToPlaylistHolder)ListView.GetChildViewHolder(ListView.GetChildAt(position));
holder.SyncLoading.Visibility = ViewStates.Gone;
holder.Status.Visibility = ViewStates.Visible;
holder.Status.SetImageResource(Resource.Drawable.Sync);
});
if(youtube != null)
{
foreach (PlaylistItem playlist in youtube)
playlist.SongContained = await YoutubeManager.SongIsContained(item.YoutubeID, playlist.YoutubeID);
int positionStart = playlists.IndexOf(Loading);
playlists.Remove(Loading);
playlists.AddRange(youtube);
adapter.NotifyItemRangeInserted(positionStart, youtube.Count - 1);
adapter.NotifyItemChanged(playlists.Count);
}
else
{
playlists.Remove(Loading);
adapter.NotifyItemRemoved(playlists.Count);
}
}
/// <summary>
/// Display a dialog that will allow the user to rename the playlist.
/// </summary>
/// <param name="item">The playlist you want to rename</param>
/// <param name="UiCallback">A callback called after the rename</param>
public static void Rename(PlaylistItem item, Action UiCallback = null)
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.instance, MainActivity.dialogTheme);
builder.SetTitle(Resource.String.rename_playlist);
View view = MainActivity.instance.LayoutInflater.Inflate(Resource.Layout.CreatePlaylistDialog, null);
view.FindViewById(Resource.Id.playlistLocation).Visibility = ViewStates.Gone;
builder.SetView(view);
builder.SetNegativeButton(Resource.String.cancel, (senderAlert, args) => { });
builder.SetPositiveButton(Resource.String.rename, async (senderAlert, args) =>
{
if (item.LocalID != 0 && !await MainActivity.instance.GetWritePermission())
return;
string newName = view.FindViewById<EditText>(Resource.Id.playlistName).Text;
if (item.YoutubeID != null)
{
try
{
Playlist playlist = new Playlist
{
Snippet = new PlaylistSnippet()
};
playlist.Snippet.Title = newName;
playlist.Id = item.YoutubeID;
await YoutubeManager.YoutubeService.Playlists.Update(playlist, "snippet").ExecuteAsync();
}
catch (System.Net.Http.HttpRequestException)
{
MainActivity.instance.Timout();
}
}
if (item.LocalID != 0)
{
ContentValues value = new ContentValues();
value.Put(Playlists.InterfaceConsts.Name, newName);
MainActivity.instance.ContentResolver.Update(Playlists.ExternalContentUri, value, Playlists.InterfaceConsts.Id + "=?", new string[] { item.LocalID.ToString() });
}
item.Name = newName;
UiCallback?.Invoke();
});
builder.Show();
}
/// <summary>
/// Display a dialog that allow the user to delete the playlist (from youtube, from the local storage or both).
/// </summary>
/// <param name="item"></param>
/// <param name="UiCallback">Called when the user deleted the playlist</param>
public static void Delete(PlaylistItem item, Action UiCallback)
{
AlertDialog dialog = new AlertDialog.Builder(MainActivity.instance, MainActivity.dialogTheme)
.SetTitle(MainActivity.instance.GetString(Resource.String.delete_playlist, item.Name))
.SetPositiveButton(Resource.String.yes, async (sender, e) =>
{
if (item.LocalID != 0 && !await MainActivity.instance.GetWritePermission())
return;
if (item.SyncState != SyncState.False)
StopSyncing(item);
if (item.YoutubeID != null)
{
if (item.HasWritePermission)
{
try
{
PlaylistsResource.DeleteRequest deleteRequest = YoutubeManager.YoutubeService.Playlists.Delete(item.YoutubeID);
await deleteRequest.ExecuteAsync();
}
catch (System.Net.Http.HttpRequestException)
{
MainActivity.instance.Timout();
}
}
else
{
//try
//{
// ChannelSectionsResource.ListRequest forkedRequest = YoutubeEngine.youtubeService.ChannelSections.List("snippet,contentDetails");
// forkedRequest.Mine = true;
// ChannelSectionListResponse forkedResponse = await forkedRequest.ExecuteAsync();
// foreach (ChannelSection section in forkedResponse.Items)
// {
// if (section.Snippet.Title == "Saved Playlists")
// {
// section.ContentDetails.Playlists.Remove(YoutubeID);
// ChannelSectionsResource.UpdateRequest request = YoutubeEngine.youtubeService.ChannelSections.Update(section, "snippet,contentDetails");
// ChannelSection response = await request.ExecuteAsync();
// }
// }
//}
//catch (System.Net.Http.HttpRequestException)
//{
// MainActivity.instance.Timout();
//}
}
}
if (item.LocalID != 0)
{
ContentResolver resolver = MainActivity.instance.ContentResolver;
Uri uri = Playlists.ExternalContentUri;
resolver.Delete(Playlists.ExternalContentUri, Playlists.InterfaceConsts.Id + "=?", new string[] { item.LocalID.ToString() });
}
UiCallback?.Invoke();
})
.SetNegativeButton(Resource.String.no, (sender, e) => { })
.Create();
dialog.Show();
}
/// <summary>
/// Display the stop syncing dialog.
/// </summary>
/// <param name="item"></param>
/// <param name="UiCallback">Callback called when the playlist is not synced anymore.</param>
public static void StopSyncingDialog(PlaylistItem item, Action UiCallback)
{
AlertDialog dialog = new AlertDialog.Builder(MainActivity.instance, MainActivity.dialogTheme)
.SetTitle(MainActivity.instance.GetString(Resource.String.stop_syncing, item.Name))
.SetPositiveButton(Resource.String.yes, (sender, e) => { StopSyncing(item); UiCallback?.Invoke(); })
.SetNegativeButton(Resource.String.no, (sender, e) => { })
.Create();
dialog.Show();
}
/// <summary>
/// Remove a playlist from the synced database.
/// </summary>
/// <param name="item"></param>
public async static void StopSyncing(PlaylistItem item)
{
await Task.Run(() =>
{
SQLiteConnection db = new SQLiteConnection(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "SyncedPlaylists.sqlite"));
db.CreateTable<PlaylistItem>();
db.Delete(db.Table<PlaylistItem>().ToList().Find(x => x.LocalID == item.LocalID));
});
}
/// <summary>
/// Display the dialog to remove a track from the playlist. This can be undo by clicking on the "undo" button of the snackbar that will apear.
/// </summary>
/// <param name="item">The playlist item</param>
/// <param name="song">The song item</param>
/// <param name="position">The position of the removed item</param>
/// <param name="RemovedCallback">A callback called when the user click ok in the dialog. You just need to remove the track from the UI, everything else is already handled.</param>
/// <param name="CancelledCallback">A callback called when the user click cancel in the dialog</param>
/// <param name="UndoCallback">A callback called when the user click undo in the snackbar</param>
public async static void RemoveTrackFromPlaylistDialog(PlaylistItem item, Song song, int position, Action RemovedCallback, Action CancelledCallback, Action UndoCallback)
{
if (!await MainActivity.instance.GetWritePermission())
return;
AlertDialog dialog = new AlertDialog.Builder(MainActivity.instance, MainActivity.dialogTheme)
.SetTitle(MainActivity.instance.GetString(Resource.String.remove_from_playlist, song.Title))
.SetPositiveButton(Resource.String.yes, async (sender, e) =>
{
if(item.LocalID != -1)
RemoveFromLocalPlaylist(song, item.LocalID);
if (item.YoutubeID != null)
{
if (song.TrackID == null)
song = await CompleteItem(song, item.YoutubeID);
RemoveFromYoutubePlaylist(song.TrackID);
}
RemovedCallback?.Invoke();
//RemoveTrackFromPlaylistCallback callback = new RemoveTrackFromPlaylistCallback(song, item.LocalID, position);
//Snackbar snackBar = Snackbar.Make(MainActivity.instance.FindViewById(Resource.Id.snackBar), (song.Title.Length > 20 ? song.Title.Substring(0, 17) + "..." : song.Title) + MainActivity.instance.GetString(Resource.String.removed_from_playlist), Snackbar.LengthLong)
// .SetAction(MainActivity.instance.GetString(Resource.String.undo), (v) =>
// {
// callback.canceled = true;
// UndoCallback?.Invoke();
// });
//snackBar.AddCallback(callback);
//snackBar.View.FindViewById<TextView>(Resource.Id.snackbar_text).SetTextColor(Color.White);
//snackBar.Show();
})
.SetNegativeButton(Resource.String.no, (sender, e) => { CancelledCallback?.Invoke(); })
.Create();
dialog.Show();
}
#endregion
#region GetPlaylists
/// <summary>
/// This method will return all playlists available on the local storage in the array "playlists".
/// If there is an error, the Task will return an error message to display to the user.
/// </summary>
/// <param name="askForPermission">Should we ask for the read perission or simple return nothing if the user has not given the read permission.</param>
/// <returns>The List<PlaylistItem> contains all the local playlists or is null if there is an erorr. The string is the error message. If there is no error, this string is null.</returns>
public static async Task<(List<PlaylistItem>, string)> GetLocalPlaylists(bool askForPermission = true)
{
if (askForPermission)
{
if (!await MainActivity.instance.GetReadPermission())
return (null, Application.Context.GetString(Resource.String.localpl_noperm));
}
else
{
if (!MainActivity.instance.HasReadPermission())
return (null, Application.Context.GetString(Resource.String.localpl_noperm));
}
List<PlaylistItem> playlists = new List<PlaylistItem>();
Uri uri = Playlists.ExternalContentUri;
await Task.Run(() =>
{
if (Looper.MyLooper() == null)
Looper.Prepare();
CursorLoader loader = new CursorLoader(Application.Context, uri, null, null, null, null);
ICursor cursor = (ICursor)loader.LoadInBackground();
if (cursor != null && cursor.MoveToFirst())
{
int nameID = cursor.GetColumnIndex(Playlists.InterfaceConsts.Name);
int listID = cursor.GetColumnIndex(Playlists.InterfaceConsts.Id);
do
{
string name = cursor.GetString(nameID);
long id = cursor.GetLong(listID);
Uri musicUri = Playlists.Members.GetContentUri("external", id);
CursorLoader cursorLoader = new CursorLoader(Application.Context, musicUri, null, null, null, null);
ICursor musicCursor = (ICursor)cursorLoader.LoadInBackground();
playlists.Add(new PlaylistItem(name, id, musicCursor.Count) { HasWritePermission = true });
}
while (cursor.MoveToNext());
cursor.Close();
}
});
if (playlists.Count == 0)
return (null, null);
else
return (playlists, null);
}
/// <summary>
/// This method will proceed the local playlists and split synced one from the local one.
/// The outputed youtube playlists will already have the right sync state set (loading, synced...)
/// </summary>
/// <param name="localPlaylists">The array of local playlists (can be obtaines with the GetLocalPlaylists method).</param>
/// <returns>The first list contains all the local only playlists and the second one contains all the synced one. Every playlists has the right sync state set.</returns>
public static async Task<(List<PlaylistItem>, List<PlaylistItem>)> ProcessSyncedPlaylists(List<PlaylistItem> localPlaylists)
{
List<PlaylistItem> syncedPlaylists = new List<PlaylistItem>();
await Task.Run(() =>
{
SQLiteConnection db = new SQLiteConnection(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "SyncedPlaylists.sqlite"));
db.CreateTable<PlaylistItem>();
syncedPlaylists = db.Table<PlaylistItem>().ToList();
});
foreach (PlaylistItem synced in syncedPlaylists)
{
PlaylistItem local = localPlaylists?.Find(x => x.LocalID == synced.LocalID);
Console.WriteLine("&SyncedName: " + synced.Name + " YoutubeID: " + synced.YoutubeID);
if (local != null)
{
synced.Count = local.Count;
localPlaylists.Remove(local); //This playlist is a synced one, we don't want to display it in the "local" collumn but in the youtube one.
//Set sync state of the playlist (SyncState can't be false since we take the playlist in the synced database)
if (synced.YoutubeID == null)
synced.SyncState = SyncState.Loading;
else
synced.SyncState = SyncState.True;
}
else
{
//If local is null, we had an error loading local playlists or another thing (can be read permission denied for example)
synced.SyncState = SyncState.Error;
}
}
return (localPlaylists, syncedPlaylists);
}
/// <summary>
/// This method return all youtube playlists owned by the user and process synced playlist if you give an array of know youtube synced playlists
/// The YoutubePlaylists array should contains the synced playlist availables. Warning, this will return your initial array(proceded if there is synced playlist) + owned
/// The second outputed var(the string) is the error message that should be displayed to the user(the list will be null if there is an error)
/// </summary>
/// <param name="SyncedPlaylists"></param>
/// <param name="UiCallback">A callback that will tell the ui to update a synced playlist with the new data got from the item.</param>
/// <returns></returns>
public static async Task<(List<PlaylistItem>, string)> GetOwnedYoutubePlaylists(List<PlaylistItem> SyncedPlaylists, Action<PlaylistItem, int> UiCallback)
{
if (YoutubeManager.IsUsingAPI)
return (new List<PlaylistItem>(), Application.Context.GetString(Resource.String.youtube_not_logged));
if (!await MainActivity.instance.WaitForYoutube())
return (null, Application.Context.GetString(Resource.String.youtube_loading_error));
List<PlaylistItem> YoutubePlaylists = new List<PlaylistItem>();
try
{
YouTubeService youtube = YoutubeManager.YoutubeService;
PlaylistsResource.ListRequest request = youtube.Playlists.List("snippet,contentDetails");
request.Mine = true;
request.MaxResults = 25;
PlaylistListResponse response = await request.ExecuteAsync();
for (int i = 0; i < response.Items.Count; i++)
{
Playlist playlist = response.Items[i];
PlaylistItem item = new PlaylistItem(playlist.Snippet.Title, playlist.Id, playlist, (int)playlist.ContentDetails.ItemCount)
{
Owner = playlist.Snippet.ChannelTitle,
ImageURL = playlist.Snippet.Thumbnails.High.Url,
HasWritePermission = true
};
ProcessPlaylistSyncState(item, SyncedPlaylists, YoutubePlaylists, UiCallback);
}
return (YoutubePlaylists, null);
}
catch (System.Net.Http.HttpRequestException)
{
return (null, Application.Context.GetString(Resource.String.youtube_loading_error)); //Should handle precise error here
}
}
/// <summary>
/// This method return all youtube playlists saved by the user and process synced playlist if you give an array of know youtube synced playlists
/// The YoutubePlaylists array should contains the synced playlist availables.Warning, this will return your initial array(proceded if there is synced playlist) + saved playlists
/// The second outputed var(the string) is the error message that should be displayed to the user(the list will be null if there is an error)
/// </summary>
/// <param name="SyncedPlaylists"></param>
/// <param name="UiCallback">A callback that will tell the ui to update a synced playlist with the new data got from the item.</param>
/// <returns></returns>
public static async Task<List<PlaylistItem>> GetSavedYoutubePlaylists(List<PlaylistItem> SyncedPlaylists, Action<PlaylistItem, int> UiCallback)
{
List<PlaylistItem> SavedPlaylists = new List<PlaylistItem>();
await Task.Run(() =>
{
SQLiteConnection db = new SQLiteConnection(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "SavedPlaylists.sqlite"));
db.CreateTable<SavedPlaylist>();
SavedPlaylists = db.Table<SavedPlaylist>().ToList().ConvertAll(x => { PlaylistItem y = x; y.YoutubeID = x.YoutubeID; y.LocalID = -1; return y; });
});
List<PlaylistItem> YoutubePlaylists = new List<PlaylistItem>();
foreach (PlaylistItem item in SavedPlaylists)
ProcessPlaylistSyncState(item, SyncedPlaylists, YoutubePlaylists, UiCallback);
return YoutubePlaylists;
}
/// <summary>
/// Complete the synced playlist array and the youtube playlists array with a new youtube playlist. The method will add the item to the right array or if the playlist is contained in one of the array, it will complete this item.
/// </summary>
/// <param name="item">The playlist you want to process</param>
/// <param name="SyncedPlaylists">An array of known synced playlists (Will be updated)</param>
/// <param name="YoutubePlaylists">An array of youtube playlists. (Will be updated)</param>
/// <param name="UiCallback">A callback that will tell the ui to update a synced playlist with the new data got from the item.</param>
public /*async*/ static void ProcessPlaylistSyncState(PlaylistItem item, List<PlaylistItem> SyncedPlaylists, List<PlaylistItem> YoutubePlaylists, Action<PlaylistItem, int> UiCallback)
{
PlaylistItem syncedItem = SyncedPlaylists?.Find(x => x.YoutubeID == item.YoutubeID);
if (syncedItem != null)
{
syncedItem.Snippet = item.Snippet;
syncedItem.Count = item.Count;
syncedItem.SyncState = SyncState.True;
if(syncedItem.ImageURL == null)
{
syncedItem.ImageURL = item.ImageURL;
/*await*/ Task.Run(() =>
{
SQLiteConnection db = new SQLiteConnection(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "SyncedPlaylists.sqlite"));
db.CreateTable<PlaylistItem>();
db.InsertOrReplace(syncedItem);
});
}
}
else if (SyncedPlaylists?.Find(x => x.Name == item.Name) != null)
{
Console.WriteLine("&Match found");
/*We couldn't find a match of a synced playlist with the exact youtube id but we found a synced playlist with the exact same name as this one (item).
* We bind them and complete the database for future calls. */
syncedItem = SyncedPlaylists.Find(x => x.Name == item.Name);
int syncIndex = SyncedPlaylists.IndexOf(syncedItem);
item.LocalID = syncedItem.LocalID;
item.SyncState = SyncState.True;
Console.WriteLine("&YoutubeID: " + item.YoutubeID);
//If the URL is the youtube "no thumb", we don't want to save this in the database. We'll wait for the next real thumb.
if (item.Count == 0)
item.ImageURL = null;
SyncedPlaylists[syncIndex] = item;
if (UiCallback != null)
MainActivity.instance.RunOnUiThread(() => { UiCallback.Invoke(item, syncIndex); });
/*await*/ Task.Run(() =>
{
SQLiteConnection db = new SQLiteConnection(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "SyncedPlaylists.sqlite"));
db.CreateTable<PlaylistItem>();
db.InsertOrReplace(item);
});
}
else
YoutubePlaylists.Add(item);
}
#endregion
#region LocalPlaylists
/// <summary>
/// Return a list containing all the songs in the local playlist.
/// </summary>
/// <param name="LocalID"></param>
/// <returns></returns>
public async static Task<List<Song>> GetTracksFromLocalPlaylist(long LocalID)
{
List<Song> songs = new List<Song>();
Uri musicUri = Playlists.Members.GetContentUri("external", LocalID);
await Task.Run(() =>
{
if (Looper.MyLooper() == null)
Looper.Prepare();
CursorLoader cursorLoader = new CursorLoader(Application.Context, musicUri, null, null, null, Playlists.Members.PlayOrder);
ICursor musicCursor = (ICursor)cursorLoader.LoadInBackground();
if (musicCursor != null && musicCursor.MoveToFirst())
{
int titleID = musicCursor.GetColumnIndex(Media.InterfaceConsts.Title);
int artistID = musicCursor.GetColumnIndex(Media.InterfaceConsts.Artist);
int albumID = musicCursor.GetColumnIndex(Media.InterfaceConsts.Album);
int thisID = musicCursor.GetColumnIndex(Media.InterfaceConsts.Id);
int pathID = musicCursor.GetColumnIndex(Media.InterfaceConsts.Data);
int playOrderID = musicCursor.GetColumnIndex(Playlists.Members.PlayOrder);
do
{
string Artist = musicCursor.GetString(artistID);
string Title = musicCursor.GetString(titleID);
string Album = musicCursor.GetString(albumID);
long AlbumArt = musicCursor.GetLong(musicCursor.GetColumnIndex(Albums.InterfaceConsts.AlbumId));
long id = musicCursor.GetLong(thisID);
string path = musicCursor.GetString(pathID);
string playOrder = musicCursor.GetString(playOrderID);
if (Title == null)
Title = "Unknown Title";
if (Artist == null)
Artist = "Unknow Artist";
if (Album == null)
Album = "Unknow Album";
songs.Add(new Song(Title, Artist, Album, null, AlbumArt, id, path) { TrackID = playOrder });
}
while (musicCursor.MoveToNext());
musicCursor.Close();
}
});
return songs;
}
/// <summary>
/// Will create a local playlist and add this playlist to the synced array if needed.
/// </summary>
/// <param name="name">The name of the playlist</param>
/// <param name="syncedPlaylist">True if you want the playlist to be created and synced on youtube too</param>
/// <returns>The id of the playlist will be returned</returns>
public async static Task<long> CreateLocalPlaylist(string name, bool syncedPlaylist)
{
if (!await MainActivity.instance.GetWritePermission())
return -1;
//Create the playlist in the local storage db.
ContentValues value = new ContentValues();
value.Put(Playlists.InterfaceConsts.Name, name);
MainActivity.instance.ContentResolver.Insert(Playlists.ExternalContentUri, value);
long playlistID = await GetPlaylistID(name);
if (syncedPlaylist)
{
await Task.Run(() =>
{
SQLiteConnection db = new SQLiteConnection(Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "SyncedPlaylists.sqlite"));
db.CreateTable<PlaylistItem>();
db.InsertOrReplace(new PlaylistItem(name, playlistID, null));
});
}
return playlistID;
}
/// <summary>
/// Will create a local playlist and add an array of songs in this playlist
/// </summary>
/// <param name="name">The name of the playlist</param>
/// <param name="items">The array of songs you want to add. Can be local one or youtube one, it will download them and add them after.</param>
/// <param name="syncedPlaylist">True if you want the playlist to be created and synced on youtube too</param>
public async static void CreateLocalPlaylist(string name, Song[] items, bool syncedPlaylist = false)
{
long playlistID = await CreateLocalPlaylist(name, syncedPlaylist);
if (playlistID == -1)
return;
if (items != null && items.Length > 0)
{
AddToLocalPlaylist(playlistID, items); //Will only add files already downloaded
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
YoutubeManager.DownloadFiles(items.Where(x => x.LocalID == -1 || x.LocalID == 0).ToList().ConvertAll(x => DownloadFile.From(x, name))); //Will download missing files and add them (if there was youtube songs in the items array).
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
}
}
/// <summary>
/// Return the id of a local playlist by using it's name. Return -1 if the name is not found.
/// </summary>
/// <param name="playlistName"></param>
/// <returns></returns>
public async static Task<long> GetPlaylistID(string playlistName)
{
Uri uri = Playlists.ExternalContentUri;
return await Task.Run(() =>
{
if (Looper.MyLooper() == null)
Looper.Prepare();
CursorLoader loader = new CursorLoader(Application.Context, uri, null, null, null, null);
ICursor cursor = (ICursor)loader.LoadInBackground();
if (cursor != null && cursor.MoveToFirst())
{
int nameID = cursor.GetColumnIndex(MediaStore.Audio.Playlists.InterfaceConsts.Name);
int plID = cursor.GetColumnIndex(MediaStore.Audio.Playlists.InterfaceConsts.Id);
do
{
string name = cursor.GetString(nameID);
if (name != playlistName)
continue;
return cursor.GetLong(plID);
}
while (cursor.MoveToNext());
cursor.Close();
}
return -1;
});
}
/// <summary>
/// Remove a track from a local playlist
/// </summary>
/// <param name="song"></param>
/// <param name="LocalPlaylistID"></param>
public /*async*/ static void RemoveFromLocalPlaylist(Song song, long LocalPlaylistID)
{
Console.WriteLine("&Remove Track From Local Playlist Called");
Console.WriteLine("&Song localID: " + song.LocalID + " LocalPlaylistID: " + LocalPlaylistID);
//await Task.Run(() =>
//{
// if (Looper.MyLooper() == null)
// Looper.Prepare();