sgx_jmp.rb

  1# frozen_string_literal: true
  2
  3require "pg/em/connection_pool"
  4require "bandwidth"
  5require "bigdecimal"
  6require "blather/client/dsl" # Require this first to not auto-include
  7require "blather/client"
  8require "braintree"
  9require "date"
 10require "dhall"
 11require "em-hiredis"
 12require "em_promise"
 13require "ougai"
 14require "ruby-bandwidth-iris"
 15require "sentry-ruby"
 16require "statsd-instrument"
 17
 18$stdout.sync = true
 19LOG = Ougai::Logger.new($stdout)
 20LOG.level = ENV.fetch("LOG_LEVEL", "info")
 21LOG.formatter = Ougai::Formatters::Readable.new(
 22	nil,
 23	nil,
 24	plain: !$stdout.isatty
 25)
 26Blather.logger = LOG
 27EM::Hiredis.logger = LOG
 28StatsD.logger = LOG
 29LOG.info "Starting"
 30
 31Sentry.init do |config|
 32	config.logger = LOG
 33	config.breadcrumbs_logger = [:sentry_logger]
 34end
 35
 36module SentryOugai
 37	class SentryLogger
 38		include Sentry::Breadcrumb::SentryLogger
 39		include Singleton
 40	end
 41
 42	def _log(severity, message=nil, ex=nil, data=nil, &block)
 43		super
 44		SentryLogger.instance.add_breadcrumb(severity, message || ex.to_s, &block)
 45	end
 46end
 47LOG.extend SentryOugai
 48
 49CONFIG =
 50	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/add_bitcoin_address"
 71require_relative "lib/backend_sgx"
 72require_relative "lib/bwmsgsv2_repo"
 73require_relative "lib/bandwidth_iris_patch"
 74require_relative "lib/bandwidth_tn_order"
 75require_relative "lib/btc_sell_prices"
 76require_relative "lib/buy_account_credit_form"
 77require_relative "lib/configure_calls_form"
 78require_relative "lib/command"
 79require_relative "lib/command_list"
 80require_relative "lib/customer"
 81require_relative "lib/customer_info_form"
 82require_relative "lib/customer_repo"
 83require_relative "lib/electrum"
 84require_relative "lib/expiring_lock"
 85require_relative "lib/em"
 86require_relative "lib/form_to_h"
 87require_relative "lib/low_balance"
 88require_relative "lib/port_in_order"
 89require_relative "lib/payment_methods"
 90require_relative "lib/paypal_done"
 91require_relative "lib/registration"
 92require_relative "lib/transaction"
 93require_relative "lib/tel_selections"
 94require_relative "lib/session_manager"
 95require_relative "lib/statsd"
 96require_relative "web"
 97
 98ELECTRUM = Electrum.new(**CONFIG[:electrum])
 99EM::Hiredis::Client.load_scripts_from("./redis_lua")
