2019-04-06 08:23:14 +00:00
#############################
2019-04-06 07:29:48 +00:00
### Some constants #########
2019-04-09 06:42:42 +00:00
:: HELP_MESSAGE = ' Unknown command .
/ login <telegram_login> — Connect to Telegram network
/ code 12345 — Enter confirmation code
/ password secret — Enter 2FA password
2019-04-13 14:42:56 +00:00
/ connect — Connect to Telegram network if have active session
2019-04-09 06:42:42 +00:00
/ disconnect — Disconnect from Telegram network
/ logout — Disconnect from Telegram network and forget session
2019-05-04 20:17:29 +00:00
/ sessions — Shows current active sessions (available for admins)
/ debug — Shows some debug information (available for admins)
/ restart — Reset Zhabogram (available for admins)
2019-04-09 06:42:42 +00:00
'
2019-04-06 08:23:14 +00:00
#############################
2019-04-06 07:29:48 +00:00
2019-04-06 06:12:54 +00:00
#############################
## XMPP Transport Class #####
#############################
class XMPPComponent
2019-04-07 11:58:07 +00:00
2019-04-06 08:23:14 +00:00
# init class and set logger #
2019-04-07 11:58:07 +00:00
def initialize ( params )
2019-04-09 06:42:42 +00:00
@@loglevel = params [ 'loglevel' ] || Logger :: DEBUG
@logger = Logger . new ( STDOUT ) ; @logger . level = @@loglevel ; @logger . progname = '[XMPPComponent]'
2019-05-04 20:17:29 +00:00
@config = { host : params [ " host " ] || 'localhost' , port : params [ " port " ] || 8899 , jid : params [ " jid " ] || 'tlgrm.localhost' , secret : params [ 'password' ] || '' , admins : params [ 'admins' ] || [ ] , debug : params [ 'debug' ] || false } # default config
2019-04-07 11:58:07 +00:00
@sessions = { }
@db = SQLite3 :: Database . new ( params [ 'db_path' ] || 'users.db' )
2019-05-04 20:17:29 +00:00
@db . execute ( " CREATE TABLE IF NOT EXISTS users(jid varchar(256), login varchar(256), PRIMARY KEY(jid) ); " )
2019-04-07 11:58:07 +00:00
@db . results_as_hash = true
end
2019-05-04 20:17:29 +00:00
# load sessions from db #
2019-04-07 11:58:07 +00:00
def load_db ( jid = nil ) # load
2019-04-09 06:42:42 +00:00
@logger . info " Initializing database.. "
2019-04-07 11:58:07 +00:00
query = ( jid . nil? ) ? " SELECT * FROM users " : " SELECT * FROM users where jid = '%s'; " % jid
2019-05-04 20:17:29 +00:00
@logger . debug ( query )
@db . execute ( query ) do | session | @sessions [ session [ 'jid' ] ] = TelegramClient . new ( self , session [ 'jid' ] , session [ 'login' ] ) end
2019-04-06 07:29:48 +00:00
end
2019-05-04 20:17:29 +00:00
# store session to db #
2019-04-07 11:58:07 +00:00
def update_db ( jid , delete = false ) # write
return if not @sessions . key? jid
2019-04-09 06:42:42 +00:00
@logger . info " Writing database [%s].. " % jid . to_s
2019-05-04 20:17:29 +00:00
query = ( delete ) ? " DELETE FROM users where jid = '%s'; " % jid . to_s : " INSERT OR REPLACE INTO users(jid, login) VALUES('%s', '%s'); " % [ jid . to_s , @sessions [ jid ] . login . to_s ]
2019-04-07 11:58:07 +00:00
@logger . debug query
@db . execute ( query )
end
2019-05-04 20:17:29 +00:00
# connecting to XMPP server #
2019-04-07 11:58:07 +00:00
def connect ( ) # :jid => transport_jid, :host => xmpp_server, :port => xmpp_component_port, :secret => xmpp_component_secret
2019-04-06 07:29:48 +00:00
@logger . info " Connecting.. "
2019-04-06 06:12:54 +00:00
begin
2019-05-04 20:17:29 +00:00
Jabber :: debug = @config [ :debug ]
2019-04-07 11:58:07 +00:00
@@transport = Jabber :: Component . new ( @config [ :jid ] )
@@transport . connect ( @config [ :host ] , @config [ :port ] )
@@transport . auth ( @config [ :secret ] )
2019-04-06 06:12:54 +00:00
@@transport . add_message_callback do | msg | msg . first_element_text ( 'body' ) ? self . message_handler ( msg ) : nil end
2019-04-07 11:58:07 +00:00
@@transport . add_presence_callback do | presence | self . presence_handler ( presence ) end
2019-04-13 14:42:56 +00:00
@@transport . add_iq_callback do | iq | self . iq_handler ( iq ) end
2019-04-16 03:45:56 +00:00
@@transport . on_exception do | exception , stream , state | self . survive ( exception , stream , state ) end
2019-04-06 07:29:48 +00:00
@logger . info " Connection established "
2019-04-07 11:58:07 +00:00
self . load_db ( )
@logger . info 'Found %s sessions in database.' % @sessions . count
2019-05-04 20:17:29 +00:00
@sessions . each do | jid , session | self . presence ( jid , nil , :subscribe ) end
2019-04-06 06:12:54 +00:00
Thread . stop ( )
2019-05-04 02:40:02 +00:00
rescue Interrupt
@logger . error 'Interrupted!'
@@transport . on_exception do | exception , | end
self . disconnect ( )
return - 11
2019-04-06 06:12:54 +00:00
rescue Exception = > e
2019-04-09 06:42:42 +00:00
@logger . error 'Connection failed: %s' % e
2019-04-07 11:58:07 +00:00
@db . close
2019-05-04 20:17:29 +00:00
exit - 8
2019-04-06 06:12:54 +00:00
end
end
2019-04-06 08:23:14 +00:00
2019-05-04 02:40:02 +00:00
# transport shutdown #
def disconnect ( )
@logger . info " Closing all connections... "
@sessions . each do | jid , session | @sessions [ jid ] . disconnect ( ) end
@@transport . close ( )
end
2019-05-04 20:17:29 +00:00
# vse umrut a ya ostanus'... #
2019-04-16 03:45:56 +00:00
def survive ( exception , stream , state )
@logger . error " Stream error on :%s (%s) " % [ state . to_s , exception . to_s ]
2019-05-04 20:17:29 +00:00
@logger . info " Trying to ressurect XMPP stream.. "
2019-04-16 03:45:56 +00:00
self . connect ( )
end
2019-05-04 20:17:29 +00:00
# message to users #
def message ( to , from = nil , body = '' )
@logger . info " Sending message from <%s> to <%s> " % [ from || @@transport . jid , to ]
msg = Jabber :: Message . new
msg . from = ( from ) ? " %s@%s " % [ from , @@transport . jid . to_s ] : @@transport . jid
msg . to = to
msg . body = body
msg . type = :chat
@logger . debug msg . to_s
@@transport . send ( msg )
end
# presence update #
def presence ( to , from = nil , type = nil , show = nil , status = nil , nickname = nil , photo = nil )
@logger . debug " Presence update request from %s.. " % from . to_s
req = Jabber :: Presence . new ( )
req . from = from . nil? ? @@transport . jid : " %s@%s " % [ from , @@transport . jid ] # presence <from>
req . to = to # presence <to>
req . type = type unless type . nil? # pres. type
req . show = show unless show . nil? # presence <show>
req . status = status unless status . nil? # presence message
req . add_element ( 'nick' , { 'xmlns' = > 'http://jabber.org/protocol/nick' } ) . add_text ( nickname ) unless nickname . nil? # nickname
req . add_element ( 'x' , { 'xmlns' = > 'vcard-temp:x:update' } ) . add_element ( " photo " ) . add_text ( photo ) unless photo . nil? # nickname
@logger . debug req . to_s
@@transport . send ( req )
end
# request timezone information #
def request_tz ( jid )
@logger . debug " Request timezone from JID %s " % jid . to_s
iq = Jabber :: Iq . new
iq . type = :get
iq . to = jid
iq . from = @@transport . jid
iq . id = 'time_req_1'
iq . add_element ( " time " , { " xmlns " = > " urn:xmpp:time " } )
@logger . debug iq . to_s
@@transport . send ( iq )
end
2019-04-06 08:23:14 +00:00
#############################
#### Callback handlers #####
#############################
2019-04-06 06:12:54 +00:00
# new message to XMPP component #
def message_handler ( msg )
2019-04-15 05:03:40 +00:00
return if msg . type == :error
2019-05-05 01:09:08 +00:00
@logger . info 'Received message from <%s> to <%s>' % [ msg . from . to_s , msg . to . to_s ]
@logger . debug msg . to_s
2019-05-04 20:17:29 +00:00
if msg . to == @@transport . jid then self . process_command ( msg . from , msg . first_element_text ( 'body' ) ) ; return ; end # treat message as internal command if received as transport jid
if @sessions . key? msg . from . bare . to_s then self . request_tz ( msg . from ) if not @sessions [ msg . from . bare . to_s ] . tz_set? ; @sessions [ msg . from . bare . to_s ] . process_outgoing_msg ( msg . to . to_s . split ( '@' ) [ 0 ] . to_i , msg . first_element_text ( 'body' ) ) ; return ; end #if @sessions.key? msg.from.bare.to_s and @sessions[msg.from.bare.to_s].online? # queue message for processing session is active for jid from
2019-04-07 11:58:07 +00:00
end
2019-05-04 20:17:29 +00:00
# new presence to XMPP component #
def presence_handler ( prsnc )
2019-05-05 01:09:08 +00:00
@logger . debug " Received presence :%s from <%s> to <%s> " % [ prsnc . type . to_s , prsnc . from . to_s , prsnc . to . to_s ]
@logger . debug ( prsnc . to_s )
2019-05-04 20:17:29 +00:00
if prsnc . type == :subscribe then reply = prsnc . answer ( false ) ; reply . type = :subscribed ; @@transport . send ( reply ) ; end # send "subscribed" reply to "subscribe" presence
if prsnc . to == @@transport . jid and @sessions . key? prsnc . from . bare . to_s and prsnc . type == :unavailable then @sessions [ prsnc . from . bare . to_s ] . disconnect ( ) ; return ; end # go offline when received offline presence from jabber user
if prsnc . to == @@transport . jid and @sessions . key? prsnc . from . bare . to_s then self . request_tz ( prsnc . from ) ; @sessions [ prsnc . from . bare . to_s ] . connect ( ) ; return ; end # connect if we have session
end
# new iq (vcard/tz) request to XMPP component #
2019-04-07 11:58:07 +00:00
def iq_handler ( iq )
2019-05-05 01:09:08 +00:00
@logger . debug " Received iq :%s from <%s> to <%s> " % [ iq . type . to_s , iq . from . to_s , iq . to . to_s ]
2019-04-13 14:42:56 +00:00
@logger . debug ( iq . to_s )
2019-04-14 02:56:29 +00:00
# vcard request #
if iq . type == :get and iq . vcard and @sessions . key? iq . from . bare . to_s then
2019-05-05 01:09:08 +00:00
@logger . debug " VCard request for <%s> " % iq . to . to_s
2019-05-04 20:17:29 +00:00
fn , nickname , given , family , phone , desc , photo = @sessions [ iq . from . bare . to_s ] . get_contact_info ( iq . to . to_s . split ( '@' ) [ 0 ] . to_i )
vcard = Jabber :: Vcard :: IqVcard . new ( )
vcard [ " FN " ] = fn
vcard [ " NICKNAME " ] = nickname if nickname
vcard [ " URL " ] = " https://t.me/%s " % nickname if nickname
vcard [ " N/GIVEN " ] = given if given
vcard [ " N/FAMILY " ] = family if family
vcard [ " DESC " ] = desc if desc
vcard [ " PHOTO/TYPE " ] = 'image/jpeg' if photo
vcard [ " PHOTO/BINVAL " ] = photo if photo
if phone then ph = vcard . add_element ( " TEL " ) ; ph . add_element ( " HOME " ) ; ph . add_element ( " VOICE " ) ; ph . add_element ( " NUMBER " ) ; ph . elements [ " NUMBER " ] . text = phone ; end
2019-04-13 15:39:20 +00:00
reply = iq . answer
2019-04-13 14:42:56 +00:00
reply . type = :result
reply . elements [ " vCard " ] = vcard
2019-05-04 20:17:29 +00:00
@logger . debug reply . to_s
2019-04-14 02:56:29 +00:00
@@transport . send ( reply )
# time response #
elsif iq . type == :result and iq . elements [ " time " ] and @sessions . key? iq . from . bare . to_s then
2019-05-05 01:09:08 +00:00
@logger . debug " Timezone response from <%s> " % iq . from . to_s
2019-04-14 02:56:29 +00:00
timezone = iq . elements [ " time " ] . elements [ " tzo " ] . text
2019-05-04 20:17:29 +00:00
@sessions [ iq . from . bare . to_s ] . timezone = timezone
2019-04-14 02:56:29 +00:00
elsif iq . type == :get then
2019-05-05 01:09:08 +00:00
@logger . debug " Unknown iq type <%s> " % iq . from . to_s
2019-04-13 15:39:20 +00:00
reply = iq . answer
2019-04-13 14:42:56 +00:00
reply . type = :error
end
@@transport . send ( reply )
2019-04-06 06:12:54 +00:00
end
2019-04-06 08:23:14 +00:00
#############################
#### Command handlers #####
#############################
2019-04-06 06:12:54 +00:00
# process internal /command #
2019-05-04 20:17:29 +00:00
def process_command ( from , body )
2019-04-06 06:12:54 +00:00
case body . split [ 0 ] # /command argument = [command, argument]
2019-05-04 20:17:29 +00:00
when '/login' # create new session
2019-05-04 22:42:59 +00:00
@sessions [ from . bare . to_s ] = TelegramClient . new ( self , from . bare . to_s , body . split [ 1 ] ) if not ( @sessions . key? from . bare . to_s and @sessions [ from . bare . to_s ] . online? )
2019-05-04 20:17:29 +00:00
@sessions [ from . bare . to_s ] . connect ( )
self . request_tz ( from )
2019-04-14 02:56:29 +00:00
self . update_db ( from . bare . to_s )
2019-05-04 20:17:29 +00:00
when '/code' , '/password' # pass auth data to telegram
@sessions [ from . bare . to_s ] . process_auth ( body . split [ 0 ] , body . split [ 1 ] ) if @sessions . key? from . bare . to_s
when '/connect' # go online
2019-05-04 21:21:59 +00:00
@sessions [ from . bare . to_s ] . connect ( ) if @sessions . key? from . bare . to_s
2019-05-04 20:17:29 +00:00
when '/disconnect' # go offline (without destroying a session)
2019-04-14 02:56:29 +00:00
@sessions [ from . bare . to_s ] . disconnect ( ) if @sessions . key? from . bare . to_s
2019-05-04 20:17:29 +00:00
when '/logout' # go offline and destroy session
2019-04-14 02:56:29 +00:00
@sessions [ from . bare . to_s ] . disconnect ( true ) if @sessions . key? from . bare . to_s
self . update_db ( from . bare . to_s , true )
@sessions . delete ( from . bare . to_s )
2019-05-04 20:17:29 +00:00
when '/debug' # show some debug information
return if not @config [ :admins ] . include? from . bare . to_s
GC . start
dump = ( defined? Memprof2 ) ? " /tmp/zhabogram.%s.dump " % Time . now . to_i : nil
Memprof2 . report ( out : dump ) if dump
response = " Debug information: \n \n "
response += " Running from: %s \n " % ` ps -p #{ $$ } -o lstart ` . lines . last . strip
2019-05-04 21:21:59 +00:00
response += " Sessions: %d online | %d total \n " % [ @sessions . inject ( 0 ) { | cnt , ( jid , sess ) | cnt = ( sess . online? ) ? cnt + 1 : cnt } , @sessions . count ]
2019-05-04 20:17:29 +00:00
response += " System memory used: %d KB \n " % ` ps -o rss -p #{ $$ } ` . lines . last . strip . to_i
response += " Objects memory allocated: %d bytes \n " % ` cut -d' ' -f1 #{ dump } ` . lines . map ( & :to_i ) . reduce ( 0 , :+ ) if dump
response += " \n Detailed memory info saved to %s \n " % dump if dump
response += " \n Run this transport with --profiler (depends on gem memprof2) to get detailed memory infnormation. \n " if not dump
self . message ( from . bare , nil , response )
when '/sessions' # show active sessions
return if not @config [ :admins ] . include? from . bare . to_s
response = " Active sessions list: \n \n "
@sessions . each do | jid , session | response += " JID: %s | Login: %s | Status: %s (%s) | Telegram profile: %s \n " % [ jid , session . login , ( session . online == true ) ? 'Online' : 'Offline' , session . auth_state , ( session . me ) ? session . format_username ( session . me . id ) : 'Unknown' ] end
self . message ( from . bare , nil , response )
when '/restart' # reset transport
return if not @config [ :admins ] . include? from . bare . to_s
self . message ( from . bare , nil , 'Trying to restart all active sessions and reconnect to XMPP server..' )
sleep ( 0 . 5 )
Process . kill ( " INT " , Process . pid )
2019-04-07 11:58:07 +00:00
else # unknown command -- display help #
2019-05-04 20:17:29 +00:00
self . message ( from . bare , nil , :: HELP_MESSAGE )
2019-04-06 06:12:54 +00:00
end
2019-05-04 20:17:29 +00:00
return
2019-04-06 06:12:54 +00:00
end
2019-04-06 08:23:14 +00:00
2019-05-04 20:17:29 +00:00
end