File size: 1,883 Bytes
ddcb2ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""Static server for local checks, plus POST /capture to save a canvas frame.

The browser can render a WebGL scene but cannot hand the pixels back to this
machine, and its downloads land somewhere unreachable. So the page posts the data
URL here and the frame lands on disk, where it can actually be looked at.

    python dev_server.py [port]
    fetch('/capture', {method:'POST', body: canvas.toDataURL('image/jpeg', 0.6)})
"""
import base64
import os
import sys
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer

ROOT = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(ROOT, "captures")


class Handler(SimpleHTTPRequestHandler):
    def do_POST(self):
        if self.path.split("?")[0] != "/capture":
            self.send_error(404)
            return
        length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(length).decode("utf-8", "replace")
        header, _, payload = body.partition(",")
        ext = "png" if "png" in header else "jpg"
        name = self.headers.get("X-Name") or "capture"
        os.makedirs(OUT, exist_ok=True)
        path = os.path.join(OUT, f"{name}.{ext}")
        with open(path, "wb") as f:
            f.write(base64.b64decode(payload))
        print(f"[capture] {path} ({os.path.getsize(path)} bytes)", flush=True)
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.end_headers()
        self.wfile.write(path.encode())

    def end_headers(self):
        self.send_header("Cache-Control", "no-store")
        super().end_headers()

    def log_message(self, *args):
        pass


if __name__ == "__main__":
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8140
    os.chdir(ROOT)
    print(f"serving {ROOT} on http://127.0.0.1:{port}", flush=True)
    ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()