diff sat/plugins/plugin_xep_0050.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 a8c2d8b3453f
children 9d0df638c8b4
line wrap: on
line diff
--- a/sat/plugins/plugin_xep_0050.py	Wed Jul 31 11:31:22 2019 +0200
+++ b/sat/plugins/plugin_xep_0050.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 for Ad-Hoc Commands (XEP-0050)
@@ -32,7 +32,7 @@
 from uuid import uuid4
 from sat.tools import xml_tools
 
-from zope.interface import implements
+from zope.interface import implementer
 
 try:
     from twisted.words.protocols.xmlstream import XMPPHandler
@@ -71,7 +71,7 @@
     C.PI_PROTOCOLS: ["XEP-0050"],
     C.PI_MAIN: "XEP_0050",
     C.PI_HANDLER: "yes",
-    C.PI_DESCRIPTION: _(u"""Implementation of Ad-Hoc Commands"""),
+    C.PI_DESCRIPTION: _("""Implementation of Ad-Hoc Commands"""),
 }
 
 
@@ -84,8 +84,8 @@
         self.callback_error = error_const
 
 
+@implementer(iwokkel.IDisco)
 class AdHocCommand(XMPPHandler):
-    implements(iwokkel.IDisco)
 
     def __init__(self, callback, label, node, features, timeout,
                  allowed_jids, allowed_groups, allowed_magics, forbidden_jids,
@@ -130,7 +130,7 @@
             try:
                 allowed.update(self.client.roster.getJidsFromGroup(group))
             except exceptions.UnknownGroupError:
-                log.warning(_(u"The groups [{group}] is unknown for profile [{profile}])")
+                log.warning(_("The groups [{group}] is unknown for profile [{profile}])")
                             .format(group=group, profile=self.client.profile))
         if requestor.userhostJID() in allowed:
             return True
@@ -204,7 +204,7 @@
         xmpp_condition, cmd_condition = error_constant
         iq_elt = jabber.error.StanzaError(xmpp_condition).toResponse(request)
         if cmd_condition:
-            error_elt = iq_elt.elements(None, "error").next()
+            error_elt = next(iq_elt.elements(None, "error"))
             error_elt.addElement(cmd_condition, NS_COMMANDS)
         self.client.send(iq_elt)
         del self.sessions[session_id]
@@ -293,7 +293,7 @@
             in_sign="sss",
             out_sign="s",
             method=self._run,
-            async=True,
+            async_=True,
         )
         host.bridge.addMethod(
             "adHocList",
@@ -301,7 +301,7 @@
             in_sign="ss",
             out_sign="s",
             method=self._listUI,
-            async=True,
+            async_=True,
         )
         self.__requesting_id = host.registerCallback(
             self._requestingEntity, with_data=True
@@ -312,7 +312,7 @@
             security_limit=2,
             help_string=D_("Execute ad-hoc commands"),
         )
-        host.registerNamespace(u'commands', NS_COMMANDS)
+        host.registerNamespace('commands', NS_COMMANDS)
 
     def getHandler(self, client):
         return XEP_0050_handler(self)
@@ -354,9 +354,9 @@
 
     def getCommandElt(self, iq_elt):
         try:
-            return iq_elt.elements(NS_COMMANDS, "command").next()
+            return next(iq_elt.elements(NS_COMMANDS, "command"))
         except StopIteration:
-            raise exceptions.NotFound(_(u"Missing command element"))
+            raise exceptions.NotFound(_("Missing command element"))
 
     def adHocError(self, error_type):
         """Shortcut to raise an AdHocError
@@ -389,7 +389,7 @@
             return C.XMLUI_DATA_LVL_WARNING
         else:
             if type_ != "info":
-                log.warning(_(u"Invalid note type [%s], using info") % type_)
+                log.warning(_("Invalid note type [%s], using info") % type_)
             return C.XMLUI_DATA_LVL_INFO
 
     def _mergeNotes(self, notes):
@@ -403,7 +403,7 @@
             C.XMLUI_DATA_LVL_WARNING: "%s: " % _("WARNING"),
             C.XMLUI_DATA_LVL_ERROR: "%s: " % _("ERROR"),
         }
-        return [u"%s%s" % (lvl_map[lvl], msg) for lvl, msg in notes]
+        return ["%s%s" % (lvl_map[lvl], msg) for lvl, msg in notes]
 
     def _commandsAnswer2XMLUI(self, iq_elt, session_id, session_data):
         """Convert command answer to an ui for frontend
@@ -429,7 +429,7 @@
             notes.append(
                 (
                     self._getDataLvl(note_elt.getAttribute("type", "info")),
-                    unicode(note_elt),
+                    str(note_elt),
                 )
             )
         for data_elt in command_elt.elements(data_form.NS_X_DATA, "x"):
@@ -461,7 +461,7 @@
                 C.XMLUI_DIALOG,
                 dialog_opt={
                     C.XMLUI_DATA_TYPE: C.XMLUI_DIALOG_NOTE,
-                    C.XMLUI_DATA_MESS: u"\n".join(self._mergeNotes(notes)),
+                    C.XMLUI_DATA_MESS: "\n".join(self._mergeNotes(notes)),
                     C.XMLUI_DATA_LVL: dlg_level,
                 },
                 session_id=session_id,
@@ -565,7 +565,7 @@
             status = XEP_0050.STATUS.EXECUTING
             form = data_form.Form("form", title=_("status selection"))
             show_options = [
-                data_form.Option(name, label) for name, label in SHOWS.items()
+                data_form.Option(name, label) for name, label in list(SHOWS.items())
             ]
             field = data_form.Field(
                 "list-single", "show", options=show_options, required=True
@@ -578,7 +578,7 @@
         elif len(actions) == 2:
             # we should have the answer here
             try:
-                x_elt = command_elt.elements(data_form.NS_X_DATA, "x").next()
+                x_elt = next(command_elt.elements(data_form.NS_X_DATA, "x"))
                 answer_form = data_form.Form.fromElement(x_elt)
                 show = answer_form["show"]
             except (KeyError, StopIteration):
@@ -593,7 +593,7 @@
             # job done, we can end the session
             status = XEP_0050.STATUS.COMPLETED
             payload = None
-            note = (self.NOTE.INFO, _(u"Status updated"))
+            note = (self.NOTE.INFO, _("Status updated"))
         else:
             self.adHocError(XEP_0050.ERROR.INTERNAL)
 
@@ -730,24 +730,24 @@
     def onCmdRequest(self, request, client):
         request.handled = True
         requestor = jid.JID(request["from"])
-        command_elt = request.elements(NS_COMMANDS, "command").next()
+        command_elt = next(request.elements(NS_COMMANDS, "command"))
         action = command_elt.getAttribute("action", self.ACTION.EXECUTE)
         node = command_elt.getAttribute("node")
         if not node:
-            client.sendError(request, u"bad-request")
+            client.sendError(request, "bad-request")
             return
         sessionid = command_elt.getAttribute("sessionid")
         commands = client._XEP_0050_commands
         try:
             command = commands[node]
         except KeyError:
-            client.sendError(request, u"item-not-found")
+            client.sendError(request, "item-not-found")
             return
         command.onRequest(command_elt, requestor, action, sessionid)
 
 
+@implementer(iwokkel.IDisco)
 class XEP_0050_handler(XMPPHandler):
-    implements(iwokkel.IDisco)
 
     def __init__(self, plugin_parent):
         self.plugin_parent = plugin_parent
@@ -772,7 +772,7 @@
         ret = []
         if nodeIdentifier == NS_COMMANDS:
             commands = self.client._XEP_0050_commands
-            for command in commands.values():
+            for command in list(commands.values()):
                 if command.isAuthorised(requestor):
                     ret.append(
                         disco.DiscoItem(self.parent.jid, command.node, command.getName())