tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

static_handler.py (1779B)


      1 # mypy: allow-untyped-defs
      2 
      3 import os
      4 
      5 
      6 class StaticHandler:
      7    def __init__(self, web_root, http_port, https_port):
      8        self.static_dir = os.path.join(
      9            os.getcwd(), "tools/wave/www")
     10        self._web_root = web_root
     11        self._http_port = http_port
     12        self._https_port = https_port
     13 
     14    def handle_request(self, request, response):
     15        file_path = request.request_path
     16 
     17        if self._web_root is not None:
     18            if not file_path.startswith(self._web_root):
     19                response.status = 404
     20                return
     21            file_path = file_path[len(self._web_root):]
     22 
     23        if file_path == "":
     24            file_path = "index.html"
     25 
     26        file_path = file_path.split("?")[0]
     27        file_path = os.path.join(self.static_dir, file_path)
     28 
     29        if not os.path.exists(file_path):
     30            response.status = 404
     31            return
     32 
     33        headers = []
     34 
     35        content_types = {
     36            "html": "text/html",
     37            "js": "text/javascript",
     38            "css": "text/css",
     39            "jpg": "image/jpeg",
     40            "jpeg": "image/jpeg",
     41            "ttf": "font/ttf",
     42            "woff": "font/woff",
     43            "woff2": "font/woff2"
     44        }
     45 
     46        headers.append(
     47            ("Content-Type", content_types[file_path.split(".")[-1]]))
     48 
     49        data = None
     50        with open(file_path, "rb") as file:
     51            data = file.read()
     52 
     53        if file_path.split("/")[-1] == "wave-service.js":
     54            data = data.decode("UTF-8")
     55            data = data.replace("{{WEB_ROOT}}", str(self._web_root))
     56            data = data.replace("{{HTTP_PORT}}", str(self._http_port))
     57            data = data.replace("{{HTTPS_PORT}}", str(self._https_port))
     58 
     59        response.content = data
     60        response.headers = headers