diff cagou/plugins/plugin_wid_chat.py @ 312:772c170b47a9

Python3 port: /!\ Cagou now runs with Python 3.6+ Port has been done in the same way as for backend (check backend commit b2d067339de3 message for details).
author Goffi <goffi@goffi.org>
date Tue, 13 Aug 2019 19:14:22 +0200
parents fe8639e64c69
children e2b51663d8b8
line wrap: on
line diff
--- a/cagou/plugins/plugin_wid_chat.py	Mon Aug 05 11:21:54 2019 +0200
+++ b/cagou/plugins/plugin_wid_chat.py	Tue Aug 13 19:14:22 2019 +0200
@@ -46,10 +46,10 @@
 log = logging.getLogger(__name__)
 
 PLUGIN_INFO = {
-    "name": _(u"chat"),
+    "name": _("chat"),
     "main": "Chat",
-    "description": _(u"instant messaging with one person or a group"),
-    "icon_symbol": u"chat",
+    "description": _("instant messaging with one person or a group"),
+    "icon_symbol": "chat",
 }
 
 # FIXME: OTR specific code is legacy, and only used nowadays for lock color
@@ -99,9 +99,9 @@
         return self.mess_data.main_message
 
     def _set_message(self, message):
-        if message == self.mess_data.message.get(u""):
+        if message == self.mess_data.message.get(""):
             return False
-        self.mess_data.message = {u"": message}
+        self.mess_data.message = {"": message}
         return True
 
     message = properties.AliasProperty(_get_message, _set_message)
@@ -135,7 +135,7 @@
             self.avatar.source = update_dict['avatar']
         if 'status' in update_dict:
             status = update_dict['status']
-            self.delivery.text =  u'\u2714' if status == 'delivered' else u''
+            self.delivery.text =  '\u2714' if status == 'delivered' else ''
 
 
 class SendButton(SymbolButton):
@@ -191,13 +191,13 @@
 
     def on_select(self, menu):
         if menu == 'bookmark':
