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