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