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