Пример #1
0
 def _check_chart_params(params, subject, start=None, end=None):
     if xor(start is None, end is None):
         raise InvalidParametersError(
             "both start and end have to be provided.")
     if start is not None and end is not None:
         if not (isinstance(start, datetime) and isinstance(end, datetime)):
             raise InvalidParametersError(
                 "start and end must be datetime.datetime instances")
         params.update({
             'from': int(calendar.timegm(start.timetuple())),
             'to': int(calendar.timegm(end.timetuple()))
         })
     return params
Пример #2
0
 def _default_params(self, extra_params = None):
     if not (self.artist and self.name):
         raise InvalidParametersError("artist and track have to be provided.")
     params = {'artist': self.artist.name, 'track': self.name}
     if extra_params is not None:
         params.update(extra_params)
     return params
Пример #3
0
 def _default_params(self, extra_params=None):
     if not self.id:
         raise InvalidParametersError("id has to be provided.")
     params = {'event': self.id}
     if extra_params is not None:
         params.update(extra_params)
     return params
Пример #4
0
 def _default_params(self, extra_params=None):
     if not self.name:
         raise InvalidParametersError("tag has to be provided.")
     params = {'tag': self.name}
     if extra_params is not None:
         params.update(extra_params)
     return params
Пример #5
0
 def _default_params(self, extra_params={}):
     if not (self.artist and self.name):
         raise InvalidParametersError(
             "artist and album have to be provided.")
     params = {'artist': self.artist.name, 'album': self.name}
     params.update(extra_params)
     return params
Пример #6
0
 def init(self, api, **kwargs):
     """
     Create a Location object by providing all the data related to it.
     
     @param api:          an instance of L{Api}
     @type api:           L{Api}
     @param city:         city in which the location is situated
     @type city:          L{str}
     @param country:      country in which the location is situated
     @type country:       L{Country}
     @param street:       street in which the location is situated
     @type street:        L{str}
     @param postal_code:  postal code of the location
     @type postal_code:   L{str}
     @param latitude:     latitude of the location
     @type latitude:      L{float}
     @param longitude:    longitude of the location
     @type longitude:     L{float}
     @param timezone:     timezone in which the location is situated
     @type timezone:      L{str}
     
     @raise InvalidParametersError: If an instance of L{Api} is not provided as the first
                                    parameter then an Exception is raised.
     """
     if not isinstance(api, Api):
         raise InvalidParametersError(
             "api reference must be supplied as an argument")
     self._api = api
     super(Location, self).init(**kwargs)
Пример #7
0
    def __init__(self,
                 api_key,
                 secret=None,
                 session_key=None,
                 input_encoding=None,
                 request_headers=None,
                 no_cache=False,
                 debug=None,
                 logfile=None):
        """
        Create an Api object to access the last.fm webservice API. Use this object as a
        starting point for accessing all the webservice methods.
        
        @param api_key:            last.fm API key
        @type api_key:             L{str}
        @param secret:             last.fm API secret (optional, required only for
                                   authenticated webservice methods)
        @type secret:              L{str}
        @param session_key:        session key for the authenticated session (optional,
                                   required only for authenticated webservice methods)
        @type session_key:         L{str}
        @param input_encoding:     encoding of the input data (optional)
        @type input_encoding:      L{str}
        @param request_headers:    HTTP headers for the requests to last.fm webservices
                                   (optional)
        @type request_headers:     L{dict}
        @param no_cache:           flag to switch off file cache (optional)
        @type no_cache:            L{bool}
        @param debug:              flag to switch on debugging (optional)
        @type debug:               L{bool}
        """
        self._api_key = api_key
        self._secret = secret
        self._session_key = session_key
        self._urllib = urllib2
        self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT
        self._initialize_request_headers(request_headers)
        self._initialize_user_agent()
        self._input_encoding = input_encoding
        self._no_cache = no_cache
        self._logfile = logfile
        self._last_fetch_time = datetime.now()
        if self._no_cache:
            self._cache = None
        else:
            self._cache = FileCache()

        if debug is not None:
            if debug in Api.DEBUG_LEVELS:
                self._debug = Api.DEBUG_LEVELS[debug]
            else:
                raise InvalidParametersError(
                    "debug parameter must be one of the keys in Api.DEBUG_LEVELS dict"
                )
        else:
            self._debug = None
        if self._debug is not None:
            Wormhole.enable()
        logging.set_api(self)
