-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbuild.py
More file actions
executable file
·327 lines (282 loc) · 10.1 KB
/
Copy pathbuild.py
File metadata and controls
executable file
·327 lines (282 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#!/usr/bin/env python3
"""
Creates manifest.json and service-worker.js
(PWA requirements) based on the contents of tracks.json
"""
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():
import hashlib
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}")
# 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}resources/icon.png",
"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",
"resources/icon.png",
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 added explicitly above with a hash; skip to avoid a bare dupe
SKIP_NAMES = {"tracks.json", "readme.md", "album_art.jpg"}
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)
# 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};
// 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;
}}
// 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)