diff sat_frontends/quick_frontend/quick_chat.py @ 2624:56f94936df1e

code style reformatting using black
author Goffi <goffi@goffi.org>
date Wed, 27 Jun 2018 20:14:46 +0200
parents 5e54afd17321
children 96911768b0f3
line wrap: on
line diff
--- a/sat_frontends/quick_frontend/quick_chat.py	Wed Jun 27 07:51:29 2018 +0200
+++ b/sat_frontends/quick_frontend/quick_chat.py	Wed Jun 27 20:14:46 2018 +0200
@@ -19,6 +19,7 @@
 
 from sat.core.i18n import _
 from sat.core.log import getLogger
+
 log = getLogger(__name__)
 from sat.core import exceptions
 from sat_frontends.quick_frontend import quick_widgets
@@ -26,31 +27,48 @@
 from collections import OrderedDict
 from sat_frontends.tools import jid
 import time
+
 try:
     from locale import getlocale
 except ImportError:
     # FIXME: pyjamas workaround
-    getlocale = lambda x: (None, 'utf-8')
+    getlocale = lambda x: (None, "utf-8")
 
 
-ROOM_USER_JOINED = 'ROOM_USER_JOINED'
-ROOM_USER_LEFT = 'ROOM_USER_LEFT'
+ROOM_USER_JOINED = "ROOM_USER_JOINED"
+ROOM_USER_LEFT = "ROOM_USER_LEFT"
 ROOM_USER_MOVED = (ROOM_USER_JOINED, ROOM_USER_LEFT)
 
 # from datetime import datetime
 
 try:
     # FIXME: to be removed when an acceptable solution is here
-    unicode('') # XXX: unicode doesn't exist in pyjamas
-except (TypeError, AttributeError): # Error raised is not the same depending on pyjsbuild options
+    unicode("")  # XXX: unicode doesn't exist in pyjamas
+except (
+    TypeError,
+    AttributeError,
+):  # Error raised is not the same depending on pyjsbuild options
     unicode = str
 
 # FIXME: day_format need to be settable (i18n)
 
+
 class Message(object):
     """Message metadata"""
 
-    def __init__(self, parent, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile):
+    def __init__(
+        self,
+        parent,
+        uid,
+        timestamp,
+        from_jid,
+        to_jid,
+        msg,
+        subject,
+        type_,
+        extra,
+        profile,
+    ):
         self.parent = parent
         self.profile = profile
         self.uid = uid
@@ -64,7 +82,11 @@
         self.nick = self.getNick(from_jid)
         self._status = None
         # own_mess is True if message was sent by profile's jid
-        self.own_mess = (from_jid.resource == self.parent.nick) if self.parent.type == C.CHAT_GROUP else (from_jid.bare == self.host.profiles[profile].whoami.bare)
+        self.own_mess = (
+            (from_jid.resource == self.parent.nick)
+            if self.parent.type == C.CHAT_GROUP
+            else (from_jid.bare == self.host.profiles[profile].whoami.bare)
+        )
         # is user mentioned here ?
         if self.parent.type == C.CHAT_GROUP and not self.own_mess:
             for m in msg.itervalues():
@@ -80,7 +102,7 @@
 
     @property
     def info_type(self):
-        return self.extra.get('info_type')
+        return self.extra.get("info_type")
 
     @property
     def mention(self):
@@ -92,7 +114,7 @@
     @property
     def history(self):
         """True if message come from history"""
-        return self.extra.get('history', False)
+        return self.extra.get("history", False)
 
     @property
     def main_message(self):
@@ -101,8 +123,8 @@
             self.selected_lang = self.parent.lang
             return self.message[self.parent.lang]
         try:
-            self.selected_lang = ''
-            return self.message['']
+            self.selected_lang = ""
+            return self.message[""]
         except KeyError:
             try:
                 lang, mess = self.message.iteritems().next()
@@ -110,24 +132,23 @@
                 return mess
             except StopIteration:
                 log.error(u"Can't find message for uid {}".format(self.uid))
