messaging with event trigger and fix messages

This commit is contained in:
Volkan Şahin 2016-03-07 17:59:02 +02:00
parent fbe9b68fe1
commit 8dd50c3ea1
5 changed files with 131 additions and 278 deletions

View file

@ -6,6 +6,7 @@ from base.config.ConfigManager import ConfigManager
from base.deamon.BaseDeamon import BaseDaemon
from base.logger.AhenkLogger import Logger
from base.Scope import Scope
from base.messaging.Messaging import Messaging
from base.messaging.MessageReceiver import MessageReceiver
from base.messaging.MessageSender import MessageSender
from base.registration.Registration import Registration
@ -47,7 +48,10 @@ class AhenkDeamon(BaseDaemon):
eventManager = EventManager()
globalscope.setEventManager(eventManager)
eventManager.register_event('registration_ok',self.reload)
messageManager = Messaging()
globalscope.setMessageManager(messageManager)
pluginManager = PluginManager()
pluginManager.loadPlugins()
globalscope.setPluginManager(pluginManager)
@ -61,16 +65,24 @@ class AhenkDeamon(BaseDaemon):
while registration.is_registered() is False:
registration.registration_request()
#message_sender=MessageSender(None,'/home/volkan/Desktop/batman.png')
#message_sender.connect_to_server()
#eventManager.register_event('registration_ok',self.reload)
#registration.unregister()
""""
"""
message_receiver = MessageReceiver()
rec_process = Process(target=message_receiver.connect_to_server)
rec_process.start()
"""
#rec_process.terminate()
#message_sender=MessageSender(None,'/home/volkan/Desktop/batman.png')
#message_sender.connect_to_server()
"""
this is must be created after message services

View file

@ -13,20 +13,6 @@ from multiprocessing import Process
from slixmpp.exceptions import IqError, IqTimeout
from base.Scope import Scope
"""
--fetch parameters of connection from conf file
--connect xmpp
--send direct message
--receive direct message
--send muc message
--receive muc message
--listen to muc invites
--auto accept muc invites
--send auto reply to muc messages
--receive file (0065)
--send file (0065)
"""
class MessageReceiver(slixmpp.ClientXMPP):
@ -35,63 +21,61 @@ class MessageReceiver(slixmpp.ClientXMPP):
# global scope of ahenk
scope = Scope().getInstance()
# logger comes from ahenk deamon
# configurationManager comes from ahenk deamon
# configuration_manager and logger comes from ahenk deamon
self.logger = scope.getLogger()
self.configurationManager = scope.getConfigurationManager()
self.event_manger=scope.getEventManager()
self.full_jid =str(self.configurationManager.get('CONNECTION', 'uid'))+'@'+str(self.configurationManager.get('CONNECTION', 'host'))
slixmpp.ClientXMPP.__init__(self, self.full_jid, 'pass')
self.my_jid=self.get_jid_id()
self.my_pass=self.get_password()
#TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST
#slixmpp.ClientXMPP.__init__(self, "volkan@localhost", "volkan")
self.receiver="lider_sunucu@localhost"
#TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST
slixmpp.ClientXMPP.__init__(self, self.my_jid,self.my_pass)
"""
self.nick = self.configurationManager.get('CONNECTION', 'nick')
self.receiver=self.configurationManager.get('CONNECTION','receiverJid')
self.sendfile=open(self.configurationManager.get('CONNECTION','sendFilePath'), 'rb')
self.receivefile=self.configurationManager.get('CONNECTION', 'receiveFileParam')
self.logger.info('Parameters were established')
"""
self.room=None
self.receiver=self.configurationManager.get('CONNECTION', 'receiverjid')+'@'+self.configurationManager.get('CONNECTION', 'host')+'/Smack'
self.nick = self.configurationManager.get('CONNECTION', 'nick')
self.receivefile=self.configurationManager.get('CONNECTION', 'receiveFileParam')
#TODO get default folder path from receivefile
self.file = open('/home/volkan/Desktop/yaz.txt', 'rb')
self.register_extensions()
self.add_listeners()
self.connect()
#!!! you have to use modified slixmpp for file transfering
#self.send_file()
def get_jid_id(self):
if self.configurationManager.get('CONNECTION', 'uid') == "" or self.configurationManager.get('CONNECTION', 'uid') is None:
return str(self.configurationManager.get('CONNECTION', 'host')) #is user want to create connection as anonymous
else:
return str(self.configurationManager.get('CONNECTION', 'uid')+'@'+self.configurationManager.get('CONNECTION', 'host')+'/ahenk')
def get_password(self):
if self.configurationManager.get('CONNECTION', 'password') == "" or self.configurationManager.get('CONNECTION', 'password') is None:
return None
else:
return str(self.configurationManager.get('CONNECTION', 'password'))
def add_listeners(self):
self.add_event_handler("session_start", self.session_start)
#self.add_event_handler("groupchat_message", self.recv_muc_message)
self.add_event_handler("message", self.recv_direct_message)
#self.room=self.add_event_handler("groupchat_invite", self.invite_auto_accept)
#file_listeners
#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.info('Listeners were added')
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)
def stream_opened(self, sid):
print('stream opened')
#self.logger.info('Stream opened. %s', sid)
return open(self.receivefile, 'wb')
return open('/home/volkan/Desktop/ooo.txt', 'wb')
def stream_data(self, data):
print('stream data')
#self.logger.info('Stream data.')
self.file.write(data)
def stream_closed(self, exception):
print('stream close')
#self.logger.info('Stream closed. %s', exception)
self.file.close()
#self.disconnect()
def session_start(self, event):
self.get_roster()
@ -99,7 +83,6 @@ class MessageReceiver(slixmpp.ClientXMPP):
def invite_auto_accept(self, inv):
self.room=inv['from']
print("(%s) invite is accepted" % str(self.room))
self.plugin['xep_0045'].joinMUC(self.room,self.nick,wait=True)

