mirror of
https://github.com/Pardus-LiderAhenk/ahenk
synced 2024-12-23 09:52:16 +03:00
python XMPP client library migrate to sleekxmpp from slixmpp
This commit is contained in:
parent
f5fc7eafc6
commit
35bb6fefd7
11 changed files with 205 additions and 355 deletions
|
@ -20,7 +20,7 @@ from base.event.EventManager import EventManager
|
|||
from base.execution.ExecutionManager import ExecutionManager
|
||||
from base.logger.AhenkLogger import Logger
|
||||
from base.messaging.MessageResponseQueue import MessageResponseQueue
|
||||
from base.messaging.Messager import Messager
|
||||
from base.messaging.Messenger import Messenger
|
||||
from base.messaging.Messaging import Messaging
|
||||
from base.plugin.plugin_manager_factory import PluginManagerFactory
|
||||
from base.registration.Registration import Registration
|
||||
|
@ -97,16 +97,10 @@ class AhenkDeamon(BaseDaemon):
|
|||
Scope.getInstance().setExecutionManager(execution_manager)
|
||||
return execution_manager
|
||||
|
||||
def init_messager(self):
|
||||
messenger = Messager()
|
||||
messenger_thread = threading.Thread(target=messenger.connect_to_server)
|
||||
messenger_thread.start()
|
||||
|
||||
while messenger.is_connected() is False:
|
||||
time.sleep(1)
|
||||
time.sleep(5)
|
||||
|
||||
Scope.getInstance().setMessager(messenger)
|
||||
def init_messenger(self):
|
||||
messenger = Messenger()
|
||||
messenger.connect_to_server()
|
||||
Scope.getInstance().setMessenger(messenger)
|
||||
return messenger
|
||||
|
||||
def init_message_response_queue(self):
|
||||
|
@ -118,7 +112,6 @@ class AhenkDeamon(BaseDaemon):
|
|||
return responseQueue
|
||||
|
||||
def check_registration(self):
|
||||
# TODO get number of attemption
|
||||
max_attemp_number = int(System.Hardware.Network.interface_size()) * 3
|
||||
logger = Scope.getInstance().getLogger()
|
||||
try:
|
||||
|
@ -197,7 +190,7 @@ class AhenkDeamon(BaseDaemon):
|
|||
self.check_registration()
|
||||
self.logger.info('[AhenkDeamon] Ahenk is registered')
|
||||
|
||||
messager = self.init_messager()
|
||||
self.messenger = self.init_messenger()
|
||||
self.logger.info('[AhenkDeamon] Messager was set')
|
||||
|
||||
self.init_message_response_queue()
|
||||
|
@ -217,13 +210,13 @@ class AhenkDeamon(BaseDaemon):
|
|||
except Exception as e:
|
||||
self.logger.error('[AhenkDeamon] Signal handler could not set up. Error Message: {} '.format(str(e)))
|
||||
|
||||
messager.send_direct_message('test')
|
||||
self.messenger.send_direct_message('test')
|
||||
|
||||
while True:
|
||||
if messager.is_connected() is False:
|
||||
self.logger.debug('reconnecting')
|
||||
Scope.getInstance().getLogger().warning('[AhenkDeamon] Connection is lost. Ahenk is trying for reconnection')
|
||||
messager = self.init_messager()
|
||||
# if messager.is_connected() is False:
|
||||
# self.logger.debug('reconnecting')
|
||||
# Scope.getInstance().getLogger().warning('[AhenkDeamon] Connection is lost. Ahenk is trying for reconnection')
|
||||
# messager = self.init_messager()
|
||||
time.sleep(1)
|
||||
|
||||
def run_command_from_fifo(self, num, stack):
|
||||
|
@ -235,7 +228,7 @@ class AhenkDeamon(BaseDaemon):
|
|||
plugin_manager = scope.getPluginManager()
|
||||
|
||||
message_manager = scope.getMessageManager()
|
||||
messenger = scope.getMessager()
|
||||
messenger = scope.getMessenger()
|
||||
|
||||
self.logger.debug('[AhenkDeamon] Signal handled')
|
||||
self.logger.debug('[AhenkDeamon] Signal is :{}'.format(str(json_data['event'])))
|
||||
|
|
|
@ -21,7 +21,7 @@ class Scope(object):
|
|||
self.eventManager = None
|
||||
self.executionManager = None
|
||||
self.dbService = None
|
||||
self.messager = None
|
||||
self.messenger = None
|
||||
self.scheduler = None
|
||||
|
||||
@staticmethod
|
||||
|
@ -102,11 +102,11 @@ class Scope(object):
|
|||
def setDbService(self, dbService):
|
||||
self.dbService = dbService
|
||||
|
||||
def getMessager(self):
|
||||
return self.messager
|
||||
def getMessenger(self):
|
||||
return self.messenger
|
||||
|
||||
def setMessager(self, messager):
|
||||
self.messager = messager
|
||||
def setMessenger(self, messenger):
|
||||
self.messenger = messenger
|
||||
|
||||
def set_scheduler(self, scheduler):
|
||||
self.scheduler = scheduler
|
||||
|
|
|
@ -31,7 +31,7 @@ class ExecutionManager(object):
|
|||
self.config_manager = scope.getConfigurationManager()
|
||||
self.event_manager = scope.getEventManager()
|
||||
self.task_manager = scope.getTaskManager()
|
||||
self.messenger = scope.getMessager()
|
||||
self.messenger = scope.getMessenger()
|
||||
self.logger = scope.getLogger()
|
||||
self.db_service = scope.getDbService()
|
||||
self.message_manager = scope.getMessageManager()
|
||||
|
@ -101,11 +101,6 @@ class ExecutionManager(object):
|
|||
|
||||
def execute_policy(self, arg):
|
||||
|
||||
##
|
||||
scope = Scope().getInstance()
|
||||
self.messenger = scope.getMessager()
|
||||
##
|
||||
|
||||
self.logger.debug('[ExecutionManager] Updating policies...')
|
||||
policy = self.json_to_PolicyBean(json.loads(arg))
|
||||
machine_uid = self.db_service.select_one_result('registration', 'jid', 'registered=1')
|
||||
|
|
|
@ -1,139 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# Author: Volkan Şahin <volkansah.in> <bm.volkansahin@gmail.com>
|
||||
# Author: İsmail BAŞARAN <ismail.basaran@tubitak.gov.tr> <basaran.ismaill@gmail.com>
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
|
||||
import slixmpp
|
||||
|
||||
sys.path.append('../..')
|
||||
from slixmpp.exceptions import IqError, IqTimeout
|
||||
from base.Scope import Scope
|
||||
|
||||
|
||||
class AnonymousMessager(slixmpp.ClientXMPP):
|
||||
def __init__(self, message, file_path):
|
||||
# global scope of ahenk
|
||||
scope = Scope().getInstance()
|
||||
|
||||
self.logger = scope.getLogger()
|
||||
self.configuration_manager = scope.getConfigurationManager()
|
||||
self.registration = scope.getRegistration()
|
||||
self.event_manager = scope.getEventManager()
|
||||
|
||||
self.host = str(self.configuration_manager.get('CONNECTION', 'host'))
|
||||
self.service = str(self.configuration_manager.get('CONNECTION', 'servicename'))
|
||||
self.port = str(self.configuration_manager.get('CONNECTION', 'port'))
|
||||
self.receive_file_path = str(self.configuration_manager.get('CONNECTION', 'receivefileparam'))
|
||||
|
||||
slixmpp.ClientXMPP.__init__(self, self.service, None)
|
||||
|
||||
self.message = None
|
||||
self.file = None
|
||||
self.receiver = self.configuration_manager.get('CONNECTION', 'receiverjid') + '@' + self.configuration_manager.get('CONNECTION', 'servicename') + '/Smack'
|
||||
|
||||
if file_path is not None and file_path != '':
|
||||
self.file = open(file_path, 'rb')
|
||||
if message is not None:
|
||||
self.message = message
|
||||
|
||||
self.logger.debug('[MessageSender] XMPP Receiver parameters were set')
|
||||
|
||||
self.add_listeners()
|
||||
self.register_extensions()
|
||||
|
||||
def add_listeners(self):
|
||||
self.add_event_handler("session_start", self.session_start)
|
||||
self.add_event_handler("message", self.recv_direct_message)
|
||||
self.add_event_handler("socks5_connected", self.stream_opened)
|
||||
self.add_event_handler("socks5_data", self.stream_data)
|
||||
self.add_event_handler("socks5_closed", self.stream_closed)
|
||||
self.logger.debug('[MessageSender] Event handlers were added')
|
||||
|
||||
def recv_direct_message(self, msg):
|
||||
if msg['type'] in ('chat', 'normal'):
|
||||
print('ANON<---' + msg['body'])
|
||||
self.logger.debug("[MessageSender] (Anonymous) Received message: {} -> {}".format(msg['from'], msg['body']))
|
||||
self.disconnect()
|
||||
self.logger.debug('[MessageSender] (Anonymous) Disconnecting...')
|
||||
j = json.loads(str(msg['body']))
|
||||
message_type = j['type']
|
||||
self.event_manager.fireEvent(message_type, str(msg['body']))
|
||||
|
||||
@asyncio.coroutine
|
||||
def session_start(self, event):
|
||||
self.logger.debug('[MessageSender] Session was started')
|
||||
self.get_roster()
|
||||
self.send_presence()
|
||||
|
||||
if self.message is not None:
|
||||
self.send_direct_message(self.message)
|
||||
|
||||
if self.file is not None:
|
||||
self.logger.debug('[MessageSender] Sending file: {}'.format(self.file.name))
|
||||
try:
|
||||
self.logger.debug('[MessageSender] Handshaking for file transferring...')
|
||||
# Open the S5B stream in which to write to.
|
||||
proxy = yield from self['xep_0065'].handshake(self.receiver)
|
||||
# Send the entire file.
|
||||
self.logger.debug('[MessageSender] Started to streaming file...')
|
||||
while True:
|
||||
data = self.file.read(1048576)
|
||||
if not data:
|
||||
break
|
||||
yield from proxy.write(data)
|
||||
# And finally close the stream.
|
||||
proxy.transport.write_eof()
|
||||
except (IqError, IqTimeout) as e:
|
||||
self.logger.error('[MessageSender] A problem occurred while transferring file to server. Error Message: {}'.format(str(e)))
|
||||
else:
|
||||
self.logger.debug('[MessageSender] File transfer finished successfully')
|
||||
finally:
|
||||
self.file.close()
|
||||
|
||||
def stream_opened(self, sid):
|
||||
self.logger.debug('[MessageSender] Stream was opened. Stream id: ' + str(self.stream_id))
|
||||
self.file = open(self.receive_file_path + self.stream_id, 'wb')
|
||||
return self.file
|
||||
|
||||
def stream_data(self, data):
|
||||
self.logger.debug('[MessageSender] Receiving file...')
|
||||
self.file.write(data)
|
||||
|
||||
def stream_closed(self, exception):
|
||||
self.logger.debug('[MessageSender] Stream was closed')
|
||||
self.file.close()
|
||||
self.logger.debug('[MessageSender] Disconnecting...')
|
||||
self.disconnect()
|
||||
|
||||
def send_direct_message(self, msg):
|
||||
self.logger.debug('[MessageSender] Sending message: ' + msg)
|
||||
print('ANON-->' + msg)
|
||||
self.send_message(mto=self.receiver, mbody=msg, mtype='normal')
|
||||
|
||||
def connect_to_server(self): # Connect to the XMPP server and start processing XMPP stanzas.
|
||||
try:
|
||||
self.logger.debug('[MessageSender] Connecting to server...')
|
||||
self.connect((self.host, self.port))
|
||||
self.process(forever=False)
|
||||
self.logger.debug('[MessageSender] Connection were established successfully')
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.error('[MessageSender] Connection to server is failed! Error Message: {}'.format(str(e)))
|
||||
return False
|
||||
|
||||
def register_extensions(self):
|
||||
try:
|
||||
self.register_plugin('xep_0030') # Service Discovery
|
||||
self.register_plugin('xep_0045') # Multi-User Chat
|
||||
self.register_plugin('xep_0199') # XMPP Ping
|
||||
self.register_plugin('xep_0065', {'auto_accept': True}) # SOCKS5 Bytestreams
|
||||
self.register_plugin('xep_0047', {'auto_accept': True}) # In-band Bytestreams
|
||||
|
||||
self.logger.debug('[MessageSender] Extension were registered: xep_0030,xep_0045,xep_0199,xep_0065,xep_0047')
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.error('[MessageSender] Extension registration is failed! Error Message: {}'.format(str(e)))
|
||||
return False
|
86
opt/ahenk/base/messaging/AnonymousMessenger.py
Normal file
86
opt/ahenk/base/messaging/AnonymousMessenger.py
Normal file
|
@ -0,0 +1,86 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# Author: Volkan Şahin <volkansah.in> <bm.volkansahin@gmail.com>
|
||||
# Author: İsmail BAŞARAN <ismail.basaran@tubitak.gov.tr> <basaran.ismaill@gmail.com>
|
||||
import json
|
||||
import sys
|
||||
|
||||
from sleekxmpp import ClientXMPP
|
||||
|
||||
sys.path.append('../..')
|
||||
from base.Scope import Scope
|
||||
|
||||
|
||||
class AnonymousMessager(ClientXMPP):
|
||||
def __init__(self, message):
|
||||
# global scope of ahenk
|
||||
scope = Scope().getInstance()
|
||||
|
||||
self.logger = scope.getLogger()
|
||||
self.configuration_manager = scope.getConfigurationManager()
|
||||
self.registration = scope.getRegistration()
|
||||
self.event_manager = scope.getEventManager()
|
||||
|
||||
self.host = str(self.configuration_manager.get('CONNECTION', 'host'))
|
||||
self.service = str(self.configuration_manager.get('CONNECTION', 'servicename'))
|
||||
self.port = str(self.configuration_manager.get('CONNECTION', 'port'))
|
||||
self.receive_file_path = str(self.configuration_manager.get('CONNECTION', 'receivefileparam'))
|
||||
|
||||
ClientXMPP.__init__(self, self.service, None)
|
||||
|
||||
self.message = message
|
||||
self.receiver = self.configuration_manager.get('CONNECTION', 'receiverjid') + '@' + self.configuration_manager.get('CONNECTION', 'servicename') + '/' + self.configuration_manager.get('CONNECTION', 'receiverresource')
|
||||
|
||||
self.logger.debug('[AnonymousMessenger] XMPP Receiver parameters were set')
|
||||
|
||||
self.add_listeners()
|
||||
self.register_extensions()
|
||||
|
||||
def add_listeners(self):
|
||||
self.add_event_handler("session_start", self.session_start)
|
||||
self.add_event_handler("message", self.recv_direct_message)
|
||||
self.logger.debug('[AnonymousMessenger] Event handlers were added')
|
||||
|
||||
def session_start(self, event):
|
||||
self.logger.debug('[AnonymousMessenger] Session was started')
|
||||
self.get_roster()
|
||||
self.send_presence()
|
||||
|
||||
if self.message is not None:
|
||||
self.send_direct_message(self.message)
|
||||
|
||||
def register_extensions(self):
|
||||
try:
|
||||
self.register_plugin('xep_0030') # Service Discovery
|
||||
self.register_plugin('xep_0199') # XMPP Ping
|
||||
|
||||
self.logger.debug('[AnonymousMessenger] Extension were registered: xep_0030,xep_0199')
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.error('[AnonymousMessenger] Extension registration is failed! Error Message: {}'.format(str(e)))
|
||||
return False
|
||||
|
||||
def connect_to_server(self):
|
||||
try:
|
||||
self.logger.debug('[AnonymousMessenger] Connecting to server...')
|
||||
self['feature_mechanisms'].unencrypted_plain = True
|
||||
self.connect((self.host, self.port), use_tls=False)
|
||||
self.process(block=True)
|
||||
self.logger.debug('[AnonymousMessenger] Connection were established successfully')
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.error('[AnonymousMessenger] Connection to server is failed! Error Message: {}'.format(str(e)))
|
||||
return False
|
||||
|
||||
def recv_direct_message(self, msg):
|
||||
if msg['type'] in ('normal'):
|
||||
self.logger.debug('[AnonymousMessenger] ---------->Received message: {}'.format(str(msg['body'])))
|
||||
self.logger.debug('[AnonymousMessenger] Disconnecting...')
|
||||
self.disconnect()
|
||||
j = json.loads(str(msg['body']))
|
||||
message_type = j['type']
|
||||
self.event_manager.fireEvent(message_type, str(msg['body']))
|
||||
|
||||
def send_direct_message(self, msg):
|
||||
self.logger.debug('[AnonymousMessenger] <<--------Sending message: {}'.format(msg))
|
||||
self.send_message(mto=self.receiver, mbody=msg, mtype='normal')
|
|
@ -16,7 +16,7 @@ class MessageResponseQueue(threading.Thread):
|
|||
super(MessageResponseQueue, self).__init__()
|
||||
scope = Scope.getInstance()
|
||||
self.logger = scope.getLogger()
|
||||
self.messageManager = scope.getMessager()
|
||||
self.messageManager = scope.getMessenger()
|
||||
self.outQueue = outQueue
|
||||
|
||||
def run(self):
|
||||
|
|
|
@ -1,177 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# Author: Volkan Şahin <volkansah.in> <bm.volkansahin@gmail.com>
|
||||
# Author: İsmail BAŞARAN <ismail.basaran@tubitak.gov.tr> <basaran.ismaill@gmail.com>
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
import slixmpp
|
||||
|
||||
sys.path.append('../..')
|
||||
from base.Scope import Scope
|
||||
|
||||
from base.messaging.FileTransfer import FileTransfer
|
||||
|
||||
|
||||
class Messager(slixmpp.ClientXMPP):
|
||||
global loop
|
||||
|
||||
def __init__(self):
|
||||
# global scope of ahenk
|
||||
scope = Scope().getInstance()
|
||||
|
||||
self.logger = scope.getLogger()
|
||||
self.configuration_manager = scope.getConfigurationManager()
|
||||
self.event_manger = scope.getEventManager()
|
||||
self.execution_manager = scope.getExecutionManager()
|
||||
|
||||
self.my_jid = str(self.configuration_manager.get('CONNECTION', 'uid') + '@' + self.configuration_manager.get('CONNECTION', 'servicename'))
|
||||
self.my_pass = str(self.configuration_manager.get('CONNECTION', 'password'))
|
||||
|
||||
slixmpp.ClientXMPP.__init__(self, self.my_jid, self.my_pass)
|
||||
|
||||
self.file = None
|
||||
self.hostname = self.configuration_manager.get('CONNECTION', 'host')
|
||||
self.resource_name = self.configuration_manager.get('CONNECTION', 'receiverresource')
|
||||
self.receiver = self.configuration_manager.get('CONNECTION', 'receiverjid') + '@' + self.configuration_manager.get('CONNECTION', 'servicename') + '/' + self.resource_name
|
||||
self.receive_file_path = self.configuration_manager.get('CONNECTION', 'receivefileparam')
|
||||
self.logger.debug('[Messager] XMPP Messager parameters were set')
|
||||
|
||||
self.register_extensions()
|
||||
self.add_listeners()
|
||||
|
||||
def add_listeners(self):
|
||||
self.add_event_handler('session_start', self.session_start)
|
||||
self.add_event_handler('session_end', self.session_end)
|
||||
self.add_event_handler('message', self.recv_direct_message)
|
||||
|
||||
self.add_event_handler('socks5_connected', self.stream_opened)
|
||||
self.add_event_handler('socks5_data', self.stream_data)
|
||||
self.add_event_handler('socks5_closed', self.stream_closed)
|
||||
|
||||
self.add_event_handler('ibb_stream_start', self.stream_opened)
|
||||
self.add_event_handler('ibb_stream_data', self.stream_data)
|
||||
self.add_event_handler('ibb_stream_end', self.stream_closed)
|
||||
|
||||
self.logger.debug('[Messager] Event handlers were added')
|
||||
|
||||
def stream_opened(self, sid):
|
||||
self.logger.debug('[Messager] Stream was opened. Stream id: ' + str(self.stream_id))
|
||||
self.file = open(self.receive_file_path + self.stream_id, 'wb')
|
||||
return self.file
|
||||
|
||||
def stream_data(self, data):
|
||||
self.logger.debug('[Messager] Receiving file...')
|
||||
self.file.write(data)
|
||||
|
||||
def stream_closed(self, exception):
|
||||
self.logger.debug('[Messager] Stream was closed')
|
||||
self.file.close()
|
||||
self.set_file_name_md5()
|
||||
|
||||
def session_start(self, event):
|
||||
self.logger.debug('[Messager] Session was started')
|
||||
self.get_roster()
|
||||
self.send_presence()
|
||||
|
||||
def session_end(self):
|
||||
print("disconnect")
|
||||
|
||||
def send_file(self, file_path):
|
||||
FileTransfer.run(file_path)
|
||||
|
||||
"""
|
||||
@asyncio.coroutine
|
||||
def send_file(self, file_path):
|
||||
self.file = open('/tmp/volkan.txt', 'rb')
|
||||
# TODO read conf file check file size if file size is bigger than max size, divide and send parts.after all send message about them
|
||||
self.logger.debug('[Messager] Sending file: ' + self.file.name)
|
||||
try:
|
||||
self.logger.debug('[Messager] Handshaking for file transfering...')
|
||||
# Open the S5B stream in which to write to.
|
||||
proxy = yield from self['xep_0065'].handshake(self.receiver)
|
||||
# Send the entire file.
|
||||
self.logger.debug('[Messager] Started to streaming file...')
|
||||
while True:
|
||||
data = self.file.read(1048576)
|
||||
if not data:
|
||||
break
|
||||
yield from proxy.write(data)
|
||||
# And finally close the stream.
|
||||
proxy.transport.write_eof()
|
||||
except (IqError, IqTimeout):
|
||||
self.logger.error('[Messager] File transfer errored')
|
||||
else:
|
||||
self.logger.debug('[Messager] File transfer finished successfully')
|
||||
finally:
|
||||
self.file.close()
|
||||
"""
|
||||
|
||||
def send_direct_message(self, msg):
|
||||
try:
|
||||
self.logger.debug('[Messager] Sending message: ' + msg)
|
||||
self.send_message(mto=self.receiver, mbody=msg, mtype='normal')
|
||||
print('<---' + msg)
|
||||
except Exception as e:
|
||||
self.logger.debug('[Messager] A problem occurred while sending direct message. Error Message: {}'.format(str(e)))
|
||||
|
||||
def recv_direct_message(self, msg):
|
||||
if msg['type'] in ('chat', 'normal'):
|
||||
j = json.loads(str(msg['body']))
|
||||
self.logger.debug('[Messager] Received message: {}'.format(str(msg['body'])))
|
||||
message_type = j['type']
|
||||
self.logger.debug('[Messager] Fired event is: {}'.format(message_type))
|
||||
print('----->' + str(msg['body']))
|
||||
self.event_manger.fireEvent(message_type, str(msg['body']))
|
||||
|
||||
def connect_to_server(self): # Connect to the XMPP server and start processing XMPP stanzas.
|
||||
try:
|
||||
self.logger.debug('[Messager] Connecting to server as thread')
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
self.connect((self.hostname, 5222))
|
||||
self.process(forever=True)
|
||||
self.logger.debug('[Messager] Connection were established successfully')
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.error('[Messager] Connection to server is failed! Error Message: {}'.format(str(e)))
|
||||
return False
|
||||
|
||||
def set_file_name_md5(self):
|
||||
self.logger.debug('[Messager] Renaming file as md5 hash')
|
||||
md5_hash = self.execution_manager.get_md5_file(self.file.name)
|
||||
os.rename(self.file.name, self.receive_file_path + md5_hash)
|
||||
|
||||
def register_extensions(self):
|
||||
try:
|
||||
self.register_plugin('xep_0030') # Service Discovery
|
||||
self.register_plugin('xep_0045') # Multi-User Chat
|
||||
self.register_plugin('xep_0199') # XMPP Ping
|
||||
self.register_plugin('xep_0065', {'auto_accept': True}) # SOCKS5 Bytestreams
|
||||
# self.register_plugin('xep_0047', {'auto_accept': True}) # In-band Bytestreams
|
||||
|
||||
self.logger.debug('[Messager]Extension were registered: xep_0030,xep_0045,xep_0199,xep_0065,xep_0047')
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.error('[Messager]Extension registration is failed!(%s)\n' % (e.errno, e.strerror))
|
||||
return False
|
||||
|
||||
'''
|
||||
|
||||
def invite_auto_accept(self, inv):
|
||||
self.room = inv['from']
|
||||
self.logger.debug('[Messager] (%s) invite is accepted' % str(self.room))
|
||||
self.plugin['xep_0045'].joinMUC(self.room, self.nick, wait=True)
|
||||
self.send_message(mto=self.room.bare, mbody='Hi all!', mtype='groupchat')
|
||||
return self.room
|
||||
|
||||
def recv_muc_message(self, msg):
|
||||
if msg['mucnick'] != self.nick:
|
||||
self.logger.debug('[Messager] %s : %s' % (str(msg['from']), str(msg['body'])))
|
||||
self.send_message(mto=msg['from'].bare, mbody='I got it, %s.' % msg['mucnick'], mtype='groupchat')
|
||||
else:
|
||||
self.logger.debug('[Messager] %s : %s' % (str(msg['mucnick']), str(msg['body'])))
|
||||
|
||||
'''
|
92
opt/ahenk/base/messaging/Messenger.py
Normal file
92
opt/ahenk/base/messaging/Messenger.py
Normal file
|
@ -0,0 +1,92 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# Author: Volkan Şahin <volkansah.in> <bm.volkansahin@gmail.com>
|
||||
# Author: İsmail BAŞARAN <ismail.basaran@tubitak.gov.tr> <basaran.ismaill@gmail.com>
|
||||
import json
|
||||
import sys
|
||||
|
||||
from sleekxmpp import ClientXMPP
|
||||
|
||||
from base.Scope import Scope
|
||||
|
||||
sys.path.append('../..')
|
||||
|
||||
|
||||
class Messenger(ClientXMPP):
|
||||
def __init__(self):
|
||||
scope = Scope().getInstance()
|
||||
|
||||
self.logger = scope.getLogger()
|
||||
self.configuration_manager = scope.getConfigurationManager()
|
||||
self.event_manger = scope.getEventManager()
|
||||
self.execution_manager = scope.getExecutionManager()
|
||||
|
||||
self.my_jid = str(self.configuration_manager.get('CONNECTION', 'uid') + '@' + self.configuration_manager.get('CONNECTION', 'servicename'))
|
||||
self.my_pass = str(self.configuration_manager.get('CONNECTION', 'password'))
|
||||
|
||||
ClientXMPP.__init__(self, self.my_jid, self.my_pass)
|
||||
|
||||
self.hostname = self.configuration_manager.get('CONNECTION', 'host')
|
||||
self.resource_name = self.configuration_manager.get('CONNECTION', 'receiverresource')
|
||||
self.receiver = self.configuration_manager.get('CONNECTION', 'receiverjid') + '@' + self.configuration_manager.get('CONNECTION', 'servicename') + '/' + self.resource_name
|
||||
self.receive_file_path = self.configuration_manager.get('CONNECTION', 'receivefileparam')
|
||||
self.logger.debug('[Messenger] XMPP Messager parameters were set')
|
||||
|
||||
self.register_extensions()
|
||||
self.add_listeners()
|
||||
|
||||
def register_extensions(self):
|
||||
try:
|
||||
self.register_plugin('xep_0030') # Service Discovery
|
||||
self.register_plugin('xep_0199') # XMPP Ping
|
||||
|
||||
self.logger.debug('[Messenger]Extension were registered: xep_0030,xep_0199')
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.error('[Messenger]Extension registration is failed! Error Message: {}'.format(str(e)))
|
||||
return False
|
||||
|
||||
def add_listeners(self):
|
||||
self.add_event_handler('session_start', self.session_start)
|
||||
self.add_event_handler('session_end', self.session_end)
|
||||
self.add_event_handler('message', self.recv_direct_message)
|
||||
|
||||
self.logger.debug('[Messenger] Event handlers were added')
|
||||
|
||||
def connect_to_server(self): # Connect to the XMPP server and start processing XMPP stanzas.
|
||||
try:
|
||||
self['feature_mechanisms'].unencrypted_plain = True
|
||||
self.connect((self.hostname, 5222), use_tls=False)
|
||||
self.process(block=False)
|
||||
self.logger.debug('[Messenger] Connection were established successfully')
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.error('[Messenger] Connection to server is failed! Error Message: {}'.format(str(e)))
|
||||
return False
|
||||
|
||||
def session_end(self):
|
||||
print("disconnect")
|
||||
|
||||
def session_start(self, event):
|
||||
self.logger.debug('[Messenger] Session was started')
|
||||
self.get_roster()
|
||||
self.send_presence()
|
||||
|
||||
def send_direct_message(self, msg):
|
||||
try:
|
||||
self.logger.debug('[Messenger] <<--------Sending message: {}'.format(msg))
|
||||
self.send_message(mto=self.receiver, mbody=msg, mtype='normal')
|
||||
except Exception as e:
|
||||
self.logger.debug('[Messenger] A problem occurred while sending direct message. Error Message: {}'.format(str(e)))
|
||||
|
||||
def recv_direct_message(self, msg):
|
||||
if msg['type'] in ('normal'):
|
||||
self.logger.debug('[Messenger] ---------->Received message: {}'.format(str(msg['body'])))
|
||||
try:
|
||||
j = json.loads(str(msg['body']))
|
||||
message_type = j['type']
|
||||
self.event_manger.fireEvent(message_type, str(msg['body']))
|
||||
self.logger.debug('[Messenger] Fired event is: {}'.format(message_type))
|
||||
|
||||
except Exception as e:
|
||||
self.logger.debug('[Messenger] A problem occurred while keeping message. Error Message: {}'.format(str(e)))
|
|
@ -76,7 +76,7 @@ class Plugin(threading.Thread):
|
|||
response = Response(type=MessageType.TASK_STATUS.value, id=item_obj.get_id(), code=self.context.get('responseCode'), message=self.context.get('responseMessage'), data=self.context.get('responseData'), content_type=self.context.get('contentType'))
|
||||
# self.response_queue.put(self.messaging.response_msg(response)) #TODO DEBUG
|
||||
self.logger.debug('[Plugin] Sending response')
|
||||
Scope.getInstance().getMessager().send_direct_message(self.messaging.task_status_msg(response)) # TODO REMOVE
|
||||
Scope.getInstance().getMessenger().send_direct_message(self.messaging.task_status_msg(response)) # TODO REMOVE
|
||||
else:
|
||||
self.logger.error('[Plugin] There is no Response. Plugin must create response after run a task!')
|
||||
|
||||
|
@ -100,7 +100,7 @@ class Plugin(threading.Thread):
|
|||
response = Response(type=MessageType.POLICY_STATUS.value, id=item_obj.get_id(), code=self.context.get('responseCode'), message=self.context.get('responseMessage'), data=self.context.get('responseData'), content_type=self.context.get('contentType'), execution_id=execution_id, policy_version=policy_ver)
|
||||
# self.response_queue.put(self.messaging.response_msg(response)) #TODO DEBUG
|
||||
self.logger.debug('[Plugin] Sending response')
|
||||
Scope.getInstance().getMessager().send_direct_message(self.messaging.policy_status_msg(response)) # TODO REMOVE
|
||||
Scope.getInstance().getMessenger().send_direct_message(self.messaging.policy_status_msg(response)) # TODO REMOVE
|
||||
else:
|
||||
self.logger.error('[Plugin] There is no Response. Plugin must create response after run a policy!')
|
||||
|
||||
|
|
|
@ -85,7 +85,7 @@ class PluginManager(object):
|
|||
|
||||
##
|
||||
scope = Scope().getInstance()
|
||||
self.messenger = scope.getMessager()
|
||||
self.messenger = scope.getMessenger()
|
||||
##
|
||||
|
||||
try:
|
||||
|
@ -145,7 +145,7 @@ class PluginManager(object):
|
|||
|
||||
##
|
||||
scope = Scope().getInstance()
|
||||
self.messenger = scope.getMessager()
|
||||
self.messenger = scope.getMessenger()
|
||||
##
|
||||
try:
|
||||
plugin = profile.get_plugin()
|
||||
|
|
|
@ -8,7 +8,7 @@ import uuid
|
|||
from uuid import getnode as get_mac
|
||||
|
||||
from base.Scope import Scope
|
||||
from base.messaging.AnonymousMessager import AnonymousMessager
|
||||
from base.messaging.AnonymousMessenger import AnonymousMessager
|
||||
from base.system.system import System
|
||||
|
||||
|
||||
|
@ -18,7 +18,7 @@ class Registration():
|
|||
self.logger = scope.getLogger()
|
||||
self.message_manager = scope.getMessageManager()
|
||||
self.event_manager = scope.getEventManager()
|
||||
self.messager = scope.getMessager()
|
||||
self.messenger = scope.getMessenger()
|
||||
self.conf_manager = scope.getConfigurationManager()
|
||||
self.db_service = scope.getDbService()
|
||||
|
||||
|
@ -31,12 +31,12 @@ class Registration():
|
|||
|
||||
def registration_request(self):
|
||||
self.logger.debug('[Registration] Requesting registration')
|
||||
anon_messager = AnonymousMessager(self.message_manager.registration_msg(), None)
|
||||
anon_messager = AnonymousMessager(self.message_manager.registration_msg())
|
||||
anon_messager.connect_to_server()
|
||||
|
||||
def ldap_registration_request(self):
|
||||
self.logger.debug('[Registration] Requesting LDAP registration')
|
||||
self.messager.send_Direct_message(self.message_manager.ldap_registration_msg())
|
||||
self.messenger.send_Direct_message(self.message_manager.ldap_registration_msg())
|
||||
|
||||
def registration_process(self, reg_reply):
|
||||
self.logger.debug('[Registration] Reading registration reply')
|
||||
|
|
Loading…
Reference in a new issue