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							Sentry.set_user(id: customer.customer_id)
169							CDR.for_inbound(customer.customer_id, params).save
170						end
171					end
172					"OK"
173				end
174
175				r.on :call_id do |call_id|
176					r.post "transfer_complete" do
177						outbound_leg = outbound_transfers.delete(call_id)
178						if params["cause"] == "hangup" && params["tag"] == "connected"
179							log.info "Normal hangup, now end #{call_id}", loggable_params
180							modify_call(call_id) { |call| call.state = "completed" }
181						elsif !outbound_leg
182							log.debug "Inbound disconnected", loggable_params
183						else
184							log.debug "Go to voicemail", loggable_params
185							modify_call(call_id) do |call|
186								call.redirect_url = url inbound_calls_path(:voicemail)
187							end
188						end
189						""
190					end
191
192					r.on "voicemail" do
193						r.post "audio" do
194							duration = Time.parse(params["endTime"]) -
195							           Time.parse(params["startTime"])
196							next "OK<5" unless duration > 5
197
198							jmp_media_url = params["mediaUrl"].sub(
199								/\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
200								"https://jmp.chat"
201							)
202
203							customer_repo.find_by_tel(params["to"]).then do |customer|
204								Sentry.set_user(id: customer.customer_id)
205								m = Blather::Stanza::Message.new
206								m.chat_state = nil
207								m.from = from_jid
208								m.subject = "New Voicemail"
209								m.body = jmp_media_url
210								m << OOB.new(jmp_media_url, desc: "Voicemail Recording")
211								customer.stanza_to(m)
212
213								"OK"
214							end
215						end
216
217						r.post "transcription" do
218							duration = Time.parse(params["endTime"]) -
219							           Time.parse(params["startTime"])
220							next "OK<5" unless duration > 5
221
222							customer_repo.find_by_tel(params["to"]).then do |customer|
223								Sentry.set_user(id: customer.customer_id)
224								m = Blather::Stanza::Message.new
225								m.chat_state = nil
226								m.from = from_jid
227								m.subject = "Voicemail Transcription"
228								m.body = BANDWIDTH_VOICE.get_recording_transcription(
229									params["accountId"], params["callId"], params["recordingId"]
230								).data.transcripts[0].text
231								customer.stanza_to(m)
232
233								"OK"
234							end
235						end
236
237						r.post do
238							customer_repo(sgx_repo: Bwmsgsv2Repo.new)
239								.find_by_tel(params["to"])
240								.then { |c|
241									Sentry.set_user(id: c.customer_id)
242									EMPromise.all([c, c.ogm(params["from"])])
243								}.then do |(customer, ogm)|
244									render :voicemail, locals: {
245										ogm: ogm,
246										transcription_enabled: customer.transcription_enabled
247									}
248								end
249						end
250					end
251
252					r.post do
253						customer_repo(
254							sgx_repo: Bwmsgsv2Repo.new
255						).find(params.fetch("customer_id")).then do |customer|
256							Sentry.set_user(id: customer.customer_id)
257							call_attempt_repo.find_inbound(
258								customer,
259								params["from"],
260								call_id: call_id,
261								digits: params["digits"]
262							).then { |ca| render(*ca.to_render) }
263						end
264					end
265				end
266
267				r.post do
268					customer_repo(
269						sgx_repo: Bwmsgsv2Repo.new
270					).find_by_tel(params["to"]).then { |customer|
271						Sentry.set_user(id: customer.customer_id)
272						EMPromise.all([
273							customer.customer_id,
274							customer.fwd,
275							call_attempt_repo.find_inbound(
276								customer, params["from"], call_id: params["callId"]
277							)
278						])
279					}.then do |(customer_id, fwd, ca)|
280						call = ca.create_call(fwd, CONFIG[:creds][:account]) { |cc|
281							cc.from = params["from"]
282							cc.application_id = params["applicationId"]
283							cc.answer_url = url inbound_calls_path(nil, customer_id)
284							cc.disconnect_url = url inbound_calls_path(:transfer_complete)
285						}
286
287						if call
288							outbound_transfers[params["callId"]] = call
289							render :ring, locals: { duration: 300 }
290						else
291							render :redirect, locals: { to: inbound_calls_path(:voicemail) }
292						end
293					end
294				end
295			end
296		end
297
298		r.on "outbound" do
299			r.on "calls" do
300				r.post "status" do
301					log.info "#{params['eventType']} #{params['callId']}", loggable_params
302					if params["eventType"] == "disconnect"
303						CDR.for_outbound(params).save.catch(&method(:log_error))
304					end
305					"OK"
306				end
307
308				r.post do
309					from = params["from"].sub(/^\+1/, "")
310					customer_repo(
311						sgx_repo: Bwmsgsv2Repo.new
312					).find_by_format(from).then do |c|
313						Sentry.set_user(id: c.customer_id)
314						call_attempt_repo.find_outbound(
315							c,
316							params["to"],
317							call_id: params["callId"],
318							digits: params["digits"]
319						).then do |ca|
320							r.json { ca.to_json }
321
322							render(*ca.to_render)
323						end
324					end
325				end
326			end
327		end
328
329		r.on "ogm" do
330			r.post "start" do
331				render :record_ogm, locals: { customer_id: params["customer_id"] }
332			end
333
334			r.post do
335				jmp_media_url = params["mediaUrl"].sub(
336					/\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
337					"https://jmp.chat"
338				)
339				ogm = OGMDownload.new(jmp_media_url)
340				ogm.download.then do
341					File.rename(ogm.path, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
342					File.chmod(0o644, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
343					customer_repo.find(params["customer_id"]).then do |customer|
344						customer.set_ogm_url("#{CONFIG[:ogm_web_root]}/#{ogm.cid}.mp3")
345					end
346				end
347			end
348		end
349
350		r.public
351	end
352end
353# rubocop:enable Metrics/ClassLength