-                return ''
+                return ""
 
     @property
     def main_message_xhtml(self):
         """rich message"""
-        xhtml = {k:v for k,v in self.extra.iteritems() if 'html' in k}
+        xhtml = {k: v for k, v in self.extra.iteritems() if "html" in k}
         if xhtml:
             # FIXME: we only return first found value for now
             return next(xhtml.itervalues())
 
-
     @property
     def time_text(self):
         """Return timestamp in a nicely formatted way"""
         # if the message was sent before today, we print the full date
         timestamp = time.localtime(self.timestamp)
         time_format = u"%c" if timestamp < self.parent.day_change else u"%H:%M"
-        return time.strftime(time_format, timestamp).decode(getlocale()[1] or 'utf-8')
+        return time.strftime(time_format, timestamp).decode(getlocale()[1] or "utf-8")
 
     @property
     def avatar(self):
@@ -140,15 +161,22 @@
         contact_list = self.host.contact_lists[self.profile]
         if self.type == C.MESS_TYPE_INFO and self.info_type in ROOM_USER_MOVED:
             try:
-                return self.extra['user_nick']
+                return self.extra["user_nick"]
             except KeyError:
                 log.error(u"extra data is missing user nick for uid {}".format(self.uid))
                 return ""
         # FIXME: converted getSpecials to list for pyjamas
-        if self.parent.type == C.CHAT_GROUP or entity in list(contact_list.getSpecials(C.CONTACT_SPECIAL_GROUP)):
+        if self.parent.type == C.CHAT_GROUP or entity in list(
+            contact_list.getSpecials(C.CONTACT_SPECIAL_GROUP)
+        ):
             return entity.resource or ""
         if entity.bare in contact_list:
-            return contact_list.getCache(entity, 'nick') or contact_list.getCache(entity, 'name') or entity.node or entity
+            return (
+                contact_list.getCache(entity, "nick")
+                or contact_list.getCache(entity, "name")
+                or entity.node
+                or entity
+            )
         return entity.node or entity
 
     @property
@@ -178,7 +206,7 @@
                 break
         if me:
             self.type = C.MESS_TYPE_INFO
-            self.extra['info_type'] = 'me'
+            self.extra["info_type"] = "me"
             nick = self.nick
             for lang, mess in self.message.iteritems():
                 self.message[lang] = u"* " + nick + mess[3:]
@@ -190,10 +218,10 @@
     def __init__(self, parent, data, profile):
         self.parent = parent
         self.profile = profile
-        self.nick = data['nick']
-        self._entity = data.get('entity')
-        self.affiliation = data['affiliation']
-        self.role = data['role']
+        self.nick = data["nick"]
+        self._entity = data.get("entity")
+        self.affiliation = data["affiliation"]
+        self.role = data["role"]
         self.widgets = set()  # widgets linked to this occupant
         self._state = None
 
@@ -201,11 +229,11 @@
     def data(self):
         """reconstruct data dict from attributes"""
         data = {}
-        data['nick'] = self.nick
+        data["nick"] = self.nick
         if self._entity is not None:
-            data['entity'] = self._entity
-        data['affiliation'] = self.affiliation
-        data['role'] = self.role
+            data["entity"] = self._entity
+        data["affiliation"] = self.affiliation
+        data["role"] = self.role
         return data
 
     @property
@@ -239,23 +267,34 @@
 
 
 class QuickChat(quick_widgets.QuickWidget):
-    visible_states = ['chat_state']  # FIXME: to be removed, used only in quick_games
+    visible_states = ["chat_state"]  # FIXME: to be removed, used only in quick_games
 
-    def __init__(self, host, target, type_=C.CHAT_ONE2ONE, nick=None, occupants=None, subject=None, profiles=None):
+    def __init__(
+        self,
+        host,
+        target,
+        type_=C.CHAT_ONE2ONE,
+        nick=None,
+        occupants=None,
+        subject=None,
+        profiles=None,
+    ):
         """
         @param type_: can be C.CHAT_ONE2ONE for single conversation or C.CHAT_GROUP for chat à la IRC
         """
