-
Notifications
You must be signed in to change notification settings - Fork 3
/
no_phone.rb
84 lines (73 loc) · 1.88 KB
/
no_phone.rb
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
require "./emailer"
class NoPhone < Sinatra::Base
helpers do
def sound_url(sound)
ENV["TWILIO_CALLBACK_URL"].to_s + "/#{sound}.mp3"
end
end
before do
validate unless request.env["REQUEST_METHOD"] == "GET"
@digits = params["Digits"].to_i if params["Digits"]
end
get "/" do
erb :index
end
# Incoming Call
post "/" do
halt 404 unless params["To"].is_a?(String)
case params["CallStatus"]
when "completed"
builder :empty_response
when "ringing"
builder :welcome
else
builder :hangup
end
end
# Incoming SMS
post "/sms" do
builder :sms
end
# Caller selected a menu item
post "/menu" do
case @digits
when 1
# Harmony or DMS
builder :leave_a_message
when 2
# All other
builder :menu
else
if ENV["EXTENSION_#{@digits}"]
builder :extension
else
builder :hangup
end
end
end
post "/extension" do
if ENV["EXTENSION_#{@digits}"]
builder :extension
else
builder :hangup
end
end
post "/voicemail" do
puts "YOU'VE GOT MAIL! #{params["RecordingUrl"]} #{params["RecordingDuration"]} seconds"
Emailer.new.voicemail_notification(params["RecordingUrl"], params["RecordingDuration"], params["From"])
builder :empty_response
end
private
def validate
auth_token = ENV["TWILIO_AUTH_TOKEN"]
# the callback URL you provided to Twilio
url = ENV["TWILIO_CALLBACK_URL"] + request.fullpath
# X-Twilio-Signature header value, rewritten by Rack
signature = request.env["HTTP_X_TWILIO_SIGNATURE"]
validator = Twilio::Security::RequestValidator.new(auth_token)
# "captures" key gets added to the params. we need to remove it for validation
twilio_params = params.clone
twilio_params.delete("captures")
halt 401 unless validator.validate(url, twilio_params, signature)
end
end