sip_account.rb

  1# frozen_string_literal: true
  2
  3require "em-synchrony/em-http" # For aget vs get
  4require "securerandom"
  5require "value_semantics/monkey_patched"
  6
  7require_relative "./catapult"
  8require_relative "./mn_words"
  9
 10class SipAccount
 11	def self.find(name)
 12		CATAPULT.endpoint_find(name).then do |found|
 13			next New.new(username: name) unless found
 14
 15			new(username: found["name"], url: found["url"])
 16		end
 17	end
 18
 19	module Common
 20		def with_random_password
 21			with(password: MN_WORDS.sample(3).join(" "))
 22		end
 23
 24	protected
 25
 26		def create
 27			CATAPULT.create_endpoint(
 28				name: username,
 29				credentials: { password: password }
 30			).then do |url|
 31				with(url: url)
 32			end
 33		end
 34	end
 35
 36	include Common
 37
 38	value_semantics do
 39		url String
 40		username String
 41		password Either(String, nil), default: nil
 42	end
 43
 44	def form
 45		form = Blather::Stanza::X.new(:result)
 46		form.title = "Sip Account Reset!"
 47		form.instructions = "These are your new SIP credentials"
 48
 49		form.fields = [
 50			{ var: "username", value: username, label: "Username" },
 51			{ var: "password", value: password, label: "Password" },
 52			{ var: "server", value: server, label: "Server" }
 53		]
 54
 55		form
 56	end
 57
 58	def put
 59		delete.then { create }
 60	end
 61
 62	def delete
 63		CATAPULT.delete(url).then do |http|
 64			unless http.response_header.status == 200
 65				raise "Delete old SIP account failed"
 66			end
 67
 68			self
 69		end
 70	end
 71
 72protected
 73
 74	protected :url, :username, :password
 75
 76	def server
 77		CATAPULT.sip_host
 78	end
 79
 80	class New
 81		include Common
 82
 83		value_semantics do
 84			username String
 85			password String, default_generator: -> { MN_WORDS.sample(3).join(" ") }
 86		end
 87
 88		def put
 89			create
 90		end
 91
 92		def with(**kwargs)
 93			if kwargs.key?(:url)
 94				SipAccount.new(internal_to_h.merge(kwargs))
 95			else
 96				super
 97			end
 98		end
 99
100		protected :username, :password
101	end
102end