~singpolyma/sgx-jmp

sgx-jmp/lib/bwmsgsv2_repo.rb -rw-r--r-- 2.1 KiB
94298f5dStephen Paul Weber Refactor alt top up to use FormTemplate 2 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
# frozen_string_literal: true

require "lazy_object"

require_relative "customer_fwd"
require_relative "ibr_repo"
require_relative "trivial_backend_sgx_repo"

class Bwmsgsv2Repo
	VOICEMAIL_TRANSCRIPTION_DISABLED = 0

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

	def get(customer_id, tel: nil)
		sgx = @trivial_repo.get(customer_id, tel: tel)
		fetch_raw(sgx).then do |(((ogm_url, fwd_time, fwd), flags), reg)|
			sgx.with(
				ogm_url: ogm_url,
				fwd: CustomerFwd.for(uri: fwd, timeout: fwd_time),
				transcription_enabled: !flags[VOICEMAIL_TRANSCRIPTION_DISABLED],
				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
			)
		])
	end

protected

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

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

	def registration(sgx)
		EMPromise.resolve(sgx.registered?)
	rescue NotLoaded::NotLoadedError
		@ibr_repo.registered?(@jid, from: sgx.from_jid)
	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),
			unpack_flags(from_jid)
		])
	end

	def unpack_flags(from_jid)
		@redis.bitfield(
			"catapult_settings_flags-#{from_jid}",
			"GET", "u1", VOICEMAIL_TRANSCRIPTION_DISABLED
		).then { |arr| arr.map { |x| x.to_i == 1 } }
	end
end