~singpolyma/sgx-jmp

ref: da80d0c78906bb02690aab89d57a5dd304fcf2e7 sgx-jmp/web.rb -rw-r--r-- 10.1 KiB
da80d0c7Stephen Paul Weber Throttle notification processing to prevent starvation 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# frozen_string_literal: true

require "digest"
require "forwardable"
require "multibases"
require "multihashes"
require "roda"
require "thin"
require "sentry-ruby"

require_relative "lib/call_attempt_repo"
require_relative "lib/cdr"
require_relative "lib/oob"
require_relative "lib/rev_ai"
require_relative "lib/roda_capture"
require_relative "lib/roda_em_promise"
require_relative "lib/rack_fiber"

class OGMDownload
	def initialize(url)
		@digest = Digest::SHA512.new
		@f = Tempfile.open("ogm")
		@req = EM::HttpRequest.new(url, tls: { verify_peer: true })
	end

	def download
		http = @req.aget
		http.stream do |chunk|
			@digest << chunk
			@f.write chunk
		end
		http.then { @f.close }.catch do |e|
			@f.close!
			EMPromise.reject(e)
		end
	end

	def cid
		Multibases.encode(
			"base58btc",
			[1, 85].pack("C*") + Multihashes.encode(@digest.digest, "sha2-512")
		).pack.to_s
	end

	def path
		@f.path
	end
end