-            G.host.bridge.menuLaunch(C.MENU_GLOBAL, (u"groups", u"bookmarks"),
+            G.host.bridge.menuLaunch(C.MENU_GLOBAL, ("groups", "bookmarks"),
                                      {}, C.NO_SECURITY_LIMIT, self.chat.profile,
                                      callback=partial(
                                         G.host.actionManager, profile=self.chat.profile),
                                      errback=G.host.errback)
         else:
-            raise exceptions.InternalError(u"Unknown menu: {}".format(menu))
+            raise exceptions.InternalError("Unknown menu: {}".format(menu))
 
 
 class ExtraButton(SymbolButton):
@@ -253,11 +253,12 @@
     text = properties.StringProperty()
     trust_button = properties.BooleanProperty(False)
     best_width = properties.NumericProperty(0)
+    bold = properties.BooleanProperty(True)
 
     def __init__(self, **kwargs):
+        super(EncryptionButton, self).__init__(**kwargs)
         self.register_event_type('on_release')
         self.register_event_type('on_trust_release')
-        super(EncryptionButton, self).__init__(**kwargs)
         if self.trust_button:
             self.add_widget(TrustManagementButton())
 
@@ -279,7 +280,7 @@
         self.chat = chat
         super(EncryptionMenu, self).__init__(**kwargs)
         btn = EncryptionButton(
-            text=_(u"unencrypted (plain text)"),
+            text=_("unencrypted (plain text)"),
             on_release=self.unencrypted,
             selected=True,
             bold=False,
@@ -287,7 +288,7 @@
         self.add_widget(btn)
         for plugin in G.host.encryption_plugins:
             btn = EncryptionButton(
-                text=plugin[u'name'],
+                text=plugin['name'],
                 on_release=partial(self.startEncryption, plugin=plugin),
                 on_trust_release=partial(self.getTrustUI, plugin=plugin),
                 trust_button=True,
@@ -296,35 +297,35 @@
             log.info("added encryption: {}".format(plugin['name']))
 
     def messageEncryptionStopCb(self):
-        log.info(_(u"Session with {destinee} is now in plain text").format(
+        log.info(_("Session with {destinee} is now in plain text").format(
             destinee = self.chat.target))
 
     def messageEncryptionStopEb(self, failure_):
-        msg = _(u"Error while stopping encryption with {destinee}: {reason}").format(
+        msg = _("Error while stopping encryption with {destinee}: {reason}").format(
             destinee = self.chat.target,
             reason = failure_)
         log.warning(msg)
-        G.host.addNote(_(u"encryption problem"), msg, C.XMLUI_DATA_LVL_ERROR)
+        G.host.addNote(_("encryption problem"), msg, C.XMLUI_DATA_LVL_ERROR)
 
     def unencrypted(self, button):
         self.dismiss()
         G.host.bridge.messageEncryptionStop(
-            unicode(self.chat.target),
+            str(self.chat.target),
             self.chat.profile,
             callback=self.messageEncryptionStopCb,
             errback=self.messageEncryptionStopEb)
 
     def messageEncryptionStartCb(self, plugin):
-        log.info(_(u"Session with {destinee} is now encrypted with {encr_name}").format(
+        log.info(_("Session with {destinee} is now encrypted with {encr_name}").format(
             destinee = self.chat.target,
             encr_name = plugin['name']))
 
     def messageEncryptionStartEb(self, failure_):
-        msg = _(u"Session can't be encrypted with {destinee}: {reason}").format(
+        msg = _("Session can't be encrypted with {destinee}: {reason}").format(
             destinee = self.chat.target,
             reason = failure_)
         log.warning(msg)
-        G.host.addNote(_(u"encryption problem"), msg, C.XMLUI_DATA_LVL_ERROR)
+        G.host.addNote(_("encryption problem"), msg, C.XMLUI_DATA_LVL_ERROR)
 
     def startEncryption(self, button, plugin):
         """Request encryption with given plugin for this session
@@ -334,7 +335,7 @@
         """
         self.dismiss()
         G.host.bridge.messageEncryptionStart(
-            unicode(self.chat.target),
+            str(self.chat.target),
             plugin['namespace'],
             True,
             self.chat.profile,
@@ -347,10 +348,10 @@
         xml_ui.show()
 
     def encryptionTrustUIGetEb(self, failure_):
-        msg = _(u"Trust manager interface can't be retrieved: {reason}").format(
+        msg = _("Trust manager interface can't be retrieved: {reason}").format(
             reason = failure_)
         log.warning(msg)
-        G.host.addNote(_(u"encryption trust management problem"), msg,
+        G.host.addNote(_("encryption trust management problem"), msg,
                        C.XMLUI_DATA_LVL_ERROR)
 
     def getTrustUI(self, button, plugin):
@@ -361,7 +362,7 @@
         """
         self.dismiss()
         G.host.bridge.encryptionTrustUIGet(
-            unicode(self.chat.target),
+            str(self.chat.target),
             plugin['namespace'],
             self.chat.profile,
             callback=self.encryptionTrustUIGetCb,
@@ -371,8 +372,8 @@
         self.dismiss()
         G.host.launchMenu(
             C.MENU_SINGLE,
-            (u"otr", u"start/refresh"),
-            {u'jid': unicode(self.chat.target)},
+            ("otr", "start/refresh"),
+            {'jid': str(self.chat.target)},
             None,
             C.NO_SECURITY_LIMIT,
             self.chat.profile
@@ -382,8 +383,8 @@
         self.dismiss()
         G.host.launchMenu(
             C.MENU_SINGLE,
-            (u"otr", u"end session"),
-            {u'jid': unicode(self.chat.target)},
+            ("otr", "end session"),
+            {'jid': str(self.chat.target)},
             None,
             C.NO_SECURITY_LIMIT,
             self.chat.profile
@@ -393,8 +394,8 @@
         self.dismiss()
         G.host.launchMenu(
             C.MENU_SINGLE,
-            (u"otr", u"authenticate"),
-            {u'jid': unicode(self.chat.target)},
+            ("otr", "authenticate"),
+            {'jid': str(self.chat.target)},
             None,
             C.NO_SECURITY_LIMIT,
             self.chat.profile
@@ -425,14 +426,11 @@
         self.extra_menu = ExtraMenu(chat=self)
         extra_btn = ExtraButton(chat=self)
         self.headerInputAddExtra(extra_btn)
-        self.header_input.hint_text = u"{}".format(target)
+        self.header_input.hint_text = "{}".format(target)
         self.postInit()
 
-    def __unicode__(self):
-        return u"Chat({})".format(self.target)
-
     def __str__(self):
-        return self.__unicode__().encode('utf-8')
+        return "Chat({})".format(self.target)
 
     def __repr__(self):
         return self.__str__()
@@ -441,7 +439,7 @@
     def factory(cls, plugin_info, target, profiles):
         profiles = list(profiles)
         if len(profiles) > 1:
-            raise NotImplementedError(u"Multi-profiles is not available yet for chat")
+            raise NotImplementedError("Multi-profiles is not available yet for chat")
         if target is None:
             target = G.host.profiles[profiles[0]].whoami
         return G.host.widgets.getOrCreateWidget(cls, target, on_new_widget=None,
@@ -467,23 +465,23 @@
     def onHeaderInput(self):
         text = self.header_input.text.strip()
         try:
-            if text.count(u'@') != 1 or text.count(u' '):
+            if text.count('@') != 1 or text.count(' '):
                 raise ValueError
             jid_ = jid.JID(text)
         except ValueError:
-            log.info(u"entered text is not a jid")
+            log.info("entered text is not a jid")
             return
 
         def discoCb(disco):
             # TODO: check if plugin XEP-0045 is activated
             if "conference" in [i[0] for i in disco[1]]:
-                G.host.bridge.mucJoin(unicode(jid_), "", "", self.profile,
+                G.host.bridge.mucJoin(str(jid_), "", "", self.profile,
                                       callback=self._mucJoinCb, errback=self._mucJoinEb)
             else:
                 self.changeWidget(jid_)
 
         def discoEb(failure):
-            log.warning(u"Disco failure, ignore this text: {}".format(failure))
+            log.warning("Disco failure, ignore this text: {}".format(failure))
 
         G.host.bridge.discoInfos(jid_.domain, self.profile, callback=discoCb,
                                  errback=discoEb)
@@ -526,7 +524,7 @@
             dropdown.clear_widgets()
 
             for jid_, jid_data in comp_data:
-                nick = jid_data.get(u'nick', u'')
+                nick = jid_data.get('nick', '')
                 if text in jid_.bare or text in nick.lower():
                     btn = JidButton(
                         jid = jid_.bare,
@@ -554,7 +552,7 @@
     def _onHistoryPrinted(self):
         """Refresh or scroll down the focus after the history is printed"""
         # self.adapter.data = self.messages
-        for mess_data in self.messages.itervalues():
+        for mess_data in self.messages.values():
             self.appendMessage(mess_data)
         super(Chat, self)._onHistoryPrinted()
 
@@ -572,7 +570,7 @@
         self.notify(mess_data)
 
     def _get_notif_msg(self, mess_data):
-        return _(u"{nick}: {message}").format(
+        return _("{nick}: {message}").format(
             nick=mess_data.nick,
             message=mess_data.main_message)
 
@@ -597,14 +595,14 @@
                 notif_msg = self._get_notif_msg(mess_data)
                 G.host.desktop_notif(
                     notif_msg,
-                    title=_(u"private message"))
+                    title=_("private message"))
                 if not is_visible:
                     G.host.addNote(
-                        _(u"private message"),
+                        _("private message"),
                         notif_msg,
-                        symbol = u"chat",
+                        symbol = "chat",
                         action = {
-                            "action": u'chat',
+                            "action": 'chat',
                             "target": self.target,
                             "profiles": self.profiles}
                         )
@@ -612,18 +610,18 @@
             if mess_data.mention and not mess_data.history:
                 notif_msg = self._get_notif_msg(mess_data)
                 G.host.addNote(
-                    _(u"mention"),
+                    _("mention"),
                     notif_msg,
-                    symbol = u"chat",
+                    symbol = "chat",
                     action = {
-                        "action": u'chat',
+                        "action": 'chat',
                         "target": self.target,
                         "profiles": self.profiles}
                     )
                 if not Window.focus:
                     G.host.desktop_notif(
                         notif_msg,
-                        title=_(u"mention ({room_jid})").format(
+                        title=_("mention ({room_jid})").format(
                             room_jid=self.target)
                         )
 
@@ -640,9 +638,9 @@
     def fileTransferEb(self, err_msg, cleaning_cb, profile):
         if cleaning_cb is not None:
             cleaning_cb()
-        msg = _(u"can't transfer file: {reason}").format(reason=err_msg)
+        msg = _("can't transfer file: {reason}").format(reason=err_msg)
         log.warning(msg)
-        G.host.addNote(_(u"File transfer error"),
+        G.host.addNote(_("File transfer error"),
                        msg,
                        level=C.XMLUI_DATA_LVL_WARNING)
 
@@ -653,9 +651,9 @@
         # FIXME: Q&D way of getting file type, upload plugins shouls give it
         mime_type = mimetypes.guess_type(metadata['url'])[0]
         if mime_type is not None:
-            if mime_type.split(u'/')[0] == 'image':
+            if mime_type.split('/')[0] == 'image':
                 # we generate url ourselves, so this formatting is safe
-                extra['xhtml'] = u"<img src='{url}' />".format(**metadata)
+                extra['xhtml'] = "<img src='{url}' />".format(**metadata)
 
         G.host.messageSend(
             self.target,
@@ -682,28 +680,28 @@
                     profile = self.profile,
                     ),
                 errback = partial(G.host.errback,
-                                  message=_(u"can't upload file: {msg}"))
+                                  message=_("can't upload file: {msg}"))
             )
         elif transfer_type == C.TRANSFER_SEND:
             if self.type == C.CHAT_GROUP:
-                log.warning(u"P2P transfer is not possible for group chat")
+                log.warning("P2P transfer is not possible for group chat")
                 # TODO: show an error dialog to user, or better hide the send button for
                 #       MUC
             else:
                 jid_ = self.target
                 if not jid_.resource:
                     jid_ = G.host.contact_lists[self.profile].getFullJid(jid_)
-                G.host.bridge.fileSend(unicode(jid_), file_path, "", "", {},
+                G.host.bridge.fileSend(str(jid_), file_path, "", "", {},
                                        profile=self.profile)
                 # TODO: notification of sending/failing
         else:
-            raise log.error(u"transfer of type {} are not handled".format(transfer_type))
+            raise log.error("transfer of type {} are not handled".format(transfer_type))
 
     def messageEncryptionStarted(self, plugin_data):
         quick_chat.QuickChat.messageEncryptionStarted(self, plugin_data)
         self.encryption_btn.symbol = SYMBOL_ENCRYPTED
         self.encryption_btn.color = COLOR_ENCRYPTED
-        self.encryption_btn.selectAlgo(plugin_data[u'name'])
+        self.encryption_btn.selectAlgo(plugin_data['name'])
 
     def messageEncryptionStopped(self, plugin_data):
         quick_chat.QuickChat.messageEncryptionStopped(self, plugin_data)
@@ -718,7 +716,7 @@
         self.changeWidget(jid_)
 
     def _mucJoinEb(self, failure):
-        log.warning(u"Can't join room: {}".format(failure))
+        log.warning("Can't join room: {}".format(failure))
 
     def onOTRState(self, state, dest_jid, profile):
         assert profile in self.profiles
@@ -727,7 +725,7 @@
         elif state in OTR_STATE_TRUST:
             self.otr_state_trust = state
         else:
-            log.error(_(u"Unknown OTR state received: {}".format(state)))
+            log.error(_("Unknown OTR state received: {}".format(state)))
             return
         self.encryption_btn.symbol = self.encryption_btn.getSymbol()
         self.encryption_btn.color = self.encryption_btn.getColor()