merged branch frontends_multi_profiles
This commit is contained in:
commit
6760c927d3
13 changed files with 4611 additions and 4514 deletions
|
|
@ -91,7 +91,7 @@ class Exp_Parrot(object):
|
|||
entity_type = "contact"
|
||||
if entity_type == 'chatroom':
|
||||
src_txt = from_jid.resource
|
||||
if src_txt == self.host.plugins["XEP-0045"].getRoomNick(from_jid.userhost(), profile):
|
||||
if src_txt == self.host.plugins["XEP-0045"].getRoomNick(from_jid.userhostJID(), profile):
|
||||
#we won't repeat our own messages
|
||||
return True
|
||||
else:
|
||||
|
|
|
|||
|
|
@ -58,9 +58,9 @@ class Quiz(object):
|
|||
log.info(_("Plugin Quiz initialization"))
|
||||
self.inheritFromRoomGame(host)
|
||||
RoomGame._init_(self, host, PLUGIN_INFO, (NS_QG, QG_TAG), game_init={'stage': None}, player_init={'score': 0})
|
||||
host.bridge.addMethod("quizGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self.prepareRoom) # args: players, room_jid, profile
|
||||
host.bridge.addMethod("quizGameCreate", ".plugin", in_sign='sass', out_sign='', method=self.createGame) # args: room_jid, players, profile
|
||||
host.bridge.addMethod("quizGameReady", ".plugin", in_sign='sss', out_sign='', method=self.playerReady) # args: player, referee, profile
|
||||
host.bridge.addMethod("quizGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self._prepareRoom) # args: players, room_jid, profile
|
||||
host.bridge.addMethod("quizGameCreate", ".plugin", in_sign='sass', out_sign='', method=self._createGame) # args: room_jid, players, profile
|
||||
host.bridge.addMethod("quizGameReady", ".plugin", in_sign='sss', out_sign='', method=self._playerReady) # args: player, referee, profile
|
||||
host.bridge.addMethod("quizGameAnswer", ".plugin", in_sign='ssss', out_sign='', method=self.playerAnswer)
|
||||
host.bridge.addSignal("quizGameStarted", ".plugin", signature='ssass') # args: room_jid, referee, players, profile
|
||||
host.bridge.addSignal("quizGameNew", ".plugin",
|
||||
|
|
@ -192,7 +192,7 @@ class Quiz(object):
|
|||
|
||||
def timerExpired(self, room_jid, profile):
|
||||
"""Called when nobody answered the question in time"""
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
game_data['stage'] = 'expired'
|
||||
mess = self.createGameElt(room_jid)
|
||||
expired_elt = mess.firstChildElement().addElement('timer_expired')
|
||||
|
|
@ -201,7 +201,7 @@ class Quiz(object):
|
|||
|
||||
def pauseTimer(self, room_jid):
|
||||
"""Stop the timer and save the time left"""
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
left = max(0, game_data["timer"].getTime() - time())
|
||||
game_data['timer'].cancel()
|
||||
game_data['time_left'] = int(left)
|
||||
|
|
@ -210,7 +210,7 @@ class Quiz(object):
|
|||
|
||||
def restartTimer(self, room_jid, profile):
|
||||
"""Restart a timer with the saved time"""
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
assert game_data['time_left'] is not None
|
||||
mess = self.createGameElt(room_jid)
|
||||
restarted_elt = mess.firstChildElement().addElement('timer_restarted')
|
||||
|
|
@ -223,7 +223,7 @@ class Quiz(object):
|
|||
|
||||
def askQuestion(self, room_jid, profile):
|
||||
"""Ask a new question"""
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
game_data['stage'] = "question"
|
||||
game_data['question_id'] = "1"
|
||||
timer = 30
|
||||
|
|
@ -235,7 +235,7 @@ class Quiz(object):
|
|||
|
||||
def checkAnswer(self, room_jid, player, answer, profile):
|
||||
"""Check if the answer given is right"""
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
players_data = game_data['players_data']
|
||||
good_answer = game_data['question_id'] == "1" and answer == "42"
|
||||
players_data[player]['score'] += 1 if good_answer else -1
|
||||
|
|
@ -264,7 +264,7 @@ Attention, tu es prêt ?""")}
|
|||
from_jid = jid.JID(mess_elt['from'])
|
||||
room_jid = jid.JID(from_jid.userhost())
|
||||
game_elt = mess_elt.firstChildElement()
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
if 'players_data' in game_data:
|
||||
players_data = game_data['players_data']
|
||||
|
||||
|
|
@ -278,8 +278,8 @@ Attention, tu es prêt ?""")}
|
|||
|
||||
elif elt.name == 'player_ready': # ready to play
|
||||
player = elt['player']
|
||||
status = self.games[room_jid.userhost()]['status']
|
||||
nb_players = len(self.games[room_jid.userhost()]['players'])
|
||||
status = self.games[room_jid]['status']
|
||||
nb_players = len(self.games[room_jid]['players'])
|
||||
status[player] = 'ready'
|
||||
log.debug(_('Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status})
|
||||
if status.values().count('ready') == nb_players: # everybody is ready, we can start the game
|
||||
|
|
@ -294,7 +294,7 @@ Attention, tu es prêt ?""")}
|
|||
elif elt.name == 'player_answer':
|
||||
player = elt['player']
|
||||
pause = game_data['stage'] == 'question' # we pause the game only if we are have a question at the moment
|
||||
#we first send a buzzer message
|
||||
# we first send a buzzer message
|
||||
mess = self.createGameElt(room_jid)
|
||||
buzzer_elt = mess.firstChildElement().addElement('player_buzzed')
|
||||
buzzer_elt['player'] = player
|
||||
|
|
@ -302,7 +302,7 @@ Attention, tu es prêt ?""")}
|
|||
self.host.profiles[profile].xmlstream.send(mess)
|
||||
if pause:
|
||||
self.pauseTimer(room_jid)
|
||||
#and we send the player answer
|
||||
# and we send the player answer
|
||||
mess = self.createGameElt(room_jid)
|
||||
_answer = unicode(elt)
|
||||
say_elt = mess.firstChildElement().addElement('player_says')
|
||||
|
|
|
|||
|
|
@ -67,10 +67,10 @@ class Radiocol(object):
|
|||
log.info(_("Radio collective initialization"))
|
||||
self.inheritFromRoomGame(host)
|
||||
RoomGame._init_(self, host, PLUGIN_INFO, (NC_RADIOCOL, RADIOC_TAG),
|
||||
game_init={'queue': [], 'upload': True, 'playing': None, 'playing_time': 0, 'to_delete': {}})
|
||||
game_init={'queue': [], 'upload': True, 'playing': None, 'playing_time': 0, 'to_delete': {}})
|
||||
self.host = host
|
||||
host.bridge.addMethod("radiocolLaunch", ".plugin", in_sign='asss', out_sign='', method=self.prepareRoom, async=True)
|
||||
host.bridge.addMethod("radiocolCreate", ".plugin", in_sign='sass', out_sign='', method=self.createGame)
|
||||
host.bridge.addMethod("radiocolLaunch", ".plugin", in_sign='asss', out_sign='', method=self._prepareRoom, async=True)
|
||||
host.bridge.addMethod("radiocolCreate", ".plugin", in_sign='sass', out_sign='', method=self._createGame)
|
||||
host.bridge.addMethod("radiocolSongAdded", ".plugin", in_sign='sss', out_sign='', method=self.radiocolSongAdded, async=True)
|
||||
host.bridge.addSignal("radiocolPlayers", ".plugin", signature='ssass') # room_jid, referee, players, profile
|
||||
host.bridge.addSignal("radiocolStarted", ".plugin", signature='ssasais') # room_jid, referee, players, [QUEUE_TO_START, QUEUE_LIMIT], profile
|
||||
|
|
@ -96,7 +96,7 @@ class Radiocol(object):
|
|||
@param profile_key: %(doc_profile_key)s
|
||||
@return: a Deferred instance
|
||||
"""
|
||||
#XXX: this is a Q&D way for the proof of concept. In the future, the song should
|
||||
# XXX: this is a Q&D way for the proof of concept. In the future, the song should
|
||||
# be streamed to the backend using XMPP file copy
|
||||
# Here we cheat because we know we are on the same host, and we don't
|
||||
# check data. Referee will have to parse the song himself to check it
|
||||
|
|
@ -115,7 +115,7 @@ class Radiocol(object):
|
|||
else:
|
||||
song = OggVorbis(song_path)
|
||||
except (OggVorbisHeaderError, HeaderNotFoundError):
|
||||
#this file is not ogg vorbis nor mp3, we reject it
|
||||
# this file is not ogg vorbis nor mp3, we reject it
|
||||
self.deleteFile(song_path) # FIXME: same host trick (see note above)
|
||||
return defer.fail(exceptions.DataError(D_("The uploaded file has been rejected, only Ogg Vorbis and MP3 songs are accepted.")))
|
||||
|
||||
|
|
@ -125,16 +125,16 @@ class Radiocol(object):
|
|||
'album': song.get("album", ["Unknown"])[0],
|
||||
'length': str(song.info.length)
|
||||
}
|
||||
radio_data = self.games[jid.JID(referee).userhost()] # FIXME: referee comes from Libervia's client side, it's unsecure
|
||||
radio_data = self.games[jid.JID(referee).userhostJID()] # FIXME: referee comes from Libervia's client side, it's unsecure
|
||||
radio_data['to_delete'][attrs['filename']] = song_path # FIXME: works only because of the same host trick, see the note under the docstring
|
||||
return self.send(jid.JID(referee), ('', 'song_added'), attrs, profile=profile)
|
||||
|
||||
def playNext(self, room_jid, profile):
|
||||
""""Play next song in queue if exists, and put a timer
|
||||
which trigger after the song has been played to play next one"""
|
||||
#TODO: songs need to be erased once played or found invalids
|
||||
# TODO: songs need to be erased once played or found invalids
|
||||
# ==> unlink done the Q&D way with the same host trick (see above)
|
||||
radio_data = self.games[room_jid.userhost()]
|
||||
radio_data = self.games[room_jid]
|
||||
if len(radio_data['players']) == 0:
|
||||
log.debug(_('No more participants in the radiocol: cleaning data'))
|
||||
radio_data['queue'] = []
|
||||
|
|
@ -143,7 +143,7 @@ class Radiocol(object):
|
|||
radio_data['to_delete'] = {}
|
||||
queue = radio_data['queue']
|
||||
if not queue:
|
||||
#nothing left to play, we need to wait for uploads
|
||||
# nothing left to play, we need to wait for uploads
|
||||
radio_data['playing'] = None
|
||||
return
|
||||
song = queue.pop(0)
|
||||
|
|
@ -153,12 +153,12 @@ class Radiocol(object):
|
|||
radio_data['playing_time'] = time.time()
|
||||
|
||||
if not radio_data['upload'] and len(queue) < QUEUE_LIMIT:
|
||||
#upload is blocked and we now have resources to get more, we reactivate it
|
||||
# upload is blocked and we now have resources to get more, we reactivate it
|
||||
self.send(room_jid, ('', 'upload_ok'), profile=profile)
|
||||
radio_data['upload'] = True
|
||||
|
||||
reactor.callLater(length, self.playNext, room_jid, profile)
|
||||
#we wait more than the song length to delete the file, to manage poorly reactive networks/clients
|
||||
# we wait more than the song length to delete the file, to manage poorly reactive networks/clients
|
||||
reactor.callLater(length + 90, self.deleteFile, filename, radio_data) # FIXME: same host trick (see above)
|
||||
|
||||
def deleteFile(self, filename, radio_data=None):
|
||||
|
|
@ -185,17 +185,17 @@ class Radiocol(object):
|
|||
|
||||
def room_game_cmd(self, mess_elt, profile):
|
||||
from_jid = jid.JID(mess_elt['from'])
|
||||
room_jid = jid.JID(from_jid.userhost())
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid.userhost(), profile)
|
||||
room_jid = from_jid.userhostJID()
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
|
||||
|
||||
radio_elt = mess_elt.firstChildElement()
|
||||
radio_data = self.games[room_jid.userhost()]
|
||||
radio_data = self.games[room_jid]
|
||||
if 'queue' in radio_data:
|
||||
queue = radio_data['queue']
|
||||
|
||||
from_referee = self.isReferee(room_jid.userhost(), from_jid.resource)
|
||||
to_referee = self.isReferee(room_jid.userhost(), jid.JID(mess_elt['to']).user)
|
||||
is_player = self.isPlayer(room_jid.userhost(), nick)
|
||||
from_referee = self.isReferee(room_jid, from_jid.resource)
|
||||
to_referee = self.isReferee(room_jid, jid.JID(mess_elt['to']).user)
|
||||
is_player = self.isPlayer(room_jid, nick)
|
||||
for elt in radio_elt.elements():
|
||||
if not from_referee and not (to_referee and elt.name == 'song_added'):
|
||||
continue # sender must be referee, expect when a song is submitted
|
||||
|
|
@ -219,20 +219,20 @@ class Radiocol(object):
|
|||
elif elt.name == 'upload_ok':
|
||||
self.host.bridge.radiocolUploadOk(room_jid.userhost(), profile)
|
||||
elif elt.name == 'song_added': # a song has been added
|
||||
#FIXME: we are KISS for the proof of concept: every song is added, to a limit of 3 in queue.
|
||||
# FIXME: we are KISS for the proof of concept: every song is added, to a limit of 3 in queue.
|
||||
# Need to manage some sort of rules to allow peoples to send songs
|
||||
if len(queue) >= QUEUE_LIMIT:
|
||||
#there are already too many songs in queue, we reject this one
|
||||
#FIXME: add an error code
|
||||
# there are already too many songs in queue, we reject this one
|
||||
# FIXME: add an error code
|
||||
self.send(from_jid, ('', 'song_rejected'), {'reason': "Too many songs in queue"}, profile=profile)
|
||||
return
|
||||
|
||||
#The song is accepted and added in queue
|
||||
# The song is accepted and added in queue
|
||||
preload_elt = self.__create_preload_elt(from_jid.resource, elt)
|
||||
queue.append(preload_elt)
|
||||
|
||||
if len(queue) >= QUEUE_LIMIT:
|
||||
#We are at the limit, we refuse new upload until next play
|
||||
# We are at the limit, we refuse new upload until next play
|
||||
self.send(room_jid, ('', 'no_upload'), profile=profile)
|
||||
radio_data['upload'] = False
|
||||
|
||||
|
|
@ -244,8 +244,8 @@ class Radiocol(object):
|
|||
else:
|
||||
log.error(_('Unmanaged game element: %s') % elt.name)
|
||||
|
||||
def getSyncDataForPlayer(self, room_jid_s, nick):
|
||||
game_data = self.games[room_jid_s]
|
||||
def getSyncDataForPlayer(self, room_jid, nick):
|
||||
game_data = self.games[room_jid]
|
||||
elements = []
|
||||
if game_data['playing']:
|
||||
preload = copy.deepcopy(game_data['playing'])
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ from sat.core.i18n import _
|
|||
from sat.core.constants import Const as C
|
||||
from sat.core.log import getLogger
|
||||
log = getLogger(__name__)
|
||||
from twisted.words.protocols.jabber.jid import JID
|
||||
from twisted.words.protocols.jabber import jid
|
||||
from twisted.words.xish import domish
|
||||
from twisted.internet import defer
|
||||
from time import time
|
||||
|
|
@ -51,7 +51,7 @@ PLUGIN_INFO = {
|
|||
class RoomGame(object):
|
||||
"""This class is used to help launching a MUC game.
|
||||
|
||||
Bridge methods callbacks: prepareRoom, playerReady, createGame
|
||||
Bridge methods callbacks: _prepareRoom, _playerReady, _createGame
|
||||
Triggered methods: userJoinedTrigger, userLeftTrigger
|
||||
Also called from subclasses: newRound
|
||||
|
||||
|
|
@ -107,7 +107,7 @@ class RoomGame(object):
|
|||
self.game_init = game_init
|
||||
self.player_init = player_init
|
||||
self.games = {}
|
||||
self.invitations = {} # list of couple (x, y) with x the time and y a list of users
|
||||
self.invitations = {} # values are a couple (x, y) with x the time and y a list of users
|
||||
|
||||
# These are the default settings, which can be overwritten by child class after initialization
|
||||
self.invite_mode = self.FROM_PLAYERS if self.player_init == {} else self.FROM_NONE
|
||||
|
|
@ -126,129 +126,134 @@ class RoomGame(object):
|
|||
def _createOrInvite(self, room, other_players, profile):
|
||||
"""
|
||||
This is called only when someone explicitly wants to play.
|
||||
|
||||
The game will not be created if one already exists in the room,
|
||||
also its creation could be postponed until all the expected players
|
||||
join the room (in that case it will be created from userJoinedTrigger).
|
||||
@param room: instance of wokkel.muc.Room
|
||||
@param other_players: list for other players JID userhosts
|
||||
@param room (wokkel.muc.Room): the room
|
||||
@param other_players (list[jid.JID]): list of the other players JID (bare)
|
||||
"""
|
||||
user_jid = self.host.getJidNStream(profile)[0]
|
||||
room_jid_s = room.occupantJID.userhost()
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
|
||||
room_jid = room.occupantJID.userhostJID()
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
|
||||
nicks = [nick]
|
||||
if self._gameExists(room_jid_s):
|
||||
if not self._checkJoinAuth(room_jid_s, user_jid.userhost(), nick):
|
||||
if self._gameExists(room_jid):
|
||||
if not self._checkJoinAuth(room_jid, user_jid, nick):
|
||||
return
|
||||
nicks.extend(self._invitePlayers(room, other_players, nick, profile))
|
||||
self._updatePlayers(room_jid_s, nicks, True, profile)
|
||||
self._updatePlayers(room_jid, nicks, True, profile)
|
||||
else:
|
||||
self._initGame(room_jid_s, nick)
|
||||
self._initGame(room_jid, nick)
|
||||
(auth, waiting, missing) = self._checkWaitAuth(room, other_players)
|
||||
nicks.extend(waiting)
|
||||
nicks.extend(self._invitePlayers(room, missing, nick, profile))
|
||||
if auth:
|
||||
self.createGame(room_jid_s, nicks, profile)
|
||||
self.createGame(room_jid, nicks, profile)
|
||||
else:
|
||||
self._updatePlayers(room_jid_s, nicks, False, profile)
|
||||
self._updatePlayers(room_jid, nicks, False, profile)
|
||||
|
||||
def _initGame(self, room_jid_s, referee_nick):
|
||||
"""Important: do not add the referee to 'players' yet. For a
|
||||
<players /> message to be emitted whenever a new player is joining,
|
||||
it is necessary to not modify 'players' outside of _updatePlayers.
|
||||
def _initGame(self, room_jid, referee_nick):
|
||||
"""
|
||||
referee = room_jid_s + '/' + referee_nick
|
||||
self.games[room_jid_s] = {'referee': referee, 'players': [], 'started': False, 'status': {}}
|
||||
self.games[room_jid_s].update(copy.deepcopy(self.game_init))
|
||||
self.invitations.setdefault(room_jid_s, [])
|
||||
|
||||
def _gameExists(self, room_jid_s, started=False):
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param referee_nick (unicode): nickname of the referee
|
||||
"""
|
||||
# Important: do not add the referee to 'players' yet. For a
|
||||
# <players /> message to be emitted whenever a new player is joining,
|
||||
# it is necessary to not modify 'players' outside of _updatePlayers.
|
||||
referee_jid = jid.JID(room_jid.userhost() + '/' + referee_nick)
|
||||
self.games[room_jid] = {'referee': referee_jid, 'players': [], 'started': False, 'status': {}}
|
||||
self.games[room_jid].update(copy.deepcopy(self.game_init))
|
||||
self.invitations.setdefault(room_jid, [])
|
||||
|
||||
def _gameExists(self, room_jid, started=False):
|
||||
"""Return True if a game has been initialized/started.
|
||||
@param started: if False, the game must be initialized to return True,
|
||||
otherwise it must be initialized and started with createGame.
|
||||
@return: True if a game is initialized/started in that room"""
|
||||
return room_jid_s in self.games and (not started or self.games[room_jid_s]['started'])
|
||||
return room_jid in self.games and (not started or self.games[room_jid]['started'])
|
||||
|
||||
def _checkJoinAuth(self, room_jid_s, user_jid_s=None, nick="", verbose=False):
|
||||
def _checkJoinAuth(self, room_jid, user_jid=None, nick="", verbose=False):
|
||||
"""Checks if this profile is allowed to join the game.
|
||||
|
||||
The parameter nick is used to check if the user is already
|
||||
a player in that game. When this method is called from
|
||||
userJoinedTrigger, nick is also used to check the user
|
||||
identity instead of user_jid_s (see TODO comment below).
|
||||
@param room_jid_s: the room hosting the game
|
||||
@param user_jid_s: JID userhost of the user
|
||||
@param nick: nick of the user
|
||||
@param room_jid (jid.JID): the JID of the room hosting the game
|
||||
@param user_jid (jid.JID): JID of the user
|
||||
@param nick (unicode): nick of the user
|
||||
@return: True if this profile can join the game
|
||||
"""
|
||||
auth = False
|
||||
if not self._gameExists(room_jid_s):
|
||||
if not self._gameExists(room_jid):
|
||||
auth = False
|
||||
elif self.join_mode == self.ALL or self.isPlayer(room_jid_s, nick):
|
||||
elif self.join_mode == self.ALL or self.isPlayer(room_jid, nick):
|
||||
auth = True
|
||||
elif self.join_mode == self.INVITED:
|
||||
user_jid_s = JID(user_jid_s).userhost()
|
||||
# considering all the batches of invitations
|
||||
for invitations in self.invitations[room_jid_s]:
|
||||
if user_jid_s is not None:
|
||||
if user_jid_s in invitations[1]:
|
||||
for invitations in self.invitations[room_jid]:
|
||||
if user_jid is not None:
|
||||
if user_jid.userhostJID() in invitations[1]:
|
||||
auth = True
|
||||
break
|
||||
else:
|
||||
# TODO: that's not secure enough but what to do if
|
||||
# wokkel.muc.User's 'entity' attribute is not set?!
|
||||
if nick in [JID(invited).user for invited in invitations[1]]:
|
||||
if nick in [invited.user for invited in invitations[1]]:
|
||||
auth = True
|
||||
break
|
||||
|
||||
if not auth and (verbose or _DEBUG):
|
||||
log.debug(_("%(user)s not allowed to join the game %(game)s in %(room)s") % {'user': user_jid_s or nick, 'game': self.name, 'room': room_jid_s})
|
||||
log.debug(_("%(user)s not allowed to join the game %(game)s in %(room)s") % {'user': user_jid.userhost() or nick, 'game': self.name, 'room': room_jid.userhost()})
|
||||
return auth
|
||||
|
||||
def _updatePlayers(self, room_jid_s, nicks, sync, profile):
|
||||
def _updatePlayers(self, room_jid, nicks, sync, profile):
|
||||
"""Update the list of players and signal to the room that some players joined the game.
|
||||
If sync is True, the news players are synchronized with the game data they have missed.
|
||||
Remark: self.games[room_jid_s]['players'] should not be modified outside this method.
|
||||
@param room_jid_s: room userhost
|
||||
@param nicks: list of players nicks in the room (referee included, in first position)
|
||||
@param sync: set to True to send synchronization data to the new players
|
||||
@param profile
|
||||
Remark: self.games[room_jid]['players'] should not be modified outside this method.
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param nicks (list[unicode]): list of players nicks in the room (referee included, in first position)
|
||||
@param sync (bool): set to True to send synchronization data to the new players
|
||||
@param profile (unicode): %(doc_profile)s
|
||||
"""
|
||||
if nicks == []:
|
||||
return
|
||||
# this is better than set(nicks).difference(...) as it keeps the order
|
||||
new_nicks = [nick for nick in nicks if nick not in self.games[room_jid_s]['players']]
|
||||
new_nicks = [nick for nick in nicks if nick not in self.games[room_jid]['players']]
|
||||
if len(new_nicks) == 0:
|
||||
return
|
||||
|
||||
def setStatus(status):
|
||||
for nick in new_nicks:
|
||||
self.games[room_jid_s]['status'][nick] = status
|
||||
self.games[room_jid]['status'][nick] = status
|
||||
|
||||
sync = sync and self._gameExists(room_jid_s, True) and len(self.games[room_jid_s]['players']) > 0
|
||||
sync = sync and self._gameExists(room_jid, True) and len(self.games[room_jid]['players']) > 0
|
||||
setStatus('desync' if sync else 'init')
|
||||
self.games[room_jid_s]['players'].extend(new_nicks)
|
||||
self._synchronizeRoom(room_jid_s, [JID(room_jid_s)], profile)
|
||||
self.games[room_jid]['players'].extend(new_nicks)
|
||||
self._synchronizeRoom(room_jid, [room_jid], profile)
|
||||
if sync:
|
||||
setStatus('init')
|
||||
|
||||
def _synchronizeRoom(self, room_jid_s, recipients, profile):
|
||||
def _synchronizeRoom(self, room_jid, recipients, profile):
|
||||
"""Communicate the list of players to the whole room or only to some users,
|
||||
also send the synchronization data to the players who recently joined the game.
|
||||
@param room_jid_s: room userhost
|
||||
@recipients: list of JIDs, the recipients of the message could be:
|
||||
- room JID
|
||||
- room JID + "/" + user nick
|
||||
@param profile
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@recipients (list[jid.JID]): list of JIDs, the recipients of the message could be:
|
||||
- room JID
|
||||
- room JID + "/" + user nick
|
||||
@param profile (unicode): %(doc_profile)s
|
||||
"""
|
||||
if self._gameExists(room_jid_s, started=True):
|
||||
element = self._createStartElement(self.games[room_jid_s]['players'])
|
||||
if self._gameExists(room_jid, started=True):
|
||||
element = self._createStartElement(self.games[room_jid]['players'])
|
||||
else:
|
||||
element = self._createStartElement(self.games[room_jid_s]['players'], name="players")
|
||||
element = self._createStartElement(self.games[room_jid]['players'], name="players")
|
||||
elements = [(element, None, None)]
|
||||
|
||||
sync_args = []
|
||||
sync_data = self._getSyncData(room_jid_s)
|
||||
sync_data = self._getSyncData(room_jid)
|
||||
for nick in sync_data:
|
||||
user_jid = JID(room_jid_s + '/' + nick)
|
||||
user_jid = jid.JID(room_jid.userhost() + '/' + nick)
|
||||
if user_jid in recipients:
|
||||
user_elements = copy.deepcopy(elements)
|
||||
for child in sync_data[nick]:
|
||||
|
|
@ -263,18 +268,18 @@ class RoomGame(object):
|
|||
for args, kwargs in sync_args:
|
||||
self._sendElements(*args, **kwargs)
|
||||
|
||||
def _getSyncData(self, room_jid_s, force_nicks=None):
|
||||
def _getSyncData(self, room_jid, force_nicks=None):
|
||||
"""The synchronization data are returned for each player who
|
||||
has the state 'desync' or if he's been contained by force_nicks.
|
||||
@param room_jid_s: room userhost
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param force_nicks: force the synchronization for this list of the nicks
|
||||
@return: a mapping between player nicks and a list of elements to
|
||||
be sent by self._synchronizeRoom for the game to be synchronized.
|
||||
"""
|
||||
if not self._gameExists(room_jid_s):
|
||||
if not self._gameExists(room_jid):
|
||||
return {}
|
||||
data = {}
|
||||
status = self.games[room_jid_s]['status']
|
||||
status = self.games[room_jid]['status']
|
||||
nicks = [nick for nick in status if status[nick] == 'desync']
|
||||
if force_nicks is None:
|
||||
force_nicks = []
|
||||
|
|
@ -282,14 +287,14 @@ class RoomGame(object):
|
|||
if nick not in nicks:
|
||||
nicks.append(nick)
|
||||
for nick in nicks:
|
||||
elements = self.getSyncDataForPlayer(room_jid_s, nick)
|
||||
elements = self.getSyncDataForPlayer(room_jid, nick)
|
||||
if elements:
|
||||
data[nick] = elements
|
||||
return data
|
||||
|
||||
def getSyncDataForPlayer(self, room_jid_s, nick):
|
||||
def getSyncDataForPlayer(self, room_jid, nick):
|
||||
"""This method may (and should probably) be overwritten by a child class.
|
||||
@param room_jid_s: room userhost
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param nick: the nick of the player to be synchronized
|
||||
@return: a list of elements to synchronize this player with the game.
|
||||
"""
|
||||
|
|
@ -297,20 +302,19 @@ class RoomGame(object):
|
|||
|
||||
def _invitePlayers(self, room, other_players, nick, profile):
|
||||
"""Invite players to a room, associated game may exist or not.
|
||||
@param room: wokkel.muc.Room instance
|
||||
@param other_players: list of JID userhosts to invite
|
||||
@param nick: nick of the user who send the invitation
|
||||
@return: list of room nicks for invited players who are already in the room
|
||||
|
||||
@param room (wokkel.muc.Room): the room
|
||||
@param other_players (list[jid.JID]): list of the players to invite
|
||||
@param nick (unicode): nick of the user who send the invitation
|
||||
@return: list[unicode] of room nicks for invited players who are already in the room
|
||||
"""
|
||||
room_jid = room.occupantJID.userhostJID()
|
||||
room_jid_s = room.occupantJID.userhost()
|
||||
if not self._checkInviteAuth(room_jid_s, nick):
|
||||
if not self._checkInviteAuth(room_jid, nick):
|
||||
return []
|
||||
# TODO: remove invitation waiting for too long, using the time data
|
||||
players_jids = [JID(player) for player in other_players]
|
||||
self.invitations[room_jid_s].append((time(), [player.userhost() for player in players_jids]))
|
||||
self.invitations[room_jid].append((time(), [player.userhostJID() for player in other_players]))
|
||||
nicks = []
|
||||
for player_jid in [player.userhostJID() for player in players_jids]:
|
||||
for player_jid in [player.userhostJID() for player in other_players]:
|
||||
# TODO: find a way to make it secure
|
||||
other_nick = self.host.plugins["XEP-0045"].getRoomNickOfUser(room, player_jid, secure=self.testing)
|
||||
if other_nick is None:
|
||||
|
|
@ -319,58 +323,59 @@ class RoomGame(object):
|
|||
nicks.append(other_nick)
|
||||
return nicks
|
||||
|
||||
def _checkInviteAuth(self, room_jid_s, nick, verbose=False):
|
||||
def _checkInviteAuth(self, room_jid, nick, verbose=False):
|
||||
"""Checks if this user is allowed to invite players
|
||||
@param room_jid_s: room userhost
|
||||
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param nick: user nick in the room
|
||||
@param verbose: display debug message
|
||||
@return: True if the user is allowed to invite other players
|
||||
"""
|
||||
auth = False
|
||||
if self.invite_mode == self.FROM_ALL or not self._gameExists(room_jid_s):
|
||||
if self.invite_mode == self.FROM_ALL or not self._gameExists(room_jid):
|
||||
auth = True
|
||||
elif self.invite_mode == self.FROM_NONE:
|
||||
auth = not self._gameExists(room_jid_s, started=True) and self.isReferee(room_jid_s, nick)
|
||||
auth = not self._gameExists(room_jid, started=True) and self.isReferee(room_jid, nick)
|
||||
elif self.invite_mode == self.FROM_REFEREE:
|
||||
auth = self.isReferee(room_jid_s, nick)
|
||||
auth = self.isReferee(room_jid, nick)
|
||||
elif self.invite_mode == self.FROM_PLAYERS:
|
||||
auth = self.isPlayer(room_jid_s, nick)
|
||||
auth = self.isPlayer(room_jid, nick)
|
||||
if not auth and (verbose or _DEBUG):
|
||||
log.debug(_("%(user)s not allowed to invite for the game %(game)s in %(room)s") % {'user': nick, 'game': self.name, 'room': room_jid_s})
|
||||
log.debug(_("%(user)s not allowed to invite for the game %(game)s in %(room)s") % {'user': nick, 'game': self.name, 'room': room_jid.userhost()})
|
||||
return auth
|
||||
|
||||
def isReferee(self, room_jid_s, nick):
|
||||
def isReferee(self, room_jid, nick):
|
||||
"""Checks if the player with this nick is the referee for the game in this room"
|
||||
@param room_jid_s: room userhost
|
||||
@param room_jid (jid.JID): room JID
|
||||
@param nick: user nick in the room
|
||||
@return: True if the user is the referee of the game in this room
|
||||
"""
|
||||
if not self._gameExists(room_jid_s):
|
||||
if not self._gameExists(room_jid):
|
||||
return False
|
||||
return room_jid_s + '/' + nick == self.games[room_jid_s]['referee']
|
||||
return jid.JID(room_jid.userhost() + '/' + nick) == self.games[room_jid]['referee']
|
||||
|
||||
def isPlayer(self, room_jid_s, nick):
|
||||
def isPlayer(self, room_jid, nick):
|
||||
"""Checks if the user with this nick is a player for the game in this room.
|
||||
@param room_jid_s: room userhost
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@param nick: user nick in the room
|
||||
@return: True if the user is a player of the game in this room
|
||||
"""
|
||||
if not self._gameExists(room_jid_s):
|
||||
if not self._gameExists(room_jid):
|
||||
return False
|
||||
# Important: the referee is not in the 'players' list right after
|
||||
# the game initialization, that's why we do also check with isReferee
|
||||
return nick in self.games[room_jid_s]['players'] or self.isReferee(room_jid_s, nick)
|
||||
return nick in self.games[room_jid]['players'] or self.isReferee(room_jid, nick)
|
||||
|
||||
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
|
||||
@param room (wokkel.muc.Room): the room
|
||||
@param other_players (list[jid.JID]): list of the players without the referee
|
||||
@param verbose (bool): display debug message
|
||||
@return: (x, y, z) with:
|
||||
x: False if we must wait, True otherwise
|
||||
y: the nicks of the players that have been checked and confirmed
|
||||
z: the players that have not been checked or that are missing
|
||||
x: False if we must wait, True otherwise
|
||||
y: the nicks of the players that have been checked and confirmed
|
||||
z: the JID of the players that have not been checked or that are missing
|
||||
"""
|
||||
if self.wait_mode == self.FOR_NONE or other_players == []:
|
||||
result = (True, [], other_players)
|
||||
|
|
@ -388,20 +393,25 @@ class RoomGame(object):
|
|||
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: %(doc_profile_key)s
|
||||
@return: a unique name for a new room to be created
|
||||
@param muc_service (jid.JID): you can leave empty to autofind the muc service
|
||||
@param profile_key (unicode): %(doc_profile_key)s
|
||||
@return: jid.JID (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.full())
|
||||
return jid.JID("sat_%s_%s" % (self.name.lower(), room.userhost()))
|
||||
|
||||
def prepareRoom(self, other_players=None, room_jid_s=None, profile_key=C.PROF_KEY_NONE):
|
||||
def _prepareRoom(self, other_players=None, room_jid_s='', profile_key=C.PROF_KEY_NONE):
|
||||
room_jid = jid.JID(room_jid_s) if room_jid_s else None
|
||||
other_players = [jid.JID(player).userhostJID() for player in other_players]
|
||||
return self.prepareRoom(other_players, room_jid, profile_key)
|
||||
|
||||
def prepareRoom(self, other_players=None, room_jid=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
|
||||
@param other_players (list[JID]): list of other players JID (bare)
|
||||
@param room_jid (jid.JID): JID of the room, or None to generate a unique name
|
||||
@param profile_key (unicode): %(doc_profile_key)s
|
||||
"""
|
||||
log.debug(_('Preparing room for %s game') % self.name)
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
|
|
@ -413,19 +423,18 @@ class RoomGame(object):
|
|||
|
||||
def roomJoined(room):
|
||||
"""@param room: instance of wokkel.muc.Room"""
|
||||
self._createOrInvite(room, [JID(player).userhost() for player in other_players], profile)
|
||||
self._createOrInvite(room, other_players, profile)
|
||||
|
||||
# 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 defer.succeed(None)
|
||||
if room_jid is None:
|
||||
room_jid = self.getUniqueName(profile_key=profile_key)
|
||||
else:
|
||||
room_jid_s = self.getUniqueName(profile_key=profile_key)
|
||||
if room_jid_s == "":
|
||||
if room_jid in self.host.plugins["XEP-0045"].clients[profile].joined_rooms:
|
||||
roomJoined(self.host.plugins["XEP-0045"].clients[profile].joined_rooms[room_jid])
|
||||
return defer.succeed(None)
|
||||
|
||||
user_jid = self.host.getJidNStream(profile)[0]
|
||||
d = self.host.plugins["XEP-0045"].join(JID(room_jid_s), user_jid.user, {}, profile)
|
||||
d = self.host.plugins["XEP-0045"].join(room_jid, user_jid.user, {}, profile)
|
||||
return d.addCallback(roomJoined)
|
||||
|
||||
def userJoinedTrigger(self, room, user, profile):
|
||||
|
|
@ -435,29 +444,29 @@ class RoomGame(object):
|
|||
@user: wokkel.muc.User object. user.nick is a unicode and user.entity a JID
|
||||
@return: True to not interrupt the main process.
|
||||
"""
|
||||
room_jid_s = room.occupantJID.userhost()
|
||||
room_jid = room.occupantJID.userhostJID()
|
||||
profile_nick = room.occupantJID.resource
|
||||
if not self.isReferee(room_jid_s, profile_nick):
|
||||
if not self.isReferee(room_jid, profile_nick):
|
||||
return True # profile is not the referee
|
||||
if not self._checkJoinAuth(room_jid_s, user.entity.userhost() if user.entity else None, user.nick):
|
||||
if not self._checkJoinAuth(room_jid, user.entity if user.entity else None, user.nick):
|
||||
# user not allowed but let him know that we are playing :p
|
||||
self._synchronizeRoom(room_jid_s, [JID(room_jid_s + '/' + user.nick)], profile)
|
||||
self._synchronizeRoom(room_jid, [jid.JID(room_jid.userhost() + '/' + user.nick)], profile)
|
||||
return True
|
||||
if self.wait_mode == self.FOR_ALL:
|
||||
# considering the last batch of invitations
|
||||
batch = len(self.invitations[room_jid_s]) - 1
|
||||
batch = len(self.invitations[room_jid]) - 1
|
||||
if batch < 0:
|
||||
log.error("Invitations from %s to play %s in %s have been lost!" % (profile_nick, self.name, room_jid_s))
|
||||
log.error("Invitations from %s to play %s in %s have been lost!" % (profile_nick, self.name, room_jid.userhost()))
|
||||
return True
|
||||
other_players = self.invitations[room_jid_s][batch][1]
|
||||
other_players = self.invitations[room_jid][batch][1]
|
||||
(auth, nicks, dummy) = self._checkWaitAuth(room, other_players)
|
||||
if auth:
|
||||
del self.invitations[room_jid_s][batch]
|
||||
del self.invitations[room_jid][batch]
|
||||
nicks.insert(0, profile_nick) # add the referee
|
||||
self.createGame(room_jid_s, nicks, profile_key=profile)
|
||||
self.createGame(room_jid, nicks, profile_key=profile)
|
||||
return True
|
||||
# let the room know that a new player joined
|
||||
self._updatePlayers(room_jid_s, [user.nick], True, profile)
|
||||
self._updatePlayers(room_jid, [user.nick], True, profile)
|
||||
return True
|
||||
|
||||
def userLeftTrigger(self, room, user, profile):
|
||||
|
|
@ -467,89 +476,95 @@ class RoomGame(object):
|
|||
@user: wokkel.muc.User object. user.nick is a unicode and user.entity a JID
|
||||
@return: True to not interrupt the main process.
|
||||
"""
|
||||
room_jid_s = room.occupantJID.userhost()
|
||||
room_jid = room.occupantJID.userhostJID()
|
||||
profile_nick = room.occupantJID.resource
|
||||
if not self.isReferee(room_jid_s, profile_nick):
|
||||
if not self.isReferee(room_jid, profile_nick):
|
||||
return True # profile is not the referee
|
||||
if self.isPlayer(room_jid_s, user.nick):
|
||||
if self.isPlayer(room_jid, user.nick):
|
||||
try:
|
||||
self.games[room_jid_s]['players'].remove(user.nick)
|
||||
self.games[room_jid]['players'].remove(user.nick)
|
||||
except ValueError:
|
||||
pass
|
||||
if len(self.games[room_jid_s]['players']) == 0:
|
||||
del self.games[room_jid_s] # finish the game
|
||||
if len(self.games[room_jid]['players']) == 0:
|
||||
return True
|
||||
if self.wait_mode == self.FOR_ALL:
|
||||
# allow this user to join the game again
|
||||
user_jid_s = user.entity.userhost()
|
||||
if len(self.invitations[room_jid_s]) == 0:
|
||||
self.invitations[room_jid_s].append((time(), [user_jid_s]))
|
||||
user_jid = user.entity.userhostJID()
|
||||
if len(self.invitations[room_jid]) == 0:
|
||||
self.invitations[room_jid].append((time(), [user_jid]))
|
||||
else:
|
||||
batch = 0 # add to the first batch of invitations
|
||||
if user_jid_s not in self.invitations[room_jid_s][batch][1]:
|
||||
self.invitations[room_jid_s][batch][1].append(user_jid_s)
|
||||
if user_jid not in self.invitations[room_jid][batch][1]:
|
||||
self.invitations[room_jid][batch][1].append(user_jid)
|
||||
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.
|
||||
def _checkCreateGameAndInit(self, room_jid, 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.
|
||||
|
||||
@param room_jid_s: room userhost
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@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
|
||||
"""
|
||||
user_nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
|
||||
user_nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
|
||||
if not user_nick:
|
||||
log.error('Internal error: profile %s has not joined the room %s' % (profile, room_jid_s))
|
||||
log.error('Internal error: profile %s has not joined the room %s' % (profile, room_jid.userhost()))
|
||||
return False, False
|
||||
if self._gameExists(room_jid_s):
|
||||
is_referee = self.isReferee(room_jid_s, user_nick)
|
||||
if self._gameExists(room_jid_s, started=True):
|
||||
log.warning(_("%(game)s game already created in room %(room)s") % {'game': self.name, 'room': room_jid_s})
|
||||
if self._gameExists(room_jid):
|
||||
is_referee = self.isReferee(room_jid, user_nick)
|
||||
if self._gameExists(room_jid, started=True):
|
||||
log.warning(_("%(game)s game already created in room %(room)s") % {'game': self.name, 'room': room_jid.userhost()})
|
||||
return False, is_referee
|
||||
elif not is_referee:
|
||||
log.warning(_("%(game)s game in room %(room)s can only be created by %(user)s") % {'game': self.name, 'room': room_jid_s, 'user': user_nick})
|
||||
log.warning(_("%(game)s game in room %(room)s can only be created by %(user)s") % {'game': self.name, 'room': room_jid.userhost(), 'user': user_nick})
|
||||
return False, False
|
||||
else:
|
||||
self._initGame(room_jid_s, user_nick)
|
||||
self._initGame(room_jid, user_nick)
|
||||
return True, False
|
||||
|
||||
def createGame(self, room_jid_s, nicks=None, profile_key=C.PROF_KEY_NONE):
|
||||
def _createGame(self, room_jid_s, nicks=None, profile_key=C.PROF_KEY_NONE):
|
||||
self.createGame(jid.JID(room_jid_s), nicks, profile_key)
|
||||
|
||||
def createGame(self, room_jid, 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.
|
||||
@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 room_jid (jid.JID): JID of the room
|
||||
@param nicks (list[unicode]): list of players nicks in the room (referee included, in first position)
|
||||
@param profile_key (unicode): %(doc_profile_key)s
|
||||
"""
|
||||
log.debug(_("Creating %(game)s game in room %(room)s") % {'game': self.name, 'room': room_jid_s})
|
||||
log.debug(_("Creating %(game)s game in room %(room)s") % {'game': self.name, 'room': room_jid})
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not profile:
|
||||
log.error(_("profile %s is unknown") % profile_key)
|
||||
return
|
||||
(create, sync) = self._checkCreateGameAndInit(room_jid_s, profile)
|
||||
(create, sync) = self._checkCreateGameAndInit(room_jid, profile)
|
||||
if nicks is None:
|
||||
nicks = []
|
||||
if not create:
|
||||
if sync:
|
||||
self._updatePlayers(room_jid_s, nicks, True, profile)
|
||||
self._updatePlayers(room_jid, nicks, True, profile)
|
||||
return
|
||||
self.games[room_jid_s]['started'] = True
|
||||
self._updatePlayers(room_jid_s, nicks, False, profile)
|
||||
self.games[room_jid]['started'] = True
|
||||
self._updatePlayers(room_jid, nicks, False, profile)
|
||||
if self.player_init:
|
||||
# specific data to each player (score, private data)
|
||||
self.games[room_jid_s].setdefault('players_data', {})
|
||||
self.games[room_jid].setdefault('players_data', {})
|
||||
for nick in nicks:
|
||||
# The dict must be COPIED otherwise it is shared between all users
|
||||
self.games[room_jid_s]['players_data'][nick] = copy.deepcopy(self.player_init)
|
||||
self.games[room_jid]['players_data'][nick] = copy.deepcopy(self.player_init)
|
||||
|
||||
def playerReady(self, player, referee, profile_key=C.PROF_KEY_NONE):
|
||||
def _playerReady(self, player_nick, referee_jid_s, profile_key=C.PROF_KEY_NONE):
|
||||
self.playerReady(player_nick, jid.JID(referee_jid_s), profile_key)
|
||||
|
||||
def playerReady(self, player_nick, referee_jid, 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
|
||||
@param referee_jid (jid.JID): JID of the referee
|
||||
"""
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not profile:
|
||||
|
|
@ -557,7 +572,7 @@ class RoomGame(object):
|
|||
return
|
||||
log.debug('new player ready: %s' % profile)
|
||||
# TODO: we probably need to add the game and room names in the sent message
|
||||
self.send(JID(referee), 'player_ready', {'player': player}, profile=profile)
|
||||
self.send(referee_jid, 'player_ready', {'player': player_nick}, profile=profile)
|
||||
|
||||
def newRound(self, room_jid, data, profile):
|
||||
"""Launch a new round (reinit the user data)
|
||||
|
|
@ -569,7 +584,7 @@ class RoomGame(object):
|
|||
@param profile
|
||||
"""
|
||||
log.debug(_('new round for %s game') % self.name)
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
players = game_data['players']
|
||||
players_data = game_data['players_data']
|
||||
game_data['stage'] = "init"
|
||||
|
|
@ -578,7 +593,7 @@ class RoomGame(object):
|
|||
|
||||
if isinstance(msg_elts, dict):
|
||||
for player in players:
|
||||
to_jid = JID(room_jid.userhost() + "/" + player) # FIXME: gof:
|
||||
to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
|
||||
elem = msg_elts[player] if isinstance(msg_elts[player], domish.Element) else None
|
||||
self.send(to_jid, elem, profile=profile)
|
||||
elif isinstance(msg_elts, domish.Element):
|
||||
|
|
|
|||
|
|
@ -59,12 +59,12 @@ class Tarot(object):
|
|||
self._sessions = memory.Sessions()
|
||||
self.inheritFromRoomGame(host)
|
||||
RoomGame._init_(self, host, PLUGIN_INFO, (NS_CG, CG_TAG),
|
||||
game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None},
|
||||
player_init={'score': 0})
|
||||
game_init={'hand_size': 18, 'init_player': 0, 'current_player': None, 'contrat': None, 'stage': None},
|
||||
player_init={'score': 0})
|
||||
self.contrats = [_('Passe'), _('Petite'), _('Garde'), _('Garde Sans'), _('Garde Contre')]
|
||||
host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self.prepareRoom, async=True) # args: players, room_jid, profile
|
||||
host.bridge.addMethod("tarotGameCreate", ".plugin", in_sign='sass', out_sign='', method=self.createGame) # args: room_jid, players, profile
|
||||
host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self.playerReady) # args: player, referee, profile
|
||||
host.bridge.addMethod("tarotGameLaunch", ".plugin", in_sign='asss', out_sign='', method=self._prepareRoom, async=True) # args: players, room_jid, profile
|
||||
host.bridge.addMethod("tarotGameCreate", ".plugin", in_sign='sass', out_sign='', method=self._createGame) # args: room_jid, players, profile
|
||||
host.bridge.addMethod("tarotGameReady", ".plugin", in_sign='sss', out_sign='', method=self._playerReady) # args: player, referee, profile
|
||||
host.bridge.addMethod("tarotGamePlayCards", ".plugin", in_sign='ssa(ss)s', out_sign='', method=self.play_cards) # args: player, referee, cards, profile
|
||||
host.bridge.addSignal("tarotGamePlayers", ".plugin", signature='ssass') # args: room_jid, referee, players, profile
|
||||
host.bridge.addSignal("tarotGameStarted", ".plugin", signature='ssass') # args: room_jid, referee, players, profile
|
||||
|
|
@ -84,7 +84,6 @@ class Tarot(object):
|
|||
self.__choose_contrat_id = host.registerCallback(self._contratChoosed, with_data=True)
|
||||
self.__score_id = host.registerCallback(self._scoreShowed, with_data=True)
|
||||
|
||||
|
||||
def __card_list_to_xml(self, cards_list, elt_name):
|
||||
"""Convert a card list to domish element"""
|
||||
cards_list_elt = domish.Element((None, elt_name))
|
||||
|
|
@ -183,17 +182,17 @@ class Tarot(object):
|
|||
@param game_data: data of the game
|
||||
@param played: cards currently on the table
|
||||
@param winner: nick of the trick winner"""
|
||||
#TODO: manage the case where excuse is played on the last trick (and lost)
|
||||
# TODO: manage the case where excuse is played on the last trick (and lost)
|
||||
players_data = game_data['players_data']
|
||||
excuse = TarotCard(("atout", "excuse"))
|
||||
|
||||
#we first check if the Excuse was already played
|
||||
#and if somebody is waiting for a card
|
||||
# we first check if the Excuse was already played
|
||||
# and if somebody is waiting for a card
|
||||
for player in game_data['players']:
|
||||
if players_data[player]['wait_for_low']:
|
||||
#the excuse owner has to give a card to somebody
|
||||
# the excuse owner has to give a card to somebody
|
||||
if winner == player:
|
||||
#the excuse owner win the trick, we check if we have something to give
|
||||
# the excuse owner win the trick, we check if we have something to give
|
||||
for card in played:
|
||||
if card.points == 0.5:
|
||||
pl_waiting = players_data[player]['wait_for_low']
|
||||
|
|
@ -203,8 +202,8 @@ class Tarot(object):
|
|||
return
|
||||
return
|
||||
|
||||
if not excuse in played:
|
||||
#the Excuse is not on the table, nothing to do
|
||||
if excuse not in played:
|
||||
# the Excuse is not on the table, nothing to do
|
||||
return
|
||||
|
||||
excuse_player = None # Who has played the Excuse ?
|
||||
|
|
@ -216,15 +215,15 @@ class Tarot(object):
|
|||
if excuse_player == winner:
|
||||
return # the excuse player win the trick, nothing to do
|
||||
|
||||
#first we remove the excuse from played cards
|
||||
# first we remove the excuse from played cards
|
||||
played.remove(excuse)
|
||||
#then we give it back to the original owner
|
||||
# then we give it back to the original owner
|
||||
owner_levees = players_data[excuse_player]['levees']
|
||||
owner_levees.append(excuse)
|
||||
#finally we give a low card to the trick winner
|
||||
# finally we give a low card to the trick winner
|
||||
low_card = None
|
||||
#We look backward in cards won by the Excuse owner to
|
||||
#find a low value card
|
||||
# We look backward in cards won by the Excuse owner to
|
||||
# find a low value card
|
||||
for card_idx in range(len(owner_levees) - 1, -1, -1):
|
||||
if owner_levees[card_idx].points == 0.5:
|
||||
low_card = owner_levees[card_idx]
|
||||
|
|
@ -233,7 +232,7 @@ class Tarot(object):
|
|||
log.debug(_('Player %(excuse_owner)s give %(card_waited)s to %(player_waiting)s for Excuse compensation') % {"excuse_owner": excuse_player, "card_waited": low_card, "player_waiting": winner})
|
||||
break
|
||||
if not low_card: # The player has no low card yet
|
||||
#TODO: manage case when player never win a trick with low card
|
||||
# TODO: manage case when player never win a trick with low card
|
||||
players_data[excuse_player]['wait_for_low'] = winner
|
||||
log.debug(_("%(excuse_owner)s keep the Excuse but has not card to give, %(winner)s is waiting for one") % {'excuse_owner': excuse_player, 'winner': winner})
|
||||
|
||||
|
|
@ -265,7 +264,7 @@ class Tarot(object):
|
|||
bouts.append(card.value)
|
||||
score += card.points
|
||||
|
||||
#We we do a basic check on score calculation
|
||||
# We do a basic check on score calculation
|
||||
check_score = 0
|
||||
defenseurs = game_data['players'][:]
|
||||
defenseurs.remove(game_data['attaquant'])
|
||||
|
|
@ -305,8 +304,8 @@ class Tarot(object):
|
|||
loosers = []
|
||||
player_score = {}
|
||||
for player in game_data['players']:
|
||||
#TODO: adjust this for 3 and 5 players variants
|
||||
#TODO: manage bonuses (petit au bout, poignée, chelem)
|
||||
# TODO: adjust this for 3 and 5 players variants
|
||||
# TODO: manage bonuses (petit au bout, poignée, chelem)
|
||||
player_score[player] = points_defenseur if player != game_data['attaquant'] else points_defenseur * -3
|
||||
players_data[player]['score'] += player_score[player] # we add score of this game to the global score
|
||||
if player_score[player] > 0:
|
||||
|
|
@ -314,7 +313,7 @@ class Tarot(object):
|
|||
else:
|
||||
loosers.append(player)
|
||||
|
||||
scores_str = _('The attacker (%(attaquant)s) makes %(points)i and needs to make %(point_limit)i (%(nb_bouts)s oulder%(plural)s%(separator)s%(bouts)s): he %(victory)s') % {'attaquant': game_data['attaquant'], 'points': score, 'point_limit': point_limit, 'nb_bouts': nb_bouts, 'plural': 's' if nb_bouts > 1 else '', 'separator': ': ' if nb_bouts != 0 else '', 'bouts': ','.join(map(str, bouts)), 'victory': 'win' if victory else 'loose'}
|
||||
scores_str = _('The attacker (%(attaquant)s) makes %(points)i and needs to make %(point_limit)i (%(nb_bouts)s oulder%(plural)s%(separator)s%(bouts)s): (s)he %(victory)s') % {'attaquant': game_data['attaquant'], 'points': score, 'point_limit': point_limit, 'nb_bouts': nb_bouts, 'plural': 's' if nb_bouts > 1 else '', 'separator': ': ' if nb_bouts != 0 else '', 'bouts': ','.join(map(str, bouts)), 'victory': 'wins' if victory else 'looses'}
|
||||
scores_str += '\n'
|
||||
for player in game_data['players']:
|
||||
scores_str += _("\n--\n%(player)s:\nscore for this game ==> %(score_game)i\ntotal score ==> %(total_score)i") % {'player': player, 'score_game': player_score[player], 'total_score': players_data[player]['score']}
|
||||
|
|
@ -332,7 +331,7 @@ class Tarot(object):
|
|||
for card in cards:
|
||||
if card.bout or card.value == "roi":
|
||||
forbidden_cards.append(card)
|
||||
#TODO: manage case where atouts (trumps) are in the dog
|
||||
# TODO: manage case where atouts (trumps) are in the dog
|
||||
elif game_data['stage'] == 'play':
|
||||
biggest_atout = None
|
||||
suit_asked = None
|
||||
|
|
@ -342,7 +341,7 @@ class Tarot(object):
|
|||
current_idx = game_data['current_player']
|
||||
current_player = players[current_idx]
|
||||
if idx == current_idx:
|
||||
#the player is the first to play, he can play what he wants
|
||||
# the player is the first to play, he can play what he wants
|
||||
return forbidden_cards
|
||||
while (idx != current_idx):
|
||||
player = players[idx]
|
||||
|
|
@ -398,13 +397,13 @@ class Tarot(object):
|
|||
# TODO: send error dialog
|
||||
return defer.succeed({})
|
||||
|
||||
room_jid_s = session_data['room_jid'].userhost()
|
||||
referee = self.games[room_jid_s]['referee']
|
||||
player = self.host.plugins["XEP-0045"].getRoomNick(room_jid_s, profile)
|
||||
room_jid = session_data['room_jid']
|
||||
referee_jid = self.games[room_jid]['referee']
|
||||
player = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
|
||||
data = xml_tools.XMLUIResult2DataFormResult(raw_data)
|
||||
contrat = data['contrat']
|
||||
log.debug(_('contrat [%(contrat)s] choosed by %(profile)s') % {'contrat': contrat, 'profile': profile})
|
||||
d = self.send(jid.JID(referee), ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile)
|
||||
d = self.send(referee_jid, ('', 'contrat_choosed'), {'player': player}, content=contrat, profile=profile)
|
||||
d.addCallback(lambda ignore: {})
|
||||
del self._sessions[raw_data["session_id"]]
|
||||
return d
|
||||
|
|
@ -443,7 +442,7 @@ class Tarot(object):
|
|||
self.send(jid.JID(referee), elem, {'player': player}, profile=profile)
|
||||
|
||||
def newRound(self, room_jid, profile):
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
game_data = self.games[room_jid]
|
||||
players = game_data['players']
|
||||
game_data['first_player'] = None # first player for the current trick
|
||||
game_data['contrat'] = None
|
||||
|
|
@ -480,11 +479,11 @@ class Tarot(object):
|
|||
"""
|
||||
from_jid = jid.JID(mess_elt['from'])
|
||||
room_jid = jid.JID(from_jid.userhost())
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid.userhost(), profile)
|
||||
nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile)
|
||||
|
||||
game_elt = mess_elt.firstChildElement()
|
||||
game_data = self.games[room_jid.userhost()]
|
||||
is_player = self.isPlayer(room_jid.userhost(), nick)
|
||||
game_data = self.games[room_jid]
|
||||
is_player = self.isPlayer(room_jid, nick)
|
||||
if 'players_data' in game_data:
|
||||
players_data = game_data['players_data']
|
||||
|
||||
|
|
@ -501,8 +500,8 @@ class Tarot(object):
|
|||
|
||||
elif elt.name == 'player_ready': # ready to play
|
||||
player = elt['player']
|
||||
status = self.games[room_jid.userhost()]['status']
|
||||
nb_players = len(self.games[room_jid.userhost()]['players'])
|
||||
status = self.games[room_jid]['status']
|
||||
nb_players = len(self.games[room_jid]['players'])
|
||||
status[player] = 'ready'
|
||||
log.debug(_('Player %(player)s is ready to start [status: %(status)s]') % {'player': player, 'status': status})
|
||||
if status.values().count('ready') == nb_players: # everybody is ready, we can start the game
|
||||
|
|
@ -519,13 +518,13 @@ class Tarot(object):
|
|||
self.host.bridge.tarotGameChooseContrat(room_jid.userhost(), xml_data, profile)
|
||||
|
||||
elif elt.name == 'contrat_choosed':
|
||||
#TODO: check we receive the contrat from the right person
|
||||
#TODO: use proper XEP-0004 way for answering form
|
||||
# TODO: check we receive the contrat from the right person
|
||||
# TODO: use proper XEP-0004 way for answering form
|
||||
player = elt['player']
|
||||
players_data[player]['contrat'] = unicode(elt)
|
||||
contrats = [players_data[player]['contrat'] for player in game_data['players']]
|
||||
if contrats.count(None):
|
||||
#not everybody has choosed his contrat, it's next one turn
|
||||
# not everybody has choosed his contrat, it's next one turn
|
||||
player = self.__next_player(game_data)
|
||||
to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof:
|
||||
self.send(to_jid, self.__ask_contrat(), profile=profile)
|
||||
|
|
@ -553,16 +552,16 @@ class Tarot(object):
|
|||
self.__start_play(room_jid, game_data, profile)
|
||||
game_data['attaquant'] = best_contrat[0]
|
||||
else:
|
||||
#Time to show the chien to everybody
|
||||
# Time to show the chien to everybody
|
||||
to_jid = jid.JID(room_jid.userhost()) # FIXME: gof:
|
||||
elem = self.__card_list_to_xml(game_data['chien'], 'chien')
|
||||
self.send(to_jid, elem, {'attaquant': best_contrat[0]}, profile=profile)
|
||||
#the attacker (attaquant) get the chien
|
||||
# the attacker (attaquant) get the chien
|
||||
game_data['hand'][best_contrat[0]].extend(game_data['chien'])
|
||||
del game_data['chien'][:]
|
||||
|
||||
if game_data['contrat'] == "Garde Sans":
|
||||
#The chien go into attaquant's (attacker) levees
|
||||
# The chien go into attaquant's (attacker) levees
|
||||
players_data[best_contrat[0]]['levees'].extend(game_data['chien'])
|
||||
del game_data['chien'][:]
|
||||
|
||||
|
|
@ -575,17 +574,17 @@ class Tarot(object):
|
|||
|
||||
elif elt.name == 'cards_played':
|
||||
if game_data['stage'] == "ecart":
|
||||
#TODO: show atouts (trumps) if player put some in écart
|
||||
# TODO: show atouts (trumps) if player put some in écart
|
||||
assert (game_data['attaquant'] == elt['player']) # TODO: throw an xml error here
|
||||
list_cards = TarotCard.from_tuples(self.__xml_to_list(elt))
|
||||
#we now check validity of card
|
||||
# we now check validity of card
|
||||
invalid_cards = self.__invalid_cards(game_data, list_cards)
|
||||
if invalid_cards:
|
||||
elem = self.__invalid_cards_elt(list_cards, invalid_cards, game_data['stage'])
|
||||
self.send(jid.JID(room_jid.userhost() + '/' + elt['player']), elem, profile=profile)
|
||||
return
|
||||
|
||||
#FIXME: gof: manage Garde Sans & Garde Contre cases
|
||||
# FIXME: gof: manage Garde Sans & Garde Contre cases
|
||||
players_data[elt['player']]['levees'].extend(list_cards) # we add the chien to attaquant's levées
|
||||
for card in list_cards:
|
||||
game_data['hand'][elt['player']].remove(card)
|
||||
|
|
@ -599,46 +598,46 @@ class Tarot(object):
|
|||
if mess_elt['type'] == 'groupchat':
|
||||
self.host.bridge.tarotGameCardsPlayed(room_jid.userhost(), elt['player'], self.__xml_to_list(elt), profile)
|
||||
else:
|
||||
#we first check validity of card
|
||||
# we first check validity of card
|
||||
invalid_cards = self.__invalid_cards(game_data, cards)
|
||||
if invalid_cards:
|
||||
elem = self.__invalid_cards_elt(cards, invalid_cards, game_data['stage'])
|
||||
self.send(jid.JID(room_jid.userhost() + '/' + current_player), elem, profile=profile)
|
||||
return
|
||||
#the card played is ok, we forward it to everybody
|
||||
#first we remove it from the hand and put in on the table
|
||||
# the card played is ok, we forward it to everybody
|
||||
# first we remove it from the hand and put in on the table
|
||||
game_data['hand'][current_player].remove(cards[0])
|
||||
players_data[current_player]['played'] = cards[0]
|
||||
|
||||
#then we forward the message
|
||||
# then we forward the message
|
||||
self.send(room_jid, elt, profile=profile)
|
||||
|
||||
#Did everybody played ?
|
||||
# Did everybody played ?
|
||||
played = [players_data[player]['played'] for player in game_data['players']]
|
||||
if all(played):
|
||||
#everybody has played
|
||||
# everybody has played
|
||||
winner = self.__winner(game_data)
|
||||
log.debug(_('The winner of this trick is %s') % winner)
|
||||
#the winner win the trick
|
||||
# the winner win the trick
|
||||
self.__excuse_hack(game_data, played, winner)
|
||||
players_data[elt['player']]['levees'].extend(played)
|
||||
#nothing left on the table
|
||||
# nothing left on the table
|
||||
for player in game_data['players']:
|
||||
players_data[player]['played'] = None
|
||||
if len(game_data['hand'][current_player]) == 0:
|
||||
#no card lef: the game is finished
|
||||
# no card left: the game is finished
|
||||
elem = self.__give_scores(*self.__calculate_scores(game_data))
|
||||
self.send(room_jid, elem, profile=profile)
|
||||
game_data['init_player'] = (game_data['init_player'] + 1) % len(game_data['players']) # we change the dealer
|
||||
for player in game_data['players']:
|
||||
game_data['status'][player] = "init"
|
||||
return
|
||||
#next player is the winner
|
||||
# next player is the winner
|
||||
next_player = game_data['first_player'] = self.__next_player(game_data, winner)
|
||||
else:
|
||||
next_player = self.__next_player(game_data)
|
||||
|
||||
#finally, we tell to the next player to play
|
||||
# finally, we tell to the next player to play
|
||||
to_jid = jid.JID(room_jid.userhost() + "/" + next_player)
|
||||
self.send(to_jid, 'your_turn', profile=profile)
|
||||
|
||||
|
|
@ -668,5 +667,5 @@ class Tarot(object):
|
|||
else:
|
||||
log.error(_('Unmanaged card game element: %s') % elt.name)
|
||||
|
||||
def getSyncDataForPlayer(self, room_jid_s, nick):
|
||||
def getSyncDataForPlayer(self, room_jid, nick):
|
||||
return []
|
||||
|
|
|
|||
|
|
@ -209,7 +209,7 @@ class TextCommands(object):
|
|||
return False
|
||||
|
||||
if not target_jid.resource:
|
||||
target_jid.resource = self.host.memory.getLastResource(target_jid, profile)
|
||||
target_jid.resource = self.host.memory.getMainResource(target_jid, profile)
|
||||
|
||||
whois_msg = [_(u"whois for %(jid)s") % {'jid': target_jid}]
|
||||
|
||||
|
|
|
|||
|
|
@ -29,8 +29,9 @@ from sat.tools import xml_tools
|
|||
from twisted.words.protocols.jabber import jid
|
||||
from twisted.python import failure
|
||||
from twisted.internet import defer
|
||||
import potr
|
||||
from sat.memory import persistent
|
||||
import potr
|
||||
import copy
|
||||
|
||||
NS_OTR = "otr_plugin"
|
||||
PRIVATE_KEY = "PRIVATE KEY"
|
||||
|
|
@ -269,7 +270,7 @@ class OTR(object):
|
|||
try:
|
||||
to_jid = jid.JID(menu_data['jid'])
|
||||
if not to_jid.resource:
|
||||
to_jid.resource = self.host.memory.getLastResource(to_jid, profile) # FIXME: temporary and unsecure, must be changed when frontends are refactored
|
||||
to_jid.resource = self.host.memory.getMainResource(to_jid, profile) # FIXME: temporary and unsecure, must be changed when frontends are refactored
|
||||
except KeyError:
|
||||
log.error(_("jid key is not present !"))
|
||||
return defer.fail(exceptions.DataError)
|
||||
|
|
@ -287,7 +288,7 @@ class OTR(object):
|
|||
try:
|
||||
to_jid = jid.JID(menu_data['jid'])
|
||||
if not to_jid.resource:
|
||||
to_jid.resource = self.host.memory.getLastResource(to_jid, profile) # FIXME: temporary and unsecure, must be changed when frontends are refactored
|
||||
to_jid.resource = self.host.memory.getMainResource(to_jid, profile) # FIXME: temporary and unsecure, must be changed when frontends are refactored
|
||||
except KeyError:
|
||||
log.error(_("jid key is not present !"))
|
||||
return defer.fail(exceptions.DataError)
|
||||
|
|
@ -304,7 +305,7 @@ class OTR(object):
|
|||
try:
|
||||
to_jid = jid.JID(menu_data['jid'])
|
||||
if not to_jid.resource:
|
||||
to_jid.resource = self.host.memory.getLastResource(to_jid, profile) # FIXME: temporary and unsecure, must be changed when frontends are refactored
|
||||
to_jid.resource = self.host.memory.getMainResource(to_jid, profile) # FIXME: temporary and unsecure, must be changed when frontends are refactored
|
||||
except KeyError:
|
||||
log.error(_("jid key is not present !"))
|
||||
return defer.fail(exceptions.DataError)
|
||||
|
|
@ -374,7 +375,7 @@ class OTR(object):
|
|||
try:
|
||||
to_jid = jid.JID(menu_data['jid'])
|
||||
if not to_jid.resource:
|
||||
to_jid.resource = self.host.memory.getLastResource(to_jid, profile) # FIXME: temporary and unsecure, must be changed when frontends are refactored
|
||||
to_jid.resource = self.host.memory.getMainResource(to_jid, profile) # FIXME: temporary and unsecure, must be changed when frontends are refactored
|
||||
except KeyError:
|
||||
log.error(_("jid key is not present !"))
|
||||
return defer.fail(exceptions.DataError)
|
||||
|
|
@ -447,9 +448,9 @@ class OTR(object):
|
|||
def sendMessageTrigger(self, mess_data, pre_xml_treatments, post_xml_treatments, profile):
|
||||
if profile in self.skipped_profiles:
|
||||
return True
|
||||
to_jid = mess_data['to']
|
||||
to_jid = copy.copy(mess_data['to'])
|
||||
if mess_data['type'] != 'groupchat' and not to_jid.resource:
|
||||
to_jid.resource = self.host.memory.getLastResource(to_jid, profile) # FIXME: it's dirty, but frontends don't manage resources correctly now, refactoring is planed
|
||||
to_jid.resource = self.host.memory.getMainResource(to_jid, profile) # FIXME: it's dirty, but frontends don't manage resources correctly now, refactoring is planed
|
||||
otrctx = self.context_managers[profile].getContextForUser(to_jid)
|
||||
if mess_data['type'] != 'groupchat' and otrctx.state != potr.context.STATE_PLAINTEXT:
|
||||
if otrctx.state == potr.context.STATE_ENCRYPTED:
|
||||
|
|
@ -475,7 +476,7 @@ class OTR(object):
|
|||
if show != "unavailable":
|
||||
return True
|
||||
if not entity.resource:
|
||||
entity.resource = self.host.memory.getLastResource(entity, profile) # FIXME: temporary and unsecure, must be changed when frontends are refactored
|
||||
entity.resource = self.host.memory.getMainResource(entity, profile) # FIXME: temporary and unsecure, must be changed when frontends are refactored
|
||||
otrctx = self.context_managers[profile].getContextForUser(entity)
|
||||
otrctx.disconnect()
|
||||
return True
|
||||
|
|
|
|||
|
|
@ -65,7 +65,7 @@ class XEP_0045(object):
|
|||
self.host = host
|
||||
self.clients = {}
|
||||
self._sessions = memory.Sessions()
|
||||
host.bridge.addMethod("joinMUC", ".plugin", in_sign='ssa{ss}s', out_sign='s', method=self._join)
|
||||
host.bridge.addMethod("joinMUC", ".plugin", in_sign='ssa{ss}s', out_sign='s', method=self._join, async=True)
|
||||
host.bridge.addMethod("mucNick", ".plugin", in_sign='sss', out_sign='', method=self.mucNick)
|
||||
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)
|
||||
|
|
@ -117,7 +117,7 @@ class XEP_0045(object):
|
|||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not self.checkClient(profile):
|
||||
raise exceptions.ProfileUnknownError("Unknown or disconnected profile")
|
||||
if room_jid.userhost() not in self.clients[profile].joined_rooms:
|
||||
if room_jid not in self.clients[profile].joined_rooms:
|
||||
raise UnknownRoom("This room has not been joined")
|
||||
return profile
|
||||
|
||||
|
|
@ -127,12 +127,11 @@ class XEP_0045(object):
|
|||
def _sendBridgeSignal(ignore=None):
|
||||
self.host.bridge.roomJoined(room.roomJID.userhost(), [user.nick for user in room.roster.values()], room.nick, profile)
|
||||
|
||||
room_jid_s = room.roomJID.userhost()
|
||||
self.clients[profile].joined_rooms[room_jid_s] = room
|
||||
self.clients[profile].joined_rooms[room.roomJID] = room
|
||||
if room.locked:
|
||||
#FIXME: the current behaviour is to create an instant room
|
||||
#and send the signal only when the room is unlocked
|
||||
#a proper configuration management should be done
|
||||
# FIXME: the current behaviour is to create an instant room
|
||||
# and send the signal only when the room is unlocked
|
||||
# a proper configuration management should be done
|
||||
print "room locked !"
|
||||
self.clients[profile].configure(room.roomJID, {}).addCallbacks(_sendBridgeSignal, lambda x: log.error(_('Error while configuring the room')))
|
||||
else:
|
||||
|
|
@ -164,27 +163,25 @@ class XEP_0045(object):
|
|||
result.append((room.roomJID.userhost(), [user.nick for user in room.roster.values()], room.nick))
|
||||
return result
|
||||
|
||||
def getRoomNick(self, room_jid_s, profile_key=C.PROF_KEY_NONE):
|
||||
def getRoomNick(self, room_jid, profile_key=C.PROF_KEY_NONE):
|
||||
"""return nick used in room by user
|
||||
|
||||
@param room_jid_s: unicode room id
|
||||
@param room_jid (jid.JID): JID of the room
|
||||
@profile_key: profile
|
||||
@return: nick or empty string in case of error"""
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not self.checkClient(profile) or room_jid_s not in self.clients[profile].joined_rooms:
|
||||
if not self.checkClient(profile) or room_jid not in self.clients[profile].joined_rooms:
|
||||
return ''
|
||||
return self.clients[profile].joined_rooms[room_jid_s].nick
|
||||
return self.clients[profile].joined_rooms[room_jid].nick
|
||||
|
||||
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
|
||||
@return: the nick or None if the user didn't join the room.
|
||||
@param room (wokkel.muc.Room): the room
|
||||
@param user (jid.JID): bare JID of the user
|
||||
@param secure (bool): set to True for a secure check
|
||||
@return: unicode or None if the user didn't join the room.
|
||||
"""
|
||||
if not isinstance(user_jid, jid.JID):
|
||||
user_jid = jid.JID(user_jid).userhostJID()
|
||||
for user in room.roster.values():
|
||||
if user.entity is not None:
|
||||
if user.entity.userhostJID() == user_jid.userhostJID():
|
||||
|
|
@ -199,11 +196,12 @@ 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
|
||||
@return: (x, y) with x a list containing the nicks of
|
||||
the users who are in the room, and y the missing users.
|
||||
@param room (wokkel.muc.Room): the room
|
||||
@param users (list[jid.JID]): list of users
|
||||
@param secure (True): set to True for a secure check
|
||||
@return: a couple (x, y) with:
|
||||
- x (list[unicode]): nicks of the users who are in the room
|
||||
- y (list[jid.JID]): JID of the missing users.
|
||||
"""
|
||||
nicks = []
|
||||
missing = []
|
||||
|
|
@ -231,6 +229,7 @@ class XEP_0045(object):
|
|||
except KeyError:
|
||||
log.error(_("room_jid key is not present !"))
|
||||
return defer.fail(exceptions.DataError)
|
||||
|
||||
def xmluiReceived(xmlui):
|
||||
return {"xmlui": xmlui.toXml()}
|
||||
return self.configureRoom(room_jid, profile).addCallback(xmluiReceived)
|
||||
|
|
@ -277,7 +276,7 @@ class XEP_0045(object):
|
|||
def isNickInRoom(self, room_jid, nick, profile):
|
||||
"""Tell if a nick is currently present in a room"""
|
||||
profile = self.getProfileAssertInRoom(room_jid, profile)
|
||||
return self.clients[profile].joined_rooms[room_jid.userhost()].inRoster(muc.User(nick))
|
||||
return self.clients[profile].joined_rooms[room_jid].inRoster(muc.User(nick))
|
||||
|
||||
def getRoomsSubjects(self, profile_key=C.PROF_KEY_NONE):
|
||||
"""Return received subjects of rooms"""
|
||||
|
|
@ -296,7 +295,7 @@ class XEP_0045(object):
|
|||
muc_service = None
|
||||
services = yield self.host.findServiceEntities("conference", "text", jid_, profile_key=profile_key)
|
||||
for service in services:
|
||||
if not ".irc." in service.userhost():
|
||||
if ".irc." not in service.userhost():
|
||||
# FIXME:
|
||||
# This ugly hack is here to avoid an issue with openfire: the IRC gateway
|
||||
# use "conference/text" identity (instead of "conference/irc")
|
||||
|
|
@ -310,10 +309,10 @@ class XEP_0045(object):
|
|||
def getUniqueName(self, muc_service=None, profile_key=C.PROF_KEY_NONE):
|
||||
"""Return unique name for a room, avoiding collision
|
||||
|
||||
@param muc_service: leave empty string to use the default service
|
||||
@return: unique room userhost, or '' if an error occured.
|
||||
@param muc_service (jid.JID) : leave empty string to use the default service
|
||||
@return: jid.JID (unique room bare JID)
|
||||
"""
|
||||
#TODO: we should use #RFC-0045 10.1.4 when available here
|
||||
# TODO: we should use #RFC-0045 10.1.4 when available here
|
||||
client = self.host.getClient(profile_key)
|
||||
room_name = uuid.uuid1()
|
||||
if muc_service is None:
|
||||
|
|
@ -337,7 +336,7 @@ class XEP_0045(object):
|
|||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not self.checkClient(profile):
|
||||
return _errDeferred()
|
||||
if room_jid.userhost() in self.clients[profile].joined_rooms:
|
||||
if room_jid in self.clients[profile].joined_rooms:
|
||||
log.warning(_('%(profile)s is already in room %(room_jid)s') % {'profile': profile, 'room_jid': room_jid.userhost()})
|
||||
return _errDeferred()
|
||||
log.info(_("[%(profile)s] is joining room %(room)s with nick %(nick)s") % {'profile': profile, 'room': room_jid.userhost(), 'nick': nick})
|
||||
|
|
@ -358,23 +357,24 @@ class XEP_0045(object):
|
|||
|
||||
def _join(self, room_jid_s, nick, options={}, profile_key=C.PROF_KEY_NONE):
|
||||
"""join method used by bridge: use the join method, but doesn't return any deferred
|
||||
@return the room userhost (given value or unique generated name)
|
||||
@return: unicode (the room bare)
|
||||
"""
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not self.checkClient(profile):
|
||||
return
|
||||
if room_jid_s == "":
|
||||
room_jid_s = self.getUniqueName(profile_key=profile_key)
|
||||
try:
|
||||
room_jid = jid.JID(room_jid_s)
|
||||
except:
|
||||
mess = _("Invalid room jid: %s") % room_jid_s
|
||||
log.warning(mess)
|
||||
self.host.bridge.newAlert(mess, _("Group chat error"), "ERROR", profile)
|
||||
return
|
||||
self.join(room_jid, nick, options, profile)
|
||||
if room_jid_s:
|
||||
try:
|
||||
room_jid = jid.JID(room_jid_s)
|
||||
except (RuntimeError, jid.InvalidFormat, AttributeError):
|
||||
mess = _("Invalid room JID: %s") % room_jid_s
|
||||
log.warning(mess)
|
||||
self.host.bridge.newAlert(mess, _("Group chat error"), "ERROR", profile)
|
||||
return defer.succeed(None)
|
||||
else:
|
||||
room_jid = self.getUniqueName(profile_key=profile_key)
|
||||
# TODO: error management + signal in bridge
|
||||
return room_jid_s
|
||||
d = self.join(room_jid, nick, options, profile)
|
||||
return d.addCallback(lambda room: room.roomJID.userhost())
|
||||
|
||||
def nick(self, room_jid, nick, profile_key):
|
||||
profile = self.getProfileAssertInRoom(room_jid, profile_key)
|
||||
|
|
@ -471,10 +471,10 @@ class XEP_0045(object):
|
|||
return False
|
||||
|
||||
if mess_data["unparsed"].strip():
|
||||
room = self.host.plugins[C.TEXT_CMDS].getRoomJID(mess_data["unparsed"].strip(), mess_data["to"].host)
|
||||
nick = (self.getRoomNick(mess_data["to"].userhost(), profile) or
|
||||
room_jid = self.host.plugins[C.TEXT_CMDS].getRoomJID(mess_data["unparsed"].strip(), mess_data["to"].host)
|
||||
nick = (self.getRoomNick(room_jid, profile) or
|
||||
self.host.getClient(profile).jid.user)
|
||||
self.join(room, nick, {}, profile)
|
||||
self.join(room_jid, nick, {}, profile)
|
||||
|
||||
return False
|
||||
|
||||
|
|
@ -630,10 +630,10 @@ class XEP_0045(object):
|
|||
""" Add MUC user information to whois """
|
||||
if mess_data['type'] != "groupchat":
|
||||
return
|
||||
if target_jid.userhost() not in self.clients[profile].joined_rooms:
|
||||
if target_jid.userhostJID() not in self.clients[profile].joined_rooms:
|
||||
log.warning(_("This room has not been joined"))
|
||||
return
|
||||
user = self.clients[profile].joined_rooms[target_jid.userhost()].getUser(target_jid.resource)
|
||||
user = self.clients[profile].joined_rooms[target_jid.userhostJID()].getUser(target_jid.resource)
|
||||
whois_msg.append(_("Nickname: %s") % user.nick)
|
||||
if user.entity:
|
||||
whois_msg.append(_("Entity: %s") % user.entity)
|
||||
|
|
@ -649,32 +649,35 @@ class XEP_0045(object):
|
|||
def presenceTrigger(self, presence_elt, client):
|
||||
# XXX: shouldn't it be done by the server ?!!
|
||||
muc_client = self.clients[client.profile]
|
||||
for room_jid_s, room in muc_client.joined_rooms.items():
|
||||
for room_jid, room in muc_client.joined_rooms.iteritems():
|
||||
elt = copy.deepcopy(presence_elt)
|
||||
elt['to'] = room_jid_s + '/' + room.nick
|
||||
elt['to'] = room_jid.userhost() + '/' + room.nick
|
||||
client.presence.send(elt)
|
||||
return True
|
||||
|
||||
|
||||
class SatMUCClient (muc.MUCClient):
|
||||
#implements(iwokkel.IDisco)
|
||||
# implements(iwokkel.IDisco)
|
||||
|
||||
def __init__(self, plugin_parent):
|
||||
self.plugin_parent = plugin_parent
|
||||
self.host = plugin_parent.host
|
||||
muc.MUCClient.__init__(self)
|
||||
self.joined_rooms = {} # FIXME: seem to do the same thing as MUCClient's _rooms attribute, must be removed
|
||||
self.rec_subjects = {}
|
||||
self.__changing_nicks = set() # used to keep trace of who is changing nick,
|
||||
# and to discard userJoinedRoom signal in this case
|
||||
print "init SatMUCClient OK"
|
||||
|
||||
@property
|
||||
def joined_rooms(self):
|
||||
return self._rooms
|
||||
|
||||
def subject(self, room, subject):
|
||||
return muc.MUCClientProtocol.subject(self, room, subject)
|
||||
|
||||
def unavailableReceived(self, presence):
|
||||
#XXX: we override this method to manage nickname change
|
||||
#TODO: feed this back to Wokkel
|
||||
# XXX: we override this method to manage nickname change
|
||||
# TODO: feed this back to Wokkel
|
||||
"""
|
||||
Unavailable presence was received.
|
||||
|
||||
|
|
@ -696,7 +699,7 @@ class SatMUCClient (muc.MUCClient):
|
|||
self.userLeftRoom(room, user)
|
||||
|
||||
def userJoinedRoom(self, room, user):
|
||||
self.host.memory.updateEntityData(room.roomJID, "type", "chatroom", self.parent.profile)
|
||||
self.host.memory.updateEntityData(room.roomJID, "type", "chatroom", profile_key=self.parent.profile)
|
||||
if user.nick in self.__changing_nicks:
|
||||
self.__changing_nicks.remove(user.nick)
|
||||
else:
|
||||
|
|
@ -713,9 +716,8 @@ class SatMUCClient (muc.MUCClient):
|
|||
# we left the room
|
||||
room_jid_s = room.roomJID.userhost()
|
||||
log.info(_("Room [%(room)s] left (%(profile)s))") % {"room": room_jid_s,
|
||||
"profile": self.parent.profile})
|
||||
"profile": self.parent.profile})
|
||||
self.host.memory.delEntityCache(room.roomJID, profile_key=self.parent.profile)
|
||||
del self.plugin_parent.clients[self.parent.profile].joined_rooms[room_jid_s]
|
||||
self.host.bridge.roomLeft(room.roomJID.userhost(), self.parent.profile)
|
||||
else:
|
||||
log.debug(_("user %(nick)s left room (%(room_id)s)") % {'nick': user.nick, 'room_id': room.occupantJID.userhost()})
|
||||
|
|
@ -733,7 +735,7 @@ class SatMUCClient (muc.MUCClient):
|
|||
|
||||
def receivedHistory(self, room, user, message):
|
||||
# http://xmpp.org/extensions/xep-0045.html#enter-history
|
||||
#log.debug('receivedHistory: room=%s user=%s body=%s' % (room.roomJID.full(), user, message))
|
||||
# log.debug('receivedHistory: room=%s user=%s body=%s' % (room.roomJID.full(), user, message))
|
||||
pass
|
||||
|
||||
def receivedSubject(self, room, user, subject):
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ from wokkel import disco, iwokkel
|
|||
from base64 import b64decode, b64encode
|
||||
from hashlib import sha1
|
||||
from sat.core import exceptions
|
||||
from sat.memory.persistent import PersistentDict
|
||||
from sat.memory import persistent
|
||||
from PIL import Image
|
||||
from cStringIO import StringIO
|
||||
|
||||
|
|
@ -56,6 +56,8 @@ PRESENCE = '/presence'
|
|||
NS_VCARD_UPDATE = 'vcard-temp:x:update'
|
||||
VCARD_UPDATE = PRESENCE + '/x[@xmlns="' + NS_VCARD_UPDATE + '"]'
|
||||
|
||||
CACHED_DATA = {'avatar', 'nick'}
|
||||
|
||||
PLUGIN_INFO = {
|
||||
"name": "XEP 0054 Plugin",
|
||||
"import_name": "XEP-0054",
|
||||
|
|
@ -79,67 +81,101 @@ class XEP_0054(object):
|
|||
self.avatar_path = os.path.join(self.host.memory.getConfig('', 'local_dir'), AVATAR_PATH)
|
||||
if not os.path.exists(self.avatar_path):
|
||||
os.makedirs(self.avatar_path)
|
||||
self.avatars_cache = PersistentDict(NS_VCARD)
|
||||
self.avatars_cache.load() # FIXME: resulting deferred must be correctly managed
|
||||
host.bridge.addMethod("getCard", ".plugin", in_sign='ss', out_sign='s', method=self.getCard)
|
||||
self.cache = {}
|
||||
host.bridge.addMethod("getCard", ".plugin", in_sign='ss', out_sign='s', method=self._getCard)
|
||||
host.bridge.addMethod("getAvatarFile", ".plugin", in_sign='s', out_sign='s', method=self.getAvatarFile)
|
||||
host.bridge.addMethod("setAvatar", ".plugin", in_sign='ss', out_sign='', method=self.setAvatar, async=True)
|
||||
host.trigger.add("presence_available", self.presenceTrigger)
|
||||
host.memory.setSignalOnUpdate("avatar")
|
||||
host.memory.setSignalOnUpdate("nick")
|
||||
|
||||
def getHandler(self, profile):
|
||||
return XEP_0054_handler(self)
|
||||
|
||||
def presenceTrigger(self, presence_elt, client):
|
||||
if client.jid.userhost() in self.avatars_cache:
|
||||
if client.jid.userhost() in self.cache[client.profile]:
|
||||
x_elt = domish.Element((NS_VCARD_UPDATE, 'x'))
|
||||
x_elt.addElement('photo', content=self.avatars_cache[client.jid.userhost()])
|
||||
x_elt.addElement('photo', content=self.cache[client.profile][client.jid.userhost()]['avatar'])
|
||||
presence_elt.addChild(x_elt)
|
||||
|
||||
return True
|
||||
|
||||
def _fillCachedValues(self, result, client):
|
||||
def _fillCachedValues(self, profile):
|
||||
#FIXME: this is really suboptimal, need to be reworked
|
||||
# the current naive approach keeps a map between all jids of all profiles
|
||||
# in persistent cache, and check if cached jid are in roster, then put avatar
|
||||
# hashs in memory.
|
||||
for _jid in client.roster.getBareJids() + [client.jid.userhost()]:
|
||||
if _jid in self.avatars_cache:
|
||||
self.host.memory.updateEntityData(jid.JID(_jid), "avatar", self.avatars_cache[_jid], client.profile)
|
||||
# in persistent cache, then put avatar
|
||||
# hashs in memory. Hashed should be shared between profiles
|
||||
for jid_s, data in self.cache[profile].iteritems():
|
||||
jid_ = jid.JID(jid_s)
|
||||
for name in CACHED_DATA:
|
||||
try:
|
||||
self.host.memory.updateEntityData(jid_, name, data[name], silent=True, profile_key=profile)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
def profileConnected(self, profile):
|
||||
client = self.host.getClient(profile)
|
||||
client.roster.got_roster.addCallback(self._fillCachedValues, client)
|
||||
@defer.inlineCallbacks
|
||||
def profileConnecting(self, profile):
|
||||
self.cache[profile] = persistent.PersistentBinaryDict(NS_VCARD, profile)
|
||||
yield self.cache[profile].load()
|
||||
self._fillCachedValues(profile)
|
||||
|
||||
def update_cache(self, jid, name, value, profile):
|
||||
def profileDisconnected(self, profile):
|
||||
log.debug(u"Deleting profile cache for avatars")
|
||||
del self.cache[profile]
|
||||
|
||||
def updateCache(self, jid_, name, value, profile):
|
||||
"""update cache value
|
||||
- save value in memory in case of change
|
||||
@param jid: jid of the owner of the vcard
|
||||
@param name: name of the item which changed
|
||||
@param value: new value of the item
|
||||
@param profile: profile which received the update
|
||||
"""
|
||||
try:
|
||||
cached = self.host.memory.getEntityData(jid, [name], profile)
|
||||
except exceptions.UnknownEntityError:
|
||||
cached = {}
|
||||
if not name in cached or cached[name] != value:
|
||||
self.host.memory.updateEntityData(jid, name, value, profile)
|
||||
if name == "avatar":
|
||||
self.avatars_cache[jid.userhost()] = value
|
||||
|
||||
def get_cache(self, entity_jid, name, profile):
|
||||
save value in memory in case of change
|
||||
@param jid_(jid.JID): jid of the owner of the vcard
|
||||
@param name(str): name of the item which changed
|
||||
@param value(unicode): new value of the item
|
||||
@param profile(unicode): profile which received the update
|
||||
"""
|
||||
assert not jid_.resource # VCard are retrieved with bare jid
|
||||
self.host.memory.updateEntityData(jid_, name, value, profile_key=profile)
|
||||
if name in CACHED_DATA:
|
||||
jid_s = jid_.userhost()
|
||||
self.cache[profile].setdefault(jid_s, {})[name] = value
|
||||
self.cache[profile].force(jid_s)
|
||||
|
||||
def getCache(self, entity_jid, name, profile):
|
||||
"""return cached value for jid
|
||||
|
||||
@param entity_jid: target contact
|
||||
@param name: name of the value ('nick' or 'avatar')
|
||||
@param profile: %(doc_profile)s
|
||||
@return: wanted value or None"""
|
||||
assert not entity_jid.resource # VCard are retrieved with bare jid
|
||||
try:
|
||||
data = self.host.memory.getEntityData(entity_jid, [name], profile)
|
||||
except exceptions.UnknownEntityError:
|
||||
return None
|
||||
return data.get(name)
|
||||
|
||||
def save_photo(self, photo_xml):
|
||||
def _getFilename(self, hash_):
|
||||
"""Get filename from hash
|
||||
|
||||
@param hash_: hash of the avatar
|
||||
@return (str): absolute filename of the avatar
|
||||
"""
|
||||
return os.path.join(self.avatar_path, hash_)
|
||||
|
||||
def saveAvatarFile(self, data, hash_):
|
||||
"""Save the avatar picture if it doesn't already exists
|
||||
|
||||
@param data(str): binary image of the avatar
|
||||
@param hash_(str): hash of the binary data (will be used for the filename)
|
||||
"""
|
||||
filename = self._getFilename(hash_)
|
||||
if not os.path.exists(filename):
|
||||
with open(filename, 'wb') as file_:
|
||||
file_.write(data)
|
||||
log.debug(_("file saved to %s") % hash_)
|
||||
else:
|
||||
log.debug(_("file [%s] already in cache") % hash_)
|
||||
|
||||
def savePhoto(self, photo_xml):
|
||||
"""Parse a <PHOTO> elem and save the picture"""
|
||||
for elem in photo_xml.elements():
|
||||
if elem.name == 'TYPE':
|
||||
|
|
@ -148,13 +184,7 @@ class XEP_0054(object):
|
|||
log.debug(_('Decoding binary'))
|
||||
decoded = b64decode(str(elem))
|
||||
image_hash = sha1(decoded).hexdigest()
|
||||
filename = self.avatar_path + '/' + image_hash
|
||||
if not os.path.exists(filename):
|
||||
with open(filename, 'wb') as file_:
|
||||
file_.write(decoded)
|
||||
log.debug(_("file saved to %s") % image_hash)
|
||||
else:
|
||||
log.debug(_("file [%s] already in cache") % image_hash)
|
||||
self.saveAvatarFile(decoded, image_hash)
|
||||
return image_hash
|
||||
|
||||
@defer.inlineCallbacks
|
||||
|
|
@ -168,7 +198,7 @@ class XEP_0054(object):
|
|||
dictionary['fullname'] = unicode(elem)
|
||||
elif elem.name == 'NICKNAME':
|
||||
dictionary['nick'] = unicode(elem)
|
||||
self.update_cache(target, 'nick', dictionary['nick'], profile)
|
||||
self.updateCache(target, 'nick', dictionary['nick'], profile)
|
||||
elif elem.name == 'URL':
|
||||
dictionary['website'] = unicode(elem)
|
||||
elif elem.name == 'EMAIL':
|
||||
|
|
@ -176,17 +206,24 @@ class XEP_0054(object):
|
|||
elif elem.name == 'BDAY':
|
||||
dictionary['birthday'] = unicode(elem)
|
||||
elif elem.name == 'PHOTO':
|
||||
dictionary["avatar"] = yield threads.deferToThread(self.save_photo, elem)
|
||||
dictionary["avatar"] = yield threads.deferToThread(self.savePhoto, elem)
|
||||
if not dictionary["avatar"]: # can happen in case of e.g. empty photo elem
|
||||
del dictionary['avatar']
|
||||
else:
|
||||
self.update_cache(target, 'avatar', dictionary['avatar'], profile)
|
||||
self.updateCache(target, 'avatar', dictionary['avatar'], profile)
|
||||
else:
|
||||
log.info(_('FIXME: [%s] VCard tag is not managed yet') % elem.name)
|
||||
|
||||
# if a data in cache doesn't exist anymore, we need to reset it
|
||||
# so we check CACHED_DATA no gotten (i.e. not in dictionary keys)
|
||||
# and we reset them
|
||||
for datum in CACHED_DATA.difference(dictionary.keys()):
|
||||
log.debug(u"reseting vcard datum [{datum}] for {entity}".format(datum=datum, entity=target.full()))
|
||||
self.updateCache(target, datum, '', profile)
|
||||
|
||||
defer.returnValue(dictionary)
|
||||
|
||||
def vcard_ok(self, answer, profile):
|
||||
def _VCardCb(self, answer, profile):
|
||||
"""Called after the first get IQ"""
|
||||
log.debug(_("VCard found"))
|
||||
|
||||
|
|
@ -202,30 +239,35 @@ class XEP_0054(object):
|
|||
log.error(_("FIXME: vCard not found as first child element"))
|
||||
self.host.bridge.actionResult("SUPPRESS", answer['id'], {}, profile) # FIXME: maybe an error message would be better
|
||||
|
||||
def vcard_err(self, failure, profile):
|
||||
def _VCardEb(self, failure, profile):
|
||||
"""Called when something is wrong with registration"""
|
||||
try:
|
||||
log.error(_("Can't find VCard of %s") % failure.value.stanza['from'])
|
||||
log.warning(_("Can't find VCard of %s") % failure.value.stanza['from'])
|
||||
self.host.bridge.actionResult("SUPPRESS", failure.value.stanza['id'], {}, profile) # FIXME: maybe an error message would be better
|
||||
self.updateCache(jid.JID(failure.value.stanza['from']), "avatar", '', profile)
|
||||
except AttributeError: # 'ConnectionLost' object has no attribute 'stanza'
|
||||
log.error(_("Can't find VCard: %s") % failure.getErrorMessage())
|
||||
log.warning(_("Can't find VCard: %s") % failure.getErrorMessage())
|
||||
|
||||
def getCard(self, target_s, profile_key=C.PROF_KEY_NONE):
|
||||
def _getCard(self, target_s, profile_key=C.PROF_KEY_NONE):
|
||||
return self.getCard(jid.JID(target_s), profile_key)
|
||||
|
||||
def getCard(self, target, profile_key=C.PROF_KEY_NONE):
|
||||
"""Ask server for VCard
|
||||
@param target_s: jid from which we want the VCard
|
||||
@result: id to retrieve the profile"""
|
||||
|
||||
@param target(jid.JID): jid from which we want the VCard
|
||||
@result: id to retrieve the profile
|
||||
"""
|
||||
current_jid, xmlstream = self.host.getJidNStream(profile_key)
|
||||
if not xmlstream:
|
||||
log.error(_('Asking vcard for a non-existant or not connected profile'))
|
||||
return ""
|
||||
raise exceptions.ProfileUnknownError('Asking vcard for a non-existant or not connected profile ({})'.format(profile_key))
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
to_jid = jid.JID(target_s)
|
||||
to_jid = target.userhostJID()
|
||||
log.debug(_("Asking for %s's VCard") % to_jid.userhost())
|
||||
reg_request = IQ(xmlstream, 'get')
|
||||
reg_request["from"] = current_jid.full()
|
||||
reg_request["to"] = to_jid.userhost()
|
||||
reg_request.addElement('vCard', NS_VCARD)
|
||||
reg_request.send(to_jid.userhost()).addCallbacks(self.vcard_ok, self.vcard_err, callbackArgs=[profile], errbackArgs=[profile])
|
||||
reg_request.send(to_jid.userhost()).addCallbacks(self._VCardCb, self._VCardEb, callbackArgs=[profile], errbackArgs=[profile])
|
||||
return reg_request["id"]
|
||||
|
||||
def getAvatarFile(self, avatar_hash):
|
||||
|
|
@ -266,6 +308,7 @@ class XEP_0054(object):
|
|||
photo_elt.addElement('TYPE', content='image/png')
|
||||
photo_elt.addElement('BINVAL', content=b64encode(img_buf.getvalue()))
|
||||
img_hash = sha1(img_buf.getvalue()).hexdigest()
|
||||
self.saveAvatarFile(img_buf.getvalue(), img_hash)
|
||||
return (vcard_set, img_hash)
|
||||
|
||||
def setAvatar(self, filepath, profile_key=C.PROF_KEY_NONE):
|
||||
|
|
@ -281,9 +324,8 @@ class XEP_0054(object):
|
|||
def elementBuilt(result):
|
||||
"""Called once the image is at the right size/format, and the vcard set element is build"""
|
||||
set_avatar_elt, img_hash = result
|
||||
self.avatars_cache[client.jid.userhost()] = img_hash # we need to update the hash, so we can send a new presence
|
||||
# element with the right hash
|
||||
return set_avatar_elt.send().addCallback(lambda ignore: client.presence.available())
|
||||
self.updateCache(client.jid.userhostJID(), 'avatar', img_hash, client.profile)
|
||||
return set_avatar_elt.send().addCallback(lambda ignore: client.presence.available()) # FIXME: should send the current presence, not always "available" !
|
||||
|
||||
d.addCallback(elementBuilt)
|
||||
|
||||
|
|
@ -307,16 +349,31 @@ class XEP_0054_handler(XMPPHandler):
|
|||
return []
|
||||
|
||||
def update(self, presence):
|
||||
"""Request for VCard's nickname
|
||||
return the cached nickname if exists, else get VCard
|
||||
"""Called on <presence/> stanza with vcard data
|
||||
|
||||
Check for avatar information, and get VCard if needed
|
||||
@param presend(domish.Element): <presence/> stanza
|
||||
"""
|
||||
from_jid = jid.JID(presence['from'])
|
||||
# FIXME: doesn't manage MUC correctly
|
||||
from_jid = jid.JID(presence['from']).userhostJID()
|
||||
#FIXME: wokkel's data_form should be used here
|
||||
x_elem = filter(lambda x: x.name == "x", presence.elements())[0] # We only want the "x" element
|
||||
for elem in x_elem.elements():
|
||||
if elem.name == 'photo':
|
||||
_hash = str(elem)
|
||||
old_avatar = self.plugin_parent.get_cache(from_jid, 'avatar', self.parent.profile)
|
||||
if not old_avatar or old_avatar != _hash:
|
||||
log.debug(_('New avatar found, requesting vcard'))
|
||||
self.plugin_parent.getCard(from_jid.userhost(), self.parent.profile)
|
||||
hash_ = str(elem)
|
||||
old_avatar = self.plugin_parent.getCache(from_jid, 'avatar', self.parent.profile)
|
||||
filename = self.plugin_parent._getFilename(hash_)
|
||||
if not old_avatar or old_avatar != hash_:
|
||||
if os.path.exists(filename):
|
||||
log.debug(u"New avatar found for [{}], it's already in cache, we use it".format(from_jid.full()))
|
||||
self.plugin_parent.updateCache(from_jid, 'avatar', hash_, self.parent.profile)
|
||||
else:
|
||||
log.debug(u'New avatar found for [{}], requesting vcard'.format(from_jid.full()))
|
||||
self.plugin_parent.getCard(from_jid, self.parent.profile)
|
||||
else:
|
||||
if os.path.exists(filename):
|
||||
log.debug(u"avatar for {} already in cache".format(from_jid.full()))
|
||||
else:
|
||||
log.error(u"Avatar for [{}] should be in cache but it is not ! We get it".format(from_jid.full()))
|
||||
self.plugin_parent.getCard(from_jid, self.parent.profile)
|
||||
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ class XEP_0060(object):
|
|||
OPT_PUBLISH_MODEL = 'pubsub#publish_model'
|
||||
|
||||
def __init__(self, host):
|
||||
log.info(_("PubSub plugin initialization"))
|
||||
log.info(_(u"PubSub plugin initialization"))
|
||||
self.host = host
|
||||
self.managedNodes = []
|
||||
self.clients = {}
|
||||
|
|
@ -202,7 +202,7 @@ class XEP_0060(object):
|
|||
d_dict = {}
|
||||
for publisher, node in data.items():
|
||||
if node not in found_nodes:
|
||||
log.debug("Skip the items retrieval for [{node}]: node doesn't exist".format(node=node))
|
||||
log.debug(u"Skip the items retrieval for [{node}]: node doesn't exist".format(node=node))
|
||||
continue # avoid pubsub "item-not-found" error
|
||||
d_dict[publisher] = self.getItems(service, node, max_items, None, sub_id, rsm, profile)
|
||||
defer.returnValue(d_dict)
|
||||
|
|
@ -248,7 +248,7 @@ class XEP_0060(object):
|
|||
d_list = []
|
||||
for nodeIdentifier in (set(nodeIdentifiers) - set(subscribed_nodes)):
|
||||
if nodeIdentifier not in found_nodes:
|
||||
log.debug("Skip the subscription to [{node}]: node doesn't exist".format(node=nodeIdentifier))
|
||||
log.debug(u"Skip the subscription to [{node}]: node doesn't exist".format(node=nodeIdentifier))
|
||||
continue # avoid sat-pubsub "SubscriptionExists" error
|
||||
d_list.append(client.subscribe(service, nodeIdentifier, sub_jid or client.parent.jid.userhostJID(), options=options))
|
||||
defer.returnValue(d_list)
|
||||
|
|
@ -278,7 +278,7 @@ class SatPubSubClient(rsm.PubSubClient):
|
|||
|
||||
def deleteReceived(self, event):
|
||||
#TODO: manage delete event
|
||||
log.debug(_("Publish node deleted"))
|
||||
log.debug(_(u"Publish node deleted"))
|
||||
|
||||
# def purgeReceived(self, event):
|
||||
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ MESSAGE_TYPES = ["chat", "groupchat"]
|
|||
PARAM_KEY = "Notifications"
|
||||
PARAM_NAME = "Enable chat state notifications"
|
||||
ENTITY_KEY = PARAM_KEY + "_" + PARAM_NAME
|
||||
DELETE_VALUE = "DELETE"
|
||||
|
||||
PLUGIN_INFO = {
|
||||
"name": "Chat State Notifications Protocol Plugin",
|
||||
|
|
@ -125,29 +126,32 @@ class XEP_0085(object):
|
|||
self.map[profile][to_jid]._onEvent('gone')
|
||||
del self.map[profile]
|
||||
|
||||
def updateEntityData(self, entity_jid, value, profile):
|
||||
"""
|
||||
Update the entity data of the given profile for one or all contacts.
|
||||
def updateCache(self, entity_jid, value, profile):
|
||||
"""Update the entity data of the given profile for one or all contacts.
|
||||
Reset the chat state(s) display if the notification has been disabled.
|
||||
@param entity_jid: contact's JID, or '@ALL@' to update all contacts.
|
||||
@param value: True, False or C.PROF_KEY_NONE to delete the entity data
|
||||
|
||||
@param entity_jid: contact's JID, or C.ENTITY_ALL to update all contacts.
|
||||
@param value: True, False or DELETE_VALUE to delete the entity data
|
||||
@param profile: current profile
|
||||
"""
|
||||
self.host.memory.updateEntityData(entity_jid, ENTITY_KEY, value, profile)
|
||||
if not value or value == C.PROF_KEY_NONE:
|
||||
# disable chat state for this or these contact(s)
|
||||
self.host.bridge.chatStateReceived(unicode(entity_jid), "", profile)
|
||||
if value == DELETE_VALUE:
|
||||
self.host.memory.delEntityDatum(entity_jid, ENTITY_KEY, profile)
|
||||
else:
|
||||
self.host.memory.updateEntityData(entity_jid, ENTITY_KEY, value, profile_key=profile)
|
||||
if not value or value == DELETE_VALUE:
|
||||
# reinit chat state UI for this or these contact(s)
|
||||
self.host.bridge.chatStateReceived(entity_jid.full(), "", profile)
|
||||
|
||||
def paramUpdateTrigger(self, name, value, category, type_, profile):
|
||||
"""
|
||||
Reset all the existing chat state entity data associated with this profile after a parameter modification.
|
||||
"""Reset all the existing chat state entity data associated with this profile after a parameter modification.
|
||||
|
||||
@param name: parameter name
|
||||
@param value: "true" to activate the notifications, or any other value to delete it
|
||||
@param category: parameter category
|
||||
@param type_: parameter type
|
||||
"""
|
||||
if (category, name) == (PARAM_KEY, PARAM_NAME):
|
||||
self.updateEntityData("@ALL@", True if value == "true" else C.PROF_KEY_NONE, profile)
|
||||
self.updateCache(C.ENTITY_ALL, True if bool("true") else DELETE_VALUE, profile=profile)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
|
@ -160,20 +164,20 @@ class XEP_0085(object):
|
|||
return True
|
||||
|
||||
from_jid = JID(message.getAttribute("from"))
|
||||
if self.__isMUC(from_jid, profile):
|
||||
if self._isMUC(from_jid, profile):
|
||||
from_jid = from_jid.userhostJID()
|
||||
else: # update entity data for one2one chat
|
||||
assert(from_jid.resource)
|
||||
# assert from_jid.resource # FIXME: assert doesn't work on normal message from server (e.g. server announce), because there is no resource
|
||||
try:
|
||||
domish.generateElementsNamed(message.elements(), name="body").next()
|
||||
try:
|
||||
domish.generateElementsNamed(message.elements(), name="active").next()
|
||||
# contact enabled Chat State Notifications
|
||||
self.updateEntityData(from_jid, True, profile)
|
||||
self.updateCache(from_jid, True, profile=profile)
|
||||
except StopIteration:
|
||||
if message.getAttribute('type') == 'chat':
|
||||
# contact didn't enable Chat State Notifications
|
||||
self.updateEntityData(from_jid, False, profile)
|
||||
self.updateCache(from_jid, False, profile=profile)
|
||||
return True
|
||||
except StopIteration:
|
||||
pass
|
||||
|
|
@ -200,27 +204,27 @@ class XEP_0085(object):
|
|||
def treatment(mess_data):
|
||||
message = mess_data['xml']
|
||||
to_jid = JID(message.getAttribute("to"))
|
||||
if not self.__checkActivation(to_jid, forceEntityData=True, profile=profile):
|
||||
if not self._checkActivation(to_jid, forceEntityData=True, profile=profile):
|
||||
return mess_data
|
||||
try:
|
||||
# message with a body always mean active state
|
||||
domish.generateElementsNamed(message.elements(), name="body").next()
|
||||
message.addElement('active', NS_CHAT_STATES)
|
||||
# launch the chat state machine (init the timer)
|
||||
if self.__isMUC(to_jid, profile):
|
||||
if self._isMUC(to_jid, profile):
|
||||
to_jid = to_jid.userhostJID()
|
||||
self.__chatStateActive(to_jid, mess_data["type"], profile)
|
||||
except StopIteration:
|
||||
if "chat_state" in mess_data["extra"]:
|
||||
state = mess_data["extra"].pop("chat_state")
|
||||
assert(state in CHAT_STATES)
|
||||
assert state in CHAT_STATES
|
||||
message.addElement(state, NS_CHAT_STATES)
|
||||
return mess_data
|
||||
|
||||
post_xml_treatments.addCallback(treatment)
|
||||
return True
|
||||
|
||||
def __isMUC(self, to_jid, profile):
|
||||
def _isMUC(self, to_jid, profile):
|
||||
"""Tell if that JID is a MUC or not
|
||||
|
||||
@param to_jid (JID): full or bare JID to check
|
||||
|
|
@ -229,13 +233,13 @@ class XEP_0085(object):
|
|||
"""
|
||||
try:
|
||||
type_ = self.host.memory.getEntityDatum(to_jid.userhostJID(), 'type', profile)
|
||||
if type_ == 'chatroom':
|
||||
if type_ == 'chatroom': # FIXME: should not use disco instead ?
|
||||
return True
|
||||
except (exceptions.UnknownEntityError, KeyError):
|
||||
pass
|
||||
return False
|
||||
|
||||
def __checkActivation(self, to_jid, forceEntityData, profile):
|
||||
def _checkActivation(self, to_jid, forceEntityData, profile):
|
||||
"""
|
||||
@param to_jid: the contact's full JID (or bare if you know it's a MUC)
|
||||
@param forceEntityData: if set to True, a non-existing
|
||||
|
|
@ -247,15 +251,16 @@ class XEP_0085(object):
|
|||
if not self.host.memory.getParamA(PARAM_NAME, PARAM_KEY, profile_key=profile):
|
||||
return False
|
||||
# check if notifications should be sent to this contact
|
||||
if self.__isMUC(to_jid, profile):
|
||||
if self._isMUC(to_jid, profile):
|
||||
return True
|
||||
assert(to_jid.resource or not self.host.memory.isContactConnected(to_jid, profile))
|
||||
# FIXME: this assertion crash when we want to send a message to an online bare jid
|
||||
# assert to_jid.resource or not self.host.memory.isEntityAvailable(to_jid, profile) # must either have a resource, or talk to an offline contact
|
||||
try:
|
||||
return self.host.memory.getEntityDatum(to_jid, ENTITY_KEY, profile)
|
||||
except (exceptions.UnknownEntityError, KeyError):
|
||||
if forceEntityData:
|
||||
# enable it for the first time
|
||||
self.updateEntityData(to_jid, True, profile)
|
||||
self.updateCache(to_jid, True, profile=profile)
|
||||
return True
|
||||
# wait for the first message before sending states
|
||||
return False
|
||||
|
|
@ -305,11 +310,11 @@ class XEP_0085(object):
|
|||
if profile is None:
|
||||
raise exceptions.ProfileUnknownError
|
||||
to_jid = JID(to_jid_s)
|
||||
if self.__isMUC(to_jid, profile):
|
||||
if self._isMUC(to_jid, profile):
|
||||
to_jid = to_jid.userhostJID()
|
||||
elif not to_jid.resource:
|
||||
to_jid.resource = self.host.memory.getLastResource(to_jid, profile)
|
||||
if not self.__checkActivation(to_jid, forceEntityData=False, profile=profile):
|
||||
to_jid.resource = self.host.memory.getMainResource(to_jid, profile)
|
||||
if not self._checkActivation(to_jid, forceEntityData=False, profile=profile):
|
||||
return
|
||||
try:
|
||||
self.map[profile][to_jid]._onEvent("composing")
|
||||
|
|
@ -347,9 +352,9 @@ class ChatStateMachine:
|
|||
notification to the contact (the "active" state is
|
||||
automatically sent with each message) and set the timer.
|
||||
"""
|
||||
assert(state in TRANSITIONS)
|
||||
assert state in TRANSITIONS
|
||||
transition = TRANSITIONS[state]
|
||||
assert("next_state" in transition and "delay" in transition)
|
||||
assert "next_state" in transition and "delay" in transition
|
||||
|
||||
if state != self.state and state != "active":
|
||||
if state != 'gone' or self.mess_type != 'groupchat':
|
||||
|
|
|
|||
|
|
@ -107,7 +107,7 @@ class XEP_0115(object):
|
|||
client.caps_sent = False
|
||||
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)
|
||||
self.host.memory.updateEntityData(client.jid, C.ENTITY_CAP_HASH, cap_hash, profile_key=profile)
|
||||
|
||||
|
||||
class XEP_0115_handler(XMPPHandler):
|
||||
|
|
@ -146,7 +146,7 @@ class XEP_0115_handler(XMPPHandler):
|
|||
if c_ver in self.host.memory.disco.hashes:
|
||||
# we already know the hash, we update the jid entity
|
||||
log.debug ("hash [%(hash)s] already in cache, updating entity [%(jid)s]" % {'hash': c_ver, 'jid': from_jid.full()})
|
||||
self.host.memory.updateEntityData(from_jid, C.ENTITY_CAP_HASH, c_ver, self.profile)
|
||||
self.host.memory.updateEntityData(from_jid, C.ENTITY_CAP_HASH, c_ver, profile_key=self.profile)
|
||||
return
|
||||
|
||||
if c_hash != 'sha-1': # unknown hash method
|
||||
|
|
|
|||
|
|
@ -120,18 +120,18 @@ class XEP_0249(object):
|
|||
#TODO: check parameters validity
|
||||
self.invite(jid.JID(target), jid.JID("%s@%s" % (roomId, service)), options, profile_key)
|
||||
|
||||
def _accept(self, room, profile_key=C.PROF_KEY_NONE):
|
||||
"""
|
||||
Accept the invitation to join a MUC
|
||||
@param room: room jid as string
|
||||
def _accept(self, room_jid, profile_key=C.PROF_KEY_NONE):
|
||||
"""Accept the invitation to join a MUC.
|
||||
|
||||
@param room (jid.JID): JID of the room
|
||||
"""
|
||||
profile = self.host.memory.getProfileName(profile_key)
|
||||
if not profile:
|
||||
log.error(_("Profile doesn't exists !"))
|
||||
return
|
||||
log.info(_('Invitation accepted for room %(room)s [%(profile)s]') % {'room': room, 'profile': profile})
|
||||
log.info(_('Invitation accepted for room %(room)s [%(profile)s]') % {'room': room_jid.userhost(), 'profile': profile})
|
||||
_jid, xmlstream = self.host.getJidNStream(profile)
|
||||
d = self.host.plugins["XEP-0045"].join(jid.JID(room), _jid.user, {}, profile)
|
||||
d = self.host.plugins["XEP-0045"].join(room_jid, _jid.user, {}, profile)
|
||||
return d
|
||||
|
||||
def onInvitation(self, message, profile):
|
||||
|
|
@ -141,28 +141,29 @@ class XEP_0249(object):
|
|||
@profile: %(doc_profile)s
|
||||
"""
|
||||
try:
|
||||
room = message.firstChildElement()['jid']
|
||||
log.info(_('Invitation received for room %(room)s [%(profile)s]') % {'room': room, 'profile': profile})
|
||||
room_jid_s = message.firstChildElement()['jid']
|
||||
log.info(_('Invitation received for room %(room)s [%(profile)s]') % {'room': room_jid_s, 'profile': profile})
|
||||
except:
|
||||
log.error(_('Error while parsing invitation'))
|
||||
return
|
||||
from_ = message["from"]
|
||||
if room in self.host.plugins["XEP-0045"].clients[profile].joined_rooms:
|
||||
from_jid_s = message["from"]
|
||||
room_jid = jid.JID(room_jid_s)
|
||||
if room_jid in self.host.plugins["XEP-0045"].clients[profile].joined_rooms:
|
||||
log.info(_("Invitation silently discarded because user is already in the room."))
|
||||
return
|
||||
autojoin = self.host.memory.getParamA(AUTOJOIN_NAME, AUTOJOIN_KEY, profile_key=profile)
|
||||
|
||||
def accept_cb(conf_id, accepted, data, profile):
|
||||
if conf_id == room and accepted:
|
||||
self._accept(room, profile)
|
||||
if conf_id == room_jid_s and accepted:
|
||||
self._accept(room_jid, profile)
|
||||
|
||||
if autojoin == "always":
|
||||
self._accept(room, profile)
|
||||
self._accept(room_jid, profile)
|
||||
elif autojoin == "never":
|
||||
self.host.bridge.newAlert(_("An invitation from %(user)s to join the room %(room)s has been declined according to your personal settings.") % {'user': from_, 'room': room}, _("MUC invitation"), "INFO", profile)
|
||||
self.host.bridge.newAlert(_("An invitation from %(user)s to join the room %(room)s has been declined according to your personal settings.") % {'user': from_jid_s, 'room': room_jid_s}, _("MUC invitation"), "INFO", profile)
|
||||
else: # leave the default value here
|
||||
data = {"message": _("You have been invited by %(user)s to join the room %(room)s. Do you accept?") % {'user': from_, 'room': room}, "title": _("MUC invitation")}
|
||||
self.host.askConfirmation(room, "YES/NO", data, accept_cb, profile)
|
||||
data = {"message": _("You have been invited by %(user)s to join the room %(room)s. Do you accept?") % {'user': from_jid_s, 'room': room_jid_s}, "title": _("MUC invitation")}
|
||||
self.host.askConfirmation(room_jid_s, "YES/NO", data, accept_cb, profile)
|
||||
|
||||
def cmd_invite(self, mess_data, profile):
|
||||
"""invite someone in the room
|
||||
|
|
|
|||
Loading…
Reference in a new issue