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/oob"
 14require_relative "lib/roda_capture"
 15require_relative "lib/roda_em_promise"
 16require_relative "lib/rack_fiber"
 17
 18class OGMDownload
 19	def initialize(url)
 20		@digest = Digest::SHA512.new
 21		@f = Tempfile.open("ogm")
 22		@req = EM::HttpRequest.new(url, tls: { verify_peer: true })
 23	end
 24
 25	def download
 26		http = @req.aget
 27		http.stream do |chunk|
 28			@digest << chunk
 29			@f.write chunk
 30		end
 31		http.then { @f.close }.catch do |e|
 32			@f.close!
 33			EMPromise.reject(e)
 34		end
 35	end
 36
 37	def cid
 38		Multibases.encode(
 39			"base58btc",
 40			[1, 85].pack("C*") + Multihashes.encode(@digest.digest, "sha2-512")
 41		).pack.to_s
 42	end
 43
 44	def path
 45		@f.path
 46	end
 47end
 48
 49# rubocop:disable Metrics/ClassLength
 50class Web < Roda
 51	use Rack::Fiber unless ENV["ENV"] == "test" # Must go first!
 52	use Sentry::Rack::CaptureExceptions
 53	plugin :json_parser
 54	plugin :type_routing
 55	plugin :public
 56	plugin :render, engine: "slim"
 57	plugin RodaCapture
 58	plugin RodaEMPromise # Must go last!
 59
 60	class << self
 61		attr_reader :customer_repo, :log, :outbound_transfers
 62
 63		def run(log, *listen_on)
 64			plugin :common_logger, log, method: :info
 65			@outbound_transfers = {}
 66			Thin::Logging.logger = log
 67			Thin::Server.start(
 68				*listen_on,
 69				freeze.app,
 70				signals: false
 71			)
 72		end
 73	end
 74
 75	extend Forwardable
 76	def_delegators :'self.class', :outbound_transfers
 77	def_delegators :request, :params
 78
 79	def log
 80		opts[:common_logger]
 81	end
 82
 83	def log_error(e)
 84		log.error(
 85			"Error raised during #{request.full_path}: #{e.class}",
 86			e,
 87			loggable_params
 88		)
 89		if e.is_a?(::Exception)
 90			Sentry.capture_exception(e)
 91		else
 92			Sentry.capture_message(e.to_s)
 93		end
 94	end
 95
 96	def loggable_params
 97		params.dup.tap do |p|
 98			p.delete("to")
 99			p.delete("from")
