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