Mercurial > libervia-backend
diff sat/plugins/plugin_misc_room_game.py @ 2624:56f94936df1e
code style reformatting using black
author | Goffi <goffi@goffi.org> |
---|---|
date | Wed, 27 Jun 2018 20:14:46 +0200 |
parents | 26edcf3a30eb |
children | 378188abe941 |
line wrap: on
line diff
--- a/sat/plugins/plugin_misc_room_game.py Wed Jun 27 07:51:29 2018 +0200 +++ b/sat/plugins/plugin_misc_room_game.py Wed Jun 27 20:14:46 2018 +0200 @@ -20,6 +20,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 import jid from twisted.words.xish import domish @@ -28,6 +29,7 @@ from wokkel import disco, iwokkel from zope.interface import implements import copy + try: from twisted.words.protocols.xmlstream import XMPPHandler except ImportError: @@ -44,12 +46,13 @@ C.PI_DEPENDENCIES: ["XEP-0045", "XEP-0249"], C.PI_MAIN: "RoomGame", C.PI_HANDLER: "no", # handler MUST be "no" (dynamic inheritance) - C.PI_DESCRIPTION: _("""Base class for MUC games""") + C.PI_DESCRIPTION: _("""Base class for MUC games"""), } # FIXME: this plugin is broken, need to be fixed + class RoomGame(object): """This class is used to help launching a MUC game. @@ -69,7 +72,7 @@ # Values for ready_mode (how to turn a MUC user into a player) ASK, FORCE = xrange(0, 2) - MESSAGE = '/message' + MESSAGE = "/message" REQUEST = '%s/%s[@xmlns="%s"]' def __init__(self, host): @@ -165,8 +168,13 @@ # 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': {}} + 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, []) @@ -175,7 +183,7 @@ @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 in self.games and (not started or self.games[room_jid]['started']) + return room_jid in self.games and (not started or self.games[room_jid]["started"]) def _checkJoinAuth(self, room_jid, user_jid=None, nick="", verbose=False): """Checks if this profile is allowed to join the game. @@ -209,7 +217,14 @@ break if not auth and (verbose or _DEBUG): - log.debug(_(u"%(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()}) + log.debug( + _(u"%(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, nicks, sync, profile): @@ -224,20 +239,26 @@ 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]['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]['status'][nick] = status + self.games[room_jid]["status"][nick] = status - 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]['players'].extend(new_nicks) + 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]["players"].extend(new_nicks) self._synchronizeRoom(room_jid, [room_jid], profile) if sync: - setStatus('init') + setStatus("init") def _synchronizeRoom(self, room_jid, recipients, profile): """Communicate the list of players to the whole room or only to some users, @@ -249,15 +270,17 @@ @param profile (unicode): %(doc_profile)s """ if self._gameExists(room_jid, started=True): - element = self._createStartElement(self.games[room_jid]['players']) + element = self._createStartElement(self.games[room_jid]["players"]) else: - element = self._createStartElement(self.games[room_jid]['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) for nick in sync_data: - user_jid = jid.JID(room_jid.userhost() + '/' + 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]: @@ -265,7 +288,7 @@ recipients.remove(user_jid) else: user_elements = [(child, None, None) for child in sync_data[nick]] - sync_args.append(([user_jid, user_elements], {'profile': profile})) + sync_args.append(([user_jid, user_elements], {"profile": profile})) for recipient in recipients: self._sendElements(recipient, elements, profile=profile) @@ -283,8 +306,8 @@ if not self._gameExists(room_jid): return {} data = {} - status = self.games[room_jid]['status'] - nicks = [nick for nick in status if status[nick] == 'desync'] + status = self.games[room_jid]["status"] + nicks = [nick for nick in status if status[nick] == "desync"] if force_nicks is None: force_nicks = [] for nick in force_nicks: @@ -316,13 +339,19 @@ if not self._checkInviteAuth(room_jid, nick): return [] # TODO: remove invitation waiting for too long, using the time data - self.invitations[room_jid].append((time(), [player.userhostJID() for player in other_players])) + self.invitations[room_jid].append( + (time(), [player.userhostJID() for player in other_players]) + ) nicks = [] 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"].getRoomEntityNick(room_jid, player_jid, secure=self.testing) + other_nick = self.host.plugins["XEP-0045"].getRoomEntityNick( + room_jid, player_jid, secure=self.testing + ) if other_nick is None: - self.host.plugins["XEP-0249"].invite(player_jid, room_jid, {"game": self.name}, profile) + self.host.plugins["XEP-0249"].invite( + player_jid, room_jid, {"game": self.name}, profile + ) else: nicks.append(other_nick) return nicks @@ -339,13 +368,18 @@ 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, started=True) and self.isReferee(room_jid, 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, nick) elif self.invite_mode == self.FROM_PLAYERS: auth = self.isPlayer(room_jid, nick) if not auth and (verbose or _DEBUG): - log.debug(_(u"%(user)s not allowed to invite for the game %(game)s in %(room)s") % {'user': nick, 'game': self.name, 'room': room_jid.userhost()}) + log.debug( + _(u"%(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, nick): @@ -356,7 +390,9 @@ """ if not self._gameExists(room_jid): return False - return jid.JID(room_jid.userhost() + '/' + nick) == self.games[room_jid]['referee'] + return ( + jid.JID(room_jid.userhost() + "/" + nick) == self.games[room_jid]["referee"] + ) def isPlayer(self, room_jid, nick): """Checks if the user with this nick is a player for the game in this room. @@ -368,7 +404,7 @@ 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]['players'] or self.isReferee(room_jid, 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. @@ -388,10 +424,21 @@ result = (False, [], other_players) else: # TODO: find a way to make it secure - (nicks, missing) = self.host.plugins["XEP-0045"].getRoomNicksOfUsers(room, other_players, secure=False) + (nicks, missing) = self.host.plugins["XEP-0045"].getRoomNicksOfUsers( + room, other_players, secure=False + ) result = (len(nicks) == len(other_players), nicks, missing) if not result[0] and (verbose or _DEBUG): - log.debug(_(u"Still waiting for %(users)s before starting the game %(game)s in %(room)s") % {'users': result[2], 'game': self.name, 'room': room.occupantJID.userhost()}) + log.debug( + _( + u"Still waiting for %(users)s before starting the game %(game)s in %(room)s" + ) + % { + "users": result[2], + "game": self.name, + "room": room.occupantJID.userhost(), + } + ) return result def getUniqueName(self, muc_service=None, profile_key=C.PROF_KEY_NONE): @@ -406,7 +453,9 @@ room = self.host.plugins["XEP-0045"].getUniqueName(client, muc_service) return jid.JID("sat_%s_%s" % (self.name.lower(), room.userhost())) - def _prepareRoom(self, other_players=None, room_jid_s='', 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) @@ -420,7 +469,7 @@ """ # FIXME: need to be refactored client = self.host.getClient(profile_key) - log.debug(_(u'Preparing room for %s game') % self.name) + log.debug(_(u"Preparing room for %s game") % self.name) profile = self.host.memory.getProfileName(profile_key) if not profile: log.error(_("Unknown profile")) @@ -438,7 +487,9 @@ user_jid = self.host.getJidNStream(profile)[0] d = self.host.plugins["XEP-0045"].join(room_jid, user_jid.user, {}, profile) - return d.addCallback(lambda dummy: self._createOrInvite(client, room_jid, other_players)) + return d.addCallback( + lambda dummy: self._createOrInvite(client, room_jid, other_players) + ) def userJoinedTrigger(self, room, user, profile): """This trigger is used to check if the new user can take part of a game, create the game if we were waiting for him or just update the players list. @@ -451,15 +502,22 @@ profile_nick = room.occupantJID.resource if not self.isReferee(room_jid, profile_nick): return True # profile is not the referee - if not self._checkJoinAuth(room_jid, user.entity 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, [jid.JID(room_jid.userhost() + '/' + 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]) - 1 if batch < 0: - log.error(u"Invitations from %s to play %s in %s have been lost!" % (profile_nick, self.name, room_jid.userhost())) + log.error( + u"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][batch][1] (auth, nicks, dummy) = self._checkWaitAuth(room, other_players) @@ -485,10 +543,10 @@ return True # profile is not the referee if self.isPlayer(room_jid, user.nick): try: - self.games[room_jid]['players'].remove(user.nick) + self.games[room_jid]["players"].remove(user.nick) except ValueError: pass - if len(self.games[room_jid]['players']) == 0: + 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 @@ -513,15 +571,24 @@ """ user_nick = self.host.plugins["XEP-0045"].getRoomNick(room_jid, profile) if not user_nick: - log.error(u'Internal error: profile %s has not joined the room %s' % (profile, room_jid.userhost())) + log.error( + u"Internal error: profile %s has not joined the room %s" + % (profile, room_jid.userhost()) + ) return False, False if self._gameExists(room_jid): is_referee = self.isReferee(room_jid, user_nick) if self._gameExists(room_jid, started=True): - log.info(_(u"%(game)s game already created in room %(room)s") % {'game': self.name, 'room': room_jid.userhost()}) + log.info( + _(u"%(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.info(_(u"%(game)s game in room %(room)s can only be created by %(user)s") % {'game': self.name, 'room': room_jid.userhost(), 'user': user_nick}) + log.info( + _(u"%(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, user_nick) @@ -539,7 +606,10 @@ @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(_(u"Creating %(game)s game in room %(room)s") % {'game': self.name, 'room': room_jid}) + log.debug( + _(u"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(_(u"profile %s is unknown") % profile_key) @@ -551,14 +621,16 @@ if sync: self._updatePlayers(room_jid, nicks, True, profile) return - self.games[room_jid]['started'] = True + 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].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]['players_data'][nick] = copy.deepcopy(self.player_init) + self.games[room_jid]["players_data"][nick] = copy.deepcopy( + self.player_init + ) 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) @@ -573,9 +645,9 @@ if not profile: log.error(_(u"profile %s is unknown") % profile_key) return - log.debug(u'new player ready: %s' % profile) + log.debug(u"new player ready: %s" % profile) # TODO: we probably need to add the game and room names in the sent message - self.send(referee_jid, 'player_ready', {'player': player_nick}, 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) @@ -586,18 +658,22 @@ - msg_elts: dict to map each user to his specific initialization message @param profile """ - log.debug(_(u'new round for %s game') % self.name) + log.debug(_(u"new round for %s game") % self.name) game_data = self.games[room_jid] - players = game_data['players'] - players_data = game_data['players_data'] - game_data['stage'] = "init" + players = game_data["players"] + players_data = game_data["players_data"] + game_data["stage"] = "init" common_data, msg_elts = copy.deepcopy(data) if data is not None else (None, None) if isinstance(msg_elts, dict): for player in players: to_jid = jid.JID(room_jid.userhost() + "/" + player) # FIXME: gof: - elem = msg_elts[player] if isinstance(msg_elts[player], domish.Element) else None + 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): self.send(room_jid, msg_elts, profile=profile) @@ -612,7 +688,7 @@ @return: the created element """ type_ = "normal" if to_jid.resource else "groupchat" - elt = domish.Element((None, 'message')) + elt = domish.Element((None, "message")) elt["to"] = to_jid.full() elt["type"] = type_ elt.addElement(self.ns_tag) @@ -632,9 +708,9 @@ return started_elt idx = 0 for player in players: - player_elt = domish.Element((None, 'player')) + player_elt = domish.Element((None, "player")) player_elt.addContent(player) - player_elt['index'] = str(idx) + player_elt["index"] = str(idx) idx += 1 started_elt.addChild(player_elt) return started_elt @@ -687,7 +763,7 @@ return RoomGameHandler(self) -class RoomGameHandler (XMPPHandler): +class RoomGameHandler(XMPPHandler): implements(iwokkel.IDisco) def __init__(self, plugin_parent): @@ -695,10 +771,14 @@ self.host = plugin_parent.host def connectionInitialized(self): - self.xmlstream.addObserver(self.plugin_parent.request, self.plugin_parent.room_game_cmd, profile=self.parent.profile) + self.xmlstream.addObserver( + self.plugin_parent.request, + self.plugin_parent.room_game_cmd, + profile=self.parent.profile, + ) - def getDiscoInfo(self, requestor, target, nodeIdentifier=''): + def getDiscoInfo(self, requestor, target, nodeIdentifier=""): return [disco.DiscoFeature(self.plugin_parent.ns_tag[0])] - def getDiscoItems(self, requestor, target, nodeIdentifier=''): + def getDiscoItems(self, requestor, target, nodeIdentifier=""): return []