View file

@ -24,12 +24,13 @@ class MessageSender(slixmpp.ClientXMPP):
self.logger = scope.getLogger()
self.configurationManager = scope.getConfigurationManager()
self.registration=scope.getRegistration()
self.event_manager = scope.getEventManager()
self.my_jid=self.get_jid_id()
self.my_pass=self.get_password()
slixmpp.ClientXMPP.__init__(self, self.my_jid,self.my_pass)
#slixmpp.ClientXMPP.__init__(self,'volkan@localhost','volkan')
#slixmpp.ClientXMPP.__init__(self, "volkan@localhost/ahenk","volkan")
self.message=None
self.file=None
@ -40,19 +41,19 @@ class MessageSender(slixmpp.ClientXMPP):
if file_path is not None and file_path!='':
self.file=open(file_path, 'rb')
print('file path-'+file_path+"-"+self.my_jid+"-"+self.my_pass)
if message is not None and message!='':
if message is not None:
self.message=message
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.register_extensions()
def get_jid_id(self):
if self.configurationManager.get('CONNECTION', 'uid') == "" or self.configurationManager.get('CONNECTION', 'uid') is None:
return str(self.configurationManager.get('CONNECTION', 'host')) #is user want to create connection as anonymous
@ -68,8 +69,9 @@ class MessageSender(slixmpp.ClientXMPP):
def recv_direct_message(self, msg):
if msg['type'] in ('chat', 'normal'):
print ("%s : %s" % (msg['from'], msg['body']))
self.registration.registration_reply=str(msg['body'])
self.disconnect(wait=False)
self.disconnect()
self.event_manager.fireEvent('confirm_registration',str(msg['body']))
@asyncio.coroutine
def session_start(self, event):
@ -77,6 +79,7 @@ class MessageSender(slixmpp.ClientXMPP):
self.send_presence()
if self.message is not None:
print("send dire")
self.send_direct_message(self.message)
if self.file is not None:
@ -97,34 +100,8 @@ class MessageSender(slixmpp.ClientXMPP):
print('File transfer finished')
finally:
self.file.close()
self.disconnect()
@asyncio.coroutine
def send_file(self,event):
print("send file")
try:
# Open the S5B stream in which to write to.
print("try")
proxy = yield from self['xep_0065'].handshake(self.receiver)
print("proxy")
# Send the entire file.
while True:
data = self.file.read(1048576)
if not data:
print("not data")
break
yield from proxy.write(data)
# And finally close the stream.
print("while bitti")
proxy.transport.write_eof()
except (IqError, IqTimeout):
print('File transfer errored')
else:
print('File transfer finished')
finally:
print("close")
self.file.close()
if self.message is None and self.file is None:
self.disconnect()
def stream_opened(self, sid):
@ -143,12 +120,9 @@ class MessageSender(slixmpp.ClientXMPP):
def send_direct_message(self,msg):
#need connection control
self.send_message(mto=self.receiver,mbody=msg,mtype='chat')
if self.configurationManager.get('CONNECTION', 'uid') != "" and self.configurationManager.get('CONNECTION', 'uid') is not None:
self.disconnect()
def connect_to_server(self):# Connect to the XMPP server and start processing XMPP stanzas.
try:
print("connec")
self.connect()
self.process(forever=False)
#self.logger.info('Connection were established successfully')

View file

