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