~singpolyma/sgx-jmp

ref: bc13638e01b9d1c96b3d61028f01a8f9043af986 sgx-jmp/sgx_jmp.rb -rw-r--r-- 7.7 KiB
bc13638eStephen Paul Weber Store customer outbound messages/day for 1 year in redis 1 year, 6 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# frozen_string_literal: true

require "pg/em"
require "bigdecimal"
require "blather/client/dsl" # Require this first to not auto-include
require "blather/client"
require "braintree"
require "date"
require "dhall"
require "em-hiredis"
require "em_promise"
require "ruby-bandwidth-iris"

CONFIG =
	Dhall::Coder
	.new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
	.load(ARGV[0], transform_keys: ->(k) { k&.to_sym })

singleton_class.class_eval do
	include Blather::DSL
	Blather::DSL.append_features(self)
end

require_relative "lib/backend_sgx"
require_relative "lib/bandwidth_tn_order"
require_relative "lib/btc_sell_prices"
require_relative "lib/buy_account_credit_form"
require_relative "lib/customer"
require_relative "lib/electrum"
require_relative "lib/em"
require_relative "lib/payment_methods"
require_relative "lib/registration"
require_relative "lib/transaction"
require_relative "lib/web_register_manager"

ELECTRUM = Electrum.new(**CONFIG[:electrum])

Faraday.default_adapter = :em_synchrony
BandwidthIris::Client.global_options = {
	account_id: CONFIG[:creds][:account],
	username: CONFIG[:creds][:username],
	password: CONFIG[:creds][:password]
}

# Braintree is not async, so wrap in EM.defer for now
class AsyncBraintree
	def initialize(environment:, merchant_id:, public_key:, private_key:, **)
		@gateway = Braintree::Gateway.new(
			environment: environment,
			merchant_id: merchant_id,
			public_key: public_key,
			private_key: private_key
		)
	end

	def respond_to_missing?(m, *)
		@gateway.respond_to?(m)
	end

	def method_missing(m, *args)
		return super unless respond_to_missing?(m, *args)

		EM.promise_defer(klass: PromiseChain) do
			@gateway.public_send(m, *args)
		end
	end

	class PromiseChain < EMPromise
		def respond_to_missing?(*)
			false # We don't actually know what we respond to...
		end

		def method_missing(m, *args)
			return super if respond_to_missing?(m, *args)
			self.then { |o| o.public_send(m, *args) }
		end
	end
end

BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])

def panic(e)
	m = e.respond_to?(:message) ? e.message : e
	warn "Error raised during event loop: #{e.class}: #{m}"
	warn e.backtrace if e.respond_to?(:backtrace)
	exit 1
end

EM.error_handler(&method(:panic))

when_ready do
	BLATHER = self
	REDIS = EM::Hiredis.connect
	BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
	DB = PG::EM::Client.new(dbname: "jmp")
	DB.type_map_for_results = PG::BasicTypeMapForResults.new(DB)
	DB.type_map_for_queries = PG::BasicTypeMapForQueries.new(DB)

	EM.add_periodic_timer(3600) do
		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
		ping.from = CONFIG[:component][:jid]
		self << ping
	end
end

# workqueue_count MUST be 0 or else Blather uses threads!
setup(
	CONFIG[:component][:jid],
	CONFIG[:component][:secret],
	CONFIG[:server][:host],
	CONFIG[:server][:port],
	nil,
	nil,
	workqueue_count: 0
)

message to: /\Aaccount@/ do |m|
	self << m.reply.tap do |out|
		out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
	end
end

message to: /\Acustomer_/, from: /@#{CONFIG[:sgx]}(\/|\Z)/ do |m|
	Customer.for_customer_id(
		m.to.node.delete_prefix("customer_")
	).then { |customer| customer.stanza_to(m) }.catch(&method(:panic))
end

message do |m|
	Customer.for_jid(m.from.stripped).then { |customer|
		today = Time.now.utc.to_date
		EMPromise.all([
			REDIS.zremrangebylex(
				"jmp_customer_outbound_messages-#{customer.customer_id}",
				"-",
				# Store message counts per day for 1 year
				"[#{(today << 12).strftime('%Y%m%d')}"
			),
			REDIS.zincrby(
				"jmp_customer_outbound_messages-#{customer.customer_id}",
				1,
				today.strftime("%Y%m%d")
			),
			customer.stanza_from(m)
		])
	}.catch(&method(:panic))
end

message :error? do |m|
	puts "MESSAGE ERROR: #{m.inspect}"
end

