sip_account.rb

 1# frozen_string_literal: true
 2
 3require "digest"
 4require "securerandom"
 5require "value_semantics/monkey_patched"
 6
 7require_relative "mn_words"
 8
 9class SipAccount
10	def self.find(name)
11		new(BandwidthIris::SipCredential.get(name))
12	rescue BandwidthIris::Errors::GenericError # 404
13		New.new(BandwidthIris::SipCredential.new(
14			user_name: name,
15			realm: CONFIG[:sip][:realm],
16			http_voice_v2_app_id: CONFIG[:sip][:app]
17		))
18	end
19
20	def initialize(api_object, password: nil)
21		@api_object = api_object
22		@password = password
23	end
24
25	def with(password:)
26		self.class.new(@api_object.class.new(@api_object.to_data.merge(
27			hash1: Digest::MD5.hexdigest("#{username}:#{server}:#{password}"),
28			hash1b: Digest::MD5.hexdigest(
29				"#{username}:#{server}:#{server}:#{password}"
30			)
31		)), password: password)
32	end
33
34	def with_random_password
35		with(password: MN_WORDS.sample(3).join(" "))
36	end
37
38	PORT = {
39		var: "port",
40		type: :fixed,
41		value: "5008",
42		label: "Port",
43		description: "usually optional"
44	}.freeze
45
46	def form
47		form = Blather::Stanza::X.new(:result)
48		form.title = "Sip Account Reset!"
49		form.instructions = "These are your new SIP credentials"
50
51		form.fields = [
52			{ var: "username", value: username, label: "Username", type: :fixed },
53			{ var: "password", value: @password, label: "Password", type: :fixed },
54			{ var: "server", value: server, label: "Server", type: :fixed },
55			PORT
56		]
57
58		form
59	end
60
61	def put
62		@api_object.update(
63			hash1: @api_object.hash1,
64			hash1b: @api_object.hash1b,
65			realm: server,
66			http_voice_v2_app_id: @api_object.http_voice_v2_app_id
67		)
68		self
69	end
70
71	def delete
72		@api_object.delete
73	end
74
75	def username
76		@api_object.user_name.to_s
77	end
78
79	def server
80		@api_object.realm
81	end
82
83	def uri
84		"sip:#{username}@#{server}"
85	end
86
87	class New < SipAccount
88		def put
89			BandwidthIris::SipCredential.create(
90				user_name: username,
91				hash1: @api_object.hash1,
92				hash1b: @api_object.hash1b,
93				realm: server,
94				http_voice_v2_app_id: @api_object.http_voice_v2_app_id
95			)
96			self
97		end
98	end
99end