Mercurial > libervia-backend
diff sat/plugins/plugin_xep_0045.py @ 4037:524856bd7b19
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.
author | Goffi <goffi@goffi.org> |
---|---|
date | Sat, 08 Apr 2023 13:54:42 +0200 |
parents | 32d714a8ea51 |
children | c23cad65ae99 |
line wrap: on
line diff
--- a/sat/plugins/plugin_xep_0045.py Fri Apr 07 15:18:39 2023 +0200 +++ b/sat/plugins/plugin_xep_0045.py Sat Apr 08 13:54:42 2023 +0200 @@ -87,93 +87,93 @@ log.info(_("Plugin XEP_0045 initialization")) self.host = host self._sessions = memory.Sessions() - # return same arguments as mucRoomJoined + a boolean set to True is the room was + # return same arguments as muc_room_joined + a boolean set to True is the room was # already joined (first argument) - host.bridge.addMethod( - "mucJoin", ".plugin", in_sign='ssa{ss}s', out_sign='(bsa{sa{ss}}ssass)', + host.bridge.add_method( + "muc_join", ".plugin", in_sign='ssa{ss}s', out_sign='(bsa{sa{ss}}ssass)', method=self._join, async_=True) - host.bridge.addMethod( - "mucNick", ".plugin", in_sign='sss', out_sign='', method=self._nick) - host.bridge.addMethod( - "mucNickGet", ".plugin", in_sign='ss', out_sign='s', method=self._getRoomNick) - host.bridge.addMethod( - "mucLeave", ".plugin", in_sign='ss', out_sign='', method=self._leave, + host.bridge.add_method( + "muc_nick", ".plugin", in_sign='sss', out_sign='', method=self._nick) + host.bridge.add_method( + "muc_nick_get", ".plugin", in_sign='ss', out_sign='s', method=self._get_room_nick) + host.bridge.add_method( + "muc_leave", ".plugin", in_sign='ss', out_sign='', method=self._leave, async_=True) - host.bridge.addMethod( - "mucOccupantsGet", ".plugin", in_sign='ss', out_sign='a{sa{ss}}', - method=self._getRoomOccupants) - host.bridge.addMethod( - "mucSubject", ".plugin", in_sign='sss', out_sign='', method=self._subject) - host.bridge.addMethod( - "mucGetRoomsJoined", ".plugin", in_sign='s', out_sign='a(sa{sa{ss}}ssas)', - method=self._getRoomsJoined) - host.bridge.addMethod( - "mucGetUniqueRoomName", ".plugin", in_sign='ss', out_sign='s', - method=self._getUniqueName) - host.bridge.addMethod( - "mucConfigureRoom", ".plugin", in_sign='ss', out_sign='s', - method=self._configureRoom, async_=True) - host.bridge.addMethod( - "mucGetDefaultService", ".plugin", in_sign='', out_sign='s', - method=self.getDefaultMUC) - host.bridge.addMethod( - "mucGetService", ".plugin", in_sign='ss', out_sign='s', - method=self._getMUCService, async_=True) + host.bridge.add_method( + "muc_occupants_get", ".plugin", in_sign='ss', out_sign='a{sa{ss}}', + method=self._get_room_occupants) + host.bridge.add_method( + "muc_subject", ".plugin", in_sign='sss', out_sign='', method=self._subject) + host.bridge.add_method( + "muc_get_rooms_joined", ".plugin", in_sign='s', out_sign='a(sa{sa{ss}}ssas)', + method=self._get_rooms_joined) + host.bridge.add_method( + "muc_get_unique_room_name", ".plugin", in_sign='ss', out_sign='s', + method=self._get_unique_name) + host.bridge.add_method( + "muc_configure_room", ".plugin", in_sign='ss', out_sign='s', + method=self._configure_room, async_=True) + host.bridge.add_method( + "muc_get_default_service", ".plugin", in_sign='', out_sign='s', + method=self.get_default_muc) + host.bridge.add_method( + "muc_get_service", ".plugin", in_sign='ss', out_sign='s', + method=self._get_muc_service, async_=True) # called when a room will be joined but must be locked until join is received # (room is prepared, history is getting retrieved) # args: room_jid, profile - host.bridge.addSignal( - "mucRoomPrepareJoin", ".plugin", signature='ss') + host.bridge.add_signal( + "muc_room_prepare_join", ".plugin", signature='ss') # args: room_jid, occupants, user_nick, subject, profile - host.bridge.addSignal( - "mucRoomJoined", ".plugin", signature='sa{sa{ss}}ssass') + host.bridge.add_signal( + "muc_room_joined", ".plugin", signature='sa{sa{ss}}ssass') # args: room_jid, profile - host.bridge.addSignal( - "mucRoomLeft", ".plugin", signature='ss') + host.bridge.add_signal( + "muc_room_left", ".plugin", signature='ss') # args: room_jid, old_nick, new_nick, profile - host.bridge.addSignal( - "mucRoomUserChangedNick", ".plugin", signature='ssss') + host.bridge.add_signal( + "muc_room_user_changed_nick", ".plugin", signature='ssss') # args: room_jid, subject, profile - host.bridge.addSignal( - "mucRoomNewSubject", ".plugin", signature='sss') - self.__submit_conf_id = host.registerCallback( - self._submitConfiguration, with_data=True) - self._room_join_id = host.registerCallback(self._UIRoomJoinCb, with_data=True) - host.importMenu( - (D_("MUC"), D_("configure")), self._configureRoomMenu, security_limit=0, + host.bridge.add_signal( + "muc_room_new_subject", ".plugin", signature='sss') + self.__submit_conf_id = host.register_callback( + self._submit_configuration, with_data=True) + self._room_join_id = host.register_callback(self._ui_room_join_cb, with_data=True) + host.import_menu( + (D_("MUC"), D_("configure")), self._configure_room_menu, security_limit=0, help_string=D_("Configure Multi-User Chat room"), type_=C.MENU_ROOM) try: self.text_cmds = self.host.plugins[C.TEXT_CMDS] except KeyError: log.info(_("Text commands not available")) else: - self.text_cmds.registerTextCommands(self) - self.text_cmds.addWhoIsCb(self._whois, 100) + self.text_cmds.register_text_commands(self) + self.text_cmds.add_who_is_cb(self._whois, 100) self._mam = self.host.plugins.get("XEP-0313") self._si = self.host.plugins["XEP-0359"] - host.trigger.add("presence_available", self.presenceTrigger) - host.trigger.add("presence_received", self.presenceReceivedTrigger) - host.trigger.add("messageReceived", self.messageReceivedTrigger, priority=1000000) - host.trigger.add("message_parse", self._message_parseTrigger) + host.trigger.add("presence_available", self.presence_trigger) + host.trigger.add("presence_received", self.presence_received_trigger) + host.trigger.add("messageReceived", self.message_received_trigger, priority=1000000) + host.trigger.add("message_parse", self._message_parse_trigger) - async def profileConnected(self, client): - client.muc_service = await self.get_MUC_service(client) + async def profile_connected(self, client): + client.muc_service = await self.get_muc_service(client) - def _message_parseTrigger(self, client, message_elt, data): + def _message_parse_trigger(self, client, message_elt, data): """Add stanza-id from the room if present""" if message_elt.getAttribute("type") != C.MESS_TYPE_GROUPCHAT: return True - # stanza_id will not be filled by parseMessage because the emitter + # stanza_id will not be filled by parse_message because the emitter # is the room and not our server, so we have to parse it here room_jid = data["from"].userhostJID() - stanza_id = self._si.getStanzaId(message_elt, room_jid) + stanza_id = self._si.get_stanza_id(message_elt, room_jid) if stanza_id: data["extra"]["stanza_id"] = stanza_id - def messageReceivedTrigger(self, client, message_elt, post_treat): + def message_received_trigger(self, client, message_elt, post_treat): if message_elt.getAttribute("type") == C.MESS_TYPE_GROUPCHAT: if message_elt.subject or message_elt.delay: return False @@ -200,7 +200,7 @@ return False return True - def getRoom(self, client: SatXMPPEntity, room_jid: jid.JID) -> muc.Room: + def get_room(self, client: SatXMPPEntity, room_jid: jid.JID) -> muc.Room: """Retrieve Room instance from its jid @param room_jid: jid of the room @@ -211,7 +211,7 @@ except KeyError: raise exceptions.NotFound(_("This room has not been joined")) - def checkRoomJoined(self, client, room_jid): + def check_room_joined(self, client, room_jid): """Check that given room has been joined in current session @param room_jid (JID): room JID @@ -219,78 +219,78 @@ if room_jid not in client._muc_client.joined_rooms: raise exceptions.NotFound(_("This room has not been joined")) - def isJoinedRoom(self, client: SatXMPPEntity, room_jid: jid.JID) -> bool: + def is_joined_room(self, client: SatXMPPEntity, room_jid: jid.JID) -> bool: """Tell if a jid is a known and joined room @room_jid: jid of the room """ try: - self.checkRoomJoined(client, room_jid) + self.check_room_joined(client, room_jid) except exceptions.NotFound: return False else: return True - def isRoom(self, client, entity_jid): + def is_room(self, client, entity_jid): """Tell if a jid is a joined MUC - similar to isJoinedRoom but returns a boolean + similar to is_joined_room but returns a boolean @param entity_jid(jid.JID): full or bare jid of the entity check @return (bool): True if the bare jid of the entity is a room jid """ try: - self.checkRoomJoined(client, entity_jid.userhostJID()) + self.check_room_joined(client, entity_jid.userhostJID()) except exceptions.NotFound: return False else: return True - def getBareOrFull(self, client, peer_jid): + def get_bare_or_full(self, client, peer_jid): """use full jid if peer_jid is an occupant of a room, bare jid else @param peer_jid(jid.JID): entity to test @return (jid.JID): bare or full jid """ if peer_jid.resource: - if not self.isRoom(client, peer_jid): + if not self.is_room(client, peer_jid): return peer_jid.userhostJID() return peer_jid - def _getRoomJoinedArgs(self, room, profile): + def _get_room_joined_args(self, room, profile): return [ room.roomJID.userhost(), - XEP_0045._getOccupants(room), + XEP_0045._get_occupants(room), room.nick, room.subject, [s.name for s in room.statuses], profile ] - def _UIRoomJoinCb(self, data, profile): + def _ui_room_join_cb(self, data, profile): room_jid = jid.JID(data['index']) - client = self.host.getClient(profile) + client = self.host.get_client(profile) self.join(client, room_jid) return {} - def _passwordUICb(self, data, client, room_jid, nick): + def _password_ui_cb(self, data, client, room_jid, nick): """Called when the user has given room password (or cancelled)""" if C.bool(data.get(C.XMLUI_DATA_CANCELLED, "false")): log.info("room join for {} is cancelled".format(room_jid.userhost())) raise failure.Failure(exceptions.CancelError(D_("Room joining cancelled by user"))) - password = data[xml_tools.formEscape('password')] - return client._muc_client.join(room_jid, nick, password).addCallbacks(self._joinCb, self._joinEb, (client, room_jid, nick), errbackArgs=(client, room_jid, nick, password)) + password = data[xml_tools.form_escape('password')] + return client._muc_client.join(room_jid, nick, password).addCallbacks(self._join_cb, self._join_eb, (client, room_jid, nick), errbackArgs=(client, room_jid, nick, password)) - def _showListUI(self, items, client, service): + def _show_list_ui(self, items, client, service): xmlui = xml_tools.XMLUI(title=D_('Rooms in {}'.format(service.full()))) - adv_list = xmlui.changeContainer('advanced_list', columns=1, selectable='single', callback_id=self._room_join_id) + adv_list = xmlui.change_container('advanced_list', columns=1, selectable='single', callback_id=self._room_join_id) items = sorted(items, key=lambda i: i.name.lower()) for item in items: - adv_list.setRowIndex(item.entity.full()) + adv_list.set_row_index(item.entity.full()) xmlui.addText(item.name) adv_list.end() - self.host.actionNew({'xmlui': xmlui.toXml()}, profile=client.profile) + self.host.action_new({'xmlui': xmlui.toXml()}, profile=client.profile) - def _joinCb(self, room, client, room_jid, nick): + def _join_cb(self, room, client, room_jid, nick): """Called when the user is in the requested room""" if room.locked: # FIXME: the current behaviour is to create an instant room @@ -298,11 +298,11 @@ # a proper configuration management should be done log.debug(_("room locked !")) d = client._muc_client.configure(room.roomJID, {}) - d.addErrback(self.host.logErrback, + d.addErrback(self.host.log_errback, msg=_('Error while configuring the room: {failure_}')) return room.fully_joined - def _joinEb(self, failure_, client, room_jid, nick, password): + def _join_eb(self, failure_, client, room_jid, nick, password): """Called when something is going wrong when joining the room""" try: condition = failure_.value.condition @@ -312,14 +312,14 @@ if condition == 'conflict': # we have a nickname conflict, we try again with "_" suffixed to current nickname nick += '_' - return client._muc_client.join(room_jid, nick, password).addCallbacks(self._joinCb, self._joinEb, (client, room_jid, nick), errbackArgs=(client, room_jid, nick, password)) + return client._muc_client.join(room_jid, nick, password).addCallbacks(self._join_cb, self._join_eb, (client, room_jid, nick), errbackArgs=(client, room_jid, nick, password)) elif condition == 'not-allowed': # room is restricted, we need a password password_ui = xml_tools.XMLUI("form", title=D_('Room {} is restricted').format(room_jid.userhost()), submit_id='') password_ui.addText(D_("This room is restricted, please enter the password")) password_ui.addPassword('password') - d = xml_tools.deferXMLUI(self.host, password_ui, profile=client.profile) - d.addCallback(self._passwordUICb, client, room_jid, nick) + d = xml_tools.defer_xmlui(self.host, password_ui, profile=client.profile) + d.addCallback(self._password_ui_cb, client, room_jid, nick) return d msg_suffix = ' with condition "{}"'.format(failure_.value.condition) @@ -328,34 +328,34 @@ room = room_jid.userhost(), suffix = msg_suffix)) log.warning(mess) xmlui = xml_tools.note(mess, D_("Group chat error"), level=C.XMLUI_DATA_LVL_ERROR) - self.host.actionNew({'xmlui': xmlui.toXml()}, profile=client.profile) + self.host.action_new({'xmlui': xmlui.toXml()}, profile=client.profile) @staticmethod - def _getOccupants(room): + def _get_occupants(room): """Get occupants of a room in a form suitable for bridge""" return {u.nick: {k:str(getattr(u,k) or '') for k in OCCUPANT_KEYS} for u in list(room.roster.values())} - def _getRoomOccupants(self, room_jid_s, profile_key): - client = self.host.getClient(profile_key) + def _get_room_occupants(self, room_jid_s, profile_key): + client = self.host.get_client(profile_key) room_jid = jid.JID(room_jid_s) - return self.getRoomOccupants(client, room_jid) + return self.get_room_occupants(client, room_jid) - def getRoomOccupants(self, client, room_jid): - room = self.getRoom(client, room_jid) - return self._getOccupants(room) + def get_room_occupants(self, client, room_jid): + room = self.get_room(client, room_jid) + return self._get_occupants(room) - def _getRoomsJoined(self, profile_key=C.PROF_KEY_NONE): - client = self.host.getClient(profile_key) - return self.getRoomsJoined(client) + def _get_rooms_joined(self, profile_key=C.PROF_KEY_NONE): + client = self.host.get_client(profile_key) + return self.get_rooms_joined(client) - def getRoomsJoined(self, client): + def get_rooms_joined(self, client): """Return rooms where user is""" result = [] for room in list(client._muc_client.joined_rooms.values()): if room.state == ROOM_STATE_LIVE: result.append( (room.roomJID.userhost(), - self._getOccupants(room), + self._get_occupants(room), room.nick, room.subject, [s.name for s in room.statuses], @@ -363,11 +363,11 @@ ) return result - def _getRoomNick(self, room_jid_s, profile_key=C.PROF_KEY_NONE): - client = self.host.getClient(profile_key) - return self.getRoomNick(client, jid.JID(room_jid_s)) + def _get_room_nick(self, room_jid_s, profile_key=C.PROF_KEY_NONE): + client = self.host.get_client(profile_key) + return self.get_room_nick(client, jid.JID(room_jid_s)) - def getRoomNick(self, client, room_jid): + def get_room_nick(self, client, room_jid): """return nick used in room by user @param room_jid (jid.JID): JID of the room @@ -375,70 +375,70 @@ @return: nick or empty string in case of error @raise exceptions.Notfound: use has not joined the room """ - self.checkRoomJoined(client, room_jid) + self.check_room_joined(client, room_jid) return client._muc_client.joined_rooms[room_jid].nick - def _configureRoom(self, room_jid_s, profile_key=C.PROF_KEY_NONE): - client = self.host.getClient(profile_key) - d = self.configureRoom(client, jid.JID(room_jid_s)) + def _configure_room(self, room_jid_s, profile_key=C.PROF_KEY_NONE): + client = self.host.get_client(profile_key) + d = self.configure_room(client, jid.JID(room_jid_s)) d.addCallback(lambda xmlui: xmlui.toXml()) return d - def _configureRoomMenu(self, menu_data, profile): + def _configure_room_menu(self, menu_data, profile): """Return room configuration form @param menu_data: %(menu_data)s @param profile: %(doc_profile)s """ - client = self.host.getClient(profile) + client = self.host.get_client(profile) try: room_jid = jid.JID(menu_data['room_jid']) except KeyError: log.error(_("room_jid key is not present !")) return defer.fail(exceptions.DataError) - def xmluiReceived(xmlui): + def xmlui_received(xmlui): if not xmlui: msg = D_("No configuration available for this room") return {"xmlui": xml_tools.note(msg).toXml()} return {"xmlui": xmlui.toXml()} - return self.configureRoom(client, room_jid).addCallback(xmluiReceived) + return self.configure_room(client, room_jid).addCallback(xmlui_received) - def configureRoom(self, client, room_jid): + def configure_room(self, client, room_jid): """return the room configuration form @param room: jid of the room to configure @return: configuration form as XMLUI """ - self.checkRoomJoined(client, room_jid) + self.check_room_joined(client, room_jid) - def config2XMLUI(result): + def config_2_xmlui(result): if not result: return "" - session_id, session_data = self._sessions.newSession(profile=client.profile) + session_id, session_data = self._sessions.new_session(profile=client.profile) session_data["room_jid"] = room_jid - xmlui = xml_tools.dataForm2XMLUI(result, submit_id=self.__submit_conf_id) + xmlui = xml_tools.data_form_2_xmlui(result, submit_id=self.__submit_conf_id) xmlui.session_id = session_id return xmlui d = client._muc_client.getConfiguration(room_jid) - d.addCallback(config2XMLUI) + d.addCallback(config_2_xmlui) return d - def _submitConfiguration(self, raw_data, profile): + def _submit_configuration(self, raw_data, profile): cancelled = C.bool(raw_data.get("cancelled", C.BOOL_FALSE)) if cancelled: return defer.succeed({}) - client = self.host.getClient(profile) + client = self.host.get_client(profile) try: - session_data = self._sessions.profileGet(raw_data["session_id"], profile) + session_data = self._sessions.profile_get(raw_data["session_id"], profile) except KeyError: log.warning(D_("Session ID doesn't exist, session has probably expired.")) _dialog = xml_tools.XMLUI('popup', title=D_('Room configuration failed')) _dialog.addText(D_("Session ID doesn't exist, session has probably expired.")) return defer.succeed({'xmlui': _dialog.toXml()}) - data = xml_tools.XMLUIResult2DataFormResult(raw_data) + data = xml_tools.xmlui_result_2_data_form_result(raw_data) d = client._muc_client.configure(session_data['room_jid'], data) _dialog = xml_tools.XMLUI('popup', title=D_('Room configuration succeed')) _dialog.addText(D_("The new settings have been saved.")) @@ -446,18 +446,18 @@ del self._sessions[raw_data["session_id"]] return d - def isNickInRoom(self, client, room_jid, nick): + def is_nick_in_room(self, client, room_jid, nick): """Tell if a nick is currently present in a room""" - self.checkRoomJoined(client, room_jid) + self.check_room_joined(client, room_jid) return client._muc_client.joined_rooms[room_jid].inRoster(muc.User(nick)) - def _getMUCService(self, jid_=None, profile=C.PROF_KEY_NONE): - client = self.host.getClient(profile) - d = defer.ensureDeferred(self.get_MUC_service(client, jid_ or None)) + def _get_muc_service(self, jid_=None, profile=C.PROF_KEY_NONE): + client = self.host.get_client(profile) + d = defer.ensureDeferred(self.get_muc_service(client, jid_ or None)) d.addCallback(lambda service_jid: service_jid.full() if service_jid is not None else '') return d - async def get_MUC_service( + async def get_muc_service( self, client: SatXMPPEntity, jid_: Optional[jid.JID] = None) -> Optional[jid.JID]: @@ -474,7 +474,7 @@ else: # we have a cached value, we return it return muc_service - services = await self.host.findServiceEntities(client, "conference", "text", jid_) + services = await self.host.find_service_entities(client, "conference", "text", jid_) for service in services: if ".irc." not in service.userhost(): # FIXME: @@ -486,11 +486,11 @@ muc_service = None return muc_service - def _getUniqueName(self, muc_service="", profile_key=C.PROF_KEY_NONE): - client = self.host.getClient(profile_key) - return self.getUniqueName(client, muc_service or None).full() + def _get_unique_name(self, muc_service="", profile_key=C.PROF_KEY_NONE): + client = self.host.get_client(profile_key) + return self.get_unique_name(client, muc_service or None).full() - def getUniqueName(self, client, muc_service=None): + def get_unique_name(self, client, muc_service=None): """Return unique name for a room, avoiding collision @param muc_service (jid.JID) : leave empty string to use the default service @@ -510,24 +510,24 @@ muc_service = muc_service.userhost() return jid.JID("{}@{}".format(room_name, muc_service)) - def getDefaultMUC(self): + def get_default_muc(self): """Return the default MUC. @return: unicode """ - return self.host.memory.getConfig(CONFIG_SECTION, 'default_muc', default_conf['default_muc']) + return self.host.memory.config_get(CONFIG_SECTION, 'default_muc', default_conf['default_muc']) def _join_eb(self, failure_, client): failure_.trap(AlreadyJoined) room = failure_.value.room - return [True] + self._getRoomJoinedArgs(room, client.profile) + return [True] + self._get_room_joined_args(room, client.profile) def _join(self, room_jid_s, nick, options, profile_key=C.PROF_KEY_NONE): """join method used by bridge - @return (tuple): already_joined boolean + room joined arguments (see [_getRoomJoinedArgs]) + @return (tuple): already_joined boolean + room joined arguments (see [_get_room_joined_args]) """ - client = self.host.getClient(profile_key) + client = self.host.get_client(profile_key) if room_jid_s: muc_service = client.muc_service try: @@ -539,10 +539,10 @@ if not room_jid.user: room_jid.user, room_jid.host = room_jid.host, muc_service else: - room_jid = self.getUniqueName(profile_key=client.profile) + room_jid = self.get_unique_name(profile_key=client.profile) # TODO: error management + signal in bridge d = self.join(client, room_jid, nick, options or None) - d.addCallback(lambda room: [False] + self._getRoomJoinedArgs(room, client.profile)) + d.addCallback(lambda room: [False] + self._get_room_joined_args(room, client.profile)) d.addErrback(self._join_eb, client) return d @@ -564,23 +564,23 @@ raise AlreadyJoined(room) log.info(_("[{profile}] is joining room {room} with nick {nick}").format( profile=client.profile, room=room_jid.userhost(), nick=nick)) - self.host.bridge.mucRoomPrepareJoin(room_jid.userhost(), client.profile) + self.host.bridge.muc_room_prepare_join(room_jid.userhost(), client.profile) password = options.get("password") try: room = await client._muc_client.join(room_jid, nick, password) except Exception as e: - room = await utils.asDeferred( - self._joinEb(failure.Failure(e), client, room_jid, nick, password) + room = await utils.as_deferred( + self._join_eb(failure.Failure(e), client, room_jid, nick, password) ) else: await defer.ensureDeferred( - self._joinCb(room, client, room_jid, nick) + self._join_cb(room, client, room_jid, nick) ) return room - def popRooms(self, client): + def pop_rooms(self, client): """Remove rooms and return data needed to re-join them This methods is to be called before a hot reconnection @@ -594,31 +594,31 @@ return args_list def _nick(self, room_jid_s, nick, profile_key=C.PROF_KEY_NONE): - client = self.host.getClient(profile_key) + client = self.host.get_client(profile_key) return self.nick(client, jid.JID(room_jid_s), nick) def nick(self, client, room_jid, nick): """Change nickname in a room""" - self.checkRoomJoined(client, room_jid) + self.check_room_joined(client, room_jid) return client._muc_client.nick(room_jid, nick) def _leave(self, room_jid, profile_key): - client = self.host.getClient(profile_key) + client = self.host.get_client(profile_key) return self.leave(client, jid.JID(room_jid)) def leave(self, client, room_jid): - self.checkRoomJoined(client, room_jid) + self.check_room_joined(client, room_jid) return client._muc_client.leave(room_jid) def _subject(self, room_jid_s, new_subject, profile_key): - client = self.host.getClient(profile_key) + client = self.host.get_client(profile_key) return self.subject(client, jid.JID(room_jid_s), new_subject) def subject(self, client, room_jid, subject): - self.checkRoomJoined(client, room_jid) + self.check_room_joined(client, room_jid) return client._muc_client.subject(room_jid, subject) - def getHandler(self, client): + def get_handler(self, client): # create a MUC client and associate it with profile' session muc_client = client._muc_client = LiberviaMUCClient(self) return muc_client @@ -632,7 +632,7 @@ """ if options is None: options = {} - self.checkRoomJoined(client, room_jid) + self.check_room_joined(client, room_jid) return client._muc_client.kick(room_jid, nick, reason=options.get('reason', None)) def ban(self, client, entity_jid, room_jid, options=None): @@ -642,7 +642,7 @@ @param room_jid (JID): jid of the room @param options: attribute with extra info (reason, password) as in #XEP-0045 """ - self.checkRoomJoined(client, room_jid) + self.check_room_joined(client, room_jid) if options is None: options = {} assert not entity_jid.resource @@ -656,7 +656,7 @@ @param room_jid_s (JID): jid of the room @param options: attribute with extra info (reason, nick) as in #XEP-0045 """ - self.checkRoomJoined(client, room_jid) + self.check_room_joined(client, room_jid) assert not entity_jid.resource assert not room_jid.resource assert 'affiliation' in options @@ -686,17 +686,17 @@ """ room_raw = mess_data["unparsed"].strip() if room_raw: - if self.isJoinedRoom(client, mess_data["to"]): + if self.is_joined_room(client, mess_data["to"]): # we use the same service as the one from the room where the command has # been entered if full jid is not entered muc_service = mess_data["to"].host - nick = self.getRoomNick(client, mess_data["to"]) or client.jid.user + nick = self.get_room_nick(client, mess_data["to"]) or client.jid.user else: # the command has been entered in a one2one conversation, so we use # our server MUC service as default service muc_service = client.muc_service or "" nick = client.jid.user - room_jid = self.text_cmds.getRoomJID(room_raw, muc_service) + room_jid = self.text_cmds.get_room_jid(room_raw, muc_service) self.join(client, room_jid, nick, {}) return False @@ -709,7 +709,7 @@ """ room_raw = mess_data["unparsed"].strip() if room_raw: - room = self.text_cmds.getRoomJID(room_raw, mess_data["to"].host) + room = self.text_cmds.get_room_jid(room_raw, mess_data["to"].host) else: room = mess_data["to"] @@ -734,10 +734,10 @@ options = mess_data["unparsed"].strip().split() try: nick = options[0] - assert self.isNickInRoom(client, mess_data["to"], nick) + assert self.is_nick_in_room(client, mess_data["to"], nick) except (IndexError, AssertionError): feedback = _("You must provide a member's nick to kick.") - self.text_cmds.feedBack(client, feedback, mess_data) + self.text_cmds.feed_back(client, feedback, mess_data) return False reason = ' '.join(options[1:]) if len(options) > 1 else None @@ -750,7 +750,7 @@ feedback_msg += _(' for the following reason: {reason}').format( reason=reason ) - self.text_cmds.feedBack(client, feedback_msg, mess_data) + self.text_cmds.feed_back(client, feedback_msg, mess_data) return True d.addCallback(cb) return d @@ -773,7 +773,7 @@ feedback = _( "You must provide a valid JID to ban, like in '/ban contact@example.net'" ) - self.text_cmds.feedBack(client, feedback, mess_data) + self.text_cmds.feed_back(client, feedback, mess_data) return False reason = ' '.join(options[1:]) if len(options) > 1 else None @@ -786,7 +786,7 @@ feedback_msg += _(' for the following reason: {reason}').format( reason=reason ) - self.text_cmds.feedBack(client, feedback_msg, mess_data) + self.text_cmds.feed_back(client, feedback_msg, mess_data) return True d.addCallback(cb) return d @@ -810,13 +810,13 @@ assert(entity_jid.host) except (RuntimeError, jid.InvalidFormat, AttributeError, IndexError, AssertionError): feedback = _("You must provide a valid JID to affiliate, like in '/affiliate contact@example.net member'") - self.text_cmds.feedBack(client, feedback, mess_data) + self.text_cmds.feed_back(client, feedback, mess_data) return False affiliation = options[1] if len(options) > 1 else 'none' if affiliation not in AFFILIATIONS: feedback = _("You must provide a valid affiliation: %s") % ' '.join(AFFILIATIONS) - self.text_cmds.feedBack(client, feedback, mess_data) + self.text_cmds.feed_back(client, feedback, mess_data) return False d = self.affiliate(client, entity_jid, mess_data["to"], {'affiliation': affiliation}) @@ -824,7 +824,7 @@ def cb(__): feedback_msg = _('New affiliation for {entity}: {affiliation}').format( entity=entity_jid, affiliation=affiliation) - self.text_cmds.feedBack(client, feedback_msg, mess_data) + self.text_cmds.feed_back(client, feedback_msg, mess_data) return True d.addCallback(cb) return d @@ -871,14 +871,14 @@ else: msg = D_("No known default MUC service {unparsed}").format( unparsed=unparsed) - self.text_cmds.feedBack(client, msg, mess_data) + self.text_cmds.feed_back(client, msg, mess_data) return False except jid.InvalidFormat: msg = D_("{} is not a valid JID!".format(unparsed)) - self.text_cmds.feedBack(client, msg, mess_data) + self.text_cmds.feed_back(client, msg, mess_data) return False d = self.host.getDiscoItems(client, service) - d.addCallback(self._showListUI, client, service) + d.addCallback(self._show_list_ui, client, service) return False @@ -904,17 +904,17 @@ if user.show: whois_msg.append(_("Show: %s") % user.show) - def presenceTrigger(self, presence_elt, client): + def presence_trigger(self, presence_elt, client): # FIXME: should we add a privacy parameters in settings to activate before # broadcasting the presence to all MUC rooms ? muc_client = client._muc_client for room_jid, room in muc_client.joined_rooms.items(): - elt = xml_tools.elementCopy(presence_elt) + elt = xml_tools.element_copy(presence_elt) elt['to'] = room_jid.userhost() + '/' + room.nick client.presence.send(elt) return True - def presenceReceivedTrigger(self, client, entity, show, priority, statuses): + def presence_received_trigger(self, client, entity, show, priority, statuses): entity_bare = entity.userhostJID() muc_client = client._muc_client if entity_bare in muc_client.joined_rooms: @@ -953,7 +953,7 @@ def _si(self): return self.plugin_parent._si - def changeRoomState(self, room, new_state): + def change_room_state(self, room, new_state): """Check that room is in expected state, and change it @param new_state: one of ROOM_STATE_* @@ -995,7 +995,7 @@ password: Optional[str] ) -> muc.Room: """Join room an retrieve history with legacy method""" - mess_data_list = await self.host.memory.historyGet( + mess_data_list = await self.host.memory.history_get( room_jid, client.jid.userhostJID(), limit=1, @@ -1018,7 +1018,7 @@ room._history_d.callback(None) return room - async def _get_MAM_history( + async def _get_mam_history( self, client: SatXMPPEntity, room: muc.Room, @@ -1030,7 +1030,7 @@ # and in order history_d.callback(None) - last_mess = await self.host.memory.historyGet( + last_mess = await self.host.memory.history_get( room_jid, None, limit=1, @@ -1056,7 +1056,7 @@ count = 0 while not complete: try: - mam_data = await self._mam.getArchives(client, mam_req, + mam_data = await self._mam.get_archives(client, mam_req, service=room_jid) except xmpp_error.StanzaError as e: if last_mess and e.condition == 'item-not-found': @@ -1083,7 +1083,7 @@ for mess_elt in elt_list: try: - fwd_message_elt = self._mam.getMessageFromResult( + fwd_message_elt = self._mam.get_message_from_result( client, mess_elt, mam_req, service=room_jid) except exceptions.DataError: continue @@ -1093,7 +1093,7 @@ 'forbidden by specifications') fwd_message_elt["to"] = client.jid.full() try: - mess_data = client.messageProt.parseMessage(fwd_message_elt) + mess_data = client.messageProt.parse_message(fwd_message_elt) except Exception as e: log.error( f"Can't parse message, ignoring it: {e}\n" @@ -1101,7 +1101,7 @@ ) continue # we attache parsed message data to element, to avoid parsing - # again in _addToHistory + # again in _add_to_history fwd_message_elt._mess_data = mess_data # and we inject to MUC workflow client._muc_client._onGroupChat(fwd_message_elt) @@ -1118,14 +1118,14 @@ # for legacy history, the following steps are done in receivedSubject but for MAM # the order is different (we have to join then get MAM archive, so subject # is received before archive), so we change state and add the callbacks here. - self.changeRoomState(room, ROOM_STATE_LIVE) - history_d.addCallbacks(self._historyCb, self._historyEb, [room], + self.change_room_state(room, ROOM_STATE_LIVE) + history_d.addCallbacks(self._history_cb, self._history_eb, [room], errbackArgs=[room]) # we wait for all callbacks to be processed await history_d - async def _join_MAM( + async def _join_mam( self, client: SatXMPPEntity, room_jid: jid.JID, @@ -1140,7 +1140,7 @@ room._history_type = HISTORY_MAM # MAM history retrieval can be very long, and doesn't need to be sync, so we don't # wait for it - defer.ensureDeferred(self._get_MAM_history(client, room, room_jid)) + defer.ensureDeferred(self._get_mam_history(client, room, room_jid)) room.fully_joined.callback(room) return room @@ -1151,7 +1151,7 @@ if not self._mam or not has_mam: return await self._join_legacy(self.client, room_jid, nick, password) else: - return await self._join_MAM(self.client, room_jid, nick, password) + return await self._join_mam(self.client, room_jid, nick, password) ## presence/roster ## @@ -1213,7 +1213,7 @@ if muc.STATUS_CODE.NEW_NICK in presence.mucStatuses: self._changing_nicks.add(presence.nick) - self.userChangedNick(room, user, presence.nick) + self.user_changed_nick(room, user, presence.nick) else: self._changing_nicks.discard(presence.nick) self.userLeftRoom(room, user) @@ -1222,12 +1222,12 @@ if user.nick == room.nick: # we have received our own nick, # this mean that the full room roster was received - self.changeRoomState(room, ROOM_STATE_SELF_PRESENCE) + self.change_room_state(room, ROOM_STATE_SELF_PRESENCE) log.debug("room {room} joined with nick {nick}".format( room=room.occupantJID.userhost(), nick=user.nick)) # we set type so we don't have to use a deferred # with disco to check entity type - self.host.memory.updateEntityData( + self.host.memory.update_entity_data( self.client, room.roomJID, C.ENTITY_TYPE, C.ENTITY_TYPE_MUC ) elif room.state not in (ROOM_STATE_OCCUPANTS, ROOM_STATE_LIVE): @@ -1272,8 +1272,8 @@ # FIXME: we disable presence in history as it's taking a lot of space # while not indispensable. In the future an option may allow # to re-enable it - # self.client.messageAddToHistory(mess_data) - self.client.messageSendToBridge(mess_data) + # self.client.message_add_to_history(mess_data) + self.client.message_send_to_bridge(mess_data) def userLeftRoom(self, room, user): @@ -1284,8 +1284,8 @@ room_jid_s = room.roomJID.userhost() log.info(_("Room ({room}) left ({profile})").format( room = room_jid_s, profile = self.client.profile)) - self.host.memory.delEntityCache(room.roomJID, profile_key=self.client.profile) - self.host.bridge.mucRoomLeft(room.roomJID.userhost(), self.client.profile) + self.host.memory.del_entity_cache(room.roomJID, profile_key=self.client.profile) + self.host.bridge.muc_room_left(room.roomJID.userhost(), self.client.profile) elif room.state != ROOM_STATE_LIVE: log.warning("Received user presence data in a room before its initialisation (current state: {state})," "this is not standard! Ignoring it: {room} ({nick})".format( @@ -1315,11 +1315,11 @@ "timestamp": time.time(), } # FIXME: disable history, see userJoinRoom comment - # self.client.messageAddToHistory(mess_data) - self.client.messageSendToBridge(mess_data) + # self.client.message_add_to_history(mess_data) + self.client.message_send_to_bridge(mess_data) - def userChangedNick(self, room, user, new_nick): - self.host.bridge.mucRoomUserChangedNick(room.roomJID.userhost(), user.nick, new_nick, self.client.profile) + def user_changed_nick(self, room, user, new_nick): + self.host.bridge.muc_room_user_changed_nick(room.roomJID.userhost(), user.nick, new_nick, self.client.profile) def userUpdatedStatus(self, room, user, show, status): entity = jid.JID(tuple=(room.roomJID.user, room.roomJID.host, user.nick)) @@ -1337,7 +1337,7 @@ } return statuses = {C.PRESENCE_STATUSES_DEFAULT: status or ''} - self.host.bridge.presenceUpdate( + self.host.bridge.presence_update( entity.full(), show or '', 0, statuses, self.client.profile) ## messages ## @@ -1345,21 +1345,21 @@ def receivedGroupChat(self, room, user, body): log.debug('receivedGroupChat: room=%s user=%s body=%s' % (room.roomJID.full(), user, body)) - def _addToHistory(self, __, user, message): + def _add_to_history(self, __, user, message): try: # message can be already parsed (with MAM), in this case mess_data # it attached to the element mess_data = message.element._mess_data except AttributeError: - mess_data = self.client.messageProt.parseMessage(message.element) + mess_data = self.client.messageProt.parse_message(message.element) if mess_data['message'] or mess_data['subject']: return defer.ensureDeferred( - self.host.memory.addToHistory(self.client, mess_data) + self.host.memory.add_to_history(self.client, mess_data) ) else: return defer.succeed(None) - def _addToHistoryEb(self, failure): + def _add_to_history_eb(self, failure): failure.trap(exceptions.CancelError) def receivedHistory(self, room, user, message): @@ -1386,17 +1386,17 @@ for c in message.element.elements(): if c.uri is None: c.uri = C.NS_CLIENT - mess_data = self.client.messageProt.parseMessage(message.element) + mess_data = self.client.messageProt.parse_message(message.element) message.element._mess_data = mess_data - self._addToHistory(None, user, message) + self._add_to_history(None, user, message) if mess_data['message'] or mess_data['subject']: - self.host.bridge.messageNew( - *self.client.messageGetBridgeArgs(mess_data), + self.host.bridge.message_new( + *self.client.message_get_bridge_args(mess_data), profile=self.client.profile ) return - room._history_d.addCallback(self._addToHistory, user, message) - room._history_d.addErrback(self._addToHistoryEb) + room._history_d.addCallback(self._add_to_history, user, message) + room._history_d.addErrback(self._add_to_history_eb) ## subject ## @@ -1426,7 +1426,7 @@ def subject(self, room, subject): return muc.MUCClientProtocol.subject(self, room, subject) - def _historyCb(self, __, room): + def _history_cb(self, __, room): """Called when history have been written to database and subject is received this method will finish joining by: @@ -1435,8 +1435,8 @@ - sending stanza put in cache - cleaning variables not needed anymore """ - args = self.plugin_parent._getRoomJoinedArgs(room, self.client.profile) - self.host.bridge.mucRoomJoined(*args) + args = self.plugin_parent._get_room_joined_args(room, self.client.profile) + self.host.bridge.muc_room_joined(*args) if room._history_type == HISTORY_LEGACY: room.fully_joined.callback(room) del room._history_d @@ -1449,15 +1449,15 @@ self.client.xmlstream.dispatch(elem) for presence_data in cache_presence.values(): if not presence_data['show'] and not presence_data['status']: - # occupants are already sent in mucRoomJoined, so if we don't have + # occupants are already sent in muc_room_joined, so if we don't have # extra information like show or statuses, we can discard the signal continue else: self.userUpdatedStatus(**presence_data) - def _historyEb(self, failure_, room): + def _history_eb(self, failure_, room): log.error("Error while managing history: {}".format(failure_)) - self._historyCb(None, room) + self._history_cb(None, room) def receivedSubject(self, room, user, subject): # when subject is received, we know that we have whole roster and history @@ -1465,12 +1465,12 @@ room.subject = subject # FIXME: subject doesn't handle xml:lang if room.state != ROOM_STATE_LIVE: if room._history_type == HISTORY_LEGACY: - self.changeRoomState(room, ROOM_STATE_LIVE) - room._history_d.addCallbacks(self._historyCb, self._historyEb, [room], errbackArgs=[room]) + self.change_room_state(room, ROOM_STATE_LIVE) + room._history_d.addCallbacks(self._history_cb, self._history_eb, [room], errbackArgs=[room]) else: # the subject has been changed log.debug(_("New subject for room ({room_id}): {subject}").format(room_id = room.roomJID.full(), subject = subject)) - self.host.bridge.mucRoomNewSubject(room.roomJID.userhost(), subject, self.client.profile) + self.host.bridge.muc_room_new_subject(room.roomJID.userhost(), subject, self.client.profile) ## disco ##