massive refactoring to switch from camelCase to snake_case:

historically, Libervia (SàT before) was using camelCase as allowed by PEP8 when using a
pre-PEP8 code, to use the same coding style as in Twisted.

However, snake_case is more readable and it's better to follow PEP8 best practices, so it
has been decided to move on full snake_case. Because Libervia has a huge codebase, this
ended with a ugly mix of camelCase and snake_case.

To fix that, this patch does a big refactoring by renaming every function and method
(including bridge) that are not coming from Twisted or Wokkel, to use fully snake_case.

This is a massive change, and may result in some bugs.
This commit is contained in:
Goffi 2023-04-08 13:54:42 +02:00
commit 6a6f15707a

View file

@ -56,9 +56,9 @@ PLUGIN_INFO = {
class RoomGame(object):
"""This class is used to help launching a MUC game.
Bridge methods callbacks: _prepareRoom, _playerReady, _createGame
Triggered methods: userJoinedTrigger, userLeftTrigger
Also called from subclasses: newRound
bridge methods callbacks: _prepare_room, _player_ready, _create_game
Triggered methods: user_joined_trigger, user_left_trigger
Also called from subclasses: new_round
For examples of messages sequences, please look in sub-classes.
"""
@ -81,13 +81,13 @@ class RoomGame(object):
class MyGame(object):
def inheritFromRoomGame(self, host):
def inherit_from_room_game(self, host):
global RoomGame
RoomGame = host.plugins["ROOM-GAME"].__class__
self.__class__ = type(self.__class__.__name__, (self.__class__, RoomGame, object), {})
def __init__(self, host):
self.inheritFromRoomGame(host)
self.inherit_from_room_game(host)
RoomGame._init_(self, host, ...)
"""
@ -125,41 +125,41 @@ class RoomGame(object):
# by an arbitrary value. If needed, this attribute would be set to True from the testcase.
self.testing = False
host.trigger.add("MUC user joined", self.userJoinedTrigger)
host.trigger.add("MUC user left", self.userLeftTrigger)
host.trigger.add("MUC user joined", self.user_joined_trigger)
host.trigger.add("MUC user left", self.user_left_trigger)
def _createOrInvite(self, room_jid, other_players, profile):
def _create_or_invite(self, room_jid, 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).
join the room (in that case it will be created from user_joined_trigger).
@param room (wokkel.muc.Room): the room
@param other_players (list[jid.JID]): list of the other players JID (bare)
"""
# FIXME: broken !
raise NotImplementedError("To be fixed")
client = self.host.getClient(profile)
user_jid = self.host.getJidNStream(profile)[0]
nick = self.host.plugins["XEP-0045"].getRoomNick(client, room_jid)
client = self.host.get_client(profile)
user_jid = self.host.get_jid_n_stream(profile)[0]
nick = self.host.plugins["XEP-0045"].get_room_nick(client, room_jid)
nicks = [nick]
if self._gameExists(room_jid):
if not self._checkJoinAuth(room_jid, user_jid, nick):
if self._game_exists(room_jid):
if not self._check_join_auth(room_jid, user_jid, nick):
return
nicks.extend(self._invitePlayers(room_jid, other_players, nick, profile))
self._updatePlayers(room_jid, nicks, True, profile)
nicks.extend(self._invite_players(room_jid, other_players, nick, profile))
self._update_players(room_jid, nicks, True, profile)
else:
self._initGame(room_jid, nick)
(auth, waiting, missing) = self._checkWaitAuth(room_jid, other_players)
self._init_game(room_jid, nick)
(auth, waiting, missing) = self._check_wait_auth(room_jid, other_players)
nicks.extend(waiting)
nicks.extend(self._invitePlayers(room_jid, missing, nick, profile))
nicks.extend(self._invite_players(room_jid, missing, nick, profile))
if auth:
self.createGame(room_jid, nicks, profile)
self.create_game(room_jid, nicks, profile)
else:
self._updatePlayers(room_jid, nicks, False, profile)
self._update_players(room_jid, nicks, False, profile)
def _initGame(self, room_jid, referee_nick):
def _init_game(self, room_jid, referee_nick):
"""
@param room_jid (jid.JID): JID of the room
@ -167,7 +167,7 @@ class RoomGame(object):
"""
# 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.
# it is necessary to not modify 'players' outside of _update_players.
referee_jid = jid.JID(room_jid.userhost() + "/" + referee_nick)
self.games[room_jid] = {
"referee": referee_jid,
@ -178,19 +178,19 @@ class RoomGame(object):
self.games[room_jid].update(copy.deepcopy(self.game_init))
self.invitations.setdefault(room_jid, [])
def _gameExists(self, room_jid, started=False):
def _game_exists(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.
otherwise it must be initialized and started with create_game.
@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"])
def _checkJoinAuth(self, room_jid, user_jid=None, nick="", verbose=False):
def _check_join_auth(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
user_joined_trigger, nick is also used to check the user
identity instead of user_jid_s (see TODO comment below).
@param room_jid (jid.JID): the JID of the room hosting the game
@param user_jid (jid.JID): JID of the user
@ -198,9 +198,9 @@ class RoomGame(object):
@return: True if this profile can join the game
"""
auth = False
if not self._gameExists(room_jid):
if not self._game_exists(room_jid):
auth = False
elif self.join_mode == self.ALL or self.isPlayer(room_jid, nick):
elif self.join_mode == self.ALL or self.is_player(room_jid, nick):
auth = True
elif self.join_mode == self.INVITED:
# considering all the batches of invitations
@ -227,7 +227,7 @@ class RoomGame(object):
)
return auth
def _updatePlayers(self, room_jid, nicks, sync, profile):
def _update_players(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]['players'] should not be modified outside this method.
@ -251,16 +251,16 @@ class RoomGame(object):
sync = (
sync
and self._gameExists(room_jid, True)
and self._game_exists(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)
self._synchronize_room(room_jid, [room_jid], profile)
if sync:
setStatus("init")
def _synchronizeRoom(self, room_jid, recipients, profile):
def _synchronize_room(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 (jid.JID): JID of the room
@ -269,16 +269,16 @@ class RoomGame(object):
- room JID + "/" + user nick
@param profile (unicode): %(doc_profile)s
"""
if self._gameExists(room_jid, started=True):
element = self._createStartElement(self.games[room_jid]["players"])
if self._game_exists(room_jid, started=True):
element = self._create_start_element(self.games[room_jid]["players"])
else:
element = self._createStartElement(
element = self._create_start_element(
self.games[room_jid]["players"], name="players"
)
elements = [(element, None, None)]
sync_args = []
sync_data = self._getSyncData(room_jid)
sync_data = self._get_sync_data(room_jid)
for nick in sync_data:
user_jid = jid.JID(room_jid.userhost() + "/" + nick)
if user_jid in recipients:
@ -291,19 +291,19 @@ class RoomGame(object):
sync_args.append(([user_jid, user_elements], {"profile": profile}))
for recipient in recipients:
self._sendElements(recipient, elements, profile=profile)
self._send_elements(recipient, elements, profile=profile)
for args, kwargs in sync_args:
self._sendElements(*args, **kwargs)
self._send_elements(*args, **kwargs)
def _getSyncData(self, room_jid, force_nicks=None):
def _get_sync_data(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 (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.
be sent by self._synchronize_room for the game to be synchronized.
"""
if not self._gameExists(room_jid):
if not self._game_exists(room_jid):
return {}
data = {}
status = self.games[room_jid]["status"]
@ -314,12 +314,12 @@ class RoomGame(object):
if nick not in nicks:
nicks.append(nick)
for nick in nicks:
elements = self.getSyncDataForPlayer(room_jid, nick)
elements = self.get_sync_data_for_player(room_jid, nick)
if elements:
data[nick] = elements
return data
def getSyncDataForPlayer(self, room_jid, nick):
def get_sync_data_for_player(self, room_jid, nick):
"""This method may (and should probably) be overwritten by a child class.
@param room_jid (jid.JID): JID of the room
@param nick: the nick of the player to be synchronized
@ -327,7 +327,7 @@ class RoomGame(object):
"""
return []
def _invitePlayers(self, room_jid, other_players, nick, profile):
def _invite_players(self, room_jid, other_players, nick, profile):
"""Invite players to a room, associated game may exist or not.
@param other_players (list[jid.JID]): list of the players to invite
@ -336,7 +336,7 @@ class RoomGame(object):
"""
raise NotImplementedError("Need to be fixed !")
# FIXME: this is broken and unsecure !
if not self._checkInviteAuth(room_jid, nick):
if not self._check_invite_auth(room_jid, nick):
return []
# TODO: remove invitation waiting for too long, using the time data
self.invitations[room_jid].append(
@ -356,7 +356,7 @@ class RoomGame(object):
nicks.append(other_nick)
return nicks
def _checkInviteAuth(self, room_jid, nick, verbose=False):
def _check_invite_auth(self, room_jid, nick, verbose=False):
"""Checks if this user is allowed to invite players
@param room_jid (jid.JID): JID of the room
@ -365,16 +365,16 @@ class RoomGame(object):
@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):
if self.invite_mode == self.FROM_ALL or not self._game_exists(room_jid):
auth = True
elif self.invite_mode == self.FROM_NONE:
auth = not self._gameExists(room_jid, started=True) and self.isReferee(
auth = not self._game_exists(room_jid, started=True) and self.is_referee(
room_jid, nick
)
elif self.invite_mode == self.FROM_REFEREE:
auth = self.isReferee(room_jid, nick)
auth = self.is_referee(room_jid, nick)
elif self.invite_mode == self.FROM_PLAYERS:
auth = self.isPlayer(room_jid, nick)
auth = self.is_player(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")
@ -382,31 +382,31 @@ class RoomGame(object):
)
return auth
def isReferee(self, room_jid, nick):
def is_referee(self, room_jid, nick):
"""Checks if the player with this nick is the referee for the game in this room"
@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):
if not self._game_exists(room_jid):
return False
return (
jid.JID(room_jid.userhost() + "/" + nick) == self.games[room_jid]["referee"]
)
def isPlayer(self, room_jid, nick):
def is_player(self, room_jid, nick):
"""Checks if the user with this nick is a player for the game in this room.
@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):
if not self._game_exists(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]["players"] or self.isReferee(room_jid, nick)
# the game initialization, that's why we do also check with is_referee
return nick in self.games[room_jid]["players"] or self.is_referee(room_jid, nick)
def _checkWaitAuth(self, room, other_players, verbose=False):
def _check_wait_auth(self, room, other_players, verbose=False):
"""Check if we must wait for other players before starting the game.
@param room (wokkel.muc.Room): the room
@ -441,26 +441,26 @@ class RoomGame(object):
)
return result
def getUniqueName(self, muc_service=None, profile_key=C.PROF_KEY_NONE):
def get_unique_name(self, muc_service=None, profile_key=C.PROF_KEY_NONE):
"""Generate unique room name
@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)
"""
client = self.host.getClient(profile_key)
client = self.host.get_client(profile_key)
# FIXME: jid.JID must be used instead of strings
room = self.host.plugins["XEP-0045"].getUniqueName(client, muc_service)
room = self.host.plugins["XEP-0045"].get_unique_name(client, muc_service)
return jid.JID("sat_%s_%s" % (self.name.lower(), room.userhost()))
def _prepareRoom(
def _prepare_room(
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)
return self.prepare_room(other_players, room_jid, profile_key)
def prepareRoom(self, other_players=None, room_jid=None, profile_key=C.PROF_KEY_NONE):
def prepare_room(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[JID]): list of other players JID (bare)
@ -468,9 +468,9 @@ class RoomGame(object):
@param profile_key (unicode): %(doc_profile_key)s
"""
# FIXME: need to be refactored
client = self.host.getClient(profile_key)
client = self.host.get_client(profile_key)
log.debug(_("Preparing room for %s game") % self.name)
profile = self.host.memory.getProfileName(profile_key)
profile = self.host.memory.get_profile_name(profile_key)
if not profile:
log.error(_("Unknown profile"))
return defer.succeed(None)
@ -479,19 +479,19 @@ class RoomGame(object):
# Create/join the given room, or a unique generated one if no room is specified.
if room_jid is None:
room_jid = self.getUniqueName(profile_key=profile_key)
room_jid = self.get_unique_name(profile_key=profile_key)
else:
self.host.plugins["XEP-0045"].checkRoomJoined(client, room_jid)
self._createOrInvite(client, room_jid, other_players)
self.host.plugins["XEP-0045"].check_room_joined(client, room_jid)
self._create_or_invite(client, room_jid, other_players)
return defer.succeed(None)
user_jid = self.host.getJidNStream(profile)[0]
user_jid = self.host.get_jid_n_stream(profile)[0]
d = self.host.plugins["XEP-0045"].join(room_jid, user_jid.user, {}, profile)
return d.addCallback(
lambda __: self._createOrInvite(client, room_jid, other_players)
lambda __: self._create_or_invite(client, room_jid, other_players)
)
def userJoinedTrigger(self, room, user, profile):
def user_joined_trigger(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.
@room: wokkel.muc.Room object. room.roster is a dict{wokkel.muc.User.nick: wokkel.muc.User}
@ -500,13 +500,13 @@ class RoomGame(object):
"""
room_jid = room.occupantJID.userhostJID()
profile_nick = room.occupantJID.resource
if not self.isReferee(room_jid, profile_nick):
if not self.is_referee(room_jid, profile_nick):
return True # profile is not the referee
if not self._checkJoinAuth(
if not self._check_join_auth(
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(
self._synchronize_room(
room_jid, [jid.JID(room_jid.userhost() + "/" + user.nick)], profile
)
return True
@ -520,17 +520,17 @@ class RoomGame(object):
)
return True
other_players = self.invitations[room_jid][batch][1]
(auth, nicks, __) = self._checkWaitAuth(room, other_players)
(auth, nicks, __) = self._check_wait_auth(room, other_players)
if auth:
del self.invitations[room_jid][batch]
nicks.insert(0, profile_nick) # add the referee
self.createGame(room_jid, nicks, profile_key=profile)
self.create_game(room_jid, nicks, profile_key=profile)
return True
# let the room know that a new player joined
self._updatePlayers(room_jid, [user.nick], True, profile)
self._update_players(room_jid, [user.nick], True, profile)
return True
def userLeftTrigger(self, room, user, profile):
def user_left_trigger(self, room, user, profile):
"""This trigger is used to update or stop the game when a user leaves.
@room: wokkel.muc.Room object. room.roster is a dict{wokkel.muc.User.nick: wokkel.muc.User}
@ -539,9 +539,9 @@ class RoomGame(object):
"""
room_jid = room.occupantJID.userhostJID()
profile_nick = room.occupantJID.resource
if not self.isReferee(room_jid, profile_nick):
if not self.is_referee(room_jid, profile_nick):
return True # profile is not the referee
if self.isPlayer(room_jid, user.nick):
if self.is_player(room_jid, user.nick):
try:
self.games[room_jid]["players"].remove(user.nick)
except ValueError:
@ -559,7 +559,7 @@ class RoomGame(object):
self.invitations[room_jid][batch][1].append(user_jid)
return True
def _checkCreateGameAndInit(self, room_jid, profile):
def _check_create_game_and_init(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.
@ -569,16 +569,16 @@ class RoomGame(object):
- 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, profile)
user_nick = self.host.plugins["XEP-0045"].get_room_nick(room_jid, profile)
if not user_nick:
log.error(
"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):
if self._game_exists(room_jid):
is_referee = self.is_referee(room_jid, user_nick)
if self._game_exists(room_jid, started=True):
log.info(
_("%(game)s game already created in room %(room)s")
% {"game": self.name, "room": room_jid.userhost()}
@ -591,13 +591,13 @@ class RoomGame(object):
)
return False, False
else:
self._initGame(room_jid, user_nick)
self._init_game(room_jid, user_nick)
return True, False
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 _create_game(self, room_jid_s, nicks=None, profile_key=C.PROF_KEY_NONE):
self.create_game(jid.JID(room_jid_s), nicks, profile_key)
def createGame(self, room_jid, nicks=None, profile_key=C.PROF_KEY_NONE):
def create_game(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,
@ -610,19 +610,19 @@ class RoomGame(object):
_("Creating %(game)s game in room %(room)s")
% {"game": self.name, "room": room_jid}
)
profile = self.host.memory.getProfileName(profile_key)
profile = self.host.memory.get_profile_name(profile_key)
if not profile:
log.error(_("profile %s is unknown") % profile_key)
return
(create, sync) = self._checkCreateGameAndInit(room_jid, profile)
(create, sync) = self._check_create_game_and_init(room_jid, profile)
if nicks is None:
nicks = []
if not create:
if sync:
self._updatePlayers(room_jid, nicks, True, profile)
self._update_players(room_jid, nicks, True, profile)
return
self.games[room_jid]["started"] = True
self._updatePlayers(room_jid, nicks, False, profile)
self._update_players(room_jid, nicks, False, profile)
if self.player_init:
# specific data to each player (score, private data)
self.games[room_jid].setdefault("players_data", {})
@ -632,16 +632,16 @@ class RoomGame(object):
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)
def _player_ready(self, player_nick, referee_jid_s, profile_key=C.PROF_KEY_NONE):
self.player_ready(player_nick, jid.JID(referee_jid_s), profile_key)
def playerReady(self, player_nick, referee_jid, profile_key=C.PROF_KEY_NONE):
def player_ready(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_jid (jid.JID): JID of the referee
"""
profile = self.host.memory.getProfileName(profile_key)
profile = self.host.memory.get_profile_name(profile_key)
if not profile:
log.error(_("profile %s is unknown") % profile_key)
return
@ -649,7 +649,7 @@ class RoomGame(object):
# 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)
def newRound(self, room_jid, data, profile):
def new_round(self, room_jid, data, profile):
"""Launch a new round (reinit the user data)
@param room_jid: room userhost
@ -681,7 +681,7 @@ class RoomGame(object):
for player in players:
players_data[player].update(copy.deepcopy(common_data))
def _createGameElt(self, to_jid):
def _create_game_elt(self, to_jid):
"""Create a generic domish Element for the game messages
@param to_jid: JID of the recipient
@ -694,7 +694,7 @@ class RoomGame(object):
elt.addElement(self.ns_tag)
return elt
def _createStartElement(self, players=None, name="started"):
def _create_start_element(self, players=None, name="started"):
"""Create a domish Element listing the game users
@param players: list of the players
@ -715,7 +715,7 @@ class RoomGame(object):
started_elt.addChild(player_elt)
return started_elt
def _sendElements(self, to_jid, data, profile=None):
def _send_elements(self, to_jid, data, profile=None):
""" TODO
@param to_jid: recipient JID
@ -729,8 +729,8 @@ class RoomGame(object):
@param profile: the profile from which the message is sent
@return: a Deferred instance
"""
client = self.host.getClient(profile)
msg = self._createGameElt(to_jid)
client = self.host.get_client(profile)
msg = self._create_game_elt(to_jid)
for elem, attrs, content in data:
if elem is not None:
if isinstance(elem, domish.Element):
@ -757,9 +757,9 @@ class RoomGame(object):
@param profile: the profile from which the message is sent
@return: a Deferred instance
"""
return self._sendElements(to_jid, [(elem, attrs, content)], profile)
return self._send_elements(to_jid, [(elem, attrs, content)], profile)
def getHandler(self, client):
def get_handler(self, client):
return RoomGameHandler(self)