sgx_jmp.rb

  1# frozen_string_literal: true
  2
  3require "pg/em/connection_pool"
  4require "bandwidth"
  5require "bigdecimal"
  6require "blather/client/dsl"
  7require "braintree"
  8require "date"
  9require "dhall"
 10require "em-hiredis"
 11require "em_promise"
 12require "ougai"
 13require "ruby-bandwidth-iris"
 14require "sentry-ruby"
 15require "statsd-instrument"
 16
 17require_relative "lib/background_log"
 18
 19$stdout.sync = true
 20LOG = Ougai::Logger.new(BackgroundLog.new($stdout))
 21LOG.level = ENV.fetch("LOG_LEVEL", "info")
 22LOG.formatter = Ougai::Formatters::Readable.new(
 23	nil,
 24	nil,
 25	plain: !$stdout.isatty
 26)
 27Blather.logger = LOG
 28EM::Hiredis.logger = LOG
 29StatsD.logger = LOG
 30LOG.info "Starting"
 31
 32def log
 33	Thread.current[:log] || LOG
 34end
 35
 36Sentry.init do |config|
 37	config.logger = LOG
 38	config.breadcrumbs_logger = [:sentry_logger]
 39end
 40
 41CONFIG = Dhall::Coder
 42	.new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
 43	.load(
 44		"(#{ARGV[0]}) : #{__dir__}/config-schema.dhall",
 45		transform_keys: ->(k) { k&.to_sym }
 46	)
 47WEB_LISTEN =
 48	if CONFIG[:web].is_a?(Hash)
 49		[CONFIG[:web][:interface], CONFIG[:web][:port]]
 50	else
 51		[CONFIG[:web]]
 52	end
 53
 54singleton_class.class_eval do
 55	include Blather::DSL
 56	Blather::DSL.append_features(self)
 57end
 58
 59require_relative "lib/session_manager"
 60
 61IQ_MANAGER = SessionManager.new(self, :id)
 62COMMAND_MANAGER = SessionManager.new(
 63	self,
 64	:sessionid,
 65	timeout: 60 * 60,
 66	error_if: ->(s) { s.cancel? }
 67)
 68
 69require_relative "lib/polyfill"
 70require_relative "lib/alt_top_up_form"
 71require_relative "lib/admin_command"
 72require_relative "lib/backend_sgx"
 73require_relative "lib/bwmsgsv2_repo"
 74require_relative "lib/bandwidth_iris_patch"
 75require_relative "lib/bandwidth_tn_order"
 76require_relative "lib/bandwidth_tn_repo"
 77require_relative "lib/btc_sell_prices"
 78require_relative "lib/buy_account_credit_form"
 79require_relative "lib/configure_calls_form"
 80require_relative "lib/command"
 81require_relative "lib/command_list"
 82require_relative "lib/customer"
 83require_relative "lib/customer_info"
 84require_relative "lib/customer_info_form"
 85require_relative "lib/customer_repo"
 86require_relative "lib/dummy_command"
 87require_relative "lib/db_notification"
 88require_relative "lib/electrum"
 89require_relative "lib/empty_repo"
 90require_relative "lib/expiring_lock"
 91require_relative "lib/em"
 92require_relative "lib/form_to_h"
 93require_relative "lib/low_balance"
 94require_relative "lib/port_in_order"
 95require_relative "lib/patches_for_sentry"
 96require_relative "lib/payment_methods"
 97require_relative "lib/paypal_done"
 98require_relative "lib/postgres"
 99require_relative "lib/reachability_form"
