web.rb

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