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