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