aboutsummaryrefslogtreecommitdiff
path: root/middleware
diff options
context:
space:
mode:
authorBobby <[email protected]>2024-07-22 19:17:21 -0400
committerBobby <[email protected]>2024-07-22 19:17:21 -0400
commit5e5080d1ae600d88170633ae1ed7c655a32ebf76 (patch)
treeee01c5d22ca052353bef6fa8979078f4b1f98bda /middleware
parent96af3e213bcfd3e38bfdd3b1e763eed389de6cbe (diff)
downloadthatcomputerscientist-5e5080d1ae600d88170633ae1ed7c655a32ebf76.tar.xz
thatcomputerscientist-5e5080d1ae600d88170633ae1ed7c655a32ebf76.zip
Ignis Middleware
Diffstat (limited to 'middleware')
-rw-r--r--middleware/ignismiddleware.py46
1 files changed, 46 insertions, 0 deletions
diff --git a/middleware/ignismiddleware.py b/middleware/ignismiddleware.py
new file mode 100644
index 00000000..b7a7b932
--- /dev/null
+++ b/middleware/ignismiddleware.py
@@ -0,0 +1,46 @@
+# Ignis Middleware
+# Scans all 'img' links
+# if they start with '/ignis/<rest of the path>' > replaces them with env 'ignis.IGNIS_CACHE_ENDPOINT/<rest of the path>'
+# if they start with '/static/<rest of the path>' > replaces them with env 'static.INGIS_STATIC_ENDPOINT/<rest of the path>'
+
+import os
+import re
+from django.utils.deprecation import MiddlewareMixin
+from bs4 import BeautifulSoup
+from dotenv import load_dotenv
+
+load_dotenv()
+
+IGNIS_CACHE_ENDPOINT = os.getenv("IGNIS_CACHE_ENDPOINT")
+IGNIS_CACHE_PROTOCOL = os.getenv("IGNIS_CACHE_PROTOCOL")
+
+DYNAMIC_ENDPOINT = f"{IGNIS_CACHE_PROTOCOL}://ignis.{IGNIS_CACHE_ENDPOINT}"
+STATIC_ENDPOINT = f"{IGNIS_CACHE_PROTOCOL}://static.{IGNIS_CACHE_ENDPOINT}"
+
+
+class IgnisMiddleware(MiddlewareMixin):
+ def __init__(self, get_response):
+ self.get_response = get_response
+
+ def __call__(self, request):
+ response = self.get_response(request)
+
+ # Do not process non-HTML responses
+ if not response["Content-Type"].startswith("text/html"):
+ return response
+
+ response.content = self.process_response(response)
+ return response
+
+ def process_response(self, response):
+ content = response.content.decode("utf-8")
+ soup = BeautifulSoup(content, "html.parser")
+
+ for image in soup.find_all("img"):
+ src = image.get("src")
+ if src.startswith("/ignis/"):
+ image["src"] = f"{DYNAMIC_ENDPOINT}{src[6:]}"
+ elif src.startswith("/static/"):
+ image["src"] = f"{STATIC_ENDPOINT}{src[7:]}"
+
+ return str(soup)