Пример #8
0
 def _hash_func(*args, **kwds):
     try:
         return hash("%s%s%s%s" %
                     (kwds['subject'].__class__.__name__,
                      kwds['subject'].name, kwds['start'], kwds['end']))
     except KeyError:
         raise InvalidParametersError(
             "subject, start and end have to be provided for hashing")
Пример #9
0
 def __getitem__(self, name):
     if name not in ObjectCache.keys:
         raise InvalidParametersError("Key does not correspond to a valid class")
     else:
         if name in _registry:
             return sorted(_registry[name].values())
         else:
             return []
Пример #10
0
 def _hash_func(*args, **kwds):
     try:
         return hash(kwds['name'].lower())
     except KeyError:
         try:
             return hash(args[1].lower())
         except IndexError:
             raise InvalidParametersError(
                 "name has to be provided for hashing")
Пример #11
0
 def _fetch_data(api, artist=None, mbid=None):
     params = {'method': 'artist.getInfo'}
     if not (artist or mbid):
         raise InvalidParametersError(
             "either artist or mbid has to be given as argument.")
     if artist:
         params.update({'artist': artist})
     elif mbid:
         params.update({'mbid': mbid})
     return api._fetch_data(params).find('artist')
Пример #12
0
    def init(self, api, **kwargs):
        if not isinstance(api, Api):
            raise InvalidParametersError(
                "api reference must be supplied as an argument")

        self._api = api
        super(Tag, self).init(**kwargs)
        self._stats = hasattr(self, '_stats') and Stats(
            subject=self, count=self._stats.count,
            rank=self._stats.rank) or None
Пример #13
0
 def _hash_func(*args, **kwds):
     try:
         return hash("latlong%s%s" % (kwds['latitude'], kwds['longitude']))
     except KeyError:
         try:
             return hash("name%s" % kwds['city'])
         except KeyError:
             raise InvalidParametersError(
                 "either latitude and longitude or city has to be provided for hashing"
             )
Пример #14
0
 def top_tracks(self):
     """
     top tracks for the location
     @rtype: L{list} of L{Track}
     """
     if self.country is None or self.city is None:
         raise InvalidParametersError(
             "country and city of this location are required for calling this method"
         )
     return Geo.get_top_tracks(self._api, self.country.name, self.city)
Пример #15
0
    def _check_params(params, artist=None, track=None, mbid=None):
        if not ((artist and track) or mbid):
            raise InvalidParametersError(
                "either (artist and track) or mbid has to be given as argument."
            )

        if artist and track:
            params.update({'artist': artist, 'track': track})
        elif mbid:
            params.update({'mbid': mbid})
        return params
Пример #16
0
 def _check_chart_params(params, subject, start=None, end=None):
     params = Chart._check_chart_params(params, subject, start, end)
     if start is not None and end is not None:
         wcl = subject.weekly_chart_list
         is_valid = False
         for wc in wcl:
             if wc.start == start and wc.end == end:
                 is_valid = True
         if not is_valid:
             raise InvalidParametersError(
                 "%s - %s chart dates are invalid" % (start, end))
     return params
Пример #17
0
 def init(self, api, **kwargs):
     if not isinstance(api, Api):
         raise InvalidParametersError("api reference must be supplied as an argument")
     
     self._api = api
     super(User, self).init(**kwargs)
     self._stats = hasattr(self, "_stats") and Stats(
         subject = self,
         match = self._stats.match,
         weight = self._stats.weight,
         playcount = self._stats.playcount
     ) or None
     self._library = User.Library(api, self)
Пример #18
0
 def _check_chart_params(cls, params, subject, start=None, end=None):
     duration = cls._period['duration']
     params = Chart._check_chart_params(params, subject, start, end)
     if start is not None and end is not None:
         mcl = MonthlyChart.get_chart_list(subject)
         is_valid = False
         for i in xrange(len(mcl) - (duration - 1)):
             if mcl[i].start == start and mcl[i +
                                              (duration - 1)].end == end:
                 is_valid = True
         if not is_valid:
             raise InvalidParametersError(
                 "%s - %s chart dates are invalid" % (start, end))
     return params
