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