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.body = jmp_media_url
276 m << OOB.new(jmp_media_url, desc: "Voicemail Recording")
277 customer.stanza_to(m)
278
279 "OK"
280 end
281 end
282
283 r.post "language_id" do
284 rev_ai.language_id_result(params).then { |result|
285 rev_ai.stt(
286 result["top_language"],
287 result.dig("metadata", "media_url"),
288 url(inbound_calls_path(
289 "voicemail/transcription",
290 call_id: call_id
291 )),
292 **result["metadata"].transform_keys(&:to_sym)
293 ).then { "OK" }
294 }.catch_only(RevAi::Failed) { |e|
295 log_error(e)
296 "Failure logged"
297 }
298 end
299
300 r.post "transcription" do
301 rev_ai.stt_result(params, request.url).then { |result|
302 next "OK" if result["text"].to_s.empty?
303
304 customer_repo.find(
305 result.dig("metadata", "customer_id")
306 ).then do |customer|
307 m = Blather::Stanza::Message.new
308 m.chat_state = nil
309 m.from = result.dig("metadata", "from_jid")
310 m.subject = "Voicemail Transcription"
311 m.body = result["text"]
312 customer.stanza_to(m)
313
314 "OK"
315 end
316 }.catch_only(RevAi::Failed) { |e|
317 log_error(e)
318 "Failure logged"
319 }
320 end
321
322 r.post do
323 find_by_tel_with_fallback(
324 sgx_repo: Bwmsgsv2Repo.new,
325 ogm_url: nil
326 ).then { |c|
327 c.ogm(params["from"]) if c.fwd.voicemail_enabled?
328 }.then { |ogm|
329 next render :hangup unless ogm
330
331 render :voicemail, locals: { ogm: ogm }
332 }.catch_only(CustomerRepo::NotFound) {
333 render "inbound/no_customer"
334 }
335 end
336 end
337
338 r.post do
339 customer_repo(
340 sgx_repo: Bwmsgsv2Repo.new
341 ).find(params.fetch("customer_id")).then do |customer|
342 call_attempt_repo.find_inbound(
343 customer,
344 params["from"],
345 call_id: call_id,
346 digits: params["digits"]
347 ).then { |ca| render(*ca.to_render) }
348 end
349 end
350 end
351
352 r.post do
353 customer_repo(
354 sgx_repo: Bwmsgsv2Repo.new
355 ).find_by_tel(params["to"]).then { |customer|
356 reachability_repo.find(customer, params["from"]).then do |reach|
357 reach.filter(if_yes: ->(_) { render :hangup }) do
358 create_call(
359 customer,
360 params["from"],
361 params["callId"],
362 params["applicationId"]
363 ).then { |call|
364 next EMPromise.reject(:voicemail) unless call
365
366 outbound_transfers[params["callId"]] = call
367 render :ring, locals: { duration: 300 }
368 }
369 end
370 end
371 }.catch_only(CustomerFwd::InfiniteTimeout) { |e|
372 render :forward, locals: { fwd: e.fwd, from: params["from"] }
373 }.catch { |e|
374 log_error(e) unless e == :voicemail
375 render :redirect, locals: { to: inbound_calls_path(:voicemail) }
376 }
377 end
378 end
379 end
380
381 r.on "outbound" do
382 r.on "calls" do
383 r.post "status" do
384 log.info "#{params['eventType']} #{params['callId']}", loggable_params
385 if params["eventType"] == "disconnect"
386 customer_id = params["from"].sub(/^(?:\+|c)/, "")
387 customer_id = from.sub(/^1/, "") if customer_id.length > 10
388 call_attempt_repo.ending_call(customer_id, params["callId"])
389 cdr_repo.put(CDR.for_outbound(params)).catch(&method(:log_error))
390 end
391 "OK"
392 end
393
394 r.post do
395 from = params["from"].sub(/^(?:\+|c)/, "")
396 from = from.sub(/^1/, "") if from.length > 10
397 customer_repo(
398 sgx_repo: Bwmsgsv2Repo.new
399 ).find_by_format(from).then { |c|
400 call_attempt_repo.find_outbound(
401 c,
402 params["to"],
403 call_id: params["callId"],
404 digits: params["digits"]
405 ).then do |ca|
406 r.json { ca.to_json }
407
408 call_attempt_repo.starting_call(c, params["callId"])
409 render(*ca.to_render)
410 end
411 }.catch_only(CustomerRepo::NotFound) {
412 render "outbound/no_customer"
413 }
414 end
415 end
416 end
417
418 r.on "ogm" do
419 r.post "start" do
420 render :record_ogm, locals: { customer_id: params["customer_id"] }
421 end
422
423 r.post do
424 jmp_media_url = params["mediaUrl"].sub(
425 /\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
426 "https://jmp.chat"
427 )
428 ogm = OGMDownload.new(jmp_media_url)
429 ogm.download.then do
430 File.rename(ogm.path, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
431 File.chmod(0o644, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
432 customer_repo.find(params["customer_id"]).then do |customer|
433 customer.set_ogm_url("#{CONFIG[:ogm_web_root]}/#{ogm.cid}.mp3")
434 end
435 end
436 end
437 end
438
439 r.public
440 end
441end
442# rubocop:enable Metrics/ClassLength