sgx-catapult.rb

  1#!/usr/bin/env ruby
  2#
  3# Copyright (C) 2017  Denver Gingerich <denver@ossguy.com>
  4#
  5# This file is part of sgx-catapult.
  6#
  7# sgx-catapult is free software: you can redistribute it and/or modify it under
  8# the terms of the GNU Affero General Public License as published by the Free
  9# Software Foundation, either version 3 of the License, or (at your option) any
 10# later version.
 11#
 12# sgx-catapult is distributed in the hope that it will be useful, but WITHOUT
 13# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 14# FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 15# details.
 16#
 17# You should have received a copy of the GNU Affero General Public License along
 18# with sgx-catapult.  If not, see <http://www.gnu.org/licenses/>.
 19
 20require 'blather/client/dsl'
 21require 'json'
 22require 'net/http'
 23require 'redis/connection/hiredis'
 24require 'uri'
 25
 26if ARGV.size != 6 then
 27	puts "Usage: sgx-catapult.rb <component_jid> <component_password> " +
 28		"<server_hostname> <server_port> <redis_hostname> <redis_port>"
 29	exit 0
 30end
 31
 32module SGXcatapult
 33	extend Blather::DSL
 34
 35	def self.run
 36		client.run
 37	end
 38
 39	def self.error_msg(orig, query_node, type, name, text = nil)
 40		orig.add_child(query_node)
 41		orig.type = :error
 42
 43		error = Nokogiri::XML::Node.new 'error', orig.document
 44		error['type'] = type
 45		orig.add_child(error)
 46
 47		suberr = Nokogiri::XML::Node.new name, orig.document
 48		suberr['xmlns'] = 'urn:ietf:params:xml:ns:xmpp-stanzas'
 49		error.add_child(suberr)
 50
 51		# TODO: add some explanatory xml:lang='en' text (see text param)
 52		puts "RESPONSE3: #{orig.inspect}"
 53		return orig
 54	end
 55
 56	setup ARGV[0], ARGV[1], ARGV[2], ARGV[3]
 57
 58	message :chat?, :body do |m|
 59		begin
 60			puts "#{m.from.to_s} -> #{m.to.to_s} #{m.body}"
 61			msg = Blather::Stanza::Message.new(m.from, 'thx for "' +
 62				m.body + '"')
 63			msg.from = m.to
 64			write_to_stream msg
 65		rescue => e
 66			# TODO: do something better with this info
 67			say m.from, e.inspect
 68		end
 69	end
 70
 71	iq '/iq/ns:query', :ns =>
 72		'http://jabber.org/protocol/disco#items' do |i, xpath_result|
 73
 74		write_to_stream i.reply
 75	end
 76
 77	iq '/iq/ns:query', :ns =>
 78		'http://jabber.org/protocol/disco#info' do |i, xpath_result|
 79
 80		msg = i.reply
 81		msg.identities = [{:name =>
 82			'Soprani.ca Gateway to XMPP - Catapult',
 83			:type => 'sms-ctplt', :category => 'gateway'}]
 84		msg.features = ["jabber:iq:register",
 85			"jabber:iq:gateway", "jabber:iq:private",
 86			"http://jabber.org/protocol/disco#info",
 87			"http://jabber.org/protocol/commands",
 88			"http://jabber.org/protocol/muc"]
 89		write_to_stream msg
 90	end
 91
 92	iq '/iq/ns:query', :ns => 'jabber:iq:register' do |i, qn|
 93		puts "IQ: #{i.inspect}"
 94
 95		if i.type == :set
 96			xn = qn.children.find { |v| v.element_name == "x" }
 97
 98			user_id = ''
 99			api_token = ''
