Update desktop file so that it runs correctly and fix date display bug
[gigfinder] / src / opt / gigfinder / events.py
1 import urllib
2 import urllib2
3
4 from resultsparser import parse_xml
5
6 class Events:
7     def __init__(self):
8         self.api_key = '1928a14bdf51369505530949d8b7e1ee'
9         self.url_base = 'http://ws.audioscrobbler.com/2.0/'
10         self.format = 'json'
11         self.method = 'geo.getevents'
12
13     def get_events(self, lat, lng, distance):
14         """ Retrieve xml and parse into events list """
15         events = []
16         for page in ['1', '2', '3']:
17             xml = self.get_xml(lat, lng, distance, page=page)
18             events.extend(parse_xml(xml, 
19                                     lat,
20                                     lng))
21         return self.sort_events(events)
22
23     def sort_events(self, events):
24         """ Sort gig by distance """
25         if len(events) > 1:
26             events.sort(cmp=self.distance_cmp, key=lambda x: x['distance'])
27         return events
28
29     def get_json(self, lat='', lng='', distance=''):
30         # testing json results
31         lat = '51.5174'
32         lng = '-0.0829'
33         distance = '10'
34         params = urllib.urlencode({'method': self.method,
35                                    'api_key': self.api_key,
36                                    'distance': distance,
37                                    'long': lng,
38                                    'lat': lat,
39                                    'format': self.format})
40         url = '%s?%s' % (self.url_base, params)
41         request = urllib2.Request(url, None)
42         response = urllib2.urlopen(request)
43         return response
44         
45     def get_xml(self, lat, lng, distance, page='1'):
46         """ Return xml from lastfm """
47         params = urllib.urlencode({'method': self.method,
48                                    'api_key': self.api_key,
49                                    'distance': distance,
50                                    'long': lng,
51                                    'lat': lat,
52                                    'page': page})
53         response = urllib.urlopen(self.url_base, params)
54         return response.read()
55     
56     def distance_cmp(self, x, y):
57         """ Compare distances for list sort """
58         if x > y:
59             return 1
60         elif x == y:
61             return 0
62         else:
63             return -1