diff sat_pubsub/bookmark_compat.py @ 494:468b7cd6c344 default tip

bookmark compat: handle mapped errors: This convert error on request (e.g. missing node) to appropriate stanza error.
author Goffi <goffi@goffi.org>
date Fri, 13 Dec 2024 12:23:47 +0100
parents 4e8e8788bc86
children
line wrap: on
line diff
--- a/sat_pubsub/bookmark_compat.py	Wed Dec 11 01:19:46 2024 +0200
+++ b/sat_pubsub/bookmark_compat.py	Fri Dec 13 12:23:47 2024 +0100
@@ -27,6 +27,7 @@
 from wokkel.iwokkel import IPubSubService
 from zope.interface import implementer
 
+from sat_pubsub import backend
 from sat_pubsub import const
 
 from . import error
@@ -41,6 +42,7 @@
 
 @implementer(iwokkel.IDisco)
 class BookmarkCompatHandler(disco.DiscoClientProtocol):
+    error_map = backend.PubSubResourceFromBackend.error_map
 
     def __init__(self, service_jid):
         super().__init__()
@@ -55,6 +57,17 @@
         self.xmlstream.addObserver(IQ_PRIVATE_GET, self._on_get)
         self.xmlstream.addObserver(IQ_PRIVATE_SET, self._on_set)
 
+    def handle_mapped_error(self, e: error.Error, iq_elt: domish.Element) -> None:
+        condition, pubsub_condition, feature = self.error_map[e.__class__]  # type: ignore
+        msg = e.msg
+        if pubsub_condition:
+            exc = pubsub.PubSubError(condition, pubsub_condition, feature, msg)
+        else:
+            exc = jabber_error.StanzaError(condition, text=msg)
+        error_elt = exc.toResponse(iq_elt)
+        self.xmlstream.send(error_elt)
+        return
+
     def _on_get(self, iq_elt: domish.Element) -> None:
         """Handle incoming legacy IQ GET requests for bookmarks.
 
@@ -110,9 +123,13 @@
         """
         assert self.backend is not None
         assert self.xmlstream is not None
-        items, __ = await self.backend.getItems(
-            NS_BOOKMARKS2, requestor, requestor, ext_data={"pep": True}
-        )
+        try:
+            items, __ = await self.backend.getItems(
+                NS_BOOKMARKS2, requestor, requestor, ext_data={"pep": True}
+            )
+        except tuple(self.error_map.keys()) as e:
+            return self.handle_mapped_error(e, iq_elt)
+
         iq_result_elt = xmlstream.toResponse(iq_elt, "result")
 
         query_elt = iq_result_elt.addElement((NS_IQ_PRIVATE, "query"))
@@ -249,7 +266,10 @@
                 new_conference_elt.addChild(new_child)
             items.append(item_elt)
 
-        await self.publish_bookmarks(iq_elt, items, requestor)
+        try:
+            await self.publish_bookmarks(iq_elt, items, requestor)
+        except tuple(self.error_map.keys()) as e:
+            return self.handle_mapped_error(e, iq_elt)
 
         iq_result_elt = xmlstream.toResponse(iq_elt, "result")
         self.xmlstream.send(iq_result_elt)