diff --git a/dragonpilot/selfdrive/fileserv/fileserv.py b/dragonpilot/selfdrive/fileserv/fileserv.py new file mode 100644 index 000000000..94b4982a5 --- /dev/null +++ b/dragonpilot/selfdrive/fileserv/fileserv.py @@ -0,0 +1,308 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +''' +MIT Non-Commercial License + +Copyright (c) 2019, dragonpilot + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, for non-commercial purposes only, subject to the following conditions: + +- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. +- Commercial use (e.g., use in a product, service, or activity intended to generate revenue) is prohibited without explicit written permission from dragonpilot. Contact ricklan@gmail.com for inquiries. +- Any project that uses the Software must visibly mention the following acknowledgment: "This project uses software from dragonpilot and is licensed under a custom license requiring permission for use." + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +''' + +import os +import signal +import threading +import socket +import math +from datetime import datetime +from urllib.parse import urlparse, parse_qs, quote + + +HOST = '0.0.0.0' +PORT = 5000 + +# --- Dynamic Path Configuration --- +DEFAULT_DIR = os.path.realpath('/data/media/0/realdata') +SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) +STATIC_DIR = os.path.join(SCRIPT_DIR, 'static') + + +def get_safe_path(base_dir, requested_path): + """Joins the requested path with a base directory and ensures it's safe.""" + normalized_req_path = os.path.normpath(requested_path.lstrip('/')) + combined_path = os.path.join(base_dir, normalized_req_path) + safe_path = os.path.realpath(combined_path) + if safe_path.startswith(os.path.realpath(base_dir)): + return safe_path + return None + +def format_file_size(size_bytes): + """Formats a file size in bytes to a human-readable string (B, KB, MB, GB).""" + if size_bytes == 0: + return "0 B" + size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") + i = int(math.floor(math.log(size_bytes, 1024))) + p = math.pow(1024, i) + s = round(size_bytes / p, 1) + return f"{s} {size_name[i]}" + +def list_directory(client_socket, path): + try: + if not os.path.isdir(path): + response = "HTTP/1.1 404 Not Found\r\n\r\n" + client_socket.sendall(response.encode()) + return + + items = [] + for entry in os.listdir(path): + full_path = os.path.join(path, entry) + try: + stat = os.stat(full_path) + is_dir = os.path.isdir(full_path) + items.append({ + 'name': entry, + 'is_dir': is_dir, + 'mtime': datetime.fromtimestamp(stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S'), + 'size': stat.st_size if not is_dir else 0 + }) + except FileNotFoundError: + continue + + items.sort(key=lambda x: (not x['is_dir'], x['name'].lower())) + + # --- HTML and CSS for the page --- + content = """ + + +
+ + +| Name | Last Modified | |
|---|---|---|
| .. (Parent Directory) | ||
| {actions_cell} | " + content += f"{item['name']} | " + content += f"{item['mtime']} | " + content += f"" + content += f"
{e}
" + client_socket.sendall(response.encode()) + +def serve_static_file(client_socket, file_path): + """Serves a static file from the filesystem.""" + mime_types = { + '.js': 'application/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + } + ext = os.path.splitext(file_path)[1].lower() + content_type = mime_types.get(ext, 'application/octet-stream') + try: + with open(file_path, 'rb') as f: + body = f.read() + headers = f"HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\nContent-Length: {len(body)}\r\n\r\n" + client_socket.sendall(headers.encode()) + client_socket.sendall(body) + except FileNotFoundError: + client_socket.sendall(b"HTTP/1.1 404 Not Found\r\n\r\nFile Not Found") + except Exception: + client_socket.sendall(b"HTTP/1.1 500 Internal Server Error\r\n\r\nError reading file") + +def serve_player(client_socket, file_path): + """Serves an HTML page with an HLS video player for .ts files.""" + encoded_path = quote(file_path) + # The