forked from JohnnyCrazy/SpotifyAPI-NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpotifyWebAPI.cs
More file actions
874 lines (803 loc) · 42.8 KB
/
SpotifyWebAPI.cs
File metadata and controls
874 lines (803 loc) · 42.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SpotifyAPI.Web.Enums;
using SpotifyAPI.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SpotifyAPI.Web
{
public sealed class SpotifyWebAPI : IDisposable
{
public const String APIBase = "https://api.spotify.com/v1";
public SpotifyWebAPI()
{
UseAuth = true;
WebClient = new SpotifyWebClient
{
JsonSettings =
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
TypeNameHandling = TypeNameHandling.All
}
};
}
public String TokenType { get; set; }
public String AccessToken { get; set; }
public Boolean UseAuth { get; set; }
public IClient WebClient { get; set; }
public void Dispose()
{
WebClient.Dispose();
GC.SuppressFinalize(this);
}
#region Search
/// <summary>
/// Get Spotify catalog information about artists, albums, tracks or playlists that match a keyword string.
/// </summary>
/// <param name="q">The search query's keywords (and optional field filters and operators), for example q=roadhouse+blues.</param>
/// <param name="type">A list of item types to search across.</param>
/// <param name="limit">The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.</param>
/// <param name="offset">The index of the first result to return. Default: 0</param>
/// <param name="market">An ISO 3166-1 alpha-2 country code or the string from_token.</param>
/// <returns></returns>
public SearchItem SearchItems(String q, SearchType type, int limit = 20, int offset = 0, String market = "")
{
limit = Math.Min(50, limit);
StringBuilder builder = new StringBuilder(APIBase + "/search");
builder.Append("?q=" + q);
builder.Append("&type=" + type.GetStringAttribute(","));
builder.Append("&limit=" + limit);
builder.Append("&offset=" + offset);
if (!String.IsNullOrEmpty(market))
builder.Append("&market=" + market);
return DownloadData<SearchItem>(builder.ToString());
}
#endregion Search
#region Albums
/// <summary>
/// Get Spotify catalog information about an album’s tracks. Optional parameters can be used to limit the number of
/// tracks returned.
/// </summary>
/// <param name="id">The Spotify ID for the album.</param>
/// <param name="limit">The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.</param>
/// <param name="offset">The index of the first track to return. Default: 0 (the first object).</param>
/// <param name="market">An ISO 3166-1 alpha-2 country code. Provide this parameter if you want to apply Track Relinking.</param>
/// <returns></returns>
public Paging<SimpleTrack> GetAlbumTracks(String id, int limit = 20, int offset = 0, String market = "")
{
limit = Math.Min(limit, 50);
StringBuilder builder = new StringBuilder(APIBase + "/albums/" + id + "/tracks");
builder.Append("?limit=" + limit);
builder.Append("&offset=" + offset);
if (!String.IsNullOrEmpty(market))
builder.Append("&market=" + market);
return DownloadData<Paging<SimpleTrack>>(builder.ToString());
}
/// <summary>
/// Get Spotify catalog information for a single album.
/// </summary>
/// <param name="id">The Spotify ID for the album.</param>
/// <param name="market">An ISO 3166-1 alpha-2 country code. Provide this parameter if you want to apply Track Relinking.</param>
/// <returns></returns>
public FullAlbum GetAlbum(String id, String market = "")
{
if (String.IsNullOrEmpty(market))
return DownloadData<FullAlbum>(APIBase + "/albums/" + id);
return DownloadData<FullAlbum>(APIBase + "/albums/" + id + "?market=" + market);
}
/// <summary>
/// Get Spotify catalog information for multiple albums identified by their Spotify IDs.
/// </summary>
/// <param name="ids">A list of the Spotify IDs for the albums. Maximum: 20 IDs.</param>
/// <param name="market">An ISO 3166-1 alpha-2 country code. Provide this parameter if you want to apply Track Relinking.</param>
/// <returns></returns>
public SeveralAlbums GetSeveralAlbums(List<String> ids, String market = "")
{
if (String.IsNullOrEmpty(market))
return DownloadData<SeveralAlbums>(APIBase + "/albums?ids=" + string.Join(",", ids.Take(20)));
return DownloadData<SeveralAlbums>(APIBase + "/albums?market=" + market + "&ids=" + string.Join(",", ids.Take(20)));
}
#endregion Albums
#region Artists
/// <summary>
/// Get Spotify catalog information for a single artist identified by their unique Spotify ID.
/// </summary>
/// <param name="id">The Spotify ID for the artist.</param>
/// <returns></returns>
public FullArtist GetArtist(String id)
{
return DownloadData<FullArtist>(APIBase + "/artists/" + id);
}
/// <summary>
/// Get Spotify catalog information about artists similar to a given artist. Similarity is based on analysis of the
/// Spotify community’s listening history.
/// </summary>
/// <param name="id">The Spotify ID for the artist.</param>
/// <returns></returns>
public SeveralArtists GetRelatedArtists(String id)
{
return DownloadData<SeveralArtists>(APIBase + "/artists/" + id + "/related-artists");
}
/// <summary>
/// Get Spotify catalog information about an artist’s top tracks by country.
/// </summary>
/// <param name="id">The Spotify ID for the artist.</param>
/// <param name="country">The country: an ISO 3166-1 alpha-2 country code.</param>
/// <returns></returns>
public SeveralTracks GetArtistsTopTracks(String id, String country)
{
return DownloadData<SeveralTracks>(APIBase + "/artists/" + id + "/top-tracks?country=" + country);
}
/// <summary>
/// Get Spotify catalog information about an artist’s albums. Optional parameters can be specified in the query string
/// to filter and sort the response.
/// </summary>
/// <param name="id">The Spotify ID for the artist.</param>
/// <param name="type">
/// A list of keywords that will be used to filter the response. If not supplied, all album types will
/// be returned
/// </param>
/// <param name="limit">The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.</param>
/// <param name="offset">The index of the first album to return. Default: 0</param>
/// <param name="market">
/// An ISO 3166-1 alpha-2 country code. Supply this parameter to limit the response to one particular
/// geographical market
/// </param>
/// <returns></returns>
public Paging<SimpleAlbum> GetArtistsAlbums(String id, AlbumType type = AlbumType.All, int limit = 20, int offset = 0, String market = "")
{
limit = Math.Min(limit, 50);
StringBuilder builder = new StringBuilder(APIBase + "/artists/" + id + "/albums");
builder.Append("?type=" + type.GetStringAttribute(","));
builder.Append("&limit=" + limit);
builder.Append("&offset=" + offset);
if (!String.IsNullOrEmpty(market))
builder.Append("&market=" + market);
return DownloadData<Paging<SimpleAlbum>>(builder.ToString());
}
/// <summary>
/// Get Spotify catalog information for several artists based on their Spotify IDs.
/// </summary>
/// <param name="ids">A list of the Spotify IDs for the artists. Maximum: 50 IDs.</param>
/// <returns></returns>
public SeveralArtists GetSeveralArtists(List<String> ids)
{
return DownloadData<SeveralArtists>(APIBase + "/artists?ids=" + string.Join(",", ids.Take(50)));
}
#endregion Artists
#region Browse
/// <summary>
/// Get a list of Spotify featured playlists (shown, for example, on a Spotify player’s “Browse” tab).
/// </summary>
/// <param name="locale">
/// The desired language, consisting of a lowercase ISO 639 language code and an uppercase ISO 3166-1
/// alpha-2 country code, joined by an underscore.
/// </param>
/// <param name="country">A country: an ISO 3166-1 alpha-2 country code.</param>
/// <param name="timestamp">A timestamp in ISO 8601 format</param>
/// <param name="limit">The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.</param>
/// <param name="offset">The index of the first item to return. Default: 0</param>
/// <remarks>AUTH NEEDED</remarks>
public FeaturedPlaylists GetFeaturedPlaylists(String locale = "", String country = "", DateTime timestamp = default(DateTime), int limit = 20, int offset = 0)
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for GetFeaturedPlaylists");
limit = Math.Max(limit, 50);
StringBuilder builder = new StringBuilder(APIBase + "/browse/featured-playlists");
builder.Append("?limit=" + limit);
builder.Append("&offset=" + offset);
if (!String.IsNullOrEmpty(locale))
builder.Append("&locale=" + locale);
if (!String.IsNullOrEmpty(country))
builder.Append("&country=" + country);
if (timestamp != default(DateTime))
builder.Append("×tamp=" + timestamp.ToString("yyyy-MM-ddTHH:mm:ss"));
return DownloadData<FeaturedPlaylists>(builder.ToString());
}
/// <summary>
/// Get a list of new album releases featured in Spotify (shown, for example, on a Spotify player’s “Browse” tab).
/// </summary>
/// <param name="country">A country: an ISO 3166-1 alpha-2 country code.</param>
/// <param name="limit">The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.</param>
/// <param name="offset">The index of the first item to return. Default: 0</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public NewAlbumReleases GetNewAlbumReleases(String country = "", int limit = 20, int offset = 0)
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for GetNewAlbumReleases");
limit = Math.Max(limit, 50);
StringBuilder builder = new StringBuilder(APIBase + "/browse/new-releases");
builder.Append("?limit=" + limit);
builder.Append("&offset=" + offset);
if (!String.IsNullOrEmpty(country))
builder.Append("&country=" + country);
return DownloadData<NewAlbumReleases>(builder.ToString());
}
/// <summary>
/// Get a list of categories used to tag items in Spotify (on, for example, the Spotify player’s “Browse” tab).
/// </summary>
/// <param name="country">
/// A country: an ISO 3166-1 alpha-2 country code. Provide this parameter if you want to narrow the
/// list of returned categories to those relevant to a particular country
/// </param>
/// <param name="locale">
/// The desired language, consisting of an ISO 639 language code and an ISO 3166-1 alpha-2 country
/// code, joined by an underscore
/// </param>
/// <param name="limit">The maximum number of categories to return. Default: 20. Minimum: 1. Maximum: 50. </param>
/// <param name="offset">The index of the first item to return. Default: 0 (the first object).</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public CategoryList GetCategories(String country = "", String locale = "", int limit = 20, int offset = 0)
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for GetCategories");
limit = Math.Min(50, limit);
StringBuilder builder = new StringBuilder(APIBase + "/browse/categories");
builder.Append("?limit=" + limit);
builder.Append("&offset=" + offset);
if (!String.IsNullOrEmpty(country))
builder.Append("&country=" + country);
if (!String.IsNullOrEmpty(locale))
builder.Append("&locale=" + locale);
return DownloadData<CategoryList>(builder.ToString());
}
/// <summary>
/// Get a single category used to tag items in Spotify (on, for example, the Spotify player’s “Browse” tab).
/// </summary>
/// <param name="categoryId">The Spotify category ID for the category.</param>
/// <param name="country">
/// A country: an ISO 3166-1 alpha-2 country code. Provide this parameter to ensure that the category
/// exists for a particular country.
/// </param>
/// <param name="locale">
/// The desired language, consisting of an ISO 639 language code and an ISO 3166-1 alpha-2 country
/// code, joined by an underscore
/// </param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public Category GetCategory(String categoryId, String country = "", String locale = "")
{
StringBuilder builder = new StringBuilder(APIBase + "/browse/categories/" + categoryId);
if (!String.IsNullOrEmpty(country))
builder.Append("?country=" + country);
if (!String.IsNullOrEmpty(locale))
builder.Append((country == "" ? "?locale=" : "&locale=") + locale);
return DownloadData<Category>(builder.ToString());
}
/// <summary>
/// Get a list of Spotify playlists tagged with a particular category.
/// </summary>
/// <param name="categoryId">The Spotify category ID for the category.</param>
/// <param name="country">A country: an ISO 3166-1 alpha-2 country code.</param>
/// <param name="limit">The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.</param>
/// <param name="offset">The index of the first item to return. Default: 0</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public CategoryPlaylist GetCategoryPlaylists(String categoryId, String country = "", int limit = 20, int offset = 0)
{
limit = Math.Min(50, limit);
StringBuilder builder = new StringBuilder(APIBase + "/browse/categories/" + categoryId + "/playlists");
builder.Append("?limit=" + limit);
builder.Append("&offset=" + offset);
if (!String.IsNullOrEmpty(country))
builder.Append("&country=" + country);
return DownloadData<CategoryPlaylist>(builder.ToString());
}
#endregion Browse
#region Follow
/// <summary>
/// Get the current user’s followed artists.
/// </summary>
/// <param name="limit">The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50. </param>
/// <param name="after">The last artist ID retrieved from the previous request.</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public FollowedArtists GetFollowedArtists(int limit = 20, String after = "")
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for GetFollowedArtists");
limit = Math.Max(limit, 50);
const FollowType followType = FollowType.Artist; //currently only artist is supported.
StringBuilder builder = new StringBuilder(APIBase + "/me/following?type=" + followType.GetStringAttribute(""));
builder.Append("&limit=" + limit);
if (!String.IsNullOrEmpty(after))
builder.Append("&after=" + after);
return DownloadData<FollowedArtists>(builder.ToString());
}
/// <summary>
/// Add the current user as a follower of one or more artists or other Spotify users.
/// </summary>
/// <param name="followType">The ID type: either artist or user.</param>
/// <param name="ids">A list of the artist or the user Spotify IDs</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse Follow(FollowType followType, List<String> ids)
{
JObject ob = new JObject
{
{"ids", new JArray(ids)}
};
return UploadData<ErrorResponse>(APIBase + "/me/following?type=" + followType.GetStringAttribute(""), ob.ToString(Formatting.None), "PUT") ?? new ErrorResponse();
}
/// <summary>
/// Add the current user as a follower of one or more artists or other Spotify users.
/// </summary>
/// <param name="followType">The ID type: either artist or user.</param>
/// <param name="id">Artists or the Users Spotify ID</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse Follow(FollowType followType, String id)
{
return Follow(followType, new List<string> { id });
}
/// <summary>
/// Remove the current user as a follower of one or more artists or other Spotify users.
/// </summary>
/// <param name="followType">The ID type: either artist or user.</param>
/// <param name="ids">A list of the artist or the user Spotify IDs</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse Unfollow(FollowType followType, List<String> ids)
{
JObject ob = new JObject
{
{"ids", new JArray(ids)}
};
return UploadData<ErrorResponse>(APIBase + "/me/following?type=" + followType.GetStringAttribute(""), ob.ToString(Formatting.None), "DELETE") ?? new ErrorResponse();
}
/// <summary>
/// Remove the current user as a follower of one or more artists or other Spotify users.
/// </summary>
/// <param name="followType">The ID type: either artist or user.</param>
/// <param name="id">Artists or the Users Spotify ID</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse Unfollow(FollowType followType, String id)
{
return Unfollow(followType, new List<string> { id });
}
/// <summary>
/// Check to see if the current user is following one or more artists or other Spotify users.
/// </summary>
/// <param name="followType">The ID type: either artist or user.</param>
/// <param name="ids">A list of the artist or the user Spotify IDs to check</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ListResponse<Boolean> IsFollowing(FollowType followType, List<String> ids)
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for IsFollowing");
JToken res = DownloadData<JToken>(APIBase + "/me/following/contains?type=" + followType.GetStringAttribute("") + "&ids=" + string.Join(",", ids));
if (res is JArray)
return new ListResponse<Boolean> { List = res.ToObject<List<Boolean>>(), Error = null };
return new ListResponse<Boolean> { List = null, Error = res["error"].ToObject<Error>() };
}
/// <summary>
/// Check to see if the current user is following one artist or another Spotify user.
/// </summary>
/// <param name="followType">The ID type: either artist or user.</param>
/// <param name="id">Artists or the Users Spotify ID</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ListResponse<Boolean> IsFollowing(FollowType followType, String id)
{
return IsFollowing(followType, new List<string> { id });
}
/// <summary>
/// Add the current user as a follower of a playlist.
/// </summary>
/// <param name="ownerId">The Spotify user ID of the person who owns the playlist.</param>
/// <param name="playlistId">
/// The Spotify ID of the playlist. Any playlist can be followed, regardless of its public/private
/// status, as long as you know its playlist ID.
/// </param>
/// <param name="showPublic">
/// If true the playlist will be included in user's public playlists, if false it will remain
/// private.
/// </param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse FollowPlaylist(String ownerId, String playlistId, bool showPublic = true)
{
JObject body = new JObject
{
{"public", showPublic}
};
return UploadData<ErrorResponse>(APIBase + "/users/" + ownerId + "/playlists/" + playlistId + "/followers", body.ToString(Formatting.None), "PUT");
}
/// <summary>
/// Remove the current user as a follower of a playlist.
/// </summary>
/// <param name="ownerId">The Spotify user ID of the person who owns the playlist.</param>
/// <param name="playlistId">The Spotify ID of the playlist that is to be no longer followed.</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse UnfollowPlaylist(String ownerId, String playlistId)
{
return UploadData<ErrorResponse>(APIBase + "/users/" + ownerId + "/playlists/" + playlistId + "/followers", "", "DELETE");
}
/// <summary>
/// Check to see if one or more Spotify users are following a specified playlist.
/// </summary>
/// <param name="ownerId">The Spotify user ID of the person who owns the playlist.</param>
/// <param name="playlistId">The Spotify ID of the playlist.</param>
/// <param name="ids">A list of Spotify User IDs</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ListResponse<Boolean> IsFollowingPlaylist(String ownerId, String playlistId, List<String> ids)
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for IsFollowingPlaylist");
JToken res = DownloadData<JToken>(APIBase + "/users/" + ownerId + "/playlists/" + playlistId + "/followers/contains?ids=" + string.Join(",", ids));
if (res is JArray)
return new ListResponse<Boolean> { List = res.ToObject<List<Boolean>>(), Error = null };
return new ListResponse<Boolean> { List = null, Error = res["error"].ToObject<Error>() };
}
/// <summary>
/// Check to see if one or more Spotify users are following a specified playlist.
/// </summary>
/// <param name="ownerId">The Spotify user ID of the person who owns the playlist.</param>
/// <param name="playlistId">The Spotify ID of the playlist.</param>
/// <param name="id">A Spotify User ID</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ListResponse<Boolean> IsFollowingPlaylist(String ownerId, String playlistId, String id)
{
return IsFollowingPlaylist(ownerId, playlistId, new List<string> { id });
}
#endregion Follow
#region Library
/// <summary>
/// Save one or more tracks to the current user’s “Your Music” library.
/// </summary>
/// <param name="ids">A list of the Spotify IDs</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse SaveTracks(List<String> ids)
{
JArray array = new JArray(ids);
return UploadData<ErrorResponse>(APIBase + "/me/tracks/", array.ToString(Formatting.None), "PUT") ?? new ErrorResponse();
}
/// <summary>
/// Save one track to the current user’s “Your Music” library.
/// </summary>
/// <param name="id">A Spotify ID</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse SaveTrack(String id)
{
return SaveTracks(new List<string> { id });
}
/// <summary>
/// Get a list of the songs saved in the current Spotify user’s “Your Music” library.
/// </summary>
/// <param name="limit">The maximum number of objects to return. Default: 20. Minimum: 1. Maximum: 50.</param>
/// <param name="offset">The index of the first object to return. Default: 0 (i.e., the first object)</param>
/// <param name="market">An ISO 3166-1 alpha-2 country code. Provide this parameter if you want to apply Track Relinking.</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public Paging<SavedTrack> GetSavedTracks(int limit = 20, int offset = 0, String market = "")
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for GetSavedTracks");
limit = Math.Min(limit, 50);
StringBuilder builder = new StringBuilder(APIBase + "/me/tracks");
builder.Append("?limit=" + limit);
builder.Append("&offset=" + offset);
if (!String.IsNullOrEmpty(market))
builder.Append("&market=" + market);
return DownloadData<Paging<SavedTrack>>(builder.ToString());
}
/// <summary>
/// Remove one or more tracks from the current user’s “Your Music” library.
/// </summary>
/// <param name="ids">A list of the Spotify IDs.</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse RemoveSavedTracks(List<String> ids)
{
JArray array = new JArray(ids);
return UploadData<ErrorResponse>(APIBase + "/me/tracks/", array.ToString(Formatting.None), "DELETE") ?? new ErrorResponse();
}
/// <summary>
/// Check if one or more tracks is already saved in the current Spotify user’s “Your Music” library.
/// </summary>
/// <param name="ids">A list of the Spotify IDs.</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ListResponse<Boolean> CheckSavedTracks(List<String> ids)
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for CheckSavedTracks");
JToken res = DownloadData<JToken>(APIBase + "/me/tracks/contains?ids=" + string.Join(",", ids));
if (res is JArray)
return new ListResponse<Boolean> { List = res.ToObject<List<Boolean>>(), Error = null };
return new ListResponse<Boolean> { List = null, Error = res["error"].ToObject<Error>() };
}
#endregion Library
#region Playlists
/// <summary>
/// Get a list of the playlists owned or followed by a Spotify user.
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <param name="limit">The maximum number of playlists to return. Default: 20. Minimum: 1. Maximum: 50. </param>
/// <param name="offset">The index of the first playlist to return. Default: 0 (the first object)</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public Paging<SimplePlaylist> GetUserPlaylists(String userId, int limit = 20, int offset = 0)
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for GetUserPlaylists");
limit = Math.Min(limit, 50);
StringBuilder builder = new StringBuilder(APIBase + "/users/" + userId + "/playlists");
builder.Append("?limit=" + limit);
builder.Append("&offset=" + offset);
return DownloadData<Paging<SimplePlaylist>>(builder.ToString());
}
/// <summary>
/// Get a playlist owned by a Spotify user.
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <param name="playlistId">The Spotify ID for the playlist.</param>
/// <param name="fields">
/// Filters for the query: a comma-separated list of the fields to return. If omitted, all fields are
/// returned.
/// </param>
/// <param name="market">An ISO 3166-1 alpha-2 country code. Provide this parameter if you want to apply Track Relinking.</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public FullPlaylist GetPlaylist(String userId, String playlistId, String fields = "", String market = "")
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for GetPlaylist");
StringBuilder builder = new StringBuilder(APIBase + "/users/" + userId + "/playlists/" + playlistId);
builder.Append("?fields=" + fields);
if (!String.IsNullOrEmpty(market))
builder.Append("&market=" + market);
return DownloadData<FullPlaylist>(builder.ToString());
}
/// <summary>
/// Get full details of the tracks of a playlist owned by a Spotify user.
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <param name="playlistId">The Spotify ID for the playlist.</param>
/// <param name="fields">
/// Filters for the query: a comma-separated list of the fields to return. If omitted, all fields are
/// returned.
/// </param>
/// <param name="limit">The maximum number of tracks to return. Default: 100. Minimum: 1. Maximum: 100.</param>
/// <param name="offset">The index of the first object to return. Default: 0 (i.e., the first object)</param>
/// <param name="market">An ISO 3166-1 alpha-2 country code. Provide this parameter if you want to apply Track Relinking.</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public Paging<PlaylistTrack> GetPlaylistTracks(String userId, String playlistId, String fields = "", int limit = 100, int offset = 0, String market = "")
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for GetPlaylistTracks");
limit = Math.Max(limit, 100);
StringBuilder builder = new StringBuilder(APIBase + "/users/" + userId + "/playlists/" + playlistId + "/tracks");
builder.Append("?fields=" + fields);
builder.Append("&limit=" + limit);
builder.Append("&offset=" + offset);
if (!String.IsNullOrEmpty(market))
builder.Append("&market=" + market);
return DownloadData<Paging<PlaylistTrack>>(builder.ToString());
}
/// <summary>
/// Create a playlist for a Spotify user. (The playlist will be empty until you add tracks.)
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <param name="playlistName">
/// The name for the new playlist, for example "Your Coolest Playlist". This name does not need
/// to be unique.
/// </param>
/// <param name="isPublic">
/// default true. If true the playlist will be public, if false it will be private. To be able to
/// create private playlists, the user must have granted the playlist-modify-private scope.
/// </param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public FullPlaylist CreatePlaylist(String userId, String playlistName, Boolean isPublic = true)
{
JObject body = new JObject
{
{"name", playlistName},
{"public", isPublic}
};
return UploadData<FullPlaylist>(APIBase + "/users/" + userId + "/playlists", body.ToString(Formatting.None));
}
/// <summary>
/// Change a playlist’s name and public/private state. (The user must, of course, own the playlist.)
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <param name="playlistId">The Spotify ID for the playlist.</param>
/// <param name="newName">The new name for the playlist, for example "My New Playlist Title".</param>
/// <param name="newPublic">If true the playlist will be public, if false it will be private.</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse UpdatePlaylist(String userId, String playlistId, String newName = null, Boolean? newPublic = null)
{
JObject body = new JObject();
if (newName != null)
body.Add("name", newName);
if (newPublic != null)
body.Add("public", newPublic);
return UploadData<ErrorResponse>(APIBase + "/users/" + userId + "/playlists/" + playlistId, body.ToString(Formatting.None), "PUT") ?? new ErrorResponse();
}
/// <summary>
/// Replace all the tracks in a playlist, overwriting its existing tracks. This powerful request can be useful for
/// replacing tracks, re-ordering existing tracks, or clearing the playlist.
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <param name="playlistId">The Spotify ID for the playlist.</param>
/// <param name="uris">A list of Spotify track URIs to set. A maximum of 100 tracks can be set in one request.</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse ReplacePlaylistTracks(String userId, String playlistId, List<String> uris)
{
JObject body = new JObject
{
{"uris", new JArray(uris.Take(100))}
};
return UploadData<ErrorResponse>(APIBase + "/users/" + userId + "/playlists/" + playlistId + "/tracks", body.ToString(Formatting.None), "PUT") ?? new ErrorResponse();
}
/// <summary>
/// Remove one or more tracks from a user’s playlist.
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <param name="playlistId">The Spotify ID for the playlist.</param>
/// <param name="uris">
/// array of objects containing Spotify URI strings (and their position in the playlist). A maximum of
/// 100 objects can be sent at once.
/// </param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse RemovePlaylistTracks(String userId, String playlistId, List<DeleteTrackUri> uris)
{
JObject body = new JObject
{
{"tracks", JArray.FromObject(uris.Take(100))}
};
return UploadData<ErrorResponse>(APIBase + "/users/" + userId + "/playlists/" + playlistId + "/tracks", body.ToString(Formatting.None), "DELETE") ?? new ErrorResponse();
}
/// <summary>
/// Remove one or more tracks from a user’s playlist.
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <param name="playlistId">The Spotify ID for the playlist.</param>
/// <param name="uri">Spotify URI</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse RemovePlaylistTrack(String userId, String playlistId, DeleteTrackUri uri)
{
return RemovePlaylistTracks(userId, playlistId, new List<DeleteTrackUri> { uri });
}
/// <summary>
/// Add one or more tracks to a user’s playlist.
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <param name="playlistId">The Spotify ID for the playlist.</param>
/// <param name="uris">A list of Spotify track URIs to add</param>
/// <param name="position">The position to insert the tracks, a zero-based index</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse AddPlaylistTracks(String userId, String playlistId, List<String> uris, int? position = null)
{
JObject body = new JObject
{
{"uris", JArray.FromObject(uris.Take(100))}
};
if (position == null)
return UploadData<ErrorResponse>(APIBase + "/users/" + userId + "/playlists/" + playlistId + "/tracks", body.ToString(Formatting.None)) ?? new ErrorResponse();
return UploadData<ErrorResponse>(APIBase + "/users/" + userId + "/playlists/" + playlistId + "/tracks?position=" + position, body.ToString(Formatting.None)) ?? new ErrorResponse();
}
/// <summary>
/// Add one or more tracks to a user’s playlist.
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <param name="playlistId">The Spotify ID for the playlist.</param>
/// <param name="uri">A Spotify Track URI</param>
/// <param name="position">The position to insert the tracks, a zero-based index</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public ErrorResponse AddPlaylistTrack(String userId, String playlistId, String uri, int? position = null)
{
return AddPlaylistTracks(userId, playlistId, new List<string> { uri }, position);
}
/// <summary>
/// Reorder a track or a group of tracks in a playlist.
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <param name="playlistId">The Spotify ID for the playlist.</param>
/// <param name="rangeStart">The position of the first track to be reordered.</param>
/// <param name="insertBefore">The position where the tracks should be inserted. </param>
/// <param name="rangeLength">The amount of tracks to be reordered. Defaults to 1 if not set.</param>
/// <param name="snapshotId">The playlist's snapshot ID against which you want to make the changes.</param>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public Snapshot ReorderPlaylist(String userId, String playlistId, int rangeStart, int insertBefore, int rangeLength = 1, String snapshotId = "")
{
JObject body = new JObject
{
{"range_start", rangeStart},
{"range_length", rangeLength},
{"insert_before", insertBefore}
};
if (!String.IsNullOrEmpty(snapshotId))
body.Add("snapshot_id", snapshotId);
return UploadData<Snapshot>(APIBase + "/users/" + userId + "/playlists/" + playlistId + "/tracks", body.ToString(Formatting.None), "PUT");
}
#endregion Playlists
#region Profiles
/// <summary>
/// Get detailed profile information about the current user (including the current user’s username).
/// </summary>
/// <returns></returns>
/// <remarks>AUTH NEEDED</remarks>
public PrivateProfile GetPrivateProfile()
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for GetPrivateProfile");
return DownloadData<PrivateProfile>(APIBase + "/me");
}
/// <summary>
/// Get public profile information about a Spotify user.
/// </summary>
/// <param name="userId">The user's Spotify user ID.</param>
/// <returns></returns>
public PublicProfile GetPublicProfile(String userId)
{
return DownloadData<PublicProfile>(APIBase + "/users/" + userId);
}
#endregion Profiles
#region Tracks
/// <summary>
/// Get Spotify catalog information for multiple tracks based on their Spotify IDs.
/// </summary>
/// <param name="ids">A list of the Spotify IDs for the tracks. Maximum: 50 IDs.</param>
/// <param name="market">An ISO 3166-1 alpha-2 country code. Provide this parameter if you want to apply Track Relinking.</param>
/// <returns></returns>
public SeveralTracks GetSeveralTracks(List<String> ids, String market = "")
{
if (String.IsNullOrEmpty(market))
return DownloadData<SeveralTracks>(APIBase + "/tracks?ids=" + string.Join(",", ids.Take(50)));
return DownloadData<SeveralTracks>(APIBase + "/tracks?market=" + market + "&ids=" + string.Join(",", ids.Take(50)));
}
/// <summary>
/// Get Spotify catalog information for a single track identified by its unique Spotify ID.
/// </summary>
/// <param name="id">The Spotify ID for the track.</param>
/// <param name="market">An ISO 3166-1 alpha-2 country code. Provide this parameter if you want to apply Track Relinking.</param>
/// <returns></returns>
public FullTrack GetTrack(String id, String market = "")
{
if (String.IsNullOrEmpty(market))
return DownloadData<FullTrack>(APIBase + "/tracks/" + id);
return DownloadData<FullTrack>(APIBase + "/tracks/" + id + "?market=" + market);
}
#endregion Tracks
#region Util
public T UploadData<T>(String url, String uploadData, String method = "POST")
{
if (!UseAuth)
throw new InvalidOperationException("Auth is required for all Upload-Actions");
WebClient.SetHeader("Authorization", TokenType + " " + AccessToken);
WebClient.SetHeader("Content-Type", "application/json");
return WebClient.UploadJson<T>(url, uploadData, method);
}
public T DownloadData<T>(String url)
{
if (UseAuth)
WebClient.SetHeader("Authorization", TokenType + " " + AccessToken);
else
WebClient.RemoveHeader("Authorization");
return WebClient.DownloadJson<T>(url);
}
#endregion Util
}
}