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
313UNBILLED_TARGETS = Set.new(CONFIG[:unbilled_targets])
314def billable_message(m)
315	b = m.body
316	!UNBILLED_TARGETS.member?(m.to.node) && \
317		(b && !b.empty? || m.find("ns:x", ns: OOB.registered_ns).first)
318end
319
320class OverLimit < StandardError
321	def initialize(customer, usage)
322		super("Please contact support")
323		@customer = customer
324		@usage = usage
325	end
326
327	def notify_admin
328		ExpiringLock.new("jmp_usage_notify-#{@customer.customer_id}").with do
329			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
330			BLATHER.say(
331				CONFIG[:notify_admin], "#{@customer.customer_id} has used " \
332				"#{@usage} messages today", :groupchat
333			)
334		end
335	end
336end
337
338class CustomerExpired < StandardError; end
339
340message do |m|
341	StatsD.increment("message")
342
343	today = Time.now.utc.to_date
344	CustomerRepo.new(set_user: Sentry.method(:set_user))
345		.find_by_jid(m.from.stripped).then { |customer|
346			next customer.stanza_from(m) unless billable_message(m)
347
348			if customer.plan_name && !customer.active?
349				raise CustomerExpired, "Your account is expired, please top up"
350			end
351
352			EMPromise.all([
353				TrustLevelRepo.new.find(customer),
354				customer.message_usage((today..today))
355			]).then { |(tl, usage)|
356				raise OverLimit.new(customer, usage) unless tl.send_message?(usage)
357			}.then do
358				EMPromise.all([
359					customer.incr_message_usage, customer.stanza_from(m)
360				])
361			end
362		}.catch_only(OverLimit) { |e|
363			e.notify_admin
364			BLATHER << m.as_error("policy-violation", :wait, e.message)
365		}.catch_only(CustomerRepo::NotFound, CustomerExpired) { |e|
366			BLATHER << m.as_error("forbidden", :auth, e.message)
367		}
368end
369
370disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
371	reply = iq.reply
372	reply.identities = [{
373		name: "JMP.chat",
374		type: "sms",
375		category: "gateway"
376	}]
377	reply.features = [
378		"http://jabber.org/protocol/disco#info",
379		"http://jabber.org/protocol/commands"
380	]
381	form = Blather::Stanza::X.find_or_create(reply.query)
382	form.type = "result"
383	form.fields = [
384		{
385			var: "FORM_TYPE",
386			type: "hidden",
387			value: "http://jabber.org/network/serverinfo"
388		}
389	] + CONFIG[:xep0157]
390	self << reply
391end
392
393disco_info do |iq|
394	reply = iq.reply
395	reply.identities = [{
396		name: "JMP.chat",
397		type: "sms",
398		category: "client"
399	}]
400	reply.features = [
401		"urn:xmpp:receipts"
402	]
403	self << reply
404end
405
406disco_items node: "http://jabber.org/protocol/commands" do |iq|
407	StatsD.increment("command_list")
408
409	reply = iq.reply
410	reply.node = "http://jabber.org/protocol/commands"
411
412	CustomerRepo.new(
413		sgx_repo: Bwmsgsv2Repo.new,
414		set_user: Sentry.method(:set_user)
415	).find_by_jid(
416		iq.from.stripped
417	).catch {
418		nil
419	}.then { |customer|
420		CommandList.for(customer, iq.from)
421	}.then { |list|
422		reply.items = list.map { |item|
423			Blather::Stanza::DiscoItems::Item.new(
424				iq.to,
425				item[:node],
426				item[:name]
427			)
428		}
429		self << reply
430	}
431end
432
433iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
434	StatsD.increment("extdisco")
435
436	reply = iq.reply
437	reply << Nokogiri::XML::Builder.new {
438		services(xmlns: "urn:xmpp:extdisco:2") do
439			service(
440				type: "sip",
441				host: CONFIG[:sip_host]
442			)
443		end
444	}.doc.root
445
446	self << reply
447end
448
449Command.new(
450	"jabber:iq:register",
451	"Register",
452	list_for: ->(*) { true },
453	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
454) {
455	Command.customer.catch_only(CustomerRepo::NotFound) {
456		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
457		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
458	}.then { |customer|
459		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
460		Registration.for(customer, TEL_SELECTIONS).then(&:write)
461	}.then {
462		StatsD.increment("registration.completed")
463	}.catch_only(Command::Execution::FinalStanza) do |e|
464		StatsD.increment("registration.completed")
465		EMPromise.reject(e)
466	end
467}.register(self).then(&CommandList.method(:register))
468
469Command.new(
470	"info",
471	"Show Account Info",
472	list_for: ->(*) { true },
473	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
474) {
475	Command.customer.then(&CustomerInfo.method(:for)).then do |info|
476		Command.finish do |reply|
477			reply.command << info.form
478		end
479	end
480}.register(self).then(&CommandList.method(:register))
481
482Command.new(
483	"usage",
484	"Show Monthly Usage"
485) {
486	report_for = (Date.today..(Date.today << 1))
487
488	Command.customer.then { |customer|
489		customer.usage_report(report_for)
490	}.then do |usage_report|
491		Command.finish do |reply|
492			reply.command << usage_report.form
493		end
494	end
495}.register(self).then(&CommandList.method(:register))
496
497Command.new(
498	"transactions",
499	"Show Transactions",
500	list_for: ->(customer:, **) { !!customer&.currency }
501) {
502	Command.customer.then(&:transactions).then do |txs|
503		Command.finish do |reply|
504			reply.command << FormTemplate.render("transactions", transactions: txs)
505		end
506	end
507}.register(self).then(&CommandList.method(:register))
508
509Command.new(
510	"configure calls",
511	"Configure Calls",
512	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
513) {
514	Command.customer.then do |customer|
515		cc_form = ConfigureCallsForm.new(customer)
516		Command.reply { |reply|
517			reply.allowed_actions = [:next]
518			reply.command << cc_form.render
519		}.then { |iq|
520			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
521				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
522			})
523		}.then { Command.finish("Configuration saved!") }
524	end
525}.register(self).then(&CommandList.method(:register))
526
527Command.new(
528	"ogm",
529	"Record Voicemail Greeting",
530	list_for: ->(fwd: nil, **) { fwd&.voicemail_enabled? },
531	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
532) {
533	Command.customer.then do |customer|
534		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
535			cc.from = customer.registered?.phone
536			cc.application_id = CONFIG[:sip][:app]
537			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
538			                "customer_id=#{customer.customer_id}"
539		end
540		Command.finish("You will now receive a call.")
541	end
542}.register(self).then(&CommandList.method(:register))
543
544Command.new(
545	"migrate billing",
546	"Switch from PayPal or expired trial to new billing",
547	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
548	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
549) {
550	EMPromise.all([
551		Command.customer,
552		Command.reply do |reply|
553			reply.allowed_actions = [:next]
554			reply.command << FormTemplate.render("migrate_billing")
555		end
556	]).then do |(customer, iq)|
557		Registration::Payment.for(
558			iq, customer, customer.registered?.phone,
559			final_message: PaypalDone::MESSAGE,
560			finish: PaypalDone
561		).then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
562			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
563			BLATHER.say(
564				CONFIG[:notify_admin],
565				"#{customer.customer_id} migrated to #{customer.currency}",
566				:groupchat
567			)
568			EMPromise.reject(s)
569		end
570	end
571}.register(self).then(&CommandList.method(:register))
572
573Command.new(
574	"credit cards",
575	"Credit Card Settings and Management"
576) {
577	Command.customer.then do |customer|
578		url = CONFIG[:credit_card_url].call(
579			customer.jid.to_s.gsub("\\", "%5C"),
580			customer.customer_id
581		)
582		desc = "Manage credits cards and settings"
583		Command.finish("#{desc}: #{url}") do |reply|
584			oob = OOB.find_or_create(reply.command)
585			oob.url = url
586			oob.desc = desc
587		end
588	end
589}.register(self).then(&CommandList.method(:register))
590
591Command.new(
592	"top up",
593	"Buy Account Credit by Credit Card",
594	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
595	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
596) {
597	Command.customer.then { |customer|
598		BuyAccountCreditForm.for(customer).then do |credit_form|
599			Command.reply { |reply|
600				reply.allowed_actions = [:complete]
601				credit_form.add_to_form(reply.form)
602			}.then do |iq|
603				Transaction.sale(customer, **credit_form.parse(iq.form))
604			end
605		end
606	}.then { |transaction|
607		transaction.insert.then do
608			Command.finish("#{transaction} added to your account balance.")
609		end
610	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
611		Command.finish(e.message, type: :error)
612	end
613}.register(self).then(&CommandList.method(:register))
614
615Command.new(
616	"alt top up",
617	"Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
618	list_for: ->(customer:, **) { !!customer&.currency }
619) {
620	Command.customer.then { |customer|
621		AltTopUpForm.for(customer)
622	}.then do |alt_form|
623		Command.reply { |reply|
624			reply.allowed_actions = [:complete]
625			reply.command << alt_form.form
626		}.then do |iq|
627			Command.finish { |reply| alt_form.parse(iq.form).action(reply) }
628		end
629	end
630}.register(self).then(&CommandList.method(:register))
631
632Command.new(
633	"plan settings",
634	"Manage your plan, including overage limits",
635	list_for: ->(customer:, **) { !!customer&.currency }
636) {
637	Command.customer.then do |customer|
638		Command.reply { |reply|
639			reply.allowed_actions = [:next]
640			reply.command << FormTemplate.render("plan_settings", customer: customer)
641		}.then { |iq|
642			Command.execution.customer_repo.put_monthly_overage_limit(
643				customer,
644				iq.form.field("monthly_overage_limit")&.value.to_i
645			)
646		}.then { Command.finish("Configuration saved!") }
647	end
648}.register(self).then(&CommandList.method(:register))
649
650Command.new(
651	"referral codes",
652	"Refer a friend for free credit"
653) {
654	Command.customer.then(&:unused_invites).then do |invites|
655		if invites.empty?
656			Command.finish("You have no more invites right now, try again later.")
657		else
658			Command.finish do |reply|
659				reply.form.type = :result
660				reply.form.title = "Unused Invite Codes"
661				reply.form.instructions =
662					"Each of these codes is single use and gives the person using " \
663					"them a free month of JMP service. You will receive credit " \
664					"equivalent to one month of free service if they later become " \
665					"a paying customer."
666				FormTable.new(
667					invites.map { |i| [i] },
668					code: "Invite Code"
669				).add_to_form(reply.form)
670			end
671		end
672	end
673}.register(self).then(&CommandList.method(:register))
674
675Command.new(
676	"sims",
677	"(e)SIM Details",
678	list_for: ->(customer:, **) { CONFIG[:keepgo] && !!customer&.currency }
679) {
680	Command.customer.then(&SIMRepo.new.method(:owned_by)).then do |sims|
681		if sims.empty?
682			next Command.finish(
683				"You have no (e)SIMs, you can get on the waitlist at https://jmp.chat/sim"
684			)
685		end
686
687		Command.finish do |reply|
688			reply.command << FormTemplate.render(
689				"sim_details",
690				sims: sims
691			)
692		end
693	end
694}.register(self).then(&CommandList.method(:register))
695
696Command.new(
697	"reset sip account",
698	"Create or Reset SIP Account",
699	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
700) {
701	Command.customer.then do |customer|
702		sip_account = customer.reset_sip_account
703		Command.reply { |reply|
704			reply.allowed_actions = [:next]
705			form = sip_account.form
706			form.type = :form
707			form.fields += [{
708				type: :boolean, var: "change_fwd",
709				label: "Should inbound calls forward to this SIP account?"
710			}]
711			reply.command << form
712		}.then do |fwd|
713			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
714				Command.execution.customer_repo.put_fwd(
715					customer,
716					customer.fwd.with(uri: sip_account.uri)
717				).then { Command.finish("Inbound calls will now forward to SIP.") }
718			else
719				Command.finish
720			end
721		end
722	end
723}.register(self).then(&CommandList.method(:register))
724
725Command.new(
726	"lnp",
727	"Port in your number from another carrier",
728	list_for: ->(**) { true }
729) {
730	EMPromise.all([
731		Command.customer,
732		Command.reply do |reply|
733			reply.allowed_actions = [:next]
734			reply.command << FormTemplate.render("lnp")
735		end
736	]).then { |(customer, iq)|
737		PortInOrder.parse(customer, iq.form).complete_with do |form|
738			Command.reply { |reply|
739				reply.allowed_actions = [:next]
740				reply.command << form
741			}.then(&:form)
742		end
743	}.then do |order|
744		order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
745		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
746		BLATHER.say(CONFIG[:notify_admin], order.message(order_id), :groupchat)
747		Command.finish(
748			"Your port-in request has been accepted, " \
749			"support will contact you with next steps"
750		)
751	end
752}.register(self).then(&CommandList.method(:register))
753
754Command.new(
755	"customer info",
756	"Show Customer Info",
757	list_for: ->(customer: nil, **) { customer&.admin? }
758) {
759	Command.customer.then do |customer|
760		raise AuthError, "You are not an admin" unless customer&.admin?
761
762		customer_repo = CustomerRepo.new(
763			sgx_repo: Bwmsgsv2Repo.new,
764			bandwidth_tn_repo: EmptyRepo.new(BandwidthTnRepo.new) # No CNAM in admin
765		)
766
767		AdminCommand::NoUser.new(customer_repo).start
768	end
769}.register(self).then(&CommandList.method(:register))
770
771Command.new(
772	"snikket",
773	"Launch Snikket Instance",
774	list_for: ->(customer: nil, **) { customer&.admin? }
775) {
776	Command.customer.then do |customer|
777		raise AuthError, "You are not an admin" unless customer&.admin?
778
779		Command.reply { |reply|
780			reply.allowed_actions = [:next]
781			reply.command << FormTemplate.render("snikket_launch")
782		}.then { |response|
783			domain = response.form.field("domain").value.to_s
784			IQ_MANAGER.write(Snikket::Launch.new(
785				nil, CONFIG[:snikket_hosting_api],
786				domain: domain
787			)).then do |launched|
788				[domain, launched]
789			end
790		}.then { |(domain, launched)|
791			Command.finish do |reply|
792				reply.command << FormTemplate.render(
793					"snikket_launched",
794					launched: launched,
795					domain: domain
796				)
797			end
798		}
799	end
800}.register(self).then(&CommandList.method(:register))
801
802def reply_with_note(iq, text, type: :info)
803	reply = iq.reply
804	reply.status = :completed
805	reply.note_type = type
806	reply.note_text = text
807
808	self << reply
809end
810
811Command.new(
812	"https://ns.cheogram.com/sgx/jid-switch",
813	"Change JID",
814	list_for: ->(customer: nil, **) { customer },
815	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
816) {
817	Command.customer.then { |customer|
818		Command.reply { |reply|
819			reply.command << FormTemplate.render("jid_switch")
820		}.then { |response|
821			new_jid = response.form.field("jid").value
822			repo = Command.execution.customer_repo
823			repo.find_by_jid(new_jid)
824				.catch_only(CustomerRepo::NotFound) { nil }
825				.then { |cust|
826					next EMPromise.reject("Customer Already Exists") if cust
827
828					repo.change_jid(customer, new_jid)
829				}
830		}.then {
831			StatsD.increment("changejid.completed")
832			Command.finish { |reply|
833				reply.note_type = :info
834				reply.note_text = "Customer JID Changed"
835			}
836		}
837	}
838}.register(self).then(&CommandList.method(:register))
839
840Command.new(
841	"web-register",
842	"Initiate Register from Web",
843	list_for: lambda { |from_jid: nil, **|
844		from_jid&.stripped.to_s == CONFIG[:web_register][:from]
845	}
846) {
847	if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
848		next EMPromise.reject(
849			Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
850		)
851	end
852
853	Command.reply { |reply|
854		reply.command << FormTemplate.render("web_register")
855	}.then do |iq|
856		jid = iq.form.field("jid")&.value.to_s.strip
857		tel = iq.form.field("tel")&.value.to_s.strip
858		if jid !~ /\./
859			Command.finish("The Jabber ID you entered was not valid.", type: :error)
860		elsif tel !~ /\A\+\d+\Z/
861			Command.finish("Invalid telephone number", type: :error)
862		else
863			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
864				cmd.to = CONFIG[:web_register][:to]
865				cmd.node = "push-register"
866				cmd.form.fields = [{ var: "to", value: jid }]
867				cmd.form.type = "submit"
868			}).then { |result|
869				TEL_SELECTIONS.set(result.form.field("from")&.value.to_s.strip, tel)
870			}.then { Command.finish }
871		end
872	end
873}.register(self).then(&CommandList.method(:register))
874
875command sessionid: /./ do |iq|
876	COMMAND_MANAGER.fulfill(iq)
877	IQ_MANAGER.fulfill(iq)
878	true
879end
880
881iq type: [:result, :error] do |iq|
882	IQ_MANAGER.fulfill(iq)
883	true
884end
885
886iq type: [:get, :set] do |iq|
887	StatsD.increment("unknown_iq")
888
889	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
890end
891
892trap(:INT) { EM.stop }
893trap(:TERM) { EM.stop }
894EM.run { client.run }