-        self.lang = ''  # default language to use for messages
+        self.lang = ""  # default language to use for messages
         quick_widgets.QuickWidget.__init__(self, host, target, profiles=profiles)
-        self._locked = True   # True when we are waiting for history/search
-                              # messageNew signals are cached when locked
+        self._locked = True  # True when we are waiting for history/search
+        # messageNew signals are cached when locked
         self._cache = OrderedDict()
         assert type_ in (C.CHAT_ONE2ONE, C.CHAT_GROUP)
         self.current_target = target
         self.type = type_
         if type_ == C.CHAT_GROUP:
             if target.resource:
-                raise exceptions.InternalError(u"a group chat entity can't have a resource")
+                raise exceptions.InternalError(
+                    u"a group chat entity can't have a resource"
+                )
             if nick is None:
                 raise exceptions.InternalError(u"nick must not be None for group chat")
 
@@ -264,14 +303,26 @@
             self.setOccupants(occupants)
         else:
             if occupants is not None or nick is not None:
-                raise exceptions.InternalError(u"only group chat can have occupants or nick")
+                raise exceptions.InternalError(
+                    u"only group chat can have occupants or nick"
+                )
         self.messages = OrderedDict()  # key: uid, value: Message instance
         self.games = {}  # key=game name (unicode), value=instance of quick_games.RoomGame
         self.subject = subject
         lt = time.localtime()
-        self.day_change = (lt.tm_year, lt.tm_mon, lt.tm_mday, 0, 0, 0, lt.tm_wday, lt.tm_yday, lt.tm_isdst)  # struct_time of day changing time
+        self.day_change = (
+            lt.tm_year,
+            lt.tm_mon,
+            lt.tm_mday,
+            0,
+            0,
+            0,
+            lt.tm_wday,
+            lt.tm_yday,
+            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.onAvatar, profiles)
 
     def postInit(self):
         """Method to be called by frontend after widget is initialised
@@ -284,7 +335,7 @@
 
     def onDelete(self):
         if self.host.AVATARS_HANDLER:
-            self.host.removeListener('avatar', self.onAvatar)
+            self.host.removeListener("avatar", self.onAvatar)
 
     @property
     def contact_list(self):
@@ -293,7 +344,9 @@
     ## Widget management ##
 
     def __str__(self):
-        return u"Chat Widget [target: {}, type: {}, profile: {}]".format(self.target, self.type, self.profile)
+        return u"Chat Widget [target: {}, type: {}, profile: {}]".format(
+            self.target, self.type, self.profile
+        )
 
     @staticmethod
     def getWidgetHash(target, profiles):
@@ -311,16 +364,18 @@
     def addTarget(self, target):
         super(QuickChat, self).addTarget(target)
         if target.resource:
-            self.current_target = target # FIXME: tmp, must use resource priority throught contactList instead
+            self.current_target = (
+                target
+            )  # FIXME: tmp, must use resource priority throught contactList instead
 
     def recreateArgs(self, args, kwargs):
         """copy important attribute for a new widget"""
-        kwargs['type_'] = self.type
+        kwargs["type_"] = self.type
         if self.type == C.CHAT_GROUP:
-            kwargs['occupants'] = {o.nick: o.data for o in self.occupants.itervalues()}
-        kwargs['subject'] = self.subject
+            kwargs["occupants"] = {o.nick: o.data for o in self.occupants.itervalues()}
+        kwargs["subject"] = self.subject
         try:
-            kwargs['nick'] = self.nick
+            kwargs["nick"] = self.nick
         except AttributeError:
             pass
 
@@ -333,7 +388,14 @@
 
         @param entity: full jid of the target
         """
-        return self.host.widgets.getOrCreateWidget(QuickChat, entity, type_=C.CHAT_ONE2ONE, force_hash=self.getPrivateHash(self.profile, entity), on_new_widget=self.onPrivateCreated, profile=self.profile) # we force hash to have a new widget, not this one again
+        return self.host.widgets.getOrCreateWidget(
+            QuickChat,
+            entity,
+            type_=C.CHAT_ONE2ONE,
+            force_hash=self.getPrivateHash(self.profile, entity),
+            on_new_widget=self.onPrivateCreated,
+            profile=self.profile,
+        )  # we force hash to have a new widget, not this one again
 
     @property
     def target(self):
