build.py (10.2 KB)


  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()