diff sat/plugins/plugin_exp_invitation.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 83cbd4545274
children 9d0df638c8b4
line wrap: on
line diff
--- a/sat/plugins/plugin_exp_invitation.py	Wed Jul 31 11:31:22 2019 +0200
+++ b/sat/plugins/plugin_exp_invitation.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 plugin to detect language (experimental)
@@ -24,7 +24,7 @@
 from twisted.internet import defer
 from twisted.words.protocols.jabber import jid
 from wokkel import disco, iwokkel
-from zope.interface import implements
+from zope.interface import implementer
 from twisted.words.protocols.jabber.xmlstream import XMPPHandler
 
 log = getLogger(__name__)
@@ -35,24 +35,24 @@
     C.PI_IMPORT_NAME: "INVITATION",
     C.PI_TYPE: "EXP",
     C.PI_PROTOCOLS: [],
-    C.PI_DEPENDENCIES: [u"XEP-0060", u"XEP-0329"],
+    C.PI_DEPENDENCIES: ["XEP-0060", "XEP-0329"],
     C.PI_RECOMMENDATIONS: [],
     C.PI_MAIN: "Invitation",
     C.PI_HANDLER: "yes",
-    C.PI_DESCRIPTION: _(u"Experimental handling of invitations"),
+    C.PI_DESCRIPTION: _("Experimental handling of invitations"),
 }
 
-NS_INVITATION = u"https://salut-a-toi/protocol/invitation:0"
+NS_INVITATION = "https://salut-a-toi/protocol/invitation:0"
 INVITATION = '/message/invitation[@xmlns="{ns_invit}"]'.format(
     ns_invit=NS_INVITATION
 )
-NS_INVITATION_LIST = NS_INVITATION + u"#list"
+NS_INVITATION_LIST = NS_INVITATION + "#list"
 
 
 class Invitation(object):
 
     def __init__(self, host):
-        log.info(_(u"Invitation plugin initialization"))
+        log.info(_("Invitation plugin initialization"))
         self.host = host
         self._p = self.host.plugins["XEP-0060"]
         # map from namespace of the invitation to callback handling it
