#!/usr/bin/env python3 from http.server import HTTPServer, SimpleHTTPRequestHandler, test # type: ignore from pathlib import Path import os import sys import argparse import subprocess import ssl # openssl req -new -x509 -keyout ssl/key.pem -out ssl/server.pem -days 365 -nodes browser_cmd = "/usr/bin/chromium --screen=1 --disk-cache-dir=/dev/null --disk-cache-size=1 --enable-logging --password-store=basic --v=1" class CORSRequestHandler(SimpleHTTPRequestHandler): def end_headers(self): self.send_header("Cross-Origin-Opener-Policy", "same-origin") self.send_header("Cross-Origin-Embedder-Policy", "require-corp") self.send_header("Access-Control-Allow-Origin", "*") super().end_headers() def shell_open(url): if sys.platform == "win32": os.startfile(url) else: opener = "open" if sys.platform == "darwin" else "xdg-open" subprocess.call([opener, url]) def serve(root, port, run_browser): os.chdir(root) protocol = 'http' # will be upgraded if we have certfiles, see below open_host = 'localhost' # we serve on 0.0.0.0 for network, but open localhost host = '0.0.0.0' server_address = (host, port) httpd = HTTPServer(server_address, CORSRequestHandler) certfile = "ssl/localhost+4.pem" keyfile = "ssl/localhost+4-key.pem" if not os.path.exists(certfile): certfile = "ssl/server.pem" if not os.path.exists(keyfile): keyfile = "ssl/key.pem" print(f"using {certfile} and {keyfile} for ssl") if os.path.exists(certfile) and os.path.exists(keyfile): context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_cert_chain(certfile, keyfile) httpd.socket = context.wrap_socket(httpd.socket, server_side=True) protocol = 'https' if run_browser: # Open the served page in the user's default browser. print("Opening the served URL in the default browser (use `--no-browser` or `-n` to disable this).") subprocess.call(["pwd"]) subprocess.call([f"../../../browser.sh", f"{protocol}://{open_host}:{port}/index.html"]) print(f"serving on port {port}") httpd.serve_forever() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-p", "--port", help="port to listen on", default=8060, type=int) parser.add_argument( "-r", "--root", help="path to serve as root (relative to `platform/web/`)", default="./bin/em/variabletime", type=Path ) browser_parser = parser.add_mutually_exclusive_group(required=False) browser_parser.add_argument( "-n", "--no-browser", help="don't open default web browser automatically", dest="browser", action="store_false" ) parser.set_defaults(browser=True) args = parser.parse_args() # Change to the directory where the script is located, # so that the script can be run from any location. os.chdir(Path(__file__).resolve().parent) serve(args.root, args.port, args.browser)