Пример #19
0
    def init(self, api, subject=None, **kwargs):
        """
        Create an Artist object by providing all the data related to it.
        
        @param api:             an instance of L{Api}
        @type api:              L{Api}
        @param name:            the artist name
        @type name:             L{str}
        @param mbid:            MBID of the artist
        @type mbid:             L{str}
        @param url:             URL of the artist on last.fm
        @type url:              L{str}
        @param image:           the images of the artist in various sizes
        @type image:            L{dict}
        @param streamable:      flag indicating if the artist is streamable from last.fm
        @type streamable:       L{bool}
        @param stats:           the artist statistics
        @type stats:            L{Stats}
        @param similar:         artists similar to the provided artist
        @type similar:          L{list} of L{Artist}
        @param top_tags:        top tags for the artist
        @type top_tags:         L{list} of L{Tag}
        @param bio:             biography of the artist
        @type bio:              L{Wiki}
        @param subject:         the subject to which this instance belongs to
        @type subject:          L{User} OR L{Artist} OR L{Tag} OR L{Track} OR L{WeeklyChart}
        
        @raise InvalidParametersError: If an instance of L{Api} is not provided as the first
                                       parameter then an Exception is raised.
        """
        if not isinstance(api, Api):
            raise InvalidParametersError(
                "api reference must be supplied as an argument")

        self._api = api
        super(Artist, self).init(**kwargs)
        self._stats = hasattr(self, "_stats") and Stats(
            subject=self,
            listeners=self._stats.listeners,
            playcount=self._stats.playcount,
            weight=self._stats.weight,
            match=self._stats.match,
            rank=self._stats.rank) or None
        self._bio = hasattr(self, "_bio") and Wiki(
            subject=self,
            published=self._bio.published,
            summary=self._bio.summary,
            content=self._bio.content) or None
        self._subject = subject
Пример #20
0
    def get_events(api,
                   location,
                   latitude=None,
                   longitude=None,
                   distance=None,
                   page=None):
        """
        Get the events for a location.
        
        @param api:          an instance of L{Api}
        @type api:           L{Api}
        @param location:     location to retrieve events for (optional)
        @type location:      L{str}
        @param latitude:     latitude value to retrieve events for (optional)
        @type latitude:      L{float}
        @param longitude:    longitude value to retrieve events for (optional)
        @type longitude:     L{float}
        @param distance:     find events within a specified distance (optional)
        @type distance:      L{float}
        
        @return:             events for the location
        @rtype:              L{lazylist} of L{Event}
        
        @raise InvalidParametersError: Either location or latitude and longitude
                                       has to be provided. Otherwise exception is
                                       raised.
        
        @note: Use L{Location.events} instead of using this method directly.
        """
        if reduce(lambda x, y: x and y is None,
                  [location, latitude, longitude], True):
            raise InvalidParametersError(
                "Either location or latitude and longitude has to be provided")

        params = {'method': 'geo.getEvents', 'location': location}
        if distance is not None:
            params.update({'distance': distance})

        if latitude is not None and longitude is not None:
            params.update({'lat': latitude, 'long': longitude})
        if page is not None:
            params.update({'page': page})

        data = api._fetch_data(params).find('events')
        total_pages = int(data.attrib['totalpages'])
        yield total_pages

        for e in data.findall('event'):
            yield Event.create_from_data(api, e)
Пример #21
0
 def attend(self, status = STATUS_ATTENDING):
     """
     Set the attendance status of the authenticated user for this event.
     
     @param status:    attendance status, should be one of: 
                       L{Event.STATUS_ATTENDING} OR L{Event.STATUS_MAYBE} OR L{Event.STATUS_NOT}
     @type status:     L{int}
     
     @raise InvalidParametersError: If status parameters is not one of the allowed values
                                    then an exception is raised.
     """
     if status not in [Event.STATUS_ATTENDING, Event.STATUS_MAYBE, Event.STATUS_NOT]:
         InvalidParametersError("status has to be 0, 1 or 2")
     params = self._default_params({'method': 'event.attend', 'status': status})
     self._api._post_data(params)
Пример #22
0
 def init(self, api, **kwargs):
     """
     Create a Country object by providing all the data related to it.
     @param api:    an instance of L{Api}
     @type api:     L{Api}
     @param name:   name of the country
     @type name:    L{str}
     
     @raise InvalidParametersError: If an instance of L{Api} is not provided as the first
                                    parameter then an Exception is raised.
     """
     if not isinstance(api, Api):
         raise InvalidParametersError(
             "api reference must be supplied as an argument")
     self._api = api
     super(Country, self).init(**kwargs)
Пример #23
0
 def init(self, api, **kwargs):
     if not isinstance(api, Api):
         raise InvalidParametersError(
             "api reference must be supplied as an argument")
     self._api = api
     super(Track, self).init(**kwargs)
     self._stats = hasattr(self, "_stats") and Stats(
         subject=self,
         match=self._stats.match,
         playcount=self._stats.playcount,
         rank=self._stats.rank,
         listeners=self._stats.listeners,
     ) or None
     self._wiki = hasattr(self, "_wiki") and Wiki(
         subject=self,
         published=self._wiki.published,
         summary=self._wiki.summary,
         content=self._wiki.content) or None
