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