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