1# frozen_string_literal: true
2
3require "digest"
4require "forwardable"
5require "multibases"
6require "multihashes"
7require "roda"
8require "thin"
9require "sentry-ruby"
10
11require_relative "lib/call_attempt_repo"
12require_relative "lib/cdr"
13require_relative "lib/oob"
14require_relative "lib/roda_capture"
15require_relative "lib/roda_em_promise"
16require_relative "lib/rack_fiber"
17
18class OGMDownload
19 def initialize(url)
20 @digest = Digest::SHA512.new
21 @f = Tempfile.open("ogm")
22 @req = EM::HttpRequest.new(url, tls: { verify_peer: true })
23 end
24
25 def download
26 http = @req.aget
27 http.stream do |chunk|
28 @digest << chunk
29 @f.write chunk
30 end
31 http.then { @f.close }.catch do |e|
32 @f.close!
33 EMPromise.reject(e)
34 end
35 end
36
37 def cid
38 Multibases.encode(
39 "base58btc",
40 [1, 85].pack("C*") + Multihashes.encode(@digest.digest, "sha2-512")
41 ).pack.to_s
42 end
43
44 def path
45 @f.path
46 end
47end
48
49# rubocop:disable Metrics/ClassLength
50class Web < Roda
51 use Rack::Fiber unless ENV["ENV"] == "test" # Must go first!
52 use Sentry::Rack::CaptureExceptions
53 plugin :json_parser
54 plugin :type_routing
55 plugin :public
56 plugin :render, engine: "slim"
57 plugin RodaCapture
58 plugin RodaEMPromise # Must go last!
59
60 class << self
61 attr_reader :customer_repo, :log, :outbound_transfers
62
63 def run(log, *listen_on)
64 plugin :common_logger, log, method: :info
65 @outbound_transfers = {}
66 Thin::Logging.logger = log
67 Thin::Server.start(
68 *listen_on,
69 freeze.app,
70 signals: false
71 )
72 end
73 end
74
75 extend Forwardable
76 def_delegators :'self.class', :outbound_transfers
77 def_delegators :request, :params
78
79 def log
80 opts[:common_logger]
81 end
82
83 def log_error(e)
84 log.error(
85 "Error raised during #{request.fullpath}: #{e.class}",
86 e,
87 loggable_params
88 )
89 if e.is_a?(::Exception)
90 Sentry.capture_exception(e)
91 else
92 Sentry.capture_message(e.to_s)
93 end
94 end
95
96 def loggable_params
97 params.dup.tap do |p|
98 p.delete("to")
99 p.delete("from")
100 end
101 end
102
103 def customer_repo(**kwargs)
104 kwargs[:set_user] = Sentry.method(:set_user) unless kwargs[:set_user]
105 opts[:customer_repo] || CustomerRepo.new(**kwargs)
106 end
107
108 def call_attempt_repo
109 opts[:call_attempt_repo] || CallAttemptRepo.new
110 end
111
112 TEL_CANDIDATES = {
113 "Restricted" => "14",
114 "anonymous" => "15",
115 "Anonymous" => "16",
116 "unavailable" => "17",
117 "Unavailable" => "18"
118 }.freeze
119
120 def sanitize_tel_candidate(candidate)
121 if candidate.length < 3
122 "13;phone-context=anonymous.phone-context.soprani.ca"
123 elsif candidate[0] == "+" && /\A\d+\z/.match(candidate[1..-1])
124 candidate
125 else
126 "#{TEL_CANDIDATES.fetch(candidate, '19')}" \
127 ";phone-context=anonymous.phone-context.soprani.ca"
128 end
129 end
130
131 def from_jid
132 Blather::JID.new(
133 sanitize_tel_candidate(params["from"]),
134 CONFIG[:component][:jid]
135 )
136 end
137
138 def inbound_calls_path(suffix, customer_id=nil)
139 ["/inbound/calls/#{params['callId']}", suffix].compact.join("/") +
140 (customer_id ? "?customer_id=#{customer_id}" : "")
141 end
142
143 def url(path)
144 "#{request.base_url}#{path}"
145 end
146
147 def modify_call(call_id)
148 body = Bandwidth::ApiModifyCallRequest.new
149 yield body
150 BANDWIDTH_VOICE.modify_call(
151 CONFIG[:creds][:account],
152 call_id,
153 body: body
154 )
155 rescue Bandwidth::ApiErrorResponseException
156 # If call does not exist, don't need to hang up or send to voicemail
157 # Other side must have hung up already
158 raise $! unless $!.response_code.to_s == "404"
159 end
160
161 route do |r|
162 r.on "inbound" do
163 r.on "calls" do
164 r.post "status" do
165 if params["eventType"] == "disconnect"
166 if (outbound_leg = outbound_transfers.delete(params["callId"]))
167 modify_call(outbound_leg) do |call|
168 call.state = "completed"
169 end
170 end
171
172 customer_repo.find_by_tel(params["to"]).then do |customer|
173 CDR.for_inbound(customer.customer_id, params).save
174 end
175 end
176 "OK"
177 end
178
179 r.on :call_id do |call_id|
180 r.post "transfer_complete" do
181 outbound_leg = outbound_transfers.delete(call_id)
182 if params["cause"] == "hangup" && params["tag"] == "connected"
183 log.info "Normal hangup, now end #{call_id}", loggable_params
184 modify_call(call_id) { |call| call.state = "completed" }
185 elsif !outbound_leg
186 log.debug "Inbound disconnected", loggable_params
187 else
188 log.debug "Go to voicemail", loggable_params
189 modify_call(call_id) do |call|
190 call.redirect_url = url inbound_calls_path(:voicemail)
191 end
192 end
193 ""
194 end
195
196 r.on "voicemail" do
197 r.post "audio" do
198 duration = Time.parse(params["endTime"]) -
199 Time.parse(params["startTime"])
200 next "OK<5" unless duration > 5
201
202 jmp_media_url = params["mediaUrl"].sub(
203 /\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
204 "https://jmp.chat"
205 )
206
207 customer_repo.find_by_tel(params["to"]).then do |customer|
208 m = Blather::Stanza::Message.new
209 m.chat_state = nil
210 m.from = from_jid
211 m.subject = "New Voicemail"
212 m.body = jmp_media_url
213 m << OOB.new(jmp_media_url, desc: "Voicemail Recording")
214 customer.stanza_to(m)
215
216 "OK"
217 end
218 end
219
220 r.post "transcription" do
221 duration = Time.parse(params["endTime"]) -
222 Time.parse(params["startTime"])
223 next "OK<5" unless duration > 5
224
225 customer_repo.find_by_tel(params["to"]).then do |customer|
226 m = Blather::Stanza::Message.new
227 m.chat_state = nil
228 m.from = from_jid
229 m.subject = "Voicemail Transcription"
230 m.body = BANDWIDTH_VOICE.get_recording_transcription(
231 params["accountId"], params["callId"], params["recordingId"]
232 ).data.transcripts[0].text
233 customer.stanza_to(m)
234
235 "OK"
236 end
237 end
238
239 r.post do
240 customer_repo(sgx_repo: Bwmsgsv2Repo.new)
241 .find_by_tel(params["to"])
242 .then { |c|
243 EMPromise.all([c, c.ogm(params["from"])])
244 }.then do |(customer, ogm)|
245 render :voicemail, locals: {
246 ogm: ogm,
247 transcription_enabled: customer.transcription_enabled
248 }
249 end
250 end
251 end
252
253 r.post do
254 customer_repo(
255 sgx_repo: Bwmsgsv2Repo.new
256 ).find(params.fetch("customer_id")).then do |customer|
257 call_attempt_repo.find_inbound(
258 customer,
259 params["from"],
260 call_id: call_id,
261 digits: params["digits"]
262 ).then { |ca| render(*ca.to_render) }
263 end
264 end
265 end
266
267 r.post do
268 customer_repo(
269 sgx_repo: Bwmsgsv2Repo.new
270 ).find_by_tel(params["to"]).then { |customer|
271 EMPromise.all([
272 customer.customer_id, customer.fwd,
273 call_attempt_repo.find_inbound(
274 customer, params["from"], call_id: params["callId"]
275 )
276 ])
277 }.then { |(customer_id, fwd, ca)|
278 call = ca.create_call(fwd, CONFIG[:creds][:account]) { |cc|
279 cc.from = params["from"]
280 cc.application_id = params["applicationId"]
281 cc.answer_url = url inbound_calls_path(nil, customer_id)
282 cc.disconnect_url = url inbound_calls_path(:transfer_complete)
283 }
284
285 next EMPromise.reject(:voicemail) unless call
286
287 outbound_transfers[params["callId"]] = call
288 render :ring, locals: { duration: 300 }
289 }.catch { |e|
290 log_error(e) unless e == :voicemail
291 render :redirect, locals: { to: inbound_calls_path(:voicemail) }
292 }
293 end
294 end
295 end
296
297 r.on "outbound" do
298 r.on "calls" do
299 r.post "status" do
300 log.info "#{params['eventType']} #{params['callId']}", loggable_params
301 if params["eventType"] == "disconnect"
302 call_attempt_repo.ending_call(c, params["callId"])
303 CDR.for_outbound(params).save.catch(&method(:log_error))
304 end
305 "OK"
306 end
307
308 r.post do
309 from = params["from"].sub(/^\+1/, "")
310 customer_repo(
311 sgx_repo: Bwmsgsv2Repo.new
312 ).find_by_format(from).then do |c|
313 call_attempt_repo.find_outbound(
314 c,
315 params["to"],
316 call_id: params["callId"],
317 digits: params["digits"]
318 ).then do |ca|
319 r.json { ca.to_json }
320
321 call_attempt_repo.starting_call(c, params["callId"])
322 render(*ca.to_render)
323 end
324 end
325 end
326 end
327 end
328
329 r.on "ogm" do
330 r.post "start" do
331 render :record_ogm, locals: { customer_id: params["customer_id"] }
332 end
333
334 r.post do
335 jmp_media_url = params["mediaUrl"].sub(
336 /\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
337 "https://jmp.chat"
338 )
339 ogm = OGMDownload.new(jmp_media_url)
340 ogm.download.then do
341 File.rename(ogm.path, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
342 File.chmod(0o644, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
343 customer_repo.find(params["customer_id"]).then do |customer|
344 customer.set_ogm_url("#{CONFIG[:ogm_web_root]}/#{ogm.cid}.mp3")
345 end
346 end
347 end
348 end
349
350 r.public
351 end
352end
353# rubocop:enable Metrics/ClassLength