@ -1,177 +1,50 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Volkan Şahin <bm.volkansahin@gmail.com>
# Author: İsmail BAŞARAN <ismail.basaran@tubitak.gov.tr> <basaran.ismaill@gmail.com>
import sys
# Author: Volkan Şahin <volkansah.in> <bm.volkansahin@gmail.com>
import sys,pwd,os
import datetime,json
sys.path.append('../..')
import slixmpp
import asyncio
import threading
from threading import Thread
from multiprocessing import Process
from slixmpp.exceptions import IqError, IqTimeout
#from ahenkd import AhenkDeamon
from base.Scope import Scope
"""
--fetch parameters of connection from conf file
--connect xmpp
--send direct message
--receive direct message
--send muc message
--receive muc message
--listen to muc invites
--auto accept muc invites
--send auto reply to muc messages
--receive file (0065)
--send file (0065)
"""
class Messaging(slixmpp.ClientXMPP):
class Messaging(object):
def __init__(self):
print("messaging initilaziton")
scope = Scope().getInstance()
self.logger = scope.getLogger()
self.configurationManager = scope.getConfigurationManager()
self.event_manger=scope.getEventManager()
# global scope of ahenk
#scope = AhenkDeamon.scope()
def login_msg(self):
data = {}
data['type'] = 'login'
data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ])
data['timestamp'] = str(datetime.datetime.now().strftime("%d-%m-%Y %I:%M"))
json_data = json.dumps(data)
return json_data
# logger comes from ahenk deamon
#self.logger = scope.getLogger()
def logout_msg(self):
data = {}
data['type'] = 'logout'
data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ])
data['timestamp'] = str(datetime.datetime.now().strftime("%d-%m-%Y %I:%M"))
json_data = json.dumps(data)
return json_data
# configurationManager comes from ahenk deamon
#self.configurationManager = scope.getConfigurationManager()
def get_policies_msg(self):
data = {}
data['type'] = 'get_policies'
data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ])
data['timestamp'] = str(datetime.datetime.now().strftime("%d-%m-%Y %I:%M"))
json_data = json.dumps(data)
return json_data
#set parameters
#slixmpp.ClientXMPP.__init__(self, self.configurationManager.get('CONNECTION', 'jid'), self.configurationManager.get('Connection_Param', 'password'))
slixmpp.ClientXMPP.__init__(self, "volkan@localhost", "volkan")
self.receiver="caner@localhost"
#slixmpp.ClientXMPP.__init__(self, "volkan@localhost", "volkan")
#self.receiver="caner@localhost"
"""
self.nick = self.configurationManager.get('CONNECTION', 'nick')
self.receiver=self.configurationManager.get('CONNECTION','receiverJid')
self.sendfile=open(self.configurationManager.get('CONNECTION','sendFilePath'), 'rb')
self.receivefile=self.configurationManager.get('CONNECTION', 'receiveFileParam')
self.logger.info('Parameters were established')
"""
self.room=None
self.register_extensions()
self.add_listeners()
print("connecting")
self.connect()
print("connected")
#!!! you have to use modified slixmpp for file transfering
#self.send_file()
def add_listeners(self):
self.add_event_handler("session_start", self.session_start)
self.add_event_handler("groupchat_message", self.recv_muc_message)
self.add_event_handler("message", self.recv_direct_message)
#self.room=self.add_event_handler("groupchat_invite", self.invite_auto_accept)
#file_listeners
#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.info('Listeners were added')
def stream_opened(self, sid):
#self.logger.info('Stream opened. %s', sid)
return open(self.receivefile, 'wb')
def stream_data(self, data):
#self.logger.info('Stream data.')
self.file.write(data)
def stream_closed(self, exception):
#self.logger.info('Stream closed. %s', exception)
self.file.close()
#self.disconnect()
def send_file(self):
try:
# Open the S5B stream in which to write to.
proxy = yield from self['xep_0065'].handshake(self.receiver)
# Send the entire 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):
print('File transfer errored')
else:
print('File transfer finished')
finally:
self.file.close()
def session_start(self, event):
self.get_roster()
self.send_presence()
def invite_auto_accept(self, inv):
self.room=inv['from']
print("(%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):#auto reply
if msg['mucnick'] != self.nick:
print("%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:
print("%s : %s" % (str(msg['mucnick']),str(msg['body'])))
def send_direct_message(self,msg):
#need connection control
self.send_message(mto=self.receiver,mbody=msg,mtype='chat')
def recv_direct_message(self, msg):
if msg['type'] in ('chat', 'normal'):
self.disconnect()
print ("%s : %s" % (msg['from'], msg['body']))
def connect_to_server(self):# Connect to the XMPP server and start processing XMPP stanzas.
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(self.process())
#self.logger.info('Connection were established successfully')
return True
except Exception as e:
print('Connection to server is failed (%s)\n' % (e.strerror))
#self.logger.error('Connection to server is failed! '+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') # SOCKS5 Bytestreams
#self.logger.info('Extension were registered: xep_0030,xep_0045,xep_0199,xep_0065')
return True
except Exception as e:
#self.logger.error('Extension registration is failed!(%s)\n' % (e.errno, e.strerror))
return False
def create_conn_thread(self):
print("deneme")
def unregister_msg(self):
data = {}
data['type'] = 'registration'
data['status'] = 'unregister'
data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ])
data['timestamp'] = str(datetime.datetime.now().strftime("%d-%m-%Y %I:%M"))
json_data = json.dumps(data)
return json_data

