Files
ac-server-scripts/ac-server-scripts-api.py
2025-11-16 15:56:57 +01:00

133 lines
4.5 KiB
Python

from http.server import HTTPServer, BaseHTTPRequestHandler
import os
import json
from urllib.parse import parse_qs
from change_track import change_track, get_all_tracks, get_configs, get_preview_image, get_outline_image
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if (self.handle_GET_path()):
return
self.send_error(404)
def do_POST(self):
if (self.handle_POST_path()):
return
self.send_error(404)
def handle_GET_path(self) -> bool:
"""
handles the path entered in the GET request.
Returns: true if the calling function should return, false otherwise
"""
# Serve preview images
if self.path.startswith("/img/"):
parts = self.path.split("/")
parts = [p for p in parts if p] # remove empty
img_type = parts[1] if len(parts) > 1 else ""
track, config = self.extract_track_and_config(parts)
img_path = ""
if (img_type == "preview"):
img_path = get_preview_image(track, config)
elif (img_type == "outline"):
img_path = get_outline_image(track, config)
else:
self.send_error(404)
return True
self.send_image(img_path)
return True
# JSON track info
if self.path.startswith("/track/"):
track = self.path.replace("/track/", "").strip("/")
configs = get_configs(track)
data = {
"track": track,
"configs": configs,
"image": f"/img/preview/{track}",
"outline": f"/img/outline/{track}"
}
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(data).encode())
return True
if self.path == "/" or self.path == "/index.html":
with open("index.html", "r") as f:
html = f.read()
tracks = get_all_tracks()
track_options = "".join([f'<option value="{t}">{t}</option>' for t in tracks])
html = html.replace("{{tracks}}", track_options)
html = html.replace("{{configs}}", "") # empty at load
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(html.encode())
return True
return False
def handle_POST_path(self):
if (self.path.startswith("/changetrack/")):
parts = self.path.split("/")
parts = [p for p in parts if p] # remove empty
track, config = self.extract_track_and_config(parts, 1)
print(f"Changing track to '{track}' with config '{config}'")
success, message = change_track(track, config)
print(message)
if success:
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
response = {"status": "success", "message": message}
self.wfile.write(json.dumps(response).encode())
return True
else:
self.send_response(400)
self.send_header("Content-type", "application/json")
self.end_headers()
response = {"status": "error", "message": message}
self.wfile.write(json.dumps(response).encode())
return True
return False
def send_image(self, img_path: str):
if os.path.exists(img_path):
self.send_response(200)
self.send_header("Content-type", "image/png")
self.end_headers()
with open(img_path, "rb") as f:
self.wfile.write(f.read())
else:
self.send_error(404)
def extract_track_and_config(self, parts: list, track_index: int = 2) -> tuple[str, str]:
print(parts)
track = parts[track_index] if len(parts) > track_index else ""
config = parts[track_index + 1] if len(parts) > track_index + 1 else ""
return track, config
server = HTTPServer(("0.0.0.0", 10303), Handler)
print("Server running on port 10303")
server.serve_forever()