-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
179 lines (161 loc) · 6.46 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import categories
from BeautifulSoup import BeautifulStoneSoup as bss
import logging
import re
import string
import random
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import urlfetch
from google.appengine.api import mail
class Twitter(webapp.RequestHandler):
def get(self):
self.post()
def post(self):
STATION = 1111
STORY = 2222
if self.request.get('title') and self.request.get('mp3'):
title = self.request.get('title')
mp3 = self.request.get('mp3')
mode = STORY
elif self.request.get('station') and self.request.get('freq'):
station = self.request.get('station')
freq = self.request.get('freq')
mode = STATION
else:
mode = STORY
r = random.randint(1, 1000000)
title = 'How+the+world+celebrates+national+groundhog+day' + str(r)
mp3 = 'mp3link.mp3'
station = 'WVTF-FM'
freq = 'FM 89.1'
tweet = ''
if mode == STATION:
tweet = 'I am listening to ' + station + ' at ' + freq + '! I found this via StarNews!'
else:
title = title.replace('+', ' ')
tweet = 'I just listened to "' + title + '" via StarNews! You can listen as well at this link: ' + mp3
mail.send_mail(sender="[email protected]",
to="[email protected]",
subject="",
body=tweet)
class MainHandler(webapp.RequestHandler):
API_KEY = 'MDA5NTMyMTcyMDEzMzgzMTYwMTU1ZDhlOA001'
BASE_URL = 'http://api.npr.org/'
FIELDS = 'title,audio'
OUTPUT = 'NPRML'
## Mimics post()
def get(self):
self.post()
## Given a method of searching (topic / location)
## finds the results of that search query.
def post(self):
if self.request.get('topic'):
self.findTopic(self.request.get('topic'))
elif self.request.get('lat') and self.request.get('long'):
self.findLocal(self.request.get('lat'), self.request.get('long'))
elif self.request.get('zip'):
self.findLocalZip(self.request.get('zip'))
elif self.request.get('city'):
self.findLocalCity(self.request.get('city'))
else:
topic = 'health'
self.findTopic(topic)
self.p('error')
# Given a location, will find a list of radio stations
# that have recorded mp3 stories, and another list of radio
# stations that can be tuned in to.
def findLocal(self, lat, lon):
if lat < 0:
lat += 360
if lon < 0:
lon += 360
# Get url to query given the lat & long.
url = self.BASE_URL + 'stations?' + 'lat=' + str(lat) + '&lon=' + str(lon) + '&apiKey=' + self.API_KEY
result = self.fetchLocalResults(url)
self.printListToCSV(result)
def findLocalZip(self, zipcode):
url = self.BASE_URL + 'stations?' + 'zip=' + str(zipcode) + '&apiKey=' + self.API_KEY
result = self.fetchLocalResults(url)
self.printListToCSV(result)
## Given a topic (must be one of a predefined list)
## Will generate an npr api query for that topic.
## Outputs a list of stories with a title and a link to the audio file.
def findTopic(self, topic):
query = {}
topic_id = categories.get_id(topic)
url = self.BASE_URL + 'query?' + 'id=' + topic_id + '&fields=' + self.FIELDS + '&output=' + self.OUTPUT + '&apiKey=' + self.API_KEY
result = self.fetchCategoryResults(url)
self.printListToCSV(result)
# Returns a list of stations that one can tune in to.
# List is of the form [[station name, frequency], ...]
def fetchLocalResults(self, url):
result = []
xml = urlfetch.fetch(url).content
soup = bss(xml)
stations = soup.findAll('station')
for station in stations:
name = station.find('name')
band = station.find('band')
freq = station.find('frequency')
if name and band and freq:
res = []
res.append(str(name.contents[0]))
channel = band.contents[0] + ' ' + freq.contents[0]
res.append(str(channel))
result.append(res)
return result
## Given a query url, takes relevant information from resulting xml.
## Returns a list of the form [[title, mp3], [title, mp3], [title, mp3], ...]
def fetchCategoryResults(self, url):
result = []
xml = urlfetch.fetch(url).content
soup = bss(xml)
stories = soup.findAll('story')
for story in stories:
story_id = story['id']
titles = story.findAll('title')
if len(titles) > 0:
title = titles[0].contents[0]
mp3_tag = story.findAll('mp3')
if len(mp3_tag) > 0:
mp3 = mp3_tag[0].contents[0]
text = str(urlfetch.fetch(mp3).content)
text = text.replace('\n', '')
index = text.find('.mp3')
text = text[:index + 4]
title_valid = title.replace(' ', '+').replace(':', '-')
res = []
res.append(str(title + ''))
res.append(text)
res.append(title_valid)
result.append(res)
return result
def p(self, string):
self.response.out.write(string)
## Given a list of the form [[..], [..], [..], [..], ...]
## prints the items as a csv.
def printListToCSV(self, items):
result = ''
limit = 10
count = 1
for item in items:
if count > limit:
break
count += 1
i = 0
while i < len(item):
if i > 0:
result += ', '
result += '"' + item[i] + '"'
i += 1
result += '\n'
self.response.out.write(result)
def main():
application = webapp.WSGIApplication([('/', MainHandler),
('/twitter', Twitter),
('/link', Link)],
debug = True)
util.run_wsgi_app(application)
if __name__=='__main__':
main()