100require_relative "lib/reachability_repo"
101require_relative "lib/registration"
102require_relative "lib/transaction"
103require_relative "lib/tel_selections"
104require_relative "lib/sim_repo"
105require_relative "lib/snikket"
106require_relative "web"
107require_relative "lib/statsd"
108
109ELECTRUM = Electrum.new(**CONFIG[:electrum])
110EM::Hiredis::Client.load_scripts_from("./redis_lua")
111
112Faraday.default_adapter = :em_synchrony
113BandwidthIris::Client.global_options = {
114	account_id: CONFIG[:creds][:account],
115	username: CONFIG[:creds][:username],
116	password: CONFIG[:creds][:password]
117}
118BANDWIDTH_VOICE = Bandwidth::Client.new(
119	voice_basic_auth_user_name: CONFIG[:creds][:username],
120	voice_basic_auth_password: CONFIG[:creds][:password]
121).voice_client.client
122
123class AuthError < StandardError; end
124
125# Braintree is not async, so wrap in EM.defer for now
126class AsyncBraintree
127	def initialize(environment:, merchant_id:, public_key:, private_key:, **)
128		@gateway = Braintree::Gateway.new(
129			environment: environment,
130			merchant_id: merchant_id,
131			public_key: public_key,
132			private_key: private_key
133		)
134		@gateway.config.logger = LOG
135	end
136
137	def respond_to_missing?(m, *)
138		@gateway.respond_to?(m) || super
139	end
140
141	def method_missing(m, *args)
142		return super unless respond_to_missing?(m, *args)
143
144		EM.promise_defer(klass: PromiseChain) do
145			@gateway.public_send(m, *args)
146		end
147	end
148
149	class PromiseChain < EMPromise
150		def respond_to_missing?(*)
151			false && super # We don't actually know what we respond to...
152		end
153
154		def method_missing(m, *args)
155			return super if respond_to_missing?(m, *args)
156
157			self.then { |o| o.public_send(m, *args) }
158		end
159	end
160end
161
162BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])
163
164def panic(e, hub=nil)
165	log.fatal(
166		"Error raised during event loop: #{e.class}",
167		e
168	)
169	if e.is_a?(::Exception)
170		(hub || Sentry).capture_exception(e, hint: { background: false })
171	else
172		(hub || Sentry).capture_message(e.to_s, hint: { background: false })
173	end
174	exit 1
175end
176
177EM.error_handler(&method(:panic))
178
179require_relative "lib/blather_client"
180@client = BlatherClient.new
181
182setup(
183	CONFIG[:component][:jid],
184	CONFIG[:component][:secret],
185	CONFIG[:server][:host],
186	CONFIG[:server][:port],
187	nil,
188	nil,
189	async: true
190)
191
192# Infer anything we might have been notified about while we were down
193def catchup_notify_low_balance(db)
194	db.query(<<~SQL).each do |c|
195		SELECT customer_id
196		FROM balances INNER JOIN customer_plans USING (customer_id)
197		WHERE balance < 5 AND expires_at > LOCALTIMESTAMP
198	SQL
199		db.query("SELECT pg_notify('low_balance', $1)", c.values)
200	end
201end
202
203def catchup_notify_possible_renewal(db)
204	db.query(<<~SQL).each do |c|
205		SELECT customer_id
206		FROM customer_plans INNER JOIN balances USING (customer_id)
207		WHERE
208			expires_at < LOCALTIMESTAMP
209			AND expires_at >= LOCALTIMESTAMP - INTERVAL '3 months'
210			AND balance >= 5
211	SQL
212		db.query("SELECT pg_notify('possible_renewal', $1)", c.values)
213	end
214end
215
216def poll_for_notify(db)
217	db.wait_for_notify_defer.then { |notify|
218		repo = CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
219		repo.find(notify[:extra]).then do |customer|
220			DbNotification.for(notify, customer, repo)
221		end
222	}.then(&:call).then {
223		EM.add_timer(0.5) { poll_for_notify(db) }
224	}.catch(&method(:panic))
225end
226
227def load_plans_to_db!
228	DB.transaction do
229		DB.exec("TRUNCATE plans")
230		CONFIG[:plans].each do |plan|
231			DB.exec("INSERT INTO plans VALUES ($1)", [plan.to_json])
232		end
233	end
234end
235
236when_ready do
237	log.info "Ready"
238	BLATHER = self
239	REDIS = EM::Hiredis.connect
240	TEL_SELECTIONS = TelSelections.new
241	BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
242	DB = Postgres.connect(dbname: "jmp")
243
244	DB.hold do |conn|
245		conn.query("LISTEN low_balance")
246		conn.query("LISTEN possible_renewal")
247		catchup_notify_low_balance(conn)
248		catchup_notify_possible_renewal(conn)
249		poll_for_notify(conn)
250	end
251
252	load_plans_to_db!
253
254	EM.add_periodic_timer(3600) do
255		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
256		ping.from = CONFIG[:component][:jid]
257		self << ping
258	end
259
260	Web.run(LOG.child, *WEB_LISTEN)
261end
262
263message to: /\Aaccount@/, body: /./ do |m|
264	StatsD.increment("deprecated_account_bot")
265
266	self << m.reply.tap { |out|
267		out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
268	}
269end
270
271before(
272	:iq,
273	type: [:error, :result],
274	to: /\Acustomer_/,
275	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
276) { |iq| halt if IQ_MANAGER.fulfill(iq) }
277
278before nil, to: /\Acustomer_/, from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/ do |s|
279	StatsD.increment("stanza_customer")
280
281	Sentry.get_current_scope.set_transaction_name("stanza_customer")
282	CustomerRepo.new(set_user: Sentry.method(:set_user)).find(
283		s.to.node.delete_prefix("customer_")
284	).then do |customer|
285		ReachabilityRepo::SMS.new
286			.find(customer, s.from.node, stanza: s).then do |reach|
287				reach.filter do
288					customer.stanza_to(s)
289				end
290			end
291	end
292
293	halt
294end
295
296ADDRESSES_NS = "http://jabber.org/protocol/address"
297message(
298	to: /\A#{CONFIG[:component][:jid]}\Z/,
299	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
300) do |m|
301	StatsD.increment("inbound_group_text")
302	Sentry.get_current_scope.set_transaction_name("inbound_group_text")
303
304	address = m.find("ns:addresses", ns: ADDRESSES_NS).first
305		&.find("ns:address", ns: ADDRESSES_NS)
306		&.find { |el| el["jid"].to_s.start_with?("customer_") }
307	pass unless address
308
309	CustomerRepo
310		.new(set_user: Sentry.method(:set_user))
311		.find_by_jid(address["jid"]).then { |customer|
312			m.from = m.from.with(domain: CONFIG[:component][:jid])
313			m.to = m.to.with(domain: customer.jid.domain)
314			address["jid"] = customer.jid.to_s
315			BLATHER << m
316		}.catch_only(CustomerRepo::NotFound) { |e|
317			BLATHER << m.as_error("forbidden", :auth, e.message)
318		}
319end
320
321# Ignore groupchat messages
322# Especially if we have the component join MUC for notifications
323message(type: :groupchat) { true }
324
325def billable_message(m)
326	b = m.body
327	b && !b.empty? || m.find("ns:x", ns: OOB.registered_ns).first
328end
329
330class OverLimit < StandardError
331	def initialize(customer, usage)
332		super("Please contact support")
333		@customer = customer
334		@usage = usage
335	end
336
337	def notify_admin
338		ExpiringLock.new("jmp_usage_notify-#{@customer.customer_id}").with do
339			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
340			BLATHER.say(
341				CONFIG[:notify_admin], "#{@customer.customer_id} has used " \
342				"#{@usage} messages today", :groupchat
343			)
344		end
345	end
346end
347
348class CustomerExpired < StandardError; end
349
350CONFIG[:direct_targets].each do |(tel, jid)|
351	customer_repo = CustomerRepo.new(
352		sgx_repo: TrivialBackendSgxRepo.new(jid: jid),
353		set_user: Sentry.method(:set_user)
354	)
355
356	message to: /\A#{Regexp.escape(tel)}@#{CONFIG[:component][:jid]}\/?/ do |m|
357		customer_repo.find_by_jid(m.from.stripped).then { |customer|
358			customer.stanza_from(m)
359		}.catch_only(CustomerRepo::NotFound) {
360			# This should not happen, but let's still get the message
361			# to support at least if it does
362			m.from = ProxiedJID.proxy(m.from, CONFIG[:component][:jid])
363			m.to = jid
364			BLATHER << m
365		}
366	end
367
368	message to: /\Acustomer_/, from: /\A#{Regexp.escape(jid)}\/?/ do |m|
369		customer_repo.find(m.to.node.delete_prefix("customer_")).then { |customer|
370			m.from = "#{tel}@sgx-jmp" # stanza_to will fix domain
371			customer.stanza_to(m)
372		}.catch_only(CustomerRepo::NotFound) { |e|
373			BLATHER << m.as_error("item-not-found", :cancel, e.message)
374		}
375	end
376end
377
378message do |m|
379	StatsD.increment("message")
380
381	today = Time.now.utc.to_date
382	CustomerRepo.new(set_user: Sentry.method(:set_user))
383		.find_by_jid(m.from.stripped).then { |customer|
384			next customer.stanza_from(m) unless billable_message(m)
385
386			if customer.plan_name && !customer.active?
387				raise CustomerExpired, "Your account is expired, please top up"
388			end
389
390			EMPromise.all([
391				TrustLevelRepo.new.find(customer),
392				customer.message_usage((today..today))
393			]).then { |(tl, usage)|
394				raise OverLimit.new(customer, usage) unless tl.send_message?(usage)
395			}.then do
396				EMPromise.all([
397					customer.incr_message_usage, customer.stanza_from(m)
398				])
399			end
400		}.catch_only(OverLimit) { |e|
401			e.notify_admin
402			BLATHER << m.as_error("policy-violation", :wait, e.message)
403		}.catch_only(CustomerRepo::NotFound, CustomerExpired) { |e|
404			BLATHER << m.as_error("forbidden", :auth, e.message)
405		}
406end
407
408disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
409	reply = iq.reply
410	reply.identities = [{
411		name: "JMP.chat",
412		type: "sms",
413		category: "gateway"
414	}]
415	reply.features = [
416		"http://jabber.org/protocol/disco#info",
417		"http://jabber.org/protocol/commands"
418	]
419	form = Blather::Stanza::X.find_or_create(reply.query)
420	form.type = "result"
421	form.fields = [
422		{
423			var: "FORM_TYPE",
424			type: "hidden",
425			value: "http://jabber.org/network/serverinfo"
426		}
427	] + CONFIG[:xep0157]
428	self << reply
429end
430
431disco_info do |iq|
432	reply = iq.reply
433	reply.identities = [{
434		name: "JMP.chat",
435		type: "sms",
436		category: "client"
437	}]
438	reply.features = [
439		"urn:xmpp:receipts"
440	]
441	self << reply
442end
443
444disco_items(
445	to: Blather::JID.new(CONFIG[:component][:jid]),
446	node: "http://jabber.org/protocol/commands"
447) do |iq|
448	StatsD.increment("command_list")
449
450	reply = iq.reply
451	reply.node = "http://jabber.org/protocol/commands"
452
453	CustomerRepo.new(
454		sgx_repo: Bwmsgsv2Repo.new,
455		set_user: Sentry.method(:set_user)
456	).find_by_jid(
457		iq.from.stripped
458	).catch {
459		nil
460	}.then { |customer|
461		CommandList.for(customer, iq.from)
462	}.then { |list|
463		reply.items = list.map { |item|
464			Blather::Stanza::DiscoItems::Item.new(
465				iq.to,
466				item[:node],
467				item[:name]
468			)
469		}
470		self << reply
471	}
472end
473
474iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
475	StatsD.increment("extdisco")
476
477	reply = iq.reply
478	reply << Nokogiri::XML::Builder.new {
479		services(xmlns: "urn:xmpp:extdisco:2") do
480			service(
481				type: "sip",
482				host: CONFIG[:sip_host]
483			)
484		end
485	}.doc.root
486
487	self << reply
488end
489
490Command.new(
491	"jabber:iq:register",
492	"Register",
493	list_for: ->(*) { true },
494	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
495) {
496	Command.customer.catch_only(CustomerRepo::NotFound) {
497		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
498		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
499	}.then { |customer|
500		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
501		Registration.for(customer, TEL_SELECTIONS).then(&:write)
502	}.then {
503		StatsD.increment("registration.completed")
504	}.catch_only(Command::Execution::FinalStanza) do |e|
505		StatsD.increment("registration.completed")
506		EMPromise.reject(e)
507	end
508}.register(self).then(&CommandList.method(:register))
509
510Command.new(
511	"info",
512	"👤 Show Account Info",
513	list_for: ->(*) { true },
514	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
515) {
516	Command.customer.then(&CustomerInfo.method(:for)).then do |info|
517		Command.finish do |reply|
518			reply.command << info.form
519		end
520	end
521}.register(self).then(&CommandList.method(:register))
522
523Command.new(
524	"usage",
525	"📊 Show Monthly Usage"
526) {
527	report_for = (Date.today..(Date.today << 1))
528
529	Command.customer.then { |customer|
530		customer.usage_report(report_for)
531	}.then do |usage_report|
532		Command.finish do |reply|
533			reply.command << usage_report.form
534		end
535	end
536}.register(self).then(&CommandList.method(:register))
537
538Command.new(
539	"cdrs",
540	"📲 Show Call Logs",
541	list_for: ->(feature_flags:, **) { feature_flags.include?(:cdrs) }
542) {
543	report_for = ((Date.today << 1)..Date.today)
544
545	Command.customer.then { |customer|
546		CDRRepo.new.find_range(customer, report_for)
547	}.then do |cdrs|
548		Command.finish do |reply|
549			reply.command << FormTemplate.render("customer_cdr", cdrs: cdrs)
550		end
551	end
552}.register(self).then(&CommandList.method(:register))
553
554Command.new(
555	"transactions",
556	"🧾 Show Transactions",
557	list_for: ->(customer:, **) { !!customer&.currency }
558) {
559	Command.customer.then(&:transactions).then do |txs|
560		Command.finish do |reply|
561			reply.command << FormTemplate.render("transactions", transactions: txs)
562		end
563	end
564}.register(self).then(&CommandList.method(:register))
565
566Command.new(
567	"configure calls",
568	"📞 Configure Calls",
569	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
570) {
571	Command.customer.then do |customer|
572		cc_form = ConfigureCallsForm.new(customer)
573		Command.reply { |reply|
574			reply.allowed_actions = [:next]
575			reply.command << cc_form.render
576		}.then { |iq|
577			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
578				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
579			})
580		}.then { Command.finish("Configuration saved!") }
581	end
582}.register(self).then(&CommandList.method(:register))
583
584Command.new(
585	"ogm",
586	"⏺️ Record Voicemail Greeting",
587	list_for: ->(fwd: nil, **) { fwd&.voicemail_enabled? },
588	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
589) {
590	Command.customer.then do |customer|
591		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
592			cc.from = customer.registered?.phone
593			cc.application_id = CONFIG[:sip][:app]
594			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
595			                "customer_id=#{customer.customer_id}"
596		end
597		Command.finish("You will now receive a call.")
598	end
599}.register(self).then(&CommandList.method(:register))
600
601Command.new(
602	"migrate billing",
603	"🏦 Switch to new billing",
604	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
605	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
606) {
607	EMPromise.all([
608		Command.customer,
609		Command.reply do |reply|
610			reply.allowed_actions = [:next]
611			reply.command << FormTemplate.render("migrate_billing")
612		end
613	]).then do |(customer, iq)|
614		Registration::Payment.for(
615			iq, customer, customer.registered?.phone,
616			final_message: PaypalDone::MESSAGE,
617			finish: PaypalDone
618		).then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
619			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
620			BLATHER.say(
621				CONFIG[:notify_admin],
622				"#{customer.customer_id} migrated to #{customer.currency}",
623				:groupchat
624			)
625			EMPromise.reject(s)
626		end
627	end
628}.register(self).then(&CommandList.method(:register))
629
630Command.new(
631	"credit cards",
632	"💳 Credit Card Settings and Management"
633) {
634	Command.customer.then do |customer|
635		url = CONFIG[:credit_card_url].call(
636			customer.jid.to_s.gsub("\\", "%5C"),
637			customer.customer_id
638		)
639		desc = "Manage credits cards and settings"
640		Command.finish("#{desc}: #{url}") do |reply|
641			oob = OOB.find_or_create(reply.command)
642			oob.url = url
643			oob.desc = desc
644		end
645	end
646}.register(self).then(&CommandList.method(:register))
647
648Command.new(
649	"top up",
650	"💲 Buy Account Credit by Credit Card",
651	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
652	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
653) {
654	Command.customer.then { |customer|
655		BuyAccountCreditForm.for(customer).then do |credit_form|
656			Command.reply { |reply|
657				reply.allowed_actions = [:complete]
658				credit_form.add_to_form(reply.form)
659			}.then do |iq|
660				CreditCardSale.create(customer, **credit_form.parse(iq.form))
661			end
662		end
663	}.then { |transaction|
664		Command.finish("#{transaction} added to your account balance.")
665	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
666		Command.finish(e.message, type: :error)
667	end
668}.register(self).then(&CommandList.method(:register))
669
670Command.new(
671	"alt top up",
672	"🪙 Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
673	list_for: ->(customer:, **) { !!customer&.currency }
674) {
675	Command.customer.then { |customer|
676		AltTopUpForm.for(customer)
677	}.then do |alt_form|
678		Command.reply { |reply|
679			reply.allowed_actions = [:complete]
680			reply.command << alt_form.form
681		}.then do |iq|
682			Command.finish { |reply| alt_form.parse(iq.form).action(reply) }
683		end
684	end
685}.register(self).then(&CommandList.method(:register))
686
687Command.new(
688	"plan settings",
689	"📝 Manage your plan, including overage limits",
690	list_for: ->(customer:, **) { !!customer&.currency }
691) {
692	Command.customer.then do |customer|
693		Command.reply { |reply|
694			reply.allowed_actions = [:next]
695			reply.command << FormTemplate.render("plan_settings", customer: customer)
696		}.then { |iq|
697			Command.execution.customer_repo.put_monthly_overage_limit(
698				customer,
699				iq.form.field("monthly_overage_limit")&.value.to_i
700			)
701		}.then { Command.finish("Configuration saved!") }
702	end
703}.register(self).then(&CommandList.method(:register))
704
705Command.new(
706	"referral codes",
707	"👥 Refer a friend for free credit"
708) {
709	Command.customer.then(&:unused_invites).then do |invites|
710		if invites.empty?
711			Command.finish(
712				"You have no more referral codes right now, " \
713				"try again later."
714			)
715		else
716			Command.finish do |reply|
717				reply.form.type = :result
718				reply.form.title = "Unused Referral Codes"
719				reply.form.instructions =
720					"Each of these codes is single use and gives the person using " \
721					"them a free month of JMP service. You will receive credit " \
722					"equivalent to one month of free service if they later become " \
723					"a paying customer."
724				FormTable.new(
725					invites.map { |i| [i] },
726					code: "Invite Code"
727				).add_to_form(reply.form)
728			end
729		end
730	end
731}.register(self).then(&CommandList.method(:register))
732
733Command.new(
734	"sims",
735	"📶 (e)SIM Details",
736	list_for: ->(customer:, **) { CONFIG[:keepgo] && !!customer&.currency }
737) {
738	Command.customer.then(&SIMRepo.new.method(:owned_by)).then do |sims|
739		if sims.empty?
740			next Command.finish(
741				"You have no (e)SIMs, you can get on the waitlist at https://jmp.chat/sim"
742			)
743		end
744
745		Command.finish do |reply|
746			reply.command << FormTemplate.render(
747				"sim_details",
748				sims: sims
749			)
750		end
751	end
752}.register(self).then(&CommandList.method(:register))
753
754Command.new(
755	"reset sip account",
756	"☎️ Create or Reset SIP Account",
757	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
758) {
759	Command.customer.then do |customer|
760		sip_account = customer.reset_sip_account
761		Command.reply { |reply|
762			reply.allowed_actions = [:next]
763			form = sip_account.form
764			form.type = :form
765			form.fields += [{
766				type: :boolean, var: "change_fwd",
767				label: "Should inbound calls forward to this SIP account?"
768			}]
769			reply.command << form
770		}.then do |fwd|
771			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
772				Command.execution.customer_repo.put_fwd(
773					customer,
774					customer.fwd.with(uri: sip_account.uri)
775				).then { Command.finish("Inbound calls will now forward to SIP.") }
776			else
777				Command.finish
778			end
779		end
780	end
781}.register(self).then(&CommandList.method(:register))
782
783Command.new(
784	"lnp",
785	"#️⃣ Port in your number from another carrier",
786	list_for: ->(**) { true }
787) {
788	EMPromise.all([
789		Command.customer,
790		Command.reply do |reply|
791			reply.allowed_actions = [:next]
792			reply.command << FormTemplate.render("lnp")
793		end
794	]).then { |(customer, iq)|
795		PortInOrder.parse(customer, iq.form).complete_with do |form|
796			Command.reply { |reply|
797				reply.allowed_actions = [:next]
798				reply.command << form
799			}.then(&:form)
800		end
801	}.then do |order|
802		order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
803		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
804		BLATHER.say(CONFIG[:notify_admin], order.message(order_id), :groupchat)
805		Command.finish(
806			"Your port-in request has been accepted, " \
807			"support will contact you with next steps"
808		)
809	end
810}.register(self).then(&CommandList.method(:register))
811
812Command.new(
813	"customer info",
814	"Show Customer Info",
815	list_for: ->(customer: nil, **) { customer&.admin? }
816) {
817	Command.customer.then do |customer|
818		raise AuthError, "You are not an admin" unless customer&.admin?
819
820		customer_repo = CustomerRepo.new(
821			sgx_repo: Bwmsgsv2Repo.new,
822			bandwidth_tn_repo: EmptyRepo.new(BandwidthTnRepo.new) # No CNAM in admin
823		)
824
825		AdminCommand::NoUser.new(customer_repo).start
826	end
827}.register(self).then(&CommandList.method(:register))
828
829Command.new(
830	"reachability",
831	"Test Reachability",
832	list_for: ->(customer: nil, **) { customer&.admin? }
833) {
834	Command.customer.then do |customer|
835		raise AuthError, "You are not an admin" unless customer&.admin?
836
837		form = ReachabilityForm.new(CustomerRepo.new)
838
839		Command.reply { |reply|
840			reply.allowed_actions = [:next]
841			reply.command << form.render
842		}.then { |response|
843			form.parse(response.form)
844		}.then { |result|
845			result.repo.get_or_create(result.target).then { |v|
846				result.target.stanza_from(result.prompt) if result.prompt
847
848				Command.finish { |reply|
849					reply.command << form.render_result(v)
850				}
851			}
852		}.catch_only(RuntimeError) { |e|
853			Command.finish(e, type: :error)
854		}
855	end
856}.register(self).then(&CommandList.method(:register))
857
858Command.new(
859	"snikket",
860	"Launch Snikket Instance",
861	list_for: ->(customer: nil, **) { customer&.admin? }
862) {
863	Command.customer.then do |customer|
864		raise AuthError, "You are not an admin" unless customer&.admin?
865
866		Command.reply { |reply|
867			reply.allowed_actions = [:next]
868			reply.command << FormTemplate.render("snikket_launch")
869		}.then { |response|
870			domain = response.form.field("domain").value.to_s
871			IQ_MANAGER.write(Snikket::Launch.new(
872				nil, CONFIG[:snikket_hosting_api],
873				domain: domain
874			)).then do |launched|
875				[domain, launched]
876			end
877		}.then { |(domain, launched)|
878			Command.finish do |reply|
879				reply.command << FormTemplate.render(
880					"snikket_launched",
881					launched: launched,
882					domain: domain
883				)
884			end
885		}
886	end
887}.register(self).then(&CommandList.method(:register))
888
889def reply_with_note(iq, text, type: :info)
890	reply = iq.reply
891	reply.status = :completed
892	reply.note_type = type
893	reply.note_text = text
894
895	self << reply
896end
897
898Command.new(
899	"https://ns.cheogram.com/sgx/jid-switch",
900	"Change JID",
901	list_for: ->(customer: nil, **) { customer },
902	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
903) {
904	Command.customer.then { |customer|
905		Command.reply { |reply|
906			reply.command << FormTemplate.render("jid_switch")
907		}.then { |response|
908			new_jid = response.form.field("jid").value
909			repo = Command.execution.customer_repo
910			repo.find_by_jid(new_jid)
911				.catch_only(CustomerRepo::NotFound) { nil }
912				.then { |cust|
913					next EMPromise.reject("Customer Already Exists") if cust
914
915					repo.change_jid(customer, new_jid)
916				}
917		}.then {
918			StatsD.increment("changejid.completed")
919			Command.finish { |reply|
920				reply.note_type = :info
921				reply.note_text = "Customer JID Changed"
922			}
923		}
924	}
925}.register(self).then(&CommandList.method(:register))
926
927Command.new(
928	"web-register",
929	"Initiate Register from Web",
930	list_for: lambda { |from_jid: nil, **|
931		from_jid&.stripped.to_s == CONFIG[:web_register][:from]
932	}
933) {
934	if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
935		next EMPromise.reject(
936			Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
937		)
938	end
939
940	Command.reply { |reply|
941		reply.command << FormTemplate.render("web_register")
942	}.then do |iq|
943		jid = iq.form.field("jid")&.value.to_s.strip
944		tel = iq.form.field("tel")&.value.to_s.strip
945		if jid !~ /\./ || jid =~ /\s/
946			Command.finish("The Jabber ID you entered was not valid.", type: :error)
947		elsif tel !~ /\A\+\d+\Z/
948			Command.finish("Invalid telephone number", type: :error)
949		else
950			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
951				cmd.to = CONFIG[:web_register][:to]
952				cmd.node = "push-register"
953				cmd.form.fields = [{ var: "to", value: jid }]
954				cmd.form.type = "submit"
955			}).then { |result|
956				TEL_SELECTIONS.set(result.form.field("from")&.value.to_s.strip, tel)
957			}.then { Command.finish }
958		end
959	end
960}.register(self).then(&CommandList.method(:register))
961
962command sessionid: /./ do |iq|
963	COMMAND_MANAGER.fulfill(iq)
964	IQ_MANAGER.fulfill(iq)
965	true
966end
967
968iq type: [:result, :error] do |iq|
969	IQ_MANAGER.fulfill(iq)
970	true
971end
972
973iq type: [:get, :set] do |iq|
974	StatsD.increment("unknown_iq")
975
976	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
977end
978
979trap(:INT) { EM.stop }
980trap(:TERM) { EM.stop }
981EM.run { client.run }