-
Notifications
You must be signed in to change notification settings - Fork 957
/
client.py
1893 lines (1610 loc) · 66.4 KB
/
client.py
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
# -*- coding: utf-8 -*-
""" A simple and thin Python library for the Spotify Web API """
__all__ = ["Spotify", "SpotifyException"]
import json
import logging
import warnings
import requests
import urllib3
import six
from spotipy.exceptions import SpotifyException
logger = logging.getLogger(__name__)
class Spotify(object):
"""
Example usage::
import spotipy
urn = 'spotify:artist:3jOstUTkEu2JkjvRdBA5Gu'
sp = spotipy.Spotify()
artist = sp.artist(urn)
print(artist)
user = sp.user('plamere')
print(user)
"""
max_retries = 3
default_retry_codes = (429, 500, 502, 503, 504)
country_codes = [
"AD",
"AR",
"AU",
"AT",
"BE",
"BO",
"BR",
"BG",
"CA",
"CL",
"CO",
"CR",
"CY",
"CZ",
"DK",
"DO",
"EC",
"SV",
"EE",
"FI",
"FR",
"DE",
"GR",
"GT",
"HN",
"HK",
"HU",
"IS",
"ID",
"IE",
"IT",
"JP",
"LV",
"LI",
"LT",
"LU",
"MY",
"MT",
"MX",
"MC",
"NL",
"NZ",
"NI",
"NO",
"PA",
"PY",
"PE",
"PH",
"PL",
"PT",
"SG",
"ES",
"SK",
"SE",
"CH",
"TW",
"TR",
"GB",
"US",
"UY"]
def __init__(
self,
auth=None,
requests_session=True,
client_credentials_manager=None,
oauth_manager=None,
auth_manager=None,
proxies=None,
requests_timeout=5,
status_forcelist=None,
retries=max_retries,
status_retries=max_retries,
backoff_factor=0.3,
language=None,
):
"""
Creates a Spotify API client.
:param auth: An authorization token (optional)
:param requests_session:
A Requests session object or a truthy value to create one.
A falsy value disables sessions.
It should generally be a good idea to keep sessions enabled
for performance reasons (connection pooling).
:param client_credentials_manager:
SpotifyClientCredentials object
:param oauth_manager:
SpotifyOAuth object
:param auth_manager:
SpotifyOauth, SpotifyClientCredentials,
or SpotifyImplicitGrant object
:param proxies:
Definition of proxies (optional).
See Requests doc https://2.python-requests.org/en/master/user/advanced/#proxies
:param requests_timeout:
Tell Requests to stop waiting for a response after a given
number of seconds
:param status_forcelist:
Tell requests what type of status codes retries should occur on
:param retries:
Total number of retries to allow
:param status_retries:
Number of times to retry on bad status codes
:param backoff_factor:
A backoff factor to apply between attempts after the second try
See urllib3 https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html
:param language:
The language parameter advertises what language the user prefers to see.
See ISO-639 language code: https://www.loc.gov/standards/iso639-2/php/code_list.php
"""
self.prefix = "https://api.spotify.com/v1/"
self._auth = auth
self.client_credentials_manager = client_credentials_manager
self.oauth_manager = oauth_manager
self.auth_manager = auth_manager
self.proxies = proxies
self.requests_timeout = requests_timeout
self.status_forcelist = status_forcelist or self.default_retry_codes
self.backoff_factor = backoff_factor
self.retries = retries
self.status_retries = status_retries
self.language = language
if isinstance(requests_session, requests.Session):
self._session = requests_session
else:
if requests_session: # Build a new session.
self._build_session()
else: # Use the Requests API module as a "session".
self._session = requests.api
def set_auth(self, auth):
self._auth = auth
@property
def auth_manager(self):
return self._auth_manager
@auth_manager.setter
def auth_manager(self, auth_manager):
if auth_manager is not None:
self._auth_manager = auth_manager
else:
self._auth_manager = (
self.client_credentials_manager or self.oauth_manager
)
def __del__(self):
"""Make sure the connection (pool) gets closed"""
if isinstance(self._session, requests.Session):
self._session.close()
def _build_session(self):
self._session = requests.Session()
retry = urllib3.Retry(
total=self.retries,
connect=None,
read=False,
status=self.status_retries,
backoff_factor=self.backoff_factor,
status_forcelist=self.status_forcelist)
adapter = requests.adapters.HTTPAdapter(max_retries=retry)
self._session.mount('http://', adapter)
self._session.mount('https://', adapter)
def _auth_headers(self):
if self._auth:
return {"Authorization": "Bearer {0}".format(self._auth)}
if not self.auth_manager:
return {}
try:
token = self.auth_manager.get_access_token(as_dict=False)
except TypeError:
token = self.auth_manager.get_access_token()
return {"Authorization": "Bearer {0}".format(token)}
def _internal_call(self, method, url, payload, params):
args = dict(params=params)
if not url.startswith("http"):
url = self.prefix + url
headers = self._auth_headers()
if "content_type" in args["params"]:
headers["Content-Type"] = args["params"]["content_type"]
del args["params"]["content_type"]
if payload:
args["data"] = payload
else:
headers["Content-Type"] = "application/json"
if payload:
args["data"] = json.dumps(payload)
if self.language is not None:
headers["Accept-Language"] = self.language
logger.debug('Sending %s to %s with Headers: %s and Body: %r ',
method, url, headers, args.get('data'))
try:
response = self._session.request(
method, url, headers=headers, proxies=self.proxies,
timeout=self.requests_timeout, **args
)
response.raise_for_status()
results = response.json()
except requests.exceptions.HTTPError as http_error:
response = http_error.response
try:
msg = response.json()["error"]["message"]
except (ValueError, KeyError):
msg = "error"
try:
reason = response.json()["error"]["reason"]
except (ValueError, KeyError):
reason = None
logger.error('HTTP Error for %s to %s returned %s due to %s',
method, url, response.status_code, msg)
raise SpotifyException(
response.status_code,
-1,
"%s:\n %s" % (response.url, msg),
reason=reason,
headers=response.headers,
)
except requests.exceptions.RetryError as retry_error:
request = retry_error.request
logger.error('Max Retries reached')
try:
reason = retry_error.args[0].reason
except (IndexError, AttributeError):
reason = None
raise SpotifyException(
599,
-1,
"%s:\n %s" % (request.path_url, "Max Retries"),
reason=reason
)
except ValueError:
results = None
logger.debug('RESULTS: %s', results)
return results
def _get(self, url, args=None, payload=None, **kwargs):
if args:
kwargs.update(args)
return self._internal_call("GET", url, payload, kwargs)
def _post(self, url, args=None, payload=None, **kwargs):
if args:
kwargs.update(args)
return self._internal_call("POST", url, payload, kwargs)
def _delete(self, url, args=None, payload=None, **kwargs):
if args:
kwargs.update(args)
return self._internal_call("DELETE", url, payload, kwargs)
def _put(self, url, args=None, payload=None, **kwargs):
if args:
kwargs.update(args)
return self._internal_call("PUT", url, payload, kwargs)
def next(self, result):
""" returns the next result given a paged result
Parameters:
- result - a previously returned paged result
"""
if result["next"]:
return self._get(result["next"])
else:
return None
def previous(self, result):
""" returns the previous result given a paged result
Parameters:
- result - a previously returned paged result
"""
if result["previous"]:
return self._get(result["previous"])
else:
return None
def track(self, track_id):
""" returns a single track given the track's ID, URI or URL
Parameters:
- track_id - a spotify URI, URL or ID
"""
trid = self._get_id("track", track_id)
return self._get("tracks/" + trid)
def tracks(self, tracks, market=None):
""" returns a list of tracks given a list of track IDs, URIs, or URLs
Parameters:
- tracks - a list of spotify URIs, URLs or IDs. Maximum: 50 IDs.
- market - an ISO 3166-1 alpha-2 country code.
"""
tlist = [self._get_id("track", t) for t in tracks]
return self._get("tracks/?ids=" + ",".join(tlist), market=market)
def artist(self, artist_id):
""" returns a single artist given the artist's ID, URI or URL
Parameters:
- artist_id - an artist ID, URI or URL
"""
trid = self._get_id("artist", artist_id)
return self._get("artists/" + trid)
def artists(self, artists):
""" returns a list of artists given the artist IDs, URIs, or URLs
Parameters:
- artists - a list of artist IDs, URIs or URLs
"""
tlist = [self._get_id("artist", a) for a in artists]
return self._get("artists/?ids=" + ",".join(tlist))
def artist_albums(
self, artist_id, album_type=None, country=None, limit=20, offset=0
):
""" Get Spotify catalog information about an artist's albums
Parameters:
- artist_id - the artist ID, URI or URL
- album_type - 'album', 'single', 'appears_on', 'compilation'
- country - limit the response to one particular country.
- limit - the number of albums to return
- offset - the index of the first album to return
"""
trid = self._get_id("artist", artist_id)
return self._get(
"artists/" + trid + "/albums",
album_type=album_type,
country=country,
limit=limit,
offset=offset,
)
def artist_top_tracks(self, artist_id, country="US"):
""" Get Spotify catalog information about an artist's top 10 tracks
by country.
Parameters:
- artist_id - the artist ID, URI or URL
- country - limit the response to one particular country.
"""
trid = self._get_id("artist", artist_id)
return self._get("artists/" + trid + "/top-tracks", country=country)
def artist_related_artists(self, artist_id):
""" Get Spotify catalog information about artists similar to an
identified artist. Similarity is based on analysis of the
Spotify community's listening history.
Parameters:
- artist_id - the artist ID, URI or URL
"""
trid = self._get_id("artist", artist_id)
return self._get("artists/" + trid + "/related-artists")
def album(self, album_id):
""" returns a single album given the album's ID, URIs or URL
Parameters:
- album_id - the album ID, URI or URL
"""
trid = self._get_id("album", album_id)
return self._get("albums/" + trid)
def album_tracks(self, album_id, limit=50, offset=0, market=None):
""" Get Spotify catalog information about an album's tracks
Parameters:
- album_id - the album ID, URI or URL
- limit - the number of items to return
- offset - the index of the first item to return
- market - an ISO 3166-1 alpha-2 country code.
"""
trid = self._get_id("album", album_id)
return self._get(
"albums/" + trid + "/tracks/", limit=limit, offset=offset, market=market
)
def albums(self, albums):
""" returns a list of albums given the album IDs, URIs, or URLs
Parameters:
- albums - a list of album IDs, URIs or URLs
"""
tlist = [self._get_id("album", a) for a in albums]
return self._get("albums/?ids=" + ",".join(tlist))
def show(self, show_id, market=None):
""" returns a single show given the show's ID, URIs or URL
Parameters:
- show_id - the show ID, URI or URL
- market - an ISO 3166-1 alpha-2 country code.
The show must be available in the given market.
If user-based authorization is in use, the user's country
takes precedence. If neither market nor user country are
provided, the content is considered unavailable for the client.
"""
trid = self._get_id("show", show_id)
return self._get("shows/" + trid, market=market)
def shows(self, shows, market=None):
""" returns a list of shows given the show IDs, URIs, or URLs
Parameters:
- shows - a list of show IDs, URIs or URLs
- market - an ISO 3166-1 alpha-2 country code.
Only shows available in the given market will be returned.
If user-based authorization is in use, the user's country
takes precedence. If neither market nor user country are
provided, the content is considered unavailable for the client.
"""
tlist = [self._get_id("show", s) for s in shows]
return self._get("shows/?ids=" + ",".join(tlist), market=market)
def show_episodes(self, show_id, limit=50, offset=0, market=None):
""" Get Spotify catalog information about a show's episodes
Parameters:
- show_id - the show ID, URI or URL
- limit - the number of items to return
- offset - the index of the first item to return
- market - an ISO 3166-1 alpha-2 country code.
Only episodes available in the given market will be returned.
If user-based authorization is in use, the user's country
takes precedence. If neither market nor user country are
provided, the content is considered unavailable for the client.
"""
trid = self._get_id("show", show_id)
return self._get(
"shows/" + trid + "/episodes/", limit=limit, offset=offset, market=market
)
def episode(self, episode_id, market=None):
""" returns a single episode given the episode's ID, URIs or URL
Parameters:
- episode_id - the episode ID, URI or URL
- market - an ISO 3166-1 alpha-2 country code.
The episode must be available in the given market.
If user-based authorization is in use, the user's country
takes precedence. If neither market nor user country are
provided, the content is considered unavailable for the client.
"""
trid = self._get_id("episode", episode_id)
return self._get("episodes/" + trid, market=market)
def episodes(self, episodes, market=None):
""" returns a list of episodes given the episode IDs, URIs, or URLs
Parameters:
- episodes - a list of episode IDs, URIs or URLs
- market - an ISO 3166-1 alpha-2 country code.
Only episodes available in the given market will be returned.
If user-based authorization is in use, the user's country
takes precedence. If neither market nor user country are
provided, the content is considered unavailable for the client.
"""
tlist = [self._get_id("episode", e) for e in episodes]
return self._get("episodes/?ids=" + ",".join(tlist), market=market)
def search(self, q, limit=10, offset=0, type="track", market=None):
""" searches for an item
Parameters:
- q - the search query (see how to write a query in the
official documentation https://developer.spotify.com/documentation/web-api/reference/search/search/) # noqa
- limit - the number of items to return (min = 1, default = 10, max = 50)
- offset - the index of the first item to return
- type - the type of item to return. One of 'artist', 'album',
'track', 'playlist', 'show', or 'episode'
- market - An ISO 3166-1 alpha-2 country code or the string
from_token.
"""
return self._get(
"search", q=q, limit=limit, offset=offset, type=type, market=market
)
def search_markets(self, q, limit=10, offset=0, type="track", markets=None, total=None):
""" (experimental) Searches multiple markets for an item
Parameters:
- q - the search query (see how to write a query in the
official documentation https://developer.spotify.com/documentation/web-api/reference/search/search/) # noqa
- limit - the number of items to return (min = 1, default = 10, max = 50). If a search is to be done on multiple
markets, then this limit is applied to each market. (e.g. search US, CA, MX each with a limit of 10).
- offset - the index of the first item to return
- type - the type's of item's to return. One or more of 'artist', 'album',
'track', 'playlist', 'show', or 'episode'. If multiple types are desired, pass in a comma separated list.
- markets - A list of ISO 3166-1 alpha-2 country codes. Search all country markets by default.
- total - the total number of results to return if multiple markets are supplied in the search.
If multiple types are specified, this only applies to the first type.
"""
warnings.warn(
"Searching multiple markets is an experimental feature. "
"Please be aware that this method's inputs and outputs can change in the future.",
UserWarning,
)
if not markets:
markets = self.country_codes
if not (isinstance(markets, list) or isinstance(markets, tuple)):
markets = []
warnings.warn(
"Searching multiple markets is poorly performing.",
UserWarning,
)
return self._search_multiple_markets(q, limit, offset, type, markets, total)
def user(self, user):
""" Gets basic profile information about a Spotify User
Parameters:
- user - the id of the usr
"""
return self._get("users/" + user)
def current_user_playlists(self, limit=50, offset=0):
""" Get current user playlists without required getting his profile
Parameters:
- limit - the number of items to return
- offset - the index of the first item to return
"""
return self._get("me/playlists", limit=limit, offset=offset)
def playlist(self, playlist_id, fields=None, market=None, additional_types=("track",)):
""" Gets playlist by id.
Parameters:
- playlist - the id of the playlist
- fields - which fields to return
- market - An ISO 3166-1 alpha-2 country code or the
string from_token.
- additional_types - list of item types to return.
valid types are: track and episode
"""
plid = self._get_id("playlist", playlist_id)
return self._get(
"playlists/%s" % (plid),
fields=fields,
market=market,
additional_types=",".join(additional_types),
)
def playlist_tracks(
self,
playlist_id,
fields=None,
limit=100,
offset=0,
market=None,
additional_types=("track",)
):
""" Get full details of the tracks of a playlist.
Parameters:
- playlist_id - the id of the playlist
- fields - which fields to return
- limit - the maximum number of tracks to return
- offset - the index of the first track to return
- market - an ISO 3166-1 alpha-2 country code.
- additional_types - list of item types to return.
valid types are: track and episode
"""
warnings.warn(
"You should use `playlist_items(playlist_id, ...,"
"additional_types=('track',))` instead",
DeprecationWarning,
)
return self.playlist_items(playlist_id, fields, limit, offset,
market, additional_types)
def playlist_items(
self,
playlist_id,
fields=None,
limit=100,
offset=0,
market=None,
additional_types=("track", "episode")
):
""" Get full details of the tracks and episodes of a playlist.
Parameters:
- playlist_id - the id of the playlist
- fields - which fields to return
- limit - the maximum number of tracks to return
- offset - the index of the first track to return
- market - an ISO 3166-1 alpha-2 country code.
- additional_types - list of item types to return.
valid types are: track and episode
"""
plid = self._get_id("playlist", playlist_id)
return self._get(
"playlists/%s/tracks" % (plid),
limit=limit,
offset=offset,
fields=fields,
market=market,
additional_types=",".join(additional_types)
)
def playlist_cover_image(self, playlist_id):
""" Get cover of a playlist.
Parameters:
- playlist_id - the id of the playlist
"""
plid = self._get_id("playlist", playlist_id)
return self._get("playlists/%s/images" % (plid))
def playlist_upload_cover_image(self, playlist_id, image_b64):
""" Replace the image used to represent a specific playlist
Parameters:
- playlist_id - the id of the playlist
- image_b64 - image data as a Base64 encoded JPEG image string
(maximum payload size is 256 KB)
"""
plid = self._get_id("playlist", playlist_id)
return self._put(
"playlists/{}/images".format(plid),
payload=image_b64,
content_type="image/jpeg",
)
def user_playlist(self, user, playlist_id=None, fields=None, market=None):
warnings.warn(
"You should use `playlist(playlist_id)` instead",
DeprecationWarning,
)
""" Gets playlist of a user
Parameters:
- user - the id of the user
- playlist_id - the id of the playlist
- fields - which fields to return
"""
if playlist_id is None:
return self._get("users/%s/starred" % user)
return self.playlist(playlist_id, fields=fields, market=market)
def user_playlist_tracks(
self,
user=None,
playlist_id=None,
fields=None,
limit=100,
offset=0,
market=None,
):
warnings.warn(
"You should use `playlist_tracks(playlist_id)` instead",
DeprecationWarning,
)
""" Get full details of the tracks of a playlist owned by a user.
Parameters:
- user - the id of the user
- playlist_id - the id of the playlist
- fields - which fields to return
- limit - the maximum number of tracks to return
- offset - the index of the first track to return
- market - an ISO 3166-1 alpha-2 country code.
"""
return self.playlist_tracks(
playlist_id,
limit=limit,
offset=offset,
fields=fields,
market=market,
)
def user_playlists(self, user, limit=50, offset=0):
""" Gets playlists of a user
Parameters:
- user - the id of the usr
- limit - the number of items to return
- offset - the index of the first item to return
"""
return self._get(
"users/%s/playlists" % user, limit=limit, offset=offset
)
def user_playlist_create(self, user, name, public=True, collaborative=False, description=""):
""" Creates a playlist for a user
Parameters:
- user - the id of the user
- name - the name of the playlist
- public - is the created playlist public
- collaborative - is the created playlist collaborative
- description - the description of the playlist
"""
data = {
"name": name,
"public": public,
"collaborative": collaborative,
"description": description
}
return self._post("users/%s/playlists" % (user,), payload=data)
def user_playlist_change_details(
self,
user,
playlist_id,
name=None,
public=None,
collaborative=None,
description=None,
):
warnings.warn(
"You should use `playlist_change_details(playlist_id, ...)` instead",
DeprecationWarning,
)
""" Changes a playlist's name and/or public/private state
Parameters:
- user - the id of the user
- playlist_id - the id of the playlist
- name - optional name of the playlist
- public - optional is the playlist public
- collaborative - optional is the playlist collaborative
- description - optional description of the playlist
"""
return self.playlist_change_details(playlist_id, name, public,
collaborative, description)
def user_playlist_unfollow(self, user, playlist_id):
""" Unfollows (deletes) a playlist for a user
Parameters:
- user - the id of the user
- name - the name of the playlist
"""
warnings.warn(
"You should use `current_user_unfollow_playlist(playlist_id)` instead",
DeprecationWarning,
)
return self.current_user_unfollow_playlist(playlist_id)
def user_playlist_add_tracks(
self, user, playlist_id, tracks, position=None
):
warnings.warn(
"You should use `playlist_add_items(playlist_id, tracks)` instead",
DeprecationWarning,
)
""" Adds tracks to a playlist
Parameters:
- user - the id of the user
- playlist_id - the id of the playlist
- tracks - a list of track URIs, URLs or IDs
- position - the position to add the tracks
"""
return self.playlist_add_items(playlist_id, tracks, position)
def user_playlist_replace_tracks(self, user, playlist_id, tracks):
""" Replace all tracks in a playlist
Parameters:
- user - the id of the user
- playlist_id - the id of the playlist
- tracks - the list of track ids to add to the playlist
"""
warnings.warn(
"You should use `playlist_replace_items(playlist_id, tracks)` instead",
DeprecationWarning,
)
return self.playlist_replace_items(playlist_id, tracks)
def user_playlist_reorder_tracks(
self,
user,
playlist_id,
range_start,
insert_before,
range_length=1,
snapshot_id=None,
):
""" Reorder tracks in a playlist
Parameters:
- user - the id of the user
- playlist_id - the id of the playlist
- range_start - the position of the first track to be reordered
- range_length - optional the number of tracks to be reordered
(default: 1)
- insert_before - the position where the tracks should be
inserted
- snapshot_id - optional playlist's snapshot ID
"""
warnings.warn(
"You should use `playlist_reorder_items(playlist_id, ...)` instead",
DeprecationWarning,
)
return self.playlist_reorder_items(playlist_id, range_start,
range_length, insert_before,
snapshot_id)
def user_playlist_remove_all_occurrences_of_tracks(
self, user, playlist_id, tracks, snapshot_id=None
):
""" Removes all occurrences of the given tracks from the given playlist
Parameters:
- user - the id of the user
- playlist_id - the id of the playlist
- tracks - the list of track ids to remove from the playlist
- snapshot_id - optional id of the playlist snapshot
"""
warnings.warn(
"You should use `playlist_remove_all_occurrences_of_items"
"(playlist_id, tracks)` instead",
DeprecationWarning,
)
return self.playlist_remove_all_occurrences_of_items(playlist_id,
tracks,
snapshot_id)
def user_playlist_remove_specific_occurrences_of_tracks(
self, user, playlist_id, tracks, snapshot_id=None
):
""" Removes all occurrences of the given tracks from the given playlist
Parameters:
- user - the id of the user
- playlist_id - the id of the playlist
- tracks - an array of objects containing Spotify URIs of the
tracks to remove with their current positions in the
playlist. For example:
[ { "uri":"4iV5W9uYEdYUVa79Axb7Rh", "positions":[2] },
{ "uri":"1301WleyT98MSxVHPZCA6M", "positions":[7] } ]
- snapshot_id - optional id of the playlist snapshot
"""
warnings.warn(
"You should use `playlist_remove_specific_occurrences_of_items"
"(playlist_id, tracks)` instead",
DeprecationWarning,
)
plid = self._get_id("playlist", playlist_id)
ftracks = []
for tr in tracks:
ftracks.append(
{
"uri": self._get_uri("track", tr["uri"]),
"positions": tr["positions"],
}
)
payload = {"tracks": ftracks}
if snapshot_id:
payload["snapshot_id"] = snapshot_id
return self._delete(
"users/%s/playlists/%s/tracks" % (user, plid), payload=payload
)
def user_playlist_follow_playlist(self, playlist_owner_id, playlist_id):
"""
Add the current authenticated user as a follower of a playlist.
Parameters:
- playlist_owner_id - the user id of the playlist owner
- playlist_id - the id of the playlist
"""
warnings.warn(
"You should use `current_user_follow_playlist(playlist_id)` instead",
DeprecationWarning,
)
return self.current_user_follow_playlist(playlist_id)
def user_playlist_is_following(
self, playlist_owner_id, playlist_id, user_ids
):
"""
Check to see if the given users are following the given playlist
Parameters:
- playlist_owner_id - the user id of the playlist owner
- playlist_id - the id of the playlist
- user_ids - the ids of the users that you want to check to see
if they follow the playlist. Maximum: 5 ids.
"""
warnings.warn(
"You should use `playlist_is_following(playlist_id, user_ids)` instead",
DeprecationWarning,
)
return self.playlist_is_following(playlist_id, user_ids)
def playlist_change_details(
self,
playlist_id,
name=None,
public=None,
collaborative=None,
description=None,
):
""" Changes a playlist's name and/or public/private state
Parameters:
- playlist_id - the id of the playlist
- name - optional name of the playlist
- public - optional is the playlist public
- collaborative - optional is the playlist collaborative
- description - optional description of the playlist
"""
data = {}
if isinstance(name, six.string_types):
data["name"] = name
if isinstance(public, bool):
data["public"] = public
if isinstance(collaborative, bool):
data["collaborative"] = collaborative
if isinstance(description, six.string_types):
data["description"] = description
return self._put(
"playlists/%s" % (playlist_id), payload=data
)
def current_user_unfollow_playlist(self, playlist_id):
""" Unfollows (deletes) a playlist for the current authenticated
user