~singpolyma/sgx-jmp

sgx-jmp/lib/customer_fwd.rb -rw-r--r-- 1.7 KiB
c4fc3de0Stephen Paul Weber Revert "Merge branch 'limit-top-up-freq'" 2 days 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
# frozen_string_literal: true

require "bandwidth"
require "value_semantics/monkey_patched"
require "uri"

class CustomerFwd
	def self.for(uri:, timeout:)
		timeout = Timeout.new(timeout)

		fwd = if uri
			if uri =~ /\Asip:(.*)@sip.cheogram.com\Z/
				uri = "xmpp:#{$1.gsub(/%([0-9A-F]{2})/i) { $1.to_i(16).chr }}"
			end

			URIS.fetch(uri.split(":", 2).first.to_sym) {
				raise "Unknown forward URI: #{uri}"
			}.new(uri: uri, timeout: timeout)
		end

		fwd && !timeout.zero? ? fwd : None.new(uri: uri, timeout: timeout)
	end

	class Timeout
		def self.new(s)
			s.is_a?(self) ? s : super
		end

		def initialize(s)
			@timeout = s.nil? || s.to_i.negative? || s.to_i > 300 ? 300 : s.to_i
		end

		def zero?
			@timeout.zero?
		end

		def to_i
			@timeout
		end

		def to_s
			to_i.to_s
		end
	end

	value_semantics do
		uri Either(/:/, NilClass)
		def_attr :timeout, Timeout, coerce: Timeout.method(:new)
	end

	def with(new_attrs)
		CustomerFwd.for(to_h.merge(new_attrs))
	end

	def create_call(account)
		request = Bandwidth::ApiCreateCallRequest.new.tap { |cc|
			cc.to = to
			cc.call_timeout = timeout.to_i
			yield cc if block_given?
		}
		BANDWIDTH_VOICE.create_call(account, body: request).data.call_id
	end

	class Tel < CustomerFwd
		def initialize(values)
			super
			raise "Bad tel format: #{uri}" unless uri.match?(/\Atel:\+1\d{10}\Z/)
		end

		def to
			uri.sub(/^tel:/, "")
		end
	end

	class SIP < CustomerFwd
		def to
			uri
		end
	end

	class XMPP < CustomerFwd
		def to
			jid = uri.sub(/^xmpp:/, "")
			"sip:#{ERB::Util.url_encode(jid)}@sip.cheogram.com"
		end
	end

	class None < CustomerFwd
		def create_call(*); end

		def to; end
	end

	URIS = {
		tel: Tel,
		sip: SIP,
		xmpp: XMPP
	}.freeze
end