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