changeset 2625:a55a14c3cbf4

plugin XEP-0070: use a confirm dialog instead of a form + simplified a bit the code
author Goffi <goffi@goffi.org>
date Wed, 27 Jun 2018 21:15:34 +0200 (2018-06-27)
parents 56f94936df1e
children 6ef2b4fa90a5
files sat/plugins/plugin_xep_0070.py sat/tools/xml_tools.py
diffstat 2 files changed, 58 insertions(+), 80 deletions(-) [+]
line wrap: on
line diff
--- a/sat/plugins/plugin_xep_0070.py	Wed Jun 27 20:14:46 2018 +0200
+++ b/sat/plugins/plugin_xep_0070.py	Wed Jun 27 21:15:34 2018 +0200
@@ -95,43 +95,21 @@
         auth_method = auth_elt["method"]
         auth_url = auth_elt["url"]
         self._dictRequest[client] = (auth_id, auth_method, auth_url, stanzaType, elt)
+        title = D_(u"Auth confirmation")
+        message = D_(u"{auth_url} needs to validate your identity, do you agree?\n"
+                     u"Validation code : {auth_id}\n\n"
+                     u"Please check that this code is the same as on {auth_url}"
+                    ).format(auth_url=auth_url, auth_id=auth_id)
+        d = xml_tools.deferConfirm(self.host, message=message, title=title,
+            profile=client.profile)
+        d.addCallback(self._authRequestCallback, client)
 
-        confirm_ui = xml_tools.XMLUI("form", title=D_(u"Auth confirmation"), submit_id="")
-        confirm_ui.addText(
-            D_(u"{} needs to validate your identity, do you agree ?".format(auth_url))
-        )
-        confirm_ui.addText(D_(u"Validation code : {}".format(auth_id)))
-        confirm_ui.addText(
-            D_(u"Please check that this code is the same as on {}".format(auth_url))
-        )
-        confirm_ui.addText(u"")
-        confirm_ui.addText(D_(u"Submit to authorize, cancel otherwise."))
-        d = xml_tools.deferredUI(self.host, confirm_ui, chained=False)
-        d.addCallback(self._authRequestCallback, client.profile)
-        self.host.actionNew({u"xmlui": confirm_ui.toXml()}, profile=client.profile)
-
-    def _authRequestCallback(self, result, profile):
-        client = self.host.getClient(profile)
+    def _authRequestCallback(self, authorized, client):
         try:
-            cancelled = result["cancelled"]
+            auth_id, auth_method, auth_url, stanzaType, elt = self._dictRequest.pop(
+                client)
         except KeyError:
-            cancelled = False
-
-        authorized = False
-
-        if cancelled:
-            auth_id, auth_method, auth_url, stanzaType, elt = self._dictRequest[client]
-            del self._dictRequest[client]
             authorized = False
-        else:
-            try:
-                auth_id, auth_method, auth_url, stanzaType, elt = self._dictRequest[
-                    client
-                ]
-                del self._dictRequest[client]
-                authorized = True
-            except KeyError:
-                authorized = False
 
         if authorized:
             if stanzaType == IQ:
--- a/sat/tools/xml_tools.py	Wed Jun 27 20:14:46 2018 +0200
+++ b/sat/tools/xml_tools.py	Wed Jun 27 21:15:34 2018 +0200
@@ -51,7 +51,8 @@
     """Get data needed to create an XMLUI's Widget from Wokkel's data_form's Field.
 
     The attribute field can be modified (if it's fixed and it has no value).
-    @param field (data_form.Field): a field with attributes "value", "fieldType", "label" and "var"
+    @param field (data_form.Field): a field with attributes "value", "fieldType",
+                                    "label" and "var"
     @param read_only (bool): if True and it makes sense, create a read only input widget
     @return: a tuple (widget_type, widget_args, widget_kwargs)
     """
@@ -749,7 +750,8 @@
         @param selectable: one of:
             'no': nothing is done
             'single': one row can be selected
