~singpolyma/sgx-jmp

ref: 3260c8a99a392510d2c52f54ac76eeb854a441f8 sgx-jmp/web.rb -rw-r--r-- 1.5 KiB
3260c8a9Stephen Paul Weber Outbound calls from v2 SIP endpoint work and save a CDR 8 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
# frozen_string_literal: true

require "roda"
require "thin"
require "sentry-ruby"

require_relative "lib/cdr"
require_relative "lib/roda_em_promise"
require_relative "lib/rack_fiber"

class Web < Roda
	use Rack::Fiber # Must go first!
	use Sentry::Rack::CaptureExceptions
	plugin :json_parser
	plugin :render, engine: "slim"
	plugin RodaEMPromise # Must go last!

	class << self
		attr_reader :customer_repo, :log
	end

	def customer_repo
		Web.customer_repo
	end

	def log
		Web.log
	end

	def params
		request.params
	end

	def self.run(log, customer_repo)
		plugin :common_logger, log, method: :info
		@log = log
		@customer_repo = customer_repo
		Thin::Logging.logger = log
		Thin::Server.start(
			"::1",
			ENV.fetch("PORT", 8080),
			freeze.app,
			signals: false
		)
	end

	route do |r|
		r.on "outbound" do
			r.on "calls" do
				r.post "status" do
					loggable = params.dup.tap { |p| p.delete("to") }
					log.info "#{params['eventType']} #{params['callId']}", loggable
					if params["eventType"] == "disconnect"
						CDR.for_disconnect(params).save.catch do |e|
							log.error("Error raised during /outbound/calls/status", e, loggable)
							Sentry.capture_exception(e)
						end
					end
					"OK"
				end

				r.post do
					customer_id = params["from"].sub(/^\+/, "")
					customer_repo.find(customer_id).then(:registered?).then do |reg|
						render :forward, locals: {
							from: reg.phone,
							to: params["to"]
						}
					end
				end
			end
		end
	end
end