100			api_secret = ''
101			phone_num = ''
102
103			if xn.nil?
104				user_id = qn.children.find {
105					|v| v.element_name == "nick" }
106				api_token = qn.children.find {
107					|v| v.element_name == "username" }
108				api_secret = qn.children.find {
109					|v| v.element_name == "password" }
110				phone_num = qn.children.find {
111					|v| v.element_name == "phone" }
112			else
113				for field in xn.children
114					if field.element_name == "field"
115						val = field.children.find { |v|
116						v.element_name == "value" }
117
118						case field['var']
119						when 'nick'
120							user_id = val.text
121						when 'username'
122							api_token = val.text
123						when 'password'
124							api_secret = val.text
125						when 'phone'
126							phone_num = val.text
127						else
128							# TODO: error
129							puts "?: " +field['var']
130						end
131					end
132				end
133			end
134
135			uri = URI.parse('https://api.catapult.inetwork.com')
136			http = Net::HTTP.new(uri.host, uri.port)
137			http.use_ssl = true
138			request = Net::HTTP::Get.new('/v1/users/' + user_id +
139				'/phoneNumbers/' + phone_num)
140			request.basic_auth api_token, api_secret
141			response = http.request(request)
142
143			puts 'API response: ' + response.to_s + ' with code ' +
144				response.code + ', body "' + response.body + '"'
145
146			if response.code == '200'
147				params = JSON.parse response.body
148				if params['numberState'] == 'enabled'
149					bare_jid = i.from.to_s.split('/')[0]
150					cred_key = "catapult_cred-" + bare_jid
151
152					# TODO: pre-validate ARGV[5] is integer
153					conn = Hiredis::Connection.new
154					conn.connect(ARGV[4], ARGV[5].to_i)
155
156					conn.write ["EXISTS", cred_key]
157					if conn.read == 1
158						# TODO: add txt re already exist
159						write_to_stream error_msg(
160							i.reply, qn, :cancel,
161							'conflict')
162						next
163					end
164
165					conn.write ["RPUSH",cred_key,user_id]
166					conn.write ["RPUSH",cred_key,api_token]
167					conn.write ["RPUSH",cred_key,api_secret]
168					conn.write ["RPUSH",cred_key,phone_num]
169
170					for n in 1..4 do
171						# TODO: catch/relay RuntimeError
172						result = conn.read
173						if result < 1
174							write_to_stream(
175							error_msg(
176							i.reply, qn, :cancel,
177							'internal-server-error')
178							)
179							next
180						end
181					end
182
183					write_to_stream i.reply
184				else
185					# TODO: add text re number disabled
186					write_to_stream error_msg(i.reply, qn,
187						:modify, 'not-acceptable')
188				end
189			elsif response.code == '401'
190				# TODO: add text re bad credentials
191				write_to_stream error_msg(i.reply, qn, :auth,
192					'not-authorized')
193			elsif response.code == '404'
194				# TODO: add text re number not found or disabled
195				write_to_stream error_msg(i.reply, qn, :cancel,
196					'item-not-found')
197			else
198				# TODO: add text re misc error, and mention code
199				write_to_stream error_msg(i.reply, qn, :modify,
200					'not-acceptable')
201			end
202
203		elsif i.type == :get
204			orig = i.reply
205
206			msg = Nokogiri::XML::Node.new 'query',orig.document
207			msg['xmlns'] = 'jabber:iq:register'
208			n1 = Nokogiri::XML::Node.new 'instructions',msg.document
209			n1.content= "Enter the information from your Account " +
210				"page as well as the Phone Number\nin your " +
211				"account you want to use (ie. '+12345678901')" +
212				".\nUser Id is nick, API Token is username, " +
213				"API Secret is password, Phone Number is phone"+
214				".\n\nThe source code for this gateway is at " +
215				"https://github.com/ossguy/sgx-catapult ." +
216				"\nCopyright (C) 2017  Denver Gingerich, " +
217				"licensed under AGPLv3+."
218			n2 = Nokogiri::XML::Node.new 'nick',msg.document
219			n3 = Nokogiri::XML::Node.new 'username',msg.document
220			n4 = Nokogiri::XML::Node.new 'password',msg.document
221			n5 = Nokogiri::XML::Node.new 'phone',msg.document
222			msg.add_child(n1)
223			msg.add_child(n2)
224			msg.add_child(n3)
225			msg.add_child(n4)
226			msg.add_child(n5)
227
228			x = Blather::Stanza::X.new :form, [
229				{:required => true, :type => :"text-single",
230				:label => 'User Id', :var => 'nick'},
231				{:required => true, :type => :"text-single",
232				:label => 'API Token', :var => 'username'},
233				{:required => true, :type => :"text-private",
234				:label => 'API Secret', :var => 'password'},
235				{:required => true, :type => :"text-single",
236				:label => 'Phone Number', :var => 'phone'}
237			]
238			x.title= 'Register for ' +
239				'Soprani.ca Gateway to XMPP - Catapult'
240			x.instructions= "Enter the details from your Account " +
241				"page as well as the Phone Number\nin your " +
242				"account you want to use (ie. '+12345678901')" +
243				".\n\nThe source code for this gateway is at " +
244				"https://github.com/ossguy/sgx-catapult ." +
245				"\nCopyright (C) 2017  Denver Gingerich, " +
246				"licensed under AGPLv3+."
247			msg.add_child(x)
248
249			orig.add_child(msg)
250			puts "RESPONSE2: #{orig.inspect}"
251			write_to_stream orig
252			puts "SENT"
253		end
254	end
255
256	subscription(:request?) do |s|
257		# TODO: are these the best to return?  really need '!' here?
258		#write_to_stream s.approve!
259		#write_to_stream s.request!
260	end
261end
262
263[:INT, :TERM].each do |sig|
264	trap(sig) {
265		puts 'Shutting down gateway...'
266		SGXcatapult.shutdown
267		puts 'Gateway has terminated.'
268
269		EM.stop
270	}
271end
272
273EM.run do
274	SGXcatapult.run
275end