-        @param auto_index: if True, indexes will be generated by frontends, starting from 0
+        @param auto_index: if True, indexes will be generated by frontends,
+                           starting from 0
         @return: created element
         """
         assert selectable in ("no", "single")
@@ -1049,7 +1051,8 @@
         @param xmlui
         @param options (list[option]): each option can be given as:
             - a single string if the label and the value are the same
-            - a tuple with a couple of string (value,label) if the label and the value differ
+            - a tuple with a couple of string (value,label) if the label and the
+              value differ
         @param selected (list[string]): list of the selected values
         @param styles (iterable[string]): flags to set the behaviour of the list
             can be:
@@ -1058,7 +1061,8 @@
                     useful when only the list itself is needed
                 - extensible: can be extended by user (i.e. new options can be added)
                 - reducible: can be reduced by user (i.e. options can be removed)
-                - inline: hint that this list should be displayed on a single line (e.g. list of labels)
+                - inline: hint that this list should be displayed on a single line
+                          (e.g. list of labels)
         @param name (string)
         @param parent
         """
@@ -1070,7 +1074,8 @@
         if u"noselect" in styles and (u"multi" in styles or selected):
             raise exceptions.DataError(
                 _(
-                    u'"multi" flag and "selected" option are not compatible with "noselect" flag'
+                    u'"multi" flag and "selected" option are not compatible with '
+                    u'"noselect" flag'
                 )
             )
         if not options:
@@ -1210,21 +1215,15 @@
 class XMLUI(object):
     """This class is used to create a user interface (form/window/parameters/etc) using SàT XML"""
 
-    def __init__(
-        self,
-        panel_type="window",
-        container="vertical",
-        dialog_opt=None,
-        title=None,
-        submit_id=None,
-        session_id=None,
-    ):
+    def __init__(self, panel_type="window", container="vertical", dialog_opt=None,
+        title=None, submit_id=None, session_id=None):
         """Init SàT XML Panel
 
         @param panel_type: one of
             - C.XMLUI_WINDOW (new window)
             - C.XMLUI_POPUP
-            - C.XMLUI_FORM (form, depend of the frontend, usually a panel with cancel/submit buttons)
+            - C.XMLUI_FORM (form, depend of the frontend, usually a panel with
+              cancel/submit buttons)
             - C.XMLUI_PARAM (parameters, presentation depend of the frontend)
             - C.XMLUI_DIALOG (one common dialog, presentation depend of frontend)
         @param container: disposition of elements, one of:
@@ -1233,18 +1232,26 @@
             - pairs: elements come on two aligned columns
               (usually one for a label, the next for the element)
             - label: associations of one LabelWidget or EmptyWidget with an other widget
-                similar to pairs but specialized in LabelWidget, and not necessarily arranged in 2 columns
+                similar to pairs but specialized in LabelWidget,
+                and not necessarily arranged in 2 columns
             - tabs: elemens are in categories with tabs (notebook)
-        @param dialog_opt: only used if panel_type == C.XMLUI_DIALOG. Dictionnary (string/string) where key can be:
+        @param dialog_opt: only used if panel_type == C.XMLUI_DIALOG.
+            Dictionnary (string/string) where key can be:
             - C.XMLUI_DATA_TYPE: type of dialog, value can be:
-                - C.XMLUI_DIALOG_MESSAGE (default): an information/error message. Action of user is necessary to close the dialog. Usually the frontend display a classic popup
-                - C.XMLUI_DIALOG_NOTE: like a C.XMLUI_DIALOG_MESSAGE, but action of user is not necessary to close, at frontend choice (it can be closed after a timeout). Usually the frontend display as a timed out notification
+                - C.XMLUI_DIALOG_MESSAGE (default): an information/error message.
+                  Action of user is necessary to close the dialog.
+                  Usually the frontend display a classic popup.
+                - C.XMLUI_DIALOG_NOTE: like a C.XMLUI_DIALOG_MESSAGE, but action of user
+                  is not necessary to close, at frontend choice (it can be closed after
+                  a timeout). Usually the frontend display as a timed out notification
                 - C.XMLUI_DIALOG_CONFIRM: dialog with 2 choices (usualy "Ok"/"Cancel").
                     returned data can contain:
-                        - "answer": "true" if answer is "ok", "yes" or equivalent, "false" else
+                        - "answer": "true" if answer is "ok", "yes" or equivalent,
+                                    "false" else
                 - C.XLMUI_DIALOG_FILE: a file selection dialog
                     returned data can contain:
-                        - "cancelled": "true" if dialog has been cancelled, not present or "false" else
+                        - "cancelled": "true" if dialog has been cancelled, not present
+                                       or "false" else
                         - "path": path of the choosed file/dir
             - C.XMLUI_DATA_MESS: message shown in dialog
             - C.XMLUI_DATA_LVL: one of:
@@ -1252,16 +1259,20 @@
                 - C.XMLUI_DATA_LVL_WARNING: attention of user is important
                 - C.XMLUI_DATA_LVL_ERROR: something went wrong
             - C.XMLUI_DATA_BTNS_SET: one of:
-                - C.XMLUI_DATA_BTNS_SET_OKCANCEL (default): classical "OK" and "Cancel" set
-                - C.XMLUI_DATA_BTNS_SET_YESNO: a translated "yes" for OK, and "no" for Cancel
+                - C.XMLUI_DATA_BTNS_SET_OKCANCEL (default): classical "OK" and "Cancel"
+                  set
+                - C.XMLUI_DATA_BTNS_SET_YESNO: a translated "yes" for OK, and "no" for
+                  Cancel
             - C.XMLUI_DATA_FILETYPE: only used for file dialogs, one of:
                 - C.XMLUI_DATA_FILETYPE_FILE: a file path is requested
                 - C.XMLUI_DATA_FILETYPE_DIR: a dir path is requested
                 - C.XMLUI_DATA_FILETYPE_DEFAULT: same as C.XMLUI_DATA_FILETYPE_FILE
 
         @param title: title or default if None
-        @param submit_id: callback id to call for panel_type we can submit (form, param, dialog)
-        @param session_id: use to keep a session attached to the dialog, must be returned by frontends
+        @param submit_id: callback id to call for panel_type we can submit (form, param,
+                          dialog)
+        @param session_id: use to keep a session attached to the dialog, must be
+                           returned by frontends
         @attribute named_widgets(dict): map from name to widget
         """
         self._introspect()  # FIXME: why doing that on each XMLUI ? should be done once
