forked from plamere/SmarterPlaylists
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugs.py
1286 lines (1070 loc) · 40.7 KB
/
plugs.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
import pbl
import datetime
import random
import spotipy
from werkzeug.contrib.cache import SimpleCache
from pbl import spotify_plugs
import simplejson as json
import time
cache = SimpleCache()
class YesNo(pbl.Conditional):
def __init__(self, yes, true_source, false_source):
def func():
return yes
super(YesNo, self).__init__(func, true_source, false_source)
class IsWeekend(pbl.Conditional):
def __init__(self, true_source, false_source):
def bool_func():
return datetime.datetime.today().weekday() >= 5
super(IsWeekend, self).__init__(bool_func, true_source, false_source)
class IsDayOfWeek(pbl.Conditional):
def __init__(self, day, true_source, false_source):
def bool_func():
return datetime.datetime.today().weekday() == day
super(IsDayOfWeek, self).__init__(bool_func, true_source, false_source)
class IsTimeOfDay(pbl.Conditional):
def __init__(self, startTime, endTime, true_source, false_source):
def bool_func():
return datetime.datetime.today().weekday() == day
super(IsDayOfWeek, self).__init__(bool_func, true_source, false_source)
class IsTimeOfDay(pbl.Conditional):
def __init__(self, startTime, endTime, true_source, false_source):
def bool_func():
return datetime.datetime.today().weekday() == day
super(IsDayOfWeek, self).__init__(bool_func, true_source, false_source)
class RandomSelector(object):
'''
Randomly selects a track from one of the given inputs
:param source_list: a list of sources
'''
def __init__(self, source_list, fail_fast):
self.name = 'randomly selecting from ' + ', '.join([s.name for s in source_list])
self.source_list = source_list
self.fail_fast = fail_fast
def next_track(self):
while (len(self.source_list) > 0):
src = random.choice(self.source_list)
track = src.next_track()
if track:
return track
elif not self.fail_fast:
self.source_list.remove(src)
else:
break
return None;
class RandomStreamSelector(object):
'''
Randomly selects a stream from a set of inputs
:param source_list: a list of sources
'''
def __init__(self, source_list):
self.source_list = source_list
self.src = random.choice(self.source_list)
self.name = 'randomly picked ' + self.src.name
def next_track(self):
return self.src.next_track()
class Comment(object):
'''
Randomly selects a stream from a set of inputs
:param source_list: a list of sources
'''
def __init__(self, text, fontsize=12, color='#000000'):
self.text = text
self.name = text
self.fontsize = fontsize
self.color = color
def next_track(self):
raise pbl.PBLException(self, "a comment is not runnable")
class TrackFilter(object):
'''
produces tracks on the true source that are not on the false source
'''
def __init__(self, true_source, false_source, invert=False, by_name=False):
prep = ' that are also in ' if invert else ' that are not in '
self.name = 'tracks in ' + true_source.name + prep + \
false_source.name
self.true_source = true_source
self.false_source = false_source
self.bad_tracks = set()
self.invert = invert
self.debug = False
self.by_name = by_name
def next_track(self):
while True:
bad_track = self.false_source.next_track()
self.bad_tracks.add(bad_track)
if bad_track:
if self.by_name:
bad_track_name = pbl.tlib.get_tn(bad_track).lower()
self.bad_tracks.add(bad_track_name)
else:
break
while True:
track = self.true_source.next_track()
if track:
if self.by_name:
track_name = pbl.tlib.get_tn(track).lower()
else:
track_name = track
if self.invert and ((track in self.bad_tracks) or (track_name in self.bad_tracks)):
return track
elif (not self.invert) and ((track not in self.bad_tracks) and (track_name not in self.bad_tracks)):
return track
else:
if self.debug:
print 'filtered out', pbl.tlib.get_tn(track)
else:
break
return None
class ArtistFilter(object):
'''
produces tracks on the true source that are not by artists the false source
'''
def __init__(self, true_source, false_source, invert=False):
prep = ' that are by ' if invert else ' that are not by '
self.name = 'tracks in ' + true_source.name + prep + \
'artists in ' + false_source.name
self.true_source = true_source
self.false_source = false_source
self.bad_artists = set()
self.invert = invert
self.debug = False
def next_track(self):
while True:
bad_track = self.false_source.next_track()
if bad_track:
tinfo = pbl.tlib.get_track(bad_track)
self.bad_artists.add(tinfo['artist'])
else:
break
while True:
track = self.true_source.next_track()
if track:
tinfo = pbl.tlib.get_track(track)
if self.invert and (tinfo['artist'] in self.bad_artists):
return track
elif (not self.invert) and (tinfo['artist'] not in self.bad_artists):
return track
else:
if self.debug:
print 'filtered out', pbl.tlib.get_tn(track)
else:
break
return None
MOST = 0
MORE = 1
LESS = 2
LEAST = 3
ALL = 4
class Danceable(pbl.AttributeRangeFilter):
ranges = [
(.8, 1),
(.6, 1),
(.0, .4),
(.0, .2),
(.0, 1),
]
def __init__(self, source, scale):
min_val = self.ranges[scale] [0]
max_val = self.ranges[scale] [1]
super(Danceable, self).__init__(source, "audio.danceability",
match=None, min_val=min_val, max_val=max_val)
class ReleaseDateFilter(pbl.AttributeRangeFilter):
def __init__(self, source, min_val, max_val):
super(ReleaseDateFilter, self).__init__(source, "spotify.album_release_date",
match=None, min_val=min_val, max_val=max_val)
class Energy(pbl.AttributeRangeFilter):
ranges = [
(.8, 1),
(.6, 1),
(.0, .4),
(.0, .2),
(.0, 1),
]
def __init__(self, source, scale):
min_val = self.ranges[scale] [0]
max_val = self.ranges[scale] [1]
super(Energy, self).__init__(source, "audio.energy",
match=None, min_val=min_val, max_val=max_val)
class Explicit(pbl.AttributeRangeFilter):
def __init__(self, source, explicit):
super(Explicit, self).__init__(source, "spotify.explicit", match=explicit)
class Live(pbl.AttributeRangeFilter):
ranges = [
(.8, 1),
(.6, 1),
(.0, .4),
(.0, .2),
(.0, 1),
]
def __init__(self, source, scale):
min_val = self.ranges[scale] [0]
max_val = self.ranges[scale] [1]
super(Live, self).__init__(source, "audio.liveness",
match=None, min_val=min_val, max_val=max_val)
class SpokenWord(pbl.AttributeRangeFilter):
ranges = [
(.8, 1),
(.6, 1),
(.0, .4),
(.0, .2),
(.0, 1),
]
def __init__(self, source, scale):
min_val = self.ranges[scale] [0]
max_val = self.ranges[scale] [1]
super(SpokenWord, self).__init__(source, "audio.speechiness",
match=None, min_val=min_val, max_val=max_val)
class Tempo(pbl.AttributeRangeFilter):
def __init__(self, source, min_tempo, max_tempo):
min_val = min_tempo
max_val = max_tempo
super(Tempo, self).__init__(source, "audio.tempo",
match=None, min_val=min_val, max_val=max_val)
class AllButTheFirst(object):
'''
Returns all but the first tracks from a stream
:param source: the source of tracks
:param sample_size: the number of tracks to skip
'''
def __init__(self, source, sample_size=10):
self.name = 'all but the first ' + str(sample_size) + ' of ' + source.name
self.source = source
self.sample_size = sample_size
self.buffer = []
self.filling = True
def next_track(self):
while self.filling:
track = self.source.next_track()
if track:
self.buffer.append(track)
else:
self.filling = False
self.buffer = self.buffer[self.sample_size:]
if len(self.buffer) > 0:
return self.buffer.pop(0)
else:
return None
class AllButTheLast(object):
'''
Returns all but the last tracks from a stream
:param source: the source of tracks
:param sample_size: the number of tracks to skip
'''
def __init__(self, source, sample_size=10):
self.name = 'all but the last ' + str(sample_size) + ' of ' + source.name
self.source = source
self.sample_size = sample_size
self.buffer = []
self.filling = True
def next_track(self):
while self.filling:
track = self.source.next_track()
if track:
self.buffer.append(track)
else:
self.filling = False
self.buffer = self.buffer[:-self.sample_size:]
if len(self.buffer) > 0:
return self.buffer.pop(0)
else:
return None
def is_authenticated():
auth_token = pbl.engine.getEnv('spotify_auth_token')
return auth_token != None
def get_user():
user = pbl.engine.getEnv('spotify_user_id')
return user
def get_spotify():
return pbl.spotify_plugs._get_spotify()
class PlaylistSave(object):
''' A PBL Sink that saves the source stream of tracks to the given playlist
:param source: the source of tracks to be saved
:param playlist_name: the name of the playlist
:param playlist_uri: the uri of the playlist
:param append: if true, append to the playlist
'''
def __init__(self, source, playlist_name= None, playlist_uri=None, append=False):
self.source = source
self.name = source.name + ' saved to ' + playlist_name
self.playlist_name = playlist_name
self.playlist_uri = playlist_uri
self.append = append
self.buffer = []
self.saved = False
self.max_size = 1000
def next_track(self):
if not is_authenticated():
raise pbl.PBLException(self, "not authenticated for save")
track = self.source.next_track()
if track and len(self.buffer) < self.max_size:
self.buffer.append(track)
elif not self.saved:
self._save_playlist()
return track
def _save_playlist(self):
self.saved = True
sp = get_spotify()
user = get_user()
if not sp:
raise pbl.PBLException(self, "not authenticated for save")
if not user:
raise pbl.PBLException(self, "no user")
# TODO - this can be slow if the user has lots of playlists
# should cache?
if self.playlist_uri:
uri = self.playlist_uri
puser = get_user_from_playlist_uri(uri)
pid = get_pid_from_playlist_uri(uri)
if not user:
raise pbl.PBLException(self, "bad uri")
# it is an error if we don't own the playlist
# TBD - what about collab playlists?
if user != puser:
raise pbl.PBLException(self, "Can't save to that playlist")
if not pid:
raise pbl.PBLException(self, "bad uri")
else:
uri = find_playlist_by_name(sp, user, self.playlist_name)
if uri:
print 'found', uri
else:
print 'creating new', self.playlist_name, 'playlist'
response = sp.user_playlist_create(user, self.playlist_name)
uri = response['uri']
pid = get_pid_from_playlist_uri(uri)
if pid:
batch_size = 100
uris = [ 'spotify:track:' + id for id in self.buffer]
for start in xrange(0, len(uris), batch_size):
turis = uris[start:start+batch_size]
if start == 0 and not self.append:
sp.user_playlist_replace_tracks(user, pid, turis)
else:
sp.user_playlist_add_tracks(user, pid, turis)
else:
print "Can't get authenticated access to spotify"
class PlaylistSaveToNew(object):
''' A PBL Sink that saves the source stream of tracks to a new playlist
:param source: the source of tracks to be saved
:param playlist_name: the name of the playlist
:param suffix_type - time(default), date, day-of-week, day-of-month
'''
formatters = {
"none": lambda: "",
"time": lambda: " - " + now().strftime("%x %X"),
"date": lambda: " - " + now().strftime("%x"),
"day-of-week": lambda: " - " + get_day_of_week(),
"day-of-month": lambda: " - " + now().strftime("%d"),
}
def __init__(self, source, playlist_name, suffix_type = "none"):
self.source = source
self.name = source.name + ' saved to ' + playlist_name
self.buffer = []
self.saved = False
self.max_size = 1000
if suffix_type == None:
suffix_type = 'none'
if suffix_type not in self.formatters:
raise pbl.PBLException(self, "bad suffix type" + suffix_type)
suffix = self.formatters[suffix_type]()
self.playlist_name = playlist_name + suffix
# print 'st', suffix_type, 's', suffix, 'pn', playlist_name, 'spn', self.playlist_name
def next_track(self):
if not is_authenticated():
raise pbl.PBLException(self, "not authenticated for save")
track = self.source.next_track()
if track and len(self.buffer) < self.max_size:
self.buffer.append(track)
elif not self.saved:
self._save_playlist()
return track
def _save_playlist(self):
self.saved = True
sp = get_spotify()
user = get_user()
if not sp:
raise pbl.PBLException(self, "not authenticated for save")
if not user:
raise pbl.PBLException(self, "no user")
# print 'creating', self.playlist_name
response = sp.user_playlist_create(user, self.playlist_name)
uri = response['uri']
pid = get_pid_from_playlist_uri(uri)
if pid:
batch_size = 100
uris = [ 'spotify:track:' + id for id in self.buffer]
for start in xrange(0, len(uris), batch_size):
turis = uris[start:start+batch_size]
sp.user_playlist_add_tracks(user, pid, turis)
else:
print "Can't get authenticated access to spotify"
def get_pid_from_playlist_uri(uri):
# spotify:user:plamere:playlist:5pjUedV8eoCJUiYzyo79eq
split_uri = uri.split(':')
if len(split_uri) == 5:
return split_uri[4]
else:
return None
def get_user_from_playlist_uri(uri):
# spotify:user:plamere:playlist:5pjUedV8eoCJUiYzyo79eq
split_uri = uri.split(':')
if len(split_uri) == 5:
return split_uri[2]
else:
return None
def find_playlist_by_name(sp, user, name):
key = user + ':::' + name
uri = cache.get(key)
if not uri:
uri = spotify_plugs._find_playlist_by_name(sp, user, name)
if uri:
cache.set(key, uri)
return uri
def save_to_playlist(title, uri, tids):
sp = get_spotify()
user = get_user()
if not sp:
raise Exception("not authenticated for save")
if not user:
raise Exception("no authenticated user")
if not uri:
response = sp.user_playlist_create(user, title)
if 'uri' in response:
uri = response['uri']
else:
raise Exception("Can't create playlist " + title)
pid = get_pid_from_playlist_uri(uri)
if pid:
batch_size = 100
uris = [ 'spotify:track:' + id for id in tids]
for start in xrange(0, len(uris), batch_size):
turis = uris[start:start+batch_size]
if start == 0:
sp.user_playlist_replace_tracks(user, pid, turis)
else:
sp.user_playlist_add_tracks(user, pid, turis)
else:
print "Can't get authenticated access to spotify"
return uri
class MySavedTracks(object):
''' A PBL Source that generates a list of the saved tracks
by the current suer
'''
def __init__(self):
self.name = 'My Saved Tracks'
self.buffer = None
def next_track(self):
if self.buffer == None:
self.buffer = []
try:
sp = get_spotify()
limit = 50
offset = 0
total = 50
while offset < total:
results = sp.current_user_saved_tracks(limit = limit, offset = offset)
for item in results['items']:
track = item['track']
if track and 'id' in track:
self.buffer.append(track['id'])
spotify_plugs._add_track(self.name, track)
else:
raise pbl.engine.PBLException(self, 'bad track')
offset += limit
total = results['total']
# print self.name, len(self.buffer), offset, total
except spotipy.SpotifyException as e:
raise pbl.engine.PBLException(self, e.msg)
if len(self.buffer) > 0:
tid = self.buffer.pop(0)
# print 'ret', self.name, tid
return tid
else:
# print 'ret', self.name, 'empty'
return None
class MyFollowedArtists(object):
''' A PBL Source that generates top tracks from followed artist
by the current user
'''
def __init__(self, num_tracks):
self.name = 'MyFollowedArtists'
self.num_tracks = num_tracks
self.buffer = None
def next_track(self):
if self.buffer == None:
self.buffer = []
try:
sp = get_spotify()
limit = 50
after = None
while True:
try:
results = get_spotify().current_user_followed_artists(limit = limit, after = after)
except spotipy.SpotifyException as e:
raise pbl.engine.PBLException(self, e.msg)
artists = results['artists']
items = artists['items']
for item in items:
artist_id = item['id']
after = artist_id
try:
results = get_spotify().artist_top_tracks(artist_id)
except spotipy.SpotifyException as e:
raise pbl.engine.PBLException(self, e.msg)
for track in results['tracks'][:self.num_tracks]:
self.buffer.append(track['id'])
spotify_plugs._add_track(self.name, track)
if len(items) < limit:
break
except spotipy.SpotifyException as e:
raise pbl.engine.PBLException(self, e.msg)
if len(self.buffer) > 0:
return self.buffer.pop(0)
else:
return None
class MySavedAlbums(object):
''' A PBL Source that the tracks from albums saved
by the current user
'''
def __init__(self):
self.name = 'My Saved Albums'
self.buffer = None
def next_track(self):
if self.buffer == None:
self.buffer = []
sp = get_spotify()
limit = 50
total = limit
offset = 0
while offset < total:
try:
results = get_spotify().current_user_saved_albums(limit = limit, offset = offset)
# print 'cusa', self.name, limit, offset, results['limit'], results['offset'], results['total']
except spotipy.SpotifyException as e:
# print 'woah'
raise pbl.engine.PBLException(self, e.msg)
items = results['items']
#print json.dumps(results, indent=4)
#break
for item in items:
album = item['album']
for track in album['tracks']['items']:
self.buffer.append(track['id'])
spotify_plugs._add_track(self.name, track)
offset += limit
total = results['total']
# print 'interim', self.name, len(self.buffer), offset, total
if results['next'] == None:
break
# print 'final', self.name, len(self.buffer), offset, total
if len(self.buffer) > 0:
tid = self.buffer.pop(0)
# print 'ret', self.name, tid
return tid
else:
# print 'ret', self.name, 'empty'
return None
class DatedPlaylistSource(object):
'''
A PBL source that generates a stream of tracks from the given Spotify
playlist with tracks potentially ordered and filtered by the date they
were added to the playlist. If only a name is provided, the playlist
will be searched for. Search success can be improved if the owner of
the playlist is also provided.
:param name: the name of the playlist
:param uri: the uri of the playlist
:param user: the owner of the playlist
:param order_by_date_added: if true, tracks are ordered by the date they
were added to the playlist
:param tracks_added_since: if not None, only tracks added after this
date are returned
:param tracks_added_before: if not None, only tracks added before this
date are returned
'''
def __init__(self, name, uri=None, user=None,
order_by_date_added=False,
tracks_added_since=None,
tracks_added_before=None):
self.name = name
self.uri = spotify_plugs.normalize_uri(uri)
self.user = user
self.order_by_date_added = order_by_date_added
self.tracks_added_before = tracks_added_before
self.tracks_added_since = tracks_added_since
self.next_offset = 0
self.limit = 100
self.tracks = []
self.total = 1
self.cur_index = 0
self.track_count = 0
def _get_uri_from_name(self, name):
results = get_spotify().search(q=name, type='playlist')
if len(results['playlists']['items']) > 0:
return results['playlists']['items'][0]['uri']
else:
return None
def _get_uri_from_name_and_user(self, name, user):
results = get_spotify().user_playlists(user)
while results:
for playlist in results['items']:
if playlist['name'].lower() == name.lower():
return playlist['uri']
if results['next']:
results = get_spotify().next(results)
else:
results = None
return None
def _parse_date(self, sdate):
try:
date = datetime.datetime.strptime(sdate, "%Y-%m-%dT%H:%M:%SZ")
return int(date.strftime("%s"))
except ValueError:
return -1
except:
return -1
def _get_more_tracks(self):
_,_,user,_,playlist_id = self.uri.split(':')
try:
results = get_spotify().user_playlist_tracks(user, playlist_id,
limit=self.limit, offset=self.next_offset)
except spotipy.SpotifyException as e:
raise engine.PBLException(self, e.msg)
self.total = results['total']
for item in results['items']:
self.track_count += 1
good_track = True
ts = self._parse_date(item['added_at'])
if self.tracks_added_before >= 0 and ts >= 0 and ts > self.tracks_added_before:
good_track = False
if self.tracks_added_since >=0 and ts >=0 and ts < self.tracks_added_since:
good_track = False
track = item['track']
if good_track and ts >= 0 and track and 'id' in track:
self.tracks.append( (track['id'], ts) )
spotify_plugs._add_track(self.name, track)
self.next_offset += self.limit
def _get_all_tracks(self):
while self.track_count < self.total:
self._get_more_tracks()
def order_tracks_by_date_added(self):
self.tracks.sort(key=lambda t:t[1])
def next_track(self):
if self.uri == None:
if self.user:
self.uri = self._get_uri_from_name_and_user(self.name, self.user)
else:
self.uri = self._get_uri_from_name(self.name)
if not self.uri:
msg = "Can't find playlist named " + self.name
if self.user:
msg += ' for user ' + self.user
raise engine.PBLException(self, msg)
if self.uri and self.cur_index >= len(self.tracks) and self.track_count < self.total:
if self.order_by_date_added:
self._get_all_tracks()
self.order_tracks_by_date_added()
else:
self._get_more_tracks()
if self.cur_index < len(self.tracks):
track, date = self.tracks[self.cur_index]
self.cur_index += 1
return track
else:
return None
class RelativeDatedPlaylistSource(object):
'''
A PBL source that generates a stream of tracks from the given Spotify
playlist with tracks potentially ordered and filtered by the relative
date they were added to the playlist. If only a name is provided, the playlist
will be searched for. Search success can be improved if the owner of
the playlist is also provided.
:param name: the name of the playlist
:param uri: the uri of the playlist
:param user: the owner of the playlist
:param order_by_date_added: if true, tracks are ordered by the date they were added to the playlist
:param tracks_added_since: if not None, only tracks added after this
relative time (given in seconds in the past from now)
:param tracks_added_before: if not None, only tracks added before this
relative time (given in seconds in the past from now)
'''
def __init__(self, name, uri=None, user=None,
order_by_date_added=False,
tracks_added_since=None,
tracks_added_before=None):
self.name = name
self.uri = spotify_plugs.normalize_uri(uri)
self.user = user
self.order_by_date_added = order_by_date_added
if tracks_added_before != None:
delta_tracks_added_before = datetime.timedelta(seconds=abs(tracks_added_before))
self.tracks_added_before = date_to_epoch(now() - delta_tracks_added_before)
else:
self.tracks_added_before = -1
if tracks_added_since != None:
delta_tracks_added_since = datetime.timedelta(seconds=abs(tracks_added_since))
self.tracks_added_since = date_to_epoch(now() - delta_tracks_added_since)
else:
self.tracks_added_since = -1
self.next_offset = 0
self.limit = 100
self.tracks = []
self.total = 1
self.cur_index = 0
self.track_count = 0
def _get_uri_from_name(self, name):
results = get_spotify().search(q=name, type='playlist')
if len(results['playlists']['items']) > 0:
return results['playlists']['items'][0]['uri']
else:
return None
def _get_uri_from_name_and_user(self, name, user):
results = get_spotify().user_playlists(user)
while results:
for playlist in results['items']:
if playlist['name'].lower() == name.lower():
return playlist['uri']
if results['next']:
results = get_spotify().next(results)
else:
results = None
return None
def _parse_date(self, sdate):
try:
date = datetime.datetime.strptime(sdate, "%Y-%m-%dT%H:%M:%SZ")
return int(date.strftime("%s"))
except ValueError:
return -1
except:
return -1
def _get_more_tracks(self):
_,_,user,_,playlist_id = self.uri.split(':')
try:
results = get_spotify().user_playlist_tracks(user, playlist_id,
limit=self.limit, offset=self.next_offset)
except spotipy.SpotifyException as e:
raise engine.PBLException(self, e.msg)
self.total = results['total']
for item in results['items']:
self.track_count += 1
good_track = True
ts = self._parse_date(item['added_at'])
if self.tracks_added_before >= 0 and ts >= 0 and ts > self.tracks_added_before:
good_track = False
if self.tracks_added_since >=0 and ts >=0 and ts < self.tracks_added_since:
good_track = False
track = item['track']
if good_track and ts >= 0 and track and 'id' in track:
self.tracks.append( (track['id'], ts) )
spotify_plugs._add_track(self.name, track)
self.next_offset += self.limit
def _get_all_tracks(self):
while self.track_count < self.total:
self._get_more_tracks()
def order_tracks_by_date_added(self):
self.tracks.sort(key=lambda t:t[1])
def next_track(self):
if self.uri == None:
if self.user:
self.uri = self._get_uri_from_name_and_user(self.name, self.user)
else:
self.uri = self._get_uri_from_name(self.name)
if not self.uri:
msg = "Can't find playlist named " + self.name
if self.user:
msg += ' for user ' + self.user
raise engine.PBLException(self, msg)
if self.uri and self.cur_index >= len(self.tracks) and self.track_count < self.total:
if self.order_by_date_added:
self._get_all_tracks()
self.order_tracks_by_date_added()
else:
self._get_more_tracks()
if self.cur_index < len(self.tracks):
track, date = self.tracks[self.cur_index]
self.cur_index += 1
return track
else:
return None
class MixIn(object):
'''
A PBL Filter that mixes two input streams based upon a small
set of rules
'''
def __init__(self, true_source, false_source,
ntracks=1, nskips=1, initial_skip = 1, fail_fast = True):
'''
params:
* true_source
* false_source
'''
self.name = 'mixing ' + true_source.name + ' with ' + \
false_source.name
self.true_source = true_source
self.false_source = false_source
self.initial_offset = initial_skip
self.ntracks = ntracks # false tracks in a row
self.nskips = nskips # true tracks in a row
self.fail_fast = fail_fast
self.which = 0
def next_track(self):
if self.which < self.initial_offset:
true_count = self.initial_offset
else:
true_count = self.nskips
false_count = self.ntracks
total_tracks_in_cycle = true_count + false_count
which_in_cycle = self.which % total_tracks_in_cycle
use_first = which_in_cycle < true_count
if use_first:
next_source = self.true_source
other_source = self.false_source
else:
next_source = self.false_source
other_source = self.true_source
track = next_source.next_track()
if not track:
if not self.fail_fast:
track = other_source.next_track()
self.which += 1
return track
class SeparateArtists(object):
''' A PBL filter that reorders the input tracks to maximize
the separation between artists
'''
def __init__(self, source):
self.name = 'SeparateArtists'