core: replaced calls to client.xmlstream.send by client.send which is the right method to use. client.xmlstream should not be used directly

This commit is contained in:
Goffi 2017-02-04 17:59:13 +01:00
commit 6467bdb3c3
14 changed files with 54 additions and 58 deletions

View file

@ -672,7 +672,7 @@ class SAT(service.Service):
@param data: message data dictionnary @param data: message data dictionnary
@param client: profile's client @param client: profile's client
""" """
client.xmlstream.send(data['xml']) client.send(data['xml'])
return data return data
def messageAddToHistory(self, data, client): def messageAddToHistory(self, data, client):

View file

@ -22,13 +22,8 @@ from sat.core.constants import Const as C
from sat.core.log import getLogger from sat.core.log import getLogger
log = getLogger(__name__) log = getLogger(__name__)
from twisted.words.xish import domish from twisted.words.xish import domish
from twisted.internet import protocol, defer, threads, reactor from twisted.internet import reactor
from twisted.words.protocols.jabber import client, jid, xmlstream from twisted.words.protocols.jabber import client as jabber_client, jid
from twisted.words.protocols import jabber
from twisted.words.protocols.jabber.xmlstream import IQ
import random
from wokkel import data_form
from time import time from time import time
@ -169,35 +164,34 @@ class Quiz(object):
def __start_play(self, room_jid, game_data, profile): def __start_play(self, room_jid, game_data, profile):
"""Start the game (tell to the first player after dealer to play""" """Start the game (tell to the first player after dealer to play"""
client = self.host.getClient(profile)
game_data['stage'] = "play" game_data['stage'] = "play"
next_player_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # the player after the dealer start next_player_idx = game_data['current_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # the player after the dealer start
game_data['first_player'] = next_player = game_data['players'][next_player_idx] game_data['first_player'] = next_player = game_data['players'][next_player_idx]
to_jid = jid.JID(room_jid.userhost() + "/" + next_player) to_jid = jid.JID(room_jid.userhost() + "/" + next_player)
mess = self.createGameElt(to_jid) mess = self.createGameElt(to_jid)
yourturn_elt = mess.firstChildElement().addElement('your_turn') mess.firstChildElement().addElement('your_turn')
self.host.profiles[profile].xmlstream.send(mess) client.send(mess)
def playerAnswer(self, player, referee, answer, profile_key=C.PROF_KEY_NONE): def playerAnswer(self, player, referee, answer, profile_key=C.PROF_KEY_NONE):
"""Called when a player give an answer""" """Called when a player give an answer"""
profile = self.host.memory.getProfileName(profile_key) client = self.host.getClient(profile_key)
if not profile: log.debug(u'new player answer (%(profile)s): %(answer)s' % {'profile': client.profile, 'answer': answer})
log.error(_(u"profile %s is unknown") % profile_key)
return
log.debug(u'new player answer (%(profile)s): %(answer)s' % {'profile': profile, 'answer': answer})
mess = self.createGameElt(jid.JID(referee)) mess = self.createGameElt(jid.JID(referee))
answer_elt = mess.firstChildElement().addElement('player_answer') answer_elt = mess.firstChildElement().addElement('player_answer')
answer_elt['player'] = player answer_elt['player'] = player
answer_elt.addContent(answer) answer_elt.addContent(answer)
self.host.profiles[profile].xmlstream.send(mess) client.send(mess)
def timerExpired(self, room_jid, profile): def timerExpired(self, room_jid, profile):
"""Called when nobody answered the question in time""" """Called when nobody answered the question in time"""
client = self.host.getClient(profile)
game_data = self.games[room_jid] game_data = self.games[room_jid]
game_data['stage'] = 'expired' game_data['stage'] = 'expired'
mess = self.createGameElt(room_jid) mess = self.createGameElt(room_jid)
expired_elt = mess.firstChildElement().addElement('timer_expired') mess.firstChildElement().addElement('timer_expired')
self.host.profiles[profile].xmlstream.send(mess) client.send(mess)
reactor.callLater(4, self.askQuestion, room_jid, profile) reactor.callLater(4, self.askQuestion, room_jid, client.profile)
def pauseTimer(self, room_jid): def pauseTimer(self, room_jid):
"""Stop the timer and save the time left""" """Stop the timer and save the time left"""
@ -210,12 +204,13 @@ class Quiz(object):
def restartTimer(self, room_jid, profile): def restartTimer(self, room_jid, profile):
"""Restart a timer with the saved time""" """Restart a timer with the saved time"""
client = self.host.getClient(profile)
game_data = self.games[room_jid] game_data = self.games[room_jid]
assert game_data['time_left'] is not None assert game_data['time_left'] is not None
mess = self.createGameElt(room_jid) mess = self.createGameElt(room_jid)
restarted_elt = mess.firstChildElement().addElement('timer_restarted') mess.firstChildElement().addElement('timer_restarted')
restarted_elt["time_left"] = str(game_data['time_left']) jabber_client.restarted_elt["time_left"] = str(game_data['time_left'])
self.host.profiles[profile].xmlstream.send(mess) client.send(mess)
game_data["timer"] = reactor.callLater(game_data['time_left'], self.timerExpired, room_jid, profile) game_data["timer"] = reactor.callLater(game_data['time_left'], self.timerExpired, room_jid, profile)
game_data["time_left"] = None game_data["time_left"] = None
game_data['stage'] = game_data['previous_stage'] game_data['stage'] = game_data['previous_stage']
@ -223,18 +218,20 @@ class Quiz(object):
def askQuestion(self, room_jid, profile): def askQuestion(self, room_jid, profile):
"""Ask a new question""" """Ask a new question"""
client = self.host.getClient(profile)
game_data = self.games[room_jid] game_data = self.games[room_jid]
game_data['stage'] = "question" game_data['stage'] = "question"
game_data['question_id'] = "1" game_data['question_id'] = "1"
timer = 30 timer = 30
mess = self.createGameElt(room_jid) mess = self.createGameElt(room_jid)
mess.firstChildElement().addChild(self.__ask_question(game_data['question_id'], u"Quel est l'âge du capitaine ?", timer)) mess.firstChildElement().addChild(self.__ask_question(game_data['question_id'], u"Quel est l'âge du capitaine ?", timer))
self.host.profiles[profile].xmlstream.send(mess) client.send(mess)
game_data["timer"] = reactor.callLater(timer, self.timerExpired, room_jid, profile) game_data["timer"] = reactor.callLater(timer, self.timerExpired, room_jid, profile)
game_data["time_left"] = None game_data["time_left"] = None
def checkAnswer(self, room_jid, player, answer, profile): def checkAnswer(self, room_jid, player, answer, profile):
"""Check if the answer given is right""" """Check if the answer given is right"""
client = self.host.getClient(profile)
game_data = self.games[room_jid] game_data = self.games[room_jid]
players_data = game_data['players_data'] players_data = game_data['players_data']
good_answer = game_data['question_id'] == "1" and answer == "42" good_answer = game_data['question_id'] == "1" and answer == "42"
@ -243,7 +240,7 @@ class Quiz(object):
mess = self.createGameElt(room_jid) mess = self.createGameElt(room_jid)
mess.firstChildElement().addChild(self.__answer_result(player, good_answer, game_data)) mess.firstChildElement().addChild(self.__answer_result(player, good_answer, game_data))
self.host.profiles[profile].xmlstream.send(mess) client.send(mess)
if good_answer: if good_answer:
reactor.callLater(4, self.askQuestion, room_jid, profile) reactor.callLater(4, self.askQuestion, room_jid, profile)
@ -261,12 +258,13 @@ Attention, tu es prêt ?""")}
reactor.callLater(10, self.askQuestion, room_jid, profile) reactor.callLater(10, self.askQuestion, room_jid, profile)
def room_game_cmd(self, mess_elt, profile): def room_game_cmd(self, mess_elt, profile):
client = self.host.getClient(profile)
from_jid = jid.JID(mess_elt['from']) from_jid = jid.JID(mess_elt['from'])
room_jid = jid.JID(from_jid.userhost()) room_jid = jid.JID(from_jid.userhost())
game_elt = mess_elt.firstChildElement() game_elt = mess_elt.firstChildElement()
game_data = self.games[room_jid] game_data = self.games[room_jid]
if 'players_data' in game_data: # if 'players_data' in game_data:
players_data = game_data['players_data'] #  players_data = game_data['players_data']
for elt in game_elt.elements(): for elt in game_elt.elements():
@ -299,7 +297,7 @@ Attention, tu es prêt ?""")}
buzzer_elt = mess.firstChildElement().addElement('player_buzzed') buzzer_elt = mess.firstChildElement().addElement('player_buzzed')
buzzer_elt['player'] = player buzzer_elt['player'] = player
buzzer_elt['pause'] = str(pause) buzzer_elt['pause'] = str(pause)
self.host.profiles[profile].xmlstream.send(mess) client.send(mess)
if pause: if pause:
self.pauseTimer(room_jid) self.pauseTimer(room_jid)
# and we send the player answer # and we send the player answer
@ -309,7 +307,7 @@ Attention, tu es prêt ?""")}
say_elt['player'] = player say_elt['player'] = player
say_elt.addContent(_answer) say_elt.addContent(_answer)
say_elt['delay'] = "3" say_elt['delay'] = "3"
reactor.callLater(2, self.host.profiles[profile].xmlstream.send, mess) reactor.callLater(2, client.send, mess)
reactor.callLater(6, self.checkAnswer, room_jid, player, _answer, profile=profile) reactor.callLater(6, self.checkAnswer, room_jid, player, _answer, profile=profile)
elif elt.name == 'player_buzzed': elif elt.name == 'player_buzzed':

View file

@ -653,9 +653,7 @@ class RoomGame(object):
@param profile: the profile from which the message is sent @param profile: the profile from which the message is sent
@return: a Deferred instance @return: a Deferred instance
""" """
if profile is None: client = self.host.getClient(profile)
log.error(_("Message can not be sent without a sender profile"))
return defer.fail(None)
msg = self._createGameElt(to_jid) msg = self._createGameElt(to_jid)
for elem, attrs, content in data: for elem, attrs, content in data:
if elem is not None: if elem is not None:
@ -667,7 +665,7 @@ class RoomGame(object):
elem.attributes.update(attrs) elem.attributes.update(attrs)
if content is not None: if content is not None:
elem.addContent(content) elem.addContent(content)
self.host.profiles[profile].xmlstream.send(msg) client.send(msg)
return defer.succeed(None) return defer.succeed(None)
def send(self, to_jid, elem=None, attrs=None, content=None, profile=None): def send(self, to_jid, elem=None, attrs=None, content=None, profile=None):

View file

@ -94,7 +94,7 @@ class Context(potr.context.Context):
'timestamp': time.time(), 'timestamp': time.time(),
} }
self.host.generateMessageXML(mess_data) self.host.generateMessageXML(mess_data)
client.xmlstream.send(mess_data['xml']) client.send(mess_data['xml'])
def setState(self, state): def setState(self, state):
client = self.user.client client = self.user.client

View file

@ -189,7 +189,7 @@ class XEP_0047(object):
client.xmlstream.addOnetimeObserver(event_close, self._onIBBClose, profile=profile) client.xmlstream.addOnetimeObserver(event_close, self._onIBBClose, profile=profile)
# finally, we send the accept stanza # finally, we send the accept stanza
iq_result_elt = xmlstream.toResponse(iq_elt, 'result') iq_result_elt = xmlstream.toResponse(iq_elt, 'result')
client.xmlstream.send(iq_result_elt) client.send(iq_result_elt)
def _onIBBClose(self, iq_elt, profile): def _onIBBClose(self, iq_elt, profile):
""""Called when an IBB <close> element is received """"Called when an IBB <close> element is received
@ -205,7 +205,7 @@ class XEP_0047(object):
sid = close_elt['sid'] sid = close_elt['sid']
iq_result_elt = xmlstream.toResponse(iq_elt, 'result') iq_result_elt = xmlstream.toResponse(iq_elt, 'result')
client.xmlstream.send(iq_result_elt) client.send(iq_result_elt)
self._killSession(sid, client) self._killSession(sid, client)
def _onIBBData(self, element, profile): def _onIBBData(self, element, profile):
@ -261,7 +261,7 @@ class XEP_0047(object):
# we can now ack success # we can now ack success
if element.name == 'iq': if element.name == 'iq':
iq_result_elt = xmlstream.toResponse(element, 'result') iq_result_elt = xmlstream.toResponse(element, 'result')
client.xmlstream.send(iq_result_elt) client.send(iq_result_elt)
def _sendError(self, error_condition, sid, iq_elt, client): def _sendError(self, error_condition, sid, iq_elt, client):
"""Send error stanza """Send error stanza
@ -275,7 +275,7 @@ class XEP_0047(object):
log.warning(u"Error while managing in-band bytestream session, cancelling: {}".format(error_condition)) log.warning(u"Error while managing in-band bytestream session, cancelling: {}".format(error_condition))
if sid is not None: if sid is not None:
self._killSession(sid, client, error_condition) self._killSession(sid, client, error_condition)
client.xmlstream.send(iq_elt) client.send(iq_elt)
def startStream(self, file_obj, to_jid, sid, block_size=None, profile=C.PROF_KEY_NONE): def startStream(self, file_obj, to_jid, sid, block_size=None, profile=C.PROF_KEY_NONE):
"""Launch the stream workflow """Launch the stream workflow

View file

@ -162,7 +162,7 @@ class AdHocCommand(XMPPHandler):
if payload is not None: if payload is not None:
command_elt.addChild(payload) command_elt.addChild(payload)
self.client.xmlstream.send(result) self.client.send(result)
if status in (XEP_0050.STATUS.COMPLETED, XEP_0050.STATUS.CANCELED): if status in (XEP_0050.STATUS.COMPLETED, XEP_0050.STATUS.CANCELED):
del self.sessions[session_id] del self.sessions[session_id]
@ -176,7 +176,7 @@ class AdHocCommand(XMPPHandler):
if cmd_condition: if cmd_condition:
error_elt = iq_elt.elements(None, "error").next() error_elt = iq_elt.elements(None, "error").next()
error_elt.addElement(cmd_condition, NS_COMMANDS) error_elt.addElement(cmd_condition, NS_COMMANDS)
self.client.xmlstream.send(iq_elt) self.client.send(iq_elt)
del self.sessions[session_id] del self.sessions[session_id]
def onRequest(self, command_elt, requestor, action, session_id): def onRequest(self, command_elt, requestor, action, session_id):

View file

@ -1252,7 +1252,7 @@ class XEP_0065(object):
query_elt['sid'] = session_data['id'] query_elt['sid'] = session_data['id']
streamhost_used_elt = query_elt.addElement('streamhost-used') streamhost_used_elt = query_elt.addElement('streamhost-used')
streamhost_used_elt['jid'] = candidate.jid.full() streamhost_used_elt['jid'] = candidate.jid.full()
client.xmlstream.send(result_elt) client.send(result_elt)
class XEP_0065_handler(XMPPHandler): class XEP_0065_handler(XMPPHandler):

View file

@ -129,17 +129,17 @@ class XEP_0070(object):
# iq # iq
log.debug(_(u"XEP-0070 reply iq")) log.debug(_(u"XEP-0070 reply iq"))
iq_result_elt = xmlstream.toResponse(elt, 'result') iq_result_elt = xmlstream.toResponse(elt, 'result')
client.xmlstream.send(iq_result_elt) client.send(iq_result_elt)
elif (stanzaType == MSG): elif (stanzaType == MSG):
# message # message
log.debug(_(u"XEP-0070 reply message")) log.debug(_(u"XEP-0070 reply message"))
msg_result_elt = xmlstream.toResponse(elt, 'result') msg_result_elt = xmlstream.toResponse(elt, 'result')
msg_result_elt.addChild(elt.elements(NS_HTTP_AUTH, 'confirm').next()) msg_result_elt.addChild(elt.elements(NS_HTTP_AUTH, 'confirm').next())
client.xmlstream.send(msg_result_elt) client.send(msg_result_elt)
else: else:
log.debug(_(u"XEP-0070 reply error")) log.debug(_(u"XEP-0070 reply error"))
result_elt = jabber.error.StanzaError("not-authorized").toResponse(elt) result_elt = jabber.error.StanzaError("not-authorized").toResponse(elt)
client.xmlstream.send(result_elt) client.send(result_elt)
class XEP_0070_handler(XMPPHandler): class XEP_0070_handler(XMPPHandler):

View file

@ -373,7 +373,7 @@ class ChatStateMachine(object):
} }
self.host.generateMessageXML(mess_data) self.host.generateMessageXML(mess_data)
mess_data['xml'].addElement(state, NS_CHAT_STATES) mess_data['xml'].addElement(state, NS_CHAT_STATES)
client.xmlstream.send(mess_data['xml']) client.send(mess_data['xml'])
self.state = state self.state = state
try: try:

View file

@ -109,7 +109,7 @@ class XEP_0095(object):
if si_condition is not None: if si_condition is not None:
iq_error_elt.error.addElement((NS_SI, si_condition)) iq_error_elt.error.addElement((NS_SI, si_condition))
client.xmlstream.send(iq_error_elt) client.send(iq_error_elt)
def acceptStream(self, iq_elt, feature_elt, misc_elts=None, profile=C.PROF_KEY_NONE): def acceptStream(self, iq_elt, feature_elt, misc_elts=None, profile=C.PROF_KEY_NONE):
"""Send the accept stream initiation answer """Send the accept stream initiation answer
@ -128,7 +128,7 @@ class XEP_0095(object):
si_elt.addChild(feature_elt) si_elt.addChild(feature_elt)
for elt in misc_elts: for elt in misc_elts:
si_elt.addChild(elt) si_elt.addChild(elt)
client.xmlstream.send(result_elt) client.send(result_elt)
def _parseOfferResult(self, iq_elt): def _parseOfferResult(self, iq_elt):
try: try:

View file

@ -139,7 +139,7 @@ class XEP_0166(object):
if error.STANZA_CONDITIONS[error_condition]['type'] == 'cancel' and sid: if error.STANZA_CONDITIONS[error_condition]['type'] == 'cancel' and sid:
self._delSession(client, sid) self._delSession(client, sid)
log.warning(u"Error while managing jingle session, cancelling: {condition}".format(error_condition)) log.warning(u"Error while managing jingle session, cancelling: {condition}".format(error_condition))
client.xmlstream.send(iq_elt) client.send(iq_elt)
def terminate(self, reason, session, profile): def terminate(self, reason, session, profile):
"""Terminate the session """Terminate the session
@ -692,7 +692,7 @@ class XEP_0166(object):
return return
# at this point we can send the <iq/> result to confirm reception of the request # at this point we can send the <iq/> result to confirm reception of the request
client.xmlstream.send(xmlstream.toResponse(request, 'result')) client.send(xmlstream.toResponse(request, 'result'))
# we now request each application plugin confirmation # we now request each application plugin confirmation
# and if all are accepted, we can accept the session # and if all are accepted, we can accept the session
@ -770,7 +770,7 @@ class XEP_0166(object):
terminate_dlist = defer.DeferredList(terminate_defers) terminate_dlist = defer.DeferredList(terminate_defers)
terminate_dlist.addCallback(lambda dummy: self._delSession(client, session['id'])) terminate_dlist.addCallback(lambda dummy: self._delSession(client, session['id']))
client.xmlstream.send(xmlstream.toResponse(request, 'result')) client.send(xmlstream.toResponse(request, 'result'))
def onSessionAccept(self, client, request, jingle_elt, session): def onSessionAccept(self, client, request, jingle_elt, session):
"""Method called once session is accepted """Method called once session is accepted
@ -789,7 +789,7 @@ class XEP_0166(object):
return return
# at this point we can send the <iq/> result to confirm reception of the request # at this point we can send the <iq/> result to confirm reception of the request
client.xmlstream.send(xmlstream.toResponse(request, 'result')) client.send(xmlstream.toResponse(request, 'result'))
# and change the state # and change the state
session['state'] = STATE_ACTIVE session['state'] = STATE_ACTIVE
@ -802,7 +802,7 @@ class XEP_0166(object):
negociate_dlist.addCallback(lambda dummy: self._callPlugins(XEP_0166.A_START, session, app_method_name=None, elements=False, profile=client.profile)) negociate_dlist.addCallback(lambda dummy: self._callPlugins(XEP_0166.A_START, session, app_method_name=None, elements=False, profile=client.profile))
def _onSessionCb(self, result, client, request, jingle_elt, session): def _onSessionCb(self, result, client, request, jingle_elt, session):
client.xmlstream.send(xmlstream.toResponse(request, 'result')) client.send(xmlstream.toResponse(request, 'result'))
def _onSessionEb(self, failure_, client, request, jingle_elt, session): def _onSessionEb(self, failure_, client, request, jingle_elt, session):
log.error(u"Error while handling onSessionInfo: {}".format(failure_.value)) log.error(u"Error while handling onSessionInfo: {}".format(failure_.value))
@ -820,7 +820,7 @@ class XEP_0166(object):
""" """
if not jingle_elt.children: if not jingle_elt.children:
# this is a session ping, see XEP-0166 §6.8 # this is a session ping, see XEP-0166 §6.8
client.xmlstream.send(xmlstream.toResponse(request, 'result')) client.send(xmlstream.toResponse(request, 'result'))
return return
try: try:
@ -852,7 +852,7 @@ class XEP_0166(object):
except exceptions.CancelError: except exceptions.CancelError:
defer.returnValue(None) defer.returnValue(None)
client.xmlstream.send(xmlstream.toResponse(request, 'result')) client.send(xmlstream.toResponse(request, 'result'))
content_name = None content_name = None
to_replace = [] to_replace = []
@ -916,7 +916,7 @@ class XEP_0166(object):
return return
# at this point we can send the <iq/> result to confirm reception of the request # at this point we can send the <iq/> result to confirm reception of the request
client.xmlstream.send(xmlstream.toResponse(request, 'result')) client.send(xmlstream.toResponse(request, 'result'))
negociate_defers = [] negociate_defers = []
negociate_defers = self._callPlugins(XEP_0166.A_TRANSPORT_ACCEPT, session, app_method_name=None, profile=client.profile) negociate_defers = self._callPlugins(XEP_0166.A_TRANSPORT_ACCEPT, session, app_method_name=None, profile=client.profile)
@ -955,7 +955,7 @@ class XEP_0166(object):
return return
# The parsing was OK, we send the <iq> result # The parsing was OK, we send the <iq> result
client.xmlstream.send(xmlstream.toResponse(request, 'result')) client.send(xmlstream.toResponse(request, 'result'))
for content_name, content_data in session['contents'].iteritems(): for content_name, content_data in session['contents'].iteritems():
try: try:

View file

@ -128,7 +128,7 @@ class XEP_0184(object):
msg_result_elt = xmlstream.toResponse(msg_elt, 'result') msg_result_elt = xmlstream.toResponse(msg_elt, 'result')
msg_result_elt.addChild(received_elt_ret) msg_result_elt.addChild(received_elt_ret)
client.xmlstream.send(msg_result_elt) client.send(msg_result_elt)
def onMessageDeliveryReceiptsReceived(self, msg_elt, client): def onMessageDeliveryReceiptsReceived(self, msg_elt, client):
"""This method is called on message delivery receipts **received** (XEP-0184 #7) """This method is called on message delivery receipts **received** (XEP-0184 #7)

View file

@ -119,7 +119,7 @@ class XEP_0249(object):
log.warning(u"Ignoring invalid invite option: {}".format(key)) log.warning(u"Ignoring invalid invite option: {}".format(key))
continue continue
x_elt[key] = value x_elt[key] = value
client.xmlstream.send(message) client.send(message)
def _accept(self, room_jid, profile_key=C.PROF_KEY_NONE): def _accept(self, room_jid, profile_key=C.PROF_KEY_NONE):
"""Accept the invitation to join a MUC. """Accept the invitation to join a MUC.

View file

@ -98,7 +98,7 @@ class XEP_0297(object):
msg.addChild(forwarded_elt) msg.addChild(forwarded_elt)
client = self.host.getClient(profile_key) client = self.host.getClient(profile_key)
return client.xmlstream.send(msg.toXml()) return client.send(msg.toXml())
class XEP_0297_handler(XMPPHandler): class XEP_0297_handler(XMPPHandler):