diff sat/memory/encryption.py @ 3028:ab2696e34d29

Python 3 port: /!\ this is a huge commit /!\ starting from this commit, SàT is needs Python 3.6+ /!\ SàT maybe be instable or some feature may not work anymore, this will improve with time This patch port backend, bridge and frontends to Python 3. Roughly this has been done this way: - 2to3 tools has been applied (with python 3.7) - all references to python2 have been replaced with python3 (notably shebangs) - fixed files not handled by 2to3 (notably the shell script) - several manual fixes - fixed issues reported by Python 3 that where not handled in Python 2 - replaced "async" with "async_" when needed (it's a reserved word from Python 3.7) - replaced zope's "implements" with @implementer decorator - temporary hack to handle data pickled in database, as str or bytes may be returned, to be checked later - fixed hash comparison for password - removed some code which is not needed anymore with Python 3 - deactivated some code which needs to be checked (notably certificate validation) - tested with jp, fixed reported issues until some basic commands worked - ported Primitivus (after porting dependencies like urwid satext) - more manual fixes
author Goffi <goffi@goffi.org>
date Tue, 13 Aug 2019 19:08:41 +0200
parents c161a294fffd
children 118d91c932a7
line wrap: on
line diff
--- a/sat/memory/encryption.py	Wed Jul 31 11:31:22 2019 +0200
+++ b/sat/memory/encryption.py	Tue Aug 13 19:08:41 2019 +0200
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python3
 # -*- coding: utf-8 -*-
 
 # SAT: a jabber client
@@ -91,7 +91,7 @@
             directed=directed)
         cls.plugins.append(plugin)
         cls.plugins.sort(key=lambda p: p.priority)
-        log.info(_(u"Encryption plugin registered: {name}").format(name=name))
+        log.info(_("Encryption plugin registered: {name}").format(name=name))
 
     @classmethod
     def getPlugins(cls):
@@ -103,7 +103,7 @@
             return next(p for p in cls.plugins if p.namespace == namespace)
         except StopIteration:
             raise exceptions.NotFound(_(
-                u"Can't find requested encryption plugin: {namespace}").format(
+                "Can't find requested encryption plugin: {namespace}").format(
                     namespace=namespace))
 
     @classmethod
