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(
250 customer,
251 params["from"],
252 call_id: call_id,
253 digits: params["digits"],
254 direction: :inbound
255 ).then { |ca| render(*ca.to_render) }
256 end
257 end
258 end
259
260 r.post do
261 customer_repo(
262 sgx_repo: Bwmsgsv2Repo.new
263 ).find_by_tel(params["to"]).then { |customer|
264 EMPromise.all([
265 customer.fwd,
266 call_attempt_repo.find(
267 customer, params["from"],
268 call_id: params["callId"], direction: :inbound
269 )
270 ])
271 }.then do |(fwd, ca)|
272 call = ca.create_call(fwd, CONFIG[:creds][:account]) { |cc|
273 cc.from = params["from"]
274 cc.application_id = params["applicationId"]
275 cc.answer_url = url inbound_calls_path(nil)
276 cc.disconnect_url = url inbound_calls_path(:transfer_complete)
277 }
278
279 if call
280 outbound_transfers[params["callId"]] = call
281 render :ring, locals: { duration: 300 }
282 else
283 render :redirect, locals: { to: inbound_calls_path(:voicemail) }
284 end
285 end
286 end
287 end
288 end
289
290 r.on "outbound" do
291 r.on "calls" do
292 r.post "status" do
293 log.info "#{params['eventType']} #{params['callId']}", loggable_params
294 if params["eventType"] == "disconnect"
295 CDR.for_outbound(params).save.catch(&method(:log_error))
296 end
297 "OK"
298 end
299
300 r.post do
301 from = params["from"].sub(/^\+1/, "")
302 customer_repo(
303 sgx_repo: Bwmsgsv2Repo.new
304 ).find_by_format(from).then do |c|
305 call_attempt_repo.find(
306 c,
307 params["to"],
308 call_id: params["callId"],
309 digits: params["digits"]
310 ).then do |ca|
311 r.json { ca.to_json }
312
313 render(*ca.to_render)
314 end
315 end
316 end
317 end
318 end
319
320 r.on "ogm" do
321 r.post "start" do
322 render :record_ogm, locals: { customer_id: params["customer_id"] }
323 end
324
325 r.post do
326 jmp_media_url = params["mediaUrl"].sub(
327 /\Ahttps:\/\/voice.bandwidth.com\/api\/v2\/accounts\/\d+/,
328 "https://jmp.chat"
329 )
330 ogm = OGMDownload.new(jmp_media_url)
331 ogm.download.then do
332 File.rename(ogm.path, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
333 File.chmod(0o644, "#{CONFIG[:ogm_path]}/#{ogm.cid}")
334 customer_repo.find(params["customer_id"]).then do |customer|
335 customer.set_ogm_url("#{CONFIG[:ogm_web_root]}/#{ogm.cid}.mp3")
336 end
337 end
338 end
339 end
340
341 r.public
342 end
343end
344# rubocop:enable Metrics/ClassLength