changeset 1579:5db55d01ce05

browser (bridge): workaround to fix unicode dumping of JSON: in Brython 3.11, emoji are broken when dumped/parsed with `ensure_ascii`, and using `ensure_ascii=False` is not working (see https://github.com/brython-dev/brython/issues/2331). This work around this and https://github.com/brython-dev/brython/issues/2332 to make sure that emoji are transmitted correctly to other tabs.
author Goffi <goffi@goffi.org>
date Wed, 22 Nov 2023 16:31:36 +0100 (12 months ago)
parents c57133362fb7
children 08342aca8c1e
files libervia/web/pages/_browser/bridge.py
diffstat 1 files changed, 14 insertions(+), 8 deletions(-) [+]
line wrap: on
line diff
--- a/libervia/web/pages/_browser/bridge.py	Wed Nov 22 16:31:36 2023 +0100
+++ b/libervia/web/pages/_browser/bridge.py	Wed Nov 22 16:31:36 2023 +0100
@@ -102,7 +102,7 @@
         self.socket.send(json.dumps({
             "type": data_type,
             "data": data
-        }))
+        }, ensure_ascii=False))
 
     def close(self) -> None:
         log.debug("closing socket")
@@ -175,7 +175,6 @@
         # set of all known tab ids
         self.tabs_ids = {tab_id}
         self.post("salut_a_vous", {
-            "id": tab_id,
             "profile": self.profile
         })
         window.bind("unload", self.on_unload)
@@ -201,9 +200,7 @@
         if connecting:
             if self.ws is None:
                 self.ws = WebSocket(self)
-                self.post("connection", {
-                    "tab_id": tab_id
-                })
+                self.post("connection", {})
                 aio.run(self._wait_for_ws())
 
         elif self.ws is not None:
@@ -233,6 +230,8 @@
 
     def on_message(self, evt) -> None:
         data = json.loads(evt.data)
+        # FIXME: we convert back to int, see FIXME in [post] for details
+        data["id"] = int(data["id"])
         if data["type"] == "bridge":
             self.handle_bridge_signal(data)
         elif data["type"] == "salut_a_toi":
@@ -285,9 +284,16 @@
             log.warning(f"unknown message type: {data}")
 
     def post(self, data_type, data: dict):
-        data["type"] = data_type
-        data["id"] = tab_id
-        self.bc.postMessage(json.dumps(data))
+        data["type"] = str(data_type)
+        # FIXME: for some reason, JSON.stringify fail when a random.randint is used with
+        #   Brython 3.11 . See https://github.com/brython-dev/brython/issues/2332,
+        #   workaround may be removed once fixed version is used.
+        data["id"] = str(tab_id)
+        # FIXME: json.dumps doesn't support "ensure_ascii=False" and fails to correctly
+        #   dump emoji. See https://github.com/brython-dev/brython/issues/2331, workaround
+        #   may be removed once fixed version is used.
+        dumped = javascript.JSON.stringify(data)
+        self.bc.postMessage(dumped)
         if data_type == "bridge":
             self.handle_bridge_signal(data)