-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathuser.py
More file actions
executable file
·810 lines (717 loc) · 31.1 KB
/
Copy pathuser.py
File metadata and controls
executable file
·810 lines (717 loc) · 31.1 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
#!/usr/bin/env python
__author__ = "Abhinav Sarkar <abhinav@abhinavsarkar.net>"
__version__ = "0.2"
__license__ = "GNU Lesser General Public License"
__package__ = "lastfm"
from lastfm.base import LastfmBase
from lastfm.mixin import chartable, mixin
import lastfm.playlist
from lastfm.decorators import (
cached_property, top_property, authentication_required, depaginate)
@chartable('album', 'artist', 'track', 'tag')
@mixin("crawlable", "shoutable", "cacheable", "property_adder")
class User(LastfmBase):
"""A class representing an user."""
class Meta(object):
properties = ["name", "real_name",
"url", "image", "stats"]
def init(self, api, **kwargs):
if not isinstance(api, Api):
raise InvalidParametersError("api reference must be supplied as an argument")
self._api = api
super(User, self).init(**kwargs)
self._stats = hasattr(self, "_stats") and Stats(
subject = self,
match = self._stats.match,
weight = self._stats.weight,
playcount = self._stats.playcount
) or None
self._library = User.Library(api, self)
@property
@authentication_required
def language(self):
"""lang for the user"""
return self._language
@property
@authentication_required
def country(self):
"""country for the user"""
return self._country
@property
@authentication_required
def age(self):
"""age for the user"""
return self._age
@property
@authentication_required
def gender(self):
"""stats for the user"""
return self._gender
@property
@authentication_required
def subscriber(self):
"""is the user a subscriber"""
return self._subscriber
@property
def authenticated(self):
"""is the user authenticated"""
try:
auth_user = self._api.get_authenticated_user()
return auth_user == self
except AuthenticationFailedError:
return False
@cached_property
def events(self):
params = self._default_params({'method': 'user.getEvents'})
data = self._api._fetch_data(params).find('events')
return [
Event.create_from_data(self._api, e)
for e in data.findall('event')
]
@depaginate
def get_past_events(self, limit = None, page = None):
params = self._default_params({'method': 'user.getPastEvents'})
if limit is not None:
params.update({'limit': limit})
if page is not None:
params.update({'page': page})
data = self._api._fetch_data(params).find('events')
total_pages = int(data.attrib['totalPages'])
yield total_pages
for e in data.findall('event'):
yield Event.create_from_data(self._api, e)
@cached_property
def past_events(self):
return self.get_past_events()
@authentication_required
@depaginate
def get_recommended_events(self, limit = None, page = None):
params = {'method': 'user.getRecommendedEvents'}
if limit is not None:
params.update({'limit': limit})
if page is not None:
params.update({'page': page})
data = self._api._fetch_data(params, sign = True, session = True).find('events')
total_pages = int(data.attrib['totalPages'])
yield total_pages
for e in data.findall('event'):
yield Event.create_from_data(self._api, e)
@cached_property
def recommended_events(self):
return self.get_recommended_events()
def get_friends(self,
limit = None):
params = self._default_params({'method': 'user.getFriends'})
if limit is not None:
params.update({'limit': limit})
data = self._api._fetch_data(params).find('friends')
return [
User(
self._api,
subject = self,
name = u.findtext('name'),
real_name = u.findtext('realname'),
image = dict([(i.get('size'), i.text) for i in u.findall('image')]),
url = u.findtext('url'),
)
for u in data.findall('user')
]
@cached_property
def friends(self):
"""friends of the user"""
return self.get_friends()
def get_neighbours(self, limit = None):
params = self._default_params({'method': 'user.getNeighbours'})
if limit is not None:
params.update({'limit': limit})
data = self._api._fetch_data(params).find('neighbours')
return [
User(
self._api,
subject = self,
name = u.findtext('name'),
real_name = u.findtext('realname'),
image = {'medium': u.findtext('image')},
url = u.findtext('url'),
stats = Stats(
subject = u.findtext('name'),
match = u.findtext('match') and float(u.findtext('match')),
),
)
for u in data.findall('user')
]
@cached_property
def neighbours(self):
"""neighbours of the user"""
return self.get_neighbours()
@top_property("neighbours")
def nearest_neighbour(self):
"""nearest neighbour of the user"""
pass
@cached_property
def playlists(self):
"""playlists of the user"""
params = self._default_params({'method': 'user.getPlaylists'})
data = self._api._fetch_data(params).find('playlists')
return [
User.Playlist(
self._api,
id = int(p.findtext('id')),
title = p.findtext('title'),
date = datetime(*(
time.strptime(
p.findtext('date').strip(),
'%Y-%m-%dT%H:%M:%S'
)[0:6])
),
size = int(p.findtext('size')),
creator = self
)
for p in data.findall('playlist')
]
@authentication_required
def create_playlist(self, title, description = None):
params = {'method': 'playlist.create',
'title': title}
if description is not None:
params['description'] = description
self._api._post_data(params)
self._playlists = None
@cached_property
def loved_tracks(self):
params = self._default_params({'method': 'user.getLovedTracks'})
data = self._api._fetch_data(params).find('lovedtracks')
return [
Track(
self._api,
subject = self,
name = t.findtext('name'),
artist = Artist(
self._api,
subject = self,
name = t.findtext('artist/name'),
mbid = t.findtext('artist/mbid'),
url = t.findtext('artist/url'),
),
mbid = t.findtext('mbid'),
image = dict([(i.get('size'), i.text) for i in t.findall('image')]),
loved_on = datetime(*(
time.strptime(
t.findtext('date').strip(),
'%d %b %Y, %H:%M'
)[0:6])
)
)
for t in data.findall('track')
]
@depaginate
def get_recent_tracks(self, limit = None, timefrom = None, timeto =None, page = None):
params = self._default_params({'method': 'user.getRecentTracks'})
if limit is not None:
params.update({'limit': limit})
if timefrom is not None:
params.update({'from' : timefrom})
if timeto is not None:
params.update({'to' : timeto})
if page is not None:
params.update({'page': page})
data = self._api._fetch_data(params, no_cache = True).find('recenttracks')
total_pages = int(data.attrib['totalPages'])
yield total_pages
for t in data.findall('track'):
track = Track(
self._api,
subject = self,
name = t.findtext('name'),
artist = Artist(
self._api,
subject = self,
name = t.findtext('artist'),
mbid = t.find('artist').attrib['mbid'],
),
album = Album(
self._api,
subject = self,
name = t.findtext('album'),
artist = Artist(
self._api,
subject = self,
name = t.findtext('artist'),
mbid = t.find('artist').attrib['mbid'],
),
mbid = t.find('album').attrib['mbid'],
),
mbid = t.findtext('mbid'),
streamable = (t.findtext('streamable') == '1'),
url = t.findtext('url'),
image = dict([(i.get('size'), i.text) for i in t.findall('image')]),
played_on = datetime(*(
time.strptime(
t.findtext('date').strip(),
'%d %b %Y, %H:%M'
)[0:6])
) if t.findtext('date') else datetime(*datetime.now().timetuple()[0:6]),
bypass_registry=True
)
if 'nowplaying' in t.attrib and t.attrib['nowplaying'] == 'true':
self._now_playing = track
yield track
@property
def recent_tracks(self):
"""recent tracks played by the user"""
return self.get_recent_tracks()
@property
def now_playing(self):
if not hasattr(self, "_now_playing"):
self._now_playing = None
self.get_recent_tracks()
return self._now_playing
#@top_property("recent_tracks")
@property
def most_recent_track(self):
"""most recent track played by the user"""
return self.recent_tracks[0]
def get_top_albums(self, period = None, page = None):
params = self._default_params({'method': 'user.getTopAlbums'})
if period is not None:
params.update({'period': period})
if page is not None:
params.update({'page': page})
data = self._api._fetch_data(params).find('topalbums')
return [
Album(
self._api,
subject = self,
name = a.findtext('name'),
artist = Artist(
self._api,
subject = self,
name = a.findtext('artist/name'),
mbid = a.findtext('artist/mbid'),
url = a.findtext('artist/url'),
),
mbid = a.findtext('mbid'),
url = a.findtext('url'),
image = dict([(i.get('size'), i.text) for i in a.findall('image')]),
stats = Stats(
subject = a.findtext('name'),
playcount = a.findtext('playcount').strip() and int(a.findtext('playcount')),
rank = a.attrib['rank'].strip() and int(a.attrib['rank'])
)
)
for a in data.findall('album')
]
@cached_property
def top_albums(self):
"""overall top albums of the user"""
return self.get_top_albums()
@top_property("top_albums")
def top_album(self):
"""overall top most album of the user"""
pass
def get_top_artists(self, period = None):
params = self._default_params({'method': 'user.getTopArtists'})
if period is not None:
params.update({'period': period})
data = self._api._fetch_data(params).find('topartists')
return [
Artist(
self._api,
subject = self,
name = a.findtext('name'),
mbid = a.findtext('mbid'),
stats = Stats(
subject = a.findtext('name'),
rank = a.attrib['rank'].strip() and int(a.attrib['rank']) or None,
playcount = a.findtext('playcount').strip() and int(a.findtext('playcount')) or None
),
url = a.findtext('url'),
streamable = (a.findtext('streamable') == "1"),
image = dict([(i.get('size'), i.text) for i in a.findall('image')]),
)
for a in data.findall('artist')
]
@cached_property
def top_artists(self):
"""top artists of the user"""
return self.get_top_artists()
@top_property("top_artists")
def top_artist(self):
"""top artist of the user"""
pass
@cached_property
@authentication_required
@depaginate
def recommended_artists(self, page = None):
params = {'method': 'user.getRecommendedArtists'}
if page is not None:
params.update({'page': page})
data = self._api._fetch_data(params, sign = True, session = True).find('recommendations')
total_pages = int(data.attrib['totalPages'])
yield total_pages
for a in data.findall('artist'):
yield Artist(
self._api,
name = a.findtext('name'),
mbid = a.findtext('mbid'),
url = a.findtext('url'),
streamable = (a.findtext('streamable') == "1"),
image = dict([(i.get('size'), i.text) for i in a.findall('image')]),
)
def get_top_tracks(self, period = None):
params = self._default_params({'method': 'user.getTopTracks'})
if period is not None:
params.update({'period': period})
data = self._api._fetch_data(params).find('toptracks')
return [
Track(
self._api,
subject = self,
name = t.findtext('name'),
artist = Artist(
self._api,
subject = self,
name = t.findtext('artist/name'),
mbid = t.findtext('artist/mbid'),
url = t.findtext('artist/url'),
),
mbid = t.findtext('mbid'),
stats = Stats(
subject = t.findtext('name'),
rank = t.attrib['rank'].strip() and int(t.attrib['rank']) or None,
playcount = t.findtext('playcount') and int(t.findtext('playcount')) or None
),
streamable = (t.findtext('streamable') == '1'),
full_track = (t.find('streamable').attrib['fulltrack'] == '1'),
image = dict([(i.get('size'), i.text) for i in t.findall('image')]),
)
for t in data.findall('track')
]
@cached_property
def top_tracks(self):
"""top tracks of the user"""
return self.get_top_tracks()
@top_property("top_tracks")
def top_track(self):
"""top track of the user"""
pass
def get_top_tags(self, limit = None):
params = self._default_params({'method': 'user.getTopTags'})
if limit is not None:
params.update({'limit': limit})
data = self._api._fetch_data(params).find('toptags')
return [
Tag(
self._api,
subject = self,
name = t.findtext('name'),
url = t.findtext('url'),
stats = Stats(
subject = t.findtext('name'),
count = int(t.findtext('count'))
)
)
for t in data.findall('tag')
]
@cached_property
def top_tags(self):
"""top tags of the user"""
return self.get_top_tags()
@top_property("top_tags")
def top_tag(self):
"""top tag of the user"""
pass
def compare(self, other, limit = None):
if isinstance(other, User):
other = other.name
return Tasteometer.compare(self._api,
'user', 'user',
self.name, other,
limit)
@property
def library(self):
return self._library
@staticmethod
def get_info(api, name):
data = api._fetch_data({'method' : 'user.getInfo', 'user' : name}).find('user')
user = User(
api,
name = data.findtext('name'),
real_name = data.findtext('realname'),
image = dict([(i.get('size'), i.text) for i in data.findall('image')]),
url = data.findtext('url'),
)
user._language = data.findtext('lang')
if data.findtext('country'):
user._country = Country(api, name = Country.ISO_CODES[data.findtext('country')])
if data.findtext('age'):
user._age = int(data.findtext('age'))
user._gender = data.findtext('gender')
user._subscriber = (data.findtext('subscriber') == "1")
user._stats = Stats(subject = user, playcount = data.findtext('playcount'))
return user
@staticmethod
def get_authenticated_user(api):
data = api._fetch_data({'method': 'user.getInfo'}, sign = True, session = True).find('user')
user = User(
api,
name = data.findtext('name'),
image = dict([(i.get('size'), i.text) for i in data.findall('image')]),
url = data.findtext('url'),
)
user._language = data.findtext('lang')
user._country = Country(api, name = Country.ISO_CODES[data.findtext('country')])
user._age = int(data.findtext('age'))
user._gender = data.findtext('gender')
user._subscriber = (data.findtext('subscriber') == "1")
user._stats = Stats(subject = user, playcount = data.findtext('playcount'))
return user
@staticmethod
def _get_all(seed_user):
return (seed_user, ['name'],
lambda api, hsh: User(api, **hsh).neighbours)
def _default_params(self, extra_params = None):
if not self.name:
raise InvalidParametersError("user has to be provided.")
params = {'user': self.name}
if extra_params is not None:
params.update(extra_params)
return params
@staticmethod
def _hash_func(*args, **kwds):
try:
return hash(kwds['name'])
except KeyError:
raise InvalidParametersError("name has to be provided for hashing")
def __hash__(self):
return self.__class__._hash_func(name = self.name)
def __eq__(self, other):
return self.name == other.name
def __lt__(self, other):
return self.name < other.name
def __repr__(self):
return "<lastfm.User: %s>" % self.name
@mixin("property_adder")
class Playlist(lastfm.playlist.Playlist):
"""A class representing a playlist belonging to the user."""
class Meta(object):
properties = ["id", "title", "date", "size", "creator"]
def init(self, api, id, title, date, size, creator):
super(User.Playlist, self).init(api, "lastfm://playlist/%s" % id)
self._id = id
self._title = title
self._date = date
self._size = size
self._creator = creator
@property
def user(self):
return self._creator
@authentication_required
def add_track(self, track, artist = None):
params = {'method': 'playlist.addTrack', 'playlistID': self.id}
if isinstance(track, Track):
params['artist'] = track.artist.name
params['track'] = track.name
else:
if artist is None:
track = self._api.search_track(track)[0]
params['artist'] = track.artist.name
params['track'] = track.name
else:
params['artist'] = isinstance(artist, Artist) and artist.name or artist
params['track'] = track
self._api._post_data(params)
self._data = None
@staticmethod
def _hash_func(*args, **kwds):
try:
return hash(kwds['id'])
except KeyError:
raise InvalidParametersError("id has to be provided for hashing")
def __hash__(self):
return self.__class__._hash_func(id = self.id)
def __repr__(self):
return "<lastfm.User.Playlist: %s>" % self.title
class Library(object):
"""A class representing the music library of the user."""
def __init__(self, api, user):
self._api = api
self._user = user
@property
def user(self):
return self._user
@depaginate
def get_albums(self, limit = None, page = None):
params = self._default_params({'method': 'library.getAlbums'})
if limit is not None:
params.update({'limit': limit})
if page is not None:
params.update({'page': page})
try:
data = self._api._fetch_data(params).find('albums')
total_pages = int(data.attrib['totalPages'])
yield total_pages
for a in data.findall('album'):
yield Album(
self._api,
subject = self,
name = a.findtext('name'),
artist = Artist(
self._api,
subject = self,
name = a.findtext('artist/name'),
mbid = a.findtext('artist/mbid'),
url = a.findtext('artist/url'),
),
mbid = a.findtext('mbid'),
url = a.findtext('url'),
image = dict([(i.get('size'), i.text) for i in a.findall('image')]),
stats = Stats(
subject = a.findtext('name'),
playcount = int(a.findtext('playcount')),
)
)
except LastfmError:
yield None
@cached_property
def albums(self):
return self.get_albums()
@authentication_required
def add_album(self, album, artist = None):
params = {'method': 'library.addAlbum'}
if isinstance(album, Album):
params['artist'] = album.artist.name
params['album'] = album.name
else:
if artist is None:
album = self._api.search_album(album)[0]
params['artist'] = album.artist.name
params['album'] = album.name
else:
params['artist'] = isinstance(artist, Artist) and artist.name or artist
params['album'] = album
self._api._post_data(params)
self._albums = None
@depaginate
def get_artists(self, limit = None, page = None):
params = self._default_params({'method': 'library.getArtists'})
if limit is not None:
params.update({'limit': limit})
if page is not None:
params.update({'page': page})
try:
data = self._api._fetch_data(params).find('artists')
total_pages = int(data.attrib['totalPages'])
yield total_pages
for a in data.findall('artist'):
yield Artist(
self._api,
subject = self,
name = a.findtext('name'),
mbid = a.findtext('mbid'),
stats = Stats(
subject = a.findtext('name'),
playcount = a.findtext('playcount') and int(a.findtext('playcount')) or None,
tagcount = a.findtext('tagcount') and int(a.findtext('tagcount')) or None
),
url = a.findtext('url'),
streamable = (a.findtext('streamable') == "1"),
image = dict([(i.get('size'), i.text) for i in a.findall('image')]),
)
except LastfmError:
yield None
@cached_property
def artists(self):
return self.get_artists()
@authentication_required
def add_artist(self, artist):
params = {'method': 'library.addArtist'}
if isinstance(artist, Artist):
params['artist'] = artist.name
else:
params['artist'] = artist
self._api._post_data(params)
self._artists = None
@depaginate
def get_tracks(self, limit = None, page = None):
params = self._default_params({'method': 'library.getTracks'})
if limit is not None:
params.update({'limit': limit})
if page is not None:
params.update({'page': page})
try:
data = self._api._fetch_data(params).find('tracks')
total_pages = int(data.attrib['totalPages'])
yield total_pages
for t in data.findall('track'):
yield Track(
self._api,
subject = self,
name = t.findtext('name'),
artist = Artist(
self._api,
subject = self,
name = t.findtext('artist/name'),
mbid = t.findtext('artist/mbid'),
url = t.findtext('artist/url'),
),
mbid = t.findtext('mbid'),
stats = Stats(
subject = t.findtext('name'),
playcount = t.findtext('playcount') and int(t.findtext('playcount')) or None,
tagcount = t.findtext('tagcount') and int(t.findtext('tagcount')) or None
),
streamable = (t.findtext('streamable') == '1'),
full_track = (t.find('streamable').attrib['fulltrack'] == '1'),
image = dict([(i.get('size'), i.text) for i in t.findall('image')]),
)
except LastfmError:
yield None
@cached_property
def tracks(self):
return self.get_tracks()
@authentication_required
def add_track(self, track, artist = None):
params = {'method': 'library.addTrack'}
if isinstance(track, Track):
params['artist'] = track.artist.name
params['track'] = track.name
else:
if artist is None:
track = self._api.search_track(track)[0]
params['artist'] = track.artist.name
params['track'] = track.name
else:
params['artist'] = isinstance(artist, Artist) and artist.name or artist
params['track'] = track
self._api._post_data(params)
self._tracks = None
def _default_params(self, extra_params = None):
if not self.user.name:
raise InvalidParametersError("user has to be provided.")
params = {'user': self.user.name}
if extra_params is not None:
params.update(extra_params)
return params
@staticmethod
def _hash_func(*args, **kwds):
try:
return hash(kwds['user'])
except KeyError:
raise InvalidParametersError("user has to be provided for hashing")
def __hash__(self):
return self.__class__._hash_func(user = self.user)
def __repr__(self):
return "<lastfm.User.Library: for user '%s'>" % self.user.name
from datetime import datetime
import time
from lastfm.api import Api
from lastfm.artist import Artist
from lastfm.album import Album
from lastfm.error import LastfmError, InvalidParametersError, AuthenticationFailedError
from lastfm.event import Event
from lastfm.geo import Country
from lastfm.stats import Stats
from lastfm.tag import Tag
from lastfm.tasteometer import Tasteometer
from lastfm.track import Track