Stop using a MainLoop
[gigfinder] / src / opt / gigfinder / events.py
1 import urllib
2 import urllib2
3
4 import location
5
6 from resultsparser import  parse_json
7
8 class Event:
9     def __init__(self, 
10                  title, 
11                  venue_name, 
12                  address, 
13                  lng,
14                  lat,
15                  artists, 
16                  start_date):
17         self.title = title
18         self.venue_name = venue_name
19         self.address = address
20         self.lng = lng
21         self.lat = lat
22         self.artists = artists
23         self.start_date = start_date
24
25     def get_distance_from(self, lng, lat):
26         return location.distance_between(float(lat), 
27                                          float(lng), 
28                                          float(self.lat), 
29                                          float(self.lng))
30
31 class Events:
32     def __init__(self):
33         self.api_key = '1928a14bdf51369505530949d8b7e1ee'
34         self.url_base = 'http://ws.audioscrobbler.com/2.0/'
35         self.format = 'json'
36         self.method = 'geo.getevents'
37
38     def get_events(self, lat, lng, distance):
39         """ Retrieve json and parse into events list """
40         events = []
41         result = self.get_json(lat, lng, distance)
42         for event  in parse_json(result):
43             events.append(Event(event[0],
44                                 event[1],
45                                 event[2],
46                                 event[3],
47                                 event[4],
48                                 event[5],
49                                 event[6]))
50         return self.sort_events(events, lat, lng)
51
52     def sort_events(self, events, lat, lng):
53         """ Sort gig by distance """
54         if len(events) > 1:
55             events.sort(cmp=self.distance_cmp, key=lambda x: x.get_distance_from(lng, lat))
56         return events
57
58     def get_json(self, lat='', lng='', distance=''):
59         params = urllib.urlencode({'method': self.method,
60                                    'api_key': self.api_key,
61                                    'distance': distance,
62                                    'long': lng,
63                                    'lat': lat,
64                                    'format': self.format})
65         url = '%s?%s' % (self.url_base, params)
66         request = urllib2.Request(url, None)
67         response = urllib2.urlopen(request)
68         return response.read()
69         
70     def distance_cmp(self, x, y):
71         """ Compare distances for list sort """
72         if x > y:
73             return 1
74         elif x == y:
75             return 0
76         else:
77             return -1