diff sat_frontends/quick_frontend/quick_chat.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 78b5f356900c
children 4b842c1fb686
line wrap: on
line diff
--- a/sat_frontends/quick_frontend/quick_chat.py	Fri Apr 07 15:18:39 2023 +0200
+++ b/sat_frontends/quick_frontend/quick_chat.py	Sat Apr 08 13:54:42 2023 +0200
@@ -55,7 +55,7 @@
         self.subject = subject
         self.type = type_
         self.extra = extra
-        self.nick = self.getNick(from_jid)
+        self.nick = self.get_nick(from_jid)
         self._status = None
         # own_mess is True if message was sent by profile's jid
         self.own_mess = (
@@ -69,7 +69,7 @@
                 if self.parent.nick.lower() in m.lower():
                     self._mention = True
                     break
-        self.handleMe()
+        self.handle_me()
         self.widgets = set()  # widgets linked to this message
 
     def __str__(self):
@@ -147,14 +147,14 @@
             return contact_list.getCache(entity, "avatar")
         except (exceptions.NotFound, KeyError):
             # we don't check the result as the avatar listener will be called
-            self.host.bridge.avatarGet(entity, True, self.profile)
+            self.host.bridge.avatar_get(entity, True, self.profile)
             return None
 
     @property
     def encrypted(self):
         return self.extra.get("encrypted", False)
 
-    def getNick(self, entity):
+    def get_nick(self, entity):
         """Return nick of an entity when possible"""
         contact_list = self.host.contact_lists[self.profile]
         if self.type == C.MESS_TYPE_INFO and self.info_type in ROOM_USER_MOVED:
@@ -163,9 +163,9 @@
             except KeyError:
                 log.error("extra data is missing user nick for uid {}".format(self.uid))
                 return ""
-        # FIXME: converted getSpecials to list for pyjamas
+        # FIXME: converted get_specials to list for pyjamas
         if self.parent.type == C.CHAT_GROUP or entity in list(
-            contact_list.getSpecials(C.CONTACT_SPECIAL_GROUP)
+            contact_list.get_specials(C.CONTACT_SPECIAL_GROUP)
         ):
             return entity.resource or ""
         if entity.bare in contact_list:
@@ -174,7 +174,7 @@
                 nicknames = contact_list.getCache(entity, "nicknames")
             except (exceptions.NotFound, KeyError):
                 # we check result as listener will be called
-                self.host.bridge.identityGet(
+                self.host.bridge.identity_get(
                     entity.bare, ["nicknames"], True, self.profile)
                 return entity.node or entity
 
@@ -200,7 +200,7 @@
             for w in self.widgets:
                 w.update({"status": status})
 
-    def handleMe(self):
+    def handle_me(self):
         """Check if messages starts with "/me " and change them if it is the case
 
         if several messages (different languages) are presents, they all need to start with "/me "
@@ -306,7 +306,7 @@
         # True when resync is in progress, avoid resynchronising twice when resync is called
         # and history is still being updated. For internal use only
         self._resync_lock = False
-        self.setLocked()
+        self.set_locked()
         if type_ == C.CHAT_GROUP:
             if target.resource:
                 raise exceptions.InternalError(
@@ -317,7 +317,7 @@
 
             self.nick = nick
             self.occupants = {}
-            self.setOccupants(occupants)
+            self.set_occupants(occupants)
         else:
             if occupants is not None or nick is not None:
                 raise exceptions.InternalError(
@@ -340,9 +340,9 @@
             lt.tm_isdst,
         )  # struct_time of day changing time
         if self.host.AVATARS_HANDLER:
-            self.host.addListener("avatar", self.onAvatar, profiles)
+            self.host.addListener("avatar", self.on_avatar, profiles)
 
-    def setLocked(self):
+    def set_locked(self):
         """Set locked flag
 
         To be set when we are waiting for history/search
@@ -353,37 +353,37 @@
             log.warning("{wid} is already locked!".format(wid=self))
             return
         self._locked = True
-        # messageNew signals are cached when locked
+        # message_new signals are cached when locked
         self._cache = OrderedDict()
         log.debug("{wid} is now locked".format(wid=self))
 
-    def setUnlocked(self):
+    def set_unlocked(self):
         if not self._locked:
             log.debug("{wid} was already unlocked".format(wid=self))
             return
         self._locked = False
         for uid, data in self._cache.items():
             if uid not in self.messages:
-                self.messageNew(*data)
+                self.message_new(*data)
             else:
                 log.debug("discarding message already in history: {data}, ".format(data=data))
         del self._cache
         log.debug("{wid} is now unlocked".format(wid=self))
 
-    def postInit(self):
+    def post_init(self):
         """Method to be called by frontend after widget is initialised
 
         handle the display of history and subject
         """
-        self.historyPrint(profile=self.profile)
+        self.history_print(profile=self.profile)
         if self.subject is not None:
-            self.setSubject(self.subject)
+            self.set_subject(self.subject)
         if self.host.ENCRYPTION_HANDLERS:
-            self.getEncryptionState()
+            self.get_encryption_state()
 
-    def onDelete(self):
+    def on_delete(self):
         if self.host.AVATARS_HANDLER:
-            self.host.removeListener("avatar", self.onAvatar)
+            self.host.removeListener("avatar", self.on_avatar)
 
     @property
     def contact_list(self):
@@ -403,13 +403,13 @@
     def sync(self, state):
         quick_widgets.QuickWidget.sync.fset(self, state)
         if not state:
-            self.setLocked()
+            self.set_locked()
 
-    def _resyncComplete(self):
+    def _resync_complete(self):
         self.sync = True
         self._resync_lock = False
 
-    def occupantsClear(self):
+    def occupants_clear(self):
         """Remove all occupants
 
         Must be overridden by frontends to clear their own representations of occupants
@@ -428,17 +428,17 @@
             break
         else:
             # we have no message yet, we can get normal history
-            self.historyPrint(callback=self._resyncComplete, profile=self.profile)
+            self.history_print(callback=self._resync_complete, profile=self.profile)
             return
         if self.type == C.CHAT_GROUP:
-            self.occupantsClear()
-            self.host.bridge.mucOccupantsGet(
-                str(self.target), self.profile, callback=self.updateOccupants,
+            self.occupants_clear()
+            self.host.bridge.muc_occupants_get(
+                str(self.target), self.profile, callback=self.update_occupants,
                 errback=log.error)
-        self.historyPrint(
+        self.history_print(
             size=C.HISTORY_LIMIT_NONE,
             filters={'timestamp_start': last_message.timestamp},
-            callback=self._resyncComplete,
+            callback=self._resync_complete,
             profile=self.profile)
 
     ## Widget management ##
@@ -449,26 +449,26 @@
         )
 
     @staticmethod
-    def getWidgetHash(target, profiles):
+    def get_widget_hash(target, profiles):
         profile = list(profiles)[0]
         return profile + "\n" + str(target.bare)
 
     @staticmethod
-    def getPrivateHash(target, profile):
+    def get_private_hash(target, profile):
         """Get unique hash for private conversations
 
         This method should be used with force_hash to get unique widget for private MUC conversations
         """
         return (str(profile), target)
 
-    def addTarget(self, target):
-        super(QuickChat, self).addTarget(target)
+    def add_target(self, target):
+        super(QuickChat, self).add_target(target)
         if target.resource:
             self.current_target = (
                 target
             )  # FIXME: tmp, must use resource priority throught contactList instead
 
-    def recreateArgs(self, args, kwargs):
+    def recreate_args(self, args, kwargs):
         """copy important attribute for a new widget"""
         kwargs["type_"] = self.type
         if self.type == C.CHAT_GROUP:
@@ -479,21 +479,21 @@
         except AttributeError:
             pass
 
-    def onPrivateCreated(self, widget):
+    def on_private_created(self, widget):
         """Method called when a new widget for private conversation (MUC) is created"""
         raise NotImplementedError
 
-    def getOrCreatePrivateWidget(self, entity):
+    def get_or_create_private_widget(self, entity):
         """Create a widget for private conversation, or get it if it already exists
 
         @param entity: full jid of the target
         """
-        return self.host.widgets.getOrCreateWidget(
+        return self.host.widgets.get_or_create_widget(
             QuickChat,
             entity,
             type_=C.CHAT_ONE2ONE,
-            force_hash=self.getPrivateHash(self.profile, entity),
-            on_new_widget=self.onPrivateCreated,
+            force_hash=self.get_private_hash(self.profile, entity),
+            on_new_widget=self.on_private_created,
             profile=self.profile,
         )  # we force hash to have a new widget, not this one again
 
@@ -505,7 +505,7 @@
 
     ## occupants ##
 
-    def setOccupants(self, occupants):
+    def set_occupants(self, occupants):
         """Set the whole list of occupants"""
         assert len(self.occupants) == 0
         for nick, data in occupants.items():
@@ -515,10 +515,10 @@
             #     nick=nick, room=self.target))
             self.occupants[nick] = Occupant(self, data, self.profile)
 
-    def updateOccupants(self, occupants):
+    def update_occupants(self, occupants):
         """Update occupants list
 
-        In opposition to setOccupants, this only add missing occupants and remove
+        In opposition to set_occupants, this only add missing occupants and remove
         occupants who have left
         """
         # FIXME: occupants with modified status are not handled
@@ -553,11 +553,11 @@
         else:
             return occupant
 
-    def setUserNick(self, nick):
+    def set_user_nick(self, nick):
         """Set the nick of the user, usefull for e.g. change the color of the user"""
         self.nick = nick
 
-    def changeUserNick(self, old_nick, new_nick):
+    def change_user_nick(self, old_nick, new_nick):
         """Change nick of a user in group list"""
         log.info("{old} is now known as {new} in room {room_jid}".format(
             old = old_nick,
@@ -566,11 +566,11 @@
 
     ## Messages ##
 
-    def manageMessage(self, entity, mess_type):
+    def manage_message(self, entity, mess_type):
         """Tell if this chat widget manage an entity and message type couple
 
         @param entity (jid.JID): (full) jid of the sending entity
-        @param mess_type (str): message type as given by messageNew
+        @param mess_type (str): message type as given by message_new
         @return (bool): True if this Chat Widget manage this couple
         """
         if self.type == C.CHAT_GROUP:
@@ -584,32 +584,32 @@
                 return True
         return False
 
-    def updateHistory(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile="@NONE@"):
+    def update_history(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile="@NONE@"):
         """Called when history need to be recreated
 
-        Remove all message from history then call historyPrint
+        Remove all message from history then call history_print
         Must probably be overriden by frontend to clear widget
         @param size (int): number of messages
         @param filters (str): patterns to filter the history results
         @param profile (str): %(doc_profile)s
         """
-        self.setLocked()
+        self.set_locked()
         self.messages.clear()
-        self.historyPrint(size, filters, profile=profile)
+        self.history_print(size, filters, profile=profile)
 
-    def _onHistoryPrinted(self):
+    def _on_history_printed(self):
         """Method called when history is printed (or failed)
 
         unlock the widget, and can be used to refresh or scroll down
         the focus after the history is printed
         """
-        self.setUnlocked()
+        self.set_unlocked()
 
-    def historyPrint(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, callback=None,
+    def history_print(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, callback=None,
                      profile="@NONE@"):
         """Print the current history
 
-        Note: self.setUnlocked will be called once history is printed
+        Note: self.set_unlocked will be called once history is printed
         @param size (int): number of messages
         @param search (str): pattern to filter the history results
         @param callback(callable, None): method to call when history has been printed
@@ -619,7 +619,7 @@
             filters = {}
         if size == 0:
             log.debug("Empty history requested, skipping")
-            self._onHistoryPrinted()
+            self._on_history_printed()
             return
         log_msg = _("now we print the history")
         if size != C.HISTORY_LIMIT_DEFAULT:
@@ -647,12 +647,12 @@
 
         self.history_filters = filters
 
-        def _historyGetCb(history):
+        def _history_get_cb(history):
             # day_format = "%A, %d %b %Y"  # to display the day change
             # previous_day = datetime.now().strftime(day_format)
             # message_day = datetime.fromtimestamp(timestamp).strftime(self.day_format)
             # if previous_day != message_day:
-            #     self.printDayChange(message_day)
+            #     self.print_day_change(message_day)
             #     previous_day = message_day
             for data in history:
                 uid, timestamp, from_jid, to_jid, message, subject, type_, extra_s = data
@@ -675,49 +675,49 @@
                     extra,
                     profile,
                 )
-            self._onHistoryPrinted()
+            self._on_history_printed()
             if callback is not None:
                 callback()
 
-        def _historyGetEb(err):
+        def _history_get_eb(err):
             log.error(_("Can't get history: {}").format(err))
-            self._onHistoryPrinted()
+            self._on_history_printed()
             if callback is not None:
                 callback()
 
-        self.host.bridge.historyGet(
+        self.host.bridge.history_get(
             str(self.host.profiles[profile].whoami.bare),
             str(target),
             size,
             True,
             {k: str(v) for k,v in filters.items()},
             profile,
-            callback=_historyGetCb,
-            errback=_historyGetEb,
+            callback=_history_get_cb,
+            errback=_history_get_eb,
         )
 
-    def messageEncryptionGetCb(self, session_data):
+    def message_encryption_get_cb(self, session_data):
         if session_data:
             session_data = data_format.deserialise(session_data)
-            self.messageEncryptionStarted(session_data)
+            self.message_encryption_started(session_data)
 
-    def messageEncryptionGetEb(self, failure_):
+    def message_encryption_get_eb(self, failure_):
         log.error(_("Can't get encryption state: {reason}").format(reason=failure_))
 
-    def getEncryptionState(self):
+    def get_encryption_state(self):
         """Retrieve encryption state with current target.
 
-        Once state is retrieved, default messageEncryptionStarted will be called if
+        Once state is retrieved, default message_encryption_started will be called if
         suitable
         """
         if self.type == C.CHAT_GROUP:
             return
-        self.host.bridge.messageEncryptionGet(str(self.target.bare), self.profile,
-                                              callback=self.messageEncryptionGetCb,
-                                              errback=self.messageEncryptionGetEb)
+        self.host.bridge.message_encryption_get(str(self.target.bare), self.profile,
+                                              callback=self.message_encryption_get_cb,
+                                              errback=self.message_encryption_get_eb)
 
 
-    def messageNew(self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra,
+    def message_new(self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra,
                    profile):
         if self._locked:
             self._cache[uid] = (
@@ -742,8 +742,8 @@
             if to_jid.resource and type_ != C.MESS_TYPE_GROUPCHAT:
                 # we have a private message, we forward it to a private conversation
                 # widget
-                chat_widget = self.getOrCreatePrivateWidget(to_jid)
-                chat_widget.messageNew(
+                chat_widget = self.get_or_create_private_widget(to_jid)
+                chat_widget.message_new(
                     uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile
                 )
                 return
@@ -768,28 +768,28 @@
 
         if "received_timestamp" in extra:
             log.warning("Delayed message received after history, this should not happen")
-        self.createMessage(message)
+        self.create_message(message)
 
-    def messageEncryptionStarted(self, session_data):
+    def message_encryption_started(self, session_data):
         self.encrypted = True
         log.debug(_("message encryption started with {target} using {encryption}").format(
             target=self.target, encryption=session_data['name']))
 
-    def messageEncryptionStopped(self, session_data):
+    def message_encryption_stopped(self, session_data):
         self.encrypted = False
         log.debug(_("message encryption stopped with {target} (was using {encryption})")
                  .format(target=self.target, encryption=session_data['name']))
 
-    def createMessage(self, message, append=False):
+    def create_message(self, message, append=False):
         """Must be implemented by frontend to create and show a new message widget
 
-        This is only called on messageNew, not on history.
-        You need to override historyPrint to handle the later
+        This is only called on message_new, not on history.
+        You need to override history_print to handle the later
         @param message(Message): message data
         """
         raise NotImplementedError
 
-    def isUserMoved(self, message):
+    def is_user_moved(self, message):
         """Return True if message is a user left/joined message
 
         @param message(Message): message to check
@@ -804,7 +804,7 @@
         else:
             return info_type in ROOM_USER_MOVED
 
-    def handleUserMoved(self, message):
+    def handle_user_moved(self, message):
         """Check if this message is a UserMoved one, and merge it when possible
 
         "merge it" means that info message indicating a user joined/left will be
@@ -813,7 +813,7 @@
         @return (bool): True if this message has been merged
             if True, a new MessageWidget must not be created and appended to history
         """
-        if self.isUserMoved(message):
+        if self.is_user_moved(message):
             for wid in self.message_widgets_rev:
                 # we merge in/out messages if no message was sent meanwhile
                 if not isinstance(wid, MessageWidget):
@@ -841,7 +841,7 @@
                     return True
         return False
 
-    def printDayChange(self, day):
+    def print_day_change(self, day):
         """Display the day on a new line.
 
         @param day(unicode): day to display (or not if this method is not overwritten)
@@ -851,7 +851,7 @@
 
     ## Room ##
 
-    def setSubject(self, subject):
+    def set_subject(self, subject):
         """Set title for a group chat"""
         if self.type != C.CHAT_GROUP:
             raise exceptions.InternalError(
@@ -859,22 +859,22 @@
             )
         self.subject = subject
 
-    def changeSubject(self, new_subject):
+    def change_subject(self, new_subject):
         """Change the subject of the room
 
         This change the subject on the room itself (i.e. via XMPP),
-        while setSubject change the subject of this widget
+        while set_subject change the subject of this widget
         """
-        self.host.bridge.mucSubject(str(self.target), new_subject, self.profile)
+        self.host.bridge.muc_subject(str(self.target), new_subject, self.profile)
 
-    def addGamePanel(self, widget):
+    def add_game_panel(self, widget):
         """Insert a game panel to this Chat dialog.
 
         @param widget (Widget): the game panel
         """
         raise NotImplementedError
 
-    def removeGamePanel(self, widget):
+    def remove_game_panel(self, widget):
         """Remove the game panel from this Chat dialog.
 
         @param widget (Widget): the game panel
@@ -891,7 +891,7 @@
 
     ## events ##
 
-    def onChatState(self, from_jid, state, profile):
+    def on_chat_state(self, from_jid, state, profile):
         """A chat state has been received"""
         if self.type == C.CHAT_GROUP:
             nick = from_jid.resource
@@ -904,7 +904,7 @@
                     )
                 )
 
-    def onMessageState(self, uid, status, profile):
+    def on_message_state(self, uid, status, profile):
         try:
             mess_data = self.messages[uid]
         except KeyError:
@@ -912,7 +912,7 @@
         else:
             mess_data.status = status
 
-    def onAvatar(self, entity, avatar_data, profile):
+    def on_avatar(self, entity, avatar_data, profile):
         if self.type == C.CHAT_GROUP:
             if entity.bare == self.target:
                 try: