web.rb

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