# rubocop:disable Metrics/ClassLength
class Web < Roda
	use Rack::Fiber unless ENV["ENV"] == "test" # Must go first!
	use Sentry::Rack::CaptureExceptions
	plugin :json_parser
	plugin :type_routing
	plugin :public
	plugin :render, engine: "slim"
	plugin RodaCapture
	plugin RodaEMPromise # Must go last!

	class << self
		attr_reader :customer_repo, :log, :outbound_transfers

		def run(log, *listen_on)
			plugin :common_logger, log, method: :info
			@outbound_transfers = {}
			Thin::Logging.logger = log
			Thin::Server.start(
				*listen_on,
				freeze.app,
				signals: false
			)
		end
	end

	extend Forwardable
	def_delegators :'self.class', :outbound_transfers
	def_delegators :request, :params

	def log
		opts[:common_logger]
	end

	def log_error(e)
		log.error(
			"Error raised during #{request.fullpath}: #{e.class}",
			e,
			loggable_params
		)
		if e.is_a?(::Exception)
			Sentry.capture_exception(e)
		else
			Sentry.capture_message(e.to_s)
		end
	end

	def loggable_params
		params.dup.tap do |p|
			p.delete("to")
			p.delete("from")
		end
	end

	def customer_repo(**kwargs)
		kwargs[:set_user] = Sentry.method(:set_user) unless kwargs[:set_user]
		opts[:customer_repo] || CustomerRepo.new(**kwargs)
	end

	def call_attempt_repo
		opts[:call_attempt_repo] || CallAttemptRepo.new
	end

	def rev_ai
		RevAi.new
	end

	TEL_CANDIDATES = {
		"Restricted" => "14",
		"anonymous" => "15",
		"Anonymous" => "16",
		"unavailable" => "17",
		"Unavailable" => "18"
	}.freeze

	def sanitize_tel_candidate(candidate)
		if candidate.length < 3
			"13;phone-context=anonymous.phone-context.soprani.ca"
		elsif candidate[0] == "+" && /\A\d+\z/.match(candidate[1..-1])
			candidate
		else
			"#{TEL_CANDIDATES.fetch(candidate, '19')}" \
				";phone-context=anonymous.phone-context.soprani.ca"
		end
	end

	def from_jid
		Blather::JID.new(
			sanitize_tel_candidate(params["from"]),
			CONFIG[:component][:jid]
		)
	end

	def inbound_calls_path(suffix, customer_id=nil, call_id: nil)
		[
			"/inbound/calls/#{call_id || params['callId']}",
			suffix
		].compact.join("/") +
			(customer_id ? "?customer_id=#{customer_id}" : "")
	end

	def url(path)
		"#{request.base_url}#{path}"
	end

	def modify_call(call_id)
		body = Bandwidth::ApiModifyCallRequest.new
		yield body
		BANDWIDTH_VOICE.modify_call(
			CONFIG[:creds][:account],
			call_id,
			body: body
		)
	rescue Bandwidth::ApiErrorResponseException
		# If call does not exist, don't need to hang up or send to voicemail
		# Other side must have hung up already
		raise $! unless $!.response_code.to_s == "404"
	end

	def do_alternate_transcription(customer, call_id)
		return unless customer.alternate_transcription_enabled

		rev_ai.language_id(
			jmp_media_url,
			url(inbound_calls_path(
				"voicemail/rev_ai/language_id", call_id: call_id
			)),
			from_jid: from_jid,
			customer_id: customer.customer_id
		)
	end

	route do |r|
		r.on "inbound" do
			r.on "calls" do
				r.post "status" do
					if params["eventType"] == "disconnect"
						if (outbound_leg = outbound_transfers.delete(params["callId"]))
							modify_call(outbound_leg) do |call|
								call.state = "completed"
							end
						end

						customer_repo.find_by_tel(params["to"]).then do |customer|
							CDR.for_inbound(customer.customer_id, params).save
						end
					end
					"OK"
				end

				r.on :call_id do |call_id|
					r.post "transfer_complete" do
						outbound_leg = outbound_transfers.delete(call_id)
						if params["cause"] == "hangup" && params["tag"] == "connected"
							log.info "Normal hangup, now end #{call_id}", loggable_params
							modify_call(call_id) { |call| call.state = "completed" }
						elsif !outbound_leg
							log.debug "Inbound disconnected", loggable_params
						else
							log.debug "Go to voicemail", loggable_params
							modify_call(call_id) do |call|
								call.redirect_url = url inbound_calls_path(:voicemail)
							end
						end
						""
					end

					r.on "voicemail" do
						r.post "audio" do
							duration = Time.parse(params["endTime"]) -
							           Time.parse(params["startTime"])
							next "OK<5" unless duration > 5

							jmp_media_url = params["mediaUrl"].sub(
								/\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
								"https://jmp.chat"
							)

							customer_repo(
								sgx_repo: Bwmsgsv2Repo.new
							).find_by_tel(params["to"]).then do |customer|
								do_alternate_transcription(customer, call_id)

								m = Blather::Stanza::Message.new
								m.chat_state = nil
								m.from = from_jid
								m.subject = "New Voicemail"
								m.body = jmp_media_url
								m << OOB.new(jmp_media_url, desc: "Voicemail Recording")
								customer.stanza_to(m)

								"OK"
							end
						end

						r.post "transcription" do
							duration = Time.parse(params["endTime"]) -
							           Time.parse(params["startTime"])
							next "OK<5" unless duration > 5

							customer_repo.find_by_tel(params["to"]).then do |customer|
								m = Blather::Stanza::Message.new
								m.chat_state = nil
								m.from = from_jid
								m.subject = "Voicemail Transcription"
								m.body = BANDWIDTH_VOICE.get_recording_transcription(
									params["accountId"], params["callId"], params["recordingId"]
								).data.transcripts[0].text
								customer.stanza_to(m)

								"OK"
							end
						end

						r.on "rev_ai" do
							r.post "language_id" do
								rev_ai.language_id_result(params).then do |result|
									rev_ai.stt(
										result["top_language"],
										result.dig("metadata", "media_url"),
										url(inbound_calls_path(
											"voicemail/rev_ai/transcription",
											call_id: call_id
										)),
										**result["metadata"].transform_keys(&:to_sym)
									).then { "OK" }
								end
							end

							r.post "transcription" do
								rev_ai.stt_result(params).then do |result|
									customer_repo.find(
										result.dig("metadata", "customer_id")
									).then do |customer|
										m = Blather::Stanza::Message.new
										m.chat_state = nil
										m.from = result.dig("metadata", "from_jid")
										m.subject = "Voicemail Transcription"
										m.body = "Alternate Transcription: #{result['text']}"
										customer.stanza_to(m)

										"OK"
									end
								end
							end
						end

						r.post do
							customer_repo(sgx_repo: Bwmsgsv2Repo.new)
								.find_by_tel(params["to"])
								.then { |c|
									EMPromise.all([c, c.ogm(params["from"])])
								}.then do |(customer, ogm)|
									render :voicemail, locals: {
										ogm: ogm,
										transcription_enabled: customer.transcription_enabled
									}
								end
						end
					end

					r.post do
						customer_repo(
							sgx_repo: Bwmsgsv2Repo.new
						).find(params.fetch("customer_id")).then do |customer|
							call_attempt_repo.find_inbound(
								customer,
								params["from"],
								call_id: call_id,
								digits: params["digits"]
							).then { |ca| render(*ca.to_render) }
						end
					end
				end

				r.post do
					customer_repo(
						sgx_repo: Bwmsgsv2Repo.new
					).find_by_tel(params["to"]).then { |customer|
						EMPromise.all([
							customer.customer_id, customer.fwd,
							call_attempt_repo.find_inbound(
								customer, params["from"], call_id: params["callId"]
							)
						])
					}.then { |(customer_id, fwd, ca)|
						call = ca.create_call(fwd, CONFIG[:creds][:account]) { |cc|
							cc.from = params["from"]
							cc.application_id = params["applicationId"]
							cc.answer_url = url inbound_calls_path(nil, customer_id)
							cc.disconnect_url = url inbound_calls_path(:transfer_complete)
						}

						next EMPromise.reject(:voicemail) unless call

						outbound_transfers[params["callId"]] = call
						render :ring, locals: { duration: 300 }
					}.catch { |e|
						log_error(e) unless e == :voicemail
						render :redirect, locals: { to: inbound_calls_path(:voicemail) }
					}
				end
			end
		end

		r.on "outbound" do
			r.on "calls" do
				r.post "status" do
					log.info "#{params['eventType']} #{params['callId']}", loggable_params
					if params["eventType"] == "disconnect"
						call_attempt_repo.ending_call(c, params["callId"])
						CDR.for_outbound(params).save.catch(&method(:log_error))
					end
					"OK"
				end

				r.post do
					from = params["from"].sub(/^\+1/, "")
					customer_repo(
						sgx_repo: Bwmsgsv2Repo.new
					).find_by_format(from).then do |c|
						call_attempt_repo.find_outbound(
							c,
							params["to"],
							call_id: params["callId"],
							digits: params["digits"]
						).then do |ca|
							r.json { ca.to_json }

							call_attempt_repo.starting_call(c, params["callId"])
							render(*ca.to_render)
						end
					end
				end
			end
		end

		r.on "ogm" do
			r.post "start" do
				render :record_ogm, locals: { customer_id: params["customer_id"] }
			end

			r.post do
				jmp_media_url = params["mediaUrl"].sub(
					/\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
					"https://jmp.chat"
				)
				ogm = OGMDownload.new(jmp_media_url)
				ogm.download.then do
					File.rename(ogm.path, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
					File.chmod(0o644, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
					customer_repo.find(params["customer_id"]).then do |customer|
						customer.set_ogm_url("#{CONFIG[:ogm_web_root]}/#{ogm.cid}.mp3")
					end
				end
			end
		end

		r.public
	end
end
# rubocop:enable Metrics/ClassLength