100		end
101	end
102
103	def customer_repo(**kwargs)
104		opts[:customer_repo] || CustomerRepo.new(**kwargs)
105	end
106
107	def call_attempt_repo
108		opts[:call_attempt_repo] || CallAttemptRepo.new
109	end
110
111	TEL_CANDIDATES = {
112		"Restricted" => "14",
113		"anonymous" => "15",
114		"Anonymous" => "16",
115		"unavailable" => "17",
116		"Unavailable" => "18"
117	}.freeze
118
119	def sanitize_tel_candidate(candidate)
120		if candidate.length < 3
121			"13;phone-context=anonymous.phone-context.soprani.ca"
122		elsif candidate[0] == "+" && /\A\d+\z/.match(candidate[1..-1])
123			candidate
124		else
125			"#{TEL_CANDIDATES.fetch(candidate, '19')}" \
126				";phone-context=anonymous.phone-context.soprani.ca"
127		end
128	end
129
130	def from_jid
131		Blather::JID.new(
132			sanitize_tel_candidate(params["from"]),
133			CONFIG[:component][:jid]
134		)
135	end
136
137	def inbound_calls_path(suffix, customer_id=nil)
138		["/inbound/calls/#{params['callId']}", suffix].compact.join("/") +
139			(customer_id ? "?customer_id=#{customer_id}" : "")
140	end
141
142	def url(path)
143		"#{request.base_url}#{path}"
144	end
145
146	def modify_call(call_id)
147		body = Bandwidth::ApiModifyCallRequest.new
148		yield body
149		BANDWIDTH_VOICE.modify_call(
150			CONFIG[:creds][:account],
151			call_id,
152			body: body
153		)
154	end
155
156	route do |r|
157		r.on "inbound" do
158			r.on "calls" do
159				r.post "status" do
160					if params["eventType"] == "disconnect"
161						if (outbound_leg = outbound_transfers.delete(params["callId"]))
162							modify_call(outbound_leg) do |call|
163								call.state = "completed"
164							end
165						end
166
167						customer_repo.find_by_tel(params["to"]).then do |customer|
168							CDR.for_inbound(customer.customer_id, params).save
169						end
170					end
171					"OK"
172				end
173
174				r.on :call_id do |call_id|
175					r.post "transfer_complete" do
176						outbound_leg = outbound_transfers.delete(call_id)
177						if params["cause"] == "hangup" && params["tag"] == "connected"
178							log.info "Normal hangup, now end #{call_id}", loggable_params
179							modify_call(call_id) { |call| call.state = "completed" }
180						elsif !outbound_leg
181							log.debug "Inbound disconnected", loggable_params
182						else
183							log.debug "Go to voicemail", loggable_params
184							modify_call(call_id) do |call|
185								call.redirect_url = url inbound_calls_path(:voicemail)
186							end
187						end
188						""
189					end
190
191					r.on "voicemail" do
192						r.post "audio" do
193							duration = Time.parse(params["endTime"]) -
194							           Time.parse(params["startTime"])
195							next "OK<5" unless duration > 5
196
197							jmp_media_url = params["mediaUrl"].sub(
198								/\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
199								"https://jmp.chat"
200							)
201
202							customer_repo.find_by_tel(params["to"]).then do |customer|
203								m = Blather::Stanza::Message.new
204								m.chat_state = nil
205								m.from = from_jid
206								m.subject = "New Voicemail"
207								m.body = jmp_media_url
208								m << OOB.new(jmp_media_url, desc: "Voicemail Recording")
209								customer.stanza_to(m)
210
211								"OK"
212							end
213						end
214
215						r.post "transcription" do
216							duration = Time.parse(params["endTime"]) -
217							           Time.parse(params["startTime"])
218							next "OK<5" unless duration > 5
219
220							customer_repo.find_by_tel(params["to"]).then do |customer|
221								m = Blather::Stanza::Message.new
222								m.chat_state = nil
223								m.from = from_jid
224								m.subject = "Voicemail Transcription"
225								m.body = BANDWIDTH_VOICE.get_recording_transcription(
226									params["accountId"], params["callId"], params["recordingId"]
227								).data.transcripts[0].text
228								customer.stanza_to(m)
229
230								"OK"
231							end
232						end
233
234						r.post do
235							customer_repo(sgx_repo: Bwmsgsv2Repo.new)
236								.find_by_tel(params["to"])
237								.then { |c|
238									EMPromise.all([c, c.ogm(params["from"])])
239								}.then do |(customer, ogm)|
240									render :voicemail, locals: {
241										ogm: ogm,
242										transcription_enabled: customer.transcription_enabled
243									}
244								end
245						end
246					end
247
248					r.post do
249						customer_repo(
250							sgx_repo: Bwmsgsv2Repo.new
251						).find(params.fetch("customer_id")).then do |customer|
252							call_attempt_repo.find_inbound(
253								customer,
254								params["from"],
255								call_id: call_id,
256								digits: params["digits"]
257							).then { |ca| render(*ca.to_render) }
258						end
259					end
260				end
261
262				r.post do
263					customer_repo(
264						sgx_repo: Bwmsgsv2Repo.new
265					).find_by_tel(params["to"]).then { |customer|
266						EMPromise.all([
267							customer.customer_id,
268							customer.fwd,
269							call_attempt_repo.find_inbound(
270								customer, params["from"],
271								call_id: params["callId"]
272							)
273						])
274					}.then do |(customer_id, fwd, ca)|
275						call = ca.create_call(fwd, CONFIG[:creds][:account]) { |cc|
276							cc.from = params["from"]
277							cc.application_id = params["applicationId"]
278							cc.answer_url = url inbound_calls_path(nil, customer_id)
279							cc.disconnect_url = url inbound_calls_path(:transfer_complete)
280						}
281
282						if call
283							outbound_transfers[params["callId"]] = call
284							render :ring, locals: { duration: 300 }
285						else
286							render :redirect, locals: { to: inbound_calls_path(:voicemail) }
287						end
288					end
289				end
290			end
291		end
292
293		r.on "outbound" do
294			r.on "calls" do
295				r.post "status" do
296					log.info "#{params['eventType']} #{params['callId']}", loggable_params
297					if params["eventType"] == "disconnect"
298						CDR.for_outbound(params).save.catch(&method(:log_error))
299					end
300					"OK"
301				end
302
303				r.post do
304					from = params["from"].sub(/^\+1/, "")
305					customer_repo(
306						sgx_repo: Bwmsgsv2Repo.new
307					).find_by_format(from).then do |c|
308						call_attempt_repo.find_outbound(
309							c,
310							params["to"],
311							call_id: params["callId"],
312							digits: params["digits"]
313						).then do |ca|
314							r.json { ca.to_json }
315
316							render(*ca.to_render)
317						end
318					end
319				end
320			end
321		end
322
323		r.on "ogm" do
324			r.post "start" do
325				render :record_ogm, locals: { customer_id: params["customer_id"] }
326			end
327
328			r.post do
329				jmp_media_url = params["mediaUrl"].sub(
330					/\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
331					"https://jmp.chat"
332				)
333				ogm = OGMDownload.new(jmp_media_url)
334				ogm.download.then do
335					File.rename(ogm.path, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
336					File.chmod(0o644, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
337					customer_repo.find(params["customer_id"]).then do |customer|
338						customer.set_ogm_url("#{CONFIG[:ogm_web_root]}/#{ogm.cid}.mp3")
339					end
340				end
341			end
342		end
343
344		r.public
345	end
346end
347# rubocop:enable Metrics/ClassLength