auto-build pwa files, merge servers into serve.py, move helpers to lib Hunter Sunday, November 8th, 2026 at 6:07 PM
23 manifest.json 24 service-worker.js 25 -# Local HTTPS certs/keys minted by https_serve.py -.https_certs/ - 26 # Personal deployment script 27 push.py
-#!/usr/bin/env python3 -""" -Creates manifest.json and service-worker.js -(PWA requirements) based on the contents of tracks.json -""" - -import hashlib -import json -import re -from pathlib import Path - -# Bootstrap into the shared venv first thing (re-execs on first run), -# so scan.rescan() has mutagen available when we call it before building. -import scan -scan.bootstrap(__file__) - - -def get_configuration(): - """Prompt user for configuration values""" - print("=" * 60) - print("PWA Configuration") - print("=" * 60) - print() - - # Get app name - app_name = input("Enter a name for your mixapp: ").strip() - if not app_name: - print("Error: App name is required") - exit(1) - - # Get base path with smart default - default_path = app_name.lower().replace(" ", "_") - print() - print(f"Enter the deployment path (or press Return/Enter for default)") - print(f"Default: /{default_path}/") - base_path_input = input("Path: ").strip() - - if base_path_input: - # User provided a path - ensure it has leading/trailing slashes - base_path = base_path_input - if not base_path.startswith("/"): - base_path = "/" + base_path - if not base_path.endswith("/"): - base_path = base_path + "/" - else: - # Use default - base_path = f"/{default_path}/" - print(f"Using default path: {base_path}") - - print() - print(f"Configuration:") - print(f" App Name: {app_name}") - print(f" Base Path: {base_path}") - print() - - return app_name, base_path - -# File paths (no need to edit these) -SCRIPT_DIR = Path(__file__).parent.absolute() -TRACKS_JSON = SCRIPT_DIR / "mix" / "tracks.json" -STYLES_CSS = SCRIPT_DIR / "resources" / "styles.css" -CUSTOM_CSS = SCRIPT_DIR / "mix" / "custom.css" - - -def get_background_color(): - """Extract the --background CSS variable, preferring custom.css over styles.css""" - # Check custom.css first (overrides styles.css) - for css_file in [CUSTOM_CSS, STYLES_CSS]: - if not css_file.exists(): - continue - with open(css_file, 'r', encoding='utf-8') as f: - content = f.read() - match = re.search( - r'--background:\s*([#a-zA-Z0-9(),.\s]+?)\s*;', - content - ) - if match: - color = match.group(1).strip() - print(f"Found background color in {css_file.name}: {color}") - return color - - print("Warning: --background not found in any CSS file. Using default color.") - return "#080a0c" - - -def build_pwa(app_name=None, base_path=None): - """Generate manifest.json and service-worker.js based on tracks.json - - Args: - app_name: Name of the app. If None, will be prompted via get_configuration() - base_path: Base path for the app. If None, will be prompted via get_configuration() - """ - # Get configuration if not provided - if app_name is None or base_path is None: - app_name, base_path = get_configuration() - - # Derived values - short_name = app_name - cache_name = app_name - app_description = f"{app_name}" - - print("Building PWA files...") - print(f" Cache name: {cache_name}") - - # Rescan /mix so tracks.json reflects any additions/removals on disk - # before we snapshot it into the service worker's static file list. - scan.rescan(silent=True) - - if not TRACKS_JSON.exists(): - print("Error: tracks.json not found.") - return - - with open(TRACKS_JSON, 'r', encoding='utf-8') as f: - tracks = json.load(f) - - # Get background color from styles.css - background_color = get_background_color() - - # mix/album_art.jpg overrides the default - custom_album_art = SCRIPT_DIR / "mix" / "album_art.jpg" - album_art_file = custom_album_art if custom_album_art.exists() else SCRIPT_DIR / "resources" / "album_art.jpg" - album_art_path = "mix/album_art.jpg" if custom_album_art.exists() else "resources/album_art.jpg" - # append a content hash so the URL changes when the image changes - if album_art_file.exists(): - art_hash = hashlib.md5(album_art_file.read_bytes()).hexdigest()[:8] - album_art_path = f"{album_art_path}?v={art_hash}" - print(f" Album art: {album_art_path}") - - # mix/icon.png overrides the default - custom_icon = SCRIPT_DIR / "mix" / "icon.png" - icon_file = custom_icon if custom_icon.exists() else SCRIPT_DIR / "resources" / "icon.png" - icon_path = "mix/icon.png" if custom_icon.exists() else "resources/icon.png" - # append a content hash so the URL changes when the image changes - if icon_file.exists(): - icon_hash = hashlib.md5(icon_file.read_bytes()).hexdigest()[:8] - icon_path = f"{icon_path}?v={icon_hash}" - print(f" Icon: {icon_path}") - - # Generate manifest.json - manifest = { - "id": base_path, - "name": app_name, - "short_name": short_name, - "description": app_description, - "start_url": base_path, - "scope": base_path, - "display": "standalone", - "background_color": background_color, - "theme_color": background_color, - "cache_name": cache_name, # Custom field for script.js to use - "album_art": album_art_path, # Custom field for script.js to use - "icons": [ - { - "src": f"{base_path}{icon_path}", - "sizes": "640x640", - "type": "image/png", - "purpose": "any maskable" - } - ] - } - - with open(SCRIPT_DIR / "manifest.json", 'w', encoding='utf-8') as f: - json.dump(manifest, f, indent=2) - print("✓ Generated manifest.json") - - # Build static files list for service worker - static_files = [ - "./", - "index.html", - "manifest.json", - "resources/styles.css", - "resources/script.js", - "mix/tracks.json", - icon_path, - album_art_path, - "resources/play.svg", - "resources/pause.svg", - "resources/prev.svg", - "resources/next.svg", - "resources/repeat.svg", - "resources/fonts/Basteleur/Basteleur-Moonlight.woff2", - ] - - AUDIO_EXTS = {".mp3", ".m4a", ".ogg", ".flac", ".wav"} - # album_art.jpg and icon.png added explicitly above with a hash; skip to avoid a bare dupe - SKIP_NAMES = {"tracks.json", "readme.md", "album_art.jpg", "icon.png"} - for path in sorted((SCRIPT_DIR / "mix").iterdir()): - if not path.is_file(): - continue - if path.name in SKIP_NAMES: - continue - if path.suffix.lower() in AUDIO_EXTS: - continue - static_files.append(f"mix/{path.name}") - - static_files_js = json.dumps(static_files) - audio_pattern = "|".join(sorted(ext[1:] for ext in AUDIO_EXTS)) - - # Generate service-worker.js - service_worker_content = f'''// Auto-generated service worker for {app_name} PWA -const CACHE_NAME = '{cache_name}'; - -// Get the base path from the service worker location -const getBasePath = () => {{ - const swPath = self.location.pathname; - return swPath.substring(0, swPath.lastIndexOf('/') + 1); -}}; - -const basePath = getBasePath(); - -// Static files to cache on install -const STATIC_FILES = {static_files_js}; -const AUDIO_FILE = /\\.({audio_pattern})$/i; - -// Install event - cache static resources only if not already cached. -// This makes installs immutable: once a file is in the cache, redeploys -// will not overwrite it, so the app stays frozen at its first-installed version. -// Audio files will be cached by the main app's blob preloading system. -self.addEventListener('install', (event) => {{ - console.log('Service Worker installing...', 'Base path:', basePath); - self.skipWaiting(); - event.waitUntil( - caches.open(CACHE_NAME).then(cache => {{ - const absoluteUrls = STATIC_FILES.map(url => {{ - if (url === './') return new URL(basePath, self.location.href).href; - return new URL(url, new URL(basePath, self.location.href)).href; - }}); - - return Promise.allSettled( - absoluteUrls.map(url => - cache.match(url).then(existing => {{ - if (existing) {{ - console.log('• Already cached, skipping:', url); - return; - }} - return fetch(url, {{ cache: 'no-cache' }}) - .then(response => {{ - if (!response.ok) {{ - throw new Error(`HTTP error! status: ${{response.status}}`); - }} - return cache.put(url, response); - }}) - .then(() => console.log('✓ Cached:', url)) - .catch(err => {{ - console.error('✗ Failed to cache:', url, err); - throw err; - }}); - }}) - ) - ).then(results => {{ - const failed = results.filter(r => r.status === 'rejected'); - console.log(`Install complete: ${{results.length - failed.length}}/${{results.length}} ok`); - }}); - }}).catch(error => {{ - console.error('Service Worker installation failed:', error); - }}) - ); -}}); - -self.addEventListener('activate', (event) => {{ - event.waitUntil(self.clients.claim()); -}}); - -// Network fetch capped with a timeout. A mixapp installed off the LAN points -// at a private-IP origin that's usually gone by launch time; without a cap an -// uncached request hangs on a TCP timeout and stalls startup (black→white -// screen). Aborting fast turns that hang into an ordinary cache-miss failure. -const fetchWithTimeout = (request, ms = 2000) => {{ - const controller = new AbortController(); - const timer = setTimeout(() => controller.abort(), ms); - return fetch(request, {{ signal: controller.signal }}) - .finally(() => clearTimeout(timer)); -}}; - -// Fetch event - cache first, network fallback -self.addEventListener('fetch', (event) => {{ - // Ignore non-http(s) requests like blob: URLs, data: URLs, chrome-extension:, etc. - if (!event.request.url.startsWith('http')) {{ - return; - }} - - event.respondWith( - caches.match(event.request) - .then((cachedResponse) => {{ - if (cachedResponse) {{ - console.log('✓ Serving from cache:', event.request.url); - return cachedResponse; - }} - - // Navigation that missed the exact cache key: serve the cached - // app shell so the document always renders from cache, online - // or off, even if the launch URL doesn't byte-match a key. - if (event.request.mode === 'navigate') {{ - const shellUrl = new URL(basePath, self.location.href).href; - return caches.match(shellUrl) - .then(shell => shell || caches.match('index.html')) - .then(shell => shell || fetchWithTimeout(event.request)); - }} - - // Not in cache - try network (time-boxed; see fetchWithTimeout) - console.log('⟳ Fetching from network:', event.request.url); - return fetchWithTimeout(event.request) - .then((networkResponse) => {{ - // Check if valid response - if (!networkResponse || networkResponse.status !== 200 || networkResponse.type === 'error') {{ - return networkResponse; - }} - - if (AUDIO_FILE.test(new URL(event.request.url).pathname)) {{ - return networkResponse; - }} - - // Clone and cache for future offline use - const responseToCache = networkResponse.clone(); - caches.open(CACHE_NAME) - .then((cache) => {{ - cache.put(event.request, responseToCache); - console.log('✓ Cached from network:', event.request.url); - }}) - .catch(err => console.error('Failed to cache:', err)); - - return networkResponse; - }}) - .catch((error) => {{ - console.error('✗ Network fetch failed for:', event.request.url, error); - throw error; - }}); - }}) - ); -}}); -''' - - with open(SCRIPT_DIR / "service-worker.js", 'w', encoding='utf-8') as f: - f.write(service_worker_content) - print("✓ Generated service-worker.js") - print() - print("PWA build complete!") - - -if __name__ == "__main__": - # When run directly, get configuration and build PWA files - app_name, base_path = get_configuration() - build_pwa(app_name, base_path)
13 14 # Hop into the shared venv (managed by scan.py) before doing anything else, 15 # so scan.rescan() has mutagen available when we call it after a purchase. -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) 16 +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) 17 import scan 18 scan.bootstrap(__file__) 19
-#!/usr/bin/env python3 -""" -Serve a mixapp over HTTPS on your local network so you can install it as a PWA -without a public web host or tunnel. - -Uses mkcert to mint a locally-trusted certificate for this machine's LAN IP. A -device won't trust that cert until it trusts mkcert's root CA, so we print -two QR codes: - - 1. an HTTP link that hands the device the mkcert root CA (the public root - cert, no secret; served to any device until you stop the script) - 2. an HTTPS link to the mixapp itself, for PWA installation - -Both servers shut down together on Ctrl+C. - -After scanning the first QR code, install + trust the CA on the device: - iOS: Settings → General → VPN & Device Management → install the profile, - then Settings → General → About → Certificate Trust Settings → - enable full trust - Android: open the downloaded file and follow the prompt to install it as a - CA certificate - -Run with --reset to revoke the CA and delete the local certificates. -""" - -import http.server -import socketserver -import socket -import ssl -import sys -import os -import json -import subprocess -import threading -from pathlib import Path - -import serve # reuse serve.py's track-management backend (TrackRequestHandler, SSE, etc.) - -CERT_HTTP_PORT = 8001 # preferred; falls back to the next free port -HTTPS_PORT = 8443 # preferred; falls back to the next free port -SCRIPT_DIR = Path(__file__).parent.absolute() -CERT_DIR = Path.home() / ".mixapps" / "https_certs" -CERT_FILE = CERT_DIR / "cert.pem" -KEY_FILE = CERT_DIR / "key.pem" -MANIFEST_FILE = SCRIPT_DIR / "manifest.json" - -# Path the phone fetches the root CA from. Anything else over HTTP 404s. -CA_DOWNLOAD_PATH = "/rootCA.pem" - - -def manifest_base_path(): - """The base path the PWA was built for (manifest scope/start_url). - The installed app launches here, so we must serve the project under - it or the standalone window 404s. Defaults to '/'.""" - try: - manifest = json.loads(MANIFEST_FILE.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError): - return "/" - base = manifest.get("scope") or manifest.get("start_url") or "/" - if not base.startswith("/"): - base = "/" + base - if not base.endswith("/"): - base = base + "/" - return base - - -def run_in_venv(): - """Re-run this script in the shared venv with qrcode available, - forwarding any user flags (eg. --reset) to the re-exec.""" - import scan - # mutagen: serve.py's upload path reads tags to canonicalize filenames. - python_path = scan.setup_venv(packages=("qrcode", "mutagen")) - try: - subprocess.check_call([str(python_path), __file__, "--in-venv", *sys.argv[1:]]) - except (KeyboardInterrupt, subprocess.CalledProcessError): - pass - sys.exit(0) - - -def get_local_ip(): - """Get the LAN IP other devices on the network can reach this machine at.""" - try: - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - s.connect(("8.8.8.8", 80)) - local_ip = s.getsockname()[0] - s.close() - return local_ip - except Exception: - return None - - -def find_available_port(start_port, max_attempts=20): - """Return the first bindable port at or after start_port. Uses SO_REUSEADDR - so a socket lingering in TIME_WAIT from a prior run doesn't block us.""" - for port in range(start_port, start_port + max_attempts): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - try: - s.bind(("", port)) - return port - except OSError: - continue - finally: - s.close() - return None - - -def print_qr_code(url, caption): - """Generate and print a QR code using block characters.""" - try: - import qrcode - - qr = qrcode.QRCode( - version=1, - error_correction=qrcode.constants.ERROR_CORRECT_L, - box_size=1, - border=1, - ) - qr.add_data(url) - qr.make(fit=True) - - matrix = qr.get_matrix() - - print(f"\n{caption}\n") - for y in range(0, len(matrix), 2): - line = " " - for x in range(len(matrix[y])): - top = matrix[y][x] - bottom = matrix[y + 1][x] if y + 1 < len(matrix) else False - if top and bottom: - line += "█" - elif top: - line += "▀" - elif bottom: - line += "▄" - else: - line += " " - print(line) - except ImportError: - print(f"\n{caption}\n (QR unavailable; open this URL manually) {url}") - except Exception as e: - print(f"\nCould not generate QR code: {e}\n open manually: {url}") - - -def mkcert_install_command(): - """Best-guess (command, package-manager-label) to install mkcert on this - platform, or (None, None) if no known manager is on PATH.""" - from shutil import which - if sys.platform == "darwin": - if which("brew"): - return (["brew", "install", "mkcert"], "Homebrew") - elif sys.platform == "win32": - if which("choco"): - return (["choco", "install", "mkcert", "-y"], "Chocolatey") - if which("scoop"): - return (["scoop", "install", "mkcert"], "Scoop") - else: # linux / other unix - # Most distros package mkcert; pick whichever manager is present. - if which("apt"): - return (["sudo", "apt", "install", "-y", "mkcert"], "apt") - if which("dnf"): - return (["sudo", "dnf", "install", "-y", "mkcert"], "dnf") - if which("pacman"): - return (["sudo", "pacman", "-S", "--noconfirm", "mkcert"], "pacman") - if which("brew"): - return (["brew", "install", "mkcert"], "Homebrew") - return (None, None) - - -def manual_install_hint(): - """Platform-appropriate manual install instructions for mkcert.""" - if sys.platform == "darwin": - return "brew install mkcert (https://github.com/FiloSottile/mkcert)" - if sys.platform == "win32": - return "choco install mkcert OR scoop install mkcert (https://github.com/FiloSottile/mkcert)" - return "install 'mkcert' via your package manager (https://github.com/FiloSottile/mkcert)" - - -def require_mkcert(): - """Ensure mkcert is on PATH, offering to install it if it isn't.""" - from shutil import which - if which("mkcert") is not None: - return - - print("mkcert is required but was not found on PATH.") - cmd, label = mkcert_install_command() - if cmd is None: - print(f" Install it manually: {manual_install_hint()}") - sys.exit(1) - - answer = input(f"Install it now with {label} ({' '.join(cmd)})? [y/N] ").strip().lower() - if answer not in ("y", "yes"): - print(f" Install it manually: {manual_install_hint()}") - sys.exit(1) - - try: - subprocess.check_call(cmd) - except (subprocess.CalledProcessError, KeyboardInterrupt): - print(f"\nInstall failed. Install it manually: {manual_install_hint()}") - sys.exit(1) - - if which("mkcert") is None: - print("mkcert still not on PATH after install. Open a new terminal and retry.") - sys.exit(1) - - -def ca_root_file(): - """Path to mkcert's root CA cert (rootCA.pem).""" - caroot = subprocess.run( - ["mkcert", "-CAROOT"], capture_output=True, text=True - ).stdout.strip() - return Path(caroot) / "rootCA.pem" - - -def ensure_ca_installed(): - """Ensure mkcert's local CA exists and is trusted by this machine. - May prompt for your password to write to the system trust store.""" - if not ca_root_file().exists(): - print("Setting up mkcert local CA (you may be prompted for your password)...") - subprocess.check_call(["mkcert", "-install"]) - - -def ensure_leaf_cert(local_ip): - """Mint a cert/key for this machine's LAN IP (and localhost) if missing - or minted for a different IP.""" - CERT_DIR.mkdir(parents=True, exist_ok=True) - if CERT_FILE.exists() and KEY_FILE.exists(): - try: - sans = ssl._ssl._test_decode_cert(str(CERT_FILE)).get("subjectAltName", ()) - except (AttributeError, OSError): - print("Couldn't read the existing certificate.") - else: - old_ips = [v for k, v in sans if k == "IP Address" and v != "127.0.0.1"] - if local_ip in old_ips: - return - print(f"This machine's LAN IP changed ({', '.join(old_ips)} → {local_ip}).") - print(f"Minting certificate for {local_ip}...") - subprocess.check_call([ - "mkcert", - "-cert-file", str(CERT_FILE), - "-key-file", str(KEY_FILE), - local_ip, "localhost", "127.0.0.1", - ]) - - -def start_ca_server(local_ip): - """Start a plain-HTTP server that hands out the mkcert root CA, and return - it running. The CA is the *public* root cert (no secret), so there's no - reason to limit how many times or to how many devices it's served. leave - it up alongside the HTTPS server so you can set up multiple devices, and - tear both down together on Ctrl+C. Caller owns shutdown.""" - ca_file = ca_root_file() - if not ca_file.exists(): - print(f"Error: root CA not found at {ca_file}") - sys.exit(1) - - ca_bytes = ca_file.read_bytes() - - class CAHandler(http.server.BaseHTTPRequestHandler): - def log_message(self, *args): - pass - - def do_GET(self): - # Redirect bare visits to the download path so a typo'd / still works. - if self.path in ("/", "/index.html"): - self.send_response(302) - self.send_header("Location", CA_DOWNLOAD_PATH) - self.end_headers() - return - if self.path != CA_DOWNLOAD_PATH: - self.send_error(404) - return - # x-x509-ca-cert makes iOS offer to install it as a CA profile. - self.send_response(200) - self.send_header("Content-Type", "application/x-x509-ca-cert") - self.send_header("Content-Length", str(len(ca_bytes))) - self.send_header( - "Content-Disposition", 'attachment; filename="rootCA.pem"' - ) - self.end_headers() - try: - self.wfile.write(ca_bytes) - except (BrokenPipeError, ConnectionResetError): - return - - port = find_available_port(CERT_HTTP_PORT) - if port is None: - print(f"Error: no free port near {CERT_HTTP_PORT} for the CA server.") - sys.exit(1) - http.server.HTTPServer.allow_reuse_address = True - httpd = http.server.HTTPServer(("", port), CAHandler) - threading.Thread(target=httpd.serve_forever, daemon=True).start() - - cert_url = f"http://{local_ip}:{port}{CA_DOWNLOAD_PATH}" - print("=" * 69) - print("STEP 1: install + trust the local CA on each device (first time only)") - print("=" * 69) - print_qr_code(cert_url, "Scan to download the root certificate:") - print(f" {cert_url}") - print("\nOn iOS, after downloading:") - print(" • Settings → General → VPN & Device Management → install the profile") - print(" • Settings → General → About → Certificate Trust Settings →") - print(" toggle ON full trust for the mkcert CA") - print("\nOn Android, after downloading:") - print(" • open the downloaded file, or Settings → Security → Encryption &") - print(" credentials → Install a certificate → CA certificate, then confirm") - print(" • installing the CA is what makes it trusted; there's no separate") - print(" trust toggle (exact menu names vary by version/manufacturer)") - print("\n(skip this step on a device that already trusts the CA from a previous run)") - return httpd - - -class TLSThreadingServer(socketserver.ThreadingTCPServer): - """Threading server that negotiates TLS in the worker thread, so - handshakes run in parallel.""" - daemon_threads = True - allow_reuse_address = True - # default backlog of 5 drops connections when a device precaches in bursts - request_queue_size = 128 - - def __init__(self, server_address, handler_cls, ssl_context): - self.ssl_context = ssl_context - super().__init__(server_address, handler_cls) - - def process_request_thread(self, request, client_address): - try: - request.settimeout(20) # cap how long a dead client's handshake lingers - request = self.ssl_context.wrap_socket(request, server_side=True) - request.settimeout(None) - except (ssl.SSLError, OSError): - # Untrusted CA, a probe, or a client that walked away. - self.shutdown_request(request) - return - super().process_request_thread(request, client_address) - - -def serve_https(local_ip, base_path, ca_httpd=None): - """Serve SCRIPT_DIR over HTTPS for PWA installation, mounted under - base_path so the installed app's start_url resolves. Runs until Ctrl+C, - then also shuts down the CA HTTP server (if given).""" - os.chdir(SCRIPT_DIR) - - # Rescan /mix periodically so edits made on disk reach connected browser - # tabs over the SSE stream, same as serve.py. - serve.start_rescan_ticker() - - # Subclass serve.py's handler so editing works over HTTPS too: it adds the - # SSE change stream (/events), reorder save (POST /tracks), drag-drop - # upload (PUT /upload/<name>), and delete (DELETE /tracks/<name>). Those - # endpoints are root-absolute, so base_path stripping (GET-only) doesn't - # touch them. - class QuietHandler(serve.TrackRequestHandler): - def end_headers(self): - self.send_header("Cache-Control", "no-cache") - super().end_headers() - - def log_message(self, *args): - pass - - def handle(self): - try: - super().handle() - except (BrokenPipeError, ConnectionResetError, ssl.SSLError): - pass - - def translate_path(self, path): - # Strip the manifest base prefix so /mixapp_name/foo maps to ./foo. - if base_path != "/" and path.startswith(base_path): - path = "/" + path[len(base_path):] - return super().translate_path(path) - - def do_GET(self): - # Bounce a bare root visit into the app so manual navigation works. - if base_path != "/" and self.path in ("/", "/index.html"): - self.send_response(302) - self.send_header("Location", base_path) - self.send_header("Content-Length", "0") - self.end_headers() - return - # super() is serve.TrackRequestHandler.do_GET, which handles - # /events (SSE) and rescans on /mix/tracks.json before serving. - return super().do_GET() - - ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) - ctx.load_cert_chain(certfile=str(CERT_FILE), keyfile=str(KEY_FILE)) - - port = find_available_port(HTTPS_PORT) - if port is None: - print(f"Error: no free port near {HTTPS_PORT} for the HTTPS server.") - if ca_httpd is not None: - ca_httpd.shutdown() - ca_httpd.server_close() - sys.exit(1) - - with TLSThreadingServer(("", port), QuietHandler, ctx) as httpd: - https_url = f"https://{local_ip}:{port}{base_path}" - - print("\n" + "=" * 59) - print("STEP 2: install your mixapp (once the device trusts the CA)") - print("=" * 59) - print_qr_code(https_url, "Scan to open your mixapp over HTTPS:") - print(f" {https_url}") - print("\nThen install it as a PWA: https://hunterirving.github.io/web_workshop/pages/pwa") - print("\nPress Ctrl+C to stop the server(s)") - - try: - httpd.serve_forever() - except KeyboardInterrupt: - print("\n\nShutting down...") - finally: - if ca_httpd is not None: - ca_httpd.shutdown() - ca_httpd.server_close() - - -def caroot_dir(): - """Path to mkcert's CAROOT folder (holds rootCA.pem and rootCA-key.pem).""" - caroot = subprocess.run( - ["mkcert", "-CAROOT"], capture_output=True, text=True - ).stdout.strip() - return Path(caroot) if caroot else None - - -def reset_certs(): - """Opt-in teardown, in two stages so it's safe alongside other mkcert use. - - mkcert keeps ONE shared CA per machine, so anything else you run with - mkcert trusts the same CA. Stage 1 removes only THIS tool's own leaf certs - (always safe). Stage 2 removes the shared mkcert CA itself (untrust + optional - key deletion). Guarded, because it affects every project that uses - mkcert, not just this one.""" - from shutil import rmtree, which - - # Stage 1: our own leaf certs. - if CERT_DIR.exists(): - rmtree(CERT_DIR) - print(f"Removed this tool's local certificates ({CERT_DIR}).") - else: - print("No local certificates to remove.") - - # Stage 2: the shared mkcert CA. Skip entirely unless asked, since other - # projects on this machine may rely on it and we can't detect them. - print( - "\nThe mkcert CA itself is SHARED across everything you use mkcert for" - " on this computer, not just this tool. Leaving it installed is normal." - ) - answer = input( - "Also remove the shared mkcert CA (untrust it system-wide)? [y/N] " - ).strip().lower() - if answer not in ("y", "yes"): - print("Left the mkcert CA in place.") - return - - if which("mkcert"): - try: - subprocess.check_call(["mkcert", "-uninstall"]) - print("Stopped this computer from trusting the mkcert CA.") - except subprocess.CalledProcessError as e: - print(f"mkcert -uninstall failed: {e}") - - # mkcert -uninstall removes trust but does NOT delete the CA. The private key - # (rootCA-key.pem) is the sensitive material, so offer to delete it too, with - # a separate confirmation since it's irreversible and shared. - caroot = caroot_dir() - if caroot and (caroot / "rootCA-key.pem").exists(): - print( - "\nThe CA's PRIVATE KEY is still on disk at:\n" - f" {caroot}\n" - "Per mkcert: \"the rootCA-key.pem file ... gives complete power to\n" - "intercept secure requests from your machine. Do not share it.\"\n" - "Deleting it removes the shared CA entirely; future mkcert use\n" - "(here or in any project) will generate a brand-new one." - ) - ans2 = input("Delete the CA key + folder now? [y/N] ").strip().lower() - if ans2 in ("y", "yes"): - rmtree(caroot) - print(f"Removed {caroot}") - else: - print("Left the CA key in place.") - - print("\nNote: this does NOT touch any device; remove or untrust the CA\n" - "there separately (see the instructions printed during install).") - - -def start(): - require_mkcert() - - local_ip = get_local_ip() - if not local_ip: - print("Error: could not determine this machine's LAN IP.") - print("Make sure you're connected to a network and try again.") - sys.exit(1) - - base_path = manifest_base_path() - if not MANIFEST_FILE.exists(): - print("Warning: manifest.json not found. Run ./build.py first so the\n" - "PWA is installable. Serving at root for now.\n") - - ensure_ca_installed() - ensure_leaf_cert(local_ip) - ca_httpd = start_ca_server(local_ip) - serve_https(local_ip, base_path, ca_httpd=ca_httpd) - - -def main(): - if "--in-venv" not in sys.argv: - run_in_venv() - else: - try: - if "--reset" in sys.argv: - reset_certs() - else: - start() - except KeyboardInterrupt: - print("\nCancelled.") - sys.exit(130) - - -if __name__ == "__main__": - main()
1 +#!/usr/bin/env python3 2 +""" 3 +Creates manifest.json and service-worker.js 4 +(PWA requirements) based on the contents of /mix. 5 +serve.py runs this automatically. 6 +""" 7 + 8 +import hashlib 9 +import json 10 +import re 11 +from pathlib import Path 12 + 13 +import scan 14 + 15 +DEFAULT_NAME = "mixapp" 16 + 17 + 18 +def shared_album(): 19 + """The album tag every track in /mix shares, or None""" 20 + try: 21 + from mutagen import File as MutagenFile # type: ignore 22 + except ImportError: 23 + return None 24 + albums = set() 25 + for path in MIX_DIR.iterdir(): 26 + if path.suffix.lower() not in scan.SUPPORTED_EXTENSIONS: 27 + continue 28 + try: 29 + audio = MutagenFile(path, easy=True) 30 + except Exception: 31 + return None 32 + album = audio.tags.get('album', [None])[0] if audio and audio.tags else None 33 + if not album: 34 + return None 35 + albums.add(album.strip()) 36 + return albums.pop() if len(albums) == 1 else None 37 + 38 + 39 +def mix_name(): 40 + """mix/name.txt if present, else the album every track shares, else DEFAULT_NAME""" 41 + if NAME_FILE.exists(): 42 + name = NAME_FILE.read_text(encoding='utf-8').strip() 43 + if name: 44 + return name 45 + return shared_album() or DEFAULT_NAME 46 + 47 + 48 +# File paths (no need to edit these) 49 +ROOT_DIR = Path(__file__).parent.parent.absolute() 50 +MIX_DIR = ROOT_DIR / "mix" 51 +NAME_FILE = MIX_DIR / "name.txt" 52 +TRACKS_JSON = ROOT_DIR / "mix" / "tracks.json" 53 +STYLES_CSS = ROOT_DIR / "resources" / "styles.css" 54 +CUSTOM_CSS = ROOT_DIR / "mix" / "custom.css" 55 + 56 + 57 +def get_background_color(log): 58 + """Extract the --background CSS variable, preferring custom.css over styles.css""" 59 + # Check custom.css first (overrides styles.css) 60 + for css_file in [CUSTOM_CSS, STYLES_CSS]: 61 + if not css_file.exists(): 62 + continue 63 + with open(css_file, 'r', encoding='utf-8') as f: 64 + content = f.read() 65 + match = re.search( 66 + r'--background:\s*([#a-zA-Z0-9(),.\s]+?)\s*;', 67 + content 68 + ) 69 + if match: 70 + color = match.group(1).strip() 71 + log(f"Found background color in {css_file.name}: {color}") 72 + return color 73 + 74 + log("Warning: --background not found in any CSS file. Using default color.") 75 + return "#080a0c" 76 + 77 + 78 +def build_pwa(silent=False): 79 + """Generate manifest.json and service-worker.js from /mix. Returns the mix name.""" 80 + log = (lambda *args: None) if silent else print 81 + app_name = mix_name() 82 + 83 + # Derived values 84 + short_name = app_name 85 + cache_name = app_name 86 + app_description = f"{app_name}" 87 + 88 + log("Building PWA files...") 89 + log(f" Cache name: {cache_name}") 90 + 91 + # Rescan /mix so tracks.json reflects any additions/removals on disk 92 + # before we snapshot it into the service worker's static file list. 93 + scan.rescan(silent=True) 94 + 95 + if not TRACKS_JSON.exists(): 96 + log("Error: tracks.json not found.") 97 + return 98 + 99 + with open(TRACKS_JSON, 'r', encoding='utf-8') as f: 100 + tracks = json.load(f) 101 + 102 + # Get background color from styles.css 103 + background_color = get_background_color(log) 104 + 105 + # mix/album_art.jpg overrides the default 106 + custom_album_art = ROOT_DIR / "mix" / "album_art.jpg" 107 + album_art_file = custom_album_art if custom_album_art.exists() else ROOT_DIR / "resources" / "album_art.jpg" 108 + album_art_path = "mix/album_art.jpg" if custom_album_art.exists() else "resources/album_art.jpg" 109 + # append a content hash so the URL changes when the image changes 110 + if album_art_file.exists(): 111 + art_hash = hashlib.md5(album_art_file.read_bytes()).hexdigest()[:8] 112 + album_art_path = f"{album_art_path}?v={art_hash}" 113 + log(f" Album art: {album_art_path}") 114 + 115 + # mix/icon.png overrides the default 116 + custom_icon = ROOT_DIR / "mix" / "icon.png" 117 + icon_file = custom_icon if custom_icon.exists() else ROOT_DIR / "resources" / "icon.png" 118 + icon_path = "mix/icon.png" if custom_icon.exists() else "resources/icon.png" 119 + # append a content hash so the URL changes when the image changes 120 + if icon_file.exists(): 121 + icon_hash = hashlib.md5(icon_file.read_bytes()).hexdigest()[:8] 122 + icon_path = f"{icon_path}?v={icon_hash}" 123 + log(f" Icon: {icon_path}") 124 + 125 + # Generate manifest.json 126 + manifest = { 127 + "name": app_name, 128 + "short_name": short_name, 129 + "description": app_description, 130 + "start_url": "./", 131 + "scope": "./", 132 + "display": "standalone", 133 + "background_color": background_color, 134 + "theme_color": background_color, 135 + "cache_name": cache_name, # Custom field for script.js to use 136 + "album_art": album_art_path, # Custom field for script.js to use 137 + "icons": [ 138 + { 139 + "src": icon_path, 140 + "sizes": "640x640", 141 + "type": "image/png", 142 + "purpose": "any maskable" 143 + } 144 + ] 145 + } 146 + 147 + with open(ROOT_DIR / "manifest.json", 'w', encoding='utf-8') as f: 148 + json.dump(manifest, f, indent=2) 149 + log("✓ Generated manifest.json") 150 + 151 + # Build static files list for service worker 152 + static_files = [ 153 + "./", 154 + "index.html", 155 + "manifest.json", 156 + "resources/styles.css", 157 + "resources/script.js", 158 + "mix/tracks.json", 159 + icon_path, 160 + album_art_path, 161 + "resources/play.svg", 162 + "resources/pause.svg", 163 + "resources/prev.svg", 164 + "resources/next.svg", 165 + "resources/repeat.svg", 166 + "resources/fonts/Basteleur/Basteleur-Moonlight.woff2", 167 + ] 168 + 169 + AUDIO_EXTS = {".mp3", ".m4a", ".ogg", ".flac", ".wav"} 170 + # album_art.jpg and icon.png added explicitly above with a hash; skip to avoid a bare dupe 171 + SKIP_NAMES = {"tracks.json", "readme.md", "album_art.jpg", "icon.png", "name.txt"} 172 + for path in sorted((ROOT_DIR / "mix").iterdir()): 173 + if not path.is_file(): 174 + continue 175 + if path.name in SKIP_NAMES: 176 + continue 177 + if path.suffix.lower() in AUDIO_EXTS: 178 + continue 179 + static_files.append(f"mix/{path.name}") 180 + 181 + static_files_js = json.dumps(static_files) 182 + audio_pattern = "|".join(sorted(ext[1:] for ext in AUDIO_EXTS)) 183 + 184 + # Generate service-worker.js 185 + service_worker_content = f'''// Auto-generated service worker for {app_name} PWA 186 +const CACHE_NAME = '{cache_name}'; 187 + 188 +// Get the base path from the service worker location 189 +const getBasePath = () => {{ 190 + const swPath = self.location.pathname; 191 + return swPath.substring(0, swPath.lastIndexOf('/') + 1); 192 +}}; 193 + 194 +const basePath = getBasePath(); 195 + 196 +// Static files to cache on install 197 +const STATIC_FILES = {static_files_js}; 198 +const AUDIO_FILE = /\\.({audio_pattern})$/i; 199 + 200 +// Install event - cache static resources only if not already cached. 201 +// This makes installs immutable: once a file is in the cache, redeploys 202 +// will not overwrite it, so the app stays frozen at its first-installed version. 203 +// Audio files will be cached by the main app's blob preloading system. 204 +self.addEventListener('install', (event) => {{ 205 + console.log('Service Worker installing...', 'Base path:', basePath); 206 + self.skipWaiting(); 207 + event.waitUntil( 208 + caches.open(CACHE_NAME).then(cache => {{ 209 + const absoluteUrls = STATIC_FILES.map(url => {{ 210 + if (url === './') return new URL(basePath, self.location.href).href; 211 + return new URL(url, new URL(basePath, self.location.href)).href; 212 + }}); 213 + 214 + return Promise.allSettled( 215 + absoluteUrls.map(url => 216 + cache.match(url).then(existing => {{ 217 + if (existing) {{ 218 + console.log('• Already cached, skipping:', url); 219 + return; 220 + }} 221 + return fetch(url, {{ cache: 'no-cache' }}) 222 + .then(response => {{ 223 + if (!response.ok) {{ 224 + throw new Error(`HTTP error! status: ${{response.status}}`); 225 + }} 226 + return cache.put(url, response); 227 + }}) 228 + .then(() => console.log('✓ Cached:', url)) 229 + .catch(err => {{ 230 + console.error('✗ Failed to cache:', url, err); 231 + throw err; 232 + }}); 233 + }}) 234 + ) 235 + ).then(results => {{ 236 + const failed = results.filter(r => r.status === 'rejected'); 237 + console.log(`Install complete: ${{results.length - failed.length}}/${{results.length}} ok`); 238 + }}); 239 + }}).catch(error => {{ 240 + console.error('Service Worker installation failed:', error); 241 + }}) 242 + ); 243 +}}); 244 + 245 +self.addEventListener('activate', (event) => {{ 246 + event.waitUntil(self.clients.claim()); 247 +}}); 248 + 249 +// Network fetch capped with a timeout. A mixapp installed off the LAN points 250 +// at a private-IP origin that's usually gone by launch time; without a cap an 251 +// uncached request hangs on a TCP timeout and stalls startup (black→white 252 +// screen). Aborting fast turns that hang into an ordinary cache-miss failure. 253 +const fetchWithTimeout = (request, ms = 2000) => {{ 254 + const controller = new AbortController(); 255 + const timer = setTimeout(() => controller.abort(), ms); 256 + return fetch(request, {{ signal: controller.signal }}) 257 + .finally(() => clearTimeout(timer)); 258 +}}; 259 + 260 +// Fetch event - cache first, network fallback 261 +self.addEventListener('fetch', (event) => {{ 262 + // Ignore non-http(s) requests like blob: URLs, data: URLs, chrome-extension:, etc. 263 + if (!event.request.url.startsWith('http')) {{ 264 + return; 265 + }} 266 + 267 + event.respondWith( 268 + caches.match(event.request) 269 + .then((cachedResponse) => {{ 270 + if (cachedResponse) {{ 271 + console.log('✓ Serving from cache:', event.request.url); 272 + return cachedResponse; 273 + }} 274 + 275 + // Navigation that missed the exact cache key: serve the cached 276 + // app shell so the document always renders from cache, online 277 + // or off, even if the launch URL doesn't byte-match a key. 278 + if (event.request.mode === 'navigate') {{ 279 + const shellUrl = new URL(basePath, self.location.href).href; 280 + return caches.match(shellUrl) 281 + .then(shell => shell || caches.match('index.html')) 282 + .then(shell => shell || fetchWithTimeout(event.request)); 283 + }} 284 + 285 + // Not in cache - try network (time-boxed; see fetchWithTimeout) 286 + console.log('⟳ Fetching from network:', event.request.url); 287 + return fetchWithTimeout(event.request) 288 + .then((networkResponse) => {{ 289 + // Check if valid response 290 + if (!networkResponse || networkResponse.status !== 200 || networkResponse.type === 'error') {{ 291 + return networkResponse; 292 + }} 293 + 294 + if (AUDIO_FILE.test(new URL(event.request.url).pathname)) {{ 295 + return networkResponse; 296 + }} 297 + 298 + // Clone and cache for future offline use 299 + const responseToCache = networkResponse.clone(); 300 + caches.open(CACHE_NAME) 301 + .then((cache) => {{ 302 + cache.put(event.request, responseToCache); 303 + console.log('✓ Cached from network:', event.request.url); 304 + }}) 305 + .catch(err => console.error('Failed to cache:', err)); 306 + 307 + return networkResponse; 308 + }}) 309 + .catch((error) => {{ 310 + console.error('✗ Network fetch failed for:', event.request.url, error); 311 + throw error; 312 + }}); 313 + }}) 314 + ); 315 +}}); 316 +''' 317 + 318 + with open(ROOT_DIR / "service-worker.js", 'w', encoding='utf-8') as f: 319 + f.write(service_worker_content) 320 + log("✓ Generated service-worker.js") 321 + log() 322 + log("PWA build complete!") 323 + return app_name 324 + 325 + 326 +if __name__ == "__main__": 327 + scan.bootstrap(__file__) 328 + build_pwa()
1 +""" 2 +Handles track edits (reorder, upload, delete) from the browser. 3 +Sends track list changes to open browser tabs as they happen. 4 +Rebuilds manifest.json and service-worker.js when /mix changes. 5 +serve.py uses this to serve your mixapp. 6 +""" 7 + 8 +import http.server 9 +import sys 10 +import json 11 +import queue 12 +import threading 13 +import time 14 +import urllib.parse 15 +from pathlib import Path 16 + 17 +ROOT_DIR = Path(__file__).parent.parent.absolute() 18 +MIX_DIR = ROOT_DIR / "mix" 19 +TRACKS_PATH = MIX_DIR / "tracks.json" 20 + 21 +PUBLIC_FILES = {"index.html", "manifest.json", "service-worker.js"} 22 +PUBLIC_DIRS = {"resources", "mix"} 23 + 24 +SUPPORTED_UPLOAD_EXTENSIONS = ('.mp3', '.m4a', '.ogg', '.flac', '.wav') 25 +MAX_UPLOAD_BYTES = 200 * 1024 * 1024 # 200 MB per request 26 + 27 +# Serializes all reads/writes of tracks.json so rescans, reorders, and future 28 +# uploads can't race each other. 29 +tracks_lock = threading.Lock() 30 + 31 +# Set of per-client SSE queues. Each connected /events client gets a queue; 32 +# broadcast_tracks() pushes the latest tracks list onto every queue. 33 +sse_subscribers = set() 34 +sse_subscribers_lock = threading.Lock() 35 + 36 +# Canonical serialization of the most recently broadcast tracks list, so we 37 +# can fire on any content change (file add/remove/reorder or a hand-edit to 38 +# tracks.json's metadata) instead of only when /mix's filenames change. 39 +last_broadcast_serialized = None 40 + 41 + 42 +def read_tracks(): 43 + """Read tracks.json from disk; return [] if missing or malformed.""" 44 + if not TRACKS_PATH.exists(): 45 + return [] 46 + try: 47 + with open(TRACKS_PATH, 'r', encoding='utf-8') as f: 48 + loaded = json.load(f) 49 + return loaded if isinstance(loaded, list) else [] 50 + except (json.JSONDecodeError, OSError): 51 + return [] 52 + 53 + 54 +def _move_track_to(tracks, filename, insert_after): 55 + """Reorder `tracks` in place so the entry matching `filename` lands at 56 + insert_after + 1 (clamped). Persists tracks.json if the order actually 57 + changed. Returns True iff a move happened. Caller must hold tracks_lock.""" 58 + cur_idx = next((i for i, t in enumerate(tracks) if t.get('filename') == filename), -1) 59 + if cur_idx == -1: 60 + return False 61 + target_idx = max(0, min(insert_after + 1, len(tracks) - 1)) 62 + if target_idx == cur_idx: 63 + return False 64 + entry = tracks.pop(cur_idx) 65 + if target_idx > cur_idx: 66 + target_idx -= 1 67 + tracks.insert(target_idx, entry) 68 + TRACKS_PATH.write_text( 69 + json.dumps(tracks, indent='\t', ensure_ascii=False) + '\n', 70 + encoding='utf-8', 71 + ) 72 + return True 73 + 74 + 75 +def _canonical_name_for(audio_path, fallback_name): 76 + """Return the 'Artist – Title.ext' filename scan would canonicalize this 77 + upload to, so we can dedup BEFORE moving the file into /mix. Returns None 78 + if metadata can't be read.""" 79 + import scan 80 + try: 81 + from mutagen import File as MutagenFile # type: ignore 82 + except ImportError: 83 + return None 84 + try: 85 + audio = MutagenFile(audio_path, easy=True) 86 + except Exception: 87 + return None 88 + title = None 89 + artist = None 90 + if audio and audio.tags: 91 + title = audio.tags.get('title', [None])[0] 92 + artist = audio.tags.get('artist', [None])[0] 93 + if not title: 94 + title = Path(fallback_name).stem 95 + if not artist: 96 + artist = "Unknown Artist" 97 + ext = Path(fallback_name).suffix 98 + return f"{scan._sanitize_filename(artist)} – {scan._sanitize_filename(title)}{ext}" 99 + 100 + 101 +def broadcast_tracks(tracks, renames=None): 102 + """Push the current tracks list to every connected SSE client if its 103 + content differs from the last broadcast. `renames`, when non-empty, 104 + carries [{from, to}, ...] so clients can migrate per-track state (eg. 105 + preloaded blob URLs) without losing it across a canonicalizing rename. 106 + Caller must hold tracks_lock.""" 107 + global last_broadcast_serialized 108 + serialized = json.dumps(tracks, ensure_ascii=False, sort_keys=True) 109 + if serialized == last_broadcast_serialized and not renames: 110 + return 111 + last_broadcast_serialized = serialized 112 + payload = {'tracks': tracks, 'renames': renames or []} 113 + with sse_subscribers_lock: 114 + subscribers = list(sse_subscribers) 115 + for q in subscribers: 116 + try: 117 + q.put_nowait(payload) 118 + except queue.Full: 119 + pass 120 + 121 + 122 +# Snapshot of the files the PWA build reads, as of the last build. 123 +last_pwa_signature = None 124 + 125 + 126 +def rebuild_pwa_if_changed(): 127 + """Regenerate manifest.json and service-worker.js when any file they're 128 + built from has changed. Returns the mix name after a rebuild, else None.""" 129 + global last_pwa_signature 130 + import build 131 + inputs = [*MIX_DIR.iterdir(), ROOT_DIR / "resources" / "styles.css"] 132 + signature = sorted((p.name, p.stat().st_mtime_ns, p.stat().st_size) for p in inputs if p.exists()) 133 + if signature == last_pwa_signature: 134 + return None 135 + last_pwa_signature = signature 136 + return build.build_pwa(silent=True) 137 + 138 + 139 +def print_mix_name(name): 140 + import build 141 + print(f"Mix name: {name}") 142 + if name == build.DEFAULT_NAME: 143 + print(" (put a name in mix/name.txt to change it)") 144 + 145 + 146 +def rescan_and_maybe_broadcast(): 147 + """Rescan /mix, then broadcast if the resulting tracks list differs from 148 + what we last sent.""" 149 + import scan 150 + tracks, _changed, renames = scan.rescan(silent=True) 151 + broadcast_tracks(tracks, renames=renames) 152 + return tracks 153 + 154 + 155 +def start_rescan_ticker(interval=1.0): 156 + """Background thread that periodically rescans /mix so changes made 157 + directly on disk (eg. user dragging a file in or `rm`-ing one from the 158 + terminal) reach connected clients without anyone hitting the server.""" 159 + def tick(): 160 + while True: 161 + time.sleep(interval) 162 + try: 163 + with tracks_lock: 164 + rescan_and_maybe_broadcast() 165 + rebuild_pwa_if_changed() 166 + except Exception as e: 167 + # Don't let a bad scan kill the ticker. 168 + print(f"rescan tick error: {e}", file=sys.stderr) 169 + t = threading.Thread(target=tick, daemon=True) 170 + t.start() 171 + 172 + 173 +class TrackRequestHandler(http.server.SimpleHTTPRequestHandler): 174 + # keep-alive; every response below needs a Content-Length or must close 175 + protocol_version = 'HTTP/1.1' 176 + # don't let idle connections pin threads forever 177 + timeout = 60 178 + # Nagle would stall the body write behind the header write 179 + disable_nagle_algorithm = True 180 + 181 + def do_GET(self): 182 + # Rescan /mix on every tracks.json fetch so the page always sees 183 + # what's actually on disk (added via rip.py/buy.py or by hand). 184 + if self.path == '/mix/tracks.json': 185 + with tracks_lock: 186 + rescan_and_maybe_broadcast() 187 + return super().do_GET() 188 + 189 + if self.path == '/events': 190 + return self._serve_sse() 191 + 192 + return super().do_GET() 193 + 194 + def _is_public(self, fs_path): 195 + parts = Path(fs_path).relative_to(self.directory).parts 196 + if not parts: 197 + return True 198 + if any(part.startswith('.') for part in parts): 199 + return False 200 + if len(parts) == 1: 201 + return parts[0] in PUBLIC_FILES 202 + name = parts[-1].lower() 203 + return parts[0] in PUBLIC_DIRS and name != 'readme.md' and not name.endswith('.uploading') 204 + 205 + def send_head(self): 206 + if not self._is_public(self.translate_path(self.path)): 207 + self.send_error(404) 208 + return None 209 + return super().send_head() 210 + 211 + def list_directory(self, path): 212 + self.send_error(404) 213 + return None 214 + 215 + def _serve_sse(self): 216 + """Server-Sent Events stream of tracks.json changes.""" 217 + self.send_response(200) 218 + self.send_header('Content-Type', 'text/event-stream') 219 + self.send_header('Cache-Control', 'no-cache') 220 + # The stream has no Content-Length, so under HTTP/1.1 it has to be 221 + # delimited by closing the socket. Sending this also flips 222 + # close_connection, so the handler won't try to reuse the socket. 223 + self.send_header('Connection', 'close') 224 + self.send_header('X-Accel-Buffering', 'no') 225 + self.end_headers() 226 + 227 + q = queue.Queue(maxsize=16) 228 + with sse_subscribers_lock: 229 + sse_subscribers.add(q) 230 + 231 + try: 232 + # Initial sync so a fresh tab gets the current state without 233 + # waiting for the next change. No renames context: a fresh 234 + # client has no prior state to migrate from. 235 + with tracks_lock: 236 + initial = read_tracks() 237 + self._send_sse_event('tracks', {'tracks': initial, 'renames': []}) 238 + 239 + while True: 240 + try: 241 + payload = q.get(timeout=15) 242 + self._send_sse_event('tracks', payload) 243 + except queue.Empty: 244 + # Heartbeat keeps proxies and idle connections from 245 + # closing the stream. 246 + self.wfile.write(b': keepalive\n\n') 247 + self.wfile.flush() 248 + except (BrokenPipeError, ConnectionResetError, OSError): 249 + pass 250 + finally: 251 + with sse_subscribers_lock: 252 + sse_subscribers.discard(q) 253 + 254 + def _reply_status(self, status, body=b''): 255 + """Short reply with a Content-Length. Errors also close the socket, 256 + since an early return can leave an unread body in the buffer.""" 257 + if isinstance(body, str): 258 + body = body.encode('utf-8') 259 + self.send_response(status) 260 + self.send_header('Content-Length', str(len(body))) 261 + if status >= 400: 262 + self.send_header('Connection', 'close') 263 + self.end_headers() 264 + if body: 265 + try: 266 + self.wfile.write(body) 267 + except (BrokenPipeError, ConnectionResetError): 268 + pass 269 + 270 + def _reply_json(self, status, payload): 271 + body = json.dumps(payload).encode('utf-8') 272 + self.send_response(status) 273 + self.send_header('Content-Type', 'application/json') 274 + self.send_header('Content-Length', str(len(body))) 275 + self.end_headers() 276 + self.wfile.write(body) 277 + 278 + def _send_sse_event(self, event, data): 279 + payload = json.dumps(data, ensure_ascii=False) 280 + message = f'event: {event}\ndata: {payload}\n\n'.encode('utf-8') 281 + self.wfile.write(message) 282 + self.wfile.flush() 283 + 284 + def do_POST(self): 285 + # Local-only: receive a reordered tracks array and overwrite tracks.json 286 + if self.path != '/tracks': 287 + self._reply_status(404) 288 + return 289 + length = int(self.headers.get('Content-Length', '0')) 290 + payload = json.loads(self.rfile.read(length)) 291 + with tracks_lock: 292 + TRACKS_PATH.write_text( 293 + json.dumps(payload, indent='\t', ensure_ascii=False) + '\n', 294 + encoding='utf-8', 295 + ) 296 + broadcast_tracks(payload) 297 + self.send_response(204) 298 + self.end_headers() 299 + 300 + def do_PUT(self): 301 + # Local-only: drag-and-drop upload from a connected browser. 302 + # Path is /upload/<url-encoded-filename>; headers carry the 303 + # desired insertion index (X-Insert-After: -1 means prepend). 304 + prefix = '/upload/' 305 + if not self.path.startswith(prefix): 306 + self._reply_status(404) 307 + return 308 + 309 + raw_name = urllib.parse.unquote(self.path[len(prefix):]) 310 + # Strip any client-supplied path components. 311 + filename = Path(raw_name).name 312 + ext = Path(filename).suffix.lower() 313 + if not filename or ext not in SUPPORTED_UPLOAD_EXTENSIONS: 314 + self._reply_status(415) 315 + return 316 + 317 + length = int(self.headers.get('Content-Length', '0')) 318 + if length <= 0 or length > MAX_UPLOAD_BYTES: 319 + self._reply_status(413) 320 + return 321 + 322 + try: 323 + insert_after = int(self.headers.get('X-Insert-After', '-1')) 324 + except ValueError: 325 + insert_after = -1 326 + 327 + # Stream the body to a temp file in MIX_DIR, then move into place 328 + # atomically so a partial write is never visible to the rescan. 329 + MIX_DIR.mkdir(parents=True, exist_ok=True) 330 + tmp_path = MIX_DIR / (filename + '.uploading') 331 + try: 332 + with open(tmp_path, 'wb') as out: 333 + remaining = length 334 + while remaining > 0: 335 + chunk = self.rfile.read(min(64 * 1024, remaining)) 336 + if not chunk: 337 + break 338 + out.write(chunk) 339 + remaining -= len(chunk) 340 + if remaining != 0: 341 + tmp_path.unlink(missing_ok=True) 342 + self._reply_status(400) 343 + return 344 + 345 + with tracks_lock: 346 + import scan 347 + # Dedup by canonical name: if a file with the canonical 348 + # "Artist – Title.ext" name already lives in /mix, drop 349 + # the upload and just reorder the existing entry to the 350 + # requested slot so the client still gets the FLIP. 351 + canonical = _canonical_name_for(tmp_path, filename) 352 + if canonical and (MIX_DIR / canonical).exists(): 353 + tmp_path.unlink(missing_ok=True) 354 + tracks = read_tracks() 355 + moved = _move_track_to(tracks, canonical, insert_after) 356 + if moved: 357 + broadcast_tracks(tracks) 358 + final_index = next((i for i, t in enumerate(tracks) if t.get('filename') == canonical), -1) 359 + self._reply_json(200, {'filename': canonical, 'duplicate': True, 'moved': moved, 'final_index': final_index}) 360 + return 361 + 362 + tmp_path.rename(MIX_DIR / filename) 363 + placed_name = filename 364 + 365 + tracks, _changed, renames = scan.rescan(silent=True) 366 + 367 + # Find the canonical (post-canonicalize) filename for the 368 + # upload by following the rename chain. 369 + new_name = placed_name 370 + for r in renames: 371 + if r['from'] == new_name: 372 + new_name = r['to'] 373 + 374 + _move_track_to(tracks, new_name, insert_after) 375 + broadcast_tracks(tracks, renames=renames) 376 + final_index = next((i for i, t in enumerate(tracks) if t.get('filename') == new_name), -1) 377 + 378 + self._reply_json(200, {'filename': new_name, 'final_index': final_index}) 379 + except Exception as e: 380 + tmp_path.unlink(missing_ok=True) 381 + self._reply_status(500, str(e)) 382 + 383 + def do_DELETE(self): 384 + # Local-only: remove a track's audio file from /mix and prune 385 + # tracks.json. Path is /tracks/<url-encoded-filename>. 386 + prefix = '/tracks/' 387 + if not self.path.startswith(prefix): 388 + self._reply_status(404) 389 + return 390 + 391 + filename = urllib.parse.unquote(self.path[len(prefix):]) 392 + target = (MIX_DIR / filename).resolve() 393 + try: 394 + target.relative_to(MIX_DIR.resolve()) 395 + except ValueError: 396 + self._reply_status(400) 397 + return 398 + if target == TRACKS_PATH.resolve() or target.name != filename: 399 + self._reply_status(400) 400 + return 401 + with tracks_lock: 402 + try: 403 + target.unlink() 404 + except FileNotFoundError: 405 + pass 406 + except OSError as e: 407 + self._reply_status(500, str(e)) 408 + return 409 + tracks = [t for t in read_tracks() if t.get('filename') != filename] 410 + TRACKS_PATH.write_text( 411 + json.dumps(tracks, indent='\t', ensure_ascii=False) + '\n', 412 + encoding='utf-8', 413 + ) 414 + broadcast_tracks(tracks) 415 + self.send_response(204) 416 + self.end_headers()
1 +#!/usr/bin/env python3 2 +""" 3 +Scans /mix directory and populates tracks.json with metadata 4 +Supports MP3, M4A, OGG, FLAC, and WAV formats 5 +Automatically manages a virtual environment for dependencies 6 +""" 7 + 8 +import os 9 +import sys 10 +import subprocess 11 +import json 12 +from pathlib import Path 13 + 14 +ROOT_DIR = Path(__file__).parent.parent.absolute() 15 +VENV_DIR = ROOT_DIR / "venv" 16 +MIX_DIR = ROOT_DIR / "mix" 17 +OUTPUT_FILE = MIX_DIR / "tracks.json" 18 + 19 + 20 +def setup_venv(packages=("mutagen",)): 21 + """Create the shared venv if missing and ensure each package is installed. 22 + Returns the path to the venv Python interpreter.""" 23 + if sys.platform == "win32": 24 + pip_path = VENV_DIR / "Scripts" / "pip" 25 + python_path = VENV_DIR / "Scripts" / "python" 26 + else: 27 + pip_path = VENV_DIR / "bin" / "pip" 28 + python_path = VENV_DIR / "bin" / "python3" 29 + 30 + if not VENV_DIR.exists() or not python_path.exists(): 31 + if VENV_DIR.exists(): 32 + print("Virtual environment incomplete, recreating...") 33 + import shutil 34 + shutil.rmtree(VENV_DIR) 35 + else: 36 + print("Creating virtual environment...") 37 + 38 + try: 39 + subprocess.check_call([sys.executable, "-m", "venv", str(VENV_DIR)]) 40 + print("Virtual environment created successfully.") 41 + except subprocess.CalledProcessError as e: 42 + print(f"Error creating virtual environment: {e}") 43 + sys.exit(1) 44 + 45 + if not pip_path.exists(): 46 + print("Installing pip in virtual environment...") 47 + try: 48 + subprocess.check_call([str(python_path), "-m", "ensurepip", "--upgrade"]) 49 + except subprocess.CalledProcessError as e: 50 + print(f"Error ensuring pip: {e}") 51 + sys.exit(1) 52 + 53 + for pkg in packages: 54 + check = subprocess.run( 55 + [str(python_path), "-c", f"import {pkg}"], 56 + capture_output=True 57 + ) 58 + if check.returncode != 0: 59 + try: 60 + subprocess.check_call([str(python_path), "-m", "pip", "install", "-q", pkg]) 61 + except subprocess.CalledProcessError: 62 + print(f"Note: Could not install {pkg} (offline?).\n") 63 + 64 + return python_path 65 + 66 + 67 +def bootstrap(script_path, packages=("mutagen",), sentinel="--in-venv"): 68 + """Ensure the calling script is running inside the shared venv 69 + with `packages` available. Re-execs through the venv Python on first call; 70 + returns immediately on the second pass once the sentinel is in argv. 71 + 72 + Each script that uses this should pass its own __file__ as script_path.""" 73 + if sentinel in sys.argv: 74 + sys.argv.remove(sentinel) 75 + return 76 + python_path = setup_venv(packages) 77 + process = subprocess.Popen([str(python_path), script_path, sentinel, *sys.argv[1:]]) 78 + while True: 79 + try: 80 + sys.exit(process.wait()) 81 + except KeyboardInterrupt: 82 + continue 83 + 84 + 85 +def run_in_venv(): 86 + """Re-run this script in the virtual environment (CLI use of scan.py).""" 87 + python_path = setup_venv() 88 + print("Running scanner in virtual environment...\n") 89 + subprocess.check_call([str(python_path), __file__, "--in-venv"]) 90 + sys.exit(0) 91 + 92 + 93 +SUPPORTED_EXTENSIONS = ('.mp3', '.m4a', '.ogg', '.flac', '.wav') 94 + 95 +_INVALID_FILENAME_CHARS = '<>:"/\\|?*' 96 + 97 + 98 +def _sanitize_filename(name): 99 + for char in _INVALID_FILENAME_CHARS: 100 + name = name.replace(char, '') 101 + return name.strip() 102 + 103 + 104 +def _write_tags(audio_file, artist, title, MutagenFile): 105 + """Write artist/title tags to disk if they don't already match. Returns 106 + True if anything was written.""" 107 + try: 108 + audio = MutagenFile(audio_file, easy=True) 109 + if audio is None: 110 + return False 111 + if audio.tags is None: 112 + audio.add_tags() 113 + current_title = audio.tags.get('title', [None])[0] 114 + current_artist = audio.tags.get('artist', [None])[0] 115 + if current_title == title and current_artist == artist: 116 + return False 117 + audio.tags['title'] = title 118 + audio.tags['artist'] = artist 119 + audio.save() 120 + return True 121 + except Exception: 122 + return False 123 + 124 + 125 +def _canonicalize(tracks, has_mutagen, MutagenFile, silent): 126 + """Rename files to 'Artist – Title.ext' and sync ID3 tags so disk state 127 + matches tracks.json metadata. Mutates `tracks` in place; returns a list 128 + of {from, to} renames so callers can migrate any external state (eg. 129 + preloaded blob URLs in connected browser tabs).""" 130 + renames = [] 131 + for entry in tracks: 132 + old_filename = entry['filename'] 133 + ext = Path(old_filename).suffix 134 + artist = _sanitize_filename(entry['artist']) 135 + title = _sanitize_filename(entry['title']) 136 + new_filename = f"{artist} – {title}{ext}" 137 + 138 + old_path = MIX_DIR / old_filename 139 + new_path = MIX_DIR / new_filename 140 + 141 + # Keep tags aligned with the (possibly hand-edited) tracks.json 142 + # entry, regardless of whether a rename is needed. 143 + if has_mutagen and old_path.exists(): 144 + _write_tags(old_path, entry['artist'], entry['title'], MutagenFile) 145 + 146 + if old_filename == new_filename: 147 + continue 148 + if not old_path.exists(): 149 + continue 150 + if new_path.exists(): 151 + # Don't clobber an unrelated file that already occupies the 152 + # canonical name. Leave the entry pointing at its current file. 153 + if not silent: 154 + print(f" Skipping rename {old_filename} -> {new_filename} (target exists)") 155 + continue 156 + try: 157 + old_path.rename(new_path) 158 + entry['filename'] = new_filename 159 + renames.append({'from': old_filename, 'to': new_filename}) 160 + if not silent: 161 + print(f" Renamed: {old_filename} -> {new_filename}") 162 + except Exception as e: 163 + if not silent: 164 + print(f" Error renaming {old_filename}: {e}") 165 + return renames 166 + 167 + 168 +def rescan(silent=False): 169 + """Reconcile tracks.json with /mix. Renames files to canonical 170 + 'Artist – Title.ext' form when they drift, syncing ID3 tags at the same 171 + time. Returns (tracks, changed, renames) where renames is a list of 172 + {from, to} dicts for any files that moved this pass.""" 173 + try: 174 + from mutagen import File as MutagenFile # type: ignore 175 + has_mutagen = True 176 + except ImportError: 177 + MutagenFile = None 178 + has_mutagen = False 179 + if not silent: 180 + print("Mutagen not available. Metadata will be derived from filenames.\n") 181 + 182 + if not MIX_DIR.exists(): 183 + MIX_DIR.mkdir(parents=True, exist_ok=True) 184 + 185 + audio_files = [f for f in MIX_DIR.iterdir() if f.suffix.lower() in SUPPORTED_EXTENSIONS] 186 + 187 + existing_tracks = [] 188 + if OUTPUT_FILE.exists(): 189 + try: 190 + with open(OUTPUT_FILE, 'r', encoding='utf-8') as f: 191 + loaded = json.load(f) 192 + if isinstance(loaded, list): 193 + existing_tracks = loaded 194 + except (json.JSONDecodeError, OSError) as e: 195 + if not silent: 196 + print(f"Warning: could not read existing {OUTPUT_FILE.name} ({e}). Starting fresh.\n") 197 + 198 + existing_by_filename = { 199 + t['filename']: t for t in existing_tracks 200 + if isinstance(t, dict) and 'filename' in t 201 + } 202 + on_disk_filenames = {f.name for f in audio_files} 203 + files_by_name = {f.name: f for f in audio_files} 204 + 205 + def read_metadata(audio_file): 206 + title = None 207 + artist = None 208 + if has_mutagen: 209 + audio = MutagenFile(audio_file, easy=True) 210 + if audio and audio.tags: 211 + title = audio.tags.get('title', [None])[0] 212 + artist = audio.tags.get('artist', [None])[0] 213 + if not title: 214 + title = audio_file.stem 215 + if not artist: 216 + artist = "Unknown Artist" 217 + return {"title": title, "artist": artist, "filename": audio_file.name} 218 + 219 + tracks = [] 220 + removed = [] 221 + for entry in existing_tracks: 222 + if not isinstance(entry, dict) or 'filename' not in entry: 223 + continue 224 + if entry['filename'] in on_disk_filenames: 225 + tracks.append(entry) 226 + else: 227 + removed.append(entry['filename']) 228 + 229 + new_files = sorted( 230 + (files_by_name[name] for name in on_disk_filenames if name not in existing_by_filename), 231 + key=lambda f: f.name, 232 + ) 233 + new_tracks = [] 234 + for audio_file in new_files: 235 + try: 236 + new_tracks.append(read_metadata(audio_file)) 237 + except Exception as e: 238 + if not silent: 239 + print(f"✗ Error reading {audio_file.name}: {e}") 240 + 241 + if not silent: 242 + for track in new_tracks: 243 + print(f"+ {track['artist']} - {track['title']}") 244 + for filename in removed: 245 + print(f"- {filename} (removed; no longer on disk)") 246 + if not new_tracks and not removed: 247 + print("No changes — tracks.json already matches /mix.") 248 + 249 + tracks.extend(new_tracks) 250 + 251 + renames = _canonicalize(tracks, has_mutagen, MutagenFile, silent) 252 + 253 + changed = bool(new_tracks) or bool(removed) or bool(renames) 254 + if changed or not OUTPUT_FILE.exists(): 255 + try: 256 + OUTPUT_FILE.write_text( 257 + json.dumps(tracks, indent='\t', ensure_ascii=False) + '\n', 258 + encoding='utf-8', 259 + ) 260 + except Exception as e: 261 + if not silent: 262 + print(f"\nError writing {OUTPUT_FILE.name}: {e}") 263 + raise 264 + 265 + return tracks, changed, renames 266 + 267 + 268 +def scan_tracks(): 269 + """CLI entry point: rescan and print a summary.""" 270 + if not MIX_DIR.exists(): 271 + print(f"Creating {MIX_DIR.name} directory...") 272 + MIX_DIR.mkdir(parents=True, exist_ok=True) 273 + print(f"✓ {MIX_DIR.name} directory created.") 274 + print(f"\nAdd audio files to the {MIX_DIR.name} directory and run this script again.") 275 + print(f"Supported formats: {', '.join(SUPPORTED_EXTENSIONS)}") 276 + sys.exit(0) 277 + 278 + audio_files = [f for f in MIX_DIR.iterdir() if f.suffix.lower() in SUPPORTED_EXTENSIONS] 279 + if not audio_files: 280 + print(f"No audio files found in {MIX_DIR}") 281 + print(f"\nPlease add audio files to the {MIX_DIR.name} directory and run this script again.") 282 + print(f"Supported formats: {', '.join(SUPPORTED_EXTENSIONS)}") 283 + sys.exit(0) 284 + 285 + print(f"Found {len(audio_files)} audio file(s). Extracting metadata...\n") 286 + tracks, changed, _renames = rescan(silent=False) 287 + if not tracks: 288 + print("\nNo valid audio files could be processed.") 289 + sys.exit(1) 290 + if changed: 291 + print(f"\n✓ Updated {OUTPUT_FILE.name} ({len(tracks)} track(s)).") 292 + 293 + 294 +def main(): 295 + """Main entry point""" 296 + # Check if we're already running in venv 297 + if "--in-venv" not in sys.argv: 298 + run_in_venv() 299 + else: 300 + scan_tracks() 301 + 302 + 303 +if __name__ == "__main__": 304 + main()
1 # /mix 2 -add your audio files here. `build.py`, `serve.py`, `rip.py`, and `buy.py` generate `tracks.json` by scanning the files in this directory. 3 +add your audio files here. `serve.py`, `rip.py`, and `buy.py` generate `tracks.json` by scanning the files in this directory. 4 5 supported formats: `.mp3`, `.m4a`, `.ogg`, `.flac`, `.wav` 6 8 - `custom.css` - custom styles to override the default theme 9 - `custom.js` - custom scripts for additional functionality 10 - `album_art.jpg` - cover art for your mix (overrides the default in `/resources`) -- `icon.png` - home screen icon for your mix (overrides the default in `/resources`) 11 +- `icon.png` - home screen icon for your mix (overrides the default in `/resources`) 12 +- `name.txt` - a text file containing your mixapp's name (displayed on your device's homescreen)
43 1. **serve it** 44 - run `./serve.py` to start a development server. while the server is running, you can: 45 - **add new tracks** by... 46 + - adding them to the `mix/` directory 47 - dragging them into the browser window - - moving them into the `mix/` directory 48 - running `./rip.py` to rip tracks from a physical CD 49 - running `./buy.py` to buy tracks on iTunes 50 - **reorder tracks** by dragging them up or down in the list 51 - **delete tracks** with `shift + click` 52 -2. **build it** - - once you're happy with your mix, run `./build.py` and follow the interactive prompts to generate `manifest.json` and `service-worker.js`, which enable PWA installation and offline functionality. - -3. **ship it** 53 +2. **ship it** 54 + - over **your own network** (recommended): 55 + - while `./serve.py` is running (with HTTPS enabled), use your phone to scan the QR codes it prints to the console (<a href="#local-network-installation">details</a>). no public host necessary, and nothing ever leaves your network. 56 - using a **public host:** 57 - when using media you have distribution rights for, you can upload the entire project directory to any static web host with HTTPS support (GitHub Pages, Neocities, AWS S3, etc).<br> - **publishing files you don't have the right to distribute may constitute copyright infringement.** - - over **your own wifi:** - - install onto your own devices using a <a href="#local-network-installation">local HTTPS server</a>. no public host necessary, and nothing ever leaves your network. 58 + **publishing files you don't have the right to distribute may constitute copyright infringement.** 59 -4. **save it** - - once your mixapp is hosted, anyone can install it by opening the URL and following their browser's PWA installation steps: 60 +3. **save it** 61 + - once your mixapp is hosted on an HTTPS-enabled server, anyone can install it by opening the URL and following their browser's PWA installation steps: 62 - **iOS (Safari)**: tap `···` → `Share` → `View More` → scroll down to reveal and tap `Add to Home Screen` → `Add` 63 - **Android**: 64 - **Firefox**: tap `⋮` → `··· More` → Add to Home screen → Add to home screen 71 ## customization 72 add `custom.css`, `custom.js`, `album_art.jpg`, and/or `icon.png` to `mix/` to customize your mixapp's appearance and behavior. 73 -## local network installation - -<details> -<summary><strong>install on your own devices without a public host</strong></summary> - -<br> 74 +your mixapp's name (displayed on your device's home screen) is set by the first of these that applies: 75 +- the text inside `mix/name.txt`, if it exists 76 +- the album name, if every track's metadata shares the same album name 77 +- `mixapp` (default) 78 79 +## local network installation 80 PWA installation requires a secure (HTTPS) connection. the easiest way to get one is to upload your files to a public host, but publishing files this way is only appropriate for content you have the right to distribute. 81 -if you'd like to install mixapps without pushing to a public host, you can use `https_serve.py` to serve the necessary files over HTTPS on your local network. 82 +if you'd like to install mixapps without pushing to a public host, you can use `serve.py` to serve the necessary files over HTTPS on your local network. 83 84 <h3>how it works</h3> 85 98 99 in practice the risk is small, because an attack needs **three** things to line up at once: your CA's private key has leaked off your computer, the attacker is on a network where they can intercept the installing device's traffic, *and* that device still trusts the CA. deny any one and there's nothing to exploit, so a few habits keep you safe: 100 - **guard your local CA's private key**: as long as you don't move or share this file, it stays safely on your computer (see <a href="#cleaning-up">cleaning up</a>). -- **install over a network you control**: your own wifi, not public/shared. 101 +- **install over a network you control**: your own home network, not a public/shared one. 102 - **leave trust disabled when it isn't needed**: iOS lets you toggle trust on/off per custom CA; on Android, you can remove the CA when you're done and re-add it next time you want to install (see <a href="#cleaning-up">cleaning up</a>). 103 104 <h3>usage</h3> 105 -1. run `./https_serve.py`. it will offer to install `mkcert` if needed, then create a local certificate authority (CA) on your computer. 106 +1. run `./serve.py`. it will offer to install `mkcert` if needed, then create a local certificate authority (CA) on your computer. if you decline, or your computer isn't connected to a network, it will serve over plain HTTP instead (you can still edit your mix, but other devices won't be able to install it). 107 2. **first time on a new device:** scan the first QR code to download the CA certificate, then install and trust it. 108 - **iOS:** 109 1. scanning the QR code prompts you to allow the download. tap **Allow**.<br> 116 117 a device that already trusts the CA from a previous run can skip this step. 118 -3. scan the second QR code to open your mixapp over HTTPS, then follow the <a href="https://hunterirving.github.io/web_workshop/pages/pwa">PWA installation instructions</a> for your device/OS to add it to your homescreen. after the initial installation and cache, mixapps work completely offline; they no longer need the network, server, or certificate. 119 +3. scan the second QR code to open your mixapp over HTTPS, then follow the <a href="https://hunterirving.github.io/web_workshop/pages/pwa">PWA installation instructions</a> for your device/OS to add it to your homescreen. after the initial installation and cache, mixapps work completely offline. they no longer need the network, server, or certificate. 120 121 <h3 id="cleaning-up">cleaning up</h3> 122 124 - **iOS, disable (keep installed):** `Settings` → `General` → `About` → `Certificate Trust Settings` → toggle the CA **off**; you can re-enable this in the future if you'd like to install another mixapp. 125 - **iOS, remove entirely:** `Settings` → `General` → `VPN & Device Management` → tap the profile → **Remove Profile**. 126 - **Android, remove:** `Settings` → `Security` → `Encryption & credentials` → `User credentials` (or `Trusted credentials` → `User`) → tap the mkcert entry → **Remove**. -- **on your computer:** keeping mkcert's CA installed long-term is normal for a development machine, as long as you protect your CA's private key. you'd only need to remove the CA if you were done with it for good or thought your private key may have been exposed. in those cases, `./https_serve.py --reset` removes this tool's own certificates, then asks separately before touching the shared mkcert CA: first to untrust it on your development machine, then to delete its private key. mkcert uses one CA for everything, so if you also use mkcert for other projects, decline those steps to leave your CA intact. -</details> 127 +- **on your computer:** keeping mkcert's CA installed long-term is normal for a development machine, as long as you protect your CA's private key. you'd only need to remove the CA if you were done with it for good or thought your private key may have been exposed. in those cases, `./serve.py --reset` deletes the local server's certificate and private key (in `~/.mixapps/https_certs`), then asks separately before touching the shared mkcert CA: first to untrust it on your development machine, then to delete its private key. mkcert uses one CA for everything, so if you also use mkcert for other projects, decline those steps to leave your CA intact. 128 129 ## licenses 130 this project is licensed under the <a href="LICENSE">GNU General Public License v3.0</a>.
15 window.navigator.standalone === true; 16 17 // Register when installed as a PWA regardless of hostname so a mixapp -// installed over LAN (via https_serve.py) caches for offline use too; 18 +// installed over LAN (via serve.py) caches for offline use too; 19 // a plain browser tab still skips the SW so dev always sees latest files. 20 if ('serviceWorker' in navigator && isInstalled) { 21 window.addEventListener('load', () => {
11 12 If /mix holds only tracks from this CD, ripping the whole disc also 13 downloads its cover art to mix/album_art.jpg, scales it to mix/icon.png -and runs build.py 14 +and names the mixapp after the album in mix/name.txt 15 """ 16 17 import os 19 20 # Hop into the shared venv (managed by scan.py) before doing anything else, 21 # so scan.rescan() has mutagen available when we call it after ripping. -sys.path.insert(0, str(os.path.dirname(os.path.abspath(__file__)))) 22 +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib")) 23 import scan 24 scan.bootstrap(__file__, packages=("mutagen", "discid")) 25 299 return {f.name for f in MIX_DIR.iterdir() if f.suffix.lower() in scan.SUPPORTED_EXTENSIONS} 300 301 -def build_mixapp(album): - """Run build.py, answering its prompts with the album name and the default path""" - print(f"\nBuilding mixapp \"{album}\"...") - subprocess.run([sys.executable, str(SCRIPT_DIR / "build.py")], input=f"{album}\n\n", text=True) 302 +def name_mixapp(album): 303 + """Write the album name to mix/name.txt, unless the mix is already named""" 304 + name_file = MIX_DIR / "name.txt" 305 + if name_file.exists(): 306 + return 307 + name_file.write_text(album + "\n", encoding="utf-8") 308 + print(f"\n✓ Named mixapp \"{album}\" in mix/name.txt") 309 310 311 def find_cd_mount(): 469 470 471 def canonical_name(artist, title, ext): - """Match scan.py / serve.py's canonical 'Artist – Title.ext' form so we 472 + """Match scan.py / editor.py's canonical 'Artist – Title.ext' form so we 473 can dedup against tracks already in /mix.""" 474 return f"{scan._sanitize_filename(artist)} – {scan._sanitize_filename(title)}{ext}" 475 703 download_album_art(release_id, release_group_id) 704 if (MIX_DIR / "album_art.jpg").exists() and not (MIX_DIR / "icon.png").exists(): 705 make_icon() - build_mixapp(album) - print("\nRun https_serve.py to install your mixapp.") 706 + name_mixapp(album) 707 + print("\nRun serve.py to install your mixapp.") 708 elif success_count > 0: 709 print("\nRun serve.py to test your mixapp.") 710
-#!/usr/bin/env python3 -""" -Scans /mix directory and populates tracks.json with metadata -Supports MP3, M4A, OGG, FLAC, and WAV formats -Automatically manages a virtual environment for dependencies -""" - -import os -import sys -import subprocess -import json -from pathlib import Path - -SCRIPT_DIR = Path(__file__).parent.absolute() -VENV_DIR = SCRIPT_DIR / "venv" -MIX_DIR = SCRIPT_DIR / "mix" -OUTPUT_FILE = MIX_DIR / "tracks.json" - - -def setup_venv(packages=("mutagen",)): - """Create the shared venv if missing and ensure each package is installed. - Returns the path to the venv Python interpreter.""" - if sys.platform == "win32": - pip_path = VENV_DIR / "Scripts" / "pip" - python_path = VENV_DIR / "Scripts" / "python" - else: - pip_path = VENV_DIR / "bin" / "pip" - python_path = VENV_DIR / "bin" / "python3" - - if not VENV_DIR.exists() or not python_path.exists(): - if VENV_DIR.exists(): - print("Virtual environment incomplete, recreating...") - import shutil - shutil.rmtree(VENV_DIR) - else: - print("Creating virtual environment...") - - try: - subprocess.check_call([sys.executable, "-m", "venv", str(VENV_DIR)]) - print("Virtual environment created successfully.") - except subprocess.CalledProcessError as e: - print(f"Error creating virtual environment: {e}") - sys.exit(1) - - if not pip_path.exists(): - print("Installing pip in virtual environment...") - try: - subprocess.check_call([str(python_path), "-m", "ensurepip", "--upgrade"]) - except subprocess.CalledProcessError as e: - print(f"Error ensuring pip: {e}") - sys.exit(1) - - for pkg in packages: - check = subprocess.run( - [str(python_path), "-c", f"import {pkg}"], - capture_output=True - ) - if check.returncode != 0: - try: - subprocess.check_call([str(python_path), "-m", "pip", "install", "-q", pkg]) - except subprocess.CalledProcessError: - print(f"Note: Could not install {pkg} (offline?).\n") - - return python_path - - -def bootstrap(script_path, packages=("mutagen",), sentinel="--in-venv"): - """Ensure the calling script is running inside the shared venv - with `packages` available. Re-execs through the venv Python on first call; - returns immediately on the second pass once the sentinel is in argv. - - Each script that uses this should pass its own __file__ as script_path.""" - if sentinel in sys.argv: - sys.argv.remove(sentinel) - return - python_path = setup_venv(packages) - process = subprocess.Popen([str(python_path), script_path, sentinel, *sys.argv[1:]]) - while True: - try: - sys.exit(process.wait()) - except KeyboardInterrupt: - continue - - -def run_in_venv(): - """Re-run this script in the virtual environment (CLI use of scan.py).""" - python_path = setup_venv() - print("Running scanner in virtual environment...\n") - subprocess.check_call([str(python_path), __file__, "--in-venv"]) - sys.exit(0) - - -SUPPORTED_EXTENSIONS = ('.mp3', '.m4a', '.ogg', '.flac', '.wav') - -_INVALID_FILENAME_CHARS = '<>:"/\\|?*' - - -def _sanitize_filename(name): - for char in _INVALID_FILENAME_CHARS: - name = name.replace(char, '') - return name.strip() - - -def _write_tags(audio_file, artist, title, MutagenFile): - """Write artist/title tags to disk if they don't already match. Returns - True if anything was written.""" - try: - audio = MutagenFile(audio_file, easy=True) - if audio is None: - return False - if audio.tags is None: - audio.add_tags() - current_title = audio.tags.get('title', [None])[0] - current_artist = audio.tags.get('artist', [None])[0] - if current_title == title and current_artist == artist: - return False - audio.tags['title'] = title - audio.tags['artist'] = artist - audio.save() - return True - except Exception: - return False - - -def _canonicalize(tracks, has_mutagen, MutagenFile, silent): - """Rename files to 'Artist – Title.ext' and sync ID3 tags so disk state - matches tracks.json metadata. Mutates `tracks` in place; returns a list - of {from, to} renames so callers can migrate any external state (eg. - preloaded blob URLs in connected browser tabs).""" - renames = [] - for entry in tracks: - old_filename = entry['filename'] - ext = Path(old_filename).suffix - artist = _sanitize_filename(entry['artist']) - title = _sanitize_filename(entry['title']) - new_filename = f"{artist} – {title}{ext}" - - old_path = MIX_DIR / old_filename - new_path = MIX_DIR / new_filename - - # Keep tags aligned with the (possibly hand-edited) tracks.json - # entry, regardless of whether a rename is needed. - if has_mutagen and old_path.exists(): - _write_tags(old_path, entry['artist'], entry['title'], MutagenFile) - - if old_filename == new_filename: - continue - if not old_path.exists(): - continue - if new_path.exists(): - # Don't clobber an unrelated file that already occupies the - # canonical name. Leave the entry pointing at its current file. - if not silent: - print(f" Skipping rename {old_filename} -> {new_filename} (target exists)") - continue - try: - old_path.rename(new_path) - entry['filename'] = new_filename - renames.append({'from': old_filename, 'to': new_filename}) - if not silent: - print(f" Renamed: {old_filename} -> {new_filename}") - except Exception as e: - if not silent: - print(f" Error renaming {old_filename}: {e}") - return renames - - -def rescan(silent=False): - """Reconcile tracks.json with /mix. Renames files to canonical - 'Artist – Title.ext' form when they drift, syncing ID3 tags at the same - time. Returns (tracks, changed, renames) where renames is a list of - {from, to} dicts for any files that moved this pass.""" - try: - from mutagen import File as MutagenFile # type: ignore - has_mutagen = True - except ImportError: - MutagenFile = None - has_mutagen = False - if not silent: - print("Mutagen not available. Metadata will be derived from filenames.\n") - - if not MIX_DIR.exists(): - MIX_DIR.mkdir(parents=True, exist_ok=True) - - audio_files = [f for f in MIX_DIR.iterdir() if f.suffix.lower() in SUPPORTED_EXTENSIONS] - - existing_tracks = [] - if OUTPUT_FILE.exists(): - try: - with open(OUTPUT_FILE, 'r', encoding='utf-8') as f: - loaded = json.load(f) - if isinstance(loaded, list): - existing_tracks = loaded - except (json.JSONDecodeError, OSError) as e: - if not silent: - print(f"Warning: could not read existing {OUTPUT_FILE.name} ({e}). Starting fresh.\n") - - existing_by_filename = { - t['filename']: t for t in existing_tracks - if isinstance(t, dict) and 'filename' in t - } - on_disk_filenames = {f.name for f in audio_files} - files_by_name = {f.name: f for f in audio_files} - - def read_metadata(audio_file): - title = None - artist = None - if has_mutagen: - audio = MutagenFile(audio_file, easy=True) - if audio and audio.tags: - title = audio.tags.get('title', [None])[0] - artist = audio.tags.get('artist', [None])[0] - if not title: - title = audio_file.stem - if not artist: - artist = "Unknown Artist" - return {"title": title, "artist": artist, "filename": audio_file.name} - - tracks = [] - removed = [] - for entry in existing_tracks: - if not isinstance(entry, dict) or 'filename' not in entry: - continue - if entry['filename'] in on_disk_filenames: - tracks.append(entry) - else: - removed.append(entry['filename']) - - new_files = sorted( - (files_by_name[name] for name in on_disk_filenames if name not in existing_by_filename), - key=lambda f: f.name, - ) - new_tracks = [] - for audio_file in new_files: - try: - new_tracks.append(read_metadata(audio_file)) - except Exception as e: - if not silent: - print(f"✗ Error reading {audio_file.name}: {e}") - - if not silent: - for track in new_tracks: - print(f"+ {track['artist']} - {track['title']}") - for filename in removed: - print(f"- {filename} (removed; no longer on disk)") - if not new_tracks and not removed: - print("No changes — tracks.json already matches /mix.") - - tracks.extend(new_tracks) - - renames = _canonicalize(tracks, has_mutagen, MutagenFile, silent) - - changed = bool(new_tracks) or bool(removed) or bool(renames) - if changed or not OUTPUT_FILE.exists(): - try: - OUTPUT_FILE.write_text( - json.dumps(tracks, indent='\t', ensure_ascii=False) + '\n', - encoding='utf-8', - ) - except Exception as e: - if not silent: - print(f"\nError writing {OUTPUT_FILE.name}: {e}") - raise - - return tracks, changed, renames - - -def scan_tracks(): - """CLI entry point: rescan and print a summary.""" - if not MIX_DIR.exists(): - print(f"Creating {MIX_DIR.name} directory...") - MIX_DIR.mkdir(parents=True, exist_ok=True) - print(f"✓ {MIX_DIR.name} directory created.") - print(f"\nAdd audio files to the {MIX_DIR.name} directory and run this script again.") - print(f"Supported formats: {', '.join(SUPPORTED_EXTENSIONS)}") - sys.exit(0) - - audio_files = [f for f in MIX_DIR.iterdir() if f.suffix.lower() in SUPPORTED_EXTENSIONS] - if not audio_files: - print(f"No audio files found in {MIX_DIR}") - print(f"\nPlease add audio files to the {MIX_DIR.name} directory and run this script again.") - print(f"Supported formats: {', '.join(SUPPORTED_EXTENSIONS)}") - sys.exit(0) - - print(f"Found {len(audio_files)} audio file(s). Extracting metadata...\n") - tracks, changed, _renames = rescan(silent=False) - if not tracks: - print("\nNo valid audio files could be processed.") - sys.exit(1) - if changed: - print(f"\n✓ Updated {OUTPUT_FILE.name} ({len(tracks)} track(s)).") - - -def main(): - """Main entry point""" - # Check if we're already running in venv - if "--in-venv" not in sys.argv: - run_in_venv() - else: - scan_tracks() - - -if __name__ == "__main__": - main()
1 #!/usr/bin/env python3 2 """ -Starts HTTP server for local testing -Automatically manages a virtual environment for dependencies 3 +Serve your mixapp so you can edit it, and install it on devices on your local 4 +network as a PWA without a public web host or tunnel. 5 + 6 +Uses mkcert to mint a locally-trusted certificate for this machine's LAN IP. A 7 +device won't trust that cert until it trusts mkcert's root CA, so we print 8 +two QR codes: 9 + 10 + 1. an HTTP link that hands the device the mkcert root CA (the public root 11 + cert, no secret; served to any device until you stop the script) 12 + 2. an HTTPS link to the mixapp itself, for PWA installation 13 + 14 +Both servers shut down together on Ctrl+C. 15 + 16 +Without mkcert or a network connection, it falls back to plain HTTP. Editing 17 +still works, but other devices can't install the mixapp. 18 + 19 +After scanning the first QR code, install + trust the CA on the device: 20 + iOS: Settings → General → VPN & Device Management → install the profile, 21 + then Settings → General → About → Certificate Trust Settings → 22 + enable full trust 23 + Android: open the downloaded file and follow the prompt to install it as a 24 + CA certificate 25 + 26 +Run with --reset to revoke the CA and delete the local certificates. 27 """ 28 29 import http.server 30 import socketserver 31 import socket 32 +import ssl 33 import sys 34 import os -import json -import queue -import threading 35 import subprocess -import time -import urllib.parse 36 +import threading 37 from pathlib import Path 38 -DEFAULT_PORT = 8000 -SCRIPT_DIR = Path(__file__).parent.absolute() -VENV_DIR = SCRIPT_DIR / "venv" -MIX_DIR = SCRIPT_DIR / "mix" -TRACKS_PATH = MIX_DIR / "tracks.json" - -PUBLIC_FILES = {"index.html", "manifest.json", "service-worker.js"} -PUBLIC_DIRS = {"resources", "mix"} 39 +sys.path.insert(0, str(Path(__file__).parent / "lib")) 40 +import editor 41 -SUPPORTED_UPLOAD_EXTENSIONS = ('.mp3', '.m4a', '.ogg', '.flac', '.wav') -MAX_UPLOAD_BYTES = 200 * 1024 * 1024 # 200 MB per request 42 +HTTP_PORT = 8000 # preferred; falls back to the next free port 43 +CERT_HTTP_PORT = 8001 # preferred; falls back to the next free port 44 +HTTPS_PORT = 8443 # preferred; falls back to the next free port 45 +SCRIPT_DIR = Path(__file__).parent.absolute() 46 +CERT_DIR = Path.home() / ".mixapps" / "https_certs" 47 +CERT_FILE = CERT_DIR / "cert.pem" 48 +KEY_FILE = CERT_DIR / "key.pem" 49 -# Serializes all reads/writes of tracks.json so rescans, reorders, and future -# uploads can't race each other. -tracks_lock = threading.Lock() 50 +# Path the phone fetches the root CA from. Anything else over HTTP 404s. 51 +CA_DOWNLOAD_PATH = "/rootCA.pem" 52 -# Set of per-client SSE queues. Each connected /events client gets a queue; -# broadcast_tracks() pushes the latest tracks list onto every queue. -sse_subscribers = set() -sse_subscribers_lock = threading.Lock() 53 -# Canonical serialization of the most recently broadcast tracks list, so we -# can fire on any content change (file add/remove/reorder or a hand-edit to -# tracks.json's metadata) instead of only when /mix's filenames change. -last_broadcast_serialized = None 54 +def base_path_for(mix_name): 55 + """Where this server mounts the app. Each mix gets its own path so mixapps 56 + installed from this machine don't share one origin-wide install.""" 57 + return "/" + mix_name.lower().replace(" ", "_") + "/" 58 59 60 def run_in_venv(): - """Re-run this script in the shared venv with serve.py's deps available""" 61 + """Re-run this script in the shared venv with qrcode available, 62 + forwarding any user flags (eg. --reset) to the re-exec.""" 63 import scan - python_path = scan.setup_venv(packages=("qrcode", "mutagen")) 64 + # mutagen: editor.py's upload path reads tags to canonicalize filenames. 65 + # psutil: finds this machine's LAN IP on networks with no internet route. 66 + python_path = scan.setup_venv(packages=("qrcode", "mutagen", "psutil")) 67 try: - subprocess.check_call([str(python_path), __file__, "--in-venv"]) 68 + subprocess.check_call([str(python_path), __file__, "--in-venv", *sys.argv[1:]]) 69 except (KeyboardInterrupt, subprocess.CalledProcessError): 70 pass 71 sys.exit(0) 72 73 74 def get_local_ip(): - """Get the local IP address for network access""" 75 + """Get the LAN IP other devices on the network can reach this machine at.""" 76 try: - # Create a socket to determine the local IP 77 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - # Connect to a public DNS server (doesn't actually send data) - s.connect(("8.8.8.8", 80)) 78 + # Asks which local address would route to a reserved documentation 79 + # address (RFC 5737). Nothing is sent, but it needs a default route. 80 + s.connect(("192.0.2.1", 80)) 81 local_ip = s.getsockname()[0] 82 s.close() 83 return local_ip 84 except Exception: - return "Unable to determine" 85 + return private_interface_ip() 86 + 87 + 88 +def private_interface_ip(): 89 + """The first private IPv4 address on any interface, for networks with no 90 + internet route. None if psutil isn't installed or there isn't one.""" 91 + try: 92 + import psutil 93 + except ImportError: 94 + return None 95 + import ipaddress 96 + for addresses in psutil.net_if_addrs().values(): 97 + for address in addresses: 98 + if address.family != socket.AF_INET: 99 + continue 100 + ip = ipaddress.ip_address(address.address) 101 + if ip.is_private and not ip.is_loopback and not ip.is_link_local: 102 + return address.address 103 + return None 104 105 -def find_available_port(start_port=DEFAULT_PORT, max_attempts=10): - """Find an available port starting from start_port""" 106 +def find_available_port(start_port, max_attempts=20): 107 + """Return the first bindable port at or after start_port. Uses SO_REUSEADDR 108 + so a socket lingering in TIME_WAIT from a prior run doesn't block us.""" 109 for port in range(start_port, start_port + max_attempts): 110 + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 111 + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 112 try: - with socketserver.TCPServer(("", port), None) as s: - return port 113 + s.bind(("", port)) 114 + return port 115 except OSError: 116 continue 117 + finally: 118 + s.close() 119 return None 120 121 -def print_qr_code(url): - """Generate and print a QR code using block characters""" 122 +def print_qr_code(url, caption): 123 + """Generate and print a QR code using block characters.""" 124 try: 125 import qrcode 126 133 qr.add_data(url) 134 qr.make(fit=True) 135 - # Get the QR code matrix 136 matrix = qr.get_matrix() 137 138 + print(f"\n{caption}\n") 139 for y in range(0, len(matrix), 2): - line = "" 140 + line = " " 141 for x in range(len(matrix[y])): 142 top = matrix[y][x] 143 bottom = matrix[y + 1][x] if y + 1 < len(matrix) else False 150 else: 151 line += " " 152 print(line) - print() 153 except ImportError: - print("\nQR code generation unavailable (qrcode library not installed)") 154 + print(f"\n{caption}\n (QR unavailable; open this URL manually) {url}") 155 except Exception as e: - print(f"\nCould not generate QR code: {e}") 156 + print(f"\nCould not generate QR code: {e}\n open manually: {url}") 157 + 158 + 159 +def mkcert_install_command(): 160 + """Best-guess (command, package-manager-label) to install mkcert on this 161 + platform, or (None, None) if no known manager is on PATH.""" 162 + from shutil import which 163 + if sys.platform == "darwin": 164 + if which("brew"): 165 + return (["brew", "install", "mkcert"], "Homebrew") 166 + elif sys.platform == "win32": 167 + if which("choco"): 168 + return (["choco", "install", "mkcert", "-y"], "Chocolatey") 169 + if which("scoop"): 170 + return (["scoop", "install", "mkcert"], "Scoop") 171 + else: # linux / other unix 172 + # Most distros package mkcert; pick whichever manager is present. 173 + if which("apt"): 174 + return (["sudo", "apt", "install", "-y", "mkcert"], "apt") 175 + if which("dnf"): 176 + return (["sudo", "dnf", "install", "-y", "mkcert"], "dnf") 177 + if which("pacman"): 178 + return (["sudo", "pacman", "-S", "--noconfirm", "mkcert"], "pacman") 179 + if which("brew"): 180 + return (["brew", "install", "mkcert"], "Homebrew") 181 + return (None, None) 182 + 183 + 184 +def manual_install_hint(): 185 + """Platform-appropriate manual install instructions for mkcert.""" 186 + if sys.platform == "darwin": 187 + return "brew install mkcert (https://github.com/FiloSottile/mkcert)" 188 + if sys.platform == "win32": 189 + return "choco install mkcert OR scoop install mkcert (https://github.com/FiloSottile/mkcert)" 190 + return "install 'mkcert' via your package manager (https://github.com/FiloSottile/mkcert)" 191 + 192 + 193 +def require_mkcert(): 194 + """Ensure mkcert is on PATH, offering to install it if it isn't. Returns 195 + False if it's still missing, so the caller can fall back to plain HTTP.""" 196 + from shutil import which 197 + if which("mkcert") is not None: 198 + return True 199 + 200 + print("To let your phone and other devices install your mixapp, this server") 201 + print("needs HTTPS, which it sets up with mkcert. mkcert isn't installed yet.\n") 202 + print("What mkcert does:") 203 + print(" • creates a certificate authority (CA) on this computer and tells this") 204 + print(" computer to trust it (you may be asked for your password)") 205 + print(" • keeps the CA's private key on this computer. Anyone who got a copy") 206 + print(" could impersonate websites to this computer and to any device that") 207 + print(" trusts the CA, so don't share it.\n") 208 + print("Without mkcert, the server uses plain HTTP. You can still edit your mix") 209 + print("here, but other devices can't install it.\n") 210 + 211 + cmd, label = mkcert_install_command() 212 + if cmd is None: 213 + print(f"To use HTTPS, install mkcert manually: {manual_install_hint()}") 214 + return False 215 216 + answer = input(f"Install mkcert with {label} ({' '.join(cmd)})? [y/N] ").strip().lower() 217 + if answer not in ("y", "yes"): 218 + print(f"To use HTTPS later, install mkcert: {manual_install_hint()}") 219 + return False 220 -def read_tracks(): - """Read tracks.json from disk; return [] if missing or malformed.""" - if not TRACKS_PATH.exists(): - return [] 221 try: - with open(TRACKS_PATH, 'r', encoding='utf-8') as f: - loaded = json.load(f) - return loaded if isinstance(loaded, list) else [] - except (json.JSONDecodeError, OSError): - return [] - - -def _move_track_to(tracks, filename, insert_after): - """Reorder `tracks` in place so the entry matching `filename` lands at - insert_after + 1 (clamped). Persists tracks.json if the order actually - changed. Returns True iff a move happened. Caller must hold tracks_lock.""" - cur_idx = next((i for i, t in enumerate(tracks) if t.get('filename') == filename), -1) - if cur_idx == -1: 222 + subprocess.check_call(cmd) 223 + except (subprocess.CalledProcessError, KeyboardInterrupt): 224 + print(f"\nInstall failed. To use HTTPS, install mkcert manually: {manual_install_hint()}") 225 return False - target_idx = max(0, min(insert_after + 1, len(tracks) - 1)) - if target_idx == cur_idx: 226 + 227 + if which("mkcert") is None: 228 + print("mkcert still isn't on PATH. Open a new terminal and run serve.py again.") 229 return False - entry = tracks.pop(cur_idx) - if target_idx > cur_idx: - target_idx -= 1 - tracks.insert(target_idx, entry) - TRACKS_PATH.write_text( - json.dumps(tracks, indent='\t', ensure_ascii=False) + '\n', - encoding='utf-8', - ) 230 return True 231 232 -def _canonical_name_for(audio_path, fallback_name): - """Return the 'Artist – Title.ext' filename scan would canonicalize this - upload to, so we can dedup BEFORE moving the file into /mix. Returns None - if metadata can't be read.""" - import scan - try: - from mutagen import File as MutagenFile # type: ignore - except ImportError: - return None - try: - audio = MutagenFile(audio_path, easy=True) - except Exception: - return None - title = None - artist = None - if audio and audio.tags: - title = audio.tags.get('title', [None])[0] - artist = audio.tags.get('artist', [None])[0] - if not title: - title = Path(fallback_name).stem - if not artist: - artist = "Unknown Artist" - ext = Path(fallback_name).suffix - return f"{scan._sanitize_filename(artist)} – {scan._sanitize_filename(title)}{ext}" - - -def broadcast_tracks(tracks, renames=None): - """Push the current tracks list to every connected SSE client if its - content differs from the last broadcast. `renames`, when non-empty, - carries [{from, to}, ...] so clients can migrate per-track state (eg. - preloaded blob URLs) without losing it across a canonicalizing rename. - Caller must hold tracks_lock.""" - global last_broadcast_serialized - serialized = json.dumps(tracks, ensure_ascii=False, sort_keys=True) - if serialized == last_broadcast_serialized and not renames: - return - last_broadcast_serialized = serialized - payload = {'tracks': tracks, 'renames': renames or []} - with sse_subscribers_lock: - subscribers = list(sse_subscribers) - for q in subscribers: - try: - q.put_nowait(payload) - except queue.Full: - pass - 233 +def ca_root_file(): 234 + """Path to mkcert's root CA cert (rootCA.pem).""" 235 + caroot = subprocess.run( 236 + ["mkcert", "-CAROOT"], capture_output=True, text=True 237 + ).stdout.strip() 238 + return Path(caroot) / "rootCA.pem" 239 -def rescan_and_maybe_broadcast(): - """Rescan /mix, then broadcast if the resulting tracks list differs from - what we last sent.""" - import scan - tracks, _changed, renames = scan.rescan(silent=True) - broadcast_tracks(tracks, renames=renames) - return tracks - - -def start_rescan_ticker(interval=1.0): - """Background thread that periodically rescans /mix so changes made - directly on disk (eg. user dragging a file in or `rm`-ing one from the - terminal) reach connected clients without anyone hitting the server.""" - def tick(): - while True: - time.sleep(interval) - try: - with tracks_lock: - rescan_and_maybe_broadcast() - except Exception as e: - # Don't let a bad scan kill the ticker. - print(f"rescan tick error: {e}", file=sys.stderr) - t = threading.Thread(target=tick, daemon=True) - t.start() - - -class TrackRequestHandler(http.server.SimpleHTTPRequestHandler): - # keep-alive; every response below needs a Content-Length or must close - protocol_version = 'HTTP/1.1' - # don't let idle connections pin threads forever - timeout = 60 - # Nagle would stall the body write behind the header write - disable_nagle_algorithm = True - - def do_GET(self): - # Rescan /mix on every tracks.json fetch so the page always sees - # what's actually on disk (added via rip.py/buy.py or by hand). - if self.path == '/mix/tracks.json': - with tracks_lock: - rescan_and_maybe_broadcast() - return super().do_GET() 240 - if self.path == '/events': - return self._serve_sse() - - return super().do_GET() - - def _is_public(self, fs_path): - parts = Path(fs_path).relative_to(self.directory).parts - if not parts: - return True - if any(part.startswith('.') for part in parts): - return False - if len(parts) == 1: - return parts[0] in PUBLIC_FILES - name = parts[-1].lower() - return parts[0] in PUBLIC_DIRS and name != 'readme.md' and not name.endswith('.uploading') - - def send_head(self): - if not self._is_public(self.translate_path(self.path)): - self.send_error(404) - return None - return super().send_head() - - def list_directory(self, path): - self.send_error(404) - return None 241 +def ensure_ca_installed(): 242 + """Ensure mkcert's local CA exists and is trusted by this machine. 243 + May prompt for your password to write to the system trust store.""" 244 + if not ca_root_file().exists(): 245 + print("Setting up mkcert local CA (you may be prompted for your password)...") 246 + subprocess.check_call(["mkcert", "-install"]) 247 - def _serve_sse(self): - """Server-Sent Events stream of tracks.json changes.""" - self.send_response(200) - self.send_header('Content-Type', 'text/event-stream') - self.send_header('Cache-Control', 'no-cache') - # The stream has no Content-Length, so under HTTP/1.1 it has to be - # delimited by closing the socket. Sending this also flips - # close_connection, so the handler won't try to reuse the socket. - self.send_header('Connection', 'close') - self.send_header('X-Accel-Buffering', 'no') - self.end_headers() - - q = queue.Queue(maxsize=16) - with sse_subscribers_lock: - sse_subscribers.add(q) 248 249 +def ensure_leaf_cert(local_ip): 250 + """Mint a cert/key for this machine's LAN IP (and localhost) if missing 251 + or minted for a different IP.""" 252 + CERT_DIR.mkdir(parents=True, exist_ok=True) 253 + if CERT_FILE.exists() and KEY_FILE.exists(): 254 try: - # Initial sync so a fresh tab gets the current state without - # waiting for the next change. No renames context: a fresh - # client has no prior state to migrate from. - with tracks_lock: - initial = read_tracks() - self._send_sse_event('tracks', {'tracks': initial, 'renames': []}) - - while True: - try: - payload = q.get(timeout=15) - self._send_sse_event('tracks', payload) - except queue.Empty: - # Heartbeat keeps proxies and idle connections from - # closing the stream. - self.wfile.write(b': keepalive\n\n') - self.wfile.flush() - except (BrokenPipeError, ConnectionResetError, OSError): 255 + sans = ssl._ssl._test_decode_cert(str(CERT_FILE)).get("subjectAltName", ()) 256 + except (AttributeError, OSError): 257 + print("Couldn't read the existing certificate.") 258 + else: 259 + old_ips = [v for k, v in sans if k == "IP Address" and v != "127.0.0.1"] 260 + if local_ip in old_ips: 261 + return 262 + print(f"This machine's LAN IP changed ({', '.join(old_ips)} → {local_ip}).") 263 + print(f"Minting certificate for {local_ip}...") 264 + subprocess.check_call([ 265 + "mkcert", 266 + "-cert-file", str(CERT_FILE), 267 + "-key-file", str(KEY_FILE), 268 + local_ip, "localhost", "127.0.0.1", 269 + ]) 270 + 271 + 272 +def start_ca_server(local_ip): 273 + """Start a plain-HTTP server that hands out the mkcert root CA, and return 274 + it running. The CA is the *public* root cert (no secret), so there's no 275 + reason to limit how many times or to how many devices it's served. leave 276 + it up alongside the HTTPS server so you can set up multiple devices, and 277 + tear both down together on Ctrl+C. Caller owns shutdown.""" 278 + ca_file = ca_root_file() 279 + if not ca_file.exists(): 280 + print(f"Error: root CA not found at {ca_file}") 281 + sys.exit(1) 282 + 283 + ca_bytes = ca_file.read_bytes() 284 + 285 + class CAHandler(http.server.BaseHTTPRequestHandler): 286 + def log_message(self, *args): 287 pass - finally: - with sse_subscribers_lock: - sse_subscribers.discard(q) - - def _reply_status(self, status, body=b''): - """Short reply with a Content-Length. Errors also close the socket, - since an early return can leave an unread body in the buffer.""" - if isinstance(body, str): - body = body.encode('utf-8') - self.send_response(status) - self.send_header('Content-Length', str(len(body))) - if status >= 400: - self.send_header('Connection', 'close') - self.end_headers() - if body: - try: - self.wfile.write(body) - except (BrokenPipeError, ConnectionResetError): - pass 288 - def _reply_json(self, status, payload): - body = json.dumps(payload).encode('utf-8') - self.send_response(status) - self.send_header('Content-Type', 'application/json') - self.send_header('Content-Length', str(len(body))) - self.end_headers() - self.wfile.write(body) - - def _send_sse_event(self, event, data): - payload = json.dumps(data, ensure_ascii=False) - message = f'event: {event}\ndata: {payload}\n\n'.encode('utf-8') - self.wfile.write(message) - self.wfile.flush() - - def do_POST(self): - # Local-only: receive a reordered tracks array and overwrite tracks.json - if self.path != '/tracks': - self._reply_status(404) - return - length = int(self.headers.get('Content-Length', '0')) - payload = json.loads(self.rfile.read(length)) - with tracks_lock: - TRACKS_PATH.write_text( - json.dumps(payload, indent='\t', ensure_ascii=False) + '\n', - encoding='utf-8', 289 + def do_GET(self): 290 + # Redirect bare visits to the download path so a typo'd / still works. 291 + if self.path in ("/", "/index.html"): 292 + self.send_response(302) 293 + self.send_header("Location", CA_DOWNLOAD_PATH) 294 + self.end_headers() 295 + return 296 + if self.path != CA_DOWNLOAD_PATH: 297 + self.send_error(404) 298 + return 299 + # x-x509-ca-cert makes iOS offer to install it as a CA profile. 300 + self.send_response(200) 301 + self.send_header("Content-Type", "application/x-x509-ca-cert") 302 + self.send_header("Content-Length", str(len(ca_bytes))) 303 + self.send_header( 304 + "Content-Disposition", 'attachment; filename="rootCA.pem"' 305 ) - broadcast_tracks(payload) - self.send_response(204) - self.end_headers() - - def do_PUT(self): - # Local-only: drag-and-drop upload from a connected browser. - # Path is /upload/<url-encoded-filename>; headers carry the - # desired insertion index (X-Insert-After: -1 means prepend). - prefix = '/upload/' - if not self.path.startswith(prefix): - self._reply_status(404) - return 306 + self.end_headers() 307 + try: 308 + self.wfile.write(ca_bytes) 309 + except (BrokenPipeError, ConnectionResetError): 310 + return 311 - raw_name = urllib.parse.unquote(self.path[len(prefix):]) - # Strip any client-supplied path components. - filename = Path(raw_name).name - ext = Path(filename).suffix.lower() - if not filename or ext not in SUPPORTED_UPLOAD_EXTENSIONS: - self._reply_status(415) 312 + port = find_available_port(CERT_HTTP_PORT) 313 + if port is None: 314 + print(f"Error: no free port near {CERT_HTTP_PORT} for the CA server.") 315 + sys.exit(1) 316 + http.server.HTTPServer.allow_reuse_address = True 317 + httpd = http.server.HTTPServer(("", port), CAHandler) 318 + threading.Thread(target=httpd.serve_forever, daemon=True).start() 319 + 320 + cert_url = f"http://{local_ip}:{port}{CA_DOWNLOAD_PATH}" 321 + print("=" * 69) 322 + print("STEP 1: install + trust the local CA on each device (first time only)") 323 + print("=" * 69) 324 + print_qr_code(cert_url, "Scan to download the root certificate:") 325 + print(f" {cert_url}") 326 + print("\nOn iOS, after downloading:") 327 + print(" • Settings → General → VPN & Device Management → install the profile") 328 + print(" • Settings → General → About → Certificate Trust Settings →") 329 + print(" toggle ON full trust for the mkcert CA") 330 + print("\nOn Android, after downloading:") 331 + print(" • open the downloaded file, or Settings → Security → Encryption &") 332 + print(" credentials → Install a certificate → CA certificate, then confirm") 333 + print(" • installing the CA is what makes it trusted; there's no separate") 334 + print(" trust toggle (exact menu names vary by version/manufacturer)") 335 + print("\n(skip this step on a device that already trusts the CA from a previous run)") 336 + return httpd 337 + 338 + 339 +class ThreadingServer(socketserver.ThreadingTCPServer): 340 + daemon_threads = True 341 + allow_reuse_address = True 342 + # default backlog of 5 drops connections when a device precaches in bursts 343 + request_queue_size = 128 344 + 345 + 346 +class TLSThreadingServer(ThreadingServer): 347 + """Threading server that negotiates TLS in the worker thread, so 348 + handshakes run in parallel.""" 349 + 350 + def __init__(self, server_address, handler_cls, ssl_context): 351 + self.ssl_context = ssl_context 352 + super().__init__(server_address, handler_cls) 353 + 354 + def process_request_thread(self, request, client_address): 355 + try: 356 + request.settimeout(20) # cap how long a dead client's handshake lingers 357 + request = self.ssl_context.wrap_socket(request, server_side=True) 358 + request.settimeout(None) 359 + except (ssl.SSLError, OSError): 360 + # Untrusted CA, a probe, or a client that walked away. 361 + self.shutdown_request(request) 362 return 363 + super().process_request_thread(request, client_address) 364 - length = int(self.headers.get('Content-Length', '0')) - if length <= 0 or length > MAX_UPLOAD_BYTES: - self._reply_status(413) - return 365 - try: - insert_after = int(self.headers.get('X-Insert-After', '-1')) - except ValueError: - insert_after = -1 - - # Stream the body to a temp file in MIX_DIR, then move into place - # atomically so a partial write is never visible to the rescan. - MIX_DIR.mkdir(parents=True, exist_ok=True) - tmp_path = MIX_DIR / (filename + '.uploading') - try: - with open(tmp_path, 'wb') as out: - remaining = length - while remaining > 0: - chunk = self.rfile.read(min(64 * 1024, remaining)) - if not chunk: - break - out.write(chunk) - remaining -= len(chunk) - if remaining != 0: - tmp_path.unlink(missing_ok=True) - self._reply_status(400) - return 366 +def make_handler(base_path): 367 + """editor.py's handler, mounted under base_path. It adds the SSE change 368 + stream (/events), reorder save (POST /tracks), drag-drop upload 369 + (PUT /upload/<name>), and delete (DELETE /tracks/<name>). Those endpoints 370 + are root-absolute, so base_path stripping (GET-only) doesn't touch them.""" 371 + class QuietHandler(editor.TrackRequestHandler): 372 + def end_headers(self): 373 + self.send_header("Cache-Control", "no-cache") 374 + super().end_headers() 375 - with tracks_lock: - import scan - # Dedup by canonical name: if a file with the canonical - # "Artist – Title.ext" name already lives in /mix, drop - # the upload and just reorder the existing entry to the - # requested slot so the client still gets the FLIP. - canonical = _canonical_name_for(tmp_path, filename) - if canonical and (MIX_DIR / canonical).exists(): - tmp_path.unlink(missing_ok=True) - tracks = read_tracks() - moved = _move_track_to(tracks, canonical, insert_after) - if moved: - broadcast_tracks(tracks) - final_index = next((i for i, t in enumerate(tracks) if t.get('filename') == canonical), -1) - self._reply_json(200, {'filename': canonical, 'duplicate': True, 'moved': moved, 'final_index': final_index}) - return - - tmp_path.rename(MIX_DIR / filename) - placed_name = filename - - tracks, _changed, renames = scan.rescan(silent=True) - - # Find the canonical (post-canonicalize) filename for the - # upload by following the rename chain. - new_name = placed_name - for r in renames: - if r['from'] == new_name: - new_name = r['to'] - - _move_track_to(tracks, new_name, insert_after) - broadcast_tracks(tracks, renames=renames) - final_index = next((i for i, t in enumerate(tracks) if t.get('filename') == new_name), -1) - - self._reply_json(200, {'filename': new_name, 'final_index': final_index}) - except Exception as e: - tmp_path.unlink(missing_ok=True) - self._reply_status(500, str(e)) - - def do_DELETE(self): - # Local-only: remove a track's audio file from /mix and prune - # tracks.json. Path is /tracks/<url-encoded-filename>. - prefix = '/tracks/' - if not self.path.startswith(prefix): - self._reply_status(404) - return 376 + def log_message(self, *args): 377 + pass 378 - filename = urllib.parse.unquote(self.path[len(prefix):]) - target = (MIX_DIR / filename).resolve() - try: - target.relative_to(MIX_DIR.resolve()) - except ValueError: - self._reply_status(400) - return - if target == TRACKS_PATH.resolve() or target.name != filename: - self._reply_status(400) - return - with tracks_lock: 379 + def handle(self): 380 try: - target.unlink() - except FileNotFoundError: 381 + super().handle() 382 + except (BrokenPipeError, ConnectionResetError, ssl.SSLError): 383 pass - except OSError as e: - self._reply_status(500, str(e)) 384 + 385 + def translate_path(self, path): 386 + # Strip the manifest base prefix so /mixapp_name/foo maps to ./foo. 387 + if base_path != "/" and path.startswith(base_path): 388 + path = "/" + path[len(base_path):] 389 + return super().translate_path(path) 390 + 391 + def do_GET(self): 392 + # Bounce a bare root visit into the app so manual navigation works. 393 + if base_path != "/" and self.path in ("/", "/index.html"): 394 + self.send_response(302) 395 + self.send_header("Location", base_path) 396 + self.send_header("Content-Length", "0") 397 + self.end_headers() 398 return - tracks = [t for t in read_tracks() if t.get('filename') != filename] - TRACKS_PATH.write_text( - json.dumps(tracks, indent='\t', ensure_ascii=False) + '\n', - encoding='utf-8', - ) - broadcast_tracks(tracks) - self.send_response(204) - self.end_headers() 399 + # super() is editor.TrackRequestHandler.do_GET, which handles 400 + # /events (SSE) and rescans on /mix/tracks.json before serving. 401 + return super().do_GET() 402 -def start_server(): - """Start the HTTP server (runs after venv is set up)""" - # Change to script directory - os.chdir(SCRIPT_DIR) 403 + return QuietHandler 404 + 405 + 406 +def serve_http(local_ip=None): 407 + """Serve SCRIPT_DIR over plain HTTP, for when HTTPS isn't available. 408 + Runs until Ctrl+C.""" 409 + port = find_available_port(HTTP_PORT) 410 + if port is None: 411 + print(f"Error: no free port near {HTTP_PORT} for the HTTP server.") 412 + sys.exit(1) 413 + 414 + with ThreadingServer(("", port), make_handler("/")) as httpd: 415 + print("\n" + "=" * 60) 416 + print("Serving over plain HTTP") 417 + print("=" * 60) 418 + print(f"\nEdit your mix at: http://localhost:{port}") 419 + if local_ip: 420 + print(f"Devices on your network can open http://{local_ip}:{port}") 421 + print("but can't install it, because installing needs HTTPS.") 422 + print("\nPress Ctrl+C to stop the server") 423 - # Periodically rescan /mix so on-disk changes propagate to the UI even - # when nothing is hitting an HTTP endpoint. - start_rescan_ticker() 424 + try: 425 + httpd.serve_forever() 426 + except KeyboardInterrupt: 427 + print("\n\nShutting down...") 428 - # Find an available port - port = find_available_port(DEFAULT_PORT) 429 430 +def serve_https(local_ip, base_path, ca_httpd=None): 431 + """Serve SCRIPT_DIR over HTTPS for PWA installation, mounted under 432 + base_path so the installed app's start_url resolves. Runs until Ctrl+C, 433 + then also shuts down the CA HTTP server (if given).""" 434 + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) 435 + ctx.load_cert_chain(certfile=str(CERT_FILE), keyfile=str(KEY_FILE)) 436 + 437 + port = find_available_port(HTTPS_PORT) 438 if port is None: - print(f"Error: Could not find an available port (tried {DEFAULT_PORT}-{DEFAULT_PORT + 9})") 439 + print(f"Error: no free port near {HTTPS_PORT} for the HTTPS server.") 440 + if ca_httpd is not None: 441 + ca_httpd.shutdown() 442 + ca_httpd.server_close() 443 sys.exit(1) 444 - # Get local IP for network access - local_ip = get_local_ip() 445 + with TLSThreadingServer(("", port), make_handler(base_path), ctx) as httpd: 446 + https_url = f"https://{local_ip}:{port}{base_path}" 447 - # Create server 448 + print("\n" + "=" * 59) 449 + print("STEP 2: install your mixapp (once the device trusts the CA)") 450 + print("=" * 59) 451 + print_qr_code(https_url, "Scan to open your mixapp over HTTPS:") 452 + print(f" {https_url}") 453 + print("\nThen install it as a PWA: https://hunterirving.github.io/web_workshop/pages/pwa") 454 + print("\nPress Ctrl+C to stop the server(s)") 455 - # Suppress default logging and broken pipe errors - class QuietHandler(TrackRequestHandler): - def end_headers(self): - self.send_header('Cache-Control', 'no-cache') - super().end_headers() 456 + try: 457 + httpd.serve_forever() 458 + except KeyboardInterrupt: 459 + print("\n\nShutting down...") 460 + finally: 461 + if ca_httpd is not None: 462 + ca_httpd.shutdown() 463 + ca_httpd.server_close() 464 - def log_message(self, format, *args): - pass 465 - def handle(self): - """Handle requests and suppress broken pipe errors""" - try: - super().handle() - except (BrokenPipeError, ConnectionResetError): - # Browser cancelled the request (normal for media streaming/preloading) - pass 466 +def caroot_dir(): 467 + """Path to mkcert's CAROOT folder (holds rootCA.pem and rootCA-key.pem).""" 468 + caroot = subprocess.run( 469 + ["mkcert", "-CAROOT"], capture_output=True, text=True 470 + ).stdout.strip() 471 + return Path(caroot) if caroot else None 472 473 - class ThreadedServer(socketserver.ThreadingTCPServer): - daemon_threads = True - # default backlog of 5 drops connections when a browser opens several at once - request_queue_size = 128 474 +def reset_certs(): 475 + """Opt-in teardown, in two stages so it's safe alongside other mkcert use. 476 - try: - with ThreadedServer(("", port), QuietHandler) as httpd: - local_url = f"http://localhost:{port}" - network_url = f"http://{local_ip}:{port}" 477 + mkcert keeps ONE shared CA per machine, so anything else you run with 478 + mkcert trusts the same CA. Stage 1 removes only THIS tool's own leaf certs 479 + (always safe). Stage 2 removes the shared mkcert CA itself (untrust + optional 480 + key deletion). Guarded, because it affects every project that uses 481 + mkcert, not just this one.""" 482 + from shutil import rmtree, which 483 - print("=" * 60) - print("💿 mixapps · local test server") - print("=" * 60 + "\n") 484 + # Stage 1: our own leaf certs. 485 + if CERT_DIR.exists(): 486 + rmtree(CERT_DIR) 487 + print(f"Removed this tool's local certificates ({CERT_DIR}).") 488 + else: 489 + print("No local certificates to remove.") 490 - # Print QR code for easy mobile access - print_qr_code(network_url) 491 + # Stage 2: the shared mkcert CA. Skip entirely unless asked, since other 492 + # projects on this machine may rely on it and we can't detect them. 493 + print( 494 + "\nThe mkcert CA itself is SHARED across everything you use mkcert for" 495 + " on this computer, not just this tool. Leaving it installed is normal." 496 + ) 497 + answer = input( 498 + "Also remove the shared mkcert CA (untrust it system-wide)? [y/N] " 499 + ).strip().lower() 500 + if answer not in ("y", "yes"): 501 + print("Left the mkcert CA in place.") 502 + return 503 - print(f"Local access: {local_url}") - print(f"Network access: {network_url}") - print("\nPress Ctrl+C to stop the server") 504 + if which("mkcert"): 505 + try: 506 + subprocess.check_call(["mkcert", "-uninstall"]) 507 + print("Stopped this computer from trusting the mkcert CA.") 508 + except subprocess.CalledProcessError as e: 509 + print(f"mkcert -uninstall failed: {e}") 510 + 511 + # mkcert -uninstall removes trust but does NOT delete the CA. The private key 512 + # (rootCA-key.pem) is the sensitive material, so offer to delete it too, with 513 + # a separate confirmation since it's irreversible and shared. 514 + caroot = caroot_dir() 515 + if caroot and (caroot / "rootCA-key.pem").exists(): 516 + print( 517 + "\nThe CA's PRIVATE KEY is still on disk at:\n" 518 + f" {caroot}\n" 519 + "Per mkcert: \"the rootCA-key.pem file ... gives complete power to\n" 520 + "intercept secure requests from your machine. Do not share it.\"\n" 521 + "Deleting it removes the shared CA entirely; future mkcert use\n" 522 + "(here or in any project) will generate a brand-new one." 523 + ) 524 + ans2 = input("Delete the CA key + folder now? [y/N] ").strip().lower() 525 + if ans2 in ("y", "yes"): 526 + rmtree(caroot) 527 + print(f"Removed {caroot}") 528 + else: 529 + print("Left the CA key in place.") 530 - # Serve forever - httpd.serve_forever() 531 + print("\nNote: this does NOT touch any device; remove or untrust the CA\n" 532 + "there separately (see the instructions printed during install).") 533 - except KeyboardInterrupt: - print("\n\nShutting down server...") - sys.exit(0) - except Exception as e: - print(f"\nError starting server: {e}") - sys.exit(1) 534 + 535 +def start(): 536 + os.chdir(SCRIPT_DIR) 537 + mix_name = editor.rebuild_pwa_if_changed() 538 + editor.print_mix_name(mix_name) 539 + 540 + # Rescan /mix periodically so edits made on disk reach connected browser 541 + # tabs over the SSE stream. 542 + editor.start_rescan_ticker() 543 + 544 + local_ip = get_local_ip() 545 + if not local_ip: 546 + print("\nCouldn't find this computer's address on a local network, so other") 547 + print("devices can't reach it. To install your mixapp on your phone, connect") 548 + print("to a network and run serve.py again.") 549 + serve_http() 550 + return 551 + 552 + if not require_mkcert(): 553 + serve_http(local_ip) 554 + return 555 + 556 + base_path = base_path_for(mix_name) 557 + ensure_ca_installed() 558 + ensure_leaf_cert(local_ip) 559 + ca_httpd = start_ca_server(local_ip) 560 + serve_https(local_ip, base_path, ca_httpd=ca_httpd) 561 562 563 def main(): - """Main entry point""" - # Check if we're already running in venv 564 if "--in-venv" not in sys.argv: 565 run_in_venv() 566 else: - start_server() 567 + try: 568 + if "--reset" in sys.argv: 569 + reset_certs() 570 + else: 571 + start() 572 + except KeyboardInterrupt: 573 + print("\nCancelled.") 574 + sys.exit(130) 575 576 577 if __name__ == "__main__":