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		plan_name = iq.form.field("plan_name").value.to_s
 605		customer = customer.with_plan(plan_name)
 606		customer.save_plan!.then {
 607			Registration::Payment.for(
 608				iq, customer, customer.registered?.phone,
 609				final_message: PaypalDone::MESSAGE,
 610				finish: PaypalDone
 611			)
 612		}.then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
 613			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 614			BLATHER.say(
 615				CONFIG[:notify_admin],
 616				"#{customer.customer_id} migrated to #{customer.currency}",
 617				:groupchat
 618			)
 619			EMPromise.reject(s)
 620		end
 621	end
 622}.register(self).then(&CommandList.method(:register))
 623
 624Command.new(
 625	"credit cards",
 626	"💳 Credit Card Settings and Management"
 627) {
 628	Command.customer.then do |customer|
 629		url = CONFIG[:credit_card_url].call(
 630			customer.jid.to_s.gsub("\\", "%5C"),
 631			customer.customer_id
 632		)
 633		desc = "Manage credits cards and settings"
 634		Command.finish("#{desc}: #{url}") do |reply|
 635			oob = OOB.find_or_create(reply.command)
 636			oob.url = url
 637			oob.desc = desc
 638		end
 639	end
 640}.register(self).then(&CommandList.method(:register))
 641
 642Command.new(
 643	"top up",
 644	"💲 Buy Account Credit by Credit Card",
 645	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
 646	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
 647) {
 648	Command.customer.then { |customer|
 649		BuyAccountCreditForm.for(customer).then do |credit_form|
 650			Command.reply { |reply|
 651				reply.allowed_actions = [:complete]
 652				reply.command << credit_form.form
 653			}.then do |iq|
 654				CreditCardSale.create(customer, **credit_form.parse(iq.form))
 655			end
 656		end
 657	}.then { |transaction|
 658		Command.finish("#{transaction} added to your account balance.")
 659	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
 660		Command.finish(e.message, type: :error)
 661	end
 662}.register(self).then(&CommandList.method(:register))
 663
 664Command.new(
 665	"alt top up",
 666	"🪙 Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
 667	list_for: ->(customer:, **) { !!customer&.currency }
 668) {
 669	Command.customer.then { |customer|
 670		AltTopUpForm.for(customer)
 671	}.then do |alt_form|
 672		Command.reply { |reply|
 673			reply.allowed_actions = [:complete]
 674			reply.command << alt_form.form
 675		}.then do |iq|
 676			Command.finish { |reply| alt_form.parse(iq.form).action(reply) }
 677		end
 678	end
 679}.register(self).then(&CommandList.method(:register))
 680
 681Command.new(
 682	"plan settings",
 683	"📝 Manage your plan, including overage limits",
 684	list_for: ->(customer:, **) { !!customer&.currency }
 685) {
 686	Command.customer.then do |customer|
 687		Command.reply { |reply|
 688			reply.allowed_actions = [:next]
 689			reply.command << FormTemplate.render("plan_settings", customer: customer)
 690		}.then { |iq|
 691			Command.execution.customer_repo.put_monthly_overage_limit(
 692				customer,
 693				iq.form.field("monthly_overage_limit")&.value.to_i
 694			)
 695		}.then { Command.finish("Configuration saved!") }
 696	end
 697}.register(self).then(&CommandList.method(:register))
 698
 699Command.new(
 700	"referral codes",
 701	"👥 Refer a friend for free credit"
 702) {
 703	repo = InvitesRepo.new
 704	Command.customer.then { |customer|
 705		EMPromise.all([
 706			repo.find_or_create_group_code(customer.customer_id),
 707			repo.unused_invites(customer.customer_id)
 708		])
 709	}.then do |(group_code, invites)|
 710		if invites.empty?
 711			Command.finish(
 712				"This code will provide credit equivalent to one month of service " \
 713				"to anyone after they sign up and pay: #{group_code}\n\n" \
 714				"You will receive credit equivalent to one month of service once " \
 715				"their payment clears."
 716			)
 717		else
 718			Command.finish do |reply|
 719				reply.command << FormTemplate.render(
 720					"codes",
 721					invites: invites,
 722					group_code: group_code
 723				)
 724			end
 725		end
 726	end
 727}.register(self).then(&CommandList.method(:register))
 728
 729Command.new(
 730	"sims",
 731	"📶 (e)SIM Details",
 732	list_for: ->(customer:, **) { CONFIG[:keepgo] && !!customer&.currency }
 733) {
 734	Command.customer.then(&SIMRepo.new.method(:owned_by)).then do |sims|
 735		if sims.empty?
 736			next Command.finish(
 737				"You have no (e)SIMs, you can get on the waitlist at https://jmp.chat/sim"
 738			)
 739		end
 740
 741		Command.finish do |reply|
 742			reply.command << FormTemplate.render(
 743				"sim_details",
 744				sims: sims
 745			)
 746		end
 747	end
 748}.register(self).then(&CommandList.method(:register))
 749
 750Command.new(
 751	"reset sip account",
 752	"☎️ Create or Reset SIP Account",
 753	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 754) {
 755	Command.customer.then do |customer|
 756		sip_account = customer.reset_sip_account
 757		Command.reply { |reply|
 758			reply.allowed_actions = [:next]
 759			form = sip_account.form
 760			form.type = :form
 761			form.fields += [{
 762				type: :boolean, var: "change_fwd",
 763				label: "Should inbound calls forward to this SIP account?"
 764			}]
 765			reply.command << form
 766		}.then do |fwd|
 767			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
 768				Command.execution.customer_repo.put_fwd(
 769					customer,
 770					customer.fwd.with(uri: sip_account.uri)
 771				).then { Command.finish("Inbound calls will now forward to SIP.") }
 772			else
 773				Command.finish
 774			end
 775		end
 776	end
 777}.register(self).then(&CommandList.method(:register))
 778
 779Command.new(
 780	"lnp",
 781	"#️⃣ Port in your number from another carrier",
 782	list_for: ->(**) { true }
 783) {
 784	EMPromise.all([
 785		Command.customer,
 786		Command.reply do |reply|
 787			reply.allowed_actions = [:next]
 788			reply.command << FormTemplate.render("lnp")
 789		end
 790	]).then { |(customer, iq)|
 791		PortInOrder.parse(customer, iq.form).complete_with do |form|
 792			Command.reply { |reply|
 793				reply.allowed_actions = [:next]
 794				reply.command << form
 795			}.then(&:form)
 796		end
 797	}.then do |order|
 798		order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
 799		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 800		BLATHER.say(CONFIG[:notify_admin], order.message(order_id), :groupchat)
 801		Command.finish(
 802			"Your port-in request has been accepted, " \
 803			"support will contact you with next steps"
 804		)
 805	end
 806}.register(self).then(&CommandList.method(:register))
 807
 808Command.new(
 809	"terminate account",
 810	"❌ Cancel your account and terminate your phone number",
 811	list_for: ->(**) { false },
 812	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 813) {
 814	Command.reply { |reply|
 815		reply.allowed_actions = [:next]
 816		reply.note_text = "Press next to confirm your account termination."
 817	}.then { Command.customer }.then { |customer|
 818		AdminAction::CancelCustomer.call(
 819			customer,
 820			customer_repo: Command.execution.customer_repo
 821		)
 822	}.then do
 823		Command.finish("Account cancelled")
 824	end
 825}.register(self).then(&CommandList.method(:register))
 826
 827Command.new(
 828	"customer info",
 829	"Show Customer Info",
 830	list_for: ->(customer: nil, **) { customer&.admin? }
 831) {
 832	Command.customer.then do |customer|
 833		raise AuthError, "You are not an admin" unless customer&.admin?
 834
 835		customer_repo = CustomerRepo.new(
 836			sgx_repo: Bwmsgsv2Repo.new,
 837			bandwidth_tn_repo: EmptyRepo.new(BandwidthTnRepo.new) # No CNAM in admin
 838		)
 839
 840		AdminCommand::NoUser.new(customer_repo).start
 841	end
 842}.register(self).then(&CommandList.method(:register))
 843
 844Command.new(
 845	"reachability",
 846	"Test Reachability",
 847	list_for: ->(customer: nil, **) { customer&.admin? }
 848) {
 849	Command.customer.then do |customer|
 850		raise AuthError, "You are not an admin" unless customer&.admin?
 851
 852		form = ReachabilityForm.new(CustomerRepo.new)
 853
 854		Command.reply { |reply|
 855			reply.allowed_actions = [:next]
 856			reply.command << form.render
 857		}.then { |response|
 858			form.parse(response.form)
 859		}.then { |result|
 860			result.repo.get_or_create(result.target).then { |v|
 861				result.target.stanza_from(result.prompt) if result.prompt
 862
 863				Command.finish { |reply|
 864					reply.command << form.render_result(v)
 865				}
 866			}
 867		}.catch_only(RuntimeError) { |e|
 868			Command.finish(e, type: :error)
 869		}
 870	end
 871}.register(self).then(&CommandList.method(:register))
 872
 873Command.new(
 874	"snikket",
 875	"Launch Snikket Instance",
 876	list_for: ->(customer: nil, **) { customer&.admin? }
 877) {
 878	Command.customer.then do |customer|
 879		raise AuthError, "You are not an admin" unless customer&.admin?
 880
 881		Command.reply { |reply|
 882			reply.allowed_actions = [:next]
 883			reply.command << FormTemplate.render("snikket_launch")
 884		}.then { |response|
 885			domain = response.form.field("domain").value.to_s
 886			IQ_MANAGER.write(Snikket::Launch.new(
 887				nil, CONFIG[:snikket_hosting_api],
 888				domain: domain
 889			)).then do |launched|
 890				Snikket::CustomerInstance.for(customer, domain, launched)
 891			end
 892		}.then { |instance|
 893			Command.finish do |reply|
 894				reply.command << FormTemplate.render(
 895					"snikket_launched",
 896					instance: instance
 897				)
 898			end
 899		}
 900	end
 901}.register(self).then(&CommandList.method(:register))
 902
 903def reply_with_note(iq, text, type: :info)
 904	reply = iq.reply
 905	reply.status = :completed
 906	reply.note_type = type
 907	reply.note_text = text
 908
 909	self << reply
 910end
 911
 912Command.new(
 913	"https://ns.cheogram.com/sgx/jid-switch",
 914	"Change JID",
 915	list_for: ->(customer: nil, **) { customer },
 916	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 917) {
 918	Command.customer.then { |customer|
 919		Command.reply { |reply|
 920			reply.command << FormTemplate.render("jid_switch")
 921		}.then { |response|
 922			new_jid = response.form.field("jid").value
 923			repo = Command.execution.customer_repo
 924			repo.find_by_jid(new_jid).catch_only(CustomerRepo::NotFound) { nil }
 925				.then { |cust|
 926					next EMPromise.reject("Customer Already Exists") if cust
 927
 928					repo.change_jid(customer, new_jid)
 929				}
 930		}.then {
 931			StatsD.increment("changejid.completed")
 932			jid = ProxiedJID.new(customer.jid).unproxied
 933			if jid.domain == CONFIG[:onboarding_domain]
 934				CustomerRepo.new.find(customer.customer_id).then do |cust|
 935					WelcomeMessage.new(cust, customer.registered?.phone).welcome
 936				end
 937			end
 938			Command.finish { |reply|
 939				reply.note_type = :info
 940				reply.note_text = "Customer JID Changed"
 941			}
 942		}
 943	}
 944}.register(self).then(&CommandList.method(:register))
 945
 946Command.new(
 947	"web-register",
 948	"Initiate Register from Web",
 949	list_for: lambda { |from_jid: nil, **|
 950		from_jid&.stripped.to_s == CONFIG[:web_register][:from]
 951	}
 952) {
 953	if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
 954		next EMPromise.reject(
 955			Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
 956		)
 957	end
 958
 959	Command.reply { |reply|
 960		reply.command << FormTemplate.render("web_register")
 961	}.then do |iq|
 962		jid = iq.form.field("jid")&.value.to_s.strip
 963		tel = iq.form.field("tel")&.value.to_s.strip
 964		if jid !~ /\./ || jid =~ /\s/
 965			Command.finish("The Jabber ID you entered was not valid.", type: :error)
 966		elsif tel !~ /\A\+\d+\Z/
 967			Command.finish("Invalid telephone number", type: :error)
 968		else
 969			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
 970				cmd.to = CONFIG[:web_register][:to]
 971				cmd.node = "push-register"
 972				cmd.form.fields = [{ var: "to", value: jid }]
 973				cmd.form.type = "submit"
 974			}).then { |result|
 975				TEL_SELECTIONS.set(result.form.field("from")&.value.to_s.strip, tel)
 976			}.then { Command.finish }
 977		end
 978	end
 979}.register(self).then(&CommandList.method(:register))
 980
 981command sessionid: /./ do |iq|
 982	COMMAND_MANAGER.fulfill(iq)
 983	IQ_MANAGER.fulfill(iq)
 984	true
 985end
 986
 987iq type: [:result, :error] do |iq|
 988	IQ_MANAGER.fulfill(iq)
 989	true
 990end
 991
 992iq type: [:get, :set] do |iq|
 993	StatsD.increment("unknown_iq")
 994
 995	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
 996end
 997
 998trap(:INT) { EM.stop }
 999trap(:TERM) { EM.stop }
1000EM.run { client.run }