@@ -88,7 +88,7 @@
         """
         if namespace in self._ns_cb:
             raise exceptions.ConflictError(
-                u"invitation namespace {namespace} is already register with {callback}"
+                "invitation namespace {namespace} is already register with {callback}"
                 .format(namespace=namespace, callback=self._ns_cb[namespace]))
         self._ns_cb[namespace] = callback
 
@@ -113,15 +113,15 @@
         client.generateMessageXML(mess_data)
         invitation_elt = mess_data["xml"].addElement("invitation", NS_INVITATION)
         if name is not None:
-            invitation_elt[u"name"] = name
-        thumb_url = extra.get(u'thumb_url')
+            invitation_elt["name"] = name
+        thumb_url = extra.get('thumb_url')
         if thumb_url:
-            if not thumb_url.startswith(u'http'):
+            if not thumb_url.startswith('http'):
                 log.warning(
-                    u"only http URLs are allowed for thumbnails, got {url}, ignoring"
+                    "only http URLs are allowed for thumbnails, got {url}, ignoring"
                     .format(url=thumb_url))
             else:
-                invitation_elt[u'thumb_url'] = thumb_url
+                invitation_elt['thumb_url'] = thumb_url
         return mess_data, invitation_elt
 
     def sendPubsubInvitation(self, client, invitee_jid, service, node,
@@ -139,11 +139,11 @@
             extra = {}
         mess_data, invitation_elt = self._generateBaseInvitation(
             client, invitee_jid, name, extra)
-        pubsub_elt = invitation_elt.addElement(u"pubsub")
-        pubsub_elt[u"service"] = service.full()
-        pubsub_elt[u"node"] = node
-        pubsub_elt[u"item"] = item_id
-        return client.send(mess_data[u"xml"])
+        pubsub_elt = invitation_elt.addElement("pubsub")
+        pubsub_elt["service"] = service.full()
+        pubsub_elt["node"] = node
+        pubsub_elt["item"] = item_id
+        return client.send(mess_data["xml"])
 
     def sendFileSharingInvitation(self, client, invitee_jid, service, repos_type=None,
                                   namespace=None, path=None, name=None, extra=None):
@@ -163,20 +163,20 @@
             extra = {}
         mess_data, invitation_elt = self._generateBaseInvitation(
             client, invitee_jid, name, extra)
-        file_sharing_elt = invitation_elt.addElement(u"file_sharing")
-        file_sharing_elt[u"service"] = service.full()
+        file_sharing_elt = invitation_elt.addElement("file_sharing")
+        file_sharing_elt["service"] = service.full()
         if repos_type is not None:
-            if repos_type not in (u"files", "photos"):
-                msg = u"unknown repository type: {repos_type}".format(
+            if repos_type not in ("files", "photos"):
+                msg = "unknown repository type: {repos_type}".format(
                     repos_type=repos_type)
                 log.warning(msg)
                 raise exceptions.DateError(msg)
-            file_sharing_elt[u"type"] = repos_type
+            file_sharing_elt["type"] = repos_type
         if namespace is not None:
-            file_sharing_elt[u"namespace"] = namespace
+            file_sharing_elt["namespace"] = namespace
         if path is not None:
-            file_sharing_elt[u"path"] = path
-        return client.send(mess_data[u"xml"])
+            file_sharing_elt["path"] = path
+        return client.send(mess_data["xml"])
 
     @defer.inlineCallbacks
     def _parsePubsubElt(self, client, pubsub_elt):
@@ -185,25 +185,25 @@
             node = pubsub_elt["node"]
             item_id = pubsub_elt.getAttribute("item")
         except (RuntimeError, KeyError):
-            log.warning(_(u"Bad invitation, ignoring"))
+            log.warning(_("Bad invitation, ignoring"))
             raise exceptions.DataError
 
         try:
             items, metadata = yield self._p.getItems(client, service, node,
                                                      item_ids=[item_id])
         except Exception as e:
-            log.warning(_(u"Can't get item linked with invitation: {reason}").format(
+            log.warning(_("Can't get item linked with invitation: {reason}").format(
                         reason=e))
         try:
             item_elt = items[0]
         except IndexError:
-            log.warning(_(u"Invitation was linking to a non existing item"))
+            log.warning(_("Invitation was linking to a non existing item"))
             raise exceptions.DataError
 
         try:
             namespace = item_elt.firstChildElement().uri
         except Exception as e:
-            log.warning(_(u"Can't retrieve namespace of invitation: {reason}").format(
+            log.warning(_("Can't retrieve namespace of invitation: {reason}").format(
                 reason = e))
             raise exceptions.DataError
 
@@ -214,41 +214,41 @@
         try:
             service = jid.JID(file_sharing_elt["service"])
         except (RuntimeError, KeyError):
-            log.warning(_(u"Bad invitation, ignoring"))
+            log.warning(_("Bad invitation, ignoring"))
             raise exceptions.DataError
-        repos_type = file_sharing_elt.getAttribute(u"type", u"files")
-        namespace = file_sharing_elt.getAttribute(u"namespace")
-        path = file_sharing_elt.getAttribute(u"path")
+        repos_type = file_sharing_elt.getAttribute("type", "files")
+        namespace = file_sharing_elt.getAttribute("namespace")
+        path = file_sharing_elt.getAttribute("path")
         args = [service, repos_type, namespace, path]
-        ns_fis = self.host.getNamespace(u"fis")
+        ns_fis = self.host.getNamespace("fis")
         return ns_fis, args
 
     @defer.inlineCallbacks
     def onInvitation(self, message_elt, client):
-        log.debug(u"invitation received [{profile}]".format(profile=client.profile))
+        log.debug("invitation received [{profile}]".format(profile=client.profile))
         invitation_elt = message_elt.invitation
 
-        name = invitation_elt.getAttribute(u"name")
+        name = invitation_elt.getAttribute("name")
         extra = {}
-        if invitation_elt.hasAttribute(u"thumb_url"):
-            extra[u'thumb_url'] = invitation_elt[u'thumb_url']
+        if invitation_elt.hasAttribute("thumb_url"):
+            extra['thumb_url'] = invitation_elt['thumb_url']
 
         for elt in invitation_elt.elements():
             if elt.uri != NS_INVITATION:
-                log.warning(u"unexpected element: {xml}".format(xml=elt.toXml()))
+                log.warning("unexpected element: {xml}".format(xml=elt.toXml()))
                 continue
-            if elt.name == u"pubsub":
+            if elt.name == "pubsub":
                 method = self._parsePubsubElt
-            elif elt.name == u"file_sharing":
+            elif elt.name == "file_sharing":
                 method = self._parseFileSharingElt
             else:
-                log.warning(u"not implemented invitation element: {xml}".format(
+                log.warning("not implemented invitation element: {xml}".format(
                     xml = elt.toXml()))
                 continue
             try:
                 namespace, args = yield method(client, elt)
             except exceptions.DataError:
-                log.warning(u"Can't parse invitation element: {xml}".format(
+                log.warning("Can't parse invitation element: {xml}".format(
                             xml = elt.toXml()))
                 continue
 
@@ -256,14 +256,14 @@
                 cb = self._ns_cb[namespace]
             except KeyError:
                 log.warning(_(
-                    u'No handler for namespace "{namespace}", invitation ignored')
+                    'No handler for namespace "{namespace}", invitation ignored')
                     .format(namespace=namespace))
             else:
                 cb(client, name, extra, *args)
 
 
+@implementer(iwokkel.IDisco)
 class PubsubInvitationHandler(XMPPHandler):
-    implements(iwokkel.IDisco)
 
     def __init__(self, plugin_parent):
         self.plugin_parent = plugin_parent