-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpotify.cs
663 lines (550 loc) · 21.4 KB
/
Spotify.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
/*-
* Copyright (c) 2014 Software Development Solutions, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using SpotifyWolf.API;
using libspotifydotnet;
namespace SpotifyWolf
{
public static class Spotify
{
private delegate bool Test();
public delegate void MainThreadMessageDelegate(object[] args);
private static AutoResetEvent _programSignal;
private static AutoResetEvent _mainSignal;
private static Queue<MainThreadMessage> _mq = new Queue<MainThreadMessage>();
private static bool _shutDown = false;
private static object _syncObj = new object();
private static object _initSync = new object();
private static bool _initted = false;
private static bool _isRunning = false;
private static bool _isLoggedIn = false;
private static Action<IntPtr> d_notify = new Action<IntPtr>(Session_OnNotifyMainThread);
private static Action<IntPtr> d_on_logged_in = new Action<IntPtr>(Session_OnLoggedIn);
private static Thread _t;
private static object _loginLock = new object();
private static readonly int REQUEST_TIMEOUT = 20;
private class MainThreadMessage
{
public MainThreadMessageDelegate d;
public object[] payload;
}
static Spotify()
{
Session.OnNotifyMainThread += d_notify;
Session.OnLoggedIn += d_on_logged_in;
}
public static bool IsRunning
{
get { return _isRunning; }
}
public static bool IsLoggedIn
{
get { return _isLoggedIn; }
}
public static bool Login()
{
if (!Configuration.Instance.HasLoginCredentials)
return false;
return Login(Configuration.Instance.ApplicationKey, Configuration.Instance.Username, Configuration.Instance.Password);
}
public static bool Login(byte[] appkey, string username, string password)
{
lock (_initSync)
{
if (!_initted)
throw new ApplicationException("Spotify message thread not initialized");
}
lock (_loginLock)
{
if (_isLoggedIn)
return true;
postMessage(Session.Login, new object[] { appkey, username, password });
_programSignal.WaitOne();
if (Session.LoginError != libspotify.sp_error.OK)
{
Logging.WriteLine(String.Format("Login failed: {0}", libspotify.sp_error_message(Session.LoginError)));
return false;
}
return true;
}
}
public static void Initialize()
{
if (_initted)
return;
lock (_initSync)
{
try
{
_programSignal = new AutoResetEvent(false);
_shutDown = false;
_t = new Thread(new ThreadStart(mainThread));
_t.Start();
_programSignal.WaitOne();
Logging.WriteLine("Message thread running...");
_initted = true;
}
catch
{
Session.OnNotifyMainThread -= d_notify;
Session.OnLoggedIn -= d_on_logged_in;
if (_t != null)
{
try
{
_t.Abort();
}
catch { }
finally
{
_t = null;
}
}
}
}
}
public static int GetUserCountry()
{
return Session.GetUserCountry();
}
public static List<PlaylistContainer.PlaylistInfo> GetAllSessionPlaylists()
{
waitFor(delegate
{
return PlaylistContainer.GetSessionContainer().IsLoaded
&& PlaylistContainer.GetSessionContainer().PlaylistsAreLoaded;
}, REQUEST_TIMEOUT);
return PlaylistContainer.GetSessionContainer().GetAllPlaylists();
}
public static List<PlaylistContainer.PlaylistInfo> GetPlaylists()
{
return GetPlaylists(0);
}
public static List<PlaylistContainer.PlaylistInfo> GetPlaylists(ulong folderID)
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
waitFor(delegate
{
return PlaylistContainer.GetSessionContainer().IsLoaded
&& PlaylistContainer.GetSessionContainer().PlaylistsAreLoaded;
}, REQUEST_TIMEOUT);
return PlaylistContainer.GetSessionContainer().GetChildren(folderID);
}
public static PlaylistContainer.PlaylistInfo GetPlaylistContainer(ulong folderID)
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
waitFor(delegate
{
return PlaylistContainer.GetSessionContainer().IsLoaded
&& PlaylistContainer.GetSessionContainer().PlaylistsAreLoaded;
}, REQUEST_TIMEOUT);
return PlaylistContainer.GetSessionContainer().FindContainer(folderID);
}
public static string GetAlbumLink(IntPtr albumPtr)
{
IntPtr linkPtr = libspotify.sp_link_create_from_album(albumPtr);
return Functions.LinkPtrToString(linkPtr);
}
public static Album AlbumFromLink(string albumLink)
{
IntPtr linkPtr = Functions.StringToLinkPtr(albumLink);
return new Album(libspotify.sp_link_as_album(linkPtr));
}
public static Playlist GetPlaylist(string playlistLink, bool needTracks)
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
Playlist playlist = Playlist.FromLink(playlistLink);
if (playlist == null)
return null;
bool success = waitFor(delegate
{
return playlist.IsLoaded && needTracks ? playlist.TracksAreLoaded : true;
}, REQUEST_TIMEOUT);
return playlist;
}
public static Playlist GetInboxPlaylist()
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
IntPtr inboxPtr = IntPtr.Zero;
try
{
inboxPtr = libspotify.sp_session_inbox_create(Session.SessionPtr);
Playlist p = new Playlist(inboxPtr);
bool success = waitFor(delegate
{
return p.IsLoaded;
}, REQUEST_TIMEOUT);
return p;
}
finally
{
try
{
if (inboxPtr != IntPtr.Zero)
libspotify.sp_playlist_release(inboxPtr);
}
catch { }
}
}
public static Playlist GetStarredPlaylist()
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
IntPtr starredPtr = IntPtr.Zero;
try
{
starredPtr = libspotify.sp_session_starred_create(Session.SessionPtr);
Playlist p = new Playlist(starredPtr);
bool success = waitFor(delegate
{
return p.IsLoaded;
}, REQUEST_TIMEOUT);
return p;
}
finally
{
try
{
if (starredPtr != IntPtr.Zero)
libspotify.sp_playlist_release(starredPtr);
}
catch { }
}
}
public static Search GetSearch(string keywords)
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
var search = Search.BeginSearch(keywords);
if (!waitFor(delegate
{
return search.IsLoaded;
}, REQUEST_TIMEOUT))
{
Logging.WriteLine("Search timeout");
return null;
}
var err = search.GetSearchError();
if (err != libspotify.sp_error.OK)
{
Logging.WriteLine(String.Format("Search failed: {0}", err));
return null;
}
return search;
}
public static TopList GetToplist(string data)
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
string[] parts = data.Split("|".ToCharArray());
int region = parts[0].Equals("ForMe") ? (int)libspotify.sp_toplistregion.SP_TOPLIST_REGION_USER : parts[0].Equals("Everywhere") ? (int)libspotify.sp_toplistregion.SP_TOPLIST_REGION_EVERYWHERE : Convert.ToInt32(parts[0]);
libspotify.sp_toplisttype type = parts[1].Equals("Artists") ? libspotify.sp_toplisttype.SP_TOPLIST_TYPE_ARTISTS : parts[1].Equals("Albums") ? libspotify.sp_toplisttype.SP_TOPLIST_TYPE_ALBUMS : libspotify.sp_toplisttype.SP_TOPLIST_TYPE_TRACKS;
TopList toplist = TopList.BeginBrowse(type, region);
bool success = waitFor(delegate
{
return toplist.IsLoaded;
}, REQUEST_TIMEOUT);
var err = toplist.GetBrowseError();
if (err != libspotify.sp_error.OK)
{
Logging.WriteLine(String.Format("Toplist browse failed: {0}", err));
return null;
}
return toplist;
}
public static string GetTrackLink(IntPtr trackPtr)
{
return GetTrackLink(trackPtr, 0);
}
public static string GetTrackLink(IntPtr trackPtr, int offset)
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
IntPtr linkPtr = libspotify.sp_link_create_from_track(trackPtr, offset);
try
{
return Functions.LinkPtrToString(linkPtr);
}
finally
{
if (linkPtr != IntPtr.Zero)
libspotify.sp_link_release(linkPtr);
}
}
public static byte[] GetAlbumArt(string link)
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
IntPtr linkPtr = Functions.StringToLinkPtr(link);
if (linkPtr == IntPtr.Zero)
return null;
try
{
IntPtr coverPtr = libspotify.sp_image_create_from_link(Session.SessionPtr, linkPtr);
using (Image img = Image.Load(coverPtr))
{
waitFor(delegate()
{
return img.IsLoaded;
}, REQUEST_TIMEOUT);
var err = img.GetLoadError();
if (err != libspotify.sp_error.OK)
{
throw new ApplicationException(String.Format("Image failed to load: {0}", err));
}
int bytes = 0;
IntPtr bufferPtr = libspotify.sp_image_data(img.ImagePtr, out bytes);
byte[] buffer = new byte[bytes];
Marshal.Copy(bufferPtr, buffer, 0, buffer.Length);
return buffer;
}
}
finally
{
if (linkPtr != IntPtr.Zero)
libspotify.sp_link_release(linkPtr);
}
}
public static IntPtr[] GetAlbumTracks(string albumLink)
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
using (Album album = Spotify.AlbumFromLink(albumLink))
{
if (!waitFor(delegate
{
return libspotify.sp_album_is_loaded(album.AlbumPtr);
}, REQUEST_TIMEOUT))
Logging.WriteLine("GetAlbumTracks() TIMEOUT waiting for album to load");
if (album.BeginBrowse())
{
if (!waitFor(delegate()
{
return album.IsBrowseComplete;
}, REQUEST_TIMEOUT))
Logging.WriteLine("GetAlbumTracks() TIMEOUT waiting for browse to complete");
}
if (album.TrackPtrs == null)
return null;
return album.TrackPtrs.ToArray();
}
}
public static string GetPlaylistLink(IntPtr playlistPtr)
{
IntPtr linkPtr = libspotify.sp_link_create_from_playlist(playlistPtr);
return Functions.LinkPtrToString(linkPtr);
}
public static string GetArtistLink(IntPtr artistPtr)
{
IntPtr linkPtr = libspotify.sp_link_create_from_artist(artistPtr);
return Functions.LinkPtrToString(linkPtr);
}
public static Artist ArtistFromLink(string artistLink)
{
IntPtr linkPtr = Functions.StringToLinkPtr(artistLink);
return new Artist(libspotify.sp_link_as_artist(linkPtr));
}
public static IntPtr[] GetArtistAlbums(string artistLink)
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
using (Artist artist = ArtistFromLink(artistLink))
{
if (!waitFor(delegate
{
return libspotify.sp_artist_is_loaded(artist.ArtistPtr);
}, REQUEST_TIMEOUT))
Logging.WriteLine("GetArtistAlbums() TIMEOUT waiting for artist to load");
if (artist.BeginBrowse())
{
if (!waitFor(delegate()
{
return artist.IsBrowseComplete;
}, REQUEST_TIMEOUT))
Logging.WriteLine("GetArtistAlbums() TIMEOUT waiting for browse to complete");
}
if (artist.AlbumPtrs == null)
return null;
return artist.AlbumPtrs.ToArray();
}
}
public static PlaylistContainer GetUserPlaylists(IntPtr userPtr)
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
IntPtr ptr = IntPtr.Zero;
try
{
ptr = libspotify.sp_session_publishedcontainer_for_user_create(Session.SessionPtr, GetUserCanonicalNamePtr(userPtr));
PlaylistContainer c = PlaylistContainer.Get(ptr);
waitFor(delegate
{
return c.IsLoaded
&& c.PlaylistsAreLoaded;
}, REQUEST_TIMEOUT);
return c;
}
finally
{
//try {
// if (ptr != IntPtr.Zero)
// libspotify.sp_playlistcontainer_release(ptr);
//} catch { }
}
}
public static IntPtr GetUserCanonicalNamePtr(IntPtr userPtr)
{
if (Session.SessionPtr == IntPtr.Zero)
throw new ApplicationException("No session");
waitFor(delegate()
{
return libspotify.sp_user_is_loaded(userPtr);
}, REQUEST_TIMEOUT);
return libspotify.sp_user_canonical_name(userPtr);
}
private static bool waitFor(Test t, int timeout)
{
DateTime start = DateTime.Now;
while (DateTime.Now.Subtract(start).Seconds < timeout)
{
if (t.Invoke())
{
return true;
}
Thread.Sleep(10);
}
return false;
}
public static void ShutDown()
{
lock (_syncObj)
{
if (_mainSignal != null)
_mainSignal.Set();
_mainSignal = null;
_t = null;
_shutDown = true;
if (Session.SessionPtr != IntPtr.Zero)
{
try
{
//libspotify.sp_error err = libspotify.sp_session_player_unload(Session.SessionPtr);
//err = libspotify.sp_session_logout(Session.SessionPtr);
//err = libspotify.sp_session_release(Session.SessionPtr);
}
catch (Exception ex)
{
Logging.WriteLine("Error cleaning up session " + ex);
}
}
_isLoggedIn = false;
_initted = false;
}
_programSignal.WaitOne(2000, false);
_programSignal = null;
}
private static void mainThread()
{
try
{
_mainSignal = new AutoResetEvent(false);
int timeout = Timeout.Infinite;
DateTime lastEvents = DateTime.MinValue;
_isRunning = true;
_programSignal.Set(); // this signals to program thread that loop is running
while (true)
{
if (_shutDown)
break;
_mainSignal.WaitOne(timeout, false);
if (_shutDown)
break;
lock (_syncObj)
{
try
{
if (Session.SessionPtr != IntPtr.Zero)
{
do
{
libspotify.sp_session_process_events(Session.SessionPtr, out timeout);
} while (!_shutDown && timeout == 0);
}
}
catch (Exception ex)
{
Logging.WriteLine("Exception invoking sp_session_process_events " + ex);
}
while (_mq.Count > 0)
{
MainThreadMessage m = _mq.Dequeue();
m.d.Invoke(m.payload);
}
}
}
}
catch (Exception ex)
{
Logging.WriteLine("mainThread() unhandled exception " + ex);
}
finally
{
_isRunning = false;
if (_programSignal != null)
_programSignal.Set();
}
}
public static void Session_OnLoggedIn(IntPtr obj)
{
if (Session.LoginError == libspotify.sp_error.OK)
_isLoggedIn = true;
if (_programSignal != null)
_programSignal.Set();
}
public static void Session_OnNotifyMainThread(IntPtr sessionPtr)
{
if (_mainSignal != null)
_mainSignal.Set();
}
private static void postMessage(MainThreadMessageDelegate d, object[] payload)
{
if (_mq == null)
throw new ApplicationException("Message queue has not been initialized");
_mq.Enqueue(new MainThreadMessage() { d = d, payload = payload });
lock (_syncObj)
{
_mainSignal.Set();
}
}
}
}