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