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