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