@@ -123,7 +123,7 @@
             if p.name.lower() == name.lower():
                 return p.namespace
         raise exceptions.NotFound(_(
-            u"Can't find a plugin with the name \"{name}\".".format(
+            "Can't find a plugin with the name \"{name}\".".format(
                 name=name)))
 
     def getBridgeData(self, session):
@@ -133,12 +133,12 @@
         @return (unicode): serialized data for bridge
         """
         if session is None:
-            return u''
-        plugin = session[u'plugin']
+            return ''
+        plugin = session['plugin']
         bridge_data = {'name': plugin.name,
                        'namespace': plugin.namespace}
-        if u'directed_devices' in session:
-            bridge_data[u'directed_devices'] = session[u'directed_devices']
+        if 'directed_devices' in session:
+            bridge_data['directed_devices'] = session['directed_devices']
 
         return data_format.serialise(bridge_data)
 
@@ -151,7 +151,7 @@
         try:
             start_encryption = plugin.instance.startEncryption
         except AttributeError:
-            log.debug(u"No startEncryption method found for {plugin}".format(
+            log.debug("No startEncryption method found for {plugin}".format(
                 plugin = plugin.namespace))
             return defer.succeed(None)
         else:
@@ -167,7 +167,7 @@
         try:
             stop_encryption = plugin.instance.stopEncryption
         except AttributeError:
-            log.debug(u"No stopEncryption method found for {plugin}".format(
+            log.debug("No stopEncryption method found for {plugin}".format(
                 plugin = plugin.namespace))
             return defer.succeed(None)
         else:
@@ -187,8 +187,8 @@
             it will be replaced by the new one
         """
         if not self.plugins:
-            raise exceptions.NotFound(_(u"No encryption plugin is registered, "
-                                        u"an encryption session can't be started"))
+            raise exceptions.NotFound(_("No encryption plugin is registered, "
+                                        "an encryption session can't be started"))
 
         if namespace is None:
             plugin = self.plugins[0]
@@ -198,10 +198,10 @@
         bare_jid = entity.userhostJID()
         if bare_jid in self._sessions:
             # we have already an encryption session with this contact
-            former_plugin = self._sessions[bare_jid][u"plugin"]
+            former_plugin = self._sessions[bare_jid]["plugin"]
             if former_plugin.namespace == namespace:
-                log.info(_(u"Session with {bare_jid} is already encrypted with {name}. "
-                           u"Nothing to do.").format(
+                log.info(_("Session with {bare_jid} is already encrypted with {name}. "
+                           "Nothing to do.").format(
                                bare_jid=bare_jid, name=former_plugin.name))
                 return
 
@@ -211,8 +211,8 @@
                 del self._sessions[bare_jid]
                 yield self._stopEncryption(former_plugin, entity)
             else:
-                msg = (_(u"Session with {bare_jid} is already encrypted with {name}. "
-                         u"Please stop encryption session before changing algorithm.")
+                msg = (_("Session with {bare_jid} is already encrypted with {name}. "
+                         "Please stop encryption session before changing algorithm.")
                        .format(bare_jid=bare_jid, name=plugin.name))
                 log.warning(msg)
                 raise exceptions.ConflictError(msg)
@@ -223,34 +223,34 @@
                 entity.resource = self.host.memory.getMainResource(self.client, entity)
                 if not entity.resource:
                     raise exceptions.NotFound(
-                        _(u"No resource found for {destinee}, can't encrypt with {name}")
+                        _("No resource found for {destinee}, can't encrypt with {name}")
                         .format(destinee=entity.full(), name=plugin.name))
-                log.info(_(u"No resource specified to encrypt with {name}, using "
-                           u"{destinee}.").format(destinee=entity.full(),
+                log.info(_("No resource specified to encrypt with {name}, using "
+                           "{destinee}.").format(destinee=entity.full(),
                                                   name=plugin.name))
             # indicate that we encrypt only for some devices
-            directed_devices = data[u'directed_devices'] = [entity.resource]
+            directed_devices = data['directed_devices'] = [entity.resource]
         elif entity.resource:
-            raise ValueError(_(u"{name} encryption must be used with bare jids."))
+            raise ValueError(_("{name} encryption must be used with bare jids."))
 
         yield self._startEncryption(plugin, entity)
         self._sessions[entity.userhostJID()] = data
-        log.info(_(u"Encryption session has been set for {entity_jid} with "
-                   u"{encryption_name}").format(
+        log.info(_("Encryption session has been set for {entity_jid} with "
+                   "{encryption_name}").format(
                    entity_jid=entity.full(), encryption_name=plugin.name))
         self.host.bridge.messageEncryptionStarted(
             entity.full(),
             self.getBridgeData(data),
             self.client.profile)
-        msg = D_(u"Encryption session started: your messages with {destinee} are "
-                 u"now end to end encrypted using {name} algorithm.").format(
+        msg = D_("Encryption session started: your messages with {destinee} are "
+                 "now end to end encrypted using {name} algorithm.").format(
                  destinee=entity.full(), name=plugin.name)
-        directed_devices = data.get(u'directed_devices')
+        directed_devices = data.get('directed_devices')
         if directed_devices:
-            msg += u"\n" + D_(u"Message are encrypted only for {nb_devices} device(s): "
-                              u"{devices_list}.").format(
+            msg += "\n" + D_("Message are encrypted only for {nb_devices} device(s): "
+                              "{devices_list}.").format(
                               nb_devices=len(directed_devices),
-                              devices_list = u', '.join(directed_devices))
+                              devices_list = ', '.join(directed_devices))
 
         self.client.feedback(bare_jid, msg)
 
@@ -266,29 +266,29 @@
         session = self.getSession(entity.userhostJID())
         if not session:
             raise failure.Failure(
-                exceptions.NotFound(_(u"There is no encryption session with this "
-                                      u"entity.")))
+                exceptions.NotFound(_("There is no encryption session with this "
+                                      "entity.")))
         plugin = session['plugin']
         if namespace is not None and plugin.namespace != namespace:
             raise exceptions.InternalError(_(
-                u"The encryption session is not run with the expected plugin: encrypted "
-                u"with {current_name} and was expecting {expected_name}").format(
-                current_name=session[u'plugin'].namespace,
+                "The encryption session is not run with the expected plugin: encrypted "
+                "with {current_name} and was expecting {expected_name}").format(
+                current_name=session['plugin'].namespace,
                 expected_name=namespace))
         if entity.resource:
             try:
-                directed_devices = session[u'directed_devices']
+                directed_devices = session['directed_devices']
             except KeyError:
                 raise exceptions.NotFound(_(
-                    u"There is a session for the whole entity (i.e. all devices of the "
-                    u"entity), not a directed one. Please use bare jid if you want to "
-                    u"stop the whole encryption with this entity."))
+                    "There is a session for the whole entity (i.e. all devices of the "
+                    "entity), not a directed one. Please use bare jid if you want to "
+                    "stop the whole encryption with this entity."))
 
             try:
                 directed_devices.remove(entity.resource)
             except ValueError:
-                raise exceptions.NotFound(_(u"There is no directed session with this "
-                                            u"entity."))
+                raise exceptions.NotFound(_("There is no directed session with this "
+                                            "entity."))
             else:
                 if not directed_devices:
                     # if we have no more directed device sessions,
@@ -302,7 +302,7 @@
             del self._sessions[entity.userhostJID()]
             yield self._stopEncryption(plugin, entity)
 
-        log.info(_(u"encryption session stopped with entity {entity}").format(
+        log.info(_("encryption session stopped with entity {entity}").format(
             entity=entity.full()))
         self.host.bridge.messageEncryptionStopped(
             entity.full(),
@@ -310,9 +310,9 @@
              'namespace': plugin.namespace,
             },
             self.client.profile)
-        msg = D_(u"Encryption session finished: your messages with {destinee} are "
-                 u"NOT end to end encrypted anymore.\nYour server administrators or "
-                 u"{destinee} server administrators will be able to read them.").format(
+        msg = D_("Encryption session finished: your messages with {destinee} are "
+                 "NOT end to end encrypted anymore.\nYour server administrators or "
+                 "{destinee} server administrators will be able to read them.").format(
                  destinee=entity.full())
 
         self.client.feedback(entity, msg)
@@ -326,7 +326,7 @@
             None if there is not encryption for this session with this jid
         """
         if entity.resource:
-            raise ValueError(u"Full jid given when expecting bare jid")
+            raise ValueError("Full jid given when expecting bare jid")
         return self._sessions.get(entity)
 
     def getTrustUI(self, entity_jid, namespace=None):
@@ -346,7 +346,7 @@
             session = self.getSession(entity_jid)
             if not session:
                 raise exceptions.NotFound(
-                    u"No encryption session currently active for {entity_jid}"
+                    "No encryption session currently active for {entity_jid}"
                     .format(entity_jid=entity_jid.full()))
             plugin = session['plugin']
         else:
@@ -355,7 +355,7 @@
             get_trust_ui = plugin.instance.getTrustUI
         except AttributeError:
             raise NotImplementedError(
-                u"Encryption plugin doesn't handle trust management UI")
+                "Encryption plugin doesn't handle trust management UI")
         else:
             return defer.maybeDeferred(get_trust_ui, self.client, entity_jid)
 
@@ -364,32 +364,32 @@
     @classmethod
     def _importMenus(cls, host):
         host.importMenu(
-             (D_(u"Encryption"), D_(u"unencrypted (plain text)")),
+             (D_("Encryption"), D_("unencrypted (plain text)")),
              partial(cls._onMenuUnencrypted, host=host),
              security_limit=0,
-             help_string=D_(u"End encrypted session"),
+             help_string=D_("End encrypted session"),
              type_=C.MENU_SINGLE,
         )
         for plg in cls.getPlugins():
             host.importMenu(
-                 (D_(u"Encryption"), plg.name),
+                 (D_("Encryption"), plg.name),
                  partial(cls._onMenuName, host=host, plg=plg),
                  security_limit=0,
-                 help_string=D_(u"Start {name} session").format(name=plg.name),
+                 help_string=D_("Start {name} session").format(name=plg.name),
                  type_=C.MENU_SINGLE,
             )
             host.importMenu(
-                 (D_(u"Encryption"), D_(u"⛨ {name} trust").format(name=plg.name)),
+                 (D_("Encryption"), D_("⛨ {name} trust").format(name=plg.name)),
                  partial(cls._onMenuTrust, host=host, plg=plg),
                  security_limit=0,
-                 help_string=D_(u"Manage {name} trust").format(name=plg.name),
+                 help_string=D_("Manage {name} trust").format(name=plg.name),
                  type_=C.MENU_SINGLE,
             )
 
     @classmethod
     def _onMenuUnencrypted(cls, data, host, profile):
         client = host.getClient(profile)
-        peer_jid = jid.JID(data[u'jid']).userhostJID()
+        peer_jid = jid.JID(data['jid']).userhostJID()
         d = client.encryption.stop(peer_jid)
         d.addCallback(lambda __: {})
         return d
@@ -397,7 +397,7 @@
     @classmethod
     def _onMenuName(cls, data, host, plg, profile):
         client = host.getClient(profile)
-        peer_jid = jid.JID(data[u'jid'])
+        peer_jid = jid.JID(data['jid'])
         if not plg.directed:
             peer_jid = peer_jid.userhostJID()
         d = client.encryption.start(peer_jid, plg.namespace, replace=True)
@@ -408,9 +408,9 @@
     @defer.inlineCallbacks
     def _onMenuTrust(cls, data, host, plg, profile):
         client = host.getClient(profile)
-        peer_jid = jid.JID(data[u'jid']).userhostJID()
+        peer_jid = jid.JID(data['jid']).userhostJID()
         ui = yield client.encryption.getTrustUI(peer_jid, plg.namespace)
-        defer.returnValue({u'xmlui': ui.toXml()})
+        defer.returnValue({'xmlui': ui.toXml()})
 
     ## Triggers ##