100
101Faraday.default_adapter = :em_synchrony
102BandwidthIris::Client.global_options = {
103	account_id: CONFIG[:creds][:account],
104	username: CONFIG[:creds][:username],
105	password: CONFIG[:creds][:password]
106}
107BANDWIDTH_VOICE = Bandwidth::Client.new(
108	voice_basic_auth_user_name: CONFIG[:creds][:username],
109	voice_basic_auth_password: CONFIG[:creds][:password]
110).voice_client.client
111
112def new_sentry_hub(stanza, name: nil)
113	hub = Sentry.get_current_hub&.new_from_top
114	raise "Sentry.init has not been called" unless hub
115
116	hub.push_scope
117	hub.current_scope.clear_breadcrumbs
118	hub.current_scope.set_transaction_name(name) if name
119	hub.current_scope.set_user(jid: stanza.from.stripped.to_s)
120	hub
121end
122
123class AuthError < StandardError; end
124
125# Braintree is not async, so wrap in EM.defer for now
126class AsyncBraintree
127	def initialize(environment:, merchant_id:, public_key:, private_key:, **)
128		@gateway = Braintree::Gateway.new(
129			environment: environment,
130			merchant_id: merchant_id,
131			public_key: public_key,
132			private_key: private_key
133		)
134		@gateway.config.logger = LOG
135	end
136
137	def respond_to_missing?(m, *)
138		@gateway.respond_to?(m) || super
139	end
140
141	def method_missing(m, *args)
142		return super unless respond_to_missing?(m, *args)
143
144		EM.promise_defer(klass: PromiseChain) do
145			@gateway.public_send(m, *args)
146		end
147	end
148
149	class PromiseChain < EMPromise
150		def respond_to_missing?(*)
151			false && super # We don't actually know what we respond to...
152		end
153
154		def method_missing(m, *args)
155			return super if respond_to_missing?(m, *args)
156
157			self.then { |o| o.public_send(m, *args) }
158		end
159	end
160end
161
162BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])
163
164def panic(e, hub=nil)
165	(Thread.current[:log] || LOG).fatal(
166		"Error raised during event loop: #{e.class}",
167		e
168	)
169	if e.is_a?(::Exception)
170		(hub || Sentry).capture_exception(e, hint: { background: false })
171	else
172		(hub || Sentry).capture_message(e.to_s, hint: { background: false })
173	end
174	exit 1
175end
176
177EM.error_handler(&method(:panic))
178
179def poll_for_notify(db)
180	db.wait_for_notify_defer.then { |notify|
181		CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new).find(notify[:extra])
182	}.then(&LowBalance.method(:for)).then(&:notify!).then {
183		poll_for_notify(db)
184	}.catch(&method(:panic))
185end
186
187def load_plans_to_db!
188	DB.transaction do
189		DB.exec("TRUNCATE plans")
190		CONFIG[:plans].each do |plan|
191			DB.exec("INSERT INTO plans VALUES ($1)", [plan.to_json])
192		end
193	end
194end
195
196when_ready do
197	LOG.info "Ready"
198	BLATHER = self
199	REDIS = EM::Hiredis.connect
200	TEL_SELECTIONS = TelSelections.new
201	BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
202	DB = PG::EM::ConnectionPool.new(dbname: "jmp") { |conn|
203		conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn)
204		conn.type_map_for_queries = PG::BasicTypeMapForQueries.new(conn)
205	}
206
207	DB.hold do |conn|
208		conn.query("LISTEN low_balance")
209		conn.query("SELECT customer_id FROM balances WHERE balance < 5").each do |c|
210			conn.query("SELECT pg_notify('low_balance', $1)", c.values)
211		end
212		poll_for_notify(conn)
213	end
214
215	load_plans_to_db!
216
217	EM.add_periodic_timer(3600) do
218		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
219		ping.from = CONFIG[:component][:jid]
220		self << ping
221	end
222
223	Web.run(LOG.child, *WEB_LISTEN)
224end
225
226# workqueue_count MUST be 0 or else Blather uses threads!
227setup(
228	CONFIG[:component][:jid],
229	CONFIG[:component][:secret],
230	CONFIG[:server][:host],
231	CONFIG[:server][:port],
232	nil,
233	nil,
234	workqueue_count: 0
235)
236
237message to: /\Aaccount@/, body: /./ do |m|
238	StatsD.increment("deprecated_account_bot")
239
240	self << m.reply.tap { |out|
241		out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
242	}
243end
244
245before(
246	:iq,
247	type: [:error, :result],
248	to: /\Acustomer_/,
249	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
250) { |iq| halt if IQ_MANAGER.fulfill(iq) }
251
252before nil, to: /\Acustomer_/, from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/ do |s|
253	StatsD.increment("stanza_customer")
254
255	sentry_hub = new_sentry_hub(s, name: "stanza_customer")
256	CustomerRepo.new.find(
257		s.to.node.delete_prefix("customer_")
258	).then { |customer|
259		sentry_hub.current_scope.set_user(
260			id: customer.customer_id,
261			jid: s.from.stripped.to_s
262		)
263		customer.stanza_to(s)
264	}.catch { |e| panic(e, sentry_hub) }
265	halt
266end
267
268ADDRESSES_NS = "http://jabber.org/protocol/address"
269message(
270	to: /\A#{CONFIG[:component][:jid]}\Z/,
271	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
272) do |m|
273	StatsD.increment("inbound_group_text")
274	sentry_hub = new_sentry_hub(m, name: "inbound_group_text")
275
276	address = m.find("ns:addresses", ns: ADDRESSES_NS).first
277		&.find("ns:address", ns: ADDRESSES_NS)
278		&.find { |el| el["jid"].to_s.start_with?("customer_") }
279	pass unless address
280
281	CustomerRepo.new.find_by_jid(address["jid"]).then { |customer|
282		m.from = m.from.with(domain: CONFIG[:component][:jid])
283		m.to = m.to.with(domain: customer.jid.domain)
284		address["jid"] = customer.jid.to_s
285		BLATHER << m
286	}.catch_only(CustomerRepo::NotFound) { |e|
287		BLATHER << m.as_error("forbidden", :auth, e.message)
288	}.catch { |e| panic(e, sentry_hub) }
289end
290
291# Ignore groupchat messages
292# Especially if we have the component join MUC for notifications
293message(type: :groupchat) { true }
294
295def billable_message(m)
296	(m.body && !m.body.empty?) || m.find("ns:x", ns: OOB.registered_ns).first
297end
298
299def notify_admin_of_usage(customer, usage, today)
300	ExpiringLock.new("jmp_usage_notify-#{customer.customer_id}").with do
301		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
302		BLATHER.say(
303			CONFIG[:notify_admin], "#{customer.customer_id} has used " \
304			"#{usage} messages since #{today - 30}", :groupchat
305		)
306	end
307end
308
309message do |m|
310	StatsD.increment("message")
311
312	sentry_hub = new_sentry_hub(m, name: "message")
313	today = Time.now.utc.to_date
314	CustomerRepo.new.find_by_jid(m.from.stripped).then { |customer|
315		sentry_hub.current_scope.set_user(
316			id: customer.customer_id, jid: m.from.stripped.to_s
317		)
318		EMPromise.all([
319			(customer.incr_message_usage if billable_message(m)),
320			customer.message_usage((today..(today - 30))).then do |usage|
321				if usage < 3500
322					customer.stanza_from(m)
323				else
324					BLATHER << m.as_error(
325						"policy-violation", :wait, "Please contact support"
326					)
327				end
328				notify_admin_of_usage(customer, usage, today) if usage > 900
329			end
330		])
331	}.catch_only(CustomerRepo::NotFound) { |e|
332		BLATHER << m.as_error("forbidden", :auth, e.message)
333	}.catch { |e| panic(e, sentry_hub) }
334end
335
336message :error? do |m|
337	StatsD.increment("message_error")
338
339	LOG.error "MESSAGE ERROR", stanza: m
340end
341
342IQ_MANAGER = SessionManager.new(self, :id)
343COMMAND_MANAGER = SessionManager.new(
344	self,
345	:sessionid,
346	timeout: 60 * 60,
347	error_if: ->(s) { s.cancel? }
348)
349
350disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
351	reply = iq.reply
352	reply.identities = [{
353		name: "JMP.chat",
354		type: "sms",
355		category: "gateway"
356	}]
357	reply.features = [
358		"http://jabber.org/protocol/disco#info",
359		"http://jabber.org/protocol/commands"
360	]
361	form = Blather::Stanza::X.find_or_create(reply.query)
362	form.type = "result"
363	form.fields = [
364		{
365			var: "FORM_TYPE",
366			type: "hidden",
367			value: "http://jabber.org/network/serverinfo"
368		}
369	] + CONFIG[:xep0157]
370	self << reply
371end
372
373disco_info do |iq|
374	reply = iq.reply
375	reply.identities = [{
376		name: "JMP.chat",
377		type: "sms",
378		category: "client"
379	}]
380	reply.features = [
381		"urn:xmpp:receipts"
382	]
383	self << reply
384end
385
386disco_items node: "http://jabber.org/protocol/commands" do |iq|
387	StatsD.increment("command_list")
388
389	sentry_hub = new_sentry_hub(iq, name: iq.node)
390	reply = iq.reply
391	reply.node = "http://jabber.org/protocol/commands"
392
393	CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new).find_by_jid(
394		iq.from.stripped
395	).catch {
396		nil
397	}.then { |customer|
398		CommandList.for(customer, iq.from)
399	}.then { |list|
400		reply.items = list.map { |item|
401			Blather::Stanza::DiscoItems::Item.new(
402				iq.to,
403				item[:node],
404				item[:name]
405			)
406		}
407		self << reply
408	}.catch { |e| panic(e, sentry_hub) }
409end
410
411iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
412	StatsD.increment("extdisco")
413
414	reply = iq.reply
415	reply << Nokogiri::XML::Builder.new {
416		services(xmlns: "urn:xmpp:extdisco:2") do
417			service(
418				type: "sip",
419				host: CONFIG[:sip_host]
420			)
421		end
422	}.doc.root
423
424	self << reply
425end
426
427Command.new(
428	"jabber:iq:register",
429	"Register",
430	list_for: ->(*) { true },
431	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
432) {
433	Command.customer.catch {
434		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
435		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
436	}.then { |customer|
437		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
438		Registration.for(customer, TEL_SELECTIONS).then(&:write)
439	}.then {
440		StatsD.increment("registration.completed")
441	}.catch_only(Command::Execution::FinalStanza) do |e|
442		StatsD.increment("registration.completed")
443		EMPromise.reject(e)
444	end
445}.register(self).then(&CommandList.method(:register))
446
447Command.new(
448	"info",
449	"Show Account Info",
450	list_for: ->(*) { true },
451	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
452) {
453	Command.customer.then(&:info).then do |info|
454		Command.finish do |reply|
455			reply.command << info.form
456		end
457	end
458}.register(self).then(&CommandList.method(:register))
459
460Command.new(
461	"usage",
462	"Show Monthly Usage"
463) {
464	report_for = (Date.today..(Date.today << 1))
465
466	Command.customer.then { |customer|
467		customer.usage_report(report_for)
468	}.then do |usage_report|
469		Command.finish do |reply|
470			reply.command << usage_report.form
471		end
472	end
473}.register(self).then(&CommandList.method(:register))
474
475Command.new(
476	"configure calls",
477	"Configure Calls",
478	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
479) {
480	Command.customer.then do |customer|
481		cc_form = ConfigureCallsForm.new(customer)
482		Command.reply { |reply|
483			reply.allowed_actions = [:next]
484			reply.command << cc_form.render
485		}.then { |iq|
486			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
487				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
488			})
489		}.then { Command.finish("Configuration saved!") }
490	end
491}.register(self).then(&CommandList.method(:register))
492
493Command.new(
494	"ogm",
495	"Record Voicemail Greeting",
496	list_for: ->(fwd: nil, **) { !!fwd },
497	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
498) {
499	Command.customer.then do |customer|
500		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
501			cc.from = customer.registered?.phone
502			cc.application_id = CONFIG[:sip][:app]
503			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
504			                "customer_id=#{customer.customer_id}"
505		end
506		Command.finish("You will now receive a call.")
507	end
508}.register(self).then(&CommandList.method(:register))
509
510Command.new(
511	"migrate billing",
512	"Switch from PayPal or expired trial to new billing",
513	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
514	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
515) {
516	EMPromise.all([
517		Command.customer,
518		Command.reply do |reply|
519			reply.allowed_actions = [:next]
520			reply.command << FormTemplate.render("migrate_billing")
521		end
522	]).then do |(customer, iq)|
523		Registration::Payment.for(
524			iq, customer, customer.registered?.phone,
525			final_message: PaypalDone::MESSAGE,
526			finish: PaypalDone
527		).then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
528			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
529			BLATHER.say(
530				CONFIG[:notify_admin],
531				"#{customer.customer_id} migrated to #{customer.currency}",
532				:groupchat
533			)
534			EMPromise.reject(s)
535		end
536	end
537}.register(self).then(&CommandList.method(:register))
538
539Command.new(
540	"credit cards",
541	"Credit Card Settings and Management"
542) {
543	Command.customer.then do |customer|
544		url = CONFIG[:credit_card_url].call(
545			customer.jid.to_s.gsub("\\", "%5C"),
546			customer.customer_id
547		)
548		desc = "Manage credits cards and settings"
549		Command.finish("#{desc}: #{url}") do |reply|
550			oob = OOB.find_or_create(reply.command)
551			oob.url = url
552			oob.desc = desc
553		end
554	end
555}.register(self).then(&CommandList.method(:register))
556
557Command.new(
558	"top up",
559	"Buy Account Credit by Credit Card",
560	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
561	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
562) {
563	Command.customer.then { |customer|
564		BuyAccountCreditForm.for(customer).then do |credit_form|
565			Command.reply { |reply|
566				reply.allowed_actions = [:complete]
567				credit_form.add_to_form(reply.form)
568			}.then do |iq|
569				Transaction.sale(customer, **credit_form.parse(iq.form))
570			end
571		end
572	}.then { |transaction|
573		transaction.insert.then do
574			Command.finish("#{transaction} added to your account balance.")
575		end
576	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
577		Command.finish(e.message, type: :error)
578	end
579}.register(self).then(&CommandList.method(:register))
580
581Command.new(
582	"alt top up",
583	"Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
584	list_for: ->(customer:, **) { !!customer&.currency }
585) {
586	Command.customer.then { |customer|
587		EMPromise.all([AltTopUpForm.for(customer), customer])
588	}.then do |(alt_form, customer)|
589		Command.reply { |reply|
590			reply.allowed_actions = [:complete]
591			reply.command << alt_form.form
592		}.then do |iq|
593			AddBitcoinAddress.for(iq, alt_form, customer).write
594		end
595	end
596}.register(self).then(&CommandList.method(:register))
597
598Command.new(
599	"plan settings",
600	"Manage your plan, including overage limits",
601	list_for: ->(customer:, **) { !!customer&.currency }
602) {
603	Command.customer.then do |customer|
604		Command.reply { |reply|
605			reply.allowed_actions = [:next]
606			reply.command << FormTemplate.render("plan_settings", customer: customer)
607		}.then { |iq|
608			Command.execution.customer_repo.put_monthly_overage_limit(
609				customer,
610				iq.form.field("monthly_overage_limit")&.value.to_i
611			)
612		}.then { Command.finish("Configuration saved!") }
613	end
614}.register(self).then(&CommandList.method(:register))
615
616Command.new(
617	"referral codes",
618	"Refer a friend for free credit"
619) {
620	Command.customer.then(&:unused_invites).then do |invites|
621		if invites.empty?
622			Command.finish("You have no more invites right now, try again later.")
623		else
624			Command.finish do |reply|
625				reply.form.type = :result
626				reply.form.title = "Unused Invite Codes"
627				reply.form.instructions =
628					"Each of these codes is single use and gives the person using " \
629					"them a free month of JMP service. You will receive credit " \
630					"equivalent to one month of free service if they later become " \
631					"a paying customer."
632				FormTable.new(
633					invites.map { |i| [i] },
634					code: "Invite Code"
635				).add_to_form(reply.form)
636			end
637		end
638	end
639}.register(self).then(&CommandList.method(:register))
640
641Command.new(
642	"reset sip account",
643	"Create or Reset SIP Account",
644	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
645) {
646	Command.customer.then do |customer|
647		sip_account = customer.reset_sip_account
648		Command.reply { |reply|
649			reply.allowed_actions = [:next]
650			form = sip_account.form
651			form.type = :form
652			form.fields += [{
653				type: :boolean, var: "change_fwd",
654				label: "Should inbound calls forward to this SIP account?"
655			}]
656			reply.command << form
657		}.then do |fwd|
658			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
659				Command.execution.customer_repo.put_fwd(
660					customer,
661					customer.fwd.with(uri: sip_account.uri)
662				).then { Command.finish("Inbound calls will now forward to SIP.") }
663			else
664				Command.finish
665			end
666		end
667	end
668}.register(self).then(&CommandList.method(:register))
669
670Command.new(
671	"lnp",
672	"Port in your number from another carrier",
673	list_for: ->(**) { true }
674) {
675	using FormToH
676
677	EMPromise.all([
678		Command.customer,
679		Command.reply do |reply|
680			reply.allowed_actions = [:next]
681			reply.command << FormTemplate.render("lnp")
682		end
683	]).then do |(customer, iq)|
684		order = PortInOrder.new(iq.form.to_h.slice(
685			"BillingTelephoneNumber", "Subscriber", "WirelessInfo"
686		).merge("CustomerOrderId" => customer.customer_id))
687		order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
688		url = "https://dashboard.bandwidth.com/portal/r/a/" \
689		      "#{CONFIG[:creds][:account]}/orders/portIn/#{order_id}"
690		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
691		BLATHER.say(
692			CONFIG[:notify_admin],
693			"New port-in request for #{customer.customer_id}: #{url}",
694			:groupchat
695		)
696		Command.finish(
697			"Your port-in request has been accepted, " \
698			"support will contact you with next steps"
699		)
700	end
701}.register(self).then(&CommandList.method(:register))
702
703Command.new(
704	"customer info",
705	"Show Customer Info",
706	list_for: ->(customer: nil, **) { customer&.admin? }
707) {
708	Command.customer.then do |customer|
709		raise AuthError, "You are not an admin" unless customer&.admin?
710
711		Command.reply { |reply|
712			reply.allowed_actions = [:next]
713			reply.command << FormTemplate.render("customer_picker")
714		}.then { |response|
715			CustomerInfoForm.new.find_customer(response)
716		}.then do |target_customer|
717			target_customer.admin_info.then do |info|
718				Command.finish do |reply|
719					reply.command << info.form
720				end
721			end
722		end
723	end
724}.register(self).then(&CommandList.method(:register))
725
726def reply_with_note(iq, text, type: :info)
727	reply = iq.reply
728	reply.status = :completed
729	reply.note_type = type
730	reply.note_text = text
731
732	self << reply
733end
734
735Command.new(
736	"web-register",
737	"Initiate Register from Web",
738	list_for: lambda { |from_jid: nil, **|
739		from_jid&.stripped.to_s == CONFIG[:web_register][:from]
740	}
741) {
742	if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
743		next EMPromise.reject(
744			Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
745		)
746	end
747
748	Command.reply { |reply|
749		reply.command << FormTemplate.render("web_register")
750	}.then do |iq|
751		jid = iq.form.field("jid")&.value.to_s.strip
752		tel = iq.form.field("tel")&.value.to_s.strip
753		if jid !~ /\./
754			Command.finish("The Jabber ID you entered was not valid.", type: :error)
755		elsif tel !~ /\A\+\d+\Z/
756			Command.finish("Invalid telephone number", type: :error)
757		else
758			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
759				cmd.to = CONFIG[:web_register][:to]
760				cmd.node = "push-register"
761				cmd.form.fields = [{ var: "to", value: jid }]
762				cmd.form.type = "submit"
763			}).then { |result|
764				TEL_SELECTIONS.set(result.form.field("from")&.value.to_s.strip, tel)
765			}.then { Command.finish }
766		end
767	end
768}.register(self).then(&CommandList.method(:register))
769
770command sessionid: /./ do |iq|
771	COMMAND_MANAGER.fulfill(iq)
772end
773
774iq type: [:result, :error] do |iq|
775	IQ_MANAGER.fulfill(iq)
776end
777
778iq type: [:get, :set] do |iq|
779	StatsD.increment("unknown_iq")
780
781	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
782end