bwmsgsv2_repo.rb

 1# frozen_string_literal: true
 2
 3require "lazy_object"
 4
 5require_relative "customer_fwd"
 6require_relative "ibr_repo"
 7require_relative "trivial_backend_sgx_repo"
 8
 9class Bwmsgsv2Repo
10	VOICEMAIL_TRANSCRIPTION_DISABLED = 0
11
12	def initialize(
13		jid: CONFIG[:sgx],
14		redis: LazyObject.new { REDIS },
15		ibr_repo: IBRRepo.new,
16		**kwargs
17	)
18		@jid = jid
19		@redis = redis
20		@ibr_repo = ibr_repo
21		@trivial_repo = TrivialBackendSgxRepo.new(jid: jid, **kwargs)
22	end
23
24	def get(customer_id)
25		sgx = @trivial_repo.get(customer_id)
26		fetch_raw(sgx.from_jid).then do |(((ogm_url, fwd_time, fwd), trans_d), reg)|
27			sgx.with(
28				ogm_url: ogm_url,
29				fwd: CustomerFwd.for(uri: fwd, timeout: fwd_time),
30				transcription_enabled: !trans_d,
31				registered?: reg
32			)
33		end
34	end
35
36	def put_transcription_enabled(customer_id, enabled)
37		sgx = @trivial_repo.get(customer_id)
38		REDIS.setbit(
39			"catapult_settings_flags-#{sgx.from_jid}",
40			Bwmsgsv2Repo::VOICEMAIL_TRANSCRIPTION_DISABLED,
41			enabled ? 0 : 1
42		)
43	end
44
45	def put_fwd(customer_id, tel, customer_fwd)
46		sgx = @trivial_repo.get(customer_id)
47		EMPromise.all([
48			set_or_delete("catapult_fwd-#{tel}", customer_fwd.uri),
49			set_or_delete(
50				"catapult_fwd_timeout-#{sgx.from_jid}",
51				customer_fwd.timeout.to_i
52			)
53		]).then do
54			set_default_location(tel) if customer_fwd.v2_safe?
55		end
56	end
57
58protected
59
60	def set_default_location(tel)
61		# Migrate location if needed
62		BandwidthIris::SipPeer.new(
63			site_id: CONFIG[:bandwidth_site],
64			id: CONFIG[:bandwidth_peer]
65		).move_tns([tel])
66	end
67
68	def set_or_delete(k, v)
69		if v.nil?
70			REDIS.del(k)
71		else
72			REDIS.set(k, v)
73		end
74	end
75
76	def fetch_raw(from_jid)
77		registration(from_jid).then do |r|
78			EMPromise.all([from_redis(from_jid, r ? r.phone : nil), r])
79		end
80	end
81
82	def registration(from_jid)
83		@ibr_repo.registered?(@jid, from: from_jid)
84	end
85
86	def from_redis(from_jid, tel)
87		EMPromise.all([
88			@redis.mget(*[
89				"catapult_ogm_url-#{from_jid}",
90				"catapult_fwd_timeout-#{from_jid}",
91				("catapult_fwd-#{tel}" if tel)
92			].compact),
93			@redis.getbit(
94				"catapult_settings_flags-#{from_jid}", VOICEMAIL_TRANSCRIPTION_DISABLED
95			).then { |x| x == 1 }
96		])
97	end
98end