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