@@ -347,25 +409,17 @@
         """set the whole list of occupants"""
         assert len(self.occupants) == 0
         for nick, data in occupants.iteritems():
-            self.occupants[nick] = Occupant(
-                self,
-                data,
-                self.profile
-                )
+            self.occupants[nick] = Occupant(self, data, self.profile)
 
     def addUser(self, occupant_data):
         """Add user if it is not in the group list"""
-        occupant = Occupant(
-            self,
-            occupant_data,
-            self.profile
-            )
+        occupant = Occupant(self, occupant_data, self.profile)
         self.occupants[occupant.nick] = occupant
         return occupant
 
     def removeUser(self, occupant_data):
         """Remove a user from the group list"""
-        nick = occupant_data['nick']
+        nick = occupant_data["nick"]
         try:
             occupant = self.occupants.pop(nick)
         except KeyError:
@@ -391,14 +445,17 @@
         @return (bool): True if this Chat Widget manage this couple
         """
         if self.type == C.CHAT_GROUP:
-            if mess_type in (C.MESS_TYPE_GROUPCHAT, C.MESS_TYPE_INFO) and self.target == entity.bare:
+            if (
+                mess_type in (C.MESS_TYPE_GROUPCHAT, C.MESS_TYPE_INFO)
+                and self.target == entity.bare
+            ):
                 return True
         else:
             if mess_type != C.MESS_TYPE_GROUPCHAT and entity in self.targets:
                 return True
         return False
 
-    def updateHistory(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile='@NONE@'):
+    def updateHistory(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
@@ -423,7 +480,7 @@
             self.messageNew(*data)
         del self._cache
 
-    def historyPrint(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile='@NONE@'):
+    def historyPrint(self, size=C.HISTORY_LIMIT_DEFAULT, filters=None, profile="@NONE@"):
         """Print the current history
 
         @param size (int): number of messages
@@ -442,21 +499,23 @@
         log.debug(log_msg)
 
         if self.type == C.CHAT_ONE2ONE:
-            special = self.host.contact_lists[self.profile].getCache(self.target, C.CONTACT_SPECIAL)
+            special = self.host.contact_lists[self.profile].getCache(
+                self.target, C.CONTACT_SPECIAL
+            )
             if special == C.CONTACT_SPECIAL_GROUP:
                 # we have a private conversation
                 # so we need full jid for the history
                 # (else we would get history from group itself)
                 # and to filter out groupchat message
                 target = self.target
-                filters['not_types'] = C.MESS_TYPE_GROUPCHAT
+                filters["not_types"] = C.MESS_TYPE_GROUPCHAT
             else:
                 target = self.target.bare
         else:
             # groupchat
             target = self.target.bare
             # FIXME: info not handled correctly
-            filters['types'] = C.MESS_TYPE_GROUPCHAT
+            filters["types"] = C.MESS_TYPE_GROUPCHAT
 
         def _historyGetCb(history):
             # day_format = "%A, %d %b %Y"  # to display the day change
@@ -476,42 +535,80 @@
                 # if ((self.type == C.CHAT_GROUP and type_ != C.MESS_TYPE_GROUPCHAT) or
                 #    (self.type == C.CHAT_ONE2ONE and type_ == C.MESS_TYPE_GROUPCHAT)):
                 #     continue
-                extra['history'] = True
-                self.messages[uid] = Message(self, uid, timestamp, from_jid, to_jid, message, subject, type_, extra, profile)
+                extra["history"] = True
+                self.messages[uid] = Message(
+                    self,
+                    uid,
+                    timestamp,
+                    from_jid,
+                    to_jid,
+                    message,
+                    subject,
+                    type_,
+                    extra,
+                    profile,
+                )
             self._onHistoryPrinted()
 
         def _historyGetEb(err):
             log.error(_(u"Can't get history: {}").format(err))
             self._onHistoryPrinted()
 