@@ -1505,14 +1516,8 @@
     return xmlui_d
 
 
-def deferXMLUI(
-    host,
-    xmlui,
-    action_extra=None,
-    security_limit=C.NO_SECURITY_LIMIT,
-    chained=False,
-    profile=C.PROF_KEY_NONE,
-):
+def deferXMLUI(host, xmlui, action_extra=None, security_limit=C.NO_SECURITY_LIMIT,
+    chained=False, profile=C.PROF_KEY_NONE):
     """Create a deferred linked to XMLUI
 
     @param xmlui(XMLUI): instance of the XMLUI
@@ -1538,23 +1543,16 @@
     return xmlui_d
 
 
-def deferDialog(
-    host,
-    message,
-    title=u"Please confirm",
-    type_=C.XMLUI_DIALOG_CONFIRM,
-    options=None,
-    action_extra=None,
-    security_limit=C.NO_SECURITY_LIMIT,
-    chained=False,
-    profile=C.PROF_KEY_NONE,
-):
+def deferDialog(host, message, title=u"Please confirm", type_=C.XMLUI_DIALOG_CONFIRM,
+    options=None, action_extra=None, security_limit=C.NO_SECURITY_LIMIT, chained=False,
+    profile=C.PROF_KEY_NONE):
     """Create a submitable dialog and manage it with a deferred
 
     @param message(unicode): message to display
     @param title(unicode): title of the dialog
     @param type(unicode): dialog type (C.XMLUI_DIALOG_*)
-    @param options(None, dict): if not None, will be used to update (extend) dialog_opt arguments of XMLUI
+    @param options(None, dict): if not None, will be used to update (extend) dialog_opt
+                                arguments of XMLUI
     @param action_extra(None, dict): extra action to merge with xmlui
         mainly used to add meta informations (see actionNew doc)
     @param security_limit: %(doc_security_limit)s
@@ -1601,8 +1599,10 @@
     def __call__(self, raw_xml, force_spaces=False, namespace=None):
         """
         @param raw_xml(unicode): the raw XML
-        @param force_spaces (bool): if True, replace occurrences of '\n' and '\t' with ' '.
-        @param namespace(unicode, None): if set, use this namespace for the wrapping element
+        @param force_spaces (bool): if True, replace occurrences of '\n' and '\t'
+                                    with ' '.
+        @param namespace(unicode, None): if set, use this namespace for the wrapping
+                                         element
         """
         # we need to wrap element in case
         # there is not a unique one on the top