Daniel@0: # -*- coding: utf-8 -*- Daniel@0: # Daniel@0: # pylast - A Python interface to Last.fm (and other API compatible social networks) Daniel@0: # Daniel@0: # Copyright 2008-2010 Amr Hassan Daniel@0: # Daniel@0: # Licensed under the Apache License, Version 2.0 (the "License"); Daniel@0: # you may not use this file except in compliance with the License. Daniel@0: # You may obtain a copy of the License at Daniel@0: # Daniel@0: # http://www.apache.org/licenses/LICENSE-2.0 Daniel@0: # Daniel@0: # Unless required by applicable law or agreed to in writing, software Daniel@0: # distributed under the License is distributed on an "AS IS" BASIS, Daniel@0: # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Daniel@0: # See the License for the specific language governing permissions and Daniel@0: # limitations under the License. Daniel@0: # Daniel@0: # http://code.google.com/p/pylast/ Daniel@0: Daniel@0: __version__ = '0.5' Daniel@0: __author__ = 'Amr Hassan' Daniel@0: __copyright__ = "Copyright (C) 2008-2010 Amr Hassan" Daniel@0: __license__ = "apache2" Daniel@0: __email__ = 'amr.hassan@gmail.com' Daniel@0: Daniel@0: import hashlib Daniel@0: from xml.dom import minidom Daniel@0: import xml.dom Daniel@0: import time Daniel@0: import shelve Daniel@0: import tempfile Daniel@0: import sys Daniel@0: import collections Daniel@0: import warnings Daniel@0: Daniel@0: def _deprecation_warning(message): Daniel@0: warnings.warn(message, DeprecationWarning) Daniel@0: Daniel@0: if sys.version_info[0] == 3: Daniel@0: from http.client import HTTPConnection Daniel@0: import html.entities as htmlentitydefs Daniel@0: from urllib.parse import splithost as url_split_host Daniel@0: from urllib.parse import quote_plus as url_quote_plus Daniel@0: Daniel@0: unichr = chr Daniel@0: Daniel@0: elif sys.version_info[0] == 2: Daniel@0: from httplib import HTTPConnection Daniel@0: import htmlentitydefs Daniel@0: from urllib import splithost as url_split_host Daniel@0: from urllib import quote_plus as url_quote_plus Daniel@0: Daniel@0: STATUS_INVALID_SERVICE = 2 Daniel@0: STATUS_INVALID_METHOD = 3 Daniel@0: STATUS_AUTH_FAILED = 4 Daniel@0: STATUS_INVALID_FORMAT = 5 Daniel@0: STATUS_INVALID_PARAMS = 6 Daniel@0: STATUS_INVALID_RESOURCE = 7 Daniel@0: STATUS_TOKEN_ERROR = 8 Daniel@0: STATUS_INVALID_SK = 9 Daniel@0: STATUS_INVALID_API_KEY = 10 Daniel@0: STATUS_OFFLINE = 11 Daniel@0: STATUS_SUBSCRIBERS_ONLY = 12 Daniel@0: STATUS_INVALID_SIGNATURE = 13 Daniel@0: STATUS_TOKEN_UNAUTHORIZED = 14 Daniel@0: STATUS_TOKEN_EXPIRED = 15 Daniel@0: Daniel@0: EVENT_ATTENDING = '0' Daniel@0: EVENT_MAYBE_ATTENDING = '1' Daniel@0: EVENT_NOT_ATTENDING = '2' Daniel@0: Daniel@0: PERIOD_OVERALL = 'overall' Daniel@0: PERIOD_7DAYS = "7day" Daniel@0: PERIOD_3MONTHS = '3month' Daniel@0: PERIOD_6MONTHS = '6month' Daniel@0: PERIOD_12MONTHS = '12month' Daniel@0: Daniel@0: DOMAIN_ENGLISH = 0 Daniel@0: DOMAIN_GERMAN = 1 Daniel@0: DOMAIN_SPANISH = 2 Daniel@0: DOMAIN_FRENCH = 3 Daniel@0: DOMAIN_ITALIAN = 4 Daniel@0: DOMAIN_POLISH = 5 Daniel@0: DOMAIN_PORTUGUESE = 6 Daniel@0: DOMAIN_SWEDISH = 7 Daniel@0: DOMAIN_TURKISH = 8 Daniel@0: DOMAIN_RUSSIAN = 9 Daniel@0: DOMAIN_JAPANESE = 10 Daniel@0: DOMAIN_CHINESE = 11 Daniel@0: Daniel@0: COVER_SMALL = 0 Daniel@0: COVER_MEDIUM = 1 Daniel@0: COVER_LARGE = 2 Daniel@0: COVER_EXTRA_LARGE = 3 Daniel@0: COVER_MEGA = 4 Daniel@0: Daniel@0: IMAGES_ORDER_POPULARITY = "popularity" Daniel@0: IMAGES_ORDER_DATE = "dateadded" Daniel@0: Daniel@0: Daniel@0: USER_MALE = 'Male' Daniel@0: USER_FEMALE = 'Female' Daniel@0: Daniel@0: SCROBBLE_SOURCE_USER = "P" Daniel@0: SCROBBLE_SOURCE_NON_PERSONALIZED_BROADCAST = "R" Daniel@0: SCROBBLE_SOURCE_PERSONALIZED_BROADCAST = "E" Daniel@0: SCROBBLE_SOURCE_LASTFM = "L" Daniel@0: SCROBBLE_SOURCE_UNKNOWN = "U" Daniel@0: Daniel@0: SCROBBLE_MODE_PLAYED = "" Daniel@0: SCROBBLE_MODE_LOVED = "L" Daniel@0: SCROBBLE_MODE_BANNED = "B" Daniel@0: SCROBBLE_MODE_SKIPPED = "S" Daniel@0: Daniel@0: class _Network(object): Daniel@0: """ Daniel@0: A music social network website that is Last.fm or one exposing a Last.fm compatible API Daniel@0: """ Daniel@0: Daniel@0: def __init__(self, name, homepage, ws_server, api_key, api_secret, session_key, submission_server, username, password_hash, Daniel@0: domain_names, urls): Daniel@0: """ Daniel@0: name: the name of the network Daniel@0: homepage: the homepage url Daniel@0: ws_server: the url of the webservices server Daniel@0: api_key: a provided API_KEY Daniel@0: api_secret: a provided API_SECRET Daniel@0: session_key: a generated session_key or None Daniel@0: submission_server: the url of the server to which tracks are submitted (scrobbled) Daniel@0: username: a username of a valid user Daniel@0: password_hash: the output of pylast.md5(password) where password is the user's password Daniel@0: domain_names: a dict mapping each DOMAIN_* value to a string domain name Daniel@0: urls: a dict mapping types to urls Daniel@0: Daniel@0: if username and password_hash were provided and not session_key, session_key will be Daniel@0: generated automatically when needed. Daniel@0: Daniel@0: Either a valid session_key or a combination of username and password_hash must be present for scrobbling. Daniel@0: Daniel@0: You should use a preconfigured network object through a get_*_network(...) method instead of creating an object Daniel@0: of this class, unless you know what you're doing. Daniel@0: """ Daniel@0: Daniel@0: self.name = name Daniel@0: self.homepage = homepage Daniel@0: self.ws_server = ws_server Daniel@0: self.api_key = api_key Daniel@0: self.api_secret = api_secret Daniel@0: self.session_key = session_key Daniel@0: self.submission_server = submission_server Daniel@0: self.username = username Daniel@0: self.password_hash = password_hash Daniel@0: self.domain_names = domain_names Daniel@0: self.urls = urls Daniel@0: Daniel@0: self.cache_backend = None Daniel@0: self.proxy_enabled = False Daniel@0: self.proxy = None Daniel@0: self.last_call_time = 0 Daniel@0: Daniel@0: #generate a session_key if necessary Daniel@0: if (self.api_key and self.api_secret) and not self.session_key and (self.username and self.password_hash): Daniel@0: sk_gen = SessionKeyGenerator(self) Daniel@0: self.session_key = sk_gen.get_session_key(self.username, self.password_hash) Daniel@0: Daniel@0: """def __repr__(self): Daniel@0: attributes = ("name", "homepage", "ws_server", "api_key", "api_secret", "session_key", "submission_server", Daniel@0: "username", "password_hash", "domain_names", "urls") Daniel@0: Daniel@0: text = "pylast._Network(%s)" Daniel@0: args = [] Daniel@0: for attr in attributes: Daniel@0: args.append("=".join((attr, repr(getattr(self, attr))))) Daniel@0: Daniel@0: return text % ", ".join(args) Daniel@0: """ Daniel@0: Daniel@0: def __str__(self): Daniel@0: return "The %s Network" %self.name Daniel@0: Daniel@0: def get_artist(self, artist_name): Daniel@0: """ Daniel@0: Return an Artist object Daniel@0: """ Daniel@0: Daniel@0: return Artist(artist_name, self) Daniel@0: Daniel@0: def get_track(self, artist, title): Daniel@0: """ Daniel@0: Return a Track object Daniel@0: """ Daniel@0: Daniel@0: return Track(artist, title, self) Daniel@0: Daniel@0: def get_album(self, artist, title): Daniel@0: """ Daniel@0: Return an Album object Daniel@0: """ Daniel@0: Daniel@0: return Album(artist, title, self) Daniel@0: Daniel@0: def get_authenticated_user(self): Daniel@0: """ Daniel@0: Returns the authenticated user Daniel@0: """ Daniel@0: Daniel@0: return AuthenticatedUser(self) Daniel@0: Daniel@0: def get_country(self, country_name): Daniel@0: """ Daniel@0: Returns a country object Daniel@0: """ Daniel@0: Daniel@0: return Country(country_name, self) Daniel@0: Daniel@0: def get_group(self, name): Daniel@0: """ Daniel@0: Returns a Group object Daniel@0: """ Daniel@0: Daniel@0: return Group(name, self) Daniel@0: Daniel@0: def get_user(self, username): Daniel@0: """ Daniel@0: Returns a user object Daniel@0: """ Daniel@0: Daniel@0: return User(username, self) Daniel@0: Daniel@0: def get_tag(self, name): Daniel@0: """ Daniel@0: Returns a tag object Daniel@0: """ Daniel@0: Daniel@0: return Tag(name, self) Daniel@0: Daniel@0: def get_scrobbler(self, client_id, client_version): Daniel@0: """ Daniel@0: Returns a Scrobbler object used for submitting tracks to the server Daniel@0: Daniel@0: Quote from http://www.last.fm/api/submissions: Daniel@0: ======== Daniel@0: Client identifiers are used to provide a centrally managed database of Daniel@0: the client versions, allowing clients to be banned if they are found to Daniel@0: be behaving undesirably. The client ID is associated with a version Daniel@0: number on the server, however these are only incremented if a client is Daniel@0: banned and do not have to reflect the version of the actual client application. Daniel@0: Daniel@0: During development, clients which have not been allocated an identifier should Daniel@0: use the identifier tst, with a version number of 1.0. Do not distribute code or Daniel@0: client implementations which use this test identifier. Do not use the identifiers Daniel@0: used by other clients. Daniel@0: ========= Daniel@0: Daniel@0: To obtain a new client identifier please contact: Daniel@0: * Last.fm: submissions@last.fm Daniel@0: * # TODO: list others Daniel@0: Daniel@0: ...and provide us with the name of your client and its homepage address. Daniel@0: """ Daniel@0: Daniel@0: _deprecation_warning("Use _Network.scrobble(...), _Network.scrobble_many(...), and Netowrk.update_now_playing(...) instead") Daniel@0: Daniel@0: return Scrobbler(self, client_id, client_version) Daniel@0: Daniel@0: def _get_language_domain(self, domain_language): Daniel@0: """ Daniel@0: Returns the mapped domain name of the network to a DOMAIN_* value Daniel@0: """ Daniel@0: Daniel@0: if domain_language in self.domain_names: Daniel@0: return self.domain_names[domain_language] Daniel@0: Daniel@0: def _get_url(self, domain, type): Daniel@0: return "http://%s/%s" %(self._get_language_domain(domain), self.urls[type]) Daniel@0: Daniel@0: def _get_ws_auth(self): Daniel@0: """ Daniel@0: Returns a (API_KEY, API_SECRET, SESSION_KEY) tuple. Daniel@0: """ Daniel@0: return (self.api_key, self.api_secret, self.session_key) Daniel@0: Daniel@0: def _delay_call(self): Daniel@0: """ Daniel@0: Makes sure that web service calls are at least a second apart Daniel@0: """ Daniel@0: Daniel@0: # delay time in seconds Daniel@0: DELAY_TIME = 1.0 Daniel@0: now = time.time() Daniel@0: Daniel@0: if (now - self.last_call_time) < DELAY_TIME: Daniel@0: time.sleep(1) Daniel@0: Daniel@0: self.last_call_time = now Daniel@0: Daniel@0: def create_new_playlist(self, title, description): Daniel@0: """ Daniel@0: Creates a playlist for the authenticated user and returns it Daniel@0: title: The title of the new playlist. Daniel@0: description: The description of the new playlist. Daniel@0: """ Daniel@0: Daniel@0: params = {} Daniel@0: params['title'] = title Daniel@0: params['description'] = description Daniel@0: Daniel@0: doc = _Request(self, 'playlist.create', params).execute(False) Daniel@0: Daniel@0: e_id = doc.getElementsByTagName("id")[0].firstChild.data Daniel@0: user = doc.getElementsByTagName('playlists')[0].getAttribute('user') Daniel@0: Daniel@0: return Playlist(user, e_id, self) Daniel@0: Daniel@0: def get_top_tags(self, limit=None): Daniel@0: """Returns a sequence of the most used tags as a sequence of TopItem objects.""" Daniel@0: Daniel@0: doc = _Request(self, "tag.getTopTags").execute(True) Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("tag"): Daniel@0: tag = Tag(_extract(node, "name"), self) Daniel@0: weight = _number(_extract(node, "count")) Daniel@0: Daniel@0: seq.append(TopItem(tag, weight)) Daniel@0: Daniel@0: if limit: Daniel@0: seq = seq[:limit] Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def enable_proxy(self, host, port): Daniel@0: """Enable a default web proxy""" Daniel@0: Daniel@0: self.proxy = [host, _number(port)] Daniel@0: self.proxy_enabled = True Daniel@0: Daniel@0: def disable_proxy(self): Daniel@0: """Disable using the web proxy""" Daniel@0: Daniel@0: self.proxy_enabled = False Daniel@0: Daniel@0: def is_proxy_enabled(self): Daniel@0: """Returns True if a web proxy is enabled.""" Daniel@0: Daniel@0: return self.proxy_enabled Daniel@0: Daniel@0: def _get_proxy(self): Daniel@0: """Returns proxy details.""" Daniel@0: Daniel@0: return self.proxy Daniel@0: Daniel@0: def enable_caching(self, file_path = None): Daniel@0: """Enables caching request-wide for all cachable calls. Daniel@0: In choosing the backend used for caching, it will try _SqliteCacheBackend first if Daniel@0: the module sqlite3 is present. If not, it will fallback to _ShelfCacheBackend which uses shelve.Shelf objects. Daniel@0: Daniel@0: * file_path: A file path for the backend storage file. If Daniel@0: None set, a temp file would probably be created, according the backend. Daniel@0: """ Daniel@0: Daniel@0: if not file_path: Daniel@0: file_path = tempfile.mktemp(prefix="pylast_tmp_") Daniel@0: Daniel@0: self.cache_backend = _ShelfCacheBackend(file_path) Daniel@0: Daniel@0: def disable_caching(self): Daniel@0: """Disables all caching features.""" Daniel@0: Daniel@0: self.cache_backend = None Daniel@0: Daniel@0: def is_caching_enabled(self): Daniel@0: """Returns True if caching is enabled.""" Daniel@0: Daniel@0: return not (self.cache_backend == None) Daniel@0: Daniel@0: def _get_cache_backend(self): Daniel@0: Daniel@0: return self.cache_backend Daniel@0: Daniel@0: def search_for_album(self, album_name): Daniel@0: """Searches for an album by its name. Returns a AlbumSearch object. Daniel@0: Use get_next_page() to retreive sequences of results.""" Daniel@0: Daniel@0: return AlbumSearch(album_name, self) Daniel@0: Daniel@0: def search_for_artist(self, artist_name): Daniel@0: """Searches of an artist by its name. Returns a ArtistSearch object. Daniel@0: Use get_next_page() to retreive sequences of results.""" Daniel@0: Daniel@0: return ArtistSearch(artist_name, self) Daniel@0: Daniel@0: def search_for_tag(self, tag_name): Daniel@0: """Searches of a tag by its name. Returns a TagSearch object. Daniel@0: Use get_next_page() to retreive sequences of results.""" Daniel@0: Daniel@0: return TagSearch(tag_name, self) Daniel@0: Daniel@0: def search_for_track(self, artist_name, track_name): Daniel@0: """Searches of a track by its name and its artist. Set artist to an empty string if not available. Daniel@0: Returns a TrackSearch object. Daniel@0: Use get_next_page() to retreive sequences of results.""" Daniel@0: Daniel@0: return TrackSearch(artist_name, track_name, self) Daniel@0: Daniel@0: def search_for_venue(self, venue_name, country_name): Daniel@0: """Searches of a venue by its name and its country. Set country_name to an empty string if not available. Daniel@0: Returns a VenueSearch object. Daniel@0: Use get_next_page() to retreive sequences of results.""" Daniel@0: Daniel@0: return VenueSearch(venue_name, country_name, self) Daniel@0: Daniel@0: def get_track_by_mbid(self, mbid): Daniel@0: """Looks up a track by its MusicBrainz ID""" Daniel@0: Daniel@0: params = {"mbid": mbid} Daniel@0: Daniel@0: doc = _Request(self, "track.getInfo", params).execute(True) Daniel@0: Daniel@0: return Track(_extract(doc, "name", 1), _extract(doc, "name"), self) Daniel@0: Daniel@0: def get_artist_by_mbid(self, mbid): Daniel@0: """Loooks up an artist by its MusicBrainz ID""" Daniel@0: Daniel@0: params = {"mbid": mbid} Daniel@0: Daniel@0: doc = _Request(self, "artist.getInfo", params).execute(True) Daniel@0: Daniel@0: return Artist(_extract(doc, "name"), self) Daniel@0: Daniel@0: def get_album_by_mbid(self, mbid): Daniel@0: """Looks up an album by its MusicBrainz ID""" Daniel@0: Daniel@0: params = {"mbid": mbid} Daniel@0: Daniel@0: doc = _Request(self, "album.getInfo", params).execute(True) Daniel@0: Daniel@0: return Album(_extract(doc, "artist"), _extract(doc, "name"), self) Daniel@0: Daniel@0: def update_now_playing(self, artist, title, album = None, album_artist = None, Daniel@0: duration = None, track_number = None, mbid = None, context = None): Daniel@0: """ Daniel@0: Used to notify Last.fm that a user has started listening to a track. Daniel@0: Daniel@0: Parameters: Daniel@0: artist (Required) : The artist name Daniel@0: title (Required) : The track title Daniel@0: album (Optional) : The album name. Daniel@0: album_artist (Optional) : The album artist - if this differs from the track artist. Daniel@0: duration (Optional) : The length of the track in seconds. Daniel@0: track_number (Optional) : The track number of the track on the album. Daniel@0: mbid (Optional) : The MusicBrainz Track ID. Daniel@0: context (Optional) : Sub-client version (not public, only enabled for certain API keys) Daniel@0: """ Daniel@0: Daniel@0: params = {"track": title, "artist": artist} Daniel@0: Daniel@0: if album: params["album"] = album Daniel@0: if album_artist: params["albumArtist"] = album_artist Daniel@0: if context: params["context"] = context Daniel@0: if track_number: params["trackNumber"] = track_number Daniel@0: if mbid: params["mbid"] = mbid Daniel@0: if duration: params["duration"] = duration Daniel@0: Daniel@0: _Request(self, "track.updateNowPlaying", params).execute() Daniel@0: Daniel@0: def scrobble(self, artist, title, timestamp, album = None, album_artist = None, track_number = None, Daniel@0: duration = None, stream_id = None, context = None, mbid = None): Daniel@0: Daniel@0: """Used to add a track-play to a user's profile. Daniel@0: Daniel@0: Parameters: Daniel@0: artist (Required) : The artist name. Daniel@0: title (Required) : The track name. Daniel@0: timestamp (Required) : The time the track started playing, in UNIX timestamp format (integer number of seconds since 00:00:00, January 1st 1970 UTC). This must be in the UTC time zone. Daniel@0: album (Optional) : The album name. Daniel@0: album_artist (Optional) : The album artist - if this differs from the track artist. Daniel@0: context (Optional) : Sub-client version (not public, only enabled for certain API keys) Daniel@0: stream_id (Optional) : The stream id for this track received from the radio.getPlaylist service. Daniel@0: track_number (Optional) : The track number of the track on the album. Daniel@0: mbid (Optional) : The MusicBrainz Track ID. Daniel@0: duration (Optional) : The length of the track in seconds. Daniel@0: """ Daniel@0: Daniel@0: return self.scrobble_many(({"artist": artist, "title": title, "timestamp": timestamp, "album": album, "album_artist": album_artist, Daniel@0: "track_number": track_number, "duration": duration, "stream_id": stream_id, "context": context, "mbid": mbid},)) Daniel@0: Daniel@0: def scrobble_many(self, tracks): Daniel@0: """ Daniel@0: Used to scrobble a batch of tracks at once. The parameter tracks is a sequence of dicts per Daniel@0: track containing the keyword arguments as if passed to the scrobble() method. Daniel@0: """ Daniel@0: Daniel@0: tracks_to_scrobble = tracks[:50] Daniel@0: if len(tracks) > 50: Daniel@0: remaining_tracks = tracks[50:] Daniel@0: else: Daniel@0: remaining_tracks = None Daniel@0: Daniel@0: params = {} Daniel@0: for i in range(len(tracks_to_scrobble)): Daniel@0: Daniel@0: params["artist[%d]" % i] = tracks_to_scrobble[i]["artist"] Daniel@0: params["track[%d]" % i] = tracks_to_scrobble[i]["title"] Daniel@0: Daniel@0: additional_args = ("timestamp", "album", "album_artist", "context", "stream_id", "track_number", "mbid", "duration") Daniel@0: args_map_to = {"album_artist": "albumArtist", "track_number": "trackNumber", "stream_id": "streamID"} # so friggin lazy Daniel@0: Daniel@0: for arg in additional_args: Daniel@0: Daniel@0: if arg in tracks_to_scrobble[i] and tracks_to_scrobble[i][arg]: Daniel@0: if arg in args_map_to: Daniel@0: maps_to = args_map_to[arg] Daniel@0: else: Daniel@0: maps_to = arg Daniel@0: Daniel@0: params["%s[%d]" %(maps_to, i)] = tracks_to_scrobble[i][arg] Daniel@0: Daniel@0: Daniel@0: _Request(self, "track.scrobble", params).execute() Daniel@0: Daniel@0: if remaining_tracks: Daniel@0: self.scrobble_many(remaining_tracks) Daniel@0: Daniel@0: class LastFMNetwork(_Network): Daniel@0: Daniel@0: """A Last.fm network object Daniel@0: Daniel@0: api_key: a provided API_KEY Daniel@0: api_secret: a provided API_SECRET Daniel@0: session_key: a generated session_key or None Daniel@0: username: a username of a valid user Daniel@0: password_hash: the output of pylast.md5(password) where password is the user's password Daniel@0: Daniel@0: if username and password_hash were provided and not session_key, session_key will be Daniel@0: generated automatically when needed. Daniel@0: Daniel@0: Either a valid session_key or a combination of username and password_hash must be present for scrobbling. Daniel@0: Daniel@0: Most read-only webservices only require an api_key and an api_secret, see about obtaining them from: Daniel@0: http://www.last.fm/api/account Daniel@0: """ Daniel@0: Daniel@0: def __init__(self, api_key="", api_secret="", session_key="", username="", password_hash=""): Daniel@0: _Network.__init__(self, Daniel@0: name = "Last.fm", Daniel@0: homepage = "http://last.fm", Daniel@0: ws_server = ("ws.audioscrobbler.com", "/2.0/"), Daniel@0: api_key = api_key, Daniel@0: api_secret = api_secret, Daniel@0: session_key = session_key, Daniel@0: submission_server = "http://post.audioscrobbler.com:80/", Daniel@0: username = username, Daniel@0: password_hash = password_hash, Daniel@0: domain_names = { Daniel@0: DOMAIN_ENGLISH: 'www.last.fm', Daniel@0: DOMAIN_GERMAN: 'www.lastfm.de', Daniel@0: DOMAIN_SPANISH: 'www.lastfm.es', Daniel@0: DOMAIN_FRENCH: 'www.lastfm.fr', Daniel@0: DOMAIN_ITALIAN: 'www.lastfm.it', Daniel@0: DOMAIN_POLISH: 'www.lastfm.pl', Daniel@0: DOMAIN_PORTUGUESE: 'www.lastfm.com.br', Daniel@0: DOMAIN_SWEDISH: 'www.lastfm.se', Daniel@0: DOMAIN_TURKISH: 'www.lastfm.com.tr', Daniel@0: DOMAIN_RUSSIAN: 'www.lastfm.ru', Daniel@0: DOMAIN_JAPANESE: 'www.lastfm.jp', Daniel@0: DOMAIN_CHINESE: 'cn.last.fm', Daniel@0: }, Daniel@0: urls = { Daniel@0: "album": "music/%(artist)s/%(album)s", Daniel@0: "artist": "music/%(artist)s", Daniel@0: "event": "event/%(id)s", Daniel@0: "country": "place/%(country_name)s", Daniel@0: "playlist": "user/%(user)s/library/playlists/%(appendix)s", Daniel@0: "tag": "tag/%(name)s", Daniel@0: "track": "music/%(artist)s/_/%(title)s", Daniel@0: "group": "group/%(name)s", Daniel@0: "user": "user/%(name)s", Daniel@0: } Daniel@0: ) Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.LastFMNetwork(%s)" %(", ".join(("'%s'" %self.api_key, "'%s'" %self.api_secret, "'%s'" %self.session_key, Daniel@0: "'%s'" %self.username, "'%s'" %self.password_hash))) Daniel@0: Daniel@0: def __str__(self): Daniel@0: return "LastFM Network" Daniel@0: Daniel@0: def get_lastfm_network(api_key="", api_secret="", session_key = "", username = "", password_hash = ""): Daniel@0: """ Daniel@0: Returns a preconfigured _Network object for Last.fm Daniel@0: Daniel@0: api_key: a provided API_KEY Daniel@0: api_secret: a provided API_SECRET Daniel@0: session_key: a generated session_key or None Daniel@0: username: a username of a valid user Daniel@0: password_hash: the output of pylast.md5(password) where password is the user's password Daniel@0: Daniel@0: if username and password_hash were provided and not session_key, session_key will be Daniel@0: generated automatically when needed. Daniel@0: Daniel@0: Either a valid session_key or a combination of username and password_hash must be present for scrobbling. Daniel@0: Daniel@0: Most read-only webservices only require an api_key and an api_secret, see about obtaining them from: Daniel@0: http://www.last.fm/api/account Daniel@0: """ Daniel@0: Daniel@0: _deprecation_warning("Create a LastFMNetwork object instead") Daniel@0: Daniel@0: return LastFMNetwork(api_key, api_secret, session_key, username, password_hash) Daniel@0: Daniel@0: class LibreFMNetwork(_Network): Daniel@0: """ Daniel@0: A preconfigured _Network object for Libre.fm Daniel@0: Daniel@0: api_key: a provided API_KEY Daniel@0: api_secret: a provided API_SECRET Daniel@0: session_key: a generated session_key or None Daniel@0: username: a username of a valid user Daniel@0: password_hash: the output of pylast.md5(password) where password is the user's password Daniel@0: Daniel@0: if username and password_hash were provided and not session_key, session_key will be Daniel@0: generated automatically when needed. Daniel@0: """ Daniel@0: Daniel@0: def __init__(self, api_key="", api_secret="", session_key = "", username = "", password_hash = ""): Daniel@0: Daniel@0: _Network.__init__(self, Daniel@0: name = "Libre.fm", Daniel@0: homepage = "http://alpha.dev.libre.fm", Daniel@0: ws_server = ("alpha.dev.libre.fm", "/2.0/"), Daniel@0: api_key = api_key, Daniel@0: api_secret = api_secret, Daniel@0: session_key = session_key, Daniel@0: submission_server = "http://turtle.libre.fm:80/", Daniel@0: username = username, Daniel@0: password_hash = password_hash, Daniel@0: domain_names = { Daniel@0: DOMAIN_ENGLISH: "alpha.dev.libre.fm", Daniel@0: DOMAIN_GERMAN: "alpha.dev.libre.fm", Daniel@0: DOMAIN_SPANISH: "alpha.dev.libre.fm", Daniel@0: DOMAIN_FRENCH: "alpha.dev.libre.fm", Daniel@0: DOMAIN_ITALIAN: "alpha.dev.libre.fm", Daniel@0: DOMAIN_POLISH: "alpha.dev.libre.fm", Daniel@0: DOMAIN_PORTUGUESE: "alpha.dev.libre.fm", Daniel@0: DOMAIN_SWEDISH: "alpha.dev.libre.fm", Daniel@0: DOMAIN_TURKISH: "alpha.dev.libre.fm", Daniel@0: DOMAIN_RUSSIAN: "alpha.dev.libre.fm", Daniel@0: DOMAIN_JAPANESE: "alpha.dev.libre.fm", Daniel@0: DOMAIN_CHINESE: "alpha.dev.libre.fm", Daniel@0: }, Daniel@0: urls = { Daniel@0: "album": "artist/%(artist)s/album/%(album)s", Daniel@0: "artist": "artist/%(artist)s", Daniel@0: "event": "event/%(id)s", Daniel@0: "country": "place/%(country_name)s", Daniel@0: "playlist": "user/%(user)s/library/playlists/%(appendix)s", Daniel@0: "tag": "tag/%(name)s", Daniel@0: "track": "music/%(artist)s/_/%(title)s", Daniel@0: "group": "group/%(name)s", Daniel@0: "user": "user/%(name)s", Daniel@0: } Daniel@0: ) Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.LibreFMNetwork(%s)" %(", ".join(("'%s'" %self.api_key, "'%s'" %self.api_secret, "'%s'" %self.session_key, Daniel@0: "'%s'" %self.username, "'%s'" %self.password_hash))) Daniel@0: Daniel@0: def __str__(self): Daniel@0: return "Libre.fm Network" Daniel@0: Daniel@0: def get_librefm_network(api_key="", api_secret="", session_key = "", username = "", password_hash = ""): Daniel@0: """ Daniel@0: Returns a preconfigured _Network object for Libre.fm Daniel@0: Daniel@0: api_key: a provided API_KEY Daniel@0: api_secret: a provided API_SECRET Daniel@0: session_key: a generated session_key or None Daniel@0: username: a username of a valid user Daniel@0: password_hash: the output of pylast.md5(password) where password is the user's password Daniel@0: Daniel@0: if username and password_hash were provided and not session_key, session_key will be Daniel@0: generated automatically when needed. Daniel@0: """ Daniel@0: Daniel@0: _deprecation_warning("DeprecationWarning: Create a LibreFMNetwork object instead") Daniel@0: Daniel@0: return LibreFMNetwork(api_key, api_secret, session_key, username, password_hash) Daniel@0: Daniel@0: class _ShelfCacheBackend(object): Daniel@0: """Used as a backend for caching cacheable requests.""" Daniel@0: def __init__(self, file_path = None): Daniel@0: self.shelf = shelve.open(file_path) Daniel@0: Daniel@0: def get_xml(self, key): Daniel@0: return self.shelf[key] Daniel@0: Daniel@0: def set_xml(self, key, xml_string): Daniel@0: self.shelf[key] = xml_string Daniel@0: Daniel@0: def has_key(self, key): Daniel@0: return key in self.shelf.keys() Daniel@0: Daniel@0: class _Request(object): Daniel@0: """Representing an abstract web service operation.""" Daniel@0: Daniel@0: def __init__(self, network, method_name, params = {}): Daniel@0: Daniel@0: self.network = network Daniel@0: self.params = {} Daniel@0: Daniel@0: for key in params: Daniel@0: self.params[key] = _unicode(params[key]) Daniel@0: Daniel@0: (self.api_key, self.api_secret, self.session_key) = network._get_ws_auth() Daniel@0: Daniel@0: self.params["api_key"] = self.api_key Daniel@0: self.params["method"] = method_name Daniel@0: Daniel@0: if network.is_caching_enabled(): Daniel@0: self.cache = network._get_cache_backend() Daniel@0: Daniel@0: if self.session_key: Daniel@0: self.params["sk"] = self.session_key Daniel@0: self.sign_it() Daniel@0: Daniel@0: def sign_it(self): Daniel@0: """Sign this request.""" Daniel@0: Daniel@0: if not "api_sig" in self.params.keys(): Daniel@0: self.params['api_sig'] = self._get_signature() Daniel@0: Daniel@0: def _get_signature(self): Daniel@0: """Returns a 32-character hexadecimal md5 hash of the signature string.""" Daniel@0: Daniel@0: keys = list(self.params.keys()) Daniel@0: Daniel@0: keys.sort() Daniel@0: Daniel@0: string = "" Daniel@0: Daniel@0: for name in keys: Daniel@0: string += name Daniel@0: string += self.params[name] Daniel@0: Daniel@0: string += self.api_secret Daniel@0: Daniel@0: return md5(string) Daniel@0: Daniel@0: def _get_cache_key(self): Daniel@0: """The cache key is a string of concatenated sorted names and values.""" Daniel@0: Daniel@0: keys = list(self.params.keys()) Daniel@0: keys.sort() Daniel@0: Daniel@0: cache_key = str() Daniel@0: Daniel@0: for key in keys: Daniel@0: if key != "api_sig" and key != "api_key" and key != "sk": Daniel@0: cache_key += key + _string(self.params[key]) Daniel@0: Daniel@0: return hashlib.sha1(cache_key).hexdigest() Daniel@0: Daniel@0: def _get_cached_response(self): Daniel@0: """Returns a file object of the cached response.""" Daniel@0: Daniel@0: if not self._is_cached(): Daniel@0: response = self._download_response() Daniel@0: self.cache.set_xml(self._get_cache_key(), response) Daniel@0: Daniel@0: return self.cache.get_xml(self._get_cache_key()) Daniel@0: Daniel@0: def _is_cached(self): Daniel@0: """Returns True if the request is already in cache.""" Daniel@0: Daniel@0: return self.cache.has_key(self._get_cache_key()) Daniel@0: Daniel@0: def _download_response(self): Daniel@0: """Returns a response body string from the server.""" Daniel@0: Daniel@0: # Delay the call if necessary Daniel@0: #self.network._delay_call() # enable it if you want. Daniel@0: Daniel@0: data = [] Daniel@0: for name in self.params.keys(): Daniel@0: data.append('='.join((name, url_quote_plus(_string(self.params[name]))))) Daniel@0: data = '&'.join(data) Daniel@0: Daniel@0: headers = { Daniel@0: "Content-type": "application/x-www-form-urlencoded", Daniel@0: 'Accept-Charset': 'utf-8', Daniel@0: 'User-Agent': "pylast" + '/' + __version__ Daniel@0: } Daniel@0: Daniel@0: (HOST_NAME, HOST_SUBDIR) = self.network.ws_server Daniel@0: Daniel@0: if self.network.is_proxy_enabled(): Daniel@0: conn = HTTPConnection(host = self._get_proxy()[0], port = self._get_proxy()[1]) Daniel@0: Daniel@0: try: Daniel@0: conn.request(method='POST', url="http://" + HOST_NAME + HOST_SUBDIR, Daniel@0: body=data, headers=headers) Daniel@0: except Exception as e: Daniel@0: raise NetworkError(self.network, e) Daniel@0: Daniel@0: else: Daniel@0: conn = HTTPConnection(host=HOST_NAME) Daniel@0: Daniel@0: try: Daniel@0: conn.request(method='POST', url=HOST_SUBDIR, body=data, headers=headers) Daniel@0: except Exception as e: Daniel@0: raise NetworkError(self.network, e) Daniel@0: Daniel@0: try: Daniel@0: response_text = _unicode(conn.getresponse().read()) Daniel@0: except Exception as e: Daniel@0: raise MalformedResponseError(self.network, e) Daniel@0: Daniel@0: self._check_response_for_errors(response_text) Daniel@0: return response_text Daniel@0: Daniel@0: def execute(self, cacheable = False): Daniel@0: """Returns the XML DOM response of the POST Request from the server""" Daniel@0: Daniel@0: if self.network.is_caching_enabled() and cacheable: Daniel@0: response = self._get_cached_response() Daniel@0: else: Daniel@0: response = self._download_response() Daniel@0: Daniel@0: return minidom.parseString(_string(response)) Daniel@0: Daniel@0: def _check_response_for_errors(self, response): Daniel@0: """Checks the response for errors and raises one if any exists.""" Daniel@0: Daniel@0: try: Daniel@0: doc = minidom.parseString(_string(response)) Daniel@0: except Exception as e: Daniel@0: raise MalformedResponseError(self.network, e) Daniel@0: Daniel@0: e = doc.getElementsByTagName('lfm')[0] Daniel@0: Daniel@0: if e.getAttribute('status') != "ok": Daniel@0: e = doc.getElementsByTagName('error')[0] Daniel@0: status = e.getAttribute('code') Daniel@0: details = e.firstChild.data.strip() Daniel@0: raise WSError(self.network, status, details) Daniel@0: Daniel@0: class SessionKeyGenerator(object): Daniel@0: """Methods of generating a session key: Daniel@0: 1) Web Authentication: Daniel@0: a. network = get_*_network(API_KEY, API_SECRET) Daniel@0: b. sg = SessionKeyGenerator(network) Daniel@0: c. url = sg.get_web_auth_url() Daniel@0: d. Ask the user to open the url and authorize you, and wait for it. Daniel@0: e. session_key = sg.get_web_auth_session_key(url) Daniel@0: 2) Username and Password Authentication: Daniel@0: a. network = get_*_network(API_KEY, API_SECRET) Daniel@0: b. username = raw_input("Please enter your username: ") Daniel@0: c. password_hash = pylast.md5(raw_input("Please enter your password: ") Daniel@0: d. session_key = SessionKeyGenerator(network).get_session_key(username, password_hash) Daniel@0: Daniel@0: A session key's lifetime is infinie, unless the user provokes the rights of the given API Key. Daniel@0: Daniel@0: If you create a Network object with just a API_KEY and API_SECRET and a username and a password_hash, a Daniel@0: SESSION_KEY will be automatically generated for that network and stored in it so you don't have to do this Daniel@0: manually, unless you want to. Daniel@0: """ Daniel@0: Daniel@0: def __init__(self, network): Daniel@0: self.network = network Daniel@0: self.web_auth_tokens = {} Daniel@0: Daniel@0: def _get_web_auth_token(self): Daniel@0: """Retrieves a token from the network for web authentication. Daniel@0: The token then has to be authorized from getAuthURL before creating session. Daniel@0: """ Daniel@0: Daniel@0: request = _Request(self.network, 'auth.getToken') Daniel@0: Daniel@0: # default action is that a request is signed only when Daniel@0: # a session key is provided. Daniel@0: request.sign_it() Daniel@0: Daniel@0: doc = request.execute() Daniel@0: Daniel@0: e = doc.getElementsByTagName('token')[0] Daniel@0: return e.firstChild.data Daniel@0: Daniel@0: def get_web_auth_url(self): Daniel@0: """The user must open this page, and you first, then call get_web_auth_session_key(url) after that.""" Daniel@0: Daniel@0: token = self._get_web_auth_token() Daniel@0: Daniel@0: url = '%(homepage)s/api/auth/?api_key=%(api)s&token=%(token)s' % \ Daniel@0: {"homepage": self.network.homepage, "api": self.network.api_key, "token": token} Daniel@0: Daniel@0: self.web_auth_tokens[url] = token Daniel@0: Daniel@0: return url Daniel@0: Daniel@0: def get_web_auth_session_key(self, url): Daniel@0: """Retrieves the session key of a web authorization process by its url.""" Daniel@0: Daniel@0: if url in self.web_auth_tokens.keys(): Daniel@0: token = self.web_auth_tokens[url] Daniel@0: else: Daniel@0: token = "" #that's gonna raise a WSError of an unauthorized token when the request is executed. Daniel@0: Daniel@0: request = _Request(self.network, 'auth.getSession', {'token': token}) Daniel@0: Daniel@0: # default action is that a request is signed only when Daniel@0: # a session key is provided. Daniel@0: request.sign_it() Daniel@0: Daniel@0: doc = request.execute() Daniel@0: Daniel@0: return doc.getElementsByTagName('key')[0].firstChild.data Daniel@0: Daniel@0: def get_session_key(self, username, password_hash): Daniel@0: """Retrieve a session key with a username and a md5 hash of the user's password.""" Daniel@0: Daniel@0: params = {"username": username, "authToken": md5(username + password_hash)} Daniel@0: request = _Request(self.network, "auth.getMobileSession", params) Daniel@0: Daniel@0: # default action is that a request is signed only when Daniel@0: # a session key is provided. Daniel@0: request.sign_it() Daniel@0: Daniel@0: doc = request.execute() Daniel@0: Daniel@0: return _extract(doc, "key") Daniel@0: Daniel@0: TopItem = collections.namedtuple("TopItem", ["item", "weight"]) Daniel@0: SimilarItem = collections.namedtuple("SimilarItem", ["item", "match"]) Daniel@0: LibraryItem = collections.namedtuple("LibraryItem", ["item", "playcount", "tagcount"]) Daniel@0: PlayedTrack = collections.namedtuple("PlayedTrack", ["track", "playback_date", "timestamp"]) Daniel@0: LovedTrack = collections.namedtuple("LovedTrack", ["track", "date", "timestamp"]) Daniel@0: ImageSizes = collections.namedtuple("ImageSizes", ["original", "large", "largesquare", "medium", "small", "extralarge"]) Daniel@0: Image = collections.namedtuple("Image", ["title", "url", "dateadded", "format", "owner", "sizes", "votes"]) Daniel@0: Shout = collections.namedtuple("Shout", ["body", "author", "date"]) Daniel@0: Daniel@0: def _string_output(funct): Daniel@0: def r(*args): Daniel@0: return _string(funct(*args)) Daniel@0: Daniel@0: return r Daniel@0: Daniel@0: def _pad_list(given_list, desired_length, padding = None): Daniel@0: """ Daniel@0: Pads a list to be of the desired_length. Daniel@0: """ Daniel@0: Daniel@0: while len(given_list) < desired_length: Daniel@0: given_list.append(padding) Daniel@0: Daniel@0: return given_list Daniel@0: Daniel@0: class _BaseObject(object): Daniel@0: """An abstract webservices object.""" Daniel@0: Daniel@0: network = None Daniel@0: Daniel@0: def __init__(self, network): Daniel@0: self.network = network Daniel@0: Daniel@0: def _request(self, method_name, cacheable = False, params = None): Daniel@0: if not params: Daniel@0: params = self._get_params() Daniel@0: Daniel@0: return _Request(self.network, method_name, params).execute(cacheable) Daniel@0: Daniel@0: def _get_params(self): Daniel@0: """Returns the most common set of parameters between all objects.""" Daniel@0: Daniel@0: return {} Daniel@0: Daniel@0: def __hash__(self): Daniel@0: return hash(self.network) + \ Daniel@0: hash(str(type(self)) + "".join(list(self._get_params().keys()) + list(self._get_params().values())).lower()) Daniel@0: Daniel@0: class _Taggable(object): Daniel@0: """Common functions for classes with tags.""" Daniel@0: Daniel@0: def __init__(self, ws_prefix): Daniel@0: self.ws_prefix = ws_prefix Daniel@0: Daniel@0: def add_tags(self, tags): Daniel@0: """Adds one or several tags. Daniel@0: * tags: A sequence of tag names or Tag objects. Daniel@0: """ Daniel@0: Daniel@0: for tag in tags: Daniel@0: self.add_tag(tag) Daniel@0: Daniel@0: def add_tag(self, tag): Daniel@0: """Adds one tag. Daniel@0: * tag: a tag name or a Tag object. Daniel@0: """ Daniel@0: Daniel@0: if isinstance(tag, Tag): Daniel@0: tag = tag.get_name() Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params['tags'] = tag Daniel@0: Daniel@0: self._request(self.ws_prefix + '.addTags', False, params) Daniel@0: Daniel@0: def remove_tag(self, tag): Daniel@0: """Remove a user's tag from this object.""" Daniel@0: Daniel@0: if isinstance(tag, Tag): Daniel@0: tag = tag.get_name() Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params['tag'] = tag Daniel@0: Daniel@0: self._request(self.ws_prefix + '.removeTag', False, params) Daniel@0: Daniel@0: def get_tags(self): Daniel@0: """Returns a list of the tags set by the user to this object.""" Daniel@0: Daniel@0: # Uncacheable because it can be dynamically changed by the user. Daniel@0: params = self._get_params() Daniel@0: Daniel@0: doc = self._request(self.ws_prefix + '.getTags', False, params) Daniel@0: tag_names = _extract_all(doc, 'name') Daniel@0: tags = [] Daniel@0: for tag in tag_names: Daniel@0: tags.append(Tag(tag, self.network)) Daniel@0: Daniel@0: return tags Daniel@0: Daniel@0: def remove_tags(self, tags): Daniel@0: """Removes one or several tags from this object. Daniel@0: * tags: a sequence of tag names or Tag objects. Daniel@0: """ Daniel@0: Daniel@0: for tag in tags: Daniel@0: self.remove_tag(tag) Daniel@0: Daniel@0: def clear_tags(self): Daniel@0: """Clears all the user-set tags. """ Daniel@0: Daniel@0: self.remove_tags(*(self.get_tags())) Daniel@0: Daniel@0: def set_tags(self, tags): Daniel@0: """Sets this object's tags to only those tags. Daniel@0: * tags: a sequence of tag names or Tag objects. Daniel@0: """ Daniel@0: Daniel@0: c_old_tags = [] Daniel@0: old_tags = [] Daniel@0: c_new_tags = [] Daniel@0: new_tags = [] Daniel@0: Daniel@0: to_remove = [] Daniel@0: to_add = [] Daniel@0: Daniel@0: tags_on_server = self.get_tags() Daniel@0: Daniel@0: for tag in tags_on_server: Daniel@0: c_old_tags.append(tag.get_name().lower()) Daniel@0: old_tags.append(tag.get_name()) Daniel@0: Daniel@0: for tag in tags: Daniel@0: c_new_tags.append(tag.lower()) Daniel@0: new_tags.append(tag) Daniel@0: Daniel@0: for i in range(0, len(old_tags)): Daniel@0: if not c_old_tags[i] in c_new_tags: Daniel@0: to_remove.append(old_tags[i]) Daniel@0: Daniel@0: for i in range(0, len(new_tags)): Daniel@0: if not c_new_tags[i] in c_old_tags: Daniel@0: to_add.append(new_tags[i]) Daniel@0: Daniel@0: self.remove_tags(to_remove) Daniel@0: self.add_tags(to_add) Daniel@0: Daniel@0: def get_top_tags(self, limit=None): Daniel@0: """Returns a list of the most frequently used Tags on this object.""" Daniel@0: Daniel@0: doc = self._request(self.ws_prefix + '.getTopTags', True) Daniel@0: Daniel@0: elements = doc.getElementsByTagName('tag') Daniel@0: seq = [] Daniel@0: Daniel@0: for element in elements: Daniel@0: tag_name = _extract(element, 'name') Daniel@0: tagcount = _extract(element, 'count') Daniel@0: Daniel@0: seq.append(TopItem(Tag(tag_name, self.network), tagcount)) Daniel@0: Daniel@0: if limit: Daniel@0: seq = seq[:limit] Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: class WSError(Exception): Daniel@0: """Exception related to the Network web service""" Daniel@0: Daniel@0: def __init__(self, network, status, details): Daniel@0: self.status = status Daniel@0: self.details = details Daniel@0: self.network = network Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return self.details Daniel@0: Daniel@0: def get_id(self): Daniel@0: """Returns the exception ID, from one of the following: Daniel@0: STATUS_INVALID_SERVICE = 2 Daniel@0: STATUS_INVALID_METHOD = 3 Daniel@0: STATUS_AUTH_FAILED = 4 Daniel@0: STATUS_INVALID_FORMAT = 5 Daniel@0: STATUS_INVALID_PARAMS = 6 Daniel@0: STATUS_INVALID_RESOURCE = 7 Daniel@0: STATUS_TOKEN_ERROR = 8 Daniel@0: STATUS_INVALID_SK = 9 Daniel@0: STATUS_INVALID_API_KEY = 10 Daniel@0: STATUS_OFFLINE = 11 Daniel@0: STATUS_SUBSCRIBERS_ONLY = 12 Daniel@0: STATUS_TOKEN_UNAUTHORIZED = 14 Daniel@0: STATUS_TOKEN_EXPIRED = 15 Daniel@0: """ Daniel@0: Daniel@0: return self.status Daniel@0: Daniel@0: class MalformedResponseError(Exception): Daniel@0: """Exception conveying a malformed response from Last.fm.""" Daniel@0: Daniel@0: def __init__(self, network, underlying_error): Daniel@0: self.network = network Daniel@0: self.underlying_error = underlying_error Daniel@0: Daniel@0: def __str__(self): Daniel@0: return "Malformed response from Last.fm. Underlying error: %s" %str(self.underlying_error) Daniel@0: Daniel@0: class NetworkError(Exception): Daniel@0: """Exception conveying a problem in sending a request to Last.fm""" Daniel@0: Daniel@0: def __init__(self, network, underlying_error): Daniel@0: self.network = network Daniel@0: self.underlying_error = underlying_error Daniel@0: Daniel@0: def __str__(self): Daniel@0: return "NetworkError: %s" %str(self.underlying_error) Daniel@0: Daniel@0: class Album(_BaseObject, _Taggable): Daniel@0: """An album.""" Daniel@0: Daniel@0: title = None Daniel@0: artist = None Daniel@0: Daniel@0: def __init__(self, artist, title, network): Daniel@0: """ Daniel@0: Create an album instance. Daniel@0: # Parameters: Daniel@0: * artist: An artist name or an Artist object. Daniel@0: * title: The album title. Daniel@0: """ Daniel@0: Daniel@0: _BaseObject.__init__(self, network) Daniel@0: _Taggable.__init__(self, 'album') Daniel@0: Daniel@0: if isinstance(artist, Artist): Daniel@0: self.artist = artist Daniel@0: else: Daniel@0: self.artist = Artist(artist, self.network) Daniel@0: Daniel@0: self.title = title Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.Album(%s, %s, %s)" %(repr(self.artist.name), repr(self.title), repr(self.network)) Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return _unicode("%s - %s") %(self.get_artist().get_name(), self.get_title()) Daniel@0: Daniel@0: def __eq__(self, other): Daniel@0: return (self.get_title().lower() == other.get_title().lower()) and (self.get_artist().get_name().lower() == other.get_artist().get_name().lower()) Daniel@0: Daniel@0: def __ne__(self, other): Daniel@0: return (self.get_title().lower() != other.get_title().lower()) or (self.get_artist().get_name().lower() != other.get_artist().get_name().lower()) Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {'artist': self.get_artist().get_name(), 'album': self.get_title(), } Daniel@0: Daniel@0: def get_artist(self): Daniel@0: """Returns the associated Artist object.""" Daniel@0: Daniel@0: return self.artist Daniel@0: Daniel@0: def get_title(self): Daniel@0: """Returns the album title.""" Daniel@0: Daniel@0: return self.title Daniel@0: Daniel@0: def get_name(self): Daniel@0: """Returns the album title (alias to Album.get_title).""" Daniel@0: Daniel@0: return self.get_title() Daniel@0: Daniel@0: def get_release_date(self): Daniel@0: """Retruns the release date of the album.""" Daniel@0: Daniel@0: return _extract(self._request("album.getInfo", cacheable = True), "releasedate") Daniel@0: Daniel@0: def get_cover_image(self, size = COVER_EXTRA_LARGE): Daniel@0: """ Daniel@0: Returns a uri to the cover image Daniel@0: size can be one of: Daniel@0: COVER_EXTRA_LARGE Daniel@0: COVER_LARGE Daniel@0: COVER_MEDIUM Daniel@0: COVER_SMALL Daniel@0: """ Daniel@0: Daniel@0: return _extract_all(self._request("album.getInfo", cacheable = True), 'image')[size] Daniel@0: Daniel@0: def get_id(self): Daniel@0: """Returns the ID""" Daniel@0: Daniel@0: return _extract(self._request("album.getInfo", cacheable = True), "id") Daniel@0: Daniel@0: def get_playcount(self): Daniel@0: """Returns the number of plays on the network""" Daniel@0: Daniel@0: return _number(_extract(self._request("album.getInfo", cacheable = True), "playcount")) Daniel@0: Daniel@0: def get_listener_count(self): Daniel@0: """Returns the number of liteners on the network""" Daniel@0: Daniel@0: return _number(_extract(self._request("album.getInfo", cacheable = True), "listeners")) Daniel@0: Daniel@0: def get_top_tags(self, limit=None): Daniel@0: """Returns a list of the most-applied tags to this album.""" Daniel@0: Daniel@0: doc = self._request("album.getInfo", True) Daniel@0: e = doc.getElementsByTagName("toptags")[0] Daniel@0: Daniel@0: seq = [] Daniel@0: for name in _extract_all(e, "name"): Daniel@0: seq.append(Tag(name, self.network)) Daniel@0: Daniel@0: if limit: Daniel@0: seq = seq[:limit] Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_tracks(self): Daniel@0: """Returns the list of Tracks on this album.""" Daniel@0: Daniel@0: uri = 'lastfm://playlist/album/%s' %self.get_id() Daniel@0: Daniel@0: return XSPF(uri, self.network).get_tracks() Daniel@0: Daniel@0: def get_mbid(self): Daniel@0: """Returns the MusicBrainz id of the album.""" Daniel@0: Daniel@0: return _extract(self._request("album.getInfo", cacheable = True), "mbid") Daniel@0: Daniel@0: def get_url(self, domain_name = DOMAIN_ENGLISH): Daniel@0: """Returns the url of the album page on the network. Daniel@0: # Parameters: Daniel@0: * domain_name str: The network's language domain. Possible values: Daniel@0: o DOMAIN_ENGLISH Daniel@0: o DOMAIN_GERMAN Daniel@0: o DOMAIN_SPANISH Daniel@0: o DOMAIN_FRENCH Daniel@0: o DOMAIN_ITALIAN Daniel@0: o DOMAIN_POLISH Daniel@0: o DOMAIN_PORTUGUESE Daniel@0: o DOMAIN_SWEDISH Daniel@0: o DOMAIN_TURKISH Daniel@0: o DOMAIN_RUSSIAN Daniel@0: o DOMAIN_JAPANESE Daniel@0: o DOMAIN_CHINESE Daniel@0: """ Daniel@0: Daniel@0: artist = _url_safe(self.get_artist().get_name()) Daniel@0: album = _url_safe(self.get_title()) Daniel@0: Daniel@0: return self.network._get_url(domain_name, "album") %{'artist': artist, 'album': album} Daniel@0: Daniel@0: def get_wiki_published_date(self): Daniel@0: """Returns the date of publishing this version of the wiki.""" Daniel@0: Daniel@0: doc = self._request("album.getInfo", True) Daniel@0: Daniel@0: if len(doc.getElementsByTagName("wiki")) == 0: Daniel@0: return Daniel@0: Daniel@0: node = doc.getElementsByTagName("wiki")[0] Daniel@0: Daniel@0: return _extract(node, "published") Daniel@0: Daniel@0: def get_wiki_summary(self): Daniel@0: """Returns the summary of the wiki.""" Daniel@0: Daniel@0: doc = self._request("album.getInfo", True) Daniel@0: Daniel@0: if len(doc.getElementsByTagName("wiki")) == 0: Daniel@0: return Daniel@0: Daniel@0: node = doc.getElementsByTagName("wiki")[0] Daniel@0: Daniel@0: return _extract(node, "summary") Daniel@0: Daniel@0: def get_wiki_content(self): Daniel@0: """Returns the content of the wiki.""" Daniel@0: Daniel@0: doc = self._request("album.getInfo", True) Daniel@0: Daniel@0: if len(doc.getElementsByTagName("wiki")) == 0: Daniel@0: return Daniel@0: Daniel@0: node = doc.getElementsByTagName("wiki")[0] Daniel@0: Daniel@0: return _extract(node, "content") Daniel@0: Daniel@0: class Artist(_BaseObject, _Taggable): Daniel@0: """An artist.""" Daniel@0: Daniel@0: name = None Daniel@0: Daniel@0: def __init__(self, name, network): Daniel@0: """Create an artist object. Daniel@0: # Parameters: Daniel@0: * name str: The artist's name. Daniel@0: """ Daniel@0: Daniel@0: _BaseObject.__init__(self, network) Daniel@0: _Taggable.__init__(self, 'artist') Daniel@0: Daniel@0: self.name = name Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.Artist(%s, %s)" %(repr(self.get_name()), repr(self.network)) Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return self.get_name() Daniel@0: Daniel@0: def __eq__(self, other): Daniel@0: return self.get_name().lower() == other.get_name().lower() Daniel@0: Daniel@0: def __ne__(self, other): Daniel@0: return self.get_name().lower() != other.get_name().lower() Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {'artist': self.get_name()} Daniel@0: Daniel@0: def get_name(self, properly_capitalized=False): Daniel@0: """Returns the name of the artist. Daniel@0: If properly_capitalized was asserted then the name would be downloaded Daniel@0: overwriting the given one.""" Daniel@0: Daniel@0: if properly_capitalized: Daniel@0: self.name = _extract(self._request("artist.getInfo", True), "name") Daniel@0: Daniel@0: return self.name Daniel@0: Daniel@0: def get_cover_image(self, size = COVER_MEGA): Daniel@0: """ Daniel@0: Returns a uri to the cover image Daniel@0: size can be one of: Daniel@0: COVER_MEGA Daniel@0: COVER_EXTRA_LARGE Daniel@0: COVER_LARGE Daniel@0: COVER_MEDIUM Daniel@0: COVER_SMALL Daniel@0: """ Daniel@0: Daniel@0: return _extract_all(self._request("artist.getInfo", True), "image")[size] Daniel@0: Daniel@0: def get_playcount(self): Daniel@0: """Returns the number of plays on the network.""" Daniel@0: Daniel@0: return _number(_extract(self._request("artist.getInfo", True), "playcount")) Daniel@0: Daniel@0: def get_mbid(self): Daniel@0: """Returns the MusicBrainz ID of this artist.""" Daniel@0: Daniel@0: doc = self._request("artist.getInfo", True) Daniel@0: Daniel@0: return _extract(doc, "mbid") Daniel@0: Daniel@0: def get_listener_count(self): Daniel@0: """Returns the number of liteners on the network.""" Daniel@0: Daniel@0: if hasattr(self, "listener_count"): Daniel@0: return self.listener_count Daniel@0: else: Daniel@0: self.listener_count = _number(_extract(self._request("artist.getInfo", True), "listeners")) Daniel@0: return self.listener_count Daniel@0: Daniel@0: def is_streamable(self): Daniel@0: """Returns True if the artist is streamable.""" Daniel@0: Daniel@0: return bool(_number(_extract(self._request("artist.getInfo", True), "streamable"))) Daniel@0: Daniel@0: def get_bio_published_date(self): Daniel@0: """Returns the date on which the artist's biography was published.""" Daniel@0: Daniel@0: return _extract(self._request("artist.getInfo", True), "published") Daniel@0: Daniel@0: def get_bio_summary(self): Daniel@0: """Returns the summary of the artist's biography.""" Daniel@0: Daniel@0: return _extract(self._request("artist.getInfo", True), "summary") Daniel@0: Daniel@0: def get_bio_content(self): Daniel@0: """Returns the content of the artist's biography.""" Daniel@0: Daniel@0: return _extract(self._request("artist.getInfo", True), "content") Daniel@0: Daniel@0: def get_upcoming_events(self): Daniel@0: """Returns a list of the upcoming Events for this artist.""" Daniel@0: Daniel@0: doc = self._request('artist.getEvents', True) Daniel@0: Daniel@0: ids = _extract_all(doc, 'id') Daniel@0: Daniel@0: events = [] Daniel@0: for e_id in ids: Daniel@0: events.append(Event(e_id, self.network)) Daniel@0: Daniel@0: return events Daniel@0: Daniel@0: def get_similar(self, limit = None): Daniel@0: """Returns the similar artists on the network.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if limit: Daniel@0: params['limit'] = limit Daniel@0: Daniel@0: doc = self._request('artist.getSimilar', True, params) Daniel@0: Daniel@0: names = _extract_all(doc, "name") Daniel@0: matches = _extract_all(doc, "match") Daniel@0: Daniel@0: artists = [] Daniel@0: for i in range(0, len(names)): Daniel@0: artists.append(SimilarItem(Artist(names[i], self.network), _number(matches[i]))) Daniel@0: Daniel@0: return artists Daniel@0: Daniel@0: def compare_with_artist(self, artist, shared_artists_limit = None): Daniel@0: """Compare this artist with another Last.fm artist. Daniel@0: Seems like the tasteometer only returns stats on subsets of artist sets... Daniel@0: Returns a sequence (tasteometer_score, (shared_artist1, shared_artist2, ...)) Daniel@0: artist: A artist object or a artistname string/unicode object. Daniel@0: """ Daniel@0: Daniel@0: if isinstance(artist, Artist): Daniel@0: artist = artist.get_name() Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if shared_artists_limit: Daniel@0: params['limit'] = shared_artists_limit Daniel@0: params['type1'] = 'artists' Daniel@0: params['type2'] = 'artists' Daniel@0: params['value1'] = self.get_name() Daniel@0: params['value2'] = artist Daniel@0: Daniel@0: doc = self._request('tasteometer.compare', False, params) Daniel@0: Daniel@0: score = _extract(doc, 'score') Daniel@0: Daniel@0: artists = doc.getElementsByTagName('artists')[0] Daniel@0: shared_artists_names = _extract_all(artists, 'name') Daniel@0: Daniel@0: shared_artists_seq = [] Daniel@0: Daniel@0: for name in shared_artists_names: Daniel@0: shared_artists_seq.append(Artist(name, self.network)) Daniel@0: Daniel@0: return (score, shared_artists_seq) Daniel@0: Daniel@0: def get_top_albums(self): Daniel@0: """Retuns a list of the top albums.""" Daniel@0: Daniel@0: doc = self._request('artist.getTopAlbums', True) Daniel@0: Daniel@0: seq = [] Daniel@0: Daniel@0: for node in doc.getElementsByTagName("album"): Daniel@0: name = _extract(node, "name") Daniel@0: artist = _extract(node, "name", 1) Daniel@0: playcount = _extract(node, "playcount") Daniel@0: Daniel@0: seq.append(TopItem(Album(artist, name, self.network), playcount)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_top_tracks(self): Daniel@0: """Returns a list of the most played Tracks by this artist.""" Daniel@0: Daniel@0: doc = self._request("artist.getTopTracks", True) Daniel@0: Daniel@0: seq = [] Daniel@0: for track in doc.getElementsByTagName('track'): Daniel@0: Daniel@0: title = _extract(track, "name") Daniel@0: artist = _extract(track, "name", 1) Daniel@0: playcount = _number(_extract(track, "playcount")) Daniel@0: Daniel@0: seq.append( TopItem(Track(artist, title, self.network), playcount) ) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_top_fans(self, limit = None): Daniel@0: """Returns a list of the Users who played this artist the most. Daniel@0: # Parameters: Daniel@0: * limit int: Max elements. Daniel@0: """ Daniel@0: Daniel@0: doc = self._request('artist.getTopFans', True) Daniel@0: Daniel@0: seq = [] Daniel@0: Daniel@0: elements = doc.getElementsByTagName('user') Daniel@0: Daniel@0: for element in elements: Daniel@0: if limit and len(seq) >= limit: Daniel@0: break Daniel@0: Daniel@0: name = _extract(element, 'name') Daniel@0: weight = _number(_extract(element, 'weight')) Daniel@0: Daniel@0: seq.append(TopItem(User(name, self.network), weight)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def share(self, users, message = None): Daniel@0: """Shares this artist (sends out recommendations). Daniel@0: # Parameters: Daniel@0: * users [User|str,]: A list that can contain usernames, emails, User objects, or all of them. Daniel@0: * message str: A message to include in the recommendation message. Daniel@0: """ Daniel@0: Daniel@0: #last.fm currently accepts a max of 10 recipient at a time Daniel@0: while(len(users) > 10): Daniel@0: section = users[0:9] Daniel@0: users = users[9:] Daniel@0: self.share(section, message) Daniel@0: Daniel@0: nusers = [] Daniel@0: for user in users: Daniel@0: if isinstance(user, User): Daniel@0: nusers.append(user.get_name()) Daniel@0: else: Daniel@0: nusers.append(user) Daniel@0: Daniel@0: params = self._get_params() Daniel@0: recipients = ','.join(nusers) Daniel@0: params['recipient'] = recipients Daniel@0: if message: Daniel@0: params['message'] = message Daniel@0: Daniel@0: self._request('artist.share', False, params) Daniel@0: Daniel@0: def get_url(self, domain_name = DOMAIN_ENGLISH): Daniel@0: """Returns the url of the artist page on the network. Daniel@0: # Parameters: Daniel@0: * domain_name: The network's language domain. Possible values: Daniel@0: o DOMAIN_ENGLISH Daniel@0: o DOMAIN_GERMAN Daniel@0: o DOMAIN_SPANISH Daniel@0: o DOMAIN_FRENCH Daniel@0: o DOMAIN_ITALIAN Daniel@0: o DOMAIN_POLISH Daniel@0: o DOMAIN_PORTUGUESE Daniel@0: o DOMAIN_SWEDISH Daniel@0: o DOMAIN_TURKISH Daniel@0: o DOMAIN_RUSSIAN Daniel@0: o DOMAIN_JAPANESE Daniel@0: o DOMAIN_CHINESE Daniel@0: """ Daniel@0: Daniel@0: artist = _url_safe(self.get_name()) Daniel@0: Daniel@0: return self.network._get_url(domain_name, "artist") %{'artist': artist} Daniel@0: Daniel@0: def get_images(self, order=IMAGES_ORDER_POPULARITY, limit=None): Daniel@0: """ Daniel@0: Returns a sequence of Image objects Daniel@0: if limit is None it will return all Daniel@0: order can be IMAGES_ORDER_POPULARITY or IMAGES_ORDER_DATE. Daniel@0: Daniel@0: If limit==None, it will try to pull all the available data. Daniel@0: """ Daniel@0: Daniel@0: images = [] Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params["order"] = order Daniel@0: nodes = _collect_nodes(limit, self, "artist.getImages", True, params) Daniel@0: for e in nodes: Daniel@0: if _extract(e, "name"): Daniel@0: user = User(_extract(e, "name"), self.network) Daniel@0: else: Daniel@0: user = None Daniel@0: Daniel@0: images.append(Image( Daniel@0: _extract(e, "title"), Daniel@0: _extract(e, "url"), Daniel@0: _extract(e, "dateadded"), Daniel@0: _extract(e, "format"), Daniel@0: user, Daniel@0: ImageSizes(*_extract_all(e, "size")), Daniel@0: (_extract(e, "thumbsup"), _extract(e, "thumbsdown")) Daniel@0: ) Daniel@0: ) Daniel@0: return images Daniel@0: Daniel@0: def get_shouts(self, limit=50): Daniel@0: """ Daniel@0: Returns a sequqence of Shout objects Daniel@0: """ Daniel@0: Daniel@0: shouts = [] Daniel@0: for node in _collect_nodes(limit, self, "artist.getShouts", False): Daniel@0: shouts.append(Shout( Daniel@0: _extract(node, "body"), Daniel@0: User(_extract(node, "author"), self.network), Daniel@0: _extract(node, "date") Daniel@0: ) Daniel@0: ) Daniel@0: return shouts Daniel@0: Daniel@0: def shout(self, message): Daniel@0: """ Daniel@0: Post a shout Daniel@0: """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params["message"] = message Daniel@0: Daniel@0: self._request("artist.Shout", False, params) Daniel@0: Daniel@0: Daniel@0: class Event(_BaseObject): Daniel@0: """An event.""" Daniel@0: Daniel@0: id = None Daniel@0: Daniel@0: def __init__(self, event_id, network): Daniel@0: _BaseObject.__init__(self, network) Daniel@0: Daniel@0: self.id = event_id Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.Event(%s, %s)" %(repr(self.id), repr(self.network)) Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return "Event #" + self.get_id() Daniel@0: Daniel@0: def __eq__(self, other): Daniel@0: return self.get_id() == other.get_id() Daniel@0: Daniel@0: def __ne__(self, other): Daniel@0: return self.get_id() != other.get_id() Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {'event': self.get_id()} Daniel@0: Daniel@0: def attend(self, attending_status): Daniel@0: """Sets the attending status. Daniel@0: * attending_status: The attending status. Possible values: Daniel@0: o EVENT_ATTENDING Daniel@0: o EVENT_MAYBE_ATTENDING Daniel@0: o EVENT_NOT_ATTENDING Daniel@0: """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params['status'] = attending_status Daniel@0: Daniel@0: self._request('event.attend', False, params) Daniel@0: Daniel@0: def get_attendees(self): Daniel@0: """ Daniel@0: Get a list of attendees for an event Daniel@0: """ Daniel@0: Daniel@0: doc = self._request("event.getAttendees", False) Daniel@0: Daniel@0: users = [] Daniel@0: for name in _extract_all(doc, "name"): Daniel@0: users.append(User(name, self.network)) Daniel@0: Daniel@0: return users Daniel@0: Daniel@0: def get_id(self): Daniel@0: """Returns the id of the event on the network. """ Daniel@0: Daniel@0: return self.id Daniel@0: Daniel@0: def get_title(self): Daniel@0: """Returns the title of the event. """ Daniel@0: Daniel@0: doc = self._request("event.getInfo", True) Daniel@0: Daniel@0: return _extract(doc, "title") Daniel@0: Daniel@0: def get_headliner(self): Daniel@0: """Returns the headliner of the event. """ Daniel@0: Daniel@0: doc = self._request("event.getInfo", True) Daniel@0: Daniel@0: return Artist(_extract(doc, "headliner"), self.network) Daniel@0: Daniel@0: def get_artists(self): Daniel@0: """Returns a list of the participating Artists. """ Daniel@0: Daniel@0: doc = self._request("event.getInfo", True) Daniel@0: names = _extract_all(doc, "artist") Daniel@0: Daniel@0: artists = [] Daniel@0: for name in names: Daniel@0: artists.append(Artist(name, self.network)) Daniel@0: Daniel@0: return artists Daniel@0: Daniel@0: def get_venue(self): Daniel@0: """Returns the venue where the event is held.""" Daniel@0: Daniel@0: doc = self._request("event.getInfo", True) Daniel@0: Daniel@0: v = doc.getElementsByTagName("venue")[0] Daniel@0: venue_id = _number(_extract(v, "id")) Daniel@0: Daniel@0: return Venue(venue_id, self.network) Daniel@0: Daniel@0: def get_start_date(self): Daniel@0: """Returns the date when the event starts.""" Daniel@0: Daniel@0: doc = self._request("event.getInfo", True) Daniel@0: Daniel@0: return _extract(doc, "startDate") Daniel@0: Daniel@0: def get_description(self): Daniel@0: """Returns the description of the event. """ Daniel@0: Daniel@0: doc = self._request("event.getInfo", True) Daniel@0: Daniel@0: return _extract(doc, "description") Daniel@0: Daniel@0: def get_cover_image(self, size = COVER_MEGA): Daniel@0: """ Daniel@0: Returns a uri to the cover image Daniel@0: size can be one of: Daniel@0: COVER_MEGA Daniel@0: COVER_EXTRA_LARGE Daniel@0: COVER_LARGE Daniel@0: COVER_MEDIUM Daniel@0: COVER_SMALL Daniel@0: """ Daniel@0: Daniel@0: doc = self._request("event.getInfo", True) Daniel@0: Daniel@0: return _extract_all(doc, "image")[size] Daniel@0: Daniel@0: def get_attendance_count(self): Daniel@0: """Returns the number of attending people. """ Daniel@0: Daniel@0: doc = self._request("event.getInfo", True) Daniel@0: Daniel@0: return _number(_extract(doc, "attendance")) Daniel@0: Daniel@0: def get_review_count(self): Daniel@0: """Returns the number of available reviews for this event. """ Daniel@0: Daniel@0: doc = self._request("event.getInfo", True) Daniel@0: Daniel@0: return _number(_extract(doc, "reviews")) Daniel@0: Daniel@0: def get_url(self, domain_name = DOMAIN_ENGLISH): Daniel@0: """Returns the url of the event page on the network. Daniel@0: * domain_name: The network's language domain. Possible values: Daniel@0: o DOMAIN_ENGLISH Daniel@0: o DOMAIN_GERMAN Daniel@0: o DOMAIN_SPANISH Daniel@0: o DOMAIN_FRENCH Daniel@0: o DOMAIN_ITALIAN Daniel@0: o DOMAIN_POLISH Daniel@0: o DOMAIN_PORTUGUESE Daniel@0: o DOMAIN_SWEDISH Daniel@0: o DOMAIN_TURKISH Daniel@0: o DOMAIN_RUSSIAN Daniel@0: o DOMAIN_JAPANESE Daniel@0: o DOMAIN_CHINESE Daniel@0: """ Daniel@0: Daniel@0: return self.network._get_url(domain_name, "event") %{'id': self.get_id()} Daniel@0: Daniel@0: def share(self, users, message = None): Daniel@0: """Shares this event (sends out recommendations). Daniel@0: * users: A list that can contain usernames, emails, User objects, or all of them. Daniel@0: * message: A message to include in the recommendation message. Daniel@0: """ Daniel@0: Daniel@0: #last.fm currently accepts a max of 10 recipient at a time Daniel@0: while(len(users) > 10): Daniel@0: section = users[0:9] Daniel@0: users = users[9:] Daniel@0: self.share(section, message) Daniel@0: Daniel@0: nusers = [] Daniel@0: for user in users: Daniel@0: if isinstance(user, User): Daniel@0: nusers.append(user.get_name()) Daniel@0: else: Daniel@0: nusers.append(user) Daniel@0: Daniel@0: params = self._get_params() Daniel@0: recipients = ','.join(nusers) Daniel@0: params['recipient'] = recipients Daniel@0: if message: Daniel@0: params['message'] = message Daniel@0: Daniel@0: self._request('event.share', False, params) Daniel@0: Daniel@0: def get_shouts(self, limit=50): Daniel@0: """ Daniel@0: Returns a sequqence of Shout objects Daniel@0: """ Daniel@0: Daniel@0: shouts = [] Daniel@0: for node in _collect_nodes(limit, self, "event.getShouts", False): Daniel@0: shouts.append(Shout( Daniel@0: _extract(node, "body"), Daniel@0: User(_extract(node, "author"), self.network), Daniel@0: _extract(node, "date") Daniel@0: ) Daniel@0: ) Daniel@0: return shouts Daniel@0: Daniel@0: def shout(self, message): Daniel@0: """ Daniel@0: Post a shout Daniel@0: """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params["message"] = message Daniel@0: Daniel@0: self._request("event.Shout", False, params) Daniel@0: Daniel@0: class Country(_BaseObject): Daniel@0: """A country at Last.fm.""" Daniel@0: Daniel@0: name = None Daniel@0: Daniel@0: def __init__(self, name, network): Daniel@0: _BaseObject.__init__(self, network) Daniel@0: Daniel@0: self.name = name Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.Country(%s, %s)" %(repr(self.name), repr(self.network)) Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return self.get_name() Daniel@0: Daniel@0: def __eq__(self, other): Daniel@0: return self.get_name().lower() == other.get_name().lower() Daniel@0: Daniel@0: def __ne__(self, other): Daniel@0: return self.get_name() != other.get_name() Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {'country': self.get_name()} Daniel@0: Daniel@0: def _get_name_from_code(self, alpha2code): Daniel@0: # TODO: Have this function lookup the alpha-2 code and return the country name. Daniel@0: Daniel@0: return alpha2code Daniel@0: Daniel@0: def get_name(self): Daniel@0: """Returns the country name. """ Daniel@0: Daniel@0: return self.name Daniel@0: Daniel@0: def get_top_artists(self): Daniel@0: """Returns a sequence of the most played artists.""" Daniel@0: Daniel@0: doc = self._request('geo.getTopArtists', True) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("artist"): Daniel@0: name = _extract(node, 'name') Daniel@0: playcount = _extract(node, "playcount") Daniel@0: Daniel@0: seq.append(TopItem(Artist(name, self.network), playcount)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_top_tracks(self): Daniel@0: """Returns a sequence of the most played tracks""" Daniel@0: Daniel@0: doc = self._request("geo.getTopTracks", True) Daniel@0: Daniel@0: seq = [] Daniel@0: Daniel@0: for n in doc.getElementsByTagName('track'): Daniel@0: Daniel@0: title = _extract(n, 'name') Daniel@0: artist = _extract(n, 'name', 1) Daniel@0: playcount = _number(_extract(n, "playcount")) Daniel@0: Daniel@0: seq.append( TopItem(Track(artist, title, self.network), playcount)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_url(self, domain_name = DOMAIN_ENGLISH): Daniel@0: """Returns the url of the event page on the network. Daniel@0: * domain_name: The network's language domain. Possible values: Daniel@0: o DOMAIN_ENGLISH Daniel@0: o DOMAIN_GERMAN Daniel@0: o DOMAIN_SPANISH Daniel@0: o DOMAIN_FRENCH Daniel@0: o DOMAIN_ITALIAN Daniel@0: o DOMAIN_POLISH Daniel@0: o DOMAIN_PORTUGUESE Daniel@0: o DOMAIN_SWEDISH Daniel@0: o DOMAIN_TURKISH Daniel@0: o DOMAIN_RUSSIAN Daniel@0: o DOMAIN_JAPANESE Daniel@0: o DOMAIN_CHINESE Daniel@0: """ Daniel@0: Daniel@0: country_name = _url_safe(self.get_name()) Daniel@0: Daniel@0: return self.network._get_url(domain_name, "country") %{'country_name': country_name} Daniel@0: Daniel@0: Daniel@0: class Library(_BaseObject): Daniel@0: """A user's Last.fm library.""" Daniel@0: Daniel@0: user = None Daniel@0: Daniel@0: def __init__(self, user, network): Daniel@0: _BaseObject.__init__(self, network) Daniel@0: Daniel@0: if isinstance(user, User): Daniel@0: self.user = user Daniel@0: else: Daniel@0: self.user = User(user, self.network) Daniel@0: Daniel@0: self._albums_index = 0 Daniel@0: self._artists_index = 0 Daniel@0: self._tracks_index = 0 Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.Library(%s, %s)" %(repr(self.user), repr(self.network)) Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return repr(self.get_user()) + "'s Library" Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {'user': self.user.get_name()} Daniel@0: Daniel@0: def get_user(self): Daniel@0: """Returns the user who owns this library.""" Daniel@0: Daniel@0: return self.user Daniel@0: Daniel@0: def add_album(self, album): Daniel@0: """Add an album to this library.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params["artist"] = album.get_artist.get_name() Daniel@0: params["album"] = album.get_name() Daniel@0: Daniel@0: self._request("library.addAlbum", False, params) Daniel@0: Daniel@0: def add_artist(self, artist): Daniel@0: """Add an artist to this library.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params["artist"] = artist.get_name() Daniel@0: Daniel@0: self._request("library.addArtist", False, params) Daniel@0: Daniel@0: def add_track(self, track): Daniel@0: """Add a track to this library.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params["track"] = track.get_title() Daniel@0: Daniel@0: self._request("library.addTrack", False, params) Daniel@0: Daniel@0: def get_albums(self, artist=None, limit=50): Daniel@0: """ Daniel@0: Returns a sequence of Album objects Daniel@0: If no artist is specified, it will return all, sorted by playcount descendingly. Daniel@0: If limit==None it will return all (may take a while) Daniel@0: """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if artist: Daniel@0: params["artist"] = artist Daniel@0: Daniel@0: seq = [] Daniel@0: for node in _collect_nodes(limit, self, "library.getAlbums", True, params): Daniel@0: name = _extract(node, "name") Daniel@0: artist = _extract(node, "name", 1) Daniel@0: playcount = _number(_extract(node, "playcount")) Daniel@0: tagcount = _number(_extract(node, "tagcount")) Daniel@0: Daniel@0: seq.append(LibraryItem(Album(artist, name, self.network), playcount, tagcount)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_artists(self, limit=50): Daniel@0: """ Daniel@0: Returns a sequence of Album objects Daniel@0: if limit==None it will return all (may take a while) Daniel@0: """ Daniel@0: Daniel@0: seq = [] Daniel@0: for node in _collect_nodes(limit, self, "library.getArtists", True): Daniel@0: name = _extract(node, "name") Daniel@0: Daniel@0: playcount = _number(_extract(node, "playcount")) Daniel@0: tagcount = _number(_extract(node, "tagcount")) Daniel@0: Daniel@0: seq.append(LibraryItem(Artist(name, self.network), playcount, tagcount)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_tracks(self, artist=None, album=None, limit=50): Daniel@0: """ Daniel@0: Returns a sequence of Album objects Daniel@0: If limit==None it will return all (may take a while) Daniel@0: """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if artist: Daniel@0: params["artist"] = artist Daniel@0: if album: Daniel@0: params["album"] = album Daniel@0: Daniel@0: seq = [] Daniel@0: for node in _collect_nodes(limit, self, "library.getTracks", True, params): Daniel@0: name = _extract(node, "name") Daniel@0: artist = _extract(node, "name", 1) Daniel@0: playcount = _number(_extract(node, "playcount")) Daniel@0: tagcount = _number(_extract(node, "tagcount")) Daniel@0: Daniel@0: seq.append(LibraryItem(Track(artist, name, self.network), playcount, tagcount)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: Daniel@0: class Playlist(_BaseObject): Daniel@0: """A Last.fm user playlist.""" Daniel@0: Daniel@0: id = None Daniel@0: user = None Daniel@0: Daniel@0: def __init__(self, user, id, network): Daniel@0: _BaseObject.__init__(self, network) Daniel@0: Daniel@0: if isinstance(user, User): Daniel@0: self.user = user Daniel@0: else: Daniel@0: self.user = User(user, self.network) Daniel@0: Daniel@0: self.id = id Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return repr(self.user) + "'s playlist # " + repr(self.id) Daniel@0: Daniel@0: def _get_info_node(self): Daniel@0: """Returns the node from user.getPlaylists where this playlist's info is.""" Daniel@0: Daniel@0: doc = self._request("user.getPlaylists", True) Daniel@0: Daniel@0: for node in doc.getElementsByTagName("playlist"): Daniel@0: if _extract(node, "id") == str(self.get_id()): Daniel@0: return node Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {'user': self.user.get_name(), 'playlistID': self.get_id()} Daniel@0: Daniel@0: def get_id(self): Daniel@0: """Returns the playlist id.""" Daniel@0: Daniel@0: return self.id Daniel@0: Daniel@0: def get_user(self): Daniel@0: """Returns the owner user of this playlist.""" Daniel@0: Daniel@0: return self.user Daniel@0: Daniel@0: def get_tracks(self): Daniel@0: """Returns a list of the tracks on this user playlist.""" Daniel@0: Daniel@0: uri = _unicode('lastfm://playlist/%s') %self.get_id() Daniel@0: Daniel@0: return XSPF(uri, self.network).get_tracks() Daniel@0: Daniel@0: def add_track(self, track): Daniel@0: """Adds a Track to this Playlist.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params['artist'] = track.get_artist().get_name() Daniel@0: params['track'] = track.get_title() Daniel@0: Daniel@0: self._request('playlist.addTrack', False, params) Daniel@0: Daniel@0: def get_title(self): Daniel@0: """Returns the title of this playlist.""" Daniel@0: Daniel@0: return _extract(self._get_info_node(), "title") Daniel@0: Daniel@0: def get_creation_date(self): Daniel@0: """Returns the creation date of this playlist.""" Daniel@0: Daniel@0: return _extract(self._get_info_node(), "date") Daniel@0: Daniel@0: def get_size(self): Daniel@0: """Returns the number of tracks in this playlist.""" Daniel@0: Daniel@0: return _number(_extract(self._get_info_node(), "size")) Daniel@0: Daniel@0: def get_description(self): Daniel@0: """Returns the description of this playlist.""" Daniel@0: Daniel@0: return _extract(self._get_info_node(), "description") Daniel@0: Daniel@0: def get_duration(self): Daniel@0: """Returns the duration of this playlist in milliseconds.""" Daniel@0: Daniel@0: return _number(_extract(self._get_info_node(), "duration")) Daniel@0: Daniel@0: def is_streamable(self): Daniel@0: """Returns True if the playlist is streamable. Daniel@0: For a playlist to be streamable, it needs at least 45 tracks by 15 different artists.""" Daniel@0: Daniel@0: if _extract(self._get_info_node(), "streamable") == '1': Daniel@0: return True Daniel@0: else: Daniel@0: return False Daniel@0: Daniel@0: def has_track(self, track): Daniel@0: """Checks to see if track is already in the playlist. Daniel@0: * track: Any Track object. Daniel@0: """ Daniel@0: Daniel@0: return track in self.get_tracks() Daniel@0: Daniel@0: def get_cover_image(self, size = COVER_EXTRA_LARGE): Daniel@0: """ Daniel@0: Returns a uri to the cover image Daniel@0: size can be one of: Daniel@0: COVER_MEGA Daniel@0: COVER_EXTRA_LARGE Daniel@0: COVER_LARGE Daniel@0: COVER_MEDIUM Daniel@0: COVER_SMALL Daniel@0: """ Daniel@0: Daniel@0: return _extract(self._get_info_node(), "image")[size] Daniel@0: Daniel@0: def get_url(self, domain_name = DOMAIN_ENGLISH): Daniel@0: """Returns the url of the playlist on the network. Daniel@0: * domain_name: The network's language domain. Possible values: Daniel@0: o DOMAIN_ENGLISH Daniel@0: o DOMAIN_GERMAN Daniel@0: o DOMAIN_SPANISH Daniel@0: o DOMAIN_FRENCH Daniel@0: o DOMAIN_ITALIAN Daniel@0: o DOMAIN_POLISH Daniel@0: o DOMAIN_PORTUGUESE Daniel@0: o DOMAIN_SWEDISH Daniel@0: o DOMAIN_TURKISH Daniel@0: o DOMAIN_RUSSIAN Daniel@0: o DOMAIN_JAPANESE Daniel@0: o DOMAIN_CHINESE Daniel@0: """ Daniel@0: Daniel@0: english_url = _extract(self._get_info_node(), "url") Daniel@0: appendix = english_url[english_url.rfind("/") + 1:] Daniel@0: Daniel@0: return self.network._get_url(domain_name, "playlist") %{'appendix': appendix, "user": self.get_user().get_name()} Daniel@0: Daniel@0: Daniel@0: class Tag(_BaseObject): Daniel@0: """A Last.fm object tag.""" Daniel@0: Daniel@0: # TODO: getWeeklyArtistChart (too lazy, i'll wait for when someone requests it) Daniel@0: Daniel@0: name = None Daniel@0: Daniel@0: def __init__(self, name, network): Daniel@0: _BaseObject.__init__(self, network) Daniel@0: Daniel@0: self.name = name Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.Tag(%s, %s)" %(repr(self.name), repr(self.network)) Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return self.get_name() Daniel@0: Daniel@0: def __eq__(self, other): Daniel@0: return self.get_name().lower() == other.get_name().lower() Daniel@0: Daniel@0: def __ne__(self, other): Daniel@0: return self.get_name().lower() != other.get_name().lower() Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {'tag': self.get_name()} Daniel@0: Daniel@0: def get_name(self, properly_capitalized=False): Daniel@0: """Returns the name of the tag. """ Daniel@0: Daniel@0: if properly_capitalized: Daniel@0: self.name = _extract(self._request("tag.getInfo", True), "name") Daniel@0: Daniel@0: return self.name Daniel@0: Daniel@0: def get_similar(self): Daniel@0: """Returns the tags similar to this one, ordered by similarity. """ Daniel@0: Daniel@0: doc = self._request('tag.getSimilar', True) Daniel@0: Daniel@0: seq = [] Daniel@0: names = _extract_all(doc, 'name') Daniel@0: for name in names: Daniel@0: seq.append(Tag(name, self.network)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_top_albums(self): Daniel@0: """Retuns a list of the top albums.""" Daniel@0: Daniel@0: doc = self._request('tag.getTopAlbums', True) Daniel@0: Daniel@0: seq = [] Daniel@0: Daniel@0: for node in doc.getElementsByTagName("album"): Daniel@0: name = _extract(node, "name") Daniel@0: artist = _extract(node, "name", 1) Daniel@0: playcount = _extract(node, "playcount") Daniel@0: Daniel@0: seq.append(TopItem(Album(artist, name, self.network), playcount)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_top_tracks(self): Daniel@0: """Returns a list of the most played Tracks by this artist.""" Daniel@0: Daniel@0: doc = self._request("tag.getTopTracks", True) Daniel@0: Daniel@0: seq = [] Daniel@0: for track in doc.getElementsByTagName('track'): Daniel@0: Daniel@0: title = _extract(track, "name") Daniel@0: artist = _extract(track, "name", 1) Daniel@0: playcount = _number(_extract(track, "playcount")) Daniel@0: Daniel@0: seq.append( TopItem(Track(artist, title, self.network), playcount) ) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_top_artists(self): Daniel@0: """Returns a sequence of the most played artists.""" Daniel@0: Daniel@0: doc = self._request('tag.getTopArtists', True) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("artist"): Daniel@0: name = _extract(node, 'name') Daniel@0: playcount = _extract(node, "playcount") Daniel@0: Daniel@0: seq.append(TopItem(Artist(name, self.network), playcount)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_weekly_chart_dates(self): Daniel@0: """Returns a list of From and To tuples for the available charts.""" Daniel@0: Daniel@0: doc = self._request("tag.getWeeklyChartList", True) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("chart"): Daniel@0: seq.append( (node.getAttribute("from"), node.getAttribute("to")) ) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_weekly_artist_charts(self, from_date = None, to_date = None): Daniel@0: """Returns the weekly artist charts for the week starting from the from_date value to the to_date value.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if from_date and to_date: Daniel@0: params["from"] = from_date Daniel@0: params["to"] = to_date Daniel@0: Daniel@0: doc = self._request("tag.getWeeklyArtistChart", True, params) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("artist"): Daniel@0: item = Artist(_extract(node, "name"), self.network) Daniel@0: weight = _number(_extract(node, "weight")) Daniel@0: seq.append(TopItem(item, weight)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_url(self, domain_name = DOMAIN_ENGLISH): Daniel@0: """Returns the url of the tag page on the network. Daniel@0: * domain_name: The network's language domain. Possible values: Daniel@0: o DOMAIN_ENGLISH Daniel@0: o DOMAIN_GERMAN Daniel@0: o DOMAIN_SPANISH Daniel@0: o DOMAIN_FRENCH Daniel@0: o DOMAIN_ITALIAN Daniel@0: o DOMAIN_POLISH Daniel@0: o DOMAIN_PORTUGUESE Daniel@0: o DOMAIN_SWEDISH Daniel@0: o DOMAIN_TURKISH Daniel@0: o DOMAIN_RUSSIAN Daniel@0: o DOMAIN_JAPANESE Daniel@0: o DOMAIN_CHINESE Daniel@0: """ Daniel@0: Daniel@0: name = _url_safe(self.get_name()) Daniel@0: Daniel@0: return self.network._get_url(domain_name, "tag") %{'name': name} Daniel@0: Daniel@0: class Track(_BaseObject, _Taggable): Daniel@0: """A Last.fm track.""" Daniel@0: Daniel@0: artist = None Daniel@0: title = None Daniel@0: Daniel@0: def __init__(self, artist, title, network): Daniel@0: _BaseObject.__init__(self, network) Daniel@0: _Taggable.__init__(self, 'track') Daniel@0: Daniel@0: if isinstance(artist, Artist): Daniel@0: self.artist = artist Daniel@0: else: Daniel@0: self.artist = Artist(artist, self.network) Daniel@0: Daniel@0: self.title = title Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.Track(%s, %s, %s)" %(repr(self.artist.name), repr(self.title), repr(self.network)) Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return self.get_artist().get_name() + ' - ' + self.get_title() Daniel@0: Daniel@0: def __eq__(self, other): Daniel@0: return (self.get_title().lower() == other.get_title().lower()) and (self.get_artist().get_name().lower() == other.get_artist().get_name().lower()) Daniel@0: Daniel@0: def __ne__(self, other): Daniel@0: return (self.get_title().lower() != other.get_title().lower()) or (self.get_artist().get_name().lower() != other.get_artist().get_name().lower()) Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {'artist': self.get_artist().get_name(), 'track': self.get_title()} Daniel@0: Daniel@0: def get_artist(self): Daniel@0: """Returns the associated Artist object.""" Daniel@0: Daniel@0: return self.artist Daniel@0: Daniel@0: def get_title(self, properly_capitalized=False): Daniel@0: """Returns the track title.""" Daniel@0: Daniel@0: if properly_capitalized: Daniel@0: self.title = _extract(self._request("track.getInfo", True), "name") Daniel@0: Daniel@0: return self.title Daniel@0: Daniel@0: def get_name(self, properly_capitalized=False): Daniel@0: """Returns the track title (alias to Track.get_title).""" Daniel@0: Daniel@0: return self.get_title(properly_capitalized) Daniel@0: Daniel@0: def get_id(self): Daniel@0: """Returns the track id on the network.""" Daniel@0: Daniel@0: doc = self._request("track.getInfo", True) Daniel@0: Daniel@0: return _extract(doc, "id") Daniel@0: Daniel@0: def get_duration(self): Daniel@0: """Returns the track duration.""" Daniel@0: Daniel@0: doc = self._request("track.getInfo", True) Daniel@0: Daniel@0: return _number(_extract(doc, "duration")) Daniel@0: Daniel@0: def get_mbid(self): Daniel@0: """Returns the MusicBrainz ID of this track.""" Daniel@0: Daniel@0: doc = self._request("track.getInfo", True) Daniel@0: Daniel@0: return _extract(doc, "mbid") Daniel@0: Daniel@0: def get_listener_count(self): Daniel@0: """Returns the listener count.""" Daniel@0: Daniel@0: if hasattr(self, "listener_count"): Daniel@0: return self.listener_count Daniel@0: else: Daniel@0: doc = self._request("track.getInfo", True) Daniel@0: self.listener_count = _number(_extract(doc, "listeners")) Daniel@0: return self.listener_count Daniel@0: Daniel@0: def get_playcount(self): Daniel@0: """Returns the play count.""" Daniel@0: Daniel@0: doc = self._request("track.getInfo", True) Daniel@0: return _number(_extract(doc, "playcount")) Daniel@0: Daniel@0: def is_streamable(self): Daniel@0: """Returns True if the track is available at Last.fm.""" Daniel@0: Daniel@0: doc = self._request("track.getInfo", True) Daniel@0: return _extract(doc, "streamable") == "1" Daniel@0: Daniel@0: def is_fulltrack_available(self): Daniel@0: """Returns True if the fulltrack is available for streaming.""" Daniel@0: Daniel@0: doc = self._request("track.getInfo", True) Daniel@0: return doc.getElementsByTagName("streamable")[0].getAttribute("fulltrack") == "1" Daniel@0: Daniel@0: def get_album(self): Daniel@0: """Returns the album object of this track.""" Daniel@0: Daniel@0: doc = self._request("track.getInfo", True) Daniel@0: Daniel@0: albums = doc.getElementsByTagName("album") Daniel@0: Daniel@0: if len(albums) == 0: Daniel@0: return Daniel@0: Daniel@0: node = doc.getElementsByTagName("album")[0] Daniel@0: return Album(_extract(node, "artist"), _extract(node, "title"), self.network) Daniel@0: Daniel@0: def get_wiki_published_date(self): Daniel@0: """Returns the date of publishing this version of the wiki.""" Daniel@0: Daniel@0: doc = self._request("track.getInfo", True) Daniel@0: Daniel@0: if len(doc.getElementsByTagName("wiki")) == 0: Daniel@0: return Daniel@0: Daniel@0: node = doc.getElementsByTagName("wiki")[0] Daniel@0: Daniel@0: return _extract(node, "published") Daniel@0: Daniel@0: def get_wiki_summary(self): Daniel@0: """Returns the summary of the wiki.""" Daniel@0: Daniel@0: doc = self._request("track.getInfo", True) Daniel@0: Daniel@0: if len(doc.getElementsByTagName("wiki")) == 0: Daniel@0: return Daniel@0: Daniel@0: node = doc.getElementsByTagName("wiki")[0] Daniel@0: Daniel@0: return _extract(node, "summary") Daniel@0: Daniel@0: def get_wiki_content(self): Daniel@0: """Returns the content of the wiki.""" Daniel@0: Daniel@0: doc = self._request("track.getInfo", True) Daniel@0: Daniel@0: if len(doc.getElementsByTagName("wiki")) == 0: Daniel@0: return Daniel@0: Daniel@0: node = doc.getElementsByTagName("wiki")[0] Daniel@0: Daniel@0: return _extract(node, "content") Daniel@0: Daniel@0: def love(self): Daniel@0: """Adds the track to the user's loved tracks. """ Daniel@0: Daniel@0: self._request('track.love') Daniel@0: Daniel@0: def ban(self): Daniel@0: """Ban this track from ever playing on the radio. """ Daniel@0: Daniel@0: self._request('track.ban') Daniel@0: Daniel@0: def get_similar(self): Daniel@0: """Returns similar tracks for this track on the network, based on listening data. """ Daniel@0: Daniel@0: doc = self._request('track.getSimilar', True) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("track"): Daniel@0: title = _extract(node, 'name') Daniel@0: artist = _extract(node, 'name', 1) Daniel@0: match = _number(_extract(node, "match")) Daniel@0: Daniel@0: seq.append(SimilarItem(Track(artist, title, self.network), match)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_top_fans(self, limit = None): Daniel@0: """Returns a list of the Users who played this track.""" Daniel@0: Daniel@0: doc = self._request('track.getTopFans', True) Daniel@0: Daniel@0: seq = [] Daniel@0: Daniel@0: elements = doc.getElementsByTagName('user') Daniel@0: Daniel@0: for element in elements: Daniel@0: if limit and len(seq) >= limit: Daniel@0: break Daniel@0: Daniel@0: name = _extract(element, 'name') Daniel@0: weight = _number(_extract(element, 'weight')) Daniel@0: Daniel@0: seq.append(TopItem(User(name, self.network), weight)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def share(self, users, message = None): Daniel@0: """Shares this track (sends out recommendations). Daniel@0: * users: A list that can contain usernames, emails, User objects, or all of them. Daniel@0: * message: A message to include in the recommendation message. Daniel@0: """ Daniel@0: Daniel@0: #last.fm currently accepts a max of 10 recipient at a time Daniel@0: while(len(users) > 10): Daniel@0: section = users[0:9] Daniel@0: users = users[9:] Daniel@0: self.share(section, message) Daniel@0: Daniel@0: nusers = [] Daniel@0: for user in users: Daniel@0: if isinstance(user, User): Daniel@0: nusers.append(user.get_name()) Daniel@0: else: Daniel@0: nusers.append(user) Daniel@0: Daniel@0: params = self._get_params() Daniel@0: recipients = ','.join(nusers) Daniel@0: params['recipient'] = recipients Daniel@0: if message: Daniel@0: params['message'] = message Daniel@0: Daniel@0: self._request('track.share', False, params) Daniel@0: Daniel@0: def get_url(self, domain_name = DOMAIN_ENGLISH): Daniel@0: """Returns the url of the track page on the network. Daniel@0: * domain_name: The network's language domain. Possible values: Daniel@0: o DOMAIN_ENGLISH Daniel@0: o DOMAIN_GERMAN Daniel@0: o DOMAIN_SPANISH Daniel@0: o DOMAIN_FRENCH Daniel@0: o DOMAIN_ITALIAN Daniel@0: o DOMAIN_POLISH Daniel@0: o DOMAIN_PORTUGUESE Daniel@0: o DOMAIN_SWEDISH Daniel@0: o DOMAIN_TURKISH Daniel@0: o DOMAIN_RUSSIAN Daniel@0: o DOMAIN_JAPANESE Daniel@0: o DOMAIN_CHINESE Daniel@0: """ Daniel@0: Daniel@0: artist = _url_safe(self.get_artist().get_name()) Daniel@0: title = _url_safe(self.get_title()) Daniel@0: Daniel@0: return self.network._get_url(domain_name, "track") %{'domain': self.network._get_language_domain(domain_name), 'artist': artist, 'title': title} Daniel@0: Daniel@0: def get_shouts(self, limit=50): Daniel@0: """ Daniel@0: Returns a sequqence of Shout objects Daniel@0: """ Daniel@0: Daniel@0: shouts = [] Daniel@0: for node in _collect_nodes(limit, self, "track.getShouts", False): Daniel@0: shouts.append(Shout( Daniel@0: _extract(node, "body"), Daniel@0: User(_extract(node, "author"), self.network), Daniel@0: _extract(node, "date") Daniel@0: ) Daniel@0: ) Daniel@0: return shouts Daniel@0: Daniel@0: class Group(_BaseObject): Daniel@0: """A Last.fm group.""" Daniel@0: Daniel@0: name = None Daniel@0: Daniel@0: def __init__(self, group_name, network): Daniel@0: _BaseObject.__init__(self, network) Daniel@0: Daniel@0: self.name = group_name Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.Group(%s, %s)" %(repr(self.name), repr(self.network)) Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return self.get_name() Daniel@0: Daniel@0: def __eq__(self, other): Daniel@0: return self.get_name().lower() == other.get_name().lower() Daniel@0: Daniel@0: def __ne__(self, other): Daniel@0: return self.get_name() != other.get_name() Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {'group': self.get_name()} Daniel@0: Daniel@0: def get_name(self): Daniel@0: """Returns the group name. """ Daniel@0: return self.name Daniel@0: Daniel@0: def get_weekly_chart_dates(self): Daniel@0: """Returns a list of From and To tuples for the available charts.""" Daniel@0: Daniel@0: doc = self._request("group.getWeeklyChartList", True) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("chart"): Daniel@0: seq.append( (node.getAttribute("from"), node.getAttribute("to")) ) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_weekly_artist_charts(self, from_date = None, to_date = None): Daniel@0: """Returns the weekly artist charts for the week starting from the from_date value to the to_date value.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if from_date and to_date: Daniel@0: params["from"] = from_date Daniel@0: params["to"] = to_date Daniel@0: Daniel@0: doc = self._request("group.getWeeklyArtistChart", True, params) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("artist"): Daniel@0: item = Artist(_extract(node, "name"), self.network) Daniel@0: weight = _number(_extract(node, "playcount")) Daniel@0: seq.append(TopItem(item, weight)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_weekly_album_charts(self, from_date = None, to_date = None): Daniel@0: """Returns the weekly album charts for the week starting from the from_date value to the to_date value.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if from_date and to_date: Daniel@0: params["from"] = from_date Daniel@0: params["to"] = to_date Daniel@0: Daniel@0: doc = self._request("group.getWeeklyAlbumChart", True, params) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("album"): Daniel@0: item = Album(_extract(node, "artist"), _extract(node, "name"), self.network) Daniel@0: weight = _number(_extract(node, "playcount")) Daniel@0: seq.append(TopItem(item, weight)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_weekly_track_charts(self, from_date = None, to_date = None): Daniel@0: """Returns the weekly track charts for the week starting from the from_date value to the to_date value.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if from_date and to_date: Daniel@0: params["from"] = from_date Daniel@0: params["to"] = to_date Daniel@0: Daniel@0: doc = self._request("group.getWeeklyTrackChart", True, params) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("track"): Daniel@0: item = Track(_extract(node, "artist"), _extract(node, "name"), self.network) Daniel@0: weight = _number(_extract(node, "playcount")) Daniel@0: seq.append(TopItem(item, weight)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_url(self, domain_name = DOMAIN_ENGLISH): Daniel@0: """Returns the url of the group page on the network. Daniel@0: * domain_name: The network's language domain. Possible values: Daniel@0: o DOMAIN_ENGLISH Daniel@0: o DOMAIN_GERMAN Daniel@0: o DOMAIN_SPANISH Daniel@0: o DOMAIN_FRENCH Daniel@0: o DOMAIN_ITALIAN Daniel@0: o DOMAIN_POLISH Daniel@0: o DOMAIN_PORTUGUESE Daniel@0: o DOMAIN_SWEDISH Daniel@0: o DOMAIN_TURKISH Daniel@0: o DOMAIN_RUSSIAN Daniel@0: o DOMAIN_JAPANESE Daniel@0: o DOMAIN_CHINESE Daniel@0: """ Daniel@0: Daniel@0: name = _url_safe(self.get_name()) Daniel@0: Daniel@0: return self.network._get_url(domain_name, "group") %{'name': name} Daniel@0: Daniel@0: def get_members(self, limit=50): Daniel@0: """ Daniel@0: Returns a sequence of User objects Daniel@0: if limit==None it will return all Daniel@0: """ Daniel@0: Daniel@0: nodes = _collect_nodes(limit, self, "group.getMembers", False) Daniel@0: Daniel@0: users = [] Daniel@0: Daniel@0: for node in nodes: Daniel@0: users.append(User(_extract(node, "name"), self.network)) Daniel@0: Daniel@0: return users Daniel@0: Daniel@0: class XSPF(_BaseObject): Daniel@0: "A Last.fm XSPF playlist.""" Daniel@0: Daniel@0: uri = None Daniel@0: Daniel@0: def __init__(self, uri, network): Daniel@0: _BaseObject.__init__(self, network) Daniel@0: Daniel@0: self.uri = uri Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {'playlistURL': self.get_uri()} Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return self.get_uri() Daniel@0: Daniel@0: def __eq__(self, other): Daniel@0: return self.get_uri() == other.get_uri() Daniel@0: Daniel@0: def __ne__(self, other): Daniel@0: return self.get_uri() != other.get_uri() Daniel@0: Daniel@0: def get_uri(self): Daniel@0: """Returns the Last.fm playlist URI. """ Daniel@0: Daniel@0: return self.uri Daniel@0: Daniel@0: def get_tracks(self): Daniel@0: """Returns the tracks on this playlist.""" Daniel@0: Daniel@0: doc = self._request('playlist.fetch', True) Daniel@0: Daniel@0: seq = [] Daniel@0: for n in doc.getElementsByTagName('track'): Daniel@0: title = _extract(n, 'title') Daniel@0: artist = _extract(n, 'creator') Daniel@0: Daniel@0: seq.append(Track(artist, title, self.network)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: class User(_BaseObject): Daniel@0: """A Last.fm user.""" Daniel@0: Daniel@0: name = None Daniel@0: Daniel@0: def __init__(self, user_name, network): Daniel@0: _BaseObject.__init__(self, network) Daniel@0: Daniel@0: self.name = user_name Daniel@0: Daniel@0: self._past_events_index = 0 Daniel@0: self._recommended_events_index = 0 Daniel@0: self._recommended_artists_index = 0 Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.User(%s, %s)" %(repr(self.name), repr(self.network)) Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return self.get_name() Daniel@0: Daniel@0: def __eq__(self, another): Daniel@0: return self.get_name() == another.get_name() Daniel@0: Daniel@0: def __ne__(self, another): Daniel@0: return self.get_name() != another.get_name() Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {"user": self.get_name()} Daniel@0: Daniel@0: def get_name(self, properly_capitalized=False): Daniel@0: """Returns the nuser name.""" Daniel@0: Daniel@0: if properly_capitalized: Daniel@0: self.name = _extract(self._request("user.getInfo", True), "name") Daniel@0: Daniel@0: return self.name Daniel@0: Daniel@0: def get_upcoming_events(self): Daniel@0: """Returns all the upcoming events for this user. """ Daniel@0: Daniel@0: doc = self._request('user.getEvents', True) Daniel@0: Daniel@0: ids = _extract_all(doc, 'id') Daniel@0: events = [] Daniel@0: Daniel@0: for e_id in ids: Daniel@0: events.append(Event(e_id, self.network)) Daniel@0: Daniel@0: return events Daniel@0: Daniel@0: def get_friends(self, limit = 50): Daniel@0: """Returns a list of the user's friends. """ Daniel@0: Daniel@0: seq = [] Daniel@0: for node in _collect_nodes(limit, self, "user.getFriends", False): Daniel@0: seq.append(User(_extract(node, "name"), self.network)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_loved_tracks(self, limit=50): Daniel@0: """Returns this user's loved track as a sequence of LovedTrack objects Daniel@0: in reverse order of their timestamp, all the way back to the first track. Daniel@0: Daniel@0: If limit==None, it will try to pull all the available data. Daniel@0: Daniel@0: This method uses caching. Enable caching only if you're pulling a Daniel@0: large amount of data. Daniel@0: Daniel@0: Use extract_items() with the return of this function to Daniel@0: get only a sequence of Track objects with no playback dates. """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if limit: Daniel@0: params['limit'] = limit Daniel@0: Daniel@0: seq = [] Daniel@0: for track in _collect_nodes(limit, self, "user.getLovedTracks", True, params): Daniel@0: Daniel@0: title = _extract(track, "name") Daniel@0: artist = _extract(track, "name", 1) Daniel@0: date = _extract(track, "date") Daniel@0: timestamp = track.getElementsByTagName("date")[0].getAttribute("uts") Daniel@0: Daniel@0: seq.append(LovedTrack(Track(artist, title, self.network), date, timestamp)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_neighbours(self, limit = 50): Daniel@0: """Returns a list of the user's friends.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if limit: Daniel@0: params['limit'] = limit Daniel@0: Daniel@0: doc = self._request('user.getNeighbours', True, params) Daniel@0: Daniel@0: seq = [] Daniel@0: names = _extract_all(doc, 'name') Daniel@0: Daniel@0: for name in names: Daniel@0: seq.append(User(name, self.network)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_past_events(self, limit=50): Daniel@0: """ Daniel@0: Returns a sequence of Event objects Daniel@0: if limit==None it will return all Daniel@0: """ Daniel@0: Daniel@0: seq = [] Daniel@0: for n in _collect_nodes(limit, self, "user.getPastEvents", False): Daniel@0: seq.append(Event(_extract(n, "id"), self.network)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_playlists(self): Daniel@0: """Returns a list of Playlists that this user owns.""" Daniel@0: Daniel@0: doc = self._request("user.getPlaylists", True) Daniel@0: Daniel@0: playlists = [] Daniel@0: for playlist_id in _extract_all(doc, "id"): Daniel@0: playlists.append(Playlist(self.get_name(), playlist_id, self.network)) Daniel@0: Daniel@0: return playlists Daniel@0: Daniel@0: def get_now_playing(self): Daniel@0: """Returns the currently playing track, or None if nothing is playing. """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params['limit'] = '1' Daniel@0: Daniel@0: doc = self._request('user.getRecentTracks', False, params) Daniel@0: Daniel@0: e = doc.getElementsByTagName('track')[0] Daniel@0: Daniel@0: if not e.hasAttribute('nowplaying'): Daniel@0: return None Daniel@0: Daniel@0: artist = _extract(e, 'artist') Daniel@0: title = _extract(e, 'name') Daniel@0: Daniel@0: return Track(artist, title, self.network) Daniel@0: Daniel@0: Daniel@0: def get_recent_tracks(self, limit = 10): Daniel@0: """Returns this user's played track as a sequence of PlayedTrack objects Daniel@0: in reverse order of their playtime, all the way back to the first track. Daniel@0: Daniel@0: If limit==None, it will try to pull all the available data. Daniel@0: Daniel@0: This method uses caching. Enable caching only if you're pulling a Daniel@0: large amount of data. Daniel@0: Daniel@0: Use extract_items() with the return of this function to Daniel@0: get only a sequence of Track objects with no playback dates. """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if limit: Daniel@0: params['limit'] = limit Daniel@0: Daniel@0: seq = [] Daniel@0: for track in _collect_nodes(limit, self, "user.getRecentTracks", True, params): Daniel@0: Daniel@0: if track.hasAttribute('nowplaying'): Daniel@0: continue #to prevent the now playing track from sneaking in here Daniel@0: Daniel@0: title = _extract(track, "name") Daniel@0: artist = _extract(track, "artist") Daniel@0: date = _extract(track, "date") Daniel@0: timestamp = track.getElementsByTagName("date")[0].getAttribute("uts") Daniel@0: Daniel@0: seq.append(PlayedTrack(Track(artist, title, self.network), date, timestamp)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_id(self): Daniel@0: """Returns the user id.""" Daniel@0: Daniel@0: doc = self._request("user.getInfo", True) Daniel@0: Daniel@0: return _extract(doc, "id") Daniel@0: Daniel@0: def get_language(self): Daniel@0: """Returns the language code of the language used by the user.""" Daniel@0: Daniel@0: doc = self._request("user.getInfo", True) Daniel@0: Daniel@0: return _extract(doc, "lang") Daniel@0: Daniel@0: def get_country(self): Daniel@0: """Returns the name of the country of the user.""" Daniel@0: Daniel@0: doc = self._request("user.getInfo", True) Daniel@0: Daniel@0: return Country(_extract(doc, "country"), self.network) Daniel@0: Daniel@0: def get_age(self): Daniel@0: """Returns the user's age.""" Daniel@0: Daniel@0: doc = self._request("user.getInfo", True) Daniel@0: Daniel@0: return _number(_extract(doc, "age")) Daniel@0: Daniel@0: def get_gender(self): Daniel@0: """Returns the user's gender. Either USER_MALE or USER_FEMALE.""" Daniel@0: Daniel@0: doc = self._request("user.getInfo", True) Daniel@0: Daniel@0: value = _extract(doc, "gender") Daniel@0: Daniel@0: if value == 'm': Daniel@0: return USER_MALE Daniel@0: elif value == 'f': Daniel@0: return USER_FEMALE Daniel@0: Daniel@0: return None Daniel@0: Daniel@0: def is_subscriber(self): Daniel@0: """Returns whether the user is a subscriber or not. True or False.""" Daniel@0: Daniel@0: doc = self._request("user.getInfo", True) Daniel@0: Daniel@0: return _extract(doc, "subscriber") == "1" Daniel@0: Daniel@0: def get_playcount(self): Daniel@0: """Returns the user's playcount so far.""" Daniel@0: Daniel@0: doc = self._request("user.getInfo", True) Daniel@0: Daniel@0: return _number(_extract(doc, "playcount")) Daniel@0: Daniel@0: def get_top_albums(self, period = PERIOD_OVERALL): Daniel@0: """Returns the top albums played by a user. Daniel@0: * period: The period of time. Possible values: Daniel@0: o PERIOD_OVERALL Daniel@0: o PERIOD_7DAYS Daniel@0: o PERIOD_3MONTHS Daniel@0: o PERIOD_6MONTHS Daniel@0: o PERIOD_12MONTHS Daniel@0: """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params['period'] = period Daniel@0: Daniel@0: doc = self._request('user.getTopAlbums', True, params) Daniel@0: Daniel@0: seq = [] Daniel@0: for album in doc.getElementsByTagName('album'): Daniel@0: name = _extract(album, 'name') Daniel@0: artist = _extract(album, 'name', 1) Daniel@0: playcount = _extract(album, "playcount") Daniel@0: Daniel@0: seq.append(TopItem(Album(artist, name, self.network), playcount)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_top_artists(self, period = PERIOD_OVERALL): Daniel@0: """Returns the top artists played by a user. Daniel@0: * period: The period of time. Possible values: Daniel@0: o PERIOD_OVERALL Daniel@0: o PERIOD_7DAYS Daniel@0: o PERIOD_3MONTHS Daniel@0: o PERIOD_6MONTHS Daniel@0: o PERIOD_12MONTHS Daniel@0: """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params['period'] = period Daniel@0: Daniel@0: doc = self._request('user.getTopArtists', True, params) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName('artist'): Daniel@0: name = _extract(node, 'name') Daniel@0: playcount = _extract(node, "playcount") Daniel@0: Daniel@0: seq.append(TopItem(Artist(name, self.network), playcount)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_top_tags(self, limit=None): Daniel@0: """Returns a sequence of the top tags used by this user with their counts as TopItem objects. Daniel@0: * limit: The limit of how many tags to return. Daniel@0: """ Daniel@0: Daniel@0: doc = self._request("user.getTopTags", True) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("tag"): Daniel@0: seq.append(TopItem(Tag(_extract(node, "name"), self.network), _extract(node, "count"))) Daniel@0: Daniel@0: if limit: Daniel@0: seq = seq[:limit] Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_top_tracks(self, period = PERIOD_OVERALL): Daniel@0: """Returns the top tracks played by a user. Daniel@0: * period: The period of time. Possible values: Daniel@0: o PERIOD_OVERALL Daniel@0: o PERIOD_7DAYS Daniel@0: o PERIOD_3MONTHS Daniel@0: o PERIOD_6MONTHS Daniel@0: o PERIOD_12MONTHS Daniel@0: """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params['period'] = period Daniel@0: Daniel@0: doc = self._request('user.getTopTracks', True, params) Daniel@0: Daniel@0: seq = [] Daniel@0: for track in doc.getElementsByTagName('track'): Daniel@0: name = _extract(track, 'name') Daniel@0: artist = _extract(track, 'name', 1) Daniel@0: playcount = _extract(track, "playcount") Daniel@0: Daniel@0: seq.append(TopItem(Track(artist, name, self.network), playcount)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_weekly_chart_dates(self): Daniel@0: """Returns a list of From and To tuples for the available charts.""" Daniel@0: Daniel@0: doc = self._request("user.getWeeklyChartList", True) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("chart"): Daniel@0: seq.append( (node.getAttribute("from"), node.getAttribute("to")) ) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_weekly_artist_charts(self, from_date = None, to_date = None): Daniel@0: """Returns the weekly artist charts for the week starting from the from_date value to the to_date value.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if from_date and to_date: Daniel@0: params["from"] = from_date Daniel@0: params["to"] = to_date Daniel@0: Daniel@0: doc = self._request("user.getWeeklyArtistChart", True, params) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("artist"): Daniel@0: item = Artist(_extract(node, "name"), self.network) Daniel@0: weight = _number(_extract(node, "playcount")) Daniel@0: seq.append(TopItem(item, weight)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_weekly_album_charts(self, from_date = None, to_date = None): Daniel@0: """Returns the weekly album charts for the week starting from the from_date value to the to_date value.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if from_date and to_date: Daniel@0: params["from"] = from_date Daniel@0: params["to"] = to_date Daniel@0: Daniel@0: doc = self._request("user.getWeeklyAlbumChart", True, params) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("album"): Daniel@0: item = Album(_extract(node, "artist"), _extract(node, "name"), self.network) Daniel@0: weight = _number(_extract(node, "playcount")) Daniel@0: seq.append(TopItem(item, weight)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_weekly_track_charts(self, from_date = None, to_date = None): Daniel@0: """Returns the weekly track charts for the week starting from the from_date value to the to_date value.""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if from_date and to_date: Daniel@0: params["from"] = from_date Daniel@0: params["to"] = to_date Daniel@0: Daniel@0: doc = self._request("user.getWeeklyTrackChart", True, params) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("track"): Daniel@0: item = Track(_extract(node, "artist"), _extract(node, "name"), self.network) Daniel@0: weight = _number(_extract(node, "playcount")) Daniel@0: seq.append(TopItem(item, weight)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def compare_with_user(self, user, shared_artists_limit = None): Daniel@0: """Compare this user with another Last.fm user. Daniel@0: Returns a sequence (tasteometer_score, (shared_artist1, shared_artist2, ...)) Daniel@0: user: A User object or a username string/unicode object. Daniel@0: """ Daniel@0: Daniel@0: if isinstance(user, User): Daniel@0: user = user.get_name() Daniel@0: Daniel@0: params = self._get_params() Daniel@0: if shared_artists_limit: Daniel@0: params['limit'] = shared_artists_limit Daniel@0: params['type1'] = 'user' Daniel@0: params['type2'] = 'user' Daniel@0: params['value1'] = self.get_name() Daniel@0: params['value2'] = user Daniel@0: Daniel@0: doc = self._request('tasteometer.compare', False, params) Daniel@0: Daniel@0: score = _extract(doc, 'score') Daniel@0: Daniel@0: artists = doc.getElementsByTagName('artists')[0] Daniel@0: shared_artists_names = _extract_all(artists, 'name') Daniel@0: Daniel@0: shared_artists_seq = [] Daniel@0: Daniel@0: for name in shared_artists_names: Daniel@0: shared_artists_seq.append(Artist(name, self.network)) Daniel@0: Daniel@0: return (score, shared_artists_seq) Daniel@0: Daniel@0: def get_image(self): Daniel@0: """Returns the user's avatar.""" Daniel@0: Daniel@0: doc = self._request("user.getInfo", True) Daniel@0: Daniel@0: return _extract(doc, "image") Daniel@0: Daniel@0: def get_url(self, domain_name = DOMAIN_ENGLISH): Daniel@0: """Returns the url of the user page on the network. Daniel@0: * domain_name: The network's language domain. Possible values: Daniel@0: o DOMAIN_ENGLISH Daniel@0: o DOMAIN_GERMAN Daniel@0: o DOMAIN_SPANISH Daniel@0: o DOMAIN_FRENCH Daniel@0: o DOMAIN_ITALIAN Daniel@0: o DOMAIN_POLISH Daniel@0: o DOMAIN_PORTUGUESE Daniel@0: o DOMAIN_SWEDISH Daniel@0: o DOMAIN_TURKISH Daniel@0: o DOMAIN_RUSSIAN Daniel@0: o DOMAIN_JAPANESE Daniel@0: o DOMAIN_CHINESE Daniel@0: """ Daniel@0: Daniel@0: name = _url_safe(self.get_name()) Daniel@0: Daniel@0: return self.network._get_url(domain_name, "user") %{'name': name} Daniel@0: Daniel@0: def get_library(self): Daniel@0: """Returns the associated Library object. """ Daniel@0: Daniel@0: return Library(self, self.network) Daniel@0: Daniel@0: def get_shouts(self, limit=50): Daniel@0: """ Daniel@0: Returns a sequqence of Shout objects Daniel@0: """ Daniel@0: Daniel@0: shouts = [] Daniel@0: for node in _collect_nodes(limit, self, "user.getShouts", False): Daniel@0: shouts.append(Shout( Daniel@0: _extract(node, "body"), Daniel@0: User(_extract(node, "author"), self.network), Daniel@0: _extract(node, "date") Daniel@0: ) Daniel@0: ) Daniel@0: return shouts Daniel@0: Daniel@0: def shout(self, message): Daniel@0: """ Daniel@0: Post a shout Daniel@0: """ Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params["message"] = message Daniel@0: Daniel@0: self._request("user.Shout", False, params) Daniel@0: Daniel@0: class AuthenticatedUser(User): Daniel@0: def __init__(self, network): Daniel@0: User.__init__(self, "", network); Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {"user": self.get_name()} Daniel@0: Daniel@0: def get_name(self): Daniel@0: """Returns the name of the authenticated user.""" Daniel@0: Daniel@0: doc = self._request("user.getInfo", True, {"user": ""}) # hack Daniel@0: Daniel@0: self.name = _extract(doc, "name") Daniel@0: return self.name Daniel@0: Daniel@0: def get_recommended_events(self, limit=50): Daniel@0: """ Daniel@0: Returns a sequence of Event objects Daniel@0: if limit==None it will return all Daniel@0: """ Daniel@0: Daniel@0: seq = [] Daniel@0: for node in _collect_nodes(limit, self, "user.getRecommendedEvents", False): Daniel@0: seq.append(Event(_extract(node, "id"), self.network)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_recommended_artists(self, limit=50): Daniel@0: """ Daniel@0: Returns a sequence of Event objects Daniel@0: if limit==None it will return all Daniel@0: """ Daniel@0: Daniel@0: seq = [] Daniel@0: for node in _collect_nodes(limit, self, "user.getRecommendedArtists", False): Daniel@0: seq.append(Artist(_extract(node, "name"), self.network)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: class _Search(_BaseObject): Daniel@0: """An abstract class. Use one of its derivatives.""" Daniel@0: Daniel@0: def __init__(self, ws_prefix, search_terms, network): Daniel@0: _BaseObject.__init__(self, network) Daniel@0: Daniel@0: self._ws_prefix = ws_prefix Daniel@0: self.search_terms = search_terms Daniel@0: Daniel@0: self._last_page_index = 0 Daniel@0: Daniel@0: def _get_params(self): Daniel@0: params = {} Daniel@0: Daniel@0: for key in self.search_terms.keys(): Daniel@0: params[key] = self.search_terms[key] Daniel@0: Daniel@0: return params Daniel@0: Daniel@0: def get_total_result_count(self): Daniel@0: """Returns the total count of all the results.""" Daniel@0: Daniel@0: doc = self._request(self._ws_prefix + ".search", True) Daniel@0: Daniel@0: return _extract(doc, "opensearch:totalResults") Daniel@0: Daniel@0: def _retreive_page(self, page_index): Daniel@0: """Returns the node of matches to be processed""" Daniel@0: Daniel@0: params = self._get_params() Daniel@0: params["page"] = str(page_index) Daniel@0: doc = self._request(self._ws_prefix + ".search", True, params) Daniel@0: Daniel@0: return doc.getElementsByTagName(self._ws_prefix + "matches")[0] Daniel@0: Daniel@0: def _retrieve_next_page(self): Daniel@0: self._last_page_index += 1 Daniel@0: return self._retreive_page(self._last_page_index) Daniel@0: Daniel@0: class AlbumSearch(_Search): Daniel@0: """Search for an album by name.""" Daniel@0: Daniel@0: def __init__(self, album_name, network): Daniel@0: Daniel@0: _Search.__init__(self, "album", {"album": album_name}, network) Daniel@0: Daniel@0: def get_next_page(self): Daniel@0: """Returns the next page of results as a sequence of Album objects.""" Daniel@0: Daniel@0: master_node = self._retrieve_next_page() Daniel@0: Daniel@0: seq = [] Daniel@0: for node in master_node.getElementsByTagName("album"): Daniel@0: seq.append(Album(_extract(node, "artist"), _extract(node, "name"), self.network)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: class ArtistSearch(_Search): Daniel@0: """Search for an artist by artist name.""" Daniel@0: Daniel@0: def __init__(self, artist_name, network): Daniel@0: _Search.__init__(self, "artist", {"artist": artist_name}, network) Daniel@0: Daniel@0: def get_next_page(self): Daniel@0: """Returns the next page of results as a sequence of Artist objects.""" Daniel@0: Daniel@0: master_node = self._retrieve_next_page() Daniel@0: Daniel@0: seq = [] Daniel@0: for node in master_node.getElementsByTagName("artist"): Daniel@0: artist = Artist(_extract(node, "name"), self.network) Daniel@0: artist.listener_count = _number(_extract(node, "listeners")) Daniel@0: seq.append(artist) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: class TagSearch(_Search): Daniel@0: """Search for a tag by tag name.""" Daniel@0: Daniel@0: def __init__(self, tag_name, network): Daniel@0: Daniel@0: _Search.__init__(self, "tag", {"tag": tag_name}, network) Daniel@0: Daniel@0: def get_next_page(self): Daniel@0: """Returns the next page of results as a sequence of Tag objects.""" Daniel@0: Daniel@0: master_node = self._retrieve_next_page() Daniel@0: Daniel@0: seq = [] Daniel@0: for node in master_node.getElementsByTagName("tag"): Daniel@0: tag = Tag(_extract(node, "name"), self.network) Daniel@0: tag.tag_count = _number(_extract(node, "count")) Daniel@0: seq.append(tag) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: class TrackSearch(_Search): Daniel@0: """Search for a track by track title. If you don't wanna narrow the results down Daniel@0: by specifying the artist name, set it to empty string.""" Daniel@0: Daniel@0: def __init__(self, artist_name, track_title, network): Daniel@0: Daniel@0: _Search.__init__(self, "track", {"track": track_title, "artist": artist_name}, network) Daniel@0: Daniel@0: def get_next_page(self): Daniel@0: """Returns the next page of results as a sequence of Track objects.""" Daniel@0: Daniel@0: master_node = self._retrieve_next_page() Daniel@0: Daniel@0: seq = [] Daniel@0: for node in master_node.getElementsByTagName("track"): Daniel@0: track = Track(_extract(node, "artist"), _extract(node, "name"), self.network) Daniel@0: track.listener_count = _number(_extract(node, "listeners")) Daniel@0: seq.append(track) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: class VenueSearch(_Search): Daniel@0: """Search for a venue by its name. If you don't wanna narrow the results down Daniel@0: by specifying a country, set it to empty string.""" Daniel@0: Daniel@0: def __init__(self, venue_name, country_name, network): Daniel@0: Daniel@0: _Search.__init__(self, "venue", {"venue": venue_name, "country": country_name}, network) Daniel@0: Daniel@0: def get_next_page(self): Daniel@0: """Returns the next page of results as a sequence of Track objects.""" Daniel@0: Daniel@0: master_node = self._retrieve_next_page() Daniel@0: Daniel@0: seq = [] Daniel@0: for node in master_node.getElementsByTagName("venue"): Daniel@0: seq.append(Venue(_extract(node, "id"), self.network)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: class Venue(_BaseObject): Daniel@0: """A venue where events are held.""" Daniel@0: Daniel@0: # TODO: waiting for a venue.getInfo web service to use. Daniel@0: Daniel@0: id = None Daniel@0: Daniel@0: def __init__(self, id, network): Daniel@0: _BaseObject.__init__(self, network) Daniel@0: Daniel@0: self.id = _number(id) Daniel@0: Daniel@0: def __repr__(self): Daniel@0: return "pylast.Venue(%s, %s)" %(repr(self.id), repr(self.network)) Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return "Venue #" + str(self.id) Daniel@0: Daniel@0: def __eq__(self, other): Daniel@0: return self.get_id() == other.get_id() Daniel@0: Daniel@0: def _get_params(self): Daniel@0: return {"venue": self.get_id()} Daniel@0: Daniel@0: def get_id(self): Daniel@0: """Returns the id of the venue.""" Daniel@0: Daniel@0: return self.id Daniel@0: Daniel@0: def get_upcoming_events(self): Daniel@0: """Returns the upcoming events in this venue.""" Daniel@0: Daniel@0: doc = self._request("venue.getEvents", True) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("event"): Daniel@0: seq.append(Event(_extract(node, "id"), self.network)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def get_past_events(self): Daniel@0: """Returns the past events held in this venue.""" Daniel@0: Daniel@0: doc = self._request("venue.getEvents", True) Daniel@0: Daniel@0: seq = [] Daniel@0: for node in doc.getElementsByTagName("event"): Daniel@0: seq.append(Event(_extract(node, "id"), self.network)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def md5(text): Daniel@0: """Returns the md5 hash of a string.""" Daniel@0: Daniel@0: h = hashlib.md5() Daniel@0: h.update(_unicode(text).encode("utf-8")) Daniel@0: Daniel@0: return h.hexdigest() Daniel@0: Daniel@0: def _unicode(text): Daniel@0: if sys.version_info[0] == 3: Daniel@0: if type(text) in (bytes, bytearray): Daniel@0: return str(text, "utf-8") Daniel@0: elif type(text) == str: Daniel@0: return text Daniel@0: else: Daniel@0: return str(text) Daniel@0: Daniel@0: elif sys.version_info[0] ==2: Daniel@0: if type(text) in (str,): Daniel@0: return unicode(text, "utf-8") Daniel@0: elif type(text) == unicode: Daniel@0: return text Daniel@0: else: Daniel@0: return unicode(text) Daniel@0: Daniel@0: def _string(text): Daniel@0: """For Python2 routines that can only process str type.""" Daniel@0: Daniel@0: if sys.version_info[0] == 3: Daniel@0: if type(text) != str: Daniel@0: return str(text) Daniel@0: else: Daniel@0: return text Daniel@0: Daniel@0: elif sys.version_info[0] == 2: Daniel@0: if type(text) == str: Daniel@0: return text Daniel@0: Daniel@0: if type(text) == int: Daniel@0: return str(text) Daniel@0: Daniel@0: return text.encode("utf-8") Daniel@0: Daniel@0: def _collect_nodes(limit, sender, method_name, cacheable, params=None): Daniel@0: """ Daniel@0: Returns a sequqnce of dom.Node objects about as close to Daniel@0: limit as possible Daniel@0: """ Daniel@0: Daniel@0: if not params: Daniel@0: params = sender._get_params() Daniel@0: Daniel@0: nodes = [] Daniel@0: page = 1 Daniel@0: end_of_pages = False Daniel@0: Daniel@0: while not end_of_pages and (not limit or (limit and len(nodes) < limit)): Daniel@0: params["page"] = str(page) Daniel@0: doc = sender._request(method_name, cacheable, params) Daniel@0: Daniel@0: main = doc.documentElement.childNodes[1] Daniel@0: Daniel@0: if main.hasAttribute("totalPages"): Daniel@0: total_pages = _number(main.getAttribute("totalPages")) Daniel@0: elif main.hasAttribute("totalpages"): Daniel@0: total_pages = _number(main.getAttribute("totalpages")) Daniel@0: else: Daniel@0: raise Exception("No total pages attribute") Daniel@0: Daniel@0: for node in main.childNodes: Daniel@0: if not node.nodeType == xml.dom.Node.TEXT_NODE and len(nodes) < limit: Daniel@0: nodes.append(node) Daniel@0: Daniel@0: if page >= total_pages: Daniel@0: end_of_pages = True Daniel@0: Daniel@0: page += 1 Daniel@0: Daniel@0: return nodes Daniel@0: Daniel@0: def _extract(node, name, index = 0): Daniel@0: """Extracts a value from the xml string""" Daniel@0: Daniel@0: nodes = node.getElementsByTagName(name) Daniel@0: Daniel@0: if len(nodes): Daniel@0: if nodes[index].firstChild: Daniel@0: return _unescape_htmlentity(nodes[index].firstChild.data.strip()) Daniel@0: else: Daniel@0: return None Daniel@0: Daniel@0: def _extract_all(node, name, limit_count = None): Daniel@0: """Extracts all the values from the xml string. returning a list.""" Daniel@0: Daniel@0: seq = [] Daniel@0: Daniel@0: for i in range(0, len(node.getElementsByTagName(name))): Daniel@0: if len(seq) == limit_count: Daniel@0: break Daniel@0: Daniel@0: seq.append(_extract(node, name, i)) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: def _url_safe(text): Daniel@0: """Does all kinds of tricks on a text to make it safe to use in a url.""" Daniel@0: Daniel@0: return url_quote_plus(url_quote_plus(_string(text))).lower() Daniel@0: Daniel@0: def _number(string): Daniel@0: """ Daniel@0: Extracts an int from a string. Returns a 0 if None or an empty string was passed Daniel@0: """ Daniel@0: Daniel@0: if not string: Daniel@0: return 0 Daniel@0: elif string == "": Daniel@0: return 0 Daniel@0: else: Daniel@0: try: Daniel@0: return int(string) Daniel@0: except ValueError: Daniel@0: return float(string) Daniel@0: Daniel@0: def _unescape_htmlentity(string): Daniel@0: Daniel@0: #string = _unicode(string) Daniel@0: Daniel@0: mapping = htmlentitydefs.name2codepoint Daniel@0: for key in mapping: Daniel@0: string = string.replace("&%s;" %key, unichr(mapping[key])) Daniel@0: Daniel@0: return string Daniel@0: Daniel@0: def extract_items(topitems_or_libraryitems): Daniel@0: """Extracts a sequence of items from a sequence of TopItem or LibraryItem objects.""" Daniel@0: Daniel@0: seq = [] Daniel@0: for i in topitems_or_libraryitems: Daniel@0: seq.append(i.item) Daniel@0: Daniel@0: return seq Daniel@0: Daniel@0: class ScrobblingError(Exception): Daniel@0: def __init__(self, message): Daniel@0: Exception.__init__(self) Daniel@0: self.message = message Daniel@0: Daniel@0: @_string_output Daniel@0: def __str__(self): Daniel@0: return self.message Daniel@0: Daniel@0: class BannedClientError(ScrobblingError): Daniel@0: def __init__(self): Daniel@0: ScrobblingError.__init__(self, "This version of the client has been banned") Daniel@0: Daniel@0: class BadAuthenticationError(ScrobblingError): Daniel@0: def __init__(self): Daniel@0: ScrobblingError.__init__(self, "Bad authentication token") Daniel@0: Daniel@0: class BadTimeError(ScrobblingError): Daniel@0: def __init__(self): Daniel@0: ScrobblingError.__init__(self, "Time provided is not close enough to current time") Daniel@0: Daniel@0: class BadSessionError(ScrobblingError): Daniel@0: def __init__(self): Daniel@0: ScrobblingError.__init__(self, "Bad session id, consider re-handshaking") Daniel@0: Daniel@0: class _ScrobblerRequest(object): Daniel@0: Daniel@0: def __init__(self, url, params, network, type="POST"): Daniel@0: Daniel@0: for key in params: Daniel@0: params[key] = str(params[key]) Daniel@0: Daniel@0: self.params = params Daniel@0: self.type = type Daniel@0: (self.hostname, self.subdir) = url_split_host(url[len("http:"):]) Daniel@0: self.network = network Daniel@0: Daniel@0: def execute(self): Daniel@0: """Returns a string response of this request.""" Daniel@0: Daniel@0: connection = HTTPConnection(self.hostname) Daniel@0: Daniel@0: data = [] Daniel@0: for name in self.params.keys(): Daniel@0: value = url_quote_plus(self.params[name]) Daniel@0: data.append('='.join((name, value))) Daniel@0: data = "&".join(data) Daniel@0: Daniel@0: headers = { Daniel@0: "Content-type": "application/x-www-form-urlencoded", Daniel@0: "Accept-Charset": "utf-8", Daniel@0: "User-Agent": "pylast" + "/" + __version__, Daniel@0: "HOST": self.hostname Daniel@0: } Daniel@0: Daniel@0: if self.type == "GET": Daniel@0: connection.request("GET", self.subdir + "?" + data, headers = headers) Daniel@0: else: Daniel@0: connection.request("POST", self.subdir, data, headers) Daniel@0: response = _unicode(connection.getresponse().read()) Daniel@0: Daniel@0: self._check_response_for_errors(response) Daniel@0: Daniel@0: return response Daniel@0: Daniel@0: def _check_response_for_errors(self, response): Daniel@0: """When passed a string response it checks for erros, raising Daniel@0: any exceptions as necessary.""" Daniel@0: Daniel@0: lines = response.split("\n") Daniel@0: status_line = lines[0] Daniel@0: Daniel@0: if status_line == "OK": Daniel@0: return Daniel@0: elif status_line == "BANNED": Daniel@0: raise BannedClientError() Daniel@0: elif status_line == "BADAUTH": Daniel@0: raise BadAuthenticationError() Daniel@0: elif status_line == "BADTIME": Daniel@0: raise BadTimeError() Daniel@0: elif status_line == "BADSESSION": Daniel@0: raise BadSessionError() Daniel@0: elif status_line.startswith("FAILED "): Daniel@0: reason = status_line[status_line.find("FAILED ")+len("FAILED "):] Daniel@0: raise ScrobblingError(reason) Daniel@0: Daniel@0: class Scrobbler(object): Daniel@0: """A class for scrobbling tracks to Last.fm""" Daniel@0: Daniel@0: session_id = None Daniel@0: nowplaying_url = None Daniel@0: submissions_url = None Daniel@0: Daniel@0: def __init__(self, network, client_id, client_version): Daniel@0: self.client_id = client_id Daniel@0: self.client_version = client_version Daniel@0: self.username = network.username Daniel@0: self.password = network.password_hash Daniel@0: self.network = network Daniel@0: Daniel@0: def _do_handshake(self): Daniel@0: """Handshakes with the server""" Daniel@0: Daniel@0: timestamp = str(int(time.time())) Daniel@0: Daniel@0: if self.password and self.username: Daniel@0: token = md5(self.password + timestamp) Daniel@0: elif self.network.api_key and self.network.api_secret and self.network.session_key: Daniel@0: if not self.username: Daniel@0: self.username = self.network.get_authenticated_user().get_name() Daniel@0: token = md5(self.network.api_secret + timestamp) Daniel@0: Daniel@0: params = {"hs": "true", "p": "1.2.1", "c": self.client_id, Daniel@0: "v": self.client_version, "u": self.username, "t": timestamp, Daniel@0: "a": token} Daniel@0: Daniel@0: if self.network.session_key and self.network.api_key: Daniel@0: params["sk"] = self.network.session_key Daniel@0: params["api_key"] = self.network.api_key Daniel@0: Daniel@0: server = self.network.submission_server Daniel@0: response = _ScrobblerRequest(server, params, self.network, "GET").execute().split("\n") Daniel@0: Daniel@0: self.session_id = response[1] Daniel@0: self.nowplaying_url = response[2] Daniel@0: self.submissions_url = response[3] Daniel@0: Daniel@0: def _get_session_id(self, new = False): Daniel@0: """Returns a handshake. If new is true, then it will be requested from the server Daniel@0: even if one was cached.""" Daniel@0: Daniel@0: if not self.session_id or new: Daniel@0: self._do_handshake() Daniel@0: Daniel@0: return self.session_id Daniel@0: Daniel@0: def report_now_playing(self, artist, title, album = "", duration = "", track_number = "", mbid = ""): Daniel@0: Daniel@0: _deprecation_warning("DeprecationWarning: Use Netowrk.update_now_playing(...) instead") Daniel@0: Daniel@0: params = {"s": self._get_session_id(), "a": artist, "t": title, Daniel@0: "b": album, "l": duration, "n": track_number, "m": mbid} Daniel@0: Daniel@0: try: Daniel@0: _ScrobblerRequest(self.nowplaying_url, params, self.network).execute() Daniel@0: except BadSessionError: Daniel@0: self._do_handshake() Daniel@0: self.report_now_playing(artist, title, album, duration, track_number, mbid) Daniel@0: Daniel@0: def scrobble(self, artist, title, time_started, source, mode, duration, album="", track_number="", mbid=""): Daniel@0: """Scrobble a track. parameters: Daniel@0: artist: Artist name. Daniel@0: title: Track title. Daniel@0: time_started: UTC timestamp of when the track started playing. Daniel@0: source: The source of the track Daniel@0: SCROBBLE_SOURCE_USER: Chosen by the user (the most common value, unless you have a reason for choosing otherwise, use this). Daniel@0: SCROBBLE_SOURCE_NON_PERSONALIZED_BROADCAST: Non-personalised broadcast (e.g. Shoutcast, BBC Radio 1). Daniel@0: SCROBBLE_SOURCE_PERSONALIZED_BROADCAST: Personalised recommendation except Last.fm (e.g. Pandora, Launchcast). Daniel@0: SCROBBLE_SOURCE_LASTFM: ast.fm (any mode). In this case, the 5-digit recommendation_key value must be set. Daniel@0: SCROBBLE_SOURCE_UNKNOWN: Source unknown. Daniel@0: mode: The submission mode Daniel@0: SCROBBLE_MODE_PLAYED: The track was played. Daniel@0: SCROBBLE_MODE_LOVED: The user manually loved the track (implies a listen) Daniel@0: SCROBBLE_MODE_SKIPPED: The track was skipped (Only if source was Last.fm) Daniel@0: SCROBBLE_MODE_BANNED: The track was banned (Only if source was Last.fm) Daniel@0: duration: Track duration in seconds. Daniel@0: album: The album name. Daniel@0: track_number: The track number on the album. Daniel@0: mbid: MusicBrainz ID. Daniel@0: """ Daniel@0: Daniel@0: _deprecation_warning("DeprecationWarning: Use Network.scrobble(...) instead") Daniel@0: Daniel@0: params = {"s": self._get_session_id(), "a[0]": _string(artist), "t[0]": _string(title), Daniel@0: "i[0]": str(time_started), "o[0]": source, "r[0]": mode, "l[0]": str(duration), Daniel@0: "b[0]": _string(album), "n[0]": track_number, "m[0]": mbid} Daniel@0: Daniel@0: _ScrobblerRequest(self.submissions_url, params, self.network).execute() Daniel@0: Daniel@0: def scrobble_many(self, tracks): Daniel@0: """ Daniel@0: Scrobble several tracks at once. Daniel@0: Daniel@0: tracks: A sequence of a sequence of parameters for each trach. The order of parameters Daniel@0: is the same as if passed to the scrobble() method. Daniel@0: """ Daniel@0: Daniel@0: _deprecation_warning("DeprecationWarning: Use Network.scrobble_many(...) instead") Daniel@0: Daniel@0: remainder = [] Daniel@0: Daniel@0: if len(tracks) > 50: Daniel@0: remainder = tracks[50:] Daniel@0: tracks = tracks[:50] Daniel@0: Daniel@0: params = {"s": self._get_session_id()} Daniel@0: Daniel@0: i = 0 Daniel@0: for t in tracks: Daniel@0: _pad_list(t, 9, "") Daniel@0: params["a[%s]" % str(i)] = _string(t[0]) Daniel@0: params["t[%s]" % str(i)] = _string(t[1]) Daniel@0: params["i[%s]" % str(i)] = str(t[2]) Daniel@0: params["o[%s]" % str(i)] = t[3] Daniel@0: params["r[%s]" % str(i)] = t[4] Daniel@0: params["l[%s]" % str(i)] = str(t[5]) Daniel@0: params["b[%s]" % str(i)] = _string(t[6]) Daniel@0: params["n[%s]" % str(i)] = t[7] Daniel@0: params["m[%s]" % str(i)] = t[8] Daniel@0: Daniel@0: i += 1 Daniel@0: Daniel@0: _ScrobblerRequest(self.submissions_url, params, self.network).execute() Daniel@0: Daniel@0: if remainder: Daniel@0: self.scrobble_many(remainder)