|
| 1 | +# SPDX-FileCopyrightText: 2023 Michal Pokusa |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Unlicense |
| 4 | +import os |
| 5 | +import re |
| 6 | + |
| 7 | +import socketpool |
| 8 | +import wifi |
| 9 | + |
| 10 | +from adafruit_httpserver import Server, Request, Response, FileResponse |
| 11 | + |
| 12 | +try: |
| 13 | + from adafruit_templateengine import render_template |
| 14 | +except ImportError as e: |
| 15 | + raise ImportError("This example requires adafruit_templateengine library.") from e |
| 16 | + |
| 17 | + |
| 18 | +pool = socketpool.SocketPool(wifi.radio) |
| 19 | +server = Server(pool, "/static", debug=True) |
| 20 | + |
| 21 | +# Create /static directory if it doesn't exist |
| 22 | +try: |
| 23 | + os.listdir("/static") |
| 24 | +except OSError as e: |
| 25 | + raise OSError("Please create a /static directory on the CIRCUITPY drive.") from e |
| 26 | + |
| 27 | + |
| 28 | +def is_file(path: str): |
| 29 | + return (os.stat(path.rstrip("/"))[0] & 0b_11110000_00000000) == 0b_10000000_00000000 |
| 30 | + |
| 31 | + |
| 32 | +@server.route("/") |
| 33 | +def directory_listing(request: Request): |
| 34 | + path = request.query_params.get("path", "").replace("%20", " ") |
| 35 | + |
| 36 | + # Preventing path traversal by removing all ../ from path |
| 37 | + path = re.sub(r"\/(\.\.)\/|\/(\.\.)|(\.\.)\/", "/", path).strip("/") |
| 38 | + |
| 39 | + # If path is a file, return it as a file response |
| 40 | + if is_file(f"/static/{path}"): |
| 41 | + return FileResponse(request, path) |
| 42 | + |
| 43 | + items = sorted( |
| 44 | + [ |
| 45 | + item + ("" if is_file(f"/static/{path}/{item}") else "/") |
| 46 | + for item in os.listdir(f"/static/{path}") |
| 47 | + ], |
| 48 | + key=lambda item: not item.endswith("/"), |
| 49 | + ) |
| 50 | + |
| 51 | + # Otherwise, return a directory listing |
| 52 | + return Response( |
| 53 | + request, |
| 54 | + render_template( |
| 55 | + "directory_listing.tpl.html", |
| 56 | + context={"path": path, "items": items}, |
| 57 | + ), |
| 58 | + content_type="text/html", |
| 59 | + ) |
| 60 | + |
| 61 | + |
| 62 | +# Start the server. |
| 63 | +server.serve_forever(str(wifi.radio.ipv4_address)) |
0 commit comments