core, plugin XEP-0115: discovery refactoring:
- hashing algorithm of XEP-0115 has been including in core
- our own hash is still calculated by XEP-0115 and can be regenerated with XEP_0115.recalculateHash
- old discovery methods have been removed. Now the following methods are used:
- hasFeature: tell if a feature is available for an entity
- getDiscoInfos: self explaining
- getDiscoItems: self explaining
- findServiceEntities: return all available items of an entity which given (category, type)
- findFeaturesSet: search for a set of features in entity + entity's items
all these methods are asynchronous, and manage cache automatically
- XEP-0115 manage in a better way hashes, and now use a trigger for presence instead of monkey patch
- new FeatureNotFound exception, when we want to do something which is not available
- refactored client initialisation sequence, removed client.initialized Deferred
- added constant APP_URL
- test_plugin_xep_0033.py has been temporarly deactivated, the time to adapt it
- lot of cleaning
This commit is contained in:
parent
382d49a628
commit
95678d7967
6 changed files with 431 additions and 479 deletions
|
|
@ -154,26 +154,18 @@ class GroupBlog(object):
|
|||
raise exceptions.ProfileUnknownError
|
||||
|
||||
client = self.host.getClient(profile)
|
||||
yield client.client_initialized # we want to be sure that the client is initialized
|
||||
|
||||
#we first check that we have a item-access pubsub server
|
||||
if not hasattr(client, "item_access_pubsub"):
|
||||
debug(_('Looking for item-access power pubsub server'))
|
||||
debug(_('Looking for item-access powered pubsub server'))
|
||||
#we don't have any pubsub server featuring item access yet
|
||||
client.item_access_pubsub = None
|
||||
client._item_access_pubsub_pending = defer.Deferred()
|
||||
for entity in self.host.memory.getServerServiceEntities("pubsub", "service", profile=profile):
|
||||
_disco = yield client.disco.requestInfo(entity)
|
||||
#if set([NS_PUBSUB_ITEM_ACCESS, NS_PUBSUB_AUTO_CREATE, NS_PUBSUB_CREATOR_JID_CHECK]).issubset(_disco.features):
|
||||
if set([NS_PUBSUB_AUTO_CREATE, NS_PUBSUB_CREATOR_JID_CHECK]).issubset(_disco.features):
|
||||
info(_("item-access powered pubsub service found: [%s]") % entity.full())
|
||||
client.item_access_pubsub = entity
|
||||
client._item_access_pubsub_pending.callback(None)
|
||||
|
||||
if hasattr(client, "_item_access_pubsub_pending"):
|
||||
#XXX: we need to wait for item access pubsub service check
|
||||
yield client._item_access_pubsub_pending
|
||||
del client._item_access_pubsub_pending
|
||||
item_access_pubsubs = yield self.host.findFeaturesSet((NS_PUBSUB_AUTO_CREATE, NS_PUBSUB_CREATOR_JID_CHECK), "pubsub", "service", profile_key=profile)
|
||||
# item_access_pubsubs = yield self.host.findFeaturesSet((NS_PUBSUB_ITEM_ACCESS, NS_PUBSUB_AUTO_CREATE, NS_PUBSUB_CREATOR_JID_CHECK), "pubsub", "service", profile_key=profile)
|
||||
try:
|
||||
client.item_access_pubsub = item_access_pubsubs.pop()
|
||||
info(_("item-access powered pubsub service found: [%s]") % client.item_access_pubsub.full())
|
||||
except KeyError:
|
||||
client.item_access_pubsub = None
|
||||
|
||||
if not client.item_access_pubsub:
|
||||
error(_("No item-access powered pubsub server found, can't use group blog"))
|
||||
|
|
|
|||
|
|
@ -362,6 +362,7 @@ class RoomGame(object):
|
|||
|
||||
def _checkWaitAuth(self, room, other_players, verbose=False):
|
||||
"""Check if we must wait for other players before starting the game.
|
||||
|
||||
@param room: wokkel.muc.Room instance
|
||||
@param other_players: list of players JID userhosts without the referee
|
||||
@param verbose: display debug message
|
||||
|
|
@ -383,17 +384,20 @@ class RoomGame(object):
|
|||
debug(_("Still waiting for %(users)s before starting the game %(game)s in %(room)s") % {'users': result[2], 'game': self.name, 'room': room.occupantJID.userhost()})
|
||||
return result
|
||||
|
||||
def getUniqueName(self, muc_service="", profile_key=C.PROF_KEY_NONE):
|
||||
"""
|
||||
def getUniqueName(self, muc_service=None, profile_key=C.PROF_KEY_NONE):
|
||||
"""Generate unique room name
|
||||
|
||||
@param muc_service: you can leave empty to autofind the muc service
|
||||
@param profile_key
|
||||
@param profile_key: %(doc_profile_key)s
|
||||
@return: a unique name for a new room to be created
|
||||
"""
|
||||
# FIXME: jid.JID must be used instead of strings
|
||||
room = self.host.plugins["XEP-0045"].getUniqueName(muc_service, profile_key=profile_key)
|
||||
return "sat_%s_%s" % (self.name.lower(), room) if room != "" else ""
|
||||
return "sat_%s_%s" % (self.name.lower(), room.full())
|
||||
|
||||
def prepareRoom(self, other_players=None, room_jid_s=None, profile_key=C.PROF_KEY_NONE):
|
||||
"""Prepare the room for a game: create it if it doesn't exist and invite players.
|
||||
|
||||
@param other_players: list for other players JID userhosts
|
||||
@param room_jid_s: JID userhost of the room, or None to generate a unique name
|
||||
@param profile_key
|
||||
|
|
@ -410,28 +414,22 @@ class RoomGame(object):
|
|||
"""@param room: instance of wokkel.muc.Room"""
|
||||
self._createOrInvite(room, [JID(player).userhost() for player in other_players], profile)
|
||||
|
||||
def afterClientInit(room_jid_s):
|
||||
"""Create/join the given room, or a unique generated one if no room is specified.
|
||||
@param room_jids: userhost of the room to join
|
||||
"""
|
||||
if room_jid_s is not None and room_jid_s != "": # a room name has been specified
|
||||
if room_jid_s in self.host.plugins["XEP-0045"].clients[profile].joined_rooms:
|
||||
roomJoined(self.host.plugins["XEP-0045"].clients[profile].joined_rooms[room_jid_s])
|
||||
return
|
||||
else:
|
||||
room_jid_s = self.getUniqueName(profile_key=profile_key)
|
||||
if room_jid_s == "":
|
||||
return
|
||||
user_jid = self.host.getJidNStream(profile)[0]
|
||||
d = self.host.plugins["XEP-0045"].join(JID(room_jid_s), user_jid.user, {}, profile)
|
||||
d.addCallback(roomJoined)
|
||||
|
||||
client = self.host.getClient(profile)
|
||||
client.client_initialized.addCallback(lambda ignore: afterClientInit(room_jid_s))
|
||||
# Create/join the given room, or a unique generated one if no room is specified.
|
||||
if room_jid_s is not None and room_jid_s != "": # a room name has been specified
|
||||
if room_jid_s in self.host.plugins["XEP-0045"].clients[profile].joined_rooms:
|
||||
roomJoined(self.host.plugins["XEP-0045"].clients[profile].joined_rooms[room_jid_s])
|
||||
return
|
||||
else:
|
||||
room_jid_s = self.getUniqueName(profile_key=profile_key)
|
||||
if room_jid_s == "":
|
||||
return
|
||||
user_jid = self.host.getJidNStream(profile)[0]
|
||||
d = self.host.plugins["XEP-0045"].join(JID(room_jid_s), user_jid.user, {}, profile)
|
||||
return d.addCallback(roomJoined)
|
||||
|
||||
def userJoinedTrigger(self, room, user, profile):
|
||||
"""This trigger is used to check if the new user can take part of a game,
|
||||
create the game if we were waiting for him or just update the players list.
|
||||
"""This trigger is used to check if the new user can take part of a game, create the game if we were waiting for him or just update the players list.
|
||||
|
||||
@room: wokkel.muc.Room object. room.roster is a dict{wokkel.muc.User.nick: wokkel.muc.User}
|
||||
@user: wokkel.muc.User object. user.nick is a unicode and user.entity a JID
|
||||
@return: True to not interrupt the main process.
|
||||
|
|
@ -463,6 +461,7 @@ class RoomGame(object):
|
|||
|
||||
def userLeftTrigger(self, room, user, profile):
|
||||
"""This trigger is used to update or stop the game when a user leaves.
|
||||
|
||||
@room: wokkel.muc.Room object. room.roster is a dict{wokkel.muc.User.nick: wokkel.muc.User}
|
||||
@user: wokkel.muc.User object. user.nick is a unicode and user.entity a JID
|
||||
@return: True to not interrupt the main process.
|
||||
|
|
@ -491,13 +490,13 @@ class RoomGame(object):
|
|||
return True
|
||||
|
||||
def _checkCreateGameAndInit(self, room_jid_s, profile):
|
||||
"""Check if that profile can create the game. If the game can be created
|
||||
but is not initialized yet, this method will also do the initialization.
|
||||
"""Check if that profile can create the game. If the game can be created but is not initialized yet, this method will also do the initialization.
|
||||
|
||||
@param room_jid_s: room userhost
|
||||
@param profile
|
||||
@return: a couple (create, sync) with:
|
||||
- create: set to True to allow the game creation
|
||||
- sync: set to True to advice a game synchronization
|
||||
- create: set to True to allow the game creation
|
||||
- sync: set to True to advice a game synchronization
|
||||
"""
|
||||
user_nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
|
||||
if not user_nick:
|
||||
|
|
@ -516,12 +515,14 @@ class RoomGame(object):
|
|||
return True, False
|
||||
|
||||
def createGame(self, room_jid_s, nicks=None, profile_key=C.PROF_KEY_NONE):
|
||||
"""Create a new game - this can be called directly from a frontend
|
||||
and skips all the checks and invitation system, but the game must
|
||||
not exist and all the players must be in the room already.
|
||||
"""Create a new game.
|
||||
|
||||
This can be called directly from a frontend and skips all the checks and invitation system,
|
||||
but the game must not exist and all the players must be in the room already.
|
||||
@param room_jid: JID userhost of the room
|
||||
@param nicks: list of players nicks in the room (referee included, in first position)
|
||||
@param profile_key: %(doc_profile_key)s"""
|
||||
@param profile_key: %(doc_profile_key)s
|
||||
"""
|
||||
debug(_("Creating %(game)s game in room %(room)s") % {'game': self.name, 'room': room_jid_s})
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not profile:
|
||||
|
|
@ -545,6 +546,7 @@ class RoomGame(object):
|
|||
|
||||
def playerReady(self, player, referee, profile_key=C.PROF_KEY_NONE):
|
||||
"""Must be called when player is ready to start a new game
|
||||
|
||||
@param player: the player nick in the room
|
||||
@param referee: referee userhost
|
||||
"""
|
||||
|
|
@ -558,10 +560,11 @@ class RoomGame(object):
|
|||
|
||||
def newRound(self, room_jid, data, profile):
|
||||
"""Launch a new round (reinit the user data)
|
||||
|
||||
@param room_jid: room userhost
|
||||
@param data: a couple (common_data, msg_elts) with:
|
||||
- common_data: backend initialization data for the new round
|
||||
- msg_elts: dict to map each user to his specific initialization message
|
||||
- common_data: backend initialization data for the new round
|
||||
- msg_elts: dict to map each user to his specific initialization message
|
||||
@param profile
|
||||
"""
|
||||
debug(_('new round for %s game') % self.name)
|
||||
|
|
@ -585,6 +588,7 @@ class RoomGame(object):
|
|||
|
||||
def _createGameElt(self, to_jid):
|
||||
"""Create a generic domish Element for the game messages
|
||||
|
||||
@param to_jid: JID of the recipient
|
||||
@return: the created element
|
||||
"""
|
||||
|
|
@ -597,10 +601,11 @@ class RoomGame(object):
|
|||
|
||||
def _createStartElement(self, players=None, name="started"):
|
||||
"""Create a domish Element listing the game users
|
||||
|
||||
@param players: list of the players
|
||||
@param name: element name:
|
||||
- "started" to signal the players that the game has been started
|
||||
- "players" to signal the list of players when the game is not started yet
|
||||
- "started" to signal the players that the game has been started
|
||||
- "players" to signal the list of players when the game is not started yet
|
||||
@return the create element
|
||||
"""
|
||||
started_elt = domish.Element((None, name))
|
||||
|
|
@ -616,15 +621,16 @@ class RoomGame(object):
|
|||
return started_elt
|
||||
|
||||
def _sendElements(self, to_jid, data, profile=None):
|
||||
"""
|
||||
""" TODO
|
||||
|
||||
@param to_jid: recipient JID
|
||||
@param data: list of (elem, attr, content) with:
|
||||
- elem: domish.Element, unicode or a couple:
|
||||
- domish.Element to be directly added as a child to the message
|
||||
- unicode name or couple (uri, name) to create a new domish.Element
|
||||
and add it as a child to the message (see domish.Element.addElement)
|
||||
- attrs: dictionary of attributes for the new child
|
||||
- content: unicode that is appended to the child content
|
||||
- elem: domish.Element, unicode or a couple:
|
||||
- domish.Element to be directly added as a child to the message
|
||||
- unicode name or couple (uri, name) to create a new domish.Element
|
||||
and add it as a child to the message (see domish.Element.addElement)
|
||||
- attrs: dictionary of attributes for the new child
|
||||
- content: unicode that is appended to the child content
|
||||
@param profile: the profile from which the message is sent
|
||||
@return: a Deferred instance
|
||||
"""
|
||||
|
|
@ -646,12 +652,13 @@ class RoomGame(object):
|
|||
return defer.succeed(None)
|
||||
|
||||
def send(self, to_jid, elem=None, attrs=None, content=None, profile=None):
|
||||
"""
|
||||
""" TODO
|
||||
|
||||
@param to_jid: recipient JID
|
||||
@param elem: domish.Element, unicode or a couple:
|
||||
- domish.Element to be directly added as a child to the message
|
||||
- unicode name or couple (uri, name) to create a new domish.Element
|
||||
and add it as a child to the message (see domish.Element.addElement)
|
||||
- domish.Element to be directly added as a child to the message
|
||||
- unicode name or couple (uri, name) to create a new domish.Element
|
||||
and add it as a child to the message (see domish.Element.addElement)
|
||||
@param attrs: dictionary of attributes for the new child
|
||||
@param content: unicode that is appended to the child content
|
||||
@param profile: the profile from which the message is sent
|
||||
|
|
|
|||
|
|
@ -32,11 +32,6 @@ from wokkel import muc
|
|||
from sat.tools import xml_tools
|
||||
|
||||
|
||||
try:
|
||||
from twisted.words.protocols.xmlstream import XMPPHandler
|
||||
except ImportError:
|
||||
from wokkel.subprotocols import XMPPHandler
|
||||
|
||||
PLUGIN_INFO = {
|
||||
"name": "XEP 0045 Plugin",
|
||||
"import_name": "XEP-0045",
|
||||
|
|
@ -53,6 +48,8 @@ PLUGIN_INFO = {
|
|||
class UnknownRoom(Exception):
|
||||
pass
|
||||
|
||||
class NotReadyYet(Exception):
|
||||
pass
|
||||
|
||||
class XEP_0045(object):
|
||||
# TODO: this plugin is messy, need a big cleanup/refactoring
|
||||
|
|
@ -67,7 +64,7 @@ class XEP_0045(object):
|
|||
host.bridge.addMethod("mucLeave", ".plugin", in_sign='ss', out_sign='', method=self.mucLeave, async=True)
|
||||
host.bridge.addMethod("getRoomsJoined", ".plugin", in_sign='s', out_sign='a(sass)', method=self.getRoomsJoined)
|
||||
host.bridge.addMethod("getRoomsSubjects", ".plugin", in_sign='s', out_sign='a(ss)', method=self.getRoomsSubjects)
|
||||
host.bridge.addMethod("getUniqueRoomName", ".plugin", in_sign='ss', out_sign='s', method=self.getUniqueName)
|
||||
host.bridge.addMethod("getUniqueRoomName", ".plugin", in_sign='ss', out_sign='s', method=self._getUniqueName)
|
||||
host.bridge.addMethod("configureRoom", ".plugin", in_sign='ss', out_sign='s', method=self._configureRoom, async=True)
|
||||
host.bridge.addSignal("roomJoined", ".plugin", signature='sasss') # args: room_jid, room_nicks, user_nick, profile
|
||||
host.bridge.addSignal("roomLeft", ".plugin", signature='ss') # args: room_jid, profile
|
||||
|
|
@ -82,8 +79,15 @@ class XEP_0045(object):
|
|||
except KeyError:
|
||||
info(_("Text commands not available"))
|
||||
|
||||
def profileConnected(self, profile):
|
||||
def assign_service(service):
|
||||
client = self.host.getClient(profile)
|
||||
client.muc_service = service
|
||||
self.getMUCService(profile_key=profile).addCallback(assign_service)
|
||||
|
||||
def __check_profile(self, profile):
|
||||
"""check if profile is used and connected
|
||||
|
||||
if profile known but disconnected, remove it from known profiles
|
||||
@param profile: profile to check
|
||||
@return: True if the profile is known and connected, else False"""
|
||||
|
|
@ -136,6 +140,7 @@ class XEP_0045(object):
|
|||
|
||||
def getRoomNick(self, room_jid_s, profile_key=C.PROF_KEY_NONE):
|
||||
"""return nick used in room by user
|
||||
|
||||
@param room_jid_s: unicode room id
|
||||
@profile_key: profile
|
||||
@return: nick or empty string in case of error"""
|
||||
|
|
@ -146,6 +151,7 @@ class XEP_0045(object):
|
|||
|
||||
def getRoomNickOfUser(self, room, user_jid, secure=True):
|
||||
"""Returns the nick of the given user in the room.
|
||||
|
||||
@room: instance of wokkel.muc.Room
|
||||
@user: JID or unicode (JID userhost).
|
||||
@param secure: set to True for a secure check
|
||||
|
|
@ -166,6 +172,7 @@ class XEP_0045(object):
|
|||
|
||||
def getRoomNicksOfUsers(self, room, users=[], secure=True):
|
||||
"""Returns the nicks of the given users in the room.
|
||||
|
||||
@room: instance of wokkel.muc.Room
|
||||
@users: list of JID or unicode (JID userhost).
|
||||
@param secure: set to True for a secure check
|
||||
|
|
@ -189,10 +196,10 @@ class XEP_0045(object):
|
|||
|
||||
def configureRoom(self, room_jid, profile_key=C.PROF_KEY_NONE):
|
||||
""" return the room configuration form
|
||||
|
||||
@param room: jid of the room to configure
|
||||
@param profile_key: %(doc_profile_key)s
|
||||
@return: configuration form as XMLUI
|
||||
|
||||
"""
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not self.__check_profile(profile):
|
||||
|
|
@ -243,38 +250,47 @@ class XEP_0045(object):
|
|||
return []
|
||||
return self.clients[profile].rec_subjects.values()
|
||||
|
||||
def getMUCService(self, profile):
|
||||
"""Return the MUC service or None"""
|
||||
@defer.inlineCallbacks
|
||||
def getMUCService(self, jid_=None, profile_key=C.PROF_KEY_NONE):
|
||||
"""Return first found MUC service of an entity
|
||||
|
||||
@param jid_: entity which may have a MUC service, or None for our own server
|
||||
@param profile_key: %(doc_profile_key)s
|
||||
"""
|
||||
muc_service = None
|
||||
for service in self.host.memory.getServerServiceEntities("conference", "text", profile=profile):
|
||||
services = yield self.host.findServiceEntities("conference", "text", jid_, profile_key=profile_key)
|
||||
for service in services:
|
||||
if not ".irc." in service.userhost():
|
||||
#FIXME:
|
||||
#This awfull ugly hack is here to avoid an issue with openfire: the irc gateway
|
||||
#use "conference/text" identity (instead of "conference/irc"), there is certainly a better way
|
||||
#to manage this, but this hack fill do it for test purpose
|
||||
# FIXME:
|
||||
# This ugly hack is here to avoid an issue with openfire: the IRC gateway
|
||||
# use "conference/text" identity (instead of "conference/irc")
|
||||
muc_service = service
|
||||
break
|
||||
return muc_service
|
||||
defer.returnValue(muc_service)
|
||||
|
||||
def _getUniqueName(self, muc_service="", profile_key=C.PROF_KEY_NONE):
|
||||
return self.getUniqueName(muc_service or None, profile_key).full()
|
||||
|
||||
def getUniqueName(self, muc_service=None, profile_key=C.PROF_KEY_NONE):
|
||||
"""Return unique name for a room, avoiding collision
|
||||
|
||||
def getUniqueName(self, muc_service="", profile_key=C.PROF_KEY_NONE):
|
||||
"""Return unique name for room, avoiding collision
|
||||
@param muc_service: leave empty string to use the default service
|
||||
@return: unique room userhost, or '' if an error occured.
|
||||
"""
|
||||
#TODO: we should use #RFC-0045 10.1.4 when available here
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not profile:
|
||||
error(_("Unknown profile"))
|
||||
return ""
|
||||
client = self.host.getClient(profile_key)
|
||||
room_name = uuid.uuid1()
|
||||
print "\n\n===> room_name:", room_name
|
||||
if muc_service == "":
|
||||
muc_service = self.getMUCService(profile)
|
||||
if not muc_service:
|
||||
error(_("Can't find a MUC service"))
|
||||
return ""
|
||||
muc_service = muc_service.userhost()
|
||||
return "%s@%s" % (room_name, muc_service)
|
||||
if muc_service is None:
|
||||
try:
|
||||
muc_service = client.muc_service
|
||||
except AttributeError:
|
||||
raise NotReadyYet("Main server MUC service has not been checked yet")
|
||||
if muc_service is None:
|
||||
warning(_("No MUC service found on main server"))
|
||||
raise exceptions.FeatureNotFound
|
||||
|
||||
muc_service = muc_service.userhost()
|
||||
return jid.JID("%s@%s" % (room_name, muc_service))
|
||||
|
||||
def join(self, room_jid, nick, options, profile_key=C.PROF_KEY_NONE):
|
||||
def _errDeferred(exc_obj=Exception, txt='Error while joining room'):
|
||||
|
|
@ -315,7 +331,7 @@ class XEP_0045(object):
|
|||
warning(mess)
|
||||
self.host.bridge.newAlert(mess, _("Group chat error"), "ERROR", profile)
|
||||
return
|
||||
d = self.join(room_jid, nick, options, profile)
|
||||
self.join(room_jid, nick, options, profile)
|
||||
# TODO: error management + signal in bridge
|
||||
return room_jid_s
|
||||
|
||||
|
|
|
|||
|
|
@ -205,7 +205,7 @@ class XEP_0050(object):
|
|||
'FORBIDDEN', 'ITEM_NOT_FOUND', 'FEATURE_NOT_IMPLEMENTED', 'INTERNAL'))(('bad-request', 'malformed-action'),
|
||||
('bad-request', 'bad-action'), ('bad-request', 'bad-locale'), ('bad-request','bad-payload'),
|
||||
('bad-request','bad-sessionid'), ('not-allowed','session-expired'), ('forbidden', None),
|
||||
('item-not-found', None), ('feature-not-implemented', None), ('internal-server-error', None)) # XEP-0050 §4.6 Table 5
|
||||
('item-not-found', None), ('feature-not-implemented', None), ('internal-server-error', None)) # XEP-0050 §4.4 Table 5
|
||||
|
||||
def __init__(self, host):
|
||||
info(_("plugin XEP-0050 initialization"))
|
||||
|
|
|
|||
|
|
@ -787,21 +787,23 @@ class XEP_0065_handler(XMPPHandler):
|
|||
"File Transfer", profile_key=self.parent.profile)
|
||||
|
||||
def connectionInitialized(self):
|
||||
def after_init(ignore):
|
||||
proxy_ent = self.host.memory.getServerServiceEntity("proxy", "bytestreams", profile=self.parent.profile)
|
||||
if not proxy_ent:
|
||||
debug(_("No proxy found on this server"))
|
||||
return
|
||||
iq_elt = jabber_client.IQ(self.parent.xmlstream, 'get')
|
||||
iq_elt["to"] = proxy_ent.full()
|
||||
iq_elt.addElement('query', NS_BS)
|
||||
iq_elt.addCallback(self._proxyDataResult)
|
||||
iq_elt.send()
|
||||
|
||||
self.xmlstream.addObserver(BS_REQUEST, self.plugin_parent.streamQuery, profile=self.parent.profile)
|
||||
proxy = self.host.memory.getParamA("Proxy", "File Transfer", profile_key=self.parent.profile)
|
||||
if not proxy:
|
||||
self.parent.client_initialized.addCallback(after_init)
|
||||
def proxiesFound(entities):
|
||||
try:
|
||||
proxy_ent = entities.pop()
|
||||
except KeyError:
|
||||
info(_("No proxy found on this server"))
|
||||
return
|
||||
iq_elt = jabber_client.IQ(self.parent.xmlstream, 'get')
|
||||
iq_elt["to"] = proxy_ent.full()
|
||||
iq_elt.addElement('query', NS_BS)
|
||||
iq_elt.addCallback(self._proxyDataResult)
|
||||
iq_elt.send()
|
||||
d = self.host.findServiceEntities("proxy", "bytestreams", profile_key=self.parent.profile)
|
||||
d.addCallback(proxiesFound)
|
||||
|
||||
|
||||
def getDiscoInfo(self, requestor, target, nodeIdentifier=''):
|
||||
return [disco.DiscoFeature(NS_BS)]
|
||||
|
|
|
|||
|
|
@ -22,16 +22,10 @@ from sat.core.constants import Const as C
|
|||
from logging import debug, info, error, warning
|
||||
from twisted.words.xish import domish
|
||||
from twisted.words.protocols.jabber import jid
|
||||
from sat.memory.persistent import PersistentBinaryDict
|
||||
import types
|
||||
|
||||
from twisted.internet import defer
|
||||
from zope.interface import implements
|
||||
|
||||
from wokkel import disco, iwokkel
|
||||
|
||||
from hashlib import sha1
|
||||
from base64 import b64encode
|
||||
|
||||
try:
|
||||
from twisted.words.protocols.xmlstream import XMPPHandler
|
||||
except ImportError:
|
||||
|
|
@ -53,97 +47,44 @@ PLUGIN_INFO = {
|
|||
}
|
||||
|
||||
|
||||
class HashGenerationError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ByteIdentity(object):
|
||||
"""This class manage identity as bytes (needed for i;octet sort),
|
||||
it is used for the hash generation"""
|
||||
|
||||
def __init__(self, identity, lang=None):
|
||||
assert isinstance(identity, disco.DiscoIdentity)
|
||||
self.category = identity.category.encode('utf-8')
|
||||
self.idType = identity.type.encode('utf-8')
|
||||
self.name = identity.name.encode('utf-8') if identity.name else ''
|
||||
self.lang = lang.encode('utf-8') if lang else ''
|
||||
|
||||
def __str__(self):
|
||||
return "%s/%s/%s/%s" % (self.category, self.idType, self.lang, self.name)
|
||||
|
||||
|
||||
class XEP_0115(object):
|
||||
cap_hash = None # capabilities hash is class variable as it is common to all profiles
|
||||
#TODO: this code is really dirty, need to clean it and try to move it to Wokkel
|
||||
|
||||
def __init__(self, host):
|
||||
info(_("Plugin XEP_0115 initialization"))
|
||||
self.host = host
|
||||
host.trigger.add("Disco Handled", self.checkHash)
|
||||
self.hash_cache = PersistentBinaryDict(NS_ENTITY_CAPABILITY) # key = hash or jid, value = features
|
||||
self.hash_cache.load()
|
||||
self.jid_hash = {} # jid to hash mapping, map to a discoInfo features if the hash method is unknown
|
||||
|
||||
def checkHash(self, profile):
|
||||
if not XEP_0115.cap_hash:
|
||||
XEP_0115.cap_hash = self.generateHash(profile)
|
||||
else:
|
||||
self.presenceHack(profile)
|
||||
return True
|
||||
host.trigger.add("Disco handled", self._checkHash)
|
||||
host.trigger.add("Presence send", self._presenceTrigger)
|
||||
|
||||
def getHandler(self, profile):
|
||||
return XEP_0115_handler(self, profile)
|
||||
|
||||
def presenceHack(self, profile):
|
||||
"""modify SatPresenceProtocol to add capabilities data"""
|
||||
def _checkHash(self, disco_d, profile):
|
||||
if XEP_0115.cap_hash is None:
|
||||
disco_d.addCallback(lambda dummy: self.recalculateHash(profile))
|
||||
return True
|
||||
|
||||
def _presenceTrigger(self, obj):
|
||||
if XEP_0115.cap_hash is not None:
|
||||
obj.addChild(XEP_0115.c_elt)
|
||||
return True
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def recalculateHash(self, profile):
|
||||
client = self.host.getClient(profile)
|
||||
presenceInst = client.presence
|
||||
disco_infos = yield client.discoHandler.info(client.jid, client.jid, '')
|
||||
cap_hash = self.host.memory.disco.generateHash(disco_infos)
|
||||
info("Our capability hash has been generated: [%s]" % cap_hash)
|
||||
debug("Generating capability domish.Element")
|
||||
c_elt = domish.Element((NS_ENTITY_CAPABILITY, 'c'))
|
||||
c_elt['hash'] = 'sha-1'
|
||||
c_elt['node'] = 'http://sat.goffi.org'
|
||||
c_elt['ver'] = XEP_0115.cap_hash
|
||||
presenceInst._c_elt = c_elt
|
||||
if "_legacy_send" in dir(presenceInst):
|
||||
debug('capabilities already added to presence instance')
|
||||
return
|
||||
|
||||
def hacked_send(self, obj):
|
||||
obj.addChild(self._c_elt)
|
||||
self._legacy_send(obj)
|
||||
new_send = types.MethodType(hacked_send, presenceInst, presenceInst.__class__)
|
||||
presenceInst._legacy_send = presenceInst.send
|
||||
presenceInst.send = new_send
|
||||
|
||||
def generateHash(self, profile_key=C.PROF_KEY_NONE):
|
||||
"""This method generate a sha1 hash as explained in xep-0115 #5.1
|
||||
it then store it in XEP_0115.cap_hash"""
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not profile:
|
||||
error('Requesting hash for an inexistant profile')
|
||||
raise HashGenerationError
|
||||
|
||||
client = self.host.getClient(profile_key)
|
||||
|
||||
def generateHash_2(services, profile):
|
||||
_s = []
|
||||
byte_identities = [ByteIdentity(service) for service in services if isinstance(service, disco.DiscoIdentity)] # FIXME: lang must be managed here
|
||||
byte_identities.sort(key=lambda i: i.lang)
|
||||
byte_identities.sort(key=lambda i: i.idType)
|
||||
byte_identities.sort(key=lambda i: i.category)
|
||||
for identity in byte_identities:
|
||||
_s.append(str(identity))
|
||||
_s.append('<')
|
||||
byte_features = [service.encode('utf-8') for service in services if isinstance(service, disco.DiscoFeature)]
|
||||
byte_features.sort() # XXX: the default sort has the same behaviour as the requested RFC 4790 i;octet sort
|
||||
for feature in byte_features:
|
||||
_s.append(feature)
|
||||
_s.append('<')
|
||||
#TODO: manage XEP-0128 data form here
|
||||
XEP_0115.cap_hash = b64encode(sha1(''.join(_s)).digest())
|
||||
debug(_('Capability hash generated: [%s]') % XEP_0115.cap_hash)
|
||||
self.presenceHack(profile)
|
||||
|
||||
client.discoHandler.info(client.jid, client.jid, '').addCallback(generateHash_2, profile)
|
||||
c_elt['node'] = C.APP_URL
|
||||
c_elt['ver'] = cap_hash
|
||||
XEP_0115.cap_hash = cap_hash
|
||||
XEP_0115.c_elt = c_elt
|
||||
if cap_hash not in self.host.memory.disco.hashes:
|
||||
self.host.memory.disco.hashes[cap_hash] = disco_infos
|
||||
self.host.memory.updateEntityData(client.jid, C.ENTITY_CAP_HASH, cap_hash, profile)
|
||||
|
||||
|
||||
class XEP_0115_handler(XMPPHandler):
|
||||
|
|
@ -163,38 +104,35 @@ class XEP_0115_handler(XMPPHandler):
|
|||
def getDiscoItems(self, requestor, target, nodeIdentifier=''):
|
||||
return []
|
||||
|
||||
def _updateCache(self, discoResult, from_jid, key):
|
||||
"""Actually update the cache
|
||||
@param discoResult: result of the requestInfo"""
|
||||
if key:
|
||||
self.plugin_parent.jid_hash[from_jid] = key
|
||||
self.plugin_parent.hash_cache[key] = discoResult.features
|
||||
else:
|
||||
#No key, that means unknown hash method
|
||||
self.plugin_parent.jid_hash[from_jid] = discoResult.features
|
||||
|
||||
@defer.inlineCallbacks
|
||||
def update(self, presence):
|
||||
"""
|
||||
Manage the capabilities of the entity
|
||||
Check if we know the version of this capatilities
|
||||
and get the capibilities if necessary
|
||||
|
||||
Check if we know the version of this capatilities and get the capibilities if necessary
|
||||
"""
|
||||
from_jid = jid.JID(presence['from'])
|
||||
c_elem = filter(lambda x: x.name == "c", presence.elements())[0] # We only want the "c" element
|
||||
c_elem = presence.elements(NS_ENTITY_CAPABILITY, 'c').next()
|
||||
try:
|
||||
ver = c_elem['ver']
|
||||
hash = c_elem['hash']
|
||||
node = c_elem['node']
|
||||
c_ver = c_elem['ver']
|
||||
c_hash = c_elem['hash']
|
||||
c_node = c_elem['node']
|
||||
except KeyError:
|
||||
warning('Received invalid capabilities tag')
|
||||
warning(_('Received invalid capabilities tag'))
|
||||
return
|
||||
if not from_jid in self.plugin_parent.jid_hash:
|
||||
if ver in self.plugin_parent.hash_cache:
|
||||
#we know that hash, we just link it with the jid
|
||||
self.plugin_parent.jid_hash[from_jid] = ver
|
||||
else:
|
||||
if hash != 'sha-1':
|
||||
#unknown hash method
|
||||
warning('Unknown hash for entity capabilities: [%s]' % hash)
|
||||
self.parent.disco.requestInfo(from_jid).addCallback(self._updateCache, from_jid, ver if hash == 'sha-1' else None)
|
||||
#TODO: me must manage the full algorithm described at XEP-0115 #5.4 part 3
|
||||
|
||||
if c_ver in self.host.memory.disco.hashes:
|
||||
# we already know the hash, we update the jid entity
|
||||
debug ("hash [%s] already in cache, updating entity" % c_ver)
|
||||
self.host.memory.updateEntityData(from_jid, C.ENTITY_CAP_HASH, c_ver, self.profile)
|
||||
return
|
||||
|
||||
yield self.host.getDiscoInfos(from_jid, self.profile)
|
||||
if c_hash != 'sha-1':
|
||||
#unknown hash method
|
||||
warning(_('Unknown hash method for entity capabilities: [%(hash_method)s] (entity: %(jid)s, node: %(node)s)') % {'hash_method':c_hash, 'jid': from_jid, 'node': c_node})
|
||||
computed_hash = self.host.memory.getEntityDatum(from_jid, C.ENTITY_CAP_HASH, self.profile)
|
||||
if computed_hash != c_ver:
|
||||
warning(_('Computed hash differ from given hash:\ngiven: [%(given_hash)s]\ncomputed: [%(computed_hash)s]\n(entity: %(jid)s, node: %(node)s)') % {'given_hash':c_ver, 'computed_hash': computed_hash, 'jid': from_jid, 'node': c_node})
|
||||
|
||||
# TODO: me must manage the full algorithm described at XEP-0115 #5.4 part 3
|
||||
|
|
|
|||
Loading…
Reference in a new issue