class SessionManager
	def initialize(blather, id_msg, timeout: 5)
		@blather = blather
		@sessions = {}
		@id_msg = id_msg
		@timeout = timeout
	end

	def promise_for(stanza)
		id = "#{stanza.to.stripped}/#{stanza.public_send(@id_msg)}"
		@sessions.fetch(id) do
			@sessions[id] = EMPromise.new
			EM.add_timer(@timeout) do
				@sessions.delete(id)&.reject(:timeout)
			end
			@sessions[id]
		end
	end

	def write(stanza)
		promise = promise_for(stanza)
		@blather << stanza
		promise
	end

	def fulfill(stanza)
		id = "#{stanza.from.stripped}/#{stanza.public_send(@id_msg)}"
		if stanza.error?
			@sessions.delete(id)&.reject(stanza)
		else
			@sessions.delete(id)&.fulfill(stanza)
		end
	end
end

IQ_MANAGER = SessionManager.new(self, :id)
COMMAND_MANAGER = SessionManager.new(self, :sessionid, timeout: 60 * 60)
web_register_manager = WebRegisterManager.new

disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
	reply = iq.reply
	reply.identities = [{
		name: "JMP.chat",
		type: "sms",
		category: "gateway"
	}]
	form = Blather::Stanza::X.find_or_create(reply.query)
	form.type = "result"
	form.fields = [
		{
			var: "FORM_TYPE",
			type: "hidden",
			value: "http://jabber.org/network/serverinfo"
		}
	] + CONFIG[:xep0157]
	self << reply
end

disco_items node: "http://jabber.org/protocol/commands" do |iq|
	reply = iq.reply
	reply.items = [
		# TODO: don't show this item if no braintree methods available
		# TODO: don't show this item if no plan for this customer
		Blather::Stanza::DiscoItems::Item.new(
			iq.to,
			"buy-credit",
			"Buy account credit"
		),
		Blather::Stanza::DiscoItems::Item.new(
			iq.to,
			"jabber:iq:register",
			"Register"
		)
	]
	self << reply
end

command :execute?, node: "jabber:iq:register", sessionid: nil do |iq|
	Customer.for_jid(iq.from.stripped).catch {
		Customer.create(iq.from.stripped)
	}.then { |customer|
		Registration.for(
			iq,
			customer,
			web_register_manager
		).then(&:write)
	}.catch(&method(:panic))
end

def reply_with_note(iq, text, type: :info)
	reply = iq.reply
	reply.status = :completed
	reply.note_type = type
	reply.note_text = text

	self << reply
end

command :execute?, node: "buy-credit", sessionid: nil do |iq|
	reply = iq.reply
	reply.allowed_actions = [:complete]

	Customer.for_jid(iq.from.stripped).then { |customer|
		BuyAccountCreditForm.new(customer).add_to_form(reply.form).then { customer }
	}.then { |customer|
		EMPromise.all([
			customer,
			customer.payment_methods,
			COMMAND_MANAGER.write(reply)
		])
	}.then { |(customer, payment_methods, iq2)|
		iq = iq2 # This allows the catch to use it also
		payment_method = payment_methods.fetch(
			iq.form.field("payment_method")&.value.to_i
		)
		amount = iq.form.field("amount").value.to_s
		Transaction.sale(customer, amount, payment_method)
	}.then { |transaction|
		transaction.insert.then { transaction.amount }
	}.then { |amount|
		reply_with_note(iq, "$#{'%.2f' % amount} added to your account balance.")
	}.catch { |e|
		text = "Failed to buy credit, system said: #{e.message}"
		reply_with_note(iq, text, type: :error)
	}.catch(&method(:panic))
end

command :execute?, node: "web-register", sessionid: nil do |iq|
	jid = iq.form.field("jid")&.value.to_s.strip
	tel = iq.form.field("tel")&.value.to_s.strip
	if iq.from.stripped != CONFIG[:web_register][:from]
		BLATHER << iq.as_error("forbidden", :auth)
	elsif jid == "" || tel !~ /\A\+\d+\Z/
		reply_with_note(iq, "Invalid JID or telephone number.", type: :error)
	else
		IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
			cmd.to = CONFIG[:web_register][:to]
			cmd.from = CONFIG[:component][:jid]
			cmd.node = "push-register"
			cmd.form.fields = [var: "to", value: jid]
			cmd.form.type = "submit"
		}).then do |result|
			final_jid = result.form.field("from")&.value.to_s.strip
			web_register_manager[final_jid] = tel
			BLATHER << iq.reply.tap { |reply| reply.status = :completed }
		end
	end
end

command sessionid: /./ do |iq|
	COMMAND_MANAGER.fulfill(iq)
end

iq :result? do |iq|
	IQ_MANAGER.fulfill(iq)
end

iq :error? do |iq|
	IQ_MANAGER.fulfill(iq)
end