-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapplication.py
212 lines (158 loc) · 6.38 KB
/
application.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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
from flask import redirect, request, render_template, Response
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql.expression import func
from functools import wraps
from story_collector import create_app, db
from story_collector.app_config import ADMIN_USER, ADMIN_PASS, USE_FAKE_DATA, APP_URL, NOTIFY_FROM_NUM, NOTIFY_TO_NUM, TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN
from story_collector.models import Story
from story_collector.fake_data import FAKE_STORIES
import twilio.twiml
from twilio.rest import TwilioRestClient
application = create_app()
if NOTIFY_FROM_NUM and NOTIFY_TO_NUM and TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN:
try:
twilio_client = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
except twilio.exceptions.TwilioException:
twilio_client = None
else:
twilio_client = None
@application.route("/")
def index():
return "hello world" # update this
@application.route("/incoming-call", methods=['GET', 'POST'])
def incoming_call():
"""Respond to incoming requests."""
print("greet")
resp = twilio.twiml.Response()
resp.play(APP_URL+'/static/assets/intro.mp3')
# get a random story that has been approved and play it
print("grabbing a random story")
random_story = Story.query.filter_by(is_approved=True).order_by(func.rand()).first()
if random_story:
resp.pause(length=2)
resp.play(APP_URL+'/static/assets/random_msg_intro.mp3')
resp.pause(length=2)
resp.play(random_story.recording_url)
resp.pause(length=3)
resp.play(APP_URL+'/static/assets/contribution_prompt.mp3')
resp.gather(numDigits=1, action="/handle-keypress", method="POST")
from_number = request.values.get('From', None)
if twilio_client and from_number:
notify('someone called! %s' %from_number[2:5])
return str(resp)
@application.route('/browse')
def browse():
if USE_FAKE_DATA:
approved = FAKE_STORIES
else:
approved = Story.query.filter_by(is_approved=True).all()
return render_template('browse.html', approved=approved)
@application.route("/handle-keypress", methods=['GET', 'POST'])
def handle_keypress():
pressed = request.values.get('Digits', None)
resp = twilio.twiml.Response()
if pressed == '1':
resp.play(APP_URL+'/static/assets/recording_prompt.mp3')
resp.record(maxLength="30", action="/handle-recording")
else:
resp.play(APP_URL+'/static/assets/contribution_prompt2.mp3')
resp.gather(numDigits=1, action="/handle-keypress", method="POST")
return str(resp)
@application.route("/handle-recording", methods=['GET', 'POST'])
def handle_recording():
recording_url = request.values.get('RecordingUrl', None)
call_sid = request.values.get('CallSid', None)
from_number = request.values.get('From', None)
to_number = request.values.get('To', None)
resp = twilio.twiml.Response()
# resp.say("Thanks! Here is your recording:")
# resp.play(recording_url)
# # TODO: handle re-recording
print("recording url: %s" %recording_url)
new_story = Story(call_sid, from_number, to_number, recording_url)
db.session.add(new_story)
db.session.commit()
# # collecting zip
# resp.play('http://lamivo.com/wwtd/collect_zip.mp3')
# resp.gather(numDigits=5, action="/collect-zip", method="POST")
# resp.pause(length=20)
resp.play(APP_URL+'/static/assets/bye.mp3')
if twilio_client:
notify("recorded: %s" %(new_story.recording_url))
return str(resp)
@application.route("/collect-zip", methods=['GET', 'POST'])
def collect_zip():
pressed = request.values.get('Digits', None)
story = Story.query.filter_by(call_sid=request.values.get('CallSid', None)).first()
story.caller_zip = pressed
db.session.commit()
resp = twilio.twiml.Response()
return str(resp)
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == ADMIN_USER and password == ADMIN_PASS
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your credentials for that url', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@application.route('/review')
@requires_auth
def review():
if USE_FAKE_DATA:
review_queue = FAKE_STORIES
approved = FAKE_STORIES
disapproved = FAKE_STORIES
else:
review_queue = Story.query.filter_by(is_approved=None).all()
approved = Story.query.filter_by(is_approved=True).all()
disapproved = Story.query.filter_by(is_approved=False).all()
return render_template('review.html', review_queue = review_queue, approved=approved, disapproved=disapproved)
@application.route('/approve/<story_id>')
@requires_auth
def approve(story_id):
story = Story.query.get(story_id)
story.is_approved = True
db.session.commit()
return redirect('/review')
@application.route('/disapprove/<story_id>')
@requires_auth
def disapprove(story_id):
story = Story.query.get(story_id)
story.is_approved = False
db.session.commit()
return redirect('/review')
@application.route('/initialize')
@requires_auth
def initialize():
print("\nINITIALIZING DB")
# TODO: only do this if tables don't exist?
print(" * making sure all tables have been created")
db.create_all()
# TODO: add stuff to create some admin users for moderation
# adding some initial responses
print(" * seeding the db with a response")
if not Story.query.filter_by(call_sid='seed1').first():
# this is lam's story about being an immigrant
rec = Story('seed1', '', '', 'https://api.twilio.com/2010-04-01/Accounts/AC8820553f8206a5c5f7608355621ccd90/Recordings/RE6ebf1e9bbfc378667985b9bdf032ebac')
rec.is_approved = True
db.session.add(rec)
db.session.commit()
print(" ...OK!")
else:
print(" ...already done previously")
return redirect('/')
def notify(msg):
twilio_client.messages.create(to=NOTIFY_TO_NUM, from_=NOTIFY_FROM_NUM, body=msg)
if __name__ == "__main__":
application.run(debug=True, host='0.0.0.0')