#!/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 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) # test(CORSRequestHandler, HTTPServer, port=port) httpd = HTTPServer(server_address, CORSRequestHandler) certfile = "ssl/localhost+4.pem" keyfile = "ssl/localhost+4-key.pem" if not os.path.exists(certfile): print("using ssl/server.pm") certfile = "ssl/server.pem" if not os.path.exists(keyfile): print("using ssl/key.pm") keyfile = "ssl/key.pem" if os.path.exists(certfile) and os.path.exists(keyfile): httpd.socket = ssl.wrap_socket(httpd.socket, server_side=True, certfile=certfile, keyfile=keyfile, ssl_version=ssl.PROTOCOL_TLS) 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([f"../browser.sh", f"{protocol}://{open_host}:{port}/msdf-theatre.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", 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)