-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbuild.py
More file actions
executable file
·318 lines (276 loc) · 9.32 KB
/
build.py
File metadata and controls
executable file
·318 lines (276 loc) · 9.32 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
#!/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
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 _next_cache_name(app_name, manifest_path):
"""Determine the next cache name by incrementing the version in an existing manifest.
If manifest.json doesn't exist or has no versioned cache_name, returns "{app_name}-v1".
If it already has e.g. "heaven-v1", returns "heaven-v1.1".
If it already has e.g. "heaven-v1.3", returns "heaven-v1.4".
"""
if manifest_path.exists():
try:
with open(manifest_path, 'r', encoding='utf-8') as f:
existing = json.load(f)
old_cache = existing.get("cache_name", "")
# Match pattern like "appname-v1" or "appname-v1.3"
match = re.match(r'^(.+)-v(\d+)(?:\.(\d+))?$', old_cache)
if match:
prefix = match.group(1)
major = int(match.group(2))
minor = int(match.group(3)) if match.group(3) is not None else 0
# If app was renamed, start fresh with new name
if prefix != app_name:
return f"{app_name}-v1"
return f"{app_name}-v{major}.{minor + 1}"
except (json.JSONDecodeError, KeyError):
pass
return f"{app_name}-v1"
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 = _next_cache_name(app_name, SCRIPT_DIR / "manifest.json")
app_description = f"{app_name}"
print("Building PWA files...")
print(f" Cache name: {cache_name}")
# Load tracks.json
if not TRACKS_JSON.exists():
print("Error: tracks.json not found. Run scan.py first.")
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()
# 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
"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",
"resources/play.svg",
"resources/pause.svg",
"resources/prev.svg",
"resources/next.svg",
"resources/repeat.svg",
]
# Conditionally include optional files if they exist
for optional_file in ["album_art.jpg", "custom.css", "custom.js"]:
if (SCRIPT_DIR / "mix" / optional_file).exists():
static_files.append(f"mix/{optional_file}")
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
// 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);
event.waitUntil(
caches.open(CACHE_NAME).then(cache => {{
// Make URLs absolute relative to service worker location
const absoluteUrls = STATIC_FILES.map(url => {{
if (url === './') return basePath;
return new URL(url, basePath + 'index.html').href;
}});
console.log('Caching', absoluteUrls.length, 'static resources');
// Cache files individually with better error handling
// Using Promise.allSettled to continue even if some fail
return Promise.allSettled(
absoluteUrls.map(url =>
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');
const succeeded = results.filter(r => r.status === 'fulfilled');
console.log(`Cached ${{succeeded.length}}/${{results.length}} static resources`);
if (failed.length > 0) {{
console.warn(`Failed to cache ${{failed.length}} resources`);
}}
}});
}}).then(() => {{
console.log('Service Worker installation complete');
return self.skipWaiting();
}}).catch(error => {{
console.error('Service Worker installation failed:', error);
}})
);
}});
// Activate event - clean up old caches
self.addEventListener('activate', (event) => {{
console.log('Service Worker activating...');
event.waitUntil(
caches.keys().then((cacheNames) => {{
return Promise.all(
cacheNames.map((cacheName) => {{
if (cacheName !== CACHE_NAME) {{
console.log('Deleting old cache:', cacheName);
return caches.delete(cacheName);
}}
}})
);
}}).then(() => self.clients.claim())
);
}});
// 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;
}}
// Not in cache - try network
console.log('⟳ Fetching from network:', event.request.url);
return fetch(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)