]> git.mar77i.info Git - hublib/commitdiff
clean up master_ws_uri templating
authormar77i <mar77i@protonmail.ch>
Thu, 3 Aug 2023 23:47:26 +0000 (01:47 +0200)
committermar77i <mar77i@protonmail.ch>
Thu, 3 Aug 2023 23:47:26 +0000 (01:47 +0200)
hub/app.py
hub/hub.py
hub/staticresource.py
hubapps/first/master.html.tpl

index 8dfb5425b704c111d87513354b6965f1578ca98f..c5c92476178ff7409e6a003c37362adef04fd805 100644 (file)
@@ -22,10 +22,11 @@ class HubApp(App):
         super().__init__(*args, **kwargs)
         self.secret = secret or token_urlsafe(64)
         self.hub = Hub(self.secret)
-        self.sr = StaticResource(self.secret, hubapp, self.hub.master_ws_uri)
+        self.sr = StaticResource(self.secret, hubapp)
         self.browser = browser
         self.hub.add_routes(self)
         self.sr.add_routes(self)
+        self.hub.update_context_vars(self.sr.context_vars)
         self.add_error_handler(Exception, self.print_exception)
 
     async def print_exception(self, req, resp, ex, params):
index 0eee3f845cbfdf610166e9e2183a05a606b1a5a8..da78e1f27b57bc31a50b7cce0f4dfcb3b296b753 100644 (file)
@@ -100,3 +100,6 @@ class Hub:
     def add_routes(self, app):
         app.add_route("/ws", self)
         app.add_route(self.master_ws_uri, self, suffix="master")
+
+    def update_context_vars(self, context_vars):
+        context_vars["master_ws_uri"] = self.master_ws_uri
index 9cc949ae7d54b9f974abfb11d579e0c65d798dba..e1e86dd633b50cc0d9eb4368f22ee11aed1f6045 100644 (file)
@@ -1,3 +1,4 @@
+from io import BytesIO
 import json
 import mimetypes
 import os
@@ -8,6 +9,9 @@ from .utils import scramble
 
 class StaticFile:
     template_ext = ".tpl"
+    template_filters = {
+        b"tojson": lambda value: json.dumps(value)
+    }
 
     def __init__(self, path):
         self.path = path
@@ -19,18 +23,32 @@ class StaticFile:
         with open(self.path, "rb") as fh:
             return fh.read()
 
-    def get(self):
-        if self.path.stat().st_mtime != self.mtime:
-            self.content = self.load_content()
-        return self.content
-
-    def render(self, context_vars):
-        content = self.get()
+    def get(self, context_vars):
+        content = self.load_content() if self.path.stat().st_mtime != self.mtime else self.content
         if self.path.suffix == self.template_ext:
-            for k, v in context_vars.items():
-                content = content.replace(b"{{ %s }}" % k.encode(), v.encode())
+            content = self.render(content, context_vars)
+        self.content = content
         return content
 
+    def render(self, content, context_vars):
+        bio = BytesIO()
+        pos = 0
+        while True:
+            new_pos = content.find(b"{{", pos)
+            if new_pos < 0:
+                break
+            bio.write(content[pos:new_pos])
+            end_pos = content.find(b"}}", new_pos)
+            assert end_pos > 0
+            full_tag = content[new_pos + 2:end_pos].split(b"|", 1)
+            value = context_vars[full_tag[0].strip().decode()]
+            if len(full_tag) == 2:
+                value = self.template_filters[full_tag[1].strip()](value)
+            bio.write(value.encode())
+            pos = end_pos + 2
+        bio.write(content[pos:])
+        return bio.getvalue()
+
     def __str__(self):
         return f"<StaticFile at \"{os.sep.join(self.path.parts[-2:])}\" [{self.mime_type}]>"
 
@@ -42,15 +60,10 @@ class StaticFile:
 
 
 class StaticResource:
-    def __init__(self, secret, current_hubapp, master_ws_uri):
+    def __init__(self, secret, current_hubapp):
         mimetypes.init()
-        hub_js_path = Path(__file__).parent / "hub.js"
-        self.static_files = {
-            "/hub.js": StaticFile(hub_js_path),
-        }
-        self.context_vars = {
-            "master_ws_uri": json.dumps(master_ws_uri),
-        }
+        self.static_files = {}
+        self.context_vars = {}
         self.master_uri = ""
         self.setup(secret, current_hubapp)
 
@@ -75,7 +88,7 @@ class StaticResource:
         if path == "/":
             path = index_uri
         res = self.static_files[path]
-        resp.data = res.render(self.context_vars)
+        resp.data = res.get(self.context_vars)
         resp.content_type = res.mime_type
 
     def add_routes(self, app):
index 7a00c9361b48fc39c523d2b7c49e726c77de6c6f..11ed0b16799c83d3e83fcd7d8ab14f05f77d6079 100644 (file)
@@ -11,7 +11,7 @@
        <script src="common.js"></script>
     <script src="hub.js"></script>
        <script type="text/javascript">
-         var ws_uri = {{ master_ws_uri }};
+         var ws_uri = {{ master_ws_uri|tojson }};
        </script>
        <script src="{{ master_js }}"></script>
   </body>