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