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