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::APIException
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 [404, 409].include?($!.response_code)
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(
215 inbound_calls_path(:transfer_complete, customer_id)
216 )
217 end
218 end
219 end
220
221 route do |r|
222 r.get "healthcheck" do
223 "OK"
224 end
225
226 r.on "inbound" do
227 r.on "calls" do
228 r.post "status" do
229 if params["eventType"] == "disconnect"
230 if (outbound_leg = outbound_transfers.delete(params["callId"]))
231 modify_call(outbound_leg) do |call|
232 call.state = "completed"
233 end
234 end
235
236 customer_repo.find_by_tel(params["to"]).then do |customer|
237 cdr_repo.put(CDR.for_inbound(customer.customer_id, params))
238 end
239 end
240 "OK"
241 end
242
243 r.on :call_id do |call_id|
244 r.post "transfer_complete" do
245 outbound_leg = outbound_transfers.delete(call_id)
246 if params["cause"] == "hangup" && params["tag"] == "connected"
247 log.info "Normal hangup, now end #{call_id}", loggable_params
248 modify_call(call_id) { |call| call.state = "completed" }
249 elsif !outbound_leg
250 log.debug "Inbound disconnected", loggable_params
251 else
252 log.debug "Go to voicemail", loggable_params
253 modify_call(call_id) do |call|
254 call.redirect_url = url inbound_calls_path(:voicemail)
255 end
256 end
257 ""
258 end
259
260 r.on "voicemail" do
261 r.post "audio" do
262 duration = Time.parse(params["endTime"]) -
263 Time.parse(params["startTime"])
264 next "OK<5" unless duration > 5
265
266 jmp_media_url = params["mediaUrl"].sub(
267 /\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
268 "https://jmp.chat"
269 )
270
271 find_by_tel_with_fallback(
272 sgx_repo: Bwmsgsv2Repo.new,
273 transcription_enabled: false
274 ).then do |customer|
275 start_transcription(customer, call_id, jmp_media_url)
276
277 m = Blather::Stanza::Message.new
278 m.chat_state = nil
279 m.from = from_jid
280 m.subject = "New Voicemail"
281 m << OOB.new(jmp_media_url)
282 customer.stanza_to(m)
283
284 "OK"
285 end
286 end
287
288 r.post "language_id" do
289 rev_ai.language_id_result(params).then { |result|
290 rev_ai.stt(
291 result["top_language"],
292 result.dig("metadata", "media_url"),
293 url(inbound_calls_path(
294 "voicemail/transcription",
295 call_id: call_id
296 )),
297 **result["metadata"].transform_keys(&:to_sym)
298 ).then { "OK" }
299 }.catch_only(RevAi::Failed) { |e|
300 log_error(e)
301 "Failure logged"
302 }
303 end
304
305 r.post "transcription" do
306 rev_ai.stt_result(params, request.url).then { |result|
307 next "OK" if result["text"].to_s.empty?
308
309 customer_repo.find(
310 result.dig("metadata", "customer_id")
311 ).then do |customer|
312 m = Blather::Stanza::Message.new
313 m.chat_state = nil
314 m.from = result.dig("metadata", "from_jid")
315 m.subject = "Voicemail Transcription"
316 m.body = result["text"]
317 customer.stanza_to(m)
318
319 "OK"
320 end
321 }.catch_only(RevAi::Failed) { |e|
322 log_error(e)
323 "Failure logged"
324 }
325 end
326
327 r.post do
328 find_by_tel_with_fallback(
329 sgx_repo: Bwmsgsv2Repo.new,
330 ogm_url: nil
331 ).then { |c|
332 c.ogm(params["from"]) if c.fwd.voicemail_enabled?
333 }.then { |ogm|
334 next render :hangup unless ogm
335
336 render :voicemail, locals: { ogm: ogm }
337 }.catch_only(CustomerRepo::NotFound) {
338 render "inbound/no_customer"
339 }
340 end
341 end
342
343 r.post do
344 customer_repo(
345 sgx_repo: Bwmsgsv2Repo.new
346 ).find(params.fetch("customer_id")).then do |customer|
347 call_attempt_repo.find_inbound(
348 customer,
349 params["from"],
350 call_id: call_id,
351 digits: params["digits"]
352 ).then { |ca| render(*ca.to_render) }
353 end
354 end
355 end
356
357 r.post do
358 customer_repo(
359 sgx_repo: Bwmsgsv2Repo.new
360 ).find_by_tel(params["to"]).then { |customer|
361 reachability_repo.find(customer, params["from"]).then do |reach|
362 reach.filter(if_yes: ->(_) { render :hangup }) do
363 create_call(
364 customer,
365 params["from"],
366 params["callId"],
367 params["applicationId"]
368 ).then { |call|
369 next EMPromise.reject(:voicemail) unless call
370
371 outbound_transfers[params["callId"]] = call
372 render :ring, locals: { duration: 300 }
373 }
374 end
375 end
376 }.catch_only(CustomerFwd::InfiniteTimeout) { |e|
377 render :forward, locals: { fwd: e.fwd, from: params["from"] }
378 }.catch { |e|
379 log_error(e) unless e == :voicemail
380 render :redirect, locals: { to: inbound_calls_path(:voicemail) }
381 }
382 end
383 end
384 end
385
386 r.on "outbound" do
387 r.on "calls" do
388 r.post "status" do
389 log.info "#{params['eventType']} #{params['callId']}", loggable_params
390 if params["eventType"] == "disconnect"
391 customer_id = params["from"].sub(/^(?:\+|c)/, "")
392 customer_id = from.sub(/^1/, "") if customer_id.length > 10
393 call_attempt_repo.ending_call(customer_id, params["callId"])
394 cdr_repo
395 .put(CDR.for_outbound(customer_id, params))
396 .catch(&method(:log_error))
397 end
398 "OK"
399 end
400
401 r.post do
402 from = params["from"].sub(/^(?:\+|c)/, "")
403 from = from.sub(/^1/, "") if from.length > 10
404 customer_repo(
405 sgx_repo: Bwmsgsv2Repo.new
406 ).find_by_format(from).then { |c|
407 call_attempt_repo.find_outbound(
408 c,
409 params["to"],
410 call_id: params["callId"],
411 digits: params["digits"]
412 ).then do |ca|
413 r.json { ca.to_json }
414
415 call_attempt_repo.starting_call(c, params["callId"])
416 render(*ca.to_render)
417 end
418 }.catch_only(CustomerRepo::NotFound) {
419 render "outbound/no_customer"
420 }
421 end
422 end
423 end
424
425 r.on "ogm" do
426 r.post "start" do
427 render :record_ogm, locals: { customer_id: params["customer_id"] }
428 end
429
430 r.post do
431 jmp_media_url = params["mediaUrl"].sub(
432 /\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
433 "https://jmp.chat"
434 )
435 ogm = OGMDownload.new(jmp_media_url)
436 ogm.download.then do
437 File.rename(ogm.path, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
438 File.chmod(0o644, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
439 customer_repo.find(params["customer_id"]).then do |customer|
440 customer.set_ogm_url("#{CONFIG[:ogm_web_root]}/#{ogm.cid}.mp3")
441 end
442 end
443 end
444 end
445
446 r.public
447 end
448end
449# rubocop:enable Metrics/ClassLength