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 repo = CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
200 repo.find(notify[:extra]).then do |customer|
201 DbNotification.for(notify, customer, repo)
202 end
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
310UNBILLED_TARGETS = Set.new(CONFIG[:unbilled_targets])
311def billable_message(m)
312 b = m.body
313 !UNBILLED_TARGETS.member?(m.to.node) && \
314 (b && !b.empty? || m.find("ns:x", ns: OOB.registered_ns).first)
315end
316
317class OverLimit < StandardError
318 def initialize(customer, usage)
319 super("Please contact support")
320 @customer = customer
321 @usage = usage
322 end
323
324 def notify_admin
325 ExpiringLock.new("jmp_usage_notify-#{@customer.customer_id}").with do
326 BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
327 BLATHER.say(
328 CONFIG[:notify_admin], "#{@customer.customer_id} has used " \
329 "#{@usage} messages today", :groupchat
330 )
331 end
332 end
333end
334
335class CustomerExpired < StandardError; end
336
337message do |m|
338 StatsD.increment("message")
339
340 sentry_hub = new_sentry_hub(m, name: "message")
341 today = Time.now.utc.to_date
342 CustomerRepo.new(set_user: sentry_hub.current_scope.method(:set_user))
343 .find_by_jid(m.from.stripped).then { |customer|
344 next customer.stanza_from(m) unless billable_message(m)
345
346 if customer.plan_name && !customer.active?
347 raise CustomerExpired, "Your account is expired, please top up"
348 end
349
350 EMPromise.all([
351 TrustLevelRepo.new.find(customer),
352 customer.message_usage((today..today))
353 ]).then { |(tl, usage)|
354 raise OverLimit.new(customer, usage) unless tl.send_message?(usage)
355 }.then do
356 EMPromise.all([
357 customer.incr_message_usage, customer.stanza_from(m)
358 ])
359 end
360 }.catch_only(OverLimit) { |e|
361 e.notify_admin
362 BLATHER << m.as_error("policy-violation", :wait, e.message)
363 }.catch_only(CustomerRepo::NotFound, CustomerExpired) { |e|
364 BLATHER << m.as_error("forbidden", :auth, e.message)
365 }.catch { |e| panic(e, sentry_hub) }
366end
367
368message :error? do |m|
369 StatsD.increment("message_error")
370
371 LOG.error "MESSAGE ERROR", stanza: m
372end
373
374IQ_MANAGER = SessionManager.new(self, :id)
375COMMAND_MANAGER = SessionManager.new(
376 self,
377 :sessionid,
378 timeout: 60 * 60,
379 error_if: ->(s) { s.cancel? }
380)
381
382disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
383 reply = iq.reply
384 reply.identities = [{
385 name: "JMP.chat",
386 type: "sms",
387 category: "gateway"
388 }]
389 reply.features = [
390 "http://jabber.org/protocol/disco#info",
391 "http://jabber.org/protocol/commands"
392 ]
393 form = Blather::Stanza::X.find_or_create(reply.query)
394 form.type = "result"
395 form.fields = [
396 {
397 var: "FORM_TYPE",
398 type: "hidden",
399 value: "http://jabber.org/network/serverinfo"
400 }
401 ] + CONFIG[:xep0157]
402 self << reply
403end
404
405disco_info do |iq|
406 reply = iq.reply
407 reply.identities = [{
408 name: "JMP.chat",
409 type: "sms",
410 category: "client"
411 }]
412 reply.features = [
413 "urn:xmpp:receipts"
414 ]
415 self << reply
416end
417
418disco_items node: "http://jabber.org/protocol/commands" do |iq|
419 StatsD.increment("command_list")
420
421 sentry_hub = new_sentry_hub(iq, name: iq.node)
422 reply = iq.reply
423 reply.node = "http://jabber.org/protocol/commands"
424
425 CustomerRepo.new(
426 sgx_repo: Bwmsgsv2Repo.new,
427 set_user: sentry_hub.current_scope.method(:set_user)
428 ).find_by_jid(
429 iq.from.stripped
430 ).catch {
431 nil
432 }.then { |customer|
433 CommandList.for(customer, iq.from)
434 }.then { |list|
435 reply.items = list.map { |item|
436 Blather::Stanza::DiscoItems::Item.new(
437 iq.to,
438 item[:node],
439 item[:name]
440 )
441 }
442 self << reply
443 }.catch { |e| panic(e, sentry_hub) }
444end
445
446iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
447 StatsD.increment("extdisco")
448
449 reply = iq.reply
450 reply << Nokogiri::XML::Builder.new {
451 services(xmlns: "urn:xmpp:extdisco:2") do
452 service(
453 type: "sip",
454 host: CONFIG[:sip_host]
455 )
456 end
457 }.doc.root
458
459 self << reply
460end
461
462Command.new(
463 "jabber:iq:register",
464 "Register",
465 list_for: ->(*) { true },
466 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
467) {
468 Command.customer.catch_only(CustomerRepo::NotFound) {
469 Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
470 Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
471 }.then { |customer|
472 Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
473 Registration.for(customer, TEL_SELECTIONS).then(&:write)
474 }.then {
475 StatsD.increment("registration.completed")
476 }.catch_only(Command::Execution::FinalStanza) do |e|
477 StatsD.increment("registration.completed")
478 EMPromise.reject(e)
479 end
480}.register(self).then(&CommandList.method(:register))
481
482Command.new(
483 "info",
484 "Show Account Info",
485 list_for: ->(*) { true },
486 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
487) {
488 Command.customer.then(&:info).then do |info|
489 Command.finish do |reply|
490 reply.command << info.form
491 end
492 end
493}.register(self).then(&CommandList.method(:register))
494
495Command.new(
496 "usage",
497 "Show Monthly Usage"
498) {
499 report_for = (Date.today..(Date.today << 1))
500
501 Command.customer.then { |customer|
502 customer.usage_report(report_for)
503 }.then do |usage_report|
504 Command.finish do |reply|
505 reply.command << usage_report.form
506 end
507 end
508}.register(self).then(&CommandList.method(:register))
509
510Command.new(
511 "transactions",
512 "Show Transactions",
513 list_for: ->(customer:, **) { !!customer&.currency }
514) {
515 Command.customer.then(&:transactions).then do |txs|
516 Command.finish do |reply|
517 reply.command << FormTemplate.render("transactions", transactions: txs)
518 end
519 end
520}.register(self).then(&CommandList.method(:register))
521
522Command.new(
523 "configure calls",
524 "Configure Calls",
525 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
526) {
527 Command.customer.then do |customer|
528 cc_form = ConfigureCallsForm.new(customer)
529 Command.reply { |reply|
530 reply.allowed_actions = [:next]
531 reply.command << cc_form.render
532 }.then { |iq|
533 EMPromise.all(cc_form.parse(iq.form).map { |k, v|
534 Command.execution.customer_repo.public_send("put_#{k}", customer, v)
535 })
536 }.then { Command.finish("Configuration saved!") }
537 end
538}.register(self).then(&CommandList.method(:register))
539
540Command.new(
541 "ogm",
542 "Record Voicemail Greeting",
543 list_for: ->(fwd: nil, **) { !!fwd },
544 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
545) {
546 Command.customer.then do |customer|
547 customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
548 cc.from = customer.registered?.phone
549 cc.application_id = CONFIG[:sip][:app]
550 cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
551 "customer_id=#{customer.customer_id}"
552 end
553 Command.finish("You will now receive a call.")
554 end
555}.register(self).then(&CommandList.method(:register))
556
557Command.new(
558 "migrate billing",
559 "Switch from PayPal or expired trial to new billing",
560 list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
561 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
562) {
563 EMPromise.all([
564 Command.customer,
565 Command.reply do |reply|
566 reply.allowed_actions = [:next]
567 reply.command << FormTemplate.render("migrate_billing")
568 end
569 ]).then do |(customer, iq)|
570 Registration::Payment.for(
571 iq, customer, customer.registered?.phone,
572 final_message: PaypalDone::MESSAGE,
573 finish: PaypalDone
574 ).then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
575 BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
576 BLATHER.say(
577 CONFIG[:notify_admin],
578 "#{customer.customer_id} migrated to #{customer.currency}",
579 :groupchat
580 )
581 EMPromise.reject(s)
582 end
583 end
584}.register(self).then(&CommandList.method(:register))
585
586Command.new(
587 "credit cards",
588 "Credit Card Settings and Management"
589) {
590 Command.customer.then do |customer|
591 url = CONFIG[:credit_card_url].call(
592 customer.jid.to_s.gsub("\\", "%5C"),
593 customer.customer_id
594 )
595 desc = "Manage credits cards and settings"
596 Command.finish("#{desc}: #{url}") do |reply|
597 oob = OOB.find_or_create(reply.command)
598 oob.url = url
599 oob.desc = desc
600 end
601 end
602}.register(self).then(&CommandList.method(:register))
603
604Command.new(
605 "top up",
606 "Buy Account Credit by Credit Card",
607 list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
608 format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
609) {
610 Command.customer.then { |customer|
611 BuyAccountCreditForm.for(customer).then do |credit_form|
612 Command.reply { |reply|
613 reply.allowed_actions = [:complete]
614 credit_form.add_to_form(reply.form)
615 }.then do |iq|
616 Transaction.sale(customer, **credit_form.parse(iq.form))
617 end
618 end
619 }.then { |transaction|
620 transaction.insert.then do
621 Command.finish("#{transaction} added to your account balance.")
622 end
623 }.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
624 Command.finish(e.message, type: :error)
625 end
626}.register(self).then(&CommandList.method(:register))
627
628Command.new(
629 "alt top up",
630 "Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
631 list_for: ->(customer:, **) { !!customer&.currency }
632) {
633 Command.customer.then { |customer|
634 EMPromise.all([AltTopUpForm.for(customer), customer])
635 }.then do |(alt_form, customer)|
636 Command.reply { |reply|
637 reply.allowed_actions = [:complete]
638 reply.command << alt_form.form
639 }.then do |iq|
640 AddBitcoinAddress.for(iq, alt_form, customer).write
641 end
642 end
643}.register(self).then(&CommandList.method(:register))
644
645Command.new(
646 "plan settings",
647 "Manage your plan, including overage limits",
648 list_for: ->(customer:, **) { !!customer&.currency }
649) {
650 Command.customer.then do |customer|
651 Command.reply { |reply|
652 reply.allowed_actions = [:next]
653 reply.command << FormTemplate.render("plan_settings", customer: customer)
654 }.then { |iq|
655 Command.execution.customer_repo.put_monthly_overage_limit(
656 customer,
657 iq.form.field("monthly_overage_limit")&.value.to_i
658 )
659 }.then { Command.finish("Configuration saved!") }
660 end
661}.register(self).then(&CommandList.method(:register))
662
663Command.new(
664 "referral codes",
665 "Refer a friend for free credit"
666) {
667 Command.customer.then(&:unused_invites).then do |invites|
668 if invites.empty?
669 Command.finish("You have no more invites right now, try again later.")
670 else
671 Command.finish do |reply|
672 reply.form.type = :result
673 reply.form.title = "Unused Invite Codes"
674 reply.form.instructions =
675 "Each of these codes is single use and gives the person using " \
676 "them a free month of JMP service. You will receive credit " \
677 "equivalent to one month of free service if they later become " \
678 "a paying customer."
679 FormTable.new(
680 invites.map { |i| [i] },
681 code: "Invite Code"
682 ).add_to_form(reply.form)
683 end
684 end
685 end
686}.register(self).then(&CommandList.method(:register))
687
688Command.new(
689 "reset sip account",
690 "Create or Reset SIP Account",
691 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
692) {
693 Command.customer.then do |customer|
694 sip_account = customer.reset_sip_account
695 Command.reply { |reply|
696 reply.allowed_actions = [:next]
697 form = sip_account.form
698 form.type = :form
699 form.fields += [{
700 type: :boolean, var: "change_fwd",
701 label: "Should inbound calls forward to this SIP account?"
702 }]
703 reply.command << form
704 }.then do |fwd|
705 if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
706 Command.execution.customer_repo.put_fwd(
707 customer,
708 customer.fwd.with(uri: sip_account.uri)
709 ).then { Command.finish("Inbound calls will now forward to SIP.") }
710 else
711 Command.finish
712 end
713 end
714 end
715}.register(self).then(&CommandList.method(:register))
716
717Command.new(
718 "lnp",
719 "Port in your number from another carrier",
720 list_for: ->(**) { true }
721) {
722 using FormToH
723
724 EMPromise.all([
725 Command.customer,
726 Command.reply do |reply|
727 reply.allowed_actions = [:next]
728 reply.command << FormTemplate.render("lnp")
729 end
730 ]).then do |(customer, iq)|
731 order = PortInOrder.new(iq.form.to_h.slice(
732 "BillingTelephoneNumber", "Subscriber", "WirelessInfo"
733 ).merge("CustomerOrderId" => customer.customer_id))
734 order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
735 url = "https://dashboard.bandwidth.com/portal/r/a/" \
736 "#{CONFIG[:creds][:account]}/orders/portIn/#{order_id}"
737 BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
738 BLATHER.say(
739 CONFIG[:notify_admin],
740 "New port-in request for #{customer.customer_id}: #{url}",
741 :groupchat
742 )
743 Command.finish(
744 "Your port-in request has been accepted, " \
745 "support will contact you with next steps"
746 )
747 end
748}.register(self).then(&CommandList.method(:register))
749
750Command.new(
751 "customer info",
752 "Show Customer Info",
753 list_for: ->(customer: nil, **) { customer&.admin? }
754) {
755 Command.customer.then do |customer|
756 raise AuthError, "You are not an admin" unless customer&.admin?
757
758 customer_repo = CustomerRepo.new(
759 sgx_repo: Bwmsgsv2Repo.new,
760 bandwidth_tn_repo: EmptyRepo.new # No CNAM in admin
761 )
762
763 Command.reply { |reply|
764 reply.allowed_actions = [:next]
765 reply.command << FormTemplate.render("customer_picker")
766 }.then { |response|
767 CustomerInfoForm.new(customer_repo).find_customer(response)
768 }.then do |target_customer|
769 AdminCommand.new(target_customer, customer_repo).start
770 end
771 end
772}.register(self).then(&CommandList.method(:register))
773
774def reply_with_note(iq, text, type: :info)
775 reply = iq.reply
776 reply.status = :completed
777 reply.note_type = type
778 reply.note_text = text
779
780 self << reply
781end
782
783Command.new(
784 "https://ns.cheogram.com/sgx/jid-switch",
785 "Change JID",
786 list_for: ->(customer: nil, **) { customer },
787 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
788) {
789 Command.customer.then { |customer|
790 Command.reply { |reply|
791 reply.command << FormTemplate.render("jid_switch")
792 }.then { |response|
793 new_jid = response.form.field("jid").value
794 repo = Command.execution.customer_repo
795 repo.find_by_jid(new_jid)
796 .catch_only(CustomerRepo::NotFound) { nil }
797 .then { |cust|
798 next EMPromise.reject("Customer Already Exists") if cust
799
800 repo.change_jid(customer, new_jid)
801 }
802 }.then {
803 StatsD.increment("changejid.completed")
804 Command.finish { |reply|
805 reply.note_type = :info
806 reply.note_text = "Customer JID Changed"
807 }
808 }
809 }
810}.register(self).then(&CommandList.method(:register))
811
812Command.new(
813 "web-register",
814 "Initiate Register from Web",
815 list_for: lambda { |from_jid: nil, **|
816 from_jid&.stripped.to_s == CONFIG[:web_register][:from]
817 }
818) {
819 if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
820 next EMPromise.reject(
821 Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
822 )
823 end
824
825 Command.reply { |reply|
826 reply.command << FormTemplate.render("web_register")
827 }.then do |iq|
828 jid = iq.form.field("jid")&.value.to_s.strip
829 tel = iq.form.field("tel")&.value.to_s.strip
830 if jid !~ /\./
831 Command.finish("The Jabber ID you entered was not valid.", type: :error)
832 elsif tel !~ /\A\+\d+\Z/
833 Command.finish("Invalid telephone number", type: :error)
834 else
835 IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
836 cmd.to = CONFIG[:web_register][:to]
837 cmd.node = "push-register"
838 cmd.form.fields = [{ var: "to", value: jid }]
839 cmd.form.type = "submit"
840 }).then { |result|
841 TEL_SELECTIONS.set(result.form.field("from")&.value.to_s.strip, tel)
842 }.then { Command.finish }
843 end
844 end
845}.register(self).then(&CommandList.method(:register))
846
847command sessionid: /./ do |iq|
848 COMMAND_MANAGER.fulfill(iq)
849end
850
851iq type: [:result, :error] do |iq|
852 IQ_MANAGER.fulfill(iq)
853end
854
855iq type: [:get, :set] do |iq|
856 StatsD.increment("unknown_iq")
857
858 self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
859end