]> git.mar77i.info Git - hublib/blob - hub/staticresource.py
functioning basic chat app
[hublib] / hub / staticresource.py
1 import json
2 import mimetypes
3 import os
4 from pathlib import Path
5
6 from .utils import scramble
7
8
9 class StaticFile:
10 template_ext = ".tpl"
11
12 def __init__(self, path):
13 self.path = path
14 self.mime_type = mimetypes.guess_type(self.remove_template_ext(str(path)))[0]
15 self.mtime = None
16 self.content = None
17
18 def load_content(self):
19 with open(self.path, "rb") as fh:
20 return fh.read()
21
22 def get(self):
23 if self.path.stat().st_mtime != self.mtime:
24 self.content = self.load_content()
25 return self.content
26
27 def render(self, context_vars):
28 content = self.get()
29 if self.path.suffix == self.template_ext:
30 for k, v in context_vars.items():
31 content = content.replace(b"{{ %s }}" % k.encode(), v.encode())
32 return content
33
34 def __str__(self):
35 return f"<StaticFile at \"{os.sep.join(self.path.parts[-2:])}\" [{self.mime_type}]>"
36
37 @classmethod
38 def remove_template_ext(cls, filename):
39 if filename.endswith(cls.template_ext):
40 filename = filename[:-4]
41 return filename
42
43
44 class StaticResource:
45 def __init__(self, secret, current_hubapp, master_ws_uri):
46 mimetypes.init()
47 hub_js_path = Path(__file__).parent / "hub.js"
48 self.static_files = {
49 "/hub.js": StaticFile(hub_js_path),
50 }
51 self.context_vars = {
52 "master_ws_uri": json.dumps(master_ws_uri),
53 }
54 self.master_uri = ""
55 self.setup(secret, current_hubapp)
56
57 def setup(self, secret, current_hubapp):
58 hubapp_dir = Path(__file__).parents[1] / "hubapps" / current_hubapp
59 for file in os.listdir(hubapp_dir):
60 uri_file = StaticFile.remove_template_ext(file)
61 if uri_file.startswith("master."):
62 uri = f"/{scramble(secret, uri_file)}"
63 if uri_file == "master.html":
64 self.master_uri = uri
65 self.context_vars[uri_file.replace(".", "_")] = uri
66 else:
67 uri = f"/{uri_file}"
68 self.static_files[uri] = StaticFile(hubapp_dir / file)
69 if uri_file == "index.html":
70 self.static_files["/"] = self.static_files[uri]
71
72 async def on_get(self, req, resp):
73 path = req.path
74 index_uri = f"/index.html"
75 if path == "/":
76 path = index_uri
77 res = self.static_files[path]
78 resp.data = res.render(self.context_vars)
79 resp.content_type = res.mime_type
80
81 def add_routes(self, app):
82 for uri_template in self.static_files:
83 app.add_route(uri_template, self)