-        self.host.bridge.historyGet(unicode(self.host.profiles[profile].whoami.bare), unicode(target), size, True, filters, profile, callback=_historyGetCb, errback=_historyGetEb)
+        self.host.bridge.historyGet(
+            unicode(self.host.profiles[profile].whoami.bare),
+            unicode(target),
+            size,
+            True,
+            filters,
+            profile,
+            callback=_historyGetCb,
+            errback=_historyGetEb,
+        )
 
-    def messageNew(self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile):
+    def messageNew(
+        self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile
+    ):
         if self._locked:
-            self._cache[uid] = (uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile)
+            self._cache[uid] = (
+                uid,
+                timestamp,
+                from_jid,
+                to_jid,
+                msg,
+                subject,
+                type_,
+                extra,
+                profile,
+            )
             return
         if self.type == C.CHAT_GROUP:
             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(uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile)
+                chat_widget.messageNew(
+                    uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile
+                )
                 return
             if type_ == C.MESS_TYPE_INFO:
                 try:
-                    info_type = extra['info_type']
+                    info_type = extra["info_type"]
                 except KeyError:
                     pass
                 else:
-                    user_data = {k[5:]:v for k,v in extra.iteritems() if k.startswith('user_')}
+                    user_data = {
+                        k[5:]: v for k, v in extra.iteritems() if k.startswith("user_")
+                    }
                     if info_type == ROOM_USER_JOINED:
                         self.addUser(user_data)
                     elif info_type == ROOM_USER_LEFT:
                         self.removeUser(user_data)
 
-        message = Message(self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile)
+        message = Message(
+            self, uid, timestamp, from_jid, to_jid, msg, subject, type_, extra, profile
+        )
         self.messages[uid] = message
 
-        if 'received_timestamp' in extra:
+        if "received_timestamp" in extra:
             log.warning(u"Delayed message received after history, this should not happen")
         self.createMessage(message)
 
@@ -537,7 +634,9 @@
     def setSubject(self, subject):
         """Set title for a group chat"""
         if self.type != C.CHAT_GROUP:
-            raise exceptions.InternalError("trying to set subject for a non group chat window")
+            raise exceptions.InternalError(
+                "trying to set subject for a non group chat window"
+            )
         self.subject = subject
 
     def changeSubject(self, new_subject):
@@ -579,8 +678,11 @@
             try:
                 self.occupants[nick].state = state
             except KeyError:
-                log.warning(u"{nick} not found in {room}, ignoring new chat state".format(
-                    nick=nick, room=self.target.bare))
+                log.warning(
+                    u"{nick} not found in {room}, ignoring new chat state".format(
+                        nick=nick, room=self.target.bare
+                    )
+                )
 
     def onMessageState(self, uid, status, profile):
         try:
@@ -594,7 +696,7 @@
         if self.type == C.CHAT_GROUP:
             if entity.bare == self.target:
                 try:
-                    self.occupants[entity.resource].update({'avatar': filename})
+                    self.occupants[entity.resource].update({"avatar": filename})
                 except KeyError:
                     # can happen for a message in history where the
                     # entity is not here anymore
@@ -603,14 +705,17 @@
                 for m in self.messages.values():
                     if m.nick == entity.resource:
                         for w in m.widgets:
-                            w.update({'avatar': filename})
+                            w.update({"avatar": filename})
         else:
-            if entity.bare == self.target.bare or entity.bare == self.host.profiles[profile].whoami.bare:
+            if (
+                entity.bare == self.target.bare
+                or entity.bare == self.host.profiles[profile].whoami.bare
+            ):
                 log.info(u"avatar updated for {}".format(entity))
                 for m in self.messages.values():
                     if m.from_jid.bare == entity.bare:
                         for w in m.widgets:
-                            w.update({'avatar': filename})
+                            w.update({"avatar": filename})
 
 
 quick_widgets.register(QuickChat)