Пример #24
0
 def init(self, api, subject=None, **kwargs):
     """
     Create an Album object by providing all the data related to it.
     
     @param api:             an instance of L{Api}
     @type api:              L{Api}
     @param name:            the album name
     @type name:             L{str}
     @param artist:          the album artist name 
     @type artist:           L{Artist}
     @param id:              the album ID
     @type id:               L{str}
     @param mbid:            MBID of the album
     @type mbid:             L{str}
     @param url:             URL of the album on last.fm
     @type url:              L{str}
     @param release_date:    release date of the album
     @type release_date:     C{datetime.datetime}
     @param image:           the cover images of the album in various sizes
     @type image:            L{dict}
     @param stats:           the album statistics
     @type stats:            L{Stats}
     @param top_tags:        top tags for the album
     @type top_tags:         L{list} of L{Tag}
     @param streamable:      flag indicating if the album is streamable from last.fm
     @type streamable:       L{bool}
     @param subject:         the subject to which this instance belongs to
     @type subject:          L{User} OR L{Artist} OR L{Tag} OR L{WeeklyChart}
     
     @raise InvalidParametersError: If an instance of L{Api} is not provided as the first
                                    parameter then an Exception is raised.
     """
     if not isinstance(api, Api):
         raise InvalidParametersError(
             "api reference must be supplied as an argument")
     self._api = api
     super(Album, self).init(**kwargs)
     self._stats = hasattr(self, "_stats") and Stats(
         subject=self,
         listeners=self._stats.listeners,
         playcount=self._stats.playcount,
         match=self._stats.match,
         rank=self._stats.rank) or None
     self._subject = subject
Пример #25
0
 def get_venue(self, venue, callback = None):
     """
     Get a venue object.
     
     @param venue:        the venue name
     @type venue:         L{str}
     @param callback:     callback function for asynchronous invocation (optional)
     @type callback:      C{function}
     
     @return:         a venue object corresponding to the venue name provided
     @rtype:          L{Venue}
     
     @raise InvalidParametersError: Exception is raised if an non-existant venue name is supplied.
     
     @see:            L{search_venue}
     @see:            L{async_callback}
     """
     try:
         return self.search_venue(venue)[0]
     except IndexError:
         raise InvalidParametersError("No such venue exists")
Пример #26
0
    def init(self, api, **kwargs):
        """
        Create an Event object by providing all the data related to it.
        
        @param api:             an instance of L{Api}
        @type api:              L{Api}
        @param id:              ID of the event
        @type id:               L{int}
        @param title:           title of the event
        @type title:            L{str}
        @param artists:         artists performing in the event
        @type artists:          L{list} of L{Artist}
        @param headliner:       headliner artist of the event
        @type headliner:        L{Artist}
        @param venue:           venue of the event
        @type venue:            L{Venue}
        @param start_date:      start date and time of the event
        @type start_date:       C{datetime.datetime}
        @param description:     description of the event
        @type description:      L{str}
        @param image:           poster images of the event in various sizes
        @type image:            L{dict}
        @param url:             URL of the event on last.fm
        @type url:              L{str}
        @param stats:           the statistics of the event (attendance and no. of reviews)
        @type stats:            L{Stats}
        @param tag:             tag for the event
        @type tag:              L{str}
        """
        if not isinstance(api, Api):
            raise InvalidParametersError(
                "api reference must be supplied as an argument")

        self._api = api
        super(Event, self).init(**kwargs)
        self._stats = hasattr(self, "_stats") and Stats(
            subject=self,
            attendance=self._stats.attendance,
            reviews=self._stats.reviews) or None
Пример #27
0
 def _hash_func(*args, **kwds):
     try:
         return hash("%s%s" % (kwds['name'], hash(kwds['artist'])))
     except KeyError:
         raise InvalidParametersError(
             "name and artist have to be provided for hashing")
Пример #28
0
 def _hash_func(*args, **kwds):
     try:
         return hash("%s%s" % (kwds['body'], kwds['author']))
     except KeyError:
         raise InvalidParametersError(
             "body and author have to be provided for hashing")
Пример #29
0
 def _hash_func(*args, **kwds):
     try:
         return hash(kwds['id'])
     except KeyError:
         raise InvalidParametersError("id has to be provided for hashing")
Пример #30
0
 def _default_params(self, extra_params = {}):
     if not self.id:
         raise InvalidParametersError("venue id has to be provided.")
     params = {'venue': self.id}
     params.update(extra_params)
     return params