~singpolyma/sgx-jmp

ref: 51a219e284d955657782967b2bbe3b979ff40edd sgx-jmp/lib/bwmsgsv2_repo.rb -rw-r--r-- 2.2 KiB
51a219e2Stephen Paul Weber v1 is gone 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
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
100
101
# frozen_string_literal: true

require "lazy_object"

require_relative "customer_fwd"
require_relative "ibr"
require_relative "trivial_backend_sgx_repo"

class Bwmsgsv2Repo
	VOICEMAIL_TRANSCRIPTION_DISABLED = 0

	def initialize(jid: CONFIG[:sgx], redis: LazyObject.new { REDIS }, **kwargs)
		@jid = jid
		@redis = redis
		@trivial_repo = TrivialBackendSgxRepo.new(jid: jid, **kwargs)
	end

	def get(customer_id)
		sgx = @trivial_repo.get(customer_id)
		fetch_raw(sgx.from_jid).then do |(((ogm_url, fwd_time, fwd), trans_d), reg)|
			sgx.with(
				ogm_url: ogm_url,
				fwd: CustomerFwd.for(uri: fwd, timeout: fwd_time),
				transcription_enabled: !trans_d,
				registered?: reg
			)
		end
	end

	def put_transcription_enabled(customer_id, enabled)
		sgx = @trivial_repo.get(customer_id)
		REDIS.setbit(
			"catapult_settings_flags-#{sgx.from_jid}",
			Bwmsgsv2Repo::VOICEMAIL_TRANSCRIPTION_DISABLED,
			enabled ? 0 : 1
		)
	end

	def put_fwd(customer_id, tel, customer_fwd)
		sgx = @trivial_repo.get(customer_id)
		EMPromise.all([
			set_or_delete("catapult_fwd-#{tel}", customer_fwd.uri),
			set_or_delete(
				"catapult_fwd_timeout-#{sgx.from_jid}",
				customer_fwd.timeout.to_i
			)
		]).then do
			set_default_location(tel) if customer_fwd.v2_safe?
		end
	end

protected

	def set_default_location(tel)
		# Migrate location if needed
		BandwidthIris::SipPeer.new(
			site_id: CONFIG[:bandwidth_site],
			id: CONFIG[:bandwidth_peer]
		).move_tns([tel])
	end

	def set_or_delete(k, v)
		if v.nil?
			REDIS.del(k)
		else
			REDIS.set(k, v)
		end
	end

	def fetch_raw(from_jid)
		registration(from_jid).then do |r|
			EMPromise.all([from_redis(from_jid, r ? r.phone : nil), r])
		end
	end

	def registration(from_jid)
		ibr = IBR.new(:get, @jid)
		ibr.from = from_jid

		IQ_MANAGER.write(ibr).catch { nil }.then do |result|
			if result.respond_to?(:registered?) && result.registered?
				result
			else
				false
			end
		end
	end

	def from_redis(from_jid, tel)
		EMPromise.all([
			@redis.mget(*[
				"catapult_ogm_url-#{from_jid}",
				"catapult_fwd_timeout-#{from_jid}",
				("catapult_fwd-#{tel}" if tel)
			].compact),
			@redis.getbit(
				"catapult_setting_flags-#{from_jid}", VOICEMAIL_TRANSCRIPTION_DISABLED
			).then { |x| x == 1 }
		])
	end
end