View file

@ -26,6 +26,12 @@ class Registration():
scope = Scope().getInstance()
self.conf_manager = scope.getConfigurationManager()
self.logger=scope.getLogger()
self.message_manager=scope.getMessageManager()
self.event_manager = scope.getEventManager()
self.event_manager.register_event('confirm_registration',self.confirm_registration)
#self.registration_reply=""
if self.conf_manager.has_section('REGISTRATION'):
if self.conf_manager.get('REGISTRATION', 'registered')=='false':
@ -34,37 +40,37 @@ class Registration():
self.logger.debug('[Registration] already registered')
else:
self.register(True)
self.registration_reply=""
#self.registration_reply=""
self.logger.debug('[Registration] ')
def registration_request(self):
message_sender=MessageSender(self.get_registration_request_message(),None)
message_sender.connect_to_server()
self.confirm_registration()
def confirm_registration(self):
if self.registration_reply != "":
j = json.loads(self.registration_reply)
self.logger.info('[REGISTRATION] register reply: '+j['message'])
status =j['status']
dn=j['dn']
def confirm_registration(self,reg_reply): #event fire and keep here
if(str(status).lower()=='registered'):
if self.conf_manager.has_section('CONNECTION') and self.conf_manager.get('REGISTRATION', 'from') is not None:
self.conf_manager.set('CONNECTION', 'uid',self.conf_manager.get('REGISTRATION', 'from'))
self.conf_manager.set('CONNECTION', 'password',self.conf_manager.get('REGISTRATION', 'password'))
self.conf_manager.set('REGISTRATION', 'dn',dn)
self.conf_manager.set('REGISTRATION', 'registered','true')
with open('/etc/ahenk/ahenk.conf', 'w') as configfile:
self.conf_manager.write(configfile)
j = json.loads(reg_reply)
self.logger.info('[REGISTRATION] register reply: '+j['message'])
status =j['status']
dn=j['dn']
self.logger.info('[REGISTRATION] registered successfully')
elif(status=='registration_error'):
self.logger.info('[REGISTRATION] registration error')
elif(status=='already_registered'):
self.logger.info('[REGISTRATION]already registered')
self.re_register()
self.registration_request()
if(str(status).lower()=='registered'):
print("registered")
if self.conf_manager.has_section('CONNECTION') and self.conf_manager.get('REGISTRATION', 'from') is not None:
self.conf_manager.set('CONNECTION', 'uid',self.conf_manager.get('REGISTRATION', 'from'))
self.conf_manager.set('CONNECTION', 'password',self.conf_manager.get('REGISTRATION', 'password'))
self.conf_manager.set('REGISTRATION', 'dn',dn)
self.conf_manager.set('REGISTRATION', 'registered','true')
with open('/etc/ahenk/ahenk.conf', 'w') as configfile:
self.conf_manager.write(configfile)
self.logger.info('[REGISTRATION] registered successfully')
elif(status=='registration_error'):
self.logger.info('[REGISTRATION] registration error')
elif(status=='already_registered'):
self.logger.info('[REGISTRATION]already registered')
self.re_register()
self.registration_request()
def is_registered(self):
if self.conf_manager.has_section('REGISTRATION') and (self.conf_manager.get('REGISTRATION', 'registered')=='true'):
@ -119,12 +125,17 @@ class Registration():
def unregister(self):
if self.conf_manager.has_section('REGISTRATION'):
message_sender=MessageSender(self.message_manager.unregister_msg(),None)
message_sender.connect_to_server()
self.conf_manager.remove_section('REGISTRATION')
self.conf_manager.set('CONNECTION', 'uid','')
self.conf_manager.set('CONNECTION', 'password','')
with open('/etc/ahenk/ahenk.conf', 'w') as configfile:
self.conf_manager.write(configfile)
def re_register(self):
self.unregister()
self.register(False)