build.py (10.8 KB)
1 #!/usr/bin/env python3 2 """ 3 Creates manifest.json and service-worker.js 4 (PWA requirements) based on the contents of tracks.json 5 """ 6 7 import hashlib 8 import json 9 import re 10 from pathlib import Path 11 12 # Bootstrap into the shared venv first thing (re-execs on first run), 13 # so scan.rescan() has mutagen available when we call it before building. 14 import scan 15 scan.bootstrap(__file__) 16 17 18 def get_configuration(): 19 """Prompt user for configuration values""" 20 print("=" * 60) 21 print("PWA Configuration") 22 print("=" * 60) 23 print() 24 25 # Get app name 26 app_name = input("Enter a name for your mixapp: ").strip() 27 if not app_name: 28 print("Error: App name is required") 29 exit(1) 30 31 # Get base path with smart default 32 default_path = app_name.lower().replace(" ", "_") 33 print() 34 print(f"Enter the deployment path (or press Return/Enter for default)") 35 print(f"Default: /{default_path}/") 36 base_path_input = input("Path: ").strip() 37 38 if base_path_input: 39 # User provided a path - ensure it has leading/trailing slashes 40 base_path = base_path_input 41 if not base_path.startswith("/"): 42 base_path = "/" + base_path 43 if not base_path.endswith("/"): 44 base_path = base_path + "/" 45 else: 46 # Use default 47 base_path = f"/{default_path}/" 48 print(f"Using default path: {base_path}") 49 50 print() 51 print(f"Configuration:") 52 print(f" App Name: {app_name}") 53 print(f" Base Path: {base_path}") 54 print() 55 56 return app_name, base_path 57 58 # File paths (no need to edit these) 59 SCRIPT_DIR = Path(__file__).parent.absolute() 60 TRACKS_JSON = SCRIPT_DIR / "mix" / "tracks.json" 61 STYLES_CSS = SCRIPT_DIR / "resources" / "styles.css" 62 CUSTOM_CSS = SCRIPT_DIR / "mix" / "custom.css" 63 64 65 def get_background_color(): 66 """Extract the --background CSS variable, preferring custom.css over styles.css""" 67 # Check custom.css first (overrides styles.css) 68 for css_file in [CUSTOM_CSS, STYLES_CSS]: 69 if not css_file.exists(): 70 continue 71 with open(css_file, 'r', encoding='utf-8') as f: 72 content = f.read() 73 match = re.search( 74 r'--background:\s*([#a-zA-Z0-9(),.\s]+?)\s*;', 75 content 76 ) 77 if match: 78 color = match.group(1).strip() 79 print(f"Found background color in {css_file.name}: {color}") 80 return color 81 82 print("Warning: --background not found in any CSS file. Using default color.") 83 return "#080a0c" 84 85 86 def build_pwa(app_name=None, base_path=None): 87 """Generate manifest.json and service-worker.js based on tracks.json 88 89 Args: 90 app_name: Name of the app. If None, will be prompted via get_configuration() 91 base_path: Base path for the app. If None, will be prompted via get_configuration() 92 """ 93 # Get configuration if not provided 94 if app_name is None or base_path is None: 95 app_name, base_path = get_configuration() 96 97 # Derived values 98 short_name = app_name 99 cache_name = app_name 100 app_description = f"{app_name}" 101 102 print("Building PWA files...") 103 print(f" Cache name: {cache_name}") 104 105 # Rescan /mix so tracks.json reflects any additions/removals on disk 106 # before we snapshot it into the service worker's static file list. 107 scan.rescan(silent=True) 108 109 if not TRACKS_JSON.exists(): 110 print("Error: tracks.json not found.") 111 return 112 113 with open(TRACKS_JSON, 'r', encoding='utf-8') as f: 114 tracks = json.load(f) 115 116 # Get background color from styles.css 117 background_color = get_background_color() 118 119 # mix/album_art.jpg overrides the default 120 custom_album_art = SCRIPT_DIR / "mix" / "album_art.jpg" 121 album_art_file = custom_album_art if custom_album_art.exists() else SCRIPT_DIR / "resources" / "album_art.jpg" 122 album_art_path = "mix/album_art.jpg" if custom_album_art.exists() else "resources/album_art.jpg" 123 # append a content hash so the URL changes when the image changes 124 if album_art_file.exists(): 125 art_hash = hashlib.md5(album_art_file.read_bytes()).hexdigest()[:8] 126 album_art_path = f"{album_art_path}?v={art_hash}" 127 print(f" Album art: {album_art_path}") 128 129 # mix/icon.png overrides the default 130 custom_icon = SCRIPT_DIR / "mix" / "icon.png" 131 icon_file = custom_icon if custom_icon.exists() else SCRIPT_DIR / "resources" / "icon.png" 132 icon_path = "mix/icon.png" if custom_icon.exists() else "resources/icon.png" 133 # append a content hash so the URL changes when the image changes 134 if icon_file.exists(): 135 icon_hash = hashlib.md5(icon_file.read_bytes()).hexdigest()[:8] 136 icon_path = f"{icon_path}?v={icon_hash}" 137 print(f" Icon: {icon_path}") 138 139 # Generate manifest.json 140 manifest = { 141 "id": base_path, 142 "name": app_name, 143 "short_name": short_name, 144 "description": app_description, 145 "start_url": base_path, 146 "scope": base_path, 147 "display": "standalone", 148 "background_color": background_color, 149 "theme_color": background_color, 150 "cache_name": cache_name, # Custom field for script.js to use 151 "album_art": album_art_path, # Custom field for script.js to use 152 "icons": [ 153 { 154 "src": f"{base_path}{icon_path}", 155 "sizes": "640x640", 156 "type": "image/png", 157 "purpose": "any maskable" 158 } 159 ] 160 } 161 162 with open(SCRIPT_DIR / "manifest.json", 'w', encoding='utf-8') as f: 163 json.dump(manifest, f, indent=2) 164 print("✓ Generated manifest.json") 165 166 # Build static files list for service worker 167 static_files = [ 168 "./", 169 "index.html", 170 "manifest.json", 171 "resources/styles.css", 172 "resources/script.js", 173 "mix/tracks.json", 174 icon_path, 175 album_art_path, 176 "resources/play.svg", 177 "resources/pause.svg", 178 "resources/prev.svg", 179 "resources/next.svg", 180 "resources/repeat.svg", 181 "resources/fonts/Basteleur/Basteleur-Moonlight.woff2", 182 ] 183 184 AUDIO_EXTS = {".mp3", ".m4a", ".ogg", ".flac", ".wav"} 185 # album_art.jpg and icon.png added explicitly above with a hash; skip to avoid a bare dupe 186 SKIP_NAMES = {"tracks.json", "readme.md", "album_art.jpg", "icon.png"} 187 for path in sorted((SCRIPT_DIR / "mix").iterdir()): 188 if not path.is_file(): 189 continue 190 if path.name in SKIP_NAMES: 191 continue 192 if path.suffix.lower() in AUDIO_EXTS: 193 continue 194 static_files.append(f"mix/{path.name}") 195 196 static_files_js = json.dumps(static_files) 197 audio_pattern = "|".join(sorted(ext[1:] for ext in AUDIO_EXTS)) 198 199 # Generate service-worker.js 200 service_worker_content = f'''// Auto-generated service worker for {app_name} PWA 201 const CACHE_NAME = '{cache_name}'; 202 203 // Get the base path from the service worker location 204 const getBasePath = () => {{ 205 const swPath = self.location.pathname; 206 return swPath.substring(0, swPath.lastIndexOf('/') + 1); 207 }}; 208 209 const basePath = getBasePath(); 210 211 // Static files to cache on install 212 const STATIC_FILES = {static_files_js}; 213 const AUDIO_FILE = /\\.({audio_pattern})$/i; 214 215 // Install event - cache static resources only if not already cached. 216 // This makes installs immutable: once a file is in the cache, redeploys 217 // will not overwrite it, so the app stays frozen at its first-installed version. 218 // Audio files will be cached by the main app's blob preloading system. 219 self.addEventListener('install', (event) => {{ 220 console.log('Service Worker installing...', 'Base path:', basePath); 221 self.skipWaiting(); 222 event.waitUntil( 223 caches.open(CACHE_NAME).then(cache => {{ 224 const absoluteUrls = STATIC_FILES.map(url => {{ 225 if (url === './') return new URL(basePath, self.location.href).href; 226 return new URL(url, new URL(basePath, self.location.href)).href; 227 }}); 228 229 return Promise.allSettled( 230 absoluteUrls.map(url => 231 cache.match(url).then(existing => {{ 232 if (existing) {{ 233 console.log('• Already cached, skipping:', url); 234 return; 235 }} 236 return fetch(url, {{ cache: 'no-cache' }}) 237 .then(response => {{ 238 if (!response.ok) {{ 239 throw new Error(`HTTP error! status: ${{response.status}}`); 240 }} 241 return cache.put(url, response); 242 }}) 243 .then(() => console.log('✓ Cached:', url)) 244 .catch(err => {{ 245 console.error('✗ Failed to cache:', url, err); 246 throw err; 247 }}); 248 }}) 249 ) 250 ).then(results => {{ 251 const failed = results.filter(r => r.status === 'rejected'); 252 console.log(`Install complete: ${{results.length - failed.length}}/${{results.length}} ok`); 253 }}); 254 }}).catch(error => {{ 255 console.error('Service Worker installation failed:', error); 256 }}) 257 ); 258 }}); 259 260 self.addEventListener('activate', (event) => {{ 261 event.waitUntil(self.clients.claim()); 262 }}); 263 264 // Network fetch capped with a timeout. A mixapp installed off the LAN points 265 // at a private-IP origin that's usually gone by launch time; without a cap an 266 // uncached request hangs on a TCP timeout and stalls startup (black→white 267 // screen). Aborting fast turns that hang into an ordinary cache-miss failure. 268 const fetchWithTimeout = (request, ms = 2000) => {{ 269 const controller = new AbortController(); 270 const timer = setTimeout(() => controller.abort(), ms); 271 return fetch(request, {{ signal: controller.signal }}) 272 .finally(() => clearTimeout(timer)); 273 }}; 274 275 // Fetch event - cache first, network fallback 276 self.addEventListener('fetch', (event) => {{ 277 // Ignore non-http(s) requests like blob: URLs, data: URLs, chrome-extension:, etc. 278 if (!event.request.url.startsWith('http')) {{ 279 return; 280 }} 281 282 event.respondWith( 283 caches.match(event.request) 284 .then((cachedResponse) => {{ 285 if (cachedResponse) {{ 286 console.log('✓ Serving from cache:', event.request.url); 287 return cachedResponse; 288 }} 289 290 // Navigation that missed the exact cache key: serve the cached 291 // app shell so the document always renders from cache, online 292 // or off, even if the launch URL doesn't byte-match a key. 293 if (event.request.mode === 'navigate') {{ 294 const shellUrl = new URL(basePath, self.location.href).href; 295 return caches.match(shellUrl) 296 .then(shell => shell || caches.match('index.html')) 297 .then(shell => shell || fetchWithTimeout(event.request)); 298 }} 299 300 // Not in cache - try network (time-boxed; see fetchWithTimeout) 301 console.log('⟳ Fetching from network:', event.request.url); 302 return fetchWithTimeout(event.request) 303 .then((networkResponse) => {{ 304 // Check if valid response 305 if (!networkResponse || networkResponse.status !== 200 || networkResponse.type === 'error') {{ 306 return networkResponse; 307 }} 308 309 if (AUDIO_FILE.test(new URL(event.request.url).pathname)) {{ 310 return networkResponse; 311 }} 312 313 // Clone and cache for future offline use 314 const responseToCache = networkResponse.clone(); 315 caches.open(CACHE_NAME) 316 .then((cache) => {{ 317 cache.put(event.request, responseToCache); 318 console.log('✓ Cached from network:', event.request.url); 319 }}) 320 .catch(err => console.error('Failed to cache:', err)); 321 322 return networkResponse; 323 }}) 324 .catch((error) => {{ 325 console.error('✗ Network fetch failed for:', event.request.url, error); 326 throw error; 327 }}); 328 }}) 329 ); 330 }}); 331 ''' 332 333 with open(SCRIPT_DIR / "service-worker.js", 'w', encoding='utf-8') as f: 334 f.write(service_worker_content) 335 print("✓ Generated service-worker.js") 336 print() 337 print("PWA build complete!") 338 339 340 if __name__ == "__main__": 341 # When run directly, get configuration and build PWA files 342 app_name, base_path = get_configuration() 343 build_pwa(app_name, base_path)